From 425ca399b79c01aa5484be79bbc792bc3b5de30f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 14 Jan 2019 14:29:09 +0000 Subject: [PATCH 0001/2038] add batch to load building for all PC Platforms --- build/Xenko.PCPlatforms.bat | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 build/Xenko.PCPlatforms.bat diff --git a/build/Xenko.PCPlatforms.bat b/build/Xenko.PCPlatforms.bat new file mode 100644 index 0000000000..468de53b91 --- /dev/null +++ b/build/Xenko.PCPlatforms.bat @@ -0,0 +1,2 @@ +set XenkoPlatforms=Windows;Linux;macOS +Xenko.sln From 29642c843d888f6ddb234d48e6cf6cabe2e389d7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 17 Jan 2019 21:10:06 -0500 Subject: [PATCH 0002/2038] grab camera fixes from Eideren --- .../Scripts/Camera/BasicCameraController.cs | 47 ++++++++++--------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs index e7abfc5f47..7ca7cb9a2a 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs @@ -64,29 +64,29 @@ private void ProcessInput() // Move with keyboard if (Input.IsKeyDown(Keys.W) || Input.IsKeyDown(Keys.Up)) { - translation.Z = -KeyboardMovementSpeed.Z; + translation.Z -= KeyboardMovementSpeed.Z; } - else if (Input.IsKeyDown(Keys.S) || Input.IsKeyDown(Keys.Down)) + if (Input.IsKeyDown(Keys.S) || Input.IsKeyDown(Keys.Down)) { - translation.Z = KeyboardMovementSpeed.Z; + translation.Z += KeyboardMovementSpeed.Z; } if (Input.IsKeyDown(Keys.A) || Input.IsKeyDown(Keys.Left)) { - translation.X = -KeyboardMovementSpeed.X; + translation.X -= KeyboardMovementSpeed.X; } - else if (Input.IsKeyDown(Keys.D) || Input.IsKeyDown(Keys.Right)) + if (Input.IsKeyDown(Keys.D) || Input.IsKeyDown(Keys.Right)) { - translation.X = KeyboardMovementSpeed.X; + translation.X += KeyboardMovementSpeed.X; } if (Input.IsKeyDown(Keys.Q)) { - translation.Y = -KeyboardMovementSpeed.Y; + translation.Y -= KeyboardMovementSpeed.Y; } - else if (Input.IsKeyDown(Keys.E)) + if (Input.IsKeyDown(Keys.E)) { - translation.Y = KeyboardMovementSpeed.Y; + translation.Y += KeyboardMovementSpeed.Y; } // Alternative translation speed @@ -98,30 +98,37 @@ private void ProcessInput() // Rotate with keyboard if (Input.IsKeyDown(Keys.NumPad2)) { - pitch = KeyboardRotationSpeed.X; + pitch += KeyboardRotationSpeed.X; } - else if (Input.IsKeyDown(Keys.NumPad8)) + if (Input.IsKeyDown(Keys.NumPad8)) { - pitch = -KeyboardRotationSpeed.X; + pitch -= KeyboardRotationSpeed.X; } if (Input.IsKeyDown(Keys.NumPad4)) { - yaw = KeyboardRotationSpeed.Y; + yaw += KeyboardRotationSpeed.Y; } - else if (Input.IsKeyDown(Keys.NumPad6)) + if (Input.IsKeyDown(Keys.NumPad6)) { - yaw = -KeyboardRotationSpeed.Y; + yaw -= KeyboardRotationSpeed.Y; } + // Deal with non-consistant frame-rate, do it before 'flick-based' inputs + // like mouse and gestures as scaling them would negatively impact their precision. + var elapsedTime = (float)Game.UpdateTime.Elapsed.TotalSeconds; + translation *= elapsedTime; + pitch *= elapsedTime; + yaw *= elapsedTime; + // Rotate with mouse if (Input.IsMouseButtonDown(MouseButton.Right)) { Input.LockMousePosition(); Game.IsMouseVisible = false; - yaw = -Input.MouseDelta.X * MouseRotationSpeed.X; - pitch = -Input.MouseDelta.Y * MouseRotationSpeed.Y; + yaw -= Input.MouseDelta.X * MouseRotationSpeed.X; + pitch -= Input.MouseDelta.Y * MouseRotationSpeed.Y; } else { @@ -155,12 +162,6 @@ private void ProcessInput() private void UpdateTransform() { - var elapsedTime = (float)Game.UpdateTime.Elapsed.TotalSeconds; - - translation *= elapsedTime; - yaw *= elapsedTime; - pitch *= elapsedTime; - // Get the local coordinate system var rotation = Matrix.RotationQuaternion(Entity.Transform.Rotation); From d0e260687c23c585813c582bf956724e58592554 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 31 Jan 2019 02:15:53 +0000 Subject: [PATCH 0003/2038] Revert "grab camera fixes from Eideren" This reverts commit 29642c843d888f6ddb234d48e6cf6cabe2e389d7. --- .../Scripts/Camera/BasicCameraController.cs | 47 +++++++++---------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs index 7ca7cb9a2a..e7abfc5f47 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Camera/BasicCameraController.cs @@ -64,29 +64,29 @@ private void ProcessInput() // Move with keyboard if (Input.IsKeyDown(Keys.W) || Input.IsKeyDown(Keys.Up)) { - translation.Z -= KeyboardMovementSpeed.Z; + translation.Z = -KeyboardMovementSpeed.Z; } - if (Input.IsKeyDown(Keys.S) || Input.IsKeyDown(Keys.Down)) + else if (Input.IsKeyDown(Keys.S) || Input.IsKeyDown(Keys.Down)) { - translation.Z += KeyboardMovementSpeed.Z; + translation.Z = KeyboardMovementSpeed.Z; } if (Input.IsKeyDown(Keys.A) || Input.IsKeyDown(Keys.Left)) { - translation.X -= KeyboardMovementSpeed.X; + translation.X = -KeyboardMovementSpeed.X; } - if (Input.IsKeyDown(Keys.D) || Input.IsKeyDown(Keys.Right)) + else if (Input.IsKeyDown(Keys.D) || Input.IsKeyDown(Keys.Right)) { - translation.X += KeyboardMovementSpeed.X; + translation.X = KeyboardMovementSpeed.X; } if (Input.IsKeyDown(Keys.Q)) { - translation.Y -= KeyboardMovementSpeed.Y; + translation.Y = -KeyboardMovementSpeed.Y; } - if (Input.IsKeyDown(Keys.E)) + else if (Input.IsKeyDown(Keys.E)) { - translation.Y += KeyboardMovementSpeed.Y; + translation.Y = KeyboardMovementSpeed.Y; } // Alternative translation speed @@ -98,37 +98,30 @@ private void ProcessInput() // Rotate with keyboard if (Input.IsKeyDown(Keys.NumPad2)) { - pitch += KeyboardRotationSpeed.X; + pitch = KeyboardRotationSpeed.X; } - if (Input.IsKeyDown(Keys.NumPad8)) + else if (Input.IsKeyDown(Keys.NumPad8)) { - pitch -= KeyboardRotationSpeed.X; + pitch = -KeyboardRotationSpeed.X; } if (Input.IsKeyDown(Keys.NumPad4)) { - yaw += KeyboardRotationSpeed.Y; + yaw = KeyboardRotationSpeed.Y; } - if (Input.IsKeyDown(Keys.NumPad6)) + else if (Input.IsKeyDown(Keys.NumPad6)) { - yaw -= KeyboardRotationSpeed.Y; + yaw = -KeyboardRotationSpeed.Y; } - // Deal with non-consistant frame-rate, do it before 'flick-based' inputs - // like mouse and gestures as scaling them would negatively impact their precision. - var elapsedTime = (float)Game.UpdateTime.Elapsed.TotalSeconds; - translation *= elapsedTime; - pitch *= elapsedTime; - yaw *= elapsedTime; - // Rotate with mouse if (Input.IsMouseButtonDown(MouseButton.Right)) { Input.LockMousePosition(); Game.IsMouseVisible = false; - yaw -= Input.MouseDelta.X * MouseRotationSpeed.X; - pitch -= Input.MouseDelta.Y * MouseRotationSpeed.Y; + yaw = -Input.MouseDelta.X * MouseRotationSpeed.X; + pitch = -Input.MouseDelta.Y * MouseRotationSpeed.Y; } else { @@ -162,6 +155,12 @@ private void ProcessInput() private void UpdateTransform() { + var elapsedTime = (float)Game.UpdateTime.Elapsed.TotalSeconds; + + translation *= elapsedTime; + yaw *= elapsedTime; + pitch *= elapsedTime; + // Get the local coordinate system var rotation = Matrix.RotationQuaternion(Entity.Transform.Rotation); From 13d0cb4f13fe64484b93978cf5934c3dc4a39c54 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 31 Jan 2019 02:16:10 +0000 Subject: [PATCH 0004/2038] revert --- sources/engine/Xenko.Graphics/SpriteFont.cs | 2 +- sources/engine/Xenko.Graphics/UIBatch.cs | 41 ++++++++++++++++--- .../Renderers/DefaultTextBlockRenderer.cs | 5 +-- .../Xenko.Assimp.Translation.vcxproj | 1 + .../Xenko.Importer.Assimp.vcxproj | 1 + .../Xenko.Importer.Common.vcxproj | 1 + .../Xenko.Importer.FBX.vcxproj | 1 + 7 files changed, 42 insertions(+), 10 deletions(-) diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 18dcb13f20..6d268f4a40 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -284,7 +284,7 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect worldMatrix.M41 += worldMatrix.M11 * xScaledShift + worldMatrix.M21 * yScaledShift; worldMatrix.M42 += worldMatrix.M12 * xScaledShift + worldMatrix.M22 * yScaledShift; worldMatrix.M43 += worldMatrix.M13 * xScaledShift + worldMatrix.M23 * yScaledShift; - + worldMatrix.M11 *= elementSize.X; worldMatrix.M12 *= elementSize.X; worldMatrix.M13 *= elementSize.X; diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index aad6f7f00f..b04b2e8e34 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -26,7 +26,7 @@ public class UIBatch : BatchBase /// /// The view projection matrix that will be used for the current begin/end draw calls. /// - private Matrix viewProjectionMatrix; + public Matrix viewProjectionMatrix; // Cached states private BlendStateDescription? currentBlendState; @@ -400,7 +400,7 @@ internal void DrawCharacter(Texture texture, ref Matrix worldViewProjectionMatri if (texture == null) throw new ArgumentNullException(nameof(texture)); // Calculate the information needed to draw. - var drawInfo = new UIImageDrawInfo + /*var drawInfo = new UIImageDrawInfo { Source = { @@ -418,8 +418,35 @@ internal void DrawCharacter(Texture texture, ref Matrix worldViewProjectionMatri UnitXWorld = worldViewProjectionMatrix.Row1, UnitYWorld = worldViewProjectionMatrix.Row2, LeftTopCornerWorld = worldViewProjectionMatrix.Row4, + };*/ + + // Calculate the information needed to draw. + var drawInfo = new UIImageDrawInfo { + Source = + { + X = sourceRectangle.X / texture.ViewWidth, + Y = sourceRectangle.Y / texture.ViewHeight, + Width = sourceRectangle.Width / texture.ViewWidth, + Height = sourceRectangle.Height / texture.ViewHeight, + }, + DepthBias = depthBias, + ColorScale = color, + ColorAdd = new Color(0, 0, 0, 0), + Swizzle = swizzle, + Primitive = PrimitiveType.Rectangle, + VertexShift = Vector4.Zero, + UnitXWorld = worldViewProjectionMatrix.Row1, + UnitYWorld = worldViewProjectionMatrix.Row2, + LeftTopCornerWorld = worldViewProjectionMatrix.Row4, }; + Matrix worldViewProjection; + Matrix.Multiply(ref worldViewProjectionMatrix, ref viewProjectionMatrix, out worldViewProjection); + drawInfo.UnitXWorld = worldViewProjection.Row1; + drawInfo.UnitYWorld = worldViewProjection.Row2; + drawInfo.UnitZWorld = worldViewProjection.Row3; + //Vector4.Transform(ref vector4LeftTop, ref worldViewProjection, out drawInfo.LeftTopCornerWorld); + var elementInfo = new ElementInfo(4, 6, ref drawInfo, depthBias); Draw(texture, ref elementInfo); @@ -438,12 +465,12 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI worldMatrix.M41 -= worldMatrix.M11 * leftTopCornerOffset.X + worldMatrix.M21 * leftTopCornerOffset.Y; worldMatrix.M42 -= worldMatrix.M12 * leftTopCornerOffset.X + worldMatrix.M22 * leftTopCornerOffset.Y; worldMatrix.M43 -= worldMatrix.M13 * leftTopCornerOffset.X + worldMatrix.M23 * leftTopCornerOffset.Y; - + // transform the world matrix into the world view project matrix Matrix.MultiplyTo(ref worldMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); // do not snap static fonts when real/virtual resolution does not match. - if (font.FontType == SpriteFontType.SDF) + /*if (font.FontType == SpriteFontType.SDF) //debug { drawCommand.SnapText = false; float scaling = drawCommand.RequestedFontSize / font.Size; @@ -456,9 +483,11 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.RealVirtualResolutionRatio = Vector2.One; // ensure that static font are not scaled internally } + */ + drawCommand.RealVirtualResolutionRatio = Vector2.One; // snap draw start position to prevent characters to be drawn in between two pixels - if (drawCommand.SnapText) + /*if (drawCommand.SnapText) { var invW = 1.0f / drawCommand.Matrix.M44; var backBufferHalfWidth = GraphicsContext.CommandList.RenderTarget.ViewWidth / 2; @@ -470,7 +499,7 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.Matrix.M42 = (float)(Math.Round(drawCommand.Matrix.M42 * backBufferHalfHeight) / backBufferHalfHeight); drawCommand.Matrix.M41 /= invW; drawCommand.Matrix.M42 /= invW; - } + }*/ font.InternalUIDraw(GraphicsContext.CommandList, ref proxy, ref drawCommand); } diff --git a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs index 1c88b8d55d..79ef37cde3 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs @@ -26,9 +26,8 @@ public override void RenderColor(UIElement element, UIRenderingContext context) if (textBlock.Font == null || textBlock.TextToDisplay == null) return; - - var drawCommand = new SpriteFont.InternalUIDrawCommand - { + + var drawCommand = new SpriteFont.InternalUIDrawCommand { Color = textBlock.RenderOpacity * textBlock.TextColor, DepthBias = context.DepthBias, RealVirtualResolutionRatio = element.LayoutingContext.RealVirtualResolutionRatio, diff --git a/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj b/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj index 82915d88e1..3d64e6c266 100644 --- a/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj +++ b/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj @@ -29,6 +29,7 @@ {FCDF1B87-1C76-46EB-AD6A-D55EF5F195B8} Xenko.AssimpNet.NetTranslation Xenko.Assimp.Translation + 10.0.17763.0 diff --git a/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj b/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj index 723a23393f..f7bb4398c4 100644 --- a/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj +++ b/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj @@ -40,6 +40,7 @@ {C2306552-6C42-464C-8981-32FEF4F9458D} ManagedCProj Xenko.Importer.Assimp + 10.0.17763.0 diff --git a/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj b/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj index e3d816d69b..e841cdedd3 100644 --- a/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj +++ b/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj @@ -40,6 +40,7 @@ {43A6E62E-1B1C-4630-ABB8-C3F716004645} ManagedCProj Xenko.Importer.Common + 10.0.17763.0 diff --git a/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj b/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj index e420df3d82..4274d9eb53 100644 --- a/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj +++ b/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj @@ -36,6 +36,7 @@ {0467D515-FD66-4B8A-A128-CB642C2ED03F} ManagedCProj Xenko.Importer.FBX + 10.0.17763.0 From 6095b32782d060c90d51153a5eed150c176973be Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 31 Jan 2019 02:16:56 +0000 Subject: [PATCH 0005/2038] Revert "revert", accidentally committed 3d text work in progress This reverts commit 13d0cb4f13fe64484b93978cf5934c3dc4a39c54. --- sources/engine/Xenko.Graphics/SpriteFont.cs | 2 +- sources/engine/Xenko.Graphics/UIBatch.cs | 41 +++---------------- .../Renderers/DefaultTextBlockRenderer.cs | 5 ++- .../Xenko.Assimp.Translation.vcxproj | 1 - .../Xenko.Importer.Assimp.vcxproj | 1 - .../Xenko.Importer.Common.vcxproj | 1 - .../Xenko.Importer.FBX.vcxproj | 1 - 7 files changed, 10 insertions(+), 42 deletions(-) diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 6d268f4a40..18dcb13f20 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -284,7 +284,7 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect worldMatrix.M41 += worldMatrix.M11 * xScaledShift + worldMatrix.M21 * yScaledShift; worldMatrix.M42 += worldMatrix.M12 * xScaledShift + worldMatrix.M22 * yScaledShift; worldMatrix.M43 += worldMatrix.M13 * xScaledShift + worldMatrix.M23 * yScaledShift; - + worldMatrix.M11 *= elementSize.X; worldMatrix.M12 *= elementSize.X; worldMatrix.M13 *= elementSize.X; diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index b04b2e8e34..aad6f7f00f 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -26,7 +26,7 @@ public class UIBatch : BatchBase /// /// The view projection matrix that will be used for the current begin/end draw calls. /// - public Matrix viewProjectionMatrix; + private Matrix viewProjectionMatrix; // Cached states private BlendStateDescription? currentBlendState; @@ -400,7 +400,7 @@ internal void DrawCharacter(Texture texture, ref Matrix worldViewProjectionMatri if (texture == null) throw new ArgumentNullException(nameof(texture)); // Calculate the information needed to draw. - /*var drawInfo = new UIImageDrawInfo + var drawInfo = new UIImageDrawInfo { Source = { @@ -418,35 +418,8 @@ internal void DrawCharacter(Texture texture, ref Matrix worldViewProjectionMatri UnitXWorld = worldViewProjectionMatrix.Row1, UnitYWorld = worldViewProjectionMatrix.Row2, LeftTopCornerWorld = worldViewProjectionMatrix.Row4, - };*/ - - // Calculate the information needed to draw. - var drawInfo = new UIImageDrawInfo { - Source = - { - X = sourceRectangle.X / texture.ViewWidth, - Y = sourceRectangle.Y / texture.ViewHeight, - Width = sourceRectangle.Width / texture.ViewWidth, - Height = sourceRectangle.Height / texture.ViewHeight, - }, - DepthBias = depthBias, - ColorScale = color, - ColorAdd = new Color(0, 0, 0, 0), - Swizzle = swizzle, - Primitive = PrimitiveType.Rectangle, - VertexShift = Vector4.Zero, - UnitXWorld = worldViewProjectionMatrix.Row1, - UnitYWorld = worldViewProjectionMatrix.Row2, - LeftTopCornerWorld = worldViewProjectionMatrix.Row4, }; - Matrix worldViewProjection; - Matrix.Multiply(ref worldViewProjectionMatrix, ref viewProjectionMatrix, out worldViewProjection); - drawInfo.UnitXWorld = worldViewProjection.Row1; - drawInfo.UnitYWorld = worldViewProjection.Row2; - drawInfo.UnitZWorld = worldViewProjection.Row3; - //Vector4.Transform(ref vector4LeftTop, ref worldViewProjection, out drawInfo.LeftTopCornerWorld); - var elementInfo = new ElementInfo(4, 6, ref drawInfo, depthBias); Draw(texture, ref elementInfo); @@ -465,12 +438,12 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI worldMatrix.M41 -= worldMatrix.M11 * leftTopCornerOffset.X + worldMatrix.M21 * leftTopCornerOffset.Y; worldMatrix.M42 -= worldMatrix.M12 * leftTopCornerOffset.X + worldMatrix.M22 * leftTopCornerOffset.Y; worldMatrix.M43 -= worldMatrix.M13 * leftTopCornerOffset.X + worldMatrix.M23 * leftTopCornerOffset.Y; - + // transform the world matrix into the world view project matrix Matrix.MultiplyTo(ref worldMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); // do not snap static fonts when real/virtual resolution does not match. - /*if (font.FontType == SpriteFontType.SDF) //debug + if (font.FontType == SpriteFontType.SDF) { drawCommand.SnapText = false; float scaling = drawCommand.RequestedFontSize / font.Size; @@ -483,11 +456,9 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.RealVirtualResolutionRatio = Vector2.One; // ensure that static font are not scaled internally } - */ - drawCommand.RealVirtualResolutionRatio = Vector2.One; // snap draw start position to prevent characters to be drawn in between two pixels - /*if (drawCommand.SnapText) + if (drawCommand.SnapText) { var invW = 1.0f / drawCommand.Matrix.M44; var backBufferHalfWidth = GraphicsContext.CommandList.RenderTarget.ViewWidth / 2; @@ -499,7 +470,7 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.Matrix.M42 = (float)(Math.Round(drawCommand.Matrix.M42 * backBufferHalfHeight) / backBufferHalfHeight); drawCommand.Matrix.M41 /= invW; drawCommand.Matrix.M42 /= invW; - }*/ + } font.InternalUIDraw(GraphicsContext.CommandList, ref proxy, ref drawCommand); } diff --git a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs index 79ef37cde3..1c88b8d55d 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs @@ -26,8 +26,9 @@ public override void RenderColor(UIElement element, UIRenderingContext context) if (textBlock.Font == null || textBlock.TextToDisplay == null) return; - - var drawCommand = new SpriteFont.InternalUIDrawCommand { + + var drawCommand = new SpriteFont.InternalUIDrawCommand + { Color = textBlock.RenderOpacity * textBlock.TextColor, DepthBias = context.DepthBias, RealVirtualResolutionRatio = element.LayoutingContext.RealVirtualResolutionRatio, diff --git a/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj b/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj index 3d64e6c266..82915d88e1 100644 --- a/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj +++ b/sources/tools/Xenko.Assimp.Translation/Xenko.Assimp.Translation.vcxproj @@ -29,7 +29,6 @@ {FCDF1B87-1C76-46EB-AD6A-D55EF5F195B8} Xenko.AssimpNet.NetTranslation Xenko.Assimp.Translation - 10.0.17763.0 diff --git a/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj b/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj index f7bb4398c4..723a23393f 100644 --- a/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj +++ b/sources/tools/Xenko.Importer.Assimp/Xenko.Importer.Assimp.vcxproj @@ -40,7 +40,6 @@ {C2306552-6C42-464C-8981-32FEF4F9458D} ManagedCProj Xenko.Importer.Assimp - 10.0.17763.0 diff --git a/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj b/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj index e841cdedd3..e3d816d69b 100644 --- a/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj +++ b/sources/tools/Xenko.Importer.Common/Xenko.Importer.Common.vcxproj @@ -40,7 +40,6 @@ {43A6E62E-1B1C-4630-ABB8-C3F716004645} ManagedCProj Xenko.Importer.Common - 10.0.17763.0 diff --git a/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj b/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj index 4274d9eb53..e420df3d82 100644 --- a/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj +++ b/sources/tools/Xenko.Importer.FBX/Xenko.Importer.FBX.vcxproj @@ -36,7 +36,6 @@ {0467D515-FD66-4B8A-A128-CB642C2ED03F} ManagedCProj Xenko.Importer.FBX - 10.0.17763.0 From 952fdb089ab799bb88e1325f9df06630f8338ea6 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 3 Feb 2019 03:00:32 +0000 Subject: [PATCH 0006/2038] fixed 3D text rendering matrix, but still needs work --- sources/engine/Xenko.Graphics/SpriteFont.cs | 9 ++++++--- sources/engine/Xenko.Graphics/UIBatch.cs | 19 +++++++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 18dcb13f20..834d4e82b8 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -280,7 +280,7 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect var xScaledShift = xShift / parameters.RealVirtualResolutionRatio.X; var yScaledShift = yShift / parameters.RealVirtualResolutionRatio.Y; - var worldMatrix = parameters.Matrix; + var worldMatrix = parameters.OriginalMatrix; worldMatrix.M41 += worldMatrix.M11 * xScaledShift + worldMatrix.M21 * yScaledShift; worldMatrix.M42 += worldMatrix.M12 * xScaledShift + worldMatrix.M22 * yScaledShift; worldMatrix.M43 += worldMatrix.M13 * xScaledShift + worldMatrix.M23 * yScaledShift; @@ -292,8 +292,11 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect worldMatrix.M22 *= elementSize.Y; worldMatrix.M23 *= elementSize.Y; + Matrix projMat = parameters.Batch.getViewProjectionMatrix(); + Matrix.Multiply(ref worldMatrix, ref projMat, out parameters.Matrix); + RectangleF sourceRectangle = glyph.Subrect; - parameters.Batch.DrawCharacter(Textures[glyph.BitmapIndex], ref worldMatrix, ref sourceRectangle, ref parameters.Color, parameters.DepthBias, swizzle); + parameters.Batch.DrawCharacter(Textures[glyph.BitmapIndex], ref parameters.Matrix, ref sourceRectangle, ref parameters.Color, parameters.DepthBias, swizzle); } /// @@ -685,7 +688,7 @@ internal struct InternalUIDrawCommand public UIBatch Batch; - public Matrix Matrix; + public Matrix OriginalMatrix, Matrix; /// /// The size of the rectangle containing the text diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index aad6f7f00f..1d1854ac7a 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -28,6 +28,10 @@ public class UIBatch : BatchBase /// private Matrix viewProjectionMatrix; + public Matrix getViewProjectionMatrix() { + return viewProjectionMatrix; + } + // Cached states private BlendStateDescription? currentBlendState; private SamplerState currentSamplerState; @@ -433,14 +437,14 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI var proxy = new SpriteFont.StringProxy(text); // shift the string position so that it is written from the left/top corner of the element - var leftTopCornerOffset = drawCommand.TextBoxSize / 2; - var worldMatrix = drawCommand.Matrix; - worldMatrix.M41 -= worldMatrix.M11 * leftTopCornerOffset.X + worldMatrix.M21 * leftTopCornerOffset.Y; - worldMatrix.M42 -= worldMatrix.M12 * leftTopCornerOffset.X + worldMatrix.M22 * leftTopCornerOffset.Y; - worldMatrix.M43 -= worldMatrix.M13 * leftTopCornerOffset.X + worldMatrix.M23 * leftTopCornerOffset.Y; + var leftTopCornerOffset = drawCommand.TextBoxSize / 2f; + drawCommand.OriginalMatrix = drawCommand.Matrix; + drawCommand.OriginalMatrix.M41 -= drawCommand.OriginalMatrix.M11 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M21 * leftTopCornerOffset.Y; + drawCommand.OriginalMatrix.M42 -= drawCommand.OriginalMatrix.M12 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M22 * leftTopCornerOffset.Y; + drawCommand.OriginalMatrix.M43 -= drawCommand.OriginalMatrix.M13 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M23 * leftTopCornerOffset.Y; // transform the world matrix into the world view project matrix - Matrix.MultiplyTo(ref worldMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); + Matrix.MultiplyTo(ref drawCommand.OriginalMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); // do not snap static fonts when real/virtual resolution does not match. if (font.FontType == SpriteFontType.SDF) @@ -457,6 +461,9 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.RealVirtualResolutionRatio = Vector2.One; // ensure that static font are not scaled internally } + drawCommand.RealVirtualResolutionRatio.X = 1f; + drawCommand.RealVirtualResolutionRatio.Y = 1f; + // snap draw start position to prevent characters to be drawn in between two pixels if (drawCommand.SnapText) { From 073cc313b6e81cf9f750de5a8887c883890db616 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 3 Feb 2019 03:00:32 +0000 Subject: [PATCH 0007/2038] fixed 3D text rendering matrix, but still needs work --- sources/engine/Xenko.Graphics/SpriteFont.cs | 9 ++++++--- sources/engine/Xenko.Graphics/UIBatch.cs | 19 +++++++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 18dcb13f20..834d4e82b8 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -280,7 +280,7 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect var xScaledShift = xShift / parameters.RealVirtualResolutionRatio.X; var yScaledShift = yShift / parameters.RealVirtualResolutionRatio.Y; - var worldMatrix = parameters.Matrix; + var worldMatrix = parameters.OriginalMatrix; worldMatrix.M41 += worldMatrix.M11 * xScaledShift + worldMatrix.M21 * yScaledShift; worldMatrix.M42 += worldMatrix.M12 * xScaledShift + worldMatrix.M22 * yScaledShift; worldMatrix.M43 += worldMatrix.M13 * xScaledShift + worldMatrix.M23 * yScaledShift; @@ -292,8 +292,11 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect worldMatrix.M22 *= elementSize.Y; worldMatrix.M23 *= elementSize.Y; + Matrix projMat = parameters.Batch.getViewProjectionMatrix(); + Matrix.Multiply(ref worldMatrix, ref projMat, out parameters.Matrix); + RectangleF sourceRectangle = glyph.Subrect; - parameters.Batch.DrawCharacter(Textures[glyph.BitmapIndex], ref worldMatrix, ref sourceRectangle, ref parameters.Color, parameters.DepthBias, swizzle); + parameters.Batch.DrawCharacter(Textures[glyph.BitmapIndex], ref parameters.Matrix, ref sourceRectangle, ref parameters.Color, parameters.DepthBias, swizzle); } /// @@ -685,7 +688,7 @@ internal struct InternalUIDrawCommand public UIBatch Batch; - public Matrix Matrix; + public Matrix OriginalMatrix, Matrix; /// /// The size of the rectangle containing the text diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index aad6f7f00f..1d1854ac7a 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -28,6 +28,10 @@ public class UIBatch : BatchBase /// private Matrix viewProjectionMatrix; + public Matrix getViewProjectionMatrix() { + return viewProjectionMatrix; + } + // Cached states private BlendStateDescription? currentBlendState; private SamplerState currentSamplerState; @@ -433,14 +437,14 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI var proxy = new SpriteFont.StringProxy(text); // shift the string position so that it is written from the left/top corner of the element - var leftTopCornerOffset = drawCommand.TextBoxSize / 2; - var worldMatrix = drawCommand.Matrix; - worldMatrix.M41 -= worldMatrix.M11 * leftTopCornerOffset.X + worldMatrix.M21 * leftTopCornerOffset.Y; - worldMatrix.M42 -= worldMatrix.M12 * leftTopCornerOffset.X + worldMatrix.M22 * leftTopCornerOffset.Y; - worldMatrix.M43 -= worldMatrix.M13 * leftTopCornerOffset.X + worldMatrix.M23 * leftTopCornerOffset.Y; + var leftTopCornerOffset = drawCommand.TextBoxSize / 2f; + drawCommand.OriginalMatrix = drawCommand.Matrix; + drawCommand.OriginalMatrix.M41 -= drawCommand.OriginalMatrix.M11 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M21 * leftTopCornerOffset.Y; + drawCommand.OriginalMatrix.M42 -= drawCommand.OriginalMatrix.M12 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M22 * leftTopCornerOffset.Y; + drawCommand.OriginalMatrix.M43 -= drawCommand.OriginalMatrix.M13 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M23 * leftTopCornerOffset.Y; // transform the world matrix into the world view project matrix - Matrix.MultiplyTo(ref worldMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); + Matrix.MultiplyTo(ref drawCommand.OriginalMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); // do not snap static fonts when real/virtual resolution does not match. if (font.FontType == SpriteFontType.SDF) @@ -457,6 +461,9 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.RealVirtualResolutionRatio = Vector2.One; // ensure that static font are not scaled internally } + drawCommand.RealVirtualResolutionRatio.X = 1f; + drawCommand.RealVirtualResolutionRatio.Y = 1f; + // snap draw start position to prevent characters to be drawn in between two pixels if (drawCommand.SnapText) { From c059d4ef6181a6eb61414aecbc788970b0c3a62e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 4 Feb 2019 18:31:13 +0000 Subject: [PATCH 0008/2038] performance improvements and cleanup of 3D text fixes --- sources/engine/Xenko.Graphics/SpriteFont.cs | 9 +++---- sources/engine/Xenko.Graphics/UIBatch.cs | 30 ++++++++++----------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 834d4e82b8..4f7c3b34e5 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -280,7 +280,7 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect var xScaledShift = xShift / parameters.RealVirtualResolutionRatio.X; var yScaledShift = yShift / parameters.RealVirtualResolutionRatio.Y; - var worldMatrix = parameters.OriginalMatrix; + var worldMatrix = parameters.Matrix; worldMatrix.M41 += worldMatrix.M11 * xScaledShift + worldMatrix.M21 * yScaledShift; worldMatrix.M42 += worldMatrix.M12 * xScaledShift + worldMatrix.M22 * yScaledShift; worldMatrix.M43 += worldMatrix.M13 * xScaledShift + worldMatrix.M23 * yScaledShift; @@ -292,11 +292,10 @@ internal void InternalUIDrawGlyph(ref InternalUIDrawCommand parameters, ref Vect worldMatrix.M22 *= elementSize.Y; worldMatrix.M23 *= elementSize.Y; - Matrix projMat = parameters.Batch.getViewProjectionMatrix(); - Matrix.Multiply(ref worldMatrix, ref projMat, out parameters.Matrix); + Matrix.Multiply(ref worldMatrix, ref parameters.Batch.viewProjectionMatrix, out Matrix outMatrix); RectangleF sourceRectangle = glyph.Subrect; - parameters.Batch.DrawCharacter(Textures[glyph.BitmapIndex], ref parameters.Matrix, ref sourceRectangle, ref parameters.Color, parameters.DepthBias, swizzle); + parameters.Batch.DrawCharacter(Textures[glyph.BitmapIndex], ref outMatrix, ref sourceRectangle, ref parameters.Color, parameters.DepthBias, swizzle); } /// @@ -688,7 +687,7 @@ internal struct InternalUIDrawCommand public UIBatch Batch; - public Matrix OriginalMatrix, Matrix; + public Matrix Matrix; /// /// The size of the rectangle containing the text diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index 1d1854ac7a..ab33e1c5f5 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -26,11 +26,7 @@ public class UIBatch : BatchBase /// /// The view projection matrix that will be used for the current begin/end draw calls. /// - private Matrix viewProjectionMatrix; - - public Matrix getViewProjectionMatrix() { - return viewProjectionMatrix; - } + public Matrix viewProjectionMatrix; // Cached states private BlendStateDescription? currentBlendState; @@ -438,16 +434,21 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI // shift the string position so that it is written from the left/top corner of the element var leftTopCornerOffset = drawCommand.TextBoxSize / 2f; - drawCommand.OriginalMatrix = drawCommand.Matrix; - drawCommand.OriginalMatrix.M41 -= drawCommand.OriginalMatrix.M11 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M21 * leftTopCornerOffset.Y; - drawCommand.OriginalMatrix.M42 -= drawCommand.OriginalMatrix.M12 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M22 * leftTopCornerOffset.Y; - drawCommand.OriginalMatrix.M43 -= drawCommand.OriginalMatrix.M13 * leftTopCornerOffset.X + drawCommand.OriginalMatrix.M23 * leftTopCornerOffset.Y; - - // transform the world matrix into the world view project matrix - Matrix.MultiplyTo(ref drawCommand.OriginalMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); + drawCommand.Matrix.M41 -= drawCommand.Matrix.M11 * leftTopCornerOffset.X + drawCommand.Matrix.M21 * leftTopCornerOffset.Y; + drawCommand.Matrix.M42 -= drawCommand.Matrix.M12 * leftTopCornerOffset.X + drawCommand.Matrix.M22 * leftTopCornerOffset.Y; + drawCommand.Matrix.M43 -= drawCommand.Matrix.M13 * leftTopCornerOffset.X + drawCommand.Matrix.M23 * leftTopCornerOffset.Y; // do not snap static fonts when real/virtual resolution does not match. - if (font.FontType == SpriteFontType.SDF) + if(drawCommand.Batch.viewProjectionMatrix.M12 != 0f || + drawCommand.Batch.viewProjectionMatrix.M13 != 0f || + drawCommand.Batch.viewProjectionMatrix.M14 != 0f ) + { + // we are drawing in 3D, don't snap or scale + drawCommand.SnapText = false; + drawCommand.RealVirtualResolutionRatio.X = 1f; + drawCommand.RealVirtualResolutionRatio.Y = 1f; + } + else if (font.FontType == SpriteFontType.SDF) { drawCommand.SnapText = false; float scaling = drawCommand.RequestedFontSize / font.Size; @@ -460,9 +461,6 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI drawCommand.RealVirtualResolutionRatio = Vector2.One; // ensure that static font are not scaled internally } - - drawCommand.RealVirtualResolutionRatio.X = 1f; - drawCommand.RealVirtualResolutionRatio.Y = 1f; // snap draw start position to prevent characters to be drawn in between two pixels if (drawCommand.SnapText) From 80b6044664c6bf1aa4a110412b4864bc586728eb Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 9 Feb 2019 02:48:28 +0000 Subject: [PATCH 0009/2038] adding worldposition function --- .../engine/Xenko.Engine/Engine/TransformComponent.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sources/engine/Xenko.Engine/Engine/TransformComponent.cs b/sources/engine/Xenko.Engine/Engine/TransformComponent.cs index a1d2c23acb..f170b33571 100644 --- a/sources/engine/Xenko.Engine/Engine/TransformComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/TransformComponent.cs @@ -280,6 +280,16 @@ public void UpdateWorldMatrix() UpdateWorldMatrixInternal(true); } + /// + /// Gets the world position. + /// Default call does not recalcuate the position. It just gets the last frame's position quickly. + /// If you pass true to this function, it will update the world position (which is a costly procedure) to get the most up-to-date position. + /// + public Vector3 WorldPosition(bool recalculate = false) { + if (recalculate) UpdateWorldMatrix(); + return WorldMatrix.TranslationVector; + } + internal void UpdateWorldMatrixInternal(bool recursive) { if (TransformLink != null) From 3853a47e7d0f73ba96f32279c234989ffce1d18b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 15 Feb 2019 02:36:39 +0000 Subject: [PATCH 0010/2038] update OpenVR to v 1.2.10 and default to Vulkan --- deps/OpenVR/Windows/x64/openvr_api.dll | 4 +- deps/OpenVR/Windows/x86/openvr_api.dll | 4 +- .../$ProjectName$.csproj.t4 | 1 + .../Xenko.VirtualReality/OpenVR/OpenVR.cs | 6 +- .../Xenko.VirtualReality/OpenVR/openvr_api.cs | 3778 ++++++++++++----- sources/targets/Xenko.GlobalSettings.targets | 4 +- 6 files changed, 2811 insertions(+), 986 deletions(-) diff --git a/deps/OpenVR/Windows/x64/openvr_api.dll b/deps/OpenVR/Windows/x64/openvr_api.dll index eda79981b9..44d9da9802 100644 --- a/deps/OpenVR/Windows/x64/openvr_api.dll +++ b/deps/OpenVR/Windows/x64/openvr_api.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:877b038c01486f6014b7711f3d5d9f8c59d976d032edc8915261d2b5656d5098 -size 314656 +oid sha256:2ec24b0118667a52196b069b12e7248011362b223e8ed044a567c3a7a875f5df +size 598816 diff --git a/deps/OpenVR/Windows/x86/openvr_api.dll b/deps/OpenVR/Windows/x86/openvr_api.dll index 644ae0761c..807aa83b8e 100644 --- a/deps/OpenVR/Windows/x86/openvr_api.dll +++ b/deps/OpenVR/Windows/x86/openvr_api.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c4ddd7ea3fe7bfffa07867c07a7651b2a141e0d61aefe24b1d7dea7f832eafc2 -size 267040 +oid sha256:c71221b5263ddfa3fd6e6a62ec53eaeeab76cfb45b5e765c476546ba8eb8a81a +size 491808 diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 index 12d0e23916..f668fcefe7 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 @@ -3,6 +3,7 @@ net461 + win-vulkan Resources\Icon.ico WinExe <#= Properties.Namespace #> diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index d08110b364..b56700cda7 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -229,7 +229,7 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport { var tex = new Texture_t { - eType = EGraphicsAPIConvention.API_DirectX, + eType = ETextureType.Vulkan, eColorSpace = EColorSpace.Auto, handle = texture.NativeResource.NativePointer, }; @@ -387,7 +387,7 @@ private static unsafe void GetProjectionUnsafe(int eyeIndex, float near, float f { projection = Matrix.Identity; var eye = eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right; - var proj = Valve.VR.OpenVR.System.GetProjectionMatrix(eye, near, far, EGraphicsAPIConvention.API_DirectX); + var proj = Valve.VR.OpenVR.System.GetProjectionMatrix(eye, near, far); Utilities.CopyMemory((IntPtr)Interop.Fixed(ref projection), (IntPtr)Interop.Fixed(ref proj), Utilities.SizeOf()); } @@ -428,7 +428,7 @@ public static bool SubmitOverlay(ulong overlayId, Texture texture) { var tex = new Texture_t { - eType = EGraphicsAPIConvention.API_DirectX, + eType = ETextureType.Vulkan, eColorSpace = EColorSpace.Auto, handle = texture.NativeResource.NativePointer, }; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs b/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs index e52622f0c5..8926d29cd9 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs @@ -4,7 +4,7 @@ // This file is auto-generated, do not edit it. // //============================================================================= -/// + using System; using System.Runtime.InteropServices; using Valve.VR; @@ -13,7 +13,7 @@ namespace Valve.VR { [StructLayout(LayoutKind.Sequential)] -internal struct IVRSystem +public struct IVRSystem { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetRecommendedRenderTargetSize(ref uint pnWidth, ref uint pnHeight); @@ -21,7 +21,7 @@ internal struct IVRSystem internal _GetRecommendedRenderTargetSize GetRecommendedRenderTargetSize; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate HmdMatrix44_t _GetProjectionMatrix(EVREye eEye, float fNearZ, float fFarZ, EGraphicsAPIConvention eProjType); + internal delegate HmdMatrix44_t _GetProjectionMatrix(EVREye eEye, float fNearZ, float fFarZ); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetProjectionMatrix GetProjectionMatrix; @@ -55,6 +55,11 @@ internal struct IVRSystem [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDXGIOutputInfo GetDXGIOutputInfo; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _GetOutputDevice(ref ulong pnDevice, ETextureType textureType, IntPtr pInstance); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOutputDevice GetOutputDevice; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsDisplayOnDesktop(); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -145,6 +150,11 @@ internal struct IVRSystem [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetMatrix34TrackedDeviceProperty GetMatrix34TrackedDeviceProperty; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetArrayTrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, uint propType, IntPtr pBuffer, uint unBufferSize, ref ETrackedPropertyError pError); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetArrayTrackedDeviceProperty GetArrayTrackedDeviceProperty; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetStringTrackedDeviceProperty(uint unDeviceIndex, ETrackedDeviceProperty prop, System.Text.StringBuilder pchValue, uint unBufferSize, ref ETrackedPropertyError pError); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -186,7 +196,7 @@ internal struct IVRSystem internal _GetControllerStateWithPose GetControllerStateWithPose; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate void _TriggerHapticPulse(uint unControllerDeviceIndex, uint unAxisId, char usDurationMicroSec); + internal delegate void _TriggerHapticPulse(uint unControllerDeviceIndex, uint unAxisId, ushort usDurationMicroSec); [MarshalAs(UnmanagedType.FunctionPtr)] internal _TriggerHapticPulse TriggerHapticPulse; @@ -201,22 +211,27 @@ internal struct IVRSystem internal _GetControllerAxisTypeNameFromEnum GetControllerAxisTypeNameFromEnum; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _CaptureInputFocus(); + internal delegate bool _IsInputAvailable(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _IsInputAvailable IsInputAvailable; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _IsSteamVRDrawingControllers(); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _CaptureInputFocus CaptureInputFocus; + internal _IsSteamVRDrawingControllers IsSteamVRDrawingControllers; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate void _ReleaseInputFocus(); + internal delegate bool _ShouldApplicationPause(); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _ReleaseInputFocus ReleaseInputFocus; + internal _ShouldApplicationPause ShouldApplicationPause; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _IsInputFocusCapturedByAnotherProcess(); + internal delegate bool _ShouldApplicationReduceRenderingWork(); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _IsInputFocusCapturedByAnotherProcess IsInputFocusCapturedByAnotherProcess; + internal _ShouldApplicationReduceRenderingWork ShouldApplicationReduceRenderingWork; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate uint _DriverDebugRequest(uint unDeviceIndex, string pchRequest, string pchResponseBuffer, uint unResponseBufferSize); + internal delegate uint _DriverDebugRequest(uint unDeviceIndex, string pchRequest, System.Text.StringBuilder pchResponseBuffer, uint unResponseBufferSize); [MarshalAs(UnmanagedType.FunctionPtr)] internal _DriverDebugRequest DriverDebugRequest; @@ -238,7 +253,7 @@ internal struct IVRSystem } [StructLayout(LayoutKind.Sequential)] -internal struct IVRExtendedDisplay +public struct IVRExtendedDisplay { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _GetWindowBounds(ref int pnX, ref int pnY, ref uint pnWidth, ref uint pnHeight); @@ -258,7 +273,7 @@ internal struct IVRExtendedDisplay } [StructLayout(LayoutKind.Sequential)] -internal struct IVRTrackedCamera +public struct IVRTrackedCamera { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetCameraErrorNameFromEnum(EVRTrackedCameraError eCameraError); @@ -276,12 +291,12 @@ internal struct IVRTrackedCamera internal _GetCameraFrameSize GetCameraFrameSize; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVRTrackedCameraError _GetCameraIntrinisics(uint nDeviceIndex, EVRTrackedCameraFrameType eFrameType, ref HmdVector2_t pFocalLength, ref HmdVector2_t pCenter); + internal delegate EVRTrackedCameraError _GetCameraIntrinsics(uint nDeviceIndex, uint nCameraIndex, EVRTrackedCameraFrameType eFrameType, ref HmdVector2_t pFocalLength, ref HmdVector2_t pCenter); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetCameraIntrinisics GetCameraIntrinisics; + internal _GetCameraIntrinsics GetCameraIntrinsics; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVRTrackedCameraError _GetCameraProjection(uint nDeviceIndex, EVRTrackedCameraFrameType eFrameType, float flZNear, float flZFar, ref HmdMatrix44_t pProjection); + internal delegate EVRTrackedCameraError _GetCameraProjection(uint nDeviceIndex, uint nCameraIndex, EVRTrackedCameraFrameType eFrameType, float flZNear, float flZFar, ref HmdMatrix44_t pProjection); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetCameraProjection GetCameraProjection; @@ -323,7 +338,7 @@ internal struct IVRTrackedCamera } [StructLayout(LayoutKind.Sequential)] -internal struct IVRApplications +public struct IVRApplications { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _AddApplicationManifest(string pchApplicationManifestFullPath, bool bTemporary); @@ -351,7 +366,7 @@ internal struct IVRApplications internal _GetApplicationKeyByIndex GetApplicationKeyByIndex; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVRApplicationError _GetApplicationKeyByProcessId(uint unProcessId, string pchAppKeyBuffer, uint unAppKeyBufferLen); + internal delegate EVRApplicationError _GetApplicationKeyByProcessId(uint unProcessId, System.Text.StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationKeyByProcessId GetApplicationKeyByProcessId; @@ -426,27 +441,27 @@ internal struct IVRApplications internal _SetDefaultApplicationForMimeType SetDefaultApplicationForMimeType; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _GetDefaultApplicationForMimeType(string pchMimeType, string pchAppKeyBuffer, uint unAppKeyBufferLen); + internal delegate bool _GetDefaultApplicationForMimeType(string pchMimeType, System.Text.StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetDefaultApplicationForMimeType GetDefaultApplicationForMimeType; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _GetApplicationSupportedMimeTypes(string pchAppKey, string pchMimeTypesBuffer, uint unMimeTypesBuffer); + internal delegate bool _GetApplicationSupportedMimeTypes(string pchAppKey, System.Text.StringBuilder pchMimeTypesBuffer, uint unMimeTypesBuffer); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationSupportedMimeTypes GetApplicationSupportedMimeTypes; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate uint _GetApplicationsThatSupportMimeType(string pchMimeType, string pchAppKeysThatSupportBuffer, uint unAppKeysThatSupportBuffer); + internal delegate uint _GetApplicationsThatSupportMimeType(string pchMimeType, System.Text.StringBuilder pchAppKeysThatSupportBuffer, uint unAppKeysThatSupportBuffer); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationsThatSupportMimeType GetApplicationsThatSupportMimeType; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate uint _GetApplicationLaunchArguments(uint unHandle, string pchArgs, uint unArgs); + internal delegate uint _GetApplicationLaunchArguments(uint unHandle, System.Text.StringBuilder pchArgs, uint unArgs); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetApplicationLaunchArguments GetApplicationLaunchArguments; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVRApplicationError _GetStartingApplication(string pchAppKeyBuffer, uint unAppKeyBufferLen); + internal delegate EVRApplicationError _GetStartingApplication(System.Text.StringBuilder pchAppKeyBuffer, uint unAppKeyBufferLen); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetStartingApplication GetStartingApplication; @@ -475,10 +490,15 @@ internal struct IVRApplications [MarshalAs(UnmanagedType.FunctionPtr)] internal _LaunchInternalProcess LaunchInternalProcess; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetCurrentSceneProcessId(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetCurrentSceneProcessId GetCurrentSceneProcessId; + } [StructLayout(LayoutKind.Sequential)] -internal struct IVRChaperone +public struct IVRChaperone { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate ChaperoneCalibrationState _GetCalibrationState(); @@ -523,7 +543,7 @@ internal struct IVRChaperone } [StructLayout(LayoutKind.Sequential)] -internal struct IVRChaperoneSetup +public struct IVRChaperoneSetup { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _CommitWorkingCopy(EChaperoneConfigFile configFile); @@ -575,6 +595,11 @@ internal struct IVRChaperoneSetup [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetWorkingCollisionBoundsInfo SetWorkingCollisionBoundsInfo; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _SetWorkingPerimeter([In, Out] HmdVector2_t[] pPointBuffer, uint unPointCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetWorkingPerimeter SetWorkingPerimeter; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatSeatedZeroPoseToRawTrackingPose); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -596,39 +621,29 @@ internal struct IVRChaperoneSetup internal _GetLiveSeatedZeroPoseToRawTrackingPose GetLiveSeatedZeroPoseToRawTrackingPose; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate void _SetWorkingCollisionBoundsTagsInfo([In, Out] byte[] pTagsBuffer, uint unTagCount); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetWorkingCollisionBoundsTagsInfo SetWorkingCollisionBoundsTagsInfo; - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _GetLiveCollisionBoundsTagsInfo([In, Out] byte[] pTagsBuffer, ref uint punTagCount); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetLiveCollisionBoundsTagsInfo GetLiveCollisionBoundsTagsInfo; - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _SetWorkingPhysicalBoundsInfo([In, Out] HmdQuad_t[] pQuadsBuffer, uint unQuadsCount); + internal delegate bool _ExportLiveToBuffer(System.Text.StringBuilder pBuffer, ref uint pnBufferLength); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetWorkingPhysicalBoundsInfo SetWorkingPhysicalBoundsInfo; + internal _ExportLiveToBuffer ExportLiveToBuffer; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _GetLivePhysicalBoundsInfo([In, Out] HmdQuad_t[] pQuadsBuffer, ref uint punQuadsCount); + internal delegate bool _ImportFromBufferToWorking(string pBuffer, uint nImportFlags); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetLivePhysicalBoundsInfo GetLivePhysicalBoundsInfo; + internal _ImportFromBufferToWorking ImportFromBufferToWorking; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _ExportLiveToBuffer(System.Text.StringBuilder pBuffer, ref uint pnBufferLength); + internal delegate void _ShowWorkingSetPreview(); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _ExportLiveToBuffer ExportLiveToBuffer; + internal _ShowWorkingSetPreview ShowWorkingSetPreview; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _ImportFromBufferToWorking(string pBuffer, uint nImportFlags); + internal delegate void _HideWorkingSetPreview(); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _ImportFromBufferToWorking ImportFromBufferToWorking; + internal _HideWorkingSetPreview HideWorkingSetPreview; } [StructLayout(LayoutKind.Sequential)] -internal struct IVRCompositor +public struct IVRCompositor { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetTrackingSpace(ETrackingUniverseOrigin eOrigin); @@ -676,7 +691,7 @@ internal struct IVRCompositor internal _GetFrameTiming GetFrameTiming; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate uint _GetFrameTimings(ref Compositor_FrameTiming pTiming, uint nFrames); + internal delegate uint _GetFrameTimings([In, Out] Compositor_FrameTiming[] pTiming, uint nFrames); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetFrameTimings GetFrameTimings; @@ -800,6 +815,11 @@ internal struct IVRCompositor [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetMirrorTextureD3D11 GetMirrorTextureD3D11; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _ReleaseMirrorTextureD3D11(IntPtr pD3D11ShaderResourceView); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _ReleaseMirrorTextureD3D11 ReleaseMirrorTextureD3D11; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRCompositorError _GetMirrorTextureGL(EVREye eEye, ref uint pglTextureId, IntPtr pglSharedTextureHandle); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -820,10 +840,35 @@ internal struct IVRCompositor [MarshalAs(UnmanagedType.FunctionPtr)] internal _UnlockGLSharedTextureForAccess UnlockGLSharedTextureForAccess; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetVulkanInstanceExtensionsRequired(System.Text.StringBuilder pchValue, uint unBufferSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetVulkanInstanceExtensionsRequired GetVulkanInstanceExtensionsRequired; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetVulkanDeviceExtensionsRequired(IntPtr pPhysicalDevice, System.Text.StringBuilder pchValue, uint unBufferSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetVulkanDeviceExtensionsRequired GetVulkanDeviceExtensionsRequired; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _SetExplicitTimingMode(EVRCompositorTimingMode eTimingMode); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetExplicitTimingMode SetExplicitTimingMode; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRCompositorError _SubmitExplicitTimingData(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SubmitExplicitTimingData SubmitExplicitTimingData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _IsMotionSmoothingEnabled(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _IsMotionSmoothingEnabled IsMotionSmoothingEnabled; + } [StructLayout(LayoutKind.Sequential)] -internal struct IVROverlay +public struct IVROverlay { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _FindOverlay(string pchOverlayKey, ref ulong pOverlayHandle); @@ -831,7 +876,7 @@ internal struct IVROverlay internal _FindOverlay FindOverlay; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _CreateOverlay(string pchOverlayKey, string pchOverlayFriendlyName, ref ulong pOverlayHandle); + internal delegate EVROverlayError _CreateOverlay(string pchOverlayKey, string pchOverlayName, ref ulong pOverlayHandle); [MarshalAs(UnmanagedType.FunctionPtr)] internal _CreateOverlay CreateOverlay; @@ -860,6 +905,11 @@ internal struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayName GetOverlayName; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _SetOverlayName(ulong ulOverlayHandle, string pchName); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetOverlayName SetOverlayName; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayImageData(ulong ulOverlayHandle, IntPtr pvBuffer, uint unBufferSize, ref uint punWidth, ref uint punHeight); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -970,6 +1020,16 @@ internal struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTextureBounds GetOverlayTextureBounds; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetOverlayRenderModel(ulong ulOverlayHandle, System.Text.StringBuilder pchValue, uint unBufferSize, ref HmdColor_t pColor, ref EVROverlayError pError); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOverlayRenderModel GetOverlayRenderModel; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _SetOverlayRenderModel(ulong ulOverlayHandle, string pchRenderModel, ref HmdColor_t pColor); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetOverlayRenderModel SetOverlayRenderModel; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _GetOverlayTransformType(ulong ulOverlayHandle, ref VROverlayTransformType peTransformType); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1001,10 +1061,20 @@ internal struct IVROverlay internal _SetOverlayTransformTrackedDeviceComponent SetOverlayTransformTrackedDeviceComponent; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _GetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle, ref uint punDeviceIndex, string pchComponentName, uint unComponentNameSize); + internal delegate EVROverlayError _GetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle, ref uint punDeviceIndex, System.Text.StringBuilder pchComponentName, uint unComponentNameSize); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTransformTrackedDeviceComponent GetOverlayTransformTrackedDeviceComponent; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _GetOverlayTransformOverlayRelative(ulong ulOverlayHandle, ref ulong ulOverlayHandleParent, ref HmdMatrix34_t pmatParentOverlayToOverlayTransform); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOverlayTransformOverlayRelative GetOverlayTransformOverlayRelative; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _SetOverlayTransformOverlayRelative(ulong ulOverlayHandle, ulong ulOverlayHandleParent, ref HmdMatrix34_t pmatParentOverlayToOverlayTransform); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetOverlayTransformOverlayRelative SetOverlayTransformOverlayRelative; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ShowOverlay(ulong ulOverlayHandle); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1055,11 +1125,6 @@ internal struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _ComputeOverlayIntersection ComputeOverlayIntersection; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _HandleControllerOverlayInteractionAsMouse(ulong ulOverlayHandle, uint unControllerDeviceIndex); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _HandleControllerOverlayInteractionAsMouse HandleControllerOverlayInteractionAsMouse; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _IsHoverTargetOverlay(ulong ulOverlayHandle); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1085,6 +1150,16 @@ internal struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _MoveGamepadFocusToNeighbor MoveGamepadFocusToNeighbor; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _SetOverlayDualAnalogTransform(ulong ulOverlay, EDualAnalogWhich eWhich, ref HmdVector2_t pvCenter, float fRadius); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetOverlayDualAnalogTransform SetOverlayDualAnalogTransform; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _GetOverlayDualAnalogTransform(ulong ulOverlay, EDualAnalogWhich eWhich, ref HmdVector2_t pvCenter, ref float pfRadius); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOverlayDualAnalogTransform GetOverlayDualAnalogTransform; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTexture(ulong ulOverlayHandle, ref Texture_t pTexture); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1106,7 +1181,7 @@ internal struct IVROverlay internal _SetOverlayFromFile SetOverlayFromFile; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _GetOverlayTexture(ulong ulOverlayHandle, ref IntPtr pNativeTextureHandle, IntPtr pNativeTextureRef, ref uint pWidth, ref uint pHeight, ref uint pNativeFormat, ref EGraphicsAPIConvention pAPI, ref EColorSpace pColorSpace); + internal delegate EVROverlayError _GetOverlayTexture(ulong ulOverlayHandle, ref IntPtr pNativeTextureHandle, IntPtr pNativeTextureRef, ref uint pWidth, ref uint pHeight, ref uint pNativeFormat, ref ETextureType pAPIType, ref EColorSpace pColorSpace, ref VRTextureBounds_t pTextureBounds); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayTexture GetOverlayTexture; @@ -1190,10 +1265,25 @@ internal struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayIntersectionMask SetOverlayIntersectionMask; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _GetOverlayFlags(ulong ulOverlayHandle, ref uint pFlags); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOverlayFlags GetOverlayFlags; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate VRMessageOverlayResponse _ShowMessageOverlay(string pchText, string pchCaption, string pchButton0Text, string pchButton1Text, string pchButton2Text, string pchButton3Text); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _ShowMessageOverlay ShowMessageOverlay; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _CloseMessageOverlay(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _CloseMessageOverlay CloseMessageOverlay; + } [StructLayout(LayoutKind.Sequential)] -internal struct IVRRenderModels +public struct IVRRenderModels { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRRenderModelError _LoadRenderModel_Async(string pchRenderModelName, ref IntPtr ppRenderModel); @@ -1260,6 +1350,11 @@ internal struct IVRRenderModels [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetComponentRenderModelName GetComponentRenderModelName; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _GetComponentStateForDevicePath(string pchRenderModelName, string pchComponentName, ulong devicePath, ref RenderModel_ControllerMode_State_t pState, ref RenderModel_ComponentState_t pComponentState); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetComponentStateForDevicePath GetComponentStateForDevicePath; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate bool _GetComponentState(string pchRenderModelName, string pchComponentName, ref VRControllerState_t pControllerState, ref RenderModel_ControllerMode_State_t pState, ref RenderModel_ComponentState_t pComponentState); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1288,7 +1383,7 @@ internal struct IVRRenderModels } [StructLayout(LayoutKind.Sequential)] -internal struct IVRNotifications +public struct IVRNotifications { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRNotificationError _CreateNotification(ulong ulOverlayHandle, ulong ulUserValue, EVRNotificationType type, string pchText, EVRNotificationStyle style, ref NotificationBitmap_t pImage, ref uint pNotificationId); @@ -1303,7 +1398,7 @@ internal struct IVRNotifications } [StructLayout(LayoutKind.Sequential)] -internal struct IVRSettings +public struct IVRSettings { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate IntPtr _GetSettingsErrorNameFromEnum(EVRSettingsError eError); @@ -1368,7 +1463,7 @@ internal struct IVRSettings } [StructLayout(LayoutKind.Sequential)] -internal struct IVRScreenshots +public struct IVRScreenshots { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRScreenshotError _RequestScreenshot(ref uint pOutScreenshotHandle, EVRScreenshotType type, string pchPreviewFilename, string pchVRFilename); @@ -1408,7 +1503,7 @@ internal struct IVRScreenshots } [StructLayout(LayoutKind.Sequential)] -internal struct IVRResources +public struct IVRResources { [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _LoadSharedResource(string pchResourceName, string pchBuffer, uint unBufferLen); @@ -1416,32 +1511,237 @@ internal struct IVRResources internal _LoadSharedResource LoadSharedResource; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate uint _GetResourceFullPath(string pchResourceName, string pchResourceTypeDirectory, string pchPathBuffer, uint unBufferLen); + internal delegate uint _GetResourceFullPath(string pchResourceName, string pchResourceTypeDirectory, System.Text.StringBuilder pchPathBuffer, uint unBufferLen); [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetResourceFullPath GetResourceFullPath; } +[StructLayout(LayoutKind.Sequential)] +public struct IVRDriverManager +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetDriverCount(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetDriverCount GetDriverCount; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate uint _GetDriverName(uint nDriver, System.Text.StringBuilder pchValue, uint unBufferSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetDriverName GetDriverName; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate ulong _GetDriverHandle(string pchDriverName); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetDriverHandle GetDriverHandle; + +} + +[StructLayout(LayoutKind.Sequential)] +public struct IVRInput +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _SetActionManifestPath(string pchActionManifestPath); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetActionManifestPath SetActionManifestPath; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetActionSetHandle(string pchActionSetName, ref ulong pHandle); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetActionSetHandle GetActionSetHandle; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetActionHandle(string pchActionName, ref ulong pHandle); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetActionHandle GetActionHandle; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetInputSourceHandle(string pchInputSourcePath, ref ulong pHandle); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetInputSourceHandle GetInputSourceHandle; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _UpdateActionState([In, Out] VRActiveActionSet_t[] pSets, uint unSizeOfVRSelectedActionSet_t, uint unSetCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _UpdateActionState UpdateActionState; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetDigitalActionData(ulong action, ref InputDigitalActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetDigitalActionData GetDigitalActionData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetAnalogActionData(ulong action, ref InputAnalogActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetAnalogActionData GetAnalogActionData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetPoseActionData(ulong action, ETrackingUniverseOrigin eOrigin, float fPredictedSecondsFromNow, ref InputPoseActionData_t pActionData, uint unActionDataSize, ulong ulRestrictToDevice); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetPoseActionData GetPoseActionData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetSkeletalActionData(ulong action, ref InputSkeletalActionData_t pActionData, uint unActionDataSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSkeletalActionData GetSkeletalActionData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetBoneCount(ulong action, ref uint pBoneCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetBoneCount GetBoneCount; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetBoneHierarchy(ulong action, [In, Out] int[] pParentIndices, uint unIndexArayCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetBoneHierarchy GetBoneHierarchy; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetBoneName(ulong action, int nBoneIndex, System.Text.StringBuilder pchBoneName, uint unNameBufferSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetBoneName GetBoneName; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetSkeletalReferenceTransforms(ulong action, EVRSkeletalTransformSpace eTransformSpace, EVRSkeletalReferencePose eReferencePose, [In, Out] VRBoneTransform_t[] pTransformArray, uint unTransformArrayCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSkeletalReferenceTransforms GetSkeletalReferenceTransforms; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetSkeletalTrackingLevel(ulong action, ref EVRSkeletalTrackingLevel pSkeletalTrackingLevel); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSkeletalTrackingLevel GetSkeletalTrackingLevel; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetSkeletalBoneData(ulong action, EVRSkeletalTransformSpace eTransformSpace, EVRSkeletalMotionRange eMotionRange, [In, Out] VRBoneTransform_t[] pTransformArray, uint unTransformArrayCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSkeletalBoneData GetSkeletalBoneData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetSkeletalSummaryData(ulong action, ref VRSkeletalSummaryData_t pSkeletalSummaryData); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSkeletalSummaryData GetSkeletalSummaryData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetSkeletalBoneDataCompressed(ulong action, EVRSkeletalMotionRange eMotionRange, IntPtr pvCompressedData, uint unCompressedSize, ref uint punRequiredCompressedSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSkeletalBoneDataCompressed GetSkeletalBoneDataCompressed; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _DecompressSkeletalBoneData(IntPtr pvCompressedBuffer, uint unCompressedBufferSize, EVRSkeletalTransformSpace eTransformSpace, [In, Out] VRBoneTransform_t[] pTransformArray, uint unTransformArrayCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _DecompressSkeletalBoneData DecompressSkeletalBoneData; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _TriggerHapticVibrationAction(ulong action, float fStartSecondsFromNow, float fDurationSeconds, float fFrequency, float fAmplitude, ulong ulRestrictToDevice); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _TriggerHapticVibrationAction TriggerHapticVibrationAction; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetActionOrigins(ulong actionSetHandle, ulong digitalActionHandle, [In, Out] ulong[] originsOut, uint originOutCount); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetActionOrigins GetActionOrigins; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetOriginLocalizedName(ulong origin, System.Text.StringBuilder pchNameArray, uint unNameArraySize, int unStringSectionsToInclude); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOriginLocalizedName GetOriginLocalizedName; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _GetOriginTrackedDeviceInfo(ulong origin, ref InputOriginInfo_t pOriginInfo, uint unOriginInfoSize); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOriginTrackedDeviceInfo GetOriginTrackedDeviceInfo; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _ShowActionOrigins(ulong actionSetHandle, ulong ulActionHandle); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _ShowActionOrigins ShowActionOrigins; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _ShowBindingsForActionSet([In, Out] VRActiveActionSet_t[] pSets, uint unSizeOfVRSelectedActionSet_t, uint unSetCount, ulong originToHighlight); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _ShowBindingsForActionSet ShowBindingsForActionSet; + +} + +[StructLayout(LayoutKind.Sequential)] +public struct IVRIOBuffer +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EIOBufferError _Open(string pchPath, EIOBufferMode mode, uint unElementSize, uint unElements, ref ulong pulBuffer); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _Open Open; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EIOBufferError _Close(ulong ulBuffer); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _Close Close; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EIOBufferError _Read(ulong ulBuffer, IntPtr pDst, uint unBytes, ref uint punRead); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _Read Read; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EIOBufferError _Write(ulong ulBuffer, IntPtr pSrc, uint unBytes); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _Write Write; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate ulong _PropertyContainer(ulong ulBuffer); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _PropertyContainer PropertyContainer; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _HasReaders(ulong ulBuffer); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _HasReaders HasReaders; + +} + +[StructLayout(LayoutKind.Sequential)] +public struct IVRSpatialAnchors +{ + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRSpatialAnchorError _CreateSpatialAnchorFromDescriptor(string pchDescriptor, ref uint pHandleOut); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _CreateSpatialAnchorFromDescriptor CreateSpatialAnchorFromDescriptor; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRSpatialAnchorError _CreateSpatialAnchorFromPose(uint unDeviceIndex, ETrackingUniverseOrigin eOrigin, ref SpatialAnchorPose_t pPose, ref uint pHandleOut); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _CreateSpatialAnchorFromPose CreateSpatialAnchorFromPose; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRSpatialAnchorError _GetSpatialAnchorPose(uint unHandle, ETrackingUniverseOrigin eOrigin, ref SpatialAnchorPose_t pPoseOut); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSpatialAnchorPose GetSpatialAnchorPose; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRSpatialAnchorError _GetSpatialAnchorDescriptor(uint unHandle, System.Text.StringBuilder pchDescriptorOut, ref uint punDescriptorBufferLenInOut); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetSpatialAnchorDescriptor GetSpatialAnchorDescriptor; + +} + -internal class CVRSystem +public class CVRSystem { IVRSystem FnTable; internal CVRSystem(IntPtr pInterface) { FnTable = (IVRSystem)Marshal.PtrToStructure(pInterface, typeof(IVRSystem)); } - internal void GetRecommendedRenderTargetSize(ref uint pnWidth,ref uint pnHeight) + public void GetRecommendedRenderTargetSize(ref uint pnWidth,ref uint pnHeight) { pnWidth = 0; pnHeight = 0; FnTable.GetRecommendedRenderTargetSize(ref pnWidth,ref pnHeight); } - internal HmdMatrix44_t GetProjectionMatrix(EVREye eEye,float fNearZ,float fFarZ,EGraphicsAPIConvention eProjType) + public HmdMatrix44_t GetProjectionMatrix(EVREye eEye,float fNearZ,float fFarZ) { - HmdMatrix44_t result = FnTable.GetProjectionMatrix(eEye,fNearZ,fFarZ,eProjType); + HmdMatrix44_t result = FnTable.GetProjectionMatrix(eEye,fNearZ,fFarZ); return result; } - internal void GetProjectionRaw(EVREye eEye,ref float pfLeft,ref float pfRight,ref float pfTop,ref float pfBottom) + public void GetProjectionRaw(EVREye eEye,ref float pfLeft,ref float pfRight,ref float pfTop,ref float pfBottom) { pfLeft = 0; pfRight = 0; @@ -1449,217 +1749,311 @@ internal void GetProjectionRaw(EVREye eEye,ref float pfLeft,ref float pfRight,re pfBottom = 0; FnTable.GetProjectionRaw(eEye,ref pfLeft,ref pfRight,ref pfTop,ref pfBottom); } - internal bool ComputeDistortion(EVREye eEye,float fU,float fV,ref DistortionCoordinates_t pDistortionCoordinates) + public bool ComputeDistortion(EVREye eEye,float fU,float fV,ref DistortionCoordinates_t pDistortionCoordinates) { bool result = FnTable.ComputeDistortion(eEye,fU,fV,ref pDistortionCoordinates); return result; } - internal HmdMatrix34_t GetEyeToHeadTransform(EVREye eEye) + public HmdMatrix34_t GetEyeToHeadTransform(EVREye eEye) { HmdMatrix34_t result = FnTable.GetEyeToHeadTransform(eEye); return result; } - internal bool GetTimeSinceLastVsync(ref float pfSecondsSinceLastVsync,ref ulong pulFrameCounter) + public bool GetTimeSinceLastVsync(ref float pfSecondsSinceLastVsync,ref ulong pulFrameCounter) { pfSecondsSinceLastVsync = 0; pulFrameCounter = 0; bool result = FnTable.GetTimeSinceLastVsync(ref pfSecondsSinceLastVsync,ref pulFrameCounter); return result; } - internal int GetD3D9AdapterIndex() + public int GetD3D9AdapterIndex() { int result = FnTable.GetD3D9AdapterIndex(); return result; } - internal void GetDXGIOutputInfo(ref int pnAdapterIndex) + public void GetDXGIOutputInfo(ref int pnAdapterIndex) { pnAdapterIndex = 0; FnTable.GetDXGIOutputInfo(ref pnAdapterIndex); } - internal bool IsDisplayOnDesktop() + public void GetOutputDevice(ref ulong pnDevice,ETextureType textureType,IntPtr pInstance) + { + pnDevice = 0; + FnTable.GetOutputDevice(ref pnDevice,textureType,pInstance); + } + public bool IsDisplayOnDesktop() { bool result = FnTable.IsDisplayOnDesktop(); return result; } - internal bool SetDisplayVisibility(bool bIsVisibleOnDesktop) + public bool SetDisplayVisibility(bool bIsVisibleOnDesktop) { bool result = FnTable.SetDisplayVisibility(bIsVisibleOnDesktop); return result; } - internal void GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin eOrigin,float fPredictedSecondsToPhotonsFromNow,TrackedDevicePose_t [] pTrackedDevicePoseArray) + public void GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin eOrigin,float fPredictedSecondsToPhotonsFromNow,TrackedDevicePose_t [] pTrackedDevicePoseArray) { FnTable.GetDeviceToAbsoluteTrackingPose(eOrigin,fPredictedSecondsToPhotonsFromNow,pTrackedDevicePoseArray,(uint) pTrackedDevicePoseArray.Length); } - internal void ResetSeatedZeroPose() + public void ResetSeatedZeroPose() { FnTable.ResetSeatedZeroPose(); } - internal HmdMatrix34_t GetSeatedZeroPoseToStandingAbsoluteTrackingPose() + public HmdMatrix34_t GetSeatedZeroPoseToStandingAbsoluteTrackingPose() { HmdMatrix34_t result = FnTable.GetSeatedZeroPoseToStandingAbsoluteTrackingPose(); return result; } - internal HmdMatrix34_t GetRawZeroPoseToStandingAbsoluteTrackingPose() + public HmdMatrix34_t GetRawZeroPoseToStandingAbsoluteTrackingPose() { HmdMatrix34_t result = FnTable.GetRawZeroPoseToStandingAbsoluteTrackingPose(); return result; } - internal uint GetSortedTrackedDeviceIndicesOfClass(ETrackedDeviceClass eTrackedDeviceClass,uint [] punTrackedDeviceIndexArray,uint unRelativeToTrackedDeviceIndex) + public uint GetSortedTrackedDeviceIndicesOfClass(ETrackedDeviceClass eTrackedDeviceClass,uint [] punTrackedDeviceIndexArray,uint unRelativeToTrackedDeviceIndex) { uint result = FnTable.GetSortedTrackedDeviceIndicesOfClass(eTrackedDeviceClass,punTrackedDeviceIndexArray,(uint) punTrackedDeviceIndexArray.Length,unRelativeToTrackedDeviceIndex); return result; } - internal EDeviceActivityLevel GetTrackedDeviceActivityLevel(uint unDeviceId) + public EDeviceActivityLevel GetTrackedDeviceActivityLevel(uint unDeviceId) { EDeviceActivityLevel result = FnTable.GetTrackedDeviceActivityLevel(unDeviceId); return result; } - internal void ApplyTransform(ref TrackedDevicePose_t pOutputPose,ref TrackedDevicePose_t pTrackedDevicePose,ref HmdMatrix34_t pTransform) + public void ApplyTransform(ref TrackedDevicePose_t pOutputPose,ref TrackedDevicePose_t pTrackedDevicePose,ref HmdMatrix34_t pTransform) { FnTable.ApplyTransform(ref pOutputPose,ref pTrackedDevicePose,ref pTransform); } - internal uint GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType) + public uint GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole unDeviceType) { uint result = FnTable.GetTrackedDeviceIndexForControllerRole(unDeviceType); return result; } - internal ETrackedControllerRole GetControllerRoleForTrackedDeviceIndex(uint unDeviceIndex) + public ETrackedControllerRole GetControllerRoleForTrackedDeviceIndex(uint unDeviceIndex) { ETrackedControllerRole result = FnTable.GetControllerRoleForTrackedDeviceIndex(unDeviceIndex); return result; } - internal ETrackedDeviceClass GetTrackedDeviceClass(uint unDeviceIndex) + public ETrackedDeviceClass GetTrackedDeviceClass(uint unDeviceIndex) { ETrackedDeviceClass result = FnTable.GetTrackedDeviceClass(unDeviceIndex); return result; } - internal bool IsTrackedDeviceConnected(uint unDeviceIndex) + public bool IsTrackedDeviceConnected(uint unDeviceIndex) { bool result = FnTable.IsTrackedDeviceConnected(unDeviceIndex); return result; } - internal bool GetBoolTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) + public bool GetBoolTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) { bool result = FnTable.GetBoolTrackedDeviceProperty(unDeviceIndex,prop,ref pError); return result; } - internal float GetFloatTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) + public float GetFloatTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) { float result = FnTable.GetFloatTrackedDeviceProperty(unDeviceIndex,prop,ref pError); return result; } - internal int GetInt32TrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) + public int GetInt32TrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) { int result = FnTable.GetInt32TrackedDeviceProperty(unDeviceIndex,prop,ref pError); return result; } - internal ulong GetUint64TrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) + public ulong GetUint64TrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) { ulong result = FnTable.GetUint64TrackedDeviceProperty(unDeviceIndex,prop,ref pError); return result; } - internal HmdMatrix34_t GetMatrix34TrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) + public HmdMatrix34_t GetMatrix34TrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,ref ETrackedPropertyError pError) { HmdMatrix34_t result = FnTable.GetMatrix34TrackedDeviceProperty(unDeviceIndex,prop,ref pError); return result; } - internal uint GetStringTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,System.Text.StringBuilder pchValue,uint unBufferSize,ref ETrackedPropertyError pError) + public uint GetArrayTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,uint propType,IntPtr pBuffer,uint unBufferSize,ref ETrackedPropertyError pError) + { + uint result = FnTable.GetArrayTrackedDeviceProperty(unDeviceIndex,prop,propType,pBuffer,unBufferSize,ref pError); + return result; + } + public uint GetStringTrackedDeviceProperty(uint unDeviceIndex,ETrackedDeviceProperty prop,System.Text.StringBuilder pchValue,uint unBufferSize,ref ETrackedPropertyError pError) { uint result = FnTable.GetStringTrackedDeviceProperty(unDeviceIndex,prop,pchValue,unBufferSize,ref pError); return result; } - internal string GetPropErrorNameFromEnum(ETrackedPropertyError error) + public string GetPropErrorNameFromEnum(ETrackedPropertyError error) { IntPtr result = FnTable.GetPropErrorNameFromEnum(error); return Marshal.PtrToStringAnsi(result); } - internal bool PollNextEvent(ref VREvent_t pEvent,uint uncbVREvent) +// This is a terrible hack to workaround the fact that VRControllerState_t and VREvent_t were +// originally mis-compiled with the wrong packing for Linux and OSX. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _PollNextEventPacked(ref VREvent_t_Packed pEvent,uint uncbVREvent); + [StructLayout(LayoutKind.Explicit)] + struct PollNextEventUnion + { + [FieldOffset(0)] + public IVRSystem._PollNextEvent pPollNextEvent; + [FieldOffset(0)] + public _PollNextEventPacked pPollNextEventPacked; + } + public bool PollNextEvent(ref VREvent_t pEvent,uint uncbVREvent) { +#if !UNITY_METRO + if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) || + (System.Environment.OSVersion.Platform == System.PlatformID.Unix)) + { + PollNextEventUnion u; + VREvent_t_Packed event_packed = new VREvent_t_Packed(); + u.pPollNextEventPacked = null; + u.pPollNextEvent = FnTable.PollNextEvent; + bool packed_result = u.pPollNextEventPacked(ref event_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VREvent_t_Packed))); + + event_packed.Unpack(ref pEvent); + return packed_result; + } +#endif bool result = FnTable.PollNextEvent(ref pEvent,uncbVREvent); return result; } - internal bool PollNextEventWithPose(ETrackingUniverseOrigin eOrigin,ref VREvent_t pEvent,uint uncbVREvent,ref TrackedDevicePose_t pTrackedDevicePose) + public bool PollNextEventWithPose(ETrackingUniverseOrigin eOrigin,ref VREvent_t pEvent,uint uncbVREvent,ref TrackedDevicePose_t pTrackedDevicePose) { bool result = FnTable.PollNextEventWithPose(eOrigin,ref pEvent,uncbVREvent,ref pTrackedDevicePose); return result; } - internal string GetEventTypeNameFromEnum(EVREventType eType) + public string GetEventTypeNameFromEnum(EVREventType eType) { IntPtr result = FnTable.GetEventTypeNameFromEnum(eType); return Marshal.PtrToStringAnsi(result); } - internal HiddenAreaMesh_t GetHiddenAreaMesh(EVREye eEye,EHiddenAreaMeshType type) + public HiddenAreaMesh_t GetHiddenAreaMesh(EVREye eEye,EHiddenAreaMeshType type) { HiddenAreaMesh_t result = FnTable.GetHiddenAreaMesh(eEye,type); return result; } - internal bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize) +// This is a terrible hack to workaround the fact that VRControllerState_t and VREvent_t were +// originally mis-compiled with the wrong packing for Linux and OSX. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _GetControllerStatePacked(uint unControllerDeviceIndex,ref VRControllerState_t_Packed pControllerState,uint unControllerStateSize); + [StructLayout(LayoutKind.Explicit)] + struct GetControllerStateUnion + { + [FieldOffset(0)] + public IVRSystem._GetControllerState pGetControllerState; + [FieldOffset(0)] + public _GetControllerStatePacked pGetControllerStatePacked; + } + public bool GetControllerState(uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize) { +#if !UNITY_METRO + if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) || + (System.Environment.OSVersion.Platform == System.PlatformID.Unix)) + { + GetControllerStateUnion u; + VRControllerState_t_Packed state_packed = new VRControllerState_t_Packed(pControllerState); + u.pGetControllerStatePacked = null; + u.pGetControllerState = FnTable.GetControllerState; + bool packed_result = u.pGetControllerStatePacked(unControllerDeviceIndex,ref state_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t_Packed))); + + state_packed.Unpack(ref pControllerState); + return packed_result; + } +#endif bool result = FnTable.GetControllerState(unControllerDeviceIndex,ref pControllerState,unControllerStateSize); return result; } - internal bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize,ref TrackedDevicePose_t pTrackedDevicePose) +// This is a terrible hack to workaround the fact that VRControllerState_t and VREvent_t were +// originally mis-compiled with the wrong packing for Linux and OSX. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _GetControllerStateWithPosePacked(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t_Packed pControllerState,uint unControllerStateSize,ref TrackedDevicePose_t pTrackedDevicePose); + [StructLayout(LayoutKind.Explicit)] + struct GetControllerStateWithPoseUnion + { + [FieldOffset(0)] + public IVRSystem._GetControllerStateWithPose pGetControllerStateWithPose; + [FieldOffset(0)] + public _GetControllerStateWithPosePacked pGetControllerStateWithPosePacked; + } + public bool GetControllerStateWithPose(ETrackingUniverseOrigin eOrigin,uint unControllerDeviceIndex,ref VRControllerState_t pControllerState,uint unControllerStateSize,ref TrackedDevicePose_t pTrackedDevicePose) { +#if !UNITY_METRO + if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) || + (System.Environment.OSVersion.Platform == System.PlatformID.Unix)) + { + GetControllerStateWithPoseUnion u; + VRControllerState_t_Packed state_packed = new VRControllerState_t_Packed(pControllerState); + u.pGetControllerStateWithPosePacked = null; + u.pGetControllerStateWithPose = FnTable.GetControllerStateWithPose; + bool packed_result = u.pGetControllerStateWithPosePacked(eOrigin,unControllerDeviceIndex,ref state_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t_Packed)),ref pTrackedDevicePose); + + state_packed.Unpack(ref pControllerState); + return packed_result; + } +#endif bool result = FnTable.GetControllerStateWithPose(eOrigin,unControllerDeviceIndex,ref pControllerState,unControllerStateSize,ref pTrackedDevicePose); return result; } - internal void TriggerHapticPulse(uint unControllerDeviceIndex,uint unAxisId,char usDurationMicroSec) + public void TriggerHapticPulse(uint unControllerDeviceIndex,uint unAxisId,ushort usDurationMicroSec) { FnTable.TriggerHapticPulse(unControllerDeviceIndex,unAxisId,usDurationMicroSec); } - internal string GetButtonIdNameFromEnum(EVRButtonId eButtonId) + public string GetButtonIdNameFromEnum(EVRButtonId eButtonId) { IntPtr result = FnTable.GetButtonIdNameFromEnum(eButtonId); return Marshal.PtrToStringAnsi(result); } - internal string GetControllerAxisTypeNameFromEnum(EVRControllerAxisType eAxisType) + public string GetControllerAxisTypeNameFromEnum(EVRControllerAxisType eAxisType) { IntPtr result = FnTable.GetControllerAxisTypeNameFromEnum(eAxisType); return Marshal.PtrToStringAnsi(result); } - internal bool CaptureInputFocus() + public bool IsInputAvailable() + { + bool result = FnTable.IsInputAvailable(); + return result; + } + public bool IsSteamVRDrawingControllers() { - bool result = FnTable.CaptureInputFocus(); + bool result = FnTable.IsSteamVRDrawingControllers(); return result; } - internal void ReleaseInputFocus() + public bool ShouldApplicationPause() { - FnTable.ReleaseInputFocus(); + bool result = FnTable.ShouldApplicationPause(); + return result; } - internal bool IsInputFocusCapturedByAnotherProcess() + public bool ShouldApplicationReduceRenderingWork() { - bool result = FnTable.IsInputFocusCapturedByAnotherProcess(); + bool result = FnTable.ShouldApplicationReduceRenderingWork(); return result; } - internal uint DriverDebugRequest(uint unDeviceIndex,string pchRequest,string pchResponseBuffer,uint unResponseBufferSize) + public uint DriverDebugRequest(uint unDeviceIndex,string pchRequest,System.Text.StringBuilder pchResponseBuffer,uint unResponseBufferSize) { uint result = FnTable.DriverDebugRequest(unDeviceIndex,pchRequest,pchResponseBuffer,unResponseBufferSize); return result; } - internal EVRFirmwareError PerformFirmwareUpdate(uint unDeviceIndex) + public EVRFirmwareError PerformFirmwareUpdate(uint unDeviceIndex) { EVRFirmwareError result = FnTable.PerformFirmwareUpdate(unDeviceIndex); return result; } - internal void AcknowledgeQuit_Exiting() + public void AcknowledgeQuit_Exiting() { FnTable.AcknowledgeQuit_Exiting(); } - internal void AcknowledgeQuit_UserPrompt() + public void AcknowledgeQuit_UserPrompt() { FnTable.AcknowledgeQuit_UserPrompt(); } } -internal class CVRExtendedDisplay +public class CVRExtendedDisplay { IVRExtendedDisplay FnTable; internal CVRExtendedDisplay(IntPtr pInterface) { FnTable = (IVRExtendedDisplay)Marshal.PtrToStructure(pInterface, typeof(IVRExtendedDisplay)); } - internal void GetWindowBounds(ref int pnX,ref int pnY,ref uint pnWidth,ref uint pnHeight) + public void GetWindowBounds(ref int pnX,ref int pnY,ref uint pnWidth,ref uint pnHeight) { pnX = 0; pnY = 0; @@ -1667,7 +2061,7 @@ internal void GetWindowBounds(ref int pnX,ref int pnY,ref uint pnWidth,ref uint pnHeight = 0; FnTable.GetWindowBounds(ref pnX,ref pnY,ref pnWidth,ref pnHeight); } - internal void GetEyeOutputViewport(EVREye eEye,ref uint pnX,ref uint pnY,ref uint pnWidth,ref uint pnHeight) + public void GetEyeOutputViewport(EVREye eEye,ref uint pnX,ref uint pnY,ref uint pnWidth,ref uint pnHeight) { pnX = 0; pnY = 0; @@ -1675,7 +2069,7 @@ internal void GetEyeOutputViewport(EVREye eEye,ref uint pnX,ref uint pnY,ref uin pnHeight = 0; FnTable.GetEyeOutputViewport(eEye,ref pnX,ref pnY,ref pnWidth,ref pnHeight); } - internal void GetDXGIOutputInfo(ref int pnAdapterIndex,ref int pnAdapterOutputIndex) + public void GetDXGIOutputInfo(ref int pnAdapterIndex,ref int pnAdapterOutputIndex) { pnAdapterIndex = 0; pnAdapterOutputIndex = 0; @@ -1684,25 +2078,25 @@ internal void GetDXGIOutputInfo(ref int pnAdapterIndex,ref int pnAdapterOutputIn } -internal class CVRTrackedCamera +public class CVRTrackedCamera { IVRTrackedCamera FnTable; internal CVRTrackedCamera(IntPtr pInterface) { FnTable = (IVRTrackedCamera)Marshal.PtrToStructure(pInterface, typeof(IVRTrackedCamera)); } - internal string GetCameraErrorNameFromEnum(EVRTrackedCameraError eCameraError) + public string GetCameraErrorNameFromEnum(EVRTrackedCameraError eCameraError) { IntPtr result = FnTable.GetCameraErrorNameFromEnum(eCameraError); return Marshal.PtrToStringAnsi(result); } - internal EVRTrackedCameraError HasCamera(uint nDeviceIndex,ref bool pHasCamera) + public EVRTrackedCameraError HasCamera(uint nDeviceIndex,ref bool pHasCamera) { pHasCamera = false; EVRTrackedCameraError result = FnTable.HasCamera(nDeviceIndex,ref pHasCamera); return result; } - internal EVRTrackedCameraError GetCameraFrameSize(uint nDeviceIndex,EVRTrackedCameraFrameType eFrameType,ref uint pnWidth,ref uint pnHeight,ref uint pnFrameBufferSize) + public EVRTrackedCameraError GetCameraFrameSize(uint nDeviceIndex,EVRTrackedCameraFrameType eFrameType,ref uint pnWidth,ref uint pnHeight,ref uint pnFrameBufferSize) { pnWidth = 0; pnHeight = 0; @@ -1710,51 +2104,51 @@ internal EVRTrackedCameraError GetCameraFrameSize(uint nDeviceIndex,EVRTrackedCa EVRTrackedCameraError result = FnTable.GetCameraFrameSize(nDeviceIndex,eFrameType,ref pnWidth,ref pnHeight,ref pnFrameBufferSize); return result; } - internal EVRTrackedCameraError GetCameraIntrinisics(uint nDeviceIndex,EVRTrackedCameraFrameType eFrameType,ref HmdVector2_t pFocalLength,ref HmdVector2_t pCenter) + public EVRTrackedCameraError GetCameraIntrinsics(uint nDeviceIndex,uint nCameraIndex,EVRTrackedCameraFrameType eFrameType,ref HmdVector2_t pFocalLength,ref HmdVector2_t pCenter) { - EVRTrackedCameraError result = FnTable.GetCameraIntrinisics(nDeviceIndex,eFrameType,ref pFocalLength,ref pCenter); + EVRTrackedCameraError result = FnTable.GetCameraIntrinsics(nDeviceIndex,nCameraIndex,eFrameType,ref pFocalLength,ref pCenter); return result; } - internal EVRTrackedCameraError GetCameraProjection(uint nDeviceIndex,EVRTrackedCameraFrameType eFrameType,float flZNear,float flZFar,ref HmdMatrix44_t pProjection) + public EVRTrackedCameraError GetCameraProjection(uint nDeviceIndex,uint nCameraIndex,EVRTrackedCameraFrameType eFrameType,float flZNear,float flZFar,ref HmdMatrix44_t pProjection) { - EVRTrackedCameraError result = FnTable.GetCameraProjection(nDeviceIndex,eFrameType,flZNear,flZFar,ref pProjection); + EVRTrackedCameraError result = FnTable.GetCameraProjection(nDeviceIndex,nCameraIndex,eFrameType,flZNear,flZFar,ref pProjection); return result; } - internal EVRTrackedCameraError AcquireVideoStreamingService(uint nDeviceIndex,ref ulong pHandle) + public EVRTrackedCameraError AcquireVideoStreamingService(uint nDeviceIndex,ref ulong pHandle) { pHandle = 0; EVRTrackedCameraError result = FnTable.AcquireVideoStreamingService(nDeviceIndex,ref pHandle); return result; } - internal EVRTrackedCameraError ReleaseVideoStreamingService(ulong hTrackedCamera) + public EVRTrackedCameraError ReleaseVideoStreamingService(ulong hTrackedCamera) { EVRTrackedCameraError result = FnTable.ReleaseVideoStreamingService(hTrackedCamera); return result; } - internal EVRTrackedCameraError GetVideoStreamFrameBuffer(ulong hTrackedCamera,EVRTrackedCameraFrameType eFrameType,IntPtr pFrameBuffer,uint nFrameBufferSize,ref CameraVideoStreamFrameHeader_t pFrameHeader,uint nFrameHeaderSize) + public EVRTrackedCameraError GetVideoStreamFrameBuffer(ulong hTrackedCamera,EVRTrackedCameraFrameType eFrameType,IntPtr pFrameBuffer,uint nFrameBufferSize,ref CameraVideoStreamFrameHeader_t pFrameHeader,uint nFrameHeaderSize) { EVRTrackedCameraError result = FnTable.GetVideoStreamFrameBuffer(hTrackedCamera,eFrameType,pFrameBuffer,nFrameBufferSize,ref pFrameHeader,nFrameHeaderSize); return result; } - internal EVRTrackedCameraError GetVideoStreamTextureSize(uint nDeviceIndex,EVRTrackedCameraFrameType eFrameType,ref VRTextureBounds_t pTextureBounds,ref uint pnWidth,ref uint pnHeight) + public EVRTrackedCameraError GetVideoStreamTextureSize(uint nDeviceIndex,EVRTrackedCameraFrameType eFrameType,ref VRTextureBounds_t pTextureBounds,ref uint pnWidth,ref uint pnHeight) { pnWidth = 0; pnHeight = 0; EVRTrackedCameraError result = FnTable.GetVideoStreamTextureSize(nDeviceIndex,eFrameType,ref pTextureBounds,ref pnWidth,ref pnHeight); return result; } - internal EVRTrackedCameraError GetVideoStreamTextureD3D11(ulong hTrackedCamera,EVRTrackedCameraFrameType eFrameType,IntPtr pD3D11DeviceOrResource,ref IntPtr ppD3D11ShaderResourceView,ref CameraVideoStreamFrameHeader_t pFrameHeader,uint nFrameHeaderSize) + public EVRTrackedCameraError GetVideoStreamTextureD3D11(ulong hTrackedCamera,EVRTrackedCameraFrameType eFrameType,IntPtr pD3D11DeviceOrResource,ref IntPtr ppD3D11ShaderResourceView,ref CameraVideoStreamFrameHeader_t pFrameHeader,uint nFrameHeaderSize) { EVRTrackedCameraError result = FnTable.GetVideoStreamTextureD3D11(hTrackedCamera,eFrameType,pD3D11DeviceOrResource,ref ppD3D11ShaderResourceView,ref pFrameHeader,nFrameHeaderSize); return result; } - internal EVRTrackedCameraError GetVideoStreamTextureGL(ulong hTrackedCamera,EVRTrackedCameraFrameType eFrameType,ref uint pglTextureId,ref CameraVideoStreamFrameHeader_t pFrameHeader,uint nFrameHeaderSize) + public EVRTrackedCameraError GetVideoStreamTextureGL(ulong hTrackedCamera,EVRTrackedCameraFrameType eFrameType,ref uint pglTextureId,ref CameraVideoStreamFrameHeader_t pFrameHeader,uint nFrameHeaderSize) { pglTextureId = 0; EVRTrackedCameraError result = FnTable.GetVideoStreamTextureGL(hTrackedCamera,eFrameType,ref pglTextureId,ref pFrameHeader,nFrameHeaderSize); return result; } - internal EVRTrackedCameraError ReleaseVideoStreamTextureGL(ulong hTrackedCamera,uint glTextureId) + public EVRTrackedCameraError ReleaseVideoStreamTextureGL(ulong hTrackedCamera,uint glTextureId) { EVRTrackedCameraError result = FnTable.ReleaseVideoStreamTextureGL(hTrackedCamera,glTextureId); return result; @@ -1762,243 +2156,248 @@ internal EVRTrackedCameraError ReleaseVideoStreamTextureGL(ulong hTrackedCamera, } -internal class CVRApplications +public class CVRApplications { IVRApplications FnTable; internal CVRApplications(IntPtr pInterface) { FnTable = (IVRApplications)Marshal.PtrToStructure(pInterface, typeof(IVRApplications)); } - internal EVRApplicationError AddApplicationManifest(string pchApplicationManifestFullPath,bool bTemporary) + public EVRApplicationError AddApplicationManifest(string pchApplicationManifestFullPath,bool bTemporary) { EVRApplicationError result = FnTable.AddApplicationManifest(pchApplicationManifestFullPath,bTemporary); return result; } - internal EVRApplicationError RemoveApplicationManifest(string pchApplicationManifestFullPath) + public EVRApplicationError RemoveApplicationManifest(string pchApplicationManifestFullPath) { EVRApplicationError result = FnTable.RemoveApplicationManifest(pchApplicationManifestFullPath); return result; } - internal bool IsApplicationInstalled(string pchAppKey) + public bool IsApplicationInstalled(string pchAppKey) { bool result = FnTable.IsApplicationInstalled(pchAppKey); return result; } - internal uint GetApplicationCount() + public uint GetApplicationCount() { uint result = FnTable.GetApplicationCount(); return result; } - internal EVRApplicationError GetApplicationKeyByIndex(uint unApplicationIndex,System.Text.StringBuilder pchAppKeyBuffer,uint unAppKeyBufferLen) + public EVRApplicationError GetApplicationKeyByIndex(uint unApplicationIndex,System.Text.StringBuilder pchAppKeyBuffer,uint unAppKeyBufferLen) { EVRApplicationError result = FnTable.GetApplicationKeyByIndex(unApplicationIndex,pchAppKeyBuffer,unAppKeyBufferLen); return result; } - internal EVRApplicationError GetApplicationKeyByProcessId(uint unProcessId,string pchAppKeyBuffer,uint unAppKeyBufferLen) + public EVRApplicationError GetApplicationKeyByProcessId(uint unProcessId,System.Text.StringBuilder pchAppKeyBuffer,uint unAppKeyBufferLen) { EVRApplicationError result = FnTable.GetApplicationKeyByProcessId(unProcessId,pchAppKeyBuffer,unAppKeyBufferLen); return result; } - internal EVRApplicationError LaunchApplication(string pchAppKey) + public EVRApplicationError LaunchApplication(string pchAppKey) { EVRApplicationError result = FnTable.LaunchApplication(pchAppKey); return result; } - internal EVRApplicationError LaunchTemplateApplication(string pchTemplateAppKey,string pchNewAppKey,AppOverrideKeys_t [] pKeys) + public EVRApplicationError LaunchTemplateApplication(string pchTemplateAppKey,string pchNewAppKey,AppOverrideKeys_t [] pKeys) { EVRApplicationError result = FnTable.LaunchTemplateApplication(pchTemplateAppKey,pchNewAppKey,pKeys,(uint) pKeys.Length); return result; } - internal EVRApplicationError LaunchApplicationFromMimeType(string pchMimeType,string pchArgs) + public EVRApplicationError LaunchApplicationFromMimeType(string pchMimeType,string pchArgs) { EVRApplicationError result = FnTable.LaunchApplicationFromMimeType(pchMimeType,pchArgs); return result; } - internal EVRApplicationError LaunchDashboardOverlay(string pchAppKey) + public EVRApplicationError LaunchDashboardOverlay(string pchAppKey) { EVRApplicationError result = FnTable.LaunchDashboardOverlay(pchAppKey); return result; } - internal bool CancelApplicationLaunch(string pchAppKey) + public bool CancelApplicationLaunch(string pchAppKey) { bool result = FnTable.CancelApplicationLaunch(pchAppKey); return result; } - internal EVRApplicationError IdentifyApplication(uint unProcessId,string pchAppKey) + public EVRApplicationError IdentifyApplication(uint unProcessId,string pchAppKey) { EVRApplicationError result = FnTable.IdentifyApplication(unProcessId,pchAppKey); return result; } - internal uint GetApplicationProcessId(string pchAppKey) + public uint GetApplicationProcessId(string pchAppKey) { uint result = FnTable.GetApplicationProcessId(pchAppKey); return result; } - internal string GetApplicationsErrorNameFromEnum(EVRApplicationError error) + public string GetApplicationsErrorNameFromEnum(EVRApplicationError error) { IntPtr result = FnTable.GetApplicationsErrorNameFromEnum(error); return Marshal.PtrToStringAnsi(result); } - internal uint GetApplicationPropertyString(string pchAppKey,EVRApplicationProperty eProperty,System.Text.StringBuilder pchPropertyValueBuffer,uint unPropertyValueBufferLen,ref EVRApplicationError peError) + public uint GetApplicationPropertyString(string pchAppKey,EVRApplicationProperty eProperty,System.Text.StringBuilder pchPropertyValueBuffer,uint unPropertyValueBufferLen,ref EVRApplicationError peError) { uint result = FnTable.GetApplicationPropertyString(pchAppKey,eProperty,pchPropertyValueBuffer,unPropertyValueBufferLen,ref peError); return result; } - internal bool GetApplicationPropertyBool(string pchAppKey,EVRApplicationProperty eProperty,ref EVRApplicationError peError) + public bool GetApplicationPropertyBool(string pchAppKey,EVRApplicationProperty eProperty,ref EVRApplicationError peError) { bool result = FnTable.GetApplicationPropertyBool(pchAppKey,eProperty,ref peError); return result; } - internal ulong GetApplicationPropertyUint64(string pchAppKey,EVRApplicationProperty eProperty,ref EVRApplicationError peError) + public ulong GetApplicationPropertyUint64(string pchAppKey,EVRApplicationProperty eProperty,ref EVRApplicationError peError) { ulong result = FnTable.GetApplicationPropertyUint64(pchAppKey,eProperty,ref peError); return result; } - internal EVRApplicationError SetApplicationAutoLaunch(string pchAppKey,bool bAutoLaunch) + public EVRApplicationError SetApplicationAutoLaunch(string pchAppKey,bool bAutoLaunch) { EVRApplicationError result = FnTable.SetApplicationAutoLaunch(pchAppKey,bAutoLaunch); return result; } - internal bool GetApplicationAutoLaunch(string pchAppKey) + public bool GetApplicationAutoLaunch(string pchAppKey) { bool result = FnTable.GetApplicationAutoLaunch(pchAppKey); return result; } - internal EVRApplicationError SetDefaultApplicationForMimeType(string pchAppKey,string pchMimeType) + public EVRApplicationError SetDefaultApplicationForMimeType(string pchAppKey,string pchMimeType) { EVRApplicationError result = FnTable.SetDefaultApplicationForMimeType(pchAppKey,pchMimeType); return result; } - internal bool GetDefaultApplicationForMimeType(string pchMimeType,string pchAppKeyBuffer,uint unAppKeyBufferLen) + public bool GetDefaultApplicationForMimeType(string pchMimeType,System.Text.StringBuilder pchAppKeyBuffer,uint unAppKeyBufferLen) { bool result = FnTable.GetDefaultApplicationForMimeType(pchMimeType,pchAppKeyBuffer,unAppKeyBufferLen); return result; } - internal bool GetApplicationSupportedMimeTypes(string pchAppKey,string pchMimeTypesBuffer,uint unMimeTypesBuffer) + public bool GetApplicationSupportedMimeTypes(string pchAppKey,System.Text.StringBuilder pchMimeTypesBuffer,uint unMimeTypesBuffer) { bool result = FnTable.GetApplicationSupportedMimeTypes(pchAppKey,pchMimeTypesBuffer,unMimeTypesBuffer); return result; } - internal uint GetApplicationsThatSupportMimeType(string pchMimeType,string pchAppKeysThatSupportBuffer,uint unAppKeysThatSupportBuffer) + public uint GetApplicationsThatSupportMimeType(string pchMimeType,System.Text.StringBuilder pchAppKeysThatSupportBuffer,uint unAppKeysThatSupportBuffer) { uint result = FnTable.GetApplicationsThatSupportMimeType(pchMimeType,pchAppKeysThatSupportBuffer,unAppKeysThatSupportBuffer); return result; } - internal uint GetApplicationLaunchArguments(uint unHandle,string pchArgs,uint unArgs) + public uint GetApplicationLaunchArguments(uint unHandle,System.Text.StringBuilder pchArgs,uint unArgs) { uint result = FnTable.GetApplicationLaunchArguments(unHandle,pchArgs,unArgs); return result; } - internal EVRApplicationError GetStartingApplication(string pchAppKeyBuffer,uint unAppKeyBufferLen) + public EVRApplicationError GetStartingApplication(System.Text.StringBuilder pchAppKeyBuffer,uint unAppKeyBufferLen) { EVRApplicationError result = FnTable.GetStartingApplication(pchAppKeyBuffer,unAppKeyBufferLen); return result; } - internal EVRApplicationTransitionState GetTransitionState() + public EVRApplicationTransitionState GetTransitionState() { EVRApplicationTransitionState result = FnTable.GetTransitionState(); return result; } - internal EVRApplicationError PerformApplicationPrelaunchCheck(string pchAppKey) + public EVRApplicationError PerformApplicationPrelaunchCheck(string pchAppKey) { EVRApplicationError result = FnTable.PerformApplicationPrelaunchCheck(pchAppKey); return result; } - internal string GetApplicationsTransitionStateNameFromEnum(EVRApplicationTransitionState state) + public string GetApplicationsTransitionStateNameFromEnum(EVRApplicationTransitionState state) { IntPtr result = FnTable.GetApplicationsTransitionStateNameFromEnum(state); return Marshal.PtrToStringAnsi(result); } - internal bool IsQuitUserPromptRequested() + public bool IsQuitUserPromptRequested() { bool result = FnTable.IsQuitUserPromptRequested(); return result; } - internal EVRApplicationError LaunchInternalProcess(string pchBinaryPath,string pchArguments,string pchWorkingDirectory) + public EVRApplicationError LaunchInternalProcess(string pchBinaryPath,string pchArguments,string pchWorkingDirectory) { EVRApplicationError result = FnTable.LaunchInternalProcess(pchBinaryPath,pchArguments,pchWorkingDirectory); return result; } + public uint GetCurrentSceneProcessId() + { + uint result = FnTable.GetCurrentSceneProcessId(); + return result; + } } -internal class CVRChaperone +public class CVRChaperone { IVRChaperone FnTable; internal CVRChaperone(IntPtr pInterface) { FnTable = (IVRChaperone)Marshal.PtrToStructure(pInterface, typeof(IVRChaperone)); } - internal ChaperoneCalibrationState GetCalibrationState() + public ChaperoneCalibrationState GetCalibrationState() { ChaperoneCalibrationState result = FnTable.GetCalibrationState(); return result; } - internal bool GetPlayAreaSize(ref float pSizeX,ref float pSizeZ) + public bool GetPlayAreaSize(ref float pSizeX,ref float pSizeZ) { pSizeX = 0; pSizeZ = 0; bool result = FnTable.GetPlayAreaSize(ref pSizeX,ref pSizeZ); return result; } - internal bool GetPlayAreaRect(ref HmdQuad_t rect) + public bool GetPlayAreaRect(ref HmdQuad_t rect) { bool result = FnTable.GetPlayAreaRect(ref rect); return result; } - internal void ReloadInfo() + public void ReloadInfo() { FnTable.ReloadInfo(); } - internal void SetSceneColor(HmdColor_t color) + public void SetSceneColor(HmdColor_t color) { FnTable.SetSceneColor(color); } - internal void GetBoundsColor(ref HmdColor_t pOutputColorArray,int nNumOutputColors,float flCollisionBoundsFadeDistance,ref HmdColor_t pOutputCameraColor) + public void GetBoundsColor(ref HmdColor_t pOutputColorArray,int nNumOutputColors,float flCollisionBoundsFadeDistance,ref HmdColor_t pOutputCameraColor) { FnTable.GetBoundsColor(ref pOutputColorArray,nNumOutputColors,flCollisionBoundsFadeDistance,ref pOutputCameraColor); } - internal bool AreBoundsVisible() + public bool AreBoundsVisible() { bool result = FnTable.AreBoundsVisible(); return result; } - internal void ForceBoundsVisible(bool bForce) + public void ForceBoundsVisible(bool bForce) { FnTable.ForceBoundsVisible(bForce); } } -internal class CVRChaperoneSetup +public class CVRChaperoneSetup { IVRChaperoneSetup FnTable; internal CVRChaperoneSetup(IntPtr pInterface) { FnTable = (IVRChaperoneSetup)Marshal.PtrToStructure(pInterface, typeof(IVRChaperoneSetup)); } - internal bool CommitWorkingCopy(EChaperoneConfigFile configFile) + public bool CommitWorkingCopy(EChaperoneConfigFile configFile) { bool result = FnTable.CommitWorkingCopy(configFile); return result; } - internal void RevertWorkingCopy() + public void RevertWorkingCopy() { FnTable.RevertWorkingCopy(); } - internal bool GetWorkingPlayAreaSize(ref float pSizeX,ref float pSizeZ) + public bool GetWorkingPlayAreaSize(ref float pSizeX,ref float pSizeZ) { pSizeX = 0; pSizeZ = 0; bool result = FnTable.GetWorkingPlayAreaSize(ref pSizeX,ref pSizeZ); return result; } - internal bool GetWorkingPlayAreaRect(ref HmdQuad_t rect) + public bool GetWorkingPlayAreaRect(ref HmdQuad_t rect) { bool result = FnTable.GetWorkingPlayAreaRect(ref rect); return result; } - internal bool GetWorkingCollisionBoundsInfo(out HmdQuad_t [] pQuadsBuffer) + public bool GetWorkingCollisionBoundsInfo(out HmdQuad_t [] pQuadsBuffer) { uint punQuadsCount = 0; bool result = FnTable.GetWorkingCollisionBoundsInfo(null,ref punQuadsCount); @@ -2006,7 +2405,7 @@ internal bool GetWorkingCollisionBoundsInfo(out HmdQuad_t [] pQuadsBuffer) result = FnTable.GetWorkingCollisionBoundsInfo(pQuadsBuffer,ref punQuadsCount); return result; } - internal bool GetLiveCollisionBoundsInfo(out HmdQuad_t [] pQuadsBuffer) + public bool GetLiveCollisionBoundsInfo(out HmdQuad_t [] pQuadsBuffer) { uint punQuadsCount = 0; bool result = FnTable.GetLiveCollisionBoundsInfo(null,ref punQuadsCount); @@ -2014,346 +2413,366 @@ internal bool GetLiveCollisionBoundsInfo(out HmdQuad_t [] pQuadsBuffer) result = FnTable.GetLiveCollisionBoundsInfo(pQuadsBuffer,ref punQuadsCount); return result; } - internal bool GetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose) + public bool GetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose) { bool result = FnTable.GetWorkingSeatedZeroPoseToRawTrackingPose(ref pmatSeatedZeroPoseToRawTrackingPose); return result; } - internal bool GetWorkingStandingZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatStandingZeroPoseToRawTrackingPose) + public bool GetWorkingStandingZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatStandingZeroPoseToRawTrackingPose) { bool result = FnTable.GetWorkingStandingZeroPoseToRawTrackingPose(ref pmatStandingZeroPoseToRawTrackingPose); return result; } - internal void SetWorkingPlayAreaSize(float sizeX,float sizeZ) + public void SetWorkingPlayAreaSize(float sizeX,float sizeZ) { FnTable.SetWorkingPlayAreaSize(sizeX,sizeZ); } - internal void SetWorkingCollisionBoundsInfo(HmdQuad_t [] pQuadsBuffer) + public void SetWorkingCollisionBoundsInfo(HmdQuad_t [] pQuadsBuffer) { FnTable.SetWorkingCollisionBoundsInfo(pQuadsBuffer,(uint) pQuadsBuffer.Length); } - internal void SetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatSeatedZeroPoseToRawTrackingPose) + public void SetWorkingPerimeter(HmdVector2_t [] pPointBuffer) + { + FnTable.SetWorkingPerimeter(pPointBuffer,(uint) pPointBuffer.Length); + } + public void SetWorkingSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatSeatedZeroPoseToRawTrackingPose) { FnTable.SetWorkingSeatedZeroPoseToRawTrackingPose(ref pMatSeatedZeroPoseToRawTrackingPose); } - internal void SetWorkingStandingZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatStandingZeroPoseToRawTrackingPose) + public void SetWorkingStandingZeroPoseToRawTrackingPose(ref HmdMatrix34_t pMatStandingZeroPoseToRawTrackingPose) { FnTable.SetWorkingStandingZeroPoseToRawTrackingPose(ref pMatStandingZeroPoseToRawTrackingPose); } - internal void ReloadFromDisk(EChaperoneConfigFile configFile) + public void ReloadFromDisk(EChaperoneConfigFile configFile) { FnTable.ReloadFromDisk(configFile); } - internal bool GetLiveSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose) + public bool GetLiveSeatedZeroPoseToRawTrackingPose(ref HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose) { bool result = FnTable.GetLiveSeatedZeroPoseToRawTrackingPose(ref pmatSeatedZeroPoseToRawTrackingPose); return result; } - internal void SetWorkingCollisionBoundsTagsInfo(byte [] pTagsBuffer) + public bool ExportLiveToBuffer(System.Text.StringBuilder pBuffer,ref uint pnBufferLength) { - FnTable.SetWorkingCollisionBoundsTagsInfo(pTagsBuffer,(uint) pTagsBuffer.Length); - } - internal bool GetLiveCollisionBoundsTagsInfo(out byte [] pTagsBuffer) - { - uint punTagCount = 0; - bool result = FnTable.GetLiveCollisionBoundsTagsInfo(null,ref punTagCount); - pTagsBuffer= new byte[punTagCount]; - result = FnTable.GetLiveCollisionBoundsTagsInfo(pTagsBuffer,ref punTagCount); - return result; - } - internal bool SetWorkingPhysicalBoundsInfo(HmdQuad_t [] pQuadsBuffer) - { - bool result = FnTable.SetWorkingPhysicalBoundsInfo(pQuadsBuffer,(uint) pQuadsBuffer.Length); + pnBufferLength = 0; + bool result = FnTable.ExportLiveToBuffer(pBuffer,ref pnBufferLength); return result; } - internal bool GetLivePhysicalBoundsInfo(out HmdQuad_t [] pQuadsBuffer) + public bool ImportFromBufferToWorking(string pBuffer,uint nImportFlags) { - uint punQuadsCount = 0; - bool result = FnTable.GetLivePhysicalBoundsInfo(null,ref punQuadsCount); - pQuadsBuffer= new HmdQuad_t[punQuadsCount]; - result = FnTable.GetLivePhysicalBoundsInfo(pQuadsBuffer,ref punQuadsCount); + bool result = FnTable.ImportFromBufferToWorking(pBuffer,nImportFlags); return result; } - internal bool ExportLiveToBuffer(System.Text.StringBuilder pBuffer,ref uint pnBufferLength) + public void ShowWorkingSetPreview() { - pnBufferLength = 0; - bool result = FnTable.ExportLiveToBuffer(pBuffer,ref pnBufferLength); - return result; + FnTable.ShowWorkingSetPreview(); } - internal bool ImportFromBufferToWorking(string pBuffer,uint nImportFlags) + public void HideWorkingSetPreview() { - bool result = FnTable.ImportFromBufferToWorking(pBuffer,nImportFlags); - return result; + FnTable.HideWorkingSetPreview(); } } -internal class CVRCompositor +public class CVRCompositor { IVRCompositor FnTable; internal CVRCompositor(IntPtr pInterface) { FnTable = (IVRCompositor)Marshal.PtrToStructure(pInterface, typeof(IVRCompositor)); } - internal void SetTrackingSpace(ETrackingUniverseOrigin eOrigin) + public void SetTrackingSpace(ETrackingUniverseOrigin eOrigin) { FnTable.SetTrackingSpace(eOrigin); } - internal ETrackingUniverseOrigin GetTrackingSpace() + public ETrackingUniverseOrigin GetTrackingSpace() { ETrackingUniverseOrigin result = FnTable.GetTrackingSpace(); return result; } - internal EVRCompositorError WaitGetPoses(TrackedDevicePose_t [] pRenderPoseArray,TrackedDevicePose_t [] pGamePoseArray) + public EVRCompositorError WaitGetPoses(TrackedDevicePose_t [] pRenderPoseArray,TrackedDevicePose_t [] pGamePoseArray) { EVRCompositorError result = FnTable.WaitGetPoses(pRenderPoseArray,(uint) pRenderPoseArray.Length,pGamePoseArray,(uint) pGamePoseArray.Length); return result; } - internal EVRCompositorError GetLastPoses(TrackedDevicePose_t [] pRenderPoseArray,TrackedDevicePose_t [] pGamePoseArray) + public EVRCompositorError GetLastPoses(TrackedDevicePose_t [] pRenderPoseArray,TrackedDevicePose_t [] pGamePoseArray) { EVRCompositorError result = FnTable.GetLastPoses(pRenderPoseArray,(uint) pRenderPoseArray.Length,pGamePoseArray,(uint) pGamePoseArray.Length); return result; } - internal EVRCompositorError GetLastPoseForTrackedDeviceIndex(uint unDeviceIndex,ref TrackedDevicePose_t pOutputPose,ref TrackedDevicePose_t pOutputGamePose) + public EVRCompositorError GetLastPoseForTrackedDeviceIndex(uint unDeviceIndex,ref TrackedDevicePose_t pOutputPose,ref TrackedDevicePose_t pOutputGamePose) { EVRCompositorError result = FnTable.GetLastPoseForTrackedDeviceIndex(unDeviceIndex,ref pOutputPose,ref pOutputGamePose); return result; } - internal EVRCompositorError Submit(EVREye eEye,ref Texture_t pTexture,ref VRTextureBounds_t pBounds,EVRSubmitFlags nSubmitFlags) + public EVRCompositorError Submit(EVREye eEye,ref Texture_t pTexture,ref VRTextureBounds_t pBounds,EVRSubmitFlags nSubmitFlags) { EVRCompositorError result = FnTable.Submit(eEye,ref pTexture,ref pBounds,nSubmitFlags); return result; } - internal void ClearLastSubmittedFrame() + public void ClearLastSubmittedFrame() { FnTable.ClearLastSubmittedFrame(); } - internal void PostPresentHandoff() + public void PostPresentHandoff() { FnTable.PostPresentHandoff(); } - internal bool GetFrameTiming(ref Compositor_FrameTiming pTiming,uint unFramesAgo) + public bool GetFrameTiming(ref Compositor_FrameTiming pTiming,uint unFramesAgo) { bool result = FnTable.GetFrameTiming(ref pTiming,unFramesAgo); return result; } - internal uint GetFrameTimings(ref Compositor_FrameTiming pTiming,uint nFrames) + public uint GetFrameTimings(Compositor_FrameTiming [] pTiming) { - uint result = FnTable.GetFrameTimings(ref pTiming,nFrames); + uint result = FnTable.GetFrameTimings(pTiming,(uint) pTiming.Length); return result; } - internal float GetFrameTimeRemaining() + public float GetFrameTimeRemaining() { float result = FnTable.GetFrameTimeRemaining(); return result; } - internal void GetCumulativeStats(ref Compositor_CumulativeStats pStats,uint nStatsSizeInBytes) + public void GetCumulativeStats(ref Compositor_CumulativeStats pStats,uint nStatsSizeInBytes) { FnTable.GetCumulativeStats(ref pStats,nStatsSizeInBytes); } - internal void FadeToColor(float fSeconds,float fRed,float fGreen,float fBlue,float fAlpha,bool bBackground) + public void FadeToColor(float fSeconds,float fRed,float fGreen,float fBlue,float fAlpha,bool bBackground) { FnTable.FadeToColor(fSeconds,fRed,fGreen,fBlue,fAlpha,bBackground); } - internal HmdColor_t GetCurrentFadeColor(bool bBackground) + public HmdColor_t GetCurrentFadeColor(bool bBackground) { HmdColor_t result = FnTable.GetCurrentFadeColor(bBackground); return result; } - internal void FadeGrid(float fSeconds,bool bFadeIn) + public void FadeGrid(float fSeconds,bool bFadeIn) { FnTable.FadeGrid(fSeconds,bFadeIn); } - internal float GetCurrentGridAlpha() + public float GetCurrentGridAlpha() { float result = FnTable.GetCurrentGridAlpha(); return result; } - internal EVRCompositorError SetSkyboxOverride(Texture_t [] pTextures) + public EVRCompositorError SetSkyboxOverride(Texture_t [] pTextures) { EVRCompositorError result = FnTable.SetSkyboxOverride(pTextures,(uint) pTextures.Length); return result; } - internal void ClearSkyboxOverride() + public void ClearSkyboxOverride() { FnTable.ClearSkyboxOverride(); } - internal void CompositorBringToFront() + public void CompositorBringToFront() { FnTable.CompositorBringToFront(); } - internal void CompositorGoToBack() + public void CompositorGoToBack() { FnTable.CompositorGoToBack(); } - internal void CompositorQuit() + public void CompositorQuit() { FnTable.CompositorQuit(); } - internal bool IsFullscreen() + public bool IsFullscreen() { bool result = FnTable.IsFullscreen(); return result; } - internal uint GetCurrentSceneFocusProcess() + public uint GetCurrentSceneFocusProcess() { uint result = FnTable.GetCurrentSceneFocusProcess(); return result; } - internal uint GetLastFrameRenderer() + public uint GetLastFrameRenderer() { uint result = FnTable.GetLastFrameRenderer(); return result; } - internal bool CanRenderScene() + public bool CanRenderScene() { bool result = FnTable.CanRenderScene(); return result; } - internal void ShowMirrorWindow() + public void ShowMirrorWindow() { FnTable.ShowMirrorWindow(); } - internal void HideMirrorWindow() + public void HideMirrorWindow() { FnTable.HideMirrorWindow(); } - internal bool IsMirrorWindowVisible() + public bool IsMirrorWindowVisible() { bool result = FnTable.IsMirrorWindowVisible(); return result; } - internal void CompositorDumpImages() + public void CompositorDumpImages() { FnTable.CompositorDumpImages(); } - internal bool ShouldAppRenderWithLowResources() + public bool ShouldAppRenderWithLowResources() { bool result = FnTable.ShouldAppRenderWithLowResources(); return result; } - internal void ForceInterleavedReprojectionOn(bool bOverride) + public void ForceInterleavedReprojectionOn(bool bOverride) { FnTable.ForceInterleavedReprojectionOn(bOverride); } - internal void ForceReconnectProcess() + public void ForceReconnectProcess() { FnTable.ForceReconnectProcess(); } - internal void SuspendRendering(bool bSuspend) + public void SuspendRendering(bool bSuspend) { FnTable.SuspendRendering(bSuspend); } - internal EVRCompositorError GetMirrorTextureD3D11(EVREye eEye,IntPtr pD3D11DeviceOrResource,ref IntPtr ppD3D11ShaderResourceView) + public EVRCompositorError GetMirrorTextureD3D11(EVREye eEye,IntPtr pD3D11DeviceOrResource,ref IntPtr ppD3D11ShaderResourceView) { EVRCompositorError result = FnTable.GetMirrorTextureD3D11(eEye,pD3D11DeviceOrResource,ref ppD3D11ShaderResourceView); return result; } - internal EVRCompositorError GetMirrorTextureGL(EVREye eEye,ref uint pglTextureId,IntPtr pglSharedTextureHandle) + public void ReleaseMirrorTextureD3D11(IntPtr pD3D11ShaderResourceView) { - pglTextureId = 0; + FnTable.ReleaseMirrorTextureD3D11(pD3D11ShaderResourceView); + } + public EVRCompositorError GetMirrorTextureGL(EVREye eEye,ref uint pglTextureId,IntPtr pglSharedTextureHandle) + { + pglTextureId = 0; EVRCompositorError result = FnTable.GetMirrorTextureGL(eEye,ref pglTextureId,pglSharedTextureHandle); return result; } - internal bool ReleaseSharedGLTexture(uint glTextureId,IntPtr glSharedTextureHandle) + public bool ReleaseSharedGLTexture(uint glTextureId,IntPtr glSharedTextureHandle) { bool result = FnTable.ReleaseSharedGLTexture(glTextureId,glSharedTextureHandle); return result; } - internal void LockGLSharedTextureForAccess(IntPtr glSharedTextureHandle) + public void LockGLSharedTextureForAccess(IntPtr glSharedTextureHandle) { FnTable.LockGLSharedTextureForAccess(glSharedTextureHandle); } - internal void UnlockGLSharedTextureForAccess(IntPtr glSharedTextureHandle) + public void UnlockGLSharedTextureForAccess(IntPtr glSharedTextureHandle) { FnTable.UnlockGLSharedTextureForAccess(glSharedTextureHandle); } + public uint GetVulkanInstanceExtensionsRequired(System.Text.StringBuilder pchValue,uint unBufferSize) + { + uint result = FnTable.GetVulkanInstanceExtensionsRequired(pchValue,unBufferSize); + return result; + } + public uint GetVulkanDeviceExtensionsRequired(IntPtr pPhysicalDevice,System.Text.StringBuilder pchValue,uint unBufferSize) + { + uint result = FnTable.GetVulkanDeviceExtensionsRequired(pPhysicalDevice,pchValue,unBufferSize); + return result; + } + public void SetExplicitTimingMode(EVRCompositorTimingMode eTimingMode) + { + FnTable.SetExplicitTimingMode(eTimingMode); + } + public EVRCompositorError SubmitExplicitTimingData() + { + EVRCompositorError result = FnTable.SubmitExplicitTimingData(); + return result; + } + public bool IsMotionSmoothingEnabled() + { + bool result = FnTable.IsMotionSmoothingEnabled(); + return result; + } } -internal class CVROverlay +public class CVROverlay { IVROverlay FnTable; internal CVROverlay(IntPtr pInterface) { FnTable = (IVROverlay)Marshal.PtrToStructure(pInterface, typeof(IVROverlay)); } - internal EVROverlayError FindOverlay(string pchOverlayKey,ref ulong pOverlayHandle) + public EVROverlayError FindOverlay(string pchOverlayKey,ref ulong pOverlayHandle) { pOverlayHandle = 0; EVROverlayError result = FnTable.FindOverlay(pchOverlayKey,ref pOverlayHandle); return result; } - internal EVROverlayError CreateOverlay(string pchOverlayKey,string pchOverlayFriendlyName,ref ulong pOverlayHandle) + public EVROverlayError CreateOverlay(string pchOverlayKey,string pchOverlayName,ref ulong pOverlayHandle) { pOverlayHandle = 0; - EVROverlayError result = FnTable.CreateOverlay(pchOverlayKey,pchOverlayFriendlyName,ref pOverlayHandle); + EVROverlayError result = FnTable.CreateOverlay(pchOverlayKey,pchOverlayName,ref pOverlayHandle); return result; } - internal EVROverlayError DestroyOverlay(ulong ulOverlayHandle) + public EVROverlayError DestroyOverlay(ulong ulOverlayHandle) { EVROverlayError result = FnTable.DestroyOverlay(ulOverlayHandle); return result; } - internal EVROverlayError SetHighQualityOverlay(ulong ulOverlayHandle) + public EVROverlayError SetHighQualityOverlay(ulong ulOverlayHandle) { EVROverlayError result = FnTable.SetHighQualityOverlay(ulOverlayHandle); return result; } - internal ulong GetHighQualityOverlay() + public ulong GetHighQualityOverlay() { ulong result = FnTable.GetHighQualityOverlay(); return result; } - internal uint GetOverlayKey(ulong ulOverlayHandle,System.Text.StringBuilder pchValue,uint unBufferSize,ref EVROverlayError pError) + public uint GetOverlayKey(ulong ulOverlayHandle,System.Text.StringBuilder pchValue,uint unBufferSize,ref EVROverlayError pError) { uint result = FnTable.GetOverlayKey(ulOverlayHandle,pchValue,unBufferSize,ref pError); return result; } - internal uint GetOverlayName(ulong ulOverlayHandle,System.Text.StringBuilder pchValue,uint unBufferSize,ref EVROverlayError pError) + public uint GetOverlayName(ulong ulOverlayHandle,System.Text.StringBuilder pchValue,uint unBufferSize,ref EVROverlayError pError) { uint result = FnTable.GetOverlayName(ulOverlayHandle,pchValue,unBufferSize,ref pError); return result; } - internal EVROverlayError GetOverlayImageData(ulong ulOverlayHandle,IntPtr pvBuffer,uint unBufferSize,ref uint punWidth,ref uint punHeight) + public EVROverlayError SetOverlayName(ulong ulOverlayHandle,string pchName) + { + EVROverlayError result = FnTable.SetOverlayName(ulOverlayHandle,pchName); + return result; + } + public EVROverlayError GetOverlayImageData(ulong ulOverlayHandle,IntPtr pvBuffer,uint unBufferSize,ref uint punWidth,ref uint punHeight) { punWidth = 0; punHeight = 0; EVROverlayError result = FnTable.GetOverlayImageData(ulOverlayHandle,pvBuffer,unBufferSize,ref punWidth,ref punHeight); return result; } - internal string GetOverlayErrorNameFromEnum(EVROverlayError error) + public string GetOverlayErrorNameFromEnum(EVROverlayError error) { IntPtr result = FnTable.GetOverlayErrorNameFromEnum(error); return Marshal.PtrToStringAnsi(result); } - internal EVROverlayError SetOverlayRenderingPid(ulong ulOverlayHandle,uint unPID) + public EVROverlayError SetOverlayRenderingPid(ulong ulOverlayHandle,uint unPID) { EVROverlayError result = FnTable.SetOverlayRenderingPid(ulOverlayHandle,unPID); return result; } - internal uint GetOverlayRenderingPid(ulong ulOverlayHandle) + public uint GetOverlayRenderingPid(ulong ulOverlayHandle) { uint result = FnTable.GetOverlayRenderingPid(ulOverlayHandle); return result; } - internal EVROverlayError SetOverlayFlag(ulong ulOverlayHandle,VROverlayFlags eOverlayFlag,bool bEnabled) + public EVROverlayError SetOverlayFlag(ulong ulOverlayHandle,VROverlayFlags eOverlayFlag,bool bEnabled) { EVROverlayError result = FnTable.SetOverlayFlag(ulOverlayHandle,eOverlayFlag,bEnabled); return result; } - internal EVROverlayError GetOverlayFlag(ulong ulOverlayHandle,VROverlayFlags eOverlayFlag,ref bool pbEnabled) + public EVROverlayError GetOverlayFlag(ulong ulOverlayHandle,VROverlayFlags eOverlayFlag,ref bool pbEnabled) { pbEnabled = false; EVROverlayError result = FnTable.GetOverlayFlag(ulOverlayHandle,eOverlayFlag,ref pbEnabled); return result; } - internal EVROverlayError SetOverlayColor(ulong ulOverlayHandle,float fRed,float fGreen,float fBlue) + public EVROverlayError SetOverlayColor(ulong ulOverlayHandle,float fRed,float fGreen,float fBlue) { EVROverlayError result = FnTable.SetOverlayColor(ulOverlayHandle,fRed,fGreen,fBlue); return result; } - internal EVROverlayError GetOverlayColor(ulong ulOverlayHandle,ref float pfRed,ref float pfGreen,ref float pfBlue) + public EVROverlayError GetOverlayColor(ulong ulOverlayHandle,ref float pfRed,ref float pfGreen,ref float pfBlue) { pfRed = 0; pfGreen = 0; @@ -2361,401 +2780,500 @@ internal EVROverlayError GetOverlayColor(ulong ulOverlayHandle,ref float pfRed,r EVROverlayError result = FnTable.GetOverlayColor(ulOverlayHandle,ref pfRed,ref pfGreen,ref pfBlue); return result; } - internal EVROverlayError SetOverlayAlpha(ulong ulOverlayHandle,float fAlpha) + public EVROverlayError SetOverlayAlpha(ulong ulOverlayHandle,float fAlpha) { EVROverlayError result = FnTable.SetOverlayAlpha(ulOverlayHandle,fAlpha); return result; } - internal EVROverlayError GetOverlayAlpha(ulong ulOverlayHandle,ref float pfAlpha) + public EVROverlayError GetOverlayAlpha(ulong ulOverlayHandle,ref float pfAlpha) { pfAlpha = 0; EVROverlayError result = FnTable.GetOverlayAlpha(ulOverlayHandle,ref pfAlpha); return result; } - internal EVROverlayError SetOverlayTexelAspect(ulong ulOverlayHandle,float fTexelAspect) + public EVROverlayError SetOverlayTexelAspect(ulong ulOverlayHandle,float fTexelAspect) { EVROverlayError result = FnTable.SetOverlayTexelAspect(ulOverlayHandle,fTexelAspect); return result; } - internal EVROverlayError GetOverlayTexelAspect(ulong ulOverlayHandle,ref float pfTexelAspect) + public EVROverlayError GetOverlayTexelAspect(ulong ulOverlayHandle,ref float pfTexelAspect) { pfTexelAspect = 0; EVROverlayError result = FnTable.GetOverlayTexelAspect(ulOverlayHandle,ref pfTexelAspect); return result; } - internal EVROverlayError SetOverlaySortOrder(ulong ulOverlayHandle,uint unSortOrder) + public EVROverlayError SetOverlaySortOrder(ulong ulOverlayHandle,uint unSortOrder) { EVROverlayError result = FnTable.SetOverlaySortOrder(ulOverlayHandle,unSortOrder); return result; } - internal EVROverlayError GetOverlaySortOrder(ulong ulOverlayHandle,ref uint punSortOrder) + public EVROverlayError GetOverlaySortOrder(ulong ulOverlayHandle,ref uint punSortOrder) { punSortOrder = 0; EVROverlayError result = FnTable.GetOverlaySortOrder(ulOverlayHandle,ref punSortOrder); return result; } - internal EVROverlayError SetOverlayWidthInMeters(ulong ulOverlayHandle,float fWidthInMeters) + public EVROverlayError SetOverlayWidthInMeters(ulong ulOverlayHandle,float fWidthInMeters) { EVROverlayError result = FnTable.SetOverlayWidthInMeters(ulOverlayHandle,fWidthInMeters); return result; } - internal EVROverlayError GetOverlayWidthInMeters(ulong ulOverlayHandle,ref float pfWidthInMeters) + public EVROverlayError GetOverlayWidthInMeters(ulong ulOverlayHandle,ref float pfWidthInMeters) { pfWidthInMeters = 0; EVROverlayError result = FnTable.GetOverlayWidthInMeters(ulOverlayHandle,ref pfWidthInMeters); return result; } - internal EVROverlayError SetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle,float fMinDistanceInMeters,float fMaxDistanceInMeters) + public EVROverlayError SetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle,float fMinDistanceInMeters,float fMaxDistanceInMeters) { EVROverlayError result = FnTable.SetOverlayAutoCurveDistanceRangeInMeters(ulOverlayHandle,fMinDistanceInMeters,fMaxDistanceInMeters); return result; } - internal EVROverlayError GetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle,ref float pfMinDistanceInMeters,ref float pfMaxDistanceInMeters) + public EVROverlayError GetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle,ref float pfMinDistanceInMeters,ref float pfMaxDistanceInMeters) { pfMinDistanceInMeters = 0; pfMaxDistanceInMeters = 0; EVROverlayError result = FnTable.GetOverlayAutoCurveDistanceRangeInMeters(ulOverlayHandle,ref pfMinDistanceInMeters,ref pfMaxDistanceInMeters); return result; } - internal EVROverlayError SetOverlayTextureColorSpace(ulong ulOverlayHandle,EColorSpace eTextureColorSpace) + public EVROverlayError SetOverlayTextureColorSpace(ulong ulOverlayHandle,EColorSpace eTextureColorSpace) { EVROverlayError result = FnTable.SetOverlayTextureColorSpace(ulOverlayHandle,eTextureColorSpace); return result; } - internal EVROverlayError GetOverlayTextureColorSpace(ulong ulOverlayHandle,ref EColorSpace peTextureColorSpace) + public EVROverlayError GetOverlayTextureColorSpace(ulong ulOverlayHandle,ref EColorSpace peTextureColorSpace) { EVROverlayError result = FnTable.GetOverlayTextureColorSpace(ulOverlayHandle,ref peTextureColorSpace); return result; } - internal EVROverlayError SetOverlayTextureBounds(ulong ulOverlayHandle,ref VRTextureBounds_t pOverlayTextureBounds) + public EVROverlayError SetOverlayTextureBounds(ulong ulOverlayHandle,ref VRTextureBounds_t pOverlayTextureBounds) { EVROverlayError result = FnTable.SetOverlayTextureBounds(ulOverlayHandle,ref pOverlayTextureBounds); return result; } - internal EVROverlayError GetOverlayTextureBounds(ulong ulOverlayHandle,ref VRTextureBounds_t pOverlayTextureBounds) + public EVROverlayError GetOverlayTextureBounds(ulong ulOverlayHandle,ref VRTextureBounds_t pOverlayTextureBounds) { EVROverlayError result = FnTable.GetOverlayTextureBounds(ulOverlayHandle,ref pOverlayTextureBounds); return result; } - internal EVROverlayError GetOverlayTransformType(ulong ulOverlayHandle,ref VROverlayTransformType peTransformType) + public uint GetOverlayRenderModel(ulong ulOverlayHandle,System.Text.StringBuilder pchValue,uint unBufferSize,ref HmdColor_t pColor,ref EVROverlayError pError) + { + uint result = FnTable.GetOverlayRenderModel(ulOverlayHandle,pchValue,unBufferSize,ref pColor,ref pError); + return result; + } + public EVROverlayError SetOverlayRenderModel(ulong ulOverlayHandle,string pchRenderModel,ref HmdColor_t pColor) + { + EVROverlayError result = FnTable.SetOverlayRenderModel(ulOverlayHandle,pchRenderModel,ref pColor); + return result; + } + public EVROverlayError GetOverlayTransformType(ulong ulOverlayHandle,ref VROverlayTransformType peTransformType) { EVROverlayError result = FnTable.GetOverlayTransformType(ulOverlayHandle,ref peTransformType); return result; } - internal EVROverlayError SetOverlayTransformAbsolute(ulong ulOverlayHandle,ETrackingUniverseOrigin eTrackingOrigin,ref HmdMatrix34_t pmatTrackingOriginToOverlayTransform) + public EVROverlayError SetOverlayTransformAbsolute(ulong ulOverlayHandle,ETrackingUniverseOrigin eTrackingOrigin,ref HmdMatrix34_t pmatTrackingOriginToOverlayTransform) { EVROverlayError result = FnTable.SetOverlayTransformAbsolute(ulOverlayHandle,eTrackingOrigin,ref pmatTrackingOriginToOverlayTransform); return result; } - internal EVROverlayError GetOverlayTransformAbsolute(ulong ulOverlayHandle,ref ETrackingUniverseOrigin peTrackingOrigin,ref HmdMatrix34_t pmatTrackingOriginToOverlayTransform) + public EVROverlayError GetOverlayTransformAbsolute(ulong ulOverlayHandle,ref ETrackingUniverseOrigin peTrackingOrigin,ref HmdMatrix34_t pmatTrackingOriginToOverlayTransform) { EVROverlayError result = FnTable.GetOverlayTransformAbsolute(ulOverlayHandle,ref peTrackingOrigin,ref pmatTrackingOriginToOverlayTransform); return result; } - internal EVROverlayError SetOverlayTransformTrackedDeviceRelative(ulong ulOverlayHandle,uint unTrackedDevice,ref HmdMatrix34_t pmatTrackedDeviceToOverlayTransform) + public EVROverlayError SetOverlayTransformTrackedDeviceRelative(ulong ulOverlayHandle,uint unTrackedDevice,ref HmdMatrix34_t pmatTrackedDeviceToOverlayTransform) { EVROverlayError result = FnTable.SetOverlayTransformTrackedDeviceRelative(ulOverlayHandle,unTrackedDevice,ref pmatTrackedDeviceToOverlayTransform); return result; } - internal EVROverlayError GetOverlayTransformTrackedDeviceRelative(ulong ulOverlayHandle,ref uint punTrackedDevice,ref HmdMatrix34_t pmatTrackedDeviceToOverlayTransform) + public EVROverlayError GetOverlayTransformTrackedDeviceRelative(ulong ulOverlayHandle,ref uint punTrackedDevice,ref HmdMatrix34_t pmatTrackedDeviceToOverlayTransform) { punTrackedDevice = 0; EVROverlayError result = FnTable.GetOverlayTransformTrackedDeviceRelative(ulOverlayHandle,ref punTrackedDevice,ref pmatTrackedDeviceToOverlayTransform); return result; } - internal EVROverlayError SetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle,uint unDeviceIndex,string pchComponentName) + public EVROverlayError SetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle,uint unDeviceIndex,string pchComponentName) { EVROverlayError result = FnTable.SetOverlayTransformTrackedDeviceComponent(ulOverlayHandle,unDeviceIndex,pchComponentName); return result; } - internal EVROverlayError GetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle,ref uint punDeviceIndex,string pchComponentName,uint unComponentNameSize) + public EVROverlayError GetOverlayTransformTrackedDeviceComponent(ulong ulOverlayHandle,ref uint punDeviceIndex,System.Text.StringBuilder pchComponentName,uint unComponentNameSize) { punDeviceIndex = 0; EVROverlayError result = FnTable.GetOverlayTransformTrackedDeviceComponent(ulOverlayHandle,ref punDeviceIndex,pchComponentName,unComponentNameSize); return result; } - internal EVROverlayError ShowOverlay(ulong ulOverlayHandle) + public EVROverlayError GetOverlayTransformOverlayRelative(ulong ulOverlayHandle,ref ulong ulOverlayHandleParent,ref HmdMatrix34_t pmatParentOverlayToOverlayTransform) + { + ulOverlayHandleParent = 0; + EVROverlayError result = FnTable.GetOverlayTransformOverlayRelative(ulOverlayHandle,ref ulOverlayHandleParent,ref pmatParentOverlayToOverlayTransform); + return result; + } + public EVROverlayError SetOverlayTransformOverlayRelative(ulong ulOverlayHandle,ulong ulOverlayHandleParent,ref HmdMatrix34_t pmatParentOverlayToOverlayTransform) + { + EVROverlayError result = FnTable.SetOverlayTransformOverlayRelative(ulOverlayHandle,ulOverlayHandleParent,ref pmatParentOverlayToOverlayTransform); + return result; + } + public EVROverlayError ShowOverlay(ulong ulOverlayHandle) { EVROverlayError result = FnTable.ShowOverlay(ulOverlayHandle); return result; } - internal EVROverlayError HideOverlay(ulong ulOverlayHandle) + public EVROverlayError HideOverlay(ulong ulOverlayHandle) { EVROverlayError result = FnTable.HideOverlay(ulOverlayHandle); return result; } - internal bool IsOverlayVisible(ulong ulOverlayHandle) + public bool IsOverlayVisible(ulong ulOverlayHandle) { bool result = FnTable.IsOverlayVisible(ulOverlayHandle); return result; } - internal EVROverlayError GetTransformForOverlayCoordinates(ulong ulOverlayHandle,ETrackingUniverseOrigin eTrackingOrigin,HmdVector2_t coordinatesInOverlay,ref HmdMatrix34_t pmatTransform) + public EVROverlayError GetTransformForOverlayCoordinates(ulong ulOverlayHandle,ETrackingUniverseOrigin eTrackingOrigin,HmdVector2_t coordinatesInOverlay,ref HmdMatrix34_t pmatTransform) { EVROverlayError result = FnTable.GetTransformForOverlayCoordinates(ulOverlayHandle,eTrackingOrigin,coordinatesInOverlay,ref pmatTransform); return result; } - internal bool PollNextOverlayEvent(ulong ulOverlayHandle,ref VREvent_t pEvent,uint uncbVREvent) +// This is a terrible hack to workaround the fact that VRControllerState_t and VREvent_t were +// originally mis-compiled with the wrong packing for Linux and OSX. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _PollNextOverlayEventPacked(ulong ulOverlayHandle,ref VREvent_t_Packed pEvent,uint uncbVREvent); + [StructLayout(LayoutKind.Explicit)] + struct PollNextOverlayEventUnion + { + [FieldOffset(0)] + public IVROverlay._PollNextOverlayEvent pPollNextOverlayEvent; + [FieldOffset(0)] + public _PollNextOverlayEventPacked pPollNextOverlayEventPacked; + } + public bool PollNextOverlayEvent(ulong ulOverlayHandle,ref VREvent_t pEvent,uint uncbVREvent) { +#if !UNITY_METRO + if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) || + (System.Environment.OSVersion.Platform == System.PlatformID.Unix)) + { + PollNextOverlayEventUnion u; + VREvent_t_Packed event_packed = new VREvent_t_Packed(); + u.pPollNextOverlayEventPacked = null; + u.pPollNextOverlayEvent = FnTable.PollNextOverlayEvent; + bool packed_result = u.pPollNextOverlayEventPacked(ulOverlayHandle,ref event_packed,(uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VREvent_t_Packed))); + + event_packed.Unpack(ref pEvent); + return packed_result; + } +#endif bool result = FnTable.PollNextOverlayEvent(ulOverlayHandle,ref pEvent,uncbVREvent); return result; } - internal EVROverlayError GetOverlayInputMethod(ulong ulOverlayHandle,ref VROverlayInputMethod peInputMethod) + public EVROverlayError GetOverlayInputMethod(ulong ulOverlayHandle,ref VROverlayInputMethod peInputMethod) { EVROverlayError result = FnTable.GetOverlayInputMethod(ulOverlayHandle,ref peInputMethod); return result; } - internal EVROverlayError SetOverlayInputMethod(ulong ulOverlayHandle,VROverlayInputMethod eInputMethod) + public EVROverlayError SetOverlayInputMethod(ulong ulOverlayHandle,VROverlayInputMethod eInputMethod) { EVROverlayError result = FnTable.SetOverlayInputMethod(ulOverlayHandle,eInputMethod); return result; } - internal EVROverlayError GetOverlayMouseScale(ulong ulOverlayHandle,ref HmdVector2_t pvecMouseScale) + public EVROverlayError GetOverlayMouseScale(ulong ulOverlayHandle,ref HmdVector2_t pvecMouseScale) { EVROverlayError result = FnTable.GetOverlayMouseScale(ulOverlayHandle,ref pvecMouseScale); return result; } - internal EVROverlayError SetOverlayMouseScale(ulong ulOverlayHandle,ref HmdVector2_t pvecMouseScale) + public EVROverlayError SetOverlayMouseScale(ulong ulOverlayHandle,ref HmdVector2_t pvecMouseScale) { EVROverlayError result = FnTable.SetOverlayMouseScale(ulOverlayHandle,ref pvecMouseScale); return result; } - internal bool ComputeOverlayIntersection(ulong ulOverlayHandle,ref VROverlayIntersectionParams_t pParams,ref VROverlayIntersectionResults_t pResults) + public bool ComputeOverlayIntersection(ulong ulOverlayHandle,ref VROverlayIntersectionParams_t pParams,ref VROverlayIntersectionResults_t pResults) { bool result = FnTable.ComputeOverlayIntersection(ulOverlayHandle,ref pParams,ref pResults); return result; } - internal bool HandleControllerOverlayInteractionAsMouse(ulong ulOverlayHandle,uint unControllerDeviceIndex) - { - bool result = FnTable.HandleControllerOverlayInteractionAsMouse(ulOverlayHandle,unControllerDeviceIndex); - return result; - } - internal bool IsHoverTargetOverlay(ulong ulOverlayHandle) + public bool IsHoverTargetOverlay(ulong ulOverlayHandle) { bool result = FnTable.IsHoverTargetOverlay(ulOverlayHandle); return result; } - internal ulong GetGamepadFocusOverlay() + public ulong GetGamepadFocusOverlay() { ulong result = FnTable.GetGamepadFocusOverlay(); return result; } - internal EVROverlayError SetGamepadFocusOverlay(ulong ulNewFocusOverlay) + public EVROverlayError SetGamepadFocusOverlay(ulong ulNewFocusOverlay) { EVROverlayError result = FnTable.SetGamepadFocusOverlay(ulNewFocusOverlay); return result; } - internal EVROverlayError SetOverlayNeighbor(EOverlayDirection eDirection,ulong ulFrom,ulong ulTo) + public EVROverlayError SetOverlayNeighbor(EOverlayDirection eDirection,ulong ulFrom,ulong ulTo) { EVROverlayError result = FnTable.SetOverlayNeighbor(eDirection,ulFrom,ulTo); return result; } - internal EVROverlayError MoveGamepadFocusToNeighbor(EOverlayDirection eDirection,ulong ulFrom) + public EVROverlayError MoveGamepadFocusToNeighbor(EOverlayDirection eDirection,ulong ulFrom) { EVROverlayError result = FnTable.MoveGamepadFocusToNeighbor(eDirection,ulFrom); return result; } - internal EVROverlayError SetOverlayTexture(ulong ulOverlayHandle,ref Texture_t pTexture) + public EVROverlayError SetOverlayDualAnalogTransform(ulong ulOverlay,EDualAnalogWhich eWhich,ref HmdVector2_t pvCenter,float fRadius) + { + EVROverlayError result = FnTable.SetOverlayDualAnalogTransform(ulOverlay,eWhich,ref pvCenter,fRadius); + return result; + } + public EVROverlayError GetOverlayDualAnalogTransform(ulong ulOverlay,EDualAnalogWhich eWhich,ref HmdVector2_t pvCenter,ref float pfRadius) + { + pfRadius = 0; + EVROverlayError result = FnTable.GetOverlayDualAnalogTransform(ulOverlay,eWhich,ref pvCenter,ref pfRadius); + return result; + } + public EVROverlayError SetOverlayTexture(ulong ulOverlayHandle,ref Texture_t pTexture) { EVROverlayError result = FnTable.SetOverlayTexture(ulOverlayHandle,ref pTexture); return result; } - internal EVROverlayError ClearOverlayTexture(ulong ulOverlayHandle) + public EVROverlayError ClearOverlayTexture(ulong ulOverlayHandle) { EVROverlayError result = FnTable.ClearOverlayTexture(ulOverlayHandle); return result; } - internal EVROverlayError SetOverlayRaw(ulong ulOverlayHandle,IntPtr pvBuffer,uint unWidth,uint unHeight,uint unDepth) + public EVROverlayError SetOverlayRaw(ulong ulOverlayHandle,IntPtr pvBuffer,uint unWidth,uint unHeight,uint unDepth) { EVROverlayError result = FnTable.SetOverlayRaw(ulOverlayHandle,pvBuffer,unWidth,unHeight,unDepth); return result; } - internal EVROverlayError SetOverlayFromFile(ulong ulOverlayHandle,string pchFilePath) + public EVROverlayError SetOverlayFromFile(ulong ulOverlayHandle,string pchFilePath) { EVROverlayError result = FnTable.SetOverlayFromFile(ulOverlayHandle,pchFilePath); return result; } - internal EVROverlayError GetOverlayTexture(ulong ulOverlayHandle,ref IntPtr pNativeTextureHandle,IntPtr pNativeTextureRef,ref uint pWidth,ref uint pHeight,ref uint pNativeFormat,ref EGraphicsAPIConvention pAPI,ref EColorSpace pColorSpace) + public EVROverlayError GetOverlayTexture(ulong ulOverlayHandle,ref IntPtr pNativeTextureHandle,IntPtr pNativeTextureRef,ref uint pWidth,ref uint pHeight,ref uint pNativeFormat,ref ETextureType pAPIType,ref EColorSpace pColorSpace,ref VRTextureBounds_t pTextureBounds) { pWidth = 0; pHeight = 0; pNativeFormat = 0; - EVROverlayError result = FnTable.GetOverlayTexture(ulOverlayHandle,ref pNativeTextureHandle,pNativeTextureRef,ref pWidth,ref pHeight,ref pNativeFormat,ref pAPI,ref pColorSpace); + EVROverlayError result = FnTable.GetOverlayTexture(ulOverlayHandle,ref pNativeTextureHandle,pNativeTextureRef,ref pWidth,ref pHeight,ref pNativeFormat,ref pAPIType,ref pColorSpace,ref pTextureBounds); return result; } - internal EVROverlayError ReleaseNativeOverlayHandle(ulong ulOverlayHandle,IntPtr pNativeTextureHandle) + public EVROverlayError ReleaseNativeOverlayHandle(ulong ulOverlayHandle,IntPtr pNativeTextureHandle) { EVROverlayError result = FnTable.ReleaseNativeOverlayHandle(ulOverlayHandle,pNativeTextureHandle); return result; } - internal EVROverlayError GetOverlayTextureSize(ulong ulOverlayHandle,ref uint pWidth,ref uint pHeight) + public EVROverlayError GetOverlayTextureSize(ulong ulOverlayHandle,ref uint pWidth,ref uint pHeight) { pWidth = 0; pHeight = 0; EVROverlayError result = FnTable.GetOverlayTextureSize(ulOverlayHandle,ref pWidth,ref pHeight); return result; } - internal EVROverlayError CreateDashboardOverlay(string pchOverlayKey,string pchOverlayFriendlyName,ref ulong pMainHandle,ref ulong pThumbnailHandle) + public EVROverlayError CreateDashboardOverlay(string pchOverlayKey,string pchOverlayFriendlyName,ref ulong pMainHandle,ref ulong pThumbnailHandle) { pMainHandle = 0; pThumbnailHandle = 0; EVROverlayError result = FnTable.CreateDashboardOverlay(pchOverlayKey,pchOverlayFriendlyName,ref pMainHandle,ref pThumbnailHandle); return result; } - internal bool IsDashboardVisible() + public bool IsDashboardVisible() { bool result = FnTable.IsDashboardVisible(); return result; } - internal bool IsActiveDashboardOverlay(ulong ulOverlayHandle) + public bool IsActiveDashboardOverlay(ulong ulOverlayHandle) { bool result = FnTable.IsActiveDashboardOverlay(ulOverlayHandle); return result; } - internal EVROverlayError SetDashboardOverlaySceneProcess(ulong ulOverlayHandle,uint unProcessId) + public EVROverlayError SetDashboardOverlaySceneProcess(ulong ulOverlayHandle,uint unProcessId) { EVROverlayError result = FnTable.SetDashboardOverlaySceneProcess(ulOverlayHandle,unProcessId); return result; } - internal EVROverlayError GetDashboardOverlaySceneProcess(ulong ulOverlayHandle,ref uint punProcessId) + public EVROverlayError GetDashboardOverlaySceneProcess(ulong ulOverlayHandle,ref uint punProcessId) { punProcessId = 0; EVROverlayError result = FnTable.GetDashboardOverlaySceneProcess(ulOverlayHandle,ref punProcessId); return result; } - internal void ShowDashboard(string pchOverlayToShow) + public void ShowDashboard(string pchOverlayToShow) { FnTable.ShowDashboard(pchOverlayToShow); } - internal uint GetPrimaryDashboardDevice() + public uint GetPrimaryDashboardDevice() { uint result = FnTable.GetPrimaryDashboardDevice(); return result; } - internal EVROverlayError ShowKeyboard(int eInputMode,int eLineInputMode,string pchDescription,uint unCharMax,string pchExistingText,bool bUseMinimalMode,ulong uUserValue) + public EVROverlayError ShowKeyboard(int eInputMode,int eLineInputMode,string pchDescription,uint unCharMax,string pchExistingText,bool bUseMinimalMode,ulong uUserValue) { EVROverlayError result = FnTable.ShowKeyboard(eInputMode,eLineInputMode,pchDescription,unCharMax,pchExistingText,bUseMinimalMode,uUserValue); return result; } - internal EVROverlayError ShowKeyboardForOverlay(ulong ulOverlayHandle,int eInputMode,int eLineInputMode,string pchDescription,uint unCharMax,string pchExistingText,bool bUseMinimalMode,ulong uUserValue) + public EVROverlayError ShowKeyboardForOverlay(ulong ulOverlayHandle,int eInputMode,int eLineInputMode,string pchDescription,uint unCharMax,string pchExistingText,bool bUseMinimalMode,ulong uUserValue) { EVROverlayError result = FnTable.ShowKeyboardForOverlay(ulOverlayHandle,eInputMode,eLineInputMode,pchDescription,unCharMax,pchExistingText,bUseMinimalMode,uUserValue); return result; } - internal uint GetKeyboardText(System.Text.StringBuilder pchText,uint cchText) + public uint GetKeyboardText(System.Text.StringBuilder pchText,uint cchText) { uint result = FnTable.GetKeyboardText(pchText,cchText); return result; } - internal void HideKeyboard() + public void HideKeyboard() { FnTable.HideKeyboard(); } - internal void SetKeyboardTransformAbsolute(ETrackingUniverseOrigin eTrackingOrigin,ref HmdMatrix34_t pmatTrackingOriginToKeyboardTransform) + public void SetKeyboardTransformAbsolute(ETrackingUniverseOrigin eTrackingOrigin,ref HmdMatrix34_t pmatTrackingOriginToKeyboardTransform) { FnTable.SetKeyboardTransformAbsolute(eTrackingOrigin,ref pmatTrackingOriginToKeyboardTransform); } - internal void SetKeyboardPositionForOverlay(ulong ulOverlayHandle,HmdRect2_t avoidRect) + public void SetKeyboardPositionForOverlay(ulong ulOverlayHandle,HmdRect2_t avoidRect) { FnTable.SetKeyboardPositionForOverlay(ulOverlayHandle,avoidRect); } - internal EVROverlayError SetOverlayIntersectionMask(ulong ulOverlayHandle,ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives,uint unNumMaskPrimitives,uint unPrimitiveSize) + public EVROverlayError SetOverlayIntersectionMask(ulong ulOverlayHandle,ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives,uint unNumMaskPrimitives,uint unPrimitiveSize) { EVROverlayError result = FnTable.SetOverlayIntersectionMask(ulOverlayHandle,ref pMaskPrimitives,unNumMaskPrimitives,unPrimitiveSize); return result; } + public EVROverlayError GetOverlayFlags(ulong ulOverlayHandle,ref uint pFlags) + { + pFlags = 0; + EVROverlayError result = FnTable.GetOverlayFlags(ulOverlayHandle,ref pFlags); + return result; + } + public VRMessageOverlayResponse ShowMessageOverlay(string pchText,string pchCaption,string pchButton0Text,string pchButton1Text,string pchButton2Text,string pchButton3Text) + { + VRMessageOverlayResponse result = FnTable.ShowMessageOverlay(pchText,pchCaption,pchButton0Text,pchButton1Text,pchButton2Text,pchButton3Text); + return result; + } + public void CloseMessageOverlay() + { + FnTable.CloseMessageOverlay(); + } } -internal class CVRRenderModels +public class CVRRenderModels { IVRRenderModels FnTable; internal CVRRenderModels(IntPtr pInterface) { FnTable = (IVRRenderModels)Marshal.PtrToStructure(pInterface, typeof(IVRRenderModels)); } - internal EVRRenderModelError LoadRenderModel_Async(string pchRenderModelName,ref IntPtr ppRenderModel) + public EVRRenderModelError LoadRenderModel_Async(string pchRenderModelName,ref IntPtr ppRenderModel) { EVRRenderModelError result = FnTable.LoadRenderModel_Async(pchRenderModelName,ref ppRenderModel); return result; } - internal void FreeRenderModel(IntPtr pRenderModel) + public void FreeRenderModel(IntPtr pRenderModel) { FnTable.FreeRenderModel(pRenderModel); } - internal EVRRenderModelError LoadTexture_Async(int textureId,ref IntPtr ppTexture) + public EVRRenderModelError LoadTexture_Async(int textureId,ref IntPtr ppTexture) { EVRRenderModelError result = FnTable.LoadTexture_Async(textureId,ref ppTexture); return result; } - internal void FreeTexture(IntPtr pTexture) + public void FreeTexture(IntPtr pTexture) { FnTable.FreeTexture(pTexture); } - internal EVRRenderModelError LoadTextureD3D11_Async(int textureId,IntPtr pD3D11Device,ref IntPtr ppD3D11Texture2D) + public EVRRenderModelError LoadTextureD3D11_Async(int textureId,IntPtr pD3D11Device,ref IntPtr ppD3D11Texture2D) { EVRRenderModelError result = FnTable.LoadTextureD3D11_Async(textureId,pD3D11Device,ref ppD3D11Texture2D); return result; } - internal EVRRenderModelError LoadIntoTextureD3D11_Async(int textureId,IntPtr pDstTexture) + public EVRRenderModelError LoadIntoTextureD3D11_Async(int textureId,IntPtr pDstTexture) { EVRRenderModelError result = FnTable.LoadIntoTextureD3D11_Async(textureId,pDstTexture); return result; } - internal void FreeTextureD3D11(IntPtr pD3D11Texture2D) + public void FreeTextureD3D11(IntPtr pD3D11Texture2D) { FnTable.FreeTextureD3D11(pD3D11Texture2D); } - internal uint GetRenderModelName(uint unRenderModelIndex,System.Text.StringBuilder pchRenderModelName,uint unRenderModelNameLen) + public uint GetRenderModelName(uint unRenderModelIndex,System.Text.StringBuilder pchRenderModelName,uint unRenderModelNameLen) { uint result = FnTable.GetRenderModelName(unRenderModelIndex,pchRenderModelName,unRenderModelNameLen); return result; } - internal uint GetRenderModelCount() + public uint GetRenderModelCount() { uint result = FnTable.GetRenderModelCount(); return result; } - internal uint GetComponentCount(string pchRenderModelName) + public uint GetComponentCount(string pchRenderModelName) { uint result = FnTable.GetComponentCount(pchRenderModelName); return result; } - internal uint GetComponentName(string pchRenderModelName,uint unComponentIndex,System.Text.StringBuilder pchComponentName,uint unComponentNameLen) + public uint GetComponentName(string pchRenderModelName,uint unComponentIndex,System.Text.StringBuilder pchComponentName,uint unComponentNameLen) { uint result = FnTable.GetComponentName(pchRenderModelName,unComponentIndex,pchComponentName,unComponentNameLen); return result; } - internal ulong GetComponentButtonMask(string pchRenderModelName,string pchComponentName) + public ulong GetComponentButtonMask(string pchRenderModelName,string pchComponentName) { ulong result = FnTable.GetComponentButtonMask(pchRenderModelName,pchComponentName); return result; } - internal uint GetComponentRenderModelName(string pchRenderModelName,string pchComponentName,System.Text.StringBuilder pchComponentRenderModelName,uint unComponentRenderModelNameLen) + public uint GetComponentRenderModelName(string pchRenderModelName,string pchComponentName,System.Text.StringBuilder pchComponentRenderModelName,uint unComponentRenderModelNameLen) { uint result = FnTable.GetComponentRenderModelName(pchRenderModelName,pchComponentName,pchComponentRenderModelName,unComponentRenderModelNameLen); return result; } - internal bool GetComponentState(string pchRenderModelName,string pchComponentName,ref VRControllerState_t pControllerState,ref RenderModel_ControllerMode_State_t pState,ref RenderModel_ComponentState_t pComponentState) + public bool GetComponentStateForDevicePath(string pchRenderModelName,string pchComponentName,ulong devicePath,ref RenderModel_ControllerMode_State_t pState,ref RenderModel_ComponentState_t pComponentState) { + bool result = FnTable.GetComponentStateForDevicePath(pchRenderModelName,pchComponentName,devicePath,ref pState,ref pComponentState); + return result; + } +// This is a terrible hack to workaround the fact that VRControllerState_t and VREvent_t were +// originally mis-compiled with the wrong packing for Linux and OSX. + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate bool _GetComponentStatePacked(string pchRenderModelName,string pchComponentName,ref VRControllerState_t_Packed pControllerState,ref RenderModel_ControllerMode_State_t pState,ref RenderModel_ComponentState_t pComponentState); + [StructLayout(LayoutKind.Explicit)] + struct GetComponentStateUnion + { + [FieldOffset(0)] + public IVRRenderModels._GetComponentState pGetComponentState; + [FieldOffset(0)] + public _GetComponentStatePacked pGetComponentStatePacked; + } + public bool GetComponentState(string pchRenderModelName,string pchComponentName,ref VRControllerState_t pControllerState,ref RenderModel_ControllerMode_State_t pState,ref RenderModel_ComponentState_t pComponentState) + { +#if !UNITY_METRO + if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) || + (System.Environment.OSVersion.Platform == System.PlatformID.Unix)) + { + GetComponentStateUnion u; + VRControllerState_t_Packed state_packed = new VRControllerState_t_Packed(pControllerState); + u.pGetComponentStatePacked = null; + u.pGetComponentState = FnTable.GetComponentState; + bool packed_result = u.pGetComponentStatePacked(pchRenderModelName,pchComponentName,ref state_packed,ref pState,ref pComponentState); + + state_packed.Unpack(ref pControllerState); + return packed_result; + } +#endif bool result = FnTable.GetComponentState(pchRenderModelName,pchComponentName,ref pControllerState,ref pState,ref pComponentState); return result; } - internal bool RenderModelHasComponent(string pchRenderModelName,string pchComponentName) + public bool RenderModelHasComponent(string pchRenderModelName,string pchComponentName) { bool result = FnTable.RenderModelHasComponent(pchRenderModelName,pchComponentName); return result; } - internal uint GetRenderModelThumbnailURL(string pchRenderModelName,System.Text.StringBuilder pchThumbnailURL,uint unThumbnailURLLen,ref EVRRenderModelError peError) + public uint GetRenderModelThumbnailURL(string pchRenderModelName,System.Text.StringBuilder pchThumbnailURL,uint unThumbnailURLLen,ref EVRRenderModelError peError) { uint result = FnTable.GetRenderModelThumbnailURL(pchRenderModelName,pchThumbnailURL,unThumbnailURLLen,ref peError); return result; } - internal uint GetRenderModelOriginalPath(string pchRenderModelName,System.Text.StringBuilder pchOriginalPath,uint unOriginalPathLen,ref EVRRenderModelError peError) + public uint GetRenderModelOriginalPath(string pchRenderModelName,System.Text.StringBuilder pchOriginalPath,uint unOriginalPathLen,ref EVRRenderModelError peError) { uint result = FnTable.GetRenderModelOriginalPath(pchRenderModelName,pchOriginalPath,unOriginalPathLen,ref peError); return result; } - internal string GetRenderModelErrorNameFromEnum(EVRRenderModelError error) + public string GetRenderModelErrorNameFromEnum(EVRRenderModelError error) { IntPtr result = FnTable.GetRenderModelErrorNameFromEnum(error); return Marshal.PtrToStringAnsi(result); @@ -2763,20 +3281,20 @@ internal string GetRenderModelErrorNameFromEnum(EVRRenderModelError error) } -internal class CVRNotifications +public class CVRNotifications { IVRNotifications FnTable; internal CVRNotifications(IntPtr pInterface) { FnTable = (IVRNotifications)Marshal.PtrToStructure(pInterface, typeof(IVRNotifications)); } - internal EVRNotificationError CreateNotification(ulong ulOverlayHandle,ulong ulUserValue,EVRNotificationType type,string pchText,EVRNotificationStyle style,ref NotificationBitmap_t pImage,ref uint pNotificationId) + public EVRNotificationError CreateNotification(ulong ulOverlayHandle,ulong ulUserValue,EVRNotificationType type,string pchText,EVRNotificationStyle style,ref NotificationBitmap_t pImage,ref uint pNotificationId) { pNotificationId = 0; EVRNotificationError result = FnTable.CreateNotification(ulOverlayHandle,ulUserValue,type,pchText,style,ref pImage,ref pNotificationId); return result; } - internal EVRNotificationError RemoveNotification(uint notificationId) + public EVRNotificationError RemoveNotification(uint notificationId) { EVRNotificationError result = FnTable.RemoveNotification(notificationId); return result; @@ -2784,109 +3302,109 @@ internal EVRNotificationError RemoveNotification(uint notificationId) } -internal class CVRSettings +public class CVRSettings { IVRSettings FnTable; internal CVRSettings(IntPtr pInterface) { FnTable = (IVRSettings)Marshal.PtrToStructure(pInterface, typeof(IVRSettings)); } - internal string GetSettingsErrorNameFromEnum(EVRSettingsError eError) + public string GetSettingsErrorNameFromEnum(EVRSettingsError eError) { IntPtr result = FnTable.GetSettingsErrorNameFromEnum(eError); return Marshal.PtrToStringAnsi(result); } - internal bool Sync(bool bForce,ref EVRSettingsError peError) + public bool Sync(bool bForce,ref EVRSettingsError peError) { bool result = FnTable.Sync(bForce,ref peError); return result; } - internal void SetBool(string pchSection,string pchSettingsKey,bool bValue,ref EVRSettingsError peError) + public void SetBool(string pchSection,string pchSettingsKey,bool bValue,ref EVRSettingsError peError) { FnTable.SetBool(pchSection,pchSettingsKey,bValue,ref peError); } - internal void SetInt32(string pchSection,string pchSettingsKey,int nValue,ref EVRSettingsError peError) + public void SetInt32(string pchSection,string pchSettingsKey,int nValue,ref EVRSettingsError peError) { FnTable.SetInt32(pchSection,pchSettingsKey,nValue,ref peError); } - internal void SetFloat(string pchSection,string pchSettingsKey,float flValue,ref EVRSettingsError peError) + public void SetFloat(string pchSection,string pchSettingsKey,float flValue,ref EVRSettingsError peError) { FnTable.SetFloat(pchSection,pchSettingsKey,flValue,ref peError); } - internal void SetString(string pchSection,string pchSettingsKey,string pchValue,ref EVRSettingsError peError) + public void SetString(string pchSection,string pchSettingsKey,string pchValue,ref EVRSettingsError peError) { FnTable.SetString(pchSection,pchSettingsKey,pchValue,ref peError); } - internal bool GetBool(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) + public bool GetBool(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) { bool result = FnTable.GetBool(pchSection,pchSettingsKey,ref peError); return result; } - internal int GetInt32(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) + public int GetInt32(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) { int result = FnTable.GetInt32(pchSection,pchSettingsKey,ref peError); return result; } - internal float GetFloat(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) + public float GetFloat(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) { float result = FnTable.GetFloat(pchSection,pchSettingsKey,ref peError); return result; } - internal void GetString(string pchSection,string pchSettingsKey,System.Text.StringBuilder pchValue,uint unValueLen,ref EVRSettingsError peError) + public void GetString(string pchSection,string pchSettingsKey,System.Text.StringBuilder pchValue,uint unValueLen,ref EVRSettingsError peError) { FnTable.GetString(pchSection,pchSettingsKey,pchValue,unValueLen,ref peError); } - internal void RemoveSection(string pchSection,ref EVRSettingsError peError) + public void RemoveSection(string pchSection,ref EVRSettingsError peError) { FnTable.RemoveSection(pchSection,ref peError); } - internal void RemoveKeyInSection(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) + public void RemoveKeyInSection(string pchSection,string pchSettingsKey,ref EVRSettingsError peError) { FnTable.RemoveKeyInSection(pchSection,pchSettingsKey,ref peError); } } -internal class CVRScreenshots +public class CVRScreenshots { IVRScreenshots FnTable; internal CVRScreenshots(IntPtr pInterface) { FnTable = (IVRScreenshots)Marshal.PtrToStructure(pInterface, typeof(IVRScreenshots)); } - internal EVRScreenshotError RequestScreenshot(ref uint pOutScreenshotHandle,EVRScreenshotType type,string pchPreviewFilename,string pchVRFilename) + public EVRScreenshotError RequestScreenshot(ref uint pOutScreenshotHandle,EVRScreenshotType type,string pchPreviewFilename,string pchVRFilename) { pOutScreenshotHandle = 0; EVRScreenshotError result = FnTable.RequestScreenshot(ref pOutScreenshotHandle,type,pchPreviewFilename,pchVRFilename); return result; } - internal EVRScreenshotError HookScreenshot(EVRScreenshotType [] pSupportedTypes) + public EVRScreenshotError HookScreenshot(EVRScreenshotType [] pSupportedTypes) { EVRScreenshotError result = FnTable.HookScreenshot(pSupportedTypes,(int) pSupportedTypes.Length); return result; } - internal EVRScreenshotType GetScreenshotPropertyType(uint screenshotHandle,ref EVRScreenshotError pError) + public EVRScreenshotType GetScreenshotPropertyType(uint screenshotHandle,ref EVRScreenshotError pError) { EVRScreenshotType result = FnTable.GetScreenshotPropertyType(screenshotHandle,ref pError); return result; } - internal uint GetScreenshotPropertyFilename(uint screenshotHandle,EVRScreenshotPropertyFilenames filenameType,System.Text.StringBuilder pchFilename,uint cchFilename,ref EVRScreenshotError pError) + public uint GetScreenshotPropertyFilename(uint screenshotHandle,EVRScreenshotPropertyFilenames filenameType,System.Text.StringBuilder pchFilename,uint cchFilename,ref EVRScreenshotError pError) { uint result = FnTable.GetScreenshotPropertyFilename(screenshotHandle,filenameType,pchFilename,cchFilename,ref pError); return result; } - internal EVRScreenshotError UpdateScreenshotProgress(uint screenshotHandle,float flProgress) + public EVRScreenshotError UpdateScreenshotProgress(uint screenshotHandle,float flProgress) { EVRScreenshotError result = FnTable.UpdateScreenshotProgress(screenshotHandle,flProgress); return result; } - internal EVRScreenshotError TakeStereoScreenshot(ref uint pOutScreenshotHandle,string pchPreviewFilename,string pchVRFilename) + public EVRScreenshotError TakeStereoScreenshot(ref uint pOutScreenshotHandle,string pchPreviewFilename,string pchVRFilename) { pOutScreenshotHandle = 0; EVRScreenshotError result = FnTable.TakeStereoScreenshot(ref pOutScreenshotHandle,pchPreviewFilename,pchVRFilename); return result; } - internal EVRScreenshotError SubmitScreenshot(uint screenshotHandle,EVRScreenshotType type,string pchSourcePreviewFilename,string pchSourceVRFilename) + public EVRScreenshotError SubmitScreenshot(uint screenshotHandle,EVRScreenshotType type,string pchSourcePreviewFilename,string pchSourceVRFilename) { EVRScreenshotError result = FnTable.SubmitScreenshot(screenshotHandle,type,pchSourcePreviewFilename,pchSourceVRFilename); return result; @@ -2894,19 +3412,19 @@ internal EVRScreenshotError SubmitScreenshot(uint screenshotHandle,EVRScreenshot } -internal class CVRResources +public class CVRResources { IVRResources FnTable; internal CVRResources(IntPtr pInterface) { FnTable = (IVRResources)Marshal.PtrToStructure(pInterface, typeof(IVRResources)); } - internal uint LoadSharedResource(string pchResourceName,string pchBuffer,uint unBufferLen) + public uint LoadSharedResource(string pchResourceName,string pchBuffer,uint unBufferLen) { uint result = FnTable.LoadSharedResource(pchResourceName,pchBuffer,unBufferLen); return result; } - internal uint GetResourceFullPath(string pchResourceName,string pchResourceTypeDirectory,string pchPathBuffer,uint unBufferLen) + public uint GetResourceFullPath(string pchResourceName,string pchResourceTypeDirectory,System.Text.StringBuilder pchPathBuffer,uint unBufferLen) { uint result = FnTable.GetResourceFullPath(pchResourceName,pchResourceTypeDirectory,pchPathBuffer,unBufferLen); return result; @@ -2914,16 +3432,255 @@ internal uint GetResourceFullPath(string pchResourceName,string pchResourceTypeD } -internal class OpenVRInterop +public class CVRDriverManager +{ + IVRDriverManager FnTable; + internal CVRDriverManager(IntPtr pInterface) + { + FnTable = (IVRDriverManager)Marshal.PtrToStructure(pInterface, typeof(IVRDriverManager)); + } + public uint GetDriverCount() + { + uint result = FnTable.GetDriverCount(); + return result; + } + public uint GetDriverName(uint nDriver,System.Text.StringBuilder pchValue,uint unBufferSize) + { + uint result = FnTable.GetDriverName(nDriver,pchValue,unBufferSize); + return result; + } + public ulong GetDriverHandle(string pchDriverName) + { + ulong result = FnTable.GetDriverHandle(pchDriverName); + return result; + } +} + + +public class CVRInput +{ + IVRInput FnTable; + internal CVRInput(IntPtr pInterface) + { + FnTable = (IVRInput)Marshal.PtrToStructure(pInterface, typeof(IVRInput)); + } + public EVRInputError SetActionManifestPath(string pchActionManifestPath) + { + EVRInputError result = FnTable.SetActionManifestPath(pchActionManifestPath); + return result; + } + public EVRInputError GetActionSetHandle(string pchActionSetName,ref ulong pHandle) + { + pHandle = 0; + EVRInputError result = FnTable.GetActionSetHandle(pchActionSetName,ref pHandle); + return result; + } + public EVRInputError GetActionHandle(string pchActionName,ref ulong pHandle) + { + pHandle = 0; + EVRInputError result = FnTable.GetActionHandle(pchActionName,ref pHandle); + return result; + } + public EVRInputError GetInputSourceHandle(string pchInputSourcePath,ref ulong pHandle) + { + pHandle = 0; + EVRInputError result = FnTable.GetInputSourceHandle(pchInputSourcePath,ref pHandle); + return result; + } + public EVRInputError UpdateActionState(VRActiveActionSet_t [] pSets,uint unSizeOfVRSelectedActionSet_t) + { + EVRInputError result = FnTable.UpdateActionState(pSets,unSizeOfVRSelectedActionSet_t,(uint) pSets.Length); + return result; + } + public EVRInputError GetDigitalActionData(ulong action,ref InputDigitalActionData_t pActionData,uint unActionDataSize,ulong ulRestrictToDevice) + { + EVRInputError result = FnTable.GetDigitalActionData(action,ref pActionData,unActionDataSize,ulRestrictToDevice); + return result; + } + public EVRInputError GetAnalogActionData(ulong action,ref InputAnalogActionData_t pActionData,uint unActionDataSize,ulong ulRestrictToDevice) + { + EVRInputError result = FnTable.GetAnalogActionData(action,ref pActionData,unActionDataSize,ulRestrictToDevice); + return result; + } + public EVRInputError GetPoseActionData(ulong action,ETrackingUniverseOrigin eOrigin,float fPredictedSecondsFromNow,ref InputPoseActionData_t pActionData,uint unActionDataSize,ulong ulRestrictToDevice) + { + EVRInputError result = FnTable.GetPoseActionData(action,eOrigin,fPredictedSecondsFromNow,ref pActionData,unActionDataSize,ulRestrictToDevice); + return result; + } + public EVRInputError GetSkeletalActionData(ulong action,ref InputSkeletalActionData_t pActionData,uint unActionDataSize) + { + EVRInputError result = FnTable.GetSkeletalActionData(action,ref pActionData,unActionDataSize); + return result; + } + public EVRInputError GetBoneCount(ulong action,ref uint pBoneCount) + { + pBoneCount = 0; + EVRInputError result = FnTable.GetBoneCount(action,ref pBoneCount); + return result; + } + public EVRInputError GetBoneHierarchy(ulong action,int [] pParentIndices) + { + EVRInputError result = FnTable.GetBoneHierarchy(action,pParentIndices,(uint) pParentIndices.Length); + return result; + } + public EVRInputError GetBoneName(ulong action,int nBoneIndex,System.Text.StringBuilder pchBoneName,uint unNameBufferSize) + { + EVRInputError result = FnTable.GetBoneName(action,nBoneIndex,pchBoneName,unNameBufferSize); + return result; + } + public EVRInputError GetSkeletalReferenceTransforms(ulong action,EVRSkeletalTransformSpace eTransformSpace,EVRSkeletalReferencePose eReferencePose,VRBoneTransform_t [] pTransformArray) + { + EVRInputError result = FnTable.GetSkeletalReferenceTransforms(action,eTransformSpace,eReferencePose,pTransformArray,(uint) pTransformArray.Length); + return result; + } + public EVRInputError GetSkeletalTrackingLevel(ulong action,ref EVRSkeletalTrackingLevel pSkeletalTrackingLevel) + { + EVRInputError result = FnTable.GetSkeletalTrackingLevel(action,ref pSkeletalTrackingLevel); + return result; + } + public EVRInputError GetSkeletalBoneData(ulong action,EVRSkeletalTransformSpace eTransformSpace,EVRSkeletalMotionRange eMotionRange,VRBoneTransform_t [] pTransformArray) + { + EVRInputError result = FnTable.GetSkeletalBoneData(action,eTransformSpace,eMotionRange,pTransformArray,(uint) pTransformArray.Length); + return result; + } + public EVRInputError GetSkeletalSummaryData(ulong action,ref VRSkeletalSummaryData_t pSkeletalSummaryData) + { + EVRInputError result = FnTable.GetSkeletalSummaryData(action,ref pSkeletalSummaryData); + return result; + } + public EVRInputError GetSkeletalBoneDataCompressed(ulong action,EVRSkeletalMotionRange eMotionRange,IntPtr pvCompressedData,uint unCompressedSize,ref uint punRequiredCompressedSize) + { + punRequiredCompressedSize = 0; + EVRInputError result = FnTable.GetSkeletalBoneDataCompressed(action,eMotionRange,pvCompressedData,unCompressedSize,ref punRequiredCompressedSize); + return result; + } + public EVRInputError DecompressSkeletalBoneData(IntPtr pvCompressedBuffer,uint unCompressedBufferSize,EVRSkeletalTransformSpace eTransformSpace,VRBoneTransform_t [] pTransformArray) + { + EVRInputError result = FnTable.DecompressSkeletalBoneData(pvCompressedBuffer,unCompressedBufferSize,eTransformSpace,pTransformArray,(uint) pTransformArray.Length); + return result; + } + public EVRInputError TriggerHapticVibrationAction(ulong action,float fStartSecondsFromNow,float fDurationSeconds,float fFrequency,float fAmplitude,ulong ulRestrictToDevice) + { + EVRInputError result = FnTable.TriggerHapticVibrationAction(action,fStartSecondsFromNow,fDurationSeconds,fFrequency,fAmplitude,ulRestrictToDevice); + return result; + } + public EVRInputError GetActionOrigins(ulong actionSetHandle,ulong digitalActionHandle,ulong [] originsOut) + { + EVRInputError result = FnTable.GetActionOrigins(actionSetHandle,digitalActionHandle,originsOut,(uint) originsOut.Length); + return result; + } + public EVRInputError GetOriginLocalizedName(ulong origin,System.Text.StringBuilder pchNameArray,uint unNameArraySize,int unStringSectionsToInclude) + { + EVRInputError result = FnTable.GetOriginLocalizedName(origin,pchNameArray,unNameArraySize,unStringSectionsToInclude); + return result; + } + public EVRInputError GetOriginTrackedDeviceInfo(ulong origin,ref InputOriginInfo_t pOriginInfo,uint unOriginInfoSize) + { + EVRInputError result = FnTable.GetOriginTrackedDeviceInfo(origin,ref pOriginInfo,unOriginInfoSize); + return result; + } + public EVRInputError ShowActionOrigins(ulong actionSetHandle,ulong ulActionHandle) + { + EVRInputError result = FnTable.ShowActionOrigins(actionSetHandle,ulActionHandle); + return result; + } + public EVRInputError ShowBindingsForActionSet(VRActiveActionSet_t [] pSets,uint unSizeOfVRSelectedActionSet_t,ulong originToHighlight) + { + EVRInputError result = FnTable.ShowBindingsForActionSet(pSets,unSizeOfVRSelectedActionSet_t,(uint) pSets.Length,originToHighlight); + return result; + } +} + + +public class CVRIOBuffer +{ + IVRIOBuffer FnTable; + internal CVRIOBuffer(IntPtr pInterface) + { + FnTable = (IVRIOBuffer)Marshal.PtrToStructure(pInterface, typeof(IVRIOBuffer)); + } + public EIOBufferError Open(string pchPath,EIOBufferMode mode,uint unElementSize,uint unElements,ref ulong pulBuffer) + { + pulBuffer = 0; + EIOBufferError result = FnTable.Open(pchPath,mode,unElementSize,unElements,ref pulBuffer); + return result; + } + public EIOBufferError Close(ulong ulBuffer) + { + EIOBufferError result = FnTable.Close(ulBuffer); + return result; + } + public EIOBufferError Read(ulong ulBuffer,IntPtr pDst,uint unBytes,ref uint punRead) + { + punRead = 0; + EIOBufferError result = FnTable.Read(ulBuffer,pDst,unBytes,ref punRead); + return result; + } + public EIOBufferError Write(ulong ulBuffer,IntPtr pSrc,uint unBytes) + { + EIOBufferError result = FnTable.Write(ulBuffer,pSrc,unBytes); + return result; + } + public ulong PropertyContainer(ulong ulBuffer) + { + ulong result = FnTable.PropertyContainer(ulBuffer); + return result; + } + public bool HasReaders(ulong ulBuffer) + { + bool result = FnTable.HasReaders(ulBuffer); + return result; + } +} + + +public class CVRSpatialAnchors +{ + IVRSpatialAnchors FnTable; + internal CVRSpatialAnchors(IntPtr pInterface) + { + FnTable = (IVRSpatialAnchors)Marshal.PtrToStructure(pInterface, typeof(IVRSpatialAnchors)); + } + public EVRSpatialAnchorError CreateSpatialAnchorFromDescriptor(string pchDescriptor,ref uint pHandleOut) + { + pHandleOut = 0; + EVRSpatialAnchorError result = FnTable.CreateSpatialAnchorFromDescriptor(pchDescriptor,ref pHandleOut); + return result; + } + public EVRSpatialAnchorError CreateSpatialAnchorFromPose(uint unDeviceIndex,ETrackingUniverseOrigin eOrigin,ref SpatialAnchorPose_t pPose,ref uint pHandleOut) + { + pHandleOut = 0; + EVRSpatialAnchorError result = FnTable.CreateSpatialAnchorFromPose(unDeviceIndex,eOrigin,ref pPose,ref pHandleOut); + return result; + } + public EVRSpatialAnchorError GetSpatialAnchorPose(uint unHandle,ETrackingUniverseOrigin eOrigin,ref SpatialAnchorPose_t pPoseOut) + { + EVRSpatialAnchorError result = FnTable.GetSpatialAnchorPose(unHandle,eOrigin,ref pPoseOut); + return result; + } + public EVRSpatialAnchorError GetSpatialAnchorDescriptor(uint unHandle,System.Text.StringBuilder pchDescriptorOut,ref uint punDescriptorBufferLenInOut) + { + punDescriptorBufferLenInOut = 0; + EVRSpatialAnchorError result = FnTable.GetSpatialAnchorDescriptor(unHandle,pchDescriptorOut,ref punDescriptorBufferLenInOut); + return result; + } +} + + +public class OpenVRInterop { [DllImportAttribute("openvr_api", EntryPoint = "VR_InitInternal", CallingConvention = CallingConvention.Cdecl)] internal static extern uint InitInternal(ref EVRInitError peError, EVRApplicationType eApplicationType); + [DllImportAttribute("openvr_api", EntryPoint = "VR_InitInternal2", CallingConvention = CallingConvention.Cdecl)] + internal static extern uint InitInternal2(ref EVRInitError peError, EVRApplicationType eApplicationType,[In, MarshalAs(UnmanagedType.LPStr)] string pStartupInfo); [DllImportAttribute("openvr_api", EntryPoint = "VR_ShutdownInternal", CallingConvention = CallingConvention.Cdecl)] internal static extern void ShutdownInternal(); [DllImportAttribute("openvr_api", EntryPoint = "VR_IsHmdPresent", CallingConvention = CallingConvention.Cdecl)] internal static extern bool IsHmdPresent(); [DllImportAttribute("openvr_api", EntryPoint = "VR_IsRuntimeInstalled", CallingConvention = CallingConvention.Cdecl)] internal static extern bool IsRuntimeInstalled(); + [DllImportAttribute("openvr_api", EntryPoint = "VR_RuntimePath", CallingConvention = CallingConvention.Cdecl)] + internal static extern string RuntimePath(); [DllImportAttribute("openvr_api", EntryPoint = "VR_GetStringForHmdError", CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr GetStringForHmdError(EVRInitError error); [DllImportAttribute("openvr_api", EntryPoint = "VR_GetGenericInterface", CallingConvention = CallingConvention.Cdecl)] @@ -2935,53 +3692,72 @@ internal class OpenVRInterop } -internal enum EVREye +public enum EVREye { Eye_Left = 0, Eye_Right = 1, } -internal enum EGraphicsAPIConvention +public enum ETextureType { - API_DirectX = 0, - API_OpenGL = 1, + Invalid = -1, + DirectX = 0, + OpenGL = 1, + Vulkan = 2, + IOSurface = 3, + DirectX12 = 4, + DXGISharedHandle = 5, + Metal = 6, } -internal enum EColorSpace +public enum EColorSpace { Auto = 0, Gamma = 1, Linear = 2, } -internal enum ETrackingResult +public enum ETrackingResult { Uninitialized = 1, Calibrating_InProgress = 100, Calibrating_OutOfRange = 101, Running_OK = 200, Running_OutOfRange = 201, + Fallback_RotationOnly = 300, } -internal enum ETrackedDeviceClass +public enum ETrackedDeviceClass { Invalid = 0, HMD = 1, Controller = 2, + GenericTracker = 3, TrackingReference = 4, - Count = 5, - Other = 1000, + DisplayRedirect = 5, + Max = 6, } -internal enum ETrackedControllerRole +public enum ETrackedControllerRole { Invalid = 0, LeftHand = 1, RightHand = 2, + OptOut = 3, + Treadmill = 4, + Max = 4, } -internal enum ETrackingUniverseOrigin +public enum ETrackingUniverseOrigin { TrackingUniverseSeated = 0, TrackingUniverseStanding = 1, TrackingUniverseRawAndUncalibrated = 2, } -internal enum ETrackedDeviceProperty +public enum EAdditionalRadioFeatures { + None = 0, + HTCLinkBox = 1, + InternalDongle = 2, + ExternalDongle = 4, +} +public enum ETrackedDeviceProperty +{ + Prop_Invalid = 0, Prop_TrackingSystemName_String = 1000, Prop_ModelNumber_String = 1001, Prop_SerialNumber_String = 1002, @@ -3016,6 +3792,17 @@ internal enum ETrackedDeviceProperty Prop_DriverVersion_String = 1031, Prop_Firmware_ForceUpdateRequired_Bool = 1032, Prop_ViveSystemButtonFixRequired_Bool = 1033, + Prop_ParentDriver_Uint64 = 1034, + Prop_ResourceRoot_String = 1035, + Prop_RegisteredDeviceType_String = 1036, + Prop_InputProfilePath_String = 1037, + Prop_NeverTracked_Bool = 1038, + Prop_NumCameras_Int32 = 1039, + Prop_CameraFrameLayout_Int32 = 1040, + Prop_CameraStreamFormat_Int32 = 1041, + Prop_AdditionalDeviceSettingsPath_String = 1042, + Prop_Identifiable_Bool = 1043, + Prop_BootloaderVersion_Uint64 = 1044, Prop_ReportsTimeSinceVSync_Bool = 2000, Prop_SecondsFromVsyncToPhotons_Float = 2001, Prop_DisplayFrequency_Float = 2002, @@ -3054,6 +3841,49 @@ internal enum ETrackedDeviceProperty Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035, Prop_DisplaySuppressed_Bool = 2036, Prop_DisplayAllowNightMode_Bool = 2037, + Prop_DisplayMCImageWidth_Int32 = 2038, + Prop_DisplayMCImageHeight_Int32 = 2039, + Prop_DisplayMCImageNumChannels_Int32 = 2040, + Prop_DisplayMCImageData_Binary = 2041, + Prop_SecondsFromPhotonsToVblank_Float = 2042, + Prop_DriverDirectModeSendsVsyncEvents_Bool = 2043, + Prop_DisplayDebugMode_Bool = 2044, + Prop_GraphicsAdapterLuid_Uint64 = 2045, + Prop_DriverProvidedChaperonePath_String = 2048, + Prop_ExpectedTrackingReferenceCount_Int32 = 2049, + Prop_ExpectedControllerCount_Int32 = 2050, + Prop_NamedIconPathControllerLeftDeviceOff_String = 2051, + Prop_NamedIconPathControllerRightDeviceOff_String = 2052, + Prop_NamedIconPathTrackingReferenceDeviceOff_String = 2053, + Prop_DoNotApplyPrediction_Bool = 2054, + Prop_CameraToHeadTransforms_Matrix34_Array = 2055, + Prop_DistortionMeshResolution_Int32 = 2056, + Prop_DriverIsDrawingControllers_Bool = 2057, + Prop_DriverRequestsApplicationPause_Bool = 2058, + Prop_DriverRequestsReducedRendering_Bool = 2059, + Prop_MinimumIpdStepMeters_Float = 2060, + Prop_AudioBridgeFirmwareVersion_Uint64 = 2061, + Prop_ImageBridgeFirmwareVersion_Uint64 = 2062, + Prop_ImuToHeadTransform_Matrix34 = 2063, + Prop_ImuFactoryGyroBias_Vector3 = 2064, + Prop_ImuFactoryGyroScale_Vector3 = 2065, + Prop_ImuFactoryAccelerometerBias_Vector3 = 2066, + Prop_ImuFactoryAccelerometerScale_Vector3 = 2067, + Prop_ConfigurationIncludesLighthouse20Features_Bool = 2069, + Prop_AdditionalRadioFeatures_Uint64 = 2070, + Prop_CameraWhiteBalance_Vector4_Array = 2071, + Prop_CameraDistortionFunction_Int32_Array = 2072, + Prop_CameraDistortionCoefficients_Float_Array = 2073, + Prop_ExpectedControllerType_String = 2074, + Prop_DriverRequestedMuraCorrectionMode_Int32 = 2200, + Prop_DriverRequestedMuraFeather_InnerLeft_Int32 = 2201, + Prop_DriverRequestedMuraFeather_InnerRight_Int32 = 2202, + Prop_DriverRequestedMuraFeather_InnerTop_Int32 = 2203, + Prop_DriverRequestedMuraFeather_InnerBottom_Int32 = 2204, + Prop_DriverRequestedMuraFeather_OuterLeft_Int32 = 2205, + Prop_DriverRequestedMuraFeather_OuterRight_Int32 = 2206, + Prop_DriverRequestedMuraFeather_OuterTop_Int32 = 2207, + Prop_DriverRequestedMuraFeather_OuterBottom_Int32 = 2208, Prop_AttachedDeviceId_String = 3000, Prop_SupportedButtons_Uint64 = 3001, Prop_Axis0Type_Int32 = 3002, @@ -3078,10 +3908,25 @@ internal enum ETrackedDeviceProperty Prop_NamedIconPathDeviceNotReady_String = 5006, Prop_NamedIconPathDeviceStandby_String = 5007, Prop_NamedIconPathDeviceAlertLow_String = 5008, + Prop_DisplayHiddenArea_Binary_Start = 5100, + Prop_DisplayHiddenArea_Binary_End = 5150, + Prop_ParentContainer = 5151, + Prop_UserConfigPath_String = 6000, + Prop_InstallPath_String = 6001, + Prop_HasDisplayComponent_Bool = 6002, + Prop_HasControllerComponent_Bool = 6003, + Prop_HasCameraComponent_Bool = 6004, + Prop_HasDriverDirectModeComponent_Bool = 6005, + Prop_HasVirtualDisplayComponent_Bool = 6006, + Prop_HasSpatialAnchorsSupport_Bool = 6007, + Prop_ControllerType_String = 7000, + Prop_LegacyInputProfile_String = 7001, + Prop_ControllerHandSelectionPriority_Int32 = 7002, Prop_VendorSpecific_Reserved_Start = 10000, Prop_VendorSpecific_Reserved_End = 10999, + Prop_TrackedDeviceProperty_Max = 1000000, } -internal enum ETrackedPropertyError +public enum ETrackedPropertyError { TrackedProp_Success = 0, TrackedProp_WrongDataType = 1, @@ -3093,15 +3938,21 @@ internal enum ETrackedPropertyError TrackedProp_ValueNotProvidedByDevice = 7, TrackedProp_StringExceedsMaximumLength = 8, TrackedProp_NotYetAvailable = 9, + TrackedProp_PermissionDenied = 10, + TrackedProp_InvalidOperation = 11, + TrackedProp_CannotWriteToWildcards = 12, + TrackedProp_IPCReadFailure = 13, } -internal enum EVRSubmitFlags +public enum EVRSubmitFlags { Submit_Default = 0, Submit_LensDistortionAlreadyApplied = 1, Submit_GlRenderBuffer = 2, - Submit_VulkanTexture = 4, + Submit_Reserved = 4, + Submit_TextureWithPose = 8, + Submit_TextureWithDepth = 16, } -internal enum EVRState +public enum EVRState { Undefined = -1, Off = 0, @@ -3113,7 +3964,7 @@ internal enum EVRState Standby = 6, Ready_Alert_Low = 7, } -internal enum EVREventType +public enum EVREventType { VREvent_None = 0, VREvent_TrackedDeviceActivated = 100, @@ -3127,18 +3978,31 @@ internal enum EVREventType VREvent_TrackedDeviceRoleChanged = 108, VREvent_WatchdogWakeUpRequested = 109, VREvent_LensDistortionChanged = 110, + VREvent_PropertyChanged = 111, + VREvent_WirelessDisconnect = 112, + VREvent_WirelessReconnect = 113, VREvent_ButtonPress = 200, VREvent_ButtonUnpress = 201, VREvent_ButtonTouch = 202, VREvent_ButtonUntouch = 203, + VREvent_DualAnalog_Press = 250, + VREvent_DualAnalog_Unpress = 251, + VREvent_DualAnalog_Touch = 252, + VREvent_DualAnalog_Untouch = 253, + VREvent_DualAnalog_Move = 254, + VREvent_DualAnalog_ModeSwitch1 = 255, + VREvent_DualAnalog_ModeSwitch2 = 256, + VREvent_DualAnalog_Cancel = 257, VREvent_MouseMove = 300, VREvent_MouseButtonDown = 301, VREvent_MouseButtonUp = 302, VREvent_FocusEnter = 303, VREvent_FocusLeave = 304, - VREvent_Scroll = 305, + VREvent_ScrollDiscrete = 305, VREvent_TouchPadMove = 306, VREvent_OverlayFocusChanged = 307, + VREvent_ReloadOverlays = 308, + VREvent_ScrollSmooth = 309, VREvent_InputFocusCaptured = 400, VREvent_InputFocusReleased = 401, VREvent_SceneFocusLost = 402, @@ -3147,8 +4011,12 @@ internal enum EVREventType VREvent_SceneFocusChanged = 405, VREvent_InputFocusChanged = 406, VREvent_SceneApplicationSecondaryRenderingStarted = 407, + VREvent_SceneApplicationUsingWrongGraphicsAdapter = 408, + VREvent_ActionBindingReloaded = 409, VREvent_HideRenderModels = 410, VREvent_ShowRenderModels = 411, + VREvent_ConsoleOpened = 420, + VREvent_ConsoleClosed = 421, VREvent_OverlayShown = 500, VREvent_OverlayHidden = 501, VREvent_DashboardActivated = 502, @@ -3163,16 +4031,19 @@ internal enum EVREventType VREvent_OverlayGamepadFocusGained = 511, VREvent_OverlayGamepadFocusLost = 512, VREvent_OverlaySharedTextureChanged = 513, - VREvent_DashboardGuideButtonDown = 514, - VREvent_DashboardGuideButtonUp = 515, VREvent_ScreenshotTriggered = 516, VREvent_ImageFailed = 517, VREvent_DashboardOverlayCreated = 518, + VREvent_SwitchGamepadFocus = 519, VREvent_RequestScreenshot = 520, VREvent_ScreenshotTaken = 521, VREvent_ScreenshotFailed = 522, VREvent_SubmitScreenshotToDashboard = 523, VREvent_ScreenshotProgressToDashboard = 524, + VREvent_PrimaryDashboardDeviceChanged = 525, + VREvent_RoomViewShown = 526, + VREvent_RoomViewHidden = 527, + VREvent_ShowUI = 528, VREvent_Notification_Shown = 600, VREvent_Notification_Hidden = 601, VREvent_Notification_BeginInteraction = 602, @@ -3187,6 +4058,7 @@ internal enum EVREventType VREvent_ChaperoneTempDataHasChanged = 802, VREvent_ChaperoneSettingsHaveChanged = 803, VREvent_SeatedZeroPoseReset = 804, + VREvent_ChaperoneFlushCache = 805, VREvent_AudioSettingsHaveChanged = 820, VREvent_BackgroundSettingHasChanged = 850, VREvent_CameraSettingsHaveChanged = 851, @@ -3194,7 +4066,21 @@ internal enum EVREventType VREvent_ModelSkinSettingsHaveChanged = 853, VREvent_EnvironmentSettingsHaveChanged = 854, VREvent_PowerSettingsHaveChanged = 855, + VREvent_EnableHomeAppSettingsHaveChanged = 856, + VREvent_SteamVRSectionSettingChanged = 857, + VREvent_LighthouseSectionSettingChanged = 858, + VREvent_NullSectionSettingChanged = 859, + VREvent_UserInterfaceSectionSettingChanged = 860, + VREvent_NotificationsSectionSettingChanged = 861, + VREvent_KeyboardSectionSettingChanged = 862, + VREvent_PerfSectionSettingChanged = 863, + VREvent_DashboardSectionSettingChanged = 864, + VREvent_WebInterfaceSectionSettingChanged = 865, + VREvent_TrackersSectionSettingChanged = 866, + VREvent_LastKnownSectionSettingChanged = 867, + VREvent_DismissedWarningsSectionSettingChanged = 868, VREvent_StatusUpdate = 900, + VREvent_WebInterface_InstallDriverCompleted = 950, VREvent_MCImageUpdated = 1000, VREvent_FirmwareUpdateStarted = 1100, VREvent_FirmwareUpdateFinished = 1101, @@ -3206,6 +4092,9 @@ internal enum EVREventType VREvent_ApplicationTransitionNewAppStarted = 1302, VREvent_ApplicationListUpdated = 1303, VREvent_ApplicationMimeTypeLoad = 1304, + VREvent_ApplicationTransitionNewAppLaunchComplete = 1305, + VREvent_ProcessConnected = 1306, + VREvent_ProcessDisconnected = 1307, VREvent_Compositor_MirrorWindowShown = 1400, VREvent_Compositor_MirrorWindowHidden = 1401, VREvent_Compositor_ChaperoneBoundsShown = 1410, @@ -3218,10 +4107,24 @@ internal enum EVREventType VREvent_PerformanceTest_EnableCapture = 1600, VREvent_PerformanceTest_DisableCapture = 1601, VREvent_PerformanceTest_FidelityLevel = 1602, + VREvent_MessageOverlay_Closed = 1650, + VREvent_MessageOverlayCloseRequested = 1651, + VREvent_Input_HapticVibration = 1700, + VREvent_Input_BindingLoadFailed = 1701, + VREvent_Input_BindingLoadSuccessful = 1702, + VREvent_Input_ActionManifestReloaded = 1703, + VREvent_Input_ActionManifestLoadFailed = 1704, + VREvent_Input_ProgressUpdate = 1705, + VREvent_Input_TrackerActivated = 1706, + VREvent_Input_BindingsUpdated = 1707, + VREvent_SpatialAnchors_PoseUpdated = 1800, + VREvent_SpatialAnchors_DescriptorUpdated = 1801, + VREvent_SpatialAnchors_RequestPoseUpdate = 1802, + VREvent_SpatialAnchors_RequestDescriptorUpdate = 1803, VREvent_VendorSpecific_Reserved_Start = 10000, VREvent_VendorSpecific_Reserved_End = 19999, } -internal enum EDeviceActivityLevel +public enum EDeviceActivityLevel { k_EDeviceActivityLevel_Unknown = -1, k_EDeviceActivityLevel_Idle = 0, @@ -3229,7 +4132,7 @@ internal enum EDeviceActivityLevel k_EDeviceActivityLevel_UserInteraction_Timeout = 2, k_EDeviceActivityLevel_Standby = 3, } -internal enum EVRButtonId +public enum EVRButtonId { k_EButton_System = 0, k_EButton_ApplicationMenu = 1, @@ -3248,33 +4151,87 @@ internal enum EVRButtonId k_EButton_SteamVR_Touchpad = 32, k_EButton_SteamVR_Trigger = 33, k_EButton_Dashboard_Back = 2, + k_EButton_Knuckles_A = 2, + k_EButton_Knuckles_B = 1, + k_EButton_Knuckles_JoyStick = 35, k_EButton_Max = 64, } -internal enum EVRMouseButton +public enum EVRMouseButton { Left = 1, Right = 2, Middle = 4, } -internal enum EHiddenAreaMeshType +public enum EDualAnalogWhich +{ + k_EDualAnalog_Left = 0, + k_EDualAnalog_Right = 1, +} +public enum EShowUIType +{ + ShowUI_ControllerBinding = 0, + ShowUI_ManageTrackers = 1, + ShowUI_QuickStart = 2, + ShowUI_Pairing = 3, +} +public enum EVRInputError +{ + None = 0, + NameNotFound = 1, + WrongType = 2, + InvalidHandle = 3, + InvalidParam = 4, + NoSteam = 5, + MaxCapacityReached = 6, + IPCError = 7, + NoActiveActionSet = 8, + InvalidDevice = 9, + InvalidSkeleton = 10, + InvalidBoneCount = 11, + InvalidCompressedData = 12, + NoData = 13, + BufferTooSmall = 14, + MismatchedActionManifest = 15, + MissingSkeletonData = 16, + InvalidBoneIndex = 17, +} +public enum EVRSpatialAnchorError +{ + Success = 0, + Internal = 1, + UnknownHandle = 2, + ArrayTooSmall = 3, + InvalidDescriptorChar = 4, + NotYetAvailable = 5, + NotAvailableInThisUniverse = 6, + PermanentlyUnavailable = 7, + WrongDriver = 8, + DescriptorTooLong = 9, + Unknown = 10, + NoRoomCalibration = 11, + InvalidArgument = 12, + UnknownDriver = 13, +} +public enum EHiddenAreaMeshType { k_eHiddenAreaMesh_Standard = 0, k_eHiddenAreaMesh_Inverse = 1, k_eHiddenAreaMesh_LineLoop = 2, + k_eHiddenAreaMesh_Max = 3, } -internal enum EVRControllerAxisType +public enum EVRControllerAxisType { k_eControllerAxis_None = 0, k_eControllerAxis_TrackPad = 1, k_eControllerAxis_Joystick = 2, k_eControllerAxis_Trigger = 3, } -internal enum EVRControllerEventOutputType +public enum EVRControllerEventOutputType { ControllerEventOutput_OSEvents = 0, ControllerEventOutput_VREvents = 1, } -internal enum ECollisionBoundsStyle +public enum ECollisionBoundsStyle { COLLISION_BOUNDS_STYLE_BEGINNER = 0, COLLISION_BOUNDS_STYLE_INTERMEDIATE = 1, @@ -3283,7 +4240,7 @@ internal enum ECollisionBoundsStyle COLLISION_BOUNDS_STYLE_NONE = 4, COLLISION_BOUNDS_STYLE_COUNT = 5, } -internal enum EVROverlayError +public enum EVROverlayError { None = 0, UnknownOverlay = 10, @@ -3306,8 +4263,11 @@ internal enum EVROverlayError NoNeighbor = 27, TooManyMaskPrimitives = 29, BadMaskPrimitive = 30, + TextureAlreadyLocked = 31, + TextureLockCapacityReached = 32, + TextureNotLocked = 33, } -internal enum EVRApplicationType +public enum EVRApplicationType { VRApplication_Other = 0, VRApplication_Scene = 1, @@ -3316,15 +4276,17 @@ internal enum EVRApplicationType VRApplication_Utility = 4, VRApplication_VRMonitor = 5, VRApplication_SteamWatchdog = 6, - VRApplication_Max = 7, + VRApplication_Bootstrapper = 7, + VRApplication_WebHelper = 8, + VRApplication_Max = 9, } -internal enum EVRFirmwareError +public enum EVRFirmwareError { None = 0, Success = 1, Fail = 2, } -internal enum EVRNotificationError +public enum EVRNotificationError { OK = 0, InvalidNotificationId = 100, @@ -3332,7 +4294,20 @@ internal enum EVRNotificationError InvalidOverlayHandle = 102, SystemWithUserValueAlreadyExists = 103, } -internal enum EVRInitError +public enum EVRSkeletalMotionRange +{ + WithController = 0, + WithoutController = 1, +} +public enum EVRSkeletalTrackingLevel +{ + VRSkeletalTracking_Estimated = 0, + VRSkeletalTracking_Partial = 1, + VRSkeletalTracking_Full = 2, + Count = 3, + Max = 2, +} +public enum EVRInitError { None = 0, Unknown = 1, @@ -3369,6 +4344,16 @@ internal enum EVRInitError Init_InvalidApplicationType = 130, Init_NotAvailableToWatchdogApps = 131, Init_WatchdogDisabledInSettings = 132, + Init_VRDashboardNotFound = 133, + Init_VRDashboardStartupFailed = 134, + Init_VRHomeNotFound = 135, + Init_VRHomeStartupFailed = 136, + Init_RebootingBusy = 137, + Init_FirmwareUpdateBusy = 138, + Init_FirmwareRecoveryBusy = 139, + Init_USBServiceBusy = 140, + Init_VRWebHelperStartupFailed = 141, + Init_TrackerManagerInitFailed = 142, Driver_Failed = 200, Driver_Unknown = 201, Driver_HmdUnknown = 202, @@ -3395,7 +4380,88 @@ internal enum EVRInitError Compositor_FirmwareRequiresUpdate = 402, Compositor_OverlayInitFailed = 403, Compositor_ScreenshotsInitFailed = 404, + Compositor_UnableToCreateDevice = 405, + Compositor_SharedStateIsNull = 406, + Compositor_NotificationManagerIsNull = 407, + Compositor_ResourceManagerClientIsNull = 408, + Compositor_MessageOverlaySharedStateInitFailure = 409, + Compositor_PropertiesInterfaceIsNull = 410, + Compositor_CreateFullscreenWindowFailed = 411, + Compositor_SettingsInterfaceIsNull = 412, + Compositor_FailedToShowWindow = 413, + Compositor_DistortInterfaceIsNull = 414, + Compositor_DisplayFrequencyFailure = 415, + Compositor_RendererInitializationFailed = 416, + Compositor_DXGIFactoryInterfaceIsNull = 417, + Compositor_DXGIFactoryCreateFailed = 418, + Compositor_DXGIFactoryQueryFailed = 419, + Compositor_InvalidAdapterDesktop = 420, + Compositor_InvalidHmdAttachment = 421, + Compositor_InvalidOutputDesktop = 422, + Compositor_InvalidDeviceProvided = 423, + Compositor_D3D11RendererInitializationFailed = 424, + Compositor_FailedToFindDisplayMode = 425, + Compositor_FailedToCreateSwapChain = 426, + Compositor_FailedToGetBackBuffer = 427, + Compositor_FailedToCreateRenderTarget = 428, + Compositor_FailedToCreateDXGI2SwapChain = 429, + Compositor_FailedtoGetDXGI2BackBuffer = 430, + Compositor_FailedToCreateDXGI2RenderTarget = 431, + Compositor_FailedToGetDXGIDeviceInterface = 432, + Compositor_SelectDisplayMode = 433, + Compositor_FailedToCreateNvAPIRenderTargets = 434, + Compositor_NvAPISetDisplayMode = 435, + Compositor_FailedToCreateDirectModeDisplay = 436, + Compositor_InvalidHmdPropertyContainer = 437, + Compositor_UpdateDisplayFrequency = 438, + Compositor_CreateRasterizerState = 439, + Compositor_CreateWireframeRasterizerState = 440, + Compositor_CreateSamplerState = 441, + Compositor_CreateClampToBorderSamplerState = 442, + Compositor_CreateAnisoSamplerState = 443, + Compositor_CreateOverlaySamplerState = 444, + Compositor_CreatePanoramaSamplerState = 445, + Compositor_CreateFontSamplerState = 446, + Compositor_CreateNoBlendState = 447, + Compositor_CreateBlendState = 448, + Compositor_CreateAlphaBlendState = 449, + Compositor_CreateBlendStateMaskR = 450, + Compositor_CreateBlendStateMaskG = 451, + Compositor_CreateBlendStateMaskB = 452, + Compositor_CreateDepthStencilState = 453, + Compositor_CreateDepthStencilStateNoWrite = 454, + Compositor_CreateDepthStencilStateNoDepth = 455, + Compositor_CreateFlushTexture = 456, + Compositor_CreateDistortionSurfaces = 457, + Compositor_CreateConstantBuffer = 458, + Compositor_CreateHmdPoseConstantBuffer = 459, + Compositor_CreateHmdPoseStagingConstantBuffer = 460, + Compositor_CreateSharedFrameInfoConstantBuffer = 461, + Compositor_CreateOverlayConstantBuffer = 462, + Compositor_CreateSceneTextureIndexConstantBuffer = 463, + Compositor_CreateReadableSceneTextureIndexConstantBuffer = 464, + Compositor_CreateLayerGraphicsTextureIndexConstantBuffer = 465, + Compositor_CreateLayerComputeTextureIndexConstantBuffer = 466, + Compositor_CreateLayerComputeSceneTextureIndexConstantBuffer = 467, + Compositor_CreateComputeHmdPoseConstantBuffer = 468, + Compositor_CreateGeomConstantBuffer = 469, + Compositor_CreatePanelMaskConstantBuffer = 470, + Compositor_CreatePixelSimUBO = 471, + Compositor_CreateMSAARenderTextures = 472, + Compositor_CreateResolveRenderTextures = 473, + Compositor_CreateComputeResolveRenderTextures = 474, + Compositor_CreateDriverDirectModeResolveTextures = 475, + Compositor_OpenDriverDirectModeResolveTextures = 476, + Compositor_CreateFallbackSyncTexture = 477, + Compositor_ShareFallbackSyncTexture = 478, + Compositor_CreateOverlayIndexBuffer = 479, + Compositor_CreateOverlayVertextBuffer = 480, + Compositor_CreateTextVertexBuffer = 481, + Compositor_CreateTextIndexBuffer = 482, + Compositor_CreateMirrorTextures = 483, + Compositor_CreateLastFrameRenderTexture = 484, VendorSpecific_UnableToConnectToOculusRuntime = 1000, + VendorSpecific_WindowsNotInDevMode = 1001, VendorSpecific_HmdFound_CantOpenDevice = 1101, VendorSpecific_HmdFound_UnableToRequestConfigStart = 1102, VendorSpecific_HmdFound_NoStoredConfig = 1103, @@ -3411,7 +4477,7 @@ internal enum EVRInitError VendorSpecific_HmdFound_ConfigFailedSanityCheck = 1113, Steam_SteamInstallationNotFound = 2000, } -internal enum EVRScreenshotType +public enum EVRScreenshotType { None = 0, Mono = 1, @@ -3420,12 +4486,12 @@ internal enum EVRScreenshotType MonoPanorama = 4, StereoPanorama = 5, } -internal enum EVRScreenshotPropertyFilenames +public enum EVRScreenshotPropertyFilenames { Preview = 0, VR = 1, } -internal enum EVRTrackedCameraError +public enum EVRTrackedCameraError { None = 0, OperationFailed = 100, @@ -3445,14 +4511,48 @@ internal enum EVRTrackedCameraError InvalidArgument = 114, InvalidFrameBufferSize = 115, } -internal enum EVRTrackedCameraFrameType +public enum EVRTrackedCameraFrameLayout +{ + Mono = 1, + Stereo = 2, + VerticalLayout = 16, + HorizontalLayout = 32, +} +public enum EVRTrackedCameraFrameType { Distorted = 0, Undistorted = 1, MaximumUndistorted = 2, MAX_CAMERA_FRAME_TYPES = 3, } -internal enum EVRApplicationError +public enum EVRDistortionFunctionType +{ + None = 0, + FTheta = 1, + Extended_FTheta = 2, + MAX_DISTORTION_FUNCTION_TYPES = 3, +} +public enum EVSync +{ + None = 0, + WaitRender = 1, + NoWaitRender = 2, +} +public enum EVRMuraCorrectionMode +{ + Default = 0, + NoCorrection = 1, +} +public enum Imu_OffScaleFlags +{ + OffScale_AccelX = 1, + OffScale_AccelY = 2, + OffScale_AccelZ = 4, + OffScale_GyroX = 8, + OffScale_GyroY = 16, + OffScale_GyroZ = 32, +} +public enum EVRApplicationError { None = 0, AppKeyAlreadyExists = 100, @@ -3470,12 +4570,13 @@ internal enum EVRApplicationError OldApplicationQuitting = 112, TransitionAborted = 113, IsTemplate = 114, + SteamVRIsExiting = 115, BufferTooSmall = 200, PropertyNotSet = 201, UnknownProperty = 202, InvalidParameter = 203, } -internal enum EVRApplicationProperty +public enum EVRApplicationProperty { Name_String = 0, LaunchType_String = 11, @@ -3487,19 +4588,22 @@ internal enum EVRApplicationProperty NewsURL_String = 51, ImagePath_String = 52, Source_String = 53, + ActionManifestURL_String = 54, IsDashboardOverlay_Bool = 60, IsTemplate_Bool = 61, IsInstanced_Bool = 62, + IsInternal_Bool = 63, + WantsCompositorPauseInStandby_Bool = 64, LastLaunchTime_Uint64 = 70, } -internal enum EVRApplicationTransitionState +public enum EVRApplicationTransitionState { VRApplicationTransition_None = 0, VRApplicationTransition_OldAppQuitSent = 10, VRApplicationTransition_WaitingForExternalLaunch = 11, VRApplicationTransition_NewAppLaunched = 20, } -internal enum ChaperoneCalibrationState +public enum ChaperoneCalibrationState { OK = 1, Warning = 100, @@ -3507,21 +4611,21 @@ internal enum ChaperoneCalibrationState Warning_BaseStationRemoved = 102, Warning_SeatedBoundsInvalid = 103, Error = 200, - Error_BaseStationUninitalized = 201, + Error_BaseStationUninitialized = 201, Error_BaseStationConflict = 202, Error_PlayAreaInvalid = 203, Error_CollisionBoundsInvalid = 204, } -internal enum EChaperoneConfigFile +public enum EChaperoneConfigFile { Live = 1, Temp = 2, } -internal enum EChaperoneImportFlags +public enum EChaperoneImportFlags { EChaperoneImport_BoundsOnly = 1, } -internal enum EVRCompositorError +public enum EVRCompositorError { None = 0, RequestFailed = 1, @@ -3534,20 +4638,28 @@ internal enum EVRCompositorError SharedTexturesNotSupported = 106, IndexOutOfRange = 107, AlreadySubmitted = 108, + InvalidBounds = 109, } -internal enum VROverlayInputMethod +public enum EVRCompositorTimingMode +{ + Implicit = 0, + Explicit_RuntimePerformsPostPresentHandoff = 1, + Explicit_ApplicationPerformsPostPresentHandoff = 2, +} +public enum VROverlayInputMethod { None = 0, Mouse = 1, + DualAnalog = 2, } -internal enum VROverlayTransformType +public enum VROverlayTransformType { VROverlayTransform_Absolute = 0, VROverlayTransform_TrackedDeviceRelative = 1, VROverlayTransform_SystemOverlay = 2, VROverlayTransform_TrackedComponent = 3, } -internal enum VROverlayFlags +public enum VROverlayFlags { None = 0, Curved = 1, @@ -3555,7 +4667,7 @@ internal enum VROverlayFlags NoDashboardTab = 3, AcceptsGamepadEvents = 4, ShowGamepadFocus = 5, - SendVRScrollEvents = 6, + SendVRDiscreteScrollEvents = 6, SendVRTouchpadEvents = 7, ShowTouchPadScrollWheel = 8, TransferOwnershipToInternalProcess = 9, @@ -3564,19 +4676,32 @@ internal enum VROverlayFlags Panorama = 12, StereoPanorama = 13, SortWithNonSceneOverlays = 14, + VisibleInDashboard = 15, + MakeOverlaysInteractiveIfVisible = 16, + SendVRSmoothScrollEvents = 17, +} +public enum VRMessageOverlayResponse +{ + ButtonPress_0 = 0, + ButtonPress_1 = 1, + ButtonPress_2 = 2, + ButtonPress_3 = 3, + CouldntFindSystemOverlay = 4, + CouldntFindOrCreateClientOverlay = 5, + ApplicationQuit = 6, } -internal enum EGamepadTextInputMode +public enum EGamepadTextInputMode { k_EGamepadTextInputModeNormal = 0, k_EGamepadTextInputModePassword = 1, k_EGamepadTextInputModeSubmit = 2, } -internal enum EGamepadTextInputLineMode +public enum EGamepadTextInputLineMode { k_EGamepadTextInputLineModeSingleLine = 0, k_EGamepadTextInputLineModeMultipleLines = 1, } -internal enum EOverlayDirection +public enum EOverlayDirection { Up = 0, Down = 1, @@ -3584,12 +4709,12 @@ internal enum EOverlayDirection Right = 3, Count = 4, } -internal enum EVROverlayIntersectionMaskPrimitiveType +public enum EVROverlayIntersectionMaskPrimitiveType { OverlayIntersectionPrimitiveType_Rectangle = 0, OverlayIntersectionPrimitiveType_Circle = 1, } -internal enum EVRRenderModelError +public enum EVRRenderModelError { None = 0, Loading = 100, @@ -3605,7 +4730,7 @@ internal enum EVRRenderModelError NotEnoughTexCoords = 308, InvalidTexture = 400, } -internal enum EVRComponentProperty +public enum EVRComponentProperty { IsStatic = 1, IsVisible = 2, @@ -3613,13 +4738,13 @@ internal enum EVRComponentProperty IsPressed = 8, IsScrolled = 16, } -internal enum EVRNotificationType +public enum EVRNotificationType { Transient = 0, Persistent = 1, Transient_SystemWithUserValue = 2, } -internal enum EVRNotificationStyle +public enum EVRNotificationStyle { None = 0, Application = 100, @@ -3627,7 +4752,7 @@ internal enum EVRNotificationStyle Contact_Enabled = 201, Contact_Active = 202, } -internal enum EVRSettingsError +public enum EVRSettingsError { None = 0, IPCFailed = 1, @@ -3636,7 +4761,7 @@ internal enum EVRSettingsError JsonParseFailed = 4, UnsetSettingHasNoDefault = 5, } -internal enum EVRScreenshotError +public enum EVRScreenshotError { None = 0, RequestFailed = 1, @@ -3645,645 +4770,1272 @@ internal enum EVRScreenshotError BufferTooSmall = 102, ScreenshotAlreadyInProgress = 108, } - -[StructLayout(LayoutKind.Explicit)] internal struct VREvent_Data_t +public enum EVRSkeletalTransformSpace { - [FieldOffset(0)] internal VREvent_Reserved_t reserved; - [FieldOffset(0)] internal VREvent_Controller_t controller; - [FieldOffset(0)] internal VREvent_Mouse_t mouse; - [FieldOffset(0)] internal VREvent_Scroll_t scroll; - [FieldOffset(0)] internal VREvent_Process_t process; - [FieldOffset(0)] internal VREvent_Notification_t notification; - [FieldOffset(0)] internal VREvent_Overlay_t overlay; - [FieldOffset(0)] internal VREvent_Status_t status; - [FieldOffset(0)] internal VREvent_Ipd_t ipd; - [FieldOffset(0)] internal VREvent_Chaperone_t chaperone; - [FieldOffset(0)] internal VREvent_PerformanceTest_t performanceTest; - [FieldOffset(0)] internal VREvent_TouchPadMove_t touchPadMove; - [FieldOffset(0)] internal VREvent_SeatedZeroPoseReset_t seatedZeroPoseReset; - [FieldOffset(0)] internal VREvent_Screenshot_t screenshot; - [FieldOffset(0)] internal VREvent_Keyboard_t keyboard; // This has to be at the end due to a mono bug + Model = 0, + Parent = 1, } - - -[StructLayout(LayoutKind.Explicit)] internal struct VROverlayIntersectionMaskPrimitive_Data_t +public enum EVRSkeletalReferencePose { - [FieldOffset(0)] internal IntersectionMaskRectangle_t m_Rectangle; - [FieldOffset(0)] internal IntersectionMaskCircle_t m_Circle; + BindPose = 0, + OpenHand = 1, + Fist = 2, + GripLimit = 3, } - -[StructLayout(LayoutKind.Sequential)] internal struct HmdMatrix34_t +public enum EVRFinger { - internal float m0; //float[3][4] - internal float m1; - internal float m2; - internal float m3; - internal float m4; - internal float m5; - internal float m6; - internal float m7; - internal float m8; - internal float m9; - internal float m10; - internal float m11; + Thumb = 0, + Index = 1, + Middle = 2, + Ring = 3, + Pinky = 4, + Count = 5, } -[StructLayout(LayoutKind.Sequential)] internal struct HmdMatrix44_t +public enum EVRFingerSplay { - internal float m0; //float[4][4] - internal float m1; - internal float m2; - internal float m3; - internal float m4; - internal float m5; - internal float m6; - internal float m7; - internal float m8; - internal float m9; - internal float m10; - internal float m11; - internal float m12; - internal float m13; - internal float m14; - internal float m15; + Thumb_Index = 0, + Index_Middle = 1, + Middle_Ring = 2, + Ring_Pinky = 3, + Count = 4, +} +public enum EVRInputFilterCancelType +{ + VRInputFilterCancel_Timers = 0, + VRInputFilterCancel_Momentum = 1, +} +public enum EVRInputStringBits +{ + VRInputString_Hand = 1, + VRInputString_ControllerType = 2, + VRInputString_InputSource = 4, + VRInputString_All = -1, +} +public enum EIOBufferError +{ + IOBuffer_Success = 0, + IOBuffer_OperationFailed = 100, + IOBuffer_InvalidHandle = 101, + IOBuffer_InvalidArgument = 102, + IOBuffer_PathExists = 103, + IOBuffer_PathDoesNotExist = 104, + IOBuffer_Permission = 105, +} +public enum EIOBufferMode +{ + Read = 1, + Write = 2, + Create = 512, +} + +[StructLayout(LayoutKind.Explicit)] public struct VREvent_Data_t +{ + [FieldOffset(0)] public VREvent_Reserved_t reserved; + [FieldOffset(0)] public VREvent_Controller_t controller; + [FieldOffset(0)] public VREvent_Mouse_t mouse; + [FieldOffset(0)] public VREvent_Scroll_t scroll; + [FieldOffset(0)] public VREvent_Process_t process; + [FieldOffset(0)] public VREvent_Notification_t notification; + [FieldOffset(0)] public VREvent_Overlay_t overlay; + [FieldOffset(0)] public VREvent_Status_t status; + [FieldOffset(0)] public VREvent_Ipd_t ipd; + [FieldOffset(0)] public VREvent_Chaperone_t chaperone; + [FieldOffset(0)] public VREvent_PerformanceTest_t performanceTest; + [FieldOffset(0)] public VREvent_TouchPadMove_t touchPadMove; + [FieldOffset(0)] public VREvent_SeatedZeroPoseReset_t seatedZeroPoseReset; + [FieldOffset(0)] public VREvent_Screenshot_t screenshot; + [FieldOffset(0)] public VREvent_ScreenshotProgress_t screenshotProgress; + [FieldOffset(0)] public VREvent_ApplicationLaunch_t applicationLaunch; + [FieldOffset(0)] public VREvent_EditingCameraSurface_t cameraSurface; + [FieldOffset(0)] public VREvent_MessageOverlay_t messageOverlay; + [FieldOffset(0)] public VREvent_Property_t property; + [FieldOffset(0)] public VREvent_DualAnalog_t dualAnalog; + [FieldOffset(0)] public VREvent_HapticVibration_t hapticVibration; + [FieldOffset(0)] public VREvent_WebConsole_t webConsole; + [FieldOffset(0)] public VREvent_InputBindingLoad_t inputBinding; + [FieldOffset(0)] public VREvent_SpatialAnchor_t spatialAnchor; + [FieldOffset(0)] public VREvent_InputActionManifestLoad_t actionManifest; + [FieldOffset(0)] public VREvent_ProgressUpdate_t progressUpdate; + [FieldOffset(0)] public VREvent_ShowUI_t showUi; + [FieldOffset(0)] public VREvent_Keyboard_t keyboard; // This has to be at the end due to a mono bug +} + + +[StructLayout(LayoutKind.Explicit)] public struct VROverlayIntersectionMaskPrimitive_Data_t +{ + [FieldOffset(0)] public IntersectionMaskRectangle_t m_Rectangle; + [FieldOffset(0)] public IntersectionMaskCircle_t m_Circle; +} + +[StructLayout(LayoutKind.Sequential)] public struct HmdMatrix34_t +{ + public float m0; //float[3][4] + public float m1; + public float m2; + public float m3; + public float m4; + public float m5; + public float m6; + public float m7; + public float m8; + public float m9; + public float m10; + public float m11; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdMatrix33_t +{ + public float m0; //float[3][3] + public float m1; + public float m2; + public float m3; + public float m4; + public float m5; + public float m6; + public float m7; + public float m8; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdMatrix44_t +{ + public float m0; //float[4][4] + public float m1; + public float m2; + public float m3; + public float m4; + public float m5; + public float m6; + public float m7; + public float m8; + public float m9; + public float m10; + public float m11; + public float m12; + public float m13; + public float m14; + public float m15; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdVector3_t +{ + public float v0; //float[3] + public float v1; + public float v2; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdVector4_t +{ + public float v0; //float[4] + public float v1; + public float v2; + public float v3; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdVector3d_t +{ + public double v0; //double[3] + public double v1; + public double v2; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdVector2_t +{ + public float v0; //float[2] + public float v1; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdQuaternion_t +{ + public double w; + public double x; + public double y; + public double z; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdQuaternionf_t +{ + public float w; + public float x; + public float y; + public float z; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdColor_t +{ + public float r; + public float g; + public float b; + public float a; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdVector3_t +[StructLayout(LayoutKind.Sequential)] public struct HmdQuad_t { - internal float v0; //float[3] - internal float v1; - internal float v2; + public HmdVector3_t vCorners0; //HmdVector3_t[4] + public HmdVector3_t vCorners1; + public HmdVector3_t vCorners2; + public HmdVector3_t vCorners3; +} +[StructLayout(LayoutKind.Sequential)] public struct HmdRect2_t +{ + public HmdVector2_t vTopLeft; + public HmdVector2_t vBottomRight; +} +[StructLayout(LayoutKind.Sequential)] public struct DistortionCoordinates_t +{ + public float rfRed0; //float[2] + public float rfRed1; + public float rfGreen0; //float[2] + public float rfGreen1; + public float rfBlue0; //float[2] + public float rfBlue1; +} +[StructLayout(LayoutKind.Sequential)] public struct Texture_t +{ + public IntPtr handle; // void * + public ETextureType eType; + public EColorSpace eColorSpace; +} +[StructLayout(LayoutKind.Sequential)] public struct TrackedDevicePose_t +{ + public HmdMatrix34_t mDeviceToAbsoluteTracking; + public HmdVector3_t vVelocity; + public HmdVector3_t vAngularVelocity; + public ETrackingResult eTrackingResult; + [MarshalAs(UnmanagedType.I1)] + public bool bPoseIsValid; + [MarshalAs(UnmanagedType.I1)] + public bool bDeviceIsConnected; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdVector4_t +[StructLayout(LayoutKind.Sequential)] public struct VRTextureBounds_t { - internal float v0; //float[4] - internal float v1; - internal float v2; - internal float v3; + public float uMin; + public float vMin; + public float uMax; + public float vMax; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdVector3d_t +[StructLayout(LayoutKind.Sequential)] public struct VRTextureWithPose_t { - internal double v0; //double[3] - internal double v1; - internal double v2; + public HmdMatrix34_t mDeviceToAbsoluteTracking; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdVector2_t +[StructLayout(LayoutKind.Sequential)] public struct VRTextureDepthInfo_t { - internal float v0; //float[2] - internal float v1; + public IntPtr handle; // void * + public HmdMatrix44_t mProjection; + public HmdVector2_t vRange; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdQuaternion_t +[StructLayout(LayoutKind.Sequential)] public struct VRTextureWithDepth_t { - internal double w; - internal double x; - internal double y; - internal double z; + public VRTextureDepthInfo_t depth; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdColor_t +[StructLayout(LayoutKind.Sequential)] public struct VRTextureWithPoseAndDepth_t { - internal float r; - internal float g; - internal float b; - internal float a; + public VRTextureDepthInfo_t depth; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdQuad_t +[StructLayout(LayoutKind.Sequential)] public struct VRVulkanTextureData_t { - internal HmdVector3_t vCorners0; //HmdVector3_t[4] - internal HmdVector3_t vCorners1; - internal HmdVector3_t vCorners2; - internal HmdVector3_t vCorners3; + public ulong m_nImage; + public IntPtr m_pDevice; // struct VkDevice_T * + public IntPtr m_pPhysicalDevice; // struct VkPhysicalDevice_T * + public IntPtr m_pInstance; // struct VkInstance_T * + public IntPtr m_pQueue; // struct VkQueue_T * + public uint m_nQueueFamilyIndex; + public uint m_nWidth; + public uint m_nHeight; + public uint m_nFormat; + public uint m_nSampleCount; } -[StructLayout(LayoutKind.Sequential)] internal struct HmdRect2_t +[StructLayout(LayoutKind.Sequential)] public struct D3D12TextureData_t { - internal HmdVector2_t vTopLeft; - internal HmdVector2_t vBottomRight; + public IntPtr m_pResource; // struct ID3D12Resource * + public IntPtr m_pCommandQueue; // struct ID3D12CommandQueue * + public uint m_nNodeMask; } -[StructLayout(LayoutKind.Sequential)] internal struct DistortionCoordinates_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Controller_t { - internal float rfRed0; //float[2] - internal float rfRed1; - internal float rfGreen0; //float[2] - internal float rfGreen1; - internal float rfBlue0; //float[2] - internal float rfBlue1; + public uint button; } -[StructLayout(LayoutKind.Sequential)] internal struct Texture_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Mouse_t { - internal IntPtr handle; // void * - internal EGraphicsAPIConvention eType; - internal EColorSpace eColorSpace; + public float x; + public float y; + public uint button; } -[StructLayout(LayoutKind.Sequential)] internal struct TrackedDevicePose_t -{ - internal HmdMatrix34_t mDeviceToAbsoluteTracking; - internal HmdVector3_t vVelocity; - internal HmdVector3_t vAngularVelocity; - internal ETrackingResult eTrackingResult; +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Scroll_t +{ + public float xdelta; + public float ydelta; + public uint repeatCount; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_TouchPadMove_t +{ [MarshalAs(UnmanagedType.I1)] - internal bool bPoseIsValid; + public bool bFingerDown; + public float flSecondsFingerDown; + public float fValueXFirst; + public float fValueYFirst; + public float fValueXRaw; + public float fValueYRaw; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Notification_t +{ + public ulong ulUserValue; + public uint notificationId; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Process_t +{ + public uint pid; + public uint oldPid; + [MarshalAs(UnmanagedType.I1)] + public bool bForced; [MarshalAs(UnmanagedType.I1)] - internal bool bDeviceIsConnected; + public bool bConnectionLost; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Overlay_t +{ + public ulong overlayHandle; + public ulong devicePath; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Status_t +{ + public uint statusState; } -[StructLayout(LayoutKind.Sequential)] internal struct VRTextureBounds_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Keyboard_t { - internal float uMin; - internal float vMin; - internal float uMax; - internal float vMax; + public byte cNewInput0,cNewInput1,cNewInput2,cNewInput3,cNewInput4,cNewInput5,cNewInput6,cNewInput7; + public string cNewInput + { + get + { + return new string(new char[] { + (char)cNewInput0, + (char)cNewInput1, + (char)cNewInput2, + (char)cNewInput3, + (char)cNewInput4, + (char)cNewInput5, + (char)cNewInput6, + (char)cNewInput7 + }).TrimEnd('\0'); + } + } + public ulong uUserValue; } -[StructLayout(LayoutKind.Sequential)] internal struct VulkanData_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Ipd_t { - internal ulong m_nImage; - internal IntPtr m_pDevice; // struct VkDevice_T * - internal IntPtr m_pPhysicalDevice; // struct VkPhysicalDevice_T * - internal IntPtr m_pInstance; // struct VkInstance_T * - internal IntPtr m_pQueue; // struct VkQueue_T * - internal uint m_nQueueFamilyIndex; - internal uint m_nWidth; - internal uint m_nHeight; - internal uint m_nFormat; - internal uint m_nSampleCount; + public float ipdMeters; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Controller_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Chaperone_t { - internal uint button; + public ulong m_nPreviousUniverse; + public ulong m_nCurrentUniverse; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Mouse_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Reserved_t { - internal float x; - internal float y; - internal uint button; + public ulong reserved0; + public ulong reserved1; + public ulong reserved2; + public ulong reserved3; + public ulong reserved4; + public ulong reserved5; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Scroll_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_PerformanceTest_t { - internal float xdelta; - internal float ydelta; - internal uint repeatCount; + public uint m_nFidelityLevel; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_TouchPadMove_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_SeatedZeroPoseReset_t { [MarshalAs(UnmanagedType.I1)] - internal bool bFingerDown; - internal float flSecondsFingerDown; - internal float fValueXFirst; - internal float fValueYFirst; - internal float fValueXRaw; - internal float fValueYRaw; + public bool bResetBySystemMenu; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Notification_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Screenshot_t { - internal ulong ulUserValue; - internal uint notificationId; + public uint handle; + public uint type; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Process_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_ScreenshotProgress_t { - internal uint pid; - internal uint oldPid; - [MarshalAs(UnmanagedType.I1)] - internal bool bForced; + public float progress; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Overlay_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_ApplicationLaunch_t { - internal ulong overlayHandle; + public uint pid; + public uint unArgsHandle; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Status_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_EditingCameraSurface_t { - internal uint statusState; + public ulong overlayHandle; + public uint nVisualMode; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Keyboard_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_MessageOverlay_t { - internal byte cNewInput0,cNewInput1,cNewInput2,cNewInput3,cNewInput4,cNewInput5,cNewInput6,cNewInput7; - internal ulong uUserValue; + public uint unVRMessageOverlayResponse; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Ipd_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_Property_t { - internal float ipdMeters; + public ulong container; + public ETrackedDeviceProperty prop; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Chaperone_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_DualAnalog_t { - internal ulong m_nPreviousUniverse; - internal ulong m_nCurrentUniverse; + public float x; + public float y; + public float transformedX; + public float transformedY; + public EDualAnalogWhich which; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Reserved_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_HapticVibration_t { - internal ulong reserved0; - internal ulong reserved1; + public ulong containerHandle; + public ulong componentHandle; + public float fDurationSeconds; + public float fFrequency; + public float fAmplitude; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_PerformanceTest_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_WebConsole_t { - internal uint m_nFidelityLevel; + public ulong webConsoleHandle; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_SeatedZeroPoseReset_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_InputBindingLoad_t { - [MarshalAs(UnmanagedType.I1)] - internal bool bResetBySystemMenu; + public ulong ulAppContainer; + public ulong pathMessage; + public ulong pathUrl; + public ulong pathControllerType; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_InputActionManifestLoad_t +{ + public ulong pathAppKey; + public ulong pathMessage; + public ulong pathMessageParam; + public ulong pathManifestPath; +} +[StructLayout(LayoutKind.Sequential)] public struct VREvent_SpatialAnchor_t +{ + public uint unHandle; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_Screenshot_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_ProgressUpdate_t { - internal uint handle; - internal uint type; + public ulong ulApplicationPropertyContainer; + public ulong pathDevice; + public ulong pathInputSource; + public ulong pathProgressAction; + public ulong pathIcon; + public float fProgress; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_ScreenshotProgress_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_ShowUI_t { - internal float progress; + public EShowUIType eType; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_ApplicationLaunch_t +[StructLayout(LayoutKind.Sequential)] public struct VREvent_t { - internal uint pid; - internal uint unArgsHandle; + public uint eventType; + public uint trackedDeviceIndex; + public float eventAgeSeconds; + public VREvent_Data_t data; } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_EditingCameraSurface_t +// This structure is for backwards binary compatibility on Linux and OSX only +[StructLayout(LayoutKind.Sequential, Pack = 4)] public struct VREvent_t_Packed { - internal ulong overlayHandle; - internal uint nVisualMode; + public uint eventType; + public uint trackedDeviceIndex; + public float eventAgeSeconds; + public VREvent_Data_t data; + public VREvent_t_Packed(VREvent_t unpacked) + { + this.eventType = unpacked.eventType; + this.trackedDeviceIndex = unpacked.trackedDeviceIndex; + this.eventAgeSeconds = unpacked.eventAgeSeconds; + this.data = unpacked.data; + } + public void Unpack(ref VREvent_t unpacked) + { + unpacked.eventType = this.eventType; + unpacked.trackedDeviceIndex = this.trackedDeviceIndex; + unpacked.eventAgeSeconds = this.eventAgeSeconds; + unpacked.data = this.data; + } } -[StructLayout(LayoutKind.Sequential)] internal struct VREvent_t +[StructLayout(LayoutKind.Sequential)] public struct HiddenAreaMesh_t { - internal uint eventType; - internal uint trackedDeviceIndex; - internal float eventAgeSeconds; - internal VREvent_Data_t data; + public IntPtr pVertexData; // const struct vr::HmdVector2_t * + public uint unTriangleCount; } -[StructLayout(LayoutKind.Sequential)] internal struct HiddenAreaMesh_t +[StructLayout(LayoutKind.Sequential)] public struct VRControllerAxis_t { - internal IntPtr pVertexData; // const struct vr::HmdVector2_t * - internal uint unTriangleCount; + public float x; + public float y; } -[StructLayout(LayoutKind.Sequential)] internal struct VRControllerAxis_t +[StructLayout(LayoutKind.Sequential)] public struct VRControllerState_t { - internal float x; - internal float y; + public uint unPacketNum; + public ulong ulButtonPressed; + public ulong ulButtonTouched; + public VRControllerAxis_t rAxis0; //VRControllerAxis_t[5] + public VRControllerAxis_t rAxis1; + public VRControllerAxis_t rAxis2; + public VRControllerAxis_t rAxis3; + public VRControllerAxis_t rAxis4; } -[StructLayout(LayoutKind.Sequential)] internal struct VRControllerState_t +// This structure is for backwards binary compatibility on Linux and OSX only +[StructLayout(LayoutKind.Sequential, Pack = 4)] public struct VRControllerState_t_Packed { - internal uint unPacketNum; - internal ulong ulButtonPressed; - internal ulong ulButtonTouched; - internal VRControllerAxis_t rAxis0; //VRControllerAxis_t[5] - internal VRControllerAxis_t rAxis1; - internal VRControllerAxis_t rAxis2; - internal VRControllerAxis_t rAxis3; - internal VRControllerAxis_t rAxis4; + public uint unPacketNum; + public ulong ulButtonPressed; + public ulong ulButtonTouched; + public VRControllerAxis_t rAxis0; //VRControllerAxis_t[5] + public VRControllerAxis_t rAxis1; + public VRControllerAxis_t rAxis2; + public VRControllerAxis_t rAxis3; + public VRControllerAxis_t rAxis4; + public VRControllerState_t_Packed(VRControllerState_t unpacked) + { + this.unPacketNum = unpacked.unPacketNum; + this.ulButtonPressed = unpacked.ulButtonPressed; + this.ulButtonTouched = unpacked.ulButtonTouched; + this.rAxis0 = unpacked.rAxis0; + this.rAxis1 = unpacked.rAxis1; + this.rAxis2 = unpacked.rAxis2; + this.rAxis3 = unpacked.rAxis3; + this.rAxis4 = unpacked.rAxis4; + } + public void Unpack(ref VRControllerState_t unpacked) + { + unpacked.unPacketNum = this.unPacketNum; + unpacked.ulButtonPressed = this.ulButtonPressed; + unpacked.ulButtonTouched = this.ulButtonTouched; + unpacked.rAxis0 = this.rAxis0; + unpacked.rAxis1 = this.rAxis1; + unpacked.rAxis2 = this.rAxis2; + unpacked.rAxis3 = this.rAxis3; + unpacked.rAxis4 = this.rAxis4; + } } -[StructLayout(LayoutKind.Sequential)] internal struct Compositor_OverlaySettings +[StructLayout(LayoutKind.Sequential)] public struct Compositor_OverlaySettings { - internal uint size; + public uint size; [MarshalAs(UnmanagedType.I1)] - internal bool curved; + public bool curved; [MarshalAs(UnmanagedType.I1)] - internal bool antialias; - internal float scale; - internal float distance; - internal float alpha; - internal float uOffset; - internal float vOffset; - internal float uScale; - internal float vScale; - internal float gridDivs; - internal float gridWidth; - internal float gridScale; - internal HmdMatrix44_t transform; -} -[StructLayout(LayoutKind.Sequential)] internal struct CameraVideoStreamFrameHeader_t -{ - internal EVRTrackedCameraFrameType eFrameType; - internal uint nWidth; - internal uint nHeight; - internal uint nBytesPerPixel; - internal uint nFrameSequence; - internal TrackedDevicePose_t standingTrackedDevicePose; -} -[StructLayout(LayoutKind.Sequential)] internal struct AppOverrideKeys_t -{ - internal IntPtr pchKey; // const char * - internal IntPtr pchValue; // const char * -} -[StructLayout(LayoutKind.Sequential)] internal struct Compositor_FrameTiming -{ - internal uint m_nSize; - internal uint m_nFrameIndex; - internal uint m_nNumFramePresents; - internal uint m_nNumMisPresented; - internal uint m_nNumDroppedFrames; - internal uint m_nReprojectionFlags; - internal double m_flSystemTimeInSeconds; - internal float m_flPreSubmitGpuMs; - internal float m_flPostSubmitGpuMs; - internal float m_flTotalRenderGpuMs; - internal float m_flCompositorRenderGpuMs; - internal float m_flCompositorRenderCpuMs; - internal float m_flCompositorIdleCpuMs; - internal float m_flClientFrameIntervalMs; - internal float m_flPresentCallCpuMs; - internal float m_flWaitForPresentCpuMs; - internal float m_flSubmitFrameMs; - internal float m_flWaitGetPosesCalledMs; - internal float m_flNewPosesReadyMs; - internal float m_flNewFrameReadyMs; - internal float m_flCompositorUpdateStartMs; - internal float m_flCompositorUpdateEndMs; - internal float m_flCompositorRenderStartMs; - internal TrackedDevicePose_t m_HmdPose; -} -[StructLayout(LayoutKind.Sequential)] internal struct Compositor_CumulativeStats -{ - internal uint m_nPid; - internal uint m_nNumFramePresents; - internal uint m_nNumDroppedFrames; - internal uint m_nNumReprojectedFrames; - internal uint m_nNumFramePresentsOnStartup; - internal uint m_nNumDroppedFramesOnStartup; - internal uint m_nNumReprojectedFramesOnStartup; - internal uint m_nNumLoading; - internal uint m_nNumFramePresentsLoading; - internal uint m_nNumDroppedFramesLoading; - internal uint m_nNumReprojectedFramesLoading; - internal uint m_nNumTimedOut; - internal uint m_nNumFramePresentsTimedOut; - internal uint m_nNumDroppedFramesTimedOut; - internal uint m_nNumReprojectedFramesTimedOut; -} -[StructLayout(LayoutKind.Sequential)] internal struct VROverlayIntersectionParams_t -{ - internal HmdVector3_t vSource; - internal HmdVector3_t vDirection; - internal ETrackingUniverseOrigin eOrigin; -} -[StructLayout(LayoutKind.Sequential)] internal struct VROverlayIntersectionResults_t -{ - internal HmdVector3_t vPoint; - internal HmdVector3_t vNormal; - internal HmdVector2_t vUVs; - internal float fDistance; -} -[StructLayout(LayoutKind.Sequential)] internal struct IntersectionMaskRectangle_t -{ - internal float m_flTopLeftX; - internal float m_flTopLeftY; - internal float m_flWidth; - internal float m_flHeight; -} -[StructLayout(LayoutKind.Sequential)] internal struct IntersectionMaskCircle_t -{ - internal float m_flCenterX; - internal float m_flCenterY; - internal float m_flRadius; -} -[StructLayout(LayoutKind.Sequential)] internal struct VROverlayIntersectionMaskPrimitive_t -{ - internal EVROverlayIntersectionMaskPrimitiveType m_nPrimitiveType; - internal VROverlayIntersectionMaskPrimitive_Data_t m_Primitive; -} -[StructLayout(LayoutKind.Sequential)] internal struct RenderModel_ComponentState_t -{ - internal HmdMatrix34_t mTrackingToComponentRenderModel; - internal HmdMatrix34_t mTrackingToComponentLocal; - internal uint uProperties; -} -[StructLayout(LayoutKind.Sequential)] internal struct RenderModel_Vertex_t -{ - internal HmdVector3_t vPosition; - internal HmdVector3_t vNormal; - internal float rfTextureCoord0; //float[2] - internal float rfTextureCoord1; -} -[StructLayout(LayoutKind.Sequential)] internal struct RenderModel_TextureMap_t -{ - internal char unWidth; - internal char unHeight; - internal IntPtr rubTextureMapData; // const uint8_t * -} -[StructLayout(LayoutKind.Sequential)] internal struct RenderModel_t -{ - internal IntPtr rVertexData; // const struct vr::RenderModel_Vertex_t * - internal uint unVertexCount; - internal IntPtr rIndexData; // const uint16_t * - internal uint unTriangleCount; - internal int diffuseTextureId; -} -[StructLayout(LayoutKind.Sequential)] internal struct RenderModel_ControllerMode_State_t + public bool antialias; + public float scale; + public float distance; + public float alpha; + public float uOffset; + public float vOffset; + public float uScale; + public float vScale; + public float gridDivs; + public float gridWidth; + public float gridScale; + public HmdMatrix44_t transform; +} +[StructLayout(LayoutKind.Sequential)] public struct VRBoneTransform_t +{ + public HmdVector4_t position; + public HmdQuaternionf_t orientation; +} +[StructLayout(LayoutKind.Sequential)] public struct CameraVideoStreamFrameHeader_t +{ + public EVRTrackedCameraFrameType eFrameType; + public uint nWidth; + public uint nHeight; + public uint nBytesPerPixel; + public uint nFrameSequence; + public TrackedDevicePose_t standingTrackedDevicePose; + public ulong ulFrameExposureTime; +} +[StructLayout(LayoutKind.Sequential)] public struct DriverDirectMode_FrameTiming +{ + public uint m_nSize; + public uint m_nNumFramePresents; + public uint m_nNumMisPresented; + public uint m_nNumDroppedFrames; + public uint m_nReprojectionFlags; +} +[StructLayout(LayoutKind.Sequential)] public struct ImuSample_t +{ + public double fSampleTime; + public HmdVector3d_t vAccel; + public HmdVector3d_t vGyro; + public uint unOffScaleFlags; +} +[StructLayout(LayoutKind.Sequential)] public struct AppOverrideKeys_t +{ + public IntPtr pchKey; // const char * + public IntPtr pchValue; // const char * +} +[StructLayout(LayoutKind.Sequential)] public struct Compositor_FrameTiming +{ + public uint m_nSize; + public uint m_nFrameIndex; + public uint m_nNumFramePresents; + public uint m_nNumMisPresented; + public uint m_nNumDroppedFrames; + public uint m_nReprojectionFlags; + public double m_flSystemTimeInSeconds; + public float m_flPreSubmitGpuMs; + public float m_flPostSubmitGpuMs; + public float m_flTotalRenderGpuMs; + public float m_flCompositorRenderGpuMs; + public float m_flCompositorRenderCpuMs; + public float m_flCompositorIdleCpuMs; + public float m_flClientFrameIntervalMs; + public float m_flPresentCallCpuMs; + public float m_flWaitForPresentCpuMs; + public float m_flSubmitFrameMs; + public float m_flWaitGetPosesCalledMs; + public float m_flNewPosesReadyMs; + public float m_flNewFrameReadyMs; + public float m_flCompositorUpdateStartMs; + public float m_flCompositorUpdateEndMs; + public float m_flCompositorRenderStartMs; + public TrackedDevicePose_t m_HmdPose; + public uint m_nNumVSyncsReadyForUse; + public uint m_nNumVSyncsToFirstView; +} +[StructLayout(LayoutKind.Sequential)] public struct Compositor_CumulativeStats +{ + public uint m_nPid; + public uint m_nNumFramePresents; + public uint m_nNumDroppedFrames; + public uint m_nNumReprojectedFrames; + public uint m_nNumFramePresentsOnStartup; + public uint m_nNumDroppedFramesOnStartup; + public uint m_nNumReprojectedFramesOnStartup; + public uint m_nNumLoading; + public uint m_nNumFramePresentsLoading; + public uint m_nNumDroppedFramesLoading; + public uint m_nNumReprojectedFramesLoading; + public uint m_nNumTimedOut; + public uint m_nNumFramePresentsTimedOut; + public uint m_nNumDroppedFramesTimedOut; + public uint m_nNumReprojectedFramesTimedOut; +} +[StructLayout(LayoutKind.Sequential)] public struct VROverlayIntersectionParams_t +{ + public HmdVector3_t vSource; + public HmdVector3_t vDirection; + public ETrackingUniverseOrigin eOrigin; +} +[StructLayout(LayoutKind.Sequential)] public struct VROverlayIntersectionResults_t +{ + public HmdVector3_t vPoint; + public HmdVector3_t vNormal; + public HmdVector2_t vUVs; + public float fDistance; +} +[StructLayout(LayoutKind.Sequential)] public struct IntersectionMaskRectangle_t +{ + public float m_flTopLeftX; + public float m_flTopLeftY; + public float m_flWidth; + public float m_flHeight; +} +[StructLayout(LayoutKind.Sequential)] public struct IntersectionMaskCircle_t +{ + public float m_flCenterX; + public float m_flCenterY; + public float m_flRadius; +} +[StructLayout(LayoutKind.Sequential)] public struct VROverlayIntersectionMaskPrimitive_t +{ + public EVROverlayIntersectionMaskPrimitiveType m_nPrimitiveType; + public VROverlayIntersectionMaskPrimitive_Data_t m_Primitive; +} +[StructLayout(LayoutKind.Sequential)] public struct RenderModel_ComponentState_t +{ + public HmdMatrix34_t mTrackingToComponentRenderModel; + public HmdMatrix34_t mTrackingToComponentLocal; + public uint uProperties; +} +[StructLayout(LayoutKind.Sequential)] public struct RenderModel_Vertex_t +{ + public HmdVector3_t vPosition; + public HmdVector3_t vNormal; + public float rfTextureCoord0; //float[2] + public float rfTextureCoord1; +} +[StructLayout(LayoutKind.Sequential)] public struct RenderModel_TextureMap_t +{ + public ushort unWidth; + public ushort unHeight; + public IntPtr rubTextureMapData; // const uint8_t * +} +// This structure is for backwards binary compatibility on Linux and OSX only +[StructLayout(LayoutKind.Sequential, Pack = 4)] public struct RenderModel_TextureMap_t_Packed +{ + public ushort unWidth; + public ushort unHeight; + public IntPtr rubTextureMapData; // const uint8_t * + public RenderModel_TextureMap_t_Packed(RenderModel_TextureMap_t unpacked) + { + this.unWidth = unpacked.unWidth; + this.unHeight = unpacked.unHeight; + this.rubTextureMapData = unpacked.rubTextureMapData; + } + public void Unpack(ref RenderModel_TextureMap_t unpacked) + { + unpacked.unWidth = this.unWidth; + unpacked.unHeight = this.unHeight; + unpacked.rubTextureMapData = this.rubTextureMapData; + } +} +[StructLayout(LayoutKind.Sequential)] public struct RenderModel_t +{ + public IntPtr rVertexData; // const struct vr::RenderModel_Vertex_t * + public uint unVertexCount; + public IntPtr rIndexData; // const uint16_t * + public uint unTriangleCount; + public int diffuseTextureId; +} +// This structure is for backwards binary compatibility on Linux and OSX only +[StructLayout(LayoutKind.Sequential, Pack = 4)] public struct RenderModel_t_Packed +{ + public IntPtr rVertexData; // const struct vr::RenderModel_Vertex_t * + public uint unVertexCount; + public IntPtr rIndexData; // const uint16_t * + public uint unTriangleCount; + public int diffuseTextureId; + public RenderModel_t_Packed(RenderModel_t unpacked) + { + this.rVertexData = unpacked.rVertexData; + this.unVertexCount = unpacked.unVertexCount; + this.rIndexData = unpacked.rIndexData; + this.unTriangleCount = unpacked.unTriangleCount; + this.diffuseTextureId = unpacked.diffuseTextureId; + } + public void Unpack(ref RenderModel_t unpacked) + { + unpacked.rVertexData = this.rVertexData; + unpacked.unVertexCount = this.unVertexCount; + unpacked.rIndexData = this.rIndexData; + unpacked.unTriangleCount = this.unTriangleCount; + unpacked.diffuseTextureId = this.diffuseTextureId; + } +} +[StructLayout(LayoutKind.Sequential)] public struct RenderModel_ControllerMode_State_t { [MarshalAs(UnmanagedType.I1)] - internal bool bScrollWheelVisible; + public bool bScrollWheelVisible; +} +[StructLayout(LayoutKind.Sequential)] public struct NotificationBitmap_t +{ + public IntPtr m_pImageData; // void * + public int m_nWidth; + public int m_nHeight; + public int m_nBytesPerPixel; +} +[StructLayout(LayoutKind.Sequential)] public struct CVRSettingHelper +{ + public IntPtr m_pSettings; // class vr::IVRSettings * +} +[StructLayout(LayoutKind.Sequential)] public struct InputAnalogActionData_t +{ + [MarshalAs(UnmanagedType.I1)] + public bool bActive; + public ulong activeOrigin; + public float x; + public float y; + public float z; + public float deltaX; + public float deltaY; + public float deltaZ; + public float fUpdateTime; +} +[StructLayout(LayoutKind.Sequential)] public struct InputDigitalActionData_t +{ + [MarshalAs(UnmanagedType.I1)] + public bool bActive; + public ulong activeOrigin; + [MarshalAs(UnmanagedType.I1)] + public bool bState; + [MarshalAs(UnmanagedType.I1)] + public bool bChanged; + public float fUpdateTime; +} +[StructLayout(LayoutKind.Sequential)] public struct InputPoseActionData_t +{ + [MarshalAs(UnmanagedType.I1)] + public bool bActive; + public ulong activeOrigin; + public TrackedDevicePose_t pose; +} +[StructLayout(LayoutKind.Sequential)] public struct InputSkeletalActionData_t +{ + [MarshalAs(UnmanagedType.I1)] + public bool bActive; + public ulong activeOrigin; +} +[StructLayout(LayoutKind.Sequential)] public struct InputOriginInfo_t +{ + public ulong devicePath; + public uint trackedDeviceIndex; + public byte rchRenderModelComponentName0,rchRenderModelComponentName1,rchRenderModelComponentName2,rchRenderModelComponentName3,rchRenderModelComponentName4,rchRenderModelComponentName5,rchRenderModelComponentName6,rchRenderModelComponentName7,rchRenderModelComponentName8,rchRenderModelComponentName9,rchRenderModelComponentName10,rchRenderModelComponentName11,rchRenderModelComponentName12,rchRenderModelComponentName13,rchRenderModelComponentName14,rchRenderModelComponentName15,rchRenderModelComponentName16,rchRenderModelComponentName17,rchRenderModelComponentName18,rchRenderModelComponentName19,rchRenderModelComponentName20,rchRenderModelComponentName21,rchRenderModelComponentName22,rchRenderModelComponentName23,rchRenderModelComponentName24,rchRenderModelComponentName25,rchRenderModelComponentName26,rchRenderModelComponentName27,rchRenderModelComponentName28,rchRenderModelComponentName29,rchRenderModelComponentName30,rchRenderModelComponentName31,rchRenderModelComponentName32,rchRenderModelComponentName33,rchRenderModelComponentName34,rchRenderModelComponentName35,rchRenderModelComponentName36,rchRenderModelComponentName37,rchRenderModelComponentName38,rchRenderModelComponentName39,rchRenderModelComponentName40,rchRenderModelComponentName41,rchRenderModelComponentName42,rchRenderModelComponentName43,rchRenderModelComponentName44,rchRenderModelComponentName45,rchRenderModelComponentName46,rchRenderModelComponentName47,rchRenderModelComponentName48,rchRenderModelComponentName49,rchRenderModelComponentName50,rchRenderModelComponentName51,rchRenderModelComponentName52,rchRenderModelComponentName53,rchRenderModelComponentName54,rchRenderModelComponentName55,rchRenderModelComponentName56,rchRenderModelComponentName57,rchRenderModelComponentName58,rchRenderModelComponentName59,rchRenderModelComponentName60,rchRenderModelComponentName61,rchRenderModelComponentName62,rchRenderModelComponentName63,rchRenderModelComponentName64,rchRenderModelComponentName65,rchRenderModelComponentName66,rchRenderModelComponentName67,rchRenderModelComponentName68,rchRenderModelComponentName69,rchRenderModelComponentName70,rchRenderModelComponentName71,rchRenderModelComponentName72,rchRenderModelComponentName73,rchRenderModelComponentName74,rchRenderModelComponentName75,rchRenderModelComponentName76,rchRenderModelComponentName77,rchRenderModelComponentName78,rchRenderModelComponentName79,rchRenderModelComponentName80,rchRenderModelComponentName81,rchRenderModelComponentName82,rchRenderModelComponentName83,rchRenderModelComponentName84,rchRenderModelComponentName85,rchRenderModelComponentName86,rchRenderModelComponentName87,rchRenderModelComponentName88,rchRenderModelComponentName89,rchRenderModelComponentName90,rchRenderModelComponentName91,rchRenderModelComponentName92,rchRenderModelComponentName93,rchRenderModelComponentName94,rchRenderModelComponentName95,rchRenderModelComponentName96,rchRenderModelComponentName97,rchRenderModelComponentName98,rchRenderModelComponentName99,rchRenderModelComponentName100,rchRenderModelComponentName101,rchRenderModelComponentName102,rchRenderModelComponentName103,rchRenderModelComponentName104,rchRenderModelComponentName105,rchRenderModelComponentName106,rchRenderModelComponentName107,rchRenderModelComponentName108,rchRenderModelComponentName109,rchRenderModelComponentName110,rchRenderModelComponentName111,rchRenderModelComponentName112,rchRenderModelComponentName113,rchRenderModelComponentName114,rchRenderModelComponentName115,rchRenderModelComponentName116,rchRenderModelComponentName117,rchRenderModelComponentName118,rchRenderModelComponentName119,rchRenderModelComponentName120,rchRenderModelComponentName121,rchRenderModelComponentName122,rchRenderModelComponentName123,rchRenderModelComponentName124,rchRenderModelComponentName125,rchRenderModelComponentName126,rchRenderModelComponentName127; + public string rchRenderModelComponentName + { + get + { + return new string(new char[] { + (char)rchRenderModelComponentName0, + (char)rchRenderModelComponentName1, + (char)rchRenderModelComponentName2, + (char)rchRenderModelComponentName3, + (char)rchRenderModelComponentName4, + (char)rchRenderModelComponentName5, + (char)rchRenderModelComponentName6, + (char)rchRenderModelComponentName7, + (char)rchRenderModelComponentName8, + (char)rchRenderModelComponentName9, + (char)rchRenderModelComponentName10, + (char)rchRenderModelComponentName11, + (char)rchRenderModelComponentName12, + (char)rchRenderModelComponentName13, + (char)rchRenderModelComponentName14, + (char)rchRenderModelComponentName15, + (char)rchRenderModelComponentName16, + (char)rchRenderModelComponentName17, + (char)rchRenderModelComponentName18, + (char)rchRenderModelComponentName19, + (char)rchRenderModelComponentName20, + (char)rchRenderModelComponentName21, + (char)rchRenderModelComponentName22, + (char)rchRenderModelComponentName23, + (char)rchRenderModelComponentName24, + (char)rchRenderModelComponentName25, + (char)rchRenderModelComponentName26, + (char)rchRenderModelComponentName27, + (char)rchRenderModelComponentName28, + (char)rchRenderModelComponentName29, + (char)rchRenderModelComponentName30, + (char)rchRenderModelComponentName31, + (char)rchRenderModelComponentName32, + (char)rchRenderModelComponentName33, + (char)rchRenderModelComponentName34, + (char)rchRenderModelComponentName35, + (char)rchRenderModelComponentName36, + (char)rchRenderModelComponentName37, + (char)rchRenderModelComponentName38, + (char)rchRenderModelComponentName39, + (char)rchRenderModelComponentName40, + (char)rchRenderModelComponentName41, + (char)rchRenderModelComponentName42, + (char)rchRenderModelComponentName43, + (char)rchRenderModelComponentName44, + (char)rchRenderModelComponentName45, + (char)rchRenderModelComponentName46, + (char)rchRenderModelComponentName47, + (char)rchRenderModelComponentName48, + (char)rchRenderModelComponentName49, + (char)rchRenderModelComponentName50, + (char)rchRenderModelComponentName51, + (char)rchRenderModelComponentName52, + (char)rchRenderModelComponentName53, + (char)rchRenderModelComponentName54, + (char)rchRenderModelComponentName55, + (char)rchRenderModelComponentName56, + (char)rchRenderModelComponentName57, + (char)rchRenderModelComponentName58, + (char)rchRenderModelComponentName59, + (char)rchRenderModelComponentName60, + (char)rchRenderModelComponentName61, + (char)rchRenderModelComponentName62, + (char)rchRenderModelComponentName63, + (char)rchRenderModelComponentName64, + (char)rchRenderModelComponentName65, + (char)rchRenderModelComponentName66, + (char)rchRenderModelComponentName67, + (char)rchRenderModelComponentName68, + (char)rchRenderModelComponentName69, + (char)rchRenderModelComponentName70, + (char)rchRenderModelComponentName71, + (char)rchRenderModelComponentName72, + (char)rchRenderModelComponentName73, + (char)rchRenderModelComponentName74, + (char)rchRenderModelComponentName75, + (char)rchRenderModelComponentName76, + (char)rchRenderModelComponentName77, + (char)rchRenderModelComponentName78, + (char)rchRenderModelComponentName79, + (char)rchRenderModelComponentName80, + (char)rchRenderModelComponentName81, + (char)rchRenderModelComponentName82, + (char)rchRenderModelComponentName83, + (char)rchRenderModelComponentName84, + (char)rchRenderModelComponentName85, + (char)rchRenderModelComponentName86, + (char)rchRenderModelComponentName87, + (char)rchRenderModelComponentName88, + (char)rchRenderModelComponentName89, + (char)rchRenderModelComponentName90, + (char)rchRenderModelComponentName91, + (char)rchRenderModelComponentName92, + (char)rchRenderModelComponentName93, + (char)rchRenderModelComponentName94, + (char)rchRenderModelComponentName95, + (char)rchRenderModelComponentName96, + (char)rchRenderModelComponentName97, + (char)rchRenderModelComponentName98, + (char)rchRenderModelComponentName99, + (char)rchRenderModelComponentName100, + (char)rchRenderModelComponentName101, + (char)rchRenderModelComponentName102, + (char)rchRenderModelComponentName103, + (char)rchRenderModelComponentName104, + (char)rchRenderModelComponentName105, + (char)rchRenderModelComponentName106, + (char)rchRenderModelComponentName107, + (char)rchRenderModelComponentName108, + (char)rchRenderModelComponentName109, + (char)rchRenderModelComponentName110, + (char)rchRenderModelComponentName111, + (char)rchRenderModelComponentName112, + (char)rchRenderModelComponentName113, + (char)rchRenderModelComponentName114, + (char)rchRenderModelComponentName115, + (char)rchRenderModelComponentName116, + (char)rchRenderModelComponentName117, + (char)rchRenderModelComponentName118, + (char)rchRenderModelComponentName119, + (char)rchRenderModelComponentName120, + (char)rchRenderModelComponentName121, + (char)rchRenderModelComponentName122, + (char)rchRenderModelComponentName123, + (char)rchRenderModelComponentName124, + (char)rchRenderModelComponentName125, + (char)rchRenderModelComponentName126, + (char)rchRenderModelComponentName127 + }).TrimEnd('\0'); + } + } +} +[StructLayout(LayoutKind.Sequential)] public struct VRActiveActionSet_t +{ + public ulong ulActionSet; + public ulong ulRestrictedToDevice; + public ulong ulSecondaryActionSet; + public uint unPadding; + public int nPriority; } -[StructLayout(LayoutKind.Sequential)] internal struct NotificationBitmap_t +[StructLayout(LayoutKind.Sequential)] public struct VRSkeletalSummaryData_t { - internal IntPtr m_pImageData; // void * - internal int m_nWidth; - internal int m_nHeight; - internal int m_nBytesPerPixel; + public float flFingerCurl0; //float[5] + public float flFingerCurl1; + public float flFingerCurl2; + public float flFingerCurl3; + public float flFingerCurl4; + public float flFingerSplay0; //float[4] + public float flFingerSplay1; + public float flFingerSplay2; + public float flFingerSplay3; } -[StructLayout(LayoutKind.Sequential)] internal struct COpenVRContext +[StructLayout(LayoutKind.Sequential)] public struct SpatialAnchorPose_t { - internal IntPtr m_pVRSystem; // class vr::IVRSystem * - internal IntPtr m_pVRChaperone; // class vr::IVRChaperone * - internal IntPtr m_pVRChaperoneSetup; // class vr::IVRChaperoneSetup * - internal IntPtr m_pVRCompositor; // class vr::IVRCompositor * - internal IntPtr m_pVROverlay; // class vr::IVROverlay * - internal IntPtr m_pVRResources; // class vr::IVRResources * - internal IntPtr m_pVRRenderModels; // class vr::IVRRenderModels * - internal IntPtr m_pVRExtendedDisplay; // class vr::IVRExtendedDisplay * - internal IntPtr m_pVRSettings; // class vr::IVRSettings * - internal IntPtr m_pVRApplications; // class vr::IVRApplications * - internal IntPtr m_pVRTrackedCamera; // class vr::IVRTrackedCamera * - internal IntPtr m_pVRScreenshots; // class vr::IVRScreenshots * + public HmdMatrix34_t mAnchorToAbsoluteTracking; +} +[StructLayout(LayoutKind.Sequential)] public struct COpenVRContext +{ + public IntPtr m_pVRSystem; // class vr::IVRSystem * + public IntPtr m_pVRChaperone; // class vr::IVRChaperone * + public IntPtr m_pVRChaperoneSetup; // class vr::IVRChaperoneSetup * + public IntPtr m_pVRCompositor; // class vr::IVRCompositor * + public IntPtr m_pVROverlay; // class vr::IVROverlay * + public IntPtr m_pVRResources; // class vr::IVRResources * + public IntPtr m_pVRRenderModels; // class vr::IVRRenderModels * + public IntPtr m_pVRExtendedDisplay; // class vr::IVRExtendedDisplay * + public IntPtr m_pVRSettings; // class vr::IVRSettings * + public IntPtr m_pVRApplications; // class vr::IVRApplications * + public IntPtr m_pVRTrackedCamera; // class vr::IVRTrackedCamera * + public IntPtr m_pVRScreenshots; // class vr::IVRScreenshots * + public IntPtr m_pVRDriverManager; // class vr::IVRDriverManager * + public IntPtr m_pVRInput; // class vr::IVRInput * + public IntPtr m_pVRIOBuffer; // class vr::IVRIOBuffer * + public IntPtr m_pVRSpatialAnchors; // class vr::IVRSpatialAnchors * + public IntPtr m_pVRNotifications; // class vr::IVRNotifications * } -internal class OpenVR +public class OpenVR { - internal static uint InitInternal(ref EVRInitError peError, EVRApplicationType eApplicationType) + public static uint InitInternal(ref EVRInitError peError, EVRApplicationType eApplicationType) { return OpenVRInterop.InitInternal(ref peError, eApplicationType); } - internal static void ShutdownInternal() + public static uint InitInternal2(ref EVRInitError peError, EVRApplicationType eApplicationType, string pchStartupInfo) + { + return OpenVRInterop.InitInternal2(ref peError, eApplicationType, pchStartupInfo); + } + + public static void ShutdownInternal() { OpenVRInterop.ShutdownInternal(); } - internal static bool IsHmdPresent() + public static bool IsHmdPresent() { return OpenVRInterop.IsHmdPresent(); } - internal static bool IsRuntimeInstalled() + public static bool IsRuntimeInstalled() { return OpenVRInterop.IsRuntimeInstalled(); } - internal static string GetStringForHmdError(EVRInitError error) + public static string RuntimePath() + { + return OpenVRInterop.RuntimePath(); + } + + public static string GetStringForHmdError(EVRInitError error) { return Marshal.PtrToStringAnsi(OpenVRInterop.GetStringForHmdError(error)); } - internal static IntPtr GetGenericInterface(string pchInterfaceVersion, ref EVRInitError peError) + public static IntPtr GetGenericInterface(string pchInterfaceVersion, ref EVRInitError peError) { return OpenVRInterop.GetGenericInterface(pchInterfaceVersion, ref peError); } - internal static bool IsInterfaceVersionValid(string pchInterfaceVersion) + public static bool IsInterfaceVersionValid(string pchInterfaceVersion) { return OpenVRInterop.IsInterfaceVersionValid(pchInterfaceVersion); } - internal static uint GetInitToken() + public static uint GetInitToken() { return OpenVRInterop.GetInitToken(); } - internal const uint k_unMaxDriverDebugResponseSize = 32768; - internal const uint k_unTrackedDeviceIndex_Hmd = 0; - internal const uint k_unMaxTrackedDeviceCount = 16; - internal const uint k_unTrackedDeviceIndexOther = 4294967294; - internal const uint k_unTrackedDeviceIndexInvalid = 4294967295; - internal const uint k_unMaxPropertyStringSize = 32768; - internal const uint k_unControllerStateAxisCount = 5; - internal const ulong k_ulOverlayHandleInvalid = 0; - internal const uint k_unScreenshotHandleInvalid = 0; - internal const string IVRSystem_Version = "IVRSystem_014"; - internal const string IVRExtendedDisplay_Version = "IVRExtendedDisplay_001"; - internal const string IVRTrackedCamera_Version = "IVRTrackedCamera_003"; - internal const uint k_unMaxApplicationKeyLength = 128; - internal const string k_pch_MimeType_HomeApp = "vr/home"; - internal const string k_pch_MimeType_GameTheater = "vr/game_theater"; - internal const string IVRApplications_Version = "IVRApplications_006"; - internal const string IVRChaperone_Version = "IVRChaperone_003"; - internal const string IVRChaperoneSetup_Version = "IVRChaperoneSetup_005"; - internal const string IVRCompositor_Version = "IVRCompositor_018"; - internal const uint k_unVROverlayMaxKeyLength = 128; - internal const uint k_unVROverlayMaxNameLength = 128; - internal const uint k_unMaxOverlayCount = 64; - internal const uint k_unMaxOverlayIntersectionMaskPrimitivesCount = 32; - internal const string IVROverlay_Version = "IVROverlay_013"; - internal const string k_pch_Controller_Component_GDC2015 = "gdc2015"; - internal const string k_pch_Controller_Component_Base = "base"; - internal const string k_pch_Controller_Component_Tip = "tip"; - internal const string k_pch_Controller_Component_HandGrip = "handgrip"; - internal const string k_pch_Controller_Component_Status = "status"; - internal const string IVRRenderModels_Version = "IVRRenderModels_005"; - internal const uint k_unNotificationTextMaxSize = 256; - internal const string IVRNotifications_Version = "IVRNotifications_002"; - internal const uint k_unMaxSettingsKeyLength = 128; - internal const string IVRSettings_Version = "IVRSettings_002"; - internal const string k_pch_SteamVR_Section = "steamvr"; - internal const string k_pch_SteamVR_RequireHmd_String = "requireHmd"; - internal const string k_pch_SteamVR_ForcedDriverKey_String = "forcedDriver"; - internal const string k_pch_SteamVR_ForcedHmdKey_String = "forcedHmd"; - internal const string k_pch_SteamVR_DisplayDebug_Bool = "displayDebug"; - internal const string k_pch_SteamVR_DebugProcessPipe_String = "debugProcessPipe"; - internal const string k_pch_SteamVR_EnableDistortion_Bool = "enableDistortion"; - internal const string k_pch_SteamVR_DisplayDebugX_Int32 = "displayDebugX"; - internal const string k_pch_SteamVR_DisplayDebugY_Int32 = "displayDebugY"; - internal const string k_pch_SteamVR_SendSystemButtonToAllApps_Bool = "sendSystemButtonToAllApps"; - internal const string k_pch_SteamVR_LogLevel_Int32 = "loglevel"; - internal const string k_pch_SteamVR_IPD_Float = "ipd"; - internal const string k_pch_SteamVR_Background_String = "background"; - internal const string k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection"; - internal const string k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight"; - internal const string k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius"; - internal const string k_pch_SteamVR_GridColor_String = "gridColor"; - internal const string k_pch_SteamVR_PlayAreaColor_String = "playAreaColor"; - internal const string k_pch_SteamVR_ShowStage_Bool = "showStage"; - internal const string k_pch_SteamVR_ActivateMultipleDrivers_Bool = "activateMultipleDrivers"; - internal const string k_pch_SteamVR_DirectMode_Bool = "directMode"; - internal const string k_pch_SteamVR_DirectModeEdidVid_Int32 = "directModeEdidVid"; - internal const string k_pch_SteamVR_DirectModeEdidPid_Int32 = "directModeEdidPid"; - internal const string k_pch_SteamVR_UsingSpeakers_Bool = "usingSpeakers"; - internal const string k_pch_SteamVR_SpeakersForwardYawOffsetDegrees_Float = "speakersForwardYawOffsetDegrees"; - internal const string k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement"; - internal const string k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses"; - internal const string k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier"; - internal const string k_pch_SteamVR_AllowAsyncReprojection_Bool = "allowAsyncReprojection"; - internal const string k_pch_SteamVR_AllowReprojection_Bool = "allowInterleavedReprojection"; - internal const string k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection"; - internal const string k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking"; - internal const string k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView"; - internal const string k_pch_SteamVR_ShowMirrorView_Bool = "showMirrorView"; - internal const string k_pch_SteamVR_MirrorViewGeometry_String = "mirrorViewGeometry"; - internal const string k_pch_SteamVR_StartMonitorFromAppLaunch = "startMonitorFromAppLaunch"; - internal const string k_pch_SteamVR_EnableHomeApp = "enableHomeApp"; - internal const string k_pch_SteamVR_SetInitialDefaultHomeApp = "setInitialDefaultHomeApp"; - internal const string k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec"; - internal const string k_pch_SteamVR_RetailDemo_Bool = "retailDemo"; - internal const string k_pch_SteamVR_IpdOffset_Float = "ipdOffset"; - internal const string k_pch_Lighthouse_Section = "driver_lighthouse"; - internal const string k_pch_Lighthouse_DisableIMU_Bool = "disableimu"; - internal const string k_pch_Lighthouse_UseDisambiguation_String = "usedisambiguation"; - internal const string k_pch_Lighthouse_DisambiguationDebug_Int32 = "disambiguationdebug"; - internal const string k_pch_Lighthouse_PrimaryBasestation_Int32 = "primarybasestation"; - internal const string k_pch_Lighthouse_DBHistory_Bool = "dbhistory"; - internal const string k_pch_Null_Section = "driver_null"; - internal const string k_pch_Null_EnableNullDriver_Bool = "enable"; - internal const string k_pch_Null_SerialNumber_String = "serialNumber"; - internal const string k_pch_Null_ModelNumber_String = "modelNumber"; - internal const string k_pch_Null_WindowX_Int32 = "windowX"; - internal const string k_pch_Null_WindowY_Int32 = "windowY"; - internal const string k_pch_Null_WindowWidth_Int32 = "windowWidth"; - internal const string k_pch_Null_WindowHeight_Int32 = "windowHeight"; - internal const string k_pch_Null_RenderWidth_Int32 = "renderWidth"; - internal const string k_pch_Null_RenderHeight_Int32 = "renderHeight"; - internal const string k_pch_Null_SecondsFromVsyncToPhotons_Float = "secondsFromVsyncToPhotons"; - internal const string k_pch_Null_DisplayFrequency_Float = "displayFrequency"; - internal const string k_pch_UserInterface_Section = "userinterface"; - internal const string k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop"; - internal const string k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray"; - internal const string k_pch_UserInterface_Screenshots_Bool = "screenshots"; - internal const string k_pch_UserInterface_ScreenshotType_Int = "screenshotType"; - internal const string k_pch_Notifications_Section = "notifications"; - internal const string k_pch_Notifications_DoNotDisturb_Bool = "DoNotDisturb"; - internal const string k_pch_Keyboard_Section = "keyboard"; - internal const string k_pch_Keyboard_TutorialCompletions = "TutorialCompletions"; - internal const string k_pch_Keyboard_ScaleX = "ScaleX"; - internal const string k_pch_Keyboard_ScaleY = "ScaleY"; - internal const string k_pch_Keyboard_OffsetLeftX = "OffsetLeftX"; - internal const string k_pch_Keyboard_OffsetRightX = "OffsetRightX"; - internal const string k_pch_Keyboard_OffsetY = "OffsetY"; - internal const string k_pch_Keyboard_Smoothing = "Smoothing"; - internal const string k_pch_Perf_Section = "perfcheck"; - internal const string k_pch_Perf_HeuristicActive_Bool = "heuristicActive"; - internal const string k_pch_Perf_NotifyInHMD_Bool = "warnInHMD"; - internal const string k_pch_Perf_NotifyOnlyOnce_Bool = "warnOnlyOnce"; - internal const string k_pch_Perf_AllowTimingStore_Bool = "allowTimingStore"; - internal const string k_pch_Perf_SaveTimingsOnExit_Bool = "saveTimingsOnExit"; - internal const string k_pch_Perf_TestData_Float = "perfTestData"; - internal const string k_pch_CollisionBounds_Section = "collisionBounds"; - internal const string k_pch_CollisionBounds_Style_Int32 = "CollisionBoundsStyle"; - internal const string k_pch_CollisionBounds_GroundPerimeterOn_Bool = "CollisionBoundsGroundPerimeterOn"; - internal const string k_pch_CollisionBounds_CenterMarkerOn_Bool = "CollisionBoundsCenterMarkerOn"; - internal const string k_pch_CollisionBounds_PlaySpaceOn_Bool = "CollisionBoundsPlaySpaceOn"; - internal const string k_pch_CollisionBounds_FadeDistance_Float = "CollisionBoundsFadeDistance"; - internal const string k_pch_CollisionBounds_ColorGammaR_Int32 = "CollisionBoundsColorGammaR"; - internal const string k_pch_CollisionBounds_ColorGammaG_Int32 = "CollisionBoundsColorGammaG"; - internal const string k_pch_CollisionBounds_ColorGammaB_Int32 = "CollisionBoundsColorGammaB"; - internal const string k_pch_CollisionBounds_ColorGammaA_Int32 = "CollisionBoundsColorGammaA"; - internal const string k_pch_Camera_Section = "camera"; - internal const string k_pch_Camera_EnableCamera_Bool = "enableCamera"; - internal const string k_pch_Camera_EnableCameraInDashboard_Bool = "enableCameraInDashboard"; - internal const string k_pch_Camera_EnableCameraForCollisionBounds_Bool = "enableCameraForCollisionBounds"; - internal const string k_pch_Camera_EnableCameraForRoomView_Bool = "enableCameraForRoomView"; - internal const string k_pch_Camera_BoundsColorGammaR_Int32 = "cameraBoundsColorGammaR"; - internal const string k_pch_Camera_BoundsColorGammaG_Int32 = "cameraBoundsColorGammaG"; - internal const string k_pch_Camera_BoundsColorGammaB_Int32 = "cameraBoundsColorGammaB"; - internal const string k_pch_Camera_BoundsColorGammaA_Int32 = "cameraBoundsColorGammaA"; - internal const string k_pch_Camera_BoundsStrength_Int32 = "cameraBoundsStrength"; - internal const string k_pch_audio_Section = "audio"; - internal const string k_pch_audio_OnPlaybackDevice_String = "onPlaybackDevice"; - internal const string k_pch_audio_OnRecordDevice_String = "onRecordDevice"; - internal const string k_pch_audio_OnPlaybackMirrorDevice_String = "onPlaybackMirrorDevice"; - internal const string k_pch_audio_OffPlaybackDevice_String = "offPlaybackDevice"; - internal const string k_pch_audio_OffRecordDevice_String = "offRecordDevice"; - internal const string k_pch_audio_VIVEHDMIGain = "viveHDMIGain"; - internal const string k_pch_Power_Section = "power"; - internal const string k_pch_Power_PowerOffOnExit_Bool = "powerOffOnExit"; - internal const string k_pch_Power_TurnOffScreensTimeout_Float = "turnOffScreensTimeout"; - internal const string k_pch_Power_TurnOffControllersTimeout_Float = "turnOffControllersTimeout"; - internal const string k_pch_Power_ReturnToWatchdogTimeout_Float = "returnToWatchdogTimeout"; - internal const string k_pch_Power_AutoLaunchSteamVROnButtonPress = "autoLaunchSteamVROnButtonPress"; - internal const string k_pch_Dashboard_Section = "dashboard"; - internal const string k_pch_Dashboard_EnableDashboard_Bool = "enableDashboard"; - internal const string k_pch_Dashboard_ArcadeMode_Bool = "arcadeMode"; - internal const string k_pch_modelskin_Section = "modelskins"; - internal const string IVRScreenshots_Version = "IVRScreenshots_001"; - internal const string IVRResources_Version = "IVRResources_001"; + public const uint k_nDriverNone = 4294967295; + public const uint k_unMaxDriverDebugResponseSize = 32768; + public const uint k_unTrackedDeviceIndex_Hmd = 0; + public const uint k_unMaxTrackedDeviceCount = 64; + public const uint k_unTrackedDeviceIndexOther = 4294967294; + public const uint k_unTrackedDeviceIndexInvalid = 4294967295; + public const ulong k_ulInvalidPropertyContainer = 0; + public const uint k_unInvalidPropertyTag = 0; + public const ulong k_ulInvalidDriverHandle = 0; + public const uint k_unFloatPropertyTag = 1; + public const uint k_unInt32PropertyTag = 2; + public const uint k_unUint64PropertyTag = 3; + public const uint k_unBoolPropertyTag = 4; + public const uint k_unStringPropertyTag = 5; + public const uint k_unHmdMatrix34PropertyTag = 20; + public const uint k_unHmdMatrix44PropertyTag = 21; + public const uint k_unHmdVector3PropertyTag = 22; + public const uint k_unHmdVector4PropertyTag = 23; + public const uint k_unHmdVector2PropertyTag = 24; + public const uint k_unHmdQuadPropertyTag = 25; + public const uint k_unHiddenAreaPropertyTag = 30; + public const uint k_unPathHandleInfoTag = 31; + public const uint k_unActionPropertyTag = 32; + public const uint k_unInputValuePropertyTag = 33; + public const uint k_unWildcardPropertyTag = 34; + public const uint k_unHapticVibrationPropertyTag = 35; + public const uint k_unSkeletonPropertyTag = 36; + public const uint k_unSpatialAnchorPosePropertyTag = 40; + public const uint k_unJsonPropertyTag = 41; + public const uint k_unActiveActionSetPropertyTag = 42; + public const uint k_unOpenVRInternalReserved_Start = 1000; + public const uint k_unOpenVRInternalReserved_End = 10000; + public const uint k_unMaxPropertyStringSize = 32768; + public const ulong k_ulInvalidActionHandle = 0; + public const ulong k_ulInvalidActionSetHandle = 0; + public const ulong k_ulInvalidInputValueHandle = 0; + public const uint k_unControllerStateAxisCount = 5; + public const ulong k_ulOverlayHandleInvalid = 0; + public const uint k_unMaxDistortionFunctionParameters = 8; + public const uint k_unScreenshotHandleInvalid = 0; + public const string IVRSystem_Version = "IVRSystem_019"; + public const string IVRExtendedDisplay_Version = "IVRExtendedDisplay_001"; + public const string IVRTrackedCamera_Version = "IVRTrackedCamera_005"; + public const uint k_unMaxApplicationKeyLength = 128; + public const string k_pch_MimeType_HomeApp = "vr/home"; + public const string k_pch_MimeType_GameTheater = "vr/game_theater"; + public const string IVRApplications_Version = "IVRApplications_006"; + public const string IVRChaperone_Version = "IVRChaperone_003"; + public const string IVRChaperoneSetup_Version = "IVRChaperoneSetup_006"; + public const string IVRCompositor_Version = "IVRCompositor_022"; + public const uint k_unVROverlayMaxKeyLength = 128; + public const uint k_unVROverlayMaxNameLength = 128; + public const uint k_unMaxOverlayCount = 64; + public const uint k_unMaxOverlayIntersectionMaskPrimitivesCount = 32; + public const string IVROverlay_Version = "IVROverlay_019"; + public const string k_pch_Controller_Component_GDC2015 = "gdc2015"; + public const string k_pch_Controller_Component_Base = "base"; + public const string k_pch_Controller_Component_Tip = "tip"; + public const string k_pch_Controller_Component_HandGrip = "handgrip"; + public const string k_pch_Controller_Component_Status = "status"; + public const string IVRRenderModels_Version = "IVRRenderModels_006"; + public const uint k_unNotificationTextMaxSize = 256; + public const string IVRNotifications_Version = "IVRNotifications_002"; + public const uint k_unMaxSettingsKeyLength = 128; + public const string IVRSettings_Version = "IVRSettings_002"; + public const string k_pch_SteamVR_Section = "steamvr"; + public const string k_pch_SteamVR_RequireHmd_String = "requireHmd"; + public const string k_pch_SteamVR_ForcedDriverKey_String = "forcedDriver"; + public const string k_pch_SteamVR_ForcedHmdKey_String = "forcedHmd"; + public const string k_pch_SteamVR_DisplayDebug_Bool = "displayDebug"; + public const string k_pch_SteamVR_DebugProcessPipe_String = "debugProcessPipe"; + public const string k_pch_SteamVR_DisplayDebugX_Int32 = "displayDebugX"; + public const string k_pch_SteamVR_DisplayDebugY_Int32 = "displayDebugY"; + public const string k_pch_SteamVR_SendSystemButtonToAllApps_Bool = "sendSystemButtonToAllApps"; + public const string k_pch_SteamVR_LogLevel_Int32 = "loglevel"; + public const string k_pch_SteamVR_IPD_Float = "ipd"; + public const string k_pch_SteamVR_Background_String = "background"; + public const string k_pch_SteamVR_BackgroundUseDomeProjection_Bool = "backgroundUseDomeProjection"; + public const string k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight"; + public const string k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius"; + public const string k_pch_SteamVR_GridColor_String = "gridColor"; + public const string k_pch_SteamVR_PlayAreaColor_String = "playAreaColor"; + public const string k_pch_SteamVR_ShowStage_Bool = "showStage"; + public const string k_pch_SteamVR_ActivateMultipleDrivers_Bool = "activateMultipleDrivers"; + public const string k_pch_SteamVR_UsingSpeakers_Bool = "usingSpeakers"; + public const string k_pch_SteamVR_SpeakersForwardYawOffsetDegrees_Float = "speakersForwardYawOffsetDegrees"; + public const string k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement"; + public const string k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses"; + public const string k_pch_SteamVR_SupersampleScale_Float = "supersampleScale"; + public const string k_pch_SteamVR_MaxRecommendedResolution_Int32 = "maxRecommendedResolution"; + public const string k_pch_SteamVR_MotionSmoothing_Bool = "motionSmoothing"; + public const string k_pch_SteamVR_MotionSmoothingOverride_Int32 = "motionSmoothingOverride"; + public const string k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking"; + public const string k_pch_SteamVR_DefaultMirrorView_Int32 = "mirrorView"; + public const string k_pch_SteamVR_ShowMirrorView_Bool = "showMirrorView"; + public const string k_pch_SteamVR_MirrorViewGeometry_String = "mirrorViewGeometry"; + public const string k_pch_SteamVR_MirrorViewGeometryMaximized_String = "mirrorViewGeometryMaximized"; + public const string k_pch_SteamVR_StartMonitorFromAppLaunch = "startMonitorFromAppLaunch"; + public const string k_pch_SteamVR_StartCompositorFromAppLaunch_Bool = "startCompositorFromAppLaunch"; + public const string k_pch_SteamVR_StartDashboardFromAppLaunch_Bool = "startDashboardFromAppLaunch"; + public const string k_pch_SteamVR_StartOverlayAppsFromDashboard_Bool = "startOverlayAppsFromDashboard"; + public const string k_pch_SteamVR_EnableHomeApp = "enableHomeApp"; + public const string k_pch_SteamVR_CycleBackgroundImageTimeSec_Int32 = "CycleBackgroundImageTimeSec"; + public const string k_pch_SteamVR_RetailDemo_Bool = "retailDemo"; + public const string k_pch_SteamVR_IpdOffset_Float = "ipdOffset"; + public const string k_pch_SteamVR_AllowSupersampleFiltering_Bool = "allowSupersampleFiltering"; + public const string k_pch_SteamVR_SupersampleManualOverride_Bool = "supersampleManualOverride"; + public const string k_pch_SteamVR_EnableLinuxVulkanAsync_Bool = "enableLinuxVulkanAsync"; + public const string k_pch_SteamVR_AllowDisplayLockedMode_Bool = "allowDisplayLockedMode"; + public const string k_pch_SteamVR_HaveStartedTutorialForNativeChaperoneDriver_Bool = "haveStartedTutorialForNativeChaperoneDriver"; + public const string k_pch_SteamVR_ForceWindows32bitVRMonitor = "forceWindows32BitVRMonitor"; + public const string k_pch_SteamVR_DebugInput = "debugInput"; + public const string k_pch_SteamVR_DebugInputBinding = "debugInputBinding"; + public const string k_pch_SteamVR_InputBindingUIBlock = "inputBindingUI"; + public const string k_pch_SteamVR_RenderCameraMode = "renderCameraMode"; + public const string k_pch_SteamVR_EnableSharedResourceJournaling = "enableSharedResourceJournaling"; + public const string k_pch_SteamVR_EnableSafeMode = "enableSafeMode"; + public const string k_pch_SteamVR_PreferredRefreshRate = "preferredRefreshRate"; + public const string k_pch_SteamVR_LastVersionNotice = "lastVersionNotice"; + public const string k_pch_SteamVR_LastVersionNoticeDate = "lastVersionNoticeDate"; + public const string k_pch_DirectMode_Section = "direct_mode"; + public const string k_pch_DirectMode_Enable_Bool = "enable"; + public const string k_pch_DirectMode_Count_Int32 = "count"; + public const string k_pch_DirectMode_EdidVid_Int32 = "edidVid"; + public const string k_pch_DirectMode_EdidPid_Int32 = "edidPid"; + public const string k_pch_Lighthouse_Section = "driver_lighthouse"; + public const string k_pch_Lighthouse_DisableIMU_Bool = "disableimu"; + public const string k_pch_Lighthouse_DisableIMUExceptHMD_Bool = "disableimuexcepthmd"; + public const string k_pch_Lighthouse_UseDisambiguation_String = "usedisambiguation"; + public const string k_pch_Lighthouse_DisambiguationDebug_Int32 = "disambiguationdebug"; + public const string k_pch_Lighthouse_PrimaryBasestation_Int32 = "primarybasestation"; + public const string k_pch_Lighthouse_DBHistory_Bool = "dbhistory"; + public const string k_pch_Lighthouse_EnableBluetooth_Bool = "enableBluetooth"; + public const string k_pch_Lighthouse_PowerManagedBaseStations_String = "PowerManagedBaseStations"; + public const string k_pch_Lighthouse_PowerManagedBaseStations2_String = "PowerManagedBaseStations2"; + public const string k_pch_Lighthouse_EnableImuFallback_Bool = "enableImuFallback"; + public const string k_pch_Null_Section = "driver_null"; + public const string k_pch_Null_SerialNumber_String = "serialNumber"; + public const string k_pch_Null_ModelNumber_String = "modelNumber"; + public const string k_pch_Null_WindowX_Int32 = "windowX"; + public const string k_pch_Null_WindowY_Int32 = "windowY"; + public const string k_pch_Null_WindowWidth_Int32 = "windowWidth"; + public const string k_pch_Null_WindowHeight_Int32 = "windowHeight"; + public const string k_pch_Null_RenderWidth_Int32 = "renderWidth"; + public const string k_pch_Null_RenderHeight_Int32 = "renderHeight"; + public const string k_pch_Null_SecondsFromVsyncToPhotons_Float = "secondsFromVsyncToPhotons"; + public const string k_pch_Null_DisplayFrequency_Float = "displayFrequency"; + public const string k_pch_UserInterface_Section = "userinterface"; + public const string k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop"; + public const string k_pch_UserInterface_MinimizeToTray_Bool = "MinimizeToTray"; + public const string k_pch_UserInterface_HidePopupsWhenStatusMinimized_Bool = "HidePopupsWhenStatusMinimized"; + public const string k_pch_UserInterface_Screenshots_Bool = "screenshots"; + public const string k_pch_UserInterface_ScreenshotType_Int = "screenshotType"; + public const string k_pch_Notifications_Section = "notifications"; + public const string k_pch_Notifications_DoNotDisturb_Bool = "DoNotDisturb"; + public const string k_pch_Keyboard_Section = "keyboard"; + public const string k_pch_Keyboard_TutorialCompletions = "TutorialCompletions"; + public const string k_pch_Keyboard_ScaleX = "ScaleX"; + public const string k_pch_Keyboard_ScaleY = "ScaleY"; + public const string k_pch_Keyboard_OffsetLeftX = "OffsetLeftX"; + public const string k_pch_Keyboard_OffsetRightX = "OffsetRightX"; + public const string k_pch_Keyboard_OffsetY = "OffsetY"; + public const string k_pch_Keyboard_Smoothing = "Smoothing"; + public const string k_pch_Perf_Section = "perfcheck"; + public const string k_pch_Perf_PerfGraphInHMD_Bool = "perfGraphInHMD"; + public const string k_pch_Perf_AllowTimingStore_Bool = "allowTimingStore"; + public const string k_pch_Perf_SaveTimingsOnExit_Bool = "saveTimingsOnExit"; + public const string k_pch_Perf_TestData_Float = "perfTestData"; + public const string k_pch_Perf_LinuxGPUProfiling_Bool = "linuxGPUProfiling"; + public const string k_pch_CollisionBounds_Section = "collisionBounds"; + public const string k_pch_CollisionBounds_Style_Int32 = "CollisionBoundsStyle"; + public const string k_pch_CollisionBounds_GroundPerimeterOn_Bool = "CollisionBoundsGroundPerimeterOn"; + public const string k_pch_CollisionBounds_CenterMarkerOn_Bool = "CollisionBoundsCenterMarkerOn"; + public const string k_pch_CollisionBounds_PlaySpaceOn_Bool = "CollisionBoundsPlaySpaceOn"; + public const string k_pch_CollisionBounds_FadeDistance_Float = "CollisionBoundsFadeDistance"; + public const string k_pch_CollisionBounds_ColorGammaR_Int32 = "CollisionBoundsColorGammaR"; + public const string k_pch_CollisionBounds_ColorGammaG_Int32 = "CollisionBoundsColorGammaG"; + public const string k_pch_CollisionBounds_ColorGammaB_Int32 = "CollisionBoundsColorGammaB"; + public const string k_pch_CollisionBounds_ColorGammaA_Int32 = "CollisionBoundsColorGammaA"; + public const string k_pch_Camera_Section = "camera"; + public const string k_pch_Camera_EnableCamera_Bool = "enableCamera"; + public const string k_pch_Camera_EnableCameraInDashboard_Bool = "enableCameraInDashboard"; + public const string k_pch_Camera_EnableCameraForCollisionBounds_Bool = "enableCameraForCollisionBounds"; + public const string k_pch_Camera_EnableCameraForRoomView_Bool = "enableCameraForRoomView"; + public const string k_pch_Camera_BoundsColorGammaR_Int32 = "cameraBoundsColorGammaR"; + public const string k_pch_Camera_BoundsColorGammaG_Int32 = "cameraBoundsColorGammaG"; + public const string k_pch_Camera_BoundsColorGammaB_Int32 = "cameraBoundsColorGammaB"; + public const string k_pch_Camera_BoundsColorGammaA_Int32 = "cameraBoundsColorGammaA"; + public const string k_pch_Camera_BoundsStrength_Int32 = "cameraBoundsStrength"; + public const string k_pch_Camera_RoomViewMode_Int32 = "cameraRoomViewMode"; + public const string k_pch_audio_Section = "audio"; + public const string k_pch_audio_OnPlaybackDevice_String = "onPlaybackDevice"; + public const string k_pch_audio_OnRecordDevice_String = "onRecordDevice"; + public const string k_pch_audio_OnPlaybackMirrorDevice_String = "onPlaybackMirrorDevice"; + public const string k_pch_audio_OffPlaybackDevice_String = "offPlaybackDevice"; + public const string k_pch_audio_OffRecordDevice_String = "offRecordDevice"; + public const string k_pch_audio_VIVEHDMIGain = "viveHDMIGain"; + public const string k_pch_Power_Section = "power"; + public const string k_pch_Power_PowerOffOnExit_Bool = "powerOffOnExit"; + public const string k_pch_Power_TurnOffScreensTimeout_Float = "turnOffScreensTimeout"; + public const string k_pch_Power_TurnOffControllersTimeout_Float = "turnOffControllersTimeout"; + public const string k_pch_Power_ReturnToWatchdogTimeout_Float = "returnToWatchdogTimeout"; + public const string k_pch_Power_AutoLaunchSteamVROnButtonPress = "autoLaunchSteamVROnButtonPress"; + public const string k_pch_Power_PauseCompositorOnStandby_Bool = "pauseCompositorOnStandby"; + public const string k_pch_Dashboard_Section = "dashboard"; + public const string k_pch_Dashboard_EnableDashboard_Bool = "enableDashboard"; + public const string k_pch_Dashboard_ArcadeMode_Bool = "arcadeMode"; + public const string k_pch_Dashboard_EnableWebUI = "webUI"; + public const string k_pch_Dashboard_EnableWebUIDevTools = "webUIDevTools"; + public const string k_pch_Dashboard_EnableWebUIDashboardReplacement = "webUIDashboard"; + public const string k_pch_modelskin_Section = "modelskins"; + public const string k_pch_Driver_Enable_Bool = "enable"; + public const string k_pch_WebInterface_Section = "WebInterface"; + public const string k_pch_WebInterface_WebEnable_Bool = "WebEnable"; + public const string k_pch_WebInterface_WebPort_String = "WebPort"; + public const string k_pch_VRWebHelper_Section = "VRWebHelper"; + public const string k_pch_VRWebHelper_DebuggerEnabled_Bool = "DebuggerEnabled"; + public const string k_pch_VRWebHelper_DebuggerPort_Int32 = "DebuggerPort"; + public const string k_pch_TrackingOverride_Section = "TrackingOverrides"; + public const string k_pch_App_BindingAutosaveURLSuffix_String = "AutosaveURL"; + public const string k_pch_App_BindingCurrentURLSuffix_String = "CurrentURL"; + public const string k_pch_App_NeedToUpdateAutosaveSuffix_Bool = "NeedToUpdateAutosave"; + public const string k_pch_Trackers_Section = "trackers"; + public const string k_pch_DesktopUI_Section = "DesktopUI"; + public const string k_pch_LastKnown_Section = "LastKnown"; + public const string k_pch_LastKnown_HMDManufacturer_String = "HMDManufacturer"; + public const string k_pch_LastKnown_HMDModel_String = "HMDModel"; + public const string k_pch_DismissedWarnings_Section = "DismissedWarnings"; + public const string IVRScreenshots_Version = "IVRScreenshots_001"; + public const string IVRResources_Version = "IVRResources_001"; + public const string IVRDriverManager_Version = "IVRDriverManager_001"; + public const uint k_unMaxActionNameLength = 64; + public const uint k_unMaxActionSetNameLength = 64; + public const uint k_unMaxActionOriginCount = 16; + public const uint k_unMaxBoneNameLength = 32; + public const string IVRInput_Version = "IVRInput_005"; + public const ulong k_ulInvalidIOBufferHandle = 0; + public const string IVRIOBuffer_Version = "IVRIOBuffer_002"; + public const uint k_ulInvalidSpatialAnchorHandle = 0; + public const string IVRSpatialAnchors_Version = "IVRSpatialAnchors_001"; static uint VRToken { get; set; } @@ -4291,9 +6043,9 @@ internal static uint GetInitToken() class COpenVRContext { - internal COpenVRContext() { Clear(); } + public COpenVRContext() { Clear(); } - internal void Clear() + public void Clear() { m_pVRSystem = null; m_pVRChaperone = null; @@ -4306,6 +6058,10 @@ internal void Clear() m_pVRApplications = null; m_pVRScreenshots = null; m_pVRTrackedCamera = null; + m_pVRInput = null; + m_pVRIOBuffer = null; + m_pVRSpatialAnchors = null; + m_pVRNotifications = null; } void CheckClear() @@ -4317,7 +6073,7 @@ void CheckClear() } } - internal CVRSystem VRSystem() + public CVRSystem VRSystem() { CheckClear(); if (m_pVRSystem == null) @@ -4330,7 +6086,7 @@ internal CVRSystem VRSystem() return m_pVRSystem; } - internal CVRChaperone VRChaperone() + public CVRChaperone VRChaperone() { CheckClear(); if (m_pVRChaperone == null) @@ -4343,7 +6099,7 @@ internal CVRChaperone VRChaperone() return m_pVRChaperone; } - internal CVRChaperoneSetup VRChaperoneSetup() + public CVRChaperoneSetup VRChaperoneSetup() { CheckClear(); if (m_pVRChaperoneSetup == null) @@ -4356,7 +6112,7 @@ internal CVRChaperoneSetup VRChaperoneSetup() return m_pVRChaperoneSetup; } - internal CVRCompositor VRCompositor() + public CVRCompositor VRCompositor() { CheckClear(); if (m_pVRCompositor == null) @@ -4369,7 +6125,7 @@ internal CVRCompositor VRCompositor() return m_pVRCompositor; } - internal CVROverlay VROverlay() + public CVROverlay VROverlay() { CheckClear(); if (m_pVROverlay == null) @@ -4382,7 +6138,7 @@ internal CVROverlay VROverlay() return m_pVROverlay; } - internal CVRRenderModels VRRenderModels() + public CVRRenderModels VRRenderModels() { CheckClear(); if (m_pVRRenderModels == null) @@ -4395,7 +6151,7 @@ internal CVRRenderModels VRRenderModels() return m_pVRRenderModels; } - internal CVRExtendedDisplay VRExtendedDisplay() + public CVRExtendedDisplay VRExtendedDisplay() { CheckClear(); if (m_pVRExtendedDisplay == null) @@ -4408,7 +6164,7 @@ internal CVRExtendedDisplay VRExtendedDisplay() return m_pVRExtendedDisplay; } - internal CVRSettings VRSettings() + public CVRSettings VRSettings() { CheckClear(); if (m_pVRSettings == null) @@ -4421,7 +6177,7 @@ internal CVRSettings VRSettings() return m_pVRSettings; } - internal CVRApplications VRApplications() + public CVRApplications VRApplications() { CheckClear(); if (m_pVRApplications == null) @@ -4434,7 +6190,7 @@ internal CVRApplications VRApplications() return m_pVRApplications; } - internal CVRScreenshots VRScreenshots() + public CVRScreenshots VRScreenshots() { CheckClear(); if (m_pVRScreenshots == null) @@ -4447,7 +6203,7 @@ internal CVRScreenshots VRScreenshots() return m_pVRScreenshots; } - internal CVRTrackedCamera VRTrackedCamera() + public CVRTrackedCamera VRTrackedCamera() { CheckClear(); if (m_pVRTrackedCamera == null) @@ -4460,6 +6216,58 @@ internal CVRTrackedCamera VRTrackedCamera() return m_pVRTrackedCamera; } + public CVRInput VRInput() + { + CheckClear(); + if (m_pVRInput == null) + { + var eError = EVRInitError.None; + var pInterface = OpenVRInterop.GetGenericInterface(FnTable_Prefix+IVRInput_Version, ref eError); + if (pInterface != IntPtr.Zero && eError == EVRInitError.None) + m_pVRInput = new CVRInput(pInterface); + } + return m_pVRInput; + } + + public CVRIOBuffer VRIOBuffer() + { + CheckClear(); + if (m_pVRIOBuffer == null) + { + var eError = EVRInitError.None; + var pInterface = OpenVRInterop.GetGenericInterface(FnTable_Prefix + IVRIOBuffer_Version, ref eError); + if (pInterface != IntPtr.Zero && eError == EVRInitError.None) + m_pVRIOBuffer = new CVRIOBuffer(pInterface); + } + return m_pVRIOBuffer; + } + + public CVRSpatialAnchors VRSpatialAnchors() + { + CheckClear(); + if (m_pVRSpatialAnchors == null) + { + var eError = EVRInitError.None; + var pInterface = OpenVRInterop.GetGenericInterface(FnTable_Prefix + IVRSpatialAnchors_Version, ref eError); + if (pInterface != IntPtr.Zero && eError == EVRInitError.None) + m_pVRSpatialAnchors = new CVRSpatialAnchors(pInterface); + } + return m_pVRSpatialAnchors; + } + + public CVRNotifications VRNotifications() + { + CheckClear(); + if (m_pVRNotifications == null) + { + var eError = EVRInitError.None; + var pInterface = OpenVRInterop.GetGenericInterface(FnTable_Prefix + IVRNotifications_Version, ref eError); + if (pInterface != IntPtr.Zero && eError == EVRInitError.None) + m_pVRNotifications = new CVRNotifications(pInterface); + } + return m_pVRNotifications; + } + private CVRSystem m_pVRSystem; private CVRChaperone m_pVRChaperone; private CVRChaperoneSetup m_pVRChaperoneSetup; @@ -4471,6 +6279,10 @@ internal CVRTrackedCamera VRTrackedCamera() private CVRApplications m_pVRApplications; private CVRScreenshots m_pVRScreenshots; private CVRTrackedCamera m_pVRTrackedCamera; + private CVRInput m_pVRInput; + private CVRIOBuffer m_pVRIOBuffer; + private CVRSpatialAnchors m_pVRSpatialAnchors; + private CVRNotifications m_pVRNotifications; }; private static COpenVRContext _OpenVRInternal_ModuleContext = null; @@ -4484,22 +6296,34 @@ static COpenVRContext OpenVRInternal_ModuleContext } } - internal static CVRSystem System { get { return OpenVRInternal_ModuleContext.VRSystem(); } } - internal static CVRChaperone Chaperone { get { return OpenVRInternal_ModuleContext.VRChaperone(); } } - internal static CVRChaperoneSetup ChaperoneSetup { get { return OpenVRInternal_ModuleContext.VRChaperoneSetup(); } } - internal static CVRCompositor Compositor { get { return OpenVRInternal_ModuleContext.VRCompositor(); } } - internal static CVROverlay Overlay { get { return OpenVRInternal_ModuleContext.VROverlay(); } } - internal static CVRRenderModels RenderModels { get { return OpenVRInternal_ModuleContext.VRRenderModels(); } } - internal static CVRExtendedDisplay ExtendedDisplay { get { return OpenVRInternal_ModuleContext.VRExtendedDisplay(); } } - internal static CVRSettings Settings { get { return OpenVRInternal_ModuleContext.VRSettings(); } } - internal static CVRApplications Applications { get { return OpenVRInternal_ModuleContext.VRApplications(); } } - internal static CVRScreenshots Screenshots { get { return OpenVRInternal_ModuleContext.VRScreenshots(); } } - internal static CVRTrackedCamera TrackedCamera { get { return OpenVRInternal_ModuleContext.VRTrackedCamera(); } } + public static CVRSystem System { get { return OpenVRInternal_ModuleContext.VRSystem(); } } + public static CVRChaperone Chaperone { get { return OpenVRInternal_ModuleContext.VRChaperone(); } } + public static CVRChaperoneSetup ChaperoneSetup { get { return OpenVRInternal_ModuleContext.VRChaperoneSetup(); } } + public static CVRCompositor Compositor { get { return OpenVRInternal_ModuleContext.VRCompositor(); } } + public static CVROverlay Overlay { get { return OpenVRInternal_ModuleContext.VROverlay(); } } + public static CVRRenderModels RenderModels { get { return OpenVRInternal_ModuleContext.VRRenderModels(); } } + public static CVRExtendedDisplay ExtendedDisplay { get { return OpenVRInternal_ModuleContext.VRExtendedDisplay(); } } + public static CVRSettings Settings { get { return OpenVRInternal_ModuleContext.VRSettings(); } } + public static CVRApplications Applications { get { return OpenVRInternal_ModuleContext.VRApplications(); } } + public static CVRScreenshots Screenshots { get { return OpenVRInternal_ModuleContext.VRScreenshots(); } } + public static CVRTrackedCamera TrackedCamera { get { return OpenVRInternal_ModuleContext.VRTrackedCamera(); } } + public static CVRInput Input { get { return OpenVRInternal_ModuleContext.VRInput(); } } + public static CVRIOBuffer IOBuffer { get { return OpenVRInternal_ModuleContext.VRIOBuffer(); } } + public static CVRSpatialAnchors SpatialAnchors { get { return OpenVRInternal_ModuleContext.VRSpatialAnchors(); } } + public static CVRNotifications Notifications { get { return OpenVRInternal_ModuleContext.VRNotifications(); } } /** Finds the active installation of vrclient.dll and initializes it */ - internal static CVRSystem Init(ref EVRInitError peError, EVRApplicationType eApplicationType = EVRApplicationType.VRApplication_Scene) + public static CVRSystem Init(ref EVRInitError peError, EVRApplicationType eApplicationType = EVRApplicationType.VRApplication_Scene, string pchStartupInfo= "") { - VRToken = InitInternal(ref peError, eApplicationType); + try + { + VRToken = InitInternal2(ref peError, eApplicationType, pchStartupInfo); + } + catch (EntryPointNotFoundException) + { + VRToken = InitInternal(ref peError, eApplicationType); + } + OpenVRInternal_ModuleContext.Clear(); if (peError != EVRInitError.None) @@ -4518,7 +6342,7 @@ internal static CVRSystem Init(ref EVRInitError peError, EVRApplicationType eApp /** unloads vrclient.dll. Any interface pointers from the interface are * invalid after this point */ - internal static void Shutdown() + public static void Shutdown() { ShutdownInternal(); } diff --git a/sources/targets/Xenko.GlobalSettings.targets b/sources/targets/Xenko.GlobalSettings.targets index 54ee2a8741..1bd01cd91f 100644 --- a/sources/targets/Xenko.GlobalSettings.targets +++ b/sources/targets/Xenko.GlobalSettings.targets @@ -4,11 +4,11 @@ - Direct3D11 + Vulkan Direct3D11 OpenGLES OpenGLES - OpenGL + Vulkan Vulkan $(XenkoGraphicsApi) $(XenkoDefaultGraphicsApi) From b96cdd9119fbb4d9c9fd2699c0c32ad8e0ab044a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 15 Feb 2019 17:26:07 +0000 Subject: [PATCH 0011/2038] linux default to vulkan, requires building with Visual Studio --- .../Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 index a576c760db..81237572fe 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 @@ -3,7 +3,7 @@ netcoreapp2.1 - linux-x64 + linux-vulkan-x64 Resources\Icon.ico WinExe <#= Properties.Namespace #> From 82f06e90eb049ebdb8136d67271b1ee4aa084711 Mon Sep 17 00:00:00 2001 From: Nicolas Musset Date: Tue, 19 Feb 2019 00:01:16 +0900 Subject: [PATCH 0012/2038] [Presentation] Fix syntax error in Int3 editor template --- .../Xenko.Core.Presentation/Themes/ExpressionDark/Theme.xaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/presentation/Xenko.Core.Presentation/Themes/ExpressionDark/Theme.xaml b/sources/presentation/Xenko.Core.Presentation/Themes/ExpressionDark/Theme.xaml index 35a2ffc740..6b5d2a8f73 100644 --- a/sources/presentation/Xenko.Core.Presentation/Themes/ExpressionDark/Theme.xaml +++ b/sources/presentation/Xenko.Core.Presentation/Themes/ExpressionDark/Theme.xaml @@ -4226,7 +4226,7 @@ /> + WatermarkContentTemplate="{Binding WatermarkContentTemplate, RelativeSource={RelativeSource Mode=TemplatedParent}}"/> From 48d33d32c3d31dcefac29e64d13bb4aa99b40983 Mon Sep 17 00:00:00 2001 From: Nicolas Musset Date: Tue, 19 Feb 2019 00:01:52 +0900 Subject: [PATCH 0013/2038] [Assets] Add Int vector types to the test asset --- .../Test/TestAsset.cs | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs b/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs index d276f973d4..0dec43de22 100644 --- a/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs +++ b/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs @@ -195,31 +195,43 @@ public sealed class TestAsset : Asset public Vector4 Vector4 { get; set; } [DataMember(48)] + [Display("Int2", "Int types")] + public Int2 Int2 { get; set; } + + [DataMember(49)] + [Display("Int3", "Int types")] + public Int3 Int3 { get; set; } + + [DataMember(50)] + [Display("Int4", "Int types")] + public Int4 Int4 { get; set; } + + [DataMember(51)] [Display("RectangleF", "Vector types")] public RectangleF RectangleF { get; set; } - [DataMember(49)] + [DataMember(52)] [Display("Rectangle", "Vector types")] public Rectangle Rectangle { get; set; } - [DataMember(50)] + [DataMember(53)] [Display("Angle", "Vector types")] public AngleSingle Angle { get; set; } - [DataMember(51)] + [DataMember(54)] [Display("Rotation", "Vector types")] public Quaternion Rotation { get; set; } - [DataMember(52)] + [DataMember(55)] [Display("Matrix", "Vector types")] public Matrix Matrix { get; set; } // TODO: Add ImageEnum and ImageFlagEnum - [DataMember(53)] + [DataMember(56)] [Display("Nullable Enum", "Class & Struct types")] public TestEnum? NullableEnum { get; set; } - [DataMember(55)] + [DataMember(57)] [Display("Nullable Rectangle", "Class & Struct types")] public Rectangle? NullableRectangle { get; set; } From 50c1e452a0b8522ab0c3eb11fd13f47b8644c29a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 19 Feb 2019 21:46:53 +0000 Subject: [PATCH 0014/2038] Revert "[Assets] Add Int vector types to the test asset" This reverts commit 48d33d32c3d31dcefac29e64d13bb4aa99b40983. --- .../Test/TestAsset.cs | 24 +++++-------------- 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs b/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs index 0dec43de22..d276f973d4 100644 --- a/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs +++ b/sources/editor/Xenko.Assets.Presentation/Test/TestAsset.cs @@ -195,43 +195,31 @@ public sealed class TestAsset : Asset public Vector4 Vector4 { get; set; } [DataMember(48)] - [Display("Int2", "Int types")] - public Int2 Int2 { get; set; } - - [DataMember(49)] - [Display("Int3", "Int types")] - public Int3 Int3 { get; set; } - - [DataMember(50)] - [Display("Int4", "Int types")] - public Int4 Int4 { get; set; } - - [DataMember(51)] [Display("RectangleF", "Vector types")] public RectangleF RectangleF { get; set; } - [DataMember(52)] + [DataMember(49)] [Display("Rectangle", "Vector types")] public Rectangle Rectangle { get; set; } - [DataMember(53)] + [DataMember(50)] [Display("Angle", "Vector types")] public AngleSingle Angle { get; set; } - [DataMember(54)] + [DataMember(51)] [Display("Rotation", "Vector types")] public Quaternion Rotation { get; set; } - [DataMember(55)] + [DataMember(52)] [Display("Matrix", "Vector types")] public Matrix Matrix { get; set; } // TODO: Add ImageEnum and ImageFlagEnum - [DataMember(56)] + [DataMember(53)] [Display("Nullable Enum", "Class & Struct types")] public TestEnum? NullableEnum { get; set; } - [DataMember(57)] + [DataMember(55)] [Display("Nullable Rectangle", "Class & Struct types")] public Rectangle? NullableRectangle { get; set; } From 386cd86adabf6c125b646adc58faacb5af3a0d12 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 20 Feb 2019 02:43:16 +0000 Subject: [PATCH 0015/2038] fix autohiding taskbar from being covered. also disable test building --- build/Xenko.sln | 56 ------------------- .../Xenko.GameStudio/GameStudioWindow.xaml.cs | 3 + .../Extensions/WindowHelper.cs | 2 +- 3 files changed, 4 insertions(+), 57 deletions(-) diff --git a/build/Xenko.sln b/build/Xenko.sln index ae2199b086..d0d85c75d9 100644 --- a/build/Xenko.sln +++ b/build/Xenko.sln @@ -499,32 +499,26 @@ Global {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Debug|Any CPU.Build.0 = Debug|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Debug|Win32.ActiveCfg = Debug|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Release|Any CPU.ActiveCfg = Release|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Release|Any CPU.Build.0 = Release|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A8F8D125-7A22-489F-99BC-9A02F545A17F}.Release|Win32.ActiveCfg = Release|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Debug|Any CPU.Build.0 = Debug|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {01700344-CF44-482C-BEBC-60213B0F844C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Debug|Win32.ActiveCfg = Debug|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Release|Any CPU.ActiveCfg = Release|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Release|Any CPU.Build.0 = Release|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {01700344-CF44-482C-BEBC-60213B0F844C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {01700344-CF44-482C-BEBC-60213B0F844C}.Release|Win32.ActiveCfg = Release|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Debug|Any CPU.Build.0 = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Debug|Win32.ActiveCfg = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Release|Any CPU.ActiveCfg = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Release|Any CPU.Build.0 = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Release|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Release|Mixed Platforms.Build.0 = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Release|Win32.ActiveCfg = Debug|Any CPU {5AA408BA-E766-453E-B661-E3D7EC46E2A6}.Release|Win32.Build.0 = Debug|Any CPU {0467D515-FD66-4B8A-A128-CB642C2ED03F}.Debug|Any CPU.ActiveCfg = Debug|Win32 @@ -560,12 +554,10 @@ Global {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Debug|Any CPU.Build.0 = Debug|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Debug|Win32.ActiveCfg = Debug|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Release|Any CPU.ActiveCfg = Release|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Release|Any CPU.Build.0 = Release|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C223FCD7-CDCC-4943-9E11-9C2CC8FA9FC4}.Release|Win32.ActiveCfg = Release|Any CPU {C2306552-6C42-464C-8981-32FEF4F9458D}.Debug|Any CPU.ActiveCfg = Debug|Win32 {C2306552-6C42-464C-8981-32FEF4F9458D}.Debug|Mixed Platforms.ActiveCfg = Debug|x64 @@ -639,11 +631,9 @@ Global {4B299721-18EA-4B6D-AFD5-2D6E188B97BD}.Release|Win32.ActiveCfg = Release|Any CPU {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Debug|Win32.ActiveCfg = Debug|Any CPU {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Release|Any CPU.ActiveCfg = Release|Any CPU {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Release|Mixed Platforms.Build.0 = Release|Any CPU {7AF4B563-AAD3-42FF-B91E-84B9D34D904A}.Release|Win32.ActiveCfg = Release|Any CPU {F61D86B5-7C3D-4441-957D-A0A6D2FA69CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F61D86B5-7C3D-4441-957D-A0A6D2FA69CA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -655,11 +645,9 @@ Global {F61D86B5-7C3D-4441-957D-A0A6D2FA69CA}.Release|Win32.ActiveCfg = Release|Any CPU {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Debug|Win32.ActiveCfg = Debug|Any CPU {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Release|Any CPU.ActiveCfg = Release|Any CPU {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Release|Mixed Platforms.Build.0 = Release|Any CPU {09F32307-595A-4CBB-BF7C-F055DA1F70EE}.Release|Win32.ActiveCfg = Release|Any CPU {7732CB84-A39A-4ADF-B740-FD32A352FA8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7732CB84-A39A-4ADF-B740-FD32A352FA8A}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -802,12 +790,10 @@ Global {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Debug|Any CPU.Build.0 = Debug|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Debug|Win32.ActiveCfg = Debug|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Release|Any CPU.ActiveCfg = Release|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Release|Any CPU.Build.0 = Release|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Release|Mixed Platforms.Build.0 = Release|Any CPU {1BE90177-FE4D-4519-839E-7EB7D78AC973}.Release|Win32.ActiveCfg = Release|Any CPU {84DEB606-77ED-49CD-9AED-D2B13C1F5A1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {84DEB606-77ED-49CD-9AED-D2B13C1F5A1E}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -837,7 +823,6 @@ Global {3E7B5D96-CF71-41EE-8CF0-70D090873390}.Release|Any CPU.ActiveCfg = Release|Any CPU {3E7B5D96-CF71-41EE-8CF0-70D090873390}.Release|Any CPU.Build.0 = Release|Any CPU {3E7B5D96-CF71-41EE-8CF0-70D090873390}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3E7B5D96-CF71-41EE-8CF0-70D090873390}.Release|Mixed Platforms.Build.0 = Release|Any CPU {3E7B5D96-CF71-41EE-8CF0-70D090873390}.Release|Win32.ActiveCfg = Release|Any CPU {39AE9C77-E94B-404F-8768-B6261B3C1E0E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {39AE9C77-E94B-404F-8768-B6261B3C1E0E}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -882,12 +867,10 @@ Global {117BF9F8-D2D9-4D32-9702-251C3E038090}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Debug|Any CPU.Build.0 = Debug|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {117BF9F8-D2D9-4D32-9702-251C3E038090}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Debug|Win32.ActiveCfg = Debug|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Release|Any CPU.ActiveCfg = Release|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Release|Any CPU.Build.0 = Release|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {117BF9F8-D2D9-4D32-9702-251C3E038090}.Release|Mixed Platforms.Build.0 = Release|Any CPU {117BF9F8-D2D9-4D32-9702-251C3E038090}.Release|Win32.ActiveCfg = Release|Any CPU {C904D2C6-5A15-4E0B-8432-33967E1735AA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C904D2C6-5A15-4E0B-8432-33967E1735AA}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -902,12 +885,10 @@ Global {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Debug|Any CPU.Build.0 = Debug|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Debug|Win32.ActiveCfg = Debug|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Release|Any CPU.ActiveCfg = Release|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Release|Any CPU.Build.0 = Release|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Release|Mixed Platforms.Build.0 = Release|Any CPU {49AAA22D-D1C8-4E0F-82E8-F462D5442463}.Release|Win32.ActiveCfg = Release|Any CPU {BB9DEEEF-F18C-40D8-B016-6434CC71B8C3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BB9DEEEF-F18C-40D8-B016-6434CC71B8C3}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -922,12 +903,10 @@ Global {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Debug|Any CPU.Build.0 = Debug|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Debug|Win32.ActiveCfg = Debug|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Release|Any CPU.ActiveCfg = Release|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Release|Any CPU.Build.0 = Release|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E7B1B17F-D04B-4978-B504-A6BB3EE846C9}.Release|Win32.ActiveCfg = Release|Any CPU {16E02D45-5530-4617-97DC-BC3BDF77DE2C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {16E02D45-5530-4617-97DC-BC3BDF77DE2C}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -942,12 +921,10 @@ Global {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Debug|Any CPU.Build.0 = Debug|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Debug|Win32.ActiveCfg = Debug|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Release|Any CPU.ActiveCfg = Release|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Release|Any CPU.Build.0 = Release|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Release|Mixed Platforms.Build.0 = Release|Any CPU {0EA748AF-E1DC-4788-BA50-8BABD56F220C}.Release|Win32.ActiveCfg = Release|Any CPU {66581DAD-70AD-4475-AE47-C6C0DF1EC5E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {66581DAD-70AD-4475-AE47-C6C0DF1EC5E2}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -1012,12 +989,10 @@ Global {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Debug|Any CPU.Build.0 = Debug|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Debug|Win32.ActiveCfg = Debug|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Release|Any CPU.ActiveCfg = Release|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Release|Any CPU.Build.0 = Release|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Release|Mixed Platforms.Build.0 = Release|Any CPU {862C7C39-8E2B-4F18-88E9-ACD6EDF818CD}.Release|Win32.ActiveCfg = Release|Any CPU {A5DC820B-9554-45B6-9677-6A2F902E7787}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A5DC820B-9554-45B6-9677-6A2F902E7787}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -1032,12 +1007,10 @@ Global {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Debug|Any CPU.Build.0 = Debug|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Debug|Win32.ActiveCfg = Debug|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Release|Any CPU.ActiveCfg = Release|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Release|Any CPU.Build.0 = Release|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {4D13D69B-C8E8-4675-8198-1BE2785FFB6D}.Release|Win32.ActiveCfg = Release|Any CPU {E136B568-3E3F-498F-A8B4-2877B7768560}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E136B568-3E3F-498F-A8B4-2877B7768560}.Debug|Any CPU.Build.0 = Debug|Any CPU @@ -1156,37 +1129,31 @@ Global {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Debug|Any CPU.Build.0 = Debug|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Debug|Win32.ActiveCfg = Debug|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Debug|Win32.Build.0 = Debug|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Release|Any CPU.ActiveCfg = Release|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Release|Any CPU.Build.0 = Release|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Release|Mixed Platforms.Build.0 = Release|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Release|Win32.ActiveCfg = Release|Any CPU {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC}.Release|Win32.Build.0 = Release|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Debug|Any CPU.Build.0 = Debug|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Debug|Win32.ActiveCfg = Debug|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Debug|Win32.Build.0 = Debug|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Release|Any CPU.ActiveCfg = Release|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Release|Any CPU.Build.0 = Release|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Release|Mixed Platforms.Build.0 = Release|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Release|Win32.ActiveCfg = Release|Any CPU {570B0FF9-246F-4C6C-8384-F6BE1887A4A9}.Release|Win32.Build.0 = Release|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Debug|Any CPU.Build.0 = Debug|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Debug|Win32.ActiveCfg = Debug|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Debug|Win32.Build.0 = Debug|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Release|Any CPU.ActiveCfg = Release|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Release|Any CPU.Build.0 = Release|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Release|Win32.ActiveCfg = Release|Any CPU {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7}.Release|Win32.Build.0 = Release|Any CPU {75D71310-ECF7-4592-9E35-3FE540040982}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1240,25 +1207,21 @@ Global {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Debug|Any CPU.Build.0 = Debug|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Debug|Win32.ActiveCfg = Debug|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Debug|Win32.Build.0 = Debug|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Release|Any CPU.ActiveCfg = Release|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Release|Any CPU.Build.0 = Release|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Release|Mixed Platforms.Build.0 = Release|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Release|Win32.ActiveCfg = Release|Any CPU {370ADF53-DFFA-461E-B72A-1302C0A0DE00}.Release|Win32.Build.0 = Release|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Debug|Any CPU.Build.0 = Debug|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Debug|Win32.ActiveCfg = Debug|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Debug|Win32.Build.0 = Debug|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Release|Any CPU.ActiveCfg = Release|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Release|Any CPU.Build.0 = Release|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Release|Mixed Platforms.Build.0 = Release|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Release|Win32.ActiveCfg = Release|Any CPU {33CC6216-3F30-4B5A-BB29-C5B47EFFA713}.Release|Win32.Build.0 = Release|Any CPU {ACD2C831-BDA2-4512-B4CC-75E8E1804F73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1288,13 +1251,11 @@ Global {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Debug|Any CPU.Build.0 = Debug|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Debug|Win32.ActiveCfg = Debug|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Debug|Win32.Build.0 = Debug|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Release|Any CPU.ActiveCfg = Release|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Release|Any CPU.Build.0 = Release|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Release|Mixed Platforms.Build.0 = Release|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Release|Win32.ActiveCfg = Release|Any CPU {25F98E38-0249-45BC-B2ED-7899297B9CF6}.Release|Win32.Build.0 = Release|Any CPU {BF32DE1B-6276-4341-B212-F8862ADBBA7A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1312,13 +1273,11 @@ Global {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Debug|Any CPU.Build.0 = Debug|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Debug|Win32.ActiveCfg = Debug|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Debug|Win32.Build.0 = Debug|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Release|Any CPU.ActiveCfg = Release|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Release|Any CPU.Build.0 = Release|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Release|Mixed Platforms.Build.0 = Release|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Release|Win32.ActiveCfg = Release|Any CPU {16D8043D-C3DB-4868-BFF3-B2EBDF537AAA}.Release|Win32.Build.0 = Release|Any CPU {0BE7189B-F04E-4C0C-BBE9-F347C0A59FEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1336,13 +1295,11 @@ Global {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Debug|Any CPU.Build.0 = Debug|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Debug|Win32.ActiveCfg = Debug|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Debug|Win32.Build.0 = Debug|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Release|Any CPU.ActiveCfg = Release|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Release|Any CPU.Build.0 = Release|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Release|Mixed Platforms.Build.0 = Release|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Release|Win32.ActiveCfg = Release|Any CPU {4F0E7E04-F067-4CE8-B8C8-1105F319D123}.Release|Win32.Build.0 = Release|Any CPU {1123EAAD-3FE3-4FD8-8DF6-4DDCF13EFCFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1360,13 +1317,11 @@ Global {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Debug|Any CPU.Build.0 = Debug|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Debug|Win32.ActiveCfg = Debug|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Debug|Win32.Build.0 = Debug|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Release|Any CPU.ActiveCfg = Release|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Release|Any CPU.Build.0 = Release|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Release|Win32.ActiveCfg = Release|Any CPU {A1A3EB96-46CE-4F2F-A3B6-EF869043DD49}.Release|Win32.Build.0 = Release|Any CPU {53782603-3096-40C2-ABD3-F8F311BAE4BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1384,25 +1339,21 @@ Global {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Debug|Any CPU.Build.0 = Debug|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Debug|Win32.ActiveCfg = Debug|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Debug|Win32.Build.0 = Debug|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Release|Any CPU.ActiveCfg = Release|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Release|Any CPU.Build.0 = Release|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Release|Win32.ActiveCfg = Release|Any CPU {E8C458AE-7B42-4DCE-B326-7F3A9065EA19}.Release|Win32.Build.0 = Release|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Debug|Any CPU.Build.0 = Debug|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Debug|Win32.ActiveCfg = Debug|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Debug|Win32.Build.0 = Debug|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Release|Any CPU.ActiveCfg = Release|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Release|Any CPU.Build.0 = Release|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Release|Mixed Platforms.Build.0 = Release|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Release|Win32.ActiveCfg = Release|Any CPU {3C855DB2-EEA3-415C-A0A8-C834DEC40531}.Release|Win32.Build.0 = Release|Any CPU {FBE1FA7B-E699-4BB2-9C8F-41F4C9F3F088}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1420,25 +1371,21 @@ Global {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Debug|Any CPU.Build.0 = Debug|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Debug|Win32.ActiveCfg = Debug|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Debug|Win32.Build.0 = Debug|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Release|Any CPU.ActiveCfg = Release|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Release|Any CPU.Build.0 = Release|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Release|Mixed Platforms.Build.0 = Release|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Release|Win32.ActiveCfg = Release|Any CPU {1AC5A693-3CC4-4450-AA76-70DA4F0C29DF}.Release|Win32.Build.0 = Release|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Debug|Any CPU.Build.0 = Debug|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Debug|Win32.ActiveCfg = Debug|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Debug|Win32.Build.0 = Debug|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Release|Any CPU.ActiveCfg = Release|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Release|Any CPU.Build.0 = Release|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Release|Mixed Platforms.Build.0 = Release|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Release|Win32.ActiveCfg = Release|Any CPU {A9A83BE5-271B-4347-9C4D-340FC3BD0B2B}.Release|Win32.Build.0 = Release|Any CPU {BD176B28-49CD-4FAD-A430-CDBCF1C2E514}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -1480,7 +1427,6 @@ Global {5BFE4386-3C42-4118-96C8-4B68441F1661}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5BFE4386-3C42-4118-96C8-4B68441F1661}.Debug|Any CPU.Build.0 = Debug|Any CPU {5BFE4386-3C42-4118-96C8-4B68441F1661}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {5BFE4386-3C42-4118-96C8-4B68441F1661}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {5BFE4386-3C42-4118-96C8-4B68441F1661}.Debug|Win32.ActiveCfg = Debug|Any CPU {5BFE4386-3C42-4118-96C8-4B68441F1661}.Debug|Win32.Build.0 = Debug|Any CPU {5BFE4386-3C42-4118-96C8-4B68441F1661}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -1540,13 +1486,11 @@ Global {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Debug|Any CPU.Build.0 = Debug|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU - {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Debug|Win32.ActiveCfg = Debug|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Debug|Win32.Build.0 = Debug|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Release|Any CPU.ActiveCfg = Release|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Release|Any CPU.Build.0 = Release|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU - {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Release|Mixed Platforms.Build.0 = Release|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Release|Win32.ActiveCfg = Release|Any CPU {2FC40214-A4AA-45DC-9C93-72ED800C40B0}.Release|Win32.Build.0 = Release|Any CPU {040F754C-17F4-4B5F-B974-93F1E39D107F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs index 6a56aeb082..700daddbc7 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs @@ -222,6 +222,9 @@ private void GameStudioLoaded(object sender, RoutedEventArgs e) // Open assets that were being edited in the previous session ReopenAssetEditors(dockingLayout.LoadOpenAssets().ToList()).Forget(); + // Make room for an autohiding taskbar so it doesn't get covered + this.MaxHeight = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Size.Height - 2.0; + // Listen to clipboard ClipboardMonitor.RegisterListener(this); // Notify start diff --git a/sources/presentation/Xenko.Core.Presentation/Extensions/WindowHelper.cs b/sources/presentation/Xenko.Core.Presentation/Extensions/WindowHelper.cs index 33d4c6e8bc..99609c3cb7 100644 --- a/sources/presentation/Xenko.Core.Presentation/Extensions/WindowHelper.cs +++ b/sources/presentation/Xenko.Core.Presentation/Extensions/WindowHelper.cs @@ -127,7 +127,7 @@ public static Rect GetWorkArea([NotNull] this Window window) var monitor = GetMonitorInfo(new WindowInteropHelper(window).Handle); if (monitor == null) return Rect.Empty; - + var area = (Rect)monitor.rcWork; var rect = window.RectFromScreen(ref area); rect.Offset(window.Left, window.Top); From b20e0e54125b9cde95bcec9b23f02808968a0be1 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 27 Feb 2019 03:17:17 +0000 Subject: [PATCH 0016/2038] unlocking openvr for vulkan --- .../engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 15 ++++++++------- .../Xenko.VirtualReality/OpenVR/OpenVROverlay.cs | 2 +- .../Xenko.VirtualReality/OpenVR/OpenVrHmd.cs | 2 +- .../OpenVR/OpenVrTouchController.cs | 2 +- .../OpenVR/OpenVrTrackedDevice.cs | 2 +- .../engine/Xenko.VirtualReality/VRDeviceSystem.cs | 2 +- 6 files changed, 13 insertions(+), 12 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index b56700cda7..74ddbbaf50 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -1,6 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 +#if XENKO_PLATFORM_WINDOWS_DESKTOP using System; using System.Text; @@ -231,7 +231,7 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport { eType = ETextureType.Vulkan, eColorSpace = EColorSpace.Auto, - handle = texture.NativeResource.NativePointer, + handle = texture.SharedHandle, //texture.NativeResource.NativePointer, }; var bounds = new VRTextureBounds_t { @@ -403,11 +403,12 @@ public static void HideMirror() public static Texture GetMirrorTexture(GraphicsDevice device, int eyeIndex) { - var nativeDevice = device.NativeDevice.NativePointer; - var eyeTexSrv = IntPtr.Zero; - Valve.VR.OpenVR.Compositor.GetMirrorTextureD3D11(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, nativeDevice, ref eyeTexSrv); + // unfortunately no mirror function for Vulkan..? see https://github.com/ValveSoftware/openvr/issues/1053 + //var nativeDevice = device.NativeDevice.NativePointer; + //var eyeTexSrv = IntPtr.Zero; + //Valve.VR.OpenVR.Compositor.GetMirrorTextureD3D11(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, nativeDevice, ref eyeTexSrv); var tex = new Texture(device); - tex.InitializeFromImpl(new ShaderResourceView(eyeTexSrv)); + //tex.InitializeFromImpl(new ShaderResourceView(eyeTexSrv)); return tex; } @@ -430,7 +431,7 @@ public static bool SubmitOverlay(ulong overlayId, Texture texture) { eType = ETextureType.Vulkan, eColorSpace = EColorSpace.Auto, - handle = texture.NativeResource.NativePointer, + handle = texture.SharedHandle, //texture.NativeResource.NativePointer, }; return Valve.VR.OpenVR.Overlay.SetOverlayTexture(overlayId, ref tex) == EVROverlayError.None; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVROverlay.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVROverlay.cs index 1dea5ffb85..124c728387 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVROverlay.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVROverlay.cs @@ -1,6 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 +#if XENKO_PLATFORM_WINDOWS_DESKTOP using Xenko.Core.Mathematics; using Xenko.Graphics; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs index f4af4949c6..0dfc1bd711 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs @@ -1,6 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 +#if XENKO_PLATFORM_WINDOWS_DESKTOP using Xenko.Core.Mathematics; using Xenko.Games; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs index 701d375f27..409e7cc6c1 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs @@ -1,6 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 +#if XENKO_PLATFORM_WINDOWS_DESKTOP using System; using Xenko.Core.Mathematics; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTrackedDevice.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTrackedDevice.cs index 972c4ef18f..6e580ca3d6 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTrackedDevice.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTrackedDevice.cs @@ -1,6 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 +#if XENKO_PLATFORM_WINDOWS_DESKTOP using System; using Xenko.Core.Mathematics; diff --git a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs index 676b73e312..7de8ded580 100644 --- a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs +++ b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs @@ -75,7 +75,7 @@ private void OnEnabledChanged(object sender, EventArgs eventArgs) } case VRApi.OpenVR: { -#if XENKO_GRAPHICS_API_DIRECT3D11 +#if XENKO_PLATFORM_WINDOWS_DESKTOP Device = new OpenVRHmd(); #endif break; From e3c9e32b0602a4788406600a5b02debea4bfcb5a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 28 Feb 2019 20:55:58 +0000 Subject: [PATCH 0017/2038] set texture SharedHandle --- sources/engine/Xenko.Graphics/Vulkan/Texture.Vulkan.cs | 3 +++ sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/Texture.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/Texture.Vulkan.cs index bb0b1fa9b9..d08c52ef4c 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/Texture.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/Texture.Vulkan.cs @@ -206,6 +206,7 @@ private unsafe void CreateBuffer() if (NativeMemory != DeviceMemory.Null) { GraphicsDevice.NativeDevice.BindBufferMemory(NativeBuffer, NativeMemory, 0); + SharedHandle = NativeMemory.NativeHandle; } } @@ -269,6 +270,7 @@ private unsafe void CreateImage() if (NativeMemory != DeviceMemory.Null) { GraphicsDevice.NativeDevice.BindImageMemory(NativeImage, NativeMemory, 0); + SharedHandle = NativeMemory.NativeHandle; } } @@ -394,6 +396,7 @@ protected internal override void OnDestroyed() { GraphicsDevice.Collect(NativeMemory); NativeMemory = DeviceMemory.Null; + SharedHandle = IntPtr.Zero; } if (NativeImage != SharpVulkan.Image.Null) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index 74ddbbaf50..93b528dceb 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -231,7 +231,7 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport { eType = ETextureType.Vulkan, eColorSpace = EColorSpace.Auto, - handle = texture.SharedHandle, //texture.NativeResource.NativePointer, + handle = texture.SharedHandle, }; var bounds = new VRTextureBounds_t { From 3a87b36e5785e2bf526083cfd9b0a602a99142b5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 6 Mar 2019 16:54:08 +0000 Subject: [PATCH 0018/2038] progress on Vulkan for OpenVR, still not done --- .../Rendering/Compositing/ForwardRenderer.cs | 9 ++- .../Xenko.VirtualReality/OpenVR/OpenVR.cs | 68 +++++++++++++++---- .../Xenko.VirtualReality/OpenVR/OpenVrHmd.cs | 14 +++- .../Xenko.VirtualReality/VRDeviceSystem.cs | 2 +- .../Xenko.VirtualReality.csproj | 22 ++++++ 5 files changed, 96 insertions(+), 19 deletions(-) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index 704d60e29b..37289e9ae1 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -172,7 +172,14 @@ protected override void InitializeCore() } vrSystem.PreferredScalings = preferredScalings; - vrSystem.RequireMirror = VRSettings.CopyMirror; +#if XENKO_GRAPHICS_API_VULKAN + // no mirror support for vulkan + vrSystem.RequireMirror = false; + VRSettings.CopyMirror = false; +#else + vrSystem.RequireMirror = VRSettings.CopyMirror; +#endif + vrSystem.MirrorWidth = GraphicsDevice.Presenter.BackBuffer.Width; vrSystem.MirrorHeight = GraphicsDevice.Presenter.BackBuffer.Height; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index 93b528dceb..3b0d0164bc 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -4,15 +4,20 @@ using System; using System.Text; +#if XENKO_GRAPHICS_API_DIRECT3D11 using SharpDX.Direct3D11; +#elif XENKO_GRAPHICS_API_VULKAN +using SharpVulkan; +#endif using Valve.VR; using Xenko.Core; using Xenko.Core.Mathematics; +using Xenko.Games; using Xenko.Graphics; namespace Xenko.VirtualReality { - internal static class OpenVR + public static class OpenVR { public class Controller { @@ -201,6 +206,22 @@ static OpenVR() public static bool InitDone = false; +#if XENKO_GRAPHICS_API_VULKAN + private static unsafe VRVulkanTextureData_t vkTexData; + public static bool InitVulkan(GameBase baseGame) { + vkTexData = new VRVulkanTextureData_t { + m_pDevice = baseGame.GraphicsDevice.NativeDevice.NativeHandle, // struct VkDevice_T * + m_pPhysicalDevice = baseGame.GraphicsDevice.NativePhysicalDevice.NativeHandle, // struct VkPhysicalDevice_T * + m_pInstance = baseGame.GraphicsDevice.NativeInstance.PhysicalDevices[0].NativeHandle, // struct VkInstance_T * + m_pQueue = baseGame.GraphicsDevice.NativeDevice.GetQueue(0, 0).NativeHandle, // struct VkQueue_T * + m_nQueueFamilyIndex = 0, + m_nFormat = (uint)37, //VkFormat.VK_FORMAT_R8G8B8A8_UNORM (37) + m_nSampleCount = 1 + }; + return false; + } +#endif + public static bool Init() { var err = EVRInitError.None; @@ -212,8 +233,7 @@ public static bool Init() InitDone = true; - //this makes the camera behave like oculus rift default! - Valve.VR.OpenVR.Compositor.SetTrackingSpace(ETrackingUniverseOrigin.TrackingUniverseSeated); + Valve.VR.OpenVR.Compositor.SetTrackingSpace(ETrackingUniverseOrigin.TrackingUniverseStanding); return true; } @@ -227,21 +247,35 @@ public static void Shutdown() public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport) { - var tex = new Texture_t - { - eType = ETextureType.Vulkan, - eColorSpace = EColorSpace.Auto, - handle = texture.SharedHandle, - }; - var bounds = new VRTextureBounds_t - { + var bounds = new VRTextureBounds_t { uMin = viewport.X, uMax = viewport.Width, vMin = viewport.Y, vMax = viewport.Height, }; +#if XENKO_GRAPHICS_API_VULKAN + vkTexData.m_nHeight = (uint)texture.Height; + vkTexData.m_nWidth = (uint)texture.Width; + unsafe { + fixed(VRVulkanTextureData_t* vkAddress = &vkTexData) { + var tex = new Texture_t { + eType = ETextureType.Vulkan, + handle = (IntPtr)vkAddress, + eColorSpace = EColorSpace.Auto, + }; + + return Valve.VR.OpenVR.Compositor.Submit(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, ref tex, ref bounds, EVRSubmitFlags.Submit_Default) == EVRCompositorError.None; + } + } +#elif XENKO_GRAPHICS_API_DIRECT3D11 + var tex = new Texture_t { + eType = ETextureType.DirectX, + handle = texture.SharedHandle, + eColorSpace = EColorSpace.Auto, + }; return Valve.VR.OpenVR.Compositor.Submit(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, ref tex, ref bounds, EVRSubmitFlags.Submit_Default) == EVRCompositorError.None; +#endif } public static void GetEyeToHead(int eyeIndex, out Matrix pose) @@ -403,13 +437,17 @@ public static void HideMirror() public static Texture GetMirrorTexture(GraphicsDevice device, int eyeIndex) { +#if XENKO_GRAPHICS_API_VULKAN // unfortunately no mirror function for Vulkan..? see https://github.com/ValveSoftware/openvr/issues/1053 - //var nativeDevice = device.NativeDevice.NativePointer; - //var eyeTexSrv = IntPtr.Zero; - //Valve.VR.OpenVR.Compositor.GetMirrorTextureD3D11(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, nativeDevice, ref eyeTexSrv); + return new Texture(device); +#else + var nativeDevice = device.NativeDevice.NativePointer; + var eyeTexSrv = IntPtr.Zero; + Valve.VR.OpenVR.Compositor.GetMirrorTextureD3D11(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, nativeDevice, ref eyeTexSrv); var tex = new Texture(device); - //tex.InitializeFromImpl(new ShaderResourceView(eyeTexSrv)); + tex.InitializeFromImpl(new ShaderResourceView(eyeTexSrv)); return tex; +#endif } public static ulong CreateOverlay() diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs index 0dfc1bd711..1bc03c9ebe 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs @@ -8,7 +8,7 @@ namespace Xenko.VirtualReality { - internal class OpenVRHmd : VRDevice + public class OpenVRHmd : VRDevice { private RectangleF leftView = new RectangleF(0.0f, 0.0f, 0.5f, 1.0f); private RectangleF rightView = new RectangleF(0.5f, 0.0f, 1.0f, 1.0f); @@ -25,11 +25,13 @@ internal class OpenVRHmd : VRDevice private Vector3 currentHeadLinearVelocity; private Vector3 currentHeadAngularVelocity; private Quaternion currentHeadRot; + private GameBase mainGame; public override bool CanInitialize => OpenVR.InitDone || OpenVR.Init(); - public OpenVRHmd() + public OpenVRHmd(GameBase game) { + mainGame = game; VRApi = VRApi.OpenVR; SupportsOverlays = true; } @@ -43,7 +45,11 @@ public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphic ActualRenderFrameSize = new Size2(width, height); +#if XENKO_GRAPHICS_API_VULKAN + needsMirror = false; // Vulkan doesn't support mirrors :/ +#else needsMirror = requireMirror; +#endif if (needsMirror) { @@ -60,6 +66,10 @@ public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphic trackedDevices = new OpenVRTrackedDevice[Valve.VR.OpenVR.k_unMaxTrackedDeviceCount]; for (int i=0; i + + + + + + + False + $(XenkoDependenciesDir)\SharpVulkan\$(XenkoPlatform)\SharpVulkan.dll + + + + + + + False + $(XenkoDependenciesDir)\SharpVulkan\Other\SharpVulkan.dll + + + + + + Properties\SharedAssemblyInfo.cs From ecc05c23954fa90345bf48ec24a5ecb1866a3e41 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 7 Mar 2019 01:31:50 +0000 Subject: [PATCH 0019/2038] more Vulkan+OpenVR progress, not working yet tho --- sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index 3b0d0164bc..f569e9cd70 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -212,11 +212,11 @@ public static bool InitVulkan(GameBase baseGame) { vkTexData = new VRVulkanTextureData_t { m_pDevice = baseGame.GraphicsDevice.NativeDevice.NativeHandle, // struct VkDevice_T * m_pPhysicalDevice = baseGame.GraphicsDevice.NativePhysicalDevice.NativeHandle, // struct VkPhysicalDevice_T * - m_pInstance = baseGame.GraphicsDevice.NativeInstance.PhysicalDevices[0].NativeHandle, // struct VkInstance_T * + m_pInstance = baseGame.GraphicsDevice.NativeInstance.NativeHandle, // struct VkInstance_T * m_pQueue = baseGame.GraphicsDevice.NativeDevice.GetQueue(0, 0).NativeHandle, // struct VkQueue_T * m_nQueueFamilyIndex = 0, m_nFormat = (uint)37, //VkFormat.VK_FORMAT_R8G8B8A8_UNORM (37) - m_nSampleCount = 1 + m_nSampleCount = 4 }; return false; } From e3e4baa8aceec5835bf7d44aa300353ea0b88f13 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 7 Mar 2019 02:17:07 +0000 Subject: [PATCH 0020/2038] adding nativeimage handle... --- sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index f569e9cd70..c8d147efb7 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -256,6 +256,7 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport #if XENKO_GRAPHICS_API_VULKAN vkTexData.m_nHeight = (uint)texture.Height; vkTexData.m_nWidth = (uint)texture.Width; + vkTexData.m_nImage = (ulong)texture.NativeImage.NativeHandle; unsafe { fixed(VRVulkanTextureData_t* vkAddress = &vkTexData) { var tex = new Texture_t { From 2752fce90b6852341e4a50280d47d73d6be5ef1d Mon Sep 17 00:00:00 2001 From: dfkeenan Date: Sat, 9 Mar 2019 22:23:29 +1000 Subject: [PATCH 0021/2038] Start work on new Add component control. --- .../View/AddEntityComponentUserControl.xaml | 153 ++++++++++++++++++ .../AddEntityComponentUserControl.xaml.cs | 43 +++++ .../View/EntityPropertyTemplates.xaml | 8 +- .../Xenko.Assets.Presentation.csproj | 14 +- 4 files changed, 214 insertions(+), 4 deletions(-) create mode 100644 sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml create mode 100644 sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml.cs diff --git a/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml b/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml new file mode 100644 index 0000000000..7db27161d3 --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml.cs b/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml.cs new file mode 100644 index 0000000000..0e36eab3ca --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml.cs @@ -0,0 +1,43 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using Xenko.Core.Presentation.Extensions; + +namespace Xenko.Assets.Presentation.View +{ + /// + /// Interaction logic for AddEntityComponentUserControl.xaml + /// + public partial class AddEntityComponentUserControl : UserControl + { + public const double ComponentListWidth = 500.0; + + public AddEntityComponentUserControl() + { + InitializeComponent(); + //FilteringComboBox.Loaded += ControlLoaded; + } + + //private void ControlLoaded(object sender, RoutedEventArgs e) + //{ + // FilteringComboBox.SelectedIndex = -1; + // FilteringComboBox.Text = ""; + // var groupList = this.FindVisualChildrenOfType().FirstOrDefault(x => x.Name == "GroupList"); + // if (groupList != null) + // groupList.SelectedIndex = -1; + //} + } +} diff --git a/sources/editor/Xenko.Assets.Presentation/View/EntityPropertyTemplates.xaml b/sources/editor/Xenko.Assets.Presentation/View/EntityPropertyTemplates.xaml index 7fcc0f7f30..4539bec37b 100644 --- a/sources/editor/Xenko.Assets.Presentation/View/EntityPropertyTemplates.xaml +++ b/sources/editor/Xenko.Assets.Presentation/View/EntityPropertyTemplates.xaml @@ -12,7 +12,8 @@ xmlns:data="clr-namespace:Xenko.Data;assembly=Xenko" xmlns:xk="http://schemas.xenko.com/xaml/presentation" xmlns:assetCommands="clr-namespace:Xenko.Core.Assets.Editor.Quantum.NodePresenters.Commands;assembly=Xenko.Core.Assets.Editor" - xmlns:qvm="clr-namespace:Xenko.Core.Presentation.Quantum.ViewModels;assembly=Xenko.Core.Presentation.Quantum"> + xmlns:qvm="clr-namespace:Xenko.Core.Presentation.Quantum.ViewModels;assembly=Xenko.Core.Presentation.Quantum" + xmlns:localView="clr-namespace:Xenko.Assets.Presentation.View"> @@ -120,7 +121,8 @@ - + diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj index 5483d409b0..710e1f0df4 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj @@ -1,4 +1,4 @@ - + @@ -164,6 +164,9 @@ ScriptNameWindow.xaml + + AddEntityComponentUserControl.xaml + DebugEntityHierarchyEditorUserControl.xaml @@ -372,6 +375,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + Designer MSBuild:Compile @@ -785,6 +792,11 @@ + + + MSBuild:Compile + + From 712ef39276f34881f659ec1b752f0380a39172b0 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 9 Mar 2019 16:56:01 +0000 Subject: [PATCH 0022/2038] OpenVR and Vulkan working! --- .../Vulkan/GraphicsAdapterFactory.Vulkan.cs | 36 ++++++++++--------- .../Xenko.VirtualReality/OpenVR/OpenVR.cs | 8 +++-- 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/GraphicsAdapterFactory.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/GraphicsAdapterFactory.Vulkan.cs index 9d68fffcd3..c95110129e 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/GraphicsAdapterFactory.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/GraphicsAdapterFactory.Vulkan.cs @@ -151,24 +151,28 @@ public unsafe GraphicsAdapterFactoryInstance(bool enableValidation) desiredExtensionNames.Add("VK_KHR_win32_surface"); if (!availableExtensionNames.Contains("VK_KHR_win32_surface")) throw new InvalidOperationException("Required extension VK_KHR_win32_surface is not available"); + + // set OpenVR extensions required + desiredExtensionNames.Add("VK_NV_external_memory_capabilities"); + #elif XENKO_PLATFORM_ANDROID - desiredExtensionNames.Add("VK_KHR_android_surface"); - if (!availableExtensionNames.Contains("VK_KHR_android_surface")) - throw new InvalidOperationException("Required extension VK_KHR_android_surface is not available"); + desiredExtensionNames.Add("VK_KHR_android_surface"); + if (!availableExtensionNames.Contains("VK_KHR_android_surface")) + throw new InvalidOperationException("Required extension VK_KHR_android_surface is not available"); #elif XENKO_PLATFORM_LINUX - if (availableExtensionNames.Contains("VK_KHR_xlib_surface")) - { - desiredExtensionNames.Add("VK_KHR_xlib_surface"); - HasXlibSurfaceSupport = true; - } - else if (availableExtensionNames.Contains("VK_KHR_xcb_surface")) - { - desiredExtensionNames.Add("VK_KHR_xcb_surface"); - } - else - { - throw new InvalidOperationException("None of the supported surface extensions VK_KHR_xcb_surface or VK_KHR_xlib_surface is available"); - } + if (availableExtensionNames.Contains("VK_KHR_xlib_surface")) + { + desiredExtensionNames.Add("VK_KHR_xlib_surface"); + HasXlibSurfaceSupport = true; + } + else if (availableExtensionNames.Contains("VK_KHR_xcb_surface")) + { + desiredExtensionNames.Add("VK_KHR_xcb_surface"); + } + else + { + throw new InvalidOperationException("None of the supported surface extensions VK_KHR_xcb_surface or VK_KHR_xlib_surface is available"); + } #endif bool enableDebugReport = enableValidation && availableExtensionNames.Contains("VK_EXT_debug_report"); if (enableDebugReport) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index c8d147efb7..fca86e806e 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -216,9 +216,9 @@ public static bool InitVulkan(GameBase baseGame) { m_pQueue = baseGame.GraphicsDevice.NativeDevice.GetQueue(0, 0).NativeHandle, // struct VkQueue_T * m_nQueueFamilyIndex = 0, m_nFormat = (uint)37, //VkFormat.VK_FORMAT_R8G8B8A8_UNORM (37) - m_nSampleCount = 4 }; - return false; + Valve.VR.OpenVR.Compositor.SetExplicitTimingMode(EVRCompositorTimingMode.Explicit_ApplicationPerformsPostPresentHandoff); + return true; } #endif @@ -257,6 +257,7 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport vkTexData.m_nHeight = (uint)texture.Height; vkTexData.m_nWidth = (uint)texture.Width; vkTexData.m_nImage = (ulong)texture.NativeImage.NativeHandle; + vkTexData.m_nSampleCount = texture.IsMultisample ? (uint)texture.MultisampleCount : 1; unsafe { fixed(VRVulkanTextureData_t* vkAddress = &vkTexData) { var tex = new Texture_t { @@ -265,6 +266,7 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport eColorSpace = EColorSpace.Auto, }; + Valve.VR.OpenVR.Compositor.SubmitExplicitTimingData(); return Valve.VR.OpenVR.Compositor.Submit(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, ref tex, ref bounds, EVRSubmitFlags.Submit_Default) == EVRCompositorError.None; } } @@ -274,7 +276,6 @@ public static bool Submit(int eyeIndex, Texture texture, ref RectangleF viewport handle = texture.SharedHandle, eColorSpace = EColorSpace.Auto, }; - return Valve.VR.OpenVR.Compositor.Submit(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, ref tex, ref bounds, EVRSubmitFlags.Submit_Default) == EVRCompositorError.None; #endif } @@ -294,6 +295,7 @@ private static unsafe void GetEyeToHeadUnsafe(int eyeIndex, out Matrix pose) public static void UpdatePoses() { + Valve.VR.OpenVR.Compositor.PostPresentHandoff(); Valve.VR.OpenVR.Compositor.WaitGetPoses(DevicePoses, GamePoses); } From a20cfe329e69c906da90af82b55cbc788fb3e389 Mon Sep 17 00:00:00 2001 From: phr00t Date: Sat, 9 Mar 2019 17:28:40 -0500 Subject: [PATCH 0023/2038] adding lock/bak/routerlog to ignore --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 32eaa513ce..10a5304a4f 100644 --- a/.gitignore +++ b/.gitignore @@ -154,3 +154,6 @@ fastlane/report.xml fastlane/screenshots *.user project.lock.json +*.lock +*.bak +routerlog.txt From e50d13d90a246a8e0a774c4b72b58e7d0161a01f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 10 Mar 2019 18:40:58 +0100 Subject: [PATCH 0024/2038] VR now uses proper OpenVR resolution and headset display rate --- .../Xenko.VirtualReality/OpenVR/OpenVrHmd.cs | 25 ++++++++++++++++--- .../Xenko.VirtualReality/VRDeviceSystem.cs | 11 ++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs index 1bc03c9ebe..c2cf313991 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs @@ -26,6 +26,7 @@ public class OpenVRHmd : VRDevice private Vector3 currentHeadAngularVelocity; private Quaternion currentHeadRot; private GameBase mainGame; + private int HMDindex; public override bool CanInitialize => OpenVR.InitDone || OpenVR.Init(); @@ -38,9 +39,10 @@ public OpenVRHmd(GameBase game) public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight) { - var width = (int)(OptimalRenderFrameSize.Width * RenderFrameScaling); + Size2 renderSize = OptimalRenderFrameSize; + var width = (int)(renderSize.Width * RenderFrameScaling); width += width % 2; - var height = (int)(OptimalRenderFrameSize.Height * RenderFrameScaling); + var height = (int)(renderSize.Height * RenderFrameScaling); height += height % 2; ActualRenderFrameSize = new Size2(width, height); @@ -64,8 +66,12 @@ public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphic rightHandController = new OpenVRTouchController(TouchControllerHand.Right); trackedDevices = new OpenVRTrackedDevice[Valve.VR.OpenVR.k_unMaxTrackedDeviceCount]; - for (int i=0; i new Size2(2160, 1200); + public override Size2 OptimalRenderFrameSize { + get { + uint width = 0, height = 0; + Valve.VR.OpenVR.System.GetRecommendedRenderTargetSize(ref width, ref height); + return new Size2((int)width, (int)height); + } + } + + public float RefreshRate() { + Valve.VR.ETrackedPropertyError err = default; + return Valve.VR.OpenVR.System.GetFloatTrackedDeviceProperty((uint)HMDindex, Valve.VR.ETrackedDeviceProperty.Prop_DisplayFrequency_Float, ref err); + } public override void Dispose() { diff --git a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs index c988a4cafe..dbecb09454 100644 --- a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs +++ b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs @@ -50,6 +50,8 @@ private void OnEnabledChanged(object sender, EventArgs eventArgs) return; } + float refreshRate = 90f; + if (physicalDeviceInUse) { Device = null; @@ -129,9 +131,18 @@ private void OnEnabledChanged(object sender, EventArgs eventArgs) var deviceManager = (GraphicsDeviceManager)Services.GetService(); if (Device != null) { + Game.IsFixedTimeStep = true; + Game.IsDrawDesynchronized = true; + deviceManager.SynchronizeWithVerticalRetrace = false; + Device.RenderFrameScaling = PreferredScalings[Device.VRApi]; Device.Enable(GraphicsDevice, deviceManager, RequireMirror, MirrorWidth, MirrorHeight); physicalDeviceInUse = true; + +#if XENKO_PLATFORM_WINDOWS_DESKTOP + if (Device is OpenVRHmd) refreshRate = ((OpenVRHmd)Device).RefreshRate(); +#endif + Game.TargetElapsedTime = TimeSpan.FromSeconds(1 / refreshRate); } else { From a3fb675e7af740291ba51e84a49295c33e8b80ed Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 12 Mar 2019 00:08:53 +0100 Subject: [PATCH 0025/2038] dynamically pick mirror support instead of using compiler directives --- .../Rendering/Compositing/ForwardRenderer.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index 37289e9ae1..6e0cfe3a2c 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -172,13 +172,13 @@ protected override void InitializeCore() } vrSystem.PreferredScalings = preferredScalings; -#if XENKO_GRAPHICS_API_VULKAN - // no mirror support for vulkan - vrSystem.RequireMirror = false; - VRSettings.CopyMirror = false; -#else - vrSystem.RequireMirror = VRSettings.CopyMirror; -#endif + if( GraphicsDevice.Platform == GraphicsPlatform.Vulkan ) { + // no mirror support for vulkan + vrSystem.RequireMirror = false; + VRSettings.CopyMirror = false; + } else { + vrSystem.RequireMirror = VRSettings.CopyMirror; + } vrSystem.MirrorWidth = GraphicsDevice.Presenter.BackBuffer.Width; vrSystem.MirrorHeight = GraphicsDevice.Presenter.BackBuffer.Height; From fa648753715837a5b94d122e7347afc70a02db84 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 14 Mar 2019 02:25:09 +0100 Subject: [PATCH 0026/2038] tweak to openvr mirror texture compiler directives --- sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index fca86e806e..f1716ec8e8 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -440,16 +440,16 @@ public static void HideMirror() public static Texture GetMirrorTexture(GraphicsDevice device, int eyeIndex) { -#if XENKO_GRAPHICS_API_VULKAN - // unfortunately no mirror function for Vulkan..? see https://github.com/ValveSoftware/openvr/issues/1053 - return new Texture(device); -#else +#if XENKO_GRAPHICS_API_DIRECT3D11 var nativeDevice = device.NativeDevice.NativePointer; var eyeTexSrv = IntPtr.Zero; Valve.VR.OpenVR.Compositor.GetMirrorTextureD3D11(eyeIndex == 0 ? EVREye.Eye_Left : EVREye.Eye_Right, nativeDevice, ref eyeTexSrv); var tex = new Texture(device); tex.InitializeFromImpl(new ShaderResourceView(eyeTexSrv)); return tex; +#else + // unfortunately no mirror function for Vulkan (not implemented for OpenGL) see https://github.com/ValveSoftware/openvr/issues/1053 + return new Texture(device); #endif } From da35e31de9604d762dad08fee0ae10b3694bdea4 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 15 Mar 2019 21:37:04 +0100 Subject: [PATCH 0027/2038] revert old commit --- .../Xenko.Core.Assets.CompilerApp.csproj | 1 - .../core/Xenko.Core.Mathematics/Xenko.Core.Mathematics.csproj | 3 --- sources/editor/Xenko.Editor/Xenko.Editor.csproj | 1 - sources/engine/Xenko.Assets/Xenko.Assets.csproj | 1 - sources/engine/Xenko.Navigation/Xenko.Navigation.csproj | 3 --- .../Xenko.Physics.Tests/Xenko.Physics.Tests.Windows.csproj | 3 --- sources/engine/Xenko.Physics/Xenko.Physics.csproj | 4 +--- 7 files changed, 1 insertion(+), 15 deletions(-) diff --git a/sources/assets/Xenko.Core.Assets.CompilerApp/Xenko.Core.Assets.CompilerApp.csproj b/sources/assets/Xenko.Core.Assets.CompilerApp/Xenko.Core.Assets.CompilerApp.csproj index 5f6d8e623a..90319295e8 100644 --- a/sources/assets/Xenko.Core.Assets.CompilerApp/Xenko.Core.Assets.CompilerApp.csproj +++ b/sources/assets/Xenko.Core.Assets.CompilerApp/Xenko.Core.Assets.CompilerApp.csproj @@ -25,7 +25,6 @@ x64 - diff --git a/sources/core/Xenko.Core.Mathematics/Xenko.Core.Mathematics.csproj b/sources/core/Xenko.Core.Mathematics/Xenko.Core.Mathematics.csproj index a73b886ea8..63fecc3627 100644 --- a/sources/core/Xenko.Core.Mathematics/Xenko.Core.Mathematics.csproj +++ b/sources/core/Xenko.Core.Mathematics/Xenko.Core.Mathematics.csproj @@ -25,9 +25,6 @@ Properties\SharedAssemblyInfo.cs - - - diff --git a/sources/editor/Xenko.Editor/Xenko.Editor.csproj b/sources/editor/Xenko.Editor/Xenko.Editor.csproj index fa305a1749..107700901b 100644 --- a/sources/editor/Xenko.Editor/Xenko.Editor.csproj +++ b/sources/editor/Xenko.Editor/Xenko.Editor.csproj @@ -17,7 +17,6 @@ - diff --git a/sources/engine/Xenko.Assets/Xenko.Assets.csproj b/sources/engine/Xenko.Assets/Xenko.Assets.csproj index 47df0c66be..a14db34717 100644 --- a/sources/engine/Xenko.Assets/Xenko.Assets.csproj +++ b/sources/engine/Xenko.Assets/Xenko.Assets.csproj @@ -14,7 +14,6 @@ XENKO_VIDEO_FFMPEG;$(DefineConstants) - diff --git a/sources/engine/Xenko.Navigation/Xenko.Navigation.csproj b/sources/engine/Xenko.Navigation/Xenko.Navigation.csproj index d7788f2ad8..cc87fff568 100644 --- a/sources/engine/Xenko.Navigation/Xenko.Navigation.csproj +++ b/sources/engine/Xenko.Navigation/Xenko.Navigation.csproj @@ -42,9 +42,6 @@ - - - diff --git a/sources/engine/Xenko.Physics.Tests/Xenko.Physics.Tests.Windows.csproj b/sources/engine/Xenko.Physics.Tests/Xenko.Physics.Tests.Windows.csproj index b00f52756d..34e2aacad4 100644 --- a/sources/engine/Xenko.Physics.Tests/Xenko.Physics.Tests.Windows.csproj +++ b/sources/engine/Xenko.Physics.Tests/Xenko.Physics.Tests.Windows.csproj @@ -42,9 +42,6 @@ - - - diff --git a/sources/engine/Xenko.Physics/Xenko.Physics.csproj b/sources/engine/Xenko.Physics/Xenko.Physics.csproj index eca797a6c3..864cd30766 100644 --- a/sources/engine/Xenko.Physics/Xenko.Physics.csproj +++ b/sources/engine/Xenko.Physics/Xenko.Physics.csproj @@ -40,12 +40,10 @@ Properties\SharedAssemblyInfo.cs - - - + From 15b9c295e125c00add8617dbb9ae463d6a1b1d2f Mon Sep 17 00:00:00 2001 From: dfkeenan Date: Sat, 9 Mar 2019 23:55:32 +1000 Subject: [PATCH 0028/2038] Make FilteringComboBox close when Escape key pressed even if list contains no items. --- .../Controls/FilteringComboBox.cs | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/sources/presentation/Xenko.Core.Presentation/Controls/FilteringComboBox.cs b/sources/presentation/Xenko.Core.Presentation/Controls/FilteringComboBox.cs index e9b5df9dc6..7d18327934 100644 --- a/sources/presentation/Xenko.Core.Presentation/Controls/FilteringComboBox.cs +++ b/sources/presentation/Xenko.Core.Presentation/Controls/FilteringComboBox.cs @@ -421,10 +421,28 @@ private void UpdateCollectionView() private void EditableTextBoxPreviewKeyDown(object sender, KeyEventArgs e) { + updatingSelection = true; + + if (e.Key == Key.Escape) + { + if (IsDropDownOpen) + { + IsDropDownOpen = false; + if (RequireSelectedItemToValidate) + editableTextBox.Cancel(); + } + else + { + editableTextBox.Cancel(); + } + } + if (listBox.Items.Count <= 0) + { + updatingSelection = false; return; + } - updatingSelection = true; var stackPanel = listBox.FindVisualChildOfType(); switch (e.Key) { From a17bb311fe9f925d74ed00f456f364a9000f548a Mon Sep 17 00:00:00 2001 From: dfkeenan Date: Sat, 16 Mar 2019 15:27:31 +1000 Subject: [PATCH 0029/2038] New Add component functionality basics working. Needs a better grouping method. --- .../Extensions/EnumerableExtensions.cs | 17 +++ .../Keys/EntityHierarchyData.cs | 4 + .../EntityHierarchyAssetNodeUpdater.cs | 11 +- .../View/AddEntityComponentUserControl.xaml | 13 ++- .../AddEntityComponentUserControl.xaml.cs | 106 ++++++++++++++++-- .../View/EntityPropertyTemplates.xaml | 4 +- .../Commands/AbstractNodeTypeGroup.cs | 79 +++++++++++++ 7 files changed, 216 insertions(+), 18 deletions(-) create mode 100644 sources/editor/Xenko.Core.Assets.Editor/Quantum/NodePresenters/Commands/AbstractNodeTypeGroup.cs diff --git a/sources/core/Xenko.Core/Extensions/EnumerableExtensions.cs b/sources/core/Xenko.Core/Extensions/EnumerableExtensions.cs index 0c8a47e94a..a2f3d099cc 100644 --- a/sources/core/Xenko.Core/Extensions/EnumerableExtensions.cs +++ b/sources/core/Xenko.Core/Extensions/EnumerableExtensions.cs @@ -149,5 +149,22 @@ internal static IEnumerable> EnumerateNodes([NotNull] this node = node.Next; } } + + /// + /// Calculates a combined hash code for items of the enumerbale. + /// + /// Generic type parameter. + /// Input enumerable to work on. + /// A combined hash code or 0 if the source is empty. + [Pure] + public static int ToHashCode(this IEnumerable source) where T : class + { + if (source.IsNullOrEmpty()) return 0; + + unchecked + { + return source.Aggregate(17, (hash, item) => hash * 23 + item.GetHashCode()); + } + } } } diff --git a/sources/editor/Xenko.Assets.Presentation/NodePresenters/Keys/EntityHierarchyData.cs b/sources/editor/Xenko.Assets.Presentation/NodePresenters/Keys/EntityHierarchyData.cs index 8a5159c625..351ed60100 100644 --- a/sources/editor/Xenko.Assets.Presentation/NodePresenters/Keys/EntityHierarchyData.cs +++ b/sources/editor/Xenko.Assets.Presentation/NodePresenters/Keys/EntityHierarchyData.cs @@ -13,5 +13,9 @@ public static class EntityHierarchyData { public const string EntityComponentAvailableTypes = nameof(EntityComponentAvailableTypes); public static readonly PropertyKey> EntityComponentAvailableTypesKey = new PropertyKey>(EntityComponentAvailableTypes, typeof(EntityHierarchyData), new PropertyCombinerMetadata(AbstractNodeEntryData.CombineProperty)); + + + public const string EntityComponentAvailableTypeGroups = nameof(EntityComponentAvailableTypeGroups); + public static readonly PropertyKey> EntityComponentAvailableTypeGroupsKey = new PropertyKey>(EntityComponentAvailableTypeGroups, typeof(EntityHierarchyData), new PropertyCombinerMetadata(AbstractNodeEntryData.CombineProperty)); } } diff --git a/sources/editor/Xenko.Assets.Presentation/NodePresenters/Updaters/EntityHierarchyAssetNodeUpdater.cs b/sources/editor/Xenko.Assets.Presentation/NodePresenters/Updaters/EntityHierarchyAssetNodeUpdater.cs index bcb8d9dae7..03225e1b89 100644 --- a/sources/editor/Xenko.Assets.Presentation/NodePresenters/Updaters/EntityHierarchyAssetNodeUpdater.cs +++ b/sources/editor/Xenko.Assets.Presentation/NodePresenters/Updaters/EntityHierarchyAssetNodeUpdater.cs @@ -14,6 +14,7 @@ using Xenko.Assets.Presentation.NodePresenters.Keys; using Xenko.Assets.Presentation.ViewModel; using Xenko.Engine; +using Xenko.Core.Presentation.Core; namespace Xenko.Assets.Presentation.NodePresenters.Updaters { @@ -50,9 +51,17 @@ protected override void UpdateNode(IAssetNodePresenter node) (EntityComponentAttributes.Get(x).AllowMultipleComponents || ((EntityComponentCollection)node.Value).All(y => y.GetType() != x))) .OrderBy(DisplayAttribute.GetDisplayName) - .Select(x => new AbstractNodeType(x)); + .Select(x => new AbstractNodeType(x)).ToArray(); node.AttachedProperties.Add(EntityHierarchyData.EntityComponentAvailableTypesKey, types); + //TODO: Choose a better grouping method. + var typeGroups = + types.GroupBy(t => Utils.SplitCamelCase( t.Type.Namespace.Substring(t.Type.Namespace.LastIndexOf('.') + 1))) + .OrderBy(g => g.Key) + .Select(g => new AbstractNodeTypeGroup(g.Key, g.ToArray())).ToArray(); + + node.AttachedProperties.Add(EntityHierarchyData.EntityComponentAvailableTypeGroupsKey, typeGroups); + // Cannot replace entity component collection. var replaceCommandIndex = node.Commands.IndexOf(x => x.Name == ReplacePropertyCommand.CommandName); if (replaceCommandIndex >= 0) diff --git a/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml b/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml index 7db27161d3..7f11524ea7 100644 --- a/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml +++ b/sources/editor/Xenko.Assets.Presentation/View/AddEntityComponentUserControl.xaml @@ -19,8 +19,9 @@ @@ -53,7 +54,7 @@ IsEnabled="{TemplateBinding IsEnabled}" CancelWithEscape="False"/> + + diff --git a/sources/editor/Xenko.Assets.Presentation/Thumbnails/HeightmapThumbnailCompiler.cs b/sources/editor/Xenko.Assets.Presentation/Thumbnails/HeightmapThumbnailCompiler.cs new file mode 100644 index 0000000000..c9872d02a3 --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/Thumbnails/HeightmapThumbnailCompiler.cs @@ -0,0 +1,87 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Collections.Generic; +using Xenko.Assets.Physics; +using Xenko.Core.Assets; +using Xenko.Core.Assets.Compiler; +using Xenko.Core.Mathematics; +using Xenko.Core.Serialization.Contents; +using Xenko.Editor.Thumbnails; +using Xenko.Graphics; +using Xenko.Physics; +using Xenko.Rendering; + +namespace Xenko.Assets.Presentation.Thumbnails +{ + [AssetCompiler(typeof(HeightmapAsset), typeof(ThumbnailCompilationContext))] + public class HeightmapThumbnailCompiler : ThumbnailCompilerBase + { + public HeightmapThumbnailCompiler() + { + IsStatic = false; + Priority = 10050; + } + + public override IEnumerable GetInputFiles(AssetItem assetItem) + { + var asset = (HeightmapAsset)assetItem.Asset; + var url = asset.Source.FullPath; + if (!string.IsNullOrEmpty(url)) + { + yield return new ObjectUrl(UrlType.File, url); + } + } + + protected override void CompileThumbnail(ThumbnailCompilerContext context, string thumbnailStorageUrl, AssetItem assetItem, Package originalPackage, AssetCompilerResult result) + { + result.BuildSteps.Add(new ThumbnailBuildStep(new HeightmapThumbnailCommand(context, assetItem, originalPackage, thumbnailStorageUrl, + new ThumbnailCommandParameters(assetItem.Asset, thumbnailStorageUrl, context.ThumbnailResolution)) + { InputFilesGetter = () => GetInputFiles(assetItem) })); + } + + /// + /// Command used to build the thumbnail of the texture in the storage + /// + public class HeightmapThumbnailCommand : ThumbnailFromSpriteBatchCommand + { + private Texture texture; + + public HeightmapThumbnailCommand(ThumbnailCompilerContext context, AssetItem assetItem, IAssetFinder assetFinder, string url, ThumbnailCommandParameters parameters) + : base(context, assetItem, assetFinder, url, parameters) + { + parameters.ColorSpace = ColorSpace.Linear; + } + + protected override void PreloadAsset() + { + base.PreloadAsset(); + + texture = LoadedAsset?.CreateTexture(GraphicsDevice); + } + + protected override void UnloadAsset() + { + if (texture != null) + { + texture.Dispose(); + texture = null; + } + + base.UnloadAsset(); + } + + protected override void RenderSprites(RenderDrawContext context) + { + if (LoadedAsset == null) + return; + + if (texture != null) + { + var destinationRectangle = new RectangleF(0, 0, Parameters.ThumbnailSize.X, Parameters.ThumbnailSize.Y); + + SpriteBatch.Draw(texture, destinationRectangle, new RectangleF(0, 0, texture.Width, texture.Height), Color.White, 0f, new Vector2(0, 0), SpriteEffects.None, swizzle: SwizzleMode.RRR1); + } + } + } + } +} diff --git a/sources/editor/Xenko.Assets.Presentation/ViewModel/Preview/HeightmapPreviewViewModel.cs b/sources/editor/Xenko.Assets.Presentation/ViewModel/Preview/HeightmapPreviewViewModel.cs new file mode 100644 index 0000000000..6ed79b697d --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/ViewModel/Preview/HeightmapPreviewViewModel.cs @@ -0,0 +1,40 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Assets.Presentation.Preview; +using Xenko.Core.Assets.Editor.ViewModel; +using Xenko.Editor.Preview; +using Xenko.Editor.Preview.ViewModel; + +namespace Xenko.Assets.Presentation.ViewModel.Preview +{ + [AssetPreviewViewModel(typeof(HeightmapPreview))] + public class HeightmapPreviewViewModel : TextureBasePreviewViewModel + { + private HeightmapPreview heightmapPreview; + private int previewHeightmapLength; + private int previewHeightmapWidth; + + public HeightmapPreviewViewModel(SessionViewModel session) + : base(session) + { + } + + public int PreviewHeightmapLength { get { return previewHeightmapLength; } private set { SetValue(ref previewHeightmapLength, value); } } + + public int PreviewHeightmapWidth { get { return previewHeightmapWidth; } private set { SetValue(ref previewHeightmapWidth, value); } } + + public override void AttachPreview(IAssetPreview preview) + { + heightmapPreview = (HeightmapPreview)preview; + heightmapPreview.NotifyHeightmapLoaded += UpdateHeightmapInfo; + UpdateHeightmapInfo(); + AttachPreviewTexture(preview); + } + + private void UpdateHeightmapInfo() + { + PreviewHeightmapWidth = heightmapPreview.Width; + PreviewHeightmapLength = heightmapPreview.Length; + } + } +} diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg index 9fbf279722..ab31fcb315 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg @@ -52,6 +52,7 @@ TemplateFolders: - !file Templates/Assets/Physics/ColliderShapePlane.xktpl - !file Templates/Assets/Physics/ColliderShapeSphere.xktpl - !file Templates/Assets/Physics/ColliderShapeCone.xktpl + - !file Templates/Assets/Physics/Heightmap.xktpl - !file Templates/Assets/Scenes/DefaultPrefab.xktpl - !file Templates/Assets/Scenes/DefaultNavigationMesh.xktpl - !file Templates/Assets/Scenes/DefaultScene.xktpl diff --git a/sources/engine/Xenko.Assets/AllAssets.Display.cs b/sources/engine/Xenko.Assets/AllAssets.Display.cs index 817fc60638..e6ee3737d6 100644 --- a/sources/engine/Xenko.Assets/AllAssets.Display.cs +++ b/sources/engine/Xenko.Assets/AllAssets.Display.cs @@ -1,4 +1,4 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Xenko.Core; @@ -102,6 +102,11 @@ namespace Physics partial class ColliderShapeAsset { } + + [Display((int)AssetDisplayPriority.Physics + 50, "Heightmap")] + partial class HeightmapAsset + { + } } namespace Rendering diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs new file mode 100644 index 0000000000..18224ff8ca --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs @@ -0,0 +1,51 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.ComponentModel; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Assets; +using Xenko.Core.Mathematics; +using Xenko.Physics; + +namespace Xenko.Assets.Physics +{ + [DataContract("HeightmapAsset")] + [CategoryOrder(20, "Convert", Expand = ExpandRule.Always)] + [AssetDescription(FileExtension)] + [AssetContentType(typeof(Heightmap))] + [AssetFormatVersion(XenkoConfig.PackageName, CurrentVersion, "3.0.0.0")] + public partial class HeightmapAsset : AssetWithSource + { + private const string CurrentVersion = "3.0.0.0"; + + public const string FileExtension = ".xkhmap"; + + [DataMember(20)] + [Display(category: "Convert")] + [NotNull] + public HeightfieldTypes Type { get; set; } = HeightfieldTypes.Float; + + [DataMember(30)] + [Display(category: "Convert")] + public float HeightScale { get; set; } = 1f; + + [DataMember(40, "Resize")] + [Display(category: "Convert", Expand = ExpandRule.Always)] + [NotNull] + public HeightmapSize Size { get; set; } = new HeightmapSize(); + + #region "HeightmapSize" + [DataContract] + public class HeightmapSize + { + [DataMember(0)] + [DefaultValue(false)] + public bool Enabled { get; set; } + + [DataMember(10)] + [InlineProperty] + public Int2 Size { get; set; } + } + #endregion + } +} diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs new file mode 100644 index 0000000000..5dc643a6d6 --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -0,0 +1,203 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Xenko.Assets.Textures; +using Xenko.Core.Assets; +using Xenko.Core.Assets.Analysis; +using Xenko.Core.Assets.Compiler; +using Xenko.Core.BuildEngine; +using Xenko.Core.Mathematics; +using Xenko.Core.Serialization.Contents; +using Xenko.Graphics; +using Xenko.Physics; +using Xenko.TextureConverter; + +namespace Xenko.Assets.Physics +{ + [AssetCompiler(typeof(HeightmapAsset), typeof(AssetCompilationContext))] + internal class HeightmapAssetCompiler : AssetCompilerBase + { + public override IEnumerable GetInputTypes(AssetItem assetItem) + { + yield return new BuildDependencyInfo(typeof(TextureAsset), typeof(AssetCompilationContext), BuildDependencyType.CompileContent); + } + + public override IEnumerable GetInputFiles(AssetItem assetItem) + { + var asset = (HeightmapAsset)assetItem.Asset; + var url = asset.Source.FullPath; + if (!string.IsNullOrEmpty(url)) + { + yield return new ObjectUrl(UrlType.File, url); + } + } + + protected override void Prepare(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result) + { + var asset = (HeightmapAsset)assetItem.Asset; + + result.BuildSteps = new AssetBuildStep(assetItem); + result.BuildSteps.Add(new HeightmapConvertCommand(targetUrlInStorage, asset, assetItem.Package) { InputFilesGetter = () => GetInputFiles(assetItem) }); + } + + public class HeightmapConvertCommand : AssetCommand + { + public HeightmapConvertCommand(string url, HeightmapAsset parameters, IAssetFinder assetFinder) + : base(url, parameters, assetFinder) + { + } + + protected override Task DoCommandOverride(ICommandContext commandContext) + { + var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService); + + var items = new Heightmap[] { new Heightmap(), }; + + foreach (var heightmap in items) + { + var source = Parameters.Source; + if (!string.IsNullOrEmpty(source)) + { + using (var textureTool = new TextureTool()) + using (var texImage = textureTool.Load(source, false)) + { + var size = Parameters.Size.Enabled && Parameters.Size.Size.X > 1 && Parameters.Size.Size.Y > 1 ? + Parameters.Size.Size : + new Int2(texImage.Width, texImage.Height); + + var heightfieldType = Parameters.Type; + + if (texImage.Width != size.X || texImage.Height != size.Y) + { + textureTool.Resize(texImage, size.X, size.Y, Filter.Rescaling.Nearest); + } + + switch (heightfieldType) + { + case HeightfieldTypes.Float: + switch (texImage.Format) + { + case PixelFormat.R32_Float: + break; + + case PixelFormat.R32G32B32A32_Float: + case PixelFormat.R16_Float: + textureTool.Convert(texImage, PixelFormat.R32_Float); + break; + + case PixelFormat.R16G16B16A16_UNorm: + case PixelFormat.R16_UNorm: + textureTool.Convert(texImage, PixelFormat.R16_SNorm); + textureTool.Convert(texImage, PixelFormat.R32_Float); + break; + + case PixelFormat.B8G8R8A8_UNorm: + case PixelFormat.R8G8B8A8_UNorm: + case PixelFormat.R8_UNorm: + textureTool.Convert(texImage, PixelFormat.R8_SNorm); + textureTool.Convert(texImage, PixelFormat.R32_Float); + break; + + default: + continue; + } + break; + + case HeightfieldTypes.Short: + switch (texImage.Format) + { + case PixelFormat.R16_SNorm: + break; + + case PixelFormat.R16G16B16A16_SNorm: + case PixelFormat.R16G16B16A16_UNorm: + case PixelFormat.R16_UNorm: + textureTool.Convert(texImage, PixelFormat.R16_SNorm); + break; + + case PixelFormat.R8G8B8A8_SNorm: + case PixelFormat.B8G8R8A8_UNorm: + case PixelFormat.R8G8B8A8_UNorm: + case PixelFormat.R8_UNorm: + textureTool.Convert(texImage, PixelFormat.R8_SNorm); + textureTool.Convert(texImage, PixelFormat.R16_SNorm); + break; + + default: + continue; + } + break; + + case HeightfieldTypes.Byte: + switch (texImage.Format) + { + case PixelFormat.R8_UNorm: + break; + + case PixelFormat.R8G8B8A8_SNorm: + case PixelFormat.B8G8R8A8_UNorm: + case PixelFormat.R8G8B8A8_UNorm: + textureTool.Convert(texImage, PixelFormat.R8_UNorm); + break; + + default: + continue; + } + break; + + default: + continue; + } + + using (var image = textureTool.ConvertToXenkoImage(texImage)) + { + var pixelBuffer = image.PixelBuffer[0]; + var scale = Parameters.HeightScale; + + switch (heightfieldType) + { + case HeightfieldTypes.Float: + heightmap.Floats = pixelBuffer.GetPixels().ToList(); + for (int i = 0; i < heightmap.Floats.Count; ++i) + { + heightmap.Floats[i] *= scale; + } + break; + + case HeightfieldTypes.Short: + heightmap.Shorts = pixelBuffer.GetPixels().ToList(); + for (int i = 0; i < heightmap.Shorts.Count; ++i) + { + heightmap.Shorts[i] = (short)MathUtil.Clamp(heightmap.Shorts[i] * scale, short.MinValue, short.MaxValue); + } + break; + + case HeightfieldTypes.Byte: + heightmap.Bytes = pixelBuffer.GetPixels().ToList(); + for (int i = 0; i < heightmap.Bytes.Count; ++i) + { + heightmap.Bytes[i] = (byte)MathUtil.Clamp(heightmap.Bytes[i] * scale, byte.MinValue, byte.MaxValue); + } + break; + + default: + continue; + } + + heightmap.HeightfieldType = heightfieldType; + heightmap.Width = size.X; + heightmap.Length = size.Y; + } + } + } + } + + assetManager.Save(Url, items[0]); + + return Task.FromResult(ResultStatus.Successful); + } + } + } +} diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapFactory.cs b/sources/engine/Xenko.Assets/Physics/HeightmapFactory.cs new file mode 100644 index 0000000000..0e42a1efbb --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/HeightmapFactory.cs @@ -0,0 +1,19 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core.Assets; + +namespace Xenko.Assets.Physics +{ + public class HeightmapFactory : AssetFactory + { + public static HeightmapAsset Create() + { + return new HeightmapAsset(); + } + + public override HeightmapAsset New() + { + return Create(); + } + } +} diff --git a/sources/engine/Xenko.Assets/Textures/TextureImporter.cs b/sources/engine/Xenko.Assets/Textures/TextureImporter.cs index 55becb22e5..82be3eb16d 100644 --- a/sources/engine/Xenko.Assets/Textures/TextureImporter.cs +++ b/sources/engine/Xenko.Assets/Textures/TextureImporter.cs @@ -7,6 +7,7 @@ using Xenko.Core.Assets; using Xenko.Core.IO; using Xenko.Assets.Sprite; +using Xenko.Assets.Physics; namespace Xenko.Assets.Textures { @@ -28,6 +29,7 @@ public override IEnumerable RootAssetTypes { yield return typeof(TextureAsset); yield return typeof(SpriteSheetAsset); // TODO: this is temporary, until we can make the asset templates ask compilers instead of importer which type they support + yield return typeof(HeightmapAsset); } } diff --git a/sources/engine/Xenko.Physics/Engine/Heightmap.cs b/sources/engine/Xenko.Physics/Engine/Heightmap.cs new file mode 100644 index 0000000000..8cb29e12e6 --- /dev/null +++ b/sources/engine/Xenko.Physics/Engine/Heightmap.cs @@ -0,0 +1,82 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Collections.Generic; +using Xenko.Core; +using Xenko.Core.Serialization; +using Xenko.Core.Serialization.Contents; +using Xenko.Engine.Design; + +namespace Xenko.Physics +{ + [DataContract] + [ContentSerializer(typeof(DataContentSerializer))] + [DataSerializerGlobal(typeof(CloneSerializer), Profile = "Clone")] + [ReferenceSerializer, DataSerializerGlobal(typeof(ReferenceSerializer), Profile = "Content")] + public class Heightmap + { + [DataMember(10)] + [Display(Browsable = false)] + public List Floats; + + [DataMember(20)] + [Display(Browsable = false)] + public List Shorts; + + [DataMember(30)] + [Display(Browsable = false)] + public List Bytes; + + [DataMember(40)] + [Display(Browsable = false)] + public HeightfieldTypes HeightfieldType; + + [DataMember(50)] + public int Width; + + [DataMember(60)] + public int Length; + + public static Heightmap Create(int width, int length, T[] data) where T : struct + { + if (width <= 1 || length <= 1 || data == null) + { + return null; + } + + var type = data.GetType(); + + if (type == typeof(float[])) + { + return new Heightmap + { + HeightfieldType = HeightfieldTypes.Float, + Width = width, + Length = length, + Floats = new List(data as float[]), + }; + } + else if (type == typeof(short[])) + { + return new Heightmap + { + HeightfieldType = HeightfieldTypes.Short, + Width = width, + Length = length, + Shorts = new List(data as short[]), + }; + } + else if (type == typeof(byte[])) + { + return new Heightmap + { + HeightfieldType = HeightfieldTypes.Byte, + Width = width, + Length = length, + Bytes = new List(data as byte[]), + }; + } + + return null; + } + } +} diff --git a/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs b/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs new file mode 100644 index 0000000000..cd3b249403 --- /dev/null +++ b/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs @@ -0,0 +1,43 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core.Annotations; +using Xenko.Graphics; + +namespace Xenko.Physics +{ + public static class HeightmapExtensions + { + public static bool IsValidSize([NotNull] this Heightmap heightmap) + { + if (heightmap == null) throw new ArgumentNullException(nameof(heightmap)); + + return heightmap.Width >= 2 && heightmap.Length >= 2; + } + + public static Texture CreateTexture([NotNull] this Heightmap heightmap, GraphicsDevice device) + { + if (heightmap == null) throw new ArgumentNullException(nameof(heightmap)); + + if (device == null || !heightmap.IsValidSize()) + { + return null; + } + + switch (heightmap.HeightfieldType) + { + case HeightfieldTypes.Float: + return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R32_Float, heightmap.Floats?.ToArray()); + + case HeightfieldTypes.Short: + return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R16_SNorm, heightmap.Shorts?.ToArray()); + + case HeightfieldTypes.Byte: + return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R8_UNorm, heightmap.Bytes?.ToArray()); + + default: + return null; + } + } + } +} From c1e9c2bf2901aeb84918de6f1bbf21a41edeab17 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Thu, 25 Jul 2019 19:15:17 +0900 Subject: [PATCH 0498/2038] [Physics] Add HeightfieldColliderShapeDesc --- .../Physics/ColliderShapeHeightfield.xktpl | 10 + .../Xenko.Assets.Presentation.xkpkg | 1 + .../Physics/ColliderShapeAssetCompiler.cs | 19 ++ .../Physics/ColliderShapeFactories.cs | 13 + .../Data/HeightfieldColliderShapeDesc.cs | 263 ++++++++++++++++++ .../Data/HeightfieldSourceHeightmap.cs | 69 +++++ .../Data/IHeightfieldInitialHeights.cs | 20 ++ 7 files changed, 395 insertions(+) create mode 100644 sources/editor/Xenko.Assets.Presentation/Templates/Assets/Physics/ColliderShapeHeightfield.xktpl create mode 100644 sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs create mode 100644 sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs create mode 100644 sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Physics/ColliderShapeHeightfield.xktpl b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Physics/ColliderShapeHeightfield.xktpl new file mode 100644 index 0000000000..7d205a0f58 --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Physics/ColliderShapeHeightfield.xktpl @@ -0,0 +1,10 @@ +!TemplateAssetFactory +Id: 1D3C9128-C94B-413B-9ABB-80ADDD372F61 +AssetTypeName: ColliderShapeAsset +Name: Heightfield +Scope: Asset +Description: A heightfield collider +Group: Physics +Icon: ..\.xktpl\ColliderPlane.png +DefaultOutputName: ColliderHeightfield +FactoryTypeName: ColliderShapeHeightfieldFactory diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg index ab31fcb315..ae338c8fb7 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg @@ -52,6 +52,7 @@ TemplateFolders: - !file Templates/Assets/Physics/ColliderShapePlane.xktpl - !file Templates/Assets/Physics/ColliderShapeSphere.xktpl - !file Templates/Assets/Physics/ColliderShapeCone.xktpl + - !file Templates/Assets/Physics/ColliderShapeHeightfield.xktpl - !file Templates/Assets/Physics/Heightmap.xktpl - !file Templates/Assets/Scenes/DefaultPrefab.xktpl - !file Templates/Assets/Scenes/DefaultNavigationMesh.xktpl diff --git a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs index b3d9c53a01..d6fa43e041 100644 --- a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs @@ -19,6 +19,7 @@ using Xenko.Assets.Textures; using VHACDSharp; using Buffer = Xenko.Graphics.Buffer; +using Xenko.Graphics; namespace Xenko.Assets.Physics { [AssetCompiler(typeof(ColliderShapeAsset), typeof(AssetCompilationContext))] @@ -34,6 +35,10 @@ public override IEnumerable GetInputTypes(AssetItem assetIt foreach (var type in AssetRegistry.GetAssetTypes(typeof(Skeleton))) { yield return new BuildDependencyInfo(type, typeof(AssetCompilationContext), BuildDependencyType.CompileContent); } + foreach (var type in AssetRegistry.GetAssetTypes(typeof(Heightmap))) + { + yield return new BuildDependencyInfo(type, typeof(AssetCompilationContext), BuildDependencyType.CompileContent); + } } public override IEnumerable GetInputTypesToExclude(AssetItem assetItem) { @@ -57,6 +62,20 @@ public override IEnumerable GetInputFiles(AssetItem assetItem) { } } } + else if (desc is HeightfieldColliderShapeDesc) + { + var heightfieldDesc = desc as HeightfieldColliderShapeDesc; + + if (heightfieldDesc.InitialHeights?.GetSource() != null) + { + var url = AttachedReferenceManager.GetUrl(heightfieldDesc.InitialHeights.GetSource()); + + if (!string.IsNullOrEmpty(url)) + { + yield return new ObjectUrl(UrlType.Content, url); + } + } + } } } diff --git a/sources/engine/Xenko.Assets/Physics/ColliderShapeFactories.cs b/sources/engine/Xenko.Assets/Physics/ColliderShapeFactories.cs index ec16ceba86..06bda887a8 100644 --- a/sources/engine/Xenko.Assets/Physics/ColliderShapeFactories.cs +++ b/sources/engine/Xenko.Assets/Physics/ColliderShapeFactories.cs @@ -95,4 +95,17 @@ public override ColliderShapeAsset New() return Create(); } } + + public class ColliderShapeHeightfieldFactory : AssetFactory + { + public static ColliderShapeAsset Create() + { + return new ColliderShapeAsset { ColliderShapes = { new HeightfieldColliderShapeDesc() } }; + } + + public override ColliderShapeAsset New() + { + return Create(); + } + } } diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs new file mode 100644 index 0000000000..ea8b33adcd --- /dev/null +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -0,0 +1,263 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.ComponentModel; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Mathematics; +using Xenko.Core.Serialization.Contents; + +namespace Xenko.Physics +{ + [ContentSerializer(typeof(DataContentSerializer))] + [DataContract("HeightfieldColliderShapeDesc")] + [Display(300, "Heightfield")] + public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc + { + [DataMember(10)] + [NotNull] + public IHeightfieldInitialHeights InitialHeights { get; set; } + + [DataMember(30)] + public HeightfieldTypes HeightfieldType; + + [DataMember(40)] + public Int2 HeightStickSize; + + [DataMember(50)] + public Vector2 HeightRange; + + [DataMember(60)] + [NotNull] + public HeightScaleSetting HeightScale { get; set; } + + [DataMember(70)] + public bool FlipQuadEdges; + + [DataMember(100)] + public Vector3 LocalOffset; + + [DataMember(110)] + public Quaternion LocalRotation; + + public HeightfieldColliderShapeDesc() + { + InitialHeights = new HeightfieldSourceHeightmap(); + HeightfieldType = HeightfieldTypes.Float; + HeightStickSize = new Int2(64, 64); + HeightRange = new Vector2(-10, 10); + HeightScale = new HeightScaleSetting(); + FlipQuadEdges = false; + LocalOffset = new Vector3(0, 0, 0); + LocalRotation = Quaternion.Identity; + } + + public bool Match(object obj) + { + var other = obj as HeightfieldColliderShapeDesc; + + if (other == null) + { + return false; + } + + if (LocalOffset != other.LocalOffset || LocalRotation != other.LocalRotation) + { + return false; + } + + var heightScaleComparison = (other.HeightScale.Enabled && HeightScale.Enabled) ? Math.Abs(other.HeightScale.Scale - HeightScale.Scale) < float.Epsilon : other.HeightScale.Enabled == HeightScale.Enabled; + + var initialHeightsComparison = (other.InitialHeights == InitialHeights) || + ((other.InitialHeights != null && InitialHeights != null) && + other.InitialHeights.GetType() == InitialHeights.GetType() && + other.InitialHeights.GetSource() == InitialHeights.GetSource()); + + return initialHeightsComparison && + other.HeightfieldType == HeightfieldType && + other.HeightStickSize == HeightStickSize && + other.HeightRange == HeightRange && + heightScaleComparison && + other.FlipQuadEdges == FlipQuadEdges; + } + + private static void FillHeights(UnmanagedArray unmanagedArray, T value) where T : struct + { + if (unmanagedArray == null) throw new ArgumentNullException(nameof(unmanagedArray)); + + for (int i = 0; i < unmanagedArray.Length; ++i) + { + unmanagedArray[i] = value; + } + } + + private static UnmanagedArray CreateHeights(int length, T[] initialHeights) where T : struct + { + var unmanagedArray = new UnmanagedArray(length); + + if (initialHeights != null) + { + unmanagedArray.Write(initialHeights, 0, 0, Math.Min(unmanagedArray.Length, initialHeights.Length)); + } + else + { + FillHeights(unmanagedArray, default); + } + + return unmanagedArray; + } + + public ColliderShape CreateShape() + { + if (HeightStickSize.X <= 1 || + HeightStickSize.Y <= 1 || + HeightRange.Y < HeightRange.X || + Math.Abs(HeightRange.Y - HeightRange.X) < float.Epsilon) + { + return null; + } + + float heightScale = (HeightfieldType != HeightfieldTypes.Float) && HeightScale.Enabled ? HeightScale.Scale : CalculateHeightScale(); + + if (Math.Abs(heightScale) < float.Epsilon) + { + return null; + } + + var arrayLength = HeightStickSize.X * HeightStickSize.Y; + + object unmanagedArray; + + switch (HeightfieldType) + { + case HeightfieldTypes.Float: + { + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.GetHeights()); + break; + } + case HeightfieldTypes.Short: + { + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.GetHeights()); + break; + } + case HeightfieldTypes.Byte: + { + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.GetHeights()); + break; + } + + default: + return null; + } + + var shape = new HeightfieldColliderShape + ( + HeightStickSize.X, + HeightStickSize.Y, + HeightfieldType, + unmanagedArray, + heightScale, + HeightRange.X, + HeightRange.Y, + FlipQuadEdges + ) + { + LocalOffset = LocalOffset, + LocalRotation = LocalRotation, + }; + + return shape; + } + + public float CalculateHeightScale() + { + if (HeightfieldType == HeightfieldTypes.Float) + { + return 1f; + } + + float heightScale = 1f; + + var max = Math.Max(Math.Abs(HeightRange.X), Math.Abs(HeightRange.Y)); + + switch (HeightfieldType) + { + case HeightfieldTypes.Short: + + heightScale = max / 0x8000; + break; + + case HeightfieldTypes.Byte: + + var minSign = Math.Sign(HeightRange.X); + var maxSign = Math.Sign(HeightRange.Y); + + // min < 0 < max + if (minSign == -1 && maxSign == 1) + { + // Byte can't handle both positive and negative together. + heightScale = HeightRange.Y / byte.MaxValue; + } + // 0 <= min < max + else if (0 <= minSign && maxSign == 1) + { + heightScale = max / byte.MaxValue; + } + // min < max <= 0 + else if (minSign == -1 && maxSign <= 0) + { + heightScale = -(max / byte.MaxValue); + } + break; + } + + return heightScale; + } + + // TODO: Should provide better way that updates the NavigationMeshCacheObject of the heightfield at rebuilding NavigationMesh. + #region "HACK: Before rebuilding NavigationMesh, use Refresh() to update the NavigationMeshCacheObject of the heightfield." + + [DataMemberIgnore] + [DefaultValue(0)] + public int RefreshCounter; + + /// + /// HACK: Before rebuilding NavigationMesh, use Refresh() to update the NavigationMeshCacheObject of the heightfield. + /// + /// GetHashCode() returns different value after calling this method. + public void Refresh() + { + RefreshCounter = (RefreshCounter + 1) % ushort.MaxValue; + } + + public override int GetHashCode() + { + return (base.GetHashCode() * 397) ^ RefreshCounter; + } + + #endregion + + [DataContract] + public class HeightScaleSetting + { + [DataMember(0)] + [DefaultValue(false)] + public bool Enabled { get; set; } + + [DataMember(10)] + [InlineProperty] + public float Scale { get; set; } + + public HeightScaleSetting() + : this(1f) + { + } + + public HeightScaleSetting(float value) + { + Scale = value; + } + } + } +} diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs b/sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs new file mode 100644 index 0000000000..6466fb47f1 --- /dev/null +++ b/sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs @@ -0,0 +1,69 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.ComponentModel; +using Xenko.Core; +using Xenko.Core.Annotations; + +namespace Xenko.Physics +{ + [DataContract] + public class HeightfieldSourceHeightmap : IHeightfieldInitialHeights + { + [DataMember(10)] + [DefaultValue(null)] + [InlineProperty] + public Heightmap Heightmap { get; set; } + + public HeightfieldSourceHeightmap() + : this(null) + { + } + + public HeightfieldSourceHeightmap(Heightmap heightmap) + { + Heightmap = heightmap; + } + + public T GetSource() where T : class + { + return Heightmap as T; + } + + public object GetSource() + { + return Heightmap; + } + + public T[] GetHeights() where T : struct + { + if (typeof(T) == typeof(byte)) + { + return Heightmap?.Bytes?.ToArray() as T[]; + } + else if (typeof(T) == typeof(short)) + { + return Heightmap?.Shorts?.ToArray() as T[]; + } + else if (typeof(T) == typeof(float)) + { + return Heightmap?.Floats?.ToArray() as T[]; + } + else + { + return null; + } + } + + public Type GetSourceType() + { + return Heightmap?.GetType(); + } + + public void SetSource(object source) + { + Heightmap = source as Heightmap; + } + } +} diff --git a/sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs b/sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs new file mode 100644 index 0000000000..c4fe65a745 --- /dev/null +++ b/sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs @@ -0,0 +1,20 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; + +namespace Xenko.Physics +{ + public interface IHeightfieldInitialHeights + { + T GetSource() where T : class; + + object GetSource(); + + T[] GetHeights() where T : struct; + + Type GetSourceType(); + + void SetSource(object source); + } +} From e5ff45b94e9cd4b75487b727da7527c32e79b749 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Thu, 25 Jul 2019 19:15:43 +0900 Subject: [PATCH 0499/2038] [Navigation] Support HeightfieldColliderShape --- .../Navigation/NavigationMeshAssetCompiler.cs | 24 ++++++++++++ .../Xenko.Navigation/NavigationMeshBuilder.cs | 37 +++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs index 1df8b8813f..9a03b52f64 100644 --- a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs @@ -31,6 +31,7 @@ public override IEnumerable GetInputTypes(AssetItem assetIt { yield return new BuildDependencyInfo(typeof(SceneAsset), typeof(AssetCompilationContext), BuildDependencyType.CompileAsset); yield return new BuildDependencyInfo(typeof(ColliderShapeAsset), typeof(AssetCompilationContext), BuildDependencyType.CompileContent); + yield return new BuildDependencyInfo(typeof(HeightmapAsset), typeof(AssetCompilationContext), BuildDependencyType.CompileContent); } public override IEnumerable GetInputFiles(AssetItem assetItem) @@ -82,6 +83,7 @@ private class NavmeshBuildCommand : AssetCommand { private readonly ContentManager contentManager = new ContentManager(MicrothreadLocalDatabases.ProviderService); private readonly Dictionary loadedColliderShapes = new Dictionary(); + private readonly Dictionary loadedHeightfieldInitialDatas = new Dictionary(); private NavigationMesh oldNavigationMesh; @@ -155,6 +157,10 @@ protected override Task DoCommandOverride(ICommandContext commandC { contentManager.Unload(pair.Key); } + foreach (var pair in loadedHeightfieldInitialDatas) + { + contentManager.Unload(pair.Key); + } if (!result.Success) return Task.FromResult(ResultStatus.Failed); @@ -299,6 +305,24 @@ private void EnsureClonedSceneAndHash() } shapeAssetDesc.Shape = loadedColliderShape; } + else + { + if (desc.GetType() == typeof(HeightfieldColliderShapeDesc)) + { + var heightfieldDesc = ((HeightfieldColliderShapeDesc)desc); + if (heightfieldDesc.InitialHeights?.GetSource() != null) + { + var assetReference = AttachedReferenceManager.GetAttachedReference(heightfieldDesc.InitialHeights.GetSource()); + object loadedHeightfieldInitialData; + if (!loadedHeightfieldInitialDatas.TryGetValue(assetReference.Url, out loadedHeightfieldInitialData)) + { + loadedHeightfieldInitialData = contentManager.Load(heightfieldDesc.InitialHeights.GetSourceType(), assetReference.Url); + loadedHeightfieldInitialDatas.Add(assetReference.Url, loadedHeightfieldInitialData); + } + heightfieldDesc.InitialHeights.SetSource(loadedHeightfieldInitialData); + } + } + } } } diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index e8bc242d46..5a39557dc0 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -571,6 +571,43 @@ private void BuildInput(StaticColliderData[] collidersLocal, CollisionFilterGrou entityNavigationMeshInputBuilder.AppendArrays(mesh.Vertices.ToArray(), indices, transform); } + else if (shapeType == typeof(HeightfieldColliderShape)) + { + var heightfield = (HeightfieldColliderShape)shape; + + var halfRange = (heightfield.MaxHeight - heightfield.MinHeight) * 0.5f; + var offset = -(heightfield.MinHeight + halfRange); + Matrix transform = Matrix.Translation(new Vector3(0, offset, 0)) * heightfield.PositiveCenterMatrix * entityWorldMatrix; + + var width = heightfield.HeightStickWidth - 1; + var length = heightfield.HeightStickLength - 1; + var mesh = GeometricPrimitive.Plane.New(width, length, width, length, normalDirection: NormalDirection.UpY, toLeftHanded: true); + + var arrayLength = heightfield.HeightStickWidth * heightfield.HeightStickLength; + switch (heightfield.HeightType) + { + case HeightfieldTypes.Short: + for (int i = 0; i < arrayLength; ++i) + { + mesh.Vertices[i].Position.Y = heightfield.ShortArray[i] * heightfield.HeightScale; + } + break; + case HeightfieldTypes.Byte: + for (int i = 0; i < arrayLength; ++i) + { + mesh.Vertices[i].Position.Y = heightfield.ByteArray[i] * heightfield.HeightScale; + } + break; + case HeightfieldTypes.Float: + for (int i = 0; i < arrayLength; ++i) + { + mesh.Vertices[i].Position.Y = heightfield.FloatArray[i]; + } + break; + } + + entityNavigationMeshInputBuilder.AppendMeshData(mesh, transform); + } else if (shapeType == typeof(CompoundColliderShape)) { // Unroll compound collider shapes From 8be230a2683398026f72d554b29da95f6eafa3e7 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Sun, 18 Aug 2019 13:22:03 +0900 Subject: [PATCH 0500/2038] Fix height scale for Short type --- .../engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index ea8b33adcd..6ec1c84e99 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -185,7 +185,7 @@ public float CalculateHeightScale() { case HeightfieldTypes.Short: - heightScale = max / 0x8000; + heightScale = max / short.MaxValue; break; case HeightfieldTypes.Byte: From 60e2d3b753018887d0a6529c8af4b4dfe04dbfa0 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Sun, 18 Aug 2019 13:22:52 +0900 Subject: [PATCH 0501/2038] Add sRGB sampling property to HeightmapAsset --- .../Xenko.Assets/Physics/HeightmapAsset.cs | 4 ++++ .../Physics/HeightmapAssetCompiler.cs | 22 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs index 18224ff8ca..d34b6e0278 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs @@ -34,6 +34,10 @@ public partial class HeightmapAsset : AssetWithSource [NotNull] public HeightmapSize Size { get; set; } = new HeightmapSize(); + [DataMember(50, "sRGB sampling")] + [Display(category: "Convert")] + public bool IsSRgb { get; set; } = true; + #region "HeightmapSize" [DataContract] public class HeightmapSize diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs index 5dc643a6d6..fec2c40c2c 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -61,7 +61,7 @@ protected override Task DoCommandOverride(ICommandContext commandC if (!string.IsNullOrEmpty(source)) { using (var textureTool = new TextureTool()) - using (var texImage = textureTool.Load(source, false)) + using (var texImage = textureTool.Load(source, Parameters.IsSRgb)) { var size = Parameters.Size.Enabled && Parameters.Size.Size.X > 1 && Parameters.Size.Size.Y > 1 ? Parameters.Size.Size : @@ -100,6 +100,13 @@ protected override Task DoCommandOverride(ICommandContext commandC textureTool.Convert(texImage, PixelFormat.R32_Float); break; + case PixelFormat.B8G8R8A8_UNorm_SRgb: + case PixelFormat.B8G8R8X8_UNorm_SRgb: + case PixelFormat.R8G8B8A8_UNorm_SRgb: + textureTool.Convert(texImage, PixelFormat.R8_SNorm); + textureTool.Convert(texImage, PixelFormat.R32_Float); + break; + default: continue; } @@ -125,6 +132,13 @@ protected override Task DoCommandOverride(ICommandContext commandC textureTool.Convert(texImage, PixelFormat.R16_SNorm); break; + case PixelFormat.B8G8R8A8_UNorm_SRgb: + case PixelFormat.B8G8R8X8_UNorm_SRgb: + case PixelFormat.R8G8B8A8_UNorm_SRgb: + textureTool.Convert(texImage, PixelFormat.R8_SNorm); + textureTool.Convert(texImage, PixelFormat.R16_SNorm); + break; + default: continue; } @@ -142,6 +156,12 @@ protected override Task DoCommandOverride(ICommandContext commandC textureTool.Convert(texImage, PixelFormat.R8_UNorm); break; + case PixelFormat.B8G8R8A8_UNorm_SRgb: + case PixelFormat.B8G8R8X8_UNorm_SRgb: + case PixelFormat.R8G8B8A8_UNorm_SRgb: + textureTool.Convert(texImage, PixelFormat.R8_UNorm); + break; + default: continue; } From 480da3eeb04d8020082d1718c54bdbbc93d92fed Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Thu, 7 Nov 2019 02:33:34 +0900 Subject: [PATCH 0502/2038] Change type of InitialHeights to Heightmap Deleted HeightfieldSourceHeightmap and IHeightfieldInitialHeights. They are no longer necessary. --- .../Navigation/NavigationMeshAssetCompiler.cs | 8 +-- .../Physics/ColliderShapeAssetCompiler.cs | 4 +- .../Data/HeightfieldColliderShapeDesc.cs | 15 ++-- .../Data/HeightfieldSourceHeightmap.cs | 69 ------------------- .../Data/IHeightfieldInitialHeights.cs | 20 ------ 5 files changed, 12 insertions(+), 104 deletions(-) delete mode 100644 sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs delete mode 100644 sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs diff --git a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs index 9a03b52f64..57e27107a7 100644 --- a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs @@ -310,16 +310,16 @@ private void EnsureClonedSceneAndHash() if (desc.GetType() == typeof(HeightfieldColliderShapeDesc)) { var heightfieldDesc = ((HeightfieldColliderShapeDesc)desc); - if (heightfieldDesc.InitialHeights?.GetSource() != null) + if (heightfieldDesc.InitialHeights != null) { - var assetReference = AttachedReferenceManager.GetAttachedReference(heightfieldDesc.InitialHeights.GetSource()); + var assetReference = AttachedReferenceManager.GetAttachedReference(heightfieldDesc.InitialHeights); object loadedHeightfieldInitialData; if (!loadedHeightfieldInitialDatas.TryGetValue(assetReference.Url, out loadedHeightfieldInitialData)) { - loadedHeightfieldInitialData = contentManager.Load(heightfieldDesc.InitialHeights.GetSourceType(), assetReference.Url); + loadedHeightfieldInitialData = contentManager.Load(typeof(Heightmap), assetReference.Url); loadedHeightfieldInitialDatas.Add(assetReference.Url, loadedHeightfieldInitialData); } - heightfieldDesc.InitialHeights.SetSource(loadedHeightfieldInitialData); + heightfieldDesc.InitialHeights = loadedHeightfieldInitialData as Heightmap; } } } diff --git a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs index d6fa43e041..f0e98a3b8c 100644 --- a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs @@ -66,9 +66,9 @@ public override IEnumerable GetInputFiles(AssetItem assetItem) { { var heightfieldDesc = desc as HeightfieldColliderShapeDesc; - if (heightfieldDesc.InitialHeights?.GetSource() != null) + if (heightfieldDesc.InitialHeights != null) { - var url = AttachedReferenceManager.GetUrl(heightfieldDesc.InitialHeights.GetSource()); + var url = AttachedReferenceManager.GetUrl(heightfieldDesc.InitialHeights); if (!string.IsNullOrEmpty(url)) { diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 6ec1c84e99..4bd017a656 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -17,7 +17,7 @@ public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc { [DataMember(10)] [NotNull] - public IHeightfieldInitialHeights InitialHeights { get; set; } + public Heightmap InitialHeights { get; set; } [DataMember(30)] public HeightfieldTypes HeightfieldType; @@ -43,7 +43,7 @@ public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc public HeightfieldColliderShapeDesc() { - InitialHeights = new HeightfieldSourceHeightmap(); + InitialHeights = new Heightmap(); HeightfieldType = HeightfieldTypes.Float; HeightStickSize = new Int2(64, 64); HeightRange = new Vector2(-10, 10); @@ -69,10 +69,7 @@ public bool Match(object obj) var heightScaleComparison = (other.HeightScale.Enabled && HeightScale.Enabled) ? Math.Abs(other.HeightScale.Scale - HeightScale.Scale) < float.Epsilon : other.HeightScale.Enabled == HeightScale.Enabled; - var initialHeightsComparison = (other.InitialHeights == InitialHeights) || - ((other.InitialHeights != null && InitialHeights != null) && - other.InitialHeights.GetType() == InitialHeights.GetType() && - other.InitialHeights.GetSource() == InitialHeights.GetSource()); + var initialHeightsComparison = (other.InitialHeights == InitialHeights); return initialHeightsComparison && other.HeightfieldType == HeightfieldType && @@ -133,17 +130,17 @@ public ColliderShape CreateShape() { case HeightfieldTypes.Float: { - unmanagedArray = CreateHeights(arrayLength, InitialHeights?.GetHeights()); + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Floats?.ToArray()); break; } case HeightfieldTypes.Short: { - unmanagedArray = CreateHeights(arrayLength, InitialHeights?.GetHeights()); + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Shorts?.ToArray()); break; } case HeightfieldTypes.Byte: { - unmanagedArray = CreateHeights(arrayLength, InitialHeights?.GetHeights()); + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Bytes?.ToArray()); break; } diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs b/sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs deleted file mode 100644 index 6466fb47f1..0000000000 --- a/sources/engine/Xenko.Physics/Data/HeightfieldSourceHeightmap.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.ComponentModel; -using Xenko.Core; -using Xenko.Core.Annotations; - -namespace Xenko.Physics -{ - [DataContract] - public class HeightfieldSourceHeightmap : IHeightfieldInitialHeights - { - [DataMember(10)] - [DefaultValue(null)] - [InlineProperty] - public Heightmap Heightmap { get; set; } - - public HeightfieldSourceHeightmap() - : this(null) - { - } - - public HeightfieldSourceHeightmap(Heightmap heightmap) - { - Heightmap = heightmap; - } - - public T GetSource() where T : class - { - return Heightmap as T; - } - - public object GetSource() - { - return Heightmap; - } - - public T[] GetHeights() where T : struct - { - if (typeof(T) == typeof(byte)) - { - return Heightmap?.Bytes?.ToArray() as T[]; - } - else if (typeof(T) == typeof(short)) - { - return Heightmap?.Shorts?.ToArray() as T[]; - } - else if (typeof(T) == typeof(float)) - { - return Heightmap?.Floats?.ToArray() as T[]; - } - else - { - return null; - } - } - - public Type GetSourceType() - { - return Heightmap?.GetType(); - } - - public void SetSource(object source) - { - Heightmap = source as Heightmap; - } - } -} diff --git a/sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs b/sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs deleted file mode 100644 index c4fe65a745..0000000000 --- a/sources/engine/Xenko.Physics/Data/IHeightfieldInitialHeights.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; - -namespace Xenko.Physics -{ - public interface IHeightfieldInitialHeights - { - T GetSource() where T : class; - - object GetSource(); - - T[] GetHeights() where T : struct; - - Type GetSourceType(); - - void SetSource(object source); - } -} From 5887e7dbe5a8a1571988df0591fd61f0b3c1611f Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 8 Nov 2019 08:16:29 +0900 Subject: [PATCH 0503/2038] [Navigation] Recreate collider shape only when the desc updated --- .../NavigationMeshBuildUtils.cs | 45 +++++++++++++++++++ .../Xenko.Navigation/NavigationMeshBuilder.cs | 5 ++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs index 7539416871..7f52cba1ac 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using Xenko.Core.Mathematics; +using Xenko.Engine; using Xenko.Physics; namespace Xenko.Navigation @@ -163,5 +164,49 @@ public static int HashEntityCollider(StaticColliderComponent collider, Collision } return hash; } + + /// + /// Checks if a static collider has latest collider shape + /// + /// The collider to check + /// true if the collider has latest collider shape, false otherwise + public static bool HasLatestColliderShape(StaticColliderComponent collider) + { + if (collider.ColliderShape == null) + { + return false; + } + else + { + if (collider.ColliderShapes.Count == 1) + { + if (!collider.ColliderShapes[0].Match(collider.ColliderShape.Description)) + { + return false; + } + } + else + { + var compound = collider.ColliderShape as CompoundColliderShape; + var descriptions = collider.ColliderShape?.Description as PhysicsComponent.ColliderShapeCollection; + if ((compound == null) || (descriptions == null) || (descriptions.Count != collider.ColliderShapes.Count)) + { + return false; + } + else + { + for (int i = 0; i < compound.Count; ++i) + { + if (!compound[i].Description.Match(collider.ColliderShapes[i])) + { + return false; + } + } + } + } + } + + return true; + } } } diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index 5a39557dc0..10503f0295 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -466,7 +466,10 @@ private void BuildInput(StaticColliderData[] collidersLocal, CollisionFilterGrou } // Make sure shape is up to date - colliderData.Component.ComposeShape(); + if (!NavigationMeshBuildUtils.HasLatestColliderShape(colliderData.Component)) + { + colliderData.Component.ComposeShape(); + } // Interate through all the colliders shapes while queueing all shapes in compound shapes to process those as well Queue shapesToProcess = new Queue(); From 6a74f6030ac18274e3353467af625307009c7526 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Wed, 13 Nov 2019 02:14:22 +0900 Subject: [PATCH 0504/2038] [Fix] Initialized HeightfieldColliderShapeDesc with pointless value --- .../engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 4bd017a656..cca1e5f54d 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -43,7 +43,7 @@ public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc public HeightfieldColliderShapeDesc() { - InitialHeights = new Heightmap(); + InitialHeights = null; HeightfieldType = HeightfieldTypes.Float; HeightStickSize = new Int2(64, 64); HeightRange = new Vector2(-10, 10); From 368bb3c164c0d41959ac32a245e11d39f4ec0455 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Tue, 19 Nov 2019 20:39:52 +0900 Subject: [PATCH 0505/2038] Fix attributes for InitialHeights --- .../engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index cca1e5f54d..680fc6aeb4 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -16,7 +16,6 @@ namespace Xenko.Physics public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc { [DataMember(10)] - [NotNull] public Heightmap InitialHeights { get; set; } [DataMember(30)] From 51b6d483ebc21b3b7a15154c80642958b915da1d Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Tue, 19 Nov 2019 21:30:41 +0900 Subject: [PATCH 0506/2038] Rename HeightScaleSetting to CustomHeightScale --- .../Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 680fc6aeb4..216b2a4fe4 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -29,7 +29,7 @@ public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc [DataMember(60)] [NotNull] - public HeightScaleSetting HeightScale { get; set; } + public CustomHeightScale HeightScale { get; set; } [DataMember(70)] public bool FlipQuadEdges; @@ -46,7 +46,7 @@ public HeightfieldColliderShapeDesc() HeightfieldType = HeightfieldTypes.Float; HeightStickSize = new Int2(64, 64); HeightRange = new Vector2(-10, 10); - HeightScale = new HeightScaleSetting(); + HeightScale = new CustomHeightScale(); FlipQuadEdges = false; LocalOffset = new Vector3(0, 0, 0); LocalRotation = Quaternion.Identity; @@ -235,7 +235,7 @@ public override int GetHashCode() #endregion [DataContract] - public class HeightScaleSetting + public class CustomHeightScale { [DataMember(0)] [DefaultValue(false)] @@ -245,12 +245,12 @@ public class HeightScaleSetting [InlineProperty] public float Scale { get; set; } - public HeightScaleSetting() + public CustomHeightScale() : this(1f) { } - public HeightScaleSetting(float value) + public CustomHeightScale(float value) { Scale = value; } From 724e08a2cce57d2897bf214fc89aa9055b2e0813 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Wed, 20 Nov 2019 08:07:24 +0900 Subject: [PATCH 0507/2038] [Navigation] Add a way to update dynamic shape and remove Refresh method of the desc --- .../DynamicNavigationMeshSystem.cs | 2 ++ .../NavigationMeshBuildUtils.cs | 32 +++++++++++++++++++ .../Xenko.Navigation/NavigationMeshBuilder.cs | 11 ++++++- .../StaticColliderCacheSettings.cs | 10 ++++++ .../Xenko.Navigation/StaticColliderData.cs | 1 + .../Data/HeightfieldColliderShapeDesc.cs | 23 ------------- 6 files changed, 55 insertions(+), 24 deletions(-) create mode 100644 sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs diff --git a/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs b/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs index 8d76348a7f..591cded9dc 100644 --- a/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs +++ b/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs @@ -177,6 +177,8 @@ public async Task Rebuild() return result.Result; } + public StaticColliderCacheSettings GetStaticColliderCacheSettings(StaticColliderComponent staticCollider) => builder?.GetStaticColliderCacheSettings(staticCollider); + internal void InitializeSettingsFromNavigationSettings(NavigationSettings navigationSettings) { BuildSettings = navigationSettings.BuildSettings; diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs index 7f52cba1ac..fd978ac8f0 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs @@ -208,5 +208,37 @@ public static bool HasLatestColliderShape(StaticColliderComponent collider) return true; } + + /// + /// Checks if a static collider is dynamic shape + /// + /// The collider to check + /// true if the collider is dynamic shape, false otherwise + public static bool IsDynamicShape(ColliderShape colliderShape) + { + if (colliderShape == null) + { + return false; + } + + if (colliderShape is HeightfieldColliderShape) + { + return true; + } + else + { + if (colliderShape is CompoundColliderShape compound) + { + for (int i = 0; i < compound.Count; ++i) + { + if (IsDynamicShape(compound[i])) + { + return true; + } + } + } + return false; + } + } } } diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index 10503f0295..8785f8d16e 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -76,6 +76,14 @@ public void Remove(StaticColliderData colliderData) } } + public StaticColliderCacheSettings GetStaticColliderCacheSettings(StaticColliderComponent staticCollider) + { + lock (colliders) + { + return colliders.Where(c => ReferenceEquals(c.Component, staticCollider)).FirstOrDefault()?.CacheSettings; + } + } + /// /// Performs the build of a navigation mesh /// @@ -438,7 +446,8 @@ private void BuildInput(StaticColliderData[] collidersLocal, CollisionFilterGrou colliderData.Previous = null; if (lastCache?.Objects.TryGetValue(colliderData.Component.Id, out colliderData.Previous) ?? false) { - if (colliderData.Previous.ParameterHash == colliderData.ParameterHash) + if ((!NavigationMeshBuildUtils.IsDynamicShape(colliderData.Component.ColliderShape) || !colliderData.CacheSettings.EnableAlwaysUpdateDynamicShape) && + (colliderData.Previous.ParameterHash == colliderData.ParameterHash)) { // In this case, we don't need to recalculate the geometry for this shape, since it wasn't changed // here we take the triangle mesh from the previous build as the current diff --git a/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs b/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs new file mode 100644 index 0000000000..d0dc4f816e --- /dev/null +++ b/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs @@ -0,0 +1,10 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +namespace Xenko.Navigation +{ + public class StaticColliderCacheSettings + { + public bool EnableAlwaysUpdateDynamicShape = true; + } +} diff --git a/sources/engine/Xenko.Navigation/StaticColliderData.cs b/sources/engine/Xenko.Navigation/StaticColliderData.cs index e7f62a39fc..36770164ad 100644 --- a/sources/engine/Xenko.Navigation/StaticColliderData.cs +++ b/sources/engine/Xenko.Navigation/StaticColliderData.cs @@ -13,6 +13,7 @@ namespace Xenko.Navigation public class StaticColliderData { public StaticColliderComponent Component; + public readonly StaticColliderCacheSettings CacheSettings = new StaticColliderCacheSettings(); internal int ParameterHash = 0; internal bool Processed = false; internal NavigationMeshInputBuilder InputBuilder; diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 216b2a4fe4..b31de066a8 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -211,29 +211,6 @@ public float CalculateHeightScale() return heightScale; } - // TODO: Should provide better way that updates the NavigationMeshCacheObject of the heightfield at rebuilding NavigationMesh. - #region "HACK: Before rebuilding NavigationMesh, use Refresh() to update the NavigationMeshCacheObject of the heightfield." - - [DataMemberIgnore] - [DefaultValue(0)] - public int RefreshCounter; - - /// - /// HACK: Before rebuilding NavigationMesh, use Refresh() to update the NavigationMeshCacheObject of the heightfield. - /// - /// GetHashCode() returns different value after calling this method. - public void Refresh() - { - RefreshCounter = (RefreshCounter + 1) % ushort.MaxValue; - } - - public override int GetHashCode() - { - return (base.GetHashCode() * 397) ^ RefreshCounter; - } - - #endregion - [DataContract] public class CustomHeightScale { From 0b688c8da10a76d3f7f9274ff1ee60455865d41f Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 22 Nov 2019 05:57:10 +0900 Subject: [PATCH 0508/2038] Simplify CalculateHeightScale --- .../Data/HeightfieldColliderShapeDesc.cs | 41 ++++--------------- 1 file changed, 7 insertions(+), 34 deletions(-) diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index b31de066a8..cb808f729c 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -168,47 +168,20 @@ public ColliderShape CreateShape() public float CalculateHeightScale() { - if (HeightfieldType == HeightfieldTypes.Float) - { - return 1f; - } - - float heightScale = 1f; - - var max = Math.Max(Math.Abs(HeightRange.X), Math.Abs(HeightRange.Y)); - switch (HeightfieldType) { - case HeightfieldTypes.Short: + case HeightfieldTypes.Float: + return 1f; - heightScale = max / short.MaxValue; - break; + case HeightfieldTypes.Short: + return Math.Max(Math.Abs(HeightRange.X), Math.Abs(HeightRange.Y)) / short.MaxValue; case HeightfieldTypes.Byte: + return HeightRange.Y / byte.MaxValue; - var minSign = Math.Sign(HeightRange.X); - var maxSign = Math.Sign(HeightRange.Y); - - // min < 0 < max - if (minSign == -1 && maxSign == 1) - { - // Byte can't handle both positive and negative together. - heightScale = HeightRange.Y / byte.MaxValue; - } - // 0 <= min < max - else if (0 <= minSign && maxSign == 1) - { - heightScale = max / byte.MaxValue; - } - // min < max <= 0 - else if (minSign == -1 && maxSign <= 0) - { - heightScale = -(max / byte.MaxValue); - } - break; + default: + return 0f; } - - return heightScale; } [DataContract] From bbdab26c8fd94874b6b8ac187f3790ec9fa6b45f Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 22 Nov 2019 06:27:27 +0900 Subject: [PATCH 0509/2038] Rename HeightmapSize to CustomHeightmapSize --- sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs index d34b6e0278..92c3bc7e54 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs @@ -32,7 +32,7 @@ public partial class HeightmapAsset : AssetWithSource [DataMember(40, "Resize")] [Display(category: "Convert", Expand = ExpandRule.Always)] [NotNull] - public HeightmapSize Size { get; set; } = new HeightmapSize(); + public CustomHeightmapSize Size { get; set; } = new CustomHeightmapSize(); [DataMember(50, "sRGB sampling")] [Display(category: "Convert")] @@ -40,7 +40,7 @@ public partial class HeightmapAsset : AssetWithSource #region "HeightmapSize" [DataContract] - public class HeightmapSize + public class CustomHeightmapSize { [DataMember(0)] [DefaultValue(false)] From 6316828c43adcc52c1ec2ecacc7ecfbef0260edb Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 22 Nov 2019 06:29:15 +0900 Subject: [PATCH 0510/2038] Clean up --- sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs | 4 ++-- .../engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs index fec2c40c2c..04b9063926 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -67,13 +67,13 @@ protected override Task DoCommandOverride(ICommandContext commandC Parameters.Size.Size : new Int2(texImage.Width, texImage.Height); - var heightfieldType = Parameters.Type; - if (texImage.Width != size.X || texImage.Height != size.Y) { textureTool.Resize(texImage, size.X, size.Y, Filter.Rescaling.Nearest); } + var heightfieldType = Parameters.Type; + switch (heightfieldType) { case HeightfieldTypes.Float: diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index cb808f729c..1114023a9d 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -66,7 +66,9 @@ public bool Match(object obj) return false; } - var heightScaleComparison = (other.HeightScale.Enabled && HeightScale.Enabled) ? Math.Abs(other.HeightScale.Scale - HeightScale.Scale) < float.Epsilon : other.HeightScale.Enabled == HeightScale.Enabled; + var heightScaleComparison = (other.HeightScale.Enabled && HeightScale.Enabled) ? + Math.Abs(other.HeightScale.Scale - HeightScale.Scale) < float.Epsilon : + other.HeightScale.Enabled == HeightScale.Enabled; var initialHeightsComparison = (other.InitialHeights == InitialHeights); From 0a54295370872d4f6e7e1618b668c17f33516461 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Sat, 23 Nov 2019 11:16:07 +0900 Subject: [PATCH 0511/2038] Add comment --- .../engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs | 8 ++++++++ sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs | 5 +++++ 2 files changed, 13 insertions(+) diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs index 04b9063926..d7fc92df5b 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -63,6 +63,8 @@ protected override Task DoCommandOverride(ICommandContext commandC using (var textureTool = new TextureTool()) using (var texImage = textureTool.Load(source, Parameters.IsSRgb)) { + // Resize the image if need + var size = Parameters.Size.Enabled && Parameters.Size.Size.X > 1 && Parameters.Size.Size.Y > 1 ? Parameters.Size.Size : new Int2(texImage.Width, texImage.Height); @@ -72,6 +74,8 @@ protected override Task DoCommandOverride(ICommandContext commandC textureTool.Resize(texImage, size.X, size.Y, Filter.Rescaling.Nearest); } + // Convert pixel format of the image + var heightfieldType = Parameters.Type; switch (heightfieldType) @@ -171,6 +175,8 @@ protected override Task DoCommandOverride(ICommandContext commandC continue; } + // Read, scale and set heights + using (var image = textureTool.ConvertToXenkoImage(texImage)) { var pixelBuffer = image.PixelBuffer[0]; @@ -206,6 +212,8 @@ protected override Task DoCommandOverride(ICommandContext commandC continue; } + // Set rest of properties + heightmap.HeightfieldType = heightfieldType; heightmap.Width = size.X; heightmap.Length = size.Y; diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index 8785f8d16e..44441f00e1 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -76,6 +76,11 @@ public void Remove(StaticColliderData colliderData) } } + /// + /// Get specific collider cache settings from the builder + /// + /// Collider component related to the collider cache settings + /// The collider cache settings if there is, null otherwise public StaticColliderCacheSettings GetStaticColliderCacheSettings(StaticColliderComponent staticCollider) { lock (colliders) From 158843763542fc29d4dde9d3736064bf91c6b904 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Thu, 28 Nov 2019 21:12:22 +0900 Subject: [PATCH 0512/2038] [Physics] Change default HeightStickSize --- .../engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 1114023a9d..4f9cb056af 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -44,7 +44,7 @@ public HeightfieldColliderShapeDesc() { InitialHeights = null; HeightfieldType = HeightfieldTypes.Float; - HeightStickSize = new Int2(64, 64); + HeightStickSize = new Int2(65, 65); HeightRange = new Vector2(-10, 10); HeightScale = new CustomHeightScale(); FlipQuadEdges = false; From 876c61aac23a6cecb24cac44d97b53c805793fc1 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 29 Nov 2019 00:10:54 +0900 Subject: [PATCH 0513/2038] [Physics] Fix a bug that tries to update disposed collider shape's debug primitive --- .../Xenko.Physics/Engine/PhysicsShapesRenderingService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Engine/PhysicsShapesRenderingService.cs b/sources/engine/Xenko.Physics/Engine/PhysicsShapesRenderingService.cs index 41b2e42490..3cce11a24a 100644 --- a/sources/engine/Xenko.Physics/Engine/PhysicsShapesRenderingService.cs +++ b/sources/engine/Xenko.Physics/Engine/PhysicsShapesRenderingService.cs @@ -64,7 +64,7 @@ public override void Update(GameTime gameTime) var unusedShapes = new List(); foreach (var keyValuePair in updatableDebugMeshes) { - if (keyValuePair.Value != null && keyValuePair.Key.DebugEntity?.Scene != null) + if (keyValuePair.Value != null && keyValuePair.Key.DebugEntity?.Scene != null && keyValuePair.Key.InternalShape != null) { keyValuePair.Key.UpdateDebugPrimitive(Game.GraphicsContext.CommandList, keyValuePair.Value); } From 07f35a3bb3ef2762569c47b276b2ec94bf23e354 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 29 Nov 2019 04:37:54 +0900 Subject: [PATCH 0514/2038] [Physics] Change default value for IsSRgb --- sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs index 92c3bc7e54..de06fe204c 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs @@ -36,7 +36,7 @@ public partial class HeightmapAsset : AssetWithSource [DataMember(50, "sRGB sampling")] [Display(category: "Convert")] - public bool IsSRgb { get; set; } = true; + public bool IsSRgb { get; set; } = false; #region "HeightmapSize" [DataContract] From 759b00e212110b2c793425e4dd83dec53195f522 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Dec 2019 13:45:05 -0500 Subject: [PATCH 0515/2038] UI: GridList improvements & added PulldownList manager --- sources/engine/Xenko.UI/GridList.cs | 74 +++++++++++-- sources/engine/Xenko.UI/PulldownList.cs | 131 ++++++++++++++++++++++++ 2 files changed, 197 insertions(+), 8 deletions(-) create mode 100644 sources/engine/Xenko.UI/PulldownList.cs diff --git a/sources/engine/Xenko.UI/GridList.cs b/sources/engine/Xenko.UI/GridList.cs index 554c56a679..2f59fa2a77 100644 --- a/sources/engine/Xenko.UI/GridList.cs +++ b/sources/engine/Xenko.UI/GridList.cs @@ -12,21 +12,27 @@ namespace Xenko.UI /// public class GridList { - private Grid myGrid; private UILibrary template; - private Dictionary> entryElements = new Dictionary>(); - private string templateName; - private float entryHeight; + + protected string templateName; + protected Dictionary> entryElements = new Dictionary>(); + protected float entryHeight, entryWidth; + protected Grid myGrid; /// /// Sort alphabetically? /// public bool AlphabeticalSort = false; + /// + /// When adding entries, adjust their width to the grid? + /// + public bool FitEntriesToWidth = true; + /// /// Maximum number of ToggleButtons that can be checked /// - public int MaxCheckedAllowed = 1; + virtual public int MaxCheckedAllowed { get; set; } = 1; /// /// Action to take when a button is clicked or ToggleButton is checked, argument is the value of the entry @@ -54,6 +60,8 @@ public GridList(Grid grid, UILibrary entryTemplate, string templateRootName = nu } else templateName = templateRootName; entryHeight = entryTemplate.UIElements[templateName].Height; + entryWidth = myGrid.Width; + if (float.IsNaN(entryWidth)) entryWidth = myGrid.ActualWidth; } /// @@ -104,6 +112,23 @@ public string GetDisplayName(object value) return null; } + /// + /// Gets whether an entry is toggled + /// + /// Value of entry + /// togglestate of toggle button + public ToggleState GetToggledState(object value) + { + if (entryElements.TryGetValue(value, out var uied)) + { + foreach (UIElement uie in uied.Values) + { + if (uie is ToggleButton tb) return tb.State; + } + } + return ToggleState.Indeterminate; + } + /// /// Add a list of entries to the list /// @@ -115,6 +140,33 @@ public void AddEntries(List entries, bool rebuildVisualListAfter = true) if (rebuildVisualListAfter) RebuildVisualList(); } + /// + /// Toggle an option on the list + /// + /// What option to select + /// + /// if true, deselect others + virtual public void Select(object value, ToggleState toggleState = ToggleState.Checked, bool deselectOthers = false) + { + foreach (var uie in entryElements) + { + foreach (UIElement uiec in uie.Value.Values) + { + if (uiec is ToggleButton tb) + { + if (uie.Key == value) + { + tb.State = toggleState; + } + else if (deselectOthers) + { + tb.State = ToggleState.UnChecked; + } + } + } + } + } + /// /// Add a specific entry to the list /// @@ -122,7 +174,7 @@ public void AddEntries(List entries, bool rebuildVisualListAfter = true) /// What is the underlying value of this entry, can't be duplicates /// If you intend to add more items and want to defer visually updating, set to false /// - public UIElement AddEntry(string displayName, object value = null, bool rebuildVisualListAfter = true) + virtual public UIElement AddEntry(string displayName, object value = null, bool rebuildVisualListAfter = true) { if (value == null) value = displayName; UIElement newEntry = template.InstantiateElement(templateName); @@ -135,6 +187,7 @@ public UIElement AddEntry(string displayName, object value = null, bool rebuildV } else if (uie is ToggleButton tbn) { + if (FitEntriesToWidth) tbn.Width = entryWidth; tbn.Checked += delegate { int alreadyChecked = GetCheckedCount(); if (alreadyChecked == 2 && MaxCheckedAllowed == 1) @@ -157,9 +210,14 @@ public UIElement AddEntry(string displayName, object value = null, bool rebuildV } else if (uie is Button bn) { + if (FitEntriesToWidth) bn.Width = entryWidth; bn.Click += delegate { EntrySelectedAction(value); }; + } + else if (uie is Grid g) + { + if (FitEntriesToWidth) g.Width = entryWidth; } } entryElements[value] = allElements; @@ -233,13 +291,13 @@ public List GetEntries(bool onlyChecked = false) return retList; } - private void AddToList(UIElement uie) + protected void AddToList(UIElement uie) { uie.Margin = new Thickness(0f, uie.Height * myGrid.Children.Count, 0f, 0f); myGrid.Children.Add(uie); } - public void RebuildVisualList() + virtual public void RebuildVisualList() { myGrid.Children.Clear(); if (AlphabeticalSort) diff --git a/sources/engine/Xenko.UI/PulldownList.cs b/sources/engine/Xenko.UI/PulldownList.cs new file mode 100644 index 0000000000..75ace33a99 --- /dev/null +++ b/sources/engine/Xenko.UI/PulldownList.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Xenko.Engine; +using Xenko.UI.Controls; +using Xenko.UI.Panels; + +namespace Xenko.UI +{ + public class PulldownList : GridList + { + /// + /// Is this pulldown list expanded and showing options? + /// + public bool CurrentlyExpanded + { + get + { + return _currentlyExpanded; + } + set + { + if (value != _currentlyExpanded) + { + _currentlyExpanded = value; + RebuildVisualList(); + } + } + } + + /// + /// How many options to display when expanded? + /// + public int OptionsToShow + { + get + { + return _optionsToShow; + } + set + { + _optionsToShow = value; + if (_optionsToShow < 1) _optionsToShow = 1; + } + } + + /// + /// This can only be one + /// + public override int MaxCheckedAllowed + { + get => base.MaxCheckedAllowed; + set + { + base.MaxCheckedAllowed = 1; + } + } + + private int _optionsToShow = 4; + private bool _currentlyExpanded = false; + private ScrollViewer scroll; + private System.EventHandler toggleChanger; + private Dictionary storedOptions = new Dictionary(); + private UIElement pulldownIndicator; + + /// + /// Toggle an option on the list + /// + /// What option to select + /// + /// if true, deselect others + public override void Select(object value, ToggleState toggleState = ToggleState.Checked, bool deselectOthers = false) + { + base.Select(value, toggleState, deselectOthers); + RebuildVisualList(); + } + + /// + /// What is selected right now? + /// + /// Selected option, null otherwise + public object GetSelection() + { + List entries = GetEntries(true); + if (entries == null || entries.Count == 0) return null; + return entries[0]; + } + + /// + /// Constructor for a pulldown list + /// + /// Grid, which needs to be inside of a scrollviewer + /// What to use for entries in the list? + /// Optional UIElement that will be shown when not expanded, like a down arrow + /// Name of the UIElement to clone when making list entries, can be null to determine automatically + public PulldownList(Grid grid, UILibrary entryTemplate, UIElement pulldownIndicator = null, string templateRootName = null) : base(grid, entryTemplate, templateRootName) + { + toggleChanger = delegate + { + _currentlyExpanded = !_currentlyExpanded; + RebuildVisualList(); + }; + scroll = grid.Parent as ScrollViewer; + if (scroll == null) throw new ArgumentException("Grid needs a ScrollViewer as Parent"); + scroll.ScrollMode = ScrollingMode.Vertical; + myGrid.Height = entryHeight; + this.pulldownIndicator = pulldownIndicator; + } + + public override UIElement AddEntry(string displayName, object value = null, bool rebuildVisualListAfter = true) + { + ButtonBase added = base.AddEntry(displayName, value, rebuildVisualListAfter) as ButtonBase; + added.Click -= toggleChanger; + added.Click += toggleChanger; + return added; + } + + override public void RebuildVisualList() + { + myGrid.Children.Clear(); + foreach (var uie in entryElements.OrderBy(i => GetToggledState(i.Key))) + { + AddToList(uie.Value[templateName]); + } + if (pulldownIndicator != null) pulldownIndicator.Visibility = _currentlyExpanded ? Visibility.Hidden : Visibility.Visible; + scroll.Height = _currentlyExpanded ? entryHeight * Math.Min(entryElements.Count, _optionsToShow + 0.5f) : entryHeight; + myGrid.Height = _currentlyExpanded ? entryHeight * entryElements.Count : entryHeight; + } + } +} From 5637c6f7482c0c10a5aee93d913e7057e3df97b8 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Dec 2019 13:46:37 -0500 Subject: [PATCH 0516/2038] SceneSystem: automatically find a camera if slot is not set --- .../Compositing/SceneCameraRenderer.cs | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/SceneCameraRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/SceneCameraRenderer.cs index 6d8b42f807..0a319f11ae 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/SceneCameraRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/SceneCameraRenderer.cs @@ -85,7 +85,27 @@ protected virtual CameraComponent ResolveCamera(RenderContext renderContext) var camera = Camera?.Camera; if (camera == null && !cameraResolutionFailed) + { + // no slot set, try to set one automatically + SceneSystem ss = renderContext.Services.GetService(); + GraphicsCompositor gc = ss?.GraphicsCompositor; + if (gc != null) + { + foreach (Entity e in ss.SceneInstance.RootScene.Entities) + { + CameraComponent cam = e.Get(); + if (cam != null) + { + cam.Slot = gc.Cameras[0].ToSlotId(); + camera = cam; + break; + } + } + } + + if (camera == null) Logger.Warning($"{nameof(SceneCameraRenderer)} [{Id}] has no camera assigned to its {nameof(CameraComponent.Slot)}[{Camera.Name}]. Make sure a camera is enabled and assigned to the corresponding {nameof(CameraComponent.Slot)}."); + } cameraResolutionFailed = camera == null; From 57c37ea4bd955e74c429c26987df300a10d09886 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Mon, 2 Dec 2019 21:12:38 +0900 Subject: [PATCH 0517/2038] [Physics] Change types of Floats, Shorts and Bytes from List to arrays --- .../Xenko.Assets/Physics/HeightmapAssetCompiler.cs | 12 ++++++------ .../Data/HeightfieldColliderShapeDesc.cs | 6 +++--- sources/engine/Xenko.Physics/Engine/Heightmap.cs | 12 ++++++------ .../Xenko.Physics/Engine/HeightmapExtensions.cs | 6 +++--- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs index d7fc92df5b..0137a5e9f5 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -185,24 +185,24 @@ protected override Task DoCommandOverride(ICommandContext commandC switch (heightfieldType) { case HeightfieldTypes.Float: - heightmap.Floats = pixelBuffer.GetPixels().ToList(); - for (int i = 0; i < heightmap.Floats.Count; ++i) + heightmap.Floats = pixelBuffer.GetPixels(); + for (int i = 0; i < heightmap.Floats.Length; ++i) { heightmap.Floats[i] *= scale; } break; case HeightfieldTypes.Short: - heightmap.Shorts = pixelBuffer.GetPixels().ToList(); - for (int i = 0; i < heightmap.Shorts.Count; ++i) + heightmap.Shorts = pixelBuffer.GetPixels(); + for (int i = 0; i < heightmap.Shorts.Length; ++i) { heightmap.Shorts[i] = (short)MathUtil.Clamp(heightmap.Shorts[i] * scale, short.MinValue, short.MaxValue); } break; case HeightfieldTypes.Byte: - heightmap.Bytes = pixelBuffer.GetPixels().ToList(); - for (int i = 0; i < heightmap.Bytes.Count; ++i) + heightmap.Bytes = pixelBuffer.GetPixels(); + for (int i = 0; i < heightmap.Bytes.Length; ++i) { heightmap.Bytes[i] = (byte)MathUtil.Clamp(heightmap.Bytes[i] * scale, byte.MinValue, byte.MaxValue); } diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 4f9cb056af..b1d2c496ba 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -131,17 +131,17 @@ public ColliderShape CreateShape() { case HeightfieldTypes.Float: { - unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Floats?.ToArray()); + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Floats); break; } case HeightfieldTypes.Short: { - unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Shorts?.ToArray()); + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Shorts); break; } case HeightfieldTypes.Byte: { - unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Bytes?.ToArray()); + unmanagedArray = CreateHeights(arrayLength, InitialHeights?.Bytes); break; } diff --git a/sources/engine/Xenko.Physics/Engine/Heightmap.cs b/sources/engine/Xenko.Physics/Engine/Heightmap.cs index 8cb29e12e6..90971da21a 100644 --- a/sources/engine/Xenko.Physics/Engine/Heightmap.cs +++ b/sources/engine/Xenko.Physics/Engine/Heightmap.cs @@ -16,15 +16,15 @@ public class Heightmap { [DataMember(10)] [Display(Browsable = false)] - public List Floats; + public float[] Floats; [DataMember(20)] [Display(Browsable = false)] - public List Shorts; + public short[] Shorts; [DataMember(30)] [Display(Browsable = false)] - public List Bytes; + public byte[] Bytes; [DataMember(40)] [Display(Browsable = false)] @@ -52,7 +52,7 @@ public static Heightmap Create(int width, int length, T[] data) where T : str HeightfieldType = HeightfieldTypes.Float, Width = width, Length = length, - Floats = new List(data as float[]), + Floats = data as float[], }; } else if (type == typeof(short[])) @@ -62,7 +62,7 @@ public static Heightmap Create(int width, int length, T[] data) where T : str HeightfieldType = HeightfieldTypes.Short, Width = width, Length = length, - Shorts = new List(data as short[]), + Shorts = data as short[], }; } else if (type == typeof(byte[])) @@ -72,7 +72,7 @@ public static Heightmap Create(int width, int length, T[] data) where T : str HeightfieldType = HeightfieldTypes.Byte, Width = width, Length = length, - Bytes = new List(data as byte[]), + Bytes = data as byte[], }; } diff --git a/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs b/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs index cd3b249403..8a88236827 100644 --- a/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs +++ b/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs @@ -27,13 +27,13 @@ public static Texture CreateTexture([NotNull] this Heightmap heightmap, Graphics switch (heightmap.HeightfieldType) { case HeightfieldTypes.Float: - return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R32_Float, heightmap.Floats?.ToArray()); + return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R32_Float, heightmap.Floats); case HeightfieldTypes.Short: - return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R16_SNorm, heightmap.Shorts?.ToArray()); + return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R16_SNorm, heightmap.Shorts); case HeightfieldTypes.Byte: - return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R8_UNorm, heightmap.Bytes?.ToArray()); + return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R8_UNorm, heightmap.Bytes); default: return null; From cc92ad69613880ef1ea1e09ae04951d21e289d22 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Mon, 2 Dec 2019 21:59:22 +0900 Subject: [PATCH 0518/2038] Revert "[Physics] Fix HeightScale that is 1 when HeightfieldTypes.Float" This reverts commit 00ce45191289da4ecbc8006f783a40e457ee0251. --- sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs b/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs index fa11b9d97d..d3a0a482b3 100644 --- a/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs +++ b/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs @@ -68,7 +68,7 @@ bool flipQuadEdges HeightStickWidth = heightStickWidth; HeightStickLength = heightStickLength; HeightType = heightType; - HeightScale = (HeightType == HeightfieldTypes.Float) ? 1f : heightScale; + HeightScale = heightScale; MinHeight = minHeight; MaxHeight = maxHeight; From 06187d02a02b3da68b7b461eff267207cd5cc6a6 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Dec 2019 15:09:13 -0500 Subject: [PATCH 0519/2038] VR: Option to have Camera's Transform be updated with VR Head (like Unity) --- .../engine/Xenko.Engine/Engine/CameraComponent.cs | 6 ++++++ .../Rendering/Compositing/ForwardRenderer.cs | 13 +++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/CameraComponent.cs b/sources/engine/Xenko.Engine/Engine/CameraComponent.cs index 24ac2b240b..8032d7fbd6 100644 --- a/sources/engine/Xenko.Engine/Engine/CameraComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/CameraComponent.cs @@ -143,6 +143,12 @@ public CameraComponent(float nearClipPlane, float farClipPlane) [DataMember(50)] public SceneCameraSlotId Slot; + /// + /// If this is a VR camera, have the local transform follow the head? + /// + [DataMember] + public bool VRHeadSetsTransform = false; + /// /// Gets or sets a value indicating whether to use custom . Default is false /// diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index 80fa70af79..13f5fc3f5f 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -327,9 +327,18 @@ protected override unsafe void CollectCore(RenderContext context) Vector3.TransformCoordinate(ref cameraPos, ref cameraRot, out cameraPos); } - if (VRSettings.IgnoreCameraRotation) + if (VRSettings.IgnoreCameraRotation || camera.VRHeadSetsTransform) { - cameraRot = Matrix.Identity; + // only remove the local rotation of the camera + cameraRot *= Matrix.RotationQuaternion(Quaternion.Invert(camera.Entity.Transform.Rotation)); + } + + if (camera.VRHeadSetsTransform) + { + // take out my local position, which isn't meant to be passed on, but set by the VR head + cameraPos -= camera.Entity.Transform.Position; + camera.Entity.Transform.Position = VRSettings.VRDevice.HeadPosition; + camera.Entity.Transform.Rotation = VRSettings.VRDevice.HeadRotation; } // Compute both view and projection matrices From 81c819529c871826039829338b0aadff6ac323af Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Dec 2019 15:09:35 -0500 Subject: [PATCH 0520/2038] VR: more useful default ResolutionScale --- .../Xenko.Engine/Rendering/Compositing/VRDeviceDescription.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/VRDeviceDescription.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/VRDeviceDescription.cs index c53e57c6be..2fdf14b3ee 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/VRDeviceDescription.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/VRDeviceDescription.cs @@ -1,4 +1,4 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; @@ -15,6 +15,6 @@ public class VRDeviceDescription public VRApi Api { get; set; } [DataMember(20)] - public float ResolutionScale { get; set; } = 1.0f; + public float ResolutionScale { get; set; } = 1.4f; } } From 4fa2ee8bfa4258374165d2286f050fd8d39d9f98 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 2 Dec 2019 14:59:01 +0100 Subject: [PATCH 0521/2038] [VSPackage] Properly initialize if package is loaded AFTER solution --- .../Xenko.VisualStudio.Package/SolutionEventsListener.cs | 4 ++-- sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/sources/tools/Xenko.VisualStudio.Package/SolutionEventsListener.cs b/sources/tools/Xenko.VisualStudio.Package/SolutionEventsListener.cs index 328dc08b1a..b04d8f0337 100644 --- a/sources/tools/Xenko.VisualStudio.Package/SolutionEventsListener.cs +++ b/sources/tools/Xenko.VisualStudio.Package/SolutionEventsListener.cs @@ -15,7 +15,7 @@ public class SolutionEventsListener : IVsSolutionEvents, IVsSolutionLoadEvents, private uint updateSolutionEventsCookie; private uint selectionEventsCoockie; - public event Action AfterSolutionLoaded; + public event Action AfterSolutionOpened; public event Action AfterSolutionBackgroundLoadComplete; public event Action BeforeSolutionClosed; @@ -89,7 +89,7 @@ int IVsSolutionEvents.OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded) int IVsSolutionEvents.OnAfterOpenSolution(object pUnkReserved, int fNewSolution) { - AfterSolutionLoaded?.Invoke(); + AfterSolutionOpened?.Invoke(); return VSConstants.S_OK; } diff --git a/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs b/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs index 39819d1d0c..34e90f81da 100644 --- a/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs +++ b/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs @@ -120,7 +120,7 @@ protected override async Task InitializeAsync(CancellationToken cancellationToke solutionEventsListener = new SolutionEventsListener(this); solutionEventsListener.BeforeSolutionClosed += solutionEventsListener_BeforeSolutionClosed; - solutionEventsListener.AfterSolutionBackgroundLoadComplete += solutionEventsListener_AfterSolutionBackgroundLoadComplete; + solutionEventsListener.AfterSolutionOpened += solutionEventsListener_AfterSolutionOpened; solutionEventsListener.AfterActiveConfigurationChange += SolutionEventsListener_AfterActiveConfigurationChange; solutionEventsListener.StartupProjectChanged += SolutionEventsListener_OnStartupProjectChanged; @@ -167,6 +167,11 @@ protected override async Task InitializeAsync(CancellationToken cancellationToke int hr = mgr.FRegisterComponent(this, crinfo, out m_componentID); } + // If there's already a solution loaded, process it + var dte = (DTE)GetService(typeof(DTE)); + if (dte.Solution.IsOpen) + await InitializeCommandProxy(); + // Go back to async thread await TaskScheduler.Default; } @@ -305,7 +310,7 @@ private void UpdateStartupProjectFromConfiguration() } } - private async void solutionEventsListener_AfterSolutionBackgroundLoadComplete() + private async void solutionEventsListener_AfterSolutionOpened() { await InitializeCommandProxy(); } From 821d93f5107b18aff6ab33b539f64b47eb19c4e2 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 2 Dec 2019 14:59:51 +0100 Subject: [PATCH 0522/2038] [VSPackage] Changed code generators to keep xksl/xkfx output before the .cs --- .../Xenko.Core.Assets/AssetItemExtensions.cs | 4 +- .../Xenko.Core.Assets/PackageSession.cs | 8 +-- .../Effect/EffectCompositorAsset.cs | 2 +- .../Xenko.Assets/XenkoPackageUpgrader.cs | 45 +++++++++++++++++ sources/shared/SharedAssemblyInfo.cs | 2 +- .../Commands/XenkoCommandsProxy.cs | 5 ++ .../tools/Xenko.VisualStudio.Package/Guids.cs | 1 + .../Shaders/EffectCodeFileGenerator.cs | 49 +++++++++++++++++++ .../Shaders/ShaderKeyFileGenerator.cs | 10 +++- .../Xenko.VisualStudio.Package.nuspec | 2 +- .../XenkoPackage.cs | 7 ++- .../source.extension.vsixmanifest | 2 +- 12 files changed, 124 insertions(+), 13 deletions(-) create mode 100644 sources/tools/Xenko.VisualStudio.Package/Shaders/EffectCodeFileGenerator.cs diff --git a/sources/assets/Xenko.Core.Assets/AssetItemExtensions.cs b/sources/assets/Xenko.Core.Assets/AssetItemExtensions.cs index 34e2ddc671..636cdf441a 100644 --- a/sources/assets/Xenko.Core.Assets/AssetItemExtensions.cs +++ b/sources/assets/Xenko.Core.Assets/AssetItemExtensions.cs @@ -29,7 +29,7 @@ public static string GetProjectInclude([NotNull] this AssetItem assetItem) [NotNull] public static UFile GetGeneratedAbsolutePath([NotNull] this AssetItem assetItem) { - return new UFile(new UFile(assetItem.FullPath).GetFullPathWithoutExtension() + ".cs"); + return new UFile(assetItem.FullPath + ".cs"); } /// @@ -39,7 +39,7 @@ public static UFile GetGeneratedAbsolutePath([NotNull] this AssetItem assetItem) /// public static string GetGeneratedInclude([NotNull] this AssetItem assetItem) { - return Path.ChangeExtension(GetProjectInclude(assetItem), ".cs"); + return GetProjectInclude(assetItem) + ".cs"; } } } diff --git a/sources/assets/Xenko.Core.Assets/PackageSession.cs b/sources/assets/Xenko.Core.Assets/PackageSession.cs index b2cd6071f2..6e7ce3f05a 100644 --- a/sources/assets/Xenko.Core.Assets/PackageSession.cs +++ b/sources/assets/Xenko.Core.Assets/PackageSession.cs @@ -156,7 +156,9 @@ public void Save(ILogger log, PackageSaveParameters saveParameters = null) } //check if the item is already there, this is possible when saving the first time when creating from a template - if (project.Items.All(x => x.EvaluatedInclude != projectInclude)) + // Note: if project has auto items, no need to add it + if (project.Items.All(x => x.EvaluatedInclude != projectInclude) + && (string.Compare(project.GetPropertyValue("EnableDefaultCompileItems"), "true", true, CultureInfo.InvariantCulture) != 0)) { var generatorAsset = projectAsset as IProjectFileGeneratorAsset; if (generatorAsset != null) @@ -181,9 +183,7 @@ public void Save(ILogger log, PackageSaveParameters saveParameters = null) } else { - // Note: if project has auto items, no need to add it - if (string.Compare(project.GetPropertyValue("EnableDefaultCompileItems"), "true", true, CultureInfo.InvariantCulture) != 0) - project.AddItem("Compile", projectInclude); + project.AddItem("Compile", projectInclude); } } } diff --git a/sources/engine/Xenko.Assets/Effect/EffectCompositorAsset.cs b/sources/engine/Xenko.Assets/Effect/EffectCompositorAsset.cs index aff901becc..e68b3cf6f8 100644 --- a/sources/engine/Xenko.Assets/Effect/EffectCompositorAsset.cs +++ b/sources/engine/Xenko.Assets/Effect/EffectCompositorAsset.cs @@ -17,7 +17,7 @@ public sealed partial class EffectCompositorAsset : ProjectSourceCodeWithFileGen /// public const string FileExtension = ".xkfx"; - public override string Generator => "XenkoShaderKeyGenerator"; + public override string Generator => "XenkoEffectCodeGenerator"; public override void SaveGeneratedAsset(AssetItem assetItem) { diff --git a/sources/engine/Xenko.Assets/XenkoPackageUpgrader.cs b/sources/engine/Xenko.Assets/XenkoPackageUpgrader.cs index 08c9778097..4b0ed7c086 100644 --- a/sources/engine/Xenko.Assets/XenkoPackageUpgrader.cs +++ b/sources/engine/Xenko.Assets/XenkoPackageUpgrader.cs @@ -141,6 +141,51 @@ public override bool UpgradeBeforeAssembliesLoaded(PackageLoadParameters loadPar } } + // Change shader generated file from .cs to .xksl.cs or .xkfx.cs + if (dependency.Version.MinVersion < new PackageVersion("3.2.0.1-beta02")) + { + // Find xksl files + var shaderFiles = project.Items.Where(x => x.ItemType == "None" && (x.EvaluatedInclude.EndsWith(".xksl", StringComparison.InvariantCultureIgnoreCase) || x.EvaluatedInclude.EndsWith(".xkfx", StringComparison.InvariantCultureIgnoreCase)) && x.HasMetadata("Generator")); + + foreach (var shaderFile in shaderFiles) + { + var shaderFilePath = Path.Combine(projectFullPath.GetFullDirectory(), new UFile(shaderFile.EvaluatedInclude)); + var oldGeneratedFilePath = Path.ChangeExtension(shaderFilePath, ".cs"); + + if (File.Exists(oldGeneratedFilePath)) + { + File.Move(oldGeneratedFilePath, shaderFilePath + ".cs"); + + // Update project (directly with Xml since it is an Update element, not an Include) + foreach (var csElement in project.Xml.ItemGroups.SelectMany(x => x.Items).Where(x => new UFile(x.Update) == new UFile(Path.ChangeExtension(shaderFile.EvaluatedInclude, ".cs")))) + { + csElement.Update = shaderFile.EvaluatedInclude + ".cs"; + isProjectDirty = true; + } + // I think we should have only Update, not Include, but let's do that just in case + foreach (var csElement in project.Xml.ItemGroups.SelectMany(x => x.Items).Where(x => new UFile(x.Include) == new UFile(Path.ChangeExtension(shaderFile.EvaluatedInclude, ".cs")))) + { + csElement.Include = shaderFile.EvaluatedInclude + ".cs"; + isProjectDirty = true; + } + + if (shaderFile.EvaluatedInclude.EndsWith(".xkfx", StringComparison.InvariantCultureIgnoreCase)) + { + shaderFile.GetMetadata("Generator").UnevaluatedValue = "XenkoEffectCodeGenerator"; + isProjectDirty = true; + } + + // Also update LastGenOutput + var lastGenOutputMetadata = shaderFile.GetMetadata("LastGenOutput"); + if (lastGenOutputMetadata != null && !lastGenOutputMetadata.IsImported) + { + lastGenOutputMetadata.UnevaluatedValue = new UFile(shaderFile.EvaluatedInclude + ".cs").GetFileName(); + isProjectDirty = true; + } + } + } + } + if (isProjectDirty) project.Save(); diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 3811d3fbed..c3b23f22e2 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = "-beta01"; + public const string NuGetVersionSuffix = "-beta02"; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. diff --git a/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs b/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs index d900769f8b..1bdeb744a5 100644 --- a/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs +++ b/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs @@ -44,6 +44,11 @@ public struct PackageInfo private readonly IXenkoCommands remote; private readonly List> assembliesLoaded = new List>(); + public static PackageInfo CurrentPackageInfo + { + get { lock (computedPackageInfoLock) { return computedPackageInfo; } } + } + static XenkoCommandsProxy() { // This assembly resolve is only used to resolve the GetExecutingAssembly on the Default Domain diff --git a/sources/tools/Xenko.VisualStudio.Package/Guids.cs b/sources/tools/Xenko.VisualStudio.Package/Guids.cs index 4e0d161b99..73381b9474 100644 --- a/sources/tools/Xenko.VisualStudio.Package/Guids.cs +++ b/sources/tools/Xenko.VisualStudio.Package/Guids.cs @@ -11,6 +11,7 @@ internal static class GuidList public const string guidToolWindowPersistanceString = "ddd10155-9f63-4694-95ce-c7ba2d74ad46"; public const string guidXenko_VisualStudio_ShaderKeyFileGenerator = "b50e6ece-b11f-477b-a8e1-1e60e0531a53"; + public const string guidXenko_VisualStudio_EffectCodeFileGenerator = "e6259cfb-c775-426e-b499-f57d0a3ba2c1"; public const string guidXenko_VisualStudio_DataCodeGenerator = "22555301-d58a-4d71-9dab-b2552cc3de0e"; diff --git a/sources/tools/Xenko.VisualStudio.Package/Shaders/EffectCodeFileGenerator.cs b/sources/tools/Xenko.VisualStudio.Package/Shaders/EffectCodeFileGenerator.cs new file mode 100644 index 0000000000..a37e197067 --- /dev/null +++ b/sources/tools/Xenko.VisualStudio.Package/Shaders/EffectCodeFileGenerator.cs @@ -0,0 +1,49 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; +using Microsoft.VisualStudio.Shell; +using Xenko.VisualStudio.CodeGenerator; +using Xenko.VisualStudio.Commands; + +namespace Xenko.VisualStudio.Shaders +{ + [ComVisible(true)] + [ClassInterface(ClassInterfaceType.None)] + [Guid(GuidList.guidXenko_VisualStudio_EffectCodeFileGenerator)] + [ProvideObject(typeof(EffectCodeFileGenerator), RegisterUsing = RegistrationMethod.CodeBase)] + public class EffectCodeFileGenerator : BaseCodeGeneratorWithSite + { + public const string DisplayName = "Xenko Effect C# Code Generator"; + public const string InternalName = "XenkoEffectCodeGenerator"; + + protected override string GetDefaultExtension() + { + return ".xkfx.cs"; + } + + protected override byte[] GenerateCode(string inputFileName, string inputFileContent) + { + + try + { + return System.Threading.Tasks.Task.Run(() => + { + var remoteCommands = XenkoCommandsProxy.GetProxy(); + return remoteCommands.GenerateShaderKeys(inputFileName, inputFileContent); + }).Result; + } + catch (Exception ex) + { + GeneratorError(4, ex.ToString(), 0, 0); + + return new byte[0]; + } + } + } +} diff --git a/sources/tools/Xenko.VisualStudio.Package/Shaders/ShaderKeyFileGenerator.cs b/sources/tools/Xenko.VisualStudio.Package/Shaders/ShaderKeyFileGenerator.cs index c269289f9a..7a980d6903 100644 --- a/sources/tools/Xenko.VisualStudio.Package/Shaders/ShaderKeyFileGenerator.cs +++ b/sources/tools/Xenko.VisualStudio.Package/Shaders/ShaderKeyFileGenerator.cs @@ -8,6 +8,7 @@ using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.Shell; +using Xenko.Core; using Xenko.VisualStudio.CodeGenerator; using Xenko.VisualStudio.Commands; @@ -24,7 +25,14 @@ public class ShaderKeyFileGenerator : BaseCodeGeneratorWithSite protected override string GetDefaultExtension() { - return ".cs"; + // Figure out extension (different in case of versions before 3.1.0.2-beta01) + if (XenkoCommandsProxy.CurrentPackageInfo.ExpectedVersion != null + && XenkoCommandsProxy.CurrentPackageInfo.ExpectedVersion < new PackageVersion("3.2.0.1-beta02")) + { + return ".cs"; + } + + return ".xksl.cs"; } protected override byte[] GenerateCode(string inputFileName, string inputFileContent) diff --git a/sources/tools/Xenko.VisualStudio.Package/Xenko.VisualStudio.Package.nuspec b/sources/tools/Xenko.VisualStudio.Package/Xenko.VisualStudio.Package.nuspec index 4fb6bd8bfb..ae2070585a 100644 --- a/sources/tools/Xenko.VisualStudio.Package/Xenko.VisualStudio.Package.nuspec +++ b/sources/tools/Xenko.VisualStudio.Package/Xenko.VisualStudio.Package.nuspec @@ -2,7 +2,7 @@ Xenko.VisualStudio.Package - 3.0.7 + 3.0.9 Xenko Xenko https://github.com/xenko3d/xenko/blob/master/LICENSE.md diff --git a/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs b/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs index 34e90f81da..cb80a3844a 100644 --- a/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs +++ b/sources/tools/Xenko.VisualStudio.Package/XenkoPackage.cs @@ -64,12 +64,15 @@ namespace Xenko.VisualStudio )] [ProvideLanguageExtensionAttribute(typeof(NShaderLanguageService), NShaderSupportedExtensions.Xenko_Shader)] [ProvideLanguageExtensionAttribute(typeof(NShaderLanguageService), NShaderSupportedExtensions.Xenko_Effect)] + // Xenko C# Effect Code Generator + [CodeGeneratorRegistration(typeof(EffectCodeFileGenerator), EffectCodeFileGenerator.InternalName, GuidList.vsContextGuidVCSProject, GeneratorRegKeyName = ".xkfx")] + [CodeGeneratorRegistration(typeof(EffectCodeFileGenerator), EffectCodeFileGenerator.DisplayName, GuidList.vsContextGuidVCSProject, GeneratorRegKeyName = EffectCodeFileGenerator.InternalName, GeneratesDesignTimeSource = true, GeneratesSharedDesignTimeSource = true)] + [CodeGeneratorRegistration(typeof(EffectCodeFileGenerator), EffectCodeFileGenerator.InternalName, GuidList.vsContextGuidVCSNewProject, GeneratorRegKeyName = ".xkfx")] + [CodeGeneratorRegistration(typeof(EffectCodeFileGenerator), EffectCodeFileGenerator.DisplayName, GuidList.vsContextGuidVCSNewProject, GeneratorRegKeyName = EffectCodeFileGenerator.InternalName, GeneratesDesignTimeSource = true, GeneratesSharedDesignTimeSource = true)] // Xenko C# Shader Key Generator [CodeGeneratorRegistration(typeof(ShaderKeyFileGenerator), ShaderKeyFileGenerator.InternalName, GuidList.vsContextGuidVCSProject, GeneratorRegKeyName = ".xksl")] - [CodeGeneratorRegistration(typeof(ShaderKeyFileGenerator), ShaderKeyFileGenerator.InternalName, GuidList.vsContextGuidVCSProject, GeneratorRegKeyName = ".xkfx")] [CodeGeneratorRegistration(typeof(ShaderKeyFileGenerator), ShaderKeyFileGenerator.DisplayName, GuidList.vsContextGuidVCSProject, GeneratorRegKeyName = ShaderKeyFileGenerator.InternalName, GeneratesDesignTimeSource = true, GeneratesSharedDesignTimeSource = true)] [CodeGeneratorRegistration(typeof(ShaderKeyFileGenerator), ShaderKeyFileGenerator.InternalName, GuidList.vsContextGuidVCSNewProject, GeneratorRegKeyName = ".xksl")] - [CodeGeneratorRegistration(typeof(ShaderKeyFileGenerator), ShaderKeyFileGenerator.InternalName, GuidList.vsContextGuidVCSNewProject, GeneratorRegKeyName = ".xkfx")] [CodeGeneratorRegistration(typeof(ShaderKeyFileGenerator), ShaderKeyFileGenerator.DisplayName, GuidList.vsContextGuidVCSNewProject, GeneratorRegKeyName = ShaderKeyFileGenerator.InternalName, GeneratesDesignTimeSource = true, GeneratesSharedDesignTimeSource = true)] // Temporarily force load for easier debugging [ProvideMenuResource("Menus.ctmenu", 1)] diff --git a/sources/tools/Xenko.VisualStudio.Package/source.extension.vsixmanifest b/sources/tools/Xenko.VisualStudio.Package/source.extension.vsixmanifest index c33189dc16..0a88be6914 100644 --- a/sources/tools/Xenko.VisualStudio.Package/source.extension.vsixmanifest +++ b/sources/tools/Xenko.VisualStudio.Package/source.extension.vsixmanifest @@ -1,7 +1,7 @@ - + Xenko Xenko VisualStudio Package Logo.ico From c21a3a50137f9eb6bead316e0368e31ed1dc7f26 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 2 Dec 2019 20:30:56 +0100 Subject: [PATCH 0523/2038] [Build] xksl.cs/xkfx.cs are now included automatically (fixes #554) # Conflicts: # sources/engine/Xenko.Rendering/Xenko.Rendering.csproj --- .../Xenko.Core.Assets.CompilerApp.targets | 12 + ...eviewTexture.cs => PreviewTexture.xkfx.cs} | 0 ...eters.cs => SceneEditorParameters.xkfx.cs} | 0 ...lectedSprite.cs => SelectedSprite.xkfx.cs} | 0 ...> XenkoEditorForwardShadingEffect.xkfx.cs} | 0 ... => XenkoEditorHighlightingEffect.xkfx.cs} | 0 ... XenkoEditorMaterialPreviewEffect.xkfx.cs} | 0 .../Xenko.Assets.Presentation.csproj | 13 - .../ActivityAndroid.cs | 33 - .../Application.iOS.cs | 31 - .../Assets/LightTiling.cs | 2 - .../Assets/LightTiling.xksl | 4 +- .../Assets/LightTiling.xksl.cs | 25 + ...cs => MultipleRenderTargetsEffect.xkfx.cs} | 0 .../MultipleRenderTargetsEffectShader.xksl.cs | 0 .../Xenko.Graphics.Tests.10_0/Info.plist | 30 - .../Properties/AndroidManifest.xml | 9 - .../Properties/AssemblyInfo.Android.cs | 43 - .../Properties/AssemblyInfo.cs | 29 - .../Resources/Drawable/icon.png | 3 - .../Resources/Icon-60@2x.png | 3 - .../Resources/Icon.png | 3 - .../Resources/Icon@2x.png | 3 - .../Resources/Resource.Designer.cs | 293 -- .../TestCubemapDeferred.cs | 163 - .../TestCubemapDisplay.cs | 116 - .../TestCubemapRendering.cs | 193 - .../Xenko.Graphics.Tests.10_0.Android.csproj | 118 - .../Xenko.Graphics.Tests.10_0.Windows.csproj | 40 +- .../Xenko.Graphics.Tests.10_0.iOS.csproj | 160 - .../ActivityAndroid.cs | 33 - .../Application.iOS.cs | 31 - ...haderTest.cs => ComputeShaderTest.xksl.cs} | 0 ...ect.cs => ComputeShaderTestEffect.xkfx.cs} | 0 ...CubemapSprite.cs => CubemapSprite.xksl.cs} | 0 ...mmersleyTest.cs => HammersleyTest.xksl.cs} | 0 .../Xenko.Graphics.Tests.11_0/Info.plist | 32 - .../Properties/AndroidManifest.xml | 9 - .../Properties/AssemblyInfo.Android.cs | 43 - .../Properties/AssemblyInfo.cs | 29 - .../Resources/Drawable/icon.png | 3 - .../Resources/Icon-60@2x.png | 3 - .../Resources/Icon.png | 3 - .../Resources/Icon@2x.png | 3 - .../Resources/Resource.Designer.cs | 293 -- .../Xenko.Graphics.Tests.11_0.Android.csproj | 138 - .../Xenko.Graphics.Tests.11_0.Windows.csproj | 61 +- .../Xenko.Graphics.Tests.11_0.iOS.csproj | 183 - .../Xenko.Graphics.Tests/ActivityAndroid.cs | 33 - .../Xenko.Graphics.Tests/Application.iOS.cs | 31 - .../Compiler/CubemapEffect.xkfx | 3 - ...CubemapEffect.cs => CubemapEffect.xkfx.cs} | 2 - .../{CustomEffect.cs => CustomEffect.xkfx.cs} | 0 .../{CustomShader.cs => CustomShader.xksl.cs} | 0 ...t.cs => MultiTexturesSpriteEffect.xkfx.cs} | 0 .../MultiTexturesSpriteShader.xksl.cs} | 0 .../{SimpleEffect.cs => SimpleEffect.xkfx.cs} | 0 .../{SimpleShader.cs => SimpleShader.xksl.cs} | 0 .../{ToGlslEffect.cs => ToGlslEffect.xkfx.cs} | 0 .../{ToGlslShader.cs => ToGlslShader.xksl.cs} | 0 .../Properties/AndroidManifest.xml | 9 - .../Properties/AssemblyInfo.Android.cs | 43 - .../Properties/AssemblyInfo.cs | 29 - .../Resources/Drawable/icon.png | 3 - .../Resources/Icon-60@2x.png | 3 - .../Xenko.Graphics.Tests/Resources/Icon.png | 3 - .../Resources/Icon@2x.png | 3 - .../Resources/Resource.Designer.cs | 293 -- .../TestCubemapDeferred.cs | 163 - .../TestCubemapDisplay.cs | 116 - .../TestCubemapRendering.cs | 193 - .../Xenko.Graphics.Tests.Android.csproj | 219 - .../Xenko.Graphics.Tests.Shared.targets | 93 - .../Xenko.Graphics.Tests.Windows.csproj | 120 +- .../Xenko.Graphics.Tests.iOS.csproj | 242 - .../Shaders/ColorUtility.xksl.cs} | 0 .../{ColorUtility.cs => ShaderBase.xksl.cs} | 0 ...ShaderBase.cs => ShaderBaseStream.xksl.cs} | 0 ...eam.cs => SignedDistanceFieldFont.xksl.cs} | 0 ... => SignedDistanceFieldFontShader.xksl.cs} | 0 ...phaCutoff.cs => SpriteAlphaCutoff.xksl.cs} | 0 .../{SpriteBase.cs => SpriteBase.xksl.cs} | 0 .../{SpriteBatch.cs => SpriteBatch.xkfx.cs} | 0 ...ontShader.cs => SpriteBatchShader.xksl.cs} | 0 .../{SpriteEffect.cs => SpriteEffect.xksl.cs} | 0 ...ture.cs => SpriteEffectExtTexture.xksl.cs} | 0 ... => SpriteEffectExtTextureRegular.xksl.cs} | 0 ...riteSignedDistanceFieldFontShader.xksl.cs} | 0 ...chShader.cs => SpriteSuperSampler.xksl.cs} | 0 .../{Texturing.cs => Texturing.xksl.cs} | 0 .../Shaders/{UIEffect.cs => UIEffect.xkfx.cs} | 0 ...SuperSampler.cs => UIEffectShader.xksl.cs} | 0 .../Xenko.Graphics/Xenko.Graphics.csproj | 187 +- .../Shaders/ComputeColorWhite.xksl.cs} | 0 .../{ParticleBase.cs => ParticleBase.xksl.cs} | 0 ...seEffect.cs => ParticleBaseEffect.xkfx.cs} | 0 ...uteColorWhite.cs => ParticleColor.xksl.cs} | 0 ...leColor.cs => ParticleColorStream.xksl.cs} | 0 ....cs => ParticleComputeColorShader.xksl.cs} | 0 ...rticleEffect.cs => ParticleEffect.xkfx.cs} | 0 ...Utilities.cs => ParticleUtilities.xksl.cs} | 0 .../Xenko.Particles/Xenko.Particles.csproj | 91 - .../Rendering/BRDF/BRDFMicrofacet.xksl.cs} | 0 ...der.cs => BackgroundCubemapShader.xksl.cs} | 0 ...oundShader.cs => BackgroundShader.xksl.cs} | 0 ...der.cs => MSAADepthResolverShader.xksl.cs} | 0 ...erEffect.cs => MSAAResolverEffect.xkfx.cs} | 0 ...erShader.cs => MSAAResolverShader.xksl.cs} | 0 ...Shader1.cs => ComputeEffectShader.xkfx.cs} | 0 .../ComputeShaderBase.xksl.cs} | 0 .../Hammersley.xksl.cs} | 0 ...rsley.cs => ImportanceSamplingGGX.xksl.cs} | 0 ... => RadiancePrefilteringGGXEffect.xkfx.cs} | 0 ...ncePrefilteringGGXNoComputeEffect.xkfx.cs} | 0 ...ncePrefilteringGGXNoComputeShader.xksl.cs} | 0 ... => RadiancePrefilteringGGXShader.xksl.cs} | 0 ...H1.cs => LambertianPrefilteringSH.xkfx.cs} | 0 ...tianPrefilteringSHNoComputeEffect.xkfx.cs} | 0 ...rtianPrefilteringSHNoComputePass1.xksl.cs} | 0 ...rtianPrefilteringSHNoComputePass2.xksl.cs} | 0 ... => LambertianPrefilteringSHPass1.xksl.cs} | 0 ... => LambertianPrefilteringSHPass2.xksl.cs} | 0 ...Velocity.cs => BackgroundVelocity.xksl.cs} | 0 ...ct.cs => BackgroundVelocityEffect.xkfx.cs} | 0 .../ColorBase.xksl.cs} | 0 .../{ColorBase.cs => DynamicSampler.xksl.cs} | 0 ...namicSampler.cs => DynamicTexture.xksl.cs} | 0 ...cTexture.cs => DynamicTextureCube.xksl.cs} | 0 ...reCube.cs => DynamicTextureStream.xksl.cs} | 0 .../{MeshVelocity.cs => MeshVelocity.xksl.cs} | 0 ...micTextureStream.cs => NormalBase.xksl.cs} | 0 .../{NormalBase.cs => NormalFromMesh.xksl.cs} | 0 ...esh.cs => NormalFromNormalMapping.xksl.cs} | 0 ...mNormalMapping.cs => NormalStream.xksl.cs} | 0 .../{NormalUpdate.cs => NormalUpdate.xksl.cs} | 0 ...rmalStream.cs => PositionHStream4.xksl.cs} | 0 ...tionHStream4.cs => PositionStream.xksl.cs} | 0 ...tionStream2.cs => PositionStream4.xksl.cs} | 0 ...am4.cs => PositionVertexTransform.xksl.cs} | 0 ...ransform.cs => ScreenPositionBase.xksl.cs} | 0 ...eenPositionBase.cs => ShadingBase.xksl.cs} | 0 .../{ShadingBase.cs => ShadingColor.xksl.cs} | 0 ...ShadingColor.cs => VelocityOutput.xksl.cs} | 0 ...locityOutput.cs => VelocityStream.xksl.cs} | 0 .../GBuffer.xksl.cs} | 0 .../CompilationErrorShader.xksl.cs} | 0 ...ErrorShader.cs => EffectCompiling.xksl.cs} | 0 ...ompiling.cs => LightConstantWhite.xksl.cs} | 0 ...Shader.cs => SelectedSpriteShader.xksl.cs} | 0 ...ite.cs => SharedTextureCoordinate.xksl.cs} | 0 .../{Sprite3DBase.cs => Sprite3DBase.xksl.cs} | 0 ...ureCoordinate.cs => SpritePicking.xksl.cs} | 0 ....cs => AmbientOcclusionBlurEffect.xkfx.cs} | 0 ....cs => AmbientOcclusionBlurShader.xksl.cs} | 0 ...cs => AmbientOcclusionRawAOEffect.xkfx.cs} | 0 ...cs => AmbientOcclusionRawAOShader.xksl.cs} | 0 .../ApplyAmbientOcclusionShader.xksl.cs} | 0 .../FXAAShader.xksl.cs} | 0 ...aderEffect.cs => FXAAShaderEffect.xkfx.cs} | 0 ...der.cs => TemporalAntiAliasShader.xksl.cs} | 0 .../BloomAfterimageCombineShader.xksl.cs} | 0 ...hader.cs => BloomAfterimageShader.xksl.cs} | 0 ...erShader.cs => BrightFilterShader.xksl.cs} | 0 ...rEffect.cs => ColorCombinerEffect.xkfx.cs} | 0 ...rShader.cs => ColorCombinerShader.xksl.cs} | 0 ...t.cs => ColorTransformGroupEffect.xkfx.cs} | 0 .../ColorTransformGroupShader.xksl.cs} | 0 ...Shader.cs => ColorTransformShader.xksl.cs} | 0 ...er.cs => LuminanceToChannelShader.xksl.cs} | 0 ...GrainShader.cs => FilmGrainShader.xksl.cs} | 0 ...cs => ToneMapCommonOperatorShader.xksl.cs} | 0 ....cs => ToneMapDragoOperatorShader.xksl.cs} | 0 ...ToneMapEffect.cs => ToneMapEffect.xkfx.cs} | 0 .../ToneMapExponentialOperatorShader.xksl.cs} | 0 ....cs => ToneMapHejl2OperatorShader.xksl.cs} | 0 ...> ToneMapHejlDawsonOperatorShader.xksl.cs} | 0 ... ToneMapLogarithmicOperatorShader.xksl.cs} | 0 ...s => ToneMapMikeDayOperatorShader.xksl.cs} | 0 ...hader.cs => ToneMapOperatorShader.xksl.cs} | 0 ... => ToneMapReinhardOperatorShader.xksl.cs} | 0 ...ToneMapShader.cs => ToneMapShader.xksl.cs} | 0 ... => ToneMapU2FilmicOperatorShader.xksl.cs} | 0 ...tingShader.cs => VignettingShader.xksl.cs} | 0 ...MaxEffect.cs => DepthMinMaxEffect.xkfx.cs} | 0 ...MaxShader.cs => DepthMinMaxShader.xksl.cs} | 0 .../Hexagonal/McIntoshCombineShader.xksl.cs} | 0 ...ect.cs => McIntoshOptimizedEffect.xkfx.cs} | 0 ...der.cs => McIntoshOptimizedShader.xksl.cs} | 0 ...r.cs => TripleRhombiCombineShader.xksl.cs} | 0 ...Confusion.cs => CircleOfConfusion.xksl.cs} | 0 ...Shader.cs => CoCLinearDepthShader.xksl.cs} | 0 ...BlurEffect.cs => CoCMapBlurEffect.xkfx.cs} | 0 ...BlurShader.cs => CoCMapBlurShader.xksl.cs} | 0 ...ffect.cs => CombineFrontCoCEffect.xkfx.cs} | 0 ...hader.cs => CombineFrontCoCShader.xksl.cs} | 0 ....cs => CombineLevelsFromCoCEffect.xkfx.cs} | 0 ....cs => CombineLevelsFromCoCShader.xksl.cs} | 0 ...> DepthAwareDirectionalBlurEffect.xkfx.cs} | 0 ...> DepthAwareDirectionalBlurShader.xksl.cs} | 0 ... => DepthAwareDirectionalBlurUtil.xksl.cs} | 0 .../{PointDepth.cs => PointDepth.xksl.cs} | 0 ...dAlphaCoC.cs => ThresholdAlphaCoC.xksl.cs} | 0 ...ront.cs => ThresholdAlphaCoCFront.xksl.cs} | 0 .../Dither/{Dither2.cs => Dither.xksl.cs} | 0 ...urEffect.cs => GaussianBlurEffect.xkfx.cs} | 0 ...urShader.cs => GaussianBlurShader.xksl.cs} | 0 ...lurShader.cs => ImageEffectShader.xksl.cs} | 0 ...lerEffect.cs => ImageScalerEffect.xkfx.cs} | 0 ...lerShader.cs => ImageScalerShader.xksl.cs} | 0 ...tEffect.cs => FlareArtifactEffect.xkfx.cs} | 0 ...tShader.cs => FlareArtifactShader.xksl.cs} | 0 ...areReplicate.cs => FlareReplicate.xksl.cs} | 0 ...tEffect.cs => AdditiveLightEffect.xksl.cs} | 0 ...tShader.cs => AdditiveLightShader.xksl.cs} | 0 ...ftsEffect.cs => LightShaftsEffect.xkfx.cs} | 0 ...ftsShader.cs => LightShaftsShader.xksl.cs} | 0 .../PostEffectBoundingRay.xksl.cs} | 0 ...axShader.cs => VolumeMinMaxShader.xksl.cs} | 0 ...eakEffect.cs => LightStreakEffect.xkfx.cs} | 0 ...eakShader.cs => LightStreakShader.xksl.cs} | 0 .../{SSLRBlurPass.cs => SSLRBlurPass.xksl.cs} | 0 ...CombinePass.cs => SSLRCombinePass.xksl.cs} | 0 .../{SSLRCommon.cs => SSLRCommon.xksl.cs} | 0 ...SSLRDepthPass.cs => SSLRDepthPass.xksl.cs} | 0 ...yTracePass.cs => SSLRRayTracePass.xksl.cs} | 0 ...ResolvePass.cs => SSLRResolvePass.xksl.cs} | 0 ...mporalPass.cs => SSLRTemporalPass.xksl.cs} | 0 .../LuminanceLogShader.xksl.cs} | 0 ...nceLogShader.cs => LuminanceUtils.xksl.cs} | 0 .../RangeCompressorShader.xksl.cs} | 0 ...der.cs => RangeDecompressorShader.xksl.cs} | 0 .../SphericalHarmonicsBase.xksl.cs} | 0 ...s => SphericalHarmonicsParameters.xkfx.cs} | 0 ....cs => SphericalHarmonicsRenderer.xksl.cs} | 0 ... SphericalHarmonicsRendererEffect.xkfx.cs} | 0 ...ase.cs => SphericalHarmonicsUtils.xksl.cs} | 0 ...=> SubsurfaceScatteringBlurEffect.xkfx.cs} | 0 ...=> SubsurfaceScatteringBlurShader.xksl.cs} | 0 ...Shader.cs => BakeLightProbeShader.xksl.cs} | 0 ...s.cs => ComputeSphericalHarmonics.xksl.cs} | 0 ...robeShader.cs => LightProbeShader.xksl.cs} | 0 ...t.cs => XenkoBakeLightProbeEffect.xkfx.cs} | 0 .../DirectLightGroup.xksl.cs} | 0 ...Group.cs => DirectLightGroupArray.xksl.cs} | 0 ...Array.cs => DirectLightGroupFixed.xksl.cs} | 0 ...raw.cs => DirectLightGroupPerDraw.xksl.cs} | 0 ...iew.cs => DirectLightGroupPerView.xksl.cs} | 0 ...GroupFixed.cs => EnvironmentLight.xksl.cs} | 0 ...Light.cs => EnvironmentLightArray.xksl.cs} | 0 ...ghtClustered.cs => LightClustered.xksl.cs} | 0 ...up.cs => LightClusteredPointGroup.xksl.cs} | 0 ...oup.cs => LightClusteredSpotGroup.xksl.cs} | 0 ...LightArray.cs => LightDirectional.xksl.cs} | 0 ...Group.cs => LightDirectionalGroup.xksl.cs} | 0 ...ightDirectional1.cs => LightPoint.xksl.cs} | 0 ...tPointGroup.cs => LightPointGroup.xksl.cs} | 0 ...eAmbient.cs => LightSimpleAmbient.xksl.cs} | 0 ...boxEffect.cs => LightSkyboxEffect.xkfx.cs} | 0 ...boxShader.cs => LightSkyboxShader.xksl.cs} | 0 .../{LightPoint1.cs => LightSpot.xksl.cs} | 0 ...cs => LightSpotAttenuationDefault.xksl.cs} | 0 ...> LightSpotAttenuationRectangular.xksl.cs} | 0 ...ghtSpotGroup.cs => LightSpotGroup.xksl.cs} | 0 ...tionRectangular.cs => LightStream.xksl.cs} | 0 .../{LightStream.cs => LightUtil.xksl.cs} | 0 ...cs => SpotLightDataInternalShader.xksl.cs} | 0 .../TextureProjectionCommon.xksl.cs} | 0 ...=> TextureProjectionFilterDefault.xksl.cs} | 0 ...ault.cs => TextureProjectionGroup.xksl.cs} | 0 ... => TextureProjectionReceiverBase.xksl.cs} | 0 ... => TextureProjectionReceiverSpot.xksl.cs} | 0 ... IMaterialCelShadingLightFunction.xksl.cs} | 0 ...=> MaterialCelShadingLightDefault.xksl.cs} | 0 ...cs => MaterialCelShadingLightRamp.xksl.cs} | 0 .../3dsMax/ComputeColorAdd3ds.xksl.cs} | 0 ...dd3ds.cs => ComputeColorDarken3ds.xksl.cs} | 0 ...s.cs => ComputeColorDifference3ds.xksl.cs} | 0 ...e3ds.cs => ComputeColorLighten3ds.xksl.cs} | 0 ...hten3ds.cs => ComputeColorMask3ds.xksl.cs} | 0 ...3ds.cs => ComputeColorMultiply3ds.xksl.cs} | 0 ...iply3ds.cs => ComputeColorOver3ds.xksl.cs} | 0 ...r3ds.cs => ComputeColorOverlay3ds.xksl.cs} | 0 ...3ds.cs => ComputeColorSubtract3ds.xksl.cs} | 0 ...lorSubtract3ds.cs => ComputeColor.xksl.cs} | 0 ...{ComputeColor.cs => ComputeColor3.xksl.cs} | 0 ...mputeColor3.cs => ComputeColorAdd.xksl.cs} | 0 ...teColorAdd.cs => ComputeColorAdd3.xksl.cs} | 0 ...lorAdd3.cs => ComputeColorAverage.xksl.cs} | 0 ...lorAverage.cs => ComputeColorCave.xksl.cs} | 0 ...ColorCave.cs => ComputeColorColor.xksl.cs} | 0 ...Color.cs => ComputeColorColorBurn.xksl.cs} | 0 ...Burn.cs => ComputeColorColorDodge.xksl.cs} | 0 ... => ComputeColorConstantColorLink.xksl.cs} | 0 ... => ComputeColorConstantFloatLink.xksl.cs} | 0 ...nk.cs => ComputeColorConstantLink.xksl.cs} | 0 ...Link.cs => ComputeColorDesaturate.xksl.cs} | 0 ...saturate.cs => ComputeColorDivide.xksl.cs} | 0 ...ivide.cs => ComputeColorExclusion.xksl.cs} | 0 ...Exclusion.cs => ComputeColorFixed.xksl.cs} | 0 ...ixed.cs => ComputeColorFromStream.xksl.cs} | 0 ...tream.cs => ComputeColorHardLight.xksl.cs} | 0 ...rdLight.cs => ComputeColorHardMix.xksl.cs} | 0 ...olorHardMix.cs => ComputeColorHue.xksl.cs} | 0 ...rHue.cs => ComputeColorIlluminate.xksl.cs} | 0 ...orIlluminate.cs => ComputeColorIn.xksl.cs} | 0 ...lorIn.cs => ComputeColorLerpAlpha.xksl.cs} | 0 ...lpha.cs => ComputeColorLinearBurn.xksl.cs} | 0 ...urn.cs => ComputeColorLinearDodge.xksl.cs} | 0 ...inearDodge.cs => ComputeColorMask.xksl.cs} | 0 ...orMask.cs => ComputeColorMultiply.xksl.cs} | 0 ...lorMultiply.cs => ComputeColorOne.xksl.cs} | 0 ...uteColorOne.cs => ComputeColorOut.xksl.cs} | 0 ...olorOut.cs => ComputeColorOutdoor.xksl.cs} | 0 ...Outdoor.cs => ComputeColorOverlay.xksl.cs} | 0 ...meter.cs => ComputeColorParameter.xksl.cs} | 0 ...verlay.cs => ComputeColorPinLight.xksl.cs} | 0 ...nLight.cs => ComputeColorSaturate.xksl.cs} | 0 ...rate.cs => ComputeColorSaturation.xksl.cs} | 0 ...turation.cs => ComputeColorScaler.xksl.cs} | 0 ...orScaler.cs => ComputeColorScreen.xksl.cs} | 0 ...creen.cs => ComputeColorSoftLight.xksl.cs} | 0 ...oftLight.cs => ComputeColorStream.xksl.cs} | 0 ...cs => ComputeColorSubstituteAlpha.xksl.cs} | 0 ...puteColorSubstituteAlphaWithColor.xksl.cs} | 0 ...hColor.cs => ComputeColorSubtract.xksl.cs} | 0 ...ract1.cs => ComputeColorSynthetic.xksl.cs} | 0 ...nthetic.cs => ComputeColorTexture.xksl.cs} | 0 ...teColorTextureDynamicScaledOffset.xksl.cs} | 0 ... => ComputeColorTextureLodSampler.xksl.cs} | 0 ...tureLodScaledOffsetDynamicSampler.xksl.cs} | 0 ...olorTextureLodScaledOffsetSampler.xksl.cs} | 0 ...mputeColorTextureLodScaledSampler.xksl.cs} | 0 ...r.cs => ComputeColorTextureRepeat.xksl.cs} | 0 ....cs => ComputeColorTextureSampler.xksl.cs} | 0 ...r.cs => ComputeColorTextureScaled.xksl.cs} | 0 ...> ComputeColorTextureScaledOffset.xksl.cs} | 0 ...TextureScaledOffsetDynamicSampler.xksl.cs} | 0 ...caledOffsetDynamicSamplerRandomUV.xksl.cs} | 0 ...teColorTextureScaledOffsetSampler.xksl.cs} | 0 ... ComputeColorTextureScaledSampler.xksl.cs} | 0 ...mpler.cs => ComputeColorThreshold.xksl.cs} | 0 ...Threshold.cs => ComputeColorValue.xksl.cs} | 0 .../ComputeColorAddMaya.xksl.cs} | 0 ...Maya.cs => ComputeColorDarkenMaya.xksl.cs} | 0 ....cs => ComputeColorDifferenceMaya.xksl.cs} | 0 ...aya.cs => ComputeColorLightenMaya.xksl.cs} | 0 ...ya.cs => ComputeColorMultiplyMaya.xksl.cs} | 0 ...lyMaya.cs => ComputeColorOverMaya.xksl.cs} | 0 ...ya.cs => ComputeColorSubtractMaya.xksl.cs} | 0 .../IMaterialHairDirectionFunction.xksl.cs} | 0 ...ialHairDirectionFunctionBitangent.xksl.cs} | 0 ...erialHairDirectionFunctionTangent.xksl.cs} | 0 .../IMaterialHairDiscardFunction.xksl.cs} | 0 ...rialHairDiscardFunctionOpaquePass.xksl.cs} | 0 ...airDiscardFunctionTransparentPass.xksl.cs} | 0 ...erialHairLightAttenuationFunction.xksl.cs} | 0 ...ghtAttenuationFunctionDirectional.xksl.cs} | 0 ...lHairLightAttenuationFunctionNone.xksl.cs} | 0 ...rShared1.cs => MaterialHairShared.xksl.cs} | 0 ...MaterialSurfaceShadingDiffuseHair.xksl.cs} | 0 ...aterialSurfaceShadingSpecularHair.xksl.cs} | 0 .../IMaterialHairShadowingFunction.xksl.cs} | 0 ...alHairShadowingFunctionScattering.xksl.cs} | 0 ...ialHairShadowingFunctionShadowing.xksl.cs} | 0 ...ing1.cs => IMaterialSurfaceDomain.xksl.cs} | 0 ...ceDomain.cs => IStreamInitializer.xksl.cs} | 0 ....cs => MaterialDisplacementStream.xksl.cs} | 0 ...Stream.cs => MaterialDomainStream.xksl.cs} | 0 ...cs => MaterialStreamAdditiveBlend.xksl.cs} | 0 ...cs => MaterialSurfaceDisplacement.xksl.cs} | 0 ...erialSurfaceDomainStageCompositor.xksl.cs} | 0 ....cs => MaterialTessellationStream.xksl.cs} | 0 .../ComputeColorMaterialAlphaBlend.xksl.cs} | 0 ...aBlend.cs => GBufferOutputNormals.xksl.cs} | 0 ...ufferOutputSpecularColorRoughness.xksl.cs} | 0 ...SubsurfaceScatteringMaterialIndex.xksl.cs} | 0 ...ularMicrofacetEnvironmentFunction.xksl.cs} | 0 ...SpecularMicrofacetFresnelFunction.xksl.cs} | 0 ...rofacetNormalDistributionFunction.xksl.cs} | 0 ...cularMicrofacetVisibilityFunction.xksl.cs} | 0 ...nction.cs => IMaterialStreamBlend.xksl.cs} | 0 ...treamBlend.cs => IMaterialSurface.xksl.cs} | 0 ...rface.cs => IMaterialSurfacePixel.xksl.cs} | 0 ...xel.cs => IMaterialSurfaceShading.xksl.cs} | 0 ...ding.cs => IMaterialSurfaceVertex.xksl.cs} | 0 ...s => MaterialFrontBackBlendShader.xksl.cs} | 0 ....cs => MaterialPixelShadingStream.xksl.cs} | 0 ...gStream.cs => MaterialPixelStream.xksl.cs} | 0 ...ecularMicrofacetEnvironmentGGXLUT.xksl.cs} | 0 ...icrofacetEnvironmentGGXPolynomial.xksl.cs} | 0 ...larMicrofacetEnvironmentThinGlass.xksl.cs} | 0 ...rialSpecularMicrofacetFresnelNone.xksl.cs} | 0 ...lSpecularMicrofacetFresnelSchlick.xksl.cs} | 0 ...pecularMicrofacetFresnelThinGlass.xksl.cs} | 0 ...rofacetNormalDistributionBeckmann.xksl.cs} | 0 ...facetNormalDistributionBlinnPhong.xksl.cs} | 0 ...arMicrofacetNormalDistributionGGX.xksl.cs} | 0 ...rMicrofacetVisibilityCookTorrance.xksl.cs} | 0 ...cularMicrofacetVisibilityImplicit.xksl.cs} | 0 ...ecularMicrofacetVisibilityKelemen.xksl.cs} | 0 ...ecularMicrofacetVisibilityNeumann.xksl.cs} | 0 ...MicrofacetVisibilitySmithBeckmann.xksl.cs} | 0 ...facetVisibilitySmithGGXCorrelated.xksl.cs} | 0 ...cetVisibilitySmithSchlickBeckmann.xksl.cs} | 0 ...crofacetVisibilitySmithSchlickGGX.xksl.cs} | 0 ...thSchlickGGX.cs => MaterialStream.xksl.cs} | 0 ...m.cs => MaterialStreamLinearBlend.xksl.cs} | 0 ...d.cs => MaterialStreamNormalBlend.xksl.cs} | 0 ...lBlend.cs => MaterialSurfaceArray.xksl.cs} | 0 ...rray.cs => MaterialSurfaceDiffuse.xksl.cs} | 0 ...MaterialSurfaceDiffuseMetalFlakes.xksl.cs} | 0 ...aceDiffuseSpecularAlphaBlendColor.xksl.cs} | 0 ...=> MaterialSurfaceEmissiveShading.xksl.cs} | 0 ...s => MaterialSurfaceGlossinessMap.xksl.cs} | 0 ...alSurfaceGlossinessMapMetalFlakes.xksl.cs} | 0 ...MaterialSurfaceLightingAndShading.xksl.cs} | 0 ...ng.cs => MaterialSurfaceMetalness.xksl.cs} | 0 ...ss.cs => MaterialSurfaceNormalMap.xksl.cs} | 0 ...aterialSurfaceNormalStreamShading.xksl.cs} | 0 ...terialSurfacePixelStageCompositor.xksl.cs} | 0 ...lSurfaceSetStreamFromComputeColor.xksl.cs} | 0 ...cs => MaterialSurfaceShadingBlend.xksl.cs} | 0 ...erialSurfaceShadingDiffuseLambert.xksl.cs} | 0 ...lSurfaceShadingSpecularBlinnPhong.xksl.cs} | 0 ...lSurfaceShadingSpecularMicrofacet.xksl.cs} | 0 ...s => MaterialSurfaceStreamShading.xksl.cs} | 0 ...cs => MaterialSurfaceStreamsBlend.xksl.cs} | 0 ...terialSurfaceTransmittanceShading.xksl.cs} | 0 ...ialSurfaceTransparentAlphaDiscard.xksl.cs} | 0 ...MaterialSurfaceVertexDisplacement.xksl.cs} | 0 ...erialSurfaceVertexStageCompositor.xksl.cs} | 0 ...ialTransmittanceReflectanceStream.xksl.cs} | 0 ...ositor.cs => MaterialVertexStream.xksl.cs} | 0 ...urfaceSubsurfaceScatteringShading.xksl.cs} | 0 ...urfaceScatteringScatteringProfile.xksl.cs} | 0 ...ingScatteringProfileCustomUniform.xksl.cs} | 0 ...ingScatteringProfileCustomVarying.xksl.cs} | 0 ...ceScatteringScatteringProfileSkin.xksl.cs} | 0 .../{CameraCube.cs => CameraCube.xksl.cs} | 0 .../Shaders/{Camera.cs => Camera.xksl.cs} | 0 .../Shaders/{Global.cs => Global.xksl.cs} | 0 .../Shaders/{GlobalVR.cs => GlobalVR.xksl.cs} | 0 ...ansformation.cs => Transformation.xksl.cs} | 0 .../ShadowGroup.xksl.cs} | 0 ...owMapCaster.cs => ShadowMapCaster.xkfx.cs} | 0 ...cs => ShadowMapCasterAlphaDiscard.xksl.cs} | 0 ...eMap.cs => ShadowMapCasterCubeMap.xkfx.cs} | 0 ... ShadowMapCasterCubeMapProjection.xksl.cs} | 0 ...s => ShadowMapCasterNoPixelShader.xksl.cs} | 0 ...1.cs => ShadowMapCasterParaboloid.xkfx.cs} | 0 ...adowMapCasterParaboloidProjection.xksl.cs} | 0 ...elShader.cs => ShadowMapCasterVsm.xksl.cs} | 0 ...apCasterVsm.cs => ShadowMapCommon.xksl.cs} | 0 ...pCommon.cs => ShadowMapFilterBase.xksl.cs} | 0 ...Base.cs => ShadowMapFilterDefault.xksl.cs} | 0 ...rDefault.cs => ShadowMapFilterPcf.xksl.cs} | 0 ...ilterVsm.cs => ShadowMapFilterVsm.xksl.cs} | 0 ...MapFilterPcf.cs => ShadowMapGroup.xksl.cs} | 0 ...rBase.cs => ShadowMapReceiverBase.xksl.cs} | 0 ...s => ShadowMapReceiverDirectional.xksl.cs} | 0 ... => ShadowMapReceiverPointCubeMap.xksl.cs} | 0 ... ShadowMapReceiverPointParaboloid.xksl.cs} | 0 ...Group.cs => ShadowMapReceiverSpot.xksl.cs} | 0 ...apReceiverSpot.cs => ShadowStream.xksl.cs} | 0 .../NormalMeshSkinning.xksl.cs} | 0 ...ng.cs => NormalVSSkinningFromMesh.xksl.cs} | 0 ... => NormalVSSkinningNormalMapping.xksl.cs} | 0 ...Mapping.cs => TangentMeshSkinning.xksl.cs} | 0 ...ning.cs => TransformationSkinning.xksl.cs} | 0 .../CubemapUtils.xksl.cs} | 0 ...ls.cs => IComputeEnvironmentColor.xksl.cs} | 0 ...s => LevelCubeMapEnvironmentColor.xksl.cs} | 0 ... RoughnessCubeMapEnvironmentColor.xksl.cs} | 0 ...ShaderBase.cs => SkyboxShaderBase.xksl.cs} | 0 ...Cubemap.cs => SkyboxShaderCubemap.xksl.cs} | 0 ...Texture.cs => SkyboxShaderTexture.xksl.cs} | 0 ...vironmentColor.cs => SkyboxStream.xksl.cs} | 0 ...phericalHarmonicsEnvironmentColor.xksl.cs} | 0 .../TessellationAE2.xksl.cs} | 0 ...ellationAE2.cs => TessellationAE3.xksl.cs} | 0 ...ellationAE3.cs => TessellationAE4.xksl.cs} | 0 ...llationAE4.cs => TessellationBase.xksl.cs} | 0 ...lationBase.cs => TessellationFlat.xksl.cs} | 0 ...ellationFlat.cs => TessellationPN.xksl.cs} | 0 .../TransformationBase.xksl.cs} | 0 ...onBase.cs => TransformationMatrix.xksl.cs} | 0 ...Matrix.cs => TransformationWAndVP.xksl.cs} | 0 ...ionWAndVP.cs => TransformationWVP.xksl.cs} | 0 ...ationWVP.cs => TransformationZero.xksl.cs} | 0 .../BlendUtils.xksl.cs} | 0 .../Utils/{DepthBase.cs => DepthBase.xksl.cs} | 0 .../{BlendUtils.cs => FlattenLayers.xksl.cs} | 0 .../{FlattenLayers.cs => HSVUtils.xksl.cs} | 0 ...lightShader.cs => HighlightShader.xksl.cs} | 0 .../Utils/{HSVUtils.cs => Math.xksl.cs} | 0 ...cs => ModelComponentPickingEffect.xkfx.cs} | 0 ...cs => ModelComponentPickingShader.xksl.cs} | 0 .../{NormalPack.cs => NormalPack.xksl.cs} | 0 .../Utils/{Math.cs => NormalUtil.xksl.cs} | 0 .../Utils/{Picking.cs => Picking.xkfx.cs} | 0 ...PickingShader.cs => PickingShader.xksl.cs} | 0 .../Utils/{NormalUtil.cs => SwapUV.xksl.cs} | 0 .../Utils/{SwapUV.cs => Utilities.xksl.cs} | 0 ...oEffectBase.cs => XenkoEffectBase.xkfx.cs} | 0 ...t.cs => XenkoForwardShadingEffect.xkfx.cs} | 0 ...cs => XenkoWireframeShadingEffect.xkfx.cs} | 0 .../Xenko.Rendering/Xenko.Rendering.csproj | 4068 +---------------- .../{SimpleEffect.cs => SimpleEffect.xkfx.cs} | 0 .../{SimpleShader.cs => SimpleShader.xksl.cs} | 0 .../GameAssets/Compiler/TestStream.xksl.cs} | 0 .../{ToGlslEffect.cs => ToGlslEffect.xkfx.cs} | 0 .../{ToGlslShader.cs => ToGlslShader.xksl.cs} | 0 .../TestStream.cs => Mixins/A.xksl.cs} | 0 .../GameAssets/Mixins/{A.cs => B.xksl.cs} | 0 .../GameAssets/Mixins/{B.cs => C.xksl.cs} | 0 .../GameAssets/Mixins/{C.cs => C1.xksl.cs} | 0 .../Mixins/{C1.cs => ComputeColor.xksl.cs} | 0 ...ComputeColor2.cs => ComputeColor2.xksl.cs} | 0 ...eColor.cs => ComputeColorRedirect.xksl.cs} | 0 ...s.cs => test_mixin_complex_params.xkfx.cs} | 0 ...eys.cs => test_mixin_compose_keys.xkfx.cs} | 0 ...in_simple.cs => test_mixin_simple.xkfx.cs} | 0 ...ild.cs => test_mixin_simple_child.xkfx.cs} | 0 ...=> test_mixin_simple_child_params.xkfx.cs} | 0 ...one.cs => test_mixin_simple_clone.xkfx.cs} | 0 ...e.cs => test_mixin_simple_compose.xkfx.cs} | 0 ...ms.cs => test_mixin_simple_params.xkfx.cs} | 0 .../BaseTestChild.xksl.cs} | 0 ...BaseTestChild.cs => BaseTestInter.xksl.cs} | 0 ...aseTestInter.cs => BaseTestParent.xksl.cs} | 0 .../{BasicMixin.cs => BasicMixin.xksl.cs} | 0 .../{BasicMixin2.cs => BasicMixin2.xksl.cs} | 0 .../Shaders/{Child.cs => Child.xksl.cs} | 0 .../{BaseTestParent.cs => ChildError.xksl.cs} | 0 .../{ChildError.cs => CloneTestBase.xksl.cs} | 0 ...oneTestBase.cs => CloneTestExtern.xksl.cs} | 0 ...oneTestExtern.cs => CloneTestRoot.xksl.cs} | 0 ...fferTest.cs => ConstantBufferTest.xksl.cs} | 0 .../{CloneTestRoot.cs => CyclicTest.xksl.cs} | 0 .../{CyclicTest.cs => DeepExtern.xksl.cs} | 0 .../{DeepExtern.cs => DeepExternTest.xksl.cs} | 0 ...{DeepExternTest.cs => ExternClone.xksl.cs} | 0 ...ExternClone.cs => ExternCloneTest.xksl.cs} | 0 .../{ExternMixin.cs => ExternMixin.xksl.cs} | 0 ...{ExternCloneTest.cs => ExternTest.xksl.cs} | 0 .../GameAssets/Shaders/ForEachTest.cs | 23 - .../{ForEachTest1.cs => ForEachTest.xksl.cs} | 0 .../{ExternTest.cs => GenericCall.xksl.cs} | 0 .../{GenericCall.cs => GenericClass.xksl.cs} | 0 ...GenericClass2.cs => GenericClass2.xksl.cs} | 0 ...{GenericClass.cs => GenericExtern.xksl.cs} | 0 ...ricTexcoord.cs => GenericTexcoord.xksl.cs} | 0 ...icExtern.cs => GeometryShaderTest.xksl.cs} | 0 ...tryShaderTest.cs => InterfaceTest.xksl.cs} | 0 ...ixin.cs => InternalReferenceMixin.xksl.cs} | 0 .../{MacroTest1.cs => MacroTest.xksl.cs} | 0 ...InterfaceTest.cs => MacroTestBase.xksl.cs} | 0 ...acroTestBase.cs => MacroTestChild.xksl.cs} | 0 ....cs => MixinFunctionParamaterTest.xksl.cs} | 0 ...roTestChild1.cs => MixinNameClash.xksl.cs} | 0 ...amaterTest.cs => MixinNoNameClash.xksl.cs} | 0 ...ameClash.cs => NonStageStreamTest.xksl.cs} | 0 .../Shaders/{Parent.cs => Parent.xksl.cs} | 0 .../GameAssets/Shaders/SemanticTest.cs | 24 - ...{SemanticTest1.cs => SemanticTest.xksl.cs} | 0 .../Shaders/{Simple.cs => Simple.xksl.cs} | 0 .../{StageBase.cs => StageBase.xksl.cs} | 0 ...NoNameClash.cs => StageCallExtern.xksl.cs} | 0 .../{StageDecl.cs => StageDecl.xksl.cs} | 0 ...eamTest.cs => StageValueReference.xksl.cs} | 0 ...ageValueTest.cs => StageValueTest.xksl.cs} | 0 ...eCallExtern.cs => StaticCallMixin.xksl.cs} | 0 .../{StaticMixin.cs => StaticMixin.xksl.cs} | 0 ...ference.cs => StaticStageCallTest.xksl.cs} | 0 ...StaticCallMixin.cs => StreamChild.xksl.cs} | 0 ...icStageCallTest.cs => StreamError.xksl.cs} | 0 .../{StreamChild.cs => StreamParent0.xksl.cs} | 0 .../{StreamError.cs => StreamParent1.xksl.cs} | 0 ...StreamParent0.cs => StreamParent2.xksl.cs} | 0 ...ent1.cs => StreamSolverExternTest.xksl.cs} | 0 .../{StreamParent2.cs => StreamTest.xksl.cs} | 0 ...erTest.cs => StructuredBufferTest.xksl.cs} | 0 ...amParent21.cs => TessellationTest.xksl.cs} | 0 .../GameAssets/Shaders/TestComputeShader.cs | 27 - ...teShader1.cs => TestComputeShader.xksl.cs} | 0 .../{TestErrors.cs => TestErrors.xksl.cs} | 0 ...rExternTest.cs => TestExternArray.xksl.cs} | 0 ...reamTest.cs => TestGenericComplex.xksl.cs} | 0 ...lationTest.cs => TestGenericMacro.xksl.cs} | 0 .../{TestGenerics.cs => TestGenerics.xksl.cs} | 0 ...{TestExternArray.cs => TestMacros.xksl.cs} | 0 ...ericComplex.cs => TestMacrosArray.xksl.cs} | 0 ...ricMacro.cs => TestMultipleStatic.xksl.cs} | 0 ...{TestMacros.cs => TestPixelStream.xksl.cs} | 0 ...rosArray.cs => TestScreenPosition.xksl.cs} | 0 .../GameAssets/Shaders/TestStreams.cs | 9 - ...estMacrosArray1.cs => TestStreams.xksl.cs} | 0 ...tance.cs => TestStructInheritance.xksl.cs} | 0 .../GameAssets/Shaders/TestStructure.cs | 9 - ...ultipleStatic.cs => TestStructure.xksl.cs} | 0 .../GameAssets/Shaders/TestVertexStream.cs | 9 - ...ixelStream.cs => TestVertexStream.xksl.cs} | 0 .../Properties/AssemblyInfo.cs | 29 - .../Xenko.Shaders.Tests.Windows.csproj | 936 +--- .../engine/Xenko.Video/Shaders/VideoShader.cs | 9 - .../Shaders/VideoShader.xksl.cs} | 0 sources/engine/Xenko.Video/Xenko.Video.csproj | 12 - sources/targets/Xenko.PostSettings.targets | 9 + sources/targets/Xenko.UnitTests.targets | 8 + .../TestGenerator.xksl.cs} | 9 +- 610 files changed, 84 insertions(+), 9166 deletions(-) rename sources/editor/Xenko.Assets.Presentation/Shaders/{PreviewTexture.cs => PreviewTexture.xkfx.cs} (100%) rename sources/editor/Xenko.Assets.Presentation/Shaders/{SceneEditorParameters.cs => SceneEditorParameters.xkfx.cs} (100%) rename sources/editor/Xenko.Assets.Presentation/Shaders/{SelectedSprite.cs => SelectedSprite.xkfx.cs} (100%) rename sources/editor/Xenko.Assets.Presentation/Shaders/{XenkoEditorForwardShadingEffect.cs => XenkoEditorForwardShadingEffect.xkfx.cs} (100%) rename sources/editor/Xenko.Assets.Presentation/Shaders/{XenkoEditorHighlightingEffect.cs => XenkoEditorHighlightingEffect.xkfx.cs} (100%) rename sources/editor/Xenko.Assets.Presentation/Shaders/{XenkoEditorMaterialPreviewEffect.cs => XenkoEditorMaterialPreviewEffect.xkfx.cs} (100%) delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/ActivityAndroid.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Application.iOS.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.cs create mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl.cs rename sources/engine/Xenko.Graphics.Tests.10_0/Assets/{MultipleRenderTargetsEffect.cs => MultipleRenderTargetsEffect.xkfx.cs} (100%) rename samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWave.cs => sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffectShader.xksl.cs (100%) delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Info.plist delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Properties/AndroidManifest.xml delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.Android.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Resources/Drawable/icon.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon-60@2x.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon@2x.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Resources/Resource.Designer.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDeferred.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDisplay.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapRendering.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Android.csproj delete mode 100644 sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.iOS.csproj delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/ActivityAndroid.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Application.iOS.cs rename sources/engine/Xenko.Graphics.Tests.11_0/Assets/{ComputeShaderTest.cs => ComputeShaderTest.xksl.cs} (100%) rename sources/engine/Xenko.Graphics.Tests.11_0/Assets/{ComputeShaderTestEffect.cs => ComputeShaderTestEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Graphics.Tests.11_0/Assets/{CubemapSprite.cs => CubemapSprite.xksl.cs} (100%) rename sources/engine/Xenko.Graphics.Tests.11_0/Assets/{HammersleyTest.cs => HammersleyTest.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Info.plist delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Properties/AndroidManifest.xml delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.Android.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Resources/Drawable/icon.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon-60@2x.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon@2x.png delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Resources/Resource.Designer.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Android.csproj delete mode 100644 sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.iOS.csproj delete mode 100644 sources/engine/Xenko.Graphics.Tests/ActivityAndroid.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/Application.iOS.cs rename sources/engine/Xenko.Graphics.Tests/Compiler/{CubemapEffect.cs => CubemapEffect.xkfx.cs} (99%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{CustomEffect.cs => CustomEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{CustomShader.cs => CustomShader.xksl.cs} (100%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{MultiTexturesSpriteEffect.cs => MultiTexturesSpriteEffect.xkfx.cs} (100%) rename sources/engine/{Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffectShader.cs => Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteShader.xksl.cs} (100%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{SimpleEffect.cs => SimpleEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{SimpleShader.cs => SimpleShader.xksl.cs} (100%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{ToGlslEffect.cs => ToGlslEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Graphics.Tests/Compiler/{ToGlslShader.cs => ToGlslShader.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Graphics.Tests/Properties/AndroidManifest.xml delete mode 100644 sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.Android.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/Resources/Drawable/icon.png delete mode 100644 sources/engine/Xenko.Graphics.Tests/Resources/Icon-60@2x.png delete mode 100644 sources/engine/Xenko.Graphics.Tests/Resources/Icon.png delete mode 100644 sources/engine/Xenko.Graphics.Tests/Resources/Icon@2x.png delete mode 100644 sources/engine/Xenko.Graphics.Tests/Resources/Resource.Designer.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/TestCubemapDeferred.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/TestCubemapDisplay.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/TestCubemapRendering.cs delete mode 100644 sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Android.csproj delete mode 100644 sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Shared.targets delete mode 100644 sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.iOS.csproj rename sources/engine/{Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteShader.cs => Xenko.Graphics/Shaders/ColorUtility.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{ColorUtility.cs => ShaderBase.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{ShaderBase.cs => ShaderBaseStream.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{ShaderBaseStream.cs => SignedDistanceFieldFont.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SignedDistanceFieldFont.cs => SignedDistanceFieldFontShader.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteAlphaCutoff.cs => SpriteAlphaCutoff.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteBase.cs => SpriteBase.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteBatch.cs => SpriteBatch.xkfx.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SignedDistanceFieldFontShader.cs => SpriteBatchShader.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteEffect.cs => SpriteEffect.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteEffectExtTexture.cs => SpriteEffectExtTexture.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteEffectExtTextureRegular.cs => SpriteEffectExtTextureRegular.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteSignedDistanceFieldFontShader.cs => SpriteSignedDistanceFieldFontShader.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteBatchShader.cs => SpriteSuperSampler.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{Texturing.cs => Texturing.xksl.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{UIEffect.cs => UIEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Graphics/Shaders/{SpriteSuperSampler.cs => UIEffectShader.xksl.cs} (100%) rename sources/engine/{Xenko.Graphics/Shaders/UIEffectShader.cs => Xenko.Particles/Shaders/ComputeColorWhite.xksl.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ParticleBase.cs => ParticleBase.xksl.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ParticleBaseEffect.cs => ParticleBaseEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ComputeColorWhite.cs => ParticleColor.xksl.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ParticleColor.cs => ParticleColorStream.xksl.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ParticleColorStream.cs => ParticleComputeColorShader.xksl.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ParticleEffect.cs => ParticleEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Particles/Shaders/{ParticleUtilities.cs => ParticleUtilities.xksl.cs} (100%) rename sources/engine/{Xenko.Particles/Shaders/ParticleComputeColorShader.cs => Xenko.Rendering/Rendering/BRDF/BRDFMicrofacet.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Background/{BackgroundCubemapShader.cs => BackgroundCubemapShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Background/{BackgroundShader.cs => BackgroundShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Compositing/{MSAADepthResolverShader.cs => MSAADepthResolverShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Compositing/{MSAAResolverEffect.cs => MSAAResolverEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Compositing/{MSAAResolverShader.cs => MSAAResolverShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/{ComputeEffectShader1.cs => ComputeEffectShader.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{BRDF/BRDFMicrofacet.cs => ComputeEffect/ComputeShaderBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/{ComputeShaderBase.cs => GGXPrefiltering/Hammersley.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/{Hammersley.cs => ImportanceSamplingGGX.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/{RadiancePrefilteringGGXEffect.cs => RadiancePrefilteringGGXEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/{RadiancePrefilteringGGXNoComputeEffect.cs => RadiancePrefilteringGGXNoComputeEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/{RadiancePrefilteringGGXNoComputeShader.cs => RadiancePrefilteringGGXNoComputeShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/{RadiancePrefilteringGGXShader.cs => RadiancePrefilteringGGXShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/{LambertianPrefilteringSH1.cs => LambertianPrefilteringSH.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/{LambertianPrefilteringSHNoComputeEffect.cs => LambertianPrefilteringSHNoComputeEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/{LambertianPrefilteringSHNoComputePass1.cs => LambertianPrefilteringSHNoComputePass1.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/{GGXPrefiltering/ImportanceSamplingGGX.cs => LambertianPrefiltering/LambertianPrefilteringSHNoComputePass2.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/{LambertianPrefilteringSHPass1.cs => LambertianPrefilteringSHPass1.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/{LambertianPrefilteringSHPass2.cs => LambertianPrefilteringSHPass2.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{BackgroundVelocity.cs => BackgroundVelocity.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{BackgroundVelocityEffect.cs => BackgroundVelocityEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass2.cs => Core/ColorBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{ColorBase.cs => DynamicSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{DynamicSampler.cs => DynamicTexture.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{DynamicTexture.cs => DynamicTextureCube.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{DynamicTextureCube.cs => DynamicTextureStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{MeshVelocity.cs => MeshVelocity.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{DynamicTextureStream.cs => NormalBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{NormalBase.cs => NormalFromMesh.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{NormalFromMesh.cs => NormalFromNormalMapping.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{NormalFromNormalMapping.cs => NormalStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{NormalUpdate.cs => NormalUpdate.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{NormalStream.cs => PositionHStream4.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{PositionHStream4.cs => PositionStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{PositionStream2.cs => PositionStream4.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{PositionStream4.cs => PositionVertexTransform.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{PositionVertexTransform.cs => ScreenPositionBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{ScreenPositionBase.cs => ShadingBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{ShadingBase.cs => ShadingColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{ShadingColor.cs => VelocityOutput.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Core/{VelocityOutput.cs => VelocityStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Core/VelocityStream.cs => Deferred/GBuffer.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Deferred/GBuffer1.cs => Editor/CompilationErrorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Editor/{CompilationErrorShader.cs => EffectCompiling.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Editor/{EffectCompiling.cs => LightConstantWhite.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Editor/{SelectedSpriteShader.cs => SelectedSpriteShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Editor/{LightConstantWhite.cs => SharedTextureCoordinate.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Editor/{Sprite3DBase.cs => Sprite3DBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Editor/{SharedTextureCoordinate.cs => SpritePicking.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/{AmbientOcclusionBlurEffect1.cs => AmbientOcclusionBlurEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/{AmbientOcclusionBlurShader.cs => AmbientOcclusionBlurShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/{AmbientOcclusionRawAOEffect.cs => AmbientOcclusionRawAOEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/{AmbientOcclusionRawAOShader.cs => AmbientOcclusionRawAOShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Editor/SpritePicking.cs => Images/AmbientOcclusion/ApplyAmbientOcclusionShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{AmbientOcclusion/ApplyAmbientOcclusionShader.cs => AntiAliasing/FXAAShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/{FXAAShaderEffect.cs => FXAAShaderEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/{TemporalAntiAliasShader.cs => TemporalAntiAliasShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{AntiAliasing/FXAAShader.cs => Bloom/BloomAfterimageCombineShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/Bloom/{BloomAfterimageShader.cs => BloomAfterimageShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/BrightFilter/{BrightFilterShader.cs => BrightFilterShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/{ColorCombinerEffect.cs => ColorCombinerEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/{ColorCombinerShader.cs => ColorCombinerShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/{ColorTransformGroupEffect.cs => ColorTransformGroupEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{Bloom/BloomAfterimageCombineShader.cs => ColorTransforms/ColorTransformGroupShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/{ColorTransformGroupShader.cs => ColorTransformShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/{ColorTransformShader.cs => LuminanceToChannelShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Noise/{FilmGrainShader.cs => FilmGrainShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapCommonOperatorShader.cs => ToneMapCommonOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapDragoOperatorShader.cs => ToneMapDragoOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapEffect.cs => ToneMapEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/{LuminanceToChannelShader.cs => ToneMap/ToneMapExponentialOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapHejl2OperatorShader.cs => ToneMapHejl2OperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapExponentialOperatorShader.cs => ToneMapHejlDawsonOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapHejlDawsonOperatorShader.cs => ToneMapLogarithmicOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapMikeDayOperatorShader.cs => ToneMapMikeDayOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapLogarithmicOperatorShader.cs => ToneMapOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapOperatorShader.cs => ToneMapReinhardOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapShader.cs => ToneMapShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/{ToneMapU2FilmicOperatorShader.cs => ToneMapU2FilmicOperatorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Vignetting/{VignettingShader.cs => VignettingShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/{DepthMinMaxEffect.cs => DepthMinMaxEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/{DepthMinMaxShader.cs => DepthMinMaxShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{ColorTransforms/ToneMap/ToneMapReinhardOperatorShader.cs => DepthOfField/BokehTechnique/Hexagonal/McIntoshCombineShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/{McIntoshOptimizedEffect.cs => McIntoshOptimizedEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/{McIntoshCombineShader.cs => McIntoshOptimizedShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/{TripleRhombiCombineShader.cs => TripleRhombiCombineShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CircleOfConfusion.cs => CircleOfConfusion.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{BokehTechnique/Hexagonal/McIntoshOptimizedShader.cs => CoCLinearDepthShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CoCMapBlurEffect.cs => CoCMapBlurEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CoCMapBlurShader.cs => CoCMapBlurShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CombineFrontCoCEffect.cs => CombineFrontCoCEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CoCLinearDepthShader.cs => CombineFrontCoCShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CombineLevelsFromCoCEffect.cs => CombineLevelsFromCoCEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CombineLevelsFromCoCShader.cs => CombineLevelsFromCoCShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{DepthAwareDirectionalBlurEffect.cs => DepthAwareDirectionalBlurEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{CombineFrontCoCShader.cs => DepthAwareDirectionalBlurShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{DepthAwareDirectionalBlurUtil.cs => DepthAwareDirectionalBlurUtil.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{PointDepth.cs => PointDepth.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{ThresholdAlphaCoC.cs => ThresholdAlphaCoC.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/{ThresholdAlphaCoCFront.cs => ThresholdAlphaCoCFront.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/Dither/{Dither2.cs => Dither.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/{GaussianBlurEffect.cs => GaussianBlurEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/{GaussianBlurShader.cs => GaussianBlurShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{DepthOfField/DepthAwareDirectionalBlurShader.cs => ImageEffectShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/{ImageScalerEffect.cs => ImageScalerEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/{ImageScalerShader.cs => ImageScalerShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/{FlareArtifactEffect.cs => FlareArtifactEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/{FlareArtifactShader.cs => FlareArtifactShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/{FlareReplicate.cs => FlareReplicate.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/{AdditiveLightEffect.cs => AdditiveLightEffect.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/{AdditiveLightShader.cs => AdditiveLightShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/{LightShaftsEffect.cs => LightShaftsEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/{LightShaftsShader.cs => LightShaftsShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{ImageEffectShader1.cs => LightShafts/PostEffectBoundingRay.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/{VolumeMinMaxShader.cs => VolumeMinMaxShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/{LightStreakEffect.cs => LightStreakEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/{LightStreakShader.cs => LightStreakShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRBlurPass.cs => SSLRBlurPass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRCombinePass.cs => SSLRCombinePass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRCommon.cs => SSLRCommon.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRDepthPass.cs => SSLRDepthPass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRRayTracePass.cs => SSLRRayTracePass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRResolvePass.cs => SSLRResolvePass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/{SSLRTemporalPass.cs => SSLRTemporalPass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{LightShafts/PostEffectBoundingRay.cs => LuminanceEffect/LuminanceLogShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/{LuminanceLogShader.cs => LuminanceUtils.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{LuminanceEffect/LuminanceUtils.cs => RangeConversion/RangeCompressorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/{RangeCompressorShader.cs => RangeDecompressorShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/{RangeConversion/RangeDecompressorShader.cs => SphericalHarmonics/SphericalHarmonicsBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/{SphericalHarmonicsParameters.cs => SphericalHarmonicsParameters.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/{SphericalHarmonicsRenderer1.cs => SphericalHarmonicsRenderer.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/{SphericalHarmonicsRendererEffect1.cs => SphericalHarmonicsRendererEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/{SphericalHarmonicsBase.cs => SphericalHarmonicsUtils.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/{SubsurfaceScatteringBlurEffect.cs => SubsurfaceScatteringBlurEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/{SubsurfaceScatteringBlurShader.cs => SubsurfaceScatteringBlurShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/LightProbes/{BakeLightProbeShader.cs => BakeLightProbeShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/LightProbes/{ComputeSphericalHarmonics.cs => ComputeSphericalHarmonics.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/LightProbes/{LightProbeShader.cs => LightProbeShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/LightProbes/{XenkoBakeLightProbeEffect.cs => XenkoBakeLightProbeEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Images/SphericalHarmonics/SphericalHarmonicsUtils.cs => Lights/DirectLightGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{DirectLightGroup.cs => DirectLightGroupArray.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{DirectLightGroupArray.cs => DirectLightGroupFixed.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{DirectLightGroupPerDraw.cs => DirectLightGroupPerDraw.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{DirectLightGroupPerView.cs => DirectLightGroupPerView.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{DirectLightGroupFixed.cs => EnvironmentLight.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{EnvironmentLight.cs => EnvironmentLightArray.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightClustered.cs => LightClustered.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightClusteredPointGroup.cs => LightClusteredPointGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightClusteredSpotGroup.cs => LightClusteredSpotGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{EnvironmentLightArray.cs => LightDirectional.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightDirectionalGroup.cs => LightDirectionalGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightDirectional1.cs => LightPoint.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightPointGroup.cs => LightPointGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSimpleAmbient.cs => LightSimpleAmbient.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSkyboxEffect.cs => LightSkyboxEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSkyboxShader.cs => LightSkyboxShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightPoint1.cs => LightSpot.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSpot1.cs => LightSpotAttenuationDefault.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSpotAttenuationDefault.cs => LightSpotAttenuationRectangular.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSpotGroup.cs => LightSpotGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightSpotAttenuationRectangular.cs => LightStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightStream.cs => LightUtil.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{LightUtil.cs => SpotLightDataInternalShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/{SpotLightDataInternalShader.cs => TextureProjection/TextureProjectionCommon.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/{TextureProjectionCommon.cs => TextureProjectionFilterDefault.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/{TextureProjectionFilterDefault.cs => TextureProjectionGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/{TextureProjectionReceiverBase.cs => TextureProjectionReceiverBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/{TextureProjectionGroup.cs => TextureProjectionReceiverSpot.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/{IMaterialCelShadingLightFunction.cs => IMaterialCelShadingLightFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/{MaterialCelShadingLightDefault.cs => MaterialCelShadingLightDefault.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/{MaterialCelShadingLightRamp2.cs => MaterialCelShadingLightRamp.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Lights/TextureProjection/TextureProjectionReceiverSpot.cs => Materials/ComputeColors/Shaders/3dsMax/ComputeColorAdd3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorAdd3ds.cs => ComputeColorDarken3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorDarken3ds.cs => ComputeColorDifference3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorDifference3ds.cs => ComputeColorLighten3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorLighten3ds.cs => ComputeColorMask3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorMask3ds.cs => ComputeColorMultiply3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorMultiply3ds.cs => ComputeColorOver3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorOver3ds.cs => ComputeColorOverlay3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/{ComputeColorOverlay3ds.cs => ComputeColorSubtract3ds.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{3dsMax/ComputeColorSubtract3ds.cs => ComputeColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColor.cs => ComputeColor3.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColor3.cs => ComputeColorAdd.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorAdd.cs => ComputeColorAdd3.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorAdd3.cs => ComputeColorAverage.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorAverage.cs => ComputeColorCave.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorCave.cs => ComputeColorColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorColor.cs => ComputeColorColorBurn.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorColorBurn.cs => ComputeColorColorDodge.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorColorDodge.cs => ComputeColorConstantColorLink.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorConstantColorLink.cs => ComputeColorConstantFloatLink.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorConstantFloatLink.cs => ComputeColorConstantLink.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorConstantLink.cs => ComputeColorDesaturate.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorDesaturate.cs => ComputeColorDivide.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorDivide.cs => ComputeColorExclusion.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorExclusion.cs => ComputeColorFixed.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorFixed.cs => ComputeColorFromStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorFromStream.cs => ComputeColorHardLight.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorHardLight.cs => ComputeColorHardMix.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorHardMix.cs => ComputeColorHue.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorHue.cs => ComputeColorIlluminate.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorIlluminate.cs => ComputeColorIn.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorIn.cs => ComputeColorLerpAlpha.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorLerpAlpha.cs => ComputeColorLinearBurn.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorLinearBurn.cs => ComputeColorLinearDodge.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorLinearDodge.cs => ComputeColorMask.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorMask.cs => ComputeColorMultiply.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorMultiply.cs => ComputeColorOne.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorOne.cs => ComputeColorOut.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorOut.cs => ComputeColorOutdoor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorOutdoor.cs => ComputeColorOverlay.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorParameter.cs => ComputeColorParameter.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorOverlay.cs => ComputeColorPinLight.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorPinLight.cs => ComputeColorSaturate.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSaturate.cs => ComputeColorSaturation.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSaturation.cs => ComputeColorScaler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorScaler.cs => ComputeColorScreen.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorScreen.cs => ComputeColorSoftLight.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSoftLight.cs => ComputeColorStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorStream.cs => ComputeColorSubstituteAlpha.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSubstituteAlpha.cs => ComputeColorSubstituteAlphaWithColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSubstituteAlphaWithColor.cs => ComputeColorSubtract.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSubtract1.cs => ComputeColorSynthetic.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorSynthetic.cs => ComputeColorTexture.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureDynamicScaledOffset.cs => ComputeColorTextureDynamicScaledOffset.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTexture.cs => ComputeColorTextureLodSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureLodSampler.cs => ComputeColorTextureLodScaledOffsetDynamicSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureLodScaledOffsetDynamicSampler.cs => ComputeColorTextureLodScaledOffsetSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureLodScaledOffsetSampler.cs => ComputeColorTextureLodScaledSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureLodScaledSampler.cs => ComputeColorTextureRepeat.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureRepeat.cs => ComputeColorTextureSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureSampler.cs => ComputeColorTextureScaled.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureScaled.cs => ComputeColorTextureScaledOffset.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureScaledOffset.cs => ComputeColorTextureScaledOffsetDynamicSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureScaledOffsetDynamicSampler.cs => ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.cs => ComputeColorTextureScaledOffsetSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureScaledOffsetSampler.cs => ComputeColorTextureScaledSampler.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorTextureScaledSampler.cs => ComputeColorThreshold.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorThreshold.cs => ComputeColorValue.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/{ComputeColorValue.cs => Maya/ComputeColorAddMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/{ComputeColorAddMaya.cs => ComputeColorDarkenMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/{ComputeColorDarkenMaya.cs => ComputeColorDifferenceMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/{ComputeColorDifferenceMaya.cs => ComputeColorLightenMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/{ComputeColorLightenMaya.cs => ComputeColorMultiplyMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/{ComputeColorMultiplyMaya.cs => ComputeColorOverMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/{ComputeColorOverMaya.cs => ComputeColorSubtractMaya.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{ComputeColors/Shaders/Maya/ComputeColorSubtractMaya.cs => Hair/DirectionFunction/IMaterialHairDirectionFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/{IMaterialHairDirectionFunction1.cs => MaterialHairDirectionFunctionBitangent.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/{MaterialHairDirectionFunctionBitangent1.cs => MaterialHairDirectionFunctionTangent.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/{DirectionFunction/MaterialHairDirectionFunctionTangent1.cs => DiscardFunction/IMaterialHairDiscardFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/{IMaterialHairDiscardFunction1.cs => MaterialHairDiscardFunctionOpaquePass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/{MaterialHairDiscardFunctionOpaquePass1.cs => MaterialHairDiscardFunctionTransparentPass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/{DiscardFunction/MaterialHairDiscardFunctionTransparentPass1.cs => LightAttenuationFunction/IMaterialHairLightAttenuationFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/{IMaterialHairLightAttenuationFunction1.cs => MaterialHairLightAttenuationFunctionDirectional.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/{MaterialHairLightAttenuationFunctionDirectional2.cs => MaterialHairLightAttenuationFunctionNone.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/{MaterialHairShared1.cs => MaterialHairShared.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/{LightAttenuationFunction/MaterialHairLightAttenuationFunctionNone1.cs => MaterialSurfaceShadingDiffuseHair.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/{MaterialSurfaceShadingSpecularHair.cs => MaterialSurfaceShadingSpecularHair.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/{MaterialSurfaceShadingDiffuseHair.cs => ShadowingFunction/IMaterialHairShadowingFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/{IMaterialHairShadowingFunction1.cs => MaterialHairShadowingFunctionScattering.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/{MaterialHairShadowingFunctionScattering1.cs => MaterialHairShadowingFunctionShadowing.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{Hair/ShadowingFunction/MaterialHairShadowingFunctionShadowing1.cs => IMaterialSurfaceDomain.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{IMaterialSurfaceDomain.cs => IStreamInitializer.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{IStreamInitializer.cs => MaterialDisplacementStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{MaterialDisplacementStream.cs => MaterialDomainStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{MaterialDomainStream.cs => MaterialStreamAdditiveBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{MaterialStreamAdditiveBlend.cs => MaterialSurfaceDisplacement.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{MaterialSurfaceDisplacement1.cs => MaterialSurfaceDomainStageCompositor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{MaterialSurfaceDomainStageCompositor1.cs => MaterialTessellationStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{MaterialTessellationStream1.cs => Shaders/ComputeColorMaterialAlphaBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{ComputeColorMaterialAlphaBlend.cs => GBufferOutputNormals.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{GBufferOutputSpecularColorRoughness.cs => GBufferOutputSpecularColorRoughness.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{GBufferOutputSubsurfaceScatteringMaterialIndex.cs => GBufferOutputSubsurfaceScatteringMaterialIndex.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{GBufferOutputNormals.cs => IMaterialSpecularMicrofacetEnvironmentFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSpecularMicrofacetEnvironmentFunction.cs => IMaterialSpecularMicrofacetFresnelFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSpecularMicrofacetFresnelFunction.cs => IMaterialSpecularMicrofacetNormalDistributionFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSpecularMicrofacetNormalDistributionFunction.cs => IMaterialSpecularMicrofacetVisibilityFunction.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSpecularMicrofacetVisibilityFunction.cs => IMaterialStreamBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialStreamBlend.cs => IMaterialSurface.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSurface.cs => IMaterialSurfacePixel.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSurfacePixel.cs => IMaterialSurfaceShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSurfaceShading.cs => IMaterialSurfaceVertex.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialFrontBackBlendShader.cs => MaterialFrontBackBlendShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{IMaterialSurfaceVertex.cs => MaterialPixelShadingStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialPixelShadingStream.cs => MaterialPixelStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetEnvironmentGGXLUT.cs => MaterialSpecularMicrofacetEnvironmentGGXLUT.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialPixelStream.cs => MaterialSpecularMicrofacetEnvironmentGGXPolynomial.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetEnvironmentThinGlass.cs => MaterialSpecularMicrofacetEnvironmentThinGlass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetEnvironmentGGXPolynomial.cs => MaterialSpecularMicrofacetFresnelNone.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetFresnelNone.cs => MaterialSpecularMicrofacetFresnelSchlick.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetFresnelSchlick.cs => MaterialSpecularMicrofacetFresnelThinGlass.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetFresnelThinGlass.cs => MaterialSpecularMicrofacetNormalDistributionBeckmann.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetNormalDistributionBeckmann.cs => MaterialSpecularMicrofacetNormalDistributionBlinnPhong.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetNormalDistributionBlinnPhong.cs => MaterialSpecularMicrofacetNormalDistributionGGX.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetNormalDistributionGGX.cs => MaterialSpecularMicrofacetVisibilityCookTorrance.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilityCookTorrance.cs => MaterialSpecularMicrofacetVisibilityImplicit.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilityImplicit.cs => MaterialSpecularMicrofacetVisibilityKelemen.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilityKelemen.cs => MaterialSpecularMicrofacetVisibilityNeumann.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilityNeumann.cs => MaterialSpecularMicrofacetVisibilitySmithBeckmann.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilitySmithBeckmann.cs => MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.cs => MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.cs => MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.cs => MaterialStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialStream.cs => MaterialStreamLinearBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialStreamLinearBlend.cs => MaterialStreamNormalBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialStreamNormalBlend.cs => MaterialSurfaceArray.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceArray.cs => MaterialSurfaceDiffuse.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceDiffuse.cs => MaterialSurfaceDiffuseMetalFlakes.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceDiffuseMetalFlakes.cs => MaterialSurfaceDiffuseSpecularAlphaBlendColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceDiffuseSpecularAlphaBlendColor.cs => MaterialSurfaceEmissiveShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceEmissiveShading.cs => MaterialSurfaceGlossinessMap.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceGlossinessMap.cs => MaterialSurfaceGlossinessMapMetalFlakes.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceGlossinessMapMetalFlakes.cs => MaterialSurfaceLightingAndShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceLightingAndShading.cs => MaterialSurfaceMetalness.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceMetalness.cs => MaterialSurfaceNormalMap.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceNormalMap.cs => MaterialSurfaceNormalStreamShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceNormalStreamShading.cs => MaterialSurfacePixelStageCompositor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfacePixelStageCompositor.cs => MaterialSurfaceSetStreamFromComputeColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceSetStreamFromComputeColor.cs => MaterialSurfaceShadingBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceShadingBlend.cs => MaterialSurfaceShadingDiffuseLambert.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceShadingDiffuseLambert.cs => MaterialSurfaceShadingSpecularBlinnPhong.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceShadingSpecularBlinnPhong.cs => MaterialSurfaceShadingSpecularMicrofacet.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceShadingSpecularMicrofacet.cs => MaterialSurfaceStreamShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceStreamShading.cs => MaterialSurfaceStreamsBlend.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceStreamsBlend.cs => MaterialSurfaceTransmittanceShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceTransmittanceShading.cs => MaterialSurfaceTransparentAlphaDiscard.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceTransparentAlphaDiscard.cs => MaterialSurfaceVertexDisplacement.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceVertexDisplacement.cs => MaterialSurfaceVertexStageCompositor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialTransmittanceReflectanceStream.cs => MaterialTransmittanceReflectanceStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/{MaterialSurfaceVertexStageCompositor.cs => MaterialVertexStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/{MaterialSurfaceSubsurfaceScatteringShading.cs => MaterialSurfaceSubsurfaceScatteringShading.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/{Shaders/MaterialVertexStream.cs => SubsurfaceScattering/ScatteringProfileFunction/IMaterialSubsurfaceScatteringScatteringProfile.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/{MaterialSubsurfaceScatteringScatteringProfileCustomUniform1.cs => MaterialSubsurfaceScatteringScatteringProfileCustomUniform.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/{IMaterialSubsurfaceScatteringScatteringProfile1.cs => MaterialSubsurfaceScatteringScatteringProfileCustomVarying.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/{MaterialSubsurfaceScatteringScatteringProfileCustomVarying1.cs => MaterialSubsurfaceScatteringScatteringProfileSkin.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/ProceduralModels/{CameraCube.cs => CameraCube.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shaders/{Camera.cs => Camera.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shaders/{Global.cs => Global.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shaders/{GlobalVR.cs => GlobalVR.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shaders/{Transformation.cs => Transformation.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileSkin1.cs => Shadows/ShadowGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCaster.cs => ShadowMapCaster.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowGroup.cs => ShadowMapCasterAlphaDiscard.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterCubeMap.cs => ShadowMapCasterCubeMap.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterAlphaDiscard.cs => ShadowMapCasterCubeMapProjection.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterCubeMapProjection1.cs => ShadowMapCasterNoPixelShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterParaboloid1.cs => ShadowMapCasterParaboloid.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterParaboloidProjection1.cs => ShadowMapCasterParaboloidProjection.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterNoPixelShader.cs => ShadowMapCasterVsm.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCasterVsm.cs => ShadowMapCommon.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapCommon.cs => ShadowMapFilterBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapFilterBase.cs => ShadowMapFilterDefault.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapFilterDefault.cs => ShadowMapFilterPcf.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapFilterVsm.cs => ShadowMapFilterVsm.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapFilterPcf.cs => ShadowMapGroup.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapReceiverBase.cs => ShadowMapReceiverBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapReceiverDirectional.cs => ShadowMapReceiverDirectional.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapReceiverPointCubeMap.cs => ShadowMapReceiverPointCubeMap.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapReceiverPointParaboloid.cs => ShadowMapReceiverPointParaboloid.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapGroup.cs => ShadowMapReceiverSpot.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Shadows/{ShadowMapReceiverSpot.cs => ShadowStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Shadows/ShadowStream.cs => Skinning/NormalMeshSkinning.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skinning/{NormalMeshSkinning.cs => NormalVSSkinningFromMesh.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skinning/{NormalVSSkinningFromMesh.cs => NormalVSSkinningNormalMapping.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skinning/{NormalVSSkinningNormalMapping.cs => TangentMeshSkinning.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skinning/{TransformationSkinning.cs => TransformationSkinning.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Skinning/TangentMeshSkinning.cs => Skyboxes/CubemapUtils.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{CubemapUtils.cs => IComputeEnvironmentColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{LevelCubeMapEnvironmentColor.cs => LevelCubeMapEnvironmentColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{RoughnessCubeMapEnvironmentColor.cs => RoughnessCubeMapEnvironmentColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{SkyboxShaderBase.cs => SkyboxShaderBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{SkyboxShaderCubemap.cs => SkyboxShaderCubemap.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{SkyboxShaderTexture.cs => SkyboxShaderTexture.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{IComputeEnvironmentColor.cs => SkyboxStream.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Skyboxes/{SphericalHarmonicsEnvironmentColor.cs => SphericalHarmonicsEnvironmentColor.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Skyboxes/SkyboxStream.cs => Tessellation/TessellationAE2.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Tessellation/{TessellationAE2.cs => TessellationAE3.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Tessellation/{TessellationAE3.cs => TessellationAE4.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Tessellation/{TessellationAE4.cs => TessellationBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Tessellation/{TessellationBase.cs => TessellationFlat.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Tessellation/{TessellationFlat.cs => TessellationPN.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Tessellation/TessellationPN.cs => Transformation/TransformationBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Transformation/{TransformationBase.cs => TransformationMatrix.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Transformation/{TransformationMatrix.cs => TransformationWAndVP.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Transformation/{TransformationWAndVP.cs => TransformationWVP.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Transformation/{TransformationWVP.cs => TransformationZero.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{Transformation/TransformationZero.cs => Utils/BlendUtils.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{DepthBase.cs => DepthBase.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{BlendUtils.cs => FlattenLayers.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{FlattenLayers.cs => HSVUtils.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{HighlightShader.cs => HighlightShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{HSVUtils.cs => Math.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{ModelComponentPickingEffect.cs => ModelComponentPickingEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{ModelComponentPickingShader.cs => ModelComponentPickingShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{NormalPack.cs => NormalPack.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{Math.cs => NormalUtil.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{Picking.cs => Picking.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{PickingShader.cs => PickingShader.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{NormalUtil.cs => SwapUV.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/Utils/{SwapUV.cs => Utilities.xksl.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{XenkoEffectBase.cs => XenkoEffectBase.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{XenkoForwardShadingEffect.cs => XenkoForwardShadingEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Rendering/Rendering/{XenkoWireframeShadingEffect.cs => XenkoWireframeShadingEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/{SimpleEffect.cs => SimpleEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/{SimpleShader.cs => SimpleShader.xksl.cs} (100%) rename sources/engine/{Xenko.Rendering/Rendering/Utils/Utilities.cs => Xenko.Shaders.Tests/GameAssets/Compiler/TestStream.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/{ToGlslEffect.cs => ToGlslEffect.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/{ToGlslShader.cs => ToGlslShader.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/{Compiler/TestStream.cs => Mixins/A.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{A.cs => B.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{B.cs => C.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{C.cs => C1.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{C1.cs => ComputeColor.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{ComputeColor2.cs => ComputeColor2.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{ComputeColor.cs => ComputeColorRedirect.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_complex_params.cs => test_mixin_complex_params.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_compose_keys.cs => test_mixin_compose_keys.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_simple.cs => test_mixin_simple.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_simple_child.cs => test_mixin_simple_child.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_simple_child_params.cs => test_mixin_simple_child_params.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_simple_clone.cs => test_mixin_simple_clone.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_simple_compose.cs => test_mixin_simple_compose.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/{test_mixin_simple_params.cs => test_mixin_simple_params.xkfx.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/{Mixins/ComputeColorRedirect.cs => Shaders/BaseTestChild.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{BaseTestChild.cs => BaseTestInter.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{BaseTestInter.cs => BaseTestParent.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{BasicMixin.cs => BasicMixin.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{BasicMixin2.cs => BasicMixin2.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{Child.cs => Child.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{BaseTestParent.cs => ChildError.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ChildError.cs => CloneTestBase.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{CloneTestBase.cs => CloneTestExtern.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{CloneTestExtern.cs => CloneTestRoot.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ConstantBufferTest.cs => ConstantBufferTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{CloneTestRoot.cs => CyclicTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{CyclicTest.cs => DeepExtern.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{DeepExtern.cs => DeepExternTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{DeepExternTest.cs => ExternClone.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ExternClone.cs => ExternCloneTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ExternMixin.cs => ExternMixin.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ExternCloneTest.cs => ExternTest.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest.cs rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ForEachTest1.cs => ForEachTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{ExternTest.cs => GenericCall.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{GenericCall.cs => GenericClass.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{GenericClass2.cs => GenericClass2.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{GenericClass.cs => GenericExtern.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{GenericTexcoord.cs => GenericTexcoord.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{GenericExtern.cs => GeometryShaderTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{GeometryShaderTest.cs => InterfaceTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{InternalReferenceMixin.cs => InternalReferenceMixin.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MacroTest1.cs => MacroTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{InterfaceTest.cs => MacroTestBase.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MacroTestBase.cs => MacroTestChild.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MacroTestChild.cs => MixinFunctionParamaterTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MacroTestChild1.cs => MixinNameClash.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MixinFunctionParamaterTest.cs => MixinNoNameClash.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MixinNameClash.cs => NonStageStreamTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{Parent.cs => Parent.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest.cs rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{SemanticTest1.cs => SemanticTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{Simple.cs => Simple.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StageBase.cs => StageBase.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{MixinNoNameClash.cs => StageCallExtern.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StageDecl.cs => StageDecl.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{NonStageStreamTest.cs => StageValueReference.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StageValueTest.cs => StageValueTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StageCallExtern.cs => StaticCallMixin.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StaticMixin.cs => StaticMixin.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StageValueReference.cs => StaticStageCallTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StaticCallMixin.cs => StreamChild.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StaticStageCallTest.cs => StreamError.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamChild.cs => StreamParent0.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamError.cs => StreamParent1.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamParent0.cs => StreamParent2.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamParent1.cs => StreamSolverExternTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamParent2.cs => StreamTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StructuredBufferTest.cs => StructuredBufferTest.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamParent21.cs => TessellationTest.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader.cs rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestComputeShader1.cs => TestComputeShader.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestErrors.cs => TestErrors.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamSolverExternTest.cs => TestExternArray.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{StreamTest.cs => TestGenericComplex.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TessellationTest.cs => TestGenericMacro.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestGenerics.cs => TestGenerics.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestExternArray.cs => TestMacros.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestGenericComplex.cs => TestMacrosArray.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestGenericMacro.cs => TestMultipleStatic.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestMacros.cs => TestPixelStream.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestMacrosArray.cs => TestScreenPosition.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStreams.cs rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestMacrosArray1.cs => TestStreams.xksl.cs} (100%) rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestStructInheritance.cs => TestStructInheritance.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructure.cs rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestMultipleStatic.cs => TestStructure.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestVertexStream.cs rename sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/{TestPixelStream.cs => TestVertexStream.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Shaders.Tests/Properties/AssemblyInfo.cs delete mode 100644 sources/engine/Xenko.Video/Shaders/VideoShader.cs rename sources/engine/{Xenko.Shaders.Tests/GameAssets/Shaders/TestScreenPosition.cs => Xenko.Video/Shaders/VideoShader.xksl.cs} (100%) rename sources/{engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest.cs => tools/Xenko.VisualStudio.Package.Tests/TestGenerator.xksl.cs} (58%) diff --git a/sources/assets/Xenko.Core.Assets.CompilerApp/build/Xenko.Core.Assets.CompilerApp.targets b/sources/assets/Xenko.Core.Assets.CompilerApp/build/Xenko.Core.Assets.CompilerApp.targets index 72a0fc51a2..0639e6f234 100644 --- a/sources/assets/Xenko.Core.Assets.CompilerApp/build/Xenko.Core.Assets.CompilerApp.targets +++ b/sources/assets/Xenko.Core.Assets.CompilerApp/build/Xenko.Core.Assets.CompilerApp.targets @@ -148,4 +148,16 @@ + + + + + + + + diff --git a/sources/editor/Xenko.Assets.Presentation/Shaders/PreviewTexture.cs b/sources/editor/Xenko.Assets.Presentation/Shaders/PreviewTexture.xkfx.cs similarity index 100% rename from sources/editor/Xenko.Assets.Presentation/Shaders/PreviewTexture.cs rename to sources/editor/Xenko.Assets.Presentation/Shaders/PreviewTexture.xkfx.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Shaders/SceneEditorParameters.cs b/sources/editor/Xenko.Assets.Presentation/Shaders/SceneEditorParameters.xkfx.cs similarity index 100% rename from sources/editor/Xenko.Assets.Presentation/Shaders/SceneEditorParameters.cs rename to sources/editor/Xenko.Assets.Presentation/Shaders/SceneEditorParameters.xkfx.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Shaders/SelectedSprite.cs b/sources/editor/Xenko.Assets.Presentation/Shaders/SelectedSprite.xkfx.cs similarity index 100% rename from sources/editor/Xenko.Assets.Presentation/Shaders/SelectedSprite.cs rename to sources/editor/Xenko.Assets.Presentation/Shaders/SelectedSprite.xkfx.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorForwardShadingEffect.cs b/sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorForwardShadingEffect.xkfx.cs similarity index 100% rename from sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorForwardShadingEffect.cs rename to sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorForwardShadingEffect.xkfx.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorHighlightingEffect.cs b/sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorHighlightingEffect.xkfx.cs similarity index 100% rename from sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorHighlightingEffect.cs rename to sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorHighlightingEffect.xkfx.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorMaterialPreviewEffect.cs b/sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorMaterialPreviewEffect.xkfx.cs similarity index 100% rename from sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorMaterialPreviewEffect.cs rename to sources/editor/Xenko.Assets.Presentation/Shaders/XenkoEditorMaterialPreviewEffect.xkfx.cs diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj index f1f54e20dd..c141b1815c 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj @@ -115,19 +115,6 @@ - - - - True - True - True - %(Filename).xkfx - - - XenkoShaderKeyGenerator - %(Filename).cs - - diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/ActivityAndroid.cs b/sources/engine/Xenko.Graphics.Tests.10_0/ActivityAndroid.cs deleted file mode 100644 index 68a44e1917..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/ActivityAndroid.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Runtime.CompilerServices; -using Android.App; -using Android.OS; -using Xenko.Effects; -using Xenko.Starter; - -namespace Xenko.Graphics.Tests -{ - [Activity(Label = "Xenko Graphics", MainLauncher = true, Icon = "@drawable/icon")] - public class ActivityAndroid : AndroidXenkoActivity - { - protected override void OnCreate(Bundle bundle) - { - RuntimeHelpers.RunModuleConstructor(typeof(MaterialKeys).Module.ModuleHandle); - - base.OnCreate(bundle); - - //Game = new TestDrawQuad(); - //Game = new TestGeometricPrimitives(); - //Game = new TestRenderToTexture(); - //Game = new TestSpriteBatch(); - //Game = new TestImageLoad(); - //Game = new TestStaticSpriteFont(); - //Game = new TestDynamicSpriteFont(); - //Game = new TestDynamicSpriteFontJapanese(); - Game = new TestDynamicSpriteFontVarious(); - - Game.Run(GameContext); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Application.iOS.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Application.iOS.cs deleted file mode 100644 index 4e86a91fad..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Application.iOS.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using MonoTouch.Foundation; -using MonoTouch.UIKit; -using Xenko.Starter; - -namespace Xenko.Graphics.Tests -{ - public class ManualApplication - { - static void Main(string[] args) - { - UIApplication.Main(args, null, "ManualAppDelegate"); - } - } - - [Register("ManualAppDelegate")] - public class ManualAppDelegate : XenkoApplicationDelegate - { - public override bool FinishedLaunching(UIApplication app, NSDictionary options) - { - //Game = new TestImageLoad(); - //Game = new TestStaticSpriteFont(); - //Game = new TestDynamicSpriteFont(); - //Game = new TestDynamicSpriteFontJapanese(); - Game = new TestDynamicSpriteFontVarious(); - - return base.FinishedLaunching(app, options); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.cs deleted file mode 100644 index accf477ccc..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.cs +++ /dev/null @@ -1,2 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl index 29e545bb17..8c60e6597f 100644 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl +++ b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl @@ -9,7 +9,7 @@ namespace Xenko.Rendering.Lights { float3 Position; float Radius; - } + }; @@ -67,5 +67,5 @@ namespace Xenko.Rendering.Lights FilteredLightIndicesBuffer[FilteredLightIndicesCount] = -1; } } - } + }; } diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl.cs new file mode 100644 index 0000000000..51d014429f --- /dev/null +++ b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/LightTiling.xksl.cs @@ -0,0 +1,25 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Lights +{ + public static partial class LightTilingKeys + { + public static readonly ValueParameterKey PointLightCount = ParameterKeys.NewValue(); + public static readonly ObjectParameterKey PointLights = ParameterKeys.NewObject(); + public static readonly ObjectParameterKey FilteredLightIndicesBuffer = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffect.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffect.cs rename to sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffect.xkfx.cs diff --git a/samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWave.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffectShader.xksl.cs similarity index 100% rename from samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWave.cs rename to sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffectShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Info.plist b/sources/engine/Xenko.Graphics.Tests.10_0/Info.plist deleted file mode 100644 index b4126d24dc..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Info.plist +++ /dev/null @@ -1,30 +0,0 @@ - - - - - CFBundleDisplayName - PDX Graphics - CFBundleIdentifier - com.xenko.graphics.tests - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1.0 - UIDeviceFamily - - 1 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationLandscapeRight - - MinimumOSVersion - 7.0 - CFBundleIconFiles - - Icon@2x.png - Icon.png - Icon-60@2x.png - - - diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AndroidManifest.xml b/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AndroidManifest.xml deleted file mode 100644 index b1df0f66f4..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AndroidManifest.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.Android.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.Android.cs deleted file mode 100644 index 27a54ef326..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.Android.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Android.App; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Graphics")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Xenko.Graphics")] -[assembly: AssemblyCopyright("Copyright © 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("1ebcac74-0858-4b96-8979-f0ac6db3c2e7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - -// Add some common permissions, these can be removed if not needed -[assembly: UsesPermission(Android.Manifest.Permission.Internet)] -[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)] diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.cs deleted file mode 100644 index 8094c50b3e..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Graphics.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("Xenko.Graphics.Tests")] -[assembly: AssemblyCopyright("Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Drawable/icon.png b/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Drawable/icon.png deleted file mode 100644 index 8c70a8b1d4..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Drawable/icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2f3ad740f385a95762943a6aad4b9681f8d2baf8935d5f3457b1855a7ee67e99 -size 15351 diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon-60@2x.png b/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon-60@2x.png deleted file mode 100644 index f8a4b181af..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon-60@2x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e0d5fcd3786c0ff6a274d767ed7d6a6281989d422ba9c2abc543f77b0d0605ac -size 14005 diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon.png b/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon.png deleted file mode 100644 index 7a12e35579..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c669dbc80ab0f766aa49dd3f4cd5fa2d59f3c90de728630e7052013b20442cd2 -size 5451 diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon@2x.png b/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon@2x.png deleted file mode 100644 index 828dd63a8f..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Icon@2x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81c3034b0ecc3c5baa665b20f36bbd016f1b6c20135be38a5f16bc0688b9fde4 -size 13031 diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Resource.Designer.cs b/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Resource.Designer.cs deleted file mode 100644 index e0641c3dc5..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Resources/Resource.Designer.cs +++ /dev/null @@ -1,293 +0,0 @@ -#pragma warning disable 1591 -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -[assembly: global::Android.Runtime.ResourceDesignerAttribute("Xenko.Graphics.Tests.Resource", IsApplication=true)] - -namespace Xenko.Graphics.Tests -{ - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] - public partial class Resource - { - - static Resource() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - public static void UpdateIdValues() - { - global::Xenko.Resource.Id.EditTextLayout = global::Xenko.Graphics.Tests.Resource.Id.EditTextLayout; - global::Xenko.Resource.Id.GameMainLayout = global::Xenko.Graphics.Tests.Resource.Id.GameMainLayout; - global::Xenko.Resource.Id.GameViewLayout = global::Xenko.Graphics.Tests.Resource.Id.GameViewLayout; - global::Xenko.Resource.Layout.Game = global::Xenko.Graphics.Tests.Resource.Layout.Game; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::Xenko.Graphics.Tests.Resource.Id.OptionHostName; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::Xenko.Graphics.Tests.Resource.Id.OptionPort; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::Xenko.Graphics.Tests.Resource.Id.OptionRemoteServer; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::Xenko.Graphics.Tests.Resource.Id.OptionsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::Xenko.Graphics.Tests.Resource.Id.ResultFullName; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::Xenko.Graphics.Tests.Resource.Id.ResultMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::Xenko.Graphics.Tests.Resource.Id.ResultResultState; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::Xenko.Graphics.Tests.Resource.Id.ResultRunSingleMethodTest; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::Xenko.Graphics.Tests.Resource.Id.ResultStackTrace; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::Xenko.Graphics.Tests.Resource.Id.ResultsFailed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::Xenko.Graphics.Tests.Resource.Id.ResultsId; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::Xenko.Graphics.Tests.Resource.Id.ResultsIgnored; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::Xenko.Graphics.Tests.Resource.Id.ResultsInconclusive; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::Xenko.Graphics.Tests.Resource.Id.ResultsMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::Xenko.Graphics.Tests.Resource.Id.ResultsPassed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::Xenko.Graphics.Tests.Resource.Id.ResultsResult; - global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::Xenko.Graphics.Tests.Resource.Id.RunTestsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::Xenko.Graphics.Tests.Resource.Id.TestSuiteListView; - global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::Xenko.Graphics.Tests.Resource.Layout.options; - global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::Xenko.Graphics.Tests.Resource.Layout.results; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::Xenko.Graphics.Tests.Resource.Layout.test_result; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::Xenko.Graphics.Tests.Resource.Layout.test_suite; - } - - public partial class Attribute - { - - static Attribute() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Attribute() - { - } - } - - public partial class Drawable - { - - // aapt resource value: 0x7f020000 - public const int dialog_disclosure = 2130837504; - - // aapt resource value: 0x7f020001 - public const int dialog_expander_ic_minimized = 2130837505; - - // aapt resource value: 0x7f020002 - public const int Icon = 2130837506; - - static Drawable() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Drawable() - { - } - } - - public partial class Id - { - - // aapt resource value: 0x7f04000f - public const int EditTextLayout = 2130968591; - - // aapt resource value: 0x7f04000d - public const int GameMainLayout = 2130968589; - - // aapt resource value: 0x7f04000e - public const int GameViewLayout = 2130968590; - - // aapt resource value: 0x7f040011 - public const int OptionHostName = 2130968593; - - // aapt resource value: 0x7f040012 - public const int OptionPort = 2130968594; - - // aapt resource value: 0x7f040010 - public const int OptionRemoteServer = 2130968592; - - // aapt resource value: 0x7f040020 - public const int OptionsButton = 2130968608; - - // aapt resource value: 0x7f04001b - public const int ResultFullName = 2130968603; - - // aapt resource value: 0x7f04001d - public const int ResultMessage = 2130968605; - - // aapt resource value: 0x7f04001c - public const int ResultResultState = 2130968604; - - // aapt resource value: 0x7f04001a - public const int ResultRunSingleMethodTest = 2130968602; - - // aapt resource value: 0x7f04001e - public const int ResultStackTrace = 2130968606; - - // aapt resource value: 0x7f040016 - public const int ResultsFailed = 2130968598; - - // aapt resource value: 0x7f040013 - public const int ResultsId = 2130968595; - - // aapt resource value: 0x7f040017 - public const int ResultsIgnored = 2130968599; - - // aapt resource value: 0x7f040018 - public const int ResultsInconclusive = 2130968600; - - // aapt resource value: 0x7f040019 - public const int ResultsMessage = 2130968601; - - // aapt resource value: 0x7f040015 - public const int ResultsPassed = 2130968597; - - // aapt resource value: 0x7f040014 - public const int ResultsResult = 2130968596; - - // aapt resource value: 0x7f04001f - public const int RunTestsButton = 2130968607; - - // aapt resource value: 0x7f040021 - public const int TestSuiteListView = 2130968609; - - // aapt resource value: 0x7f040002 - public const int dialog_BoolField = 2130968578; - - // aapt resource value: 0x7f040003 - public const int dialog_Button = 2130968579; - - // aapt resource value: 0x7f040009 - public const int dialog_DisclosureField = 2130968585; - - // aapt resource value: 0x7f040005 - public const int dialog_ImageLeft = 2130968581; - - // aapt resource value: 0x7f040007 - public const int dialog_ImageRight = 2130968583; - - // aapt resource value: 0x7f040000 - public const int dialog_LabelField = 2130968576; - - // aapt resource value: 0x7f040001 - public const int dialog_LabelSubtextField = 2130968577; - - // aapt resource value: 0x7f040008 - public const int dialog_Panel = 2130968584; - - // aapt resource value: 0x7f04000a - public const int dialog_RadioButtonList = 2130968586; - - // aapt resource value: 0x7f040006 - public const int dialog_SliderField = 2130968582; - - // aapt resource value: 0x7f04000b - public const int dialog_Spinner = 2130968587; - - // aapt resource value: 0x7f040004 - public const int dialog_ValueField = 2130968580; - - // aapt resource value: 0x7f04000c - public const int iFormFieldValue = 2130968588; - - static Id() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Id() - { - } - } - - public partial class Layout - { - - // aapt resource value: 0x7f030000 - public const int dialog_achievements = 2130903040; - - // aapt resource value: 0x7f030001 - public const int dialog_boolfieldleft = 2130903041; - - // aapt resource value: 0x7f030002 - public const int dialog_boolfieldright = 2130903042; - - // aapt resource value: 0x7f030003 - public const int dialog_boolfieldsubleft = 2130903043; - - // aapt resource value: 0x7f030004 - public const int dialog_boolfieldsubright = 2130903044; - - // aapt resource value: 0x7f030005 - public const int dialog_button = 2130903045; - - // aapt resource value: 0x7f030006 - public const int dialog_datefield = 2130903046; - - // aapt resource value: 0x7f030007 - public const int dialog_fieldsetlabel = 2130903047; - - // aapt resource value: 0x7f030008 - public const int dialog_floatimage = 2130903048; - - // aapt resource value: 0x7f030009 - public const int dialog_labelfieldbelow = 2130903049; - - // aapt resource value: 0x7f03000a - public const int dialog_labelfieldright = 2130903050; - - // aapt resource value: 0x7f03000b - public const int dialog_onofffieldright = 2130903051; - - // aapt resource value: 0x7f03000c - public const int dialog_panel = 2130903052; - - // aapt resource value: 0x7f03000d - public const int dialog_root = 2130903053; - - // aapt resource value: 0x7f03000e - public const int dialog_selectlist = 2130903054; - - // aapt resource value: 0x7f03000f - public const int dialog_selectlistfield = 2130903055; - - // aapt resource value: 0x7f030010 - public const int dialog_textarea = 2130903056; - - // aapt resource value: 0x7f030011 - public const int dialog_textfieldbelow = 2130903057; - - // aapt resource value: 0x7f030012 - public const int dialog_textfieldright = 2130903058; - - // aapt resource value: 0x7f030013 - public const int Game = 2130903059; - - // aapt resource value: 0x7f030014 - public const int options = 2130903060; - - // aapt resource value: 0x7f030015 - public const int results = 2130903061; - - // aapt resource value: 0x7f030016 - public const int test_result = 2130903062; - - // aapt resource value: 0x7f030017 - public const int test_suite = 2130903063; - - static Layout() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Layout() - { - } - } - } -} -#pragma warning restore 1591 diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDeferred.cs b/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDeferred.cs deleted file mode 100644 index 82a703ca18..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDeferred.cs +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Threading.Tasks; - -using Xunit; - -using Xenko.Core.Mathematics; -using Xenko.Effects; -using Xenko.Effects.Cubemap; -using Xenko.Effects.Renderers; -using Xenko.Engine; -using Xenko.EntityModel; -using Xenko.Extensions; - -namespace Xenko.Graphics.Tests -{ - public class TestCubemapDeferred : TestGameBase - { - private LightingIBLRenderer IBLRenderer; - - private Entity teapotEntity; - - private Entity dynamicCubemapEntity; - - public TestCubemapDeferred() - { - GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_11_0 }; - } - - protected override async Task LoadContent() - { - await base.LoadContent(); - - // create pipeline - CreatePipeline(); - - // setup the scene - var material = Asset.Load("BasicMaterial"); - teapotEntity = new Entity() - { - new ModelComponent() - { - Model = new Model() - { - material, - new Mesh() - { - Draw = GeometricPrimitive.Teapot.New(GraphicsDevice).ToMeshDraw(), - MaterialIndex = 0, - } - } - } - }; - Entities.Add(teapotEntity); - - var textureCube = Asset.Load("uv_cube"); - var staticCubemapEntity = new Entity() - { - new CubemapSourceComponent(textureCube) { InfluenceRadius = 2f, IsDynamic = false }, - new TransformationComponent() { Translation = Vector3.UnitZ } - }; - Entities.Add(staticCubemapEntity); - - dynamicCubemapEntity = new Entity() - { - new CubemapSourceComponent(textureCube) { InfluenceRadius = 0.5f, IsDynamic = false }, - new TransformationComponent() { Translation = Vector3.Zero } - }; - Entities.Add(dynamicCubemapEntity); - - var mainCamera = new Entity() - { - new CameraComponent - { - AspectRatio = 8/4.8f, - FarPlane = 20, - NearPlane = 1, - VerticalFieldOfView = 0.6f, - Target = teapotEntity, - TargetUp = Vector3.UnitY, - }, - new TransformationComponent - { - Translation = new Vector3(4, 3, 0) - } - }; - Entities.Add(mainCamera); - - RenderSystem.Pipeline.SetCamera(mainCamera.Get()); - - Script.Add(GameScript1); - } - - private void CreatePipeline() - { - // Processor - Entities.Processors.Add(new CubemapSourceProcessor(GraphicsDevice)); - - // Rendering pipeline - RenderSystem.Pipeline.Renderers.Add(new CameraSetter(Services)); - - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) - { - ClearColor = Color.CornflowerBlue, - EnableClearDepth = true, - ClearDepth = 1f - }); - - // Create G-buffer pass - var gbufferPipeline = new RenderPipeline("GBuffer"); - // Renders the G-buffer for opaque geometry. - gbufferPipeline.Renderers.Add(new ModelRenderer(Services, "CubemapIBLEffect.XenkoGBufferShaderPass")); - var gbufferProcessor = new GBufferRenderProcessor(Services, gbufferPipeline, GraphicsDevice.DepthStencilBuffer, false); - - // Add sthe G-buffer pass to the pipeline. - RenderSystem.Pipeline.Renderers.Add(gbufferProcessor); - - var readOnlyDepthBuffer = GraphicsDevice.DepthStencilBuffer; // TODO ToDepthStencilBuffer(true); - IBLRenderer = new LightingIBLRenderer(Services, "CubemapIBLSpecular", readOnlyDepthBuffer); - RenderSystem.Pipeline.Renderers.Add(IBLRenderer); - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) - { - ClearColor = Color.CornflowerBlue, - EnableClearDepth = false, - }); - RenderSystem.Pipeline.Renderers.Add(new DelegateRenderer(Services) { Render = ShowIBL }); - } - - private void ShowIBL(RenderContext context) - { - GraphicsDevice.DrawTexture(IBLRenderer.IBLTexture); - } - - private async Task GameScript1() - { - while (IsRunning) - { - // Wait next rendering frame - await Script.NextFrame(); - - teapotEntity.Transform.Rotation = Quaternion.RotationY((float)(2 * Math.PI * UpdateTime.Total.TotalMilliseconds / 5000.0f)); - dynamicCubemapEntity.Transform.Translation = new Vector3(2f * (float)Math.Sin(2 * Math.PI * UpdateTime.Total.TotalMilliseconds / 15000.0f), 0, 0); - } - } - - public static void Main() - { - using (var game = new TestCubemapDeferred()) - game.Run(); - } - - /// - /// Run the test - /// - [Fact] - public void RunCubemapRendering() - { - RunGameTest(new TestCubemapDeferred()); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDisplay.cs b/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDisplay.cs deleted file mode 100644 index 0f3b5934fd..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapDisplay.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Threading.Tasks; - -using Xunit; - -using Xenko.Core.Mathematics; -using Xenko.Effects; -using Xenko.Engine; -using Xenko.EntityModel; -using Xenko.Extensions; - -namespace Xenko.Graphics.Tests -{ - public class TestCubemapDisplay : TestGameBase - { - private Entity mainCamera; - private float cameraDistance = 3; - private float cameraHeight = 3; - private Vector3 cameraUp = Vector3.UnitY; - - public TestCubemapDisplay() - { - GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_9_1 }; - } - - protected override async Task LoadContent() - { - await base.LoadContent(); - - CreatePipeline(); - - var material = Asset.Load("BasicMaterial"); - var textureCube = Asset.Load("uv_cube"); - material.Parameters.Set(TexturingKeys.TextureCube0, textureCube); - var mesh = new Mesh() - { - Draw = GeometricPrimitive.GeoSphere.New(GraphicsDevice).ToMeshDraw(), - Material = material - }; - mesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group1); - - var entity = new Entity() - { - new ModelComponent() - { - Model = new Model() { mesh } - }, - new TransformationComponent() - }; - - Entities.Add(entity); - - var mainCameraTargetEntity = new Entity(Vector3.Zero); - Entities.Add(mainCameraTargetEntity); - mainCamera = new Entity() - { - new CameraComponent - { - AspectRatio = 8/4.8f, - FarPlane = 1000, - NearPlane = 1, - VerticalFieldOfView = 0.6f, - Target = mainCameraTargetEntity, - TargetUp = cameraUp, - }, - new TransformationComponent - { - Translation = cameraDistance * Vector3.UnitX - } - }; - Entities.Add(mainCamera); - - RenderSystem.Pipeline.SetCamera(mainCamera.Get()); - - // Add a custom script - Script.Add(GameScript1); - } - - private void CreatePipeline() - { - RenderSystem.Pipeline.Renderers.Add(new CameraSetter(Services)); - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) { ClearColor = Color.CornflowerBlue }); - RenderSystem.Pipeline.Renderers.Add(new ModelRenderer(Services, "CubemapDisplayEffect")); - } - - private async Task GameScript1() - { - while (IsRunning) - { - // Wait next rendering frame - await Script.NextFrame(); - - var angle = Math.PI * UpdateTime.Total.TotalMilliseconds / 5000; - mainCamera.Transform.Translation = new Vector3((float)(cameraDistance * Math.Cos(angle)), cameraHeight, (float)(cameraDistance * Math.Sin(angle))); - } - } - - public static void Main() - { - using (var game = new TestCubemapDisplay()) - game.Run(); - } - - /// - /// Run the test - /// - [Fact] - public void RunCubemapRendering() - { - RunGameTest(new TestCubemapDisplay()); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapRendering.cs b/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapRendering.cs deleted file mode 100644 index b10141aa81..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/TestCubemapRendering.cs +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Xunit; -using Xenko.Core.Mathematics; -using Xenko.Effects; -using Xenko.Effects.Cubemap; -using Xenko.Engine; -using Xenko.EntityModel; -using Xenko.Extensions; -using Xenko.Input; - -namespace Xenko.Graphics.Tests -{ - public class TestCubemapRendering : TestGameBase - { - private Entity mainCamera; - private Vector3 cameraInitPos = new Vector3(10, 0, 0); - private Vector3 cameraUp = Vector3.UnitY; - private Entity[] primitiveEntities; - private Vector3[] rotationAxis; - - public TestCubemapRendering() - { - // cannot render cubemap in level below 10.1 - GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_11_0 }; - } - - protected override async Task LoadContent() - { - await base.LoadContent(); - - CreatePipeline(true); - - IsMouseVisible = true; - - //Input.ActivatedGestures.Add(new GestureConfigDrag()); - - // Creates all primitives - // type pos axis - var primitives = new List> - { - Tuple.Create(GeometricPrimitive.Cube.New(GraphicsDevice), 2 * Vector3.UnitX, new Vector3(1,1,1)), - Tuple.Create(GeometricPrimitive.Teapot.New(GraphicsDevice), -2 * Vector3.UnitX, new Vector3(-1,1,1)), - Tuple.Create(GeometricPrimitive.GeoSphere.New(GraphicsDevice), 2 * Vector3.UnitY, new Vector3(1,0,1)), - Tuple.Create(GeometricPrimitive.Cylinder.New(GraphicsDevice), -2 * Vector3.UnitY, new Vector3(-1,-1,1)), - Tuple.Create(GeometricPrimitive.Torus.New(GraphicsDevice), 2 * Vector3.UnitZ, new Vector3(1,-1,1)), - Tuple.Create(GeometricPrimitive.Sphere.New(GraphicsDevice), -2 * Vector3.UnitZ, new Vector3(0,1,1)), - }; - - primitiveEntities = new Entity[primitives.Count]; - rotationAxis = new Vector3[primitives.Count]; - var material = Asset.Load("BasicMaterial"); - for (var i =0; i < primitives.Count; ++i) - { - var mesh = new Mesh - { - Draw = primitives[i].Item1.ToMeshDraw(), - MaterialIndex = 0, - }; - mesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group1); - - var entity = new Entity - { - new ModelComponent - { - Model = new Model { mesh, material } - }, - new TransformationComponent { Translation = primitives[i].Item2 } - }; - Entities.Add(entity); - primitiveEntities[i] = entity; - rotationAxis[i] = primitives[i].Item3; - } - - var reflectivePrimitive = GeometricPrimitive.Sphere.New(GraphicsDevice); - var reflectiveMesh = new Mesh - { - Draw = reflectivePrimitive.ToMeshDraw(), - }; - reflectiveMesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group2); - - var reflectEntity = new Entity - { - new ModelComponent - { - Model = new Model { reflectiveMesh } - }, - new TransformationComponent(), - new CubemapSourceComponent { IsDynamic = true, Size = 128 } - }; - Entities.Add(reflectEntity); - reflectEntity.Get().Parameters.Set(TexturingKeys.TextureCube0, reflectEntity.Get().Texture); - - var mainCameraTargetEntity = new Entity(Vector3.Zero); - Entities.Add(mainCameraTargetEntity); - mainCamera = new Entity - { - new CameraComponent - { - AspectRatio = 8/4.8f, - FarPlane = 1000, - NearPlane = 1, - VerticalFieldOfView = 0.6f, - Target = mainCameraTargetEntity, - TargetUp = cameraUp, - }, - new TransformationComponent - { - Translation = cameraInitPos - } - }; - Entities.Add(mainCamera); - - RenderSystem.Pipeline.SetCamera(mainCamera.Get()); - - // Add a custom script - Script.Add(GameScript1); - } - - private void CreatePipeline(bool renderInOnePass) - { - // Processor - Entities.Processors.Add(new CubemapSourceProcessor(GraphicsDevice)); - - // Rendering pipeline - var cubeMapPipeline = new RenderPipeline("CubeMap"); - cubeMapPipeline.Renderers.Add(new ModelRenderer(Services, renderInOnePass ? "CubemapGeomEffect" : "CubemapEffect").AddLayerFilter(RenderGroups.Group1)); - RenderSystem.Pipeline.Renderers.Add(new CubemapRenderer(Services, cubeMapPipeline, renderInOnePass)); - RenderSystem.Pipeline.Renderers.Add(new CameraSetter(Services)); - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) { ClearColor = Color.CornflowerBlue }); - RenderSystem.Pipeline.Renderers.Add(new ModelRenderer(Services, "CubemapEffect")); - } - - private async Task GameScript1() - { - var dragValue = Vector2.Zero; - var rotationFactor = 0.125f; - var rotationUpFactor = 0.1f; - var rotate = true; - while (IsRunning) - { - // Wait next rendering frame - await Script.NextFrame(); - - if (Input.IsKeyPressed(Keys.Space)) - rotate = !rotate; - - if (rotate) - { - var rotationPrim = (float) (2*Math.PI*UpdateTime.Total.TotalMilliseconds/15000); - for (var i = 0; i < primitiveEntities.Length; ++i) - { - primitiveEntities[i].Transform.Rotation = Quaternion.RotationAxis(rotationAxis[i], rotationPrim); - } - } - - // rotate camera - dragValue = 0.95f * dragValue; - if (Input.PointerEvents.Count > 0) - { - dragValue = Input.PointerEvents.Aggregate(Vector2.Zero, (t, x) => x.DeltaPosition + t); - } - rotationFactor -= dragValue.X; - rotationUpFactor += dragValue.Y; - if (rotationUpFactor > 0.45f) - rotationUpFactor = 0.45f; - else if (rotationUpFactor < -0.45f) - rotationUpFactor = -0.45f; - mainCamera.Transform.Translation = Vector3.Transform(cameraInitPos, Quaternion.RotationZ((float)(Math.PI * rotationUpFactor)) * Quaternion.RotationY((float)(2 * Math.PI * rotationFactor))); - } - } - - public static void Main() - { - using (var game = new TestCubemapRendering()) - game.Run(); - } - - /// - /// Run the test - /// - [Fact] - public void RunCubemapRendering() - { - RunGameTest(new TestCubemapRendering()); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Android.csproj b/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Android.csproj deleted file mode 100644 index a569a1074b..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Android.csproj +++ /dev/null @@ -1,118 +0,0 @@ - - - - - - - Debug - AnyCPU - {570B0FF9-246F-4C6C-8384-F6BE1887A4A9} - {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - PackageReference - Properties - Xenko.Graphics.Tests - Xenko.Graphics.Tests.10_0 - v8.1 - 512 - true - Resources\Resource.Designer.cs - - Properties\AndroidManifest.xml - armeabi,armeabi-v7a,x86 - - - - - true - obj\ - Android - Android - {04ed1618-1a06-4a69-ac34-1006a978af11} - true - OpenGLES - Tests\$(XenkoGraphicsApi)\$(AssemblyName) - - true - true - - - $(MSBuildThisFileDirectory)Xenko.Graphics.Tests.10_0.xkpkg - ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) - $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID;XENKO_GRAPHICS_API_OPENGL;XENKO_GRAPHICS_API_OPENGLES - prompt - 4 - True - None - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID;XENKO_GRAPHICS_API_OPENGL;XENKO_GRAPHICS_API_OPENGLES - prompt - 4 - False - SdkOnly - - - - - - - - - - - NUnitLiteLauncher.Android.cs - - - - - - - - True - True - True - MultipleRenderTargetsEffect.xkfx - - - True - True - True - MultipleRenderTargetsEffectShader.xksl - - - - - - - - - XenkoShaderKeyGenerator - MultipleRenderTargetsEffect.cs - - - XenkoShaderKeyGenerator - MultipleRenderTargetsEffectShader.cs - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Windows.csproj b/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Windows.csproj index 304bc60adc..b5e115f3f9 100644 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Windows.csproj +++ b/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.Windows.csproj @@ -7,7 +7,6 @@ Xenko.Graphics.Tests.10_0 net461 false - false * Windows Windows @@ -28,46 +27,21 @@ Xenko.Engine.NextGen.NextGenTest1 - - + - - + - - - True - True - True - MultipleRenderTargetsEffect.xkfx - - - True - True - True - MultipleRenderTargetsEffectShader.xksl - - - - - - - - - XenkoShaderKeyGenerator - MultipleRenderTargetsEffect.cs - - - XenkoShaderKeyGenerator - MultipleRenderTargetsEffectShader.cs - - + + + + + \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.iOS.csproj b/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.iOS.csproj deleted file mode 100644 index 38ce9bddca..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.10_0/Xenko.Graphics.Tests.10_0.iOS.csproj +++ /dev/null @@ -1,160 +0,0 @@ - - - - - - - Debug - AnyCPU - {570B0FF9-246F-4C6C-8384-F6BE1887A4A9} - {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Exe - PackageReference - Properties - Resources - Xenko.Graphics.Tests - XenkoGraphicsTests10_0 - obj\ - iOS - iOS - {04ed1618-1a06-4a69-ac34-1006a978af11} - true - OpenGLES - Tests\$(XenkoGraphicsApi)\$(AssemblyName) - - true - true - - - $(MSBuildThisFileDirectory)Xenko.Graphics.Tests.10_0.xkpkg - ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) - $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - True - iPhone Developer - True - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - iPhone Developer - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - True - iPhone Distribution - True - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - iPhone Distribution - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - None - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - None - - - Xenko.Core.Tests.Application - - - - - - - - - NUnitLiteLauncher.iPhone.cs - - - - - - - - True - True - True - MultipleRenderTargetsEffect.xkfx - - - True - True - True - MultipleRenderTargetsEffectShader.xksl - - - - - - - - - XenkoShaderKeyGenerator - MultipleRenderTargetsEffect.cs - - - XenkoShaderKeyGenerator - MultipleRenderTargetsEffectShader.cs - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/ActivityAndroid.cs b/sources/engine/Xenko.Graphics.Tests.11_0/ActivityAndroid.cs deleted file mode 100644 index 68a44e1917..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/ActivityAndroid.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Runtime.CompilerServices; -using Android.App; -using Android.OS; -using Xenko.Effects; -using Xenko.Starter; - -namespace Xenko.Graphics.Tests -{ - [Activity(Label = "Xenko Graphics", MainLauncher = true, Icon = "@drawable/icon")] - public class ActivityAndroid : AndroidXenkoActivity - { - protected override void OnCreate(Bundle bundle) - { - RuntimeHelpers.RunModuleConstructor(typeof(MaterialKeys).Module.ModuleHandle); - - base.OnCreate(bundle); - - //Game = new TestDrawQuad(); - //Game = new TestGeometricPrimitives(); - //Game = new TestRenderToTexture(); - //Game = new TestSpriteBatch(); - //Game = new TestImageLoad(); - //Game = new TestStaticSpriteFont(); - //Game = new TestDynamicSpriteFont(); - //Game = new TestDynamicSpriteFontJapanese(); - Game = new TestDynamicSpriteFontVarious(); - - Game.Run(GameContext); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Application.iOS.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Application.iOS.cs deleted file mode 100644 index 4e86a91fad..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Application.iOS.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using MonoTouch.Foundation; -using MonoTouch.UIKit; -using Xenko.Starter; - -namespace Xenko.Graphics.Tests -{ - public class ManualApplication - { - static void Main(string[] args) - { - UIApplication.Main(args, null, "ManualAppDelegate"); - } - } - - [Register("ManualAppDelegate")] - public class ManualAppDelegate : XenkoApplicationDelegate - { - public override bool FinishedLaunching(UIApplication app, NSDictionary options) - { - //Game = new TestImageLoad(); - //Game = new TestStaticSpriteFont(); - //Game = new TestDynamicSpriteFont(); - //Game = new TestDynamicSpriteFontJapanese(); - Game = new TestDynamicSpriteFontVarious(); - - return base.FinishedLaunching(app, options); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTest.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTest.cs rename to sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTest.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTestEffect.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTestEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTestEffect.cs rename to sources/engine/Xenko.Graphics.Tests.11_0/Assets/ComputeShaderTestEffect.xkfx.cs diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Assets/CubemapSprite.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Assets/CubemapSprite.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests.11_0/Assets/CubemapSprite.cs rename to sources/engine/Xenko.Graphics.Tests.11_0/Assets/CubemapSprite.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Assets/HammersleyTest.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Assets/HammersleyTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests.11_0/Assets/HammersleyTest.cs rename to sources/engine/Xenko.Graphics.Tests.11_0/Assets/HammersleyTest.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Info.plist b/sources/engine/Xenko.Graphics.Tests.11_0/Info.plist deleted file mode 100644 index cce2f372fe..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Info.plist +++ /dev/null @@ -1,32 +0,0 @@ - - - - - CFBundleDisplayName - PDX Graphics - CFBundleIdentifier - com.xenko.graphics.tests - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1.0 - UIDeviceFamily - - 1 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationLandscapeRight - - MinimumOSVersion - 7.0 - NSMainNibFile - - CFBundleIconFiles - - Icon@2x.png - Icon.png - Icon-60@2x.png - - - diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AndroidManifest.xml b/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AndroidManifest.xml deleted file mode 100644 index 188726f409..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AndroidManifest.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.Android.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.Android.cs deleted file mode 100644 index 27a54ef326..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.Android.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Android.App; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Graphics")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Xenko.Graphics")] -[assembly: AssemblyCopyright("Copyright © 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("1ebcac74-0858-4b96-8979-f0ac6db3c2e7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - -// Add some common permissions, these can be removed if not needed -[assembly: UsesPermission(Android.Manifest.Permission.Internet)] -[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)] diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.cs deleted file mode 100644 index 8094c50b3e..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Graphics.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("Xenko.Graphics.Tests")] -[assembly: AssemblyCopyright("Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Drawable/icon.png b/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Drawable/icon.png deleted file mode 100644 index d38fb06661..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Drawable/icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:67ad238d2d0126e2cec3976d052bacf5dfaad7586b1e48f0eeadf6a5b4c497c6 -size 14758 diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon-60@2x.png b/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon-60@2x.png deleted file mode 100644 index f8a4b181af..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon-60@2x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e0d5fcd3786c0ff6a274d767ed7d6a6281989d422ba9c2abc543f77b0d0605ac -size 14005 diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon.png b/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon.png deleted file mode 100644 index 7a12e35579..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c669dbc80ab0f766aa49dd3f4cd5fa2d59f3c90de728630e7052013b20442cd2 -size 5451 diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon@2x.png b/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon@2x.png deleted file mode 100644 index 828dd63a8f..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Icon@2x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81c3034b0ecc3c5baa665b20f36bbd016f1b6c20135be38a5f16bc0688b9fde4 -size 13031 diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Resource.Designer.cs b/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Resource.Designer.cs deleted file mode 100644 index e0641c3dc5..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Resources/Resource.Designer.cs +++ /dev/null @@ -1,293 +0,0 @@ -#pragma warning disable 1591 -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -[assembly: global::Android.Runtime.ResourceDesignerAttribute("Xenko.Graphics.Tests.Resource", IsApplication=true)] - -namespace Xenko.Graphics.Tests -{ - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] - public partial class Resource - { - - static Resource() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - public static void UpdateIdValues() - { - global::Xenko.Resource.Id.EditTextLayout = global::Xenko.Graphics.Tests.Resource.Id.EditTextLayout; - global::Xenko.Resource.Id.GameMainLayout = global::Xenko.Graphics.Tests.Resource.Id.GameMainLayout; - global::Xenko.Resource.Id.GameViewLayout = global::Xenko.Graphics.Tests.Resource.Id.GameViewLayout; - global::Xenko.Resource.Layout.Game = global::Xenko.Graphics.Tests.Resource.Layout.Game; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::Xenko.Graphics.Tests.Resource.Id.OptionHostName; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::Xenko.Graphics.Tests.Resource.Id.OptionPort; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::Xenko.Graphics.Tests.Resource.Id.OptionRemoteServer; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::Xenko.Graphics.Tests.Resource.Id.OptionsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::Xenko.Graphics.Tests.Resource.Id.ResultFullName; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::Xenko.Graphics.Tests.Resource.Id.ResultMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::Xenko.Graphics.Tests.Resource.Id.ResultResultState; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::Xenko.Graphics.Tests.Resource.Id.ResultRunSingleMethodTest; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::Xenko.Graphics.Tests.Resource.Id.ResultStackTrace; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::Xenko.Graphics.Tests.Resource.Id.ResultsFailed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::Xenko.Graphics.Tests.Resource.Id.ResultsId; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::Xenko.Graphics.Tests.Resource.Id.ResultsIgnored; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::Xenko.Graphics.Tests.Resource.Id.ResultsInconclusive; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::Xenko.Graphics.Tests.Resource.Id.ResultsMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::Xenko.Graphics.Tests.Resource.Id.ResultsPassed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::Xenko.Graphics.Tests.Resource.Id.ResultsResult; - global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::Xenko.Graphics.Tests.Resource.Id.RunTestsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::Xenko.Graphics.Tests.Resource.Id.TestSuiteListView; - global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::Xenko.Graphics.Tests.Resource.Layout.options; - global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::Xenko.Graphics.Tests.Resource.Layout.results; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::Xenko.Graphics.Tests.Resource.Layout.test_result; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::Xenko.Graphics.Tests.Resource.Layout.test_suite; - } - - public partial class Attribute - { - - static Attribute() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Attribute() - { - } - } - - public partial class Drawable - { - - // aapt resource value: 0x7f020000 - public const int dialog_disclosure = 2130837504; - - // aapt resource value: 0x7f020001 - public const int dialog_expander_ic_minimized = 2130837505; - - // aapt resource value: 0x7f020002 - public const int Icon = 2130837506; - - static Drawable() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Drawable() - { - } - } - - public partial class Id - { - - // aapt resource value: 0x7f04000f - public const int EditTextLayout = 2130968591; - - // aapt resource value: 0x7f04000d - public const int GameMainLayout = 2130968589; - - // aapt resource value: 0x7f04000e - public const int GameViewLayout = 2130968590; - - // aapt resource value: 0x7f040011 - public const int OptionHostName = 2130968593; - - // aapt resource value: 0x7f040012 - public const int OptionPort = 2130968594; - - // aapt resource value: 0x7f040010 - public const int OptionRemoteServer = 2130968592; - - // aapt resource value: 0x7f040020 - public const int OptionsButton = 2130968608; - - // aapt resource value: 0x7f04001b - public const int ResultFullName = 2130968603; - - // aapt resource value: 0x7f04001d - public const int ResultMessage = 2130968605; - - // aapt resource value: 0x7f04001c - public const int ResultResultState = 2130968604; - - // aapt resource value: 0x7f04001a - public const int ResultRunSingleMethodTest = 2130968602; - - // aapt resource value: 0x7f04001e - public const int ResultStackTrace = 2130968606; - - // aapt resource value: 0x7f040016 - public const int ResultsFailed = 2130968598; - - // aapt resource value: 0x7f040013 - public const int ResultsId = 2130968595; - - // aapt resource value: 0x7f040017 - public const int ResultsIgnored = 2130968599; - - // aapt resource value: 0x7f040018 - public const int ResultsInconclusive = 2130968600; - - // aapt resource value: 0x7f040019 - public const int ResultsMessage = 2130968601; - - // aapt resource value: 0x7f040015 - public const int ResultsPassed = 2130968597; - - // aapt resource value: 0x7f040014 - public const int ResultsResult = 2130968596; - - // aapt resource value: 0x7f04001f - public const int RunTestsButton = 2130968607; - - // aapt resource value: 0x7f040021 - public const int TestSuiteListView = 2130968609; - - // aapt resource value: 0x7f040002 - public const int dialog_BoolField = 2130968578; - - // aapt resource value: 0x7f040003 - public const int dialog_Button = 2130968579; - - // aapt resource value: 0x7f040009 - public const int dialog_DisclosureField = 2130968585; - - // aapt resource value: 0x7f040005 - public const int dialog_ImageLeft = 2130968581; - - // aapt resource value: 0x7f040007 - public const int dialog_ImageRight = 2130968583; - - // aapt resource value: 0x7f040000 - public const int dialog_LabelField = 2130968576; - - // aapt resource value: 0x7f040001 - public const int dialog_LabelSubtextField = 2130968577; - - // aapt resource value: 0x7f040008 - public const int dialog_Panel = 2130968584; - - // aapt resource value: 0x7f04000a - public const int dialog_RadioButtonList = 2130968586; - - // aapt resource value: 0x7f040006 - public const int dialog_SliderField = 2130968582; - - // aapt resource value: 0x7f04000b - public const int dialog_Spinner = 2130968587; - - // aapt resource value: 0x7f040004 - public const int dialog_ValueField = 2130968580; - - // aapt resource value: 0x7f04000c - public const int iFormFieldValue = 2130968588; - - static Id() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Id() - { - } - } - - public partial class Layout - { - - // aapt resource value: 0x7f030000 - public const int dialog_achievements = 2130903040; - - // aapt resource value: 0x7f030001 - public const int dialog_boolfieldleft = 2130903041; - - // aapt resource value: 0x7f030002 - public const int dialog_boolfieldright = 2130903042; - - // aapt resource value: 0x7f030003 - public const int dialog_boolfieldsubleft = 2130903043; - - // aapt resource value: 0x7f030004 - public const int dialog_boolfieldsubright = 2130903044; - - // aapt resource value: 0x7f030005 - public const int dialog_button = 2130903045; - - // aapt resource value: 0x7f030006 - public const int dialog_datefield = 2130903046; - - // aapt resource value: 0x7f030007 - public const int dialog_fieldsetlabel = 2130903047; - - // aapt resource value: 0x7f030008 - public const int dialog_floatimage = 2130903048; - - // aapt resource value: 0x7f030009 - public const int dialog_labelfieldbelow = 2130903049; - - // aapt resource value: 0x7f03000a - public const int dialog_labelfieldright = 2130903050; - - // aapt resource value: 0x7f03000b - public const int dialog_onofffieldright = 2130903051; - - // aapt resource value: 0x7f03000c - public const int dialog_panel = 2130903052; - - // aapt resource value: 0x7f03000d - public const int dialog_root = 2130903053; - - // aapt resource value: 0x7f03000e - public const int dialog_selectlist = 2130903054; - - // aapt resource value: 0x7f03000f - public const int dialog_selectlistfield = 2130903055; - - // aapt resource value: 0x7f030010 - public const int dialog_textarea = 2130903056; - - // aapt resource value: 0x7f030011 - public const int dialog_textfieldbelow = 2130903057; - - // aapt resource value: 0x7f030012 - public const int dialog_textfieldright = 2130903058; - - // aapt resource value: 0x7f030013 - public const int Game = 2130903059; - - // aapt resource value: 0x7f030014 - public const int options = 2130903060; - - // aapt resource value: 0x7f030015 - public const int results = 2130903061; - - // aapt resource value: 0x7f030016 - public const int test_result = 2130903062; - - // aapt resource value: 0x7f030017 - public const int test_suite = 2130903063; - - static Layout() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Layout() - { - } - } - } -} -#pragma warning restore 1591 diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Android.csproj b/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Android.csproj deleted file mode 100644 index a496b5f3b1..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Android.csproj +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - Debug - AnyCPU - {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7} - {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - PackageReference - Properties - Xenko.Graphics.Tests - Xenko.Graphics.Tests.11_0 - v8.1 - 512 - true - Resources\Resource.Designer.cs - - Properties\AndroidManifest.xml - armeabi,armeabi-v7a,x86 - - - - - true - obj\ - Android - Android - {04ed1618-1a06-4a69-ac34-1006a978af11} - true - OpenGLES - Tests\$(XenkoGraphicsApi)\$(AssemblyName) - - true - true - - - $(MSBuildThisFileDirectory)Xenko.Graphics.Tests.11_0.xkpkg - ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) - $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID;XENKO_GRAPHICS_API_OPENGL;XENKO_GRAPHICS_API_OPENGLES - prompt - 4 - True - None - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID;XENKO_GRAPHICS_API_OPENGL;XENKO_GRAPHICS_API_OPENGLES - prompt - 4 - False - SdkOnly - - - - - - - - - - - NUnitLiteLauncher.Android.cs - - - - - - - - ComputeShaderTestEffect.xkfx - True - True - True - - - HammersleyTest.xksl - True - True - True - - - True - True - True - ComputeShaderTest.xksl - - - True - True - True - CubemapSprite.xksl - - - - - - - - - XenkoShaderKeyGenerator - ComputeShaderTestEffect.cs - - - XenkoShaderKeyGenerator - HammersleyTest.cs - - - XenkoShaderKeyGenerator - ComputeShaderTest.cs - - - XenkoShaderKeyGenerator - CubemapSprite.cs - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Windows.csproj b/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Windows.csproj index bc9ea9fb35..d06f4e8d95 100644 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Windows.csproj +++ b/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.Windows.csproj @@ -7,7 +7,6 @@ Xenko.Graphics.Tests.11_0 net461 false - false * Windows Windows @@ -28,65 +27,19 @@ Xenko.Graphics.Tests.TestRadiancePrefilteringGgx - - + + + - - + + - - - ComputeShaderTestEffect.xkfx - True - True - True - - - HammersleyTest.xksl - True - True - True - - - True - True - True - ComputeShaderTest.xksl - - - True - True - True - CubemapSprite.xksl - - - - - - - - - XenkoShaderKeyGenerator - ComputeShaderTestEffect.cs - - - XenkoShaderKeyGenerator - HammersleyTest.cs - - - XenkoShaderKeyGenerator - ComputeShaderTest.cs - - - XenkoShaderKeyGenerator - CubemapSprite.cs - - + - + diff --git a/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.iOS.csproj b/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.iOS.csproj deleted file mode 100644 index 178a7c9672..0000000000 --- a/sources/engine/Xenko.Graphics.Tests.11_0/Xenko.Graphics.Tests.11_0.iOS.csproj +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - - Debug - AnyCPU - {7CA99C7B-E3A2-4DE6-9D6C-314AE39BBBB7} - {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Exe - PackageReference - Properties - Resources - Xenko.Graphics.Tests - XenkoGraphicsTests110 - obj\ - iOS - iOS - {04ed1618-1a06-4a69-ac34-1006a978af11} - true - OpenGLES - Tests\$(XenkoGraphicsApi)\$(AssemblyName) - - true - true - - - $(MSBuildThisFileDirectory)Xenko.Graphics.Tests.11_0.xkpkg - ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) - $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - True - iPhone Developer - True - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - iPhone Developer - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - True - iPhone Distribution - True - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - iPhone Distribution - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - OpenGLES - ..\..\..\Bin\iOS-OpenGLES\ - obj\iOS\Debug\ - prompt - 4 - None - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - None - - - Xenko.Core.Tests.Application - - - - - - - - - NUnitLiteLauncher.iPhone.cs - - - - - - - - ComputeShaderTestEffect.xkfx - True - True - True - - - HammersleyTest.xksl - True - True - True - - - True - True - True - ComputeShaderTest.xksl - - - True - True - True - CubemapSprite.xksl - - - - - - - - - XenkoShaderKeyGenerator - ComputeShaderTestEffect.cs - - - XenkoShaderKeyGenerator - HammersleyTest.cs - - - XenkoShaderKeyGenerator - ComputeShaderTest.cs - - - XenkoShaderKeyGenerator - CubemapSprite.cs - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests/ActivityAndroid.cs b/sources/engine/Xenko.Graphics.Tests/ActivityAndroid.cs deleted file mode 100644 index 68a44e1917..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/ActivityAndroid.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Runtime.CompilerServices; -using Android.App; -using Android.OS; -using Xenko.Effects; -using Xenko.Starter; - -namespace Xenko.Graphics.Tests -{ - [Activity(Label = "Xenko Graphics", MainLauncher = true, Icon = "@drawable/icon")] - public class ActivityAndroid : AndroidXenkoActivity - { - protected override void OnCreate(Bundle bundle) - { - RuntimeHelpers.RunModuleConstructor(typeof(MaterialKeys).Module.ModuleHandle); - - base.OnCreate(bundle); - - //Game = new TestDrawQuad(); - //Game = new TestGeometricPrimitives(); - //Game = new TestRenderToTexture(); - //Game = new TestSpriteBatch(); - //Game = new TestImageLoad(); - //Game = new TestStaticSpriteFont(); - //Game = new TestDynamicSpriteFont(); - //Game = new TestDynamicSpriteFontJapanese(); - Game = new TestDynamicSpriteFontVarious(); - - Game.Run(GameContext); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests/Application.iOS.cs b/sources/engine/Xenko.Graphics.Tests/Application.iOS.cs deleted file mode 100644 index 4e86a91fad..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Application.iOS.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using MonoTouch.Foundation; -using MonoTouch.UIKit; -using Xenko.Starter; - -namespace Xenko.Graphics.Tests -{ - public class ManualApplication - { - static void Main(string[] args) - { - UIApplication.Main(args, null, "ManualAppDelegate"); - } - } - - [Register("ManualAppDelegate")] - public class ManualAppDelegate : XenkoApplicationDelegate - { - public override bool FinishedLaunching(UIApplication app, NSDictionary options) - { - //Game = new TestImageLoad(); - //Game = new TestStaticSpriteFont(); - //Game = new TestDynamicSpriteFont(); - //Game = new TestDynamicSpriteFontJapanese(); - Game = new TestDynamicSpriteFontVarious(); - - return base.FinishedLaunching(app, options); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx b/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx index 39fb03c53a..14c756fc80 100644 --- a/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx +++ b/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx @@ -1,8 +1,5 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using Xenko.Effects.Data; -using Xenko.Effects; - namespace Test { effect CubemapDisplayEffect diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx.cs similarity index 99% rename from sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx.cs index 68fb6224ae..c9a89f0fdb 100644 --- a/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.cs +++ b/sources/engine/Xenko.Graphics.Tests/Compiler/CubemapEffect.xkfx.cs @@ -14,8 +14,6 @@ using Xenko.Core.Mathematics; using Buffer = Xenko.Graphics.Buffer; -using Xenko.Effects.Data; -using Xenko.Effects; namespace Test { internal static partial class ShaderMixins diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/CustomEffect.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/CustomEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/CustomEffect.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/CustomEffect.xkfx.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/CustomShader.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/CustomShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/CustomShader.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/CustomShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteEffect.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteEffect.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteEffect.xkfx.cs diff --git a/sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffectShader.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests.10_0/Assets/MultipleRenderTargetsEffectShader.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/SimpleEffect.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/SimpleEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/SimpleEffect.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/SimpleEffect.xkfx.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/SimpleShader.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/SimpleShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/SimpleShader.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/SimpleShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslEffect.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslEffect.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslEffect.xkfx.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslShader.cs b/sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslShader.cs rename to sources/engine/Xenko.Graphics.Tests/Compiler/ToGlslShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics.Tests/Properties/AndroidManifest.xml b/sources/engine/Xenko.Graphics.Tests/Properties/AndroidManifest.xml deleted file mode 100644 index c09468d1fe..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Properties/AndroidManifest.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.Android.cs b/sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.Android.cs deleted file mode 100644 index 27a54ef326..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.Android.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using Android.App; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Graphics")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Xenko.Graphics")] -[assembly: AssemblyCopyright("Copyright © 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("1ebcac74-0858-4b96-8979-f0ac6db3c2e7")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - -// Add some common permissions, these can be removed if not needed -[assembly: UsesPermission(Android.Manifest.Permission.Internet)] -[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)] diff --git a/sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.cs b/sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 8094c50b3e..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Graphics.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("Xenko.Graphics.Tests")] -[assembly: AssemblyCopyright("Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sources/engine/Xenko.Graphics.Tests/Resources/Drawable/icon.png b/sources/engine/Xenko.Graphics.Tests/Resources/Drawable/icon.png deleted file mode 100644 index d68a524f7d..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Resources/Drawable/icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c51544282fca0d3f04dead09d63f6b383055c10b4bee2578f19253880aa47dd9 -size 15950 diff --git a/sources/engine/Xenko.Graphics.Tests/Resources/Icon-60@2x.png b/sources/engine/Xenko.Graphics.Tests/Resources/Icon-60@2x.png deleted file mode 100644 index f8a4b181af..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Resources/Icon-60@2x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e0d5fcd3786c0ff6a274d767ed7d6a6281989d422ba9c2abc543f77b0d0605ac -size 14005 diff --git a/sources/engine/Xenko.Graphics.Tests/Resources/Icon.png b/sources/engine/Xenko.Graphics.Tests/Resources/Icon.png deleted file mode 100644 index 7a12e35579..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Resources/Icon.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c669dbc80ab0f766aa49dd3f4cd5fa2d59f3c90de728630e7052013b20442cd2 -size 5451 diff --git a/sources/engine/Xenko.Graphics.Tests/Resources/Icon@2x.png b/sources/engine/Xenko.Graphics.Tests/Resources/Icon@2x.png deleted file mode 100644 index 828dd63a8f..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Resources/Icon@2x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:81c3034b0ecc3c5baa665b20f36bbd016f1b6c20135be38a5f16bc0688b9fde4 -size 13031 diff --git a/sources/engine/Xenko.Graphics.Tests/Resources/Resource.Designer.cs b/sources/engine/Xenko.Graphics.Tests/Resources/Resource.Designer.cs deleted file mode 100644 index e0641c3dc5..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Resources/Resource.Designer.cs +++ /dev/null @@ -1,293 +0,0 @@ -#pragma warning disable 1591 -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -[assembly: global::Android.Runtime.ResourceDesignerAttribute("Xenko.Graphics.Tests.Resource", IsApplication=true)] - -namespace Xenko.Graphics.Tests -{ - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] - public partial class Resource - { - - static Resource() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - public static void UpdateIdValues() - { - global::Xenko.Resource.Id.EditTextLayout = global::Xenko.Graphics.Tests.Resource.Id.EditTextLayout; - global::Xenko.Resource.Id.GameMainLayout = global::Xenko.Graphics.Tests.Resource.Id.GameMainLayout; - global::Xenko.Resource.Id.GameViewLayout = global::Xenko.Graphics.Tests.Resource.Id.GameViewLayout; - global::Xenko.Resource.Layout.Game = global::Xenko.Graphics.Tests.Resource.Layout.Game; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionHostName = global::Xenko.Graphics.Tests.Resource.Id.OptionHostName; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionPort = global::Xenko.Graphics.Tests.Resource.Id.OptionPort; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionRemoteServer = global::Xenko.Graphics.Tests.Resource.Id.OptionRemoteServer; - global::Xamarin.Android.NUnitLite.Resource.Id.OptionsButton = global::Xenko.Graphics.Tests.Resource.Id.OptionsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultFullName = global::Xenko.Graphics.Tests.Resource.Id.ResultFullName; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultMessage = global::Xenko.Graphics.Tests.Resource.Id.ResultMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultResultState = global::Xenko.Graphics.Tests.Resource.Id.ResultResultState; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultRunSingleMethodTest = global::Xenko.Graphics.Tests.Resource.Id.ResultRunSingleMethodTest; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultStackTrace = global::Xenko.Graphics.Tests.Resource.Id.ResultStackTrace; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsFailed = global::Xenko.Graphics.Tests.Resource.Id.ResultsFailed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsId = global::Xenko.Graphics.Tests.Resource.Id.ResultsId; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsIgnored = global::Xenko.Graphics.Tests.Resource.Id.ResultsIgnored; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsInconclusive = global::Xenko.Graphics.Tests.Resource.Id.ResultsInconclusive; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsMessage = global::Xenko.Graphics.Tests.Resource.Id.ResultsMessage; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsPassed = global::Xenko.Graphics.Tests.Resource.Id.ResultsPassed; - global::Xamarin.Android.NUnitLite.Resource.Id.ResultsResult = global::Xenko.Graphics.Tests.Resource.Id.ResultsResult; - global::Xamarin.Android.NUnitLite.Resource.Id.RunTestsButton = global::Xenko.Graphics.Tests.Resource.Id.RunTestsButton; - global::Xamarin.Android.NUnitLite.Resource.Id.TestSuiteListView = global::Xenko.Graphics.Tests.Resource.Id.TestSuiteListView; - global::Xamarin.Android.NUnitLite.Resource.Layout.options = global::Xenko.Graphics.Tests.Resource.Layout.options; - global::Xamarin.Android.NUnitLite.Resource.Layout.results = global::Xenko.Graphics.Tests.Resource.Layout.results; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_result = global::Xenko.Graphics.Tests.Resource.Layout.test_result; - global::Xamarin.Android.NUnitLite.Resource.Layout.test_suite = global::Xenko.Graphics.Tests.Resource.Layout.test_suite; - } - - public partial class Attribute - { - - static Attribute() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Attribute() - { - } - } - - public partial class Drawable - { - - // aapt resource value: 0x7f020000 - public const int dialog_disclosure = 2130837504; - - // aapt resource value: 0x7f020001 - public const int dialog_expander_ic_minimized = 2130837505; - - // aapt resource value: 0x7f020002 - public const int Icon = 2130837506; - - static Drawable() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Drawable() - { - } - } - - public partial class Id - { - - // aapt resource value: 0x7f04000f - public const int EditTextLayout = 2130968591; - - // aapt resource value: 0x7f04000d - public const int GameMainLayout = 2130968589; - - // aapt resource value: 0x7f04000e - public const int GameViewLayout = 2130968590; - - // aapt resource value: 0x7f040011 - public const int OptionHostName = 2130968593; - - // aapt resource value: 0x7f040012 - public const int OptionPort = 2130968594; - - // aapt resource value: 0x7f040010 - public const int OptionRemoteServer = 2130968592; - - // aapt resource value: 0x7f040020 - public const int OptionsButton = 2130968608; - - // aapt resource value: 0x7f04001b - public const int ResultFullName = 2130968603; - - // aapt resource value: 0x7f04001d - public const int ResultMessage = 2130968605; - - // aapt resource value: 0x7f04001c - public const int ResultResultState = 2130968604; - - // aapt resource value: 0x7f04001a - public const int ResultRunSingleMethodTest = 2130968602; - - // aapt resource value: 0x7f04001e - public const int ResultStackTrace = 2130968606; - - // aapt resource value: 0x7f040016 - public const int ResultsFailed = 2130968598; - - // aapt resource value: 0x7f040013 - public const int ResultsId = 2130968595; - - // aapt resource value: 0x7f040017 - public const int ResultsIgnored = 2130968599; - - // aapt resource value: 0x7f040018 - public const int ResultsInconclusive = 2130968600; - - // aapt resource value: 0x7f040019 - public const int ResultsMessage = 2130968601; - - // aapt resource value: 0x7f040015 - public const int ResultsPassed = 2130968597; - - // aapt resource value: 0x7f040014 - public const int ResultsResult = 2130968596; - - // aapt resource value: 0x7f04001f - public const int RunTestsButton = 2130968607; - - // aapt resource value: 0x7f040021 - public const int TestSuiteListView = 2130968609; - - // aapt resource value: 0x7f040002 - public const int dialog_BoolField = 2130968578; - - // aapt resource value: 0x7f040003 - public const int dialog_Button = 2130968579; - - // aapt resource value: 0x7f040009 - public const int dialog_DisclosureField = 2130968585; - - // aapt resource value: 0x7f040005 - public const int dialog_ImageLeft = 2130968581; - - // aapt resource value: 0x7f040007 - public const int dialog_ImageRight = 2130968583; - - // aapt resource value: 0x7f040000 - public const int dialog_LabelField = 2130968576; - - // aapt resource value: 0x7f040001 - public const int dialog_LabelSubtextField = 2130968577; - - // aapt resource value: 0x7f040008 - public const int dialog_Panel = 2130968584; - - // aapt resource value: 0x7f04000a - public const int dialog_RadioButtonList = 2130968586; - - // aapt resource value: 0x7f040006 - public const int dialog_SliderField = 2130968582; - - // aapt resource value: 0x7f04000b - public const int dialog_Spinner = 2130968587; - - // aapt resource value: 0x7f040004 - public const int dialog_ValueField = 2130968580; - - // aapt resource value: 0x7f04000c - public const int iFormFieldValue = 2130968588; - - static Id() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Id() - { - } - } - - public partial class Layout - { - - // aapt resource value: 0x7f030000 - public const int dialog_achievements = 2130903040; - - // aapt resource value: 0x7f030001 - public const int dialog_boolfieldleft = 2130903041; - - // aapt resource value: 0x7f030002 - public const int dialog_boolfieldright = 2130903042; - - // aapt resource value: 0x7f030003 - public const int dialog_boolfieldsubleft = 2130903043; - - // aapt resource value: 0x7f030004 - public const int dialog_boolfieldsubright = 2130903044; - - // aapt resource value: 0x7f030005 - public const int dialog_button = 2130903045; - - // aapt resource value: 0x7f030006 - public const int dialog_datefield = 2130903046; - - // aapt resource value: 0x7f030007 - public const int dialog_fieldsetlabel = 2130903047; - - // aapt resource value: 0x7f030008 - public const int dialog_floatimage = 2130903048; - - // aapt resource value: 0x7f030009 - public const int dialog_labelfieldbelow = 2130903049; - - // aapt resource value: 0x7f03000a - public const int dialog_labelfieldright = 2130903050; - - // aapt resource value: 0x7f03000b - public const int dialog_onofffieldright = 2130903051; - - // aapt resource value: 0x7f03000c - public const int dialog_panel = 2130903052; - - // aapt resource value: 0x7f03000d - public const int dialog_root = 2130903053; - - // aapt resource value: 0x7f03000e - public const int dialog_selectlist = 2130903054; - - // aapt resource value: 0x7f03000f - public const int dialog_selectlistfield = 2130903055; - - // aapt resource value: 0x7f030010 - public const int dialog_textarea = 2130903056; - - // aapt resource value: 0x7f030011 - public const int dialog_textfieldbelow = 2130903057; - - // aapt resource value: 0x7f030012 - public const int dialog_textfieldright = 2130903058; - - // aapt resource value: 0x7f030013 - public const int Game = 2130903059; - - // aapt resource value: 0x7f030014 - public const int options = 2130903060; - - // aapt resource value: 0x7f030015 - public const int results = 2130903061; - - // aapt resource value: 0x7f030016 - public const int test_result = 2130903062; - - // aapt resource value: 0x7f030017 - public const int test_suite = 2130903063; - - static Layout() - { - global::Android.Runtime.ResourceIdManager.UpdateIdValues(); - } - - private Layout() - { - } - } - } -} -#pragma warning restore 1591 diff --git a/sources/engine/Xenko.Graphics.Tests/TestCubemapDeferred.cs b/sources/engine/Xenko.Graphics.Tests/TestCubemapDeferred.cs deleted file mode 100644 index 82a703ca18..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/TestCubemapDeferred.cs +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Threading.Tasks; - -using Xunit; - -using Xenko.Core.Mathematics; -using Xenko.Effects; -using Xenko.Effects.Cubemap; -using Xenko.Effects.Renderers; -using Xenko.Engine; -using Xenko.EntityModel; -using Xenko.Extensions; - -namespace Xenko.Graphics.Tests -{ - public class TestCubemapDeferred : TestGameBase - { - private LightingIBLRenderer IBLRenderer; - - private Entity teapotEntity; - - private Entity dynamicCubemapEntity; - - public TestCubemapDeferred() - { - GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_11_0 }; - } - - protected override async Task LoadContent() - { - await base.LoadContent(); - - // create pipeline - CreatePipeline(); - - // setup the scene - var material = Asset.Load("BasicMaterial"); - teapotEntity = new Entity() - { - new ModelComponent() - { - Model = new Model() - { - material, - new Mesh() - { - Draw = GeometricPrimitive.Teapot.New(GraphicsDevice).ToMeshDraw(), - MaterialIndex = 0, - } - } - } - }; - Entities.Add(teapotEntity); - - var textureCube = Asset.Load("uv_cube"); - var staticCubemapEntity = new Entity() - { - new CubemapSourceComponent(textureCube) { InfluenceRadius = 2f, IsDynamic = false }, - new TransformationComponent() { Translation = Vector3.UnitZ } - }; - Entities.Add(staticCubemapEntity); - - dynamicCubemapEntity = new Entity() - { - new CubemapSourceComponent(textureCube) { InfluenceRadius = 0.5f, IsDynamic = false }, - new TransformationComponent() { Translation = Vector3.Zero } - }; - Entities.Add(dynamicCubemapEntity); - - var mainCamera = new Entity() - { - new CameraComponent - { - AspectRatio = 8/4.8f, - FarPlane = 20, - NearPlane = 1, - VerticalFieldOfView = 0.6f, - Target = teapotEntity, - TargetUp = Vector3.UnitY, - }, - new TransformationComponent - { - Translation = new Vector3(4, 3, 0) - } - }; - Entities.Add(mainCamera); - - RenderSystem.Pipeline.SetCamera(mainCamera.Get()); - - Script.Add(GameScript1); - } - - private void CreatePipeline() - { - // Processor - Entities.Processors.Add(new CubemapSourceProcessor(GraphicsDevice)); - - // Rendering pipeline - RenderSystem.Pipeline.Renderers.Add(new CameraSetter(Services)); - - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) - { - ClearColor = Color.CornflowerBlue, - EnableClearDepth = true, - ClearDepth = 1f - }); - - // Create G-buffer pass - var gbufferPipeline = new RenderPipeline("GBuffer"); - // Renders the G-buffer for opaque geometry. - gbufferPipeline.Renderers.Add(new ModelRenderer(Services, "CubemapIBLEffect.XenkoGBufferShaderPass")); - var gbufferProcessor = new GBufferRenderProcessor(Services, gbufferPipeline, GraphicsDevice.DepthStencilBuffer, false); - - // Add sthe G-buffer pass to the pipeline. - RenderSystem.Pipeline.Renderers.Add(gbufferProcessor); - - var readOnlyDepthBuffer = GraphicsDevice.DepthStencilBuffer; // TODO ToDepthStencilBuffer(true); - IBLRenderer = new LightingIBLRenderer(Services, "CubemapIBLSpecular", readOnlyDepthBuffer); - RenderSystem.Pipeline.Renderers.Add(IBLRenderer); - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) - { - ClearColor = Color.CornflowerBlue, - EnableClearDepth = false, - }); - RenderSystem.Pipeline.Renderers.Add(new DelegateRenderer(Services) { Render = ShowIBL }); - } - - private void ShowIBL(RenderContext context) - { - GraphicsDevice.DrawTexture(IBLRenderer.IBLTexture); - } - - private async Task GameScript1() - { - while (IsRunning) - { - // Wait next rendering frame - await Script.NextFrame(); - - teapotEntity.Transform.Rotation = Quaternion.RotationY((float)(2 * Math.PI * UpdateTime.Total.TotalMilliseconds / 5000.0f)); - dynamicCubemapEntity.Transform.Translation = new Vector3(2f * (float)Math.Sin(2 * Math.PI * UpdateTime.Total.TotalMilliseconds / 15000.0f), 0, 0); - } - } - - public static void Main() - { - using (var game = new TestCubemapDeferred()) - game.Run(); - } - - /// - /// Run the test - /// - [Fact] - public void RunCubemapRendering() - { - RunGameTest(new TestCubemapDeferred()); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests/TestCubemapDisplay.cs b/sources/engine/Xenko.Graphics.Tests/TestCubemapDisplay.cs deleted file mode 100644 index 0f3b5934fd..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/TestCubemapDisplay.cs +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Threading.Tasks; - -using Xunit; - -using Xenko.Core.Mathematics; -using Xenko.Effects; -using Xenko.Engine; -using Xenko.EntityModel; -using Xenko.Extensions; - -namespace Xenko.Graphics.Tests -{ - public class TestCubemapDisplay : TestGameBase - { - private Entity mainCamera; - private float cameraDistance = 3; - private float cameraHeight = 3; - private Vector3 cameraUp = Vector3.UnitY; - - public TestCubemapDisplay() - { - GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_9_1 }; - } - - protected override async Task LoadContent() - { - await base.LoadContent(); - - CreatePipeline(); - - var material = Asset.Load("BasicMaterial"); - var textureCube = Asset.Load("uv_cube"); - material.Parameters.Set(TexturingKeys.TextureCube0, textureCube); - var mesh = new Mesh() - { - Draw = GeometricPrimitive.GeoSphere.New(GraphicsDevice).ToMeshDraw(), - Material = material - }; - mesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group1); - - var entity = new Entity() - { - new ModelComponent() - { - Model = new Model() { mesh } - }, - new TransformationComponent() - }; - - Entities.Add(entity); - - var mainCameraTargetEntity = new Entity(Vector3.Zero); - Entities.Add(mainCameraTargetEntity); - mainCamera = new Entity() - { - new CameraComponent - { - AspectRatio = 8/4.8f, - FarPlane = 1000, - NearPlane = 1, - VerticalFieldOfView = 0.6f, - Target = mainCameraTargetEntity, - TargetUp = cameraUp, - }, - new TransformationComponent - { - Translation = cameraDistance * Vector3.UnitX - } - }; - Entities.Add(mainCamera); - - RenderSystem.Pipeline.SetCamera(mainCamera.Get()); - - // Add a custom script - Script.Add(GameScript1); - } - - private void CreatePipeline() - { - RenderSystem.Pipeline.Renderers.Add(new CameraSetter(Services)); - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) { ClearColor = Color.CornflowerBlue }); - RenderSystem.Pipeline.Renderers.Add(new ModelRenderer(Services, "CubemapDisplayEffect")); - } - - private async Task GameScript1() - { - while (IsRunning) - { - // Wait next rendering frame - await Script.NextFrame(); - - var angle = Math.PI * UpdateTime.Total.TotalMilliseconds / 5000; - mainCamera.Transform.Translation = new Vector3((float)(cameraDistance * Math.Cos(angle)), cameraHeight, (float)(cameraDistance * Math.Sin(angle))); - } - } - - public static void Main() - { - using (var game = new TestCubemapDisplay()) - game.Run(); - } - - /// - /// Run the test - /// - [Fact] - public void RunCubemapRendering() - { - RunGameTest(new TestCubemapDisplay()); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests/TestCubemapRendering.cs b/sources/engine/Xenko.Graphics.Tests/TestCubemapRendering.cs deleted file mode 100644 index b10141aa81..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/TestCubemapRendering.cs +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Xunit; -using Xenko.Core.Mathematics; -using Xenko.Effects; -using Xenko.Effects.Cubemap; -using Xenko.Engine; -using Xenko.EntityModel; -using Xenko.Extensions; -using Xenko.Input; - -namespace Xenko.Graphics.Tests -{ - public class TestCubemapRendering : TestGameBase - { - private Entity mainCamera; - private Vector3 cameraInitPos = new Vector3(10, 0, 0); - private Vector3 cameraUp = Vector3.UnitY; - private Entity[] primitiveEntities; - private Vector3[] rotationAxis; - - public TestCubemapRendering() - { - // cannot render cubemap in level below 10.1 - GraphicsDeviceManager.PreferredGraphicsProfile = new[] { GraphicsProfile.Level_11_0 }; - } - - protected override async Task LoadContent() - { - await base.LoadContent(); - - CreatePipeline(true); - - IsMouseVisible = true; - - //Input.ActivatedGestures.Add(new GestureConfigDrag()); - - // Creates all primitives - // type pos axis - var primitives = new List> - { - Tuple.Create(GeometricPrimitive.Cube.New(GraphicsDevice), 2 * Vector3.UnitX, new Vector3(1,1,1)), - Tuple.Create(GeometricPrimitive.Teapot.New(GraphicsDevice), -2 * Vector3.UnitX, new Vector3(-1,1,1)), - Tuple.Create(GeometricPrimitive.GeoSphere.New(GraphicsDevice), 2 * Vector3.UnitY, new Vector3(1,0,1)), - Tuple.Create(GeometricPrimitive.Cylinder.New(GraphicsDevice), -2 * Vector3.UnitY, new Vector3(-1,-1,1)), - Tuple.Create(GeometricPrimitive.Torus.New(GraphicsDevice), 2 * Vector3.UnitZ, new Vector3(1,-1,1)), - Tuple.Create(GeometricPrimitive.Sphere.New(GraphicsDevice), -2 * Vector3.UnitZ, new Vector3(0,1,1)), - }; - - primitiveEntities = new Entity[primitives.Count]; - rotationAxis = new Vector3[primitives.Count]; - var material = Asset.Load("BasicMaterial"); - for (var i =0; i < primitives.Count; ++i) - { - var mesh = new Mesh - { - Draw = primitives[i].Item1.ToMeshDraw(), - MaterialIndex = 0, - }; - mesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group1); - - var entity = new Entity - { - new ModelComponent - { - Model = new Model { mesh, material } - }, - new TransformationComponent { Translation = primitives[i].Item2 } - }; - Entities.Add(entity); - primitiveEntities[i] = entity; - rotationAxis[i] = primitives[i].Item3; - } - - var reflectivePrimitive = GeometricPrimitive.Sphere.New(GraphicsDevice); - var reflectiveMesh = new Mesh - { - Draw = reflectivePrimitive.ToMeshDraw(), - }; - reflectiveMesh.Parameters.Set(RenderingParameters.RenderGroup, RenderGroups.Group2); - - var reflectEntity = new Entity - { - new ModelComponent - { - Model = new Model { reflectiveMesh } - }, - new TransformationComponent(), - new CubemapSourceComponent { IsDynamic = true, Size = 128 } - }; - Entities.Add(reflectEntity); - reflectEntity.Get().Parameters.Set(TexturingKeys.TextureCube0, reflectEntity.Get().Texture); - - var mainCameraTargetEntity = new Entity(Vector3.Zero); - Entities.Add(mainCameraTargetEntity); - mainCamera = new Entity - { - new CameraComponent - { - AspectRatio = 8/4.8f, - FarPlane = 1000, - NearPlane = 1, - VerticalFieldOfView = 0.6f, - Target = mainCameraTargetEntity, - TargetUp = cameraUp, - }, - new TransformationComponent - { - Translation = cameraInitPos - } - }; - Entities.Add(mainCamera); - - RenderSystem.Pipeline.SetCamera(mainCamera.Get()); - - // Add a custom script - Script.Add(GameScript1); - } - - private void CreatePipeline(bool renderInOnePass) - { - // Processor - Entities.Processors.Add(new CubemapSourceProcessor(GraphicsDevice)); - - // Rendering pipeline - var cubeMapPipeline = new RenderPipeline("CubeMap"); - cubeMapPipeline.Renderers.Add(new ModelRenderer(Services, renderInOnePass ? "CubemapGeomEffect" : "CubemapEffect").AddLayerFilter(RenderGroups.Group1)); - RenderSystem.Pipeline.Renderers.Add(new CubemapRenderer(Services, cubeMapPipeline, renderInOnePass)); - RenderSystem.Pipeline.Renderers.Add(new CameraSetter(Services)); - RenderSystem.Pipeline.Renderers.Add(new RenderTargetSetter(Services) { ClearColor = Color.CornflowerBlue }); - RenderSystem.Pipeline.Renderers.Add(new ModelRenderer(Services, "CubemapEffect")); - } - - private async Task GameScript1() - { - var dragValue = Vector2.Zero; - var rotationFactor = 0.125f; - var rotationUpFactor = 0.1f; - var rotate = true; - while (IsRunning) - { - // Wait next rendering frame - await Script.NextFrame(); - - if (Input.IsKeyPressed(Keys.Space)) - rotate = !rotate; - - if (rotate) - { - var rotationPrim = (float) (2*Math.PI*UpdateTime.Total.TotalMilliseconds/15000); - for (var i = 0; i < primitiveEntities.Length; ++i) - { - primitiveEntities[i].Transform.Rotation = Quaternion.RotationAxis(rotationAxis[i], rotationPrim); - } - } - - // rotate camera - dragValue = 0.95f * dragValue; - if (Input.PointerEvents.Count > 0) - { - dragValue = Input.PointerEvents.Aggregate(Vector2.Zero, (t, x) => x.DeltaPosition + t); - } - rotationFactor -= dragValue.X; - rotationUpFactor += dragValue.Y; - if (rotationUpFactor > 0.45f) - rotationUpFactor = 0.45f; - else if (rotationUpFactor < -0.45f) - rotationUpFactor = -0.45f; - mainCamera.Transform.Translation = Vector3.Transform(cameraInitPos, Quaternion.RotationZ((float)(Math.PI * rotationUpFactor)) * Quaternion.RotationY((float)(2 * Math.PI * rotationFactor))); - } - } - - public static void Main() - { - using (var game = new TestCubemapRendering()) - game.Run(); - } - - /// - /// Run the test - /// - [Fact] - public void RunCubemapRendering() - { - RunGameTest(new TestCubemapRendering()); - } - } -} diff --git a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Android.csproj b/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Android.csproj deleted file mode 100644 index a9485e8188..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Android.csproj +++ /dev/null @@ -1,219 +0,0 @@ - - - - - - - Debug - AnyCPU - {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC} - {EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Library - PackageReference - v8.1 - 512 - true - Resources\Resource.Designer.cs - - Properties\AndroidManifest.xml - armeabi,armeabi-v7a,x86 - - - - - Xenko.Graphics.Tests - Properties - Xenko.Graphics.Tests - obj\ - $(XenkoPlatform) - true - OpenGLES - Tests\$(XenkoGraphicsApi)\$(AssemblyName) - - true - true - - - $(MSBuildThisFileDirectory)Xenko.Graphics.Tests.xkpkg - ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) - $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID - prompt - 4 - True - None - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID - prompt - 4 - False - SdkOnly - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID - prompt - 4 - False - SdkOnly - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_ANDROID - prompt - 4 - False - SdkOnly - - - - - - - - - - NUnitLiteLauncher.Android.cs - - - - True - True - True - CustomEffect.xkfx - - - True - True - True - CustomShader.xksl - - - - True - True - True - MultiTexturesSpriteEffect.xkfx - - - True - True - True - MultiTexturesSpriteShader.xksl - - - SimpleEffect.xkfx - True - True - True - - - SimpleShader.xksl - True - True - True - - - ToGlslEffect.xkfx - True - True - True - - - True - True - True - ToGlslShader.xksl - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - XenkoShaderKeyGenerator - CustomEffect.cs - - - XenkoShaderKeyGenerator - CustomShader.cs - - - XenkoShaderKeyGenerator - MultiTexturesSpriteEffect.cs - - - XenkoShaderKeyGenerator - MultiTexturesSpriteShader.cs - - - XenkoShaderKeyGenerator - SimpleEffect.cs - - - XenkoShaderKeyGenerator - SimpleShader.cs - - - XenkoShaderKeyGenerator - ToGlslEffect.cs - - - XenkoShaderKeyGenerator - ToGlslShader.cs - - - - - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Shared.targets b/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Shared.targets deleted file mode 100644 index 4e8aeccf5e..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Shared.targets +++ /dev/null @@ -1,93 +0,0 @@ - - - - - {0E916AB7-5A6C-4820-8AB1-AA492FE66D68} - Xenko.Core - - - {1DE01410-22C9-489B-9796-1ADDAB1F64E5} - Xenko.Core.IO - - - {1320F627-EE43-4115-8E89-19D1753E51F2} - Xenko.Core.MicroThreading - - - {0E916AB7-5A6C-4820-8AB1-AA492FE66D68} - Xenko.Core - - - {5210FB81-B807-49BB-AF0D-31FB6A83A572} - Xenko.Core.Serialization - - - {1677B922-CCF0-44DE-B57E-1CDD3D2B8E8A} - Xenko.Core.Mathematics - - - {84DEB606-77ED-49CD-9AED-D2B13C1F5A1E} - Xenko.Input - - - {273BDD15-7392-4078-91F0-AF23594A3D7B} - Xenko.Shaders - - - {72390339-b2a1-4f61-a800-31ed0975b515} - Xenko - - - {C121A566-555E-42B9-9B0A-1696529A9088} - Xenko.Engine - - - {FB06C76A-6BB7-40BE-9AFA-FEC13B045FB5} - Xenko.Graphics - - - {42780CBD-3FE7-48E3-BD5B-59945EA20137} - Xenko.Games - - - {D002FEB1-00A6-4AB1-A83F-1F253465E64D} - Xenko.Graphics.Regression - - - {f32fda80-b6dd-47a8-8681-437e2c0d3f31} - Xenko.Particles - - - {dd592516-b341-40fe-9100-1b0fa784a060} - Xenko.Physics - - - {9BC63BEC-F305-451D-BB31-262938EA964D} - Xenko.SpriteStudio.Runtime - - - {fbe1fa7b-e699-4bb2-9c8f-41f4c9f3f088} - Xenko.Navigation - - - - - - - - - {E8B3553F-A79F-4E50-B75B-ACEE771C320C} - Xenko.Shaders.Compiler - - - {14A47447-2A24-4ECD-B24D-6571499DCD4C} - Xenko.Shaders.Parser - - - {F2D52EDB-BC17-4243-B06D-33CD20F87A7F} - Xenko.Core.Shaders - - - - - diff --git a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Windows.csproj b/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Windows.csproj index 7cbbd3c15e..d718cc6096 100644 --- a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Windows.csproj +++ b/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.Windows.csproj @@ -1,4 +1,4 @@ - + @@ -7,7 +7,6 @@ Xenko.Graphics.Tests net461 false - false * Windows Windows @@ -27,123 +26,10 @@ Xenko.Graphics.Tests.TestDynamicSpriteFont - + - - True - True - True - CustomEffect.xkfx - - - True - True - True - CustomShader.xksl - - - - True - True - True - MultiTexturesSpriteEffect.xkfx - - - True - True - True - MultiTexturesSpriteShader.xksl - - - SimpleEffect.xkfx - True - True - True - - - SimpleShader.xksl - True - True - True - - - ToGlslEffect.xkfx - True - True - True - - - True - True - True - ToGlslShader.xksl - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - XenkoShaderKeyGenerator - CustomEffect.cs - - - XenkoShaderKeyGenerator - CustomShader.cs - - - XenkoShaderKeyGenerator - MultiTexturesSpriteEffect.cs - - - XenkoShaderKeyGenerator - MultiTexturesSpriteShader.cs - - - XenkoShaderKeyGenerator - SimpleEffect.cs - - - XenkoShaderKeyGenerator - SimpleShader.cs - - - XenkoShaderKeyGenerator - ToGlslEffect.cs - - - XenkoShaderKeyGenerator - ToGlslShader.cs - - + diff --git a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.iOS.csproj b/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.iOS.csproj deleted file mode 100644 index 75965e34b3..0000000000 --- a/sources/engine/Xenko.Graphics.Tests/Xenko.Graphics.Tests.iOS.csproj +++ /dev/null @@ -1,242 +0,0 @@ - - - - - - - Debug - AnyCPU - {9DE0AA56-0DE7-4ADC-BAAC-CD38B7139EBC} - {FEACFBD2-3405-455C-9665-78FE426C6842};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - Exe - PackageReference - Resources - XenkoGraphicsTests - Properties - Xenko.Graphics.Tests - obj\ - $(XenkoPlatform) - true - OpenGLES - Tests\$(XenkoGraphicsApi)\$(AssemblyName) - - true - true - - - $(MSBuildThisFileDirectory)Xenko.Graphics.Tests.xkpkg - ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) - $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - ARMv7, ARMv7s, ARM64 - True - iPhone Developer - True - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - ARMv7, ARMv7s, ARM64 - iPhone Developer - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - ARMv7, ARMv7s, ARM64 - True - iPhone Distribution - True - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - false - True - ARMv7, ARMv7s, ARM64 - iPhone Distribution - - - true - full - false - DEBUG;TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - True - None - i386, x86_64 - - - pdbonly - true - TRACE;XENKO_PLATFORM_MONO_MOBILE;XENKO_PLATFORM_IOS - prompt - 4 - None - i386, x86_64 - - - Xenko.Core.Tests.Application - - - - - - - - NUnitLiteLauncher.iPhone.cs - - - - True - True - True - CustomEffect.xkfx - - - True - True - True - CustomShader.xksl - - - - True - True - True - MultiTexturesSpriteEffect.xkfx - - - True - True - True - MultiTexturesSpriteShader.xksl - - - SimpleEffect.xkfx - True - True - True - - - SimpleShader.xksl - True - True - True - - - ToGlslEffect.xkfx - True - True - True - - - True - True - True - ToGlslShader.xksl - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - XenkoShaderKeyGenerator - CustomEffect.cs - - - XenkoShaderKeyGenerator - CustomShader.cs - - - XenkoShaderKeyGenerator - MultiTexturesSpriteEffect.cs - - - XenkoShaderKeyGenerator - MultiTexturesSpriteShader.cs - - - XenkoShaderKeyGenerator - SimpleEffect.cs - - - XenkoShaderKeyGenerator - SimpleShader.cs - - - XenkoShaderKeyGenerator - ToGlslEffect.cs - - - XenkoShaderKeyGenerator - ToGlslShader.cs - - - - - - - - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteShader.cs b/sources/engine/Xenko.Graphics/Shaders/ColorUtility.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics.Tests/Compiler/MultiTexturesSpriteShader.cs rename to sources/engine/Xenko.Graphics/Shaders/ColorUtility.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/ColorUtility.cs b/sources/engine/Xenko.Graphics/Shaders/ShaderBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/ColorUtility.cs rename to sources/engine/Xenko.Graphics/Shaders/ShaderBase.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/ShaderBase.cs b/sources/engine/Xenko.Graphics/Shaders/ShaderBaseStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/ShaderBase.cs rename to sources/engine/Xenko.Graphics/Shaders/ShaderBaseStream.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/ShaderBaseStream.cs b/sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFont.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/ShaderBaseStream.cs rename to sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFont.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFont.cs b/sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFontShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFont.cs rename to sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFontShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteAlphaCutoff.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteAlphaCutoff.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteAlphaCutoff.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteAlphaCutoff.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteBase.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteBase.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteBase.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteBatch.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteBatch.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteBatch.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteBatch.xkfx.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFontShader.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteBatchShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SignedDistanceFieldFontShader.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteBatchShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteEffect.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteEffect.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteEffect.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTexture.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTexture.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTexture.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTexture.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTextureRegular.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTextureRegular.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTextureRegular.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteEffectExtTextureRegular.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteSignedDistanceFieldFontShader.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteSignedDistanceFieldFontShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteSignedDistanceFieldFontShader.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteSignedDistanceFieldFontShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteBatchShader.cs b/sources/engine/Xenko.Graphics/Shaders/SpriteSuperSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteBatchShader.cs rename to sources/engine/Xenko.Graphics/Shaders/SpriteSuperSampler.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/Texturing.cs b/sources/engine/Xenko.Graphics/Shaders/Texturing.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/Texturing.cs rename to sources/engine/Xenko.Graphics/Shaders/Texturing.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/UIEffect.cs b/sources/engine/Xenko.Graphics/Shaders/UIEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/UIEffect.cs rename to sources/engine/Xenko.Graphics/Shaders/UIEffect.xkfx.cs diff --git a/sources/engine/Xenko.Graphics/Shaders/SpriteSuperSampler.cs b/sources/engine/Xenko.Graphics/Shaders/UIEffectShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/SpriteSuperSampler.cs rename to sources/engine/Xenko.Graphics/Shaders/UIEffectShader.xksl.cs diff --git a/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj b/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj index ffb447bdd9..9c54977465 100644 --- a/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj +++ b/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj @@ -1,4 +1,4 @@ - + true true @@ -80,120 +80,11 @@ $(XenkoDependenciesDir)SharpFont\Portable\SharpFont.dll - Properties\SharedAssemblyInfo.cs - - ColorUtility.xksl - True - True - True - - - True - True - True - SignedDistanceFieldFontShader.xksl - - - True - True - True - SignedDistanceFieldFont.xksl - - - True - True - True - SpriteAlphaCutoff.xksl - - - True - True - True - SpriteEffectExtTexture.xksl - - - True - True - True - SpriteEffectExtTextureRegular.xksl - - - True - True - True - SpriteSignedDistanceFieldFontShader.xksl - - - True - True - True - SpriteSuperSampler.xksl - - - UIEffect.xkfx - True - True - True - - - SpriteBatch.xkfx - True - True - True - - - ShaderBaseStream.xksl - True - True - True - - - FrameworkResources.resx - True - True - - - SpriteBase.xksl - True - True - True - - - SpriteBatchShader.xksl - True - True - True - - - ShaderBase.xksl - True - True - True - - - SpriteEffect.xksl - True - True - True - - - Texturing.xksl - True - True - True - - - True - True - True - UIEffectShader.xksl - - @@ -203,9 +94,6 @@ - - - ResXFileCodeGenerator @@ -214,79 +102,6 @@ - - - - - - XenkoShaderKeyGenerator - SignedDistanceFieldFontShader.cs - - - XenkoShaderKeyGenerator - SignedDistanceFieldFont.cs - - - XenkoShaderKeyGenerator - SpriteAlphaCutoff.cs - - - XenkoShaderKeyGenerator - SpriteEffectExtTexture.cs - - - XenkoShaderKeyGenerator - SpriteEffectExtTextureRegular.cs - - - XenkoShaderKeyGenerator - SpriteSignedDistanceFieldFontShader.cs - - - XenkoShaderKeyGenerator - SpriteSuperSampler.cs - - - XenkoShaderKeyGenerator - UIEffect.cs - - - XenkoShaderKeyGenerator - SpriteBatch.cs - - - XenkoShaderKeyGenerator - ShaderBaseStream.cs - - - XenkoShaderKeyGenerator - ColorUtility.cs - - - XenkoShaderKeyGenerator - SpriteBase.cs - - - XenkoShaderKeyGenerator - SpriteBatchShader.cs - - - XenkoShaderKeyGenerator - ShaderBase.cs - - - XenkoShaderKeyGenerator - SpriteEffect.cs - - - XenkoShaderKeyGenerator - Texturing.cs - - - XenkoShaderKeyGenerator - UIEffectShader.cs - - diff --git a/sources/engine/Xenko.Graphics/Shaders/UIEffectShader.cs b/sources/engine/Xenko.Particles/Shaders/ComputeColorWhite.xksl.cs similarity index 100% rename from sources/engine/Xenko.Graphics/Shaders/UIEffectShader.cs rename to sources/engine/Xenko.Particles/Shaders/ComputeColorWhite.xksl.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleBase.cs b/sources/engine/Xenko.Particles/Shaders/ParticleBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleBase.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleBase.xksl.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleBaseEffect.cs b/sources/engine/Xenko.Particles/Shaders/ParticleBaseEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleBaseEffect.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleBaseEffect.xkfx.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ComputeColorWhite.cs b/sources/engine/Xenko.Particles/Shaders/ParticleColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ComputeColorWhite.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleColor.xksl.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleColor.cs b/sources/engine/Xenko.Particles/Shaders/ParticleColorStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleColor.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleColorStream.xksl.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleColorStream.cs b/sources/engine/Xenko.Particles/Shaders/ParticleComputeColorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleColorStream.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleComputeColorShader.xksl.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleEffect.cs b/sources/engine/Xenko.Particles/Shaders/ParticleEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleEffect.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleEffect.xkfx.cs diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleUtilities.cs b/sources/engine/Xenko.Particles/Shaders/ParticleUtilities.xksl.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleUtilities.cs rename to sources/engine/Xenko.Particles/Shaders/ParticleUtilities.xksl.cs diff --git a/sources/engine/Xenko.Particles/Xenko.Particles.csproj b/sources/engine/Xenko.Particles/Xenko.Particles.csproj index 424dd4a7ea..3be49d0ef6 100644 --- a/sources/engine/Xenko.Particles/Xenko.Particles.csproj +++ b/sources/engine/Xenko.Particles/Xenko.Particles.csproj @@ -13,105 +13,14 @@ * true - - - - - - Properties\SharedAssemblyInfo.cs - - True - True - True - ComputeColorWhite.xksl - - - True - True - True - ParticleBaseEffect.xkfx - - - True - True - True - ParticleColor.xksl - - - True - True - True - ParticleColorStream.xksl - - - True - True - True - ParticleComputeColorShader.xksl - - - True - True - True - ParticleEffect.xkfx - - - True - True - True - ParticleUtilities.xksl - - - True - True - True - ParticleBase.xksl - - - - XenkoShaderKeyGenerator - ComputeColorWhite.cs - - - XenkoShaderKeyGenerator - ParticleBase.cs - - - XenkoShaderKeyGenerator - ParticleBaseEffect.cs - - - XenkoShaderKeyGenerator - ParticleColor.cs - - - XenkoShaderKeyGenerator - ParticleColorStream.cs - - - XenkoShaderKeyGenerator - ParticleComputeColorShader.cs - - - XenkoShaderKeyGenerator - ParticleEffect.cs - - - XenkoShaderKeyGenerator - ParticleUtilities.cs - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.Particles/Shaders/ParticleComputeColorShader.cs b/sources/engine/Xenko.Rendering/Rendering/BRDF/BRDFMicrofacet.xksl.cs similarity index 100% rename from sources/engine/Xenko.Particles/Shaders/ParticleComputeColorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/BRDF/BRDFMicrofacet.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Background/BackgroundCubemapShader.cs b/sources/engine/Xenko.Rendering/Rendering/Background/BackgroundCubemapShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Background/BackgroundCubemapShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Background/BackgroundCubemapShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Background/BackgroundShader.cs b/sources/engine/Xenko.Rendering/Rendering/Background/BackgroundShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Background/BackgroundShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Background/BackgroundShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAADepthResolverShader.cs b/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAADepthResolverShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Compositing/MSAADepthResolverShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Compositing/MSAADepthResolverShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverShader.cs b/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolverShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeEffectShader1.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeEffectShader.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeEffectShader1.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeEffectShader.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/BRDF/BRDFMicrofacet.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeShaderBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/BRDF/BRDFMicrofacet.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeShaderBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeShaderBase.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/Hammersley.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/ComputeShaderBase.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/Hammersley.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/Hammersley.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/ImportanceSamplingGGX.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/Hammersley.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/ImportanceSamplingGGX.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXEffect.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeEffect.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeShader.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeShader.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXNoComputeShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXShader.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXShader.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/RadiancePrefilteringGGXShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSH1.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSH.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSH1.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSH.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputeEffect.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputeEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputeEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputeEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass1.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass1.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass1.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass1.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/ImportanceSamplingGGX.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/GGXPrefiltering/ImportanceSamplingGGX.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass2.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass1.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass1.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass1.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass1.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass2.cs b/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass2.cs rename to sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHPass2.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocity.cs b/sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocity.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocity.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocity.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocityEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocityEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocityEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/BackgroundVelocityEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass2.cs b/sources/engine/Xenko.Rendering/Rendering/Core/ColorBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ComputeEffect/LambertianPrefiltering/LambertianPrefilteringSHNoComputePass2.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/ColorBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/ColorBase.cs b/sources/engine/Xenko.Rendering/Rendering/Core/DynamicSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/ColorBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/DynamicSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/DynamicSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Core/DynamicTexture.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/DynamicSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/DynamicTexture.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/DynamicTexture.cs b/sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureCube.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/DynamicTexture.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureCube.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureCube.cs b/sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureCube.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/MeshVelocity.cs b/sources/engine/Xenko.Rendering/Rendering/Core/MeshVelocity.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/MeshVelocity.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/MeshVelocity.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureStream.cs b/sources/engine/Xenko.Rendering/Rendering/Core/NormalBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/DynamicTextureStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/NormalBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/NormalBase.cs b/sources/engine/Xenko.Rendering/Rendering/Core/NormalFromMesh.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/NormalBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/NormalFromMesh.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/NormalFromMesh.cs b/sources/engine/Xenko.Rendering/Rendering/Core/NormalFromNormalMapping.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/NormalFromMesh.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/NormalFromNormalMapping.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/NormalFromNormalMapping.cs b/sources/engine/Xenko.Rendering/Rendering/Core/NormalStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/NormalFromNormalMapping.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/NormalStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/NormalUpdate.cs b/sources/engine/Xenko.Rendering/Rendering/Core/NormalUpdate.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/NormalUpdate.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/NormalUpdate.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/NormalStream.cs b/sources/engine/Xenko.Rendering/Rendering/Core/PositionHStream4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/NormalStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/PositionHStream4.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/PositionHStream4.cs b/sources/engine/Xenko.Rendering/Rendering/Core/PositionStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/PositionHStream4.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/PositionStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/PositionStream2.cs b/sources/engine/Xenko.Rendering/Rendering/Core/PositionStream4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/PositionStream2.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/PositionStream4.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/PositionStream4.cs b/sources/engine/Xenko.Rendering/Rendering/Core/PositionVertexTransform.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/PositionStream4.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/PositionVertexTransform.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/PositionVertexTransform.cs b/sources/engine/Xenko.Rendering/Rendering/Core/ScreenPositionBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/PositionVertexTransform.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/ScreenPositionBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/ScreenPositionBase.cs b/sources/engine/Xenko.Rendering/Rendering/Core/ShadingBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/ScreenPositionBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/ShadingBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/ShadingBase.cs b/sources/engine/Xenko.Rendering/Rendering/Core/ShadingColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/ShadingBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/ShadingColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/ShadingColor.cs b/sources/engine/Xenko.Rendering/Rendering/Core/VelocityOutput.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/ShadingColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/VelocityOutput.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/VelocityOutput.cs b/sources/engine/Xenko.Rendering/Rendering/Core/VelocityStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/VelocityOutput.cs rename to sources/engine/Xenko.Rendering/Rendering/Core/VelocityStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Core/VelocityStream.cs b/sources/engine/Xenko.Rendering/Rendering/Deferred/GBuffer.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Core/VelocityStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Deferred/GBuffer.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Deferred/GBuffer1.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/CompilationErrorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Deferred/GBuffer1.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/CompilationErrorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/CompilationErrorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/EffectCompiling.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/CompilationErrorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/EffectCompiling.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/EffectCompiling.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/LightConstantWhite.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/EffectCompiling.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/LightConstantWhite.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/SelectedSpriteShader.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/SelectedSpriteShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/SelectedSpriteShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/SelectedSpriteShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/LightConstantWhite.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/SharedTextureCoordinate.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/LightConstantWhite.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/SharedTextureCoordinate.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/Sprite3DBase.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/Sprite3DBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/Sprite3DBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/Sprite3DBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/SharedTextureCoordinate.cs b/sources/engine/Xenko.Rendering/Rendering/Editor/SpritePicking.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/SharedTextureCoordinate.cs rename to sources/engine/Xenko.Rendering/Rendering/Editor/SpritePicking.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurEffect1.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurEffect1.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionBlurShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/AmbientOcclusionRawAOShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Editor/SpritePicking.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/ApplyAmbientOcclusionShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Editor/SpritePicking.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/ApplyAmbientOcclusionShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/ApplyAmbientOcclusionShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AmbientOcclusion/ApplyAmbientOcclusionShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShaderEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShaderEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShaderEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShaderEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/TemporalAntiAliasShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/TemporalAntiAliasShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/TemporalAntiAliasShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/TemporalAntiAliasShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageCombineShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/AntiAliasing/FXAAShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageCombineShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/BrightFilter/BrightFilterShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/BrightFilter/BrightFilterShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/BrightFilter/BrightFilterShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/BrightFilter/BrightFilterShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorCombiner/ColorCombinerShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageCombineShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/Bloom/BloomAfterimageCombineShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformGroupShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/LuminanceToChannelShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ColorTransformShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/LuminanceToChannelShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Noise/FilmGrainShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Noise/FilmGrainShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Noise/FilmGrainShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Noise/FilmGrainShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapCommonOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapCommonOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapCommonOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapCommonOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapDragoOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapDragoOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapDragoOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapDragoOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/LuminanceToChannelShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapExponentialOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/LuminanceToChannelShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapExponentialOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejl2OperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejl2OperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejl2OperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejl2OperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapExponentialOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejlDawsonOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapExponentialOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejlDawsonOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejlDawsonOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapLogarithmicOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapHejlDawsonOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapLogarithmicOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapMikeDayOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapMikeDayOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapMikeDayOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapMikeDayOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapLogarithmicOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapLogarithmicOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapReinhardOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapReinhardOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapU2FilmicOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapU2FilmicOperatorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapU2FilmicOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapU2FilmicOperatorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Vignetting/VignettingShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Vignetting/VignettingShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Vignetting/VignettingShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/Vignetting/VignettingShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthMinMax/DepthMinMaxShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapReinhardOperatorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshCombineShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ColorTransforms/ToneMap/ToneMapReinhardOperatorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshCombineShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshCombineShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshCombineShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/TripleRhombiCombineShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/TripleRhombiCombineShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/TripleRhombiCombineShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/TripleRhombiCombineShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CircleOfConfusion.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CircleOfConfusion.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CircleOfConfusion.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CircleOfConfusion.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCLinearDepthShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/BokehTechnique/Hexagonal/McIntoshOptimizedShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCLinearDepthShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCMapBlurShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCLinearDepthShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CoCLinearDepthShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineLevelsFromCoCShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/CombineFrontCoCShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurUtil.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurUtil.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurUtil.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurUtil.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/PointDepth.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/PointDepth.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/PointDepth.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/PointDepth.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoC.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoC.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoC.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoC.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoCFront.cs b/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoCFront.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoCFront.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/ThresholdAlphaCoCFront.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/Dither/Dither2.cs b/sources/engine/Xenko.Rendering/Rendering/Images/Dither/Dither.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/Dither/Dither2.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/Dither/Dither.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/GaussianBlur/GaussianBlurShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ImageEffectShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/DepthOfField/DepthAwareDirectionalBlurShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ImageEffectShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/ImageScaler/ImageScalerShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareArtifactShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareReplicate.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareReplicate.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareReplicate.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LensFlare/FlareReplicate.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightEffect.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/AdditiveLightShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/LightShaftsShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/ImageEffectShader1.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/PostEffectBoundingRay.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/ImageEffectShader1.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/PostEffectBoundingRay.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/VolumeMinMaxShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/VolumeMinMaxShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/VolumeMinMaxShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/VolumeMinMaxShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LightStreak/LightStreakShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRBlurPass.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRBlurPass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRBlurPass.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRBlurPass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCombinePass.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCombinePass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCombinePass.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCombinePass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCommon.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCommon.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCommon.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRCommon.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRDepthPass.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRDepthPass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRDepthPass.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRDepthPass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRRayTracePass.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRRayTracePass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRRayTracePass.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRRayTracePass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRResolvePass.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRResolvePass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRResolvePass.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRResolvePass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRTemporalPass.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRTemporalPass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRTemporalPass.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LocalReflections/SSLRTemporalPass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/PostEffectBoundingRay.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceLogShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LightShafts/PostEffectBoundingRay.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceLogShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceLogShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceUtils.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceLogShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceUtils.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceUtils.cs b/sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeCompressorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/LuminanceEffect/LuminanceUtils.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeCompressorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeCompressorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeDecompressorShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeCompressorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeDecompressorShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeDecompressorShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/RangeConversion/RangeDecompressorShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsParameters.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsParameters.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsParameters.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsParameters.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRenderer1.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRenderer.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRenderer1.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRenderer.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRendererEffect1.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRendererEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRendererEffect1.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsRendererEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsBase.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsUtils.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsUtils.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurShader.cs b/sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Images/SubsurfaceScattering/SubsurfaceScatteringBlurShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/LightProbes/BakeLightProbeShader.cs b/sources/engine/Xenko.Rendering/Rendering/LightProbes/BakeLightProbeShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/LightProbes/BakeLightProbeShader.cs rename to sources/engine/Xenko.Rendering/Rendering/LightProbes/BakeLightProbeShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/LightProbes/ComputeSphericalHarmonics.cs b/sources/engine/Xenko.Rendering/Rendering/LightProbes/ComputeSphericalHarmonics.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/LightProbes/ComputeSphericalHarmonics.cs rename to sources/engine/Xenko.Rendering/Rendering/LightProbes/ComputeSphericalHarmonics.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/LightProbes/LightProbeShader.cs b/sources/engine/Xenko.Rendering/Rendering/LightProbes/LightProbeShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/LightProbes/LightProbeShader.cs rename to sources/engine/Xenko.Rendering/Rendering/LightProbes/LightProbeShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/LightProbes/XenkoBakeLightProbeEffect.cs b/sources/engine/Xenko.Rendering/Rendering/LightProbes/XenkoBakeLightProbeEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/LightProbes/XenkoBakeLightProbeEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/LightProbes/XenkoBakeLightProbeEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsUtils.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Images/SphericalHarmonics/SphericalHarmonicsUtils.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupArray.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupArray.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupArray.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupFixed.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupArray.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupFixed.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerDraw.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerDraw.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerDraw.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerDraw.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerView.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerView.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerView.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupPerView.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupFixed.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLight.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/DirectLightGroupFixed.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLight.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLight.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLightArray.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLight.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLightArray.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClustered.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClustered.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightClustered.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightClustered.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLightArray.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectional.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/EnvironmentLightArray.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectional.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectionalGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectionalGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectionalGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectionalGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectional1.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightPoint.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightDirectional1.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightPoint.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightPointGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightPointGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightPointGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightPointGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSimpleAmbient.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSimpleAmbient.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSimpleAmbient.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSimpleAmbient.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxShader.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightPoint1.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpot.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightPoint1.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSpot.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpot1.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationDefault.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSpot1.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationDefault.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationDefault.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationRectangular.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationDefault.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationRectangular.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationRectangular.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightSpotAttenuationRectangular.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightStream.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightUtil.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/LightUtil.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightUtil.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/SpotLightDataInternalShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/LightUtil.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/SpotLightDataInternalShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/SpotLightDataInternalShader.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionCommon.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/SpotLightDataInternalShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionCommon.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionCommon.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionFilterDefault.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionCommon.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionFilterDefault.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionFilterDefault.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionFilterDefault.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverBase.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverSpot.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverSpot.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/IMaterialCelShadingLightFunction.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/IMaterialCelShadingLightFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/IMaterialCelShadingLightFunction.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/IMaterialCelShadingLightFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightDefault.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightDefault.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightDefault.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightDefault.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightRamp2.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightRamp.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightRamp2.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/CelShading/MaterialCelShadingLightRamp.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverSpot.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorAdd3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Lights/TextureProjection/TextureProjectionReceiverSpot.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorAdd3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorAdd3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDarken3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorAdd3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDarken3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDarken3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDifference3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDarken3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDifference3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDifference3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorLighten3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorDifference3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorLighten3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorLighten3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMask3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorLighten3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMask3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMask3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMultiply3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMask3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMultiply3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMultiply3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOver3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorMultiply3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOver3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOver3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOverlay3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOver3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOverlay3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOverlay3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorSubtract3ds.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorOverlay3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorSubtract3ds.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorSubtract3ds.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/3dsMax/ComputeColorSubtract3ds.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor3.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor3.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor3.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColor3.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd3.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd3.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd3.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAverage.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAdd3.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAverage.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAverage.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorCave.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorAverage.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorCave.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorCave.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorCave.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorBurn.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorBurn.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorBurn.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorDodge.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorBurn.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorDodge.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorDodge.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantColorLink.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorColorDodge.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantColorLink.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantColorLink.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantFloatLink.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantColorLink.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantFloatLink.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantFloatLink.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantLink.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantFloatLink.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantLink.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantLink.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDesaturate.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorConstantLink.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDesaturate.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDesaturate.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDivide.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDesaturate.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDivide.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDivide.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorExclusion.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorDivide.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorExclusion.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorExclusion.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFixed.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorExclusion.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFixed.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFixed.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFromStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFixed.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFromStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFromStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardLight.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorFromStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardLight.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardLight.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardMix.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardLight.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardMix.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardMix.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHue.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHardMix.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHue.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHue.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIlluminate.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorHue.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIlluminate.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIlluminate.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIn.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIlluminate.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIn.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIn.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLerpAlpha.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorIn.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLerpAlpha.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLerpAlpha.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearBurn.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLerpAlpha.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearBurn.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearBurn.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearDodge.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearBurn.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearDodge.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearDodge.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMask.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorLinearDodge.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMask.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMask.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMultiply.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMask.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMultiply.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMultiply.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOne.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorMultiply.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOne.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOne.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOut.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOne.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOut.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOut.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOutdoor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOut.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOutdoor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOutdoor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOverlay.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOutdoor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOverlay.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorParameter.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorParameter.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorParameter.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorParameter.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOverlay.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorPinLight.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorOverlay.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorPinLight.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorPinLight.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturate.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorPinLight.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturate.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturate.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturation.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturate.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturation.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturation.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScaler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSaturation.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScaler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScaler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScreen.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScaler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScreen.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScreen.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSoftLight.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorScreen.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSoftLight.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSoftLight.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSoftLight.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlpha.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlpha.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlpha.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlphaWithColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlpha.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlphaWithColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlphaWithColor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubtract.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubstituteAlphaWithColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubtract.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubtract1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSynthetic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSubtract1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSynthetic.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSynthetic.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTexture.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorSynthetic.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTexture.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureDynamicScaledOffset.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureDynamicScaledOffset.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureDynamicScaledOffset.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureDynamicScaledOffset.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTexture.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTexture.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetDynamicSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetDynamicSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetDynamicSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetDynamicSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledOffsetSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureRepeat.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureLodScaledSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureRepeat.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureRepeat.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureRepeat.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaled.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaled.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaled.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffset.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaled.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffset.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffset.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffset.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledOffsetSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledSampler.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledSampler.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorThreshold.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorTextureScaledSampler.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorThreshold.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorThreshold.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorValue.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorThreshold.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorValue.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorValue.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorAddMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/ComputeColorValue.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorAddMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorAddMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDarkenMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorAddMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDarkenMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDarkenMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDifferenceMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDarkenMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDifferenceMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDifferenceMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorLightenMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorDifferenceMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorLightenMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorLightenMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorMultiplyMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorLightenMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorMultiplyMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorMultiplyMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorOverMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorMultiplyMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorOverMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorOverMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorSubtractMaya.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorOverMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorSubtractMaya.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorSubtractMaya.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/IMaterialHairDirectionFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/ComputeColors/Shaders/Maya/ComputeColorSubtractMaya.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/IMaterialHairDirectionFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/IMaterialHairDirectionFunction1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionBitangent.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/IMaterialHairDirectionFunction1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionBitangent.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionBitangent1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionTangent.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionBitangent1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionTangent.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionTangent1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/IMaterialHairDiscardFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DirectionFunction/MaterialHairDirectionFunctionTangent1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/IMaterialHairDiscardFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/IMaterialHairDiscardFunction1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionOpaquePass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/IMaterialHairDiscardFunction1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionOpaquePass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionOpaquePass1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionTransparentPass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionOpaquePass1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionTransparentPass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionTransparentPass1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/IMaterialHairLightAttenuationFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/DiscardFunction/MaterialHairDiscardFunctionTransparentPass1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/IMaterialHairLightAttenuationFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/IMaterialHairLightAttenuationFunction1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionDirectional.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/IMaterialHairLightAttenuationFunction1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionDirectional.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionDirectional2.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionNone.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionDirectional2.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionNone.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialHairShared1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialHairShared.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialHairShared1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialHairShared.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionNone1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingDiffuseHair.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/LightAttenuationFunction/MaterialHairLightAttenuationFunctionNone1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingDiffuseHair.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingSpecularHair.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingSpecularHair.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingSpecularHair.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingSpecularHair.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingDiffuseHair.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/IMaterialHairShadowingFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/MaterialSurfaceShadingDiffuseHair.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/IMaterialHairShadowingFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/IMaterialHairShadowingFunction1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionScattering.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/IMaterialHairShadowingFunction1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionScattering.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionScattering1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionShadowing.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionScattering1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionShadowing.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionShadowing1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/IMaterialSurfaceDomain.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Hair/ShadowingFunction/MaterialHairShadowingFunctionShadowing1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/IMaterialSurfaceDomain.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/IMaterialSurfaceDomain.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/IStreamInitializer.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/IMaterialSurfaceDomain.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/IStreamInitializer.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/IStreamInitializer.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDisplacementStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/IStreamInitializer.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDisplacementStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDisplacementStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDomainStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDisplacementStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDomainStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDomainStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialStreamAdditiveBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/MaterialDomainStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/MaterialStreamAdditiveBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialStreamAdditiveBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDisplacement.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/MaterialStreamAdditiveBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDisplacement.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDisplacement1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDomainStageCompositor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDisplacement1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDomainStageCompositor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDomainStageCompositor1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialTessellationStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/MaterialSurfaceDomainStageCompositor1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/MaterialTessellationStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialTessellationStream1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/ComputeColorMaterialAlphaBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/MaterialTessellationStream1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/ComputeColorMaterialAlphaBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/ComputeColorMaterialAlphaBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputNormals.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/ComputeColorMaterialAlphaBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputNormals.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSpecularColorRoughness.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSpecularColorRoughness.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSpecularColorRoughness.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSpecularColorRoughness.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSubsurfaceScatteringMaterialIndex.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSubsurfaceScatteringMaterialIndex.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSubsurfaceScatteringMaterialIndex.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputSubsurfaceScatteringMaterialIndex.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputNormals.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetEnvironmentFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/GBufferOutputNormals.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetEnvironmentFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetEnvironmentFunction.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetFresnelFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetEnvironmentFunction.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetFresnelFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetFresnelFunction.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetNormalDistributionFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetFresnelFunction.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetNormalDistributionFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetNormalDistributionFunction.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetVisibilityFunction.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetNormalDistributionFunction.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetVisibilityFunction.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetVisibilityFunction.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialStreamBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSpecularMicrofacetVisibilityFunction.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialStreamBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialStreamBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurface.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialStreamBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurface.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurface.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfacePixel.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurface.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfacePixel.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfacePixel.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfacePixel.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceVertex.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceVertex.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialFrontBackBlendShader.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialFrontBackBlendShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialFrontBackBlendShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialFrontBackBlendShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceVertex.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelShadingStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/IMaterialSurfaceVertex.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelShadingStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelShadingStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelShadingStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXLUT.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXLUT.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXLUT.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXLUT.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXPolynomial.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialPixelStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXPolynomial.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentThinGlass.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentThinGlass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentThinGlass.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentThinGlass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXPolynomial.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelNone.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetEnvironmentGGXPolynomial.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelNone.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelNone.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelSchlick.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelNone.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelSchlick.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelSchlick.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelThinGlass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelSchlick.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelThinGlass.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelThinGlass.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBeckmann.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetFresnelThinGlass.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBeckmann.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBeckmann.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBlinnPhong.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBeckmann.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBlinnPhong.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBlinnPhong.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionGGX.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionBlinnPhong.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionGGX.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionGGX.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityCookTorrance.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetNormalDistributionGGX.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityCookTorrance.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityCookTorrance.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityImplicit.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityCookTorrance.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityImplicit.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityImplicit.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityKelemen.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityImplicit.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityKelemen.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityKelemen.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityNeumann.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityKelemen.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityNeumann.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityNeumann.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithBeckmann.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilityNeumann.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithBeckmann.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithBeckmann.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithBeckmann.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamLinearBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamLinearBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamLinearBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamNormalBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamLinearBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamNormalBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamNormalBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceArray.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialStreamNormalBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceArray.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceArray.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuse.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceArray.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuse.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuse.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseMetalFlakes.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuse.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseMetalFlakes.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseMetalFlakes.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseSpecularAlphaBlendColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseMetalFlakes.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseSpecularAlphaBlendColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseSpecularAlphaBlendColor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceEmissiveShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceDiffuseSpecularAlphaBlendColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceEmissiveShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceEmissiveShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMap.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceEmissiveShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMap.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMap.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMapMetalFlakes.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMap.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMapMetalFlakes.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMapMetalFlakes.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceLightingAndShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceGlossinessMapMetalFlakes.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceLightingAndShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceLightingAndShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceMetalness.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceLightingAndShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceMetalness.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceMetalness.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalMap.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceMetalness.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalMap.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalMap.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalStreamShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalMap.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalStreamShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalStreamShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfacePixelStageCompositor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceNormalStreamShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfacePixelStageCompositor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfacePixelStageCompositor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceSetStreamFromComputeColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfacePixelStageCompositor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceSetStreamFromComputeColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceSetStreamFromComputeColor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceSetStreamFromComputeColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingDiffuseLambert.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingDiffuseLambert.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingDiffuseLambert.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularBlinnPhong.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingDiffuseLambert.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularBlinnPhong.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularBlinnPhong.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularMicrofacet.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularBlinnPhong.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularMicrofacet.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularMicrofacet.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceShadingSpecularMicrofacet.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamsBlend.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamsBlend.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamsBlend.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransmittanceShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceStreamsBlend.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransmittanceShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransmittanceShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransparentAlphaDiscard.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransmittanceShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransparentAlphaDiscard.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransparentAlphaDiscard.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexDisplacement.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceTransparentAlphaDiscard.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexDisplacement.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexDisplacement.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexStageCompositor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexDisplacement.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexStageCompositor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialTransmittanceReflectanceStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialTransmittanceReflectanceStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialTransmittanceReflectanceStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialTransmittanceReflectanceStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexStageCompositor.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialVertexStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialSurfaceVertexStageCompositor.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialVertexStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/MaterialSurfaceSubsurfaceScatteringShading.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/MaterialSurfaceSubsurfaceScatteringShading.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/MaterialSurfaceSubsurfaceScatteringShading.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/MaterialSurfaceSubsurfaceScatteringShading.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialVertexStream.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/IMaterialSubsurfaceScatteringScatteringProfile.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/Shaders/MaterialVertexStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/IMaterialSubsurfaceScatteringScatteringProfile.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomUniform1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomUniform.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomUniform1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomUniform.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/IMaterialSubsurfaceScatteringScatteringProfile1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomVarying.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/IMaterialSubsurfaceScatteringScatteringProfile1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomVarying.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomVarying1.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileSkin.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileCustomVarying1.cs rename to sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileSkin.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/ProceduralModels/CameraCube.cs b/sources/engine/Xenko.Rendering/Rendering/ProceduralModels/CameraCube.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/ProceduralModels/CameraCube.cs rename to sources/engine/Xenko.Rendering/Rendering/ProceduralModels/CameraCube.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shaders/Camera.cs b/sources/engine/Xenko.Rendering/Rendering/Shaders/Camera.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shaders/Camera.cs rename to sources/engine/Xenko.Rendering/Rendering/Shaders/Camera.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shaders/Global.cs b/sources/engine/Xenko.Rendering/Rendering/Shaders/Global.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shaders/Global.cs rename to sources/engine/Xenko.Rendering/Rendering/Shaders/Global.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shaders/GlobalVR.cs b/sources/engine/Xenko.Rendering/Rendering/Shaders/GlobalVR.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shaders/GlobalVR.cs rename to sources/engine/Xenko.Rendering/Rendering/Shaders/GlobalVR.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shaders/Transformation.cs b/sources/engine/Xenko.Rendering/Rendering/Shaders/Transformation.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shaders/Transformation.cs rename to sources/engine/Xenko.Rendering/Rendering/Shaders/Transformation.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileSkin1.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Materials/SubsurfaceScattering/ScatteringProfileFunction/MaterialSubsurfaceScatteringScatteringProfileSkin1.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCaster.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCaster.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCaster.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCaster.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterAlphaDiscard.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterAlphaDiscard.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMap.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMap.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMap.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMap.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterAlphaDiscard.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMapProjection.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterAlphaDiscard.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMapProjection.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMapProjection1.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterNoPixelShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterCubeMapProjection1.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterNoPixelShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloid1.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloid.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloid1.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloid.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloidProjection1.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloidProjection.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloidProjection1.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterParaboloidProjection.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterNoPixelShader.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterVsm.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterNoPixelShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterVsm.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterVsm.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCommon.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCasterVsm.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCommon.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCommon.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapCommon.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterBase.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterDefault.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterDefault.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterDefault.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterPcf.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterDefault.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterPcf.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterVsm.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterVsm.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterVsm.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterVsm.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterPcf.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapGroup.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapFilterPcf.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapGroup.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverBase.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverDirectional.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverDirectional.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverDirectional.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverDirectional.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointCubeMap.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointCubeMap.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointCubeMap.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointCubeMap.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointParaboloid.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointParaboloid.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointParaboloid.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverPointParaboloid.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapGroup.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverSpot.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapGroup.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverSpot.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverSpot.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowMapReceiverSpot.cs rename to sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowStream.cs b/sources/engine/Xenko.Rendering/Rendering/Skinning/NormalMeshSkinning.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Shadows/ShadowStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Skinning/NormalMeshSkinning.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skinning/NormalMeshSkinning.cs b/sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningFromMesh.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skinning/NormalMeshSkinning.cs rename to sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningFromMesh.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningFromMesh.cs b/sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningNormalMapping.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningFromMesh.cs rename to sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningNormalMapping.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningNormalMapping.cs b/sources/engine/Xenko.Rendering/Rendering/Skinning/TangentMeshSkinning.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skinning/NormalVSSkinningNormalMapping.cs rename to sources/engine/Xenko.Rendering/Rendering/Skinning/TangentMeshSkinning.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skinning/TransformationSkinning.cs b/sources/engine/Xenko.Rendering/Rendering/Skinning/TransformationSkinning.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skinning/TransformationSkinning.cs rename to sources/engine/Xenko.Rendering/Rendering/Skinning/TransformationSkinning.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skinning/TangentMeshSkinning.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/CubemapUtils.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skinning/TangentMeshSkinning.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/CubemapUtils.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/CubemapUtils.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/IComputeEnvironmentColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/CubemapUtils.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/IComputeEnvironmentColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/LevelCubeMapEnvironmentColor.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/LevelCubeMapEnvironmentColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/LevelCubeMapEnvironmentColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/LevelCubeMapEnvironmentColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/RoughnessCubeMapEnvironmentColor.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/RoughnessCubeMapEnvironmentColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/RoughnessCubeMapEnvironmentColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/RoughnessCubeMapEnvironmentColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderBase.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderCubemap.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderCubemap.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderCubemap.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderCubemap.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderTexture.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderTexture.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderTexture.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxShaderTexture.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/IComputeEnvironmentColor.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/IComputeEnvironmentColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxStream.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SphericalHarmonicsEnvironmentColor.cs b/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SphericalHarmonicsEnvironmentColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/SphericalHarmonicsEnvironmentColor.cs rename to sources/engine/Xenko.Rendering/Rendering/Skyboxes/SphericalHarmonicsEnvironmentColor.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxStream.cs b/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Skyboxes/SkyboxStream.cs rename to sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE2.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE2.cs b/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE3.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE2.cs rename to sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE3.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE3.cs b/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE3.cs rename to sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE4.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE4.cs b/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationAE4.cs rename to sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationBase.cs b/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationFlat.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationFlat.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationFlat.cs b/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationPN.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationFlat.cs rename to sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationPN.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationPN.cs b/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Tessellation/TessellationPN.cs rename to sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationBase.cs b/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationMatrix.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationMatrix.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationMatrix.cs b/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWAndVP.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationMatrix.cs rename to sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWAndVP.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWAndVP.cs b/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWVP.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWAndVP.cs rename to sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWVP.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWVP.cs b/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationZero.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationWVP.cs rename to sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationZero.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationZero.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/BlendUtils.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Transformation/TransformationZero.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/BlendUtils.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/DepthBase.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/DepthBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/DepthBase.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/DepthBase.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/BlendUtils.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/FlattenLayers.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/BlendUtils.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/FlattenLayers.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/FlattenLayers.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/HSVUtils.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/FlattenLayers.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/HSVUtils.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/HighlightShader.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/HighlightShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/HighlightShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/HighlightShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/HSVUtils.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/Math.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/HSVUtils.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/Math.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingEffect.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingShader.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/ModelComponentPickingShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/NormalPack.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/NormalPack.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/NormalPack.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/NormalPack.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/Math.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/NormalUtil.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/Math.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/NormalUtil.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/Picking.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/Picking.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/Picking.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/Picking.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/PickingShader.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/PickingShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/PickingShader.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/PickingShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/NormalUtil.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/SwapUV.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/NormalUtil.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/SwapUV.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/SwapUV.cs b/sources/engine/Xenko.Rendering/Rendering/Utils/Utilities.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/SwapUV.cs rename to sources/engine/Xenko.Rendering/Rendering/Utils/Utilities.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/XenkoEffectBase.cs b/sources/engine/Xenko.Rendering/Rendering/XenkoEffectBase.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/XenkoEffectBase.cs rename to sources/engine/Xenko.Rendering/Rendering/XenkoEffectBase.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/XenkoForwardShadingEffect.cs b/sources/engine/Xenko.Rendering/Rendering/XenkoForwardShadingEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/XenkoForwardShadingEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/XenkoForwardShadingEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/XenkoWireframeShadingEffect.cs b/sources/engine/Xenko.Rendering/Rendering/XenkoWireframeShadingEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/XenkoWireframeShadingEffect.cs rename to sources/engine/Xenko.Rendering/Rendering/XenkoWireframeShadingEffect.xkfx.cs diff --git a/sources/engine/Xenko.Rendering/Xenko.Rendering.csproj b/sources/engine/Xenko.Rendering/Xenko.Rendering.csproj index c7dd05e6b9..29a5d508e0 100644 --- a/sources/engine/Xenko.Rendering/Xenko.Rendering.csproj +++ b/sources/engine/Xenko.Rendering/Xenko.Rendering.csproj @@ -16,4077 +16,11 @@ Properties\SharedAssemblyInfo.cs - - True - True - True - BackgroundShader.xksl - - - True - True - True - BackgroundCubemapShader.xksl - - - True - True - True - MSAADepthResolverShader.xksl - - - XenkoShaderKeyGenerator - BackgroundCubemapShader.cs - - - XenkoShaderKeyGenerator - MSAADepthResolverShader.cs - - - XenkoShaderKeyGenerator - MSAAResolverEffect.cs - - - True - True - True - MSAAResolverEffect.xkfx - - - True - True - True - MSAAResolverShader.xksl - - - True - True - True - RadiancePrefilteringGGXNoComputeEffect.xkfx - - - True - True - True - RadiancePrefilteringGGXNoComputeShader.xksl - - - True - True - True - LambertianPrefilteringSHNoComputeEffect.xkfx - - - True - True - True - LambertianPrefilteringSHNoComputePass1.xksl - - - True - True - True - LambertianPrefilteringSHNoComputePass2.xksl - - - True - CompilationErrorShader.xksl - True - True - - - True - EffectCompiling.xksl - True - True - - - True - LightConstantWhite.xksl - True - True - - - True - SelectedSpriteShader.xksl - True - True - - - True - SharedTextureCoordinate.xksl - True - True - - - True - Sprite3DBase.xksl - True - True - - - True - SpritePicking.xksl - True - True - - - True - True - True - IMaterialHairDiscardFunction.xksl - - - True - True - True - MaterialHairDiscardFunctionOpaquePass.xksl - - - True - True - True - MaterialHairDiscardFunctionTransparentPass.xksl - - - True - True - True - MaterialSurfaceSubsurfaceScatteringShading.xksl - - - True - True - True - NormalUpdate.xksl - - - True - True - True - SSLRDepthPass.xksl - - - True - True - True - SSLRResolvePass.xksl - - - True - True - True - SSLRTemporalPass.xksl - - - True - True - True - LightSpotAttenuationDefault.xksl - - - True - True - True - LightSpotAttenuationRectangular.xksl - - - True - True - True - SpotLightDataInternalShader.xksl - - - True - True - True - TextureProjectionCommon.xksl - - - True - True - True - TextureProjectionFilterDefault.xksl - - - True - True - True - TextureProjectionGroup.xksl - - - True - True - True - TextureProjectionReceiverBase.xksl - - - True - True - True - TextureProjectionReceiverSpot.xksl - - - True - True - True - GBufferOutputNormals.xksl - - - True - True - True - GBufferOutputSpecularColorRoughness.xksl - - - ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.xksl - True - True - True - - - MaterialSurfaceDiffuseMetalFlakes.xksl - True - True - True - - - MaterialSurfaceGlossinessMapMetalFlakes.xksl - True - True - True - - - True - True - True - BackgroundVelocity.xksl - - - True - True - True - BackgroundVelocityEffect.xkfx - - - True - True - True - MeshVelocity.xksl - - - True - True - True - VelocityOutput.xksl - - - True - True - True - VelocityStream.xksl - - - TemporalAntiAliasShader.xksl - True - True - True - - - True - True - True - SSLRBlurPass.xksl - - - True - True - True - AdditiveLightEffect.xksl - - - True - True - True - LightShaftsEffect.xkfx - - - True - True - True - SSLRCombinePass.xksl - - - True - True - True - SSLRCommon.xksl - - - True - True - True - SSLRRayTracePass.xksl - - - XenkoShaderKeyGenerator - NormalUpdate.cs - - - XenkoShaderKeyGenerator - SSLRBlurPass.cs - - - XenkoShaderKeyGenerator - SSLRCombinePass.cs - - - XenkoShaderKeyGenerator - SSLRCommon.cs - - - XenkoShaderKeyGenerator - SSLRDepthPass.cs - - - XenkoShaderKeyGenerator - SSLRRayTracePass.cs - - - True - True - True - RangeCompressorShader.xksl - - - True - True - True - RangeDecompressorShader.xksl - - - True - True - True - PostEffectBoundingRay.xksl - - - True - True - True - AdditiveLightShader.xksl - - - True - True - True - LightShaftsShader.xksl - - - True - True - True - VolumeMinMaxShader.xksl - - - IMaterialSpecularMicrofacetEnvironmentFunction.xksl - True - True - True - - - MaterialSpecularMicrofacetEnvironmentGGXLUT.xksl - True - True - True - - - MaterialSpecularMicrofacetEnvironmentThinGlass.xksl - True - True - True - - - MaterialSpecularMicrofacetFresnelThinGlass.xksl - True - True - True - - - MaterialSpecularMicrofacetEnvironmentGGXPolynomial.xksl - True - True - True - - - MaterialTransmittanceReflectanceStream.xksl - True - True - True - - - MaterialSurfaceTransmittanceShading.xksl - True - True - True - - - MaterialSurfaceNormalStreamShading.xksl - True - True - True - - - MaterialSurfaceShadingDiffuseHair.xksl - True - True - True - - - True - True - True - GlobalVR.xksl - - - True - True - True - ShadowMapCasterAlphaDiscard.xksl - - - GBufferOutputSubsurfaceScatteringMaterialIndex.xksl - True - True - True - - - True - True - True - ShadowMapCasterNoPixelShader.xksl - - - True - True - True - IMaterialSubsurfaceScatteringScatteringProfile.xksl - - - True - True - True - MaterialSubsurfaceScatteringScatteringProfileCustomUniform.xksl - - - True - True - True - MaterialSubsurfaceScatteringScatteringProfileCustomVarying.xksl - - - True - True - True - MaterialSubsurfaceScatteringScatteringProfileSkin.xksl - - - True - True - True - MaterialHairLightAttenuationFunctionDirectional.xksl - - - True - True - True - Dither.xksl - - - True - True - True - GBuffer.xksl - - - SphericalHarmonicsUtils.xksl - True - True - True - - - BakeLightProbeShader.xksl - True - True - True - - - LightProbeShader.xksl - True - True - True - - - XenkoBakeLightProbeEffect.xkfx - True - True - True - - - XenkoShaderKeyGenerator - BackgroundShader.cs - - - XenkoShaderKeyGenerator - MSAAResolverShader.cs - - - XenkoShaderKeyGenerator - BackgroundVelocity.cs - - - XenkoShaderKeyGenerator - BackgroundVelocityEffect.cs - - - XenkoShaderKeyGenerator - MeshVelocity.cs - - - XenkoShaderKeyGenerator - VelocityOutput.cs - - - XenkoShaderKeyGenerator - VelocityStream.cs - - - XenkoShaderKeyGenerator - TemporalAntiAliasShader.cs - - - XenkoShaderKeyGenerator - AdditiveLightEffect.cs - - - XenkoShaderKeyGenerator - LightShaftsEffect.cs - - - XenkoShaderKeyGenerator - SSLRResolvePass.cs - - - XenkoShaderKeyGenerator - SSLRTemporalPass.cs - - - XenkoShaderKeyGenerator - RangeCompressorShader.cs - - - XenkoShaderKeyGenerator - RangeDecompressorShader.cs - - - - - XenkoShaderKeyGenerator - Dither2.cs - - - XenkoShaderKeyGenerator - AdditiveLightShader.cs - - - XenkoShaderKeyGenerator - LightShaftsShader.cs - - - XenkoShaderKeyGenerator - PostEffectBoundingRay.cs - - - XenkoShaderKeyGenerator - VolumeMinMaxShader.cs - - - LightClusteredPointGroup.cs - XenkoShaderKeyGenerator - - - LightClusteredSpotGroup.cs - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - LightSpotAttenuationDefault.cs - - - XenkoShaderKeyGenerator - LightSpotAttenuationRectangular.cs - - - LightSpotGroup.cs - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - SpotLightDataInternalShader.cs - - - XenkoShaderKeyGenerator - TextureProjectionCommon.cs - - - XenkoShaderKeyGenerator - TextureProjectionFilterDefault.cs - - - XenkoShaderKeyGenerator - TextureProjectionGroup.cs - - - XenkoShaderKeyGenerator - TextureProjectionReceiverBase.cs - - - XenkoShaderKeyGenerator - TextureProjectionReceiverSpot.cs - - - XenkoShaderKeyGenerator - MaterialCelShadingLightRamp2.cs - - - True - True - True - MaterialCelShadingLightRamp.xksl - - - XenkoShaderKeyGenerator - AmbientOcclusionBlurShader.cs - - - XenkoShaderKeyGenerator - AmbientOcclusionRawAOEffect.cs - - - XenkoShaderKeyGenerator - ApplyAmbientOcclusionShader.cs - - - XenkoShaderKeyGenerator - AmbientOcclusionRawAOShader.cs - - - XenkoShaderKeyGenerator - AmbientOcclusionBlurEffect1.cs - - - True - True - True - AmbientOcclusionBlurEffect.xkfx - - - True - True - True - AmbientOcclusionBlurShader.xksl - - - True - True - True - AmbientOcclusionRawAOEffect.xkfx - - - True - True - True - ApplyAmbientOcclusionShader.xksl - - - True - True - True - AmbientOcclusionRawAOShader.xksl - - - True - True - True - IMaterialHairDirectionFunction.xksl - - - True - True - True - IMaterialHairLightAttenuationFunction.xksl - - - True - True - True - MaterialHairLightAttenuationFunctionNone.xksl - - - True - True - True - IMaterialHairShadowingFunction.xksl - - - True - True - True - MaterialHairDirectionFunctionBitangent.xksl - - - True - True - True - MaterialHairDirectionFunctionTangent.xksl - - - True - True - True - MaterialHairShadowingFunctionScattering.xksl - - - True - True - True - MaterialHairShadowingFunctionShadowing.xksl - - - True - True - True - MaterialHairShared.xksl - - - True - True - True - MaterialSurfaceShadingSpecularHair.xksl - - - True - True - True - FXAAShaderEffect.xkfx - - - LuminanceToChannelShader.xksl - True - True - True - - - True - True - True - ToneMapHejl2OperatorShader.xksl - - - CombineFrontCoCShader.xksl - True - True - - - DirectLightGroupPerDraw.xksl - True - True - True - - - DirectLightGroupPerView.xksl - True - True - True - - - LightClusteredSpotGroup.xksl - True - True - True - - - LightClustered.xksl - True - True - True - - - LightDirectional.xksl - True - True - True - - - LightSpot.xksl - True - True - True - - - LightPoint.xksl - True - True - True - - - LightClusteredPointGroup.xksl - True - True - True - - - True - True - True - ComputeColorThreshold.xksl - - - ComputeColorFromStream.xksl - True - True - True - - - Properties.tt - True - True - - - True - True - True - ShadowMapCasterCubeMap.xkfx - - - True - True - True - ShadowMapCasterCubeMapProjection.xksl - - - True - True - True - ShadowMapCasterParaboloid.xkfx - - - True - True - True - ShadowMapCasterParaboloidProjection.xksl - - - True - True - True - ShadowMapReceiverPointCubeMap.xksl - - - True - True - True - ShadowMapReceiverPointParaboloid.xksl - - - ComputeSphericalHarmonics.xksl - True - True - True - - - True - True - True - SkyboxShaderBase.xksl - - - True - True - True - SkyboxShaderCubemap.xksl - - - True - True - True - SkyboxShaderTexture.xksl - - - True - True - True - SubsurfaceScatteringBlurEffect.xkfx - - - True - True - True - SubsurfaceScatteringBlurShader.xksl - - - XenkoShaderKeyGenerator - GBuffer1.cs - - - XenkoShaderKeyGenerator - SphericalHarmonicsUtils.cs - - - XenkoShaderKeyGenerator - BakeLightProbeShader.cs - - - XenkoShaderKeyGenerator - LightProbeShader.cs - - - XenkoShaderKeyGenerator - XenkoBakeLightProbeEffect.cs - - - XenkoShaderKeyGenerator - DirectLightGroupPerDraw.cs - - - XenkoShaderKeyGenerator - DirectLightGroupPerView.cs - - - XenkoShaderKeyGenerator - LightClustered.cs - - - XenkoShaderKeyGenerator - LightClusteredSpotGroup.cs - - - XenkoShaderKeyGenerator - LightDirectional1.cs - - - XenkoShaderKeyGenerator - LightSpot1.cs - - - XenkoShaderKeyGenerator - LightPoint1.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureScaledOffsetDynamicSamplerRandomUV.cs - - - XenkoShaderKeyGenerator - ComputeColorThreshold.cs - - - XenkoShaderKeyGenerator - LightClusteredPointGroup.cs - - - XenkoShaderKeyGenerator - IMaterialHairDirectionFunction1.cs - - - XenkoShaderKeyGenerator - IMaterialHairDiscardFunction1.cs - - - XenkoShaderKeyGenerator - MaterialHairDiscardFunctionOpaquePass1.cs - - - XenkoShaderKeyGenerator - MaterialHairDiscardFunctionTransparentPass1.cs - - - XenkoShaderKeyGenerator - IMaterialHairLightAttenuationFunction1.cs - - - XenkoShaderKeyGenerator - MaterialHairLightAttenuationFunctionDirectional2.cs - - - XenkoShaderKeyGenerator - MaterialHairLightAttenuationFunctionNone1.cs - - - XenkoShaderKeyGenerator - IMaterialHairShadowingFunction1.cs - - - XenkoShaderKeyGenerator - MaterialHairDirectionFunctionBitangent1.cs - - - XenkoShaderKeyGenerator - MaterialHairDirectionFunctionTangent1.cs - - - XenkoShaderKeyGenerator - MaterialHairShadowingFunctionScattering1.cs - - - XenkoShaderKeyGenerator - MaterialHairShadowingFunctionShadowing1.cs - - - XenkoShaderKeyGenerator - MaterialHairShared1.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceShadingDiffuseHair.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceShadingSpecularHair.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceSubsurfaceScatteringShading.cs - - - XenkoShaderKeyGenerator - GBufferOutputSubsurfaceScatteringMaterialIndex.cs - - - XenkoShaderKeyGenerator - IMaterialSubsurfaceScatteringScatteringProfile1.cs - - - XenkoShaderKeyGenerator - MaterialSubsurfaceScatteringScatteringProfileCustomUniform1.cs - - - XenkoShaderKeyGenerator - MaterialSubsurfaceScatteringScatteringProfileCustomVarying1.cs - - - XenkoShaderKeyGenerator - MaterialSubsurfaceScatteringScatteringProfileSkin1.cs - - - XenkoShaderKeyGenerator - SubsurfaceScatteringBlurEffect.cs - - - XenkoShaderKeyGenerator - SubsurfaceScatteringBlurShader.cs - - - XenkoShaderKeyGenerator - ComputeSphericalHarmonics.cs - - - XenkoShaderKeyGenerator - GBufferOutputNormals.cs - - - XenkoShaderKeyGenerator - GBufferOutputSpecularColorRoughness.cs - - - XenkoShaderKeyGenerator - IMaterialSpecularMicrofacetEnvironmentFunction.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetEnvironmentGGXLUT.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetEnvironmentThinGlass.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetFresnelThinGlass.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetEnvironmentGGXPolynomial.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceDiffuseMetalFlakes.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceGlossinessMapMetalFlakes.cs - - - XenkoShaderKeyGenerator - MaterialTransmittanceReflectanceStream.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceTransmittanceShading.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceNormalStreamShading.cs - - - XenkoShaderKeyGenerator - GlobalVR.cs - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - ShadowMapCasterAlphaDiscard.cs - - - XenkoShaderKeyGenerator - ShadowMapCasterCubeMap.cs - - - XenkoShaderKeyGenerator - ShadowMapCasterCubeMapProjection1.cs - - - XenkoShaderKeyGenerator - ShadowMapCasterNoPixelShader.cs - - - XenkoShaderKeyGenerator - ShadowMapCasterParaboloid1.cs - - - XenkoShaderKeyGenerator - ShadowMapCasterParaboloidProjection1.cs - - - XenkoShaderKeyGenerator - ShadowMapReceiverPointCubeMap.cs - - - XenkoShaderKeyGenerator - ShadowMapReceiverPointParaboloid.cs - - - XenkoShaderKeyGenerator - SkyboxShaderBase.cs - - - XenkoShaderKeyGenerator - SkyboxShaderCubemap.cs - - - XenkoShaderKeyGenerator - SkyboxShaderTexture.cs - - - XenkoShaderKeyGenerator - HighlightShader.cs - - - True - True - True - HighlightShader.xksl - - - Picking.xkfx - True - True - True - - - PickingShader.xksl - True - True - True - - - DepthMinMaxShader.xksl - True - True - True - - - DepthMinMaxEffect.xkfx - True - True - True - - - LightPointGroup.xksl - True - True - True - - - LightUtil.xksl - True - True - True - - - LightSpotGroup.xksl - True - True - True - - - LightSkyboxEffect.xkfx - True - True - True - - - MaterialFrontBackBlendShader.xksl - True - True - True - - - MaterialSurfaceDiffuse.xksl - True - True - True - - - MaterialSurfaceDiffuseSpecularAlphaBlendColor.xksl - True - True - True - - - XenkoWireframeShadingEffect.xkfx - True - True - True - - - ShadowMapReceiverBase.xksl - True - True - True - - - ShadowMapReceiverSpot.xksl - True - True - True - - - DirectLightGroupFixed.xksl - True - True - - - BloomAfterimageCombineShader.xksl - True - True - True - - - BloomAfterimageShader.xksl - True - True - True - - - CombineFrontCoCEffect.xkfx - True - True - True - - - True - True - True - PointDepth.xksl - - - True - True - True - ThresholdAlphaCoCFront.xksl - - - True - True - True - ComputeColorSubtract.xksl - - - FilmGrainShader.xksl - True - True - True - - - ThresholdAlphaCoC.xksl - True - True - True - - - True - True - True - VignettingShader.xksl - - - True - True - True - IMaterialSurfaceDomain.xksl - - - True - True - True - IStreamInitializer.xksl - - - True - True - True - MaterialDisplacementStream.xksl - - - True - True - True - MaterialDomainStream.xksl - - - True - True - True - MaterialStreamAdditiveBlend.xksl - - - True - True - True - MaterialSurfaceDisplacement.xksl - - - True - True - True - MaterialSurfaceDomainStageCompositor.xksl - - - True - True - True - MaterialTessellationStream.xksl - - - BRDFMicrofacet.xksl - True - True - True - - - ComputeColorAdd3ds.xksl - True - True - True - - - ComputeColorDarken3ds.xksl - True - True - True - - - ComputeColorDifference3ds.xksl - True - True - True - - - ComputeColorLighten3ds.xksl - True - True - True - - - ComputeColorMask3ds.xksl - True - True - True - - - ComputeColorMultiply3ds.xksl - True - True - True - - - ComputeColorOver3ds.xksl - True - True - True - - - ComputeColorOverlay3ds.xksl - True - True - True - - - ComputeColorSubtract3ds.xksl - True - True - True - - - ComputeColor.xksl - True - True - True - - - ComputeColor3.xksl - True - True - True - - - ComputeColorAdd.xksl - True - True - True - - - ComputeColorAdd3.xksl - True - True - True - - - ComputeColorAverage.xksl - True - True - True - - - ComputeColorCave.xksl - True - True - True - - - ComputeColorColor.xksl - True - True - True - - - ComputeColorColorBurn.xksl - True - True - True - - - ComputeColorColorDodge.xksl - True - True - True - - - ComputeColorConstantColorLink.xksl - True - True - True - - - ComputeColorConstantFloatLink.xksl - True - True - True - - - ComputeColorConstantLink.xksl - True - True - True - - - ComputeColorDesaturate.xksl - True - True - True - - - ComputeColorDivide.xksl - True - True - True - - - ComputeColorExclusion.xksl - True - True - True - - - ComputeColorFixed.xksl - True - True - True - - - ComputeColorHardLight.xksl - True - True - True - - - ComputeColorHardMix.xksl - True - True - True - - - ComputeColorHue.xksl - True - True - True - - - ComputeColorIlluminate.xksl - True - True - True - - - ComputeColorIn.xksl - True - True - True - - - ComputeColorLerpAlpha.xksl - True - True - True - - - ComputeColorLinearBurn.xksl - True - True - True - - - ComputeColorLinearDodge.xksl - True - True - True - - - ComputeColorMask.xksl - True - True - True - - - ComputeColorMultiply.xksl - True - True - True - - - ComputeColorOne.xksl - True - True - True - - - ComputeColorOut.xksl - True - True - True - - - ComputeColorOutdoor.xksl - True - True - True - - - ComputeColorOverlay.xksl - True - True - True - - - ComputeColorParameter.xksl - True - True - True - - - ComputeColorPinLight.xksl - True - True - True - - - ComputeColorSaturate.xksl - True - True - True - - - ComputeColorSaturation.xksl - True - True - True - - - ComputeColorScaler.xksl - True - True - True - - - ComputeColorScreen.xksl - True - True - True - - - ComputeColorSoftLight.xksl - True - True - True - - - ComputeColorStream.xksl - True - True - True - - - ComputeColorSubstituteAlpha.xksl - True - True - True - - - ComputeColorSubstituteAlphaWithColor.xksl - True - True - True - - - ComputeColorSynthetic.xksl - True - True - True - - - ComputeColorTexture.xksl - True - True - True - - - ComputeColorTextureDynamicScaledOffset.xksl - True - True - True - - - ComputeColorTextureLodSampler.xksl - True - True - True - - - ComputeColorTextureLodScaledOffsetDynamicSampler.xksl - True - True - True - - - ComputeColorTextureLodScaledOffsetSampler.xksl - True - True - True - - - ComputeColorTextureLodScaledSampler.xksl - True - True - True - - - ComputeColorTextureRepeat.xksl - True - True - True - - - ComputeColorTextureSampler.xksl - True - True - True - - - ComputeColorTextureScaled.xksl - True - True - True - - - ComputeColorTextureScaledOffset.xksl - True - True - True - - - ComputeColorTextureScaledOffsetDynamicSampler.xksl - True - True - True - - - ComputeColorTextureScaledOffsetSampler.xksl - True - True - True - - - ComputeColorTextureScaledSampler.xksl - True - True - True - - - ComputeColorValue.xksl - True - True - True - - - ComputeColorAddMaya.xksl - True - True - True - - - ComputeColorDarkenMaya.xksl - True - True - True - - - ComputeColorDifferenceMaya.xksl - True - True - True - - - ComputeColorLightenMaya.xksl - True - True - True - - - ComputeColorMultiplyMaya.xksl - True - True - True - - - ComputeColorOverMaya.xksl - True - True - True - - - ComputeColorSubtractMaya.xksl - True - True - True - - - ComputeEffectShader.xkfx - True - True - True - - - ComputeShaderBase.xksl - True - True - True - - - Hammersley.xksl - True - True - True - - - ImportanceSamplingGGX.xksl - True - True - True - - - RadiancePrefilteringGGXEffect.xkfx - True - True - True - - - RadiancePrefilteringGGXShader.xksl - True - True - True - - - LambertianPrefilteringSH.xkfx - True - True - True - - - LambertianPrefilteringSHPass1.xksl - True - True - True - - - LambertianPrefilteringSHPass2.xksl - True - True - True - - - ColorBase.xksl - True - True - True - - - DynamicSampler.xksl - True - True - True - - - DynamicTexture.xksl - True - True - True - - - DynamicTextureCube.xksl - True - True - True - - - DynamicTextureStream.xksl - True - True - True - - - NormalBase.xksl - True - True - True - - - NormalFromMesh.xksl - True - True - True - - - NormalFromNormalMapping.xksl - True - True - True - - - NormalStream.xksl - True - True - True - - - PositionHStream4.xksl - True - True - True - - - PositionStream.xksl - True - True - True - - - PositionStream2.xksl - True - True - True - - - PositionStream4.xksl - True - True - True - - - PositionVertexTransform.xksl - True - True - True - - - ScreenPositionBase.xksl - True - True - True - - - ShadingBase.xksl - True - True - True - - - ShadingColor.xksl - True - True - True - - - True - True - True - FlareArtifactEffect.xkfx - - - True - True - True - FlareArtifactShader.xksl - - - True - True - True - FlareReplicate.xksl - - - True - True - True - LightStreakEffect.xkfx - - - True - True - True - LightStreakShader.xksl - - - ComputeColorMaterialAlphaBlend.xksl - True - True - True - - - MaterialSurfaceTransparentAlphaDiscard.xksl - True - True - True - - - XenkoForwardShadingEffect.xkfx - True - True - True - - - XenkoEffectBase.xkfx - True - True - True - - - CameraCube.xksl - True - True - True - - - FXAAShader.xksl - True - True - True - - - BrightFilterShader.xksl - True - True - True - - - ColorCombinerEffect.xkfx - True - True - True - - - ColorCombinerShader.xksl - True - True - True - - - ColorTransformGroupEffect.xkfx - True - True - True - - - ColorTransformGroupShader.xksl - True - True - True - - - ColorTransformShader.xksl - True - True - True - - - ToneMapCommonOperatorShader.xksl - True - True - True - - - ToneMapDragoOperatorShader.xksl - True - True - True - - - ToneMapEffect.xkfx - True - True - True - - - ToneMapExponentialOperatorShader.xksl - True - True - True - - - ToneMapHejlDawsonOperatorShader.xksl - True - True - True - - - ToneMapLogarithmicOperatorShader.xksl - True - True - True - - - ToneMapMikeDayOperatorShader.xksl - True - True - True - - - ToneMapOperatorShader.xksl - True - True - True - - - ToneMapReinhardOperatorShader.xksl - True - True - True - - - ToneMapShader.xksl - True - True - True - - - ToneMapU2FilmicOperatorShader.xksl - True - True - True - - - McIntoshCombineShader.xksl - True - True - True - - - McIntoshOptimizedEffect.xkfx - True - True - True - - - McIntoshOptimizedShader.xksl - True - True - True - - - TripleRhombiCombineShader.xksl - True - True - True - - - CircleOfConfusion.xksl - True - True - True - - - CoCLinearDepthShader.xksl - True - True - True - - - CoCMapBlurEffect.xkfx - True - True - True - - - CoCMapBlurShader.xksl - True - True - True - - - CombineLevelsFromCoCEffect.xkfx - True - True - True - - - CombineLevelsFromCoCShader.xksl - True - True - True - - - DepthAwareDirectionalBlurEffect.xkfx - True - True - True - - - DepthAwareDirectionalBlurShader.xksl - True - True - True - - - DepthAwareDirectionalBlurUtil.xksl - True - True - True - - - GaussianBlurEffect.xkfx - True - True - True - - - GaussianBlurShader.xksl - True - True - True - - - ImageEffectShader.xksl - True - True - True - - - ImageScalerEffect.xkfx - True - True - True - - - ImageScalerShader.xksl - True - True - True - - - LuminanceLogShader.xksl - True - True - True - - - LuminanceUtils.xksl - True - True - True - - - SphericalHarmonicsBase.xksl - True - True - True - - - SphericalHarmonicsParameters.xkfx - True - True - True - - - SphericalHarmonicsRenderer.xksl - True - True - True - - - SphericalHarmonicsRendererEffect.xkfx - True - True - True - - - DirectLightGroup.xksl - True - True - True - - - DirectLightGroupArray.xksl - True - True - True - - - EnvironmentLight.xksl - True - True - True - - - EnvironmentLightArray.xksl - True - True - True - - - LightDirectionalGroup.xksl - True - True - True - - - LightSimpleAmbient.xksl - True - True - True - - - LightSkyboxShader.xksl - True - True - True - - - LightStream.xksl - True - True - True - - - IMaterialSpecularMicrofacetFresnelFunction.xksl - True - True - True - - - IMaterialSpecularMicrofacetNormalDistributionFunction.xksl - True - True - True - - - IMaterialSpecularMicrofacetVisibilityFunction.xksl - True - True - True - - - IMaterialStreamBlend.xksl - True - True - True - - - IMaterialSurface.xksl - True - True - True - - - IMaterialSurfacePixel.xksl - True - True - True - - - IMaterialSurfaceShading.xksl - True - True - True - - - IMaterialSurfaceVertex.xksl - True - True - True - - - MaterialPixelShadingStream.xksl - True - True - True - - - MaterialPixelStream.xksl - True - True - True - - - MaterialSpecularMicrofacetFresnelNone.xksl - True - True - True - - - MaterialSpecularMicrofacetFresnelSchlick.xksl - True - True - True - - - MaterialSpecularMicrofacetNormalDistributionBeckmann.xksl - True - True - True - - - MaterialSpecularMicrofacetNormalDistributionBlinnPhong.xksl - True - True - True - - - MaterialSpecularMicrofacetNormalDistributionGGX.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilityCookTorrance.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilityImplicit.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilityKelemen.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilityNeumann.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilitySmithBeckmann.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.xksl - True - True - True - - - MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.xksl - True - True - True - - - MaterialStream.xksl - True - True - True - - - MaterialStreamLinearBlend.xksl - True - True - True - - - MaterialStreamNormalBlend.xksl - True - True - True - - - MaterialSurfaceArray.xksl - True - True - True - - - MaterialSurfaceShadingBlend.xksl - True - True - True - - - MaterialSurfaceEmissiveShading.xksl - True - True - True - - - MaterialSurfaceGlossinessMap.xksl - True - True - True - - - MaterialSurfaceLightingAndShading.xksl - True - True - True - - - MaterialSurfaceMetalness.xksl - True - True - True - - - MaterialSurfaceNormalMap.xksl - True - True - True - - - MaterialSurfacePixelStageCompositor.xksl - True - True - True - - - MaterialSurfaceSetStreamFromComputeColor.xksl - True - True - True - - - MaterialSurfaceShadingDiffuseLambert.xksl - True - True - True - - - MaterialSurfaceShadingSpecularBlinnPhong.xksl - True - True - True - - - MaterialSurfaceShadingSpecularMicrofacet.xksl - True - True - True - - - MaterialSurfaceStreamsBlend.xksl - True - True - True - - - MaterialSurfaceStreamShading.xksl - True - True - True - - - MaterialSurfaceVertexDisplacement.xksl - True - True - True - - - MaterialSurfaceVertexStageCompositor.xksl - True - True - True - - - MaterialVertexStream.xksl - True - True - True - - - ShadowGroup.xksl - True - True - True - - - ShadowMapReceiverDirectional.xksl - True - True - True - - - ShadowMapCaster.xkfx - True - True - True - - - ShadowMapCasterVsm.xksl - True - True - True - - - ShadowMapCommon.xksl - True - True - True - - - ShadowMapFilterBase.xksl - True - True - True - - - ShadowMapFilterDefault.xksl - True - True - True - - - ShadowMapFilterPcf.xksl - True - True - True - - - ShadowMapFilterVsm.xksl - True - True - True - - - ShadowMapGroup.xksl - True - True - True - - - ShadowStream.xksl - True - True - True - - - NormalMeshSkinning.xksl - True - True - True - - - NormalVSSkinningFromMesh.xksl - True - True - True - - - NormalVSSkinningNormalMapping.xksl - True - True - True - - - TangentMeshSkinning.xksl - True - True - True - - - TransformationSkinning.xksl - True - True - True - - - True - True - True - CubemapUtils.xksl - - - IComputeEnvironmentColor.xksl - True - True - True - - - LevelCubeMapEnvironmentColor.xksl - True - True - True - - - RoughnessCubeMapEnvironmentColor.xksl - True - True - True - - - SkyboxStream.xksl - True - True - True - - - SphericalHarmonicsEnvironmentColor.xksl - True - True - True - - - True - True - True - TessellationAE2.xksl - - - True - True - True - TessellationAE3.xksl - - - True - True - True - TessellationAE4.xksl - - - True - True - True - TessellationBase.xksl - - - True - True - True - TessellationFlat.xksl - - - True - True - True - TessellationPN.xksl - - - TransformationBase.xksl - True - True - True - - - TransformationMatrix.xksl - True - True - True - - - TransformationWAndVP.xksl - True - True - True - - - TransformationWVP.xksl - True - True - True - - - TransformationZero.xksl - True - True - True - - - BlendUtils.xksl - True - True - True - - - ModelComponentPickingShader.xksl - True - True - True - - - DepthBase.xksl - True - True - True - - - FlattenLayers.xksl - True - True - True - - - HSVUtils.xksl - True - True - True - - - Math.xksl - True - True - True - - - NormalPack.xksl - True - True - True - - - NormalUtil.xksl - True - True - True - - - ModelComponentPickingEffect.xkfx - True - True - True - - - SwapUV.xksl - True - True - True - - - Utilities.xksl - True - True - True - - - Camera.xksl - True - True - True - - - Global.xksl - True - True - True - - - True - True - True - Transformation.xksl - - - - - XenkoShaderKeyGenerator - BRDFMicrofacet.cs - - - XenkoShaderKeyGenerator - RadiancePrefilteringGGXNoComputeEffect.cs - - - XenkoShaderKeyGenerator - RadiancePrefilteringGGXNoComputeShader.cs - - - XenkoShaderKeyGenerator - LambertianPrefilteringSHNoComputeEffect.cs - - - XenkoShaderKeyGenerator - LambertianPrefilteringSHNoComputePass1.cs - - - XenkoShaderKeyGenerator - LambertianPrefilteringSHNoComputePass2.cs - - - XenkoShaderKeyGenerator - LuminanceToChannelShader.cs - - - XenkoShaderKeyGenerator - ToneMapHejl2OperatorShader.cs - - - XenkoShaderKeyGenerator - ComputeColorAdd3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorDarken3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorDifference3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorLighten3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorMask3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorMultiply3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorOver3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorOverlay3ds.cs - - - XenkoShaderKeyGenerator - ComputeColorSubtract3ds.cs - - - XenkoShaderKeyGenerator - ComputeColor.cs - - - XenkoShaderKeyGenerator - ComputeColor3.cs - - - XenkoShaderKeyGenerator - ComputeColorAdd.cs - - - XenkoShaderKeyGenerator - ComputeColorAdd3.cs - - - XenkoShaderKeyGenerator - ComputeColorAverage.cs - - - XenkoShaderKeyGenerator - ComputeColorCave.cs - - - XenkoShaderKeyGenerator - ComputeColorColor.cs - - - XenkoShaderKeyGenerator - ComputeColorColorBurn.cs - - - XenkoShaderKeyGenerator - ComputeColorColorDodge.cs - - - XenkoShaderKeyGenerator - ComputeColorConstantColorLink.cs - - - XenkoShaderKeyGenerator - ComputeColorConstantFloatLink.cs - - - XenkoShaderKeyGenerator - ComputeColorConstantLink.cs - - - XenkoShaderKeyGenerator - ComputeColorDesaturate.cs - - - XenkoShaderKeyGenerator - ComputeColorDivide.cs - - - XenkoShaderKeyGenerator - ComputeColorExclusion.cs - - - XenkoShaderKeyGenerator - ComputeColorFixed.cs - - - XenkoShaderKeyGenerator - ComputeColorHardLight.cs - - - XenkoShaderKeyGenerator - ComputeColorHardMix.cs - - - XenkoShaderKeyGenerator - ComputeColorHue.cs - - - XenkoShaderKeyGenerator - ComputeColorIlluminate.cs - - - XenkoShaderKeyGenerator - ComputeColorIn.cs - - - XenkoShaderKeyGenerator - ComputeColorLerpAlpha.cs - - - XenkoShaderKeyGenerator - ComputeColorLinearBurn.cs - - - XenkoShaderKeyGenerator - ComputeColorLinearDodge.cs - - - XenkoShaderKeyGenerator - ComputeColorMask.cs - - - XenkoShaderKeyGenerator - ComputeColorMultiply.cs - - - XenkoShaderKeyGenerator - ComputeColorOne.cs - - - XenkoShaderKeyGenerator - ComputeColorOut.cs - - - XenkoShaderKeyGenerator - ComputeColorOutdoor.cs - - - XenkoShaderKeyGenerator - ComputeColorOverlay.cs - - - XenkoShaderKeyGenerator - ComputeColorParameter.cs - - - XenkoShaderKeyGenerator - ComputeColorPinLight.cs - - - XenkoShaderKeyGenerator - ComputeColorSaturate.cs - - - XenkoShaderKeyGenerator - ComputeColorSaturation.cs - - - XenkoShaderKeyGenerator - ComputeColorScaler.cs - - - XenkoShaderKeyGenerator - ComputeColorScreen.cs - - - XenkoShaderKeyGenerator - ComputeColorSoftLight.cs - - - XenkoShaderKeyGenerator - ComputeColorStream.cs - - - XenkoShaderKeyGenerator - ComputeColorSubstituteAlpha.cs - - - XenkoShaderKeyGenerator - ComputeColorSubstituteAlphaWithColor.cs - - - XenkoShaderKeyGenerator - ComputeColorSubtract1.cs - - - XenkoShaderKeyGenerator - ComputeColorSynthetic.cs - - - XenkoShaderKeyGenerator - ComputeColorTexture.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureDynamicScaledOffset.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureLodSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureLodScaledOffsetDynamicSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureLodScaledOffsetSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureLodScaledSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureRepeat.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorFromStream.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureScaled.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureScaledOffset.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureScaledOffsetDynamicSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureScaledOffsetSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorTextureScaledSampler.cs - - - XenkoShaderKeyGenerator - ComputeColorValue.cs - - - XenkoShaderKeyGenerator - ComputeColorAddMaya.cs - - - XenkoShaderKeyGenerator - ComputeColorDarkenMaya.cs - - - XenkoShaderKeyGenerator - ComputeColorDifferenceMaya.cs - - - XenkoShaderKeyGenerator - ComputeColorLightenMaya.cs - - - XenkoShaderKeyGenerator - ComputeColorMultiplyMaya.cs - - - XenkoShaderKeyGenerator - ComputeColorOverMaya.cs - - - XenkoShaderKeyGenerator - ComputeColorSubtractMaya.cs - - - XenkoShaderKeyGenerator - ComputeEffectShader1.cs - - - XenkoShaderKeyGenerator - ComputeShaderBase.cs - - - XenkoShaderKeyGenerator - Hammersley.cs - - - XenkoShaderKeyGenerator - ImportanceSamplingGGX.cs - - - XenkoShaderKeyGenerator - RadiancePrefilteringGGXEffect.cs - - - XenkoShaderKeyGenerator - RadiancePrefilteringGGXShader.cs - - - XenkoShaderKeyGenerator - LambertianPrefilteringSH1.cs - - - XenkoShaderKeyGenerator - LambertianPrefilteringSHPass1.cs - - - XenkoShaderKeyGenerator - LambertianPrefilteringSHPass2.cs - - - XenkoShaderKeyGenerator - ColorBase.cs - - - XenkoShaderKeyGenerator - DynamicSampler.cs - - - XenkoShaderKeyGenerator - DynamicTexture.cs - - - XenkoShaderKeyGenerator - DynamicTextureCube.cs - - - XenkoShaderKeyGenerator - DynamicTextureStream.cs - - - XenkoShaderKeyGenerator - NormalBase.cs - - - XenkoShaderKeyGenerator - NormalFromMesh.cs - - - XenkoShaderKeyGenerator - NormalFromNormalMapping.cs - - - XenkoShaderKeyGenerator - NormalStream.cs - - - XenkoShaderKeyGenerator - PositionHStream4.cs - - - XenkoShaderKeyGenerator - PositionStream.cs - - - XenkoShaderKeyGenerator - PositionStream2.cs - - - XenkoShaderKeyGenerator - PositionStream4.cs - - - XenkoShaderKeyGenerator - PositionVertexTransform.cs - - - XenkoShaderKeyGenerator - ScreenPositionBase.cs - - - XenkoShaderKeyGenerator - ShadingBase.cs - - - XenkoShaderKeyGenerator - ShadingColor.cs - - - XenkoShaderKeyGenerator - FXAAShaderEffect.cs - - - - XenkoShaderKeyGenerator - FXAAShader.cs - - - XenkoShaderKeyGenerator - BloomAfterimageCombineShader.cs - - - XenkoShaderKeyGenerator - BloomAfterimageShader.cs - - - XenkoShaderKeyGenerator - BrightFilterShader.cs - - - XenkoShaderKeyGenerator - ColorCombinerEffect.cs - - - XenkoShaderKeyGenerator - ColorCombinerShader.cs - - - XenkoShaderKeyGenerator - ColorTransformGroupEffect.cs - - - XenkoShaderKeyGenerator - ColorTransformGroupShader.cs - - - XenkoShaderKeyGenerator - ColorTransformShader.cs - - - XenkoShaderKeyGenerator - FilmGrainShader.cs - - - XenkoShaderKeyGenerator - ToneMapCommonOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapDragoOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapEffect.cs - - - XenkoShaderKeyGenerator - ToneMapExponentialOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapHejlDawsonOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapLogarithmicOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapMikeDayOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapReinhardOperatorShader.cs - - - XenkoShaderKeyGenerator - ToneMapShader.cs - - - XenkoShaderKeyGenerator - ToneMapU2FilmicOperatorShader.cs - - - XenkoShaderKeyGenerator - McIntoshCombineShader.cs - - - XenkoShaderKeyGenerator - McIntoshOptimizedEffect.cs - - - XenkoShaderKeyGenerator - McIntoshOptimizedShader.cs - - - XenkoShaderKeyGenerator - TripleRhombiCombineShader.cs - - - XenkoShaderKeyGenerator - CombineFrontCoCShader.cs - - - XenkoShaderKeyGenerator - CombineFrontCoCEffect.cs - - - XenkoShaderKeyGenerator - PointDepth.cs - - - XenkoShaderKeyGenerator - ThresholdAlphaCoC.cs - - - XenkoShaderKeyGenerator - CircleOfConfusion.cs - - - XenkoShaderKeyGenerator - CoCLinearDepthShader.cs - - - XenkoShaderKeyGenerator - CoCMapBlurEffect.cs - - - XenkoShaderKeyGenerator - CoCMapBlurShader.cs - - - XenkoShaderKeyGenerator - CombineLevelsFromCoCEffect.cs - - - XenkoShaderKeyGenerator - CombineLevelsFromCoCShader.cs - - - XenkoShaderKeyGenerator - DepthAwareDirectionalBlurEffect.cs - - - XenkoShaderKeyGenerator - DepthAwareDirectionalBlurShader.cs - - - XenkoShaderKeyGenerator - DepthAwareDirectionalBlurUtil.cs - - - XenkoShaderKeyGenerator - ThresholdAlphaCoCFront.cs - - - XenkoShaderKeyGenerator - GaussianBlurEffect.cs - - - XenkoShaderKeyGenerator - GaussianBlurShader.cs - - - XenkoShaderKeyGenerator - ImageEffectShader1.cs - - - XenkoShaderKeyGenerator - DepthMinMaxShader.cs - - - XenkoShaderKeyGenerator - DepthMinMaxEffect.cs - - - XenkoShaderKeyGenerator - ImageScalerEffect.cs - - - XenkoShaderKeyGenerator - ImageScalerShader.cs - - - XenkoShaderKeyGenerator - FlareArtifactEffect.cs - - - XenkoShaderKeyGenerator - FlareArtifactShader.cs - - - XenkoShaderKeyGenerator - FlareReplicate.cs - - - XenkoShaderKeyGenerator - LightStreakEffect.cs - - - XenkoShaderKeyGenerator - LightStreakShader.cs - - - XenkoShaderKeyGenerator - LuminanceLogShader.cs - - - XenkoShaderKeyGenerator - LuminanceUtils.cs - - - XenkoShaderKeyGenerator - SphericalHarmonicsBase.cs - - - XenkoShaderKeyGenerator - SphericalHarmonicsParameters.cs - - - XenkoShaderKeyGenerator - SphericalHarmonicsRenderer1.cs - - - XenkoShaderKeyGenerator - SphericalHarmonicsRendererEffect1.cs - - - XenkoShaderKeyGenerator - VignettingShader.cs - - - XenkoShaderKeyGenerator - DirectLightGroupFixed.cs - - - XenkoShaderKeyGenerator - DirectLightGroup.cs - - - XenkoShaderKeyGenerator - DirectLightGroupArray.cs - - - XenkoShaderKeyGenerator - EnvironmentLight.cs - - - XenkoShaderKeyGenerator - EnvironmentLightArray.cs - - - XenkoShaderKeyGenerator - LightPointGroup.cs - - - XenkoShaderKeyGenerator - LightUtil.cs - - - XenkoShaderKeyGenerator - LightSpotGroup.cs - - - XenkoShaderKeyGenerator - LightDirectionalGroup.cs - - - XenkoShaderKeyGenerator - LightSimpleAmbient.cs - - - XenkoShaderKeyGenerator - LightSkyboxShader.cs - - - XenkoShaderKeyGenerator - LightStream.cs - - - XenkoShaderKeyGenerator - LightSkyboxEffect.cs - - - - XenkoShaderKeyGenerator - IMaterialSurfaceDomain.cs - - - XenkoShaderKeyGenerator - IStreamInitializer.cs - - - XenkoShaderKeyGenerator - MaterialDisplacementStream.cs - - - XenkoShaderKeyGenerator - MaterialDomainStream.cs - - - - XenkoShaderKeyGenerator - MaterialStreamAdditiveBlend.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceDisplacement1.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceDomainStageCompositor1.cs - - - XenkoShaderKeyGenerator - MaterialTessellationStream1.cs - - - XenkoShaderKeyGenerator - MaterialFrontBackBlendShader.cs - - - XenkoShaderKeyGenerator - ComputeColorMaterialAlphaBlend.cs - - - XenkoShaderKeyGenerator - IMaterialSpecularMicrofacetFresnelFunction.cs - - - XenkoShaderKeyGenerator - IMaterialSpecularMicrofacetNormalDistributionFunction.cs - - - XenkoShaderKeyGenerator - IMaterialSpecularMicrofacetVisibilityFunction.cs - - - XenkoShaderKeyGenerator - IMaterialStreamBlend.cs - - - XenkoShaderKeyGenerator - IMaterialSurface.cs - - - XenkoShaderKeyGenerator - IMaterialSurfacePixel.cs - - - XenkoShaderKeyGenerator - IMaterialSurfaceShading.cs - - - XenkoShaderKeyGenerator - IMaterialSurfaceVertex.cs - - - XenkoShaderKeyGenerator - MaterialPixelShadingStream.cs - - - XenkoShaderKeyGenerator - MaterialPixelStream.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetFresnelNone.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetFresnelSchlick.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetNormalDistributionBeckmann.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetNormalDistributionBlinnPhong.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetNormalDistributionGGX.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilityCookTorrance.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilityImplicit.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilityKelemen.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilityNeumann.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilitySmithBeckmann.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilitySmithGGXCorrelated.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilitySmithSchlickBeckmann.cs - - - XenkoShaderKeyGenerator - MaterialSpecularMicrofacetVisibilitySmithSchlickGGX.cs - - - XenkoShaderKeyGenerator - MaterialStream.cs - - - XenkoShaderKeyGenerator - MaterialStreamLinearBlend.cs - - - XenkoShaderKeyGenerator - MaterialStreamNormalBlend.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceDiffuse.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceDiffuseSpecularAlphaBlendColor.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceTransparentAlphaDiscard.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceArray.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceShadingBlend.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceEmissiveShading.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceGlossinessMap.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceLightingAndShading.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceMetalness.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceNormalMap.cs - - - XenkoShaderKeyGenerator - MaterialSurfacePixelStageCompositor.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceSetStreamFromComputeColor.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceShadingDiffuseLambert.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceShadingSpecularBlinnPhong.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceShadingSpecularMicrofacet.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceStreamsBlend.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceStreamShading.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceVertexDisplacement.cs - - - XenkoShaderKeyGenerator - MaterialSurfaceVertexStageCompositor.cs - - - XenkoShaderKeyGenerator - MaterialVertexStream.cs - - - XenkoShaderKeyGenerator - Picking.cs - - - XenkoShaderKeyGenerator - PickingShader.cs - - - XenkoShaderKeyGenerator - XenkoWireframeShadingEffect.cs - - - XenkoShaderKeyGenerator - XenkoForwardShadingEffect.cs - - - XenkoShaderKeyGenerator - XenkoEffectBase.cs - - - XenkoShaderKeyGenerator - CameraCube.cs - - - - - XenkoShaderKeyGenerator - ShadowGroup.cs - - - XenkoShaderKeyGenerator - ShadowMapReceiverBase.cs - - - XenkoShaderKeyGenerator - ShadowMapReceiverSpot.cs - - - XenkoShaderKeyGenerator - ShadowMapReceiverDirectional.cs - - - XenkoShaderKeyGenerator - ShadowMapCaster.cs - - - XenkoShaderKeyGenerator - ShadowMapCasterVsm.cs - - - XenkoShaderKeyGenerator - ShadowMapCommon.cs - - - XenkoShaderKeyGenerator - ShadowMapFilterBase.cs - - - XenkoShaderKeyGenerator - ShadowMapFilterDefault.cs - - - XenkoShaderKeyGenerator - ShadowMapFilterPcf.cs - - - XenkoShaderKeyGenerator - ShadowMapFilterVsm.cs - - - XenkoShaderKeyGenerator - ShadowMapGroup.cs - - - XenkoShaderKeyGenerator - ShadowStream.cs - - - XenkoShaderKeyGenerator - NormalMeshSkinning.cs - - - XenkoShaderKeyGenerator - NormalVSSkinningFromMesh.cs - - - XenkoShaderKeyGenerator - NormalVSSkinningNormalMapping.cs - - - XenkoShaderKeyGenerator - TangentMeshSkinning.cs - - - XenkoShaderKeyGenerator - TransformationSkinning.cs - - - XenkoShaderKeyGenerator - CubemapUtils.cs - - - XenkoShaderKeyGenerator - IComputeEnvironmentColor.cs - - - XenkoShaderKeyGenerator - LevelCubeMapEnvironmentColor.cs - - - XenkoShaderKeyGenerator - RoughnessCubeMapEnvironmentColor.cs - - - XenkoShaderKeyGenerator - SkyboxStream.cs - - - XenkoShaderKeyGenerator - SphericalHarmonicsEnvironmentColor.cs - - - XenkoShaderKeyGenerator - TessellationAE2.cs - - - XenkoShaderKeyGenerator - TessellationAE3.cs - - - XenkoShaderKeyGenerator - TessellationAE4.cs - - - XenkoShaderKeyGenerator - TessellationBase.cs - - - XenkoShaderKeyGenerator - TessellationFlat.cs - - - XenkoShaderKeyGenerator - TessellationPN.cs - - - XenkoShaderKeyGenerator - TransformationBase.cs - - - XenkoShaderKeyGenerator - TransformationMatrix.cs - - - XenkoShaderKeyGenerator - TransformationWAndVP.cs - - - XenkoShaderKeyGenerator - TransformationWVP.cs - - - XenkoShaderKeyGenerator - TransformationZero.cs - - - XenkoShaderKeyGenerator - BlendUtils.cs - - - XenkoShaderKeyGenerator - ModelComponentPickingShader.cs - - - XenkoShaderKeyGenerator - DepthBase.cs - - - XenkoShaderKeyGenerator - FlattenLayers.cs - - - XenkoShaderKeyGenerator - HSVUtils.cs - - - XenkoShaderKeyGenerator - Math.cs - - - XenkoShaderKeyGenerator - NormalPack.cs - - - XenkoShaderKeyGenerator - NormalUtil.cs - - - XenkoShaderKeyGenerator - ModelComponentPickingEffect.cs - - - XenkoShaderKeyGenerator - SwapUV.cs - - - XenkoShaderKeyGenerator - Utilities.cs - - - XenkoShaderKeyGenerator - Camera.cs - - - XenkoShaderKeyGenerator - Global.cs - - - XenkoShaderKeyGenerator - Transformation.cs - - - TextTemplatingFileGenerator Properties.cs - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - - XenkoShaderKeyGenerator - - @@ -4096,4 +30,4 @@ - \ No newline at end of file + diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleEffect.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleEffect.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleEffect.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleShader.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleShader.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/SimpleShader.xksl.cs diff --git a/sources/engine/Xenko.Rendering/Rendering/Utils/Utilities.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/TestStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Rendering/Rendering/Utils/Utilities.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/TestStream.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslEffect.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslEffect.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslEffect.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslEffect.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslShader.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslShader.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/ToGlslShader.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/TestStream.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/A.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Compiler/TestStream.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/A.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/A.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/B.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/A.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/B.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/B.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/B.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C1.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C1.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/C1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor2.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor2.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor2.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColorRedirect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColor.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColorRedirect.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_complex_params.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_complex_params.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_complex_params.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_complex_params.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_compose_keys.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_compose_keys.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_compose_keys.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_compose_keys.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child_params.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child_params.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child_params.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_child_params.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_clone.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_clone.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_clone.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_clone.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_compose.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_compose.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_compose.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_compose.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_params.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_params.xkfx.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_params.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/test_mixin_simple_params.xkfx.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColorRedirect.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestChild.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Mixins/ComputeColorRedirect.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestChild.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestChild.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestInter.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestChild.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestInter.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestInter.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestParent.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestInter.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestParent.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin2.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin2.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BasicMixin2.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Child.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Child.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Child.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Child.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestParent.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ChildError.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/BaseTestParent.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ChildError.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ChildError.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ChildError.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestBase.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestBase.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestExtern.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestBase.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestExtern.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestExtern.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestRoot.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestExtern.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestRoot.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ConstantBufferTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ConstantBufferTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ConstantBufferTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ConstantBufferTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestRoot.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CyclicTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CloneTestRoot.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CyclicTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CyclicTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExtern.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/CyclicTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExtern.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExtern.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExternTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExtern.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExternTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExternTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternClone.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/DeepExternTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternClone.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternClone.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternCloneTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternClone.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternCloneTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternMixin.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternMixin.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternMixin.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternMixin.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternCloneTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternCloneTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest.cs deleted file mode 100644 index 5263961629..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -using System; -using Xenko.Core; -using Xenko.Effects; -using Xenko.Graphics; -using Xenko.Shaders; -using Xenko.Core.Mathematics; -using Buffer = Xenko.Graphics.Buffer; - -namespace Xenko.Effects -{ - public static partial class ForEachTestKeys - { - public static readonly ParameterKey collec = ParameterKeys.New(); - } -} diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ForEachTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericCall.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/ExternTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericCall.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericCall.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericCall.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass2.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass2.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass2.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericExtern.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericClass.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericExtern.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericTexcoord.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericTexcoord.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericTexcoord.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericTexcoord.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericExtern.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GeometryShaderTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GenericExtern.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GeometryShaderTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GeometryShaderTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InterfaceTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/GeometryShaderTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InterfaceTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InternalReferenceMixin.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InternalReferenceMixin.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InternalReferenceMixin.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InternalReferenceMixin.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InterfaceTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/InterfaceTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestBase.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestBase.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestChild.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestBase.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestChild.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestChild.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinFunctionParamaterTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestChild.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinFunctionParamaterTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestChild1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNameClash.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTestChild1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNameClash.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinFunctionParamaterTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNoNameClash.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinFunctionParamaterTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNoNameClash.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNameClash.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/NonStageStreamTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNameClash.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/NonStageStreamTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Parent.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Parent.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Parent.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Parent.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest.cs deleted file mode 100644 index bbaaacdfdd..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -using System; -using Xenko.Core; -using Xenko.Effects; -using Xenko.Graphics; -using Xenko.Shaders; -using Xenko.Core.Mathematics; -using Buffer = Xenko.Graphics.Buffer; - -namespace Xenko.Effects -{ - public static partial class SemanticTestKeys - { - public static readonly ParameterKey sem0 = ParameterKeys.New(); - public static readonly ParameterKey sem1 = ParameterKeys.New(); - } -} diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/SemanticTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Simple.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Simple.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Simple.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/Simple.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageBase.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageBase.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageBase.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageBase.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNoNameClash.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageCallExtern.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MixinNoNameClash.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageCallExtern.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageDecl.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageDecl.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageDecl.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageDecl.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/NonStageStreamTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueReference.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/NonStageStreamTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueReference.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageCallExtern.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticCallMixin.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageCallExtern.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticCallMixin.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticMixin.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticMixin.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticMixin.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticMixin.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueReference.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticStageCallTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StageValueReference.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticStageCallTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticCallMixin.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamChild.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticCallMixin.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamChild.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticStageCallTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamError.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StaticStageCallTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamError.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamChild.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent0.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamChild.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent0.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamError.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent1.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamError.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent1.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent0.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent2.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent0.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent2.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamSolverExternTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamSolverExternTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent2.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent2.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StructuredBufferTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StructuredBufferTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StructuredBufferTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StructuredBufferTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent21.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TessellationTest.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamParent21.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TessellationTest.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader.cs deleted file mode 100644 index 9063cbb6a9..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader.cs +++ /dev/null @@ -1,27 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -using System; -using Xenko.Core; -using Xenko.Effects; -using Xenko.Graphics; -using Xenko.Shaders; -using Xenko.Core.Mathematics; -using Buffer = Xenko.Graphics.Buffer; - -namespace Xenko.Effects -{ - public static partial class TestComputeShaderKeys - { - public static readonly ParameterKey ThreadGroupCountGlobal = ParameterKeys.New(); - public static readonly ParameterKey ParticleCount = ParameterKeys.New(); - public static readonly ParameterKey ParticleStartIndex = ParameterKeys.New(); - public static readonly ParameterKey ParticleSortBuffer = ParameterKeys.New(); - public static readonly ParameterKey ParticleSortBufferRO = ParticleSortBuffer; - } -} diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestComputeShader.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestErrors.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestErrors.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestErrors.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestErrors.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamSolverExternTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestExternArray.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamSolverExternTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestExternArray.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericComplex.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/StreamTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericComplex.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TessellationTest.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericMacro.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TessellationTest.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericMacro.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenerics.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenerics.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenerics.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenerics.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestExternArray.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacros.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestExternArray.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacros.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericComplex.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacrosArray.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericComplex.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacrosArray.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericMacro.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMultipleStatic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestGenericMacro.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMultipleStatic.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacros.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestPixelStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacros.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestPixelStream.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacrosArray.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestScreenPosition.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacrosArray.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestScreenPosition.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStreams.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStreams.cs deleted file mode 100644 index 274fe38f51..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStreams.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -// Nothing to generate diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacrosArray1.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStreams.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMacrosArray1.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStreams.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructInheritance.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructInheritance.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructInheritance.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructInheritance.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructure.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructure.cs deleted file mode 100644 index 274fe38f51..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructure.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -// Nothing to generate diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMultipleStatic.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructure.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestMultipleStatic.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestStructure.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestVertexStream.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestVertexStream.cs deleted file mode 100644 index 274fe38f51..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestVertexStream.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -// Nothing to generate diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestPixelStream.cs b/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestVertexStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestPixelStream.cs rename to sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestVertexStream.xksl.cs diff --git a/sources/engine/Xenko.Shaders.Tests/Properties/AssemblyInfo.cs b/sources/engine/Xenko.Shaders.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 09b9806b0b..0000000000 --- a/sources/engine/Xenko.Shaders.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Reflection; -using System.Resources; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Xenko.Shaders.Tests")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("Xenko.Shaders.Tests")] -[assembly: AssemblyCopyright("Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: NeutralResourcesLanguage("en")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/sources/engine/Xenko.Shaders.Tests/Xenko.Shaders.Tests.Windows.csproj b/sources/engine/Xenko.Shaders.Tests/Xenko.Shaders.Tests.Windows.csproj index 2dcc7a29c2..743435ea8d 100644 --- a/sources/engine/Xenko.Shaders.Tests/Xenko.Shaders.Tests.Windows.csproj +++ b/sources/engine/Xenko.Shaders.Tests/Xenko.Shaders.Tests.Windows.csproj @@ -7,7 +7,6 @@ Xenko.Shaders.Tests $(TargetFrameworkTool) false - false Windows Windows {3fb96652-1efa-47e5-8a78-acbf06d50f24} @@ -25,6 +24,10 @@ ..\..\..\Bin\$(XenkoPlatformFullName)\$(XenkoOutputFolder) $(BaseIntermediateOutputPath)$(XenkoPlatformFullName)-$(XenkoGraphicsApi)\$(Configuration) + + + + @@ -33,937 +36,6 @@ - - - - - - - True - True - True - SimpleEffect.xkfx - - - True - True - True - SimpleShader.xksl - - - True - True - True - ToGlslEffect.xkfx - - - TestStream.xksl - True - True - True - - - True - True - True - ToGlslShader.xksl - - - ComputeColorRedirect.xksl - True - True - True - - - test_mixin_compose_keys.xkfx - True - True - True - - - ComputeColor2.xksl - True - True - True - - - ComputeColor.xksl - True - True - True - - - C1.xksl - True - True - True - - - C.xksl - True - True - True - - - B.xksl - True - True - True - - - A.xksl - True - True - True - - - True - True - True - test_mixin_complex_params.xkfx - - - True - True - True - test_mixin_simple.xkfx - - - True - True - True - test_mixin_simple_child.xkfx - - - True - True - True - test_mixin_simple_child_params.xkfx - - - True - True - True - test_mixin_simple_clone.xkfx - - - True - True - True - test_mixin_simple_compose.xkfx - - - True - True - True - test_mixin_simple_params.xkfx - - - True - True - True - GenericClass2.xksl - - - True - True - True - MacroTestBase.xksl - - - True - True - True - TestMacrosArray.xksl - - - - True - True - True - GenericClass.xksl - - - True - True - True - MacroTest.xksl - - - True - True - True - MacroTestChild.xksl - - - True - True - True - Simple.xksl - - - True - True - True - StreamTest.xksl - - - True - True - True - TestComputeShader.xksl - - - True - True - True - TestMacros.xksl - - - - True - True - True - CloneTestBase.xksl - - - True - True - True - BaseTestChild.xksl - - - True - True - True - BaseTestInter.xksl - - - True - True - True - BaseTestParent.xksl - - - True - True - True - BasicMixin.xksl - - - True - True - True - BasicMixin2.xksl - - - True - True - True - Child.xksl - - - True - True - True - ChildError.xksl - - - True - True - True - CloneTestExtern.xksl - - - True - True - True - ConstantBufferTest.xksl - - - True - True - True - CyclicTest.xksl - - - True - True - True - DeepExtern.xksl - - - True - True - True - DeepExternTest.xksl - - - True - True - True - ExternClone.xksl - - - True - True - True - ExternCloneTest.xksl - - - True - True - True - ExternMixin.xksl - - - True - True - True - ExternTest.xksl - - - True - True - True - ForEachTest.xksl - - - True - True - True - GenericCall.xksl - - - True - True - True - GenericExtern.xksl - - - True - True - True - GenericTexcoord.xksl - - - GeometryShaderTest.xksl - True - True - True - - - True - True - True - InterfaceTest.xksl - - - True - True - True - InternalReferenceMixin.xksl - - - True - True - True - MixinFunctionParamaterTest.xksl - - - True - True - True - MixinNameClash.xksl - - - True - True - True - MixinNoNameClash.xksl - - - True - True - True - NonStageStreamTest.xksl - - - True - True - True - Parent.xksl - - - True - True - True - CloneTestRoot.xksl - - - True - True - True - SemanticTest.xksl - - - True - True - True - StageBase.xksl - - - True - True - True - StageCallExtern.xksl - - - True - True - True - StageDecl.xksl - - - True - True - True - StageValueReference.xksl - - - True - True - True - StageValueTest.xksl - - - True - True - True - StaticCallMixin.xksl - - - True - True - True - StaticMixin.xksl - - - True - True - True - StaticStageCallTest.xksl - - - True - True - True - StreamChild.xksl - - - True - True - True - StreamParent0.xksl - - - True - True - True - StreamParent1.xksl - - - True - True - True - StreamError.xksl - - - True - True - True - StreamParent2.xksl - - - True - True - True - StreamSolverExternTest.xksl - - - True - True - True - StructuredBufferTest.xksl - - - TessellationTest.xksl - True - True - True - - - True - True - True - TestErrors.xksl - - - True - True - True - TestExternArray.xksl - - - True - True - True - TestMultipleStatic.xksl - - - True - True - True - TestPixelStream.xksl - - - True - True - True - TestScreenPosition.xksl - - - True - True - True - TestStreams.xksl - - - True - True - True - TestGenerics.xksl - - - True - True - True - TestStructInheritance.xksl - - - True - True - True - TestStructure.xksl - - - True - True - True - TestGenericComplex.xksl - - - True - True - True - TestGenericMacro.xksl - - - True - True - True - TestVertexStream.xksl - - - - - - - - - - - - - - - - - - XenkoShaderKeyGenerator - SimpleEffect.cs - - - XenkoShaderKeyGenerator - SimpleShader.cs - - - XenkoShaderKeyGenerator - ToGlslEffect.cs - - - XenkoShaderKeyGenerator - TestStream.cs - - - XenkoShaderKeyGenerator - ToGlslShader.cs - - - XenkoShaderKeyGenerator - A.cs - - - XenkoShaderKeyGenerator - B.cs - - - XenkoShaderKeyGenerator - C.cs - - - XenkoShaderKeyGenerator - C1.cs - - - XenkoShaderKeyGenerator - ComputeColor.cs - - - XenkoShaderKeyGenerator - ComputeColor2.cs - - - XenkoShaderKeyGenerator - ComputeColorRedirect.cs - - - XenkoShaderKeyGenerator - test_mixin_compose_keys.cs - - - XenkoShaderKeyGenerator - test_mixin_complex_params.cs - - - XenkoShaderKeyGenerator - test_mixin_simple.cs - - - XenkoShaderKeyGenerator - test_mixin_simple_child.cs - - - XenkoShaderKeyGenerator - test_mixin_simple_child_params.cs - - - XenkoShaderKeyGenerator - test_mixin_simple_clone.cs - - - XenkoShaderKeyGenerator - test_mixin_simple_compose.cs - - - XenkoShaderKeyGenerator - test_mixin_simple_params.cs - - - XenkoShaderKeyGenerator - TestMacrosArray1.cs - - - XenkoShaderKeyGenerator - BaseTestChild.cs - - - XenkoShaderKeyGenerator - BaseTestInter.cs - - - XenkoShaderKeyGenerator - BaseTestParent.cs - - - XenkoShaderKeyGenerator - BasicMixin.cs - - - XenkoShaderKeyGenerator - BasicMixin2.cs - - - XenkoShaderKeyGenerator - Child.cs - - - XenkoShaderKeyGenerator - ChildError.cs - - - XenkoShaderKeyGenerator - CyclicTest.cs - - - XenkoShaderKeyGenerator - DeepExtern.cs - - - XenkoShaderKeyGenerator - DeepExternTest.cs - - - XenkoShaderKeyGenerator - ExternMixin.cs - - - XenkoShaderKeyGenerator - ExternTest.cs - - - XenkoShaderKeyGenerator - GenericCall.cs - - - XenkoShaderKeyGenerator - GenericExtern.cs - - - XenkoShaderKeyGenerator - GenericTexcoord.cs - - - XenkoShaderKeyGenerator - GeometryShaderTest.cs - - - XenkoShaderKeyGenerator - InternalReferenceMixin.cs - - - XenkoShaderKeyGenerator - MixinNameClash.cs - - - XenkoShaderKeyGenerator - MixinNoNameClash.cs - - - XenkoShaderKeyGenerator - Parent.cs - - - XenkoShaderKeyGenerator - StaticCallMixin.cs - - - XenkoShaderKeyGenerator - StaticMixin.cs - - - XenkoShaderKeyGenerator - TessellationTest.cs - - - XenkoShaderKeyGenerator - TestGenerics.cs - - - XenkoShaderKeyGenerator - GenericClass2.cs - - - XenkoShaderKeyGenerator - MacroTestBase.cs - - - XenkoShaderKeyGenerator - ConstantBufferTest.cs - - - XenkoShaderKeyGenerator - ForEachTest1.cs - - - XenkoShaderKeyGenerator - GenericClass.cs - - - XenkoShaderKeyGenerator - MacroTest1.cs - - - XenkoShaderKeyGenerator - MacroTestChild1.cs - - - XenkoShaderKeyGenerator - NonStageStreamTest.cs - - - XenkoShaderKeyGenerator - Simple.cs - - - XenkoShaderKeyGenerator - StageBase.cs - - - XenkoShaderKeyGenerator - StreamChild.cs - - - XenkoShaderKeyGenerator - StreamParent0.cs - - - XenkoShaderKeyGenerator - CloneTestBase.cs - - - XenkoShaderKeyGenerator - CloneTestExtern.cs - - - XenkoShaderKeyGenerator - ExternClone.cs - - - XenkoShaderKeyGenerator - CloneTestRoot.cs - - - XenkoShaderKeyGenerator - SemanticTest1.cs - - - - - XenkoShaderKeyGenerator - StageDecl.cs - - - XenkoShaderKeyGenerator - StageValueReference.cs - - - - - XenkoShaderKeyGenerator - ExternCloneTest.cs - - - XenkoShaderKeyGenerator - MixinFunctionParamaterTest.cs - - - XenkoShaderKeyGenerator - TestPixelStream.cs - - - XenkoShaderKeyGenerator - TestScreenPosition.cs - - - XenkoShaderKeyGenerator - TestStreams.cs - - - XenkoShaderKeyGenerator - TestVertexStream.cs - - - - - XenkoShaderKeyGenerator - InterfaceTest.cs - - - - - XenkoShaderKeyGenerator - TestGenericComplex.cs - - - - - XenkoShaderKeyGenerator - TestStructure.cs - - - - - XenkoShaderKeyGenerator - TestStructInheritance.cs - - - - - XenkoShaderKeyGenerator - TestGenericMacro.cs - - - - - XenkoShaderKeyGenerator - StructuredBufferTest.cs - - - - - XenkoShaderKeyGenerator - StageCallExtern.cs - - - XenkoShaderKeyGenerator - StageValueTest.cs - - - XenkoShaderKeyGenerator - StaticStageCallTest.cs - - - XenkoShaderKeyGenerator - StreamParent1.cs - - - XenkoShaderKeyGenerator - StreamError.cs - - - XenkoShaderKeyGenerator - StreamParent21.cs - - - XenkoShaderKeyGenerator - StreamSolverExternTest.cs - - - XenkoShaderKeyGenerator - StreamTest.cs - - - XenkoShaderKeyGenerator - TestComputeShader1.cs - - - XenkoShaderKeyGenerator - TestErrors.cs - - - XenkoShaderKeyGenerator - TestExternArray.cs - - - XenkoShaderKeyGenerator - TestMacros.cs - - - XenkoShaderKeyGenerator - TestMultipleStatic.cs - - diff --git a/sources/engine/Xenko.Video/Shaders/VideoShader.cs b/sources/engine/Xenko.Video/Shaders/VideoShader.cs deleted file mode 100644 index 274fe38f51..0000000000 --- a/sources/engine/Xenko.Video/Shaders/VideoShader.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -// Nothing to generate diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestScreenPosition.cs b/sources/engine/Xenko.Video/Shaders/VideoShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/TestScreenPosition.cs rename to sources/engine/Xenko.Video/Shaders/VideoShader.xksl.cs diff --git a/sources/engine/Xenko.Video/Xenko.Video.csproj b/sources/engine/Xenko.Video/Xenko.Video.csproj index fa1380c61d..9cff845d5e 100644 --- a/sources/engine/Xenko.Video/Xenko.Video.csproj +++ b/sources/engine/Xenko.Video/Xenko.Video.csproj @@ -24,12 +24,6 @@ Properties\SharedAssemblyInfo.cs - - VideoShader.xksl - True - True - True - @@ -55,12 +49,6 @@ - - - XenkoShaderKeyGenerator - VideoShader.cs - - diff --git a/sources/targets/Xenko.PostSettings.targets b/sources/targets/Xenko.PostSettings.targets index 828c6ee8b5..db809a9fae 100644 --- a/sources/targets/Xenko.PostSettings.targets +++ b/sources/targets/Xenko.PostSettings.targets @@ -26,4 +26,13 @@ + + + + + + + + + diff --git a/sources/targets/Xenko.UnitTests.targets b/sources/targets/Xenko.UnitTests.targets index a30f368b6c..a2e34ff982 100644 --- a/sources/targets/Xenko.UnitTests.targets +++ b/sources/targets/Xenko.UnitTests.targets @@ -63,4 +63,12 @@ + + + + + + + + diff --git a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest.cs b/sources/tools/Xenko.VisualStudio.Package.Tests/TestGenerator.xksl.cs similarity index 58% rename from sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest.cs rename to sources/tools/Xenko.VisualStudio.Package.Tests/TestGenerator.xksl.cs index 4a1a029e58..fb3be741c0 100644 --- a/sources/engine/Xenko.Shaders.Tests/GameAssets/Shaders/MacroTest.cs +++ b/sources/tools/Xenko.VisualStudio.Package.Tests/TestGenerator.xksl.cs @@ -8,16 +8,17 @@ using System; using Xenko.Core; -using Xenko.Effects; +using Xenko.Rendering; using Xenko.Graphics; using Xenko.Shaders; using Xenko.Core.Mathematics; using Buffer = Xenko.Graphics.Buffer; -namespace Xenko.Effects +namespace Xenko.Rendering { - public static partial class MacroTestKeys + public static partial class TestGeneratorKeys { - public static readonly ParameterKey u = ParameterKeys.New(); + public static readonly ValueParameterKey TestFloat = ParameterKeys.NewValue(); + public static readonly ValueParameterKey TestColor = ParameterKeys.NewValue(); } } From d2c419ae821d579f147deab1c9c081252fd3c7ad Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 2 Dec 2019 21:05:42 +0100 Subject: [PATCH 0524/2038] [Samples] Updated samples to use auto include for xksl/xkfx # Conflicts: # sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs --- .../{FogEffect.cs => FogEffect.xksl.cs} | 0 ...tMain.cs => SpaceEscapeEffectMain.xkfx.cs} | 0 ...rld.cs => TransformationBendWorld.xksl.cs} | 0 ...eUV.cs => TransformationTextureUV.xksl.cs} | 0 .../SpaceEscape.Game/SpaceEscape.Game.csproj | 42 --------------- .../CustomEffect.Game.csproj | 12 ----- .../Effects/{Effect.cs => Effect.xksl.cs} | 0 ...WaveNormal.cs => ComputeColorWave.xksl.cs} | 0 .../Effects/ComputeColorWaveNormal.xksl.cs} | 0 .../MaterialShader.Game.csproj | 22 -------- ...ColorRed.cs => ComputeColorRadial.xksl.cs} | 0 ...xtureScroll.cs => ComputeColorRed.xksl.cs} | 0 ...r.cs => ComputeColorTextureScroll.xksl.cs} | 0 ...Effect.cs => ParticleCustomEffect.xkfx.cs} | 0 .../Effects/ParticleCustomShader.xksl.cs | 9 ++++ .../ParticlesSample.Game.csproj | 52 ------------------- .../ThisPackageVersion.cs | 2 +- 17 files changed, 10 insertions(+), 129 deletions(-) rename samples/Games/SpaceEscape/SpaceEscape.Game/Effects/{FogEffect.cs => FogEffect.xksl.cs} (100%) rename samples/Games/SpaceEscape/SpaceEscape.Game/Effects/{SpaceEscapeEffectMain.cs => SpaceEscapeEffectMain.xkfx.cs} (100%) rename samples/Games/SpaceEscape/SpaceEscape.Game/Effects/{TransformationBendWorld.cs => TransformationBendWorld.xksl.cs} (100%) rename samples/Games/SpaceEscape/SpaceEscape.Game/Effects/{TransformationTextureUV.cs => TransformationTextureUV.xksl.cs} (100%) rename samples/Graphics/CustomEffect/CustomEffect.Game/Effects/{Effect.cs => Effect.xksl.cs} (100%) rename samples/Graphics/MaterialShader/MaterialShader.Game/Effects/{ComputeColorWaveNormal.cs => ComputeColorWave.xksl.cs} (100%) rename samples/{Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRadial.cs => Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWaveNormal.xksl.cs} (100%) rename samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/{ComputeColorRed.cs => ComputeColorRadial.xksl.cs} (100%) rename samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/{ComputeColorTextureScroll.cs => ComputeColorRed.xksl.cs} (100%) rename samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/{ParticleCustomShader.cs => ComputeColorTextureScroll.xksl.cs} (100%) rename samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/{ParticleCustomEffect.cs => ParticleCustomEffect.xkfx.cs} (100%) create mode 100644 samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomShader.xksl.cs diff --git a/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/FogEffect.cs b/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/FogEffect.xksl.cs similarity index 100% rename from samples/Games/SpaceEscape/SpaceEscape.Game/Effects/FogEffect.cs rename to samples/Games/SpaceEscape/SpaceEscape.Game/Effects/FogEffect.xksl.cs diff --git a/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/SpaceEscapeEffectMain.cs b/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/SpaceEscapeEffectMain.xkfx.cs similarity index 100% rename from samples/Games/SpaceEscape/SpaceEscape.Game/Effects/SpaceEscapeEffectMain.cs rename to samples/Games/SpaceEscape/SpaceEscape.Game/Effects/SpaceEscapeEffectMain.xkfx.cs diff --git a/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationBendWorld.cs b/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationBendWorld.xksl.cs similarity index 100% rename from samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationBendWorld.cs rename to samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationBendWorld.xksl.cs diff --git a/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationTextureUV.cs b/samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationTextureUV.xksl.cs similarity index 100% rename from samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationTextureUV.cs rename to samples/Games/SpaceEscape/SpaceEscape.Game/Effects/TransformationTextureUV.xksl.cs diff --git a/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj b/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj index 96df07d4dc..f33888adf2 100644 --- a/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj +++ b/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj @@ -11,46 +11,4 @@ - - - XenkoShaderKeyGenerator - FogEffect.cs - - - True - True - True - FogEffect.xksl - - - XenkoShaderKeyGenerator - SpaceEscapeEffectMain.cs - - - True - True - True - SpaceEscapeEffectMain.xkfx - - - XenkoShaderKeyGenerator - TransformationBendWorld.cs - - - True - True - True - TransformationBendWorld.xksl - - - XenkoShaderKeyGenerator - TransformationTextureUV.cs - - - True - True - True - TransformationTextureUV.xksl - - \ No newline at end of file diff --git a/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj b/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj index 8939e24ecb..f54d11f89e 100644 --- a/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj +++ b/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj @@ -10,16 +10,4 @@ - - - XenkoShaderKeyGenerator - Effect.cs - - - True - True - True - Effect.xksl - - \ No newline at end of file diff --git a/samples/Graphics/CustomEffect/CustomEffect.Game/Effects/Effect.cs b/samples/Graphics/CustomEffect/CustomEffect.Game/Effects/Effect.xksl.cs similarity index 100% rename from samples/Graphics/CustomEffect/CustomEffect.Game/Effects/Effect.cs rename to samples/Graphics/CustomEffect/CustomEffect.Game/Effects/Effect.xksl.cs diff --git a/samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWaveNormal.cs b/samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWave.xksl.cs similarity index 100% rename from samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWaveNormal.cs rename to samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWave.xksl.cs diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRadial.cs b/samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWaveNormal.xksl.cs similarity index 100% rename from samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRadial.cs rename to samples/Graphics/MaterialShader/MaterialShader.Game/Effects/ComputeColorWaveNormal.xksl.cs diff --git a/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj b/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj index 34003fafbb..3c6fd2f175 100644 --- a/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj +++ b/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj @@ -10,26 +10,4 @@ - - - XenkoShaderKeyGenerator - ComputeColorWave.cs - - - True - True - True - ComputeColorWave.xksl - - - XenkoShaderKeyGenerator - ComputeColorWaveNormal.cs - - - True - True - True - ComputeColorWaveNormal.xksl - - \ No newline at end of file diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRed.cs b/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRadial.xksl.cs similarity index 100% rename from samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRed.cs rename to samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRadial.xksl.cs diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorTextureScroll.cs b/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRed.xksl.cs similarity index 100% rename from samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorTextureScroll.cs rename to samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorRed.xksl.cs diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomShader.cs b/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorTextureScroll.xksl.cs similarity index 100% rename from samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomShader.cs rename to samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ComputeColorTextureScroll.xksl.cs diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomEffect.cs b/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomEffect.xkfx.cs similarity index 100% rename from samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomEffect.cs rename to samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomEffect.xkfx.cs diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomShader.xksl.cs b/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomShader.xksl.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/samples/Particles/ParticlesSample/ParticlesSample.Game/Effects/ParticleCustomShader.xksl.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj b/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj index 3e5c8b18b6..bebd2bf514 100644 --- a/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj +++ b/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj @@ -11,56 +11,4 @@ - - - XenkoShaderKeyGenerator - ComputeColorRadial.cs - - - True - True - True - ComputeColorRadial.xksl - - - XenkoShaderKeyGenerator - ComputeColorRed.cs - - - True - True - True - ComputeColorRed.xksl - - - XenkoShaderKeyGenerator - ComputeColorTextureScroll.cs - - - True - True - True - ComputeColorTextureScroll.xksl - - - XenkoShaderKeyGenerator - ParticleCustomEffect.cs - - - True - True - True - ParticleCustomEffect.xkfx - - - XenkoShaderKeyGenerator - ParticleCustomShader.cs - - - True - True - True - ParticleCustomShader.xksl - - \ No newline at end of file diff --git a/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs b/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs index 9540b02046..1a2f7aa895 100644 --- a/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs +++ b/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs @@ -3,6 +3,6 @@ namespace Xenko.Samples.Templates static class ThisPackageVersion { // we version this package manually because most of the time the samples are big and don't need to be updated - public static string Current = "3.1.0.1"; + public static string Current = "3.2.0.1-beta02"; } } From 764871eed66221cf5ca0f12511046cb776f42198 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 2 Dec 2019 21:39:04 +0100 Subject: [PATCH 0525/2038] [Editor] Better detection of VS Preview version --- .../VisualStudio/VisualStudioVersions.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sources/core/Xenko.Core.Design/VisualStudio/VisualStudioVersions.cs b/sources/core/Xenko.Core.Design/VisualStudio/VisualStudioVersions.cs index 5bb776023f..70af7c825c 100644 --- a/sources/core/Xenko.Core.Design/VisualStudio/VisualStudioVersions.cs +++ b/sources/core/Xenko.Core.Design/VisualStudio/VisualStudioVersions.cs @@ -148,6 +148,17 @@ private static List BuildIDEInfos() var nickname = inst2.GetProperties().GetValue("nickname") as string; if (!string.IsNullOrEmpty(nickname)) displayName = $"{displayName} ({nickname})"; + else + { + var installationName = inst2.GetInstallationName(); + // In case of Preview, we have: + // "installationName": "VisualStudioPreview/16.4.0-pre.6.0+29519.161" + // "channelId": "VisualStudio.16.Preview" + if (installationName.Contains("Preview")) + { + displayName = displayName + " (Preview)"; + } + } } catch (COMException) { From 880b5fccf5f458d575ae0e90d89504271ffb7c5d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 4 Dec 2019 11:37:04 -0500 Subject: [PATCH 0526/2038] VR: widespread and significant improvements to entire VR system Disabled Oculus, which isn't supported. Use OpenVR instead. Supports multiple forward renderers now in VR. Post processing effect layers now shall work. Significant performance improvements around post processing and VR. --- .../Xenko.Engine/Engine/CameraComponent.cs | 3 + .../Rendering/Compositing/ForwardRenderer.cs | 228 +++++++++--------- .../Xenko.VirtualReality/DummyDevice.cs | 6 +- .../Xenko.VirtualReality/Fove/FoveHmd.cs | 4 +- .../OculusOVR/OculusOvrHmd.cs | 10 +- .../Xenko.VirtualReality/OpenVR/OpenVrHmd.cs | 47 ++-- sources/engine/Xenko.VirtualReality/VRApi.cs | 2 +- .../engine/Xenko.VirtualReality/VRDevice.cs | 4 +- .../Xenko.VirtualReality/VRDeviceSystem.cs | 12 +- 9 files changed, 150 insertions(+), 166 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/CameraComponent.cs b/sources/engine/Xenko.Engine/Engine/CameraComponent.cs index 8032d7fbd6..0759854834 100644 --- a/sources/engine/Xenko.Engine/Engine/CameraComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/CameraComponent.cs @@ -35,6 +35,9 @@ public sealed class CameraComponent : ActivableEntityComponent public const float DefaultFarClipPlane = 1000.0f; + internal ulong VRProjectionPose; + internal Matrix[] cachedVRProjections; + /// /// Create a new instance. /// diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index 13f5fc3f5f..f8e28d7ec5 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -41,6 +41,8 @@ public partial class ForwardRenderer : SceneRendererBase, ISharedRenderer private Texture currentDepthStencil; private Texture currentDepthStencilNonMSAA; + private static List VRRenderers = new List(); + protected Texture viewOutputTarget; protected Texture viewDepthStencil; @@ -155,50 +157,52 @@ protected override void InitializeCore() var camera = Context.GetCurrentCamera(); + // only update vrSystem if it isn't already enabled vrSystem = Services.GetService(); if (vrSystem != null) { if (VRSettings.Enabled) { - var requiredDescs = VRSettings.RequiredApis.ToArray(); - vrSystem.PreferredApis = requiredDescs.Select(x => x.Api).Distinct().ToArray(); + VRRenderers.Add(this); - // remove VR API duplicates and keep first desired config only - var preferredScalings = new Dictionary(); - foreach (var desc in requiredDescs) + if (vrSystem.Enabled) { - if (!preferredScalings.ContainsKey(desc.Api)) - preferredScalings[desc.Api] = desc.ResolutionScale; + // VR is already enabled, grab the device + VRSettings.VRDevice = vrSystem.Device; } - vrSystem.PreferredScalings = preferredScalings; + else + { + var requiredDescs = VRSettings.RequiredApis.ToArray(); + vrSystem.PreferredApis = requiredDescs.Select(x => x.Api).Distinct().ToArray(); - if( GraphicsDevice.Platform == GraphicsPlatform.Vulkan ) { - // no mirror support for vulkan - vrSystem.RequireMirror = false; - VRSettings.CopyMirror = false; - } else { - vrSystem.RequireMirror = VRSettings.CopyMirror; - } + // remove VR API duplicates and keep first desired config only + var preferredScalings = new Dictionary(); + foreach (var desc in requiredDescs) + { + if (!preferredScalings.ContainsKey(desc.Api)) + preferredScalings[desc.Api] = desc.ResolutionScale; + } + vrSystem.PreferredScalings = preferredScalings; - vrSystem.MirrorWidth = GraphicsDevice.Presenter.BackBuffer.Width; - vrSystem.MirrorHeight = GraphicsDevice.Presenter.BackBuffer.Height; + vrSystem.RequireMirror = VRSettings.CopyMirror; - vrSystem.Enabled = true; //careful this will trigger the whole chain of initialization! - vrSystem.Visible = true; + vrSystem.Enabled = true; //careful this will trigger the whole chain of initialization! + vrSystem.Visible = true; - VRSettings.VRDevice = vrSystem.Device; + VRSettings.VRDevice = vrSystem.Device; - vrSystem.PreviousUseCustomProjectionMatrix = camera.UseCustomProjectionMatrix; - vrSystem.PreviousUseCustomViewMatrix = camera.UseCustomViewMatrix; - vrSystem.PreviousCameraProjection = camera.ProjectionMatrix; + vrSystem.PreviousUseCustomProjectionMatrix = camera.UseCustomProjectionMatrix; + vrSystem.PreviousUseCustomViewMatrix = camera.UseCustomViewMatrix; + vrSystem.PreviousCameraProjection = camera.ProjectionMatrix; - if (VRSettings.VRDevice.SupportsOverlays) - { - foreach (var overlay in VRSettings.Overlays) + if (VRSettings.VRDevice.SupportsOverlays) { - if (overlay != null && overlay.Texture != null) + foreach (var overlay in VRSettings.Overlays) { - overlay.Overlay = VRSettings.VRDevice.CreateOverlay(overlay.Texture.Width, overlay.Texture.Height, overlay.Texture.MipLevels, (int)overlay.Texture.MultisampleCount); + if (overlay != null && overlay.Texture != null) + { + overlay.Overlay = VRSettings.VRDevice.CreateOverlay(overlay.Texture.Width, overlay.Texture.Height, overlay.Texture.MipLevels, (int)overlay.Texture.MultisampleCount); + } } } } @@ -312,48 +316,71 @@ protected override unsafe void CollectCore(RenderContext context) if (VRSettings.Enabled && VRSettings.VRDevice != null) { - Vector3 cameraPos, cameraScale; - Matrix cameraRot; + Matrix* viewMatrices = stackalloc Matrix[2]; + Matrix* projectionMatrices = stackalloc Matrix[2]; - if (!vrSystem.PreviousUseCustomViewMatrix) + // only update the camera once, if we have multiple forward renderers on the same camera + ulong poseCount = VRSettings.VRDevice.PoseCount; + if (poseCount == 0 || poseCount != camera.VRProjectionPose) { - camera.Entity.Transform.WorldMatrix.Decompose(out cameraScale, out cameraRot, out cameraPos); - } - else - { - camera.ViewMatrix.Decompose(out cameraScale, out cameraRot, out cameraPos); - cameraRot.Transpose(); - Vector3.Negate(ref cameraPos, out cameraPos); - Vector3.TransformCoordinate(ref cameraPos, ref cameraRot, out cameraPos); - } + camera.VRProjectionPose = poseCount; - if (VRSettings.IgnoreCameraRotation || camera.VRHeadSetsTransform) - { - // only remove the local rotation of the camera - cameraRot *= Matrix.RotationQuaternion(Quaternion.Invert(camera.Entity.Transform.Rotation)); - } + Vector3 cameraPos, cameraScale; + Matrix cameraRot; - if (camera.VRHeadSetsTransform) - { - // take out my local position, which isn't meant to be passed on, but set by the VR head - cameraPos -= camera.Entity.Transform.Position; - camera.Entity.Transform.Position = VRSettings.VRDevice.HeadPosition; - camera.Entity.Transform.Rotation = VRSettings.VRDevice.HeadRotation; - } + if (!vrSystem.PreviousUseCustomViewMatrix) + { + camera.Entity.Transform.WorldMatrix.Decompose(out cameraScale, out cameraRot, out cameraPos); + } + else + { + camera.ViewMatrix.Decompose(out cameraScale, out cameraRot, out cameraPos); + cameraRot.Transpose(); + Vector3.Negate(ref cameraPos, out cameraPos); + Vector3.TransformCoordinate(ref cameraPos, ref cameraRot, out cameraPos); + } - // Compute both view and projection matrices - Matrix* viewMatrices = stackalloc Matrix[2]; - Matrix* projectionMatrices = stackalloc Matrix[2]; - for (var i = 0; i < 2; ++i) - VRSettings.VRDevice.ReadEyeParameters(i == 0 ? Eyes.Left : Eyes.Right, camera.NearClipPlane, camera.FarClipPlane, ref cameraPos, ref cameraRot, VRSettings.IgnoreDeviceRotation, VRSettings.IgnoreDevicePosition, out viewMatrices[i], out projectionMatrices[i]); + if (VRSettings.IgnoreCameraRotation || camera.VRHeadSetsTransform) + { + // only remove the local rotation of the camera + cameraRot *= Matrix.RotationQuaternion(Quaternion.Invert(camera.Entity.Transform.Rotation)); + } + + if (camera.VRHeadSetsTransform) + { + // take out my local position, which isn't meant to be passed on, but set by the VR head + cameraPos -= camera.Entity.Transform.Position; + camera.Entity.Transform.Position = VRSettings.VRDevice.HeadPosition; + camera.Entity.Transform.Rotation = VRSettings.VRDevice.HeadRotation; + } - // if the VRDevice disagreed with the near and far plane, we must re-discover them and follow: - var near = projectionMatrices[0].M43 / projectionMatrices[0].M33; - var far = near * (-projectionMatrices[0].M33 / (-projectionMatrices[0].M33 - 1)); - if (Math.Abs(near - camera.NearClipPlane) > 1e-8f) - camera.NearClipPlane = near; - if (Math.Abs(near - camera.FarClipPlane) > 1e-8f) - camera.FarClipPlane = far; + // Compute both view and projection matrices + for (var i = 0; i < 2; ++i) + VRSettings.VRDevice.ReadEyeParameters(i == 0 ? Eyes.Left : Eyes.Right, camera.NearClipPlane, camera.FarClipPlane, ref cameraPos, ref cameraRot, VRSettings.IgnoreDeviceRotation, VRSettings.IgnoreDevicePosition, out viewMatrices[i], out projectionMatrices[i]); + + // cache these projection values + if (camera.cachedVRProjections == null) camera.cachedVRProjections = new Matrix[4]; + camera.cachedVRProjections[0] = viewMatrices[0]; + camera.cachedVRProjections[1] = viewMatrices[1]; + camera.cachedVRProjections[2] = projectionMatrices[0]; + camera.cachedVRProjections[3] = projectionMatrices[1]; + + // if the VRDevice disagreed with the near and far plane, we must re-discover them and follow: + var near = projectionMatrices[0].M43 / projectionMatrices[0].M33; + var far = near * (-projectionMatrices[0].M33 / (-projectionMatrices[0].M33 - 1)); + if (Math.Abs(near - camera.NearClipPlane) > 1e-8f) + camera.NearClipPlane = near; + if (Math.Abs(near - camera.FarClipPlane) > 1e-8f) + camera.FarClipPlane = far; + } + else + { + // already calculated this camera, use the cached information + viewMatrices[0] = camera.cachedVRProjections[0]; + viewMatrices[1] = camera.cachedVRProjections[1]; + projectionMatrices[0] = camera.cachedVRProjections[2]; + projectionMatrices[1] = camera.cachedVRProjections[3]; + } // Compute a view matrix and projection matrix that cover both eyes for shadow map and culling ComputeCommonViewMatrices(context, viewMatrices, projectionMatrices); @@ -598,7 +625,7 @@ protected virtual void DrawView(RenderContext context, RenderDrawContext drawCon { // Run post effects // Note: OpaqueRenderStage can't be null otherwise colorTargetIndex would be -1 - PostEffects.Draw(drawContext, OpaqueRenderStage.OutputValidator, renderTargets.Items, depthStencil, viewOutputTarget); + if (eyeCount == 1) PostEffects.Draw(drawContext, OpaqueRenderStage.OutputValidator, renderTargets.Items, depthStencil, viewOutputTarget); } else { @@ -636,80 +663,49 @@ protected override void DrawCore(RenderContext context, RenderDrawContext drawCo if (!isFullViewport) return; - var hasPostEffects = PostEffects != null; // When we have post effect we need to bind a different framebuffer for each view to be sure effects impinge on the other view. + var hasPostEffects = PostEffects != null; Texture vrFullSurface; using (drawContext.PushRenderTargetsAndRestore()) { var currentRenderTarget = drawContext.CommandList.RenderTarget; - var vrFullFrameSize = VRSettings.VRDevice.ActualRenderFrameSize; - var desiredRenderTargetSize = !hasPostEffects ? vrFullFrameSize : new Size2(vrFullFrameSize.Width / 2, vrFullFrameSize.Height); - if (hasPostEffects || desiredRenderTargetSize.Width != currentRenderTarget.Width || desiredRenderTargetSize.Height != currentRenderTarget.Height) + var desiredRenderTargetSize = VRSettings.VRDevice.ActualRenderFrameSize; + + if (desiredRenderTargetSize.Width != currentRenderTarget.Width || desiredRenderTargetSize.Height != currentRenderTarget.Height) drawContext.CommandList.SetRenderTargets(null, null); // force to create and bind a new render target PrepareRenderTargets(drawContext, desiredRenderTargetSize); - //prepare the final VR target vrFullSurface = viewOutputTarget; - if (hasPostEffects) - { - var frameSize = VRSettings.VRDevice.ActualRenderFrameSize; - var renderTargetDescription = TextureDescription.New2D(frameSize.Width, frameSize.Height, 1, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.ShaderResource | TextureFlags.RenderTarget); - vrFullSurface = PushScopedResource(drawContext.GraphicsContext.Allocator.GetTemporaryTexture2D(renderTargetDescription)); - } //draw per eye using (context.SaveViewportAndRestore()) using (drawContext.PushRenderTargetsAndRestore()) { ViewCount = 2; - bool isWindowsMixedReality = false; for (var i = 0; i < 2; i++) { -#if XENKO_PLATFORM_UWP - if (GraphicsDevice.Platform == GraphicsPlatform.Direct3D11 && drawContext.GraphicsDevice.Presenter is WindowsMixedRealityGraphicsPresenter graphicsPresenter) - { - isWindowsMixedReality = true; - - MSAALevel = MultisampleCount.None; - currentRenderTargets.Clear(); - - if (i == 0) - { - currentRenderTargets.Add(graphicsPresenter.LeftEyeBuffer); - } - else - { - currentRenderTargets.Add(graphicsPresenter.RightEyeBuffer); - } - } -#endif - drawContext.CommandList.SetRenderTargets(currentDepthStencil, currentRenderTargets.Count, currentRenderTargets.Items); - if (!hasPostEffects && !isWindowsMixedReality) // need to change the viewport between each eye - { - var frameSize = VRSettings.VRDevice.ActualRenderFrameSize; - drawContext.CommandList.SetViewport(new Viewport(i * frameSize.Width / 2, 0, frameSize.Width / 2, frameSize.Height)); - } - else if (i == 0) // the viewport is the same for both eyes so we set it only once - { - drawContext.CommandList.SetViewport(new Viewport(0.0f, 0.0f, VRSettings.VRDevice.ActualRenderFrameSize.Width / 2.0f, VRSettings.VRDevice.ActualRenderFrameSize.Height)); - } + var frameSize = VRSettings.VRDevice.ActualRenderFrameSize; + drawContext.CommandList.SetViewport(new Viewport(i * frameSize.Width / 2, 0, frameSize.Width / 2, frameSize.Height)); using (context.PushRenderViewAndRestore(VRSettings.RenderViews[i])) { // Clear render target and depth stencil - if (hasPostEffects || i == 0) // need to clear for each eye in the case we have two different render targets - Clear?.Draw(drawContext); + if (i == 0) Clear?.Draw(drawContext); ViewIndex = i; + // draw view, but skip post processing (it will not do it, since eye count > 1) DrawView(context, drawContext, i, 2); - if (hasPostEffects) // copy the rendered view into the vr full view framebuffer - drawContext.CommandList.CopyRegion(viewOutputTarget, 0, null, vrFullSurface, 0, VRSettings.VRDevice.ActualRenderFrameSize.Width / 2 * i); + // last eye, draw post effects over both eyes if we have some + if (hasPostEffects && i == 1) + { + PostEffects.Draw(drawContext, OpaqueRenderStage.OutputValidator, currentRenderTargets.Items, currentDepthStencil, vrFullSurface); + } } } @@ -724,19 +720,15 @@ protected override void DrawCore(RenderContext context, RenderDrawContext drawCo } } - VRSettings.VRDevice.Commit(drawContext.CommandList, vrFullSurface); + // if we are on our last forward renderer and our scene is ready for submission + if (this == VRRenderers[VRRenderers.Count - 1]) + VRSettings.VRDevice.Commit(drawContext.CommandList, vrFullSurface); } } - //draw mirror to backbuffer (if size is matching and full viewport) + //draw mirror if desired if (VRSettings.CopyMirror) - { - CopyOrScaleTexture(drawContext, VRSettings.VRDevice.MirrorTexture, drawContext.CommandList.RenderTarget); - } - else if (hasPostEffects) - { CopyOrScaleTexture(drawContext, vrFullSurface, drawContext.CommandList.RenderTarget); - } } else { @@ -829,7 +821,7 @@ private void PrepareRenderTargets(RenderDrawContext drawContext, Texture outputR for (int index = 0; index < renderTargets.Count; index++) { - if (renderTargets[index].Semantic is ColorTargetSemantic && PostEffects == null && actualMultisampleCount == MultisampleCount.None) + if (renderTargets[index].Semantic is ColorTargetSemantic && actualMultisampleCount == MultisampleCount.None) { currentRenderTargets[index] = outputRenderTarget; } diff --git a/sources/engine/Xenko.VirtualReality/DummyDevice.cs b/sources/engine/Xenko.VirtualReality/DummyDevice.cs index d006d2f706..fba6a5c2ec 100644 --- a/sources/engine/Xenko.VirtualReality/DummyDevice.cs +++ b/sources/engine/Xenko.VirtualReality/DummyDevice.cs @@ -43,6 +43,8 @@ public class DummyDevice : VRDevice public override TouchController RightHand => null; + public override ulong PoseCount => 0; + public override TrackedItem[] TrackedItems => new TrackedItem[0]; public override bool CanInitialize => true; @@ -97,9 +99,9 @@ public DummyDevice(IServiceRegistry services) window = services.GetService().Window; } - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight) + public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror) { - ActualRenderFrameSize = optimalRenderFrameSize = new Size2(mirrorWidth, mirrorHeight); + ActualRenderFrameSize = optimalRenderFrameSize = new Size2(2560, 1440); MirrorTexture = Texture.New2D(device, ActualRenderFrameSize.Width, ActualRenderFrameSize.Height, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource); } diff --git a/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs b/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs index 60589ffeda..b0feff855a 100644 --- a/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs +++ b/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs @@ -21,13 +21,15 @@ internal class FoveHmd : VRDevice private const float EyeHeight = 0.08f; private const float EyeForward = -0.04f; + public override ulong PoseCount => 0; + internal FoveHmd() { referenceMatrixInv = Matrix.RotationZ(MathUtil.Pi); referenceMatrixInv.Invert(); } - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight) + public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror) { // RenderFrame = Texture.New2D(device, RenderFrameSize.Width, RenderFrameSize.Height, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource); // nonSrgbFrame = Texture.New2D(device, RenderFrameSize.Width, RenderFrameSize.Height, PixelFormat.R8G8B8A8_UNorm, TextureFlags.RenderTarget | TextureFlags.ShaderResource); diff --git a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs index dc3724b703..f1c04df722 100644 --- a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs +++ b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs @@ -23,6 +23,8 @@ internal class OculusOvrHmd : VRDevice private IntPtr ovrSession; private Texture[] textures; + public override ulong PoseCount => 0; + private OculusTouchController leftHandController; private OculusTouchController rightHandController; private readonly List overlays = new List(); @@ -31,7 +33,7 @@ internal class OculusOvrHmd : VRDevice internal OculusOvrHmd() { SupportsOverlays = true; - VRApi = VRApi.Oculus; + //VRApi = VRApi.Oculus; } public override void Dispose() @@ -48,9 +50,9 @@ public override void Dispose() } } - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight) + public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror) { - graphicsDevice = device; + /*graphicsDevice = device; long adapterId; ovrSession = OculusOvr.CreateSessionDx(out adapterId); //Game.GraphicsDeviceManager.RequiredAdapterUid = adapterId.ToString(); //should not be needed @@ -84,7 +86,7 @@ public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphic ActualRenderFrameSize = new Size2(textures[0].Width, textures[0].Height); leftHandController = new OculusTouchController(TouchControllerHand.Left); - rightHandController = new OculusTouchController(TouchControllerHand.Right); + rightHandController = new OculusTouchController(TouchControllerHand.Right);*/ } private OculusOvr.PosesProperties currentPoses; diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs index 885fb20867..a8d383968a 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrHmd.cs @@ -12,9 +12,6 @@ public class OpenVRHmd : VRDevice { private RectangleF leftView = new RectangleF(0.0f, 0.0f, 0.5f, 1.0f); private RectangleF rightView = new RectangleF(0.5f, 0.0f, 1.0f, 1.0f); - private Texture bothEyesMirror; - private Texture leftEyeMirror; - private Texture rightEyeMirror; private DeviceState state; private OpenVRTouchController leftHandController; private OpenVRTouchController rightHandController; @@ -27,9 +24,18 @@ public class OpenVRHmd : VRDevice private Quaternion currentHeadRot; private GameBase mainGame; private int HMDindex; + private ulong poseCount; public override bool CanInitialize => OpenVR.InitDone || OpenVR.Init(); + public override ulong PoseCount + { + get + { + return poseCount; + } + } + public OpenVRHmd(GameBase game) { mainGame = game; @@ -37,30 +43,11 @@ public OpenVRHmd(GameBase game) SupportsOverlays = true; } - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight) + public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror) { - Size2 renderSize = OptimalRenderFrameSize; - var width = (int)(renderSize.Width * RenderFrameScaling); - width += width % 2; - var height = (int)(renderSize.Height * RenderFrameScaling); - height += height % 2; - - ActualRenderFrameSize = new Size2(width, height); + ActualRenderFrameSize = OptimalRenderFrameSize; -#if XENKO_GRAPHICS_API_VULKAN - needsMirror = false; // Vulkan doesn't support mirrors :/ -#else needsMirror = requireMirror; -#endif - - if (needsMirror) - { - bothEyesMirror = Texture.New2D(device, width, height, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource); - } - - leftEyeMirror = OpenVR.GetMirrorTexture(device, 0); - rightEyeMirror = OpenVR.GetMirrorTexture(device, 1); - MirrorTexture = bothEyesMirror; leftHandController = new OpenVRTouchController(TouchControllerHand.Left); rightHandController = new OpenVRTouchController(TouchControllerHand.Right); @@ -90,6 +77,7 @@ public override void Draw(GameTime gameTime) state = OpenVR.GetHeadPose(out currentHead, out currentHeadLinearVelocity, out currentHeadAngularVelocity); Vector3 scale; currentHead.Decompose(out scale, out currentHeadRot, out currentHeadPos); + poseCount++; } public override void Update(GameTime gameTime) @@ -132,13 +120,6 @@ public override void Commit(CommandList commandList, Texture renderFrame) { OpenVR.Submit(0, renderFrame, ref leftView); OpenVR.Submit(1, renderFrame, ref rightView); - - if (needsMirror) - { - var wholeRegion = new ResourceRegion(0, 0, 0, ActualRenderFrameSize.Width, ActualRenderFrameSize.Height, 1); - commandList.CopyRegion(leftEyeMirror, 0, wholeRegion, bothEyesMirror, 0); - commandList.CopyRegion(rightEyeMirror, 0, wholeRegion, bothEyesMirror, 0, ActualRenderFrameSize.Width / 2); - } } public override void Recenter() { @@ -176,6 +157,10 @@ public override Size2 OptimalRenderFrameSize { get { uint width = 0, height = 0; Valve.VR.OpenVR.System.GetRecommendedRenderTargetSize(ref width, ref height); + width = (uint)(width * RenderFrameScaling); + width += width % 2; + height = (uint)(height * RenderFrameScaling); + height += height % 2; return new Size2((int)width, (int)height); } } diff --git a/sources/engine/Xenko.VirtualReality/VRApi.cs b/sources/engine/Xenko.VirtualReality/VRApi.cs index 22f431cf4c..5569c1269d 100644 --- a/sources/engine/Xenko.VirtualReality/VRApi.cs +++ b/sources/engine/Xenko.VirtualReality/VRApi.cs @@ -4,7 +4,7 @@ namespace Xenko.VirtualReality { public enum VRApi { - Oculus = 0, + //Oculus = 0, OpenVR = 1, //WindowsMixedReality = 2, Dummy = 100, diff --git a/sources/engine/Xenko.VirtualReality/VRDevice.cs b/sources/engine/Xenko.VirtualReality/VRDevice.cs index 28bcae58b2..a690fd831d 100644 --- a/sources/engine/Xenko.VirtualReality/VRDevice.cs +++ b/sources/engine/Xenko.VirtualReality/VRDevice.cs @@ -40,6 +40,8 @@ protected VRDevice() public abstract TrackedItem[] TrackedItems { get; } + public abstract ulong PoseCount { get; } + public VRApi VRApi { get; protected set; } /// @@ -61,7 +63,7 @@ public virtual void ReleaseOverlay(VROverlay overlay) { } - public abstract void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight); + public abstract void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror); public virtual void Recenter() { diff --git a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs index 36001aa542..66de877aa7 100644 --- a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs +++ b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs @@ -70,10 +70,6 @@ public VRDeviceSystem(IServiceRegistry registry) : base(registry) public bool RequireMirror; - public int MirrorWidth; - - public int MirrorHeight; - public bool PreviousUseCustomProjectionMatrix; public bool PreviousUseCustomViewMatrix; @@ -108,14 +104,14 @@ private void OnEnabledChanged(object sender, EventArgs eventArgs) Device = new DummyDevice(Services); break; } - case VRApi.Oculus: + /*case VRApi.Oculus: { #if XENKO_GRAPHICS_API_DIRECT3D11 Device = new OculusOvrHmd(); #endif break; - } + }*/ case VRApi.OpenVR: { #if XENKO_GRAPHICS_API_VULKAN || XENKO_GRAPHICS_API_DIRECT3D11 @@ -177,7 +173,7 @@ private void OnEnabledChanged(object sender, EventArgs eventArgs) deviceManager.SynchronizeWithVerticalRetrace = false; Device.RenderFrameScaling = PreferredScalings[Device.VRApi]; - Device.Enable(GraphicsDevice, deviceManager, RequireMirror, MirrorWidth, MirrorHeight); + Device.Enable(GraphicsDevice, deviceManager, RequireMirror); Device.SetTrackingSpace(TrackingSpace.Standing); physicalDeviceInUse = true; @@ -205,7 +201,7 @@ private void OnEnabledChanged(object sender, EventArgs eventArgs) Game = Game, RenderFrameScaling = 1.0f, }; - Device.Enable(GraphicsDevice, deviceManager, RequireMirror, MirrorWidth, MirrorHeight); + Device.Enable(GraphicsDevice, deviceManager, RequireMirror); } // init virtual buttons for use with VR input From 6ea07b8370ad4fb8617e8779bf9b5454a516e019 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 4 Dec 2019 12:57:30 -0500 Subject: [PATCH 0527/2038] VR: fixes for different VR forward renderer configurations & counts --- .../Rendering/Compositing/ForwardRenderer.cs | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index f8e28d7ec5..ba963f6366 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -209,16 +209,20 @@ protected override void InitializeCore() } else { - vrSystem.Enabled = false; - vrSystem.Visible = false; - + VRRenderers.Remove(this); VRSettings.VRDevice = null; - if (vrSystem.Device != null) //we had a device before so we know we need to restore the camera + if (VRRenderers.Count == 0) { - camera.UseCustomViewMatrix = vrSystem.PreviousUseCustomViewMatrix; - camera.UseCustomProjectionMatrix = vrSystem.PreviousUseCustomProjectionMatrix; - camera.ProjectionMatrix = vrSystem.PreviousCameraProjection; + vrSystem.Enabled = false; + vrSystem.Visible = false; + + if (vrSystem.Device != null) //we had a device before so we know we need to restore the camera + { + camera.UseCustomViewMatrix = vrSystem.PreviousUseCustomViewMatrix; + camera.UseCustomProjectionMatrix = vrSystem.PreviousUseCustomProjectionMatrix; + camera.ProjectionMatrix = vrSystem.PreviousCameraProjection; + } } } } @@ -663,7 +667,7 @@ protected override void DrawCore(RenderContext context, RenderDrawContext drawCo if (!isFullViewport) return; - var hasPostEffects = PostEffects != null; + bool hasPostEffects = PostEffects != null, presentingVR = this == VRRenderers[VRRenderers.Count - 1]; Texture vrFullSurface; using (drawContext.PushRenderTargetsAndRestore()) @@ -704,6 +708,12 @@ protected override void DrawCore(RenderContext context, RenderDrawContext drawCo // last eye, draw post effects over both eyes if we have some if (hasPostEffects && i == 1) { + if (presentingVR) + { + var renderTargetDescription = TextureDescription.New2D(frameSize.Width, frameSize.Height, 1, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.ShaderResource | TextureFlags.RenderTarget); + vrFullSurface = PushScopedResource(drawContext.GraphicsContext.Allocator.GetTemporaryTexture2D(renderTargetDescription)); + } + PostEffects.Draw(drawContext, OpaqueRenderStage.OutputValidator, currentRenderTargets.Items, currentDepthStencil, vrFullSurface); } } @@ -721,8 +731,7 @@ protected override void DrawCore(RenderContext context, RenderDrawContext drawCo } // if we are on our last forward renderer and our scene is ready for submission - if (this == VRRenderers[VRRenderers.Count - 1]) - VRSettings.VRDevice.Commit(drawContext.CommandList, vrFullSurface); + if (presentingVR) VRSettings.VRDevice.Commit(drawContext.CommandList, vrFullSurface); } } From fd3e6a3caeb1ed611381d40dc1492fc429a29e67 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 4 Dec 2019 21:34:03 -0500 Subject: [PATCH 0528/2038] VR: shortcut to enabling or disabling VR setting on any renderers easier for games to startup and pick whether it is in VR mode or not --- .../Compositing/GraphicsCompositor.cs | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/GraphicsCompositor.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/GraphicsCompositor.cs index 06dce434f5..39fefbd64d 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/GraphicsCompositor.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/GraphicsCompositor.cs @@ -74,6 +74,9 @@ public class GraphicsCompositor : RendererBase /// public ISceneRenderer Editor { get; set; } + [DataMemberIgnore] + private List cachedProcessor; + private void gatherPostProcessors(ISceneRenderer renderer) { if (renderer is SceneCameraRenderer scr) @@ -111,8 +114,31 @@ public List PostProcessing { } } - [DataMemberIgnore] - private List cachedProcessor; + /// + /// Shortcut to setting VR settings on renderers to enable or disable. Only renderers with Required APIs set will be enabled via this method. + /// + /// Whether to enable or disable VR settings on renderers + public void SetVRRenderers(bool enable) + { + recursiveVRSet(Game, enable); + } + + private void recursiveVRSet(ISceneRenderer r, bool enable) + { + if (r is ForwardRenderer fr) + { + fr.VRSettings.Enabled = enable && fr.VRSettings.RequiredApis.Count > 0; + } + else if (r is SceneCameraRenderer scr) + { + recursiveVRSet(scr.Child, enable); + } + else if (r is SceneRendererCollection src) + { + foreach (ISceneRenderer isr in src.Children) + recursiveVRSet(isr, enable); + } + } /// protected override void InitializeCore() From 5b04b2b03f6056f00a773234996d0b073897fe2b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 5 Dec 2019 20:41:06 -0500 Subject: [PATCH 0529/2038] PostProcessing: fix for Bright Filter and Color Transforms --- .../Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs | 2 +- .../Xenko.Rendering/Rendering/Images/IPostProcessingEffects.cs | 2 ++ .../Xenko.Rendering/Rendering/Images/PostProcessingEffects.cs | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index ba963f6366..6880a38664 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -830,7 +830,7 @@ private void PrepareRenderTargets(RenderDrawContext drawContext, Texture outputR for (int index = 0; index < renderTargets.Count; index++) { - if (renderTargets[index].Semantic is ColorTargetSemantic && actualMultisampleCount == MultisampleCount.None) + if (renderTargets[index].Semantic is ColorTargetSemantic && (PostEffects == null || PostEffects.RequiresRenderTargetChange == false) && actualMultisampleCount == MultisampleCount.None) { currentRenderTargets[index] = outputRenderTarget; } diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/IPostProcessingEffects.cs b/sources/engine/Xenko.Rendering/Rendering/Images/IPostProcessingEffects.cs index 4fd0a5170a..0b929c6119 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Images/IPostProcessingEffects.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Images/IPostProcessingEffects.cs @@ -18,5 +18,7 @@ public interface IPostProcessingEffects : ISharedRenderer, IDisposable bool RequiresNormalBuffer { get; } bool RequiresSpecularRoughnessBuffer { get; } + + bool RequiresRenderTargetChange { get; } } } diff --git a/sources/engine/Xenko.Rendering/Rendering/Images/PostProcessingEffects.cs b/sources/engine/Xenko.Rendering/Rendering/Images/PostProcessingEffects.cs index 1c910fa68a..e380c797e8 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Images/PostProcessingEffects.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Images/PostProcessingEffects.cs @@ -266,6 +266,8 @@ public void Draw(RenderDrawContext drawContext, RenderOutputValidator outputVali public bool RequiresSpecularRoughnessBuffer => LocalReflections.Enabled; + public bool RequiresRenderTargetChange => BrightFilter.Enabled || ColorTransforms.Enabled; + protected override void DrawCore(RenderDrawContext context) { var input = GetInput(0); From 4c09a907f482e43b50fc7ec0b9cdcee9b449f1be Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 6 Dec 2019 19:19:14 -0500 Subject: [PATCH 0530/2038] version bump to 3.4 --- sources/shared/SharedAssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index c3b23f22e2..0654911d09 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -25,7 +25,7 @@ internal class XenkoVersion /// /// The version used by editor for display purpose. 4th digit needs to be at least 1 if used (due to NuGet special cases). /// - public const string PublicVersion = "3.3.4"; + public const string PublicVersion = "3.4"; /// /// The current assembly version as text, currently same as . @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = "-beta02"; + public const string NuGetVersionSuffix = ""; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From e7b2a952ecb8e31b62ba1d2fef2f93a46b8b516f Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 6 Dec 2019 22:11:19 +0900 Subject: [PATCH 0531/2038] Lock height arrays for using them on another thread --- .../Xenko.Navigation/NavigationMeshBuilder.cs | 45 +++++----- .../Shapes/HeightfieldColliderShape.cs | 83 +++++++++++++++++-- 2 files changed, 103 insertions(+), 25 deletions(-) diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index 44441f00e1..0a3007b480 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -601,26 +601,33 @@ private void BuildInput(StaticColliderData[] collidersLocal, CollisionFilterGrou var mesh = GeometricPrimitive.Plane.New(width, length, width, length, normalDirection: NormalDirection.UpY, toLeftHanded: true); var arrayLength = heightfield.HeightStickWidth * heightfield.HeightStickLength; - switch (heightfield.HeightType) + + using (heightfield.LockToReadHeights()) { - case HeightfieldTypes.Short: - for (int i = 0; i < arrayLength; ++i) - { - mesh.Vertices[i].Position.Y = heightfield.ShortArray[i] * heightfield.HeightScale; - } - break; - case HeightfieldTypes.Byte: - for (int i = 0; i < arrayLength; ++i) - { - mesh.Vertices[i].Position.Y = heightfield.ByteArray[i] * heightfield.HeightScale; - } - break; - case HeightfieldTypes.Float: - for (int i = 0; i < arrayLength; ++i) - { - mesh.Vertices[i].Position.Y = heightfield.FloatArray[i]; - } - break; + switch (heightfield.HeightType) + { + case HeightfieldTypes.Short: + if (heightfield.ShortArray == null) continue; + for (int i = 0; i < arrayLength; ++i) + { + mesh.Vertices[i].Position.Y = heightfield.ShortArray[i] * heightfield.HeightScale; + } + break; + case HeightfieldTypes.Byte: + if (heightfield.ByteArray == null) continue; + for (int i = 0; i < arrayLength; ++i) + { + mesh.Vertices[i].Position.Y = heightfield.ByteArray[i] * heightfield.HeightScale; + } + break; + case HeightfieldTypes.Float: + if (heightfield.FloatArray == null) continue; + for (int i = 0; i < arrayLength; ++i) + { + mesh.Vertices[i].Position.Y = heightfield.FloatArray[i]; + } + break; + } } entityNavigationMeshInputBuilder.AppendMeshData(mesh, transform); diff --git a/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs b/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs index d3a0a482b3..30093b280d 100644 --- a/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs +++ b/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; using Xenko.Core; using Xenko.Core.Mathematics; using Xenko.Core.Threading; @@ -152,16 +153,86 @@ public override void UpdateDebugPrimitive(CommandList commandList, IDebugPrimiti heightfieldDebugPrimitive.Update(commandList); } + private readonly ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim(); + + ~HeightfieldColliderShape() + { + lockSlim.Dispose(); + } + public override void Dispose() { base.Dispose(); - ShortArray?.Dispose(); - ShortArray = null; - ByteArray?.Dispose(); - ByteArray = null; - FloatArray?.Dispose(); - FloatArray = null; + using (LockToReadAndWriteHeights()) + { + ShortArray?.Dispose(); + ShortArray = null; + ByteArray?.Dispose(); + ByteArray = null; + FloatArray?.Dispose(); + FloatArray = null; + } + } + + public HeightArrayLock LockToReadHeights() + { + return new HeightArrayLock(HeightArrayLock.LockTypes.Read, lockSlim); + } + + public HeightArrayLock LockToReadAndWriteHeights() + { + return new HeightArrayLock(HeightArrayLock.LockTypes.ReadWrite, lockSlim); + } + + public class HeightArrayLock : IDisposable + { + public enum LockTypes + { + Read = 0, + ReadWrite = 1, + } + + private readonly ReaderWriterLockSlim readerWriterLockSlim; + + internal HeightArrayLock(LockTypes lockType, ReaderWriterLockSlim lockSlim) + { + if (lockSlim == null) + { + throw new ArgumentNullException(nameof(lockSlim)); + } + + readerWriterLockSlim = lockSlim; + + switch (lockType) + { + case LockTypes.Read: + readerWriterLockSlim.EnterReadLock(); + break; + case LockTypes.ReadWrite: + readerWriterLockSlim.EnterWriteLock(); + break; + default: + throw new ArgumentException($"{ nameof(lockType) } is invalid type"); + } + } + + public void Unlock() + { + if (readerWriterLockSlim.IsReadLockHeld) + { + readerWriterLockSlim.ExitReadLock(); + } + else if (readerWriterLockSlim.IsWriteLockHeld) + { + readerWriterLockSlim.ExitWriteLock(); + } + } + + public void Dispose() + { + Unlock(); + } } private enum BulletPhyScalarType From 6001f2e4c2a8dd98243b0f546b4f9d7893262a46 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 11 Dec 2019 21:00:55 -0500 Subject: [PATCH 0532/2038] Physics: fix CollisionFlags management --- .../Elements/RigidbodyComponent.cs | 31 +++++++------------ .../Elements/StaticColliderComponent.cs | 2 +- 2 files changed, 13 insertions(+), 20 deletions(-) diff --git a/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs b/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs index a19ddbf0fd..4e0bf7ce84 100644 --- a/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs @@ -234,36 +234,29 @@ public RigidBodyTypes RigidBodyType } set { + if (type == value) return; + type = value; if (InternalRigidBody == null) return; + InternalRigidBody.InterpolationAngularVelocity = Vector3.Zero; + InternalRigidBody.LinearVelocity = Vector3.Zero; + InternalRigidBody.InterpolationAngularVelocity = Vector3.Zero; + InternalRigidBody.AngularVelocity = Vector3.Zero; + switch (value) { case RigidBodyTypes.Dynamic: - if (((int)InternalRigidBody.CollisionFlags & (int)BulletSharp.CollisionFlags.StaticObject) != 0) InternalRigidBody.CollisionFlags ^= BulletSharp.CollisionFlags.StaticObject; - if (((int)InternalRigidBody.CollisionFlags & (int)BulletSharp.CollisionFlags.KinematicObject) != 0) InternalRigidBody.CollisionFlags ^= BulletSharp.CollisionFlags.KinematicObject; - if (InternalRigidBody != null && Simulation != null && !OverrideGravity) InternalRigidBody.Gravity = Simulation.Gravity; - if (InternalRigidBody != null) - { - InternalRigidBody.InterpolationAngularVelocity = Vector3.Zero; - InternalRigidBody.LinearVelocity = Vector3.Zero; - InternalRigidBody.InterpolationAngularVelocity = Vector3.Zero; - InternalRigidBody.AngularVelocity = Vector3.Zero; - } + if (Simulation != null && !OverrideGravity) InternalRigidBody.Gravity = Simulation.Gravity; + InternalRigidBody.CollisionFlags &= ~BulletSharp.CollisionFlags.StaticObject; + InternalRigidBody.CollisionFlags &= ~BulletSharp.CollisionFlags.KinematicObject; break; case RigidBodyTypes.Kinematic: - if (((int)InternalRigidBody.CollisionFlags & (int)BulletSharp.CollisionFlags.StaticObject) != 0) InternalRigidBody.CollisionFlags ^= BulletSharp.CollisionFlags.StaticObject; + InternalRigidBody.CollisionFlags &= ~BulletSharp.CollisionFlags.StaticObject; InternalRigidBody.CollisionFlags |= BulletSharp.CollisionFlags.KinematicObject; - if (InternalRigidBody != null && !OverrideGravity) InternalRigidBody.Gravity = Vector3.Zero; - if (InternalRigidBody != null) - { - InternalRigidBody.InterpolationAngularVelocity = Vector3.Zero; - InternalRigidBody.LinearVelocity = Vector3.Zero; - InternalRigidBody.InterpolationAngularVelocity = Vector3.Zero; - InternalRigidBody.AngularVelocity = Vector3.Zero; - } + if (!OverrideGravity) InternalRigidBody.Gravity = Vector3.Zero; break; } } diff --git a/sources/engine/Xenko.Physics/Elements/StaticColliderComponent.cs b/sources/engine/Xenko.Physics/Elements/StaticColliderComponent.cs index e86d2a3aee..2854077c28 100644 --- a/sources/engine/Xenko.Physics/Elements/StaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Elements/StaticColliderComponent.cs @@ -18,7 +18,7 @@ protected override void OnAttach() UserObject = this, }; - NativeCollisionObject.CollisionFlags |= BulletSharp.CollisionFlags.NoContactResponse; + NativeCollisionObject.CollisionFlags |= BulletSharp.CollisionFlags.NoContactResponse | BulletSharp.CollisionFlags.StaticObject; if (ColliderShape.NeedsCustomCollisionCallback) { From 22b458f4bb933fc9143887df6d8d1bc884980434 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 12 Dec 2019 11:22:56 -0500 Subject: [PATCH 0533/2038] bump version to new beta --- sources/shared/SharedAssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 0654911d09..16faa10ea2 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -25,7 +25,7 @@ internal class XenkoVersion /// /// The version used by editor for display purpose. 4th digit needs to be at least 1 if used (due to NuGet special cases). /// - public const string PublicVersion = "3.4"; + public const string PublicVersion = "3.4.1"; /// /// The current assembly version as text, currently same as . @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = ""; + public const string NuGetVersionSuffix = "-beta01"; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From 9119d4a42620b602a06ee5298d1a234b249d25ce Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 13 Dec 2019 01:09:05 +0900 Subject: [PATCH 0534/2038] Rename EnableAlwaysUpdateDynamicShape to AlwaysUpdateDynamicShape --- sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs | 2 +- sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index 0a3007b480..505305dc78 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -451,7 +451,7 @@ private void BuildInput(StaticColliderData[] collidersLocal, CollisionFilterGrou colliderData.Previous = null; if (lastCache?.Objects.TryGetValue(colliderData.Component.Id, out colliderData.Previous) ?? false) { - if ((!NavigationMeshBuildUtils.IsDynamicShape(colliderData.Component.ColliderShape) || !colliderData.CacheSettings.EnableAlwaysUpdateDynamicShape) && + if ((!NavigationMeshBuildUtils.IsDynamicShape(colliderData.Component.ColliderShape) || !colliderData.CacheSettings.AlwaysUpdateDynamicShape) && (colliderData.Previous.ParameterHash == colliderData.ParameterHash)) { // In this case, we don't need to recalculate the geometry for this shape, since it wasn't changed diff --git a/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs b/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs index d0dc4f816e..29068c2121 100644 --- a/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs +++ b/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs @@ -5,6 +5,6 @@ namespace Xenko.Navigation { public class StaticColliderCacheSettings { - public bool EnableAlwaysUpdateDynamicShape = true; + public bool AlwaysUpdateDynamicShape = true; } } From 6041a625d2e4cef74109775525474886b07ecca7 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 13 Dec 2019 08:33:57 +0900 Subject: [PATCH 0535/2038] Add Component property to StaticColliderCacheSettings --- .../Navigation/NavigationMeshAssetCompiler.cs | 3 ++- .../Processors/StaticColliderProcessor.cs | 2 +- .../Xenko.Navigation/StaticColliderCacheSettings.cs | 9 +++++++++ sources/engine/Xenko.Navigation/StaticColliderData.cs | 2 +- 4 files changed, 13 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs index 57e27107a7..7d1ad8fd5c 100644 --- a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs @@ -285,7 +285,8 @@ private void EnsureClonedSceneAndHash() { staticColliderDatas.Add(new StaticColliderData { - Component = colliderComponent + Component = colliderComponent, + CacheSettings = new StaticColliderCacheSettings(colliderComponent), }); if (colliderComponent.Enabled && !colliderComponent.IsTrigger && ((int)asset.IncludedCollisionGroups & (int)colliderComponent.CollisionGroup) != 0) diff --git a/sources/engine/Xenko.Navigation/Processors/StaticColliderProcessor.cs b/sources/engine/Xenko.Navigation/Processors/StaticColliderProcessor.cs index 2d83a37347..8a853b931e 100644 --- a/sources/engine/Xenko.Navigation/Processors/StaticColliderProcessor.cs +++ b/sources/engine/Xenko.Navigation/Processors/StaticColliderProcessor.cs @@ -16,7 +16,7 @@ internal class StaticColliderProcessor : EntityProcessor protected override StaticColliderData GenerateComponentData(Entity entity, StaticColliderComponent component) { - return new StaticColliderData { Component = component }; + return new StaticColliderData { Component = component, CacheSettings = new StaticColliderCacheSettings(component), }; } /// diff --git a/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs b/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs index 29068c2121..4ceea9a764 100644 --- a/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs +++ b/sources/engine/Xenko.Navigation/StaticColliderCacheSettings.cs @@ -1,10 +1,19 @@ // Copyright (c) Xenko contributors (https://xenko.com) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Physics; + namespace Xenko.Navigation { public class StaticColliderCacheSettings { + public StaticColliderComponent Component { get; private set; } + public bool AlwaysUpdateDynamicShape = true; + + public StaticColliderCacheSettings(StaticColliderComponent staticCollider) + { + Component = staticCollider; + } } } diff --git a/sources/engine/Xenko.Navigation/StaticColliderData.cs b/sources/engine/Xenko.Navigation/StaticColliderData.cs index 36770164ad..1a8ce3335c 100644 --- a/sources/engine/Xenko.Navigation/StaticColliderData.cs +++ b/sources/engine/Xenko.Navigation/StaticColliderData.cs @@ -13,7 +13,7 @@ namespace Xenko.Navigation public class StaticColliderData { public StaticColliderComponent Component; - public readonly StaticColliderCacheSettings CacheSettings = new StaticColliderCacheSettings(); + public StaticColliderCacheSettings CacheSettings; internal int ParameterHash = 0; internal bool Processed = false; internal NavigationMeshInputBuilder InputBuilder; From cc7f3b49122176a58469678bcbc70fe04cb43081 Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Fri, 13 Dec 2019 08:34:17 +0900 Subject: [PATCH 0536/2038] Overloading GetStaticColliderCacheSettings to get all cache settings --- .../Xenko.Navigation/DynamicNavigationMeshSystem.cs | 2 ++ .../engine/Xenko.Navigation/NavigationMeshBuilder.cs | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs b/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs index 591cded9dc..69532ac107 100644 --- a/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs +++ b/sources/engine/Xenko.Navigation/DynamicNavigationMeshSystem.cs @@ -179,6 +179,8 @@ public async Task Rebuild() public StaticColliderCacheSettings GetStaticColliderCacheSettings(StaticColliderComponent staticCollider) => builder?.GetStaticColliderCacheSettings(staticCollider); + public StaticColliderCacheSettings[] GetStaticColliderCacheSettings() => builder?.GetStaticColliderCacheSettings(); + internal void InitializeSettingsFromNavigationSettings(NavigationSettings navigationSettings) { BuildSettings = navigationSettings.BuildSettings; diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs index 505305dc78..4fac7c1440 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuilder.cs @@ -89,6 +89,18 @@ public StaticColliderCacheSettings GetStaticColliderCacheSettings(StaticCollider } } + /// + /// Get all collider cache settings from the builder + /// + /// All collider cache settings that are valid currently + public StaticColliderCacheSettings[] GetStaticColliderCacheSettings() + { + lock (colliders) + { + return colliders.Select(c => c.CacheSettings).ToArray(); + } + } + /// /// Performs the build of a navigation mesh /// From 4799cd4c80044ce3993e16bf5697269b387c123a Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Mon, 16 Dec 2019 00:57:28 +0900 Subject: [PATCH 0537/2038] Fix the check whether collider shape needs the recreating at rebuilding navigation mesh --- .../Xenko.Navigation/NavigationMeshBuildUtils.cs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs b/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs index fd978ac8f0..26c31f3d58 100644 --- a/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs +++ b/sources/engine/Xenko.Navigation/NavigationMeshBuildUtils.cs @@ -188,21 +188,20 @@ public static bool HasLatestColliderShape(StaticColliderComponent collider) else { var compound = collider.ColliderShape as CompoundColliderShape; - var descriptions = collider.ColliderShape?.Description as PhysicsComponent.ColliderShapeCollection; - if ((compound == null) || (descriptions == null) || (descriptions.Count != collider.ColliderShapes.Count)) - { - return false; - } - else + if ((compound != null) && (compound.Count == collider.ColliderShapes.Count)) { for (int i = 0; i < compound.Count; ++i) { - if (!compound[i].Description.Match(collider.ColliderShapes[i])) + if (!collider.ColliderShapes[i].Match(compound[i].Description)) { return false; } } } + else + { + return false; + } } } From c21946db8d19e6ec0814d77f9c91365dba013eb4 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 18 Dec 2019 09:14:20 -0500 Subject: [PATCH 0538/2038] Project Templates: upgrade .NET frameworks --- .../Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 | 2 +- .../Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 | 2 +- .../Core/ProjectExecutable.macOS/$ProjectName$.csproj.t4 | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 index ba9ce1c847..ae9f74b0e1 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 @@ -2,7 +2,7 @@ - netcoreapp2.1 + netcoreapp2.2 linux-vulkan-x64 Resources\Icon.ico WinExe diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 index ec848b48cf..ac0dceb440 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Windows/$ProjectName$.csproj.t4 @@ -2,7 +2,7 @@ - net461 + net48 win-vulkan Resources\Icon.ico WinExe diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.macOS/$ProjectName$.csproj.t4 b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.macOS/$ProjectName$.csproj.t4 index e61a972653..1c715e255f 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.macOS/$ProjectName$.csproj.t4 +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.macOS/$ProjectName$.csproj.t4 @@ -2,7 +2,7 @@ - netcoreapp2.1 + netcoreapp2.2 osx-x64 Resources\Icon.ico WinExe From 739a56ea656b07e4c6845664f46fba8596fb7df2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 10:55:16 -0500 Subject: [PATCH 0539/2038] Physics: adding bepuphysics integration (code only, no GameStudio integration for now) --- deps/bepuphysics2/BepuPhysics.dll | 3 + deps/bepuphysics2/BepuPhysics.pdb | 3 + deps/bepuphysics2/BepuUtilities.dll | 3 + deps/bepuphysics2/BepuUtilities.pdb | 3 + sources/core/Xenko.Core/ServiceRegistry.cs | 7 + .../Game/EntityHierarchyEditorGame.cs | 2 +- .../Thumbnails/ThumbnailGenerator.cs | 2 +- sources/engine/Xenko.Games/GameBase.cs | 2 +- sources/engine/Xenko.Games/GameSystemBase.cs | 6 +- .../engine/Xenko.Physics/Bepu/BepuContact.cs | 13 + .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 178 +++++ .../Xenko.Physics/Bepu/BepuHitResult.cs | 29 + .../Bepu/BepuPhysicsComponent.cs | 154 ++++ .../Bepu/BepuRigidbodyComponent.cs | 491 ++++++++++++ .../Bepu/BepuSimpleThreadDispatcher.cs | 115 +++ .../Xenko.Physics/Bepu/BepuSimulation.cs | 747 ++++++++++++++++++ .../Bepu/BepuStaticColliderComponent.cs | 101 +++ .../Elements/RigidbodyComponent.cs | 6 +- .../Xenko.Physics/Engine/PhysicsProcessor.cs | 8 +- .../engine/Xenko.Physics/IPhysicsSystem.cs | 2 +- .../engine/Xenko.Physics/PhysicsSettings.cs | 2 +- ...llet2PhysicsSystem.cs => PhysicsSystem.cs} | 99 ++- .../engine/Xenko.Physics/Xenko.Physics.csproj | 13 +- .../NuGetAssemblyResolver.cs | 8 - 24 files changed, 1946 insertions(+), 51 deletions(-) create mode 100644 deps/bepuphysics2/BepuPhysics.dll create mode 100644 deps/bepuphysics2/BepuPhysics.pdb create mode 100644 deps/bepuphysics2/BepuUtilities.dll create mode 100644 deps/bepuphysics2/BepuUtilities.pdb create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuContact.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuHitResult.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs rename sources/engine/Xenko.Physics/{Bullet2PhysicsSystem.cs => PhysicsSystem.cs} (51%) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll new file mode 100644 index 0000000000..82fd4d32b1 --- /dev/null +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ab3c4a23b725f907cdebc8b3f85773587205091ea2f4f1e2256d6977b3930fb +size 706048 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb new file mode 100644 index 0000000000..266ae1157c --- /dev/null +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08bbd1710c884f1a31c246938cc2674f40d33ff3c1a0ce5abe4b6caeb63be510 +size 306132 diff --git a/deps/bepuphysics2/BepuUtilities.dll b/deps/bepuphysics2/BepuUtilities.dll new file mode 100644 index 0000000000..cfd585a89e --- /dev/null +++ b/deps/bepuphysics2/BepuUtilities.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9acf725ec6d278bc6fa115711455e7bb631809f67ca201cc63d44b9c5f40a47e +size 126464 diff --git a/deps/bepuphysics2/BepuUtilities.pdb b/deps/bepuphysics2/BepuUtilities.pdb new file mode 100644 index 0000000000..0ceb229e38 --- /dev/null +++ b/deps/bepuphysics2/BepuUtilities.pdb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ec7053a569de51042dde5c78dcb11251d1ec27c474e22f690db5f051a9831c5 +size 51596 diff --git a/sources/core/Xenko.Core/ServiceRegistry.cs b/sources/core/Xenko.Core/ServiceRegistry.cs index 58c0fc402b..3a34284546 100644 --- a/sources/core/Xenko.Core/ServiceRegistry.cs +++ b/sources/core/Xenko.Core/ServiceRegistry.cs @@ -40,6 +40,13 @@ public class ServiceRegistry : IServiceRegistry /// public event EventHandler ServiceRemoved; + public static ServiceRegistry instance { get; private set; } + + public ServiceRegistry(bool setMainInstance = false) + { + if (setMainInstance) instance = this; + } + /// public T GetService() where T : class diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EntityHierarchyEditorGame.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EntityHierarchyEditorGame.cs index 819af43b2f..6554f8bf62 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EntityHierarchyEditorGame.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/Game/EntityHierarchyEditorGame.cs @@ -258,7 +258,7 @@ protected override void Initialize() } //init physics system - var physicsSystem = new Bullet2PhysicsSystem(Services); + var physicsSystem = new PhysicsSystem(Services); Services.AddService(physicsSystem); GameSystems.Add(physicsSystem); } diff --git a/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs b/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs index 1e771e3ab7..8d7074bd25 100644 --- a/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs +++ b/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs @@ -118,7 +118,7 @@ public ThumbnailGenerator(EffectCompilerBase effectCompiler) var uiSystem = new UISystem(Services); Services.AddService(uiSystem); - var physicsSystem = new Bullet2PhysicsSystem(Services); + var physicsSystem = new PhysicsSystem(Services); Services.AddService(physicsSystem); gameSystems = new GameSystemCollection(Services) { fontSystem, uiSystem, physicsSystem }; diff --git a/sources/engine/Xenko.Games/GameBase.cs b/sources/engine/Xenko.Games/GameBase.cs index 1a342a63d6..762d44ed10 100644 --- a/sources/engine/Xenko.Games/GameBase.cs +++ b/sources/engine/Xenko.Games/GameBase.cs @@ -111,7 +111,7 @@ protected GameBase() updateCountAverageSlowLimit = (float)(maxLastCount + (lastUpdateCount.Length - maxLastCount)) / lastUpdateCount.Length; // Externals - Services = new ServiceRegistry(); + Services = new ServiceRegistry(true); // Database file provider Services.AddService(new DatabaseFileProviderService(null)); diff --git a/sources/engine/Xenko.Games/GameSystemBase.cs b/sources/engine/Xenko.Games/GameSystemBase.cs index d6feb2eaf9..5a524ef0c9 100644 --- a/sources/engine/Xenko.Games/GameSystemBase.cs +++ b/sources/engine/Xenko.Games/GameSystemBase.cs @@ -50,10 +50,10 @@ public abstract class GameSystemBase : ComponentBase, IGameSystemBase, IUpdateab /// /// The GameSystem is expecting the following services to be registered: and . /// - protected GameSystemBase([NotNull] IServiceRegistry registry) + protected GameSystemBase(IServiceRegistry registry) { - Services = registry ?? throw new ArgumentNullException(nameof(registry)); - Game = (GameBase)Services.GetService(); + Services = registry ?? ServiceRegistry.instance; + Game = (GameBase)Services?.GetService(); } /// diff --git a/sources/engine/Xenko.Physics/Bepu/BepuContact.cs b/sources/engine/Xenko.Physics/Bepu/BepuContact.cs new file mode 100644 index 0000000000..4261edef19 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuContact.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Engine; + +namespace Xenko.Physics.Bepu +{ + public struct BepuContact + { + public BepuPhysicsComponent A, B; + public Xenko.Core.Mathematics.Vector3 Normal, Position; + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs new file mode 100644 index 0000000000..0c69dced73 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -0,0 +1,178 @@ +/* + * - need to switch between which list index is processing for contact collection + * - need to clear list of index we will start populating + * - throw out contact information without normal or position information...? when count == 0...? + * + */ + +using System; +using System.Collections.Generic; +using System.Text; +using BepuPhysics.Collidables; +using BepuPhysics.Constraints; +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Games; +using Xenko.Graphics; +using Xenko.Rendering.Rendering; + +namespace Xenko.Physics.Bepu +{ + public class BepuHelpers + { + internal static PhysicsSystem physicsSystem; + + internal static void AssureServiceAdded() + { + if (physicsSystem == null) + { + physicsSystem = ServiceRegistry.instance.GetService(); + if (physicsSystem == null) + { + physicsSystem = new PhysicsSystem(ServiceRegistry.instance); + ServiceRegistry.instance.AddService(physicsSystem); + var gameSystems = ServiceRegistry.instance.GetSafeServiceAs(); + gameSystems.Add(physicsSystem); + ((IReferencable)physicsSystem).AddReference(); + physicsSystem.Create(null, PhysicsEngineFlags.None, true); + } + else if (physicsSystem.HasSimulation() == false) + { + physicsSystem.Create(null, PhysicsEngineFlags.None, true); + } + } + } + + public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) + { + Vector3[] positions; + int[] indicies; + + if (modelMesh.Draw is StagedMeshDraw) + { + StagedMeshDraw smd = modelMesh.Draw as StagedMeshDraw; + + object verts = smd.Verticies; + + if (verts is VertexPositionNormalColor[]) + { + VertexPositionNormalColor[] vpnc = verts as VertexPositionNormalColor[]; + positions = new Vector3[vpnc.Length]; + for (int k = 0; k < vpnc.Length; k++) + positions[k] = vpnc[k].Position; + } + else if (verts is VertexPositionNormalTexture[]) + { + VertexPositionNormalTexture[] vpnc = verts as VertexPositionNormalTexture[]; + positions = new Vector3[vpnc.Length]; + for (int k = 0; k < vpnc.Length; k++) + positions[k] = vpnc[k].Position; + } + else if (verts is VertexPositionNormalTextureTangent[]) + { + VertexPositionNormalTextureTangent[] vpnc = verts as VertexPositionNormalTextureTangent[]; + positions = new Vector3[vpnc.Length]; + for (int k = 0; k < vpnc.Length; k++) + positions[k] = vpnc[k].Position; + } + else + { + outMesh = new Mesh(); + return false; + } + + // take care of indicies + indicies = (int[])(object)smd.Indicies; + } + else + { + Xenko.Graphics.Buffer buf = modelMesh.Draw?.VertexBuffers[0].Buffer; + Xenko.Graphics.Buffer ibuf = modelMesh.Draw?.IndexBuffer.Buffer; + if (buf == null || buf.VertIndexData == null || + ibuf == null || ibuf.VertIndexData == null) + { + outMesh = new Mesh(); + return false; + } + + if (ModelBatcher.UnpackRawVertData(buf.VertIndexData, modelMesh.Draw.VertexBuffers[0].Declaration, + out positions, out Core.Mathematics.Vector3[] normals, out Core.Mathematics.Vector2[] uvs, + out Color4[] colors, out Vector4[] tangents) == false) + { + outMesh = new Mesh(); + return false; + } + + // indicies + fixed (byte* pdst = ibuf.VertIndexData) + { + if (modelMesh.Draw.IndexBuffer.Is32Bit) + { + var dst = (uint*)pdst; + + int numIndices = ibuf.VertIndexData.Length / sizeof(uint); + indicies = new int[numIndices]; + for (var k = 0; k < numIndices; k++) + { + // Offset indices + indicies[k] = (int)dst[k]; + } + } + else + { + var dst = (ushort*)pdst; + + int numIndices = ibuf.VertIndexData.Length / sizeof(ushort); + indicies = new int[numIndices]; + for (var k = 0; k < numIndices; k++) + { + // Offset indices + indicies[k] = dst[k]; + } + } + } + } + + return GenerateMeshShape(positions, indicies, out outMesh, scale); + } + + public static unsafe bool GenerateMeshShape(Vector3[] positions, int[] indicies, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) + { + // ok, should have what we need to make triangles + var memory = stackalloc Triangle[indicies.Length]; + BepuUtilities.Memory.Buffer triangles = new BepuUtilities.Memory.Buffer(memory, indicies.Length); + + for (int i = 0; i < indicies.Length; i += 3) + { + triangles[i].A = ToBepu(positions[indicies[i]]); + triangles[i].B = ToBepu(positions[indicies[i+1]]); + triangles[i].C = ToBepu(positions[indicies[i+2]]); + } + + outMesh = new Mesh(triangles, new System.Numerics.Vector3(scale?.X ?? 1f, scale?.Y ?? 1f, scale?.Z ?? 1f), BepuSimulation.instance.pBufferPool); + + return true; + } + + public static unsafe System.Numerics.Vector3 ToBepu(Xenko.Core.Mathematics.Vector3 v) + { + return *((System.Numerics.Vector3*)(void*)&v); + } + + public static unsafe Xenko.Core.Mathematics.Vector3 ToXenko(System.Numerics.Vector3 v) + { + return *((Xenko.Core.Mathematics.Vector3*)(void*)&v); + } + + public static unsafe Xenko.Core.Mathematics.Quaternion ToXenko(BepuUtilities.Quaternion q) + { + return *((Xenko.Core.Mathematics.Quaternion*)(void*)&q); + } + + public static unsafe BepuUtilities.Quaternion ToBepu(Xenko.Core.Mathematics.Quaternion q) + { + return *((BepuUtilities.Quaternion*)(void*)&q); + } + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHitResult.cs b/sources/engine/Xenko.Physics/Bepu/BepuHitResult.cs new file mode 100644 index 0000000000..0bde35c6a3 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuHitResult.cs @@ -0,0 +1,29 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System.Runtime.InteropServices; +using Xenko.Core.Mathematics; +using Xenko.Engine; + +namespace Xenko.Physics.Bepu +{ + /// + /// The result of a Physics Raycast or ShapeSweep operation + /// + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct BepuHitResult + { + public Vector3 Normal; + + public Vector3 Point; + + public float HitFraction; + + public bool Succeeded; + + /// + /// The Collider hit if Succeeded + /// + public BepuPhysicsComponent Collider; + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs new file mode 100644 index 0000000000..710f185ee8 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -0,0 +1,154 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using BepuPhysics; +using BepuPhysics.Constraints; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Core.MicroThreading; +using Xenko.Engine.Design; +using Xenko.Physics; +using Xenko.Physics.Bepu; +using Xenko.Physics.Engine; +using Xenko.Rendering; + +namespace Xenko.Engine +{ + [DataContract("BepuPhysicsComponent", Inherited = true)] + [Display("BepuPhysics", Expand = ExpandRule.Once)] + [AllowMultipleComponents] + [ComponentOrder(3100)] + //[ComponentCategory("BepuPhysics")] + public abstract class BepuPhysicsComponent : ActivableEntityComponent + { + protected static Logger logger = GlobalLogger.GetLogger("BepuPhysicsComponent"); + + internal int AddedHandle = -1; + + public int GetHandle() + { + return AddedHandle; + } + + public BepuPhysicsComponent() + { + BepuHelpers.AssureServiceAdded(); + } + + /// + /// Gets or sets the collision group. + /// + /// + /// The collision group. + /// + /// + /// Which collision group the component belongs to. This can't be changed at runtime. The default is DefaultFilter. + /// + /// + /// The collider will still produce events, to allow non trigger rigidbodies or static colliders to act as a trigger if required for certain filtering groups. + /// + [DataMember(30)] + [Display("Collision group")] + [DefaultValue(CollisionFilterGroups.DefaultFilter)] + public CollisionFilterGroups CollisionGroup { get; set; } = CollisionFilterGroups.DefaultFilter; + + /// + /// Gets or sets the can collide with. + /// + /// + /// The can collide with. + /// + /// + /// Which collider groups this component collides with. With nothing selected, it collides with all groups. This can't be changed at runtime. + /// + /// /// + /// The collider will still produce events, to allow non trigger rigidbodies or static colliders to act as a trigger if required for certain filtering groups. + /// + [DataMember(40)] + [Display("Collides with...")] + [DefaultValue(CollisionFilterGroupFlags.AllFilter)] + public CollisionFilterGroupFlags CanCollideWith { get; set; } = CollisionFilterGroupFlags.AllFilter; + + /// + /// When updating the associated TransformComponent, should we not set rotation? + /// + [DataMember(69)] + public bool IgnorePhysicsRotation = false; + + [DataMemberIgnore] + public Vector3? LocalPhysicsOffset = null; + + /// + /// Gets or sets the tag. + /// + /// + /// The tag. + /// + [DataMemberIgnore] + public string Tag { get; set; } + + [DataMember] + public float FrictionCoefficient = 0.5f; + + [DataMember] + public float MaximumRecoveryVelocity = 2f; + + [DataMember] + public SpringSettings SpringSettings = new SpringSettings(30f, 1f); + + #region Utility + + /// + /// Computes the physics transformation from the TransformComponent values + /// + /// + internal void DerivePhysicsTransform(ref Matrix fromMatrix, out Matrix outMatrix) + { + fromMatrix.Decompose(out Vector3 scale, out Matrix rotation, out Vector3 translation); + DerivePhysicsTransform(translation, rotation, scale, out outMatrix); + } + + internal void DerivePhysicsTransform(Vector3? worldPosition, Matrix? worldRotation, Vector3? worldScale, out Matrix outMatrix) + { + Vector3 translation = worldPosition ?? Entity.Transform.WorldPosition(), scale; + Matrix rotation; + + if( worldScale.HasValue ) { + scale = worldScale.Value; + } else { + Entity.Transform.WorldMatrix.GetScale(out scale); + } + + if (worldRotation.HasValue) { + rotation = worldRotation.Value; + } else { + Entity.Transform.WorldMatrix.GetRotationMatrix(out rotation); + } + + var translationMatrix = Matrix.Translation(translation); + Matrix.Multiply(ref rotation, ref translationMatrix, out outMatrix); + } + + internal virtual void UpdateTransformationComponent() { } + + [DataMemberIgnore] + public virtual Vector3 Position { get; set; } + + [DataMemberIgnore] + public virtual Quaternion Rotation { get; set; } + + /// + /// Is this a "ghost"? Useful for triggers that detect collisions, but don't cause them + /// + [DataMember] + public bool GhostBody { get; set; } + + #endregion Utility + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs new file mode 100644 index 0000000000..42456a1c73 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -0,0 +1,491 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.Collections.Generic; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Collections; +using Xenko.Core.Mathematics; +using Xenko.Rendering; +using BepuPhysics; +using BepuUtilities; +using Xenko.Engine; +using Xenko.Physics; +using BepuPhysics.Collidables; +using BepuPhysics.Constraints; + +namespace Xenko.Physics.Bepu +{ + [DataContract("BepuRigidbodyComponent")] + [Display("Bepu Rigidbody")] + public sealed class BepuRigidbodyComponent : BepuPhysicsComponent + { + public BodyDescription bodyDescription; + + private BodyReference _internalReference = new BodyReference(); + + public BodyReference InternalBody + { + get + { + _internalReference.Bodies = BepuSimulation.instance.internalSimulation.Bodies; + _internalReference.Handle = AddedHandle; + return _internalReference; + } + } + + public Action ActionPerSimulationTick; + + /// + /// Gets a value indicating whether this instance is active (awake). + /// + /// + /// true if this instance is active; otherwise, false. + /// + public bool IsActive => InternalBody.Awake; + + [DataMember(67)] + public float CcdMotionThreshold + { + get + { + return bodyDescription.Collidable.Continuity.SweepConvergenceThreshold; + } + set + { + bodyDescription.Collidable.Continuity.SweepConvergenceThreshold = value; + + if (InternalBody.Exists) + InternalBody.Collidable.Continuity.SweepConvergenceThreshold = value; + } + } + + /// + /// Gets or sets if this element will store collisions in CurrentPhysicalContacts. Uses less CPU than ProcessCollisions + /// + /// + /// true, false + /// + /// + /// Stores contact points in a simple CurrentPhysicalContacts list, instead of new/update/ended events. Uses less CPU than ProcessCollisions and is multithreading supported + /// + [Display("Simple collision storage")] + [DataMemberIgnore] + public bool CollectCollisions + { + get + { + return _collectCollisions; + } + set + { + if (value && processingPhysicalContacts == null) + { + processingPhysicalContacts = new List[2]; + processingPhysicalContacts[0] = new List(); + processingPhysicalContacts[1] = new List(); + } + _collectCollisions = value; + } + } + private bool _collectCollisions = false; + + /// + /// If we are using ProcessCollisionSlim, this list will maintain all current collisions + /// + [DataMemberIgnore] + public List CurrentContacts + { + get + { + if (processingPhysicalContacts == null) return null; + + return new List(processingPhysicalContacts[processingPhysicalContactsIndex]); + } + } + + internal void swapProcessingContactsList() + { + if (processingPhysicalContacts == null || IsActive == false) return; + + processingPhysicalContacts[processingPhysicalContactsIndex].Clear(); + processingPhysicalContactsIndex ^= 1; + } + + internal List[] processingPhysicalContacts; + internal int processingPhysicalContactsIndex; + + private static readonly BodyInertia KinematicInertia = new BodyInertia() + { + InverseMass = 0f, + InverseInertiaTensor = new Symmetric3x3() + { + XX = 0f, + YX = 0f, + ZX = 0f, + YY = 0f, + ZY = 0f, + ZZ = 0f + } + }; + + private RigidBodyTypes type = RigidBodyTypes.Dynamic; + private Vector3 gravity = Vector3.Zero; + + public BepuRigidbodyComponent() : base() + { + bodyDescription = new BodyDescription(); + bodyDescription.LocalInertia.InverseMass = 1f; + bodyDescription.Activity.MinimumTimestepCountUnderThreshold = 32; + bodyDescription.Activity.SleepThreshold = 0.01f; + } + + /// + /// Attempts to awake the collider. + /// + /// if set to true [force activation]. + public void Activate() + { + BodyReference ib = InternalBody; + ib.Awake = true; + } + + /// + /// Gets or sets the rolling friction of this element + /// + /// + /// true, false + /// + /// + /// The rolling friction + /// + [DataMember(66)] + public float RollingFriction => 0f; + + public float SleepThreshold + { + get + { + return bodyDescription.Activity.SleepThreshold; + } + set + { + bodyDescription.Activity.SleepThreshold = value; + + if (InternalBody.Exists) + InternalBody.Activity.SleepThreshold = value; + } + } + + /// + /// Gets or sets the mass of this Rigidbody + /// + /// + /// true, false + /// + /// + /// Objects with higher mass push objects with lower mass more when they collide. For large differences, use point values; for example, write 0.1 or 10, not 1 or 100000. + /// + [DataMember(80)] + [DataMemberRange(0, 6)] + public float Mass + { + get + { + return mass; + } + set + { + if (mass <= 0.00001f) mass = 0.00001f; + + mass = value; + + UpdateInertia(); + } + } + + private void UpdateInertia() + { + if (type == RigidBodyTypes.Kinematic) + { + bodyDescription.LocalInertia = KinematicInertia; + } + else if (ColliderShape != null) + { + ColliderShape.ComputeInertia(mass, out bodyDescription.LocalInertia); + } + + if (InternalBody.Exists) + { + InternalBody.LocalInertia = bodyDescription.LocalInertia; + } + } + + private IConvexShape _myshape; + + public IConvexShape ColliderShape + { + get => _myshape; + set + { + bool wasAddedToScene = AddedToScene; + + AddedToScene = false; + + _myshape = value; + UpdateInertia(); + + AddedToScene = wasAddedToScene; + } + } + + public void ReloadColliderShape() + { + if (_myshape == null || AddedToScene == false) return; + ColliderShape = _myshape; + } + + private float mass = 1f; + + /// + /// Gets or sets the linear damping of this rigidbody + /// + /// + /// true, false + /// + /// + /// The amount of damping for directional forces + /// + [DataMember(85)] + public float LinearDamping = 0f; + + /// + /// Gets or sets the angular damping of this rigidbody + /// + /// + /// true, false + /// + /// + /// The amount of damping for rotational forces + /// + [DataMember(90)] + public float AngularDamping = 0f; + + /// + /// Gets or sets if this Rigidbody overrides world gravity + /// + /// + /// true, false + /// + /// + /// Override gravity with the vector specified in Gravity + /// + [DataMember(95)] + public bool OverrideGravity; + + /// + /// Gets or sets the gravity acceleration applied to this RigidBody + /// + /// + /// A vector representing moment and direction + /// + /// + /// The gravity acceleration applied to this rigidbody + /// + [DataMember(100)] + public Vector3 Gravity; + + /// + /// Gets or sets the type. + /// + /// + /// The type. + /// + public RigidBodyTypes RigidBodyType + { + get + { + return type; + } + set + { + type = value; + + UpdateInertia(); + } + } + + [DataMemberIgnore] + public bool AddedToScene + { + get + { + return AddedHandle != -1; + } + set + { + if (AddedToScene == value) return; + + if (value) + { + Mass = mass; + RigidBodyType = type; + BepuSimulation.instance.AddRigidBody(this, (CollisionFilterGroupFlags)CollisionGroup, CanCollideWith); + SleepThreshold = bodyDescription.Activity.SleepThreshold; + Position = Entity.Transform.WorldPosition(); + Rotation = Entity.Transform.WorldRotation(); + } + else + { + if (processingPhysicalContacts != null) + { + processingPhysicalContacts[0].Clear(); + processingPhysicalContacts[1].Clear(); + } + + BepuSimulation.instance.RemoveRigidBody(this); + } + } + } + + /// + /// Applies the impulse. + /// + /// The impulse. + public void ApplyImpulse(Vector3 impulse) + { + System.Numerics.Vector3 i = new System.Numerics.Vector3(impulse.X, impulse.Y, impulse.Z); + InternalBody.ApplyLinearImpulse(i); + } + + /// + /// Applies the impulse. + /// + /// The impulse. + /// The local offset. + public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) + { + System.Numerics.Vector3 i = new System.Numerics.Vector3(impulse.X, impulse.Y, impulse.Z); + System.Numerics.Vector3 o = new System.Numerics.Vector3(localOffset.X, localOffset.Y, localOffset.Z); + InternalBody.ApplyImpulse(i, o); + } + + /// + /// Applies the torque impulse. + /// + /// The torque. + public void ApplyTorqueImpulse(Vector3 torque) + { + System.Numerics.Vector3 i = new System.Numerics.Vector3(torque.X, torque.Y, torque.Z); + InternalBody.ApplyAngularImpulse(i); + } + + [DataMemberIgnore] + public override Vector3 Position + { + get + { + return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Pose.Position : bodyDescription.Pose.Position); + } + set + { + bodyDescription.Pose.Position.X = value.X; + bodyDescription.Pose.Position.Y = value.Y; + bodyDescription.Pose.Position.Z = value.Z; + + if (InternalBody.Exists) + { + InternalBody.Pose.Position = bodyDescription.Pose.Position; + } + } + } + + [DataMemberIgnore] + public override Xenko.Core.Mathematics.Quaternion Rotation + { + get + { + return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); + } + set + { + bodyDescription.Pose.Orientation.X = value.X; + bodyDescription.Pose.Orientation.Y = value.Y; + bodyDescription.Pose.Orientation.Z = value.Z; + bodyDescription.Pose.Orientation.Z = value.W; + + if (InternalBody.Exists) + { + InternalBody.Pose.Orientation = bodyDescription.Pose.Orientation; + } + } + } + + /// + /// Gets or sets the angular velocity. + /// + /// + /// The angular velocity. + /// + [DataMemberIgnore] + public Vector3 AngularVelocity + { + get + { + return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Velocity.Angular : bodyDescription.Velocity.Angular); + } + set + { + bodyDescription.Velocity.Angular.X = value.X; + bodyDescription.Velocity.Angular.Y = value.Y; + bodyDescription.Velocity.Angular.Z = value.Z; + + if (InternalBody.Exists) + { + InternalBody.Velocity.Angular = bodyDescription.Velocity.Angular; + } + } + } + + /// + /// Gets or sets the linear velocity. + /// + /// + /// The linear velocity. + /// + [DataMemberIgnore] + public Vector3 LinearVelocity + { + get + { + return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Velocity.Linear : bodyDescription.Velocity.Linear); + } + set + { + bodyDescription.Velocity.Linear.X = value.X; + bodyDescription.Velocity.Linear.Y = value.Y; + bodyDescription.Velocity.Linear.Z = value.Z; + + if (InternalBody.Exists) + { + InternalBody.Velocity.Linear = bodyDescription.Velocity.Linear; + } + } + } + + /// + /// Updades the graphics transformation from the given physics transformation + /// + /// + internal override void UpdateTransformationComponent() + { + var entity = Entity; + + entity.Transform.Position = Position; + if (LocalPhysicsOffset.HasValue) entity.Transform.Position += LocalPhysicsOffset.Value; + if (IgnorePhysicsRotation == false) entity.Transform.Rotation = Rotation; + } + + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs new file mode 100644 index 0000000000..b952e1dea9 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading; +using BepuUtilities; +using BepuUtilities.Memory; + +namespace Xenko.Physics.Engine +{ + internal class BepuSimpleThreadDispatcher : IThreadDispatcher, IDisposable + { + int threadCount; + public int ThreadCount => threadCount; + struct Worker + { + public Thread Thread; + public AutoResetEvent Signal; + } + + Worker[] workers; + AutoResetEvent finished; + + BufferPool[] bufferPools; + + public BepuSimpleThreadDispatcher(int threadCount) + { + this.threadCount = threadCount; + workers = new Worker[threadCount - 1]; + for (int i = 0; i < workers.Length; ++i) + { + workers[i] = new Worker { Thread = new Thread(WorkerLoop), Signal = new AutoResetEvent(false) }; + workers[i].Thread.IsBackground = true; + workers[i].Thread.Start(workers[i].Signal); + } + finished = new AutoResetEvent(false); + bufferPools = new BufferPool[threadCount]; + for (int i = 0; i < bufferPools.Length; ++i) + { + bufferPools[i] = new BufferPool(); + } + } + + void DispatchThread(int workerIndex) + { + //Debug.Assert(workerBody != null); + workerBody(workerIndex); + + if (Interlocked.Increment(ref completedWorkerCounter) == threadCount) + { + finished.Set(); + } + } + + volatile Action workerBody; + int workerIndex; + int completedWorkerCounter; + + void WorkerLoop(object untypedSignal) + { + var signal = (AutoResetEvent)untypedSignal; + while (true) + { + signal.WaitOne(); + if (disposed) + return; + DispatchThread(Interlocked.Increment(ref workerIndex) - 1); + } + } + + void SignalThreads() + { + for (int i = 0; i < workers.Length; ++i) + { + workers[i].Signal.Set(); + } + } + + public void DispatchWorkers(Action workerBody) + { + //Debug.Assert(this.workerBody == null); + workerIndex = 1; //Just make the inline thread worker 0. While the other threads might start executing first, the user should never rely on the dispatch order. + completedWorkerCounter = 0; + this.workerBody = workerBody; + SignalThreads(); + //Calling thread does work. No reason to spin up another worker and block this one! + DispatchThread(0); + finished.WaitOne(); + this.workerBody = null; + } + + volatile bool disposed; + public void Dispose() + { + if (!disposed) + { + disposed = true; + SignalThreads(); + for (int i = 0; i < bufferPools.Length; ++i) + { + bufferPools[i].Clear(); + } + foreach (var worker in workers) + { + worker.Thread.Join(); + worker.Signal.Dispose(); + } + } + } + + public BufferPool GetThreadMemoryPool(int workerIndex) + { + return bufferPools[workerIndex]; + } + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs new file mode 100644 index 0000000000..c40dcbe6be --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -0,0 +1,747 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Security; +using System.Threading; +using BepuPhysics; +using BepuPhysics.Collidables; +using BepuPhysics.CollisionDetection; +using BepuPhysics.Constraints; +using BepuPhysics.Trees; +using BepuUtilities; +using BepuUtilities.Memory; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Physics.Engine; +using Xenko.Rendering; + +namespace Xenko.Physics.Bepu +{ + public class BepuSimulation : IDisposable + { + private const CollisionFilterGroups DefaultGroup = CollisionFilterGroups.DefaultFilter; + private const CollisionFilterGroupFlags DefaultFlags = CollisionFilterGroupFlags.AllFilter; + + public BepuPhysics.Simulation internalSimulation; + public static BepuSimulation instance; + + private PoseIntegratorCallbacks poseCallbacks; + internal BufferPool pBufferPool; + private BepuSimpleThreadDispatcher threadDispatcher = new BepuSimpleThreadDispatcher(Environment.ProcessorCount); + +#if DEBUG + private static readonly Logger Log = GlobalLogger.GetLogger(typeof(Simulation).FullName); +#endif + + /// + /// Totally disable the simulation if set to true + /// + public static bool DisableSimulation = false; + + internal static Dictionary StaticMappings = new Dictionary(); + internal static Dictionary RigidMappings = new Dictionary(); + + internal List AllRigidbodies = new List(); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static BepuRigidbodyComponent getRigidFromIndex(int index) + { + return RigidMappings[instance.internalSimulation.Bodies.ActiveSet.IndexToHandle[index]]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static BepuPhysicsComponent getFromHandle(int handle, CollidableMobility mobility) + { + return mobility == CollidableMobility.Static ? (BepuPhysicsComponent)StaticMappings[handle] : (BepuPhysicsComponent)RigidMappings[handle]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static BepuPhysicsComponent getFromReference(CollidableReference cref) + { + return cref.Mobility == CollidableMobility.Static ? (BepuPhysicsComponent)StaticMappings[cref.Handle] : (BepuPhysicsComponent)RigidMappings[cref.Handle]; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool CanCollide(int source, CollidableMobility sourcemob, int target, CollidableMobility targetmob) + { + return ((uint)getFromHandle(source, sourcemob).CollisionGroup & (uint)getFromHandle(target, targetmob).CanCollideWith) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static bool CanCollide(CollidableReference a, CollidableReference b) + { + return ((uint)getFromReference(a).CollisionGroup & (uint)getFromReference(b).CanCollideWith) != 0; + } + + unsafe struct NarrowPhaseCallbacks : INarrowPhaseCallbacks + { + /// + /// Performs any required initialization logic after the Simulation instance has been constructed. + /// + /// Simulation that owns these callbacks. + public void Initialize(BepuPhysics.Simulation simulation) + { + //Often, the callbacks type is created before the simulation instance is fully constructed, so the simulation will call this function when it's ready. + //Any logic which depends on the simulation existing can be put here. + } + + /// + /// Chooses whether to allow contact generation to proceed for two overlapping collidables. + /// + /// Index of the worker that identified the overlap. + /// Reference to the first collidable in the pair. + /// Reference to the second collidable in the pair. + /// True if collision detection should proceed, false otherwise. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowContactGeneration(int workerIndex, CollidableReference a, CollidableReference b) + { + //Before creating a narrow phase pair, the broad phase asks this callback whether to bother with a given pair of objects. + //This can be used to implement arbitrary forms of collision filtering. See the RagdollDemo or NewtDemo for examples. + //Here, we'll make sure at least one of the two bodies is dynamic. + //The engine won't generate static-static pairs, but it will generate kinematic-kinematic pairs. + //That's useful if you're trying to make some sort of sensor/trigger object, but since kinematic-kinematic pairs + //can't generate constraints (both bodies have infinite inertia), simple simulations can just ignore such pairs. + return (a.Mobility == CollidableMobility.Dynamic || b.Mobility == CollidableMobility.Dynamic) && CanCollide(a, b); + } + + /// + /// Chooses whether to allow contact generation to proceed for the children of two overlapping collidables in a compound-including pair. + /// + /// Parent pair of the two child collidables. + /// Index of the child of collidable A in the pair. If collidable A is not compound, then this is always 0. + /// Index of the child of collidable B in the pair. If collidable B is not compound, then this is always 0. + /// True if collision detection should proceed, false otherwise. + /// This is called for each sub-overlap in a collidable pair involving compound collidables. If neither collidable in a pair is compound, this will not be called. + /// For compound-including pairs, if the earlier call to AllowContactGeneration returns false for owning pair, this will not be called. Note that it is possible + /// for this function to be called twice for the same subpair if the pair has continuous collision detection enabled; + /// the CCD sweep test that runs before the contact generation test also asks before performing child pair tests. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB) + { + //This is similar to the top level broad phase callback above. It's called by the narrow phase before generating + //subpairs between children in parent shapes. + //This only gets called in pairs that involve at least one shape type that can contain multiple children, like a Compound. + return CanCollide(pair.A, pair.B); + } + + public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponent B, TManifold manifold) where TManifold : struct, IContactManifold + { + BepuRigidbodyComponent ar = (A as BepuRigidbodyComponent); + BepuRigidbodyComponent br = (B as BepuRigidbodyComponent); + bool Acollect = (ar?.CollectCollisions ?? false); + bool Bcollect = (br?.CollectCollisions ?? false); + // do we want to store this collision? + if (Acollect || Bcollect) + { + BepuContact bc = new BepuContact() + { + A = A, + B = B, + Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), + Position = B.Position - BepuHelpers.ToXenko(manifold.SimpleGetOffset()) + }; + if (Acollect) ar.processingPhysicalContacts[ar.processingPhysicalContactsIndex ^ 1].Add(bc); + if (Bcollect) br.processingPhysicalContacts[br.processingPhysicalContactsIndex ^ 1].Add(bc); + } + } + + /// + /// Provides a notification that a manifold has been created for a pair. Offers an opportunity to change the manifold's details. + /// + /// Index of the worker thread that created this manifold. + /// Pair of collidables that the manifold was detected between. + /// Set of contacts detected between the collidables. + /// Material properties of the manifold. + /// True if a constraint should be created for the manifold, false otherwise. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe bool ConfigureContactManifold(int workerIndex, CollidablePair pair, ref TManifold manifold, out PairMaterialProperties pairMaterial) where TManifold : struct, IContactManifold + { + BepuPhysicsComponent a = getFromReference(pair.A); + BepuPhysicsComponent b = getFromReference(pair.B); + pairMaterial.FrictionCoefficient = a.FrictionCoefficient * b.FrictionCoefficient; + pairMaterial.MaximumRecoveryVelocity = a.MaximumRecoveryVelocity * b.MaximumRecoveryVelocity; + pairMaterial.SpringSettings = a.SpringSettings; + if (((uint)a.CanCollideWith & (uint)b.CollisionGroup) != 0) + { + RecordContact(a, b, manifold); + return !a.GhostBody && !b.GhostBody; + } + return false; + } + + /// + /// Provides a notification that a manifold has been created between the children of two collidables in a compound-including pair. + /// Offers an opportunity to change the manifold's details. + /// + /// Index of the worker thread that created this manifold. + /// Pair of collidables that the manifold was detected between. + /// Index of the child of collidable A in the pair. If collidable A is not compound, then this is always 0. + /// Index of the child of collidable B in the pair. If collidable B is not compound, then this is always 0. + /// Set of contacts detected between the collidables. + /// True if this manifold should be considered for constraint generation, false otherwise. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool ConfigureContactManifold(int workerIndex, CollidablePair pair, int childIndexA, int childIndexB, ref ConvexContactManifold manifold) + { + BepuPhysicsComponent A = getFromReference(pair.A); + BepuPhysicsComponent B = getFromReference(pair.B); + if (((uint)A.CanCollideWith & (uint)B.CollisionGroup) != 0) + { + RecordContact(A, B, manifold); + return !A.GhostBody && !B.GhostBody; + } + return false; + } + + /// + /// Releases any resources held by the callbacks. Called by the owning narrow phase when it is being disposed. + /// + public void Dispose() + { + } + } + + //Note that the engine does not require any particular form of gravity- it, like all the contact callbacks, is managed by a callback. + public struct PoseIntegratorCallbacks : IPoseIntegratorCallbacks + { + System.Numerics.Vector3 gravityDt; + public System.Numerics.Vector3 Gravity; + float indt; + + /// + /// Gets how the pose integrator should handle angular velocity integration. + /// + public AngularIntegrationMode AngularIntegrationMode => AngularIntegrationMode.Nonconserving; //Don't care about fidelity in this demo! + + public PoseIntegratorCallbacks(System.Numerics.Vector3 gravity) : this() + { + Gravity = gravity; + } + + /// + /// Called prior to integrating the simulation's active bodies. When used with a substepping timestepper, this could be called multiple times per frame with different time step values. + /// + /// Current time step duration. + public void PrepareForIntegration(float dt) + { + //No reason to recalculate gravity * dt for every body; just cache it ahead of time. + gravityDt = Gravity * dt; + indt = dt; + } + + /// + /// Callback called for each active body within the simulation during body integration. + /// + /// Index of the body being visited. + /// Body's current pose. + /// Body's current local inertia. + /// Index of the worker thread processing this body. + /// Reference to the body's current velocity to integrate. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void IntegrateVelocity(int bodyIndex, in RigidPose pose, in BodyInertia localInertia, int workerIndex, ref BodyVelocity velocity) + { + //Note that we avoid accelerating kinematics. Kinematics are any body with an inverse mass of zero (so a mass of ~infinity). No force can move them. + if (localInertia.InverseMass > 0) + { + BepuRigidbodyComponent rb = BepuSimulation.getRigidFromIndex(bodyIndex) as BepuRigidbodyComponent; + + velocity.Linear += rb.OverrideGravity ? BepuHelpers.ToBepu(rb.Gravity) * indt : gravityDt; + + // damping? + if (rb.LinearDamping > 0f) + velocity.Linear -= velocity.Linear * indt * rb.LinearDamping; + + if (rb.AngularDamping > 0f) + velocity.Angular -= velocity.Angular * indt * rb.AngularDamping; + } + } + } + + /// + /// Initializes the Physics engine using the specified flags. + /// + /// + /// + /// SoftBody processing is not yet available + internal BepuSimulation(PhysicsSettings configuration) + { + MaxSubSteps = configuration.MaxSubSteps; + FixedTimeStep = configuration.FixedTimeStep; + + pBufferPool = new BufferPool(); + poseCallbacks = new PoseIntegratorCallbacks(new System.Numerics.Vector3(0f, -9.81f, 0f)); + internalSimulation = BepuPhysics.Simulation.Create(pBufferPool, new NarrowPhaseCallbacks(), poseCallbacks); + instance = this; + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + + } + + public RenderGroup ColliderShapesRenderGroup { get; set; } = RenderGroup.Group0; + + internal void AddCollider(BepuStaticColliderComponent component, CollisionFilterGroupFlags group, CollisionFilterGroupFlags mask) + { + if (component.AddedHandle > -1) return; // already added + component.staticDescription.Collidable = component.ColliderShape.GenerateDescription(internalSimulation); + component.AddedHandle = internalSimulation.Statics.Add(component.staticDescription); + StaticMappings[component.AddedHandle] = component; + } + + internal void RemoveCollider(BepuStaticColliderComponent component) + { + int addedIndex = component.AddedHandle; + if (addedIndex == -1) return; // already removed + internalSimulation.Statics.Remove(addedIndex); + component.AddedHandle = -1; + StaticMappings.Remove(addedIndex); + } + + internal void AddRigidBody(BepuRigidbodyComponent rigidBody, CollisionFilterGroupFlags group, CollisionFilterGroupFlags mask) + { + if (rigidBody.AddedHandle > -1) return; // already added + rigidBody.ColliderShape.ComputeInertia(rigidBody.Mass, out rigidBody.bodyDescription.LocalInertia); + rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); + RigidMappings[rigidBody.AddedHandle] = rigidBody; + AllRigidbodies.Add(rigidBody); + } + + internal void RemoveRigidBody(BepuRigidbodyComponent rigidBody) + { + int addedIndex = rigidBody.AddedHandle; + if (addedIndex == -1) return; // already removed + internalSimulation.Bodies.Remove(addedIndex); + rigidBody.AddedHandle = -1; + RigidMappings.Remove(rigidBody.AddedHandle); + AllRigidbodies.Remove(rigidBody); + } + + struct RayHitClosestHandler : IRayHitHandler + { + public CollisionFilterGroupFlags findGroups; + public float T, startLength; + public BepuHitResult HitCollidable; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)findGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable, int childIndex) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)findGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Numerics.Vector3 normal, CollidableReference collidable, int childIndex) + { + if (t < T) + { + //Cache the earliest impact. + T = t; + HitCollidable.HitFraction = t / startLength; + HitCollidable.Normal.X = normal.X; + HitCollidable.Normal.Y = normal.Y; + HitCollidable.Normal.Z = normal.Z; + HitCollidable.Point.X = ray.Origin.X + ray.Direction.X * t; + HitCollidable.Point.Y = ray.Origin.Y + ray.Direction.Y * t; + HitCollidable.Point.Z = ray.Origin.Z + ray.Direction.Z * t; + HitCollidable.Collider = getFromReference(collidable); + HitCollidable.Succeeded = true; + } + + //We are only interested in the earliest hit. This callback is executing within the traversal, so modifying maximumT informs the traversal + //that it can skip any AABBs which are more distant than the new maximumT. + if (t < maximumT) + maximumT = t; + } + } + + struct RayHitAllHandler : IRayHitHandler + { + public CollisionFilterGroupFlags hitGroups; + public float startLength; + public List HitCollidables; + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)hitGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable, int childIndex) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)hitGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Numerics.Vector3 normal, CollidableReference collidable, int childIndex) + { + BepuHitResult HitCollidable = new BepuHitResult(); + HitCollidable.HitFraction = t / startLength; + HitCollidable.Normal.X = normal.X; + HitCollidable.Normal.Y = normal.Y; + HitCollidable.Normal.Z = normal.Z; + HitCollidable.Point.X = ray.Origin.X + ray.Direction.X * t; + HitCollidable.Point.Y = ray.Origin.Y + ray.Direction.Y * t; + HitCollidable.Point.Z = ray.Origin.Z + ray.Direction.Z * t; + HitCollidable.Collider = getFromReference(collidable); + HitCollidable.Succeeded = true; + HitCollidables.Add(HitCollidable); + } + } + + /// + /// Raycasts and returns the closest hit + /// + /// From. + /// To. + /// The collision group of this raycast + /// The collision group that this raycast can collide with + /// The list with hit results. + public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + RayHitClosestHandler rhch = new RayHitClosestHandler() + { + findGroups = hitGroups, + startLength = length + }; + internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); + return rhch.HitCollidable; + } + + /// + /// Raycasts penetrating any shape the ray encounters. + /// Filtering by CollisionGroup + /// + /// From. + /// To. + /// The list to fill with results. + /// The collision group of this raycast + /// The collision group that this raycast can collide with + public void RaycastPenetrating(Vector3 from, Vector3 direction, float length, List resultsOutput, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + RayHitAllHandler rhch = new RayHitAllHandler() + { + hitGroups = hitGroups, + HitCollidables = resultsOutput, + startLength = length + }; + internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); + } + + struct SweepTestFirst : ISweepHitHandler + { + public CollisionFilterGroupFlags hitGroups; + public BepuHitResult result; + public float T, startLength; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)hitGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable, int child) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)hitGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLocation, in System.Numerics.Vector3 hitNormal, CollidableReference collidable) + { + if (t < T) + { + T = t; + result.Succeeded = true; + result.Collider = getFromReference(collidable); + result.Normal.X = hitNormal.X; + result.Normal.Y = hitNormal.Y; + result.Normal.Z = hitNormal.Z; + result.Point.X = hitLocation.X; + result.Point.Y = hitLocation.Y; + result.Point.Z = hitLocation.Z; + result.HitFraction = t / startLength; + } + + //Changing the maximum T value prevents the traversal from visiting any leaf nodes more distant than that later in the traversal. + //It is effectively an optimization that you can use if you only care about the time of first impact. + if (t < maximumT) + maximumT = t; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) + { + result.Succeeded = true; + result.Collider = getFromReference(collidable); + maximumT = 0; + T = 0; + } + } + + struct SweepTestAll : ISweepHitHandler + { + public CollisionFilterGroupFlags hitGroups; + public List results; + public float startLength; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)hitGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowTest(CollidableReference collidable, int child) + { + return ((uint)getFromReference(collidable).CollisionGroup & (uint)hitGroups) != 0; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLocation, in System.Numerics.Vector3 hitNormal, CollidableReference collidable) + { + BepuHitResult result = new BepuHitResult(); + result.Succeeded = true; + result.Collider = getFromReference(collidable); + result.Normal.X = hitNormal.X; + result.Normal.Y = hitNormal.Y; + result.Normal.Z = hitNormal.Z; + result.Point.X = hitLocation.X; + result.Point.Y = hitLocation.Y; + result.Point.Z = hitLocation.Z; + result.HitFraction = t / startLength; + results.Add(result); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) + { + BepuHitResult result = new BepuHitResult(); + result.Succeeded = true; + result.Collider = getFromReference(collidable); + results.Add(result); + } + } + + /// + /// Performs a test to see if a collider shape collides with anything, and if so, returns the closest hit to the center of the shape. + /// + /// The shape. + /// Where to test. + /// Group of the shape. + /// What the shape should collide with + /// PhysicsComponent of thing hitting shapetest + public BepuPhysicsComponent ShapeTest(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + SweepTestFirst sshh = new SweepTestFirst() + { + hitGroups = hitGroups, + startLength = 0f, + }; + RigidPose rp = new RigidPose(); + rp.Position.X = position.X; + rp.Position.Y = position.Y; + rp.Position.Z = position.Z; + rp.Orientation.X = rotation.X; + rp.Orientation.Y = rotation.Y; + rp.Orientation.Z = rotation.Z; + rp.Orientation.W = rotation.W; + internalSimulation.Sweep(shape, rp, new BodyVelocity(), 0f, pBufferPool, ref sshh); + return sshh.result.Collider; + } + + /// + /// Performs a test to see if a collider shape collides with anything, and if so, returns all results in a list + /// + /// The shape. + /// Where to test. + /// Where to store results + /// Group of the shape. + /// What the shape should collide with + /// + public void ShapeTestPenetrating(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + SweepTestAll sshh = new SweepTestAll() + { + hitGroups = hitGroups, + startLength = 0f, + results = output + }; + RigidPose rp = new RigidPose(); + rp.Position.X = position.X; + rp.Position.Y = position.Y; + rp.Position.Z = position.Z; + rp.Orientation.X = rotation.X; + rp.Orientation.Y = rotation.Y; + rp.Orientation.Z = rotation.Z; + rp.Orientation.W = rotation.W; + internalSimulation.Sweep(shape, rp, new BodyVelocity(), 0f, pBufferPool, ref sshh); + } + + /// + /// Performs a sweep test using a collider shape and returns the closest hit + /// + /// The shape. + /// From. + /// To. + /// The collision group of this shape sweep + /// The collision group that this shape sweep can collide with + /// + /// This kind of shape cannot be used for a ShapeSweep. + public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + SweepTestFirst sshh = new SweepTestFirst() + { + hitGroups = hitGroups, + startLength = length, + }; + RigidPose rp = new RigidPose(); + rp.Position.X = position.X; + rp.Position.Y = position.Y; + rp.Position.Z = position.Z; + rp.Orientation.X = rotation.X; + rp.Orientation.Y = rotation.Y; + rp.Orientation.Z = rotation.Z; + rp.Orientation.W = rotation.W; + internalSimulation.Sweep(shape, rp, new BodyVelocity(new System.Numerics.Vector3(direction.X, direction.Y, direction.Z)), length, pBufferPool, ref sshh); + return sshh.result; + } + + /// + /// Performs a sweep test using a collider shape and never stops until "to" + /// + /// The shape. + /// From. + /// To. + /// The list to fill with results. + /// The collision group of this shape sweep + /// The collision group that this shape sweep can collide with + /// This kind of shape cannot be used for a ShapeSweep. + public void ShapeSweepPenetrating(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + SweepTestAll sshh = new SweepTestAll() + { + hitGroups = hitGroups, + startLength = length, + results = output + }; + RigidPose rp = new RigidPose(); + rp.Position.X = position.X; + rp.Position.Y = position.Y; + rp.Position.Z = position.Z; + rp.Orientation.X = rotation.X; + rp.Orientation.Y = rotation.Y; + rp.Orientation.Z = rotation.Z; + rp.Orientation.W = rotation.W; + internalSimulation.Sweep(shape, rp, new BodyVelocity(new System.Numerics.Vector3(direction.X, direction.Y, direction.Z)), length, pBufferPool, ref sshh); + } + + /// + /// Gets or sets the gravity. + /// + /// + /// The gravity. + /// + /// + /// Cannot perform this action when the physics engine is set to CollisionsOnly + /// or + /// Cannot perform this action when the physics engine is set to CollisionsOnly + /// + public Vector3 Gravity + { + get + { + return new Vector3(poseCallbacks.Gravity.X, poseCallbacks.Gravity.Y, poseCallbacks.Gravity.Z); + } + set + { + poseCallbacks.Gravity.X = value.X; + poseCallbacks.Gravity.Y = value.Y; + poseCallbacks.Gravity.Z = value.Z; + } + } + + /// + /// The maximum number of steps that the Simulation is allowed to take each tick. + /// If the engine is running slow (large deltaTime), then you must increase the number of maxSubSteps to compensate for this, otherwise your simulation is “losing” time. + /// It's important that frame DeltaTime is always less than MaxSubSteps*FixedTimeStep, otherwise you are losing time. + /// + public int MaxSubSteps { get; set; } + + /// + /// By decreasing the size of fixedTimeStep, you are increasing the “resolution” of the simulation. + /// Default is 1.0f / 60.0f or 60fps + /// + public float FixedTimeStep { get; set; } + + public class SimulationArgs : EventArgs + { + public float DeltaTime; + } + + /// + /// Called right before the physics simulation. + /// This event might not be fired by the main thread. + /// + public event EventHandler SimulationBegin; + + protected virtual void OnSimulationBegin(SimulationArgs e) + { + var handler = SimulationBegin; + handler?.Invoke(this, e); + } + + internal int UpdatedRigidbodies; + + private readonly SimulationArgs simulationArgs = new SimulationArgs(); + + internal ProfilingState SimulationProfiler; + + internal void Simulate(float deltaTime) + { + if (internalSimulation == null || DisableSimulation) return; + + OnSimulationBegin(simulationArgs); + + internalSimulation.Timestep(deltaTime, threadDispatcher); + + OnSimulationEnd(simulationArgs); + } + + /// + /// Called right after the physics simulation. + /// This event might not be fired by the main thread. + /// + public event EventHandler SimulationEnd; + + /// + /// Called right before processing a tick of the physics simulation. + /// + public event EventHandler PreSimulationTick; + + protected virtual void OnSimulationEnd(SimulationArgs e) + { + var handler = SimulationEnd; + handler?.Invoke(this, e); + } + + protected virtual void OnPreSimulationTick(float timeStep) + { + var handler = PreSimulationTick; + handler?.Invoke(this, timeStep); + } + } +} diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs new file mode 100644 index 0000000000..ac55837a59 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -0,0 +1,101 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using BepuPhysics; +using BepuPhysics.Collidables; +using Xenko.Core; +using Xenko.Engine; + +namespace Xenko.Physics.Bepu +{ + [DataContract("BepuStaticColliderComponent")] + [Display("Bepu Static collider")] + public sealed class BepuStaticColliderComponent : BepuPhysicsComponent + { + public StaticDescription staticDescription; + private StaticReference _internalStatic; + + public IShape ColliderShape; + + public StaticReference InternalStatic + { + get + { + _internalStatic.Statics = BepuSimulation.instance.internalSimulation.Statics; + _internalStatic.Handle = AddedHandle; + return _internalStatic; + } + } + + public BepuStaticColliderComponent() : base () + { + _internalStatic = new StaticReference(); + staticDescription = new StaticDescription(); + } + + [DataMemberIgnore] + public override Xenko.Core.Mathematics.Vector3 Position + { + get + { + return BepuHelpers.ToXenko(InternalStatic.Exists ? InternalStatic.Pose.Position : staticDescription.Pose.Position); + } + set + { + staticDescription.Pose.Position.X = value.X; + staticDescription.Pose.Position.Y = value.Y; + staticDescription.Pose.Position.Z = value.Z; + + if (InternalStatic.Exists) + { + InternalStatic.Pose.Position = staticDescription.Pose.Position; + } + } + } + + [DataMemberIgnore] + public override Xenko.Core.Mathematics.Quaternion Rotation + { + get + { + return BepuHelpers.ToXenko(InternalStatic.Exists ? InternalStatic.Pose.Orientation : staticDescription.Pose.Orientation); + } + set + { + staticDescription.Pose.Orientation.X = value.X; + staticDescription.Pose.Orientation.Y = value.Y; + staticDescription.Pose.Orientation.Z = value.Z; + staticDescription.Pose.Orientation.Z = value.W; + + if (InternalStatic.Exists) + { + InternalStatic.Pose.Orientation = staticDescription.Pose.Orientation; + } + } + } + + [DataMemberIgnore] + public bool AddedToScene + { + get + { + return AddedHandle != -1; + } + set + { + if (AddedToScene == value) return; + + if (value) + { + BepuSimulation.instance.AddCollider(this, (CollisionFilterGroupFlags)CollisionGroup, CanCollideWith); + Position = Entity.Transform.WorldPosition(); + Rotation = Entity.Transform.WorldRotation(); + } + else + { + BepuSimulation.instance.RemoveCollider(this); + } + } + } + } +} diff --git a/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs b/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs index 4e0bf7ce84..6d378a7930 100644 --- a/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Elements/RigidbodyComponent.cs @@ -374,13 +374,13 @@ private void RigidBodySetWorldTransform(ref Matrix physicsTransform) UpdateBoneTransformation(ref physicsTransform); } - if (Bullet2PhysicsSystem.timeToSimulate > 0f) + if (PhysicsSystem.timeToSimulate > 0f) { // interpolate awaiting simulation time - Entity.Transform.Position += (Vector3)InternalRigidBody.InterpolationLinearVelocity * Bullet2PhysicsSystem.timeToSimulate; + Entity.Transform.Position += (Vector3)InternalRigidBody.InterpolationLinearVelocity * PhysicsSystem.timeToSimulate; if (IgnorePhysicsRotation == false) { - Vector3 angSpeed = (Vector3)InternalRigidBody.InterpolationAngularVelocity * Bullet2PhysicsSystem.timeToSimulate; + Vector3 angSpeed = (Vector3)InternalRigidBody.InterpolationAngularVelocity * PhysicsSystem.timeToSimulate; Entity.Transform.Rotation *= Quaternion.RotationYawPitchRoll(angSpeed.X, angSpeed.Y, angSpeed.Z); } } diff --git a/sources/engine/Xenko.Physics/Engine/PhysicsProcessor.cs b/sources/engine/Xenko.Physics/Engine/PhysicsProcessor.cs index 4d7170462b..8c63b3f2b8 100644 --- a/sources/engine/Xenko.Physics/Engine/PhysicsProcessor.cs +++ b/sources/engine/Xenko.Physics/Engine/PhysicsProcessor.cs @@ -27,7 +27,7 @@ public class AssociatedData private readonly HashSet boneElements = new HashSet(); private readonly HashSet characters = new HashSet(); - private Bullet2PhysicsSystem physicsSystem; + private PhysicsSystem physicsSystem; private SceneSystem sceneSystem; private Scene debugScene; @@ -185,10 +185,10 @@ protected override void OnEntityComponentRemoved(Entity entity, PhysicsComponent protected internal override void OnSystemAdd() { - physicsSystem = (Bullet2PhysicsSystem)Services.GetService(); + physicsSystem = (PhysicsSystem)Services.GetService(); if (physicsSystem == null) { - physicsSystem = new Bullet2PhysicsSystem(Services); + physicsSystem = new PhysicsSystem(Services); Services.AddService(physicsSystem); var gameSystems = Services.GetSafeServiceAs(); gameSystems.Add(physicsSystem); @@ -204,7 +204,7 @@ protected internal override void OnSystemAdd() gameSystems.Add(debugShapeRendering); } - Simulation = OverlapTest.mySimulation = physicsSystem.Create(this); + Simulation = OverlapTest.mySimulation = physicsSystem.Create(this) as Simulation; sceneSystem = Services.GetSafeServiceAs(); } diff --git a/sources/engine/Xenko.Physics/IPhysicsSystem.cs b/sources/engine/Xenko.Physics/IPhysicsSystem.cs index 59e2eed6e2..2fb6e929d7 100644 --- a/sources/engine/Xenko.Physics/IPhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/IPhysicsSystem.cs @@ -7,7 +7,7 @@ namespace Xenko.Physics { public interface IPhysicsSystem : IGameSystemBase { - Simulation Create(PhysicsProcessor processor, PhysicsEngineFlags flags = PhysicsEngineFlags.None); + object Create(PhysicsProcessor processor, PhysicsEngineFlags flags = PhysicsEngineFlags.None, bool bepu = false); void Release(PhysicsProcessor processor); } } diff --git a/sources/engine/Xenko.Physics/PhysicsSettings.cs b/sources/engine/Xenko.Physics/PhysicsSettings.cs index ce164a5291..d9ca14b697 100644 --- a/sources/engine/Xenko.Physics/PhysicsSettings.cs +++ b/sources/engine/Xenko.Physics/PhysicsSettings.cs @@ -1,4 +1,4 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Xenko.Core; diff --git a/sources/engine/Xenko.Physics/Bullet2PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs similarity index 51% rename from sources/engine/Xenko.Physics/Bullet2PhysicsSystem.cs rename to sources/engine/Xenko.Physics/PhysicsSystem.cs index e623d4ff0b..6fcb215f68 100644 --- a/sources/engine/Xenko.Physics/Bullet2PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -7,15 +7,17 @@ using Xenko.Core; using Xenko.Engine; using Xenko.Games; +using Xenko.Physics.Bepu; namespace Xenko.Physics { - public class Bullet2PhysicsSystem : GameSystem, IPhysicsSystem + public class PhysicsSystem : GameSystem, IPhysicsSystem { private class PhysicsScene { public PhysicsProcessor Processor; public Simulation Simulation; + public BepuSimulation BepuSimulation; } internal static volatile float timeToSimulate; @@ -25,11 +27,7 @@ private class PhysicsScene private readonly List scenes = new List(); - static Bullet2PhysicsSystem() - { - } - - public Bullet2PhysicsSystem(IServiceRegistry registry) + public PhysicsSystem(IServiceRegistry registry) : base(registry) { UpdateOrder = -1000; //make sure physics runs before everything @@ -77,15 +75,31 @@ protected override void Destroy() foreach (var scene in scenes) { - scene.Simulation.Dispose(); + scene.Simulation?.Dispose(); + scene.BepuSimulation?.Dispose(); } } - public Simulation Create(PhysicsProcessor sceneProcessor, PhysicsEngineFlags flags = PhysicsEngineFlags.None) + public object Create(PhysicsProcessor sceneProcessor, PhysicsEngineFlags flags = PhysicsEngineFlags.None, bool bepu = false) { - var scene = new PhysicsScene { Processor = sceneProcessor, Simulation = new Simulation(sceneProcessor, physicsConfiguration) }; + var scene = new PhysicsScene + { + Processor = sceneProcessor, + Simulation = bepu == false ? new Simulation(sceneProcessor, physicsConfiguration) : null, + BepuSimulation = bepu ? new BepuSimulation(physicsConfiguration) : null + }; scenes.Add(scene); - return scene.Simulation; + return bepu ? (object)scene.BepuSimulation : (object)scene.Simulation; + } + + public bool HasSimulation() + { + for (int i=0; i PreserveNewest + + ..\..\..\deps\bepuphysics2\BepuPhysics.dll + + + ..\..\..\deps\bepuphysics2\BepuUtilities.dll + ..\..\..\deps\BulletPhysics\$(XenkoBulletPlatform)\$(XenkoBulletSignedDir)BulletSharp.NetStandard.dll @@ -34,10 +40,13 @@ Properties\SharedAssemblyInfo.cs + + + + - @@ -47,6 +56,8 @@ + + \ No newline at end of file diff --git a/sources/shared/Xenko.NuGetResolver/NuGetAssemblyResolver.cs b/sources/shared/Xenko.NuGetResolver/NuGetAssemblyResolver.cs index 666798ce56..3c60248602 100644 --- a/sources/shared/Xenko.NuGetResolver/NuGetAssemblyResolver.cs +++ b/sources/shared/Xenko.NuGetResolver/NuGetAssemblyResolver.cs @@ -6,17 +6,9 @@ using System.IO; using System.Linq; using System.Reflection; -using System.Threading; using System.Threading.Tasks; -using Newtonsoft.Json.Linq; -using NuGet.Commands; using NuGet.Common; using NuGet.Configuration; -using NuGet.Frameworks; -using NuGet.LibraryModel; -using NuGet.ProjectModel; -using NuGet.Protocol; -using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace Xenko.Core.Assets From 55a13774de7e1b4b30b9eb1020af9b7094f0e919 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 11:52:41 -0500 Subject: [PATCH 0540/2038] Physics: add helpers to add bodies to scene (and some summaries) --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 24 +++++++++++++++++++ .../Bepu/BepuPhysicsComponent.cs | 13 ++++++---- .../Bepu/BepuRigidbodyComponent.cs | 15 +++++++++++- .../Bepu/BepuStaticColliderComponent.cs | 6 ++++- 4 files changed, 52 insertions(+), 6 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 0c69dced73..e70b1ff36b 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -44,6 +44,30 @@ internal static void AssureServiceAdded() } } + /// + /// Goes through the whole scene and adds bepu physics objects to the simulation. Only will add if AllowHelperToAdd is true (which is set to true by default) + /// and if the body isn't added already. + /// + /// + public static void AddAllBodiesToSimulation(Scene rootScene) + { + foreach (Entity e in rootScene.Entities) + AddAllBodiesToSimulation(e); + } + + /// + /// Goes through the entity and children and adds bepu physics objects to the simulation. Only will add if AllowHelperToAdd is true (which is set to true by default) + /// and if the body isn't added already. + /// + /// + public static void AddAllBodiesToSimulation(Entity rootEntity) + { + BepuPhysicsComponent pc = rootEntity.Get(); + if (pc?.AllowHelperToAdd ?? false) pc.AddedToScene = true; + foreach (Entity e in rootEntity.GetChildren()) + AddAllBodiesToSimulation(e); + } + public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) { Vector3[] positions; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 710f185ee8..5ebdcb8d45 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -36,6 +36,15 @@ public int GetHandle() return AddedHandle; } + /// + /// Allow BepuHelpers.AddAllBodiesToSimulation to add this? + /// + [DataMember] + public bool AllowHelperToAdd { get; set; } = true; + + [DataMemberIgnore] + public virtual bool AddedToScene { get; set; } + public BepuPhysicsComponent() { BepuHelpers.AssureServiceAdded(); @@ -102,8 +111,6 @@ public BepuPhysicsComponent() [DataMember] public SpringSettings SpringSettings = new SpringSettings(30f, 1f); - #region Utility - /// /// Computes the physics transformation from the TransformComponent values /// @@ -148,7 +155,5 @@ internal virtual void UpdateTransformationComponent() { } /// [DataMember] public bool GhostBody { get; set; } - - #endregion Utility } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 42456a1c73..69079131fb 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -21,10 +21,16 @@ namespace Xenko.Physics.Bepu [Display("Bepu Rigidbody")] public sealed class BepuRigidbodyComponent : BepuPhysicsComponent { + /// + /// Description of the body to be created when added to the scene + /// public BodyDescription bodyDescription; private BodyReference _internalReference = new BodyReference(); + /// + /// Reference to the body after being added to the scene + /// public BodyReference InternalBody { get @@ -35,6 +41,9 @@ public BodyReference InternalBody } } + /// + /// Action to be called after simulation, but before transforms are set to new positions. Arguments are this and simulation time. + /// public Action ActionPerSimulationTick; /// @@ -316,8 +325,12 @@ public RigidBodyTypes RigidBodyType } } + /// + /// Set this to true to add this object to the physics simulation. Will automatically remove itself when the entity. is removed from the scene. Will NOT automatically add the rigidbody + /// to the scene when the entity is added, though. + /// [DataMemberIgnore] - public bool AddedToScene + public override bool AddedToScene { get { diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index ac55837a59..164fc429c2 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -74,8 +74,12 @@ public override Xenko.Core.Mathematics.Quaternion Rotation } } + /// + /// Set this to true to add this object to the physics simulation. Will automatically remove itself when the entity. is removed from the scene. Will NOT automatically add the rigidbody + /// to the scene when the entity is added, though. + /// [DataMemberIgnore] - public bool AddedToScene + public override bool AddedToScene { get { From e1d9c549f121bfcb74ca38ba46cd9df1a4b4063c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 13:52:05 -0500 Subject: [PATCH 0541/2038] Physics: helpers for compound shape creation --- deps/bepuphysics2/BepuPhysics.dll | 4 +-- deps/bepuphysics2/BepuPhysics.pdb | 4 +-- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 33 +++++++++++++++++++ 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index 82fd4d32b1..4f3a26de7f 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9ab3c4a23b725f907cdebc8b3f85773587205091ea2f4f1e2256d6977b3930fb -size 706048 +oid sha256:fa60c5f654bbffde1c90f3eb950db42646db23a9857e8c4fd7bc4e09c89f8d4c +size 707584 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index 266ae1157c..f83002842d 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:08bbd1710c884f1a31c246938cc2674f40d33ff3c1a0ce5abe4b6caeb63be510 -size 306132 +oid sha256:3be9aaf4b3f765ac776ada3b230315a3d033b18ff017d509d33beb8dc28d3731 +size 306752 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index e70b1ff36b..247a466e76 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -44,6 +44,39 @@ internal static void AssureServiceAdded() } } + /// + /// Easily makes a Compound shape for you, given a list of individual shapes and how they should be offset. + /// + /// List of shapes, must be IConvexShape if isDynamic is true + /// Matching length list of offsets of bodies, can be null if nothing has an offset + /// Matching length list of rotations of bodies, can be null if nothing is rotated + /// True if intended to use in a dynamic situation, false if kinematic or static + /// + public static ICompoundShape MakeCompound(List shapes, List offsets = null, List rotations = null, bool isDynamic = true, int bigThreshold = 5) + { + using (var compoundBuilder = new CompoundBuilder(BepuSimulation.instance.pBufferPool, BepuSimulation.instance.internalSimulation.Shapes, shapes.Count)) + { + bool allConvex = true; + + //All allocations from the buffer pool used for the final compound shape will be disposed when the demo is disposed. Don't have to worry about leaks in these demos. + for (int i=0; i /// Goes through the whole scene and adds bepu physics objects to the simulation. Only will add if AllowHelperToAdd is true (which is set to true by default) /// and if the body isn't added already. From f46c859becd9a5a02085760e6d0c38b85453915f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 14:28:23 -0500 Subject: [PATCH 0542/2038] Physics: update bepu libraries to better support multithreading --- deps/bepuphysics2/BepuPhysics.dll | 2 +- deps/bepuphysics2/BepuPhysics.pdb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index 4f3a26de7f..e14b344eac 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fa60c5f654bbffde1c90f3eb950db42646db23a9857e8c4fd7bc4e09c89f8d4c +oid sha256:6a6add99e052eb32710df48924a4f5c13a9ba3d340e882b8d46148cc550afc00 size 707584 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index f83002842d..e8669c31dd 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3be9aaf4b3f765ac776ada3b230315a3d033b18ff017d509d33beb8dc28d3731 -size 306752 +oid sha256:54df8a4bd9fdadec295d7cdb725e04fbd1df35f4266372cb6f9e77527d556098 +size 306836 From 95764b94b79d0a6fc76d82b57e7bd9ab33a082c1 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 15:30:33 -0500 Subject: [PATCH 0543/2038] Physics: helpers to generate properly sized collision shapes of entities --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 247a466e76..5f43942fc5 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -44,6 +44,47 @@ internal static void AssureServiceAdded() } } + private static Vector3 getBounds(Entity e) + { + ModelComponent mc = e.Get(); + if (mc == null || mc.Model == null || mc.Model.Meshes.Count < 0f) return Vector3.Zero; + + Vector3 biggest = Vector3.Zero; + for (int i=0; i biggest.X) biggest.X = extent.X; + if (extent.Y > biggest.Y) biggest.Y = extent.Y; + if (extent.Z > biggest.Z) biggest.Z = extent.Z; + } + return biggest * e.Transform.WorldScale(); + } + + public static Box GenerateBoxOfEntity(Entity e, float scale = 1f) + { + Vector3 b = getBounds(e) * scale * 2f; + return new Box(b.X, b.Y, b.Z); + } + + public static Sphere GenerateSphereOfEntity(Entity e, float scale = 1f) + { + Vector3 b = getBounds(e); + return new Sphere(Math.Max(b.Z, Math.Max(b.X, b.Y)) * scale); + } + + public static Capsule GenerateCapsuleOfEntity(Entity e, float scale = 1f, bool XZradius = true) + { + Vector3 b = getBounds(e) * scale; + return XZradius ? new Capsule(Math.Max(b.X, b.Z), b.Y * 2f) : new Capsule(b.Y, 2f * Math.Max(b.X, b.Z)); + } + + public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool XZradius = true) + { + Vector3 b = getBounds(e) * scale; + return XZradius ? new Cylinder(Math.Max(b.X, b.Z), b.Y * 2f) : new Cylinder(b.Y, 2f * Math.Max(b.X, b.Z)); + } + /// /// Easily makes a Compound shape for you, given a list of individual shapes and how they should be offset. /// From 8f0b362dc2343964caee926a83d03e967d8bd6ad Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 16:57:23 -0500 Subject: [PATCH 0544/2038] Physics: use Lists instead of arrays in helper functions --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 5f43942fc5..8965f013bd 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -144,8 +144,8 @@ public static void AddAllBodiesToSimulation(Entity rootEntity) public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) { - Vector3[] positions; - int[] indicies; + List positions; + List indicies; if (modelMesh.Draw is StagedMeshDraw) { @@ -156,21 +156,21 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out if (verts is VertexPositionNormalColor[]) { VertexPositionNormalColor[] vpnc = verts as VertexPositionNormalColor[]; - positions = new Vector3[vpnc.Length]; + positions = new List(vpnc.Length); for (int k = 0; k < vpnc.Length; k++) positions[k] = vpnc[k].Position; } else if (verts is VertexPositionNormalTexture[]) { VertexPositionNormalTexture[] vpnc = verts as VertexPositionNormalTexture[]; - positions = new Vector3[vpnc.Length]; + positions = new List(vpnc.Length); for (int k = 0; k < vpnc.Length; k++) positions[k] = vpnc[k].Position; } else if (verts is VertexPositionNormalTextureTangent[]) { VertexPositionNormalTextureTangent[] vpnc = verts as VertexPositionNormalTextureTangent[]; - positions = new Vector3[vpnc.Length]; + positions = new List(vpnc.Length); for (int k = 0; k < vpnc.Length; k++) positions[k] = vpnc[k].Position; } @@ -181,7 +181,7 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out } // take care of indicies - indicies = (int[])(object)smd.Indicies; + indicies = new List((int[])(object)smd.Indicies); } else { @@ -195,7 +195,7 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out } if (ModelBatcher.UnpackRawVertData(buf.VertIndexData, modelMesh.Draw.VertexBuffers[0].Declaration, - out positions, out Core.Mathematics.Vector3[] normals, out Core.Mathematics.Vector2[] uvs, + out Vector3[] arraypositions, out Core.Mathematics.Vector3[] normals, out Core.Mathematics.Vector2[] uvs, out Color4[] colors, out Vector4[] tangents) == false) { outMesh = new Mesh(); @@ -210,7 +210,7 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out var dst = (uint*)pdst; int numIndices = ibuf.VertIndexData.Length / sizeof(uint); - indicies = new int[numIndices]; + indicies = new List(numIndices); for (var k = 0; k < numIndices; k++) { // Offset indices @@ -222,7 +222,7 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out var dst = (ushort*)pdst; int numIndices = ibuf.VertIndexData.Length / sizeof(ushort); - indicies = new int[numIndices]; + indicies = new List(numIndices); for (var k = 0; k < numIndices; k++) { // Offset indices @@ -230,18 +230,21 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out } } } + + // take care of positions + positions = new List(arraypositions); } return GenerateMeshShape(positions, indicies, out outMesh, scale); } - public static unsafe bool GenerateMeshShape(Vector3[] positions, int[] indicies, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) + public static unsafe bool GenerateMeshShape(List positions, List indicies, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) { // ok, should have what we need to make triangles - var memory = stackalloc Triangle[indicies.Length]; - BepuUtilities.Memory.Buffer triangles = new BepuUtilities.Memory.Buffer(memory, indicies.Length); + var memory = stackalloc Triangle[indicies.Count]; + BepuUtilities.Memory.Buffer triangles = new BepuUtilities.Memory.Buffer(memory, indicies.Count); - for (int i = 0; i < indicies.Length; i += 3) + for (int i = 0; i < indicies.Count; i += 3) { triangles[i].A = ToBepu(positions[indicies[i]]); triangles[i].B = ToBepu(positions[indicies[i+1]]); From dd74934901b2589c96c664f3267b5ce42b5ee9e3 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 19:05:32 -0500 Subject: [PATCH 0545/2038] Physics: helper function for transforming a single shape --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 8965f013bd..8c37ee80f9 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -61,6 +61,20 @@ private static Vector3 getBounds(Entity e) return biggest * e.Transform.WorldScale(); } + public static IShape OffsetSingleShape(IShape shape, Vector3? offset = null, Quaternion? rotation = null) + { + if (offset.HasValue == false && rotation.HasValue == false) return shape; + + using (var compoundBuilder = new CompoundBuilder(BepuSimulation.instance.pBufferPool, BepuSimulation.instance.internalSimulation.Shapes, 1)) + { + compoundBuilder.AddForKinematicEasy(shape, new BepuPhysics.RigidPose(ToBepu(offset ?? Vector3.Zero), ToBepu(rotation ?? Quaternion.Identity)), 1f); + + compoundBuilder.BuildKinematicCompound(out var children); + + return new Compound(children); + } + } + public static Box GenerateBoxOfEntity(Entity e, float scale = 1f) { Vector3 b = getBounds(e) * scale * 2f; From 5de732810e2a759349eed76cc6b45be6a8a72e8e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 20:48:47 -0500 Subject: [PATCH 0546/2038] Physics: fix Mesh creation and disposal --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 14 +++++++------- .../Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 1 - .../engine/Xenko.Physics/Bepu/BepuSimulation.cs | 9 +++++++++ 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 8c37ee80f9..0d27fe2671 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -255,18 +255,18 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out public static unsafe bool GenerateMeshShape(List positions, List indicies, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) { // ok, should have what we need to make triangles - var memory = stackalloc Triangle[indicies.Count]; - BepuUtilities.Memory.Buffer triangles = new BepuUtilities.Memory.Buffer(memory, indicies.Count); + int triangleCount = indicies.Count / 3; + BepuSimulation.instance.pBufferPool.Take(triangleCount, out BepuUtilities.Memory.Buffer triangles); - for (int i = 0; i < indicies.Count; i += 3) + for (int i = 0; i < triangleCount; i ++) { - triangles[i].A = ToBepu(positions[indicies[i]]); - triangles[i].B = ToBepu(positions[indicies[i+1]]); - triangles[i].C = ToBepu(positions[indicies[i+2]]); + int shiftedi = i * 3; + triangles[i].A = ToBepu(positions[indicies[shiftedi]]); + triangles[i].B = ToBepu(positions[indicies[shiftedi+1]]); + triangles[i].C = ToBepu(positions[indicies[shiftedi+2]]); } outMesh = new Mesh(triangles, new System.Numerics.Vector3(scale?.X ?? 1f, scale?.Y ?? 1f, scale?.Z ?? 1f), BepuSimulation.instance.pBufferPool); - return true; } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 5ebdcb8d45..e333d28341 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -24,7 +24,6 @@ namespace Xenko.Engine [Display("BepuPhysics", Expand = ExpandRule.Once)] [AllowMultipleComponents] [ComponentOrder(3100)] - //[ComponentCategory("BepuPhysics")] public abstract class BepuPhysicsComponent : ActivableEntityComponent { protected static Logger logger = GlobalLogger.GetLogger("BepuPhysicsComponent"); diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index c40dcbe6be..0f95defe55 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -284,7 +284,16 @@ internal BepuSimulation(PhysicsSettings configuration) /// public void Dispose() { + pBufferPool.Clear(); + } + /// + /// Free up memory used to store triangles for a mesh collision shape + /// + /// + public void DisposeMesh(BepuPhysics.Collidables.Mesh m) + { + m.Dispose(pBufferPool); } public RenderGroup ColliderShapesRenderGroup { get; set; } = RenderGroup.Group0; From 29dec270b77b55bda4c651531f765827ba2da270 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 19 Dec 2019 22:40:01 -0500 Subject: [PATCH 0547/2038] Physics: make it easier to initialize BepuPhysics when needed, also add a bit more CompoundShape nesting protection --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 16 ++++++++-------- .../Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 2 +- .../engine/Xenko.Physics/Bepu/BepuSimulation.cs | 15 ++++++++++++++- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 0d27fe2671..549c380049 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -1,10 +1,3 @@ -/* - * - need to switch between which list index is processing for contact collection - * - need to clear list of index we will start populating - * - throw out contact information without normal or position information...? when count == 0...? - * - */ - using System; using System.Collections.Generic; using System.Text; @@ -23,7 +16,10 @@ public class BepuHelpers { internal static PhysicsSystem physicsSystem; - internal static void AssureServiceAdded() + /// + /// Good to call this at the start of your application. Will automatically get called in some situations, but not be soon enough. + /// + public static void AssureBepuSystemCreated() { if (physicsSystem == null) { @@ -65,6 +61,8 @@ public static IShape OffsetSingleShape(IShape shape, Vector3? offset = null, Qua { if (offset.HasValue == false && rotation.HasValue == false) return shape; + if (shape is ICompoundShape) throw new InvalidOperationException("Cannot offset a compound shape. Can't support nested compounds."); + using (var compoundBuilder = new CompoundBuilder(BepuSimulation.instance.pBufferPool, BepuSimulation.instance.internalSimulation.Shapes, 1)) { compoundBuilder.AddForKinematicEasy(shape, new BepuPhysics.RigidPose(ToBepu(offset ?? Vector3.Zero), ToBepu(rotation ?? Quaternion.Identity)), 1f); @@ -116,6 +114,8 @@ public static ICompoundShape MakeCompound(List shapes, List off //All allocations from the buffer pool used for the final compound shape will be disposed when the demo is disposed. Don't have to worry about leaks in these demos. for (int i=0; i diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 0f95defe55..3830094a91 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -29,7 +29,20 @@ public class BepuSimulation : IDisposable private const CollisionFilterGroupFlags DefaultFlags = CollisionFilterGroupFlags.AllFilter; public BepuPhysics.Simulation internalSimulation; - public static BepuSimulation instance; + + private static BepuSimulation _instance; + public static BepuSimulation instance + { + get + { + if (_instance == null) BepuHelpers.AssureBepuSystemCreated(); + return _instance; + } + private set + { + _instance = value; + } + } private PoseIntegratorCallbacks poseCallbacks; internal BufferPool pBufferPool; From f69146ac6793178d207febd9e2296d01bff8af29 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 20 Dec 2019 10:51:33 -0500 Subject: [PATCH 0548/2038] Physics: can only create compound shapes of convex shapes --- deps/bepuphysics2/BepuPhysics.dll | 2 +- deps/bepuphysics2/BepuPhysics.pdb | 2 +- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index e14b344eac..6984ede3eb 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6a6add99e052eb32710df48924a4f5c13a9ba3d340e882b8d46148cc550afc00 +oid sha256:907c7f267ab46c15697e86176979ec898b06cbc2125ea25834c7814c1d85f653 size 707584 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index e8669c31dd..d7331756a1 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:54df8a4bd9fdadec295d7cdb725e04fbd1df35f4266372cb6f9e77527d556098 +oid sha256:0634edeaab7a9b323ef926a35c327901a9388f181b76b07ba3d22c5fdc495d95 size 306836 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 549c380049..8f59cee1b8 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -57,7 +57,7 @@ private static Vector3 getBounds(Entity e) return biggest * e.Transform.WorldScale(); } - public static IShape OffsetSingleShape(IShape shape, Vector3? offset = null, Quaternion? rotation = null) + public static IShape OffsetSingleShape(IConvexShape shape, Vector3? offset = null, Quaternion? rotation = null) { if (offset.HasValue == false && rotation.HasValue == false) return shape; @@ -105,7 +105,7 @@ public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool /// Matching length list of rotations of bodies, can be null if nothing is rotated /// True if intended to use in a dynamic situation, false if kinematic or static /// - public static ICompoundShape MakeCompound(List shapes, List offsets = null, List rotations = null, bool isDynamic = true, int bigThreshold = 5) + public static ICompoundShape MakeCompound(List shapes, List offsets = null, List rotations = null, bool isDynamic = true, int bigThreshold = 5) { using (var compoundBuilder = new CompoundBuilder(BepuSimulation.instance.pBufferPool, BepuSimulation.instance.internalSimulation.Shapes, shapes.Count)) { From 042f155806ae33c3095bf0007194527fb791129b Mon Sep 17 00:00:00 2001 From: tebjan Date: Wed, 18 Dec 2019 16:31:54 +0100 Subject: [PATCH 0549/2038] Added VideoSerializer in order to carry the original FileProvider with the deserialized video. --- .../Xenko.Assets/Media/VideoAssetCompiler.cs | 2 +- sources/engine/Xenko.Video/Video.cs | 6 +++- sources/engine/Xenko.Video/VideoInstance.cs | 8 +++-- sources/engine/Xenko.Video/VideoSerializer.cs | 30 +++++++++++++++++++ 4 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 sources/engine/Xenko.Video/VideoSerializer.cs diff --git a/sources/engine/Xenko.Assets/Media/VideoAssetCompiler.cs b/sources/engine/Xenko.Assets/Media/VideoAssetCompiler.cs index 7cd4c0c89f..1fa1185cdf 100644 --- a/sources/engine/Xenko.Assets/Media/VideoAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Media/VideoAssetCompiler.cs @@ -66,7 +66,7 @@ private class EncodeVideoFileCommand : AssetCommand public EncodeVideoFileCommand(string url, VideoConvertParameters description, IAssetFinder assetFinder, AVCodecID[] listSupportedCodecNames) : base(url, description, assetFinder) { - Version = 3; + Version = 4; ListSupportedCodecNames = listSupportedCodecNames; } diff --git a/sources/engine/Xenko.Video/Video.cs b/sources/engine/Xenko.Video/Video.cs index e50899a2c4..db9cc26848 100644 --- a/sources/engine/Xenko.Video/Video.cs +++ b/sources/engine/Xenko.Video/Video.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using Xenko.Core; +using Xenko.Core.IO; using Xenko.Core.Serialization; using Xenko.Core.Serialization.Contents; @@ -14,9 +15,12 @@ namespace Xenko.Video [DebuggerDisplay("{" + nameof(Name) + "}")] [ContentSerializer(typeof(DataContentSerializer - - - - - + + + + + \ No newline at end of file diff --git a/samples/Games/JumpyJet/Assets/Shared/Scene.xkscene b/samples/Games/JumpyJet/Assets/Shared/Scene.xkscene index bc0191ae48..d95201a596 100644 --- a/samples/Games/JumpyJet/Assets/Shared/Scene.xkscene +++ b/samples/Games/JumpyJet/Assets/Shared/Scene.xkscene @@ -85,8 +85,9 @@ Hierarchy: Rotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} Scale: {X: 1.0, Y: 1.0, Z: 1.0} Children: {} - a941cd713c0995458f02918f1c0258bd: !JumpyJet.PipesScript,JumpyJet.Game - Id: 71cd41a9-093c-4595-8f02-918f1c0258bd + a124a98b8ada02d77a29033b4c58dcc8: !JumpyJet.PipesScript,JumpyJet.Game + Id: a3abb282-de05-4800-b279-e562372a4185 + PipePrefabUrl: ce7c2b81-110c-4150-bf9a-d902b03b3d41:Pipe Set - Entity: Id: fb0a2c4b-0ae0-47c0-a222-089448e7890c Name: Character diff --git a/samples/Games/JumpyJet/JumpyJet.Game/JumpyJet.Game.csproj b/samples/Games/JumpyJet/JumpyJet.Game/JumpyJet.Game.csproj index 733d36303c..4223abe768 100644 --- a/samples/Games/JumpyJet/JumpyJet.Game/JumpyJet.Game.csproj +++ b/samples/Games/JumpyJet/JumpyJet.Game/JumpyJet.Game.csproj @@ -4,11 +4,11 @@ JumpyJet - - - - - - + + + + + + \ No newline at end of file diff --git a/samples/Games/JumpyJet/JumpyJet.Game/PipesScript.cs b/samples/Games/JumpyJet/JumpyJet.Game/PipesScript.cs index 820e903573..c0116509f9 100644 --- a/samples/Games/JumpyJet/JumpyJet.Game/PipesScript.cs +++ b/samples/Games/JumpyJet/JumpyJet.Game/PipesScript.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using Xenko.Core.Mathematics; +using Xenko.Core.Serialization; using Xenko.Engine; using Xenko.Engine.Events; @@ -29,9 +30,11 @@ public class PipesScript : SyncScript private float sceneWidth; private float pipeOvervaluedWidth = 1f; + public UrlReference PipePrefabUrl { get; set; } + public override void Start() { - var pipeSetPrefab = Content.Load("Pipe Set"); + var pipeSetPrefab = Content.Load(PipePrefabUrl); // Create PipeSets sceneWidth = GameGlobals.GamePixelToUnitScale*GraphicsDevice.Presenter.BackBuffer.Width; diff --git a/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj b/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj index f33888adf2..c6fa89730a 100644 --- a/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj +++ b/samples/Games/SpaceEscape/SpaceEscape.Game/SpaceEscape.Game.csproj @@ -5,10 +5,10 @@ true - - - - - + + + + + \ No newline at end of file diff --git a/samples/Graphics/AnimatedModel/AnimatedModel.Game/AnimatedModel.Game.csproj b/samples/Graphics/AnimatedModel/AnimatedModel.Game/AnimatedModel.Game.csproj index fe62727d8d..1f64e741e8 100644 --- a/samples/Graphics/AnimatedModel/AnimatedModel.Game/AnimatedModel.Game.csproj +++ b/samples/Graphics/AnimatedModel/AnimatedModel.Game/AnimatedModel.Game.csproj @@ -4,10 +4,10 @@ AnimatedModel - - - - - + + + + + \ No newline at end of file diff --git a/samples/Graphics/AnimatedModel/Assets/Shared/Scene.xkscene b/samples/Graphics/AnimatedModel/Assets/Shared/Scene.xkscene index 19872eef3a..caf294b76c 100644 --- a/samples/Graphics/AnimatedModel/Assets/Shared/Scene.xkscene +++ b/samples/Graphics/AnimatedModel/Assets/Shared/Scene.xkscene @@ -103,8 +103,8 @@ Hierarchy: Size: Large DepthRange: {} PartitionMode: !LightDirectionalShadowMap.PartitionLogarithmic {} - ComputeTransmittance: false BiasParameters: {} + ComputeTransmittance: false Intensity: 0.6 - Entity: Id: bb7065d2-498a-45d7-b4b1-0bb1a573cc69 @@ -158,8 +158,8 @@ Hierarchy: Size: Large DepthRange: {} PartitionMode: !LightDirectionalShadowMap.PartitionLogarithmic {} - ComputeTransmittance: false BiasParameters: {} + ComputeTransmittance: false Intensity: 0.6 - Entity: Id: df07ee24-de65-4561-8f4a-da086654e07b diff --git a/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj b/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj index f54d11f89e..9a2dd1a514 100644 --- a/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj +++ b/samples/Graphics/CustomEffect/CustomEffect.Game/CustomEffect.Game.csproj @@ -4,10 +4,10 @@ CustomEffect - - - - - + + + + + \ No newline at end of file diff --git a/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj b/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj index 3c6fd2f175..6502f60ec7 100644 --- a/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj +++ b/samples/Graphics/MaterialShader/MaterialShader.Game/MaterialShader.Game.csproj @@ -4,10 +4,10 @@ MaterialShader - - - - - + + + + + \ No newline at end of file diff --git a/samples/Graphics/SpriteFonts/SpriteFonts.Game/SpriteFonts.Game.csproj b/samples/Graphics/SpriteFonts/SpriteFonts.Game/SpriteFonts.Game.csproj index 5e8d75be08..e310aedb45 100644 --- a/samples/Graphics/SpriteFonts/SpriteFonts.Game/SpriteFonts.Game.csproj +++ b/samples/Graphics/SpriteFonts/SpriteFonts.Game/SpriteFonts.Game.csproj @@ -4,10 +4,10 @@ SpriteFonts - - - - - + + + + + \ No newline at end of file diff --git a/samples/Graphics/SpriteStudioDemo/SpriteStudioDemo.Game/SpriteStudioDemo.Game.csproj b/samples/Graphics/SpriteStudioDemo/SpriteStudioDemo.Game/SpriteStudioDemo.Game.csproj index a663b76f9e..6037e257ff 100644 --- a/samples/Graphics/SpriteStudioDemo/SpriteStudioDemo.Game/SpriteStudioDemo.Game.csproj +++ b/samples/Graphics/SpriteStudioDemo/SpriteStudioDemo.Game/SpriteStudioDemo.Game.csproj @@ -4,12 +4,12 @@ SpriteStudioDemo - - - - - - - + + + + + + + \ No newline at end of file diff --git a/samples/Input/GravitySensor/GravitySensor.Game/GravitySensor.Game.csproj b/samples/Input/GravitySensor/GravitySensor.Game/GravitySensor.Game.csproj index 87feb2538e..d19f1e2837 100644 --- a/samples/Input/GravitySensor/GravitySensor.Game/GravitySensor.Game.csproj +++ b/samples/Input/GravitySensor/GravitySensor.Game/GravitySensor.Game.csproj @@ -4,11 +4,11 @@ GravitySensor - - - - - - + + + + + + \ No newline at end of file diff --git a/samples/Input/TouchInputs/TouchInputs.Game/TouchInputs.Game.csproj b/samples/Input/TouchInputs/TouchInputs.Game/TouchInputs.Game.csproj index d86376d9b7..202fd97bb0 100644 --- a/samples/Input/TouchInputs/TouchInputs.Game/TouchInputs.Game.csproj +++ b/samples/Input/TouchInputs/TouchInputs.Game/TouchInputs.Game.csproj @@ -4,10 +4,10 @@ TouchInputs - - - - - + + + + + \ No newline at end of file diff --git a/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj b/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj index bebd2bf514..41ab43cc8b 100644 --- a/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj +++ b/samples/Particles/ParticlesSample/ParticlesSample.Game/ParticlesSample.Game.csproj @@ -5,10 +5,10 @@ true - - - - - + + + + + \ No newline at end of file diff --git a/samples/Physics/PhysicsSample/PhysicsSample.Game/PhysicsSample.Game.csproj b/samples/Physics/PhysicsSample/PhysicsSample.Game/PhysicsSample.Game.csproj index 9d7f2a08de..98a418bd95 100644 --- a/samples/Physics/PhysicsSample/PhysicsSample.Game/PhysicsSample.Game.csproj +++ b/samples/Physics/PhysicsSample/PhysicsSample.Game/PhysicsSample.Game.csproj @@ -4,11 +4,11 @@ PhysicsSample - - - - - - + + + + + + \ No newline at end of file diff --git a/samples/Templates/FirstPersonShooter/FirstPersonShooter/FirstPersonShooter.Game/FirstPersonShooter.Game.csproj b/samples/Templates/FirstPersonShooter/FirstPersonShooter/FirstPersonShooter.Game/FirstPersonShooter.Game.csproj index 1461d6537b..58f23161fd 100644 --- a/samples/Templates/FirstPersonShooter/FirstPersonShooter/FirstPersonShooter.Game/FirstPersonShooter.Game.csproj +++ b/samples/Templates/FirstPersonShooter/FirstPersonShooter/FirstPersonShooter.Game/FirstPersonShooter.Game.csproj @@ -4,12 +4,12 @@ FirstPersonShooter - - - - - - + + + + + + diff --git a/samples/Templates/Packs/MaterialPackage/MaterialPackage.csproj b/samples/Templates/Packs/MaterialPackage/MaterialPackage.csproj index 5c8068775a..1e0f213097 100644 --- a/samples/Templates/Packs/MaterialPackage/MaterialPackage.csproj +++ b/samples/Templates/Packs/MaterialPackage/MaterialPackage.csproj @@ -3,7 +3,7 @@ netstandard2.0 - - + + \ No newline at end of file diff --git a/samples/Templates/Packs/PrototypingBlocks/PrototypingBlocks.csproj b/samples/Templates/Packs/PrototypingBlocks/PrototypingBlocks.csproj index 6a372d5963..bb15ce2041 100644 --- a/samples/Templates/Packs/PrototypingBlocks/PrototypingBlocks.csproj +++ b/samples/Templates/Packs/PrototypingBlocks/PrototypingBlocks.csproj @@ -3,8 +3,8 @@ netstandard2.0 - - - + + + \ No newline at end of file diff --git a/samples/Templates/Packs/SamplesAssetPackage/SamplesAssetPackage.csproj b/samples/Templates/Packs/SamplesAssetPackage/SamplesAssetPackage.csproj index 5c8068775a..1e0f213097 100644 --- a/samples/Templates/Packs/SamplesAssetPackage/SamplesAssetPackage.csproj +++ b/samples/Templates/Packs/SamplesAssetPackage/SamplesAssetPackage.csproj @@ -3,7 +3,7 @@ netstandard2.0 - - + + \ No newline at end of file diff --git a/samples/Templates/Packs/VFXPackage/VFXPackage.csproj b/samples/Templates/Packs/VFXPackage/VFXPackage.csproj index 120313f727..5eed6cdeb3 100644 --- a/samples/Templates/Packs/VFXPackage/VFXPackage.csproj +++ b/samples/Templates/Packs/VFXPackage/VFXPackage.csproj @@ -3,8 +3,8 @@ netstandard2.0 - - - + + + \ No newline at end of file diff --git a/samples/Templates/Packs/mannequinModel/mannequinModel.csproj b/samples/Templates/Packs/mannequinModel/mannequinModel.csproj index b052f52716..b29f22b548 100644 --- a/samples/Templates/Packs/mannequinModel/mannequinModel.csproj +++ b/samples/Templates/Packs/mannequinModel/mannequinModel.csproj @@ -3,7 +3,7 @@ netstandard2.0 - - + + \ No newline at end of file diff --git a/samples/Templates/ThirdPersonPlatformer/ThirdPersonPlatformer/ThirdPersonPlatformer.Game/ThirdPersonPlatformer.Game.csproj b/samples/Templates/ThirdPersonPlatformer/ThirdPersonPlatformer/ThirdPersonPlatformer.Game/ThirdPersonPlatformer.Game.csproj index e0a7e5b55d..3c2df7fe7d 100644 --- a/samples/Templates/ThirdPersonPlatformer/ThirdPersonPlatformer/ThirdPersonPlatformer.Game/ThirdPersonPlatformer.Game.csproj +++ b/samples/Templates/ThirdPersonPlatformer/ThirdPersonPlatformer/ThirdPersonPlatformer.Game/ThirdPersonPlatformer.Game.csproj @@ -4,12 +4,12 @@ ThirdPersonPlatformer - - - - - - + + + + + + diff --git a/samples/Templates/TopDownRPG/TopDownRPG/Assets/DynamicScene.xkscene b/samples/Templates/TopDownRPG/TopDownRPG/Assets/DynamicScene.xkscene index 614d24bcb5..6ca596a086 100644 --- a/samples/Templates/TopDownRPG/TopDownRPG/Assets/DynamicScene.xkscene +++ b/samples/Templates/TopDownRPG/TopDownRPG/Assets/DynamicScene.xkscene @@ -45,8 +45,8 @@ Hierarchy: Size: XLarge DepthRange: {} PartitionMode: !LightDirectionalShadowMap.PartitionLogarithmic {} - ComputeTransmittance: false BiasParameters: {} + ComputeTransmittance: false Intensity: 5.0 - Entity: Id: 2b57370f-e61c-41c5-b8c4-df6619837e29 @@ -84,7 +84,7 @@ Hierarchy: LocalRotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} 2eac96e8c90a836d8754e3f24fa1a99e: !Gameplay.SceneStreaming,TopDownRPG.Game Id: 5b6e2307-e465-4da0-8d84-b9624682ef9f - Url: EasternChunk + Url: feaab56f-3f56-48e0-83be-dfe2f38f65a6:EasternChunk Trigger: !RigidbodyComponent ref!! 00eee251-501b-4d85-b1b2-cdf1d7608ee4 - Entity: Id: 3113203c-2276-420b-bf0d-fce00d95dc58 @@ -122,7 +122,7 @@ Hierarchy: LocalRotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} 2eac96e8c90a836d8754e3f24fa1a99e: !Gameplay.SceneStreaming,TopDownRPG.Game Id: 276ff6f0-dcc0-4945-b13e-f2dd2664b4e0 - Url: SouthernChunk + Url: 7cdb3d4a-151d-4851-a736-fec1bba593d3:SouthernChunk Trigger: !RigidbodyComponent ref!! 52032222-a039-47be-9d21-4a6c3adca582 - Entity: Id: 36396dfa-6aa4-4489-a7f5-e45f569bb082 @@ -291,7 +291,7 @@ Hierarchy: LocalRotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} 2eac96e8c90a836d8754e3f24fa1a99e: !Gameplay.SceneStreaming,TopDownRPG.Game Id: 0d6efc2a-7d05-4295-aa27-1438d51972c0 - Url: WesternChunk + Url: 465718fa-96e7-4d3b-897d-8e7075b1a9ae:WesternChunk Trigger: !RigidbodyComponent ref!! 06ed6375-b5de-40e6-88e8-16ba15e8f474 - Folder: GlobalLights Entity: @@ -376,7 +376,7 @@ Hierarchy: LocalRotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} 2eac96e8c90a836d8754e3f24fa1a99e: !Gameplay.SceneStreaming,TopDownRPG.Game Id: 1f7da7c0-2b66-4b6b-b5c2-924baea7652c - Url: NorthernChunk + Url: cd7db7bc-2d8e-45be-a6d9-4b7e9008e949:NorthernChunk Trigger: !RigidbodyComponent ref!! 34034a61-5c72-4401-8c28-f112ab89f36b - Entity: Id: c3648c46-3fef-42fd-a935-6c2663254381 @@ -414,7 +414,7 @@ Hierarchy: LocalRotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} 2eac96e8c90a836d8754e3f24fa1a99e: !Gameplay.SceneStreaming,TopDownRPG.Game Id: 399f44ea-00ce-44fc-80ff-474e65ec1c9b - Url: CentralChunk + Url: 805ec36b-feab-40fb-93cd-8f5083937659:CentralChunk Trigger: !RigidbodyComponent ref!! 78b1ff69-cfed-4a09-8c1b-eb12cbf817b1 - Entity: Id: f7e977f3-a569-4ae2-a4e8-89afaf7e0817 diff --git a/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/Gameplay/SceneStreaming.cs b/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/Gameplay/SceneStreaming.cs index ef25fbc8c8..60f5313e2e 100644 --- a/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/Gameplay/SceneStreaming.cs +++ b/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/Gameplay/SceneStreaming.cs @@ -10,6 +10,7 @@ using System.Threading.Tasks; using Xenko.Core; using Xenko.Core.Mathematics; +using Xenko.Core.Serialization; using Xenko.Engine; using Xenko.Physics; @@ -29,7 +30,7 @@ public class SceneStreaming : SyncScript /// /// The url of the scene to load /// - public string Url { get; set; } + public UrlReference Url { get; set; } /// /// The trigger volume. This should be a static collider, set to be a trigger @@ -99,14 +100,14 @@ public override void Update() if (shouldLoad) { // If we should load syncrhonously, just create a completed task and load - Instance = Content.Load(Url); + Instance = Content.Load(Url); loadingTask = Task.FromResult(Instance); } else if (shouldPreLoad) { loadCancellation = new CancellationTokenSource(); - var localLoadingTask = loadingTask = Content.LoadAsync(Url); + var localLoadingTask = loadingTask = Content.LoadAsync(Url); Script.AddTask(async () => { await loadingTask; diff --git a/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/TopDownRPG.Game.csproj b/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/TopDownRPG.Game.csproj index 2216d6f7c6..d915e41e6a 100644 --- a/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/TopDownRPG.Game.csproj +++ b/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Game/TopDownRPG.Game.csproj @@ -4,13 +4,13 @@ TopDownRPG - - - - - - - + + + + + + + diff --git a/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Windows/Resources/Icon.ico b/samples/Templates/TopDownRPG/TopDownRPG/TopDownRPG.Windows/Resources/Icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..29256adf2605509afb9ba10e5616eec8e8a7086f GIT binary patch literal 34750 zcmeHQdvF!i89y-z2_Oa)5af{{k3_WU*vGWf3ixdQQd`ln?M!Q{Q*~+u{;*)DlIx>b z6qT2#L+h(pfmSW3GmcPl6<_#56hu*(v?^dgNfjlSkkjAqWWUYc&Dq_%_ukxl(fiGO z`Ocol_x-+a&z?Pd_S}t9WvWsQ9H=0x)n%1RU7(a2I+VwC>d$?ZT8q58x~}78sCQP4 zQYW3{9FJ4#lUk)FPwqNyI8CX=XDZbI9jFQo%&*2@JJnUrQ+0jjsnOtLs^_b*{T8VD z0gF__VT;svMlDgN9e1Dl(aB5I+24CmodZ7i`^(gn$t%=_XZ%zB^vs9U&(3;C{rray zsb8JFQeA%G<7)1#=hVX4FRH~iy`=76{F?gPog3A%ziv`1?%k{&`^Q%G(T=^U^^<+7 zbx)i6eD9ZP-xuv_|Naiu(cY;J9OzV?25*KcwtPmW)24{3z6{KdStQ(WYYUVHN!jJ+xoNVYQB; zQ3I<$14lWB4fSJ>0gZL-j4;Df^$4eYWZynDhaX0D#}Dg26o6ClJ30dehnU;`r&Lw5QrADFRI*&D<|?IHF~$n> znE5PcJ=SMCGRIjA)e6J08LuI}RupH94y%i@>W+@iOWXE!+)eIiKX4E7CNP+6M-C!y zInu|XtncL)~n{wvE%8kgaz^=VUfP+O%|R zwA?szovFvV7oWRI@B6%+eoO)X06fuQrl&yn$Cvzgm0N%IjCII1x+jTl9J@A8G9Eh>yg@(VesN>x;Rye{S8pyKVD^ zmQOcrX!(rHH1g8wpFZ4iuCMdcxxSouXF5Kdn8x_ftK%Eu6Er@bE`65LMiN`du<I0H@WvI=l){D#XP|lRPN1>Q`g(>U`W$9;pg@H>U#Z@x>jGSlDb?q&#F?bsz$Y` zTGgQ@sZP~sm}%y*jCEL-ZP=DNL?0#RVRhiiU_LjOsCXm5^JSx;d|Tb1ydWKtPYJF8 zUkje&;aSv);~>?M`O+40mPapb&=ze{|4{I*kGAjC8(-RKc*FV~8gpM{>(!ZJKwE*687wk75nV@Wk=)F^F2o)nZ%pajrY#(ls+aP)}#1l@LV4=Z+%3}t+p)~%(kpHU zy;r~X;!geQ3p=dLvQtsV8}pgn=R4GP5C(sL7^ZG<`?B=uZh1?JZBJi&)E0BG>6eJ3 z$%3@@N%1d8`uh2*IJO0gAHy}jTdOAwyj>r6#Ntq9oj;66uOD9D!qR@*S6`kwE(i5H$gpL6o+t%^-ldBv2Erf5q&4>zMC=*$F(i> zZ5X5sG75wL{%f6o`280BHrtXXb<)6K<{xZ_x?%ILHBKEd5h-mLqJ=>Bh5UPu@3994ck(O(FL8qKm+#bqWNbM5PFPg(HAVKGZvwN7V^ckY-^zcDy(w4cQl53qH}p^~f7Q2#{$a ziC;~0(-xREZCGlNkKIz;Sa8hx%fVsvZxkNtZ5JP5a0}=*g|q>ttuP{1iRXBvm$34l z-TU<4m%O2|kILnxcfGE+zyB$VNv{Y3q$QcP^y;Dwu(3(oUM$2$j1Cd=cp8UX#60W) z(?_Z~J)YrC7<`9*cMD%D8>0T4od@VL{zLW$zYI3EXw&~JNo>UE&_W3uj;AuO{mTPp zeT?sk<$05m?~J)-iFedaQ@t9AtbKqE!OlMOB$YExTvw&d6b!(`=T>5LXsQQ)1@hdr zjA_4o0t>)%Q``8R#$zuQ_h+rf&pU_vPYls#@w8H#NCJeIRWg^Bl`Lv?-8&et}*(3 z$hI#*vDhN^$Ufs)t0bn!!6{>>#TWX}1U8grUwT>eq${D^T&pqrj1{}sgicAaUnPwL z_>*Q|;=u4-@HZovb<7~bYnA;yjXv|N07F|zTBVdjX403?EIkSvXMBC;F=z~pyWbJi zH(8J=eQ9dIxODQcyYxK^H|Pg&zgc=`II|AxvW;z=nVLGzJQEkY_#!^=80jXkp`gBW zw6ktW8OFRPu{@1Fv(AP^^3st2Y^p&<_9Z`_IL930e0^pWY*y2_U`PkAt&X&Jd}x9+ zWE+>_V3xX;dlR4Ku@f|V?BWmfNiwA`O~>^xy3c$)rtgA`m~DOi{b@1ewJCYoNYMu= zeW?>^{pj+y^|HG+>E$t*ZC0VJL)5hroYT1b{e^y$1<8Bo4sfoBy0V@R`tkaYVWT(k z_os5P;kTXbvFL^Dt^ULJE4|Wx1iKTTCL9}@eo^sXzW{1Z9c0SAcp9+#pAlqCj3X`M zCpUrQj)U1>H{kx2l@Eg5-)9(i8}_g{gRRWwgYP*d!vw>=Pw9jz<$ajHTyPxaPJU!}-`7oeXMM06Xs*xN>Yh`APF z)~}qnPlb*`uOCMCrI7W*IP15s!quG3b)n0g6Y2z~^d;N+?NZ*oUi zznI=%xNFIbtA$n|Pu^e1`3rl0)Znl0UWhqNz=mL9Jkx%E#75FK2oB4m>IAiolb?>A zeBg+Kxm33lfl>rAivX@=b2-PA$y%-3%9TpgXx&-{S*3L|WU?F&4#-b(3ln5BMlFRW z*;duqiJw>DcUF@+@KY=N{;C#9h2LL+8ZrJ+;*U;XzY=9qsdCC@{1%>)o1ZAT5sH$V zqP$Y_rJl4CJqbsz0->GQ6&!*~a5g)*#SigI{1m?>4sqir^|?=LGB^P)?bAXKN>qwK zDFUSklp;`yKq&&D5x^V*vn-7nS5KCPD3fHtr5B40vy+EeWH_PTZ^7C|wi2&k79X;eq7O3GwIEn?Ed%DXZ_`h~nyt_N_M*4YF$nPet={xqVo~TA1o+;o z=UsdkS*REkgYSikL4fah>GR^VUk3GqnU}8Cryqa6KI4SkFm=sKrg^aaQi-}5y7 zZJ}|&(4$lKa)#LT`+mt!!q<*7od*}w{V(6XOU#NP28HrHA_jSx{}$T!LdKw2d@n={ zf_zVB{o{t;KdtdU)iPqXAZ{YB6Apn_n@oC`|o1*y%%B-wEy8@#KENu?r}Nm^Ww8#0$i@f zMF0Mma@TPrqI@rs{ZHB67u@|%aJg3e&tU%>H-hDLFDUF;`#~oA-=K^8AGsIM5WmA1 zbN^#reV1zjV0*-1%j?+xI6MCSN9u&WgLVIFC9ucc|2j?L=#|iO1-K0yMF;EtXZmK{ z|Llvy*K+^6HwLA2DFUSklp;`yKq&&H2z+%T5H-P=LY?e5C>3YT*B@L31<)n{UbP?V$ut^_4;I=ICT@k{&^zaVRSandbox - - - - - - + + + + + + diff --git a/samples/Tutorials/CSharpBeginner/CSharpBeginner/CSharpBeginner.Game/CSharpBeginner.Game.csproj b/samples/Tutorials/CSharpBeginner/CSharpBeginner/CSharpBeginner.Game/CSharpBeginner.Game.csproj new file mode 100644 index 0000000000..9ac020033e --- /dev/null +++ b/samples/Tutorials/CSharpBeginner/CSharpBeginner/CSharpBeginner.Game/CSharpBeginner.Game.csproj @@ -0,0 +1,18 @@ + + + netstandard2.0 + CSharpBeginner + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/Tutorials/CSharpBeginner/CSharpBeginner/CSharpBeginner.Game/CSharpBeginner.Game.xkpkg b/samples/Tutorials/CSharpBeginner/CSharpBeginner/CSharpBeginner.Game/CSharpBeginner.Game.xkpkg new file mode 100644 index 0000000000..4455d1e391 --- /dev/null +++ b/samples/Tutorials/CSharpBeginner/CSharpBeginner/CSharpBeginner.Game/CSharpBeginner.Game.xkpkg @@ -0,0 +1,32 @@ +!Package +SerializedVersion: {Assets: 3.1.0.0} +Meta: + Name: CSharpBeginner.Game + Version: 1.0.0 + Authors: [] + Owners: [] + RootNamespace: CSharpBasics + Dependencies: null +AssetFolders: + - Path: !dir ../Assets + - Path: !dir Effects +ResourceFolders: + - !dir ../Resources +OutputGroupDirectories: {} +ExplicitFolders: [] +Bundles: [] +TemplateFolders: [] +RootAssets: + - 0a019d87-d943-4543-9b51-a4016200dff9:Scenes/Basics/Properties + - 137dcdfa-bfc8-4805-92a3-dd48f2b79061:Scenes/Basics/DeltaTime + - 328aea72-1405-48be-bf32-2363a61870f7:Scenes/Basics/Virtual buttons + - 52a557d6-1f2c-4983-a0bb-2c12d562d3bf:Scenes/Basics/Cloning entities + - 678cb64e-9dcd-44ea-8cdd-947667bbcc5a:Scenes/Basics/Adding a component + - 79af0b55-a70f-4c7a-8f5b-967d55661736:XenkoUILibrary + - 90c8a632-2df9-4335-8f09-24cb13e131b6:Scenes/Basics/Getting the entity + - 9e1b53ff-dc0c-410a-8972-14f949f83a01:Scenes/Basics/Child entities + - ba8ed57d-74b9-4121-baf0-6a92463b600a:Scenes/Basics/Getting a component + - c00aec52-d6b8-4eab-80c2-460ac8109da6:Scenes/Basics/Mouse input + - d8597439-175b-42b3-81ca-d6553655e38f:Scenes/Basics/Removing entities + - dbb3b809-4ff0-41da-b125-78a5ea1ec89c:Scenes/Basics/TransformPosition + - ee2eb459-7847-42b5-bd69-fc43a6625fd5:Scenes/Basics/Keyboard input diff --git a/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene b/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene index 942e216af8..de861503c6 100644 --- a/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene +++ b/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene @@ -19,14 +19,18 @@ Hierarchy: Rotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} Scale: {X: 1.0, Y: 1.0, Z: 1.0} Children: {} - ac2b7de7553bbc4ba5bbd9c3ba319cc1: !GameMenu.SplashScript,GameMenu.Game - Id: e77d2bac-3b55-4bbc-a5bb-d9c3ba319cc1 f6b6b1a8d48a8045bd940370455f3450: !UIComponent Id: a8b1b6f6-8ad4-4580-bd94-0370455f3450 Page: 62c493c2-13ea-4fac-bbaf-578afafac104:SplashUI Resolution: {X: 640.0, Y: 1136.0, Z: 1000.0} Size: {X: 1.0, Y: 1.0, Z: 1.0} ResolutionStretch: FixedWidthFixedHeight + fd54344b6ac8b2ed232d62dc08820239: !GameMenu.SplashScript,GameMenu.Game + Id: c7c92d4b-2c04-446f-b8c5-59e9d2b989cd + NextSceneUrl: 9294c606-6173-4215-a8dc-0d5043d68333:MainScene + 2f704fab49b226562874d765af6b6918: !GameMenu.SplashScript,GameMenu.Game + Id: 10460fb9-8816-4db7-9b7f-452c3d653779 + NextSceneUrl: 9294c606-6173-4215-a8dc-0d5043d68333:MainScene - Entity: Id: a604bc4e-f7f3-42c1-b98f-eeea9e10b54c Name: Camera diff --git a/samples/UI/GameMenu/GameMenu.Game/GameMenu.Game.csproj b/samples/UI/GameMenu/GameMenu.Game/GameMenu.Game.csproj index b1aac351ee..b179442729 100644 --- a/samples/UI/GameMenu/GameMenu.Game/GameMenu.Game.csproj +++ b/samples/UI/GameMenu/GameMenu.Game/GameMenu.Game.csproj @@ -4,10 +4,10 @@ GameMenu - - - - - + + + + + \ No newline at end of file diff --git a/samples/UI/GameMenu/GameMenu.Game/SplashScript.cs b/samples/UI/GameMenu/GameMenu.Game/SplashScript.cs index 7bfdd9e0c3..779e6df9cf 100644 --- a/samples/UI/GameMenu/GameMenu.Game/SplashScript.cs +++ b/samples/UI/GameMenu/GameMenu.Game/SplashScript.cs @@ -1,6 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Linq; +using Xenko.Core.Serialization; using Xenko.Engine; using Xenko.Input; @@ -8,6 +9,8 @@ namespace GameMenu { public class SplashScript : UISceneBase { + public UrlReference NextSceneUrl { get; set; } + protected override void LoadScene() { // Allow user to resize the window with the mouse. @@ -19,7 +22,7 @@ protected override void UpdateScene() if (Input.PointerEvents.Any(e => e.EventType == PointerEventType.Pressed)) { // Next scene - SceneSystem.SceneInstance.RootScene = Content.Load("MainScene"); + SceneSystem.SceneInstance.RootScene = Content.Load(NextSceneUrl); Cancel(); } } diff --git a/samples/UI/UIElementLink/Assets/Shared/BillboardedScreen.xkscene b/samples/UI/UIElementLink/Assets/Shared/BillboardedScreen.xkscene index 1eeafff442..60a95ed5e7 100644 --- a/samples/UI/UIElementLink/Assets/Shared/BillboardedScreen.xkscene +++ b/samples/UI/UIElementLink/Assets/Shared/BillboardedScreen.xkscene @@ -63,8 +63,8 @@ Hierarchy: Size: Large DepthRange: {} PartitionMode: !LightDirectionalShadowMap.PartitionLogarithmic {} - ComputeTransmittance: false BiasParameters: {} + ComputeTransmittance: false - Entity: Id: 820d34a8-2971-4381-abfa-2965d94ec672 Name: Splash @@ -78,7 +78,7 @@ Hierarchy: a7872780eefdc542b4880d3c4b46f129: !UIElementLink.SplashScript,UIElementLink.Game Id: 802787a7-fdee-42c5-b488-0d3c4b46f129 SplashScreenImages: e8e2f386-e79e-4875-993f-8bdaf0ef72c5:SplashScreenImages - NextScene: FullScreen + NextScene: 67a9eb30-7686-4b8c-89c3-19f12755774e:FullScreen f6b6b1a8d48a8045bd940370455f3450: !UIComponent Id: a8b1b6f6-8ad4-4580-bd94-0370455f3450 Page: null @@ -153,8 +153,8 @@ Hierarchy: InheritRotation: true Rotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} InheritScale: true - ScaleUniform: 1.0 Scale: {X: 1.0, Y: 1.0, Z: 1.0} + ScaleUniform: 1.0 SeedOffset: 0 DisplayParticlePosition: false DisplayParticleRotation: true diff --git a/samples/UI/UIElementLink/Assets/Shared/FullScreen.xkscene b/samples/UI/UIElementLink/Assets/Shared/FullScreen.xkscene index d88bad5327..4ff3cb52a0 100644 --- a/samples/UI/UIElementLink/Assets/Shared/FullScreen.xkscene +++ b/samples/UI/UIElementLink/Assets/Shared/FullScreen.xkscene @@ -63,8 +63,8 @@ Hierarchy: Size: Large DepthRange: {} PartitionMode: !LightDirectionalShadowMap.PartitionLogarithmic {} - ComputeTransmittance: false BiasParameters: {} + ComputeTransmittance: false - Entity: Id: 820d34a8-2971-4381-abfa-2965d94ec672 Name: Splash @@ -78,7 +78,7 @@ Hierarchy: a7872780eefdc542b4880d3c4b46f129: !UIElementLink.SplashScript,UIElementLink.Game Id: 802787a7-fdee-42c5-b488-0d3c4b46f129 SplashScreenImages: e8e2f386-e79e-4875-993f-8bdaf0ef72c5:SplashScreenImages - NextScene: TiltedScreen + NextScene: 0bbdf1ab-bb41-46c5-86ef-4f2635d65c6a:TiltedScreen f6b6b1a8d48a8045bd940370455f3450: !UIComponent Id: a8b1b6f6-8ad4-4580-bd94-0370455f3450 Page: null @@ -152,8 +152,8 @@ Hierarchy: InheritRotation: true Rotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} InheritScale: true - ScaleUniform: 1.0 Scale: {X: 1.0, Y: 1.0, Z: 1.0} + ScaleUniform: 1.0 SeedOffset: 0 DisplayParticlePosition: false DisplayParticleRotation: true diff --git a/samples/UI/UIElementLink/Assets/Shared/TiltedScreen.xkscene b/samples/UI/UIElementLink/Assets/Shared/TiltedScreen.xkscene index c9eb58bc57..1675b5fed3 100644 --- a/samples/UI/UIElementLink/Assets/Shared/TiltedScreen.xkscene +++ b/samples/UI/UIElementLink/Assets/Shared/TiltedScreen.xkscene @@ -63,8 +63,8 @@ Hierarchy: Size: Large DepthRange: {} PartitionMode: !LightDirectionalShadowMap.PartitionLogarithmic {} - ComputeTransmittance: false BiasParameters: {} + ComputeTransmittance: false - Entity: Id: 820d34a8-2971-4381-abfa-2965d94ec672 Name: Splash @@ -78,7 +78,7 @@ Hierarchy: a7872780eefdc542b4880d3c4b46f129: !UIElementLink.SplashScript,UIElementLink.Game Id: 802787a7-fdee-42c5-b488-0d3c4b46f129 SplashScreenImages: e8e2f386-e79e-4875-993f-8bdaf0ef72c5:SplashScreenImages - NextScene: BillboardedScreen + NextScene: a140a866-a7b3-4c89-8953-5f7adc428c0a:BillboardedScreen f6b6b1a8d48a8045bd940370455f3450: !UIComponent Id: a8b1b6f6-8ad4-4580-bd94-0370455f3450 Page: null @@ -154,8 +154,8 @@ Hierarchy: InheritRotation: true Rotation: {X: 0.0, Y: 0.0, Z: 0.0, W: 1.0} InheritScale: true - ScaleUniform: 1.0 Scale: {X: 1.0, Y: 1.0, Z: 1.0} + ScaleUniform: 1.0 SeedOffset: 0 DisplayParticlePosition: false DisplayParticleRotation: true diff --git a/samples/UI/UIElementLink/UIElementLink.Game/SplashScript.cs b/samples/UI/UIElementLink/UIElementLink.Game/SplashScript.cs index 2e61b128d4..7ad4767dac 100644 --- a/samples/UI/UIElementLink/UIElementLink.Game/SplashScript.cs +++ b/samples/UI/UIElementLink/UIElementLink.Game/SplashScript.cs @@ -3,6 +3,7 @@ using System; using Xenko.Core.Extensions; using Xenko.Core.Mathematics; +using Xenko.Core.Serialization; using Xenko.Engine; using Xenko.Graphics; using Xenko.Rendering.Sprites; @@ -16,7 +17,7 @@ public class SplashScript : UISceneBase { public SpriteSheet SplashScreenImages; - public string NextScene; + public UrlReference NextScene; private Button followedButton; @@ -24,10 +25,10 @@ public class SplashScript : UISceneBase private void LoadNextScene() { - if (NextScene.IsNullOrEmpty()) + if (NextScene?.IsEmpty ?? true) return; - SceneSystem.SceneInstance.RootScene = Content.Load(NextScene); + SceneSystem.SceneInstance.RootScene = Content.Load(NextScene); Cancel(); } diff --git a/samples/UI/UIElementLink/UIElementLink.Game/UIElementLink.Game.csproj b/samples/UI/UIElementLink/UIElementLink.Game/UIElementLink.Game.csproj index da3e1693c8..8620fee23f 100644 --- a/samples/UI/UIElementLink/UIElementLink.Game/UIElementLink.Game.csproj +++ b/samples/UI/UIElementLink/UIElementLink.Game/UIElementLink.Game.csproj @@ -4,10 +4,10 @@ UIElementLink - - - - - + + + + + \ No newline at end of file diff --git a/samples/UI/UIParticles/UIParticles.Game/UIParticles.Game.csproj b/samples/UI/UIParticles/UIParticles.Game/UIParticles.Game.csproj index c7b810e9b4..3dbd7696f5 100644 --- a/samples/UI/UIParticles/UIParticles.Game/UIParticles.Game.csproj +++ b/samples/UI/UIParticles/UIParticles.Game/UIParticles.Game.csproj @@ -4,10 +4,10 @@ UIParticles - - - - - + + + + + \ No newline at end of file diff --git a/sources/assets/Xenko.Core.Assets/AssetRegistry.cs b/sources/assets/Xenko.Core.Assets/AssetRegistry.cs index c87cd88e10..2ef2c4c726 100644 --- a/sources/assets/Xenko.Core.Assets/AssetRegistry.cs +++ b/sources/assets/Xenko.Core.Assets/AssetRegistry.cs @@ -11,6 +11,7 @@ using Xenko.Core.Serialization.Contents; using Xenko.Core.VisualStudio; using Xenko.Core.Yaml.Serialization; +using Xenko.Core.Serialization; namespace Xenko.Core.Assets { @@ -289,6 +290,14 @@ public static IReadOnlyList GetAssetTypes(Type contentType) lock (RegistryLock) { var currentType = contentType; + if (UrlReferenceHelper.IsGenericUrlReferenceType(currentType)) + { + currentType = UrlReferenceHelper.GetTargetContentType(currentType); + } + else if (UrlReferenceHelper.IsUrlReferenceType(contentType)) + { + return GetPublicTypes().Where(t => IsAssetType(t)).ToList(); + } List assetTypes; return ContentToAssetTypes.TryGetValue(currentType, out assetTypes) ? new List(assetTypes) : new List(); } diff --git a/sources/assets/Xenko.Core.Assets/Serializers/UrlReferenceSerializer.cs b/sources/assets/Xenko.Core.Assets/Serializers/UrlReferenceSerializer.cs new file mode 100644 index 0000000000..ee78bcb0cb --- /dev/null +++ b/sources/assets/Xenko.Core.Assets/Serializers/UrlReferenceSerializer.cs @@ -0,0 +1,51 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core.Serialization; +using Xenko.Core.Yaml; +using Xenko.Core.Yaml.Events; +using Xenko.Core.Yaml.Serialization; + +namespace Xenko.Core.Assets.Serializers +{ + /// + /// A Yaml serializer for + /// + [YamlSerializerFactory(YamlAssetProfile.Name)] + internal class UrlReferenceSerializer : AssetScalarSerializerBase + { + public override bool CanVisit(Type type) + { + return UrlReferenceHelper.IsUrlReferenceType(type); + } + + public override object ConvertFrom(ref ObjectContext context, Scalar fromScalar) + { + if (!AssetReference.TryParse(fromScalar.Value, out var guid, out var location)) + { + throw new YamlException(fromScalar.Start, fromScalar.End, "Unable to decode url reference [{0}]. Expecting format GUID:LOCATION".ToFormat(fromScalar.Value)); + } + + var urlReference = UrlReferenceHelper.CreateReference(context.Descriptor.Type, guid, location.FullPath); + + return urlReference; + } + + public override string ConvertTo(ref ObjectContext objectContext) + { + if (objectContext.Instance is UrlReference urlReference) + { + var attachedReference = AttachedReferenceManager.GetAttachedReference(urlReference); + + if (attachedReference != null) + { + return $"{attachedReference.Id}:{urlReference.Url}"; + } + } + + throw new YamlException($"Unable to extract url reference from object [{objectContext.Instance}]"); + } + + + } +} diff --git a/sources/core/Xenko.Core.Design/Module.cs b/sources/core/Xenko.Core.Design/Module.cs index cf620f171e..4bdcd6932f 100644 --- a/sources/core/Xenko.Core.Design/Module.cs +++ b/sources/core/Xenko.Core.Design/Module.cs @@ -2,9 +2,9 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.ComponentModel; - using Xenko.Core.Mathematics; using Xenko.Core.Reflection; +using Xenko.Core.Serialization; using Xenko.Core.TypeConverters; namespace Xenko.Core @@ -16,6 +16,7 @@ public static void Initialize() { // Make sure that this assembly is registered AssemblyRegistry.Register(typeof(Module).Assembly, AssemblyCommonCategories.Assets); + TypeDescriptor.AddAttributes(typeof(Color), new TypeConverterAttribute(typeof(ColorConverter))); TypeDescriptor.AddAttributes(typeof(Color3), new TypeConverterAttribute(typeof(Color3Converter))); TypeDescriptor.AddAttributes(typeof(Color4), new TypeConverterAttribute(typeof(Color4Converter))); @@ -28,6 +29,7 @@ public static void Initialize() TypeDescriptor.AddAttributes(typeof(Vector2), new TypeConverterAttribute(typeof(Vector2Converter))); TypeDescriptor.AddAttributes(typeof(Vector3), new TypeConverterAttribute(typeof(Vector3Converter))); TypeDescriptor.AddAttributes(typeof(Vector4), new TypeConverterAttribute(typeof(Vector4Converter))); + TypeDescriptor.AddAttributes(typeof(IUrlReference), new TypeConverterAttribute(typeof(UrlReferenceConverter))); } } } diff --git a/sources/core/Xenko.Core.Design/TypeConverters/TypeConverterHelper.cs b/sources/core/Xenko.Core.Design/TypeConverters/TypeConverterHelper.cs index 89ee11194e..a6c4edf32b 100644 --- a/sources/core/Xenko.Core.Design/TypeConverters/TypeConverterHelper.cs +++ b/sources/core/Xenko.Core.Design/TypeConverters/TypeConverterHelper.cs @@ -20,12 +20,13 @@ public static bool CanConvert([NotNull] Type sourceType, [NotNull] Type destinat if (sourceType == null) throw new ArgumentNullException(nameof(sourceType)); if (destinationType == null) throw new ArgumentNullException(nameof(destinationType)); + var context = new DestinationTypeDescriptorContext(destinationType); // already same type or inherited (also works with interface), or // implements IConvertible, or // can convert from source type to target type return destinationType.IsAssignableFrom(sourceType) || (typeof(IConvertible).IsAssignableFrom(sourceType) && Type.GetTypeCode(destinationType) != TypeCode.Object) || - TypeDescriptor.GetConverter(sourceType).CanConvertTo(destinationType) || TypeDescriptor.GetConverter(destinationType).CanConvertFrom(sourceType); + TypeDescriptor.GetConverter(sourceType).CanConvertTo(destinationType) || TypeDescriptor.GetConverter(destinationType).CanConvertFrom(context, sourceType); } /// @@ -69,10 +70,11 @@ public static bool TryConvert(object source, [NotNull] Type destinationType, out return true; } // Try to convert using the target type converter + var context = new DestinationTypeDescriptorContext(destinationType); converter = TypeDescriptor.GetConverter(destinationType); - if (converter.CanConvertFrom(sourceType)) + if (converter.CanConvertFrom(context, sourceType)) { - target = converter.ConvertFrom(source); + target = converter.ConvertFrom(context, System.Globalization.CultureInfo.CurrentCulture, source); return true; } } @@ -92,5 +94,43 @@ public static bool TryConvert(object source, [NotNull] Type destinationType, out target = null; return false; } + + public static Type GetDestinationType(ITypeDescriptorContext context) + { + if (context is DestinationTypeDescriptorContext c) return c.DestinationType; + + return null; + } + + private class DestinationTypeDescriptorContext : ITypeDescriptorContext + { + public DestinationTypeDescriptorContext(Type destinationType) + { + DestinationType = destinationType; + } + + public Type DestinationType { get; } + + public IContainer Container => null; + + public object Instance => null; + + public PropertyDescriptor PropertyDescriptor => null; + + public object GetService(Type serviceType) + { + return null; + } + + public void OnComponentChanged() + { + + } + + public bool OnComponentChanging() + { + return true; + } + } } } diff --git a/sources/core/Xenko.Core.Design/TypeConverters/UrlReferenceConverter.cs b/sources/core/Xenko.Core.Design/TypeConverters/UrlReferenceConverter.cs new file mode 100644 index 0000000000..8a9b518675 --- /dev/null +++ b/sources/core/Xenko.Core.Design/TypeConverters/UrlReferenceConverter.cs @@ -0,0 +1,35 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.ComponentModel; +using System.Globalization; +using Xenko.Core.Serialization; + +namespace Xenko.Core.TypeConverters +{ + /// + /// Defines a type converter for . + /// + public class UrlReferenceConverter : BaseConverter + { + + public UrlReferenceConverter() + { + //TODO: PropertyDescriptor does not support Properties, only fields so can not currently Set Properties. Does not seem to impact usage. + } + + /// + public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + { + return UrlReferenceHelper.IsUrlReferenceType(TypeConverterHelper.GetDestinationType(context)); + } + + /// + public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + { + var attachedReference = AttachedReferenceManager.GetAttachedReference(value); + var destinationType = TypeConverterHelper.GetDestinationType(context); + return UrlReferenceHelper.CreateReference(destinationType, attachedReference.Id, attachedReference.Url); + } + } +} diff --git a/sources/core/Xenko.Core.Serialization/Serialization/AttachedReferenceManager.cs b/sources/core/Xenko.Core.Serialization/Serialization/AttachedReferenceManager.cs index 157a13c722..4f588d766f 100644 --- a/sources/core/Xenko.Core.Serialization/Serialization/AttachedReferenceManager.cs +++ b/sources/core/Xenko.Core.Serialization/Serialization/AttachedReferenceManager.cs @@ -85,10 +85,8 @@ public static AttachedReference GetOrCreateAttachedReference(object obj) public static T CreateProxyObject(AssetId id, string location) where T : class, new() { var result = new T(); - var attachedReference = GetOrCreateAttachedReference(result); - attachedReference.Id = id; - attachedReference.Url = location; - attachedReference.IsProxy = true; + InitializeProxyObject(result, id, location); + return result; } @@ -121,11 +119,15 @@ public static object CreateProxyObject(Type type, AssetId id, string location) } } var result = emptyCtor.Invoke(EmptyObjectArray); - var attachedReference = GetOrCreateAttachedReference(result); + InitializeProxyObject(result, id, location); + return result; + } + private static void InitializeProxyObject(object proxyObject, AssetId id, string location) + { + var attachedReference = GetOrCreateAttachedReference(proxyObject); attachedReference.Id = id; attachedReference.Url = location; attachedReference.IsProxy = true; - return result; } } } diff --git a/sources/core/Xenko.Core.Serialization/Serialization/Contents/ContentManager.cs b/sources/core/Xenko.Core.Serialization/Serialization/Contents/ContentManager.cs index c8b15dc925..d22d4d4a14 100644 --- a/sources/core/Xenko.Core.Serialization/Serialization/Contents/ContentManager.cs +++ b/sources/core/Xenko.Core.Serialization/Serialization/Contents/ContentManager.cs @@ -232,7 +232,7 @@ private static Task ScheduleAsync(Func action) /// The URL of the asset to retrieve. /// The loaded asset, or null if the asset has not been loaded. /// This function does not increase the reference count on the asset. - public T Get(string url) + public T Get(string url) where T : class { return (T)Get(typeof(T), url); } @@ -250,7 +250,7 @@ public object Get(Type type, string url) } /// - /// Gets or sets whether an asset with the given URL is currently loaded. + /// Gets whether an asset with the given URL is currently loaded. /// /// The URL to check. /// If true, this method will return true only if an asset with the given URL has been manually loaded via , and not if the asset has been only loaded indirectly from another asset. diff --git a/sources/core/Xenko.Core.Serialization/Serialization/Contents/IContentManager.cs b/sources/core/Xenko.Core.Serialization/Serialization/Contents/IContentManager.cs index d8c854d5c3..bc3686348d 100644 --- a/sources/core/Xenko.Core.Serialization/Serialization/Contents/IContentManager.cs +++ b/sources/core/Xenko.Core.Serialization/Serialization/Contents/IContentManager.cs @@ -45,12 +45,35 @@ public interface IContentManager /// Task LoadAsync(string url, ContentManagerLoaderSettings settings = null) where T : class; + /// + /// Gets a previously loaded asset from its URL. + /// + /// The type of asset to retrieve. + /// The URL of the asset to retrieve. + /// The loaded asset, or null if the asset has not been loaded. + /// This function does not increase the reference count on the asset. + T Get(string url) where T : class; + + /// + /// Gets whether an asset with the given URL is currently loaded. + /// + /// The URL to check. + /// If true, this method will return true only if an asset with the given URL has been manually loaded via , and not if the asset has been only loaded indirectly from another asset. + /// True if an asset with the given URL is currently loaded, false otherwise. + bool IsLoaded(string url, bool loadedManuallyOnly = false); + /// /// Unloads the specified object. /// /// The object to unload. void Unload(object obj); + /// + /// Unloads the asset at the specified URL. + /// + /// The URL. + void Unload(string url); + /// /// Gets the serializer. /// diff --git a/sources/core/Xenko.Core.Serialization/Serialization/IUrlReference.cs b/sources/core/Xenko.Core.Serialization/Serialization/IUrlReference.cs new file mode 100644 index 0000000000..ca7042180c --- /dev/null +++ b/sources/core/Xenko.Core.Serialization/Serialization/IUrlReference.cs @@ -0,0 +1,18 @@ +namespace Xenko.Core.Serialization +{ + /// + /// Represents a Url to an asset. + /// + public interface IUrlReference + { + // + /// Gets the Url of the referenced asset. + /// + string Url { get; } + + /// + /// Gets whether the is null or empty. + /// + bool IsEmpty { get; } + } +} diff --git a/sources/core/Xenko.Core.Serialization/Serialization/Serializers/UrlReferenceDataSerializer.cs b/sources/core/Xenko.Core.Serialization/Serialization/Serializers/UrlReferenceDataSerializer.cs new file mode 100644 index 0000000000..ec5a73616d --- /dev/null +++ b/sources/core/Xenko.Core.Serialization/Serialization/Serializers/UrlReferenceDataSerializer.cs @@ -0,0 +1,56 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core.Annotations; +using Xenko.Core.Assets; + +namespace Xenko.Core.Serialization.Serializers +{ + /// + /// Serializer base class for for . + /// + public abstract class UrlReferenceDataSerializerBase : DataSerializer + where T: IUrlReference + { + /// + public override void Serialize(ref T urlReference, ArchiveMode mode, [NotNull] SerializationStream stream) + { + if (mode == ArchiveMode.Serialize) + { + var attachedReference = AttachedReferenceManager.GetAttachedReference(urlReference); + if(attachedReference == null) + { + throw new InvalidOperationException("UrlReference does not have an AttachedReference."); + } + + stream.Write(attachedReference.Id); + stream.Write(attachedReference.Url); + } + else + { + var id = stream.Read(); + var url = stream.ReadString(); + + urlReference = (T)UrlReferenceHelper.CreateReference(typeof(T), id, url); + } + } + } + + /// + /// Serializer for . + /// + public sealed class UrlReferenceDataSerializer : UrlReferenceDataSerializerBase + { + + } + + /// + /// Serializer for . + /// + /// The type of asset. + public sealed class UrlReferenceDataSerializer : UrlReferenceDataSerializerBase> + where T : class + { + + } +} diff --git a/sources/core/Xenko.Core.Serialization/Serialization/UrlReference.cs b/sources/core/Xenko.Core.Serialization/Serialization/UrlReference.cs new file mode 100644 index 0000000000..ba5383cc8e --- /dev/null +++ b/sources/core/Xenko.Core.Serialization/Serialization/UrlReference.cs @@ -0,0 +1,57 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core.Serialization.Serializers; + +namespace Xenko.Core.Serialization +{ + /// + /// Represents a Url to an asset. + /// + [DataSerializer(typeof(UrlReferenceDataSerializer))] + public sealed class UrlReference : UrlReferenceBase + { + /// + /// Create a new instance. + /// + public UrlReference() + { + + } + + /// + /// Create a new instance. + /// + /// + /// If is null or empty. + public UrlReference(string url) : base(url) + { + } + } + + /// + /// Represents a Url to an asset of type . + /// + /// The type off asset. + [DataSerializer(typeof(UrlReferenceDataSerializer<>), Mode = DataSerializerGenericMode.GenericArguments)] + public sealed class UrlReference : UrlReferenceBase + where T : class + { + /// + /// Create a new instance. + /// + public UrlReference() + { + + } + + /// + /// Create a new instance. + /// + /// + /// If is null or empty. + public UrlReference(string url) : base(url) + { + } + } +} diff --git a/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceBase.cs b/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceBase.cs new file mode 100644 index 0000000000..e3b362c8a1 --- /dev/null +++ b/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceBase.cs @@ -0,0 +1,70 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core.Serialization.Contents; + +namespace Xenko.Core.Serialization +{ + /// + /// Base class for implementations + /// + [DataContract("urlref", Inherited = true)] + [DataStyle(DataStyle.Compact)] + [ReferenceSerializer] + public abstract class UrlReferenceBase : IUrlReference + { + private string url; + + /// + /// Create a new instance. + /// + protected UrlReferenceBase() + { + + } + + /// + /// Create a new instance. + /// + /// + /// If is null or empty. + protected UrlReferenceBase(string url) + { + if (string.IsNullOrWhiteSpace(url)) + { + throw new ArgumentNullException(nameof(url), $"{nameof(url)} cannot be null or empty."); + } + + this.url = url; + } + + // + /// Gets the Url of the referenced asset. + /// + [DataMember(10)] + public string Url + { + get => url; + internal set + { + if (string.IsNullOrEmpty(value)) + { + throw new ArgumentNullException(nameof(value), $"{nameof(Url)} cannot be null or empty."); + } + url = value; + } + } + + /// + /// Gets whether the url is null or empty. + /// + [DataMemberIgnore] + public bool IsEmpty => string.IsNullOrEmpty(url); + + /// + public override string ToString() + { + return $"{Url}"; + } + } +} diff --git a/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceContentManagerExtenstions.cs b/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceContentManagerExtenstions.cs new file mode 100644 index 0000000000..3ce51318e8 --- /dev/null +++ b/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceContentManagerExtenstions.cs @@ -0,0 +1,134 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.IO; +using System.Threading.Tasks; +using Xenko.Core.IO; +using Xenko.Core.Serialization.Contents; + +namespace Xenko.Core.Serialization +{ + /// + /// Extension methods of to allow usage of and . + /// + public static class UrlReferenceContentManagerExtenstions + { + /// + /// Check if the specified asset url exists. + /// + /// The . + /// The URL. + /// true if the specified asset url exists, false otherwise. + /// If is null or empty. Or is null. + public static bool Exists(this IContentManager content, IUrlReference urlReference) + { + CheckArguments(content, urlReference); + + return content.Exists(urlReference.Url); + } + + /// + /// Opens the specified URL as a stream used for custom raw asset loading. + /// + /// The . + /// The URL to the raw asset. + /// The type of stream needed + /// A stream to the raw asset. + /// If is null or empty. Or is null. + public static Stream OpenAsStream(this IContentManager content, UrlReference urlReference, StreamFlags streamFlags = StreamFlags.None) + { + CheckArguments(content, urlReference); + + return content.OpenAsStream(urlReference.Url, streamFlags); + } + + /// + /// Loads content from the specified URL. + /// + /// The content type. + /// The . + /// The URL to load from. + /// The settings. If null, fallback to . + /// The loaded content. + /// If is null or empty. Or is null. + public static T Load(this IContentManager content, UrlReference urlReference, ContentManagerLoaderSettings settings = null) + where T : class + { + CheckArguments(content, urlReference); + + return content.Load(urlReference.Url, settings); + } + + /// + /// Loads content from the specified URL asynchronously. + /// + /// The content type. + /// The . + /// The URL to load from. + /// The settings. If null, fallback to . + /// The loaded content. + /// If is null or empty. Or is null. + public static Task LoadAsync(this IContentManager content, UrlReference urlReference, ContentManagerLoaderSettings settings = null) + where T : class + { + CheckArguments(content, urlReference); + + return content.LoadAsync(urlReference.Url, settings); + } + + /// + /// Gets a previously loaded asset from its URL. + /// + /// The type of asset to retrieve. + /// The URL of the asset to retrieve. + /// The loaded asset, or null if the asset has not been loaded. + /// If is null or empty. Or is null. + /// This function does not increase the reference count on the asset. + public static T Get(this IContentManager content, UrlReference urlReference) + where T : class + { + CheckArguments(content, urlReference); + + return content.Get(urlReference.Url); + } + + /// + /// Gets whether an asset with the given URL is currently loaded. + /// + /// The URL to check. + /// If true, this method will return true only if an asset with the given URL has been manually loaded via , and not if the asset has been only loaded indirectly from another asset. + /// True if an asset with the given URL is currently loaded, false otherwise. + /// If is null or empty. Or is null. + public static bool IsLoaded(this IContentManager content, IUrlReference urlReference, bool loadedManuallyOnly = false) + { + CheckArguments(content, urlReference); + + return content.IsLoaded(urlReference.Url, loadedManuallyOnly); + } + + /// + /// Unloads the asset at the specified URL. + /// + /// The URL. + /// If is null or empty. Or is null. + public static void Unload(this IContentManager content, IUrlReference urlReference) + { + CheckArguments(content, urlReference); + + content.Unload(urlReference.Url); + } + + private static void CheckArguments(IContentManager content, IUrlReference urlReference) + { + if (content == null) + { + throw new ArgumentNullException(nameof(content)); + } + + if (urlReference == null || urlReference.IsEmpty) + { + throw new ArgumentNullException(nameof(urlReference)); + } + } + } +} diff --git a/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceHelper.cs b/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceHelper.cs new file mode 100644 index 0000000000..c4dae40af7 --- /dev/null +++ b/sources/core/Xenko.Core.Serialization/Serialization/UrlReferenceHelper.cs @@ -0,0 +1,85 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core.Assets; + +namespace Xenko.Core.Serialization +{ + /// + /// A Helper class for and . + /// + public static class UrlReferenceHelper + { + /// + /// Creates a url reference to the given asset that matches the given reference type. + /// + /// The type of reference to create. + /// The target asset id to create. + /// The target asset url to create. + /// A url reference to the given asset if it's not null and is a valid reference url type, null otherwise. + /// A reference type is either an or a . + public static object CreateReference(Type referenceType, AssetId assetId, string assetUrl) + { + if (assetId != null && assetUrl != null && IsUrlReferenceType(referenceType)) + { + var urlReference = (UrlReferenceBase)AttachedReferenceManager.CreateProxyObject(referenceType, assetId, assetUrl); + + urlReference.Url = assetUrl; + + return urlReference; + } + + return null; + } + + /// + /// Checks if the given type is either an or a + /// + /// The type to test. + /// + public static bool IsUrlReferenceType(Type type) + => type != null && typeof(UrlReference).IsAssignableFrom(type) || IsGenericUrlReferenceType(type); + + /// + /// Checks if the given type is a + /// + /// The type to test. + /// + public static bool IsGenericUrlReferenceType(Type type) + => type != null && IsSubclassOfRawGeneric(GenericType, type); + + /// + /// Gets the asset content type for a given url reference type. + /// + /// The type is an url reference type, either an or a + /// The target content type or null. + public static Type GetTargetContentType(Type type) + { + if (!IsUrlReferenceType(type)) return null; + + if (IsSubclassOfRawGeneric(GenericType, type)) + { + return type.GetGenericArguments()[0]; + } + + return null; + } + + private static readonly Type GenericType = typeof(UrlReference<>); + + //TODO: this should probably be put in one of the Reflection helper classes. + static bool IsSubclassOfRawGeneric(Type type, Type c) + { + while (c != null && c != typeof(object)) + { + var cur = c.IsGenericType ? c.GetGenericTypeDefinition() : c; + if (type == cur) + { + return true; + } + c = c.BaseType; + } + return false; + } + } +} diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/ContentReferenceCollector.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/ContentReferenceCollector.cs index fbdd625fdd..277ab4a723 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/ContentReferenceCollector.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/ContentReferenceCollector.cs @@ -1,4 +1,4 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Collections.Generic; using Xenko.Core.Assets; @@ -83,7 +83,7 @@ protected override void VisitNode(IGraphNode node) } } var objectNode = node as IObjectNode; - if (objectNode != null) + if (objectNode != null && objectNode.Indices != null) { if (AssetRegistry.IsContentType(objectNode.Descriptor.GetInnerCollectionType())) { diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/SceneStreaming.cs b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/SceneStreaming.cs index 3319057fc3..68192d7ee5 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/SceneStreaming.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/SceneStreaming.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using Xenko.Core; using Xenko.Core.Mathematics; +using Xenko.Core.Serialization; using Xenko.Engine; using Xenko.Physics; @@ -27,7 +28,7 @@ public class ##Scriptname## : SyncScript /// /// The url of the scene to load /// - public string Url { get; set; } + public UrlReference Url { get; set; } /// /// The trigger volume. This should be a static collider, set to be a trigger @@ -97,14 +98,14 @@ public override void Update() if (shouldLoad) { // If we should load syncrhonously, just create a completed task and load - Instance = Content.Load(Url); + Instance = Content.Load(Url); loadingTask = Task.FromResult(Instance); } else if (shouldPreLoad) { loadCancellation = new CancellationTokenSource(); - var localLoadingTask = loadingTask = Content.LoadAsync(Url); + var localLoadingTask = loadingTask = Content.LoadAsync(Url); Script.AddTask(async () => { await loadingTask; diff --git a/sources/editor/Xenko.Core.Assets.Editor/Services/ContentReferenceHelper.cs b/sources/editor/Xenko.Core.Assets.Editor/Services/ContentReferenceHelper.cs index 3ba479724c..bfc54c39ab 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Services/ContentReferenceHelper.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/Services/ContentReferenceHelper.cs @@ -35,6 +35,11 @@ public static object CreateReference(AssetViewModel asset, Type referenceType) { if (asset != null) { + if (UrlReferenceHelper.IsUrlReferenceType(referenceType)) + { + return AttachedReferenceManager.CreateProxyObject(referenceType, asset.Id, asset.Url); + } + if (AssetRegistry.IsContentType(referenceType)) { var assetType = asset.AssetItem.Asset.GetType(); diff --git a/sources/editor/Xenko.Editor/EditorGame/ContentLoader/EditorContentLoader.cs b/sources/editor/Xenko.Editor/EditorGame/ContentLoader/EditorContentLoader.cs index 1738d35d6c..c1c8365414 100644 --- a/sources/editor/Xenko.Editor/EditorGame/ContentLoader/EditorContentLoader.cs +++ b/sources/editor/Xenko.Editor/EditorGame/ContentLoader/EditorContentLoader.cs @@ -148,7 +148,7 @@ public void BuildAndReloadAsset(AssetId assetId) Session.Dispatcher.InvokeAsync(() => BuildAndReloadAssets(assetToRebuild.Yield())); } - public T GetRuntimeObject(AssetItem assetItem) + public T GetRuntimeObject(AssetItem assetItem) where T : class { if (assetItem == null) throw new ArgumentNullException(nameof(assetItem)); diff --git a/sources/editor/Xenko.Editor/EditorGame/ContentLoader/IEditorContentLoader.cs b/sources/editor/Xenko.Editor/EditorGame/ContentLoader/IEditorContentLoader.cs index 3e2680819d..ae4f408e74 100644 --- a/sources/editor/Xenko.Editor/EditorGame/ContentLoader/IEditorContentLoader.cs +++ b/sources/editor/Xenko.Editor/EditorGame/ContentLoader/IEditorContentLoader.cs @@ -57,6 +57,6 @@ public interface IEditorContentLoader : IDisposable /// The expected type of the run-time object. /// The asset corresponding to the run-time object to retrieve. /// The run-time object corresponding to the given asset item if it exists, null otherwise. - T GetRuntimeObject(AssetItem assetItem); + T GetRuntimeObject(AssetItem assetItem) where T : class; } } diff --git a/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs b/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs index 1a2f7aa895..f7a68fb94c 100644 --- a/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs +++ b/sources/editor/Xenko.Samples.Templates/ThisPackageVersion.cs @@ -3,6 +3,6 @@ namespace Xenko.Samples.Templates static class ThisPackageVersion { // we version this package manually because most of the time the samples are big and don't need to be updated - public static string Current = "3.2.0.1-beta02"; + public static string Current = "3.2.0.1-beta03"; } } diff --git a/sources/presentation/Xenko.Core.Quantum/GraphNodeBase.cs b/sources/presentation/Xenko.Core.Quantum/GraphNodeBase.cs index c9c5324216..a097171a5b 100644 --- a/sources/presentation/Xenko.Core.Quantum/GraphNodeBase.cs +++ b/sources/presentation/Xenko.Core.Quantum/GraphNodeBase.cs @@ -6,6 +6,7 @@ using System.Linq; using Xenko.Core.Annotations; using Xenko.Core.Reflection; +using Xenko.Core.TypeConverters; namespace Xenko.Core.Quantum { @@ -81,5 +82,15 @@ public void Seal() { IsSealed = true; } + + protected static object ConvertValue(object value, Type type) + { + if (value == null) + return null; + object convertedValue; + if (!TypeConverterHelper.TryConvert(value, type, out convertedValue)) + throw new InvalidOperationException("Can not convert value to the required type"); + return convertedValue; + } } } diff --git a/sources/presentation/Xenko.Core.Quantum/MemberNode.cs b/sources/presentation/Xenko.Core.Quantum/MemberNode.cs index 154b1ca753..742811e468 100644 --- a/sources/presentation/Xenko.Core.Quantum/MemberNode.cs +++ b/sources/presentation/Xenko.Core.Quantum/MemberNode.cs @@ -111,7 +111,7 @@ private void Update(object newValue, bool sendNotification) var containerValue = Parent.Retrieve(); if (containerValue == null) throw new InvalidOperationException("Container's value is null"); - MemberDescriptor.Set(containerValue, newValue); + MemberDescriptor.Set(containerValue, ConvertValue(newValue, MemberDescriptor.Type)); if (containerValue.GetType().GetTypeInfo().IsValueType) ((GraphNodeBase)Parent).UpdateFromMember(containerValue, NodeIndex.Empty); diff --git a/sources/presentation/Xenko.Core.Quantum/ObjectNode.cs b/sources/presentation/Xenko.Core.Quantum/ObjectNode.cs index 0c9a7a7082..1aa10d478d 100644 --- a/sources/presentation/Xenko.Core.Quantum/ObjectNode.cs +++ b/sources/presentation/Xenko.Core.Quantum/ObjectNode.cs @@ -221,11 +221,11 @@ private void Update(object newValue, NodeIndex index, bool sendNotification) var dictionaryDescriptor = Descriptor as DictionaryDescriptor; if (collectionDescriptor != null) { - collectionDescriptor.SetValue(Value, index.Int, newValue); + collectionDescriptor.SetValue(Value, index.Int, ConvertValue(newValue, collectionDescriptor.ElementType)); } else if (dictionaryDescriptor != null) { - dictionaryDescriptor.SetValue(Value, index.Value, newValue); + dictionaryDescriptor.SetValue(Value, index.Value, ConvertValue(newValue, dictionaryDescriptor.ValueType)); } else throw new NotSupportedException("Unable to set the node value, the collection is unsupported"); From 4b37b75f72c7b2b098ca632197f493a7224220c4 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Fri, 20 Dec 2019 13:58:00 +0100 Subject: [PATCH 0555/2038] Merge pull request #571 from vvvv/video-serializer --- .../Storage/ObjectDatabase.cs | 22 +++++++++++++++++++ .../Xenko.Video/VideoInstance.Direct3D.cs | 9 ++------ sources/engine/Xenko.Video/VideoInstance.cs | 18 +++++++-------- 3 files changed, 33 insertions(+), 16 deletions(-) diff --git a/sources/core/Xenko.Core.Serialization/Storage/ObjectDatabase.cs b/sources/core/Xenko.Core.Serialization/Storage/ObjectDatabase.cs index 0e55176065..08dbfd80e8 100644 --- a/sources/core/Xenko.Core.Serialization/Storage/ObjectDatabase.cs +++ b/sources/core/Xenko.Core.Serialization/Storage/ObjectDatabase.cs @@ -112,6 +112,28 @@ public void CreateBundle(ObjectId[] objectIds, string bundleName, BundleOdbBacke BundleOdbBackend.CreateBundle(packUrl, backendRead1, objectIds, disableCompressionIds, indexMap, dependencies, useIncrementalBundle); } + public bool TryGetObjectLocation(ObjectId objectId, out string filePath, out long start, out long end) + { + if (BundleBackend != null && BundleBackend.TryGetObjectLocation(objectId, out filePath, out start, out end)) + return true; + + foreach (var backend in new[] { backendRead1, backendRead2 }) + { + if (backend != null && backend.Exists(objectId)) + { + filePath = backend.GetFilePath(objectId); + start = 0; + end = backend.GetSize(objectId); + return true; + } + } + + filePath = null; + start = 0; + end = 0; + return false; + } + /// /// Loads the specified bundle. /// diff --git a/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs b/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs index 930ae8a953..a6245245c0 100644 --- a/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs +++ b/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs @@ -9,6 +9,7 @@ using SharpDX.MediaFoundation; using Xenko.Core; using Xenko.Core.IO; +using Xenko.Core.Serialization; using Xenko.Graphics; using Xenko.Media; @@ -177,13 +178,7 @@ partial void InitializeMediaImpl(string url, long startPosition, long length, re // set the video source var mediaEngineEx = mediaEngine.QueryInterface(); - var databaseUrl = videoComponent.Source?.CompressedDataUrl; - if (databaseUrl == null) - { - Logger.Info("The video source is null. The video won't play."); - throw new Exception(); - } - videoFileStream = contentManager.OpenAsStream(databaseUrl, StreamFlags.Seekable); + videoFileStream = new VirtualFileStream(File.OpenRead(url), startPosition, startPosition + length); videoDataStream = new ByteStream(videoFileStream); // Creates an URL to the file diff --git a/sources/engine/Xenko.Video/VideoInstance.cs b/sources/engine/Xenko.Video/VideoInstance.cs index 238b791825..a42bc7fd72 100644 --- a/sources/engine/Xenko.Video/VideoInstance.cs +++ b/sources/engine/Xenko.Video/VideoInstance.cs @@ -471,20 +471,20 @@ public void InitializeFromDataSource() var fileProvider = source.FileProvider; if (!fileProvider.ContentIndexMap.TryGetValue(dataUrl, out ObjectId objectId) || - !fileProvider.ObjectDatabase.BundleBackend.TryGetObjectLocation(objectId, out url, out startPosition, out end)) + !fileProvider.ObjectDatabase.TryGetObjectLocation(objectId, out url, out startPosition, out end)) { throw new InvalidOperationException("Video files needs to be stored on the virtual file system in a non-compressed form."); } - } - // Initialize media - InitializeMedia(url, startPosition, end - startPosition); + // Initialize media + InitializeMedia(url, startPosition, end - startPosition); - // Set playback properties - UpdateAudioVolume(); - UpdateLoopingSettings(); - UpdatePlayRangeSettings(); - UpdateSpeedSettings(); + // Set playback properties + UpdateAudioVolume(); + UpdateLoopingSettings(); + UpdatePlayRangeSettings(); + UpdateSpeedSettings(); + } // Do not play and pause the new video. The new video always starts in the 'Stopped' state // It is responsibility of the user the revert play state after changing the source video. From ac62199c3986416fe3c862242427d9c6b802e2a3 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Fri, 20 Dec 2019 14:00:20 +0100 Subject: [PATCH 0556/2038] [Samples] GameMenu: remove duplicate SplashScript (from UrlReference branch) --- samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene | 3 --- 1 file changed, 3 deletions(-) diff --git a/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene b/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene index de861503c6..d28e564027 100644 --- a/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene +++ b/samples/UI/GameMenu/Assets/Shared/SplashScene.xkscene @@ -28,9 +28,6 @@ Hierarchy: fd54344b6ac8b2ed232d62dc08820239: !GameMenu.SplashScript,GameMenu.Game Id: c7c92d4b-2c04-446f-b8c5-59e9d2b989cd NextSceneUrl: 9294c606-6173-4215-a8dc-0d5043d68333:MainScene - 2f704fab49b226562874d765af6b6918: !GameMenu.SplashScript,GameMenu.Game - Id: 10460fb9-8816-4db7-9b7f-452c3d653779 - NextSceneUrl: 9294c606-6173-4215-a8dc-0d5043d68333:MainScene - Entity: Id: a604bc4e-f7f3-42c1-b98f-eeea9e10b54c Name: Camera From 49e6ec98b710b58ba3b286d4a8f16513458b6ea8 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 20 Dec 2019 13:47:58 -0500 Subject: [PATCH 0557/2038] Physics: helpers to generate multiple static mesh collision components --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 8f59cee1b8..0da89d02bf 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -97,10 +97,46 @@ public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool return XZradius ? new Cylinder(Math.Max(b.X, b.Z), b.Y * 2f) : new Cylinder(b.Y, 2f * Math.Max(b.X, b.Z)); } + /// + /// Since you can't have non-convex shapes (e.g. mesh's) in a compound object, this helper will generate a bunch of individual static components to attach to an entity, with each shape. + /// + /// Entity to add static components to + /// shapes that will generate a static component for each + /// optional offset for each + /// optional rotation for each + public static void GenerateStaticComponents(Entity e, List shapes, List offsets = null, List rotations = null) + { + for (int i=0; i + /// Disposes of all mesh buffers used on an entity, of all static colliders + /// + /// Entity to dispose of static mesh colliders + public static void DisposeAllStaticMeshes(Entity e) + { + foreach(BepuStaticColliderComponent sc in e.GetAll()) + { + if (sc.ColliderShape is Mesh m) + { + sc.AddedToScene = false; + m.Dispose(BepuSimulation.instance.pBufferPool); + sc.ColliderShape = null; + } + } + } + /// /// Easily makes a Compound shape for you, given a list of individual shapes and how they should be offset. /// - /// List of shapes, must be IConvexShape if isDynamic is true + /// List of convex shapes /// Matching length list of offsets of bodies, can be null if nothing has an offset /// Matching length list of rotations of bodies, can be null if nothing is rotated /// True if intended to use in a dynamic situation, false if kinematic or static From c9ddfd6d21b5ba5785d4deae8740c11296ae5f9c Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Tue, 10 Dec 2019 15:00:26 +0900 Subject: [PATCH 0558/2038] Change type of InitialHeights to IInitialHeightData EmptyHeightData is to create empty heightfield. HeightDataFromHeightmap is to create heightfield from heightmap. # Conflicts: # sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs # sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs --- .../Physics/ColliderShapeAssetCompiler.cs | 5 ++- .../Data/HeightfieldColliderShapeDesc.cs | 2 +- .../engine/Xenko.Physics/EmptyHeightData.cs | 40 ++++++++++++++++++ .../Xenko.Physics/HeightDataFromHeightmap.cs | 42 +++++++++++++++++++ .../Xenko.Physics/IInitialHeightData.cs | 21 ++++++++++ 5 files changed, 107 insertions(+), 3 deletions(-) create mode 100644 sources/engine/Xenko.Physics/EmptyHeightData.cs create mode 100644 sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs create mode 100644 sources/engine/Xenko.Physics/IInitialHeightData.cs diff --git a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs index f0e98a3b8c..3644443e35 100644 --- a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs @@ -65,10 +65,11 @@ public override IEnumerable GetInputFiles(AssetItem assetItem) { else if (desc is HeightfieldColliderShapeDesc) { var heightfieldDesc = desc as HeightfieldColliderShapeDesc; + var initialHeights = heightfieldDesc?.InitialHeights as HeightDataFromHeightmap; - if (heightfieldDesc.InitialHeights != null) + if (initialHeights?.Heightmap != null) { - var url = AttachedReferenceManager.GetUrl(heightfieldDesc.InitialHeights); + var url = AttachedReferenceManager.GetUrl(initialHeights.Heightmap); if (!string.IsNullOrEmpty(url)) { diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index a8ce67945e..47065430dd 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -72,7 +72,7 @@ public bool Match(object obj) var heightScaleComparison = other.HeightScale?.Match(HeightScale) ?? HeightScale == null; - var initialHeightsComparison = (other.InitialHeights == InitialHeights); + var initialHeightsComparison = other.InitialHeights?.Match(InitialHeights) ?? InitialHeights == null; return initialHeightsComparison && other.HeightfieldType == HeightfieldType && diff --git a/sources/engine/Xenko.Physics/EmptyHeightData.cs b/sources/engine/Xenko.Physics/EmptyHeightData.cs new file mode 100644 index 0000000000..9391d36f9b --- /dev/null +++ b/sources/engine/Xenko.Physics/EmptyHeightData.cs @@ -0,0 +1,40 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core; +using Xenko.Core.Mathematics; + +namespace Xenko.Physics +{ + [DataContract] + [Display("Empty")] + public class EmptyHeightData : IInitialHeightData + { + [DataMember(10)] + public HeightfieldTypes HeightType { get; set; } = HeightfieldTypes.Float; + + [DataMember(20)] + public Int2 HeightStickSize { get; set; } = new Int2(65, 65); + + [Display(Browsable = false)] + public float[] Floats => null; + + [Display(Browsable = false)] + public short[] Shorts => null; + + [Display(Browsable = false)] + public byte[] Bytes => null; + + public bool Match(object obj) + { + var other = obj as EmptyHeightData; + + if (other == null) + { + return false; + } + + return other.HeightType == HeightType && + other.HeightStickSize == HeightStickSize; + } + } +} diff --git a/sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs b/sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs new file mode 100644 index 0000000000..ebe3f6e56d --- /dev/null +++ b/sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs @@ -0,0 +1,42 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core; +using Xenko.Core.Mathematics; + +namespace Xenko.Physics +{ + [DataContract] + [Display("Heightmap")] + public class HeightDataFromHeightmap : IInitialHeightData + { + [DataMember(10)] + public Heightmap Heightmap { get; set; } + + [Display(Browsable = false)] + public HeightfieldTypes HeightType => Heightmap?.HeightType ?? default; + + [Display(Browsable = false)] + public Int2 HeightStickSize => Heightmap?.Size ?? default; + + [Display(Browsable = false)] + public float[] Floats => Heightmap?.Floats; + + [Display(Browsable = false)] + public short[] Shorts => Heightmap?.Shorts; + + [Display(Browsable = false)] + public byte[] Bytes => Heightmap?.Bytes; + + public bool Match(object obj) + { + var other = obj as HeightDataFromHeightmap; + + if (other == null) + { + return false; + } + + return other.Heightmap == Heightmap; + } + } +} diff --git a/sources/engine/Xenko.Physics/IInitialHeightData.cs b/sources/engine/Xenko.Physics/IInitialHeightData.cs new file mode 100644 index 0000000000..32087fb40a --- /dev/null +++ b/sources/engine/Xenko.Physics/IInitialHeightData.cs @@ -0,0 +1,21 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core.Mathematics; + +namespace Xenko.Physics +{ + public interface IInitialHeightData + { + HeightfieldTypes HeightType { get; } + + Int2 HeightStickSize { get; } + + float[] Floats { get; } + + short[] Shorts { get; } + + byte[] Bytes { get; } + + bool Match(object obj); + } +} From 5f01f9f7ea026cdea7edae3b31fa9a786c6d628a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 20 Dec 2019 16:43:11 -0500 Subject: [PATCH 0559/2038] Heightmap: catchup on all missed commits --- .../Preview/HeightmapPreview.cs | 4 +- .../Navigation/NavigationMeshAssetCompiler.cs | 52 ++++++++++++------- .../Xenko.Assets/Physics/HeightmapAsset.cs | 2 +- .../Physics/HeightmapAssetCompiler.cs | 13 +++-- .../Data/HeightfieldColliderShapeDesc.cs | 52 +++++++++---------- .../engine/Xenko.Physics/Engine/Heightmap.cs | 28 ++++------ .../Engine/HeightmapExtensions.cs | 10 ++-- .../Shapes/HeightfieldColliderShape.cs | 15 ++---- 8 files changed, 88 insertions(+), 88 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Preview/HeightmapPreview.cs b/sources/editor/Xenko.Assets.Presentation/Preview/HeightmapPreview.cs index f128e298d5..012a13e740 100644 --- a/sources/editor/Xenko.Assets.Presentation/Preview/HeightmapPreview.cs +++ b/sources/editor/Xenko.Assets.Presentation/Preview/HeightmapPreview.cs @@ -17,8 +17,8 @@ public class HeightmapPreview : PreviewFromSpriteBatch private Texture heightmapTexture; private BlendStateDescription adequateBlendState; - public int Width => heightmap?.Width ?? 0; - public int Length => heightmap?.Length ?? 0; + public int Width => heightmap?.Size.X ?? 0; + public int Length => heightmap?.Size.Y ?? 0; /// /// Gets or sets a callback that will be invoked when the texture is loaded. diff --git a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs index 7d1ad8fd5c..5916140db7 100644 --- a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs @@ -26,7 +26,7 @@ namespace Xenko.Assets.Navigation { [AssetCompiler(typeof(NavigationMeshAsset), typeof(AssetCompilationContext))] class NavigationMeshAssetCompiler : AssetCompilerBase - { + { public override IEnumerable GetInputTypes(AssetItem assetItem) { yield return new BuildDependencyInfo(typeof(SceneAsset), typeof(AssetCompilationContext), BuildDependencyType.CompileAsset); @@ -64,6 +64,21 @@ public override IEnumerable GetInputFiles(AssetItem assetItem) yield return new ObjectUrl(UrlType.Content, assetReference.Url); } } + else if (desc is HeightfieldColliderShapeDesc) + { + var heightfieldDesc = desc as HeightfieldColliderShapeDesc; + var initialHeights = heightfieldDesc?.InitialHeights as HeightDataFromHeightmap; + + if (initialHeights?.Heightmap != null) + { + var url = AttachedReferenceManager.GetUrl(initialHeights.Heightmap); + + if (!string.IsNullOrEmpty(url)) + { + yield return new ObjectUrl(UrlType.Content, url); + } + } + } } } } @@ -105,7 +120,7 @@ public NavmeshBuildCommand(string url, AssetItem assetItem, NavigationMeshAsset gameSettingsAsset = context.GetGameSettingsAsset(); asset = value; assetUrl = url; - + Version = 1; // Removed separate debug model stored in the navigation mesh } @@ -116,11 +131,11 @@ protected override void ComputeParameterHash(BinarySerializationWriter writer) EnsureClonedSceneAndHash(); writer.Write(sceneHash); writer.Write(asset.SelectedGroups); - + var navigationSettings = gameSettingsAsset.GetOrCreate(); writer.Write(navigationSettings.Groups); } - + protected override Task DoCommandOverride(ICommandContext commandContext) { var intermediateDataId = ComputeAssetIntermediateDataId(); @@ -131,7 +146,7 @@ protected override Task DoCommandOverride(ICommandContext commandC foreach (var colliderData in staticColliderDatas) navigationMeshBuilder.Add(colliderData); - + var navigationSettings = gameSettingsAsset.GetOrCreate(); var groupsLookup = navigationSettings.Groups.ToDictionary(x => x.Id, x => x); @@ -151,7 +166,7 @@ protected override Task DoCommandOverride(ICommandContext commandC } var result = navigationMeshBuilder.Build(asset.BuildSettings, groups, asset.IncludedCollisionGroups, boundingBoxes, CancellationToken.None); - + // Unload loaded collider shapes foreach (var pair in loadedColliderShapes) { @@ -264,7 +279,7 @@ private void EnsureClonedSceneAndHash() if (boundingBoxComponent == null && colliderComponent == null) continue; - + // Update world transform entity.Transform.UpdateWorldMatrix(); @@ -306,22 +321,21 @@ private void EnsureClonedSceneAndHash() } shapeAssetDesc.Shape = loadedColliderShape; } - else + else if (desc is HeightfieldColliderShapeDesc) { - if (desc.GetType() == typeof(HeightfieldColliderShapeDesc)) + var heightfieldDesc = desc as HeightfieldColliderShapeDesc; + var initialHeights = heightfieldDesc?.InitialHeights as HeightDataFromHeightmap; + + if (initialHeights?.Heightmap != null) { - var heightfieldDesc = ((HeightfieldColliderShapeDesc)desc); - if (heightfieldDesc.InitialHeights != null) + var assetReference = AttachedReferenceManager.GetAttachedReference(initialHeights.Heightmap); + object loadedHeightfieldInitialData; + if (!loadedHeightfieldInitialDatas.TryGetValue(assetReference.Url, out loadedHeightfieldInitialData)) { - var assetReference = AttachedReferenceManager.GetAttachedReference(heightfieldDesc.InitialHeights); - object loadedHeightfieldInitialData; - if (!loadedHeightfieldInitialDatas.TryGetValue(assetReference.Url, out loadedHeightfieldInitialData)) - { - loadedHeightfieldInitialData = contentManager.Load(typeof(Heightmap), assetReference.Url); - loadedHeightfieldInitialDatas.Add(assetReference.Url, loadedHeightfieldInitialData); - } - heightfieldDesc.InitialHeights = loadedHeightfieldInitialData as Heightmap; + loadedHeightfieldInitialData = contentManager.Load(typeof(Heightmap), assetReference.Url); + loadedHeightfieldInitialDatas.Add(assetReference.Url, loadedHeightfieldInitialData); } + initialHeights.Heightmap = loadedHeightfieldInitialData as Heightmap; } } } diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs index 32d9cf0c99..b5598ec856 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs @@ -21,7 +21,7 @@ public partial class HeightmapAsset : AssetWithSource [DataMember(20)] [Display(category: "Convert")] [NotNull] - public HeightfieldTypes Type { get; set; } = HeightfieldTypes.Float; + public HeightfieldTypes HeightType { get; set; } = HeightfieldTypes.Float; [DataMember(30)] [Display(category: "Convert")] diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs index 1e1d395590..05c680050a 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -1,7 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; using Xenko.Assets.Textures; using Xenko.Core.Assets; @@ -69,6 +68,11 @@ protected override Task DoCommandOverride(ICommandContext commandC Parameters.Resizing.Size : new Int2(texImage.Width, texImage.Height); + if (!HeightfieldColliderShapeDesc.IsValidHeightStickSize(size)) + { + continue; + } + if (texImage.Width != size.X || texImage.Height != size.Y) { textureTool.Resize(texImage, size.X, size.Y, Filter.Rescaling.Nearest); @@ -76,7 +80,7 @@ protected override Task DoCommandOverride(ICommandContext commandC // Convert pixel format of the image - var heightfieldType = Parameters.Type; + var heightfieldType = Parameters.HeightType; switch (heightfieldType) { @@ -214,9 +218,8 @@ protected override Task DoCommandOverride(ICommandContext commandC // Set rest of properties - heightmap.HeightfieldType = heightfieldType; - heightmap.Width = size.X; - heightmap.Length = size.Y; + heightmap.HeightType = heightfieldType; + heightmap.Size = size; } } } diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index 47065430dd..fe08b3b5e8 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -15,13 +15,9 @@ namespace Xenko.Physics public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc { [DataMember(10)] - public Heightmap InitialHeights { get; set; } - - [DataMember(30)] - public HeightfieldTypes HeightfieldType; - - [DataMember(40)] - public Int2 HeightStickSize; + [NotNull] + [Display(Expand = ExpandRule.Always)] + public IInitialHeightData InitialHeights { get; set; } = new HeightDataFromHeightmap(); [DataMember(50)] public Vector2 HeightRange; @@ -45,9 +41,6 @@ public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc public HeightfieldColliderShapeDesc() { - InitialHeights = null; - HeightfieldType = HeightfieldTypes.Float; - HeightStickSize = new Int2(65, 65); HeightRange = new Vector2(-10, 10); HeightScale = new HeightScaleFromHeightRange(); FlipQuadEdges = false; @@ -75,14 +68,17 @@ public bool Match(object obj) var initialHeightsComparison = other.InitialHeights?.Match(InitialHeights) ?? InitialHeights == null; return initialHeightsComparison && - other.HeightfieldType == HeightfieldType && - other.HeightStickSize == HeightStickSize && other.HeightRange == HeightRange && heightScaleComparison && other.FlipQuadEdges == FlipQuadEdges && other.IsRecenteringOffsetted == IsRecenteringOffsetted; } + public static bool IsValidHeightStickSize(Int2 size) + { + return size.X >= HeightfieldColliderShape.MinimumHeightStickWidth && size.Y >= HeightfieldColliderShape.MinimumHeightStickLength; + } + private static void FillHeights(UnmanagedArray unmanagedArray, T value) where T : struct { if (unmanagedArray == null) throw new ArgumentNullException(nameof(unmanagedArray)); @@ -134,20 +130,20 @@ public ColliderShape CreateShape() switch (InitialHeights.HeightType) { case HeightfieldTypes.Float: - { - unmanagedArray = CreateHeights(arrayLength, InitialHeights.Floats); - break; - } + { + unmanagedArray = CreateHeights(arrayLength, InitialHeights.Floats); + break; + } case HeightfieldTypes.Short: - { - unmanagedArray = CreateHeights(arrayLength, InitialHeights.Shorts); - break; - } + { + unmanagedArray = CreateHeights(arrayLength, InitialHeights.Shorts); + break; + } case HeightfieldTypes.Byte: - { - unmanagedArray = CreateHeights(arrayLength, InitialHeights.Bytes); - break; - } + { + unmanagedArray = CreateHeights(arrayLength, InitialHeights.Bytes); + break; + } default: return null; @@ -166,10 +162,10 @@ public ColliderShape CreateShape() HeightRange.Y, FlipQuadEdges ) - { - LocalOffset = LocalOffset + new Vector3(0, offsetToCancelRecenter, 0), - LocalRotation = LocalRotation, - }; + { + LocalOffset = LocalOffset + new Vector3(0, offsetToCancelRecenter, 0), + LocalRotation = LocalRotation, + }; return shape; } diff --git a/sources/engine/Xenko.Physics/Engine/Heightmap.cs b/sources/engine/Xenko.Physics/Engine/Heightmap.cs index 90971da21a..df872c2199 100644 --- a/sources/engine/Xenko.Physics/Engine/Heightmap.cs +++ b/sources/engine/Xenko.Physics/Engine/Heightmap.cs @@ -1,7 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Collections.Generic; using Xenko.Core; +using Xenko.Core.Mathematics; using Xenko.Core.Serialization; using Xenko.Core.Serialization.Contents; using Xenko.Engine.Design; @@ -28,17 +28,14 @@ public class Heightmap [DataMember(40)] [Display(Browsable = false)] - public HeightfieldTypes HeightfieldType; + public HeightfieldTypes HeightType; [DataMember(50)] - public int Width; + public Int2 Size { get; set; } - [DataMember(60)] - public int Length; - - public static Heightmap Create(int width, int length, T[] data) where T : struct + public static Heightmap Create(Int2 size, T[] data) where T : struct { - if (width <= 1 || length <= 1 || data == null) + if (!HeightfieldColliderShapeDesc.IsValidHeightStickSize(size) || data == null) { return null; } @@ -49,9 +46,8 @@ public static Heightmap Create(int width, int length, T[] data) where T : str { return new Heightmap { - HeightfieldType = HeightfieldTypes.Float, - Width = width, - Length = length, + HeightType = HeightfieldTypes.Float, + Size = size, Floats = data as float[], }; } @@ -59,9 +55,8 @@ public static Heightmap Create(int width, int length, T[] data) where T : str { return new Heightmap { - HeightfieldType = HeightfieldTypes.Short, - Width = width, - Length = length, + HeightType = HeightfieldTypes.Short, + Size = size, Shorts = data as short[], }; } @@ -69,9 +64,8 @@ public static Heightmap Create(int width, int length, T[] data) where T : str { return new Heightmap { - HeightfieldType = HeightfieldTypes.Byte, - Width = width, - Length = length, + HeightType = HeightfieldTypes.Byte, + Size = size, Bytes = data as byte[], }; } diff --git a/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs b/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs index 8a88236827..9fd3d26a7b 100644 --- a/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs +++ b/sources/engine/Xenko.Physics/Engine/HeightmapExtensions.cs @@ -12,7 +12,7 @@ public static bool IsValidSize([NotNull] this Heightmap heightmap) { if (heightmap == null) throw new ArgumentNullException(nameof(heightmap)); - return heightmap.Width >= 2 && heightmap.Length >= 2; + return heightmap.Size.X >= 2 && heightmap.Size.Y >= 2; } public static Texture CreateTexture([NotNull] this Heightmap heightmap, GraphicsDevice device) @@ -24,16 +24,16 @@ public static Texture CreateTexture([NotNull] this Heightmap heightmap, Graphics return null; } - switch (heightmap.HeightfieldType) + switch (heightmap.HeightType) { case HeightfieldTypes.Float: - return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R32_Float, heightmap.Floats); + return Texture.New2D(device, heightmap.Size.X, heightmap.Size.Y, PixelFormat.R32_Float, heightmap.Floats); case HeightfieldTypes.Short: - return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R16_SNorm, heightmap.Shorts); + return Texture.New2D(device, heightmap.Size.X, heightmap.Size.Y, PixelFormat.R16_SNorm, heightmap.Shorts); case HeightfieldTypes.Byte: - return Texture.New2D(device, heightmap.Width, heightmap.Length, PixelFormat.R8_UNorm, heightmap.Bytes); + return Texture.New2D(device, heightmap.Size.X, heightmap.Size.Y, PixelFormat.R8_UNorm, heightmap.Bytes); default: return null; diff --git a/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs b/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs index 30093b280d..0e599eb864 100644 --- a/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs +++ b/sources/engine/Xenko.Physics/Shapes/HeightfieldColliderShape.cs @@ -36,6 +36,9 @@ public HeightfieldColliderShape(int heightStickWidth, int heightStickLength, Unm public class HeightfieldColliderShape : ColliderShape { + public static readonly int MinimumHeightStickWidth = 2; + public static readonly int MinimumHeightStickLength = 2; + public HeightfieldColliderShape(int heightStickWidth, int heightStickLength, UnmanagedArray dynamicFieldData, float heightScale, float minHeight, float maxHeight, bool flipQuadEdges) : this(heightStickWidth, heightStickLength, HeightfieldTypes.Short, dynamicFieldData, heightScale, minHeight, maxHeight, flipQuadEdges) { @@ -143,7 +146,7 @@ public override IDebugPrimitive CreateUpdatableDebugPrimitive(GraphicsDevice gra public override void UpdateDebugPrimitive(CommandList commandList, IDebugPrimitive debugPrimitive) { - HeightfieldDebugPrimitive heightfieldDebugPrimitive = debugPrimitive as HeightfieldDebugPrimitive; + var heightfieldDebugPrimitive = debugPrimitive as HeightfieldDebugPrimitive; if (heightfieldDebugPrimitive == null) { @@ -235,16 +238,6 @@ public void Dispose() } } - private enum BulletPhyScalarType - { - PhyFloat, - PhyDouble, - PhyInteger, - PhyShort, - PhyFixedpoint88, - PhyUchar, - } - public class HeightfieldDebugPrimitive : IDebugPrimitive { private static readonly int MaxTileWidth = 64; From 243699f1c640c4dd43bd77b9245c31d1d14aa5f3 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 21 Dec 2019 14:38:35 -0500 Subject: [PATCH 0560/2038] Physics: add collision groups/flags to helper function --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 0da89d02bf..b7f2f387e7 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -104,7 +104,8 @@ public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool /// shapes that will generate a static component for each /// optional offset for each /// optional rotation for each - public static void GenerateStaticComponents(Entity e, List shapes, List offsets = null, List rotations = null) + public static void GenerateStaticComponents(Entity e, List shapes, List offsets = null, List rotations = null, + CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroupFlags collidesWith = CollisionFilterGroupFlags.AllFilter) { for (int i=0; i shapes, List< sc.ColliderShape = shapes[i]; sc.Position = offsets?[i] ?? Vector3.Zero; sc.Rotation = rotations?[i] ?? Quaternion.Identity; + sc.CanCollideWith = collidesWith; + sc.CollisionGroup = group; e.Add(sc); } } From 56f430d5924ca53c74d427945d9d1670a809f2b1 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 21 Dec 2019 17:46:24 -0500 Subject: [PATCH 0561/2038] Physics: mirror simulation extension for BepuSimulation --- .../Xenko.Physics/PhysicsScriptComponentExtensions.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/sources/engine/Xenko.Physics/PhysicsScriptComponentExtensions.cs b/sources/engine/Xenko.Physics/PhysicsScriptComponentExtensions.cs index 4d5d3f47a9..8bbc87802f 100644 --- a/sources/engine/Xenko.Physics/PhysicsScriptComponentExtensions.cs +++ b/sources/engine/Xenko.Physics/PhysicsScriptComponentExtensions.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Xenko.Engine; +using Xenko.Physics.Bepu; namespace Xenko.Physics { @@ -19,5 +20,15 @@ public static Simulation GetSimulation(this ScriptComponent scriptComponent) { return scriptComponent.SceneSystem.SceneInstance.GetProcessor()?.Simulation; } + + /// + /// Gets the curent . + /// + /// The script component to query bepu physics from + /// The simulation object or null if there are no bepu simulation running for the current scene. + public static BepuSimulation GetBepuSimulation(this ScriptComponent scriptComponent) + { + return BepuSimulation.instance; + } } } From 4f210eca0726ce37b7b1af71c1a325a75b550d08 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 21 Dec 2019 18:31:03 -0500 Subject: [PATCH 0562/2038] Physics: add helper functions for RayCast and SweepCast --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 3830094a91..2f39f6bef7 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -424,6 +424,25 @@ public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Nume } } + /// + /// Raycasts and returns the closest hit + /// + /// From. + /// To. + /// The collision group of this raycast + /// The collision group that this raycast can collide with + /// The list with hit results. + public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + Vector3 diff = to - from; + float length = diff.Length(); + float inv = 1.0f / length; + diff.X *= inv; + diff.Y *= inv; + diff.Z *= inv; + return Raycast(from, diff, length, hitGroups); + } + /// /// Raycasts and returns the closest hit /// @@ -443,6 +462,26 @@ public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, Coll return rhch.HitCollidable; } + /// + /// Raycasts penetrating any shape the ray encounters. + /// Filtering by CollisionGroup + /// + /// From. + /// To. + /// The list to fill with results. + /// The collision group of this raycast + /// The collision group that this raycast can collide with + public void RaycastPenetrating(Vector3 from, Vector3 to, List resultsOutput, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + Vector3 diff = to - from; + float length = diff.Length(); + float inv = 1.0f / length; + diff.X *= inv; + diff.Y *= inv; + diff.Z *= inv; + RaycastPenetrating(from, diff, length, resultsOutput, hitGroups); + } + /// /// Raycasts penetrating any shape the ray encounters. /// Filtering by CollisionGroup @@ -613,6 +652,27 @@ public void ShapeTestPenetrating(IConvexShape shape, Vector3 position, Xenko.Cor internalSimulation.Sweep(shape, rp, new BodyVelocity(), 0f, pBufferPool, ref sshh); } + /// + /// Performs a sweep test using a collider shape and returns the closest hit + /// + /// The shape. + /// From. + /// To. + /// The collision group of this shape sweep + /// The collision group that this shape sweep can collide with + /// + /// This kind of shape cannot be used for a ShapeSweep. + public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + Vector3 diff = endpoint - position; + float length = diff.Length(); + float inv = 1.0f / length; + diff.X *= inv; + diff.Y *= inv; + diff.Z *= inv; + return ShapeSweep(shape, position, rotation, diff, length, hitGroups); + } + /// /// Performs a sweep test using a collider shape and returns the closest hit /// @@ -642,6 +702,27 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core return sshh.result; } + /// + /// Performs a sweep test using a collider shape and never stops until "to" + /// + /// The shape. + /// From. + /// To. + /// The list to fill with results. + /// The collision group of this shape sweep + /// The collision group that this shape sweep can collide with + /// This kind of shape cannot be used for a ShapeSweep. + public void ShapeSweepPenetrating(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) + { + Vector3 diff = endpoint - position; + float length = diff.Length(); + float inv = 1.0f / length; + diff.X *= inv; + diff.Y *= inv; + diff.Z *= inv; + ShapeSweepPenetrating(shape, position, rotation, diff, length, output, hitGroups); + } + /// /// Performs a sweep test using a collider shape and never stops until "to" /// From 9d787b4158f9fb15bd1672dbbe2a1b205fbcd99b Mon Sep 17 00:00:00 2001 From: Eideren Date: Sat, 21 Dec 2019 20:55:51 +0100 Subject: [PATCH 0563/2038] Add buffer to set ignore collision pre-NativeObject creation # Conflicts: # sources/engine/Xenko.Physics/Engine/PhysicsComponent.cs --- .../Xenko.Physics/Engine/PhysicsComponent.cs | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Engine/PhysicsComponent.cs b/sources/engine/Xenko.Physics/Engine/PhysicsComponent.cs index 8ac2b5d1f0..eb4a641503 100644 --- a/sources/engine/Xenko.Physics/Engine/PhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Engine/PhysicsComponent.cs @@ -393,6 +393,9 @@ public float CcdSweptSphereRadius } } + + private Dictionary ignoreCollisionBuffer; + /// /// When updating the associated TransformComponent, should we not set rotation? /// @@ -773,6 +776,15 @@ internal void Attach(PhysicsProcessor.AssociatedData data) BoneIndex = -1; OnAttach(); + + if(ignoreCollisionBuffer != null && NativeCollisionObject != null) + { + foreach(var kvp in ignoreCollisionBuffer) + { + IgnoreCollisionWith(kvp.Key, kvp.Value); + } + ignoreCollisionBuffer = null; + } } internal void Detach() @@ -856,6 +868,24 @@ protected virtual void OnUpdateBones() public void IgnoreCollisionWith(PhysicsComponent other, CollisionState state) { var otherNative = other.NativeCollisionObject; + if(NativeCollisionObject == null || other.NativeCollisionObject == null) + { + if(ignoreCollisionBuffer != null || other.ignoreCollisionBuffer == null) + { + if(ignoreCollisionBuffer == null) + ignoreCollisionBuffer = new Dictionary(); + if(ignoreCollisionBuffer.ContainsKey(other)) + ignoreCollisionBuffer[other] = state; + else + ignoreCollisionBuffer.Add(other, state); + } + else + { + other.IgnoreCollisionWith(this, state); + } + return; + } + switch(state) { // Note that we're calling 'SetIgnoreCollisionCheck' on both objects as bullet doesn't @@ -886,7 +916,22 @@ public void IgnoreCollisionWith(PhysicsComponent other, CollisionState state) public bool IsIgnoringCollisionWith(PhysicsComponent other) { - return ! NativeCollisionObject.CheckCollideWith(other.NativeCollisionObject); + if(ignoreCollisionBuffer != null) + { + return ignoreCollisionBuffer.TryGetValue(other, out var state) && state == CollisionState.Ignore; + } + else if(other.ignoreCollisionBuffer != null) + { + return other.IsIgnoringCollisionWith(this); + } + else if(other.NativeCollisionObject == null || NativeCollisionObject == null) + { + return false; + } + else + { + return ! NativeCollisionObject.CheckCollideWith(other.NativeCollisionObject); + } } [DataContract] From f10a8230008db4cc366a9dfeb064bd9dcc65e30d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 21 Dec 2019 21:31:31 -0500 Subject: [PATCH 0564/2038] Physics: fix function that adds (and now removes) all physical objects to simulation --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 14 +++++++------- .../Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index b7f2f387e7..528d492a94 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -176,23 +176,23 @@ public static ICompoundShape MakeCompound(List shapes, List /// - public static void AddAllBodiesToSimulation(Scene rootScene) + public static void SetBodiesInSimulation(Scene rootScene, bool add = true) { foreach (Entity e in rootScene.Entities) - AddAllBodiesToSimulation(e); + SetBodiesInSimulation(e, add); } /// - /// Goes through the entity and children and adds bepu physics objects to the simulation. Only will add if AllowHelperToAdd is true (which is set to true by default) + /// Goes through the entity and children and adds/removes bepu physics objects to the simulation. Only will add/remove if AllowHelperToManage is true (which is set to true by default) /// and if the body isn't added already. /// /// - public static void AddAllBodiesToSimulation(Entity rootEntity) + public static void SetBodiesInSimulation(Entity rootEntity, bool add = true) { - BepuPhysicsComponent pc = rootEntity.Get(); - if (pc?.AllowHelperToAdd ?? false) pc.AddedToScene = true; + foreach (BepuPhysicsComponent pc in rootEntity.GetAll()) + if (pc.AllowHelperToManage) pc.AddedToScene = add; foreach (Entity e in rootEntity.GetChildren()) - AddAllBodiesToSimulation(e); + SetBodiesInSimulation(e, add); } public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 31931d3759..1753d26f0c 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -39,7 +39,7 @@ public int GetHandle() /// Allow BepuHelpers.AddAllBodiesToSimulation to add this? /// [DataMember] - public bool AllowHelperToAdd { get; set; } = true; + public bool AllowHelperToManage { get; set; } = true; [DataMemberIgnore] public virtual bool AddedToScene { get; set; } From ca11d01ac3be9dd143c396fc3888e7203f3705a7 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Sun, 22 Dec 2019 22:21:06 +0100 Subject: [PATCH 0565/2038] [Assets] Compiler: Use executable entry package to read certain user game settings) --- .../PackageBuilder.cs | 3 ++- .../Compiler/AssetCompilerContext.cs | 5 +++++ .../Xenko.Assets/GameSettingsAssetCompiler.cs | 14 ++++++++------ 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/sources/assets/Xenko.Core.Assets.CompilerApp/PackageBuilder.cs b/sources/assets/Xenko.Core.Assets.CompilerApp/PackageBuilder.cs index 1470a5adc5..7b93f2677e 100644 --- a/sources/assets/Xenko.Core.Assets.CompilerApp/PackageBuilder.cs +++ b/sources/assets/Xenko.Core.Assets.CompilerApp/PackageBuilder.cs @@ -113,7 +113,8 @@ private BuildResultCode BuildMaster() { Platform = builderOptions.Platform, CompilationContext = typeof(AssetCompilationContext), - BuildConfiguration = builderOptions.ProjectConfiguration + BuildConfiguration = builderOptions.ProjectConfiguration, + Package = package, }; // Command line properties diff --git a/sources/assets/Xenko.Core.Assets/Compiler/AssetCompilerContext.cs b/sources/assets/Xenko.Core.Assets/Compiler/AssetCompilerContext.cs index f370201c4f..a6eb0899f0 100644 --- a/sources/assets/Xenko.Core.Assets/Compiler/AssetCompilerContext.cs +++ b/sources/assets/Xenko.Core.Assets/Compiler/AssetCompilerContext.cs @@ -21,6 +21,11 @@ public class AssetCompilerContext : CompilerContext /// public string BuildConfiguration { get; set; } + /// + /// Gets or sets the entry package this build was called upon. + /// + public Package Package { get; set; } + /// /// Gets or sets the target platform for compiler is being used for. /// diff --git a/sources/engine/Xenko.Assets/GameSettingsAssetCompiler.cs b/sources/engine/Xenko.Assets/GameSettingsAssetCompiler.cs index 1426740c6f..a5f74872de 100644 --- a/sources/engine/Xenko.Assets/GameSettingsAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/GameSettingsAssetCompiler.cs @@ -30,7 +30,7 @@ protected override void Prepare(AssetCompilerContext context, AssetItem assetIte var asset = (GameSettingsAsset)assetItem.Asset; // TODO: We should ignore game settings stored in dependencies result.BuildSteps = new AssetBuildStep(assetItem); - result.BuildSteps.Add(new GameSettingsCompileCommand(targetUrlInStorage, assetItem.Package, context.Platform, context.GetCompilationMode(), asset)); + result.BuildSteps.Add(new GameSettingsCompileCommand(targetUrlInStorage, assetItem.Package, context.Package, context.Platform, context.GetCompilationMode(), asset)); } public override IEnumerable GetRuntimeTypes(AssetItem assetItem) @@ -45,10 +45,12 @@ private class GameSettingsCompileCommand : AssetCommand private readonly PlatformType platform; private readonly CompilationMode compilationMode; private readonly Package package; - public GameSettingsCompileCommand(string url, Package package, PlatformType platform, CompilationMode compilationMode, GameSettingsAsset asset) + private readonly Package entryPackage; + public GameSettingsCompileCommand(string url, Package package, Package entryPackage, PlatformType platform, CompilationMode compilationMode, GameSettingsAsset asset) : base(url, asset, package) { this.package = package; + this.entryPackage = entryPackage ?? package; this.platform = platform; this.compilationMode = compilationMode; } @@ -59,8 +61,8 @@ protected override void ComputeParameterHash(BinarySerializationWriter writer) // Hash used parameters from package writer.Write(package.Meta.Name); - writer.Write(package.UserSettings.GetValue(GameUserSettings.Effect.EffectCompilation)); - writer.Write(package.UserSettings.GetValue(GameUserSettings.Effect.RecordUsedEffects)); + writer.Write(entryPackage.UserSettings.GetValue(GameUserSettings.Effect.EffectCompilation)); + writer.Write(entryPackage.UserSettings.GetValue(GameUserSettings.Effect.RecordUsedEffects)); writer.Write(compilationMode); // Hash platform @@ -77,8 +79,8 @@ protected override Task DoCommandOverride(ICommandContext commandC SplashScreenUrl = Parameters.SplashScreenTexture != null && (compilationMode == CompilationMode.Release || compilationMode == CompilationMode.AppStore) ? AttachedReferenceManager.GetUrl(Parameters.SplashScreenTexture) : null, SplashScreenColor = Parameters.SplashScreenColor, DoubleViewSplashScreen = Parameters.DoubleViewSplashScreen, - EffectCompilation = package.UserSettings.GetValue(GameUserSettings.Effect.EffectCompilation), - RecordUsedEffects = package.UserSettings.GetValue(GameUserSettings.Effect.RecordUsedEffects), + EffectCompilation = entryPackage.UserSettings.GetValue(GameUserSettings.Effect.EffectCompilation), + RecordUsedEffects = entryPackage.UserSettings.GetValue(GameUserSettings.Effect.RecordUsedEffects), Configurations = new PlatformConfigurations(), CompilationMode = compilationMode }; From 62fa90fc722b98ac10315fbae93634426e60b8c9 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 22 Dec 2019 17:06:21 -0500 Subject: [PATCH 0566/2038] Physics: fix rotation setting bug --- sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 2 +- .../engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 69079131fb..931b4294aa 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -426,7 +426,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation bodyDescription.Pose.Orientation.X = value.X; bodyDescription.Pose.Orientation.Y = value.Y; bodyDescription.Pose.Orientation.Z = value.Z; - bodyDescription.Pose.Orientation.Z = value.W; + bodyDescription.Pose.Orientation.W = value.W; if (InternalBody.Exists) { diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index 164fc429c2..a1674b6951 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -65,7 +65,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation staticDescription.Pose.Orientation.X = value.X; staticDescription.Pose.Orientation.Y = value.Y; staticDescription.Pose.Orientation.Z = value.Z; - staticDescription.Pose.Orientation.Z = value.W; + staticDescription.Pose.Orientation.W = value.W; if (InternalStatic.Exists) { From cff22970b04a82ed94e29cd6fd4b11218bd5e69a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 22 Dec 2019 18:09:40 -0500 Subject: [PATCH 0567/2038] Physics: fix raycasts and sweepcasts --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 2f39f6bef7..6fd1bdffa7 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -351,7 +351,7 @@ internal void RemoveRigidBody(BepuRigidbodyComponent rigidBody) struct RayHitClosestHandler : IRayHitHandler { public CollisionFilterGroupFlags findGroups; - public float T, startLength; + public float furthestHitSoFar, startLength; public BepuHitResult HitCollidable; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowTest(CollidableReference collidable) @@ -368,10 +368,10 @@ public bool AllowTest(CollidableReference collidable, int childIndex) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Numerics.Vector3 normal, CollidableReference collidable, int childIndex) { - if (t < T) + if (t < furthestHitSoFar) { //Cache the earliest impact. - T = t; + furthestHitSoFar = t; HitCollidable.HitFraction = t / startLength; HitCollidable.Normal.X = normal.X; HitCollidable.Normal.Y = normal.Y; @@ -456,7 +456,8 @@ public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, Coll RayHitClosestHandler rhch = new RayHitClosestHandler() { findGroups = hitGroups, - startLength = length + startLength = length, + furthestHitSoFar = float.MaxValue }; internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); return rhch.HitCollidable; @@ -506,7 +507,7 @@ struct SweepTestFirst : ISweepHitHandler { public CollisionFilterGroupFlags hitGroups; public BepuHitResult result; - public float T, startLength; + public float furthestHitSoFar, startLength; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowTest(CollidableReference collidable) @@ -523,9 +524,9 @@ public bool AllowTest(CollidableReference collidable, int child) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLocation, in System.Numerics.Vector3 hitNormal, CollidableReference collidable) { - if (t < T) + if (t < furthestHitSoFar) { - T = t; + furthestHitSoFar = t; result.Succeeded = true; result.Collider = getFromReference(collidable); result.Normal.X = hitNormal.X; @@ -549,7 +550,7 @@ public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) result.Succeeded = true; result.Collider = getFromReference(collidable); maximumT = 0; - T = 0; + furthestHitSoFar = 0; } } @@ -611,6 +612,7 @@ public BepuPhysicsComponent ShapeTest(IConvexShape shape, Vector3 position, Xenk { hitGroups = hitGroups, startLength = 0f, + furthestHitSoFar = float.MaxValue }; RigidPose rp = new RigidPose(); rp.Position.X = position.X; @@ -689,6 +691,7 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core { hitGroups = hitGroups, startLength = length, + furthestHitSoFar = float.MaxValue }; RigidPose rp = new RigidPose(); rp.Position.X = position.X; From 9aa2f543a8e147850df1e249796281a4fc0ba8d3 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 22 Dec 2019 22:01:17 -0500 Subject: [PATCH 0568/2038] Physics: cleanup, continuous collision and performance improvements --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 5 +++ .../Bepu/BepuRigidbodyComponent.cs | 31 +++++++++---------- 2 files changed, 19 insertions(+), 17 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 528d492a94..ac504d1c81 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text; using BepuPhysics.Collidables; using BepuPhysics.Constraints; @@ -309,21 +310,25 @@ public static unsafe bool GenerateMeshShape(List positions, List i return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe System.Numerics.Vector3 ToBepu(Xenko.Core.Mathematics.Vector3 v) { return *((System.Numerics.Vector3*)(void*)&v); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe Xenko.Core.Mathematics.Vector3 ToXenko(System.Numerics.Vector3 v) { return *((Xenko.Core.Mathematics.Vector3*)(void*)&v); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe Xenko.Core.Mathematics.Quaternion ToXenko(BepuUtilities.Quaternion q) { return *((Xenko.Core.Mathematics.Quaternion*)(void*)&q); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe BepuUtilities.Quaternion ToBepu(Xenko.Core.Mathematics.Quaternion q) { return *((BepuUtilities.Quaternion*)(void*)&q); diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 931b4294aa..9cfc06e206 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -54,6 +54,9 @@ public BodyReference InternalBody /// public bool IsActive => InternalBody.Awake; + /// + /// Use continuous collision detection? Set greater than 0 to use, 0 or less to disable + /// [DataMember(67)] public float CcdMotionThreshold { @@ -64,12 +67,14 @@ public float CcdMotionThreshold set { bodyDescription.Collidable.Continuity.SweepConvergenceThreshold = value; + bodyDescription.Collidable.Continuity.Mode = value > 0 ? ContinuousDetectionMode.Continuous : ContinuousDetectionMode.Discrete; + bodyDescription.Collidable.Continuity.MinimumSweepTimestep = value > 0 ? 1e-3f : 0f; if (InternalBody.Exists) - InternalBody.Collidable.Continuity.SweepConvergenceThreshold = value; + InternalBody.Collidable.Continuity = bodyDescription.Collidable.Continuity; } } - + /// /// Gets or sets if this element will store collisions in CurrentPhysicalContacts. Uses less CPU than ProcessCollisions /// @@ -161,17 +166,9 @@ public void Activate() } /// - /// Gets or sets the rolling friction of this element + /// How slow does this need to be to sleep? Set less than 0 to never sleep /// - /// - /// true, false - /// - /// - /// The rolling friction - /// - [DataMember(66)] - public float RollingFriction => 0f; - + [DataMember] public float SleepThreshold { get @@ -249,6 +246,9 @@ public IConvexShape ColliderShape } } + /// + /// If you made a modification to the existing ColliderShape (like changed its radius), try reloading it via this function. + /// public void ReloadColliderShape() { if (_myshape == null || AddedToScene == false) return; @@ -368,8 +368,7 @@ public override bool AddedToScene /// The impulse. public void ApplyImpulse(Vector3 impulse) { - System.Numerics.Vector3 i = new System.Numerics.Vector3(impulse.X, impulse.Y, impulse.Z); - InternalBody.ApplyLinearImpulse(i); + InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); } /// @@ -379,9 +378,7 @@ public void ApplyImpulse(Vector3 impulse) /// The local offset. public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) { - System.Numerics.Vector3 i = new System.Numerics.Vector3(impulse.X, impulse.Y, impulse.Z); - System.Numerics.Vector3 o = new System.Numerics.Vector3(localOffset.X, localOffset.Y, localOffset.Z); - InternalBody.ApplyImpulse(i, o); + InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); } /// From 0a18592291c49ca49594f41f1acffd8678fdd289 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 23 Dec 2019 09:21:29 -0500 Subject: [PATCH 0569/2038] Physics: helper functions to clear simulation of bodies --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 12 ++++++++++ .../Xenko.Physics/Bepu/BepuSimulation.cs | 22 ++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index ac504d1c81..e7bd7fbb89 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -196,6 +196,18 @@ public static void SetBodiesInSimulation(Entity rootEntity, bool add = true) SetBodiesInSimulation(e, add); } + /// + /// Shortcut to clearing the simulation of all bodies. Optionally clears all the buffers too (e.g. mesh colliders), which is enabled by default + /// + public static void ClearSimulation(bool clearBuffers = true) + { + BepuSimulation.instance.Clear(clearBuffers); + } + + /// + /// Generate a mesh collider from a given mesh. The mesh must have a readable buffer behind it to generate veriticies from + /// + /// Returns false if no mesh could be made public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) { List positions; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 6fd1bdffa7..aefadbcfe9 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -62,6 +62,26 @@ private set internal List AllRigidbodies = new List(); + /// + /// Clears out the whole simulation of bodies, optionally clears all related buffers (like meshes) too + /// + /// Clear out all buffers, like mesh shapes? Defaults to true + public void Clear(bool clearBuffers = true) + { + internalSimulation.Clear(); + + if (clearBuffers) pBufferPool.Clear(); + + for (int i = 0; i < AllRigidbodies.Count; i++) + AllRigidbodies[i].AddedHandle = -1; + foreach (BepuStaticColliderComponent sc in StaticMappings.Values) + sc.AddedHandle = -1; + + StaticMappings.Clear(); + RigidMappings.Clear(); + AllRigidbodies.Clear(); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static BepuRigidbodyComponent getRigidFromIndex(int index) { @@ -297,7 +317,7 @@ internal BepuSimulation(PhysicsSettings configuration) /// public void Dispose() { - pBufferPool.Clear(); + Clear(true); } /// From 4d82c216ee16193d4b8210446766da36238e540f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 23 Dec 2019 12:02:44 -0500 Subject: [PATCH 0570/2038] Physics: fix contact testing (skip "empty" values etc.) --- .../Bepu/BepuRigidbodyComponent.cs | 37 +++++++++++++++---- .../Xenko.Physics/Bepu/BepuSimulation.cs | 3 ++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 9cfc06e206..2de0b67891 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -94,16 +94,32 @@ public bool CollectCollisions } set { - if (value && processingPhysicalContacts == null) + if (_collectCollisions == value) return; + + if (value) + { + if (processingPhysicalContacts == null) + { + processingPhysicalContacts = new List[2]; + processingPhysicalContacts[0] = new List(); + processingPhysicalContacts[1] = new List(); + _currentContacts = new List(); + } + } + else if (processingPhysicalContacts != null) { - processingPhysicalContacts = new List[2]; - processingPhysicalContacts[0] = new List(); - processingPhysicalContacts[1] = new List(); + _currentContacts.Clear(); + _currentContacts = null; + processingPhysicalContacts[0].Clear(); + processingPhysicalContacts[1].Clear(); + processingPhysicalContacts = null; } + _collectCollisions = value; } } private bool _collectCollisions = false; + private List _currentContacts; /// /// If we are using ProcessCollisionSlim, this list will maintain all current collisions @@ -113,9 +129,16 @@ public List CurrentContacts { get { - if (processingPhysicalContacts == null) return null; + if (_currentContacts == null) return null; + + _currentContacts.Clear(); + + List getFrom = processingPhysicalContacts[processingPhysicalContactsIndex]; + + for (int i = 0; i < getFrom.Count; i++) + _currentContacts.Add(getFrom[i]); - return new List(processingPhysicalContacts[processingPhysicalContactsIndex]); + return _currentContacts; } } @@ -123,8 +146,8 @@ internal void swapProcessingContactsList() { if (processingPhysicalContacts == null || IsActive == false) return; - processingPhysicalContacts[processingPhysicalContactsIndex].Clear(); processingPhysicalContactsIndex ^= 1; + processingPhysicalContacts[processingPhysicalContactsIndex ^ 1].Clear(); } internal List[] processingPhysicalContacts; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index aefadbcfe9..a688c9e5a6 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -165,6 +165,9 @@ public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int chi public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponent B, TManifold manifold) where TManifold : struct, IContactManifold { + // sanity checking + if (A == null || B == null || manifold.Count == 0) return; + BepuRigidbodyComponent ar = (A as BepuRigidbodyComponent); BepuRigidbodyComponent br = (B as BepuRigidbodyComponent); bool Acollect = (ar?.CollectCollisions ?? false); From fb4699286868a0c6239cf7f0c9c29ad5d4837746 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 23 Dec 2019 12:04:05 -0500 Subject: [PATCH 0571/2038] Physics: inline all the things! --- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index a688c9e5a6..0cfacb49cb 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -163,6 +163,7 @@ public bool AllowContactGeneration(int workerIndex, CollidablePair pair, int chi return CanCollide(pair.A, pair.B); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponent B, TManifold manifold) where TManifold : struct, IContactManifold { // sanity checking From 7787887df8f7d7109a1374dab7702edb93242f20 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 23 Dec 2019 14:24:50 -0500 Subject: [PATCH 0572/2038] Physics: add a maximum contact collection count option --- .../Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 10 ++++++++-- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 8 ++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 2de0b67891..38752f6c8d 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -74,6 +74,12 @@ public float CcdMotionThreshold InternalBody.Collidable.Continuity = bodyDescription.Collidable.Continuity; } } + + /// + /// If we are collecting collisions, how many to store before we stop storing them? Defaults to 32. Prevents crazy counts when objects are heavily overlapping. + /// + [DataMember] + public int CollectCollisionMaximumCount = 32; /// /// Gets or sets if this element will store collisions in CurrentPhysicalContacts. Uses less CPU than ProcessCollisions @@ -133,7 +139,7 @@ public List CurrentContacts _currentContacts.Clear(); - List getFrom = processingPhysicalContacts[processingPhysicalContactsIndex]; + List getFrom = processingPhysicalContacts[processingPhysicalContactsIndex^1]; for (int i = 0; i < getFrom.Count; i++) _currentContacts.Add(getFrom[i]); @@ -147,7 +153,7 @@ internal void swapProcessingContactsList() if (processingPhysicalContacts == null || IsActive == false) return; processingPhysicalContactsIndex ^= 1; - processingPhysicalContacts[processingPhysicalContactsIndex ^ 1].Clear(); + processingPhysicalContacts[processingPhysicalContactsIndex].Clear(); } internal List[] processingPhysicalContacts; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 0cfacb49cb..ecd63621b3 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -171,8 +171,8 @@ public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponen BepuRigidbodyComponent ar = (A as BepuRigidbodyComponent); BepuRigidbodyComponent br = (B as BepuRigidbodyComponent); - bool Acollect = (ar?.CollectCollisions ?? false); - bool Bcollect = (br?.CollectCollisions ?? false); + bool Acollect = ar == null ? false : ar.CollectCollisions && ar.CollectCollisionMaximumCount > ar.processingPhysicalContacts[ar.processingPhysicalContactsIndex].Count; + bool Bcollect = br == null ? false : br.CollectCollisions && br.CollectCollisionMaximumCount > br.processingPhysicalContacts[br.processingPhysicalContactsIndex].Count; // do we want to store this collision? if (Acollect || Bcollect) { @@ -183,8 +183,8 @@ public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponen Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), Position = B.Position - BepuHelpers.ToXenko(manifold.SimpleGetOffset()) }; - if (Acollect) ar.processingPhysicalContacts[ar.processingPhysicalContactsIndex ^ 1].Add(bc); - if (Bcollect) br.processingPhysicalContacts[br.processingPhysicalContactsIndex ^ 1].Add(bc); + if (Acollect) ar.processingPhysicalContacts[ar.processingPhysicalContactsIndex].Add(bc); + if (Bcollect) br.processingPhysicalContacts[br.processingPhysicalContactsIndex].Add(bc); } } From ece6f70d654b9b1ca90d516e25591e7d17d05984 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 23 Dec 2019 15:11:35 -0500 Subject: [PATCH 0573/2038] Physics: more options for static component creation helper --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index e7bd7fbb89..e04f756a64 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -106,7 +106,8 @@ public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool /// optional offset for each /// optional rotation for each public static void GenerateStaticComponents(Entity e, List shapes, List offsets = null, List rotations = null, - CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroupFlags collidesWith = CollisionFilterGroupFlags.AllFilter) + CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroupFlags collidesWith = CollisionFilterGroupFlags.AllFilter, + float FrictionCoefficient = 0.5f, float MaximumRecoverableVelocity = 3f, SpringSettings? springSettings = null) { for (int i=0; i shapes, List< sc.Rotation = rotations?[i] ?? Quaternion.Identity; sc.CanCollideWith = collidesWith; sc.CollisionGroup = group; + sc.FrictionCoefficient = FrictionCoefficient; + sc.MaximumRecoveryVelocity = MaximumRecoverableVelocity; + if (springSettings.HasValue) sc.SpringSettings = springSettings.Value; e.Add(sc); } } From 381eb875136466e4a996bf260b9969b73b27852d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 24 Dec 2019 14:14:14 -0500 Subject: [PATCH 0574/2038] Physics: multithreading fixes, sanity checking and better automatic body management --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 33 +++- .../Bepu/BepuPhysicsComponent.cs | 4 +- .../Bepu/BepuRigidbodyComponent.cs | 31 ++-- .../Xenko.Physics/Bepu/BepuSimulation.cs | 149 +++++++++++++----- .../Bepu/BepuStaticColliderComponent.cs | 13 +- sources/engine/Xenko.Physics/PhysicsSystem.cs | 63 ++++---- 6 files changed, 201 insertions(+), 92 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index e04f756a64..6b6a9eb9dd 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -58,6 +58,37 @@ private static Vector3 getBounds(Entity e) return biggest * e.Transform.WorldScale(); } + /// + /// Is this an OK shape? Checks for 0 or negative sizes, or compounds with no children etc... + /// + /// Shape to check + /// true is this shape is sane, false if it has problems + public static bool SanityCheckShape(IShape shape) + { + if (shape is Box box) + return box.HalfHeight > 0f && box.HalfLength > 0f && box.HalfWidth > 0f; + + if (shape is Sphere sphere) + return sphere.Radius > 0f; + + if (shape is Cylinder cylinder) + return cylinder.Radius > 0f && cylinder.HalfLength > 0f; + + if (shape is Capsule capsule) + return capsule.HalfLength > 0f && capsule.Radius > 0f; + + if (shape is Triangle triangle) + return triangle.A != triangle.B && triangle.A != triangle.C && triangle.B != triangle.C; + + if (shape is ICompoundShape compound) + return compound.ChildCount > 0; + + if (shape is Mesh mesh) + return mesh.ChildCount > 0; + + return shape != null; + } + public static IShape OffsetSingleShape(IConvexShape shape, Vector3? offset = null, Quaternion? rotation = null) { if (offset.HasValue == false && rotation.HasValue == false) return shape; @@ -195,7 +226,7 @@ public static void SetBodiesInSimulation(Scene rootScene, bool add = true) public static void SetBodiesInSimulation(Entity rootEntity, bool add = true) { foreach (BepuPhysicsComponent pc in rootEntity.GetAll()) - if (pc.AllowHelperToManage) pc.AddedToScene = add; + if (pc.AutomaticAdd) pc.AddedToScene = add; foreach (Entity e in rootEntity.GetChildren()) SetBodiesInSimulation(e, add); } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 1753d26f0c..f7652b334d 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -36,10 +36,10 @@ public int GetHandle() } /// - /// Allow BepuHelpers.AddAllBodiesToSimulation to add this? + /// Allow the physics system to automatically add, based on changes to the entity in the scene? /// [DataMember] - public bool AllowHelperToManage { get; set; } = true; + public bool AutomaticAdd { get; set; } = true; [DataMemberIgnore] public virtual bool AddedToScene { get; set; } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 38752f6c8d..77759aa3ee 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -257,7 +257,7 @@ private void UpdateInertia() } } - private IConvexShape _myshape; + private IConvexShape _myshape = null; public IConvexShape ColliderShape { @@ -369,24 +369,21 @@ public override bool AddedToScene { if (AddedToScene == value) return; + if (ColliderShape == null) + throw new InvalidOperationException(Entity.Name + " has no ColliderShape, can't be added!"); + + if (BepuHelpers.SanityCheckShape(ColliderShape) == false) + throw new InvalidOperationException(Entity.Name + " has a broken ColliderShape! Check sizes and/or children count."); + if (value) { Mass = mass; RigidBodyType = type; - BepuSimulation.instance.AddRigidBody(this, (CollisionFilterGroupFlags)CollisionGroup, CanCollideWith); - SleepThreshold = bodyDescription.Activity.SleepThreshold; - Position = Entity.Transform.WorldPosition(); - Rotation = Entity.Transform.WorldRotation(); + BepuSimulation.instance.ToBeAdded.Enqueue(this); } else { - if (processingPhysicalContacts != null) - { - processingPhysicalContacts[0].Clear(); - processingPhysicalContacts[1].Clear(); - } - - BepuSimulation.instance.RemoveRigidBody(this); + BepuSimulation.instance.ToBeRemoved.Enqueue(this); } } } @@ -397,7 +394,8 @@ public override bool AddedToScene /// The impulse. public void ApplyImpulse(Vector3 impulse) { - InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); + if (InternalBody.Exists) + InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); } /// @@ -407,7 +405,8 @@ public void ApplyImpulse(Vector3 impulse) /// The local offset. public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) { - InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); + if (InternalBody.Exists) + InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); } /// @@ -416,8 +415,8 @@ public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) /// The torque. public void ApplyTorqueImpulse(Vector3 torque) { - System.Numerics.Vector3 i = new System.Numerics.Vector3(torque.X, torque.Y, torque.Z); - InternalBody.ApplyAngularImpulse(i); + if (InternalBody.Exists) + InternalBody.ApplyAngularImpulse(BepuHelpers.ToBepu(torque)); } [DataMemberIgnore] diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index ecd63621b3..d1ac837d2b 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; @@ -14,10 +15,13 @@ using BepuPhysics.Trees; using BepuUtilities; using BepuUtilities.Memory; +using Xenko.Core; using Xenko.Core.Collections; using Xenko.Core.Diagnostics; using Xenko.Core.Mathematics; using Xenko.Engine; +using Xenko.Engine.Design; +using Xenko.Games; using Xenko.Physics.Engine; using Xenko.Rendering; @@ -30,6 +34,8 @@ public class BepuSimulation : IDisposable public BepuPhysics.Simulation internalSimulation; + internal ConcurrentQueue ToBeAdded = new ConcurrentQueue(), ToBeRemoved = new ConcurrentQueue(); + private static BepuSimulation _instance; public static BepuSimulation instance { @@ -46,6 +52,7 @@ private set private PoseIntegratorCallbacks poseCallbacks; internal BufferPool pBufferPool; + internal int clearRequested; private BepuSimpleThreadDispatcher threadDispatcher = new BepuSimpleThreadDispatcher(Environment.ProcessorCount); #if DEBUG @@ -66,20 +73,30 @@ private set /// Clears out the whole simulation of bodies, optionally clears all related buffers (like meshes) too /// /// Clear out all buffers, like mesh shapes? Defaults to true - public void Clear(bool clearBuffers = true) + /// Clear everything right now. Might cause crashes if simulation is happening at the same time! + public void Clear(bool clearBuffers = true, bool forceRightNow = false) { - internalSimulation.Clear(); + if (forceRightNow) + { + clearRequested = 0; + + internalSimulation.Clear(); - if (clearBuffers) pBufferPool.Clear(); + if (clearBuffers) pBufferPool.Clear(); - for (int i = 0; i < AllRigidbodies.Count; i++) - AllRigidbodies[i].AddedHandle = -1; - foreach (BepuStaticColliderComponent sc in StaticMappings.Values) - sc.AddedHandle = -1; + for (int i = 0; i < AllRigidbodies.Count; i++) + AllRigidbodies[i].AddedHandle = -1; + foreach (BepuStaticColliderComponent sc in StaticMappings.Values) + sc.AddedHandle = -1; - StaticMappings.Clear(); - RigidMappings.Clear(); - AllRigidbodies.Clear(); + StaticMappings.Clear(); + RigidMappings.Clear(); + AllRigidbodies.Clear(); + + return; + } + + clearRequested = clearBuffers ? 2 : 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -307,6 +324,11 @@ public void IntegrateVelocity(int bodyIndex, in RigidPose pose, in BodyInertia l /// SoftBody processing is not yet available internal BepuSimulation(PhysicsSettings configuration) { + Game GameService = ServiceRegistry.instance.GetService() as Game; + GameService.SceneSystem.SceneInstance.EntityAdded += EntityAdded; + GameService.SceneSystem.SceneInstance.EntityRemoved += EntityRemoved; + GameService.SceneSystem.SceneInstance.ComponentChanged += ComponentChanged; + MaxSubSteps = configuration.MaxSubSteps; FixedTimeStep = configuration.FixedTimeStep; @@ -316,12 +338,33 @@ internal BepuSimulation(PhysicsSettings configuration) instance = this; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EntityAdded(object sender, Entity e) + { + foreach (BepuPhysicsComponent bpc in e.GetAll()) + if (bpc.AutomaticAdd) bpc.AddedToScene = true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void EntityRemoved(object sender, Entity e) + { + foreach (BepuPhysicsComponent bpc in e.GetAll()) + bpc.AddedToScene = false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void ComponentChanged(object sender, EntityComponentEventArgs e) + { + if (e.PreviousComponent is BepuPhysicsComponent rem) rem.AddedToScene = false; + if (e.NewComponent is BepuPhysicsComponent add && add.AutomaticAdd) add.AddedToScene = true; + } + /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// public void Dispose() { - Clear(true); + Clear(true, true); } /// @@ -335,41 +378,63 @@ public void DisposeMesh(BepuPhysics.Collidables.Mesh m) public RenderGroup ColliderShapesRenderGroup { get; set; } = RenderGroup.Group0; - internal void AddCollider(BepuStaticColliderComponent component, CollisionFilterGroupFlags group, CollisionFilterGroupFlags mask) + internal void ProcessAdds() { - if (component.AddedHandle > -1) return; // already added - component.staticDescription.Collidable = component.ColliderShape.GenerateDescription(internalSimulation); - component.AddedHandle = internalSimulation.Statics.Add(component.staticDescription); - StaticMappings[component.AddedHandle] = component; - } - - internal void RemoveCollider(BepuStaticColliderComponent component) - { - int addedIndex = component.AddedHandle; - if (addedIndex == -1) return; // already removed - internalSimulation.Statics.Remove(addedIndex); - component.AddedHandle = -1; - StaticMappings.Remove(addedIndex); - } - - internal void AddRigidBody(BepuRigidbodyComponent rigidBody, CollisionFilterGroupFlags group, CollisionFilterGroupFlags mask) - { - if (rigidBody.AddedHandle > -1) return; // already added - rigidBody.ColliderShape.ComputeInertia(rigidBody.Mass, out rigidBody.bodyDescription.LocalInertia); - rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); - rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); - RigidMappings[rigidBody.AddedHandle] = rigidBody; - AllRigidbodies.Add(rigidBody); + while (ToBeAdded.Count > 0) + { + if (ToBeAdded.TryDequeue(out var component)) + { + if (component.AddedHandle > -1) continue; // already added + if (component is BepuStaticColliderComponent scc) + { + scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation); + scc.AddedHandle = internalSimulation.Statics.Add(scc.staticDescription); + StaticMappings[scc.AddedHandle] = scc; + } + else if (component is BepuRigidbodyComponent rigidBody) + { + rigidBody.ColliderShape.ComputeInertia(rigidBody.Mass, out rigidBody.bodyDescription.LocalInertia); + rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + AllRigidbodies.Add(rigidBody); + rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); + RigidMappings[rigidBody.AddedHandle] = rigidBody; + rigidBody.SleepThreshold = rigidBody.bodyDescription.Activity.SleepThreshold; + } + component.Position = component.Entity.Transform.WorldPosition(); + component.Rotation = component.Entity.Transform.WorldRotation(); + } + } } - internal void RemoveRigidBody(BepuRigidbodyComponent rigidBody) + internal void ProcessRemovals() { - int addedIndex = rigidBody.AddedHandle; - if (addedIndex == -1) return; // already removed - internalSimulation.Bodies.Remove(addedIndex); - rigidBody.AddedHandle = -1; - RigidMappings.Remove(rigidBody.AddedHandle); - AllRigidbodies.Remove(rigidBody); + while (ToBeRemoved.Count > 0) + { + if (ToBeRemoved.TryDequeue(out var component)) + { + int addedIndex = component.AddedHandle; + if (addedIndex == -1) continue; // already removed + if (component is BepuStaticColliderComponent scc) + { + scc.AddedHandle = -1; + internalSimulation.Statics.Remove(addedIndex); + StaticMappings.Remove(addedIndex); + } + else if (component is BepuRigidbodyComponent rigidBody) + { + rigidBody.AddedHandle = -1; + internalSimulation.Bodies.Remove(addedIndex); + RigidMappings.Remove(addedIndex); + AllRigidbodies.Remove(rigidBody); + + if (rigidBody.processingPhysicalContacts != null) + { + rigidBody.processingPhysicalContacts[0].Clear(); + rigidBody.processingPhysicalContacts[1].Clear(); + } + } + } + } } struct RayHitClosestHandler : IRayHitHandler diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index a1674b6951..1b7c2fca3d 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -1,6 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; using BepuPhysics; using BepuPhysics.Collidables; using Xenko.Core; @@ -89,15 +90,19 @@ public override bool AddedToScene { if (AddedToScene == value) return; + if (ColliderShape == null) + throw new InvalidOperationException(Entity.Name + " has no ColliderShape, can't be added!"); + + if (BepuHelpers.SanityCheckShape(ColliderShape) == false) + throw new InvalidOperationException(Entity.Name + " has a broken ColliderShape! Check sizes and/or children count."); + if (value) { - BepuSimulation.instance.AddCollider(this, (CollisionFilterGroupFlags)CollisionGroup, CanCollideWith); - Position = Entity.Transform.WorldPosition(); - Rotation = Entity.Transform.WorldRotation(); + BepuSimulation.instance.ToBeAdded.Enqueue(this); } else { - BepuSimulation.instance.RemoveCollider(this); + BepuSimulation.instance.ToBeRemoved.Enqueue(this); } } } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index 6fcb215f68..12f7f351d7 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -126,44 +126,55 @@ private void RunPhysicsSimulation(float time) //first process any needed cleanup physicsScene.Processor.UpdateRemovals(); - //read skinned meshes bone positions and write them to the physics engine - physicsScene.Processor.UpdateBones(); + // after we took care of cleanup, are we disabled? + if (Simulation.DisableSimulation == false) + { + //read skinned meshes bone positions and write them to the physics engine + physicsScene.Processor.UpdateBones(); - //simulate physics - physicsScene.Simulation.Simulate(time); + //simulate physics + physicsScene.Simulation.Simulate(time); - //update character bound entity's transforms from physics engine simulation - physicsScene.Processor.UpdateCharacters(); + //update character bound entity's transforms from physics engine simulation + physicsScene.Processor.UpdateCharacters(); - //Perform clean ups before test contacts in this frame - physicsScene.Simulation.BeginContactTesting(); + //Perform clean ups before test contacts in this frame + physicsScene.Simulation.BeginContactTesting(); - //handle frame contacts - physicsScene.Processor.UpdateContacts(); + //handle frame contacts + physicsScene.Processor.UpdateContacts(); - //This is the heavy contact logic - physicsScene.Simulation.EndContactTesting(); + //This is the heavy contact logic + physicsScene.Simulation.EndContactTesting(); - //send contact events - physicsScene.Simulation.SendEvents(); + //send contact events + physicsScene.Simulation.SendEvents(); + } } if (physicsScene.BepuSimulation != null) { - physicsScene.BepuSimulation.Simulate(time); + // remove all bodies set to be removed + physicsScene.BepuSimulation.ProcessRemovals(); + + // did we request a clear? + int clearMode = physicsScene.BepuSimulation.clearRequested; + if (clearMode > 0) physicsScene.BepuSimulation.Clear(clearMode == 2, true); - // update all rigidbodies - for (int j=0; j Date: Sun, 29 Dec 2019 22:33:58 -0500 Subject: [PATCH 0575/2038] Vulkan: minor synchronization adjustment to prevent an extremely rare crash --- sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs index 01847fc9b8..4317f026b9 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs @@ -184,16 +184,16 @@ public unsafe void Recreate(IntPtr dataPointer) CommandBufferCount = 1, Level = CommandBufferLevel.Primary }; + var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo, Flags = CommandBufferUsageFlags.OneTimeSubmit }; + CommandBuffer commandBuffer; using (GraphicsDevice.QueueLock.ReadLock()) { GraphicsDevice.NativeDevice.AllocateCommandBuffers(ref commandBufferAllocateInfo, &commandBuffer); + commandBuffer.Begin(ref beginInfo); } - var beginInfo = new CommandBufferBeginInfo { StructureType = StructureType.CommandBufferBeginInfo, Flags = CommandBufferUsageFlags.OneTimeSubmit }; - commandBuffer.Begin(ref beginInfo); - // Copy to upload buffer if (dataPointer != IntPtr.Zero) { From 4e0715c8eaa6dddc2870b937f0a581a4447a6daa Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 30 Dec 2019 18:28:10 -0500 Subject: [PATCH 0576/2038] Physics: significant multithreading improvements and added ShapeTest --- deps/bepuphysics2/BepuPhysics.dll | 4 +- deps/bepuphysics2/BepuPhysics.pdb | 4 +- deps/bepuphysics2/BepuUtilities.dll | 2 +- deps/bepuphysics2/BepuUtilities.pdb | 2 +- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 34 ++- .../Bepu/BepuPhysicsComponent.cs | 20 +- .../Bepu/BepuRigidbodyComponent.cs | 145 ++++++---- .../Xenko.Physics/Bepu/BepuShapeTest.cs | 129 +++++++++ .../Xenko.Physics/Bepu/BepuSimulation.cs | 261 +++++++----------- .../Bepu/BepuStaticColliderComponent.cs | 22 +- sources/engine/Xenko.Physics/PhysicsSystem.cs | 10 +- 11 files changed, 389 insertions(+), 244 deletions(-) create mode 100644 sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index 6984ede3eb..957e57fb69 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:907c7f267ab46c15697e86176979ec898b06cbc2125ea25834c7814c1d85f653 -size 707584 +oid sha256:7bf9386d5351060290829239eace5d8cf1d9f8788fe82843fbefe912b03ac1be +size 708608 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index d7331756a1..ad9d647ef4 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0634edeaab7a9b323ef926a35c327901a9388f181b76b07ba3d22c5fdc495d95 -size 306836 +oid sha256:3fc14faff58cba5b7343cfb1ff4d242307f1e62c06855e31eff9a1eb878f224a +size 307432 diff --git a/deps/bepuphysics2/BepuUtilities.dll b/deps/bepuphysics2/BepuUtilities.dll index cfd585a89e..b65ef4bb2b 100644 --- a/deps/bepuphysics2/BepuUtilities.dll +++ b/deps/bepuphysics2/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9acf725ec6d278bc6fa115711455e7bb631809f67ca201cc63d44b9c5f40a47e +oid sha256:720f94d42658c454702909a9048a92c767c588ee6ddbb243a2de9d4bd922fc0f size 126464 diff --git a/deps/bepuphysics2/BepuUtilities.pdb b/deps/bepuphysics2/BepuUtilities.pdb index 0ceb229e38..5498017bd5 100644 --- a/deps/bepuphysics2/BepuUtilities.pdb +++ b/deps/bepuphysics2/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:8ec7053a569de51042dde5c78dcb11251d1ec27c474e22f690db5f051a9831c5 +oid sha256:d96cc0a279842979d00d468d89907b025a2c2fd99da8ed846fd82e0d56129b9a size 51596 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 6b6a9eb9dd..e1da51ff29 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -95,7 +95,7 @@ public static IShape OffsetSingleShape(IConvexShape shape, Vector3? offset = nul if (shape is ICompoundShape) throw new InvalidOperationException("Cannot offset a compound shape. Can't support nested compounds."); - using (var compoundBuilder = new CompoundBuilder(BepuSimulation.instance.pBufferPool, BepuSimulation.instance.internalSimulation.Shapes, 1)) + using (var compoundBuilder = new CompoundBuilder(BepuSimulation.safeBufferPool, BepuSimulation.instance.internalSimulation.Shapes, 1)) { compoundBuilder.AddForKinematicEasy(shape, new BepuPhysics.RigidPose(ToBepu(offset ?? Vector3.Zero), ToBepu(rotation ?? Quaternion.Identity)), 1f); @@ -166,7 +166,7 @@ public static void DisposeAllStaticMeshes(Entity e) if (sc.ColliderShape is Mesh m) { sc.AddedToScene = false; - m.Dispose(BepuSimulation.instance.pBufferPool); + DisposeMesh(m); sc.ColliderShape = null; } } @@ -182,7 +182,7 @@ public static void DisposeAllStaticMeshes(Entity e) /// public static ICompoundShape MakeCompound(List shapes, List offsets = null, List rotations = null, bool isDynamic = true, int bigThreshold = 5) { - using (var compoundBuilder = new CompoundBuilder(BepuSimulation.instance.pBufferPool, BepuSimulation.instance.internalSimulation.Shapes, shapes.Count)) + using (var compoundBuilder = new CompoundBuilder(BepuSimulation.safeBufferPool, BepuSimulation.instance.internalSimulation.Shapes, shapes.Count)) { bool allConvex = true; @@ -203,7 +203,7 @@ public static ICompoundShape MakeCompound(List shapes, List BufferPoolMap = new Dictionary(); + public static unsafe bool GenerateMeshShape(List positions, List indicies, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) { + var usePool = BepuSimulation.safeBufferPool; + // ok, should have what we need to make triangles int triangleCount = indicies.Count / 3; - BepuSimulation.instance.pBufferPool.Take(triangleCount, out BepuUtilities.Memory.Buffer triangles); + usePool.Take(triangleCount, out BepuUtilities.Memory.Buffer triangles); for (int i = 0; i < triangleCount; i ++) { @@ -353,10 +357,28 @@ public static unsafe bool GenerateMeshShape(List positions, List i triangles[i].C = ToBepu(positions[indicies[shiftedi+2]]); } - outMesh = new Mesh(triangles, new System.Numerics.Vector3(scale?.X ?? 1f, scale?.Y ?? 1f, scale?.Z ?? 1f), BepuSimulation.instance.pBufferPool); + outMesh = new Mesh(triangles, new System.Numerics.Vector3(scale?.X ?? 1f, scale?.Y ?? 1f, scale?.Z ?? 1f), usePool); + + BufferPoolMap[outMesh] = usePool; + return true; } + /// + /// Mesh had to have been made by BepuHelpers for the BufferPool to be tracked + /// + /// + /// true if memory was cleared + public static bool DisposeMesh(Mesh m) + { + if(BufferPoolMap.TryGetValue(m, out var bp)) + { + m.Dispose(bp); + return true; + } + return false; + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe System.Numerics.Vector3 ToBepu(Xenko.Core.Mathematics.Vector3 v) { diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index f7652b334d..6d9f2795f8 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -4,7 +4,9 @@ using System; using System.Collections.Generic; using System.ComponentModel; +using System.Runtime.CompilerServices; using BepuPhysics; +using BepuPhysics.Collidables; using BepuPhysics.Constraints; using Xenko.Core; using Xenko.Core.Annotations; @@ -110,6 +112,12 @@ public BepuPhysicsComponent() [DataMember] public SpringSettings SpringSettings = new SpringSettings(30f, 1f); + [DataMember] + virtual public IShape ColliderShape { get; set; } + + [DataMemberIgnore] + virtual public TypedIndex ShapeIndex { get; } + /// /// Computes the physics transformation from the TransformComponent values /// @@ -141,7 +149,17 @@ internal void DerivePhysicsTransform(Vector3? worldPosition, Matrix? worldRotati Matrix.Multiply(ref rotation, ref translationMatrix, out outMatrix); } - internal virtual void UpdateTransformationComponent() { } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal virtual bool CheckCurrentValid() + { + if (AddedHandle == -1) return false; + ref var location = ref BepuSimulation.instance.internalSimulation.Bodies.HandleToLocation[AddedHandle]; + if (location.SetIndex < 0 || location.SetIndex >= BepuSimulation.instance.internalSimulation.Bodies.Sets.Length) return false; + ref var set = ref BepuSimulation.instance.internalSimulation.Bodies.Sets[location.SetIndex]; + if (location.Index < 0 || location.Index >= set.Count) return false; + if (set.IndexToHandle[location.Index] != AddedHandle) return false; + return true; + } [DataMemberIgnore] public virtual Vector3 Position { get; set; } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 77759aa3ee..04d9b0d630 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -14,6 +14,7 @@ using Xenko.Physics; using BepuPhysics.Collidables; using BepuPhysics.Constraints; +using System.Runtime.CompilerServices; namespace Xenko.Physics.Bepu { @@ -21,11 +22,15 @@ namespace Xenko.Physics.Bepu [Display("Bepu Rigidbody")] public sealed class BepuRigidbodyComponent : BepuPhysicsComponent { + internal const int CONTACT_LIST_LENGTH = 4; + /// /// Description of the body to be created when added to the scene /// + [DataMember] public BodyDescription bodyDescription; + [DataMemberIgnore] private BodyReference _internalReference = new BodyReference(); /// @@ -44,6 +49,7 @@ public BodyReference InternalBody /// /// Action to be called after simulation, but before transforms are set to new positions. Arguments are this and simulation time. /// + [DataMemberIgnore] public Action ActionPerSimulationTick; /// @@ -52,7 +58,23 @@ public BodyReference InternalBody /// /// true if this instance is active; otherwise, false. /// - public bool IsActive => InternalBody.Awake; + [DataMemberIgnore] + public bool IsActive + { + get => CheckCurrentValid() && InternalBody.Awake; + set + { + if (CheckCurrentValid() == false || InternalBody.Awake == value) return; + + BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue(delegate { + if (CheckCurrentValid()) + { + BodyReference ib = InternalBody; + ib.Awake = value; + } + }); + } + } /// /// Use continuous collision detection? Set greater than 0 to use, 0 or less to disable @@ -70,7 +92,7 @@ public float CcdMotionThreshold bodyDescription.Collidable.Continuity.Mode = value > 0 ? ContinuousDetectionMode.Continuous : ContinuousDetectionMode.Discrete; bodyDescription.Collidable.Continuity.MinimumSweepTimestep = value > 0 ? 1e-3f : 0f; - if (InternalBody.Exists) + if (CheckCurrentValid()) InternalBody.Collidable.Continuity = bodyDescription.Collidable.Continuity; } } @@ -106,9 +128,8 @@ public bool CollectCollisions { if (processingPhysicalContacts == null) { - processingPhysicalContacts = new List[2]; - processingPhysicalContacts[0] = new List(); - processingPhysicalContacts[1] = new List(); + processingPhysicalContacts = new List[CONTACT_LIST_LENGTH]; + for (int i=0; i< CONTACT_LIST_LENGTH; i++) processingPhysicalContacts[i] = new List(); _currentContacts = new List(); } } @@ -116,15 +137,17 @@ public bool CollectCollisions { _currentContacts.Clear(); _currentContacts = null; - processingPhysicalContacts[0].Clear(); - processingPhysicalContacts[1].Clear(); processingPhysicalContacts = null; } _collectCollisions = value; } } + + [DataMemberIgnore] private bool _collectCollisions = false; + + [DataMemberIgnore] private List _currentContacts; /// @@ -139,10 +162,18 @@ public List CurrentContacts _currentContacts.Clear(); - List getFrom = processingPhysicalContacts[processingPhysicalContactsIndex^1]; + List getFrom = processingPhysicalContacts[(processingPhysicalContactsIndex+1)%CONTACT_LIST_LENGTH]; - for (int i = 0; i < getFrom.Count; i++) - _currentContacts.Add(getFrom[i]); + // make sure to only add legit contact points, and to not crash if threading blips happen + try + { + for (int i = 0; i < getFrom.Count; i++) + { + BepuContact bc = getFrom[i]; + if (bc.A != null && bc.B != null) _currentContacts.Add(bc); + } + } + catch (Exception e) { } return _currentContacts; } @@ -152,11 +183,22 @@ internal void swapProcessingContactsList() { if (processingPhysicalContacts == null || IsActive == false) return; - processingPhysicalContactsIndex ^= 1; + if (processingPhysicalContactsIndex == 0) + { + processingPhysicalContactsIndex = CONTACT_LIST_LENGTH - 1; + } + else + { + processingPhysicalContactsIndex--; + } + processingPhysicalContacts[processingPhysicalContactsIndex].Clear(); } + [DataMemberIgnore] internal List[] processingPhysicalContacts; + + [DataMemberIgnore] internal int processingPhysicalContactsIndex; private static readonly BodyInertia KinematicInertia = new BodyInertia() @@ -179,20 +221,13 @@ internal void swapProcessingContactsList() public BepuRigidbodyComponent() : base() { bodyDescription = new BodyDescription(); + bodyDescription.Pose.Orientation.W = 1f; bodyDescription.LocalInertia.InverseMass = 1f; bodyDescription.Activity.MinimumTimestepCountUnderThreshold = 32; bodyDescription.Activity.SleepThreshold = 0.01f; } - /// - /// Attempts to awake the collider. - /// - /// if set to true [force activation]. - public void Activate() - { - BodyReference ib = InternalBody; - ib.Awake = true; - } + public override TypedIndex ShapeIndex { get => bodyDescription.Collidable.Shape; } /// /// How slow does this need to be to sleep? Set less than 0 to never sleep @@ -208,7 +243,7 @@ public float SleepThreshold { bodyDescription.Activity.SleepThreshold = value; - if (InternalBody.Exists) + if (CheckCurrentValid()) InternalBody.Activity.SleepThreshold = value; } } @@ -246,44 +281,35 @@ private void UpdateInertia() { bodyDescription.LocalInertia = KinematicInertia; } - else if (ColliderShape != null) + else if (ColliderShape is IConvexShape ics) { - ColliderShape.ComputeInertia(mass, out bodyDescription.LocalInertia); + ics.ComputeInertia(mass, out bodyDescription.LocalInertia); } - if (InternalBody.Exists) + if (CheckCurrentValid()) { - InternalBody.LocalInertia = bodyDescription.LocalInertia; + InternalBody.SetLocalInertia(bodyDescription.LocalInertia); } } - private IConvexShape _myshape = null; - - public IConvexShape ColliderShape + [DataMemberIgnore] + public override IShape ColliderShape { - get => _myshape; + get => base.ColliderShape; set { - bool wasAddedToScene = AddedToScene; - - AddedToScene = false; + if (AddedToScene) + { + // remove and readd me to update shape + BepuSimulation.instance.ToBeRemoved.Enqueue(this); + BepuSimulation.instance.ToBeAdded.Enqueue(this); + } - _myshape = value; + base.ColliderShape = value; UpdateInertia(); - - AddedToScene = wasAddedToScene; } } - /// - /// If you made a modification to the existing ColliderShape (like changed its radius), try reloading it via this function. - /// - public void ReloadColliderShape() - { - if (_myshape == null || AddedToScene == false) return; - ColliderShape = _myshape; - } - private float mass = 1f; /// @@ -394,7 +420,7 @@ public override bool AddedToScene /// The impulse. public void ApplyImpulse(Vector3 impulse) { - if (InternalBody.Exists) + if (CheckCurrentValid()) InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); } @@ -405,7 +431,7 @@ public void ApplyImpulse(Vector3 impulse) /// The local offset. public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) { - if (InternalBody.Exists) + if (CheckCurrentValid()) InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); } @@ -415,7 +441,7 @@ public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) /// The torque. public void ApplyTorqueImpulse(Vector3 torque) { - if (InternalBody.Exists) + if (CheckCurrentValid()) InternalBody.ApplyAngularImpulse(BepuHelpers.ToBepu(torque)); } @@ -424,7 +450,7 @@ public override Vector3 Position { get { - return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Pose.Position : bodyDescription.Pose.Position); + return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalBody.Pose.Position : bodyDescription.Pose.Position); } set { @@ -432,7 +458,7 @@ public override Vector3 Position bodyDescription.Pose.Position.Y = value.Y; bodyDescription.Pose.Position.Z = value.Z; - if (InternalBody.Exists) + if (CheckCurrentValid()) { InternalBody.Pose.Position = bodyDescription.Pose.Position; } @@ -444,7 +470,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { get { - return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); + return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); } set { @@ -453,7 +479,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation bodyDescription.Pose.Orientation.Z = value.Z; bodyDescription.Pose.Orientation.W = value.W; - if (InternalBody.Exists) + if (CheckCurrentValid()) { InternalBody.Pose.Orientation = bodyDescription.Pose.Orientation; } @@ -471,7 +497,7 @@ public Vector3 AngularVelocity { get { - return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Velocity.Angular : bodyDescription.Velocity.Angular); + return CheckCurrentValid() ? BepuHelpers.ToXenko(InternalBody.Velocity.Angular) : Vector3.Zero; } set { @@ -479,7 +505,7 @@ public Vector3 AngularVelocity bodyDescription.Velocity.Angular.Y = value.Y; bodyDescription.Velocity.Angular.Z = value.Z; - if (InternalBody.Exists) + if (CheckCurrentValid()) { InternalBody.Velocity.Angular = bodyDescription.Velocity.Angular; } @@ -497,7 +523,7 @@ public Vector3 LinearVelocity { get { - return BepuHelpers.ToXenko(InternalBody.Exists ? InternalBody.Velocity.Linear : bodyDescription.Velocity.Linear); + return CheckCurrentValid() ? BepuHelpers.ToXenko(InternalBody.Velocity.Linear) : Vector3.Zero; } set { @@ -505,18 +531,24 @@ public Vector3 LinearVelocity bodyDescription.Velocity.Linear.Y = value.Y; bodyDescription.Velocity.Linear.Z = value.Z; - if (InternalBody.Exists) + if (CheckCurrentValid()) { InternalBody.Velocity.Linear = bodyDescription.Velocity.Linear; } } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal override bool CheckCurrentValid() + { + return base.CheckCurrentValid() && InternalBody.Exists; + } + /// /// Updades the graphics transformation from the given physics transformation /// /// - internal override void UpdateTransformationComponent() + internal void UpdateTransformationComponent() { var entity = Entity; @@ -524,6 +556,5 @@ internal override void UpdateTransformationComponent() if (LocalPhysicsOffset.HasValue) entity.Transform.Position += LocalPhysicsOffset.Value; if (IgnorePhysicsRotation == false) entity.Transform.Rotation = Rotation; } - } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs new file mode 100644 index 0000000000..2da8c8c373 --- /dev/null +++ b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs @@ -0,0 +1,129 @@ +using BepuPhysics; +using BepuPhysics.Collidables; +using BepuPhysics.CollisionDetection; +using BepuUtilities; +using BepuUtilities.Collections; +using BepuUtilities.Memory; +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Runtime.CompilerServices; +using System.Text; +using Xenko.Core.Threading; +using Xenko.Engine; + +namespace Xenko.Physics.Bepu +{ + /// + /// Shows one way of handling collision queries that require contact-level test accuracy. + /// + public class BepuShapeTest + { + /// + /// Provides callbacks for filtering and data collection to the CollisionBatcher we'll be using to test query shapes against the detected environment. + /// + public struct BatcherCallbacks : ICollisionCallbacks + { + public List contactList; + public Xenko.Core.Mathematics.Vector3 position; + + //These callbacks provide filtering and reporting for pairs being processed by the collision batcher. + //"Pair id" refers to the identifier given to the pair when it was added to the batcher. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool AllowCollisionTesting(int pairId, int childA, int childB) + { + //If you wanted to filter based on the children of an encountered nonconvex object, here would be the place to do it. + //The pairId could be used to look up the involved objects and any metadata necessary for filtering. + return true; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnChildPairCompleted(int pairId, int childA, int childB, ref ConvexContactManifold manifold) + { + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void OnPairCompleted(int pairId, ref TManifold manifold) where TManifold : struct, IContactManifold + { + if (manifold.Count > 0) + { + contactList.Add(new BepuContact() + { + Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), + Position = BepuHelpers.ToXenko(manifold.SimpleGetOffset()) + position + }); + } + } + } + + /// + /// Called by the BroadPhase.GetOverlaps to collect all encountered collidables. + /// + struct BroadPhaseOverlapEnumerator : IBreakableForEach + { + public List components; + public uint lookingFor; + + public bool LoopBody(CollidableReference reference) + { + BepuPhysicsComponent bpc = BepuSimulation.getFromReference(reference); + if (((uint)bpc.CollisionGroup & lookingFor) != 0) components.Add(bpc); + return true; + } + } + + /// + /// Adds a shape query to the collision batcher. + /// + /// Type of the shape to test. + /// Shape data to test. + /// Size of the shape data in bytes. + /// Minimum of the query shape's bounding box. + /// Maximum of the query shape's bounding box. + /// Pose of the query shape. + /// Id to use to refer to this query when the collision batcher finishes processing it. + /// Batcher to add the query's tests to. + static private unsafe void AddQueryToBatch(int queryShapeType, void* queryShapeData, int queryShapeSize, in Vector3 queryBoundsMin, + in Vector3 queryBoundsMax, Vector3 queryPos, BepuUtilities.Quaternion queryRot, + ref CollisionBatcher batcher, CollisionFilterGroupFlags lookingFor) + { + var broadPhaseEnumerator = new BroadPhaseOverlapEnumerator { components = new List(), lookingFor = (uint)lookingFor }; + BepuSimulation.instance.internalSimulation.BroadPhase.GetOverlaps(queryBoundsMin, queryBoundsMax, ref broadPhaseEnumerator); + for (int overlapIndex = 0; overlapIndex < broadPhaseEnumerator.components.Count; ++overlapIndex) + { + BepuPhysicsComponent bpc = broadPhaseEnumerator.components[overlapIndex]; + batcher.CacheShapeB(bpc.ColliderShape.TypeId, queryShapeType, queryShapeData, queryShapeSize, out var cachedQueryShapeData); + batcher.AddDirectly(bpc.ColliderShape.TypeId, queryShapeType, + bpc.ColliderShape.GetPointer(), cachedQueryShapeData, + queryPos - BepuHelpers.ToBepu(bpc.Position), queryRot, BepuHelpers.ToBepu(bpc.Rotation), 0, new PairContinuation(0)); + } + } + + /// + /// Adds a shape query to the collision batcher. + /// + /// Type of the query shape. + /// Shape to use in the query. + /// Pose of the query shape. + /// Id to use to refer to this query when the collision batcher finishes processing it. + /// Batcher to add the query's tests to. + static public unsafe List SingleQuery(TShape shape, Xenko.Core.Mathematics.Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, CollisionFilterGroupFlags lookingFor) where TShape : struct, IConvexShape + { + List contacts = new List(); + var batcher = new CollisionBatcher(BepuSimulation.safeBufferPool, BepuSimulation.instance.internalSimulation.Shapes, + BepuSimulation.instance.internalSimulation.NarrowPhase.CollisionTaskRegistry, 0f, new BatcherCallbacks() { contactList = contacts, position = position }); + BepuUtilities.Quaternion q = BepuHelpers.ToBepu(rotation); + Vector3 v = BepuHelpers.ToBepu(position); + shape.ComputeBounds(q, out var boundingBoxMin, out var boundingBoxMax); + boundingBoxMin += v; + boundingBoxMax += v; + using(BepuSimulation.instance.simulationLocker.ReadLock()) + { + AddQueryToBatch(shape.TypeId, Unsafe.AsPointer(ref shape), shape.GetSize(), boundingBoxMin, boundingBoxMax, v, q, ref batcher, lookingFor); + batcher.Flush(); + } + return contacts; + } + } +} + diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index d1ac837d2b..3bea81b734 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -23,6 +23,7 @@ using Xenko.Engine.Design; using Xenko.Games; using Xenko.Physics.Engine; +using Xenko.Core.Threading; using Xenko.Rendering; namespace Xenko.Physics.Bepu @@ -36,6 +37,10 @@ public class BepuSimulation : IDisposable internal ConcurrentQueue ToBeAdded = new ConcurrentQueue(), ToBeRemoved = new ConcurrentQueue(); + public ReaderWriterLockSlim simulationLocker { get; private set; } = new ReaderWriterLockSlim(); + + public ConcurrentQueue> ActionsBeforeSimulationStep = new ConcurrentQueue>(); + private static BepuSimulation _instance; public static BepuSimulation instance { @@ -50,8 +55,29 @@ private set } } + [ThreadStatic] + private static BufferPool threadStaticPool; + + /// + /// Gets a thread-safe buffer pool + /// + public static BufferPool safeBufferPool + { + get + { + if (threadStaticPool == null) + { + threadStaticPool = new BufferPool(); + allBufferPools.Add(threadStaticPool); + } + return threadStaticPool; + } + } + private PoseIntegratorCallbacks poseCallbacks; - internal BufferPool pBufferPool; + + private static List allBufferPools = new List(); + internal int clearRequested; private BepuSimpleThreadDispatcher threadDispatcher = new BepuSimpleThreadDispatcher(Environment.ProcessorCount); @@ -80,18 +106,25 @@ public void Clear(bool clearBuffers = true, bool forceRightNow = false) { clearRequested = 0; - internalSimulation.Clear(); + using (simulationLocker.WriteLock()) + { + internalSimulation.Clear(); - if (clearBuffers) pBufferPool.Clear(); + if (clearBuffers) + { + for (int i = 0; i < allBufferPools.Count; i++) + allBufferPools[i].Clear(); + } - for (int i = 0; i < AllRigidbodies.Count; i++) - AllRigidbodies[i].AddedHandle = -1; - foreach (BepuStaticColliderComponent sc in StaticMappings.Values) - sc.AddedHandle = -1; + for (int i = 0; i < AllRigidbodies.Count; i++) + AllRigidbodies[i].AddedHandle = -1; + foreach (BepuStaticColliderComponent sc in StaticMappings.Values) + sc.AddedHandle = -1; - StaticMappings.Clear(); - RigidMappings.Clear(); - AllRigidbodies.Clear(); + StaticMappings.Clear(); + RigidMappings.Clear(); + AllRigidbodies.Clear(); + } return; } @@ -329,12 +362,10 @@ internal BepuSimulation(PhysicsSettings configuration) GameService.SceneSystem.SceneInstance.EntityRemoved += EntityRemoved; GameService.SceneSystem.SceneInstance.ComponentChanged += ComponentChanged; - MaxSubSteps = configuration.MaxSubSteps; - FixedTimeStep = configuration.FixedTimeStep; - - pBufferPool = new BufferPool(); poseCallbacks = new PoseIntegratorCallbacks(new System.Numerics.Vector3(0f, -9.81f, 0f)); - internalSimulation = BepuPhysics.Simulation.Create(pBufferPool, new NarrowPhaseCallbacks(), poseCallbacks); + + // we will give the simulation its own bufferpool + internalSimulation = BepuPhysics.Simulation.Create(new BufferPool(), new NarrowPhaseCallbacks(), poseCallbacks); instance = this; } @@ -367,15 +398,6 @@ public void Dispose() Clear(true, true); } - /// - /// Free up memory used to store triangles for a mesh collision shape - /// - /// - public void DisposeMesh(BepuPhysics.Collidables.Mesh m) - { - m.Dispose(pBufferPool); - } - public RenderGroup ColliderShapesRenderGroup { get; set; } = RenderGroup.Group0; internal void ProcessAdds() @@ -387,17 +409,24 @@ internal void ProcessAdds() if (component.AddedHandle > -1) continue; // already added if (component is BepuStaticColliderComponent scc) { - scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation); - scc.AddedHandle = internalSimulation.Statics.Add(scc.staticDescription); - StaticMappings[scc.AddedHandle] = scc; + using (simulationLocker.WriteLock()) + { + scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation); + scc.AddedHandle = internalSimulation.Statics.Add(scc.staticDescription); + StaticMappings[scc.AddedHandle] = scc; + } } else if (component is BepuRigidbodyComponent rigidBody) { - rigidBody.ColliderShape.ComputeInertia(rigidBody.Mass, out rigidBody.bodyDescription.LocalInertia); - rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); - AllRigidbodies.Add(rigidBody); - rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); - RigidMappings[rigidBody.AddedHandle] = rigidBody; + if (rigidBody.ColliderShape is IConvexShape ics) + ics.ComputeInertia(rigidBody.Mass, out rigidBody.bodyDescription.LocalInertia); + using (simulationLocker.WriteLock()) + { + rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + AllRigidbodies.Add(rigidBody); + rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); + RigidMappings[rigidBody.AddedHandle] = rigidBody; + } rigidBody.SleepThreshold = rigidBody.bodyDescription.Activity.SleepThreshold; } component.Position = component.Entity.Transform.WorldPosition(); @@ -416,21 +445,27 @@ internal void ProcessRemovals() if (addedIndex == -1) continue; // already removed if (component is BepuStaticColliderComponent scc) { - scc.AddedHandle = -1; - internalSimulation.Statics.Remove(addedIndex); - StaticMappings.Remove(addedIndex); + using(simulationLocker.WriteLock()) + { + scc.AddedHandle = -1; + internalSimulation.Statics.Remove(addedIndex); + StaticMappings.Remove(addedIndex); + } } else if (component is BepuRigidbodyComponent rigidBody) { - rigidBody.AddedHandle = -1; - internalSimulation.Bodies.Remove(addedIndex); - RigidMappings.Remove(addedIndex); - AllRigidbodies.Remove(rigidBody); + using(simulationLocker.WriteLock()) + { + rigidBody.AddedHandle = -1; + internalSimulation.Bodies.Remove(addedIndex); + RigidMappings.Remove(addedIndex); + AllRigidbodies.Remove(rigidBody); + } if (rigidBody.processingPhysicalContacts != null) { - rigidBody.processingPhysicalContacts[0].Clear(); - rigidBody.processingPhysicalContacts[1].Clear(); + for (int i = 0; i < rigidBody.processingPhysicalContacts.Length; i++) + rigidBody.processingPhysicalContacts[i].Clear(); } } } @@ -548,7 +583,10 @@ public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, Coll startLength = length, furthestHitSoFar = float.MaxValue }; - internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); + using(simulationLocker.ReadLock()) + { + internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); + } return rhch.HitCollidable; } @@ -589,7 +627,10 @@ public void RaycastPenetrating(Vector3 from, Vector3 direction, float length, Li HitCollidables = resultsOutput, startLength = length }; - internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); + using (simulationLocker.ReadLock()) + { + internalSimulation.RayCast(new System.Numerics.Vector3(from.X, from.Y, from.Z), new System.Numerics.Vector3(direction.X, direction.Y, direction.Z), length, ref rhch); + } } struct SweepTestFirst : ISweepHitHandler @@ -687,62 +728,6 @@ public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) } } - /// - /// Performs a test to see if a collider shape collides with anything, and if so, returns the closest hit to the center of the shape. - /// - /// The shape. - /// Where to test. - /// Group of the shape. - /// What the shape should collide with - /// PhysicsComponent of thing hitting shapetest - public BepuPhysicsComponent ShapeTest(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, CollisionFilterGroupFlags hitGroups = DefaultFlags) - { - SweepTestFirst sshh = new SweepTestFirst() - { - hitGroups = hitGroups, - startLength = 0f, - furthestHitSoFar = float.MaxValue - }; - RigidPose rp = new RigidPose(); - rp.Position.X = position.X; - rp.Position.Y = position.Y; - rp.Position.Z = position.Z; - rp.Orientation.X = rotation.X; - rp.Orientation.Y = rotation.Y; - rp.Orientation.Z = rotation.Z; - rp.Orientation.W = rotation.W; - internalSimulation.Sweep(shape, rp, new BodyVelocity(), 0f, pBufferPool, ref sshh); - return sshh.result.Collider; - } - - /// - /// Performs a test to see if a collider shape collides with anything, and if so, returns all results in a list - /// - /// The shape. - /// Where to test. - /// Where to store results - /// Group of the shape. - /// What the shape should collide with - /// - public void ShapeTestPenetrating(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) - { - SweepTestAll sshh = new SweepTestAll() - { - hitGroups = hitGroups, - startLength = 0f, - results = output - }; - RigidPose rp = new RigidPose(); - rp.Position.X = position.X; - rp.Position.Y = position.Y; - rp.Position.Z = position.Z; - rp.Orientation.X = rotation.X; - rp.Orientation.Y = rotation.Y; - rp.Orientation.Z = rotation.Z; - rp.Orientation.W = rotation.W; - internalSimulation.Sweep(shape, rp, new BodyVelocity(), 0f, pBufferPool, ref sshh); - } - /// /// Performs a sweep test using a collider shape and returns the closest hit /// @@ -790,7 +775,10 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core rp.Orientation.Y = rotation.Y; rp.Orientation.Z = rotation.Z; rp.Orientation.W = rotation.W; - internalSimulation.Sweep(shape, rp, new BodyVelocity(new System.Numerics.Vector3(direction.X, direction.Y, direction.Z)), length, pBufferPool, ref sshh); + using (simulationLocker.ReadLock()) + { + internalSimulation.Sweep(shape, rp, new BodyVelocity(new System.Numerics.Vector3(direction.X, direction.Y, direction.Z)), length, safeBufferPool, ref sshh); + } return sshh.result; } @@ -841,7 +829,10 @@ public void ShapeSweepPenetrating(IConvexShape shape, Vector3 position, Xenko.Co rp.Orientation.Y = rotation.Y; rp.Orientation.Z = rotation.Z; rp.Orientation.W = rotation.W; - internalSimulation.Sweep(shape, rp, new BodyVelocity(new System.Numerics.Vector3(direction.X, direction.Y, direction.Z)), length, pBufferPool, ref sshh); + using (simulationLocker.ReadLock()) + { + internalSimulation.Sweep(shape, rp, new BodyVelocity(new System.Numerics.Vector3(direction.X, direction.Y, direction.Z)), length, safeBufferPool, ref sshh); + } } /// @@ -869,74 +860,14 @@ public Vector3 Gravity } } - /// - /// The maximum number of steps that the Simulation is allowed to take each tick. - /// If the engine is running slow (large deltaTime), then you must increase the number of maxSubSteps to compensate for this, otherwise your simulation is “losing” time. - /// It's important that frame DeltaTime is always less than MaxSubSteps*FixedTimeStep, otherwise you are losing time. - /// - public int MaxSubSteps { get; set; } - - /// - /// By decreasing the size of fixedTimeStep, you are increasing the “resolution” of the simulation. - /// Default is 1.0f / 60.0f or 60fps - /// - public float FixedTimeStep { get; set; } - - public class SimulationArgs : EventArgs - { - public float DeltaTime; - } - - /// - /// Called right before the physics simulation. - /// This event might not be fired by the main thread. - /// - public event EventHandler SimulationBegin; - - protected virtual void OnSimulationBegin(SimulationArgs e) - { - var handler = SimulationBegin; - handler?.Invoke(this, e); - } - - internal int UpdatedRigidbodies; - - private readonly SimulationArgs simulationArgs = new SimulationArgs(); - - internal ProfilingState SimulationProfiler; - internal void Simulate(float deltaTime) { if (internalSimulation == null || DisableSimulation) return; - OnSimulationBegin(simulationArgs); - - internalSimulation.Timestep(deltaTime, threadDispatcher); - - OnSimulationEnd(simulationArgs); - } - - /// - /// Called right after the physics simulation. - /// This event might not be fired by the main thread. - /// - public event EventHandler SimulationEnd; - - /// - /// Called right before processing a tick of the physics simulation. - /// - public event EventHandler PreSimulationTick; - - protected virtual void OnSimulationEnd(SimulationArgs e) - { - var handler = SimulationEnd; - handler?.Invoke(this, e); - } - - protected virtual void OnPreSimulationTick(float timeStep) - { - var handler = PreSimulationTick; - handler?.Invoke(this, timeStep); + using (BepuSimulation.instance.simulationLocker.ReadLock()) + { + internalSimulation.Timestep(deltaTime, threadDispatcher); + } } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index 1b7c2fca3d..cf3e24a425 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using System.Runtime.CompilerServices; using BepuPhysics; using BepuPhysics.Collidables; using Xenko.Core; @@ -16,8 +17,6 @@ public sealed class BepuStaticColliderComponent : BepuPhysicsComponent public StaticDescription staticDescription; private StaticReference _internalStatic; - public IShape ColliderShape; - public StaticReference InternalStatic { get @@ -26,12 +25,15 @@ public StaticReference InternalStatic _internalStatic.Handle = AddedHandle; return _internalStatic; } - } + } + + public override TypedIndex ShapeIndex { get => staticDescription.Collidable.Shape; } public BepuStaticColliderComponent() : base () { _internalStatic = new StaticReference(); staticDescription = new StaticDescription(); + staticDescription.Pose.Orientation.W = 1f; } [DataMemberIgnore] @@ -39,7 +41,7 @@ public override Xenko.Core.Mathematics.Vector3 Position { get { - return BepuHelpers.ToXenko(InternalStatic.Exists ? InternalStatic.Pose.Position : staticDescription.Pose.Position); + return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalStatic.Pose.Position : staticDescription.Pose.Position); } set { @@ -47,7 +49,7 @@ public override Xenko.Core.Mathematics.Vector3 Position staticDescription.Pose.Position.Y = value.Y; staticDescription.Pose.Position.Z = value.Z; - if (InternalStatic.Exists) + if (CheckCurrentValid()) { InternalStatic.Pose.Position = staticDescription.Pose.Position; } @@ -59,7 +61,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { get { - return BepuHelpers.ToXenko(InternalStatic.Exists ? InternalStatic.Pose.Orientation : staticDescription.Pose.Orientation); + return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalStatic.Pose.Orientation : staticDescription.Pose.Orientation); } set { @@ -68,13 +70,19 @@ public override Xenko.Core.Mathematics.Quaternion Rotation staticDescription.Pose.Orientation.Z = value.Z; staticDescription.Pose.Orientation.W = value.W; - if (InternalStatic.Exists) + if (CheckCurrentValid()) { InternalStatic.Pose.Orientation = staticDescription.Pose.Orientation; } } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal override bool CheckCurrentValid() + { + return base.CheckCurrentValid() && InternalStatic.Exists; + } + /// /// Set this to true to add this object to the physics simulation. Will automatically remove itself when the entity. is removed from the scene. Will NOT automatically add the rigidbody /// to the scene when the entity is added, though. diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index 12f7f351d7..1d57e42bd0 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -1,6 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -25,6 +26,8 @@ private class PhysicsScene private ManualResetEventSlim doUpdateEvent; private Thread physicsThread; + public static float TimeScale = 1f; + private readonly List scenes = new List(); public PhysicsSystem(IServiceRegistry registry) @@ -154,6 +157,9 @@ private void RunPhysicsSimulation(float time) if (physicsScene.BepuSimulation != null) { + // do anything before simulation + while (physicsScene.BepuSimulation.ActionsBeforeSimulationStep.TryDequeue(out Action a)) a(time); + // remove all bodies set to be removed physicsScene.BepuSimulation.ProcessRemovals(); @@ -208,12 +214,12 @@ public override void Update(GameTime gameTime) { if (isMultithreaded) { - timeToSimulate += (float)gameTime.Elapsed.TotalSeconds; + timeToSimulate += (float)gameTime.Elapsed.TotalSeconds * TimeScale; doUpdateEvent.Set(); } else { - RunPhysicsSimulation((float)gameTime.Elapsed.TotalSeconds); + RunPhysicsSimulation((float)gameTime.Elapsed.TotalSeconds * TimeScale); } } } From e8e5550b997282c9ca2d2008a2784bb1a9615c71 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 30 Dec 2019 19:09:11 -0500 Subject: [PATCH 0577/2038] CharacterComponent: fix orientation initialization --- sources/engine/Xenko.Physics/Elements/CharacterComponent.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs b/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs index 93406d1794..f01befabd5 100644 --- a/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs +++ b/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs @@ -15,6 +15,7 @@ public sealed class CharacterComponent : PhysicsComponent { public CharacterComponent() { + Orientation = Quaternion.Identity; StepHeight = 0.1f; } From 742524f1545891550db0b5e7992b3c4a3df5e173 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 30 Dec 2019 22:52:56 -0500 Subject: [PATCH 0578/2038] Physics: remove duplicate inertia calculation (which breaks kinematic bodies) --- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 3bea81b734..57ec4aad18 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -418,8 +418,6 @@ internal void ProcessAdds() } else if (component is BepuRigidbodyComponent rigidBody) { - if (rigidBody.ColliderShape is IConvexShape ics) - ics.ComputeInertia(rigidBody.Mass, out rigidBody.bodyDescription.LocalInertia); using (simulationLocker.WriteLock()) { rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); From d55c40204573d1ee9aff2059f5cae1849e8e4484 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 31 Dec 2019 17:11:50 -0500 Subject: [PATCH 0579/2038] Physics: fix collision shape changing --- deps/bepuphysics2/BepuPhysics.dll | 2 +- deps/bepuphysics2/BepuPhysics.pdb | 2 +- deps/bepuphysics2/BepuUtilities.dll | 2 +- deps/bepuphysics2/BepuUtilities.pdb | 2 +- .../Bepu/BepuRigidbodyComponent.cs | 38 ++++++++++++++++--- .../Xenko.Physics/Bepu/BepuSimulation.cs | 13 ++++++- 6 files changed, 48 insertions(+), 11 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index 957e57fb69..d9fc0deea6 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7bf9386d5351060290829239eace5d8cf1d9f8788fe82843fbefe912b03ac1be +oid sha256:fde9f3f53b24e6bc79d6b63f548b341a686a1ee0b0e88bb0b7fd4530982e5041 size 708608 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index ad9d647ef4..ac4367b79f 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3fc14faff58cba5b7343cfb1ff4d242307f1e62c06855e31eff9a1eb878f224a +oid sha256:c86085acd216d6d8b1da8829a8331b00535aa87c3ab32ef0ffd51e99be3d8952 size 307432 diff --git a/deps/bepuphysics2/BepuUtilities.dll b/deps/bepuphysics2/BepuUtilities.dll index b65ef4bb2b..a2032b96bb 100644 --- a/deps/bepuphysics2/BepuUtilities.dll +++ b/deps/bepuphysics2/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:720f94d42658c454702909a9048a92c767c588ee6ddbb243a2de9d4bd922fc0f +oid sha256:5ac84baa3473b17780872f49177367a23b6e569e2b91e133f85bf210a5acc949 size 126464 diff --git a/deps/bepuphysics2/BepuUtilities.pdb b/deps/bepuphysics2/BepuUtilities.pdb index 5498017bd5..bdcbe8f6e4 100644 --- a/deps/bepuphysics2/BepuUtilities.pdb +++ b/deps/bepuphysics2/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d96cc0a279842979d00d468d89907b025a2c2fd99da8ed846fd82e0d56129b9a +oid sha256:afb1853b76f3fbd9fc9e1455afb2280b4a7d3c0f52ec2f7cdaea195658b681a5 size 51596 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 04d9b0d630..de55fd6d8a 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -271,17 +271,17 @@ public float Mass mass = value; - UpdateInertia(); + UpdateInertia(newShape ?? ColliderShape); } } - private void UpdateInertia() + private void UpdateInertia(IShape useShape) { if (type == RigidBodyTypes.Kinematic) { bodyDescription.LocalInertia = KinematicInertia; } - else if (ColliderShape is IConvexShape ics) + else if (useShape is IConvexShape ics) { ics.ComputeInertia(mass, out bodyDescription.LocalInertia); } @@ -292,21 +292,47 @@ private void UpdateInertia() } } + [DataMemberIgnore] + internal IShape newShape; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void swapNewShape() + { + base.ColliderShape = newShape; + newShape = null; + } + [DataMemberIgnore] public override IShape ColliderShape { get => base.ColliderShape; set { + if (value == null || value == ColliderShape) return; + + newShape = null; + if (AddedToScene) { + if (ColliderShape != null) + { + newShape = value; + } + else + { + base.ColliderShape = value; + } + // remove and readd me to update shape BepuSimulation.instance.ToBeRemoved.Enqueue(this); BepuSimulation.instance.ToBeAdded.Enqueue(this); } + else + { + base.ColliderShape = value; + } - base.ColliderShape = value; - UpdateInertia(); + UpdateInertia(newShape ?? base.ColliderShape); } } @@ -376,7 +402,7 @@ public RigidBodyTypes RigidBodyType { type = value; - UpdateInertia(); + UpdateInertia(newShape ?? ColliderShape); } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 57ec4aad18..d4a64fc5c6 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -420,12 +420,23 @@ internal void ProcessAdds() { using (simulationLocker.WriteLock()) { - rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + if (rigidBody.newShape != null) + { + TypedIndex ti = rigidBody.newShape.AddToShapes(internalSimulation.Shapes); + rigidBody.bodyDescription.Collidable = new CollidableDescription(ti, 0.1f); + rigidBody.InternalBody.SetShape(ti); + rigidBody.swapNewShape(); + } + else + { + rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + } AllRigidbodies.Add(rigidBody); rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); RigidMappings[rigidBody.AddedHandle] = rigidBody; } rigidBody.SleepThreshold = rigidBody.bodyDescription.Activity.SleepThreshold; + rigidBody.CcdMotionThreshold = rigidBody.bodyDescription.Collidable.Continuity.SweepConvergenceThreshold; } component.Position = component.Entity.Transform.WorldPosition(); component.Rotation = component.Entity.Transform.WorldRotation(); From 6973043277fc3c12ee6bd06237526dc00475e754 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 31 Dec 2019 23:23:22 -0500 Subject: [PATCH 0580/2038] Physics: option to skip "at zero" ray and sweep tests --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index d4a64fc5c6..56e0bee3f6 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -486,6 +486,8 @@ struct RayHitClosestHandler : IRayHitHandler public CollisionFilterGroupFlags findGroups; public float furthestHitSoFar, startLength; public BepuHitResult HitCollidable; + public bool skipAtZero; + [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowTest(CollidableReference collidable) { @@ -501,6 +503,8 @@ public bool AllowTest(CollidableReference collidable, int childIndex) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Numerics.Vector3 normal, CollidableReference collidable, int childIndex) { + if (skipAtZero && t <= float.Epsilon) return; + if (t < furthestHitSoFar) { //Cache the earliest impact. @@ -565,7 +569,7 @@ public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Nume /// The collision group of this raycast /// The collision group that this raycast can collide with /// The list with hit results. - public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags hitGroups = DefaultFlags) + public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) { Vector3 diff = to - from; float length = diff.Length(); @@ -573,7 +577,7 @@ public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags diff.X *= inv; diff.Y *= inv; diff.Z *= inv; - return Raycast(from, diff, length, hitGroups); + return Raycast(from, diff, length, hitGroups, skipAtZero); } /// @@ -584,13 +588,14 @@ public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags /// The collision group of this raycast /// The collision group that this raycast can collide with /// The list with hit results. - public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags) + public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) { RayHitClosestHandler rhch = new RayHitClosestHandler() { findGroups = hitGroups, startLength = length, - furthestHitSoFar = float.MaxValue + furthestHitSoFar = float.MaxValue, + skipAtZero = skipAtZero }; using(simulationLocker.ReadLock()) { @@ -647,6 +652,7 @@ struct SweepTestFirst : ISweepHitHandler public CollisionFilterGroupFlags hitGroups; public BepuHitResult result; public float furthestHitSoFar, startLength; + public bool skipAtZero; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowTest(CollidableReference collidable) @@ -663,6 +669,8 @@ public bool AllowTest(CollidableReference collidable, int child) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLocation, in System.Numerics.Vector3 hitNormal, CollidableReference collidable) { + if (skipAtZero && t <= float.Epsilon) return; + if (t < furthestHitSoFar) { furthestHitSoFar = t; @@ -686,6 +694,8 @@ public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLoc [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) { + if (skipAtZero) return; + result.Succeeded = true; result.Collider = getFromReference(collidable); maximumT = 0; @@ -747,7 +757,7 @@ public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) /// The collision group that this shape sweep can collide with /// /// This kind of shape cannot be used for a ShapeSweep. - public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags) + public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) { Vector3 diff = endpoint - position; float length = diff.Length(); @@ -755,7 +765,7 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core diff.X *= inv; diff.Y *= inv; diff.Z *= inv; - return ShapeSweep(shape, position, rotation, diff, length, hitGroups); + return ShapeSweep(shape, position, rotation, diff, length, hitGroups, skipAtZero); } /// @@ -768,13 +778,14 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core /// The collision group that this shape sweep can collide with /// /// This kind of shape cannot be used for a ShapeSweep. - public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags) + public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) { SweepTestFirst sshh = new SweepTestFirst() { hitGroups = hitGroups, startLength = length, - furthestHitSoFar = float.MaxValue + furthestHitSoFar = float.MaxValue, + skipAtZero = skipAtZero }; RigidPose rp = new RigidPose(); rp.Position.X = position.X; From 8a2191caef3955504e4961b37230b4a37e603ae2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 1 Jan 2020 12:20:12 -0500 Subject: [PATCH 0581/2038] Physics: maximum speed and move some things to Rigidbody --- .../Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 9 --------- .../Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 15 +++++++++++++++ .../engine/Xenko.Physics/Bepu/BepuSimulation.cs | 8 ++++++++ 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 6d9f2795f8..c7f8217647 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -85,15 +85,6 @@ public BepuPhysicsComponent() [DefaultValue(CollisionFilterGroupFlags.AllFilter)] public CollisionFilterGroupFlags CanCollideWith { get; set; } = CollisionFilterGroupFlags.AllFilter; - /// - /// When updating the associated TransformComponent, should we not set rotation? - /// - [DataMember(69)] - public bool IgnorePhysicsRotation = false; - - [DataMemberIgnore] - public Vector3? LocalPhysicsOffset = null; - /// /// Gets or sets the tag. /// diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index de55fd6d8a..b13a4c4175 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -248,6 +248,12 @@ public float SleepThreshold } } + /// + /// Forcefully cap the velocity of this rigidbody to this magnitude. Can prevent weird issues without the need of continuous collision detection. + /// + [DataMember] + public float MaximumSpeed = 0f; + /// /// Gets or sets the mass of this Rigidbody /// @@ -570,6 +576,15 @@ internal override bool CheckCurrentValid() return base.CheckCurrentValid() && InternalBody.Exists; } + /// + /// When updating the associated TransformComponent, should we not set rotation? + /// + [DataMember(69)] + public bool IgnorePhysicsRotation = false; + + [DataMemberIgnore] + public Vector3? LocalPhysicsOffset = null; + /// /// Updades the graphics transformation from the given physics transformation /// diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 56e0bee3f6..175207e96f 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -345,6 +345,14 @@ public void IntegrateVelocity(int bodyIndex, in RigidPose pose, in BodyInertia l if (rb.AngularDamping > 0f) velocity.Angular -= velocity.Angular * indt * rb.AngularDamping; + + // velocity cap? + if (rb.MaximumSpeed > 0f) + { + float sqrmag = velocity.Linear.LengthSquared(); + if (sqrmag > rb.MaximumSpeed * rb.MaximumSpeed) + velocity.Linear *= rb.MaximumSpeed / (float)Math.Sqrt(sqrmag); + } } } } From f9134a4858b1f07f6262af77630b80c33c37a25e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 1 Jan 2020 16:33:59 -0500 Subject: [PATCH 0582/2038] Physics: add option to lock rotation of rigidbodies (good for characters) --- .../Bepu/BepuRigidbodyComponent.cs | 43 ++++++++++++++----- 1 file changed, 33 insertions(+), 10 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index b13a4c4175..bc052ed0dc 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -204,15 +204,7 @@ internal void swapProcessingContactsList() private static readonly BodyInertia KinematicInertia = new BodyInertia() { InverseMass = 0f, - InverseInertiaTensor = new Symmetric3x3() - { - XX = 0f, - YX = 0f, - ZX = 0f, - YY = 0f, - ZY = 0f, - ZZ = 0f - } + InverseInertiaTensor = default }; private RigidBodyTypes type = RigidBodyTypes.Dynamic; @@ -254,6 +246,28 @@ public float SleepThreshold [DataMember] public float MaximumSpeed = 0f; + /// + /// Prevent this rigidbody from rotating or falling over? + /// + [DataMember] + public bool RotationLock + { + get + { + return _rotationLock; + } + set + { + if (_rotationLock == value) return; + + _rotationLock = value; + + UpdateInertia(newShape ?? ColliderShape); + } + } + + private bool _rotationLock = false; + /// /// Gets or sets the mass of this Rigidbody /// @@ -287,10 +301,19 @@ private void UpdateInertia(IShape useShape) { bodyDescription.LocalInertia = KinematicInertia; } - else if (useShape is IConvexShape ics) + else if (useShape is IConvexShape ics && !_rotationLock) { ics.ComputeInertia(mass, out bodyDescription.LocalInertia); } + else if (_rotationLock) + { + bodyDescription.LocalInertia.InverseMass = 1f / mass; + bodyDescription.LocalInertia.InverseInertiaTensor = default; + } + else if (useShape is BepuPhysics.Collidables.Mesh m) + { + m.ComputeInertia(mass, out bodyDescription.LocalInertia); + } if (CheckCurrentValid()) { From cf9bb064ba97091bcad3dcdaf904028ef54ad349 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 2 Jan 2020 11:03:35 -0500 Subject: [PATCH 0583/2038] Physics: better defaults and processing to reduce default bounciness --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 2 +- sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 2 +- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index e1da51ff29..afadd3a367 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -138,7 +138,7 @@ public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool /// optional rotation for each public static void GenerateStaticComponents(Entity e, List shapes, List offsets = null, List rotations = null, CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroupFlags collidesWith = CollisionFilterGroupFlags.AllFilter, - float FrictionCoefficient = 0.5f, float MaximumRecoverableVelocity = 3f, SpringSettings? springSettings = null) + float FrictionCoefficient = 0.5f, float MaximumRecoverableVelocity = 2f, SpringSettings? springSettings = null) { for (int i=0; i(int workerIndex, Collidab BepuPhysicsComponent a = getFromReference(pair.A); BepuPhysicsComponent b = getFromReference(pair.B); pairMaterial.FrictionCoefficient = a.FrictionCoefficient * b.FrictionCoefficient; - pairMaterial.MaximumRecoveryVelocity = a.MaximumRecoveryVelocity * b.MaximumRecoveryVelocity; - pairMaterial.SpringSettings = a.SpringSettings; + pairMaterial.MaximumRecoveryVelocity = (a.MaximumRecoveryVelocity + b.MaximumRecoveryVelocity) * 0.5f; + pairMaterial.SpringSettings.AngularFrequency = (a.SpringSettings.AngularFrequency + b.SpringSettings.AngularFrequency) * 0.5f; + pairMaterial.SpringSettings.TwiceDampingRatio = (a.SpringSettings.TwiceDampingRatio + b.SpringSettings.TwiceDampingRatio) * 0.5f; if (((uint)a.CanCollideWith & (uint)b.CollisionGroup) != 0) { RecordContact(a, b, manifold); From 0641371420a6c82c2c852f950ef59bd63c299223 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 3 Jan 2020 14:46:29 -0500 Subject: [PATCH 0584/2038] Physics: more reliable adding/removing/reusing physics objects also added experimental "debug shape" bounding box helper --- .../Bepu/BepuPhysicsComponent.cs | 60 ++++++++++ .../Bepu/BepuRigidbodyComponent.cs | 69 ++++++------ .../Xenko.Physics/Bepu/BepuSimulation.cs | 106 ++++++++---------- .../Bepu/BepuStaticColliderComponent.cs | 14 ++- sources/engine/Xenko.Physics/PhysicsSystem.cs | 19 ++-- 5 files changed, 160 insertions(+), 108 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 7a0a1e94ad..4874bc3595 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -15,10 +15,15 @@ using Xenko.Core.Mathematics; using Xenko.Core.MicroThreading; using Xenko.Engine.Design; +using Xenko.Extensions; +using Xenko.Games; +using Xenko.Graphics.GeometricPrimitives; using Xenko.Physics; using Xenko.Physics.Bepu; using Xenko.Physics.Engine; using Xenko.Rendering; +using Xenko.Rendering.Materials; +using Xenko.Rendering.Materials.ComputeColors; namespace Xenko.Engine { @@ -163,5 +168,60 @@ internal virtual bool CheckCurrentValid() /// [DataMember] public bool GhostBody { get; set; } + + private static Material debugShapeMaterial; + private static Xenko.Rendering.Mesh cubeMesh; + + public Entity GenerateDebugColliderEntity() + { + System.Numerics.Vector3 min, max; + if (ColliderShape is IConvexShape ics) + { + ics.ComputeBounds(BepuHelpers.ToBepu(Quaternion.Identity), out min, out max); + } + else if (ColliderShape is BepuPhysics.Collidables.Mesh cm) + { + cm.ComputeBounds(BepuHelpers.ToBepu(Quaternion.Identity), out min, out max); + } + else return null; + + Vector3 centerOffset = BepuHelpers.ToXenko(max + min) * 0.5f; + + Game g = ServiceRegistry.instance.GetService() as Game; + + if (debugShapeMaterial == null) + { + var materialDescription = new MaterialDescriptor + { + Attributes = + { + DiffuseModel = new MaterialDiffuseLambertModelFeature(), + Diffuse = new MaterialDiffuseMapFeature(new ComputeColor { Key = MaterialKeys.DiffuseValue }) + } + }; + + debugShapeMaterial = Material.New(g.GraphicsDevice, materialDescription); + debugShapeMaterial.Passes[0].Parameters.Set(MaterialKeys.DiffuseValue, Color.Red); + + var meshDraw = GeometricPrimitive.Cube.New(g.GraphicsDevice, Vector3.One).ToMeshDraw(); + + cubeMesh = new Rendering.Mesh { Draw = meshDraw }; + } + + Entity e = new Entity(Entity.Name + "-physicsBB"); + + Model m = new Model(); + m.Add(debugShapeMaterial); + m.Meshes.Add(cubeMesh); + + ModelComponent mc = e.GetOrCreate(); + mc.Model = m; + + e.Transform.Scale = new Vector3(max.X - min.X, max.Y - min.Y, max.Z - min.Z); + e.Transform.Position = Position + centerOffset; + e.Transform.Rotation = Rotation; + + return e; + } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index bc052ed0dc..5b1bb3c3eb 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -262,7 +262,7 @@ public bool RotationLock _rotationLock = value; - UpdateInertia(newShape ?? ColliderShape); + UpdateInertia(); } } @@ -291,17 +291,17 @@ public float Mass mass = value; - UpdateInertia(newShape ?? ColliderShape); + UpdateInertia(); } } - private void UpdateInertia(IShape useShape) + private void UpdateInertia() { if (type == RigidBodyTypes.Kinematic) { bodyDescription.LocalInertia = KinematicInertia; } - else if (useShape is IConvexShape ics && !_rotationLock) + else if (ColliderShape is IConvexShape ics && !_rotationLock) { ics.ComputeInertia(mass, out bodyDescription.LocalInertia); } @@ -310,7 +310,7 @@ private void UpdateInertia(IShape useShape) bodyDescription.LocalInertia.InverseMass = 1f / mass; bodyDescription.LocalInertia.InverseInertiaTensor = default; } - else if (useShape is BepuPhysics.Collidables.Mesh m) + else if (ColliderShape is BepuPhysics.Collidables.Mesh m) { m.ComputeInertia(mass, out bodyDescription.LocalInertia); } @@ -321,16 +321,6 @@ private void UpdateInertia(IShape useShape) } } - [DataMemberIgnore] - internal IShape newShape; - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal void swapNewShape() - { - base.ColliderShape = newShape; - newShape = null; - } - [DataMemberIgnore] public override IShape ColliderShape { @@ -339,29 +329,32 @@ public override IShape ColliderShape { if (value == null || value == ColliderShape) return; - newShape = null; - - if (AddedToScene) + if (AddedToScene && ColliderShape != null) { - if (ColliderShape != null) - { - newShape = value; - } - else + base.ColliderShape = value; + + BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue((time) => { - base.ColliderShape = value; - } + // first check if we are removing this when we get here... if so, don't change shape + if (BepuSimulation.instance.ToBeRemoved.Contains(this)) return; + + // remove the old shape + BepuSimulation.instance.internalSimulation.Shapes.Remove(bodyDescription.Collidable.Shape); - // remove and readd me to update shape - BepuSimulation.instance.ToBeRemoved.Enqueue(this); - BepuSimulation.instance.ToBeAdded.Enqueue(this); + // add the new shape + TypedIndex ti = ColliderShape.AddToShapes(BepuSimulation.instance.internalSimulation.Shapes); + bodyDescription.Collidable = new CollidableDescription(ti, 0.1f); + + // set it to the internalbody + InternalBody.SetShape(ti); + }); } else { base.ColliderShape = value; } - UpdateInertia(newShape ?? base.ColliderShape); + UpdateInertia(); } } @@ -431,7 +424,7 @@ public RigidBodyTypes RigidBodyType { type = value; - UpdateInertia(newShape ?? ColliderShape); + UpdateInertia(); } } @@ -448,8 +441,6 @@ public override bool AddedToScene } set { - if (AddedToScene == value) return; - if (ColliderShape == null) throw new InvalidOperationException(Entity.Name + " has no ColliderShape, can't be added!"); @@ -458,13 +449,19 @@ public override bool AddedToScene if (value) { - Mass = mass; - RigidBodyType = type; - BepuSimulation.instance.ToBeAdded.Enqueue(this); + lock (BepuSimulation.instance.ToBeAdded) + { + BepuSimulation.instance.ToBeAdded.Add(this); + BepuSimulation.instance.ToBeRemoved.Remove(this); + } } else { - BepuSimulation.instance.ToBeRemoved.Enqueue(this); + lock (BepuSimulation.instance.ToBeAdded) + { + BepuSimulation.instance.ToBeRemoved.Add(this); + BepuSimulation.instance.ToBeAdded.Remove(this); + } } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 5c7d56f366..944dc67695 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -35,7 +35,7 @@ public class BepuSimulation : IDisposable public BepuPhysics.Simulation internalSimulation; - internal ConcurrentQueue ToBeAdded = new ConcurrentQueue(), ToBeRemoved = new ConcurrentQueue(); + internal HashSet ToBeAdded = new HashSet(), ToBeRemoved = new HashSet(); public ReaderWriterLockSlim simulationLocker { get; private set; } = new ReaderWriterLockSlim(); @@ -411,83 +411,69 @@ public void Dispose() internal void ProcessAdds() { - while (ToBeAdded.Count > 0) + foreach (BepuPhysicsComponent component in ToBeAdded) { - if (ToBeAdded.TryDequeue(out var component)) + if (component.AddedHandle > -1) continue; // already added + if (component is BepuStaticColliderComponent scc) { - if (component.AddedHandle > -1) continue; // already added - if (component is BepuStaticColliderComponent scc) + using (simulationLocker.WriteLock()) { - using (simulationLocker.WriteLock()) - { - scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation); - scc.AddedHandle = internalSimulation.Statics.Add(scc.staticDescription); - StaticMappings[scc.AddedHandle] = scc; - } + scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation); + scc.AddedHandle = internalSimulation.Statics.Add(scc.staticDescription); + StaticMappings[scc.AddedHandle] = scc; } - else if (component is BepuRigidbodyComponent rigidBody) + } + else if (component is BepuRigidbodyComponent rigidBody) + { + using (simulationLocker.WriteLock()) { - using (simulationLocker.WriteLock()) - { - if (rigidBody.newShape != null) - { - TypedIndex ti = rigidBody.newShape.AddToShapes(internalSimulation.Shapes); - rigidBody.bodyDescription.Collidable = new CollidableDescription(ti, 0.1f); - rigidBody.InternalBody.SetShape(ti); - rigidBody.swapNewShape(); - } - else - { - rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); - } - AllRigidbodies.Add(rigidBody); - rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); - RigidMappings[rigidBody.AddedHandle] = rigidBody; - } - rigidBody.SleepThreshold = rigidBody.bodyDescription.Activity.SleepThreshold; - rigidBody.CcdMotionThreshold = rigidBody.bodyDescription.Collidable.Continuity.SweepConvergenceThreshold; + rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + AllRigidbodies.Add(rigidBody); + rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); + RigidMappings[rigidBody.AddedHandle] = rigidBody; } - component.Position = component.Entity.Transform.WorldPosition(); - component.Rotation = component.Entity.Transform.WorldRotation(); - } + rigidBody.SleepThreshold = rigidBody.bodyDescription.Activity.SleepThreshold; + rigidBody.CcdMotionThreshold = rigidBody.bodyDescription.Collidable.Continuity.SweepConvergenceThreshold; + } + component.Position = component.Entity.Transform.WorldPosition(); + component.Rotation = component.Entity.Transform.WorldRotation(); } + ToBeAdded.Clear(); } internal void ProcessRemovals() { - while (ToBeRemoved.Count > 0) + foreach (BepuPhysicsComponent component in ToBeRemoved) { - if (ToBeRemoved.TryDequeue(out var component)) + int addedIndex = component.AddedHandle; + if (addedIndex == -1) continue; // already removed + if (component is BepuStaticColliderComponent scc) + { + using(simulationLocker.WriteLock()) + { + scc.AddedHandle = -1; + internalSimulation.Statics.Remove(addedIndex); + StaticMappings.Remove(addedIndex); + } + } + else if (component is BepuRigidbodyComponent rigidBody) { - int addedIndex = component.AddedHandle; - if (addedIndex == -1) continue; // already removed - if (component is BepuStaticColliderComponent scc) + using(simulationLocker.WriteLock()) { - using(simulationLocker.WriteLock()) - { - scc.AddedHandle = -1; - internalSimulation.Statics.Remove(addedIndex); - StaticMappings.Remove(addedIndex); - } - } - else if (component is BepuRigidbodyComponent rigidBody) + rigidBody.AddedHandle = -1; + internalSimulation.Bodies.Remove(addedIndex); + RigidMappings.Remove(addedIndex); + AllRigidbodies.Remove(rigidBody); + } + + if (rigidBody.processingPhysicalContacts != null) { - using(simulationLocker.WriteLock()) - { - rigidBody.AddedHandle = -1; - internalSimulation.Bodies.Remove(addedIndex); - RigidMappings.Remove(addedIndex); - AllRigidbodies.Remove(rigidBody); - } - - if (rigidBody.processingPhysicalContacts != null) - { - for (int i = 0; i < rigidBody.processingPhysicalContacts.Length; i++) - rigidBody.processingPhysicalContacts[i].Clear(); - } + for (int i = 0; i < rigidBody.processingPhysicalContacts.Length; i++) + rigidBody.processingPhysicalContacts[i].Clear(); } } } + ToBeRemoved.Clear(); } struct RayHitClosestHandler : IRayHitHandler diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index cf3e24a425..dce3490660 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -96,8 +96,6 @@ public override bool AddedToScene } set { - if (AddedToScene == value) return; - if (ColliderShape == null) throw new InvalidOperationException(Entity.Name + " has no ColliderShape, can't be added!"); @@ -106,11 +104,19 @@ public override bool AddedToScene if (value) { - BepuSimulation.instance.ToBeAdded.Enqueue(this); + lock (BepuSimulation.instance.ToBeAdded) + { + BepuSimulation.instance.ToBeAdded.Add(this); + BepuSimulation.instance.ToBeRemoved.Remove(this); + } } else { - BepuSimulation.instance.ToBeRemoved.Enqueue(this); + lock (BepuSimulation.instance.ToBeAdded) + { + BepuSimulation.instance.ToBeAdded.Remove(this); + BepuSimulation.instance.ToBeRemoved.Add(this); + } } } } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index 1d57e42bd0..939404e808 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -157,18 +157,21 @@ private void RunPhysicsSimulation(float time) if (physicsScene.BepuSimulation != null) { - // do anything before simulation + // do anything before simulation (which might modify ToBeAdded or ToBeRemoved) while (physicsScene.BepuSimulation.ActionsBeforeSimulationStep.TryDequeue(out Action a)) a(time); - // remove all bodies set to be removed - physicsScene.BepuSimulation.ProcessRemovals(); + lock (physicsScene.BepuSimulation.ToBeAdded) + { + // remove all bodies set to be removed + physicsScene.BepuSimulation.ProcessRemovals(); - // did we request a clear? - int clearMode = physicsScene.BepuSimulation.clearRequested; - if (clearMode > 0) physicsScene.BepuSimulation.Clear(clearMode == 2, true); + // did we request a clear? + int clearMode = physicsScene.BepuSimulation.clearRequested; + if (clearMode > 0) physicsScene.BepuSimulation.Clear(clearMode == 2, true); - // add everyone waiting (which could have been something just removed) - physicsScene.BepuSimulation.ProcessAdds(); + // add everyone waiting (which could have been something just removed) + physicsScene.BepuSimulation.ProcessAdds(); + } if (Simulation.DisableSimulation == false) { From a2e6bd066d0c72191643655790a586dbab5042dd Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 13:02:49 -0500 Subject: [PATCH 0585/2038] Update README.md --- README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/README.md b/README.md index 38847009be..b8366374ea 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,31 @@ Xenko comes with an editor that allows you create and manage the content of your To learn more about Xenko, visit [xenko.com](https://xenko.com/). +## Why this fork? + +My games require the engine to be developed at a faster pace than Xenko. I'm in need of fixes, new features and better performance. These changes will not be supported by the core team, and the absolute most recent changes may not be fully stable. However, you may find them very helpful, and in some cases, essential to projects. + +## What is different? + +Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. + +* Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. +* Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. +* BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. +* Ease of use: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. +* Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors or rendering 3D text from multiple cameras. +* EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). +* UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). +* ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). +* More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. +* Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. +* Easy generating procedural meshes: StagedMeshDraw takes a list of verticies and indicies, no "buffer binding" or "GraphicsDevice" needed. Also will actually upload the mesh when it tries to get rendered automatically, saving time and resources if the mesh doesn't actually ever get viewed. +* Less likely to lose work: files are not actually deleted from GameStudio, just moved to the Recylce Bin. +* Performance: lots of tweaks have been made throughout the engine to maximize performance. This includes reducing locks and enumeration reduction, for example. +* Includes dfkeenan's toolkit designed for this fork (from https://github.com/dfkeenan/XenkoToolkit). May need to add the Toolkit Nuget package to use. +* Takes good things from many different Xenko forks, including the original Xenko branch when it gets updated. May not get everything, like some of the tutorials, sample, non-PC platforms or launcher updates, which I don't maintain. +* Probably lots of other stuff: haven't kept that great of track of improvements, I usually fix things as needed and keep moving forward! + ## License Focus is covered by [MIT](LICENSE.md), unless stated otherwise (i.e. for some files that are copied from other projects). From 7869140ca534b8da2c7d933ddce90139a8223cd9 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 13:11:50 -0500 Subject: [PATCH 0586/2038] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b8366374ea..12fc165dbc 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Welcome to the Focus Engine source code repository! Focus is an open-source C# game engine for realistic rendering and VR based off of Xenko. You'll still see "Xenko" in many places. The engine is highly modular and aims at giving game makers more flexibility in their development. -Xenko comes with an editor that allows you create and manage the content of your games or applications in a visual and intuitive way. +Focus comes with an editor that allows you create and manage the content of your games or applications in a visual and intuitive way. ![Focus Game Studio](https://xenko.com/images/external/script-editor.png) @@ -26,6 +26,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors or rendering 3D text from multiple cameras. * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). +* UI Text features: vertically align text or use tags to dynamically change text colors. Use
tags to have multiline text set straight from GameStudio. * ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). * More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. * Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. From 562deb5b72e66473dcca6d351575c13698ae1ad4 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 13:15:33 -0500 Subject: [PATCH 0587/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 12fc165dbc..3661dfedff 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors or rendering 3D text from multiple cameras. * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). -* UI Text features: vertically align text or use tags to dynamically change text colors. Use
tags to have multiline text set straight from GameStudio. +* UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. * ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). * More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. * Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. From a6275622950ac5b514de60080d263e6ab8998ec4 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 13:18:57 -0500 Subject: [PATCH 0588/2038] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 3661dfedff..4413f2ee04 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Performance: lots of tweaks have been made throughout the engine to maximize performance. This includes reducing locks and enumeration reduction, for example. * Includes dfkeenan's toolkit designed for this fork (from https://github.com/dfkeenan/XenkoToolkit). May need to add the Toolkit Nuget package to use. * Takes good things from many different Xenko forks, including the original Xenko branch when it gets updated. May not get everything, like some of the tutorials, sample, non-PC platforms or launcher updates, which I don't maintain. +* Simple binary distribution: No launcher needed. Just download and run the latest release (after making sure you have all of the Visual Studio build prerequisites, see https://github.com/phr00t/FocusEngine/releases. * Probably lots of other stuff: haven't kept that great of track of improvements, I usually fix things as needed and keep moving forward! ## License From 65a145fa114d351c4b0840ebaf165309205b2997 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 13:20:46 -0500 Subject: [PATCH 0589/2038] Update README.md --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 4413f2ee04..ed84573800 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ Find explanations and information about Xenko: Ask for help or report issues: * [Chat with the community on Discord](https://discord.gg/f6aerfE) [![Join the chat at https://discord.gg/f6aerfE](https://img.shields.io/discord/500285081265635328.svg?style=flat&logo=discord&label=discord)](https://discord.gg/f6aerfE) * [Discuss topics on our forums](http://forums.xenko.com/) -* [Report engine issues](https://github.com/xenko3d/xenko/issues) +* [Report engine issues](https://github.com/phr00t/xenko/issues) * [Donate to support the project](https://www.patreon.com/phr00tssoftware) ## Building from source @@ -78,7 +78,3 @@ Ask for help or report issues: 1. Clone Focus: `git clone https://github.com/phr00t/FocusEngine.git` 2. Run `\build\Xenko.PCPlatforms.bat`, which starts Visual Studio 2019, and build. - -### Contribution Guidelines - -Please check our [Contributing Guidelines](docs/CONTRIBUTING.md). From c06320c8957141477fdce5709c7a815ad6aa4422 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 13:23:29 -0500 Subject: [PATCH 0590/2038] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ed84573800..56e403a47a 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Easy generating procedural meshes: StagedMeshDraw takes a list of verticies and indicies, no "buffer binding" or "GraphicsDevice" needed. Also will actually upload the mesh when it tries to get rendered automatically, saving time and resources if the mesh doesn't actually ever get viewed. * Less likely to lose work: files are not actually deleted from GameStudio, just moved to the Recylce Bin. * Performance: lots of tweaks have been made throughout the engine to maximize performance. This includes reducing locks and enumeration reduction, for example. +* Easy adding/removing entities from the scene: Just do myEntity.Scene = myScene (to add it) or myEntity.Scene = null (to remove it). * Includes dfkeenan's toolkit designed for this fork (from https://github.com/dfkeenan/XenkoToolkit). May need to add the Toolkit Nuget package to use. * Takes good things from many different Xenko forks, including the original Xenko branch when it gets updated. May not get everything, like some of the tutorials, sample, non-PC platforms or launcher updates, which I don't maintain. * Simple binary distribution: No launcher needed. Just download and run the latest release (after making sure you have all of the Visual Studio build prerequisites, see https://github.com/phr00t/FocusEngine/releases. From 039162ea95a01e73543183cb89dae77c14accfbe Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 15:14:16 -0500 Subject: [PATCH 0591/2038] Physics: add maximum time to simulate per frame option, defaults to 0.5 seconds --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 4 ++- .../engine/Xenko.Physics/PhysicsSettings.cs | 6 ++++ sources/engine/Xenko.Physics/PhysicsSystem.cs | 28 +++++++++++++------ 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 944dc67695..5b688b5812 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -41,6 +41,8 @@ public class BepuSimulation : IDisposable public ConcurrentQueue> ActionsBeforeSimulationStep = new ConcurrentQueue>(); + public static float TimeScale = 1f; + private static BepuSimulation _instance; public static BepuSimulation instance { @@ -881,7 +883,7 @@ internal void Simulate(float deltaTime) using (BepuSimulation.instance.simulationLocker.ReadLock()) { - internalSimulation.Timestep(deltaTime, threadDispatcher); + internalSimulation.Timestep(deltaTime * TimeScale, threadDispatcher); } } } diff --git a/sources/engine/Xenko.Physics/PhysicsSettings.cs b/sources/engine/Xenko.Physics/PhysicsSettings.cs index d9ca14b697..0279c5b421 100644 --- a/sources/engine/Xenko.Physics/PhysicsSettings.cs +++ b/sources/engine/Xenko.Physics/PhysicsSettings.cs @@ -24,5 +24,11 @@ public class PhysicsSettings : Configuration /// [DataMember(30)] public float FixedTimeStep = 1.0f / 60.0f; + + /// + /// Default maximum time to simulate per frame. + /// + [DataMember] + public float MaxSimulationTime = 0.5f; } } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index 939404e808..f8e35361d0 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -26,7 +26,7 @@ private class PhysicsScene private ManualResetEventSlim doUpdateEvent; private Thread physicsThread; - public static float TimeScale = 1f; + public static float MaximumSimulationTime = 0.5f; private readonly List scenes = new List(); @@ -52,6 +52,8 @@ public override void Initialize() { physicsConfiguration = Game?.Settings != null ? Game.Settings.Configurations.Get() : new PhysicsSettings(); + MaximumSimulationTime = physicsConfiguration.MaxSimulationTime; + if (isMultithreaded) { doUpdateEvent = new ManualResetEventSlim(false); @@ -201,12 +203,13 @@ private void PhysicsProcessingThreadBody() { while (runThread) { - if (doUpdateEvent.Wait(1000) && timeToSimulate > 0f) - { + if (doUpdateEvent.Wait(1000)) { float simulateThisInterval = timeToSimulate; - timeToSimulate -= simulateThisInterval; - - RunPhysicsSimulation(simulateThisInterval); + if (simulateThisInterval > 0f) + { + timeToSimulate -= simulateThisInterval; + RunPhysicsSimulation(simulateThisInterval); + } } doUpdateEvent.Reset(); @@ -217,12 +220,21 @@ public override void Update(GameTime gameTime) { if (isMultithreaded) { - timeToSimulate += (float)gameTime.Elapsed.TotalSeconds * TimeScale; + float gt = (float)gameTime.Elapsed.TotalSeconds; + if (timeToSimulate + gt > MaximumSimulationTime) + { + timeToSimulate = MaximumSimulationTime; + } + else + { + timeToSimulate += gt; + } + doUpdateEvent.Set(); } else { - RunPhysicsSimulation((float)gameTime.Elapsed.TotalSeconds * TimeScale); + RunPhysicsSimulation((float)Math.Min(MaximumSimulationTime, gameTime.Elapsed.TotalSeconds)); } } } From 6c2da1d9c3d27ebc9b51899f9f3eab25faf804ed Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 21:46:12 -0500 Subject: [PATCH 0592/2038] Physics: get shape from entity now supports being offset by center --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 62 ++++++++++++------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index afadd3a367..1c8a6e4a62 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -41,20 +41,25 @@ public static void AssureBepuSystemCreated() } } - private static Vector3 getBounds(Entity e) + private static Vector3 getBounds(Entity e, out Vector3 center) { ModelComponent mc = e.Get(); - if (mc == null || mc.Model == null || mc.Model.Meshes.Count < 0f) return Vector3.Zero; + center = new Vector3(); + if (mc == null || mc.Model == null || mc.Model.Meshes.Count <= 0f) return Vector3.Zero; - Vector3 biggest = Vector3.Zero; - for (int i=0; i biggest.X) biggest.X = extent.X; if (extent.Y > biggest.Y) biggest.Y = extent.Y; if (extent.Z > biggest.Z) biggest.Z = extent.Z; + center += bb.Center; } + center /= count; return biggest * e.Transform.WorldScale(); } @@ -89,7 +94,7 @@ public static bool SanityCheckShape(IShape shape) return shape != null; } - public static IShape OffsetSingleShape(IConvexShape shape, Vector3? offset = null, Quaternion? rotation = null) + public static IShape OffsetSingleShape(IConvexShape shape, Vector3? offset = null, Quaternion? rotation = null, bool kinematic = false) { if (offset.HasValue == false && rotation.HasValue == false) return shape; @@ -97,36 +102,49 @@ public static IShape OffsetSingleShape(IConvexShape shape, Vector3? offset = nul using (var compoundBuilder = new CompoundBuilder(BepuSimulation.safeBufferPool, BepuSimulation.instance.internalSimulation.Shapes, 1)) { - compoundBuilder.AddForKinematicEasy(shape, new BepuPhysics.RigidPose(ToBepu(offset ?? Vector3.Zero), ToBepu(rotation ?? Quaternion.Identity)), 1f); - - compoundBuilder.BuildKinematicCompound(out var children); + if (kinematic) + { + compoundBuilder.AddForKinematicEasy(shape, new BepuPhysics.RigidPose(ToBepu(offset ?? Vector3.Zero), ToBepu(rotation ?? Quaternion.Identity)), 1f); + } + else + { + compoundBuilder.AddEasy(shape, new BepuPhysics.RigidPose(ToBepu(offset ?? Vector3.Zero), ToBepu(rotation ?? Quaternion.Identity)), 1f); + } - return new Compound(children); + return compoundBuilder.BuildCompleteCompoundShape(BepuSimulation.instance.internalSimulation.Shapes, BepuSimulation.safeBufferPool, kinematic); } } - public static Box GenerateBoxOfEntity(Entity e, float scale = 1f) + public static IShape GenerateBoxOfEntity(Entity e, float scale = 1f, bool allowOffsetCompound = true) { - Vector3 b = getBounds(e) * scale * 2f; - return new Box(b.X, b.Y, b.Z); + Vector3 b = getBounds(e, out Vector3 center) * scale * 2f; + var box = new Box(b.X, b.Y, b.Z); + if (allowOffsetCompound && center.LengthSquared() > 0.01f) return OffsetSingleShape(box, center); + return box; } - public static Sphere GenerateSphereOfEntity(Entity e, float scale = 1f) + public static IShape GenerateSphereOfEntity(Entity e, float scale = 1f, bool allowOffsetCompound = true) { - Vector3 b = getBounds(e); - return new Sphere(Math.Max(b.Z, Math.Max(b.X, b.Y)) * scale); + Vector3 b = getBounds(e, out Vector3 center); + var box = new Sphere(Math.Max(b.Z, Math.Max(b.X, b.Y)) * scale); + if (allowOffsetCompound && center.LengthSquared() > 0.01f) return OffsetSingleShape(box, center); + return box; } - public static Capsule GenerateCapsuleOfEntity(Entity e, float scale = 1f, bool XZradius = true) + public static IShape GenerateCapsuleOfEntity(Entity e, float scale = 1f, bool XZradius = true, bool allowOffsetCompound = true) { - Vector3 b = getBounds(e) * scale; - return XZradius ? new Capsule(Math.Max(b.X, b.Z), b.Y * 2f) : new Capsule(b.Y, 2f * Math.Max(b.X, b.Z)); + Vector3 b = getBounds(e, out Vector3 center) * scale; + var box = XZradius ? new Capsule(Math.Max(b.X, b.Z), b.Y * 2f) : new Capsule(b.Y, 2f * Math.Max(b.X, b.Z)); + if (allowOffsetCompound && center.LengthSquared() > 0.01f) return OffsetSingleShape(box, center); + return box; } - public static Cylinder GenerateCylinderOfEntity(Entity e, float scale = 1f, bool XZradius = true) + public static IShape GenerateCylinderOfEntity(Entity e, float scale = 1f, bool XZradius = true, bool allowOffsetCompound = true) { - Vector3 b = getBounds(e) * scale; - return XZradius ? new Cylinder(Math.Max(b.X, b.Z), b.Y * 2f) : new Cylinder(b.Y, 2f * Math.Max(b.X, b.Z)); + Vector3 b = getBounds(e, out Vector3 center) * scale; + var box = XZradius ? new Cylinder(Math.Max(b.X, b.Z), b.Y * 2f) : new Cylinder(b.Y, 2f * Math.Max(b.X, b.Z)); + if (allowOffsetCompound && center.LengthSquared() > 0.01f) return OffsetSingleShape(box, center); + return box; } /// From 6181b44c49edb09501ec04eaf695d42db5f91f7f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 21:47:15 -0500 Subject: [PATCH 0593/2038] Physics: fixes to the debug bounding box shape function --- .../engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 4874bc3595..740f2256fe 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -172,7 +172,7 @@ internal virtual bool CheckCurrentValid() private static Material debugShapeMaterial; private static Xenko.Rendering.Mesh cubeMesh; - public Entity GenerateDebugColliderEntity() + public Entity AttachDebugShapeAsChild() { System.Numerics.Vector3 min, max; if (ColliderShape is IConvexShape ics) @@ -217,9 +217,10 @@ public Entity GenerateDebugColliderEntity() ModelComponent mc = e.GetOrCreate(); mc.Model = m; - e.Transform.Scale = new Vector3(max.X - min.X, max.Y - min.Y, max.Z - min.Z); - e.Transform.Position = Position + centerOffset; - e.Transform.Rotation = Rotation; + e.Transform.Scale = new Vector3(max.X - min.X, max.Y - min.Y, max.Z - min.Z) / Entity.Transform.WorldScale(); + e.Transform.Position = centerOffset / Entity.Transform.WorldScale(); + if (this is BepuRigidbodyComponent rb && rb.IgnorePhysicsRotation) e.Transform.Rotation = Rotation; + e.Transform.Parent = Entity.Transform; return e; } From a591add77b398b6f494d50344b9b184e5e2fd901 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 4 Jan 2020 21:47:50 -0500 Subject: [PATCH 0594/2038] Physics: expose SpeculativeMargin bepuphysics property --- .../Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 6 ++++++ .../Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 15 ++++++++++++++- .../engine/Xenko.Physics/Bepu/BepuSimulation.cs | 4 ++-- .../Bepu/BepuStaticColliderComponent.cs | 13 +++++++++++++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 740f2256fe..84bb045dd7 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -169,6 +169,12 @@ internal virtual bool CheckCurrentValid() [DataMember] public bool GhostBody { get; set; } + /// + /// How much ahead-of-time to look for contacts? Defaults to 0.1 + /// + [DataMember] + virtual public float SpeculativeMargin { get; set; } = 0.1f; + private static Material debugShapeMaterial; private static Xenko.Rendering.Mesh cubeMesh; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 5b1bb3c3eb..030fa00500 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -321,6 +321,19 @@ private void UpdateInertia() } } + [DataMember] + public override float SpeculativeMargin + { + get => base.SpeculativeMargin; + set + { + base.SpeculativeMargin = value; + + if (CheckCurrentValid()) + InternalBody.Collidable.SpeculativeMargin = value; + } + } + [DataMemberIgnore] public override IShape ColliderShape { @@ -343,7 +356,7 @@ public override IShape ColliderShape // add the new shape TypedIndex ti = ColliderShape.AddToShapes(BepuSimulation.instance.internalSimulation.Shapes); - bodyDescription.Collidable = new CollidableDescription(ti, 0.1f); + bodyDescription.Collidable = new CollidableDescription(ti, SpeculativeMargin); // set it to the internalbody InternalBody.SetShape(ti); diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 5b688b5812..eaaea59d5b 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -420,7 +420,7 @@ internal void ProcessAdds() { using (simulationLocker.WriteLock()) { - scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation); + scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation, scc.SpeculativeMargin); scc.AddedHandle = internalSimulation.Statics.Add(scc.staticDescription); StaticMappings[scc.AddedHandle] = scc; } @@ -429,7 +429,7 @@ internal void ProcessAdds() { using (simulationLocker.WriteLock()) { - rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation); + rigidBody.bodyDescription.Collidable = rigidBody.ColliderShape.GenerateDescription(internalSimulation, rigidBody.SpeculativeMargin); AllRigidbodies.Add(rigidBody); rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); RigidMappings[rigidBody.AddedHandle] = rigidBody; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index dce3490660..05e88eb1a1 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -77,6 +77,19 @@ public override Xenko.Core.Mathematics.Quaternion Rotation } } + [DataMember] + public override float SpeculativeMargin + { + get => base.SpeculativeMargin; + set + { + base.SpeculativeMargin = value; + + if (CheckCurrentValid()) + InternalStatic.Collidable.SpeculativeMargin = value; + } + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal override bool CheckCurrentValid() { From 2207ae7adb7aaab24145e5844e80ec577b7d1192 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 5 Jan 2020 10:34:20 -0500 Subject: [PATCH 0595/2038] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 56e403a47a..09a92a3f6e 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,8 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * Ease of use: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors or rendering 3D text from multiple cameras. -* EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). +* CinematicAction: Simple system for performing cinematic actions on objects and calling functions at certain times. Can build a simple timeline for things to move, rotate and execute. See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs +* EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). * UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. * ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). From 3733b390cf5e8ece86b26dcb044181294a00ab7c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 5 Jan 2020 11:15:39 -0500 Subject: [PATCH 0596/2038] Physics: improve bullet error reporting for non-convex character shapes --- .../engine/Xenko.Physics/Elements/CharacterComponent.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs b/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs index f01befabd5..5eea214380 100644 --- a/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs +++ b/sources/engine/Xenko.Physics/Elements/CharacterComponent.cs @@ -239,6 +239,11 @@ public void SetVelocity(Vector3 velocity) protected override void OnAttach() { + BulletSharp.ConvexShape cshape = ColliderShape.InternalShape as BulletSharp.ConvexShape; + + if (cshape == null) + throw new ArgumentException(Entity.Name + " needs a convex shape for its CharacterComponent!"); + NativeCollisionObject = new BulletSharp.PairCachingGhostObject { CollisionShape = ColliderShape.InternalShape, @@ -255,7 +260,7 @@ protected override void OnAttach() NativeCollisionObject.ContactProcessingThreshold = !Simulation.CanCcd ? 1e18f : 1e30f; BulletSharp.Math.Vector3 unitY = new BulletSharp.Math.Vector3(0f, 1f, 0f); - KinematicCharacter = new BulletSharp.KinematicCharacterController((BulletSharp.PairCachingGhostObject)NativeCollisionObject, (BulletSharp.ConvexShape)ColliderShape.InternalShape, StepHeight, ref unitY); + KinematicCharacter = new BulletSharp.KinematicCharacterController((BulletSharp.PairCachingGhostObject)NativeCollisionObject, cshape, StepHeight, ref unitY); base.OnAttach(); From 7fc96379a803ef7f6117e78b6fb4537567e19b2a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 5 Jan 2020 11:20:39 -0500 Subject: [PATCH 0597/2038] Physics: add copies of debug and release bepu DLLs so devs can easily swap if needed --- deps/bepuphysics2/Debug/BepuPhysics.dll | 3 +++ deps/bepuphysics2/Debug/BepuPhysics.pdb | 3 +++ deps/bepuphysics2/Debug/BepuUtilities.dll | 3 +++ deps/bepuphysics2/Debug/BepuUtilities.pdb | 3 +++ deps/bepuphysics2/Release/BepuPhysics.dll | 3 +++ deps/bepuphysics2/Release/BepuPhysics.pdb | 3 +++ deps/bepuphysics2/Release/BepuUtilities.dll | 3 +++ deps/bepuphysics2/Release/BepuUtilities.pdb | 3 +++ 8 files changed, 24 insertions(+) create mode 100644 deps/bepuphysics2/Debug/BepuPhysics.dll create mode 100644 deps/bepuphysics2/Debug/BepuPhysics.pdb create mode 100644 deps/bepuphysics2/Debug/BepuUtilities.dll create mode 100644 deps/bepuphysics2/Debug/BepuUtilities.pdb create mode 100644 deps/bepuphysics2/Release/BepuPhysics.dll create mode 100644 deps/bepuphysics2/Release/BepuPhysics.pdb create mode 100644 deps/bepuphysics2/Release/BepuUtilities.dll create mode 100644 deps/bepuphysics2/Release/BepuUtilities.pdb diff --git a/deps/bepuphysics2/Debug/BepuPhysics.dll b/deps/bepuphysics2/Debug/BepuPhysics.dll new file mode 100644 index 0000000000..92963f7b54 --- /dev/null +++ b/deps/bepuphysics2/Debug/BepuPhysics.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40c886b90c58dffa07847b6449423d32580e406c4997a00ed500c27a42b44369 +size 811008 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.pdb b/deps/bepuphysics2/Debug/BepuPhysics.pdb new file mode 100644 index 0000000000..5a95dcbd0e --- /dev/null +++ b/deps/bepuphysics2/Debug/BepuPhysics.pdb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3034d312600d0ccb286f21a6b44c91c5ab96dc6670983135c18bf3d10509afc9 +size 401620 diff --git a/deps/bepuphysics2/Debug/BepuUtilities.dll b/deps/bepuphysics2/Debug/BepuUtilities.dll new file mode 100644 index 0000000000..247df3637e --- /dev/null +++ b/deps/bepuphysics2/Debug/BepuUtilities.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32c4db783dd1936c8d4ea236596e53c697f6a81fedfdf834651f894d239305a5 +size 150016 diff --git a/deps/bepuphysics2/Debug/BepuUtilities.pdb b/deps/bepuphysics2/Debug/BepuUtilities.pdb new file mode 100644 index 0000000000..3cfcf64a34 --- /dev/null +++ b/deps/bepuphysics2/Debug/BepuUtilities.pdb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:373ebad5e6a12de3573d2642837d607ab489c2be1d675c61bb341d666b9e3c44 +size 68484 diff --git a/deps/bepuphysics2/Release/BepuPhysics.dll b/deps/bepuphysics2/Release/BepuPhysics.dll new file mode 100644 index 0000000000..d9fc0deea6 --- /dev/null +++ b/deps/bepuphysics2/Release/BepuPhysics.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fde9f3f53b24e6bc79d6b63f548b341a686a1ee0b0e88bb0b7fd4530982e5041 +size 708608 diff --git a/deps/bepuphysics2/Release/BepuPhysics.pdb b/deps/bepuphysics2/Release/BepuPhysics.pdb new file mode 100644 index 0000000000..ac4367b79f --- /dev/null +++ b/deps/bepuphysics2/Release/BepuPhysics.pdb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c86085acd216d6d8b1da8829a8331b00535aa87c3ab32ef0ffd51e99be3d8952 +size 307432 diff --git a/deps/bepuphysics2/Release/BepuUtilities.dll b/deps/bepuphysics2/Release/BepuUtilities.dll new file mode 100644 index 0000000000..a2032b96bb --- /dev/null +++ b/deps/bepuphysics2/Release/BepuUtilities.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ac84baa3473b17780872f49177367a23b6e569e2b91e133f85bf210a5acc949 +size 126464 diff --git a/deps/bepuphysics2/Release/BepuUtilities.pdb b/deps/bepuphysics2/Release/BepuUtilities.pdb new file mode 100644 index 0000000000..bdcbe8f6e4 --- /dev/null +++ b/deps/bepuphysics2/Release/BepuUtilities.pdb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afb1853b76f3fbd9fc9e1455afb2280b4a7d3c0f52ec2f7cdaea195658b681a5 +size 51596 From 9c17a7324bedeef87ee36f470f301e0a66a9b813 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 7 Jan 2020 15:25:02 -0500 Subject: [PATCH 0598/2038] Physics: asynchronous processing changes + big mesh processing helpers --- deps/bepuphysics2/BepuPhysics.dll | 4 +- deps/bepuphysics2/BepuPhysics.pdb | 4 +- deps/bepuphysics2/Debug/BepuPhysics.dll | 4 +- deps/bepuphysics2/Debug/BepuPhysics.pdb | 4 +- deps/bepuphysics2/Release/BepuPhysics.dll | 4 +- deps/bepuphysics2/Release/BepuPhysics.pdb | 4 +- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 101 ++++++++++-- .../Bepu/BepuPhysicsComponent.cs | 12 -- .../Bepu/BepuRigidbodyComponent.cs | 144 ++++++++++-------- .../Xenko.Physics/Bepu/BepuSimulation.cs | 9 +- .../Bepu/BepuStaticColliderComponent.cs | 20 +-- sources/engine/Xenko.Physics/PhysicsSystem.cs | 1 - 12 files changed, 186 insertions(+), 125 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index d9fc0deea6..a03b571685 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fde9f3f53b24e6bc79d6b63f548b341a686a1ee0b0e88bb0b7fd4530982e5041 -size 708608 +oid sha256:db5d18c30b319d663a660c6b0fa4bb4c0fd0252f77594e399c04909225520425 +size 714240 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index ac4367b79f..2e37787389 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c86085acd216d6d8b1da8829a8331b00535aa87c3ab32ef0ffd51e99be3d8952 -size 307432 +oid sha256:c732eae915202c17c79c0367da9ecb579b5a2fcf8059d3f819be1f128768b559 +size 309228 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.dll b/deps/bepuphysics2/Debug/BepuPhysics.dll index 92963f7b54..45255e949a 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.dll +++ b/deps/bepuphysics2/Debug/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:40c886b90c58dffa07847b6449423d32580e406c4997a00ed500c27a42b44369 -size 811008 +oid sha256:9d5001dfc4427d2bdd6b0379111543f1c643db5fcf2c9bae994f694799f2860e +size 815104 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.pdb b/deps/bepuphysics2/Debug/BepuPhysics.pdb index 5a95dcbd0e..b8d502102b 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.pdb +++ b/deps/bepuphysics2/Debug/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3034d312600d0ccb286f21a6b44c91c5ab96dc6670983135c18bf3d10509afc9 -size 401620 +oid sha256:13917b9e6a0a63719b062f10ec7f124c6cc6c0515b9cb140f685858959420743 +size 404008 diff --git a/deps/bepuphysics2/Release/BepuPhysics.dll b/deps/bepuphysics2/Release/BepuPhysics.dll index d9fc0deea6..a03b571685 100644 --- a/deps/bepuphysics2/Release/BepuPhysics.dll +++ b/deps/bepuphysics2/Release/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:fde9f3f53b24e6bc79d6b63f548b341a686a1ee0b0e88bb0b7fd4530982e5041 -size 708608 +oid sha256:db5d18c30b319d663a660c6b0fa4bb4c0fd0252f77594e399c04909225520425 +size 714240 diff --git a/deps/bepuphysics2/Release/BepuPhysics.pdb b/deps/bepuphysics2/Release/BepuPhysics.pdb index ac4367b79f..2e37787389 100644 --- a/deps/bepuphysics2/Release/BepuPhysics.pdb +++ b/deps/bepuphysics2/Release/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c86085acd216d6d8b1da8829a8331b00535aa87c3ab32ef0ffd51e99be3d8952 -size 307432 +oid sha256:c732eae915202c17c79c0367da9ecb579b5a2fcf8059d3f819be1f128768b559 +size 309228 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 1c8a6e4a62..ac8cb37f12 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Text; +using System.Threading.Tasks; using BepuPhysics.Collidables; using BepuPhysics.Constraints; using Xenko.Core; @@ -257,15 +258,8 @@ public static void ClearSimulation(bool clearBuffers = true) BepuSimulation.instance.Clear(clearBuffers); } - /// - /// Generate a mesh collider from a given mesh. The mesh must have a readable buffer behind it to generate veriticies from - /// - /// Returns false if no mesh could be made - public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) + private static unsafe bool getMeshOutputs(Xenko.Rendering.Mesh modelMesh, out List positions, out List indicies) { - List positions; - List indicies; - if (modelMesh.Draw is StagedMeshDraw) { StagedMeshDraw smd = modelMesh.Draw as StagedMeshDraw; @@ -295,7 +289,8 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out } else { - outMesh = new Mesh(); + positions = null; + indicies = null; return false; } @@ -309,7 +304,8 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out if (buf == null || buf.VertIndexData == null || ibuf == null || ibuf.VertIndexData == null) { - outMesh = new Mesh(); + positions = null; + indicies = null; return false; } @@ -317,7 +313,8 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out out Vector3[] arraypositions, out Core.Mathematics.Vector3[] normals, out Core.Mathematics.Vector2[] uvs, out Color4[] colors, out Vector4[] tangents) == false) { - outMesh = new Mesh(); + positions = null; + indicies = null; return false; } @@ -354,9 +351,42 @@ public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out positions = new List(arraypositions); } + return true; + } + + /// + /// Generate a mesh collider from a given mesh. The mesh must have a readable buffer behind it to generate veriticies from + /// + /// Returns false if no mesh could be made + public static unsafe bool GenerateMeshShape(Xenko.Rendering.Mesh modelMesh, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) + { + if (getMeshOutputs(modelMesh, out var positions, out var indicies) == false) + { + outMesh = default; + return false; + } + return GenerateMeshShape(positions, indicies, out outMesh, scale); } + /// + /// Generate a mesh collider from a given mesh. The mesh must have a readable buffer behind it to generate veriticies from + /// + /// Returns false if no mesh could be made + public static unsafe bool GenerateBigMeshStaticColliders(Entity e, Xenko.Rendering.Mesh modelMesh, Vector3? scale = null, + CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroupFlags collidesWith = CollisionFilterGroupFlags.AllFilter, + float friction = 0.5f, float maximumRecoverableVelocity = 1f, SpringSettings? springSettings = null) + { + if (getMeshOutputs(modelMesh, out var positions, out var indicies) == false) + { + return false; + } + + GenerateBigMeshStaticColliders(e, positions, indicies, scale, group, collidesWith, friction, maximumRecoverableVelocity, springSettings); + + return true; + } + private static Dictionary BufferPoolMap = new Dictionary(); public static unsafe bool GenerateMeshShape(List positions, List indicies, out BepuPhysics.Collidables.Mesh outMesh, Vector3? scale = null) @@ -382,6 +412,55 @@ public static unsafe bool GenerateMeshShape(List positions, List i return true; } + public static unsafe void GenerateBigMeshStaticColliders(Entity e, List positions, List indicies, Vector3? scale = null, + CollisionFilterGroups group = CollisionFilterGroups.DefaultFilter, CollisionFilterGroupFlags collidesWith = CollisionFilterGroupFlags.AllFilter, + float friction = 0.5f, float maximumRecoverableVelocity = 1f, SpringSettings? springSettings = null) + { + // get a thread-safe buffer pool + var usePool = BepuSimulation.safeBufferPool; + + // ok, should have what we need to make triangles + int triangleCount = indicies.Count / 3; + usePool.Take(triangleCount, out BepuUtilities.Memory.Buffer triangles); + + for (int i = 0; i < triangleCount; i++) + { + int shiftedi = i * 3; + triangles[i].A = ToBepu(positions[indicies[shiftedi]]); + triangles[i].B = ToBepu(positions[indicies[shiftedi + 1]]); + triangles[i].C = ToBepu(positions[indicies[shiftedi + 2]]); + } + + List> meshBuffers = new List>(); + + int sliced = 0; + while (sliced < triangleCount) + { + int grablen = Math.Min(triangleCount / System.Environment.ProcessorCount, triangleCount - sliced); + meshBuffers.Add(triangles.Slice(sliced, grablen)); + sliced += grablen; + } + + // list of meshes to make static colliders with + List meshes = new List(); + + // dispatch buffers to be made into meshes + Xenko.Core.Threading.Dispatcher.For(0, meshBuffers.Count, (index) => + { + var pool = BepuSimulation.safeBufferPool; + var mesh = new Mesh(meshBuffers[index], new System.Numerics.Vector3(scale?.X ?? 1f, scale?.Y ?? 1f, scale?.Z ?? 1f), pool); + + lock (meshes) + { + meshes.Add(mesh); + BufferPoolMap[mesh] = pool; + } + }); + + // generate a static collider for every mesh on the list for the entity e + GenerateStaticComponents(e, meshes, null, null, group, collidesWith, friction, maximumRecoverableVelocity, springSettings); + } + /// /// Mesh had to have been made by BepuHelpers for the BufferPool to be tracked /// diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 84bb045dd7..1d13264dec 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -145,18 +145,6 @@ internal void DerivePhysicsTransform(Vector3? worldPosition, Matrix? worldRotati Matrix.Multiply(ref rotation, ref translationMatrix, out outMatrix); } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal virtual bool CheckCurrentValid() - { - if (AddedHandle == -1) return false; - ref var location = ref BepuSimulation.instance.internalSimulation.Bodies.HandleToLocation[AddedHandle]; - if (location.SetIndex < 0 || location.SetIndex >= BepuSimulation.instance.internalSimulation.Bodies.Sets.Length) return false; - ref var set = ref BepuSimulation.instance.internalSimulation.Bodies.Sets[location.SetIndex]; - if (location.Index < 0 || location.Index >= set.Count) return false; - if (set.IndexToHandle[location.Index] != AddedHandle) return false; - return true; - } - [DataMemberIgnore] public virtual Vector3 Position { get; set; } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 030fa00500..aafe50a980 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -15,6 +15,7 @@ using BepuPhysics.Collidables; using BepuPhysics.Constraints; using System.Runtime.CompilerServices; +using Xenko.Core.Threading; namespace Xenko.Physics.Bepu { @@ -31,18 +32,20 @@ public sealed class BepuRigidbodyComponent : BepuPhysicsComponent public BodyDescription bodyDescription; [DataMemberIgnore] - private BodyReference _internalReference = new BodyReference(); + private BodyReference _internalReference; /// /// Reference to the body after being added to the scene /// - public BodyReference InternalBody + public ref BodyReference InternalBody { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { _internalReference.Bodies = BepuSimulation.instance.internalSimulation.Bodies; _internalReference.Handle = AddedHandle; - return _internalReference; + + return ref _internalReference; } } @@ -61,17 +64,17 @@ public BodyReference InternalBody [DataMemberIgnore] public bool IsActive { - get => CheckCurrentValid() && InternalBody.Awake; + get + { + return AddedToScene && InternalBody.Awake; + } set { - if (CheckCurrentValid() == false || InternalBody.Awake == value) return; + if (IsActive == value) return; - BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue(delegate { - if (CheckCurrentValid()) - { - BodyReference ib = InternalBody; - ib.Awake = value; - } + BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue((time) => + { + InternalBody.Awake = value; }); } } @@ -88,12 +91,14 @@ public float CcdMotionThreshold } set { + if (bodyDescription.Collidable.Continuity.SweepConvergenceThreshold == value) return; + bodyDescription.Collidable.Continuity.SweepConvergenceThreshold = value; bodyDescription.Collidable.Continuity.Mode = value > 0 ? ContinuousDetectionMode.Continuous : ContinuousDetectionMode.Discrete; bodyDescription.Collidable.Continuity.MinimumSweepTimestep = value > 0 ? 1e-3f : 0f; - if (CheckCurrentValid()) - InternalBody.Collidable.Continuity = bodyDescription.Collidable.Continuity; + if (AddedToScene) + InternalBody.SetCollidable(bodyDescription.Collidable); } } @@ -233,10 +238,12 @@ public float SleepThreshold } set { + if (bodyDescription.Activity.SleepThreshold == value) return; + bodyDescription.Activity.SleepThreshold = value; - if (CheckCurrentValid()) - InternalBody.Activity.SleepThreshold = value; + if (AddedToScene) + InternalBody.SetActivity(bodyDescription.Activity); } } @@ -295,7 +302,7 @@ public float Mass } } - private void UpdateInertia() + private void UpdateInertia(bool skipset = false) { if (type == RigidBodyTypes.Kinematic) { @@ -315,22 +322,22 @@ private void UpdateInertia() m.ComputeInertia(mass, out bodyDescription.LocalInertia); } - if (CheckCurrentValid()) - { - InternalBody.SetLocalInertia(bodyDescription.LocalInertia); - } + if (skipset == false && AddedToScene) + InternalBody.LocalInertia = bodyDescription.LocalInertia; } [DataMember] public override float SpeculativeMargin { - get => base.SpeculativeMargin; + get => bodyDescription.Collidable.SpeculativeMargin; set { - base.SpeculativeMargin = value; + if (bodyDescription.Collidable.SpeculativeMargin == value) return; + + bodyDescription.Collidable.SpeculativeMargin = value; - if (CheckCurrentValid()) - InternalBody.Collidable.SpeculativeMargin = value; + if (AddedToScene) + InternalBody.SetCollidable(bodyDescription.Collidable); } } @@ -346,28 +353,35 @@ public override IShape ColliderShape { base.ColliderShape = value; + UpdateInertia(true); + BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue((time) => { - // first check if we are removing this when we get here... if so, don't change shape - if (BepuSimulation.instance.ToBeRemoved.Contains(this)) return; - - // remove the old shape - BepuSimulation.instance.internalSimulation.Shapes.Remove(bodyDescription.Collidable.Shape); - - // add the new shape - TypedIndex ti = ColliderShape.AddToShapes(BepuSimulation.instance.internalSimulation.Shapes); - bodyDescription.Collidable = new CollidableDescription(ti, SpeculativeMargin); - - // set it to the internalbody - InternalBody.SetShape(ti); + BepuSimulation bs = BepuSimulation.instance; + + // don't worry about switching if we are to be removed + if (bs.ToBeRemoved.Contains(this)) + return; + + using (bs.simulationLocker.WriteLock()) + { + // remove me with the old shape + bs.internalSimulation.Bodies.Remove(AddedHandle); + BepuSimulation.RigidMappings.Remove(AddedHandle); + + // add me with the new shape + bodyDescription.Collidable = ColliderShape.GenerateDescription(bs.internalSimulation, SpeculativeMargin); + AddedHandle = bs.internalSimulation.Bodies.Add(bodyDescription); + BepuSimulation.RigidMappings[AddedHandle] = this; + } }); } else { base.ColliderShape = value; - } - UpdateInertia(); + UpdateInertia(); + } } } @@ -435,6 +449,8 @@ public RigidBodyTypes RigidBodyType } set { + if (type == value) return; + type = value; UpdateInertia(); @@ -485,7 +501,7 @@ public override bool AddedToScene /// The impulse. public void ApplyImpulse(Vector3 impulse) { - if (CheckCurrentValid()) + if (AddedToScene) InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); } @@ -496,7 +512,7 @@ public void ApplyImpulse(Vector3 impulse) /// The local offset. public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) { - if (CheckCurrentValid()) + if (AddedToScene) InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); } @@ -506,7 +522,7 @@ public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) /// The torque. public void ApplyTorqueImpulse(Vector3 torque) { - if (CheckCurrentValid()) + if (AddedToScene) InternalBody.ApplyAngularImpulse(BepuHelpers.ToBepu(torque)); } @@ -515,18 +531,18 @@ public override Vector3 Position { get { - return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalBody.Pose.Position : bodyDescription.Pose.Position); + return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Pose.Position : bodyDescription.Pose.Position); } set { + if (bodyDescription.Pose.Position == BepuHelpers.ToBepu(value)) return; + bodyDescription.Pose.Position.X = value.X; bodyDescription.Pose.Position.Y = value.Y; bodyDescription.Pose.Position.Z = value.Z; - if (CheckCurrentValid()) - { - InternalBody.Pose.Position = bodyDescription.Pose.Position; - } + if (AddedToScene) + InternalBody.SetPosition(bodyDescription.Pose.Position); } } @@ -535,19 +551,19 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { get { - return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); + return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); } set { + if (bodyDescription.Pose.Orientation == BepuHelpers.ToBepu(value)) return; + bodyDescription.Pose.Orientation.X = value.X; bodyDescription.Pose.Orientation.Y = value.Y; bodyDescription.Pose.Orientation.Z = value.Z; bodyDescription.Pose.Orientation.W = value.W; - if (CheckCurrentValid()) - { - InternalBody.Pose.Orientation = bodyDescription.Pose.Orientation; - } + if (AddedToScene) + InternalBody.SetRotation(bodyDescription.Pose.Orientation); } } @@ -562,18 +578,18 @@ public Vector3 AngularVelocity { get { - return CheckCurrentValid() ? BepuHelpers.ToXenko(InternalBody.Velocity.Angular) : Vector3.Zero; + return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Velocity.Angular : bodyDescription.Velocity.Angular); } set { + if (bodyDescription.Velocity.Angular == BepuHelpers.ToBepu(value)) return; + bodyDescription.Velocity.Angular.X = value.X; bodyDescription.Velocity.Angular.Y = value.Y; bodyDescription.Velocity.Angular.Z = value.Z; - if (CheckCurrentValid()) - { - InternalBody.Velocity.Angular = bodyDescription.Velocity.Angular; - } + if (AddedToScene) + InternalBody.SetAngularVelocity(bodyDescription.Velocity.Angular); } } @@ -588,27 +604,21 @@ public Vector3 LinearVelocity { get { - return CheckCurrentValid() ? BepuHelpers.ToXenko(InternalBody.Velocity.Linear) : Vector3.Zero; + return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Velocity.Linear : bodyDescription.Velocity.Linear); } set { + if (bodyDescription.Velocity.Linear == BepuHelpers.ToBepu(value)) return; + bodyDescription.Velocity.Linear.X = value.X; bodyDescription.Velocity.Linear.Y = value.Y; bodyDescription.Velocity.Linear.Z = value.Z; - if (CheckCurrentValid()) - { - InternalBody.Velocity.Linear = bodyDescription.Velocity.Linear; - } + if (AddedToScene) + InternalBody.SetLinearVelocity(bodyDescription.Velocity.Linear); } } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal override bool CheckCurrentValid() - { - return base.CheckCurrentValid() && InternalBody.Exists; - } - /// /// When updating the associated TransformComponent, should we not set rotation? /// diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index eaaea59d5b..7ad045fb72 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -19,11 +19,11 @@ using Xenko.Core.Collections; using Xenko.Core.Diagnostics; using Xenko.Core.Mathematics; +using Xenko.Core.Threading; using Xenko.Engine; using Xenko.Engine.Design; using Xenko.Games; using Xenko.Physics.Engine; -using Xenko.Core.Threading; using Xenko.Rendering; namespace Xenko.Physics.Bepu @@ -434,8 +434,6 @@ internal void ProcessAdds() rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); RigidMappings[rigidBody.AddedHandle] = rigidBody; } - rigidBody.SleepThreshold = rigidBody.bodyDescription.Activity.SleepThreshold; - rigidBody.CcdMotionThreshold = rigidBody.bodyDescription.Collidable.Continuity.SweepConvergenceThreshold; } component.Position = component.Entity.Transform.WorldPosition(); component.Rotation = component.Entity.Transform.WorldRotation(); @@ -881,10 +879,7 @@ internal void Simulate(float deltaTime) { if (internalSimulation == null || DisableSimulation) return; - using (BepuSimulation.instance.simulationLocker.ReadLock()) - { - internalSimulation.Timestep(deltaTime * TimeScale, threadDispatcher); - } + internalSimulation.Timestep(deltaTime * TimeScale, threadDispatcher); } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index 05e88eb1a1..4b3558fa7c 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -41,7 +41,7 @@ public override Xenko.Core.Mathematics.Vector3 Position { get { - return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalStatic.Pose.Position : staticDescription.Pose.Position); + return BepuHelpers.ToXenko(AddedToScene ? InternalStatic.Pose.Position : staticDescription.Pose.Position); } set { @@ -49,10 +49,8 @@ public override Xenko.Core.Mathematics.Vector3 Position staticDescription.Pose.Position.Y = value.Y; staticDescription.Pose.Position.Z = value.Z; - if (CheckCurrentValid()) - { + if (AddedToScene) InternalStatic.Pose.Position = staticDescription.Pose.Position; - } } } @@ -61,7 +59,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { get { - return BepuHelpers.ToXenko(CheckCurrentValid() ? InternalStatic.Pose.Orientation : staticDescription.Pose.Orientation); + return BepuHelpers.ToXenko(AddedToScene ? InternalStatic.Pose.Orientation : staticDescription.Pose.Orientation); } set { @@ -70,10 +68,8 @@ public override Xenko.Core.Mathematics.Quaternion Rotation staticDescription.Pose.Orientation.Z = value.Z; staticDescription.Pose.Orientation.W = value.W; - if (CheckCurrentValid()) - { + if (AddedToScene) InternalStatic.Pose.Orientation = staticDescription.Pose.Orientation; - } } } @@ -85,17 +81,11 @@ public override float SpeculativeMargin { base.SpeculativeMargin = value; - if (CheckCurrentValid()) + if (AddedToScene) InternalStatic.Collidable.SpeculativeMargin = value; } } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal override bool CheckCurrentValid() - { - return base.CheckCurrentValid() && InternalStatic.Exists; - } - /// /// Set this to true to add this object to the physics simulation. Will automatically remove itself when the entity. is removed from the scene. Will NOT automatically add the rigidbody /// to the scene when the entity is added, though. diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index f8e35361d0..73ff8765c0 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -183,7 +183,6 @@ private void RunPhysicsSimulation(float time) // update all rigidbodies for (int j = 0; j < physicsScene.BepuSimulation.AllRigidbodies.Count; j++) { - // are we still in the scene? BepuRigidbodyComponent rb = physicsScene.BepuSimulation.AllRigidbodies[j]; rb.swapProcessingContactsList(); From b8042ec3178f77671bada73f3c143ad1dc689ee9 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 7 Jan 2020 21:14:41 -0500 Subject: [PATCH 0599/2038] Physics: more sane default max simulation time --- sources/engine/Xenko.Physics/PhysicsSettings.cs | 2 +- sources/engine/Xenko.Physics/PhysicsSystem.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Physics/PhysicsSettings.cs b/sources/engine/Xenko.Physics/PhysicsSettings.cs index 0279c5b421..9c1b00a41d 100644 --- a/sources/engine/Xenko.Physics/PhysicsSettings.cs +++ b/sources/engine/Xenko.Physics/PhysicsSettings.cs @@ -29,6 +29,6 @@ public class PhysicsSettings : Configuration /// Default maximum time to simulate per frame. /// [DataMember] - public float MaxSimulationTime = 0.5f; + public float MaxSimulationTime = 0.04f; } } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index 73ff8765c0..4990eb9133 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -26,7 +26,7 @@ private class PhysicsScene private ManualResetEventSlim doUpdateEvent; private Thread physicsThread; - public static float MaximumSimulationTime = 0.5f; + public static float MaximumSimulationTime = 0.04f; private readonly List scenes = new List(); From 742c3d43ce8254013c75bd2e8d4736288bff769e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 8 Jan 2020 11:24:35 -0500 Subject: [PATCH 0600/2038] Physics: implement better time management & improve default timing values --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 1 + .../engine/Xenko.Physics/PhysicsSettings.cs | 4 ++-- sources/engine/Xenko.Physics/PhysicsSystem.cs | 20 +++++++++++++------ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 7ad045fb72..b8b21d9001 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -42,6 +42,7 @@ public class BepuSimulation : IDisposable public ConcurrentQueue> ActionsBeforeSimulationStep = new ConcurrentQueue>(); public static float TimeScale = 1f; + public static int MaxSubSteps = 1; private static BepuSimulation _instance; public static BepuSimulation instance diff --git a/sources/engine/Xenko.Physics/PhysicsSettings.cs b/sources/engine/Xenko.Physics/PhysicsSettings.cs index 9c1b00a41d..97aeded148 100644 --- a/sources/engine/Xenko.Physics/PhysicsSettings.cs +++ b/sources/engine/Xenko.Physics/PhysicsSettings.cs @@ -17,7 +17,7 @@ public class PhysicsSettings : Configuration /// The maximum number of simulations the the physics engine can run in a frame to compensate for slowdown /// [DataMember(20)] - public int MaxSubSteps = 1; + public int MaxSubSteps = 2; /// /// The length in seconds of a physics simulation frame. The default is 0.016667 (one sixtieth of a second) @@ -29,6 +29,6 @@ public class PhysicsSettings : Configuration /// Default maximum time to simulate per frame. ///
[DataMember] - public float MaxSimulationTime = 0.04f; + public float MaxSimulationTime = 0.025f; } } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index 4990eb9133..b2feb3d852 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -26,7 +26,8 @@ private class PhysicsScene private ManualResetEventSlim doUpdateEvent; private Thread physicsThread; - public static float MaximumSimulationTime = 0.04f; + public static int MaxSubSteps = 2; + public static float MaximumSimulationTime = 0.025f; private readonly List scenes = new List(); @@ -178,7 +179,13 @@ private void RunPhysicsSimulation(float time) if (Simulation.DisableSimulation == false) { // simulate! - physicsScene.BepuSimulation.Simulate(time); + float totalTime = time; + for(int k=0; k 0f; k++) + { + float simtime = Math.Min(MaximumSimulationTime, totalTime); + physicsScene.BepuSimulation.Simulate(simtime); + totalTime -= simtime; + } // update all rigidbodies for (int j = 0; j < physicsScene.BepuSimulation.AllRigidbodies.Count; j++) @@ -206,8 +213,8 @@ private void PhysicsProcessingThreadBody() float simulateThisInterval = timeToSimulate; if (simulateThisInterval > 0f) { - timeToSimulate -= simulateThisInterval; RunPhysicsSimulation(simulateThisInterval); + timeToSimulate -= simulateThisInterval; } } @@ -220,9 +227,10 @@ public override void Update(GameTime gameTime) if (isMultithreaded) { float gt = (float)gameTime.Elapsed.TotalSeconds; - if (timeToSimulate + gt > MaximumSimulationTime) + float totalTimeCap = MaximumSimulationTime * MaxSubSteps; + if (timeToSimulate + gt > totalTimeCap) { - timeToSimulate = MaximumSimulationTime; + timeToSimulate = totalTimeCap; } else { @@ -233,7 +241,7 @@ public override void Update(GameTime gameTime) } else { - RunPhysicsSimulation((float)Math.Min(MaximumSimulationTime, gameTime.Elapsed.TotalSeconds)); + RunPhysicsSimulation((float)Math.Min(MaximumSimulationTime * MaxSubSteps, gameTime.Elapsed.TotalSeconds)); } } } From 95f954d359a793b3cab1f314126fe26704cb960c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 8 Jan 2020 13:27:59 -0500 Subject: [PATCH 0601/2038] Graphics: get supported display modes easily using SDL --- sources/engine/Xenko.Games/GameWindow.cs | 11 +++++++ .../engine/Xenko.Games/SDL/GameWindowSDL.cs | 13 ++++++-- sources/engine/Xenko.Graphics/SDL/Window.cs | 33 ++++++++++++++++++- 3 files changed, 54 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Games/GameWindow.cs b/sources/engine/Xenko.Games/GameWindow.cs index 65304d30f0..706da15758 100644 --- a/sources/engine/Xenko.Games/GameWindow.cs +++ b/sources/engine/Xenko.Games/GameWindow.cs @@ -23,6 +23,7 @@ #pragma warning disable SA1402 // File may only contain a single type using System; +using System.Collections.Generic; using Xenko.Core; using Xenko.Core.Mathematics; using Xenko.Graphics; @@ -169,6 +170,16 @@ public string Title #region Public Methods and Operators + virtual public List GetDisplayModes(int display = -1, bool maxRefreshRateOnly = true) + { + throw new NotImplementedException("Only implemented for SDL windows"); + } + + virtual public void GetDisplayInformation(out int width, out int height, out int refresh_rate, int display = -1) + { + throw new NotImplementedException("Only implemented for SDL windows"); + } + public abstract void BeginScreenDeviceChange(bool willBeFullScreen); public void EndScreenDeviceChange() diff --git a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs index 4d958e35f0..b58ebc04ff 100644 --- a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs +++ b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if XENKO_UI_SDL using System; +using System.Collections.Generic; using System.Diagnostics; using SDL2; using Xenko.Core.Mathematics; @@ -191,8 +192,16 @@ public override bool Visible /// /// Gets refresh rate of window in Hz. /// - public void GetDisplayInformation(out int width, out int height, out int refresh_rate, int display = -1) { - Window.GetDisplayInformation(out width, out height, out refresh_rate, display == -1 ? window.GetWindowDisplay() : display); + public override void GetDisplayInformation(out int width, out int height, out int refresh_rate, int display = -1) { + Window.GetDisplayInformation(out width, out height, out refresh_rate, display == -1 ? window?.GetWindowDisplay() ?? 0 : display); + } + + /// + /// Gets available display modes for a given display (-1 will just pick the current display). + /// + public override List GetDisplayModes(int display = -1, bool maxRefreshRateOnly = true) + { + return Window.GetDisplayModes(maxRefreshRateOnly, display == -1 ? window?.GetWindowDisplay() ?? 0 : display); } public override Int2 Position diff --git a/sources/engine/Xenko.Graphics/SDL/Window.cs b/sources/engine/Xenko.Graphics/SDL/Window.cs index 47111e4adc..72e7ed2af3 100644 --- a/sources/engine/Xenko.Graphics/SDL/Window.cs +++ b/sources/engine/Xenko.Graphics/SDL/Window.cs @@ -6,6 +6,7 @@ namespace Xenko.Graphics.SDL { + using System.Collections.Generic; #pragma warning disable SA1200 // Using directives must be placed correctly // Using is here otherwise it would conflict with the current namespace that also defines SDL. using SDL2; @@ -45,7 +46,7 @@ static Window() /// /// Get the current display information of the display (defaults to 0, the first display). /// - static public void GetDisplayInformation(out int width, out int height, out int refresh_rate, int display = 0) { + public static void GetDisplayInformation(out int width, out int height, out int refresh_rate, int display = 0) { SDL.SDL_GetCurrentDisplayMode(display, out SDL.SDL_DisplayMode mode); width = mode.w; height = mode.h; @@ -60,6 +61,36 @@ public int GetWindowDisplay() { return SDL.SDL_GetWindowDisplayIndex(SdlHandle); } + /// + /// Returns a list of supported resolutions and refresh rates. + /// + /// List of width, height and refresh rates + public static List GetDisplayModes(bool maxRefreshOnly = true, int display = 0) + { + int modes = SDL.SDL_GetNumDisplayModes(display); + List modeList = new List(); + for (int i=0; i /// Initializes a new instance of the class with as the title of the Window. ///
From a756b311721c2d6f83e971e0b6645e7ed774c0a9 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 8 Jan 2020 20:58:31 -0500 Subject: [PATCH 0602/2038] UI Editor: better selection & doesn't select hidden things --- .../Game/UIEditorGameAdornerService.Events.cs | 31 +++++++++++++++---- sources/engine/Xenko.UI/UIElement.cs | 18 +++++++++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/UIEditor/Game/UIEditorGameAdornerService.Events.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/UIEditor/Game/UIEditorGameAdornerService.Events.cs index edf4980b8c..bdd06c3126 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/UIEditor/Game/UIEditorGameAdornerService.Events.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/UIEditor/Game/UIEditorGameAdornerService.Events.cs @@ -13,6 +13,8 @@ using Xenko.Input; using Xenko.Rendering.UI; using Xenko.UI; +using Xenko.Assets.Presentation.AssetEditors.UIEditor.ViewModels; +using Xenko.Core; namespace Xenko.Assets.Presentation.AssetEditors.UIEditor.Game { @@ -299,14 +301,31 @@ private static IAdornerBase GetAssociatedAdorner(UIElement visual) private bool TryGetElementIdAtPosition(ref Vector3 worldPosition, out Guid elementId) { - var hitResults = GetAdornerVisualsAtPosition(ref worldPosition); - var visual = hitResults?.OrderBy(r => -r.IntersectionPoint.Z).FirstOrDefault()?.Element; - if (visual == null || !visual.DependencyProperties.TryGetValue(AssociatedElementIdPropertyKey, out elementId)) + var hitResults = GetAdornerVisualsAtPosition(ref worldPosition) as List; + float smallestArea = float.MaxValue; + elementId = default; + for (int i=0; i public bool IsVisible => Visibility == Visibility.Visible; + /// + /// This checks the whole UIElement parent tree for visibility + /// + public bool IsVisibleInTree + { + get + { + if (Visibility != Visibility.Visible) return false; + UIElement checkToRoot = this; + while (checkToRoot?.Parent != null) + { + checkToRoot = checkToRoot.Parent; + if (checkToRoot.Visibility != Visibility.Visible) return false; + } + return true; + } + } + /// /// Gets a value indicating whether this element takes some place in the user interface. /// From 1d042f9b01dd1637a5ba229322fa934a4a305570 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 8 Jan 2020 21:02:37 -0500 Subject: [PATCH 0603/2038] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 09a92a3f6e..aa1da83b62 100644 --- a/README.md +++ b/README.md @@ -22,11 +22,12 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. -* Ease of use: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. +* API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors or rendering 3D text from multiple cameras. * CinematicAction: Simple system for performing cinematic actions on objects and calling functions at certain times. Can build a simple timeline for things to move, rotate and execute. See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). +* Better UI Editor: Selecting things in the editor works more intuitively, like hidden things are skipped and smaller things are easier to click. * UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. * ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). * More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. From fcfb52de9d021171b273f38f2b4da829cb0d4d4d Mon Sep 17 00:00:00 2001 From: Eideren Date: Wed, 8 Jan 2020 19:25:23 +0100 Subject: [PATCH 0604/2038] Initial proposal --- .../Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs b/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs index 1bdeb744a5..47daa13829 100644 --- a/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs +++ b/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs @@ -337,7 +337,7 @@ internal static async Task FindXenkoSdkDir(string solution, string } else { - // TODO: Report error from log + throw new InvalidOperationException( $"Could not restore {packageName} {packageInfo.ExpectedVersion}, build it or pull it from nugget manually." ); } } } From 5a027acf1b200299fc3921cabbd293eb0fae180d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 9 Jan 2020 09:06:47 -0500 Subject: [PATCH 0605/2038] UI: Make sure something removed is not considered over the mouse --- sources/engine/Xenko.UI/Panels/Panel.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sources/engine/Xenko.UI/Panels/Panel.cs b/sources/engine/Xenko.UI/Panels/Panel.cs index 1c8e238d64..d411c8b573 100644 --- a/sources/engine/Xenko.UI/Panels/Panel.cs +++ b/sources/engine/Xenko.UI/Panels/Panel.cs @@ -9,6 +9,7 @@ using Xenko.Core.Annotations; using Xenko.Core.Collections; using Xenko.Core.Mathematics; +using Xenko.Rendering.UI; using Xenko.UI.Controls; namespace Xenko.UI.Panels @@ -143,6 +144,9 @@ protected virtual void OnLogicalChildRemoved(UIElement oldElement, int index) throw new UIInternalException("The parent of the removed children UIElement not null"); SetParent(oldElement, null); SetVisualParent(oldElement, null); + + if (oldElement.MouseOverState != MouseOverState.MouseOverNone) + MouseOverState = MouseOverState.MouseOverNone; } /// From ff5d06e5dfd1c30e7f11932fcdfa8f02e0992604 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 9 Jan 2020 12:09:08 -0500 Subject: [PATCH 0606/2038] UI: GridList and PulldownList fixes (selection via code and fixing widths) --- sources/engine/Xenko.UI/GridList.cs | 35 ++++++++++++++++++++++--- sources/engine/Xenko.UI/PulldownList.cs | 1 + 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.UI/GridList.cs b/sources/engine/Xenko.UI/GridList.cs index 2f59fa2a77..91b22daf62 100644 --- a/sources/engine/Xenko.UI/GridList.cs +++ b/sources/engine/Xenko.UI/GridList.cs @@ -39,6 +39,19 @@ public class GridList /// public Action EntrySelectedAction = (value) => { }; + protected bool UpdateEntryWidth() + { + float newWidth = myGrid.Width; + if (float.IsNaN(newWidth)) newWidth = myGrid.ActualWidth; + if (!float.IsNaN(newWidth) && + entryWidth != newWidth) + { + entryWidth = newWidth; + return true; + } + return false; + } + /// /// Make a GridList for the given Grid /// @@ -60,8 +73,7 @@ public GridList(Grid grid, UILibrary entryTemplate, string templateRootName = nu } else templateName = templateRootName; entryHeight = entryTemplate.UIElements[templateName].Height; - entryWidth = myGrid.Width; - if (float.IsNaN(entryWidth)) entryWidth = myGrid.ActualWidth; + UpdateEntryWidth(); } /// @@ -140,6 +152,22 @@ public void AddEntries(List entries, bool rebuildVisualListAfter = true) if (rebuildVisualListAfter) RebuildVisualList(); } + protected void RepairWidth() + { + foreach (var uie in entryElements) + { + foreach (UIElement uiec in uie.Value.Values) + { + if (uiec is ToggleButton || + uiec is Button || + uiec is Grid) + { + uiec.Width = entryWidth; + } + } + } + } + /// /// Toggle an option on the list /// @@ -154,7 +182,7 @@ virtual public void Select(object value, ToggleState toggleState = ToggleState.C { if (uiec is ToggleButton tb) { - if (uie.Key == value) + if (uie.Key.Equals(value)) { tb.State = toggleState; } @@ -299,6 +327,7 @@ protected void AddToList(UIElement uie) virtual public void RebuildVisualList() { + if (UpdateEntryWidth()) RepairWidth(); myGrid.Children.Clear(); if (AlphabeticalSort) { diff --git a/sources/engine/Xenko.UI/PulldownList.cs b/sources/engine/Xenko.UI/PulldownList.cs index 75ace33a99..b64863b82d 100644 --- a/sources/engine/Xenko.UI/PulldownList.cs +++ b/sources/engine/Xenko.UI/PulldownList.cs @@ -118,6 +118,7 @@ public override UIElement AddEntry(string displayName, object value = null, bool override public void RebuildVisualList() { + if (UpdateEntryWidth()) RepairWidth(); myGrid.Children.Clear(); foreach (var uie in entryElements.OrderBy(i => GetToggledState(i.Key))) { From 308b8d794c69338cb4d42c1af7f1fb03f3e8825f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 9 Jan 2020 15:24:13 -0500 Subject: [PATCH 0607/2038] SetDefaultSettings will only return true if default resolution/fullscreen was changed --- sources/engine/Xenko.Engine/Engine/Game.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sources/engine/Xenko.Engine/Engine/Game.cs b/sources/engine/Xenko.Engine/Engine/Game.cs index 4cec8ade2e..09007bda20 100644 --- a/sources/engine/Xenko.Engine/Engine/Game.cs +++ b/sources/engine/Xenko.Engine/Engine/Game.cs @@ -205,7 +205,10 @@ public LogMessageType ConsoleLogLevel /// /// If AutoLoadDefaultSettings is true, these values will be set on game start. Set width & height to int.MaxValue to use highest native values. /// + /// true if default settings changed public bool SetDefaultSettings(int width, int height, bool fullscreen) { + GetDefaultSettings(out int current_width, out int current_height, out bool current_fullscreen); + if (width == current_width && height == current_height && current_fullscreen == fullscreen) return false; try { System.IO.File.WriteAllText("DefaultResolution.txt", width.ToString() + "\n" + height.ToString() + "\n" + From af0a6dec019401c08a6b4949df65fa2e7abd9008 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 11:42:00 -0500 Subject: [PATCH 0608/2038] Audio: be able to import more than one sound at a time in GameStudio --- .../Templates/SoundFromFileTemplateGenerator.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs b/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs index c9b2f0453e..9c8107da2b 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs @@ -39,14 +39,14 @@ public override bool IsSupportingTemplate(TemplateDescription templateDescriptio protected override IEnumerable CreateAssets(AssetTemplateGeneratorParameters parameters) { var importedAssets = new List(); - using (var media = new FFmpegMedia()) + foreach (var assetItem in base.CreateAssets(parameters)) { - foreach (var assetItem in base.CreateAssets(parameters)) + if (assetItem.Asset is SoundAsset soundAsset) { - if (assetItem.Asset is SoundAsset soundAsset) + using (var media = new FFmpegMedia()) { media.Open(soundAsset.Source.ToWindowsPath()); - foreach( var audioTrack in media.Streams.OfType().ToList()) + foreach (var audioTrack in media.Streams.OfType().ToList()) { var assetCopy = AssetCloner.Clone(soundAsset); assetCopy.Index = audioTrack.Index; From c6617a5456b2b4f5b2ad8c17677f9001c7afd300 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 11:47:47 -0500 Subject: [PATCH 0609/2038] Audio: don't add extra text to asset name if not needed --- .../Templates/SoundFromFileTemplateGenerator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs b/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs index 9c8107da2b..7dc5e37540 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/SoundFromFileTemplateGenerator.cs @@ -52,7 +52,7 @@ protected override IEnumerable CreateAssets(AssetTemplateGeneratorPar assetCopy.Index = audioTrack.Index; assetCopy.SampleRate = audioTrack.SampleRate; - importedAssets.Add(new AssetItem(assetItem.Location + " track " + audioTrack.Index, assetCopy)); + importedAssets.Add(new AssetItem(assetItem.Location + (audioTrack.Index > 0 ? " track " + audioTrack.Index : ""), assetCopy)); } } } From b0f7f8b0a792fb503cf4ef1e55efe044d6be051e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 11:58:34 -0500 Subject: [PATCH 0610/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index aa1da83b62..74ff21a1c5 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. -* Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors or rendering 3D text from multiple cameras. +* Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors, importing multiple audio files at once, or rendering 3D text from multiple cameras. * CinematicAction: Simple system for performing cinematic actions on objects and calling functions at certain times. Can build a simple timeline for things to move, rotate and execute. See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). From 9e431c08137de10ba41d585b63e826ecb0fe63ed Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 12:01:02 -0500 Subject: [PATCH 0611/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 74ff21a1c5..7f3768201a 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). * Better UI Editor: Selecting things in the editor works more intuitively, like hidden things are skipped and smaller things are easier to click. * UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. -* ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). +* ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/ModelBatcher.cs * More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. * Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. * Easy generating procedural meshes: StagedMeshDraw takes a list of verticies and indicies, no "buffer binding" or "GraphicsDevice" needed. Also will actually upload the mesh when it tries to get rendered automatically, saving time and resources if the mesh doesn't actually ever get viewed. From f83f52dae4b77d56a5e3aafd0568de64530dcd15 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 16:52:13 -0500 Subject: [PATCH 0612/2038] Audio: added SimpleAudioPool to easily play sound effects for your entire project from one object --- sources/engine/Xenko.Audio/SoundInstance.cs | 26 +++ .../Xenko.Engine/Engine/SimpleAudioPool.cs | 221 ++++++++++++++++++ 2 files changed, 247 insertions(+) create mode 100644 sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index 4c841b7c5d..81524f12ed 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -4,6 +4,7 @@ using System; using System.Threading.Tasks; using Xenko.Core; +using Xenko.Core.Mathematics; using Xenko.Media; namespace Xenko.Audio @@ -28,6 +29,8 @@ public class SoundInstance : ComponentBase, IPositionableSound internal AudioListener Listener; + public bool IsSpatialized => spatialized; + /// /// Initializes a new instance of the class using a dynamic sound source. /// @@ -204,6 +207,29 @@ public void Apply3D(AudioEmitter emitter) emitter.Apply3D(Source); } + /// + /// Quick and easy way to apply 3D parameters without an AudioEmitter + /// + public void Apply3D(Vector3 Position, Vector3? velocity = null, Quaternion? direction = null, float distanceScale = 1f) + { + if (!spatialized) return; + + if (distanceScale != 1f) + Vector3.Lerp(ref Listener.Position, ref Position, distanceScale, out Position); + + Vector3 vel = velocity ?? Vector3.Zero; + Vector3 dir = direction == null ? Vector3.UnitZ : Vector3.Transform(Vector3.UnitZ, direction.Value); + Vector3 up = direction == null ? Vector3.UnitY : Vector3.Transform(Vector3.UnitY, direction.Value); + Matrix m = Matrix.Transformation(Vector3.One, direction ?? Quaternion.Identity, Position); + + if (engine.State == AudioEngineState.Invalidated) + return; + + if (!spatialized) return; + + AudioLayer.SourcePush3D(Source, ref Position, ref dir, ref up, ref vel, ref m); + } + /// /// Pause the sounds. /// diff --git a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs new file mode 100644 index 0000000000..3ff7865657 --- /dev/null +++ b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs @@ -0,0 +1,221 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using Xenko.Audio; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Collections; +using Xenko.Core.Mathematics; +using Xenko.Engine.Design; +using Xenko.Games; + +namespace Xenko.Engine +{ + [Display("Simple Audio Pool", Expand = ExpandRule.Once)] + [DataContract("SimpleAudioPool")] + [ComponentOrder(7500)] + [ComponentCategory("Audio")] + public sealed class SimpleAudioPool : ActivableEntityComponent + { + private struct PositionalSound + { + public SoundInstance soundInstance; + public TransformComponent transform; + public Vector3 pos; + public float distance_scale; + } + + public AudioListenerComponent Listener; + public float MaxSoundDistance = 48f; + + private Dictionary Sounds = new Dictionary(); + private Dictionary> instances = new Dictionary>(); + private List currentPositionals = new List(); + private System.Random rand; + private Game internalGame; + + private SoundInstance getFreeInstance(string url, bool spatialized) + { + if (instances.TryGetValue(url, out var ins)) + { + for (int i=0; i lsi1 = new List(); + lsi1.Add(si1); + instances[url] = lsi1; + return si1; + } + + // don't have this sound... try loading it! + if (internalGame == null) + internalGame = ServiceRegistry.instance.GetService() as Game; + + Sound snd2; + try + { + snd2 = internalGame.Content.Load(url); + } + catch(Exception) + { + return null; + } + + if (!snd2.Spatialized && spatialized) + throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); + + SoundInstance si = snd2.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + List lsi = new List(); + lsi.Add(si); + instances[url] = lsi; + Sounds[url] = snd2; + return si; + + } + + public void Reset() + { + StopAllSounds(); + Sounds.Clear(); + foreach (List si in instances.Values) + { + for (int i=0; i si in instances.Values) + { + for (int i=0; i 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; + SoundInstance s = getFreeInstance(url, true); + if (s == null) return null; + s.Pitch = pitch; + s.Volume = volume; + s.IsLooping = looped; + s.Pan = pan; + s.Apply3D(position, null, null, distanceScale); + s.Play(); + currentPositionals.Add(new PositionalSound() + { + pos = position, + soundInstance = s, + transform = null, + distance_scale = distanceScale + }); + return s; + } + + public SoundInstance PlayAttachedSound(string url, TransformComponent parent, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + { + Vector3 pos = parent.WorldPosition(); + float sqrDist = (pos - Listener.Listener.Position).LengthSquared(); + if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; + SoundInstance s = getFreeInstance(url, true); + if (s == null) return null; + s.Pitch = pitch; + s.Volume = volume; + s.IsLooping = looped; + s.Pan = pan; + s.Apply3D(pos, null, null, distanceScale); + s.Play(); + currentPositionals.Add(new PositionalSound() + { + pos = default, + soundInstance = s, + transform = parent, + distance_scale = distanceScale + }); + return s; + } + } +} From 36ef2175fcc536a1a61fe579117b8d3ee9ec5eac Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 16:56:27 -0500 Subject: [PATCH 0613/2038] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7f3768201a..64e5e89ead 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors, importing multiple audio files at once, or rendering 3D text from multiple cameras. +* SimpleAudioPool: easily play all sound effects for your whole project from a single object, which handles loading and pooling sound instances automatically. If you use positional sounds, make sure you call UpdatePlayingSoundPositions every frame! See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs * CinematicAction: Simple system for performing cinematic actions on objects and calling functions at certain times. Can build a simple timeline for things to move, rotate and execute. See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). From e34845cfef2b8e481b04f851f53c33795283a72e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 10 Jan 2020 21:35:45 -0500 Subject: [PATCH 0614/2038] Audio: SimpleAudioPool improvements --- .../Xenko.Engine/Engine/SimpleAudioPool.cs | 49 +++++++++---------- 1 file changed, 22 insertions(+), 27 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs index 3ff7865657..f34ee4bcea 100644 --- a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs +++ b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs @@ -23,7 +23,7 @@ public sealed class SimpleAudioPool : ActivableEntityComponent private struct PositionalSound { public SoundInstance soundInstance; - public TransformComponent transform; + public Entity entity; public Vector3 pos; public float distance_scale; } @@ -33,12 +33,14 @@ private struct PositionalSound private Dictionary Sounds = new Dictionary(); private Dictionary> instances = new Dictionary>(); - private List currentPositionals = new List(); + private List currentAttached = new List(); private System.Random rand; private Game internalGame; private SoundInstance getFreeInstance(string url, bool spatialized) { + if (url == null) return null; + if (instances.TryGetValue(url, out var ins)) { for (int i=0; i 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; SoundInstance s = getFreeInstance(url, true); @@ -208,11 +203,11 @@ public SoundInstance PlayAttachedSound(string url, TransformComponent parent, fl s.Pan = pan; s.Apply3D(pos, null, null, distanceScale); s.Play(); - currentPositionals.Add(new PositionalSound() + currentAttached.Add(new PositionalSound() { - pos = default, + pos = pos, soundInstance = s, - transform = parent, + entity = parent, distance_scale = distanceScale }); return s; From 7c2207eaa01ad1a262a30dec51e8691cb21fb6eb Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 11 Jan 2020 13:45:29 -0500 Subject: [PATCH 0615/2038] Audio: option to set range by percentages, instead of absolute times --- sources/engine/Xenko.Audio/SoundInstance.cs | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index 81524f12ed..34a3340c96 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -414,6 +414,39 @@ public void SetRange(PlayRange range) } } + /// + /// Sets the range of the sound to play. + /// + /// % of when to start, 0.5 is starting at the exact middle + /// % of when to end. 1 is default (100%) + public void SetRangePercent(double startPercent, double endPercent = 1f) + { + if (engine.State == AudioEngineState.Invalidated) + return; + + var state = PlayState; + + if (state == PlayState.Playing) + { + Stop(); + } + + if (soundSource == null) + { + double len = sound.TotalLength.TotalSeconds; + AudioLayer.SourceSetRange(Source, startPercent * len, endPercent * len); + } + else + { + throw new ArgumentException("SetRangePercent cannot work with streamed audio."); + } + + if (state == PlayState.Playing) + { + Play(); + } + } + /// /// Gets the position in time of this playing instance. /// From 0bac02bd4d5aae0ca6733b32179a533f894b2ac2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 11 Jan 2020 13:45:59 -0500 Subject: [PATCH 0616/2038] Audio: fixes and better error reporting in SimpleAudioPool --- .../Xenko.Engine/Engine/SimpleAudioPool.cs | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs index f34ee4bcea..e220833a65 100644 --- a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs +++ b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs @@ -28,9 +28,15 @@ private struct PositionalSound public float distance_scale; } + [DataMember] public AudioListenerComponent Listener; + + [DataMember] public float MaxSoundDistance = 48f; + [DataMember] + public int MaxSameSoundOverlaps = 8; + private Dictionary Sounds = new Dictionary(); private Dictionary> instances = new Dictionary>(); private List currentAttached = new List(); @@ -48,6 +54,10 @@ private SoundInstance getFreeInstance(string url, bool spatialized) if (ins[i].PlayState == Media.PlayState.Stopped) return ins[i]; } + + // have we reached our max sounds though? + if (ins.Count >= MaxSameSoundOverlaps) return null; + // don't have a free one to play, add a new one to the list if (Sounds.TryGetValue(url, out var snd0)) { @@ -71,15 +81,8 @@ private SoundInstance getFreeInstance(string url, bool spatialized) if (internalGame == null) internalGame = ServiceRegistry.instance.GetService() as Game; - Sound snd2; - try - { - snd2 = internalGame.Content.Load(url); - } - catch(Exception) - { - return null; - } + // this might throw an exception if you provided a bad url + Sound snd2 = internalGame.Content.Load(url); if (!snd2.Spatialized && spatialized) throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); @@ -90,7 +93,6 @@ private SoundInstance getFreeInstance(string url, bool spatialized) instances[url] = lsi; Sounds[url] = snd2; return si; - } public void Reset() From 34c53be4f04dad609900e30f6b77022607add12b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 11 Jan 2020 13:48:19 -0500 Subject: [PATCH 0617/2038] Audio: rearrange SimpleAudioPool to put more common functions at the top --- .../Xenko.Engine/Engine/SimpleAudioPool.cs | 221 +++++++++--------- 1 file changed, 112 insertions(+), 109 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs index e220833a65..9c15f8dfc0 100644 --- a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs +++ b/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs @@ -14,6 +14,9 @@ namespace Xenko.Engine { + /// + /// Efficiently plays and manages sound effects for an entire project + /// [Display("Simple Audio Pool", Expand = ExpandRule.Once)] [DataContract("SimpleAudioPool")] [ComponentOrder(7500)] @@ -37,82 +40,61 @@ private struct PositionalSound [DataMember] public int MaxSameSoundOverlaps = 8; - private Dictionary Sounds = new Dictionary(); - private Dictionary> instances = new Dictionary>(); - private List currentAttached = new List(); - private System.Random rand; - private Game internalGame; - - private SoundInstance getFreeInstance(string url, bool spatialized) + public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume = 1f, float pan = 0.5f, bool looped = false) { - if (url == null) return null; - - if (instances.TryGetValue(url, out var ins)) - { - for (int i=0; i= MaxSameSoundOverlaps) return null; - - // don't have a free one to play, add a new one to the list - if (Sounds.TryGetValue(url, out var snd0)) - { - SoundInstance si0 = snd0.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); - ins.Add(si0); - return si0; - } - } - - // don't have a list for this, make one - if (Sounds.TryGetValue(url, out var snd1)) + SoundInstance s = getFreeInstance(url, false); + if (s != null) { - SoundInstance si1 = snd1.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); - List lsi1 = new List(); - lsi1.Add(si1); - instances[url] = lsi1; - return si1; + s.Pitch = pitch; + s.Volume = volume; + s.IsLooping = looped; + s.Pan = pan; + s.Play(); } + return s; + } - // don't have this sound... try loading it! - if (internalGame == null) - internalGame = ServiceRegistry.instance.GetService() as Game; - - // this might throw an exception if you provided a bad url - Sound snd2 = internalGame.Content.Load(url); - - if (!snd2.Spatialized && spatialized) - throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); - - SoundInstance si = snd2.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); - List lsi = new List(); - lsi.Add(si); - instances[url] = lsi; - Sounds[url] = snd2; - return si; + public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + { + float sqrDist = (position - Listener.Listener.Position).LengthSquared(); + if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; + SoundInstance s = getFreeInstance(url, true); + if (s == null) return null; + s.Pitch = pitch; + s.Volume = volume; + s.IsLooping = looped; + s.Pan = pan; + s.Apply3D(position, null, null, distanceScale); + s.Play(); + return s; } - public void Reset() + public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) { - StopAllSounds(); - Sounds.Clear(); - foreach (List si in instances.Values) + Vector3 pos = parent.Transform.WorldPosition(); + float sqrDist = (pos - Listener.Listener.Position).LengthSquared(); + if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; + SoundInstance s = getFreeInstance(url, true); + if (s == null) return null; + s.Pitch = pitch; + s.Volume = volume; + s.IsLooping = looped; + s.Pan = pan; + s.Apply3D(pos, null, null, distanceScale); + s.Play(); + currentAttached.Add(new PositionalSound() { - for (int i=0; i si in instances.Values) + foreach (List si in instances.Values) { - for (int i=0; i si in instances.Values) { - s.Pitch = pitch; - s.Volume = volume; - s.IsLooping = looped; - s.Pan = pan; - s.Play(); + for (int i = 0; i < si.Count; i++) + { + si[i].Dispose(); + } + si.Clear(); } - return s; + instances.Clear(); } - public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) - { - float sqrDist = (position - Listener.Listener.Position).LengthSquared(); - if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; - SoundInstance s = getFreeInstance(url, true); - if (s == null) return null; - s.Pitch = pitch; - s.Volume = volume; - s.IsLooping = looped; - s.Pan = pan; - s.Apply3D(position, null, null, distanceScale); - s.Play(); - return s; - } + private Dictionary Sounds = new Dictionary(); + private Dictionary> instances = new Dictionary>(); + private List currentAttached = new List(); + private System.Random rand; + private Game internalGame; - public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + private SoundInstance getFreeInstance(string url, bool spatialized) { - Vector3 pos = parent.Transform.WorldPosition(); - float sqrDist = (pos - Listener.Listener.Position).LengthSquared(); - if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; - SoundInstance s = getFreeInstance(url, true); - if (s == null) return null; - s.Pitch = pitch; - s.Volume = volume; - s.IsLooping = looped; - s.Pan = pan; - s.Apply3D(pos, null, null, distanceScale); - s.Play(); - currentAttached.Add(new PositionalSound() + if (url == null) return null; + + if (instances.TryGetValue(url, out var ins)) { - pos = pos, - soundInstance = s, - entity = parent, - distance_scale = distanceScale - }); - return s; + for (int i=0; i= MaxSameSoundOverlaps) return null; + + // don't have a free one to play, add a new one to the list + if (Sounds.TryGetValue(url, out var snd0)) + { + SoundInstance si0 = snd0.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + ins.Add(si0); + return si0; + } + } + + // don't have a list for this, make one + if (Sounds.TryGetValue(url, out var snd1)) + { + SoundInstance si1 = snd1.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + List lsi1 = new List(); + lsi1.Add(si1); + instances[url] = lsi1; + return si1; + } + + // don't have this sound... try loading it! + if (internalGame == null) + internalGame = ServiceRegistry.instance.GetService() as Game; + + // this might throw an exception if you provided a bad url + Sound snd2 = internalGame.Content.Load(url); + + if (!snd2.Spatialized && spatialized) + throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); + + SoundInstance si = snd2.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + List lsi = new List(); + lsi.Add(si); + instances[url] = lsi; + Sounds[url] = snd2; + return si; } } } From e5e236b0a94f5d87758bff131b213c2ca35b0312 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 12 Jan 2020 20:42:26 -0500 Subject: [PATCH 0618/2038] UI: Add missing new properties for other text types --- sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs | 1 + .../engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs | 3 +++ 2 files changed, 4 insertions(+) diff --git a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs index 6fbd4dfac3..5af786400a 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs @@ -118,6 +118,7 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var drawCommand = new SpriteFont.InternalUIDrawCommand { Color = editText.RenderOpacity * editText.TextColor, + IsFullscreen = context.IsFullscreen, DepthBias = context.DepthBias + 2, RealVirtualResolutionRatio = fontScale, RequestedFontSize = editText.ActualTextSize, diff --git a/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs index 390f2d3b3b..99164dd357 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs @@ -40,11 +40,14 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var drawCommand = new SpriteFont.InternalUIDrawCommand { Color = scrollingText.RenderOpacity * scrollingText.TextColor, + VertAlignment = scrollingText.TextVerticalAlignment, + LineSpacingAdjustment = scrollingText.LineSpacingAdjustment, DepthBias = context.DepthBias + 1, RealVirtualResolutionRatio = element.LayoutingContext.RealVirtualResolutionRatio, RequestedFontSize = scrollingText.ActualTextSize, Batch = Batch, SnapText = context.ShouldSnapText && !scrollingText.DoNotSnapText, + IsFullscreen = context.IsFullscreen, Matrix = textWorldMatrix, Alignment = TextAlignment.Left, TextBoxSize = new Vector2(scrollingText.ActualWidth, scrollingText.ActualHeight) From aa831a98f839eefb242501c138809fd515c8fd6a Mon Sep 17 00:00:00 2001 From: Eideren Date: Sun, 12 Jan 2020 11:58:24 +0100 Subject: [PATCH 0619/2038] Show message box before throwing --- .../Commands/XenkoCommandsProxy.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs b/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs index 47daa13829..e053beaa29 100644 --- a/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs +++ b/sources/tools/Xenko.VisualStudio.Package/Commands/XenkoCommandsProxy.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Reflection; using System.Threading.Tasks; +using System.Windows.Forms; using NShader; using NuGet.Common; using NuGet.Versioning; @@ -337,7 +338,9 @@ internal static async Task FindXenkoSdkDir(string solution, string } else { - throw new InvalidOperationException( $"Could not restore {packageName} {packageInfo.ExpectedVersion}, build it or pull it from nugget manually." ); + MessageBox.Show( $"Could not restore {packageName} {packageInfo.ExpectedVersion}, this visual studio extension may fail to work properly without it." + + $"To fix this you can either build {packageName} or pull the right version from nugget manually" ); + throw new InvalidOperationException( $"Could not restore {packageName} {packageInfo.ExpectedVersion}." ); } } } From 64c97dbced9a73c5130539bb6b0fea388439909a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 13 Jan 2020 16:12:57 -0500 Subject: [PATCH 0620/2038] Fonts: add option for glyph margin for baking text effects & more fixed a bug with sizing offline / static fonts --- .../SpriteFont/Compiler/BitmapUtils.cs | 7 ++++++ .../SpriteFont/Compiler/GlyphPacker.cs | 12 +++++----- .../Compiler/OfflineRasterizedFontCompiler.cs | 4 ++-- .../OfflineRasterizedSpriteFontWriter.cs | 4 ++-- .../SpriteFont/SpriteFontAsset.cs | 5 +++++ .../Xenko.Graphics/Font/FontDataFactory.cs | 8 +++---- .../engine/Xenko.Graphics/Font/FontSystem.cs | 8 +++---- .../Xenko.Graphics/Font/IFontFactory.cs | 4 ++-- .../Font/OfflineRasterizedSpriteFont.cs | 11 +++++++++- sources/engine/Xenko.Graphics/UIBatch.cs | 22 +++---------------- 10 files changed, 45 insertions(+), 40 deletions(-) diff --git a/sources/engine/Xenko.Assets/SpriteFont/Compiler/BitmapUtils.cs b/sources/engine/Xenko.Assets/SpriteFont/Compiler/BitmapUtils.cs index 423afbdd56..a4daedda95 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/Compiler/BitmapUtils.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/Compiler/BitmapUtils.cs @@ -285,6 +285,13 @@ public static void PadBorderPixels(Bitmap bitmap, Rectangle region) // Copies a single pixel within a bitmap, preserving RGB but forcing alpha to zero. static void CopyBorderPixel(PixelAccessor bitmapData, int sourceX, int sourceY, int destX, int destY) { + if (sourceX < 0 || sourceY < 0 || destX < 0 || destY < 0 || + sourceX >= bitmapData.Region.Width || + sourceY >= bitmapData.Region.Height || + destX >= bitmapData.Region.Width || + destY >= bitmapData.Region.Height) + return; + DrawingColor color = bitmapData[sourceX, sourceY]; bitmapData[destX, destY] = DrawingColor.FromArgb(0, color); diff --git a/sources/engine/Xenko.Assets/SpriteFont/Compiler/GlyphPacker.cs b/sources/engine/Xenko.Assets/SpriteFont/Compiler/GlyphPacker.cs index ee07a2871a..d6b48e39f5 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/Compiler/GlyphPacker.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/Compiler/GlyphPacker.cs @@ -85,7 +85,7 @@ namespace Xenko.Assets.SpriteFont.Compiler // Helper for arranging many small bitmaps onto a single larger surface. internal static class GlyphPacker { - public static Bitmap ArrangeGlyphs(Glyph[] sourceGlyphs) + public static Bitmap ArrangeGlyphs(Glyph[] sourceGlyphs, int margin = 2) { // Build up a list of all the glyphs needing to be arranged. List glyphs = new List(); @@ -97,8 +97,8 @@ public static Bitmap ArrangeGlyphs(Glyph[] sourceGlyphs) glyph.Source = sourceGlyphs[i]; // Leave a one pixel border around every glyph in the output bitmap. - glyph.Width = sourceGlyphs[i].Subrect.Width + 2; - glyph.Height = sourceGlyphs[i].Subrect.Height + 2; + glyph.Width = sourceGlyphs[i].Subrect.Width + margin; + glyph.Height = sourceGlyphs[i].Subrect.Height + margin; glyphs.Add(glyph); } @@ -121,12 +121,12 @@ public static Bitmap ArrangeGlyphs(Glyph[] sourceGlyphs) // Create the merged output bitmap. outputHeight = MakeValidTextureSize(outputHeight, false); - return CopyGlyphsToOutput(glyphs, outputWidth, outputHeight); + return CopyGlyphsToOutput(glyphs, outputWidth, outputHeight, margin); } // Once arranging is complete, copies each glyph to its chosen position in the single larger output bitmap. - static Bitmap CopyGlyphsToOutput(List glyphs, int width, int height) + static Bitmap CopyGlyphsToOutput(List glyphs, int width, int height, int margin = 2) { Bitmap output = new Bitmap(width, height, PixelFormat.Format32bppArgb); @@ -134,7 +134,7 @@ static Bitmap CopyGlyphsToOutput(List glyphs, int width, int heig { Glyph sourceGlyph = glyph.Source; Rectangle sourceRegion = sourceGlyph.Subrect; - Rectangle destinationRegion = new Rectangle(glyph.X + 1, glyph.Y + 1, sourceRegion.Width, sourceRegion.Height); + Rectangle destinationRegion = new Rectangle(glyph.X + margin / 2, glyph.Y + margin / 2, sourceRegion.Width, sourceRegion.Height); BitmapUtils.CopyRect(sourceGlyph.Bitmap, sourceRegion, output, destinationRegion); diff --git a/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedFontCompiler.cs b/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedFontCompiler.cs index 70d073269a..d925c02f19 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedFontCompiler.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedFontCompiler.cs @@ -115,7 +115,7 @@ public static Graphics.SpriteFont Compile(IFontFactory fontFactory, SpriteFontAs foreach (Glyph glyph in glyphs) GlyphCropper.Crop(glyph); - Bitmap bitmap = GlyphPacker.ArrangeGlyphs(glyphs); + Bitmap bitmap = GlyphPacker.ArrangeGlyphs(glyphs, fontAsset.GlyphPackingMargin); // Automatically detect whether this is a monochromatic or color font? //if (fontAsset.Format == FontTextureFormat.Auto) @@ -139,7 +139,7 @@ public static Graphics.SpriteFont Compile(IFontFactory fontFactory, SpriteFontAs } } - return OfflineRasterizedSpriteFontWriter.CreateSpriteFontData(fontFactory, fontAsset, glyphs, lineSpacing, baseLine, bitmap, srgb); + return OfflineRasterizedSpriteFontWriter.CreateSpriteFontData(fontFactory, fontAsset, glyphs, lineSpacing, baseLine, bitmap, srgb, fontAsset.GlyphPackingMargin); } static Glyph[] ImportFont(SpriteFontAsset options, out float lineSpacing, out float baseLine) diff --git a/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedSpriteFontWriter.cs b/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedSpriteFontWriter.cs index e17ddd2c1f..8e4fcf0503 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedSpriteFontWriter.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/Compiler/OfflineRasterizedSpriteFontWriter.cs @@ -87,13 +87,13 @@ namespace Xenko.Assets.SpriteFont.Compiler // Writes the output sprite font binary file. internal static class OfflineRasterizedSpriteFontWriter { - public static Graphics.SpriteFont CreateSpriteFontData(IFontFactory fontFactory, SpriteFontAsset options, Glyph[] glyphs, float lineSpacing, float baseLine, Bitmap bitmap, bool srgb) + public static Graphics.SpriteFont CreateSpriteFontData(IFontFactory fontFactory, SpriteFontAsset options, Glyph[] glyphs, float lineSpacing, float baseLine, Bitmap bitmap, bool srgb, int margin = 0) { var fontGlyphs = ConvertGlyphs(glyphs); var images = new[] { GetImage(options, bitmap, srgb) }; var sizeInPixels = options.FontType.Size; - return fontFactory.NewStatic(sizeInPixels, fontGlyphs, images, baseLine, lineSpacing, null, options.Spacing, options.LineSpacing, options.DefaultCharacter); + return fontFactory.NewStatic(sizeInPixels, fontGlyphs, images, baseLine, lineSpacing, null, options.Spacing, options.LineSpacing, options.DefaultCharacter, margin); } static Graphics.Font.Glyph[] ConvertGlyphs(Glyph[] glyphs) diff --git a/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAsset.cs b/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAsset.cs index 47313edbd9..a83210a819 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAsset.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAsset.cs @@ -111,5 +111,10 @@ public partial class SpriteFontAsset : Asset [DataMemberRange(-500, 500, 1, 10, 2)] [Display(null, "Rendering")] public float LineGapBaseLineFactor { get; set; } = 1.0f; + + [DataMember] + [DefaultValue(0)] + [Display(null, "Rendering")] + public int GlyphPackingMargin { get; set; } = 0; } } diff --git a/sources/engine/Xenko.Graphics/Font/FontDataFactory.cs b/sources/engine/Xenko.Graphics/Font/FontDataFactory.cs index 69b7d2c317..35c6b80f95 100644 --- a/sources/engine/Xenko.Graphics/Font/FontDataFactory.cs +++ b/sources/engine/Xenko.Graphics/Font/FontDataFactory.cs @@ -14,14 +14,14 @@ namespace Xenko.Graphics.Font ///
public class FontDataFactory : IFontFactory { - public SpriteFont NewStatic(float size, IList glyphs, IList textures, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ') + public SpriteFont NewStatic(float size, IList glyphs, IList textures, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ', int margin = 0) { if (textures == null) throw new ArgumentNullException("textures"); - return new OfflineRasterizedSpriteFont(size, glyphs, textures, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter); + return new OfflineRasterizedSpriteFont(size, glyphs, textures, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter, margin); } - public SpriteFont NewStatic(float size, IList glyphs, IList images, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ') + public SpriteFont NewStatic(float size, IList glyphs, IList images, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ', int margin = 0) { // creates the textures from the images if any. Texture[] textures = null; @@ -32,7 +32,7 @@ public SpriteFont NewStatic(float size, IList glyphs, IList images textures[i] = images[i].ToSerializableVersion(); } - return new OfflineRasterizedSpriteFont(size, glyphs, textures, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter); + return new OfflineRasterizedSpriteFont(size, glyphs, textures, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter, margin); } public SpriteFont NewDynamic(float defaultSize, string fontName, FontStyle style, FontAntiAliasMode antiAliasMode, bool useKerning, float extraSpacing, float extraLineSpacing, char defaultCharacter) diff --git a/sources/engine/Xenko.Graphics/Font/FontSystem.cs b/sources/engine/Xenko.Graphics/Font/FontSystem.cs index 0275d3703c..3e4e1adcc8 100644 --- a/sources/engine/Xenko.Graphics/Font/FontSystem.cs +++ b/sources/engine/Xenko.Graphics/Font/FontSystem.cs @@ -58,9 +58,9 @@ public void Unload() allocatedSpriteFont.Dispose(); } - public SpriteFont NewStatic(float size, IList glyphs, IList images, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ') + public SpriteFont NewStatic(float size, IList glyphs, IList images, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ', int margin = 10) { - var font = new OfflineRasterizedSpriteFont(size, glyphs, null, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter) { FontSystem = this }; + var font = new OfflineRasterizedSpriteFont(size, glyphs, null, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter, margin) { FontSystem = this }; // affects the textures from the images. foreach (var image in images) @@ -80,9 +80,9 @@ public SpriteFont NewScalable(float size, IList glyphs, IList imag return font; } - public SpriteFont NewStatic(float size, IList glyphs, IList textures, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ') + public SpriteFont NewStatic(float size, IList glyphs, IList textures, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ', int margin = 0) { - return new OfflineRasterizedSpriteFont(size, glyphs, textures, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter) { FontSystem = this }; + return new OfflineRasterizedSpriteFont(size, glyphs, textures, baseOffset, defaultLineSpacing, kernings, extraSpacing, extraLineSpacing, defaultCharacter, margin) { FontSystem = this }; } public SpriteFont NewScalable(float size, IList glyphs, IList textures, float baseOffset, float defaultLineSpacing, IList kernings = null, float extraSpacing = 0, float extraLineSpacing = 0, char defaultCharacter = ' ') diff --git a/sources/engine/Xenko.Graphics/Font/IFontFactory.cs b/sources/engine/Xenko.Graphics/Font/IFontFactory.cs index 39127fa4eb..8be2ca5749 100644 --- a/sources/engine/Xenko.Graphics/Font/IFontFactory.cs +++ b/sources/engine/Xenko.Graphics/Font/IFontFactory.cs @@ -27,7 +27,7 @@ public interface IFontFactory /// The textures should be disposed manually (if useless) after that the sprite font is not used anymore. /// The newly created static font SpriteFont NewStatic(float size, IList glyphs, IList textures, float baseOffset, float defaultLineSpacing, - IList kernings = null, float extraSpacing = 0f, float extraLineSpacing = 0f, char defaultCharacter = ' '); + IList kernings = null, float extraSpacing = 0f, float extraLineSpacing = 0f, char defaultCharacter = ' ', int margin = 0); /// /// Create a new instance of a static font. @@ -44,7 +44,7 @@ SpriteFont NewStatic(float size, IList glyphs, IList textures, f /// The font does not copy the provided glyphs information. Provided glyphs should not be modified after the creation of the font. /// The newly created static font SpriteFont NewStatic(float size, IList glyphs, IList images, float baseOffset, float defaultLineSpacing, - IList kernings = null, float extraSpacing = 0f, float extraLineSpacing = 0f, char defaultCharacter = ' '); + IList kernings = null, float extraSpacing = 0f, float extraLineSpacing = 0f, char defaultCharacter = ' ', int margin = 0); /// /// Create a new instance of a dynamic font. diff --git a/sources/engine/Xenko.Graphics/Font/OfflineRasterizedSpriteFont.cs b/sources/engine/Xenko.Graphics/Font/OfflineRasterizedSpriteFont.cs index f378b8541b..c4fbaccabc 100644 --- a/sources/engine/Xenko.Graphics/Font/OfflineRasterizedSpriteFont.cs +++ b/sources/engine/Xenko.Graphics/Font/OfflineRasterizedSpriteFont.cs @@ -22,7 +22,7 @@ internal OfflineRasterizedSpriteFont() { } - internal OfflineRasterizedSpriteFont(float size, IList glyphs, IEnumerable textures, float baseOffset, float defaultLineSpacing, IList kernings, float extraSpacing, float extraLineSpacing, char defaultCharacter) + internal OfflineRasterizedSpriteFont(float size, IList glyphs, IEnumerable textures, float baseOffset, float defaultLineSpacing, IList kernings, float extraSpacing, float extraLineSpacing, char defaultCharacter, int margin = 0) { Size = size; StaticTextures = new List(); @@ -38,6 +38,15 @@ internal OfflineRasterizedSpriteFont(float size, IList glyphs, IEnumerabl foreach (var glyph in glyphs) { var character = (char)glyph.Character; + if (margin > 0) + { + glyph.Subrect.Width += margin; + glyph.Subrect.Height += margin; + glyph.Subrect.X -= margin / 2; + glyph.Subrect.Y -= margin / 2; + glyph.Offset.Y -= margin / 2; + glyph.Offset.X -= margin / 2; + } CharacterToGlyph[character] = glyph; } diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index 0419caa3a0..64cf6d725e 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -442,26 +442,10 @@ internal void DrawString(SpriteFont font, string text, ref SpriteFont.InternalUI // transform the world matrix into the world view project matrix Matrix.MultiplyTo(ref worldMatrix, ref viewProjectionMatrix, out drawCommand.Matrix); - if (!drawCommand.IsFullscreen) { - // we are drawing in 3D, don't snap or scale - drawCommand.SnapText = false; - drawCommand.RealVirtualResolutionRatio.X = 1f; - drawCommand.RealVirtualResolutionRatio.Y = 1f; - } - else if (font.FontType == SpriteFontType.SDF) - { - drawCommand.SnapText = false; - float scaling = drawCommand.RequestedFontSize / font.Size; - drawCommand.RealVirtualResolutionRatio = 1 / new Vector2(scaling, scaling); - } - else if ((font.FontType == SpriteFontType.Static)) - { - if ((drawCommand.RealVirtualResolutionRatio.X != 1 || drawCommand.RealVirtualResolutionRatio.Y != 1)) - drawCommand.SnapText = false; // we don't want snapping of the resolution of the screen does not match virtual resolution. (character alignment problems) + drawCommand.SnapText = false; + float scaling = drawCommand.RequestedFontSize / font.Size; + drawCommand.RealVirtualResolutionRatio = 1 / new Vector2(scaling, scaling); - drawCommand.RealVirtualResolutionRatio = Vector2.One; // ensure that static font are not scaled internally - } - // snap draw start position to prevent characters to be drawn in between two pixels if (drawCommand.SnapText) { From bd02b154aeb756318e2f726a4207fe9d8f161467 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 13 Jan 2020 21:01:15 -0500 Subject: [PATCH 0621/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 64e5e89ead..7edbf80aef 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). * Better UI Editor: Selecting things in the editor works more intuitively, like hidden things are skipped and smaller things are easier to click. -* UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. +* UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. Need text shadows, outlines or bevels? Precompile a font (right click it in the asset view) that has a Glyph Margin > 0, which will generate a PNG with room to edit in effects right into the glyphs. * ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/ModelBatcher.cs * More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. * Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. From 541259e91fd97872b0da5cd1d6365ead8bbb166a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 13 Jan 2020 21:02:12 -0500 Subject: [PATCH 0622/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7edbf80aef..e333127fcc 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ My games require the engine to be developed at a faster pace than Xenko. I'm in Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. -* Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. +* Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. From 59a66203f16d2f03e7945dccf03f64681d13b263 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 13 Jan 2020 21:05:21 -0500 Subject: [PATCH 0623/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e333127fcc..e9e2a40c26 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. -* BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. Look at the Xenko.Physics.Bepu namespace on how to use it. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. +* BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, has an easier API, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. See https://github.com/phr00t/FocusEngine/tree/master/sources/engine/Xenko.Physics/Bepu. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors, importing multiple audio files at once, or rendering 3D text from multiple cameras. * SimpleAudioPool: easily play all sound effects for your whole project from a single object, which handles loading and pooling sound instances automatically. If you use positional sounds, make sure you call UpdatePlayingSoundPositions every frame! See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs From c4bd46d1d60b1af0f645b5dd5fe1804bac73ea2c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 13 Jan 2020 22:10:33 -0500 Subject: [PATCH 0624/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9e2a40c26..ac7c16af25 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ My games require the engine to be developed at a faster pace than Xenko. I'm in Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. -* Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. +* Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. See https://github.com/phr00t/FOVTester2 for a super simple example of how easy a VR project is. * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, has an easier API, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. See https://github.com/phr00t/FocusEngine/tree/master/sources/engine/Xenko.Physics/Bepu. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. From 9ae8ea9f180297e9dbd7f4106f577da150ff8f93 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 13 Jan 2020 22:15:52 -0500 Subject: [PATCH 0625/2038] Audio: SetRangePercent support for streamed SoundInstances --- sources/engine/Xenko.Audio/SoundInstance.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index 34a3340c96..f1a364cc52 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -438,7 +438,10 @@ public void SetRangePercent(double startPercent, double endPercent = 1f) } else { - throw new ArgumentException("SetRangePercent cannot work with streamed audio."); + soundSource.PlayRange = + new PlayRange( + new TimeSpan((long)Math.Round((double)sound.TotalLength.Ticks * startPercent)), + new TimeSpan((long)Math.Round((double)sound.TotalLength.Ticks * endPercent))); } if (state == PlayState.Playing) From e140676b9a31cceec7c41a05b5cf985ba81870c2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 14 Jan 2020 08:53:55 -0500 Subject: [PATCH 0626/2038] CinematicAnimation: Add ability to loop an animation --- .../engine/Xenko.Engine/Cinematics/CinematicAnimation.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs b/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs index 84666adfcc..54136e8db8 100644 --- a/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs +++ b/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs @@ -58,6 +58,11 @@ public class CinematicAnimation ///
public bool Paused = false; + /// + /// Does this animation loop? + /// + public bool Looping = false; + /// /// What time are we at in the animation? /// @@ -99,6 +104,7 @@ public CinematicAnimation(bool initialize_as_paused = false) public void Play(float time_delta) { if (Paused) return; + if (Looping && RemainingActions.Count == 0 && AllActions.Count > 0) Reset(); for (int i = 0; i < RemainingActions.Count; i++) { CinematicAction ca = RemainingActions[i]; From 47378376345e8e66d42277bdd7fb91da177d7210 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 14 Jan 2020 09:05:18 -0500 Subject: [PATCH 0627/2038] Audio: rename SimpleAudioPool to GlobalSoundManager, which is more accurate --- .../Engine/{SimpleAudioPool.cs => GlobalSoundManager.cs} | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) rename sources/engine/Xenko.Engine/Engine/{SimpleAudioPool.cs => GlobalSoundManager.cs} (97%) diff --git a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs similarity index 97% rename from sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs rename to sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 9c15f8dfc0..2d2aadefae 100644 --- a/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -17,11 +17,11 @@ namespace Xenko.Engine /// /// Efficiently plays and manages sound effects for an entire project /// - [Display("Simple Audio Pool", Expand = ExpandRule.Once)] - [DataContract("SimpleAudioPool")] + [Display("Global Sound Manager", Expand = ExpandRule.Once)] + [DataContract("GlobalSoundManager")] [ComponentOrder(7500)] [ComponentCategory("Audio")] - public sealed class SimpleAudioPool : ActivableEntityComponent + public sealed class GlobalSoundManager : ActivableEntityComponent { private struct PositionalSound { From 0f00bfb48dc3e73a9a437ace1e8983d6cc1f6051 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 14 Jan 2020 12:56:14 -0500 Subject: [PATCH 0628/2038] Audio: GlobalSoundManager will find Listener automatically if not specified --- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 52 ++++++++++++++++--- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 2d2aadefae..bd87ff3d28 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -31,9 +31,6 @@ private struct PositionalSound public float distance_scale; } - [DataMember] - public AudioListenerComponent Listener; - [DataMember] public float MaxSoundDistance = 48f; @@ -160,11 +157,54 @@ public void Reset() instances.Clear(); } + private Game game + { + get + { + // don't have this sound... try loading it! + if (internalGame == null) + internalGame = ServiceRegistry.instance?.GetService() as Game; + + return internalGame; + } + } + + [DataMember] + public AudioListenerComponent Listener + { + get + { + if (_listener == null || _listener.Entity.Scene == null) + { + Game g = game; + + if (g != null) + { + // find a valid listener! + foreach (AudioListenerComponent alc in g.Audio.Listeners.Keys) + { + _listener = alc; + break; + } + } + } + return _listener; + } + set + { + // don't set us to something null, which just breaks things + if (value == null) return; + + _listener = value; + } + } + private Dictionary Sounds = new Dictionary(); private Dictionary> instances = new Dictionary>(); private List currentAttached = new List(); private System.Random rand; private Game internalGame; + private AudioListenerComponent _listener; private SoundInstance getFreeInstance(string url, bool spatialized) { @@ -200,12 +240,8 @@ private SoundInstance getFreeInstance(string url, bool spatialized) return si1; } - // don't have this sound... try loading it! - if (internalGame == null) - internalGame = ServiceRegistry.instance.GetService() as Game; - // this might throw an exception if you provided a bad url - Sound snd2 = internalGame.Content.Load(url); + Sound snd2 = game.Content.Load(url); if (!snd2.Spatialized && spatialized) throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); From ed232f32257147a42e1e83d5c11d31b1d7d75888 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 14 Jan 2020 12:56:42 -0500 Subject: [PATCH 0629/2038] Scenes: added persistent entity list to survive root scene changes --- sources/engine/Xenko.Engine/Engine/SceneInstance.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/sources/engine/Xenko.Engine/Engine/SceneInstance.cs b/sources/engine/Xenko.Engine/Engine/SceneInstance.cs index e94127e664..2fe594f9dc 100644 --- a/sources/engine/Xenko.Engine/Engine/SceneInstance.cs +++ b/sources/engine/Xenko.Engine/Engine/SceneInstance.cs @@ -56,6 +56,11 @@ public SceneInstance(IServiceRegistry registry) : this(registry, null) { } + /// + /// Entities in this list will persist across root scene changes, IF the entity was attached in the previous scene. + /// + public HashSet PersistentEntities = new HashSet(); + /// /// Initializes a new instance of the class. /// @@ -97,6 +102,11 @@ public Scene RootScene if (value != null) { Add(value); + + // return any persistent entities + foreach (Entity e in PersistentEntities) + e.Scene = value; + HandleRendererTypes(); } From 746d74261b9fd731442e9136791464e99aa271d2 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Wed, 15 Jan 2020 17:51:17 +1100 Subject: [PATCH 0630/2038] Added Voxel Global Illumination Includes: Voxelization Architecture - Arbitrary output attributes - Voxelization methods, modifiers, isotropic/anisotropic, etc... Global Illumination - Voxel light type - Cone layouts and march settings Debug Visualization # Conflicts: # build/Xenko.sln --- build/Xenko.sln | 14 + sources/engine/Xenko.Voxels/Module.cs | 17 + .../Xenko.Voxels/Properties/AssemblyInfo.cs | 7 + .../IVoxelVisualization.cs | 12 + .../Shaders/VoxelVisualizationRawEffect.cs | 47 ++ .../Shaders/VoxelVisualizationRawEffect.xksl | 13 + .../Shaders/VoxelVisualizationRawShader.cs | 25 + .../Shaders/VoxelVisualizationRawShader.xksl | 28 + .../VoxelVisualizationRawShaderKeys.cs | 12 + .../Shaders/VoxelVisualizationViewEffect.cs | 62 ++ .../Shaders/VoxelVisualizationViewEffect.xksl | 21 + .../Shaders/VoxelVisualizationViewShader.cs | 25 + .../Shaders/VoxelVisualizationViewShader.xksl | 28 + .../VoxelVisualizationViewShaderKeys.cs | 12 + .../VoxelVisualizationRaw.cs | 31 + .../VoxelVisualizationView.cs | 47 ++ .../ForwardRendererVoxels.cs | 71 ++ .../GraphicsCompositor/IVoxelRenderer.cs | 24 + .../Voxels/GraphicsCompositor/VoxelDebug.cs | 67 ++ .../VoxelPipelineProcessor.cs | 35 + .../GraphicsCompositor/VoxelRenderFeature.cs | 182 +++++ .../GraphicsCompositor/VoxelRenderer.cs | 260 +++++++ .../GraphicsCompositor/VoxelViewContext.cs | 17 + .../XenkoForwardShadingEffectVXGI.cs | 118 +++ .../XenkoForwardShadingEffectVXGI.xksl | 73 ++ .../Xenko.Voxels/Voxels/Light/LightVoxel.cs | 38 + .../Voxels/Light/LightVoxelEffect.cs | 75 ++ .../Voxels/Light/LightVoxelEffect.xksl | 34 + .../Voxels/Light/LightVoxelRenderer.cs | 192 +++++ .../Voxels/Light/LightVoxelShader.cs | 25 + .../Voxels/Light/LightVoxelShader.xksl | 45 ++ .../Voxels/Light/LightVoxelShaderKeys.cs | 14 + .../Voxels/Marching/IVoxelMarchMethod.cs | 14 + .../Voxels/Marching/IVoxelSampler.cs | 9 + .../Voxels/Marching/IVoxelSampler.xksl | 34 + .../Marching/MarchSets/IVoxelMarchSet.cs | 14 + .../MarchSets/Shaders/VoxelMarchSet.cs | 9 + .../MarchSets/Shaders/VoxelMarchSet.xksl | 4 + .../Shaders/VoxelMarchSetHemisphere12.cs | 9 + .../Shaders/VoxelMarchSetHemisphere12.xksl | 42 + .../Shaders/VoxelMarchSetHemisphere6.cs | 9 + .../Shaders/VoxelMarchSetHemisphere6.xksl | 40 + .../MarchSets/VoxelMarchSetHemisphere12.cs | 39 + .../MarchSets/VoxelMarchSetHemisphere6.cs | 39 + .../Marching/Shaders/MarchAttributes.cs | 9 + .../Marching/Shaders/MarchAttributes.xksl | 4 + .../Marching/Shaders/MarchAttributesEffect.cs | 51 ++ .../Shaders/MarchAttributesEffect.xksl | 16 + .../Marching/Shaders/MarchAttributesKeys.cs | 12 + .../Voxels/Marching/Shaders/VoxelMarchBeam.cs | 9 + .../Marching/Shaders/VoxelMarchBeam.xksl | 27 + .../Voxels/Marching/Shaders/VoxelMarchCone.cs | 9 + .../Marching/Shaders/VoxelMarchCone.xksl | 27 + .../Marching/Shaders/VoxelMarchConeFast.cs | 9 + .../Marching/Shaders/VoxelMarchConeFast.xksl | 27 + .../Shaders/VoxelMarchConePerMipmap.cs | 9 + .../Shaders/VoxelMarchConePerMipmap.xksl | 22 + .../Marching/Shaders/VoxelMarchMethod.cs | 9 + .../Marching/Shaders/VoxelMarchMethod.xksl | 5 + .../Shaders/VoxelRadiusMarchMethod.cs | 9 + .../Shaders/VoxelRadiusMarchMethod.xksl | 5 + .../Voxels/Marching/VoxelMarchBeam.cs | 41 + .../Voxels/Marching/VoxelMarchCone.cs | 42 + .../Marching/VoxelMarchConePerMipmap.cs | 37 + .../engine/Xenko.Voxels/Voxels/VoxelUtils.cs | 52 ++ .../Attributes/IVoxelAttribute.cs | 39 + .../Attributes/Shaders/VoxelAttribute.cs | 9 + .../Attributes/Shaders/VoxelAttribute.xksl | 9 + ...oxelAttributeDirectionalCoverageSampler.cs | 9 + ...elAttributeDirectionalCoverageSampler.xksl | 41 + ...VoxelAttributeDirectionalCoverageShader.cs | 23 + ...xelAttributeDirectionalCoverageShader.xksl | 54 ++ .../VoxelAttributeEmissionOpacityShader.cs | 9 + .../VoxelAttributeEmissionOpacityShader.xksl | 29 + .../Shaders/VoxelAttributeSoliditySampler.cs | 9 + .../VoxelAttributeSoliditySampler.xksl | 37 + .../Shaders/VoxelAttributeSolidityShader.cs | 23 + .../Shaders/VoxelAttributeSolidityShader.xksl | 106 +++ .../VoxelAttributeDirectionalCoverage.cs | 113 +++ .../VoxelAttributeEmissionOpacity.cs | 142 ++++ .../Attributes/VoxelAttributeSolidity.cs | 121 +++ .../BufferWriters/IVoxelBufferWriter.cs | 13 + .../Shaders/VoxelBufferWriteAssign.cs | 9 + .../Shaders/VoxelBufferWriteAssign.xksl | 13 + .../Shaders/VoxelBufferWriteMax.cs | 9 + .../Shaders/VoxelBufferWriteMax.xksl | 14 + .../Shaders/VoxelBufferWriter.cs | 9 + .../Shaders/VoxelBufferWriter.xksl | 27 + .../BufferWriters/VoxelBufferWriteAssign.cs | 21 + .../BufferWriters/VoxelBufferWriteMax.cs | 21 + .../FragmentPackers/IVoxelFragmentPacker.cs | 15 + .../FragmentPackers/Shaders/DataPacking.cs | 9 + .../FragmentPackers/Shaders/DataPacking.xksl | 96 +++ .../Shaders/VoxelFragmentPackFloat16.cs | 9 + .../Shaders/VoxelFragmentPackFloat16.xksl | 61 ++ .../Shaders/VoxelFragmentPackFloat32.cs | 9 + .../Shaders/VoxelFragmentPackFloat32.xksl | 59 ++ .../VoxelFragmentPackFloatR11G11B10.cs | 9 + .../VoxelFragmentPackFloatR11G11B10.xksl | 64 ++ .../Shaders/VoxelFragmentPacker.cs | 9 + .../Shaders/VoxelFragmentPacker.xksl | 19 + .../VoxelFragmentPackFloat16.cs | 24 + .../VoxelFragmentPackFloat32.cs | 24 + .../VoxelFragmentPackFloatR11G11B10.cs | 24 + .../Voxelization/Layout/IVoxelLayout.cs | 25 + .../Shaders/VoxelAnisotropicPairedSampler.cs | 9 + .../VoxelAnisotropicPairedSampler.xksl | 38 + .../VoxelAnisotropicPairedWriter_Float4.cs | 23 + .../VoxelAnisotropicPairedWriter_Float4.xksl | 56 ++ .../Layout/Shaders/VoxelAnisotropicSampler.cs | 9 + .../Shaders/VoxelAnisotropicSampler.xksl | 49 ++ .../Shaders/VoxelAnisotropicWriter_Float4.cs | 23 + .../VoxelAnisotropicWriter_Float4.xksl | 92 +++ .../Layout/Shaders/VoxelIsotropicSampler.cs | 23 + .../Layout/Shaders/VoxelIsotropicSampler.xksl | 40 + .../Shaders/VoxelIsotropicWriter_Float4.cs | 24 + .../Shaders/VoxelIsotropicWriter_Float4.xksl | 42 + .../Layout/Shaders/VoxelLayout_Float4.cs | 9 + .../Layout/Shaders/VoxelLayout_Float4.xksl | 12 + .../Layout/VoxelLayoutAnisotropic.cs | 90 +++ .../Layout/VoxelLayoutAnisotropicPaired.cs | 89 +++ .../Layout/VoxelLayoutIsotropic.cs | 127 ++++ .../VoxelModifierApplierAnisotropic.cs | 9 + .../VoxelModifierApplierAnisotropic.xksl | 7 + ...lModifierApplierAntiAliasingAnisotropic.cs | 9 + ...odifierApplierAntiAliasingAnisotropic.xksl | 13 + .../VoxelModifierApplierOpacifyAnisotropic.cs | 9 + ...oxelModifierApplierOpacifyAnisotropic.xksl | 15 + ...VoxelModifierApplierSolidifyAnisotropic.cs | 9 + ...xelModifierApplierSolidifyAnisotropic.xksl | 13 + .../VoxelModifierApplierAnisotropicPaired.cs | 9 + ...VoxelModifierApplierAnisotropicPaired.xksl | 7 + ...ierApplierAntiAliasingAnisotropicPaired.cs | 9 + ...rApplierAntiAliasingAnisotropicPaired.xksl | 10 + ...ModifierApplierOpacifyAnisotropicPaired.cs | 9 + ...difierApplierOpacifyAnisotropicPaired.xksl | 12 + ...ierApplierOpacifyAnisotropicPaired.xksl.cs | 9 + ...odifierApplierSolidifyAnisotropicPaired.cs | 9 + ...ifierApplierSolidifyAnisotropicPaired.xksl | 10 + ...xelModifierApplierAntiAliasingIsotropic.cs | 9 + ...lModifierApplierAntiAliasingIsotropic.xksl | 8 + .../VoxelModifierApplierIsotropic.cs | 9 + .../VoxelModifierApplierIsotropic.xksl | 7 + .../VoxelModifierApplierOpacifyIsotropic.cs | 23 + .../VoxelModifierApplierOpacifyIsotropic.xksl | 8 + .../VoxelModifierApplierSolidifyIsotropic.cs | 9 + ...VoxelModifierApplierSolidifyIsotropic.xksl | 8 + .../IVoxelModifierEmissionOpacity.cs | 8 + ...oxelModifierEmissionOpacityAntiAliasing.cs | 33 + .../VoxelModifierEmissionOpacityOpacify.cs | 36 + .../VoxelModifierEmissionOpacitySolidify.cs | 32 + .../Voxelization/Modifiers/IVoxelModifier.cs | 17 + .../Voxelization/Modifiers/VoxelModifier.cs | 9 + .../Voxelization/Modifiers/VoxelModifier.xksl | 10 + .../Modifiers/VoxelModifierBase.cs | 14 + .../Voxels/Voxelization/RenderVoxelVolume.cs | 64 ++ .../StorageMethod/IVoxelStorageMethod.cs | 12 + .../VoxelStorageMethodIndirect.cs | 33 + .../Voxelization/VoxelPositionStream.cs | 9 + .../Voxelization/VoxelPositionStream.xksl | 6 + .../VoxelStorage/IVoxelStorage.cs | 18 + .../VoxelStorage/IVoxelStorageTexture.cs | 18 + .../Voxelization/VoxelStorage/LocalSamples.cs | 9 + .../VoxelStorage/LocalSamples.xksl | 4 + .../Mipmapping/VoxelMipmapHeuristic.cs | 9 + .../Mipmapping/VoxelMipmapHeuristic.xksl | 52 ++ .../Mipmapping/VoxelMipmapPhysicallyBased.cs | 9 + .../VoxelMipmapPhysicallyBased.xksl | 39 + .../VoxelMipmapPhysicallyBased.xksl.cs | 9 + .../Mipmapping/VoxelMipmapSimple.cs | 25 + .../Mipmapping/VoxelMipmapSimple.xksl | 26 + .../Processing/BufferToTexture.cs | 26 + .../Processing/BufferToTexture.xksl | 19 + .../Processing/BufferToTextureColumns.cs | 9 + .../Processing/BufferToTextureColumns.xksl | 81 ++ .../BufferToTextureColumnsEffect.cs | 68 ++ .../BufferToTextureColumnsEffect.xksl | 26 + .../Processing/BufferToTextureEffect.cs | 36 + .../Processing/BufferToTextureEffect.xksl | 9 + .../Processing/BufferToTextureKeys.cs | 13 + .../VoxelStorage/Processing/ClearBuffer.cs | 24 + .../VoxelStorage/Processing/ClearBuffer.xksl | 12 + .../Shaders/VoxelStorageClipmapShader.cs | 30 + .../Shaders/VoxelStorageClipmapShader.xksl | 105 +++ .../Shaders/VoxelStorageShader.cs | 9 + .../Shaders/VoxelStorageShader.xksl | 19 + .../VoxelStorageTextureClipmapShader.cs | 27 + .../VoxelStorageTextureClipmapShader.xksl | 179 +++++ .../Shaders/VoxelStorageTextureShader.cs | 9 + .../Shaders/VoxelStorageTextureShader.xksl | 8 + .../VoxelStorage/VoxelStorageClipmaps.cs | 368 +++++++++ .../VoxelStorage/VoxelStorageContext.cs | 35 + .../VoxelStorageTextureClipmap.cs | 192 +++++ .../VoxelStorage/VoxelStorers/IVoxelStorer.cs | 20 + .../VoxelStorers/VoxelStorerClipmap.cs | 162 ++++ .../Voxelization/VoxelVolumeComponent.cs | 65 ++ .../Voxelization/VoxelVolumeProcessor.cs | 122 +++ .../VoxelizationMethod/IVoxelizationMethod.cs | 31 + .../Shader/VoxelizationMethod.cs | 9 + .../Shader/VoxelizationMethod.xksl | 17 + .../Shader/VoxelizationMethodDominantAxis.cs | 9 + .../VoxelizationMethodDominantAxis.xksl | 48 ++ .../Shader/VoxelizationMethodSingleAxis.cs | 9 + .../Shader/VoxelizationMethodSingleAxis.xksl | 20 + .../VoxelizationMethodDominantAxis.cs | 144 ++++ .../VoxelizationMethodSingleAxis.cs | 151 ++++ .../VoxelizationMethodTriAxis.cs | 81 ++ .../Voxels/Voxelization/VoxelizationPass.cs | 47 ++ .../Voxelization/VoxelizationPassList.cs | 42 + .../Voxelization/VoxelizeToFragments.cs | 9 + .../Voxelization/VoxelizeToFragments.xksl | 35 + .../Voxelization/VoxelizeToFragmentsEffect.cs | 54 ++ .../VoxelizeToFragmentsEffect.xksl | 24 + .../Voxelization/VoxelizeToFragmentsKeys.cs | 13 + .../engine/Xenko.Voxels/Xenko.Voxels.csproj | 715 ++++++++++++++++++ .../engine/Xenko.Voxels/Xenko.Voxels.xkpkg | 5 + 216 files changed, 8370 insertions(+) create mode 100644 sources/engine/Xenko.Voxels/Module.cs create mode 100644 sources/engine/Xenko.Voxels/Properties/AssemblyInfo.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShaderKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShaderKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/IVoxelRenderer.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelDebug.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelPipelineProcessor.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxel.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShaderKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelMarchMethod.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/IVoxelMarchSet.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchBeam.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/VoxelUtils.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/IVoxelBufferWriter.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteAssign.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteMax.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/IVoxelFragmentPacker.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat16.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat32.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloatR11G11B10.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/IVoxelStorageMethod.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/VoxelStorageMethodIndirect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorage.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageContext.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/IVoxelStorer.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Xenko.Voxels.csproj create mode 100644 sources/engine/Xenko.Voxels/Xenko.Voxels.xkpkg diff --git a/build/Xenko.sln b/build/Xenko.sln index 59c20f020b..c31d6ca849 100644 --- a/build/Xenko.sln +++ b/build/Xenko.sln @@ -425,6 +425,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "fr", "fr", "{62E9A8E4-79AF- EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Xenko.Rendering", "..\sources\engine\Xenko.Rendering\Xenko.Rendering.csproj", "{AD4FDC24-B64D-4ED7-91AA-62C9EDA12FA4}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Xenko.Voxels", "..\sources\engine\Xenko.Voxels\Xenko.Voxels.csproj", "{66BE41FC-FC52-48D0-9C04-BCE8CC393020}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Xenko.Toolkit", "..\sources\tools\Xenko.Toolkit\Xenko.Toolkit.csproj", "{42F46D75-ED70-46B4-8B0F-BAB923E3AC59}" EndProject Global @@ -1519,6 +1520,18 @@ Global {AD4FDC24-B64D-4ED7-91AA-62C9EDA12FA4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {AD4FDC24-B64D-4ED7-91AA-62C9EDA12FA4}.Release|Win32.ActiveCfg = Release|Any CPU {AD4FDC24-B64D-4ED7-91AA-62C9EDA12FA4}.Release|Win32.Build.0 = Release|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Debug|Any CPU.Build.0 = Debug|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Debug|Win32.ActiveCfg = Debug|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Debug|Win32.Build.0 = Debug|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Release|Any CPU.Build.0 = Release|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Release|Win32.ActiveCfg = Release|Any CPU + {66BE41FC-FC52-48D0-9C04-BCE8CC393020}.Release|Win32.Build.0 = Release|Any CPU {42F46D75-ED70-46B4-8B0F-BAB923E3AC59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {42F46D75-ED70-46B4-8B0F-BAB923E3AC59}.Debug|Any CPU.Build.0 = Debug|Any CPU {42F46D75-ED70-46B4-8B0F-BAB923E3AC59}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU @@ -1655,6 +1668,7 @@ Global {040F754C-17F4-4B5F-B974-93F1E39D107F} = {75608B5C-1C03-4B38-810E-14EED5165E59} {62E9A8E4-79AF-4081-84D5-FEC5A0B28598} = {FC791F56-C1F1-4C41-A193-868D8197F8E2} {AD4FDC24-B64D-4ED7-91AA-62C9EDA12FA4} = {4C142567-C42B-40F5-B092-798882190209} + {66BE41FC-FC52-48D0-9C04-BCE8CC393020} = {4C142567-C42B-40F5-B092-798882190209} {42F46D75-ED70-46B4-8B0F-BAB923E3AC59} = {4C142567-C42B-40F5-B092-798882190209} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/sources/engine/Xenko.Voxels/Module.cs b/sources/engine/Xenko.Voxels/Module.cs new file mode 100644 index 0000000000..d6aa7b1a06 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Module.cs @@ -0,0 +1,17 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Reflection; +using Xenko.Core; +using Xenko.Core.Reflection; + +namespace Xenko.Voxels +{ + internal class Module + { + [ModuleInitializer] + public static void Initialize() + { + AssemblyRegistry.Register(typeof(Module).GetTypeInfo().Assembly, AssemblyCommonCategories.Assets); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Properties/AssemblyInfo.cs b/sources/engine/Xenko.Voxels/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..5550c60e8e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Properties/AssemblyInfo.cs @@ -0,0 +1,7 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Xenko.Engine" + Xenko.PublicKeys.Default)] +[assembly: InternalsVisibleTo("Xenko.Editor" + Xenko.PublicKeys.Default)] +[assembly: InternalsVisibleTo("Xenko.Assets.Presentation" + Xenko.PublicKeys.Default)] diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs new file mode 100644 index 0000000000..82241541cc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Rendering.Images; + +namespace Xenko.Rendering.Voxels.Debug +{ + public interface IVoxelVisualization + { + ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.cs new file mode 100644 index 0000000000..6360eb8f54 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.cs @@ -0,0 +1,47 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels.Debug +{ + internal static partial class ShaderMixins + { + internal partial class VoxelVisualizationRawEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "VoxelVisualizationRawShader"); + if (context.GetParam(VoxelVisualizationRawShaderKeys.Attribute) != null) + { + + { + var __mixinToCompose__ = context.GetParam(VoxelVisualizationRawShaderKeys.Attribute); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "Attribute", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("VoxelVisualizationRawEffect", new VoxelVisualizationRawEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.xksl new file mode 100644 index 0000000000..9939cb8c8d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.xksl @@ -0,0 +1,13 @@ +namespace Xenko.Rendering.Voxels.Debug +{ + effect VoxelVisualizationRawEffect + { + using params VoxelVisualizationRawShaderKeys; + + mixin VoxelVisualizationRawShader; + if (VoxelVisualizationRawShaderKeys.Attribute != null) + { + mixin compose Attribute = VoxelVisualizationRawShaderKeys.Attribute; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.cs new file mode 100644 index 0000000000..b1ec8bee7c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.cs @@ -0,0 +1,25 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels.Debug +{ + public static partial class VoxelVisualizationRawShaderKeys + { + public static readonly ValueParameterKey range = ParameterKeys.NewValue(); + public static readonly ValueParameterKey rangeOffset = ParameterKeys.NewValue(); + public static readonly ValueParameterKey mip = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl new file mode 100644 index 0000000000..2dbfaff317 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl @@ -0,0 +1,28 @@ +namespace Xenko.Rendering.Voxels.Debug +{ + shader VoxelVisualizationRawShader : ImageEffectShader + { + compose IVoxelSampler Attribute; + float2 range; + float rangeOffset; + float mip; + + stage override float4 Shading() + { + float2 offsetRange = range + float(abs(range.y-range.x) * rangeOffset).xx; + float2 screenPos = streams.TexCoord.xy; + screenPos.y = 1.0 - screenPos.y; + + float4 color = float4(0, 0, 0, 0); + for (int i = 0; i < 200; i++) + { + color += Attribute.SampleRaw(float3(streams.TexCoord.x, lerp(offsetRange.x, offsetRange.y, (float)i / 200.0), streams.TexCoord.y), mip-1, (mip>0)?1:0, 0) * (1.0 - color.a); + if (color.a > 0.99) + { + break; + } + } + return color.xyzz + float4(0.1, 0.1, 0.1, 1.0) * (1.0 - color.a); + } + }; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShaderKeys.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShaderKeys.cs new file mode 100644 index 0000000000..a8f2901588 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShaderKeys.cs @@ -0,0 +1,12 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels.Debug +{ + public partial class VoxelVisualizationRawShaderKeys + { + public static readonly PermutationParameterKey Attribute = ParameterKeys.NewPermutation(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.cs new file mode 100644 index 0000000000..cfbedef36d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.cs @@ -0,0 +1,62 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels.Debug +{ + internal static partial class ShaderMixins + { + internal partial class VoxelVisualizationViewEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "VoxelVisualizationViewShader"); + if (context.GetParam(VoxelVisualizationViewShaderKeys.marcher) != null) + { + + { + var __mixinToCompose__ = context.GetParam(VoxelVisualizationViewShaderKeys.marcher); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "marcher", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + if (context.GetParam(MarchAttributesKeys.AttributeSamplers) != null) + { + foreach(var attr in context.GetParam(MarchAttributesKeys.AttributeSamplers)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributeSamplers", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("VoxelVisualizationViewEffect", new VoxelVisualizationViewEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl new file mode 100644 index 0000000000..3c1d647c24 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl @@ -0,0 +1,21 @@ +namespace Xenko.Rendering.Voxels.Debug +{ + effect VoxelVisualizationViewEffect + { + using params VoxelVisualizationViewShaderKeys; + using params MarchAttributesKeys; + + mixin VoxelVisualizationViewShader; + if (VoxelVisualizationViewShaderKeys.marcher != null) + { + mixin compose marcher = VoxelVisualizationViewShaderKeys.marcher; + } + if (MarchAttributesKeys.AttributeSamplers != null) + { + foreach (var attr in MarchAttributesKeys.AttributeSamplers) + { + mixin compose AttributeSamplers += (attr); + } + } + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.cs new file mode 100644 index 0000000000..4079725ebd --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.cs @@ -0,0 +1,25 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels.Debug +{ + public static partial class VoxelVisualizationViewShaderKeys + { + public static readonly ValueParameterKey background = ParameterKeys.NewValue(); + public static readonly ValueParameterKey view = ParameterKeys.NewValue(); + public static readonly ValueParameterKey viewInv = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl new file mode 100644 index 0000000000..b089a1b9ac --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl @@ -0,0 +1,28 @@ +namespace Xenko.Rendering.Voxels.Debug +{ + shader VoxelVisualizationViewShader : MarchAttributes, ImageEffectShader + { + compose VoxelMarchMethod marcher; + + float4 background; + float4x4 view; + float4x4 viewInv; + + stage override float4 Shading() + { + float2 screenPos = streams.TexCoord.xy; + screenPos.y = 1.0 - screenPos.y; + + float4 p1 = mul(float4(screenPos*2.0-1.0,1,1), viewInv); + p1.xyz/=p1.w; + float4 p2 = mul(float4(0,0,0,1), viewInv); + p2.xyz/=p2.w; + + float3 rayDir = normalize( p1.xyz - p2.xyz); + float3 rayPos = p2.xyz; + + float4 color = marcher.March(rayPos, rayDir); + return color.xyzz + background * saturate(1.0-color.a); + } + }; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShaderKeys.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShaderKeys.cs new file mode 100644 index 0000000000..3209283de1 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShaderKeys.cs @@ -0,0 +1,12 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels.Debug +{ + public partial class VoxelVisualizationViewShaderKeys + { + public static readonly PermutationParameterKey marcher = ParameterKeys.NewPermutation(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs new file mode 100644 index 0000000000..822821bf18 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Rendering.Images; + +namespace Xenko.Rendering.Voxels.Debug +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Debug")] + public class VoxelVisualizationRaw : IVoxelVisualization + { + public int Mipmap = 0; + public Vector2 Range = new Vector2(0.0f,1.0f); + public int RangeOffset = 0; + private ImageEffectShader voxelDebugEffectShader = new ImageEffectShader("VoxelVisualizationRawEffect"); + public ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr) + { + VoxelViewContext viewContext = new VoxelViewContext(context, 0); + attr.UpdateSamplingLayout("Attribute"); + attr.ApplySamplingParameters(viewContext, voxelDebugEffectShader.Parameters); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationRawShaderKeys.Attribute, attr.GetSamplingShader()); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationRawShaderKeys.mip, Mipmap); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationRawShaderKeys.rangeOffset, RangeOffset); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationRawShaderKeys.range, Range); + + return voxelDebugEffectShader; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs new file mode 100644 index 0000000000..cf3dca0d6c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core.Mathematics; +using Xenko.Core; +using Xenko.Rendering.Images; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Shadows; + +namespace Xenko.Rendering.Voxels.Debug +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Standard")] + public class VoxelVisualizationView : IVoxelVisualization + { + [NotNull] + public IVoxelMarchMethod MarchMethod { get; set; } = new VoxelMarchBeam(200, 1.0f, 1.0f); + + public Color Background = new Color(0.1f,0.1f,0.1f,1.0f); + + private ImageEffectShader voxelDebugEffectShader = new ImageEffectShader("VoxelVisualizationViewEffect"); + public ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr) + { + VoxelViewContext viewContext = new VoxelViewContext(context, 0); + Matrix ViewProjection = context.RenderContext.RenderView.ViewProjection; + + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationViewShaderKeys.view, ViewProjection); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationViewShaderKeys.viewInv, Matrix.Invert(ViewProjection)); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationViewShaderKeys.background, (Vector4)Background); + + attr.UpdateSamplingLayout("AttributeSamplers[0]"); + attr.ApplySamplingParameters(viewContext, voxelDebugEffectShader.Parameters); + MarchMethod.UpdateMarchingLayout("marcher"); + MarchMethod.ApplyMarchingParameters(voxelDebugEffectShader.Parameters); + voxelDebugEffectShader.Parameters.Set(VoxelVisualizationViewShaderKeys.marcher, MarchMethod.GetMarchingShader(0)); + + ShaderSourceCollection collection = new ShaderSourceCollection + { + attr.GetSamplingShader() + }; + voxelDebugEffectShader.Parameters.Set(MarchAttributesKeys.AttributeSamplers, collection); + + return voxelDebugEffectShader; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs new file mode 100644 index 0000000000..d1fafc34d1 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs @@ -0,0 +1,71 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Runtime.InteropServices; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Core.Storage; +using Xenko.Graphics; +using Xenko.Rendering.Images; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Shadows; +using Xenko.Rendering.SubsurfaceScattering; +using Xenko.VirtualReality; +using Xenko.Rendering.Compositing; +using Xenko.Rendering.Voxels.Debug; + +namespace Xenko.Rendering.Voxels +{ + /// + /// Renders your game. It should use current and . + /// + [Display("Forward & Voxel renderer")] + public class ForwardRendererVoxels : ForwardRenderer + { + public IVoxelRenderer VoxelRenderer { get; set; } + + protected IShadowMapRenderer ShadowMapRenderer_notPrivate; + + public VoxelDebug VoxelVisualization { get; set; } + + protected override void InitializeCore() + { + ShadowMapRenderer_notPrivate = Context.RenderSystem.RenderFeatures.OfType().FirstOrDefault()?.RenderFeatures.OfType().FirstOrDefault()?.ShadowMapRenderer; + base.InitializeCore(); + } + protected override unsafe void CollectCore(RenderContext context) + { + VoxelRenderer?.Collect(Context, ShadowMapRenderer_notPrivate); + base.CollectCore(context); + } + protected override void DrawCore(RenderContext context, RenderDrawContext drawContext) + { + using (drawContext.PushRenderTargetsAndRestore()) + { + VoxelRenderer?.Draw(drawContext, ShadowMapRenderer_notPrivate); + } + + base.DrawCore(context, drawContext); + } + + protected override void DrawView(RenderContext context, RenderDrawContext drawContext, int eyeIndex, int eyeCount) + { + base.DrawView(context, drawContext, eyeIndex, eyeCount); + + // Voxel Debug if enabled + if (VoxelVisualization != null) + { + VoxelVisualization.VoxelRenderer = VoxelRenderer; + VoxelVisualization.Draw(drawContext, viewOutputTarget); + } + } + } +} + + diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/IVoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/IVoxelRenderer.cs new file mode 100644 index 0000000000..1b9dba9d05 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/IVoxelRenderer.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Xenko.Core; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Graphics; +using Xenko.Rendering; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Shadows; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelRenderer + { + void Collect(RenderContext Context, IShadowMapRenderer ShadowMapRenderer); + + void Draw(RenderDrawContext drawContext, IShadowMapRenderer ShadowMapRenderer); + Dictionary GetProcessedVolumes(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelDebug.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelDebug.cs new file mode 100644 index 0000000000..80945d36e9 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelDebug.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Graphics; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Collections; +using Xenko.Core.Extensions; +using Xenko.Core.Mathematics; +using Xenko.Shaders; +using Xenko.Rendering.Images; +using Xenko.Rendering.Voxels; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Skyboxes; +using System.Linq; +using Xenko.Rendering.Compositing; + +namespace Xenko.Rendering.Voxels.Debug +{ + [DataContract("VoxelDebug")] + public class VoxelDebug : ImageEffect + { + [DataMemberIgnore] + public IVoxelRenderer VoxelRenderer; + protected override void InitializeCore() + { + base.InitializeCore(); + } + protected override void DrawCore(RenderDrawContext context) + { + if (!Initialized) + Initialize(context.RenderContext); + + if (VoxelRenderer == null) + { + return; + } + + Dictionary datas = VoxelRenderer.GetProcessedVolumes(); + if (datas == null) + { + return; + } + foreach (var datapairs in datas) + { + var data = datapairs.Value; + + if (!data.VisualizeVoxels || data.VoxelVisualization == null || data.VisualizationAttribute == null) + continue; + + ImageEffectShader shader = data.VoxelVisualization.GetShader(context, data.VisualizationAttribute); + + if (shader == null) + continue; + + shader.SetOutput(GetSafeOutput(0)); + + shader.Draw(context); + } + } + public void Draw(RenderDrawContext drawContext, Texture output) + { + SetOutput(output); + DrawCore(drawContext); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelPipelineProcessor.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelPipelineProcessor.cs new file mode 100644 index 0000000000..f912b671b6 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelPipelineProcessor.cs @@ -0,0 +1,35 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Collections.Generic; +using System.ComponentModel; +using Xenko.Graphics; + +namespace Xenko.Rendering.Voxels +{ + /// + /// Pipline processor for that cast shadows, to properly disable culling and depth clip. + /// + public class VoxelPipelineProcessor : PipelineProcessor + { + public List VoxelRenderStage { get; set; } = new List(); + + [DefaultValue(false)] + public bool DepthClipping { get; set; } = false; + + public override void Process(RenderNodeReference renderNodeReference, ref RenderNode renderNode, RenderObject renderObject, PipelineStateDescription pipelineState) + { + // Disable culling and depth clip + if (VoxelRenderStage.Contains(renderNode.RenderStage)) + { + pipelineState.RasterizerState = new RasterizerStateDescription(CullMode.None) { DepthClipEnable = DepthClipping }; + pipelineState.DepthStencilState.DepthBufferEnable = false; + pipelineState.DepthStencilState.DepthBufferWriteEnable = false; + pipelineState.DepthStencilState.StencilEnable = false; + pipelineState.DepthStencilState.StencilWriteMask = 0; + pipelineState.DepthStencilState.StencilMask = 0; + pipelineState.BlendState.RenderTarget0.BlendEnable = false; + pipelineState.BlendState.IndependentBlendEnable = false; + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs new file mode 100644 index 0000000000..55aab9b7d8 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs @@ -0,0 +1,182 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Core.Storage; +using Xenko.Core.Threading; +using Xenko.Graphics; +using Xenko.Rendering.Shadows; +using Xenko.Rendering.Voxels; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + /// + /// A render feature that computes and uploads info for voxelization + /// + public class VoxelRenderFeature : SubRenderFeature + { + [DataMemberIgnore] + public static readonly PropertyKey> CurrentProcessedVoxelVolumes = new PropertyKey>("VoxelRenderFeature.CurrentProcessedVoxelVolumes", typeof(VoxelRenderFeature)); + + private Dictionary renderVoxelVolumeData; + + [DataMember] + public RenderStage VoxelizerRenderStage { get; set; } + + private LogicalGroupReference VoxelizerStorerCasterKey; + private StaticObjectPropertyKey renderEffectKey; + + protected override void InitializeCore() + { + base.InitializeCore(); + renderEffectKey = ((RootEffectRenderFeature)RootRenderFeature).RenderEffectKey; + VoxelizerStorerCasterKey = ((RootEffectRenderFeature)RootRenderFeature).CreateViewLogicalGroup("VoxelizerStorer"); + } + + public override void PrepareEffectPermutations(RenderDrawContext context) + { + renderVoxelVolumeData = Context.VisibilityGroup.Tags.Get(CurrentProcessedVoxelVolumes); + if (renderVoxelVolumeData == null) return; + + + var renderEffects = RootRenderFeature.RenderData.GetData(renderEffectKey); + int effectSlotCount = ((RootEffectRenderFeature)RootRenderFeature).EffectPermutationSlotCount; + + + var rootEffectRenderFeature = ((RootEffectRenderFeature)RootRenderFeature); + + if (rootEffectRenderFeature == null) return; + + foreach (var processedVolumeKeyValue in renderVoxelVolumeData) + { + var processedVolume = processedVolumeKeyValue.Value; + + if (processedVolume == null) continue; + + foreach (VoxelizationPass pass in processedVolume.passList.passes) + { + var viewFeature = pass.view.Features[RootRenderFeature.Index]; + if (processedVolume == null) + continue; + + pass.storer.UpdateVoxelizationLayout("Storage"); + for (int i = 0; i < pass.AttributesIndirect.Count; i++) + { + var attr = pass.AttributesIndirect[i]; + attr.UpdateVoxelizationLayout("AttributesIndirect["+i+"]"); + } + + var effectSlot = rootEffectRenderFeature.GetEffectPermutationSlot(RenderSystem.RenderStages[pass.view.RenderStages[0].Index]); + + foreach (var renderObject in pass.view.RenderObjects) + { + var staticObjectNode = renderObject.StaticObjectNode; + if (staticObjectNode == null) + continue; + + var staticEffectObjectNode = staticObjectNode * effectSlotCount + effectSlot.Index; + if (staticEffectObjectNode == null) + continue; + + RenderEffect renderEffect = null; + try + { + renderEffect = renderEffects[staticEffectObjectNode]; + } + catch + { + } + if (renderEffect != null) + { + renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.Storage, pass.source); + renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.RequireGeometryShader, pass.storer.RequireGeometryShader() || pass.method.RequireGeometryShader()); + renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount, pass.storer.GeometryShaderOutputCount() * pass.method.GeometryShaderOutputCount()); + } + } + } + } + } + public override void Prepare(RenderDrawContext context) + { + renderVoxelVolumeData = Context.VisibilityGroup.Tags.Get(CurrentProcessedVoxelVolumes); + if (renderVoxelVolumeData == null) return; + + foreach (var processedVolumeKeyValue in renderVoxelVolumeData) + { + var processedVolume = processedVolumeKeyValue.Value; + foreach (VoxelizationPass pass in processedVolume.passList.passes) + { + var viewFeature = pass.view.Features[RootRenderFeature.Index]; + + + var viewParameters = new ParameterCollection(); + // Find a PerView layout from an effect in normal state + ViewResourceGroupLayout firstViewLayout = null; + foreach (var viewLayout in viewFeature.Layouts) + { + // Only process view layouts in normal state + if (viewLayout.State != RenderEffectState.Normal) + continue; + + var viewLighting = viewLayout.GetLogicalGroup(VoxelizerStorerCasterKey); + if (viewLighting.Hash != ObjectId.Empty) + { + firstViewLayout = viewLayout; + break; + } + } + + // Nothing found for this view (no effects in normal state) + if (firstViewLayout == null) + continue; + + + var firstViewLighting = firstViewLayout.GetLogicalGroup(VoxelizerStorerCasterKey); + + // Prepare layout (should be similar for all PerView) + { + + // Generate layout + var viewParameterLayout = new ParameterCollectionLayout(); + viewParameterLayout.ProcessLogicalGroup(firstViewLayout, ref firstViewLighting); + + viewParameters.UpdateLayout(viewParameterLayout); + } + + + + ParameterCollection VSViewParameters = viewParameters; + + pass.storer.ApplyVoxelizationParameters(VSViewParameters); + foreach (var attr in processedVolume.Attributes) + { + attr.Attribute.ApplyVoxelizationParameters(VSViewParameters); + } + + foreach (var viewLayout in viewFeature.Layouts) + { + + + if (viewLayout.State != RenderEffectState.Normal) + continue; + + var voxelizerStorer = viewLayout.GetLogicalGroup(VoxelizerStorerCasterKey); + if (voxelizerStorer.Hash == ObjectId.Empty) + continue; + + if (voxelizerStorer.Hash != firstViewLighting.Hash) + throw new InvalidOperationException("PerView VoxelizerStorer layout differs between different RenderObject in the same RenderView"); + + + var resourceGroup = viewLayout.Entries[pass.view.Index].Resources; + resourceGroup.UpdateLogicalGroup(ref voxelizerStorer, VSViewParameters); + } + } + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs new file mode 100644 index 0000000000..8413b16658 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs @@ -0,0 +1,260 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Xenko.Core; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Shaders; +using Xenko.Graphics; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Voxels; +using Xenko.Core.Extensions; +using System.Linq; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public class VoxelRenderer : IVoxelRenderer + { + [DataMemberIgnore] + public static readonly PropertyKey> CurrentRenderVoxelVolumes = new PropertyKey>("VoxelRenderer.CurrentRenderVoxelVolumes", typeof(VoxelRenderer)); + [DataMemberIgnore] + public static readonly PropertyKey> CurrentProcessedVoxelVolumes = new PropertyKey>("VoxelRenderer.CurrentProcessedVoxelVolumes", typeof(VoxelRenderer)); + private Dictionary renderVoxelVolumes; + private Dictionary renderVoxelVolumeData; + + + readonly ProfilingKey PassesVoxelizationProfilingKey = new ProfilingKey("Voxelization: Passes"); + readonly ProfilingKey FragmentVoxelizationProfilingKey = new ProfilingKey("Voxelization: Passes - Fragments"); + readonly ProfilingKey BufferProcessingVoxelizationProfilingKey = new ProfilingKey("Voxelization: Arrangement"); + readonly ProfilingKey MipmappingVoxelizationProfilingKey = new ProfilingKey("Voxelization: Mipmapping"); + + public List VoxelStages { get; set; } = new List(); + + public Dictionary GetProcessedVolumes() + { + return renderVoxelVolumeData; + } + public virtual void Collect(RenderContext Context, Shadows.IShadowMapRenderer ShadowMapRenderer) + { + renderVoxelVolumes = Context.VisibilityGroup.Tags.Get(CurrentRenderVoxelVolumes); + renderVoxelVolumeData = Context.VisibilityGroup.Tags.Get(CurrentProcessedVoxelVolumes); + + if (renderVoxelVolumes == null || renderVoxelVolumes.Count == 0) + return; + + //Setup per volume passes and texture allocations + foreach ( var pair in renderVoxelVolumes ) + { + var dataVolume = pair.Value; + var bounds = dataVolume.VolumeSize; + + ProcessedVoxelVolume processedVolume; + if (!renderVoxelVolumeData.TryGetValue(pair.Key, out processedVolume)) + { + processedVolume = new ProcessedVoxelVolume(); + renderVoxelVolumeData.Add(pair.Key, processedVolume); + } + + + //Setup matrix + Vector3 matScale = dataVolume.VolumeSize; + Vector3 matTrans = dataVolume.VolumeTranslation; + + Matrix corMatrix = Matrix.Scaling(matScale) * Matrix.Translation(matTrans); + VoxelStorageContext storageContext = new VoxelStorageContext + { + device = Context.GraphicsDevice, + Extents = bounds, + VoxelSize = dataVolume.AproxVoxelSize, + Matrix = corMatrix + }; + + if (dataVolume.VoxelGridSnapping) + { + matTrans /= storageContext.RealVoxelSize(); + matTrans.X = (float)Math.Floor(matTrans.X); + matTrans.Y = (float)Math.Floor(matTrans.Y); + matTrans.Z = (float)Math.Floor(matTrans.Z); + matTrans *= storageContext.RealVoxelSize(); + + corMatrix = Matrix.Scaling(matScale) * Matrix.Translation(matTrans); + storageContext.Matrix = corMatrix; + } + storageContext.Translation = matTrans; + storageContext.VoxelSpaceTranslation = matTrans / storageContext.RealVoxelSize(); + + //Update storage + dataVolume.Storage.UpdateFromContext(storageContext); + + //Transfer voxelization info + processedVolume.VisualizeVoxels = dataVolume.VisualizeVoxels; + processedVolume.Storage = dataVolume.Storage; + processedVolume.StorageContext = storageContext; + processedVolume.VoxelizationMethod = dataVolume.VoxelizationMethod; + processedVolume.VoxelVisualization = dataVolume.VoxelVisualization; + processedVolume.VisualizationAttribute = dataVolume.VisualizationAttribute; + processedVolume.Voxelize = dataVolume.Voxelize; + processedVolume.OutputAttributes = dataVolume.Attributes; + + processedVolume.Attributes.Clear(); + processedVolume.passList.Clear(); + processedVolume.groupedPasses.Clear(); + + processedVolume.passList.defaultVoxelizationMethod = dataVolume.VoxelizationMethod; + + + //Create final list of attributes (including temporary ones) + foreach (var attr in dataVolume.Attributes) + { + attr.CollectAttributes(processedVolume.Attributes, VoxelizationStage.Initial, true); + } + + //Allocate textures and space in the temporary buffer + foreach (var attr in processedVolume.Attributes) + { + attr.Attribute.PrepareLocalStorage(storageContext, dataVolume.Storage); + if (attr.Output) + { + attr.Attribute.PrepareOutputStorage(storageContext, dataVolume.Storage); + } + else + { + attr.Attribute.ClearOutputStorage(); + } + } + dataVolume.Storage.UpdateTempStorage(storageContext); + + //Create list of voxelization passes that need to be done + dataVolume.Storage.CollectVoxelizationPasses(processedVolume, storageContext); + + //Group voxelization passes where the RenderStage can be shared + //TODO: Group identical attributes + for (int i = 0; i < processedVolume.passList.passes.Count; i++) + { + bool added = false; + var passA = processedVolume.passList.passes[i]; + for (int group = 0; group < processedVolume.groupedPasses.Count; group++) + { + var passB = processedVolume.groupedPasses[group][0]; + if ( + passB.storer.CanShareRenderStage(passA.storer) + && passB.method.CanShareRenderStage(passA.method) + && passB.AttributesDirect.SequenceEqual(passA.AttributesDirect) + && passB.AttributesIndirect.SequenceEqual(passA.AttributesIndirect) + && passB.AttributesTemp.SequenceEqual(passA.AttributesTemp) + ) + { + processedVolume.groupedPasses[group].Add(passA); + added = true; + break; + } + } + if (!added) + { + List newGroup = new List + { + passA + }; + processedVolume.groupedPasses.Add(newGroup); + } + } + + if (VoxelStages.Count < processedVolume.groupedPasses.Count) + { + throw new ArgumentOutOfRangeException(processedVolume.groupedPasses.Count.ToString() + " Render Stages required for voxelization, only " + VoxelStages.Count.ToString() + " provided."); + } + + //Finish preparing the passes, collecting views and setting up shader sources and shadows + for (int group = 0; group < processedVolume.groupedPasses.Count; group++) + { + foreach(var pass in processedVolume.groupedPasses[group]) + { + pass.renderStage = VoxelStages[group]; + pass.source = pass.storer.GetVoxelizationShader(pass, processedVolume); + pass.view.RenderStages.Add(pass.renderStage); + + Context.RenderSystem.Views.Add(pass.view); + Context.VisibilityGroup.TryCollect(pass.view); + + if (pass.requireShadows) + { + ShadowMapRenderer?.RenderViewsWithShadows.Add(pass.view); + } + } + } + } + } + public virtual void Draw(RenderDrawContext drawContext, Shadows.IShadowMapRenderer ShadowMapRenderer) + { + if (renderVoxelVolumes == null || renderVoxelVolumes.Count == 0) + return; + + var context = drawContext; + + using (drawContext.PushRenderTargetsAndRestore()) + { + // Draw all shadow views generated for the current view + foreach (var processedVolumeKeyValue in renderVoxelVolumeData) + { + var processedVolume = processedVolumeKeyValue.Value; + if (!processedVolume.Voxelize) continue; + + VoxelStorageContext storageContext = processedVolume.StorageContext; + + using (drawContext.QueryManager.BeginProfile(Color.Black, PassesVoxelizationProfilingKey)) + { + foreach (VoxelizationPass pass in processedVolume.passList.passes) + { + RenderView voxelizeRenderView = pass.view; + + if (pass.requireShadows) + { + //Render Shadow Maps + RenderView oldView = drawContext.RenderContext.RenderView; + + drawContext.RenderContext.RenderView = voxelizeRenderView; + ShadowMapRenderer.Draw(drawContext); + drawContext.RenderContext.RenderView = oldView; + } + + //Render/Collect voxel fragments + using (drawContext.QueryManager.BeginProfile(Color.Black, FragmentVoxelizationProfilingKey)) + { + using (drawContext.PushRenderTargetsAndRestore()) + { + pass.method.Render(storageContext, context, pass.view); + } + } + } + foreach (VoxelizationPass pass in processedVolume.passList.passes) + { + pass.method.Reset(); + } + } + + //Fill and write to voxel volume + using (drawContext.QueryManager.BeginProfile(Color.Black, BufferProcessingVoxelizationProfilingKey)) + { + processedVolume.Storage.PostProcess(storageContext, context, processedVolume); + } + + //Mipmap + using (drawContext.QueryManager.BeginProfile(Color.Black, MipmappingVoxelizationProfilingKey)) + { + foreach (var attr in processedVolume.Attributes) + { + if (attr.Output) + { + attr.Attribute.PostProcess(context); + } + } + } + } + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs new file mode 100644 index 0000000000..e32bbc26e4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Xenko.Rendering.Voxels +{ + public struct VoxelViewContext + { + public int ViewIndex; + public bool IsVoxelView; + public VoxelViewContext(RenderDrawContext context, int viewIndex) + { + ViewIndex = viewIndex; + IsVoxelView = ViewIndex != 0; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.cs new file mode 100644 index 0000000000..38d86d154c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.cs @@ -0,0 +1,118 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +using Xenko.Rendering.Data; +using Xenko.Rendering.Materials; +namespace Xenko.Rendering.Voxels +{ + internal static partial class ShaderMixins + { + internal partial class XenkoLightingVXGI : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + ShaderSourceCollection directLightGroups = context.GetParam(LightingKeys.DirectLightGroups); + if (directLightGroups != null) + { + foreach(ShaderSource directLightGroup in directLightGroups) + + { + + { + var __mixinToCompose__ = (directLightGroup); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "directLightGroups", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + ShaderSourceCollection environmentLights = context.GetParam(LightingKeys.EnvironmentLights); + if (environmentLights != null) + { + foreach(ShaderSource environmentLight in environmentLights) + + { + + { + var __mixinToCompose__ = (environmentLight); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "environmentLights", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("XenkoLightingVXGI", new XenkoLightingVXGI()); + } + } + } + internal static partial class ShaderMixins + { + internal partial class XenkoForwardShadingEffectVXGI : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "XenkoEffectBase"); + ShaderSource extensionPixelStageSurfaceShaders = context.GetParam(MaterialKeys.PixelStageSurfaceShaders); + if (extensionPixelStageSurfaceShaders != null) + { + context.Mixin(mixin, "MaterialSurfacePixelStageCompositor"); + + { + var __mixinToCompose__ = (extensionPixelStageSurfaceShaders); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "materialPixelStage", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + + { + var __mixinToCompose__ = context.GetParam(MaterialKeys.PixelStageStreamInitializer); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "streamInitializerPixelStage", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + ShaderSource extensionPixelStageSurfaceFilter = context.GetParam(MaterialKeys.PixelStageSurfaceFilter); + if (extensionPixelStageSurfaceFilter != null) + { + context.Mixin(mixin, (extensionPixelStageSurfaceFilter)); + } + } + context.Mixin(mixin, "XenkoLightingVXGI"); + if (context.ChildEffectName == "VoxelizeToFragmentsEffect") + { + context.Mixin(mixin, "VoxelizeToFragmentsEffect"); + return; + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("XenkoForwardShadingEffectVXGI", new XenkoForwardShadingEffectVXGI()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.xksl new file mode 100644 index 0000000000..7f94f27fbb --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.xksl @@ -0,0 +1,73 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Rendering.Data; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + partial effect XenkoLightingVXGI + { + using params LightingKeys; + + // ----------------------------------------------- + // Add light groups + // ----------------------------------------------- + ShaderSourceCollection directLightGroups = LightingKeys.DirectLightGroups; + if (directLightGroups != null) + { + foreach(ShaderSource directLightGroup in directLightGroups) + { + // Use parenthesis (...) to avoid lightGroup to be interpreted as a mixin named "lightGroup" + mixin compose directLightGroups += (directLightGroup); + } + } + + // ----------------------------------------------- + // Add environment light groups + // ----------------------------------------------- + ShaderSourceCollection environmentLights = LightingKeys.EnvironmentLights; + if (environmentLights != null) + { + foreach(ShaderSource environmentLight in environmentLights) + { + // Use parenthesis (...) to avoid lightGroup to be interpreted as a mixin named "lightGroup" + mixin compose environmentLights += (environmentLight); + } + } + } + + /// + /// Forward shading effect + /// + effect XenkoForwardShadingEffectVXGI + { + using params MaterialKeys; + + // Derive from XenkoEffectBase + mixin XenkoEffectBase; + + // ----------------------------------------------- + // Mix material and lighting shading for Pixel Shader + // ----------------------------------------------- + ShaderSource extensionPixelStageSurfaceShaders = MaterialKeys.PixelStageSurfaceShaders; + if (extensionPixelStageSurfaceShaders != null) + { + mixin MaterialSurfacePixelStageCompositor; + mixin compose materialPixelStage = (extensionPixelStageSurfaceShaders); + mixin compose streamInitializerPixelStage = MaterialKeys.PixelStageStreamInitializer; + + ShaderSource extensionPixelStageSurfaceFilter = MaterialKeys.PixelStageSurfaceFilter; + if (extensionPixelStageSurfaceFilter != null) + { + mixin (extensionPixelStageSurfaceFilter); + } + } + + // ----------------------------------------------- + // Add direct and environment light groups + // ----------------------------------------------- + mixin XenkoLightingVXGI; + + mixin child VoxelizeToFragmentsEffect; + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxel.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxel.cs new file mode 100644 index 0000000000..40504cc8bc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxel.cs @@ -0,0 +1,38 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Rendering.Lights; + +namespace Xenko.Rendering.Voxels.VoxelGI +{ + /// + /// A light casting from a voxel representation. + /// + [DataContract("LightVoxel")] + [Display("Voxel")] + public class LightVoxel : IEnvironmentLight + { + [DataMember(1)] + public VoxelVolumeComponent Volume { get; set; } + [DataMember(10)] + public int AttributeIndex { get; set; } = 0; + + [DataMember(20)] + public IVoxelMarchSet DiffuseMarcher { get; set; } = new VoxelMarchSetHemisphere6(new VoxelMarchConePerMipmap()); + [DataMember(30)] + public IVoxelMarchMethod SpecularMarcher { get; set; } = new VoxelMarchCone(30, 0.5f, 1.0f); + + [DataMember(40)] + public float BounceIntensityScale { get; set; } + [DataMember(50)] + public float SpecularIntensityScale { get; set; } + + public bool Update(RenderLight light) + { + return true; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.cs new file mode 100644 index 0000000000..6e95231d59 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.cs @@ -0,0 +1,75 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +using Xenko.Rendering.Data; +using Xenko.Rendering.Lights; +namespace Xenko.Rendering.Voxels.VoxelGI +{ + internal static partial class ShaderMixins + { + internal partial class LightVoxelEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "LightVoxelShader"); + if (context.GetParam(LightVoxelShaderKeys.diffuseMarcher) != null) + { + + { + var __mixinToCompose__ = context.GetParam(LightVoxelShaderKeys.diffuseMarcher); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "diffuseMarcher", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + if (context.GetParam(LightVoxelShaderKeys.specularMarcher) != null) + { + + { + var __mixinToCompose__ = context.GetParam(LightVoxelShaderKeys.specularMarcher); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "specularMarcher", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + if (context.GetParam(MarchAttributesKeys.AttributeSamplers) != null) + { + foreach(var attr in context.GetParam(MarchAttributesKeys.AttributeSamplers)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributeSamplers", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("LightVoxelEffect", new LightVoxelEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.xksl new file mode 100644 index 0000000000..e5e6fca5f1 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.xksl @@ -0,0 +1,34 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Rendering.Data; +using Xenko.Rendering.Lights; + +namespace Xenko.Rendering.Voxels.VoxelGI +{ + /// + /// Base effect + /// + effect LightVoxelEffect + { + using params LightVoxelShaderKeys; + using params MarchAttributesKeys; + + mixin LightVoxelShader; + + if (LightVoxelShaderKeys.diffuseMarcher != null) + { + mixin compose diffuseMarcher = LightVoxelShaderKeys.diffuseMarcher; + } + if (LightVoxelShaderKeys.specularMarcher != null) + { + mixin compose specularMarcher = LightVoxelShaderKeys.specularMarcher; + } + if (MarchAttributesKeys.AttributeSamplers!=null) + { + foreach (var attr in MarchAttributesKeys.AttributeSamplers) + { + mixin compose AttributeSamplers += (attr); + } + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs new file mode 100644 index 0000000000..0a424f4aec --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs @@ -0,0 +1,192 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using System; +using System.Collections.Generic; +using Xenko.Core.Collections; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Graphics; +using Xenko.Rendering.Skyboxes; +using Xenko.Shaders; +using Xenko.Rendering.Voxels; +using Xenko.Rendering.Shadows; +using Xenko.Rendering.Lights; +using Xenko.Engine.Processors; + +namespace Xenko.Rendering.Voxels.VoxelGI +{ + /// + /// Light renderer for . + /// + public class LightVoxelRenderer : LightGroupRendererBase + { + private readonly Dictionary lightShaderGroupsPerVoxel = new Dictionary(); + private PoolListStruct pool = new PoolListStruct(8, CreateLightVoxelShaderGroup); + + public override Type[] LightTypes { get; } = { typeof(LightVoxel) }; + + public LightVoxelRenderer() + { + IsEnvironmentLight = true; + } + + + public override void Reset() + { + base.Reset(); + + foreach (var lightShaderGroup in lightShaderGroupsPerVoxel) + lightShaderGroup.Value.Reset(); + + lightShaderGroupsPerVoxel.Clear(); + pool.Reset(); + } + + /// + public override void ProcessLights(ProcessLightsParameters parameters) + { + foreach (var index in parameters.LightIndices) + { + // For now, we allow only one cubemap at once + var light = parameters.LightCollection[index]; + + // Prepare LightVoxelShaderGroup + LightVoxelShaderGroup lightShaderGroup; + if (!lightShaderGroupsPerVoxel.TryGetValue(light, out lightShaderGroup)) + { + lightShaderGroup = pool.Add(); + lightShaderGroup.Light = light; + + lightShaderGroupsPerVoxel.Add(light, lightShaderGroup); + } + } + + // Consume all the lights + parameters.LightIndices.Clear(); + } + + public override void UpdateShaderPermutationEntry(ForwardLightingRenderFeature.LightShaderPermutationEntry shaderEntry) + { + foreach (var cubemap in lightShaderGroupsPerVoxel) + { + shaderEntry.EnvironmentLights.Add(cubemap.Value); + } + } + + private static LightVoxelShaderGroup CreateLightVoxelShaderGroup() + { + return new LightVoxelShaderGroup(new ShaderMixinGeneratorSource("LightVoxelEffect")); + } + + private class LightVoxelShaderGroup : LightShaderGroup + { + private ValueParameterKey intensityKey; + private ValueParameterKey specularIntensityKey; + + private PermutationParameterKey diffuseMarcherKey; + private PermutationParameterKey specularMarcherKey; + private PermutationParameterKey attributeSamplersKey; + + public RenderLight Light { get; set; } + + public LightVoxelShaderGroup(ShaderSource mixin) : base(mixin) + { + HasEffectPermutations = true; + } + IVoxelAttribute GetTraceAttr() + { + var lightVoxel = ((LightVoxel)Light.Type); + if (lightVoxel.Volume == null) + { + throw new ArgumentNullException("No Voxel Volume Component selected for voxel light."); + } + //ProcessedVoxelVolume processedVolume = Voxels.VoxelRenderer.GetDataForComponent(lightVoxel.Volume); + var voxelVolumeProcessor = lightVoxel.Volume.Entity.EntityManager.GetProcessor(); + if (voxelVolumeProcessor == null) + return null; + ProcessedVoxelVolume processedVolume = voxelVolumeProcessor.GetProcessedVolumeForComponent(lightVoxel.Volume); + if (processedVolume == null) + return null; + + if (processedVolume.OutputAttributes.Count > lightVoxel.AttributeIndex) + { + return processedVolume.OutputAttributes[lightVoxel.AttributeIndex]; + } + else + { + throw new ArgumentOutOfRangeException("Tried to access attribute index " + lightVoxel.AttributeIndex.ToString() + " (zero-indexed) when the Voxel Volume Component has only " + processedVolume.OutputAttributes.Count.ToString() + " attributes."); + } + } + public override void UpdateLayout(string compositionName) + { + base.UpdateLayout(compositionName); + + intensityKey = LightVoxelShaderKeys.Intensity.ComposeWith(compositionName); + specularIntensityKey = LightVoxelShaderKeys.SpecularIntensity.ComposeWith(compositionName); + + diffuseMarcherKey = LightVoxelShaderKeys.diffuseMarcher.ComposeWith(compositionName); + specularMarcherKey = LightVoxelShaderKeys.specularMarcher.ComposeWith(compositionName); + attributeSamplersKey = MarchAttributesKeys.AttributeSamplers.ComposeWith(compositionName); + + if (GetTraceAttr() != null) + { + if (((LightVoxel)Light.Type).DiffuseMarcher != null) + ((LightVoxel)Light.Type).DiffuseMarcher.UpdateMarchingLayout("diffuseMarcher." + compositionName); + if (((LightVoxel)Light.Type).SpecularMarcher != null) + ((LightVoxel)Light.Type).SpecularMarcher.UpdateMarchingLayout("specularMarcher." + compositionName); + GetTraceAttr().UpdateSamplingLayout("AttributeSamplers[0]." + compositionName); + } + } + + public override void ApplyEffectPermutations(RenderEffect renderEffect) + { + if (GetTraceAttr() != null) + { + ShaderSourceCollection collection = new ShaderSourceCollection + { + GetTraceAttr().GetSamplingShader() + }; + renderEffect.EffectValidator.ValidateParameter(attributeSamplersKey, collection); + + if (((LightVoxel)Light.Type).DiffuseMarcher != null) + renderEffect.EffectValidator.ValidateParameter(diffuseMarcherKey, ((LightVoxel)Light.Type).DiffuseMarcher.GetMarchingShader(0)); + if (((LightVoxel)Light.Type).SpecularMarcher != null) + renderEffect.EffectValidator.ValidateParameter(specularMarcherKey, ((LightVoxel)Light.Type).SpecularMarcher.GetMarchingShader(0)); + } + } + + public override void ApplyViewParameters(RenderDrawContext context, int viewIndex, ParameterCollection parameters) + { + VoxelViewContext viewContext = new VoxelViewContext(context, viewIndex); + base.ApplyViewParameters(context, viewIndex, parameters); + + var lightVoxel = ((LightVoxel)Light.Type); + + var intensity = Light.Intensity; + var intensityBounceScale = lightVoxel.BounceIntensityScale; + var specularIntensity = lightVoxel.SpecularIntensityScale * intensity; + + if (viewContext.IsVoxelView) + { + intensity *= intensityBounceScale / 3.141592f; + specularIntensity = 0.0f; + } + + if (lightVoxel.Volume == null) + return; + + parameters.Set(intensityKey, intensity); + parameters.Set(specularIntensityKey, specularIntensity); + + if (GetTraceAttr() != null) + { + lightVoxel.DiffuseMarcher?.ApplyMarchingParameters(parameters); + lightVoxel.SpecularMarcher?.ApplyMarchingParameters(parameters); + GetTraceAttr().ApplySamplingParameters(viewContext, parameters); + } + } + } + } +} + diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.cs new file mode 100644 index 0000000000..ad76088540 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.cs @@ -0,0 +1,25 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +using Xenko.Rendering.Lights; +namespace Xenko.Rendering.Voxels.VoxelGI +{ + public static partial class LightVoxelShaderKeys + { + public static readonly ValueParameterKey Intensity = ParameterKeys.NewValue(); + public static readonly ValueParameterKey SpecularIntensity = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.xksl new file mode 100644 index 0000000000..3dc5c2292f --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.xksl @@ -0,0 +1,45 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Rendering.Lights; +namespace Xenko.Rendering.Voxels.VoxelGI +{ + /// + /// Defines a Voxel environment light + /// + shader LightVoxelShader : MarchAttributes, Camera, Texturing, EnvironmentLight, MaterialPixelShadingStream, NormalStream, PositionStream4, Transformation + { + cbuffer PerView.Lighting + { + float Intensity; + float SpecularIntensity; + } + + compose VoxelMarchSet diffuseMarcher; + compose VoxelRadiusMarchMethod specularMarcher; + + override void PrepareEnvironmentLight() + { + base.PrepareEnvironmentLight(); + if (Intensity > 0.0) + { + float3 worldPos = streams.PositionWS; + + float3 tan = normalize(cross(streams.normalWS.xyz, normalize(float3(1, 1, 1)))); + float3 bitan = cross(tan, streams.normalWS.xyz); + float3x3 tangentMatrix = float3x3(tan, bitan, streams.normalWS.xyz); + + float4 reflLighting = float4(0, 0, 0, 0); + + float3 startPos = worldPos + streams.normalWS.xyz * specularMarcher.StepSizeRadius(1.0); + + reflLighting = diffuseMarcher.March(worldPos, streams.normalWS.xyz); + + streams.envLightDiffuseColor = reflLighting.rgb * Intensity; + if (SpecularIntensity > 0.0) + streams.envLightSpecularColor = specularMarcher.MarchRadius(startPos, reflect(-streams.viewWS, streams.normalWS), sqrt(streams.alphaRoughness)).rgb * SpecularIntensity; + else + streams.envLightSpecularColor = float4(0,0,0,0); + } + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShaderKeys.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShaderKeys.cs new file mode 100644 index 0000000000..731df07aa6 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShaderKeys.cs @@ -0,0 +1,14 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using Xenko.Shaders; +using Xenko.Rendering.Lights; + +namespace Xenko.Rendering.Voxels.VoxelGI +{ + public partial class LightVoxelShaderKeys + { + public static readonly PermutationParameterKey diffuseMarcher = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey specularMarcher = ParameterKeys.NewPermutation(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelMarchMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelMarchMethod.cs new file mode 100644 index 0000000000..3dbaf19a7a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelMarchMethod.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelMarchMethod + { + ShaderSource GetMarchingShader(int attrID); + void UpdateMarchingLayout(string compositionName); + void ApplyMarchingParameters(ParameterCollection parameters); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.xksl new file mode 100644 index 0000000000..cf7d495ca3 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.xksl @@ -0,0 +1,34 @@ +namespace Xenko.Rendering.Voxels +{ + shader IVoxelSampler + { + float4 Sample(float3 position, float3 normal, float diameter) + { + return 0; + } + float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) + { + return 0; + } + float4 SampleNearestMip(float3 position, float3 normal, float diameter) + { + return 0; + } + float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + return float4(1, 0, 0, 0); + } + float VoxelSize() + { + return 1.0; + } + float4 Test() + { + return float4(1,0,0,1); + } + float4 ComputeLocal(float3 position) + { + return 0; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/IVoxelMarchSet.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/IVoxelMarchSet.cs new file mode 100644 index 0000000000..2a3ab7e9f0 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/IVoxelMarchSet.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelMarchSet + { + ShaderSource GetMarchingShader(int attrID); + void UpdateMarchingLayout(string compositionName); + void ApplyMarchingParameters(ParameterCollection parameters); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.xksl new file mode 100644 index 0000000000..920c53a8e2 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.xksl @@ -0,0 +1,4 @@ +shader VoxelMarchSet +{ + float4 March(float3 rayPos, float3 rayDir){ return float4(0, 0, 0, 0); } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl new file mode 100644 index 0000000000..87d7e21c39 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl @@ -0,0 +1,42 @@ +shader VoxelMarchSetHemisphere12 : VoxelMarchSet +{ + compose VoxelMarchMethod Marcher; + override float4 March(float3 rayPos, float3 rayDir) + { + float3 tan = normalize(cross(rayDir, normalize(float3(1, 1, 1)))); + float3 bitan = cross(tan, rayDir); + float3x3 tangentMatrix = float3x3(tan, bitan, rayDir); + + float3 startPos = rayPos + rayDir * Marcher.StepSize(); + + float4 reflLighting = float4(0, 0, 0, 0); + + rayDir = mul(float3(-0.38, -0.37, 0.84), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + rayDir = mul(float3(-0.31, 0.43, 0.84), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + rayDir = mul(float3(0.36, 0.39, 0.84), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + rayDir = mul(float3(0.36, -0.39, 0.84), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + + rayDir = mul(float3(-0.87, 0.41, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(-0.35, 0.90, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(0.40, 0.88, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(0.92, 0.31, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(0.87, -0.43, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(0.30, -0.92, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(-0.43, -0.87, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + rayDir = mul(float3(-0.93, -0.28, 0.22), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + + return reflLighting; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl new file mode 100644 index 0000000000..f2f74d081e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl @@ -0,0 +1,40 @@ +shader VoxelMarchSetHemisphere6 : VoxelMarchSet +{ + compose VoxelMarchMethod Marcher; + override float4 March(float3 rayPos, float3 rayDir) + { + float3 tan = normalize(cross(rayDir, normalize(float3(1, 1, 1)))); + float3 bitan = cross(tan, rayDir); + float3x3 tangentMatrix = float3x3(tan, bitan, rayDir); + + float3 startPos = rayPos + rayDir * Marcher.StepSize(); + + float4 reflLighting = float4(0, 0, 0, 0); + + float mainDot = 1.0; + float sideDot = dot(normalize(float3(0.527, -0.723, 0.445)), float3(0, 0, 1)); + float divisor = mainDot + sideDot * 5; + mainDot /= divisor; + sideDot /= divisor; + + rayDir = mul(float3(0, 0, 1), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * mainDot; + + rayDir = mul(normalize(float3(0.85, 0.278, 0.445)), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * sideDot; + + rayDir = mul(normalize(float3(0.527, -0.723, 0.445)), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * sideDot; + + rayDir = mul(normalize(float3(-0.526, -0.724, 0.445)), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * sideDot; + + rayDir = mul(normalize(float3(-0.851, 0.277, 0.445)), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * sideDot; + + rayDir = mul(normalize(float3(0.895, 0.445, 0.445)), tangentMatrix); + reflLighting += Marcher.March(startPos, rayDir) * sideDot; + + return reflLighting; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs new file mode 100644 index 0000000000..42437b7ac9 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Hemisphere (12)")] + public class VoxelMarchSetHemisphere12 : IVoxelMarchSet + { + public IVoxelMarchMethod Marcher { set; get; } = new VoxelMarchCone(9, 1.0f, 1.0f); + public VoxelMarchSetHemisphere12() + { + + } + public VoxelMarchSetHemisphere12(IVoxelMarchMethod marcher) + { + Marcher = marcher; + } + public ShaderSource GetMarchingShader(int attrID) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchSetHemisphere12")); + mixin.AddComposition("Marcher", Marcher.GetMarchingShader(attrID)); + return mixin; + } + + public void UpdateMarchingLayout(string compositionName) + { + Marcher.UpdateMarchingLayout("Marcher."+compositionName); + } + public void ApplyMarchingParameters(ParameterCollection parameters) + { + Marcher.ApplyMarchingParameters(parameters); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs new file mode 100644 index 0000000000..80e753da34 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Hemisphere (6)")] + public class VoxelMarchSetHemisphere6 : IVoxelMarchSet + { + public IVoxelMarchMethod Marcher { set; get; } = new VoxelMarchCone(9, 1.0f, 1.7f); + public VoxelMarchSetHemisphere6() + { + + } + public VoxelMarchSetHemisphere6(IVoxelMarchMethod marcher) + { + Marcher = marcher; + } + public ShaderSource GetMarchingShader(int attrID) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchSetHemisphere6")); + mixin.AddComposition("Marcher", Marcher.GetMarchingShader(attrID)); + return mixin; + } + + public void UpdateMarchingLayout(string compositionName) + { + Marcher.UpdateMarchingLayout("Marcher." + compositionName); + } + public void ApplyMarchingParameters(ParameterCollection parameters) + { + Marcher.ApplyMarchingParameters(parameters); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.xksl new file mode 100644 index 0000000000..a9247cd79d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.xksl @@ -0,0 +1,4 @@ +shader MarchAttributes +{ + stage compose IVoxelSampler AttributeSamplers[]; +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.cs new file mode 100644 index 0000000000..90bf1846e0 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.cs @@ -0,0 +1,51 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + internal static partial class ShaderMixins + { + internal partial class MarchAttributesEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "MarchAttributes"); + if (context.GetParam(MarchAttributesKeys.AttributeSamplers) != null) + { + foreach(var attr in context.GetParam(MarchAttributesKeys.AttributeSamplers)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributeSamplers", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("MarchAttributesEffect", new MarchAttributesEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.xksl new file mode 100644 index 0000000000..b78ca40f4c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.xksl @@ -0,0 +1,16 @@ +namespace Xenko.Rendering.Voxels +{ + partial effect MarchAttributesEffect + { + using params MarchAttributesKeys; + + mixin MarchAttributes; + if (MarchAttributesKeys.AttributeSamplers!=null) + { + foreach (var attr in MarchAttributesKeys.AttributeSamplers) + { + mixin compose AttributeSamplers += (attr); + } + } + }; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesKeys.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesKeys.cs new file mode 100644 index 0000000000..44abc13d6d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesKeys.cs @@ -0,0 +1,12 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. + +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public partial class MarchAttributesKeys + { + public static readonly PermutationParameterKey AttributeSamplers = ParameterKeys.NewPermutation(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl new file mode 100644 index 0000000000..66c71fbbc3 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl @@ -0,0 +1,27 @@ +shader VoxelMarchBeam : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes +{ + override float4 March(float3 rayPos, float3 rayDir) + { + return MarchRadius(rayPos, rayDir, 1.0); + } + override float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale) + { + float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); + float dist = voxelSize; + float4 light = float4(0.0, 0.0, 0.0, 0.0); + + for (int i = 0; i < steps; i++) + { + float size = beamDiameter * radiusScale; + float3 pos = rayPos + rayDir * dist; + + light += AttributeSamplers[AttributeID].Sample(pos, -rayDir, AttributeSamplers[AttributeID].VoxelSize() * size) * saturate(1.0 - light.a); + + dist += AttributeSamplers[AttributeID].VoxelSize() * stepScale; + } + return light; + } + + override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } + override float StepSizeRadius(float radiusScale) { return radiusScale * AttributeSamplers[AttributeID].VoxelSize(); } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl new file mode 100644 index 0000000000..23bc6c3171 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl @@ -0,0 +1,27 @@ +shader VoxelMarchCone : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes +{ + override float4 March(float3 rayPos, float3 rayDir) + { + return MarchRadius(rayPos, rayDir, 1.0); + } + override float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale) + { + float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); + float dist = 0; + float4 light = float4(0.0, 0.0, 0.0, 0.0); + rayPos += voxelSize * rayDir; + for (int i = 0; i < steps; i ++) + { + float size = max(voxelSize, coneRatio * radiusScale * dist); + float3 pos = rayPos + rayDir * dist; + + light += AttributeSamplers[AttributeID].Sample(pos, -rayDir, size) * saturate(1.0 - light.a); + + dist += size * stepScale; + } + return light; + } + + override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } + override float StepSizeRadius(float radiusScale) { return radiusScale * AttributeSamplers[AttributeID].VoxelSize(); } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl new file mode 100644 index 0000000000..8fcbe3e343 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl @@ -0,0 +1,27 @@ +shader VoxelMarchConeFast : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes +{ + override float4 March(float3 rayPos, float3 rayDir) + { + return MarchRadius(rayPos, rayDir, 1.0); + } + override float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale) + { + float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); + float dist = 0; + float4 light = float4(0.0, 0.0, 0.0, 0.0); + rayPos += voxelSize * rayDir; + for (int i = 0; i < steps; i++) + { + float size = max(voxelSize, coneRatio * radiusScale * dist); + float3 pos = rayPos + rayDir * dist; + + light += AttributeSamplers[AttributeID].SampleNearestMip(pos, -rayDir, size) * saturate(1.0 - light.a); + + dist += size * stepScale; + } + return light; + } + + override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } + override float StepSizeRadius(float radiusScale) { return radiusScale * AttributeSamplers[AttributeID].VoxelSize(); } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl new file mode 100644 index 0000000000..00d5153ff3 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl @@ -0,0 +1,22 @@ +shader VoxelMarchConePerMipmap : VoxelMarchMethod, MarchAttributes +{ + override float4 March(float3 rayPos, float3 rayDir) + { + float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); + float dist = voxelSize; + float size = 0; + float4 light = float4(0.0, 0.0, 0.0, 0.0); + for (int i = 0; i < steps; i++) + { + float3 pos = rayPos + rayDir * dist; + + light += AttributeSamplers[AttributeID].SampleByMipNearestMip(pos, -rayDir, size) * saturate(1.0 - light.a); + + dist *= 2; + size += 1; + } + return light; + } + + override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.xksl new file mode 100644 index 0000000000..371396c5d5 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.xksl @@ -0,0 +1,5 @@ +shader VoxelMarchMethod +{ + float4 March(float3 rayPos, float3 rayDir){ return float4(0, 0, 0, 0); } + float StepSize(){ return 1.0; } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.xksl new file mode 100644 index 0000000000..4dddce2a77 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.xksl @@ -0,0 +1,5 @@ +shader VoxelRadiusMarchMethod +{ + float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale){ return float4(0, 0, 0, 0); } + float StepSizeRadius(float radiusScale){ return radiusScale; } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchBeam.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchBeam.cs new file mode 100644 index 0000000000..21ea94757d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchBeam.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Beam")] + public class VoxelMarchBeam : IVoxelMarchMethod + { + public int Steps = 9; + public float StepScale = 1.0f; + public float BeamDiameter = 1.0f; + public VoxelMarchBeam() + { + + } + public VoxelMarchBeam(int steps, float stepScale, float diameter) + { + Steps = steps; + StepScale = stepScale; + BeamDiameter = diameter; + } + public ShaderSource GetMarchingShader(int attrID) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchBeam", Steps, StepScale, BeamDiameter)); + mixin.Macros.Add(new ShaderMacro("AttributeID", attrID)); + return mixin; + } + + public void UpdateMarchingLayout(string compositionName) + { + } + public void ApplyMarchingParameters(ParameterCollection parameters) + { + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs new file mode 100644 index 0000000000..2f8ffa4c9e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Cone")] + public class VoxelMarchCone : IVoxelMarchMethod + { + public bool Fast = false; + public int Steps = 9; + public float StepScale = 1.0f; + public float ConeRatio = 1.0f; + + public VoxelMarchCone() + { + + } + public VoxelMarchCone(int steps, float stepScale, float ratio) + { + Steps = steps; + StepScale = stepScale; + ConeRatio = ratio; + } + public ShaderSource GetMarchingShader(int attrID) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(new ShaderClassSource(Fast? "VoxelMarchConeFast" : "VoxelMarchCone", Steps, StepScale, ConeRatio)); + mixin.Macros.Add(new ShaderMacro("AttributeID", attrID)); + return mixin; + } + public void UpdateMarchingLayout(string compositionName) + { + } + public void ApplyMarchingParameters(ParameterCollection parameters) + { + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs new file mode 100644 index 0000000000..4da56d0e39 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Cone (Mipmap Exact)")] + public class VoxelMarchConePerMipmap : IVoxelMarchMethod + { + public int Steps = 7; + + public VoxelMarchConePerMipmap() + { + + } + public VoxelMarchConePerMipmap(int steps) + { + Steps = steps; + } + public ShaderSource GetMarchingShader(int attrID) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchConePerMipmap", Steps)); + mixin.Macros.Add(new ShaderMacro("AttributeID", attrID)); + return mixin; + } + public void UpdateMarchingLayout(string compositionName) + { + } + public void ApplyMarchingParameters(ParameterCollection parameters) + { + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/VoxelUtils.cs b/sources/engine/Xenko.Voxels/Voxels/VoxelUtils.cs new file mode 100644 index 0000000000..9c7fee3ba6 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/VoxelUtils.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core.Mathematics; +using Xenko.Graphics; + +namespace Xenko.Rendering.Voxels +{ + static class VoxelUtils + { + public static bool DisposeBufferBySpecs(Xenko.Graphics.Buffer buf, int count) + { + if (buf == null || buf.ElementCount != count) + { + if (buf != null) + buf.Dispose(); + + return true; + } + return false; + } + + public static bool TextureDimensionsEqual(Texture tex, Vector3 dim) + { + return (tex.Width == dim.X && + tex.Height == dim.Y && + tex.Depth == dim.Z); + } + public static bool DisposeTextureBySpecs(Xenko.Graphics.Texture tex, Vector3 dim, Xenko.Graphics.PixelFormat pixelFormat) + { + if (tex == null || !TextureDimensionsEqual(tex, dim) || tex.Format != pixelFormat) + { + if (tex != null) + tex.Dispose(); + + return true; + } + return false; + } + public static bool DisposeTextureBySpecs(Xenko.Graphics.Texture tex, Vector3 dim, Xenko.Graphics.PixelFormat pixelFormat, MultisampleCount samples) + { + if (tex == null || !TextureDimensionsEqual(tex, dim) || tex.Format != pixelFormat || tex.MultisampleCount != samples) + { + if (tex != null) + tex.Dispose(); + + return true; + } + return false; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs new file mode 100644 index 0000000000..88c247e0be --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelAttribute + { + void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage); + void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage); + void ClearOutputStorage(); + + void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output); + void CollectAttributes(List attributes, VoxelizationStage stage, bool output); + + void PostProcess(RenderDrawContext drawContext); + + //Writing + ShaderSource GetVoxelizationShader(); + void UpdateVoxelizationLayout(string compositionName); + void ApplyVoxelizationParameters(ParameterCollection parameters); + + void SetBufferOffset(int id); + int GetBufferOffset(); + + //Sampling + ShaderSource GetSamplingShader(); + void UpdateSamplingLayout(string compositionName); + void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); + + void SetLocalSamplerID(int id); + int GetLocalSamplerID(); + + + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.xksl new file mode 100644 index 0000000000..2597448d54 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.xksl @@ -0,0 +1,9 @@ +shader VoxelAttribute +{ + void InitializeDummy(){} + void InitializeFromStreams(){} + void InitializeFromBuffer(RWBuffer buffer, uint address, uint2 base_stride){} + void IndirectWrite(RWBuffer buffer, uint address){} + void DirectWrite(uint3 address, uint strideIndex, uint stride){} + float4 SampleLocal(){return float4(0,0,0,1);}; +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.xksl new file mode 100644 index 0000000000..b5100759e6 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.xksl @@ -0,0 +1,41 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelAttributeDirectionalCoverageSampler : IVoxelSampler, Texturing + { + compose VoxelStorageTextureShader storage; + + override float4 ComputeLocal(float3 position) + { + return float4(0,0,0,1); + } + + float4 SetColor(float3 col) + { + return float4(col.r,col.g,col.b,max(col.r,max(col.g,col.b))); + } + override float4 Sample(float3 position, float3 normal, float diameter) + { + return SetColor(storage.Sample(position, diameter, 0).rgb); + } + override float4 SampleNearestMip(float3 position, float3 normal, float diameter) + { + return SetColor(storage.SampleNearestMip(position, diameter, 0).rgb); + } + override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) + { + return SetColor(storage.SampleByMipNearestMip(position, diameter, 0).rgb); + } + override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + return storage.SampleRaw(pos,mipmap,textureID,axis); + } + override float VoxelSize() + { + return storage.VoxelSize(); + } + override float4 Test() + { + return float4(0,1,0,1); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.cs new file mode 100644 index 0000000000..e429b9b132 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.cs @@ -0,0 +1,23 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelAttributeDirectionalCoverageShaderKeys + { + public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.xksl new file mode 100644 index 0000000000..26b2cbb2d7 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.xksl @@ -0,0 +1,54 @@ +shader VoxelAttributeDirectionalCoverageShader : VoxelAttribute, ShaderBaseStream, NormalStream, DataPacking +{ + stream uint Voxel_Coverage; + stream float3 Voxel_CoverageResolved; + stream uint coverage : SV_Coverage; + + RWTexture3D DirectOutput; + + override void InitializeDummy() + { + streams.Voxel_Coverage = 0; + streams.Voxel_CoverageResolved = float3(0,0,0); + } + override void InitializeFromStreams() + { + uint shift = 0; + float xdot = abs(streams.normalWS.x); + float ydot = abs(streams.normalWS.y); + float zdot = abs(streams.normalWS.z); + if (xdot > ydot && xdot > zdot) + shift = 0; + if (ydot > xdot && ydot > zdot) + shift = 8; + if (zdot > ydot && zdot > xdot) + shift = 16; + streams.Voxel_Coverage = uint(streams.coverage)< buffer, uint address) + { + uint unusedOut; + InterlockedOr(buffer[address], streams.Voxel_Coverage, unusedOut); + address++; + } + override void InitializeFromBuffer(RWBuffer buffer, uint address, uint2 base_stride) + { + streams.Voxel_Coverage = buffer[address]; + address++; + + uint3 coverage = UnpackByte3ToUint3(streams.Voxel_Coverage); + streams.Voxel_CoverageResolved = (float3(countbits(coverage.x),countbits(coverage.y),countbits(coverage.z)))/8.0; + } + float3 GetResolved(){ + return streams.Voxel_CoverageResolved; + } + override float4 SampleLocal() + { + return float4(streams.Voxel_CoverageResolved, 1.0); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.xksl new file mode 100644 index 0000000000..8bcbf5d171 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.xksl @@ -0,0 +1,29 @@ +shader VoxelAttributeEmissionOpacityShader : VoxelAttribute, ShaderBaseStream +{ + compose VoxelLayout_Float4 layout; + + override void InitializeDummy() + { + layout.InitializeDummy(); + } + override void InitializeFromStreams() + { + layout.InitializeFromStreams(streams.ColorTarget); + } + override void DirectWrite(uint3 address, uint strideIndex, uint stride) + { + layout.DirectWrite(address, strideIndex, stride); + } + override void IndirectWrite(RWBuffer buffer, uint address) + { + layout.IndirectWrite(buffer,address); + } + override void InitializeFromBuffer(RWBuffer buffer, uint address, uint2 base_stride) + { + layout.InitializeFromBuffer(buffer, address); + } + override float4 SampleLocal() + { + return layout.SampleLocal(); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.xksl new file mode 100644 index 0000000000..09b7115edc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.xksl @@ -0,0 +1,37 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelAttributeSoliditySampler : IVoxelSampler, Texturing + { + compose VoxelStorageTextureShader storage; + + override float4 ComputeLocal(float3 position) + { + return float4(0,0,0,1); + } + + float4 SetColor(float4 col) + { + return float4(0,0,0,col.a); + } + override float4 Sample(float3 position, float3 normal, float diameter) + { + return SetColor(storage.Sample(position, diameter, 0).rrrr); + } + override float4 SampleNearestMip(float3 position, float3 normal, float diameter) + { + return SetColor(storage.SampleNearestMip(position, diameter, 0).rrrr); + } + override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) + { + return SetColor(storage.SampleByMipNearestMip(position, diameter, 0).rrrr); + } + override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + return storage.SampleRaw(pos,mipmap,textureID,axis); + } + override float VoxelSize() + { + return storage.VoxelSize(); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.cs new file mode 100644 index 0000000000..210b36a073 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.cs @@ -0,0 +1,23 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelAttributeSolidityShaderKeys + { + public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.xksl new file mode 100644 index 0000000000..45a1f158a0 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.xksl @@ -0,0 +1,106 @@ +shader VoxelAttributeSolidityShader : VoxelAttribute, VoxelPositionStream, ShaderBaseStream, NormalStream, DataPacking +{ + stream uint Voxel_SolidifyTop; + stream uint Voxel_SolidifyBottom; + stream float Voxel_Solidity; + stream int sendTo; + stream int ignoreTil; + + RWTexture3D DirectOutput; + + override void InitializeDummy() + { + streams.Voxel_SolidifyTop = 0; + streams.Voxel_SolidifyBottom = 0; + streams.Voxel_Solidity = 0; + streams.sendTo = 0; + streams.ignoreTil = 0; + } + override void InitializeFromStreams() + { + uint pos = FloatUnormToUint(streams.PositionVXS.y) & (0xFFFFFFFF << 2); + uint invpos = FloatUnormToUint(1.0 - streams.PositionVXS.y) & (0xFFFFFFFF << 2); + uint type = 0; + streams.normalWS = normalize(streams.normalWS); + if (streams.normalWS.y < -0.0) + type = 1; + if (streams.normalWS.y > 0.0) + type = 2; + + streams.Voxel_SolidifyTop = pos + type; + streams.Voxel_SolidifyBottom = invpos + type; + + streams.sendTo = 0; + streams.ignoreTil = 0; + } + override void DirectWrite(uint3 address, uint strideIndex, uint stride) + { + address.y += strideIndex * stride; + DirectOutput[address] = streams.Voxel_Solidity; + } + override void IndirectWrite(RWBuffer buffer, uint address) + { + InterlockedMax(buffer[address], streams.Voxel_SolidifyTop); + address++; + InterlockedMax(buffer[address], streams.Voxel_SolidifyBottom); + } + bool ResolvesSelf() + { + return (streams.Voxel_SolidifyTop & 3) == 2 && (streams.Voxel_SolidifyBottom & 3) == 1; + } + bool IsSender() + { + return (streams.Voxel_SolidifyTop & 3) == 1; + } + bool IsReceiver() + { + return (streams.Voxel_SolidifyBottom & 3) == 2; + } + override float4 SampleLocal() + { + return float4(IsReceiver()?1:0,IsSender()?1:0,ResolvesSelf()?1:0,streams.Voxel_Solidity); + } + override void InitializeFromBuffer(RWBuffer buffer, uint address, uint2 base_stride) + { + int Y = streams.PositionVXPS.y; + int maxY = streams.VoxelVolumeSize.y; + + uint originalAddress = address; + + streams.Voxel_Solidity = 0; + + if (Y>streams.ignoreTil) + { + if (Y>=streams.sendTo) + { + streams.ignoreTil = maxY; + for(int y = Y ; y < maxY; y++) + { + uint tempAddress = base_stride.x + base_stride.y * y; + streams.Voxel_SolidifyTop = buffer[tempAddress]; + streams.Voxel_SolidifyBottom = buffer[tempAddress + 1]; + if (IsReceiver()) + { + if (streams.ignoreTil attributes, VoxelizationStage stage, bool output) + { + attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); + } + + public void PostProcess(RenderDrawContext drawContext) + { + CoverageTex.PostProcess(drawContext, "VoxelMipmapSimple"); + } + + + + + ShaderClassSource source = new ShaderClassSource("VoxelAttributeDirectionalCoverageShader"); + ObjectParameterKey DirectOutput; + + public ShaderSource GetVoxelizationShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(source); + return mixin; + } + public void UpdateVoxelizationLayout(string compositionName) + { + DirectOutput = VoxelAttributeDirectionalCoverageShaderKeys.DirectOutput.ComposeWith(compositionName); + } + public void ApplyVoxelizationParameters(ParameterCollection parameters) + { + CoverageTex?.ApplyVoxelizationParameters(DirectOutput, parameters); + } + + int bufferOffset; + + public void SetBufferOffset(int bo) + { + bufferOffset = bo; + } + public int GetBufferOffset() + { + return bufferOffset; + } + + + + + ShaderClassSource sampler = new ShaderClassSource("VoxelAttributeDirectionalCoverageSampler"); + + public ShaderSource GetSamplingShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(sampler); + if (CoverageTex!=null) + mixin.AddComposition("storage", CoverageTex.GetSamplingShader()); + return mixin; + } + public void UpdateSamplingLayout(string compositionName) + { + CoverageTex?.UpdateSamplingLayout("storage." + compositionName); + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + CoverageTex?.ApplySamplingParameters(viewContext, parameters); + } + + int samplerLocalID; + + public void SetLocalSamplerID(int id) + { + samplerLocalID = id; + } + public int GetLocalSamplerID() + { + return samplerLocalID; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs new file mode 100644 index 0000000000..a6163a264d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; +using Xenko.Core.Mathematics; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Emission+Opacity")] + public class VoxelAttributeEmissionOpacity : IVoxelAttribute + { + public enum LightFalloffs + { + [Display("Sharp")] Sharp, + [Display("Physically Based")] PhysicallyBased, + [Display("Physically Based + Shadowing Heuristic")] Heuristic, + } + + [NotNull] + public IVoxelLayout VoxelLayout { get; set; } = new VoxelLayoutIsotropic(); + + public List Modifiers { get; set; } = new List(); + + public LightFalloffs LightFalloff { get; set; } = LightFalloffs.Heuristic; + + + public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + { + SetBufferOffset(VoxelLayout.PrepareLocalStorage(context, storage)); + } + public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + { + VoxelLayout.PrepareOutputStorage(context, storage); + } + public void ClearOutputStorage() + { + VoxelLayout.ClearOutputStorage(); + } + + + + + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) + { + passList.defaultVoxelizationMethod.CollectVoxelizationPasses(passList, storer, view, resolution, this, stage, output, true); + } + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + { + foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + { + modifier.CollectAttributes(attributes, VoxelizationStage.Post, false); + } + attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); + } + + public void PostProcess(RenderDrawContext drawContext) + { + switch (LightFalloff) + { + case LightFalloffs.Sharp: + VoxelLayout.PostProcess(drawContext, "VoxelMipmapSimple"); break; + case LightFalloffs.PhysicallyBased: + VoxelLayout.PostProcess(drawContext, "VoxelMipmapPhysicallyBased"); break; + case LightFalloffs.Heuristic: + VoxelLayout.PostProcess(drawContext, "VoxelMipmapHeuristic"); break; + } + } + + + + + ShaderClassSource source = new ShaderClassSource("VoxelAttributeEmissionOpacityShader"); + + public ShaderSource GetVoxelizationShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(source); + mixin.AddComposition("layout", VoxelLayout.GetVoxelizationShader(Modifiers)); + return mixin; + } + public void UpdateVoxelizationLayout(string compositionName) + { + int i = 0; + foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + { + modifier.UpdateVoxelizationLayout("Modifiers[" + i.ToString() + "].layout." + compositionName); + i++; + } + VoxelLayout.UpdateVoxelizationLayout("layout." + compositionName, Modifiers); + } + public void ApplyVoxelizationParameters(ParameterCollection parameters) + { + foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + { + modifier.ApplyVoxelizationParameters(parameters); + } + VoxelLayout.ApplyVoxelizationParameters(parameters, Modifiers); + } + + int bufferOffset; + + public void SetBufferOffset(int bo) + { + bufferOffset = bo; + } + public int GetBufferOffset() + { + return bufferOffset; + } + + + + + public ShaderSource GetSamplingShader() + { + return VoxelLayout.GetSamplingShader(); + } + public void UpdateSamplingLayout(string compositionName) + { + VoxelLayout.UpdateSamplingLayout(compositionName); + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + VoxelLayout.ApplySamplingParameters(viewContext, parameters); + } + + int samplerLocalID; + + public void SetLocalSamplerID(int id) + { + samplerLocalID = id; + } + public int GetLocalSamplerID() + { + return samplerLocalID; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs new file mode 100644 index 0000000000..e6e220377b --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; +using Xenko.Core.Mathematics; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Solidity")] + public class VoxelAttributeSolidity : IVoxelAttribute + { + IVoxelStorageTexture SolidityTex; + + public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + { + SetBufferOffset(storage.RequestTempStorage(64)); + } + public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + { + storage.UpdateTexture(context, ref SolidityTex, Graphics.PixelFormat.R8_UNorm, 1); + } + public void ClearOutputStorage() + { + SolidityTex = null; + } + + + + + VoxelizationMethodSingleAxis method = new VoxelizationMethodSingleAxis + { + MultisampleCount = Graphics.MultisampleCount.None, + VoxelizationAxis = VoxelizationMethodSingleAxis.Axis.Y + }; + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) + { + method.CollectVoxelizationPasses(passList, storer, view, resolution, this, stage, output, false); + } + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + { + attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); + } + + public void PostProcess(RenderDrawContext drawContext) + { + SolidityTex?.PostProcess(drawContext, "VoxelMipmapSimple"); + } + + + + + ShaderClassSource source = new ShaderClassSource("VoxelAttributeSolidityShader"); + ObjectParameterKey DirectOutput; + + public ShaderSource GetVoxelizationShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(source); + return mixin; + } + public void UpdateVoxelizationLayout(string compositionName) + { + DirectOutput = VoxelAttributeSolidityShaderKeys.DirectOutput.ComposeWith(compositionName); + } + public void ApplyVoxelizationParameters(ParameterCollection parameters) + { + SolidityTex?.ApplyVoxelizationParameters(DirectOutput, parameters); + } + + int bufferOffset; + + public void SetBufferOffset(int bo) + { + bufferOffset = bo; + } + public int GetBufferOffset() + { + return bufferOffset; + } + + + + + ValueParameterKey BrightnessKey; + ShaderClassSource sampler = new ShaderClassSource("VoxelAttributeSoliditySampler"); + + public ShaderSource GetSamplingShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(sampler); + if (SolidityTex!=null) + mixin.AddComposition("storage", SolidityTex.GetSamplingShader()); + return mixin; + } + public void UpdateSamplingLayout(string compositionName) + { + BrightnessKey = VoxelIsotropicSamplerKeys.maxBrightness.ComposeWith(compositionName); + SolidityTex?.UpdateSamplingLayout("storage." + compositionName); + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + parameters.Set(BrightnessKey, 1.0f); + SolidityTex?.ApplySamplingParameters(viewContext, parameters); + } + + int samplerLocalID; + + public void SetLocalSamplerID(int id) + { + samplerLocalID = id; + } + public int GetLocalSamplerID() + { + return samplerLocalID; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/IVoxelBufferWriter.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/IVoxelBufferWriter.cs new file mode 100644 index 0000000000..d4f68d806a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/IVoxelBufferWriter.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelBufferWriter + { + ShaderSource GetShader(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.xksl new file mode 100644 index 0000000000..bd21b906dc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.xksl @@ -0,0 +1,13 @@ + shader VoxelBufferWriteAssign : VoxelBufferWriter + { + override void Write_Internal(RWBuffer fragmentsBuffer, inout uint address, uint data) + { + fragmentsBuffer[address] = data; + address++; + } + + override float4 Test() + { + return float4(0,1,0,1); + } + }; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.xksl new file mode 100644 index 0000000000..5fc152f439 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.xksl @@ -0,0 +1,14 @@ + shader VoxelBufferWriteMax : VoxelBufferWriter + { + override void Write_Internal(RWBuffer fragmentsBuffer, inout uint address, uint data) + { + uint unusedOut = -1; + InterlockedMax(fragmentsBuffer[address], data, unusedOut); + address++; + } + + override float4 Test() + { + return float4(0,1,0,1); + } + }; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.xksl new file mode 100644 index 0000000000..1284cfbf40 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.xksl @@ -0,0 +1,27 @@ + shader VoxelBufferWriter + { + void Write_Internal(RWBuffer fragmentsBuffer, inout uint address, uint data){} + void Write_Internal(RWBuffer fragmentsBuffer, inout uint address, uint2 data) + { + Write_Internal(fragmentsBuffer, address,data.x); + Write_Internal(fragmentsBuffer, address,data.y); + } + void Write_Internal(RWBuffer fragmentsBuffer, inout uint address, uint3 data) + { + Write_Internal(fragmentsBuffer, address,data.x); + Write_Internal(fragmentsBuffer, address,data.y); + Write_Internal(fragmentsBuffer, address,data.z); + } + void Write_Internal(RWBuffer fragmentsBuffer, inout uint address, uint4 data) + { + Write_Internal(fragmentsBuffer, address,data.x); + Write_Internal(fragmentsBuffer, address,data.y); + Write_Internal(fragmentsBuffer, address,data.z); + Write_Internal(fragmentsBuffer, address,data.w); + } + + float4 Test() + { + return float4(1,0,0,1); + } + }; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteAssign.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteAssign.cs new file mode 100644 index 0000000000..992e97383e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteAssign.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + //[DataContract("VoxelFlickerReductionNone")] + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("None")] + public class VoxelBufferWriteAssign : IVoxelBufferWriter + { + ShaderSource source = new ShaderClassSource("VoxelBufferWriteAssign"); + public ShaderSource GetShader() + { + return source; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteMax.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteMax.cs new file mode 100644 index 0000000000..22c85f0bdb --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/VoxelBufferWriteMax.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + //[DataContract("VoxelFlickerReductionAverage")] + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Max")] + public class VoxelBufferWriteMax : IVoxelBufferWriter + { + ShaderSource source = new ShaderClassSource("VoxelBufferWriteMax"); + public ShaderSource GetShader() + { + return source; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/IVoxelFragmentPacker.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/IVoxelFragmentPacker.cs new file mode 100644 index 0000000000..5c7f3b6c74 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/IVoxelFragmentPacker.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelFragmentPacker + { + ShaderSource GetShader(); + int GetBits(int channels); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.xksl new file mode 100644 index 0000000000..a8689adb1a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.xksl @@ -0,0 +1,96 @@ +shader DataPacking +{ + uint FloatToUnsignedFloatWExponent5(float num, int mantissa) + { + uint fltInt32 = asuint(num); + int offset = (23-mantissa); + int bitdepth = mantissa+5; + int bias = 15;//pow(2,5 - 1) - 1; + int biascounter = 0x38000000;//(127-bias)<<23; + + if (((fltInt32 & 0x7f800000) >> offset) <= (biascounter >> offset)) + return 0; + + uint fltInt16 = (((fltInt32 & 0x7fffffff) >> offset) - (biascounter >> offset)) & (0xFFFFFFFF >> (32-bitdepth)); + + return fltInt16; + } + float UnsignedFloatWExponent5ToFloat(uint num, int mantissa) + { + uint fltInt16 = num; + int offset = (23-mantissa); + int bitdepth = mantissa+5; + int bias = pow(2,5 - 1) - 1; + int biascounter = (127-bias)<<23; + + if (num==0) + return 0; + + uint fltInt32 = ((fltInt16) << offset) + 0x38000000; + + return asfloat(fltInt32); + } + uint Float3ToR11G11B10(float3 num) + { + return FloatToUnsignedFloatWExponent5(num.r, 6) | (FloatToUnsignedFloatWExponent5(num.g, 6)<<11) | (FloatToUnsignedFloatWExponent5(num.b, 5)<<22); + } + float3 R11G11B10ToFloat3(uint num) + { + float3 ret; + ret.r = UnsignedFloatWExponent5ToFloat(num & (0xFFFFFFFF>>(32-11)),6); + ret.g = UnsignedFloatWExponent5ToFloat((num>>11) & (0xFFFFFFFF>>(32-11)),6); + ret.b = UnsignedFloatWExponent5ToFloat((num>>22),5); + return ret; + } + uint FloatToHalfFloat(float num) + { + uint fltInt32 = asuint(num); + + if (((fltInt32 & 0x7f800000) >> 13) <= (0x38000000 >> 13)) + return 0; + + uint fltInt16 = (((fltInt32 & 0x7fffffff) >> 13) - (0x38000000 >> 13)) & 0x00007fff; + fltInt16 |= ((fltInt32 & 0x80000000) >> 16); + + return fltInt16; + } + float HalfFloatToFloat(uint num) + { + if (num==0) + return 0; + + uint fltInt16 = num; + + uint fltInt32 = ((fltInt16 & 0x00008000) << 16); + fltInt32 |= ((fltInt16 & 0x00007fff) << 13) + 0x38000000; + + return asfloat(fltInt32); + } + uint PackFloat2ToHalfFloat2(float2 num) + { + return FloatToHalfFloat(num.r) | (FloatToHalfFloat(num.g)<<16); + } + float2 UnpackHalfFloat2ToFloat2(uint num) + { + return float2( HalfFloatToFloat(num & 0x0000ffff), + HalfFloatToFloat(num >> 16) ); + } + + uint3 UnpackByte3ToUint3(uint num) + { + return uint3( + num & 0x000000ff, + (num >> 8) & 0x000000ff, + (num >> 16) & 0x000000ff + ); + } + + uint FloatUnormToUint(float num) + { + return (uint)(num * 4294967295.0); + } + float UintToFloatUnorm(uint num) + { + return float(num) / 4294967295.0; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.xksl new file mode 100644 index 0000000000..8335291f01 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.xksl @@ -0,0 +1,61 @@ +shader VoxelFragmentPackFloat16 : VoxelFragmentPacker, DataPacking +{ + override void Skip(inout uint address, float unpacked){address += 1;} + override void Skip(inout uint address, float2 unpacked){address += 1;} + override void Skip(inout uint address, float3 unpacked){address += 2;} + override void Skip(inout uint address, float4 unpacked){address += 2;} + override void Write(RWBuffer fragmentsBuffer, inout uint address, float unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, FloatToHalfFloat(unpacked.r)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float2 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, PackFloat2ToHalfFloat2(unpacked.rg)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float3 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, + uint2( + PackFloat2ToHalfFloat2(unpacked.rg), + FloatToHalfFloat(unpacked.b) + ) + ); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float4 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, + uint2( + PackFloat2ToHalfFloat2(unpacked.rg), + PackFloat2ToHalfFloat2(unpacked.ba) + ) + ); + } + + + + + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float unpacked) + { + unpacked = HalfFloatToFloat(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float2 unpacked) + { + unpacked = UnpackHalfFloat2ToFloat2(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float3 unpacked) + { + unpacked.rg = UnpackHalfFloat2ToFloat2(fragmentsBuffer[address]); + address++; + unpacked.b = HalfFloatToFloat(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float4 unpacked) + { + unpacked.rg = UnpackHalfFloat2ToFloat2(fragmentsBuffer[address]); + address++; + unpacked.ba = UnpackHalfFloat2ToFloat2(fragmentsBuffer[address]); + address++; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.xksl new file mode 100644 index 0000000000..302431dad4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.xksl @@ -0,0 +1,59 @@ +shader VoxelFragmentPackFloat32 : VoxelFragmentPacker +{ + override void Skip(inout uint address, float unpacked){address += 1;} + override void Skip(inout uint address, float2 unpacked){address += 2;} + override void Skip(inout uint address, float3 unpacked){address += 3;} + override void Skip(inout uint address, float4 unpacked){address += 4;} + override void Write(RWBuffer fragmentsBuffer, inout uint address, float unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, asuint(unpacked)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float2 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, asuint(unpacked)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float3 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, asuint(unpacked)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float4 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, asuint(unpacked)); + } + + + + + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float unpacked) + { + unpacked = asfloat(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float2 unpacked) + { + unpacked.r = asfloat(fragmentsBuffer[address]); + address++; + unpacked.g = asfloat(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float3 unpacked) + { + unpacked.r = asfloat(fragmentsBuffer[address]); + address++; + unpacked.g = asfloat(fragmentsBuffer[address]); + address++; + unpacked.b = asfloat(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float4 unpacked) + { + unpacked.r = asfloat(fragmentsBuffer[address]); + address++; + unpacked.g = asfloat(fragmentsBuffer[address]); + address++; + unpacked.b = asfloat(fragmentsBuffer[address]); + address++; + unpacked.a = asfloat(fragmentsBuffer[address]); + address++; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.xksl new file mode 100644 index 0000000000..19410f1bf0 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.xksl @@ -0,0 +1,64 @@ +shader VoxelFragmentPackFloatR11G11B10 : VoxelFragmentPacker, DataPacking +{ + override void Skip(inout uint address, float unpacked){address += 1;} + override void Skip(inout uint address, float2 unpacked){address += 1;} + override void Skip(inout uint address, float3 unpacked){address += 1;} + override void Skip(inout uint address, float4 unpacked){address += 2;} + override void Write(RWBuffer fragmentsBuffer, inout uint address, float3 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, Float3ToR11G11B10(unpacked)); + } + + + + + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float3 unpacked) + { + unpacked.rgb = R11G11B10ToFloat3(fragmentsBuffer[address]); + address++; + } + + + + //Until partial packing is implemented (if ever), write some halfs when not writing exactly 3 values + //Otherwise many bits are wasted + //Keep layout consistent though (or things like InterlockedMax can give unexpected results) + override void Write(RWBuffer fragmentsBuffer, inout uint address, float unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, FloatToHalfFloat(unpacked.r)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float2 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, PackFloat2ToHalfFloat2(unpacked.rg)); + } + override void Write(RWBuffer fragmentsBuffer, inout uint address, float4 unpacked) + { + writer.Write_Internal(fragmentsBuffer, address, + uint2( + Float3ToR11G11B10(unpacked.rgb), + FloatToHalfFloat(unpacked.a) + ) + ); + } + + + + + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float unpacked) + { + unpacked = HalfFloatToFloat(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float2 unpacked) + { + unpacked = UnpackHalfFloat2ToFloat2(fragmentsBuffer[address]); + address++; + } + override void Read(RWBuffer fragmentsBuffer, inout uint address, out float4 unpacked) + { + unpacked.rgb = R11G11B10ToFloat3(fragmentsBuffer[address]); + address++; + unpacked.a = HalfFloatToFloat(fragmentsBuffer[address]); + address++; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.xksl new file mode 100644 index 0000000000..2630f872fb --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.xksl @@ -0,0 +1,19 @@ +shader VoxelFragmentPacker +{ + compose VoxelBufferWriter writer; + + void Skip(inout uint address, float unpacked){} + void Skip(inout uint address, float2 unpacked){} + void Skip(inout uint address, float3 unpacked){} + void Skip(inout uint address, float4 unpacked){} + + void Write(RWBuffer fragmentsBuffer, inout uint address, float unpacked){} + void Write(RWBuffer fragmentsBuffer, inout uint address, float2 unpacked){} + void Write(RWBuffer fragmentsBuffer, inout uint address, float3 unpacked){} + void Write(RWBuffer fragmentsBuffer, inout uint address, float4 unpacked){} + + void Read(RWBuffer fragmentsBuffer, inout uint address, out float unpacked){unpacked = 0;} + void Read(RWBuffer fragmentsBuffer, inout uint address, out float2 unpacked){unpacked = float2(0,0);} + void Read(RWBuffer fragmentsBuffer, inout uint address, out float3 unpacked){unpacked = float3(0,0,0);} + void Read(RWBuffer fragmentsBuffer, inout uint address, out float4 unpacked){unpacked = float4(0,0,0,0);} +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat16.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat16.cs new file mode 100644 index 0000000000..a600ad9cfc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat16.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Float16")] + public class VoxelFragmentPackFloat16 : IVoxelFragmentPacker + { + ShaderSource source = new ShaderClassSource("VoxelFragmentPackFloat16"); + public ShaderSource GetShader() + { + return source; + } + public int GetBits(int channels) + { + return channels * 16; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat32.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat32.cs new file mode 100644 index 0000000000..6f95eb396c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloat32.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Float32")] + public class VoxelFragmentPackFloat32 : IVoxelFragmentPacker + { + ShaderSource source = new ShaderClassSource("VoxelFragmentPackFloat32"); + public ShaderSource GetShader() + { + return source; + } + public int GetBits(int channels) + { + return channels * 32; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloatR11G11B10.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloatR11G11B10.cs new file mode 100644 index 0000000000..1035c3718e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/VoxelFragmentPackFloatR11G11B10.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("R11G11B10F")] + public class VoxelFragmentPackFloatR11G11B10 : IVoxelFragmentPacker + { + ShaderSource source = new ShaderClassSource("VoxelFragmentPackFloatR11G11B10"); + public ShaderSource GetShader() + { + return source; + } + public int GetBits(int channels) + { + return ((channels+2) / 3)*32;//(channels)/3 * 32 + (channels % 3) * 11; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs new file mode 100644 index 0000000000..a5fe847841 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelLayout + { + int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage); + void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage); + void ClearOutputStorage(); + + void PostProcess(RenderDrawContext drawContext, string MipMapShader); + + //Writing + ShaderSource GetVoxelizationShader(List modifiers); + void UpdateVoxelizationLayout(string compositionName, List modifiers); + void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers); + + //Sampling + ShaderSource GetSamplingShader(); + void UpdateSamplingLayout(string compositionName); + void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl new file mode 100644 index 0000000000..cd72d604fa --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl @@ -0,0 +1,38 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelAnisotropicPairedSampler : IVoxelSampler, Texturing + { + + compose VoxelStorageTextureShader storage; + override float4 Sample(float3 position, float3 normal, float diameter) + { + return storage.Sample(position, diameter, 0)*abs(normal.x)+ + storage.Sample(position, diameter, 1)*abs(normal.y)+ + storage.Sample(position, diameter, 2)*abs(normal.z); + } + override float4 SampleNearestMip(float3 position, float3 normal, float diameter) + { + return storage.SampleNearestMip(position, diameter, 0) * abs(normal.x) + + storage.SampleNearestMip(position, diameter, 1) * abs(normal.y) + + storage.SampleNearestMip(position, diameter, 2) * abs(normal.z); + } + override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) + { + return storage.SampleByMipNearestMip(position, diameter, 0) * abs(normal.x) + + storage.SampleByMipNearestMip(position, diameter, 1) * abs(normal.y) + + storage.SampleByMipNearestMip(position, diameter, 2) * abs(normal.z); + } + override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + return storage.SampleRaw(pos, mipmap, textureID, axis); + } + override float VoxelSize() + { + return storage.VoxelSize(); + } + override float4 Test() + { + return float4(0,1,0,1); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs new file mode 100644 index 0000000000..c663c7a6ce --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs @@ -0,0 +1,23 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelAnisotropicPairedWriter_Float4Keys + { + public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl new file mode 100644 index 0000000000..80f41faac8 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl @@ -0,0 +1,56 @@ +shader VoxelAnisotropicPairedWriter_Float4 : VoxelLayout_Float4, NormalStream +{ + stream float4 axisX; + stream float4 axisY; + stream float4 axisZ; + RWTexture3D DirectOutput; + compose VoxelFragmentPacker writer; + + compose VoxelModifierApplierAnisotropicPaired Modifiers[]; + override void InitializeDummy() + { + streams.axisX = float4(0,0,0,0); + streams.axisY = float4(0,0,0,0); + streams.axisZ = float4(0,0,0,0); + } + override void InitializeFromStreams(float4 original) + { + streams.axisX = original * abs(streams.normalWS.x); + streams.axisY = original * abs(streams.normalWS.y); + streams.axisZ = original * abs(streams.normalWS.z); + } + override void DirectWrite(uint3 address, uint strideIndex, uint stride) + { + address.y += strideIndex * stride * 3; + float4 tempAxisX = streams.axisX; + float4 tempAxisY = streams.axisY; + float4 tempAxisZ = streams.axisZ; + foreach (var modifier in Modifiers) + { + modifier.Apply(tempAxisX, tempAxisY, tempAxisZ); + } + streams.axisX = tempAxisX; + streams.axisY = tempAxisY; + streams.axisZ = tempAxisZ; + + DirectOutput[address] = streams.axisX;address.y += stride; + DirectOutput[address] = streams.axisY;address.y += stride; + DirectOutput[address] = streams.axisZ; + } + override void IndirectWrite(RWBuffer buffer, uint address) + { + writer.Write(buffer, address, streams.axisX); + writer.Write(buffer, address, streams.axisY); + writer.Write(buffer, address, streams.axisZ); + } + override void InitializeFromBuffer(RWBuffer buffer, uint address) + { + writer.Read(buffer, address, streams.axisX); + writer.Read(buffer, address, streams.axisY); + writer.Read(buffer, address, streams.axisZ); + } + override float4 SampleLocal() + { + return streams.axisX; + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl new file mode 100644 index 0000000000..5b8280a95b --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl @@ -0,0 +1,49 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelAnisotropicSampler : IVoxelSampler, Texturing + { + compose VoxelStorageTextureShader storage; + override float4 Sample(float3 position, float3 normal, float diameter) + { + float4 sum = float4(0,0,0,0); + + sum = storage.Sample(position, diameter, normal.x > 0 ? 0 : 1) * abs(normal.x); + sum += storage.Sample(position, diameter, normal.y > 0 ? 2 : 3) * abs(normal.y); + sum += storage.Sample(position, diameter, normal.z > 0 ? 4 : 5) * abs(normal.z); + + return sum; + } + override float4 SampleNearestMip(float3 position, float3 normal, float diameter) + { + float4 sum = float4(0, 0, 0, 0); + + sum = storage.SampleNearestMip(position, diameter, normal.x > 0 ? 0 : 1) * abs(normal.x); + sum += storage.SampleNearestMip(position, diameter, normal.y > 0 ? 2 : 3) * abs(normal.y); + sum += storage.SampleNearestMip(position, diameter, normal.z > 0 ? 4 : 5) * abs(normal.z); + + return sum; + } + override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) + { + float4 sum = float4(0, 0, 0, 0); + + sum = storage.SampleByMipNearestMip(position, diameter, normal.x > 0 ? 0 : 1) * abs(normal.x); + sum += storage.SampleByMipNearestMip(position, diameter, normal.y > 0 ? 2 : 3) * abs(normal.y); + sum += storage.SampleByMipNearestMip(position, diameter, normal.z > 0 ? 4 : 5) * abs(normal.z); + + return sum; + } + override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + return storage.SampleRaw(pos, mipmap, textureID, axis); + } + override float VoxelSize() + { + return storage.VoxelSize(); + } + override float4 Test() + { + return float4(0,1,0,1); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs new file mode 100644 index 0000000000..68eb016b55 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs @@ -0,0 +1,23 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelAnisotropicWriter_Float4Keys + { + public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl new file mode 100644 index 0000000000..ebe9a906ee --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl @@ -0,0 +1,92 @@ +shader VoxelAnisotropicWriter_Float4 : VoxelLayout_Float4, NormalStream +{ + stream float4 axisXP; + stream float4 axisXN; + stream float4 axisYP; + stream float4 axisYN; + stream float4 axisZP; + stream float4 axisZN; + RWTexture3D DirectOutput; + compose VoxelFragmentPacker writer; + + compose VoxelModifierApplierAnisotropic Modifiers[]; + override void InitializeDummy() + { + streams.axisXP = float4(0,0,0,0); + streams.axisYP = float4(0,0,0,0); + streams.axisZP = float4(0,0,0,0); + streams.axisXN = float4(0,0,0,0); + streams.axisYN = float4(0,0,0,0); + streams.axisZN = float4(0,0,0,0); + } + override void InitializeFromStreams(float4 original) + { + if (streams.normalWS.x > 0) + streams.axisXP = original * streams.normalWS.x; + else + streams.axisXN = original * -streams.normalWS.x; + + if (streams.normalWS.y > 0) + streams.axisYP = original * streams.normalWS.y; + else + streams.axisYN = original * -streams.normalWS.y; + + if (streams.normalWS.z > 0) + streams.axisZP = original * streams.normalWS.z; + else + streams.axisZN = original * -streams.normalWS.z; + } + override void DirectWrite(uint3 address, uint strideIndex, uint stride) + { + address.y += strideIndex * stride * 6; + float4 tempAxisXP = streams.axisXP; + float4 tempAxisXN = streams.axisXN; + float4 tempAxisYP = streams.axisYP; + float4 tempAxisYN = streams.axisYN; + float4 tempAxisZP = streams.axisZP; + float4 tempAxisZN = streams.axisZN; + foreach (var modifier in Modifiers) + { + modifier.Apply(tempAxisXP, tempAxisXN, tempAxisYP, tempAxisYN, tempAxisZP, tempAxisZN); + } + streams.axisXP = tempAxisXP; + streams.axisXN = tempAxisXN; + streams.axisYP = tempAxisYP; + streams.axisYN = tempAxisYN; + streams.axisZP = tempAxisZP; + streams.axisZN = tempAxisZN; + DirectOutput[address] = streams.axisXP; + address.y += stride; + DirectOutput[address] = streams.axisXN; + address.y += stride; + DirectOutput[address] = streams.axisYP; + address.y += stride; + DirectOutput[address] = streams.axisYN; + address.y += stride; + DirectOutput[address] = streams.axisZP; + address.y += stride; + DirectOutput[address] = streams.axisZN; + } + override void IndirectWrite(RWBuffer buffer, uint address) + { + writer.Write(buffer, address, streams.axisXP); + writer.Write(buffer, address, streams.axisXN); + writer.Write(buffer, address, streams.axisYP); + writer.Write(buffer, address, streams.axisYN); + writer.Write(buffer, address, streams.axisZP); + writer.Write(buffer, address, streams.axisZN); + } + override void InitializeFromBuffer(RWBuffer buffer, uint address) + { + writer.Read(buffer, address, streams.axisXP); + writer.Read(buffer, address, streams.axisXN); + writer.Read(buffer, address, streams.axisYP); + writer.Read(buffer, address, streams.axisYN); + writer.Read(buffer, address, streams.axisZP); + writer.Read(buffer, address, streams.axisZN); + } + override float4 SampleLocal() + { + return streams.axisXP; + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.cs new file mode 100644 index 0000000000..3ac878ef71 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.cs @@ -0,0 +1,23 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class VoxelIsotropicSamplerKeys + { + public static readonly ValueParameterKey maxBrightness = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl new file mode 100644 index 0000000000..0d76247213 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl @@ -0,0 +1,40 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelIsotropicSampler : IVoxelSampler, Texturing + { + compose VoxelStorageTextureShader storage; + cbuffer PerView.Lighting + { + float maxBrightness; + } + + override float4 ComputeLocal(float3 position) + { + return float4(0,0,0,1); + } + override float4 Sample(float3 position, float3 normal, float diameter) + { + return storage.Sample(position, diameter, 0) * float4(maxBrightness, maxBrightness, maxBrightness, 1.0); + } + override float4 SampleNearestMip(float3 position, float3 normal, float diameter) + { + return storage.SampleNearestMip(position, diameter, 0) * float4(maxBrightness, maxBrightness, maxBrightness, 1.0); + } + override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) + { + return storage.SampleByMipNearestMip(position, diameter, 0) * float4(maxBrightness, maxBrightness, maxBrightness, 1.0); + } + override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + return storage.SampleRaw(pos,mipmap,textureID,axis); + } + override float VoxelSize() + { + return storage.VoxelSize(); + } + override float4 Test() + { + return float4(0,1,0,1); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.cs new file mode 100644 index 0000000000..97ac563f97 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.cs @@ -0,0 +1,24 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelIsotropicWriter_Float4Keys + { + public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + public static readonly ValueParameterKey maxBrightnessInv = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.xksl new file mode 100644 index 0000000000..ebe3a26a80 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.xksl @@ -0,0 +1,42 @@ +shader VoxelIsotropicWriter_Float4 : VoxelLayout_Float4 +{ + stream float4 center; + RWTexture3D DirectOutput; + compose VoxelFragmentPacker writer; + + float maxBrightnessInv; + + compose VoxelModifierApplierIsotropic Modifiers[]; + override void InitializeDummy() + { + streams.center = float4(0,0,0,0); + } + override void InitializeFromStreams(float4 original) + { + streams.center = original; + } + override void DirectWrite(uint3 address, uint strideIndex, uint stride) + { + address.y += strideIndex * stride; + float4 tempcenter = streams.center; + foreach (var modifier in Modifiers) + { + modifier.Apply(tempcenter); + } + streams.center = tempcenter; + + DirectOutput[address] = float4(streams.center.rgb * maxBrightnessInv, streams.center.a); + } + override void IndirectWrite(RWBuffer buffer, uint address) + { + writer.Write(buffer, address, streams.center); + } + override void InitializeFromBuffer(RWBuffer buffer, uint address) + { + writer.Read(buffer, address, streams.center); + } + override float4 SampleLocal() + { + return streams.center; + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.xksl new file mode 100644 index 0000000000..59b88cbde1 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.xksl @@ -0,0 +1,12 @@ +shader VoxelLayout_Float4 : NormalStream +{ + void InitializeDummy(){} + void InitializeFromStreams(float4 original){} + void IndirectWrite(RWBuffer buffer, uint address){} + void InitializeFromBuffer(RWBuffer buffer, uint address){} + void DirectWrite(uint3 address, uint strideIndex, uint stride){} + float4 SampleLocal() + { + return float4(0,0,0,0); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs new file mode 100644 index 0000000000..1b1b585e4d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Anisotropic (6 sided)")] + public class VoxelLayoutAnisotropic : IVoxelLayout + { + [NotNull] + public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); + + + + + IVoxelStorageTexture IsotropicTex; + + public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + { + return StorageMethod.PrepareLocalStorage(context, storage, 4, 6); + } + public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + { + storage.UpdateTexture(context, ref IsotropicTex, Graphics.PixelFormat.R16G16B16A16_Float, 6); + } + public void ClearOutputStorage() + { + IsotropicTex = null; + } + + public void PostProcess(RenderDrawContext drawContext, string MipMapShader) + { + IsotropicTex.PostProcess(drawContext, MipMapShader); + } + + + + + ShaderClassSource writer = new ShaderClassSource("VoxelAnisotropicWriter_Float4"); + ObjectParameterKey DirectOutput; + + public ShaderSource GetVoxelizationShader(List modifiers) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(writer); + StorageMethod.Apply(mixin); + foreach (var attr in modifiers) + { + ShaderSource applier = attr.GetApplier("Anisotropic"); + if (applier != null) + mixin.AddCompositionToArray("Modifiers", applier); + } + return mixin; + } + public void UpdateVoxelizationLayout(string compositionName, List modifier) + { + DirectOutput = VoxelAnisotropicWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); + } + public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifier) + { + IsotropicTex.ApplyVoxelizationParameters(DirectOutput, parameters); + } + + + + + ShaderClassSource sampler = new ShaderClassSource("VoxelAnisotropicSampler"); + + public ShaderSource GetSamplingShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(sampler); + mixin.AddComposition("storage", IsotropicTex.GetSamplingShader()); + return mixin; + } + public void UpdateSamplingLayout(string compositionName) + { + IsotropicTex.UpdateSamplingLayout("storage." + compositionName); + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + IsotropicTex.ApplySamplingParameters(viewContext, parameters); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs new file mode 100644 index 0000000000..775535611f --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Anisotropic (3 sided)")] + public class VoxelLayoutAnisotropicPaired : IVoxelLayout + { + [NotNull] + public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); + + + + IVoxelStorageTexture IsotropicTex; + + public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + { + return StorageMethod.PrepareLocalStorage(context, storage, 4, 3); + } + public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + { + storage.UpdateTexture(context, ref IsotropicTex, Graphics.PixelFormat.R16G16B16A16_Float, 3); + } + public void ClearOutputStorage() + { + IsotropicTex = null; + } + + public void PostProcess(RenderDrawContext drawContext, string MipMapShader) + { + IsotropicTex.PostProcess(drawContext, MipMapShader); + } + + + + + ShaderClassSource writer = new ShaderClassSource("VoxelAnisotropicPairedWriter_Float4"); + ObjectParameterKey DirectOutput; + + public ShaderSource GetVoxelizationShader(List modifiers) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(writer); + StorageMethod.Apply(mixin); + foreach (var attr in modifiers) + { + ShaderSource applier = attr.GetApplier("AnisotropicPaired"); + if (applier != null) + mixin.AddCompositionToArray("Modifiers", applier); + } + return mixin; + } + public void UpdateVoxelizationLayout(string compositionName, List modifier) + { + DirectOutput = VoxelAnisotropicPairedWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); + } + public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) + { + IsotropicTex.ApplyVoxelizationParameters(DirectOutput, parameters); + } + + + + + ShaderClassSource sampler = new ShaderClassSource("VoxelAnisotropicPairedSampler"); + + public ShaderSource GetSamplingShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(sampler); + mixin.AddComposition("storage", IsotropicTex.GetSamplingShader()); + return mixin; + } + public void UpdateSamplingLayout(string compositionName) + { + IsotropicTex.UpdateSamplingLayout("storage."+compositionName); + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + IsotropicTex.ApplySamplingParameters(viewContext, parameters); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs new file mode 100644 index 0000000000..2bfa26c21e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Isotropic (single)")] + public class VoxelLayoutIsotropic : IVoxelLayout + { + public enum StorageFormats + { + R10G10B10A2, + RGBA8, + RGBA16F, + }; + + [NotNull] + public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); + + public StorageFormats StorageFormat { get; set; } = StorageFormats.RGBA16F; + + [Display("Max Brightness (non float format)")] + public float maxBrightness = 10.0f; + + + + + IVoxelStorageTexture IsotropicTex; + + public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + { + return StorageMethod.PrepareLocalStorage(context, storage, 4, 1); + } + public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + { + Graphics.PixelFormat format = Graphics.PixelFormat.R16G16B16A16_Float; + switch (StorageFormat) + { + case StorageFormats.RGBA8: + format = Graphics.PixelFormat.R8G8B8A8_UNorm; + break; + case StorageFormats.R10G10B10A2: + format = Graphics.PixelFormat.R10G10B10A2_UNorm; + break; + case StorageFormats.RGBA16F: + format = Graphics.PixelFormat.R16G16B16A16_Float; + break; + } + storage.UpdateTexture(context, ref IsotropicTex, format, 1); + } + public void ClearOutputStorage() + { + IsotropicTex = null; + } + + public void PostProcess(RenderDrawContext drawContext, string MipMapShader) + { + IsotropicTex.PostProcess(drawContext, MipMapShader); + } + + + + + ShaderClassSource writer = new ShaderClassSource("VoxelIsotropicWriter_Float4"); + ValueParameterKey BrightnessInvKey; + ObjectParameterKey DirectOutput; + + public ShaderSource GetVoxelizationShader(List modifiers) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(writer); + StorageMethod.Apply(mixin); + foreach (var attr in modifiers) + { + ShaderSource applier = attr.GetApplier("Isotropic"); + if (applier != null) + mixin.AddCompositionToArray("Modifiers", applier); + } + return mixin; + } + public void UpdateVoxelizationLayout(string compositionName, List modifiers) + { + DirectOutput = VoxelIsotropicWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); + BrightnessInvKey = VoxelIsotropicWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); + } + public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) + { + if (StorageFormat != StorageFormats.RGBA16F) + parameters.Set(BrightnessInvKey, 1.0f / maxBrightness); + else + parameters.Set(BrightnessInvKey, 1.0f); + IsotropicTex.ApplyVoxelizationParameters(DirectOutput, parameters); + } + + + + + ValueParameterKey BrightnessKey; + ShaderClassSource sampler = new ShaderClassSource("VoxelIsotropicSampler"); + + public ShaderSource GetSamplingShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(sampler); + mixin.AddComposition("storage", IsotropicTex.GetSamplingShader()); + return mixin; + } + public void UpdateSamplingLayout(string compositionName) + { + BrightnessKey = VoxelIsotropicSamplerKeys.maxBrightness.ComposeWith(compositionName); + IsotropicTex.UpdateSamplingLayout("storage."+compositionName); + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + if (StorageFormat != StorageFormats.RGBA16F) + parameters.Set(BrightnessKey, maxBrightness); + else + parameters.Set(BrightnessKey, 1.0f); + IsotropicTex.ApplySamplingParameters(viewContext, parameters); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.xksl new file mode 100644 index 0000000000..deabdd93e8 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.xksl @@ -0,0 +1,7 @@ +shader VoxelModifierApplierAnisotropic +{ + void Apply(inout float4 XP, inout float4 XN, inout float4 YP, inout float4 YN, inout float4 ZP, inout float4 ZN){ } + void Apply(inout float3 XP, inout float3 XN, inout float3 YP, inout float3 YN, inout float3 ZP, inout float3 ZN){ } + void Apply(inout float2 XP, inout float2 XN, inout float2 YP, inout float2 YN, inout float2 ZP, inout float2 ZN){ } + void Apply(inout float XP, inout float XN, inout float YP, inout float YN, inout float ZP, inout float ZN){ } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.xksl new file mode 100644 index 0000000000..b025ef18cb --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.xksl @@ -0,0 +1,13 @@ +shader VoxelModifierApplierAntiAliasingAnisotropic : VoxelModifierApplierAnisotropic, LocalSamples +{ + override void Apply(inout float4 XP, inout float4 XN, inout float4 YP, inout float4 YN, inout float4 ZP, inout float4 ZN) + { + float3 PlaneCoverage = streams.LocalSample[DirectionalOpacityAttributeID].xyz; + XP *= PlaneCoverage.x; + XN *= PlaneCoverage.x; + YP *= PlaneCoverage.y; + YN *= PlaneCoverage.y; + ZP *= PlaneCoverage.z; + ZN *= PlaneCoverage.z; + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.xksl new file mode 100644 index 0000000000..941ea7b492 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.xksl @@ -0,0 +1,15 @@ +shader VoxelModifierApplierOpacifyAnisotropic : VoxelModifierApplierAnisotropic +{ + [Link("VoxelModifierApplierOpacifyIsotropic.Amount")] + float Amount; + + override void Apply(inout float4 XP, inout float4 XN, inout float4 YP, inout float4 YN, inout float4 ZP, inout float4 ZN) + { + XP.a *= Amount; + XN.a *= Amount; + YP.a *= Amount; + YN.a *= Amount; + ZP.a *= Amount; + ZN.a *= Amount; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.xksl new file mode 100644 index 0000000000..5126312998 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.xksl @@ -0,0 +1,13 @@ +shader VoxelModifierApplierSolidifyAnisotropic : VoxelModifierApplierAnisotropic, LocalSamples +{ + override void Apply(inout float4 XP, inout float4 XN, inout float4 YP, inout float4 YN, inout float4 ZP, inout float4 ZN) + { + float Solidity = streams.LocalSample[SolidityAttributeID].a; + XP.a = max(Solidity, XP.a); + XN.a = max(Solidity, XN.a); + YP.a = max(Solidity, YP.a); + YN.a = max(Solidity, YN.a); + ZP.a = max(Solidity, ZP.a); + ZN.a = max(Solidity, ZN.a); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.xksl new file mode 100644 index 0000000000..325ddcb624 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.xksl @@ -0,0 +1,7 @@ +shader VoxelModifierApplierAnisotropicPaired +{ + void Apply(inout float4 X, inout float4 Y, inout float4 Z){ } + void Apply(inout float3 X, inout float3 Y, inout float3 Z){ } + void Apply(inout float2 X, inout float2 Y, inout float2 Z){ } + void Apply(inout float X, inout float Y, inout float Z){ } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl new file mode 100644 index 0000000000..e628dec7c5 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl @@ -0,0 +1,10 @@ +shader VoxelModifierApplierAntiAliasingAnisotropicPaired : VoxelModifierApplierAnisotropicPaired, LocalSamples +{ + override void Apply(inout float4 X, inout float4 Y, inout float4 Z) + { + float3 PlaneCoverage = streams.LocalSample[DirectionalOpacityAttributeID].xyz; + X *= PlaneCoverage.x; + Y *= PlaneCoverage.y; + Z *= PlaneCoverage.z; + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl new file mode 100644 index 0000000000..2ee99ac5d4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl @@ -0,0 +1,12 @@ +shader VoxelModifierApplierOpacifyAnisotropicPaired : VoxelModifierApplierAnisotropicPaired +{ + [Link("VoxelModifierApplierOpacifyIsotropic.Amount")] + float Amount; + + override void Apply(inout float4 X, inout float4 Y, inout float4 Z) + { + X.a *= Amount; + Y.a *= Amount; + Z.a *= Amount; + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl.cs new file mode 100644 index 0000000000..2d108c4eaf --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.xksl.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.xksl new file mode 100644 index 0000000000..b6dd522512 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.xksl @@ -0,0 +1,10 @@ +shader VoxelModifierApplierSolidifyAnisotropicPaired : VoxelModifierApplierAnisotropicPaired, LocalSamples +{ + override void Apply(inout float4 X, inout float4 Y, inout float4 Z) + { + float Solidity = streams.LocalSample[SolidityAttributeID].a; + X.a = max(Solidity, X.a); + Y.a = max(Solidity, Y.a); + Z.a = max(Solidity, Z.a); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl new file mode 100644 index 0000000000..1a12af1001 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl @@ -0,0 +1,8 @@ +shader VoxelModifierApplierAntiAliasingIsotropic : VoxelModifierApplierIsotropic, LocalSamples +{ + override void Apply(inout float4 center) + { + float3 PlaneCoverage = streams.LocalSample[DirectionalOpacityAttributeID].xyz; + center *= max(PlaneCoverage.x, max(PlaneCoverage.y, PlaneCoverage.z)); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.xksl new file mode 100644 index 0000000000..2f98ecfaf9 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.xksl @@ -0,0 +1,7 @@ +shader VoxelModifierApplierIsotropic +{ + void Apply(inout float4 center){} + void Apply(inout float3 center){} + void Apply(inout float2 center){} + void Apply(inout float center){} +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.cs new file mode 100644 index 0000000000..18245950cd --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.cs @@ -0,0 +1,23 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelModifierApplierOpacifyIsotropicKeys + { + public static readonly ValueParameterKey Amount = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.xksl new file mode 100644 index 0000000000..fb2b98c2c0 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.xksl @@ -0,0 +1,8 @@ +shader VoxelModifierApplierOpacifyIsotropic : VoxelModifierApplierIsotropic +{ + float Amount; + override void Apply(inout float4 center) + { + center.a *= Amount; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.xksl new file mode 100644 index 0000000000..a38ed8b997 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.xksl @@ -0,0 +1,8 @@ +shader VoxelModifierApplierSolidifyIsotropic : VoxelModifierApplierIsotropic, LocalSamples +{ + override void Apply(inout float4 center) + { + float Solidity = streams.LocalSample[SolidityAttributeID].a; + center.a = max(Solidity, center.a); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs new file mode 100644 index 0000000000..0fb2da2e3a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs @@ -0,0 +1,8 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Rendering.Voxels; + +public interface IVoxelModifierEmissionOpacity : IVoxelModifier +{ +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs new file mode 100644 index 0000000000..88f5c44753 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Rendering.Voxels; +using Xenko.Shaders; + +[DataContract(DefaultMemberMode = DataMemberMode.Default)] +[Display("Anti Aliasing")] +public class VoxelModifierEmissionOpacityAntiAliasing : VoxelModifierBase, IVoxelModifierEmissionOpacity +{ + VoxelAttributeDirectionalCoverage directionalCoverage = new VoxelAttributeDirectionalCoverage(); + + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + { + if (!Enabled) return; + directionalCoverage.CollectAttributes(attributes, stage, output); + } + public bool RequiresColumns() + { + if (!Enabled) return false; + return true; + } + public ShaderSource GetApplier(string layout) + { + if (!Enabled) return null; + return new ShaderClassSource("VoxelModifierApplierAntiAliasing" + layout, directionalCoverage.GetLocalSamplerID()); + } + + public void UpdateVoxelizationLayout(string compositionName) { } + public void ApplyVoxelizationParameters(ParameterCollection parameters) { } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs new file mode 100644 index 0000000000..26e2c712e0 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Rendering.Voxels; +using Xenko.Shaders; + +[DataContract(DefaultMemberMode = DataMemberMode.Default)] +[Display("Opacify")] +public class VoxelModifierEmissionOpacityOpacify : VoxelModifierBase, IVoxelModifierEmissionOpacity +{ + public float Amount = 2.0f; + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { } + public bool RequiresColumns() + { + if (!Enabled) return false; + return true; + } + public ShaderSource GetApplier(string layout) + { + if (!Enabled) return null; + return new ShaderClassSource("VoxelModifierApplierOpacify" + layout); + } + + ValueParameterKey AmountKey; + public void UpdateVoxelizationLayout(string compositionName) + { + AmountKey = VoxelModifierApplierOpacifyIsotropicKeys.Amount.ComposeWith(compositionName); + } + + public void ApplyVoxelizationParameters(ParameterCollection parameters) + { + parameters.Set(AmountKey, Amount); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs new file mode 100644 index 0000000000..0f7ee4b7d2 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Rendering.Voxels; +using Xenko.Shaders; + +[DataContract(DefaultMemberMode = DataMemberMode.Default)] +[Display("Solidify")] +public class VoxelModifierEmissionOpacitySolidify : VoxelModifierBase, IVoxelModifierEmissionOpacity +{ + VoxelAttributeSolidity solidityAttribute = new VoxelAttributeSolidity(); + + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + { + if (!Enabled) return; + solidityAttribute.CollectAttributes(attributes, stage, output); + } + public bool RequiresColumns() + { + if (!Enabled) return false; + return true; + } + public ShaderSource GetApplier(string layout) + { + if (!Enabled) return null; + return new ShaderClassSource("VoxelModifierApplierSolidify" + layout, solidityAttribute.GetLocalSamplerID()); + } + public void UpdateVoxelizationLayout(string compositionName) { } + public void ApplyVoxelizationParameters(ParameterCollection parameters) { } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs new file mode 100644 index 0000000000..f7041a8c56 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Rendering.Voxels; +using Xenko.Shaders; + +public interface IVoxelModifier +{ + bool RequiresColumns(); + void CollectAttributes(List attributes, VoxelizationStage stage, bool output); + void UpdateVoxelizationLayout(string compositionName); + void ApplyVoxelizationParameters(ParameterCollection parameters); + ShaderSource GetApplier(string layout); +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl new file mode 100644 index 0000000000..a9bc28f824 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl @@ -0,0 +1,10 @@ +shader VoxelModifier +{ + void SetupStreamsDummy(){} + void SetupStreams(){} + float4 VoxelizeDirect(uint3 address, uint stride){} + void VoxelizeIndirectWrite(RWBuffer buffer, inout uint address){} + void VoxelizeIndirectRead(RWBuffer buffer, inout uint address, uint2 base_stride){} + + void Apply(inout float4 color){return float4(0,0,0,0);} +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs new file mode 100644 index 0000000000..e82ef355d9 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +[DataContract(DefaultMemberMode = DataMemberMode.Default)] +public abstract class VoxelModifierBase +{ + [DataMember(-20)] + [DefaultValue(true)] + public bool Enabled { get; set; } = true; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs new file mode 100644 index 0000000000..0ed6c31ae4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core.Mathematics; +using Xenko.Games; +using Xenko.Engine; +using Xenko.Shaders; +using Xenko.Rendering.Voxels.Debug; + +namespace Xenko.Rendering.Voxels +{ + public class DataVoxelVolume + { + public Vector3 VolumeSize; + public Vector3 VolumeTranslation; + public float AproxVoxelSize; + public bool Voxelize; + + public bool VoxelGridSnapping; + public bool VisualizeVoxels; + public IVoxelAttribute VisualizationAttribute; + public IVoxelVisualization VoxelVisualization; + + public List Attributes = new List(); + + public IVoxelStorage Storage; + public IVoxelizationMethod VoxelizationMethod; + } + public enum VoxelizationStage + { + Initial, + Post + } + public struct AttributeStream + { + public IVoxelAttribute Attribute; + public VoxelizationStage Stage; + public bool Output; + public AttributeStream(IVoxelAttribute a, VoxelizationStage s, bool o) + { + Attribute = a; + Stage = s; + Output = o; + } + } + public class ProcessedVoxelVolume + { + public bool Voxelize; + public bool VisualizeVoxels; + public IVoxelAttribute VisualizationAttribute; + public IVoxelVisualization VoxelVisualization; + + public IVoxelStorage Storage; + public IVoxelizationMethod VoxelizationMethod; + public VoxelStorageContext StorageContext; + + public VoxelizationPassList passList = new VoxelizationPassList(); + + public List> groupedPasses = new List>(); + + public List OutputAttributes = new List(); + public List Attributes = new List(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/IVoxelStorageMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/IVoxelStorageMethod.cs new file mode 100644 index 0000000000..af8d166192 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/IVoxelStorageMethod.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelStorageMethod + { + void Apply(ShaderMixinSource mixin); + int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage, int channels, int layoutCount); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/VoxelStorageMethodIndirect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/VoxelStorageMethodIndirect.cs new file mode 100644 index 0000000000..e03f8c947d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/StorageMethod/VoxelStorageMethodIndirect.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; +using Xenko.Rendering.Materials; +using Xenko.Core.Annotations; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Filtered")] + public class VoxelStorageMethodIndirect : IVoxelStorageMethod + { + [NotNull] + public IVoxelFragmentPacker TempStorageFormat { get; set; } = new VoxelFragmentPackFloatR11G11B10(); + [NotNull] + public IVoxelBufferWriter Filter { get; set; } = new VoxelBufferWriteMax(); + + public void Apply(ShaderMixinSource mixin) + { + var writermixin = new ShaderMixinSource(); + writermixin.Mixins.Add((ShaderClassSource)TempStorageFormat.GetShader()); + writermixin.AddComposition("writer", Filter.GetShader()); + mixin.AddComposition("writer", writermixin); + } + + public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage, int channels, int layoutCount) + { + return storage.RequestTempStorage(TempStorageFormat.GetBits(channels) * layoutCount); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.xksl new file mode 100644 index 0000000000..bf41a01acc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.xksl @@ -0,0 +1,6 @@ +shader VoxelPositionStream +{ + stage stream float3 PositionVXS : POSITIONVXS; + stage stream int3 PositionVXPS : POSITIONVXPS; + stage stream float3 VoxelVolumeSize : VOXELVOLUMESIZE; +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorage.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorage.cs new file mode 100644 index 0000000000..13cf0916ec --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorage.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using Xenko.Graphics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelStorage + { + void UpdateFromContext(VoxelStorageContext context); + void CollectVoxelizationPasses(ProcessedVoxelVolume data, VoxelStorageContext storageContext); + + int RequestTempStorage(int count); + void UpdateTexture(VoxelStorageContext context, ref IVoxelStorageTexture texture, Xenko.Graphics.PixelFormat pixelFormat, int layoutSize); + void UpdateTempStorage(VoxelStorageContext context); + void PostProcess(VoxelStorageContext context, RenderDrawContext drawContext, ProcessedVoxelVolume data); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs new file mode 100644 index 0000000000..5792306f65 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Graphics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelStorageTexture + { + void UpdateVoxelizationLayout(string compositionName); + void UpdateSamplingLayout(string compositionName); + void ApplyVoxelizationParameters(ObjectParameterKey MainKey, ParameterCollection parameters); + void PostProcess(RenderDrawContext drawContext, string MipMapShader); + ShaderClassSource GetSamplingShader(); + void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.xksl new file mode 100644 index 0000000000..1e725fba7b --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.xksl @@ -0,0 +1,4 @@ +shader LocalSamples +{ + stage stream float4 LocalSample[10]; +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl new file mode 100644 index 0000000000..0c167d133e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl @@ -0,0 +1,52 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelMipmapHeuristic : Math, Texturing, ComputeShaderBase + { + [Link("VoxelMipmapSimple.ReadOffset")] + stage float3 ReadOffset; + [Link("VoxelMipmapSimple.ReadTex")] + stage Texture3D ReadTex; + [Link("VoxelMipmapSimple.WriteTex")] + stage RWTexture3D WriteTex; + override void Compute() + { + uint3 pos = streams.DispatchThreadId; + + uint3 posR = pos * 2 + (int3)ReadOffset; + float4 fragmentSum = ( + ReadTex.Load(int4(posR, 0)) + + ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)) + + ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)) + + ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)) + + ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)) + + ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)) + + ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)) + + ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) + ); + float filledSum = ( + ceil(ReadTex.Load(int4(posR, 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)).a) + + ceil(ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)).a) + ); + fragmentSum.rgb /= max(filledSum, 4); + fragmentSum.a /= 8; + WriteTex[pos] = (fragmentSum); + //Rather than divide by 8... + //I figure that since the visible surface of the + //emitter is a 2D projection, it should decrease + //by 2 dimensions rather than 3 (i.e divide by 4 rather than 8). + + //This makes the lighting fall-off much more realistic, + //but I find the opacity coverage too strong then. + //so keep that dividing by 8. + + //Of course, then the brightness in areas with clusters of voxels + //becomes too high, so instead divide by the number of filled voxels, minimum 4 + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl new file mode 100644 index 0000000000..bd309ba38e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl @@ -0,0 +1,39 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelMipmapPhysicallyBased : Math, Texturing, ComputeShaderBase + { + [Link("VoxelMipmapSimple.ReadOffset")] + stage float3 ReadOffset; + [Link("VoxelMipmapSimple.ReadTex")] + stage Texture3D ReadTex; + [Link("VoxelMipmapSimple.WriteTex")] + stage RWTexture3D WriteTex; + override void Compute() + { + uint3 pos = streams.DispatchThreadId; + + uint3 posR = pos * 2 + (int3)ReadOffset; + float4 fragmentSum = ( + ReadTex.Load(int4(posR, 0)) + + ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)) + + ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)) + + ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)) + + ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)) + + ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)) + + ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)) + + ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) + ); + fragmentSum.rgb /= 4; + fragmentSum.a /= 8; + WriteTex[pos] = (fragmentSum); + //Rather than divide by 8... + //I figure that since the visible surface of the + //emitter is a 2D projection, it should decrease + //by 2 dimensions rather than 3 (i.e divide by 4 rather than 8). + + //This makes the lighting fall-off much more realistic, + //but I find the opacity coverage too strong then. + //so keep that dividing by 8. + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl.cs new file mode 100644 index 0000000000..2d108c4eaf --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs new file mode 100644 index 0000000000..7d29a660ef --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs @@ -0,0 +1,25 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class VoxelMipmapSimpleKeys + { + public static readonly ValueParameterKey ReadOffset = ParameterKeys.NewValue(); + public static readonly ObjectParameterKey ReadTex = ParameterKeys.NewObject(); + public static readonly ObjectParameterKey WriteTex = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl new file mode 100644 index 0000000000..ae25ba3f05 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl @@ -0,0 +1,26 @@ +namespace Xenko.Rendering.Voxels +{ + shader VoxelMipmapSimple : Math, Texturing, ComputeShaderBase + { + stage float3 ReadOffset; + stage Texture3D ReadTex; + stage RWTexture3D WriteTex; + override void Compute() + { + uint3 pos = streams.DispatchThreadId; + + uint3 posR = pos * 2 + (int3)ReadOffset; + float4 fragmentSum = ( + ReadTex.Load(int4(posR, 0)) + + ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)) + + ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)) + + ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)) + + ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)) + + ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)) + + ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)) + + ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) + ); + WriteTex[pos] = (fragmentSum / 8.0); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.cs new file mode 100644 index 0000000000..84d1b77f75 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.cs @@ -0,0 +1,26 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class BufferToTextureKeys + { + public static readonly ObjectParameterKey VoxelFragments = ParameterKeys.NewObject(); + public static readonly ValueParameterKey clipMapResolution = ParameterKeys.NewValue(); + public static readonly ValueParameterKey storageUints = ParameterKeys.NewValue(); + public static readonly ValueParameterKey clipOffset = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl new file mode 100644 index 0000000000..f9ab74619c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl @@ -0,0 +1,19 @@ +namespace Xenko.Rendering.Voxels +{ + //TODO: Currently broken, is being kept around for its shader keys + shader BufferToTexture : LocalSamples, ComputeShaderBase, VoxelPositionStream, DataPacking + { + stage RWBuffer VoxelFragments; + + stage float3 clipMapResolution; + + stage float storageUints; + + stage uint clipOffset; + + override void Compute() + { + //TODO + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.xksl new file mode 100644 index 0000000000..3da911dd33 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.xksl @@ -0,0 +1,81 @@ +namespace Xenko.Rendering.Voxels +{ + shader BufferToTextureColumns : LocalSamples, ComputeShaderBase, VoxelPositionStream, DataPacking + { + [Link("BufferToTexture.VoxelFragments")] + stage RWBuffer VoxelFragments; + + [Link("BufferToTexture.clipMapResolution")] + stage float3 clipMapResolution; + + [Link("BufferToTexture.storageUints")] + stage float storageUints; + + [Link("BufferToTexture.clipOffset")] + stage uint clipOffset; + + + compose VoxelAttribute AttributesTemp[]; + compose VoxelAttribute AttributesIndirect[]; + + #ifndef IndirectStoreMacro + #define IndirectStoreMacro + #define IndirectReadAndStoreMacro + #endif + + override void Compute() + { + int3 clipMapResolutionI = (int3)clipMapResolution; + + uint3 pos = streams.DispatchThreadId.xyz; + uint clipIndex = streams.DispatchThreadId.y + clipOffset; + + pos.y = 0; + streams.PositionVXPS = pos; + streams.VoxelVolumeSize = clipMapResolutionI; + + uint wStride = clipMapResolutionI.x * clipMapResolutionI.y * clipMapResolutionI.z; + uint VoxelFragmentsIndex = clipIndex * wStride + pos.x + pos.y * clipMapResolutionI.x + pos.z * clipMapResolutionI.x * clipMapResolutionI.y; + VoxelFragmentsIndex *= (uint)storageUints; + + uint yStride = clipMapResolutionI.x * (uint)storageUints; + uint initialVoxelFragmentsIndex = VoxelFragmentsIndex; + + foreach (var attr in AttributesTemp) + attr.InitializeDummy(); + foreach (var attr in AttributesIndirect) + attr.InitializeDummy(); + + IndirectStoreMacro + + VoxelFragmentsIndex += (uint)storageUints * clipMapResolutionI.x; + + foreach (var attr in AttributesIndirect) + attr.DirectWrite(streams.PositionVXPS, clipIndex, (int)clipMapResolutionI.y); + + streams.PositionVXPS.y++; + for (int i = 0; streams.PositionVXPS.y < clipMapResolutionI.y-1 ; streams.PositionVXPS.y ++) + { + uint VoxelFragmentsIndexOld = VoxelFragmentsIndex; + + //See VoxelStorageClipmaps.cs Line #307 + IndirectReadAndStoreMacro + + foreach (var attr in AttributesIndirect) + attr.DirectWrite(streams.PositionVXPS, clipIndex, (int)clipMapResolutionI.y); + + VoxelFragmentsIndex = VoxelFragmentsIndexOld + (uint)storageUints * clipMapResolutionI.x; + } + foreach (var attr in AttributesTemp) + attr.InitializeDummy(); + + foreach (var attr in AttributesIndirect) + attr.InitializeDummy(); + + IndirectStoreMacro + + foreach (var attr in AttributesIndirect) + attr.DirectWrite(streams.PositionVXPS, clipIndex, (int)clipMapResolutionI.y); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.cs new file mode 100644 index 0000000000..fdb114d9cd --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.cs @@ -0,0 +1,68 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + internal static partial class ShaderMixins + { + internal partial class BufferToTextureColumnsEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "BufferToTextureColumns"); + if (context.GetParam(BufferToTextureKeys.AttributesIndirect) != null) + { + foreach(var attr in context.GetParam(BufferToTextureKeys.AttributesIndirect)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributesIndirect", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + if (context.GetParam(BufferToTextureKeys.AttributesTemp) != null) + { + foreach(var attr in context.GetParam(BufferToTextureKeys.AttributesTemp)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributesTemp", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + mixin.AddMacro("IndirectReadAndStoreMacro", context.GetParam(BufferToTextureKeys.IndirectReadAndStoreMacro)); + mixin.AddMacro("IndirectStoreMacro", context.GetParam(BufferToTextureKeys.IndirectStoreMacro)); + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("BufferToTextureColumnsEffect", new BufferToTextureColumnsEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.xksl new file mode 100644 index 0000000000..60be573b0a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.xksl @@ -0,0 +1,26 @@ +namespace Xenko.Rendering.Voxels +{ + partial effect BufferToTextureColumnsEffect + { + using params BufferToTextureKeys; + + mixin BufferToTextureColumns; + if (BufferToTextureKeys.AttributesIndirect!=null) + { + foreach (var attr in BufferToTextureKeys.AttributesIndirect) + { + mixin compose AttributesIndirect += (attr); + } + } + if (BufferToTextureKeys.AttributesTemp!=null) + { + foreach (var attr in BufferToTextureKeys.AttributesTemp) + { + mixin compose AttributesTemp += (attr); + } + } + + mixin macro BufferToTextureKeys.IndirectReadAndStoreMacro; + mixin macro BufferToTextureKeys.IndirectStoreMacro; + }; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs new file mode 100644 index 0000000000..837a586525 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs @@ -0,0 +1,36 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + internal static partial class ShaderMixins + { + internal partial class BufferToTextureEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "BufferToTexture"); + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("BufferToTextureEffect", new BufferToTextureEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl new file mode 100644 index 0000000000..1685893276 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl @@ -0,0 +1,9 @@ +namespace Xenko.Rendering.Voxels +{ + partial effect BufferToTextureEffect + { + using params BufferToTextureKeys; + + mixin BufferToTexture; + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureKeys.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureKeys.cs new file mode 100644 index 0000000000..fcb2c81fb6 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureKeys.cs @@ -0,0 +1,13 @@ +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public partial class BufferToTextureKeys + { + public static readonly PermutationParameterKey AttributesIndirect = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey AttributesTemp = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey AttributeLocalSamples = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey IndirectReadAndStoreMacro = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey IndirectStoreMacro = ParameterKeys.NewPermutation(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.cs new file mode 100644 index 0000000000..abadc8e1dc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.cs @@ -0,0 +1,24 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class ClearBufferKeys + { + public static readonly ObjectParameterKey buffer = ParameterKeys.NewObject(); + public static readonly ValueParameterKey offset = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.xksl new file mode 100644 index 0000000000..d0580293f2 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.xksl @@ -0,0 +1,12 @@ +namespace Xenko.Rendering.Voxels +{ + shader ClearBuffer : ComputeShaderBase + { + stage RWBuffer buffer; + int offset; + override void Compute() + { + buffer[streams.DispatchThreadId.x + offset] = 0; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.cs new file mode 100644 index 0000000000..e3c944023e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.cs @@ -0,0 +1,30 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelStorageClipmapShaderKeys + { + public static readonly ValueParameterKey clipMapResolution = ParameterKeys.NewValue(); + public static readonly ValueParameterKey clipPos = ParameterKeys.NewValue(); + public static readonly ValueParameterKey clipScale = ParameterKeys.NewValue(); + public static readonly ValueParameterKey clipOffset = ParameterKeys.NewValue(); + public static readonly ValueParameterKey clipMapCount = ParameterKeys.NewValue(); + public static readonly ValueParameterKey perClipMapOffsetScale = ParameterKeys.NewValue(); + public static readonly ValueParameterKey storageUints = ParameterKeys.NewValue(); + public static readonly ObjectParameterKey fragmentsBuffer = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.xksl new file mode 100644 index 0000000000..1df2611e6d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.xksl @@ -0,0 +1,105 @@ +shader VoxelStorageClipmapShader : VoxelStorageShader, Texturing, ShaderBaseStream, Transformation +{ + cbuffer PerView.VoxelizerStorer + { + float3 clipMapResolution; + //#ifdef singleClip + float clipPos; + float3 clipScale; + float3 clipOffset; + //#else + float clipMapCount; + float4 perClipMapOffsetScale[20]; + //#endif + float storageUints; + } + rgroup PerView.VoxelizerStorer + { + RWBuffer fragmentsBuffer; + } + compose VoxelAttribute AttributesTemp[]; + compose VoxelAttribute AttributesDirect[]; + compose VoxelAttribute AttributesIndirect[]; + + #ifdef singleClip + #define clipScaleIn clipScale + #define clipOffsetIn clipOffset + #define clipPosIn ((uint)clipPos) + #else + stage stream uint clipIndex; + #define clipScaleIn perClipMapOffsetScale[streams.clipIndex].w + #define clipOffsetIn perClipMapOffsetScale[streams.clipIndex].xyz + #define clipPosIn ((streams.clipIndex) * clipMapResolutionI.x * clipMapResolutionI.y * clipMapResolutionI.z) + #endif + + #ifndef IndirectStoreMacro + #define IndirectStoreMacro + #endif + + override bool MightStoreFragments() + { + float3 texPos = streams.PositionWS.xyz * clipScaleIn + clipOffsetIn; + return dot(texPos - saturate(texPos), float3(1, 1, 1)) == 0; + } + override void StoreFragments() + { + int3 clipMapResolutionI = (int3)clipMapResolution; + + float3 texPos = streams.PositionWS.xyz * clipScaleIn + clipOffsetIn; + + streams.PositionVXS = texPos; + streams.VoxelVolumeSize = clipMapResolution; + streams.PositionVXPS = int3(floor(saturate(texPos) * clipMapResolution)); + + int3 pixelPos = streams.PositionVXPS; + + uint index = clipPosIn + pixelPos.x + pixelPos.y * clipMapResolutionI.x + pixelPos.z * clipMapResolutionI.x * clipMapResolutionI.y; + + uint writeindex = index * (uint)storageUints; + + foreach (var attr in AttributesTemp) + { + attr.InitializeFromStreams(); + } + + foreach (var attr in AttributesDirect) + { + attr.InitializeFromStreams(); + } + + foreach (var attr in AttributesIndirect) + { + attr.InitializeFromStreams(); + } + + //See VoxelStorageClipmaps.cs Line #307 and Line #425 + IndirectStoreMacro + } + #ifndef singleClip + override void GenerateTriangles(triangle Input input[3], inout TriangleStream triangleStream) + { + method.InitializeFromTriangle(input); + int3 clipMapResolutionI = (int3)clipMapResolution; + + for (streams.clipIndex = 0; streams.clipIndex < clipMapCount; streams.clipIndex++) + { + [unroll] + for (int i = 0; i < 3 ; i ++) + { + streams = input[i]; + streams.ShadingPosition.xyz = mul(float4(streams.PositionWS.xyz * clipScaleIn + clipOffsetIn, 1),Transformation.View).xyz; + streams.ShadingPosition.xyz = streams.ShadingPosition.xyz * 2 - 1; + method.Append(triangleStream); + } + method.RestartStrip(triangleStream); + } + } + #else + override void PrepareVertex() + { + method.PrepareVertex(); + streams.ShadingPosition.xyz = mul(float4(streams.PositionWS.xyz * clipScaleIn + clipOffsetIn, 1),Transformation.View).xyz; + streams.ShadingPosition.xyz = streams.ShadingPosition.xyz * 2 - 1; + } + #endif +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.xksl new file mode 100644 index 0000000000..08aa5323f9 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.xksl @@ -0,0 +1,19 @@ +shader VoxelStorageShader : VoxelPositionStream, PositionStream4, ShaderBaseStream +{ + compose VoxelizationMethod method; + void PrepareFragments(){ method.PrepareFragment(); } + void StoreFragments(){ } + bool MightStoreFragments(){ return false; } + void PrepareVertex(){ method.PrepareVertex(); } + void GenerateTriangles(triangle Input input [3], inout TriangleStream triangleStream) + { + method.InitializeFromTriangle(input); + [unroll] + for (int i = 0; i < 3 ; i++) + { + streams = input[i]; + method.Append(triangleStream); + } + method.RestartStrip(triangleStream); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.cs new file mode 100644 index 0000000000..cc653c2120 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.cs @@ -0,0 +1,27 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelStorageTextureClipmapShaderKeys + { + public static readonly ValueParameterKey perMapOffsetScale = ParameterKeys.NewValue(); + public static readonly ObjectParameterKey clipMaps = ParameterKeys.NewObject(); + public static readonly ObjectParameterKey mipMaps = ParameterKeys.NewObject(); + public static readonly ObjectParameterKey LinearBorderSampler3D = ParameterKeys.NewObject(); + public static readonly ObjectParameterKey LinearBorderSampler3D_NearestMip = ParameterKeys.NewObject(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.xksl new file mode 100644 index 0000000000..f8dc22c11e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.xksl @@ -0,0 +1,179 @@ +shader VoxelStorageTextureClipmapShader : VoxelStorageTextureShader, Texturing +{ + #define MapCount 20 + cbuffer PerView.Lighting + { + float4 perMapOffsetScale[MapCount]; + } + rgroup PerView.Lighting + { + Texture3D clipMaps; + Texture3D mipMaps; + } + + stage SamplerState LinearBorderSampler3D + { + Filter = MIN_MAG_MIP_LINEAR; + AddressU = Border; + AddressV = Border; + AddressW = Border; + }; + stage SamplerState LinearBorderSampler3D_NearestMip + { + Filter = MIN_MAG_LINEAR_MIP_POINT; + AddressU = Border; + AddressV = Border; + AddressW = Border; + }; + override float VoxelSize() + { + return voxelSizeT; + } + override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) + { + if (textureID == 0) + { + return clipMaps.SampleLevel(Sampler, pos, 0); + } + else + { + return mipMaps.SampleLevel(Sampler, pos, mipmap); + } + return float4(0,0,0,0); + } + + override float4 SampleNearestMip(float3 pos, float diameter, int axis) + { + diameter *= 1.0 / voxelSizeT; + float mipmap = log2(max(1, diameter)); + return SampleByMipNearestMip(pos, mipmap, axis); + } + override float4 SampleByMipNearestMip(float3 pos, float mipmap, int axis) + { + //Clipmaps + float3 clipMapSizeClip = float3(1, 1.0 / (clipCountT * axisCountT), 1); + float3 axisStrideClip = float3(0, 1.0 / (clipCountT * axisCountT), 0); + float3 clipSetStrideClip = float3(0, 1.0 / clipCountT, 0); + + //Mipmaps + float3 axisSizeMip = float3(1, 1.0 / (axisCountT), 1); + float3 axisStrideMip = float3(0, 1.0 / (axisCountT), 0); + + float mipBase = floor(mipmap); + + float4 offsetScale = perMapOffsetScale[mipBase]; + pos = pos * offsetScale.w + offsetScale.xyz; + + if (mipBase >= clipCountT) + { + //Seperate the different axis within the same texture + //by clamping to the usable texel range + //and fading out above and below + float boundaryFade = 1.0; + if (axisCountT > 1) + { + float height = mipHeightT / (pow(2, mipBase - clipCountT)); + + float texelY = pos.y * height; + float texelYClamped = clamp(texelY, 1, height - 1); + float boundaryFade = saturate(1.0 - abs(texelYClamped - texelY)); + + pos.y = texelYClamped / height; + + pos *= axisSizeMip; + pos += axisStrideMip * axis; + } + return mipMaps.SampleLevel(LinearBorderSampler3D_NearestMip, pos, mipBase - clipCountT) * boundaryFade; + } + else + { + pos.y = saturate(pos.y); + + pos *= clipMapSizeClip; + pos += axisStrideClip * axis + clipSetStrideClip * mipBase; + return clipMaps.SampleLevel(LinearBorderSampler3D_NearestMip, pos, 0); + } + } + override float4 Sample(float3 pos, float diameter, int axis) + { + //Clipmaps + float3 clipMapSizeClip = float3(1, 1.0 / (clipCountT * axisCountT), 1); + float3 axisStrideClip = float3(0, 1.0 / (clipCountT * axisCountT), 0); + float3 clipSetStrideClip = float3(0, 1.0 / clipCountT, 0); + + //Mipmaps + float3 axisSizeMip = float3(1, 1.0 / (axisCountT), 1); + float3 axisStrideMip = float3(0, 1.0 / (axisCountT), 0); + + + diameter *= 1.0 / voxelSizeT; + float mipmap = log2(max(1, diameter)); + + float mipBase = floor(mipmap); + + + float4 offsetScale = perMapOffsetScale[mipBase]; + float3 posFine = pos * offsetScale.w + offsetScale.xyz; + + offsetScale = perMapOffsetScale[mipBase + 1]; + float3 posCoarse = pos * offsetScale.w + offsetScale.xyz; + if (mipBase >= clipCountT) + { + //Seperate the different axis within the same texture + //by clamping to the usable texel range + //and fading out above and below + float boundaryFade = 1.0; + if (axisCountT > 1) + { + float height = mipHeightT / (pow(2, mipBase - clipCountT)); + + float texelY = posFine.y * height; + float texelYClamped = clamp(texelY, 1, height - 1); + float boundaryFade = saturate(1.0 - abs(texelYClamped - texelY)); + + posFine.y = texelYClamped / height; + + posFine *= axisSizeMip; + posFine += axisStrideMip * axis; + + posCoarse *= axisSizeMip; + posCoarse += axisStrideMip * axis; + } + return lerp ( + mipMaps.SampleLevel(LinearBorderSampler3D, posFine, mipBase - clipCountT), + mipMaps.SampleLevel(LinearBorderSampler3D, posCoarse, mipBase - clipCountT + 1), + mipmap - mipBase) * boundaryFade; + } + else + { + posFine.y = saturate(posFine.y); + posCoarse.y = saturate(posCoarse.y); + if (mipBase == clipCountT-1) + { + posFine *= clipMapSizeClip; + posFine += axisStrideClip * axis + clipSetStrideClip * mipBase; + + posCoarse *= axisSizeMip; + posCoarse += axisStrideMip * axis; + return lerp( + clipMaps.SampleLevel(LinearBorderSampler3D, posFine, 0), + mipMaps.SampleLevel(LinearBorderSampler3D, posCoarse, 0), + mipmap-mipBase + ); + } + else + { + posFine *= clipMapSizeClip; + posFine += axisStrideClip * axis + clipSetStrideClip * mipBase; + + posCoarse *= clipMapSizeClip; + posCoarse += axisStrideClip * axis + clipSetStrideClip * (mipBase+1); + return lerp( + clipMaps.SampleLevel(LinearBorderSampler3D, posFine, 0), + clipMaps.SampleLevel(LinearBorderSampler3D, posCoarse, 0), + mipmap-mipBase + ); + } + } + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.xksl new file mode 100644 index 0000000000..fc4fdb9873 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.xksl @@ -0,0 +1,8 @@ +shader VoxelStorageTextureShader +{ + float4 Sample(float3 pos, float diameter, int axis){ return float4(0, 1, 0, 0); } + float4 SampleNearestMip(float3 pos, float diameter, int axis){ return float4(0, 1, 0, 0); } + float4 SampleByMipNearestMip(float3 pos, float mipmap, int axis){ return float4(0, 1, 0, 0); } + float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis){ return float4(1, 0, 0, 0); } + float VoxelSize(){ return 1.0; }; +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs new file mode 100644 index 0000000000..4cdf4f1744 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs @@ -0,0 +1,368 @@ +using System; +using System.Collections.Generic; +using Xenko.Core.Mathematics; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Graphics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Clipmaps")] + public class VoxelStorageClipmaps : IVoxelStorage + { + public enum Resolutions{ + x32 = 32, + x64 = 64, + x128 = 128, + x256 = 256 + }; + public enum UpdateMethods + { + [Display("Single Clipmap")] SingleClipmap, + [Display("All Clipmaps (Geometry Shader)")] AllClipmapsGeometryShader, + [Display("All Clipmaps (Multiple Renders)")] AllClipmapsMultipleRenders, + }; + + [DataMember(0)] + public Resolutions ClipResolution { get; set; } = Resolutions.x128; + [DataMember(10)] + public UpdateMethods UpdatesPerFrame { get; set; } = UpdateMethods.SingleClipmap; + [DataMember(20)] + public bool DownsampleFinerClipMaps { get; set; } = true; + + int storageUints; + Xenko.Graphics.Buffer FragmentsBuffer = null; + + int ClipMapCount; + int MipMapCount; + int ClipMapCurrent = -1; + Vector3 ClipMapResolution; + + Vector3[] PerMapSnappingOffset = new Vector3[20]; + Vector4[] PerMapOffsetScale = new Vector4[20]; + Vector3[] MippingOffset = new Vector3[20]; + Int3[] MippingOffsetTranslation = new Int3[20]; + + bool ShouldUpdateClipIndex(int i) + { + return i == ClipMapCurrent || UpdatesPerFrame != UpdateMethods.SingleClipmap || (i >= ClipMapCount && ClipMapCurrent == ClipMapCount - 1); + } + + public void UpdateFromContext(VoxelStorageContext context) + { + var virtualResolution = context.Resolution(); + var largestDimension = (double)Math.Max(virtualResolution.X, Math.Max(virtualResolution.Y, virtualResolution.Z)); + + ClipMapCount = (int)Math.Log(largestDimension / Math.Min(largestDimension, (double)ClipResolution), 2) + 1; + + ClipMapCurrent++; + if (ClipMapCurrent >= ClipMapCount) + { + ClipMapCurrent = 0; + } + + float FinestClipMapScale = (float)Math.Pow(2, ClipMapCount - 1); + ClipMapResolution = new Vector3(virtualResolution.X, virtualResolution.Y, virtualResolution.Z) / FinestClipMapScale; + MipMapCount = (int)Math.Floor(Math.Log(Math.Min(ClipMapResolution.X, Math.Min(ClipMapResolution.Y, ClipMapResolution.Z)), 2)); + + int voxelScale = 1; + + for (int i = 0; i < (ClipMapCount + MipMapCount); i++) + { + Vector3 SnappedVolumeTranslation = context.VoxelSpaceTranslation; + SnappedVolumeTranslation.X = (float)Math.Floor(SnappedVolumeTranslation.X / voxelScale) * voxelScale; + SnappedVolumeTranslation.Y = (float)Math.Floor(SnappedVolumeTranslation.Y / voxelScale) * voxelScale; + SnappedVolumeTranslation.Z = (float)Math.Floor(SnappedVolumeTranslation.Z / voxelScale) * voxelScale; + + if (ShouldUpdateClipIndex(i)) + { + PerMapSnappingOffset[i] = -SnappedVolumeTranslation * context.RealVoxelSize(); + MippingOffsetTranslation[i] = new Int3((int)SnappedVolumeTranslation.X, (int)SnappedVolumeTranslation.Y, (int)SnappedVolumeTranslation.Z); + } + + voxelScale *= 2; + } + + float extentScale = (float)Math.Pow(2f, ClipMapCount - 1); + voxelScale = 1; + + for (int i = 0; i < (ClipMapCount + MipMapCount); i++) + { + if (ShouldUpdateClipIndex(i)) + { + Vector3 offset = (PerMapSnappingOffset[i]) * extentScale / context.Extents + 0.5f; + PerMapOffsetScale[i] = new Vector4(offset, (1.0f / context.Extents.X) * extentScale); + } + + if (i + 1 == ClipMapCurrent || ShouldUpdateClipIndex(i)) + { + MippingOffset[i] = (Vector3)((MippingOffsetTranslation[i] - MippingOffsetTranslation[i + 1]) / voxelScale); + } + + if (i < ClipMapCount - 1) + { + extentScale /= 2; + } + voxelScale *= 2; + } + + } + + + int tempStorageCounter; + public int RequestTempStorage(int count) + { + int bufferOffset = tempStorageCounter / 32; + tempStorageCounter += ((count+31)/32)*32; + return bufferOffset; + } + + public void UpdateTempStorage(VoxelStorageContext context) + { + storageUints = (tempStorageCounter + 31)/32; + tempStorageCounter = 0; + + var resolution = ClipMapResolution; + int fragments = (int)(resolution.X * resolution.Y * resolution.Z) * ClipMapCount; + + if (VoxelUtils.DisposeBufferBySpecs(FragmentsBuffer, storageUints * fragments) && storageUints * fragments > 0) + { + FragmentsBuffer = Xenko.Graphics.Buffer.Typed.New(context.device, storageUints * fragments, PixelFormat.R32_UInt, true); + } + } + + + + public void UpdateTexture(VoxelStorageContext context, ref IVoxelStorageTexture texture, Xenko.Graphics.PixelFormat pixelFormat, int LayoutSize) + { + VoxelStorageTextureClipmap clipmap = texture as VoxelStorageTextureClipmap; + if (clipmap == null) + { + clipmap = new VoxelStorageTextureClipmap(); + } + + Vector3 ClipMapTextureResolution = new Vector3(ClipMapResolution.X, ClipMapResolution.Y * ClipMapCount * LayoutSize, ClipMapResolution.Z); + Vector3 MipMapResolution = new Vector3(ClipMapResolution.X / 2, ClipMapResolution.Y / 2 * LayoutSize, ClipMapResolution.Z / 2); + if (VoxelUtils.DisposeTextureBySpecs(clipmap.ClipMaps, ClipMapTextureResolution, pixelFormat)) + { + clipmap.ClipMaps = Xenko.Graphics.Texture.New3D(context.device, (int)ClipMapTextureResolution.X, (int)ClipMapTextureResolution.Y, (int)ClipMapTextureResolution.Z, new MipMapCount(false), pixelFormat, TextureFlags.ShaderResource | TextureFlags.UnorderedAccess); + } + if (VoxelUtils.DisposeTextureBySpecs(clipmap.MipMaps, MipMapResolution, pixelFormat)) + { + if (clipmap.TempMipMaps != null) + { + for (int i = 0; i < clipmap.TempMipMaps.Length; i++) + { + clipmap.TempMipMaps[i].Dispose(); + } + } + + Vector3 MipMapResolutionMax = MipMapResolution; + + clipmap.MipMaps = Xenko.Graphics.Texture.New3D(context.device, (int)MipMapResolution.X, (int)MipMapResolution.Y, (int)MipMapResolution.Z, new MipMapCount(true), pixelFormat, TextureFlags.ShaderResource | TextureFlags.UnorderedAccess); + + clipmap.TempMipMaps = new Xenko.Graphics.Texture[MipMapCount]; + + for (int i = 0; i < clipmap.TempMipMaps.Length; i++) + { + clipmap.TempMipMaps[i] = Xenko.Graphics.Texture.New3D(context.device, (int)MipMapResolutionMax.X, (int)MipMapResolutionMax.Y, (int)MipMapResolutionMax.Z, false, pixelFormat, TextureFlags.ShaderResource | TextureFlags.UnorderedAccess); + + MipMapResolutionMax /= 2; + } + } + clipmap.DownsampleFinerClipMaps = DownsampleFinerClipMaps; + clipmap.ClipMapResolution = ClipMapResolution; + clipmap.ClipMapCount = ClipMapCount; + clipmap.LayoutSize = LayoutSize; + clipmap.VoxelSize = context.RealVoxelSize(); + clipmap.VolumeTranslation = new Int3((int)context.VoxelSpaceTranslation.X, (int)context.VoxelSpaceTranslation.Y, (int)context.VoxelSpaceTranslation.Z); + + Array.Copy(MippingOffset, clipmap.MippingOffset, MippingOffset.Length); + Array.Copy(PerMapOffsetScale, clipmap.PerMapOffsetScale, PerMapOffsetScale.Length); + + + + texture = clipmap; + } + + public void CollectVoxelizationPasses(ProcessedVoxelVolume data, VoxelStorageContext storageContext) + { + Matrix BaseVoxelMatrix = storageContext.Matrix; + BaseVoxelMatrix.Invert(); + BaseVoxelMatrix = BaseVoxelMatrix * Matrix.Scaling(2f, 2f, 2f); + if (UpdatesPerFrame != UpdateMethods.AllClipmapsMultipleRenders) + { + /* + * Having trouble with shadow culling when this is enabled - currently performed in vertex shader instead + if (UpdateMethod == UpdateMethods.OneClipPerFrame) + { + BaseVoxelMatrix = Matrix.Scaling(PerMapOffsetScale[ClipMapCurrent].W) * Matrix.Translation(PerMapOffsetScale[ClipMapCurrent].XYZ()); + BaseVoxelMatrix = BaseVoxelMatrix * Matrix.Translation(-0.5f,-0.5f,-0.5f); + BaseVoxelMatrix = BaseVoxelMatrix * Matrix.Scaling(2f, 2f, 2f); + } + */ + VoxelStorerClipmap Storer = new VoxelStorerClipmap + { + storageUints = storageUints, + FragmentsBuffer = FragmentsBuffer, + ClipMapCount = ClipMapCount, + ClipMapCurrent = ClipMapCurrent, + ClipMapResolution = ClipMapResolution, + PerMapOffsetScale = PerMapOffsetScale, + UpdatesPerFrame = UpdatesPerFrame + }; + foreach (var attr in data.Attributes) + { + attr.Attribute.CollectVoxelizationPasses(data.passList, Storer, BaseVoxelMatrix, ClipMapResolution, attr.Stage, attr.Output); + } + } + if (UpdatesPerFrame == UpdateMethods.AllClipmapsMultipleRenders) + { + for (int i = 0; i < ClipMapCount; i++) + { + VoxelStorerClipmap Storer = new VoxelStorerClipmap + { + storageUints = storageUints, + FragmentsBuffer = FragmentsBuffer, + ClipMapCount = ClipMapCount, + ClipMapCurrent = i, + ClipMapResolution = ClipMapResolution, + PerMapOffsetScale = PerMapOffsetScale, + UpdatesPerFrame = UpdateMethods.SingleClipmap + }; + foreach (var attr in data.Attributes) + { + attr.Attribute.CollectVoxelizationPasses(data.passList, Storer, BaseVoxelMatrix, ClipMapResolution, attr.Stage, attr.Output); + } + } + } + } + + Xenko.Rendering.ComputeEffect.ComputeEffectShader BufferToTextureColumns; + Xenko.Rendering.ComputeEffect.ComputeEffectShader ClearBuffer; + + public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext drawContext, ProcessedVoxelVolume data) + { + if (Math.Max(Math.Max(ClipMapResolution.X, ClipMapResolution.Y), ClipMapResolution.Z) < 32) + return; + if (FragmentsBuffer == null) + return; + var context = drawContext.RenderContext; + if (ClearBuffer == null) + { + ClearBuffer = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(context) { ShaderSourceName = "ClearBuffer" }; + //BufferToTexture = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(Context) { ShaderSourceName = "BufferToTextureEffect" }; + BufferToTextureColumns = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(context) { ShaderSourceName = "BufferToTextureColumnsEffect" }; + } + + List IndirectVoxels = new List(); + List TempVoxels = new List(); + ShaderSourceCollection Indirect = new ShaderSourceCollection(); + ShaderSourceCollection Temp = new ShaderSourceCollection(); + foreach (var attr in data.Attributes) + { + if (attr.Stage != VoxelizationStage.Post) continue; + if (attr.Output) + { + Indirect.Add(attr.Attribute.GetVoxelizationShader()); + IndirectVoxels.Add(attr.Attribute); + } + else + { + Temp.Add(attr.Attribute.GetVoxelizationShader()); + TempVoxels.Add(attr.Attribute); + } + } + + + var BufferWriter = BufferToTextureColumns; + for (int i = 0; i < IndirectVoxels.Count; i++) + { + var attr = IndirectVoxels[i]; + attr.UpdateVoxelizationLayout("AttributesIndirect[" + i + "]"); + } + for (int i = 0; i < TempVoxels.Count; i++) + { + var attr = TempVoxels[i]; + attr.UpdateVoxelizationLayout("AttributesTemp[" + i + "]"); + } + foreach (var attr in data.Attributes) + { + attr.Attribute.ApplyVoxelizationParameters(BufferWriter.Parameters); + } + + + BufferWriter.ThreadGroupCounts = new Int3(32, 1, 32); + if (UpdatesPerFrame == UpdateMethods.SingleClipmap) + { + BufferWriter.ThreadNumbers = new Int3((int)ClipMapResolution.X / BufferWriter.ThreadGroupCounts.X, 1 / BufferWriter.ThreadGroupCounts.Y, (int)ClipMapResolution.Z / BufferWriter.ThreadGroupCounts.Z); + } + else + { + BufferWriter.ThreadNumbers = new Int3((int)ClipMapResolution.X / BufferWriter.ThreadGroupCounts.X, ClipMapCount / BufferWriter.ThreadGroupCounts.Y, (int)ClipMapResolution.Z / BufferWriter.ThreadGroupCounts.Z); + } + + BufferWriter.Parameters.Set(BufferToTextureKeys.VoxelFragments, FragmentsBuffer); + BufferWriter.Parameters.Set(BufferToTextureKeys.clipMapResolution, ClipMapResolution); + BufferWriter.Parameters.Set(BufferToTextureKeys.storageUints, storageUints); + + BufferWriter.Parameters.Set(BufferToTextureKeys.clipOffset, (uint)(UpdatesPerFrame == UpdateMethods.SingleClipmap ? ClipMapCurrent : 0)); + + + //Modifiers are stored within attributes, yet need to be able to query their results. + //Ideally a stage stream could resolve this, however due to the lack of pointers, there would be a cyclic dependency of AttributesList->Attribute->Modifier->AttributesList->... + //So instead the results will be stored within a second array that only contains float4s. Unfortunately the only way to iterate through the AttributesList is by foreach, which + //makes it difficult to access the results array (AttributeLocalSamples) by index. So instead it's just all done through this macro... + string IndirectReadAndStoreMacro = ""; + string IndirectStoreMacro = ""; + int sampleIndex = 0; + for (int i = 0; i < Temp.Count; i ++) + { + string iStr = i.ToString(); + string sampleIndexStr = sampleIndex.ToString(); + IndirectReadAndStoreMacro += "AttributesTemp[" + iStr + "].InitializeFromBuffer(VoxelFragments, VoxelFragmentsIndex + " + TempVoxels[i].GetBufferOffset().ToString() + ", uint2(" + TempVoxels[i].GetBufferOffset().ToString() + " + initialVoxelFragmentsIndex, yStride));\n" + + "streams.LocalSample[" + sampleIndexStr + "] = AttributesTemp[" + iStr + "].SampleLocal();\n\n"; + IndirectStoreMacro += "streams.LocalSample[" + sampleIndexStr + "] = AttributesTemp[" + iStr + "].SampleLocal();\n"; + TempVoxels[i].SetLocalSamplerID(sampleIndex); + sampleIndex++; + } + for (int i = 0; i < Indirect.Count; i++) + { + string iStr = i.ToString(); + string sampleIndexStr = sampleIndex.ToString(); + IndirectReadAndStoreMacro += "AttributesIndirect[" + iStr + "].InitializeFromBuffer(VoxelFragments, VoxelFragmentsIndex + " + IndirectVoxels[i].GetBufferOffset().ToString() + ", uint2(" + IndirectVoxels[i].GetBufferOffset().ToString() + " + initialVoxelFragmentsIndex, yStride));\n" + + "streams.LocalSample[" + sampleIndexStr + "] = AttributesIndirect[" + iStr + "].SampleLocal();\n\n"; + IndirectStoreMacro += "streams.LocalSample[" + sampleIndexStr + "] = AttributesIndirect[" + iStr + "].SampleLocal();\n"; + IndirectVoxels[i].SetLocalSamplerID(sampleIndex); + sampleIndex++; + } + + BufferWriter.Parameters.Set(BufferToTextureKeys.AttributesIndirect, Indirect); + BufferWriter.Parameters.Set(BufferToTextureKeys.AttributesTemp, Temp); + BufferWriter.Parameters.Set(BufferToTextureKeys.IndirectReadAndStoreMacro, IndirectReadAndStoreMacro); + BufferWriter.Parameters.Set(BufferToTextureKeys.IndirectStoreMacro, IndirectStoreMacro); + + ((RendererBase)BufferWriter).Draw(drawContext); + + ClearBuffer.Parameters.Set(ClearBufferKeys.buffer, FragmentsBuffer); + + if (UpdatesPerFrame != UpdateMethods.SingleClipmap) + { + //Clear all + ClearBuffer.ThreadNumbers = new Int3(1024, 1, 1); + ClearBuffer.ThreadGroupCounts = new Int3(FragmentsBuffer.ElementCount / 1024, 1, 1); + ClearBuffer.Parameters.Set(ClearBufferKeys.offset, 0); + } + else + { + //Clear next clipmap buffer + ClearBuffer.ThreadNumbers = new Int3(1024, 1, 1); + ClearBuffer.ThreadGroupCounts = new Int3((int)(ClipMapResolution.X * ClipMapResolution.Y * ClipMapResolution.Z * storageUints) / 1024, 1, 1); + ClearBuffer.Parameters.Set(ClearBufferKeys.offset, (int)(((ClipMapCurrent+1) % ClipMapCount) * ClipMapResolution.X * ClipMapResolution.Y * ClipMapResolution.Z * storageUints)); + } + ((RendererBase)ClearBuffer).Draw(drawContext); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageContext.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageContext.cs new file mode 100644 index 0000000000..11d34a3e27 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageContext.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using Xenko.Core.Mathematics; +using Xenko.Graphics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public class VoxelStorageContext + { + public GraphicsDevice device; + public Vector3 Extents; + public Vector3 Translation; + public Vector3 VoxelSpaceTranslation; + public float VoxelSize; + public Matrix Matrix; + + public float RealVoxelSize() + { + Int3 resolution = Resolution(); + return Extents.X/(float)resolution.X; + } + public Int3 Resolution() + { + var resolution = Extents / VoxelSize; + + //Calculate closest power of 2 on each axis + resolution.X = (float)Math.Pow(2, Math.Round(Math.Log(resolution.X, 2))); + resolution.Y = (float)Math.Pow(2, Math.Round(Math.Log(resolution.Y, 2))); + resolution.Z = (float)Math.Pow(2, Math.Round(Math.Log(resolution.Z, 2))); + + return new Int3((int)resolution.X, (int)resolution.Y, (int)resolution.Z); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs new file mode 100644 index 0000000000..5d53d410a7 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs @@ -0,0 +1,192 @@ +using System; +using System.Collections.Generic; +using Xenko.Core.Mathematics; +using Xenko.Graphics; +using Xenko.Rendering.Shadows; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public class VoxelStorageTextureClipmap : IVoxelStorageTexture + { + public Vector3 ClipMapResolution; + public int ClipMapCount; + public int LayoutSize; + public float VoxelSize; + public Int3 VolumeTranslation; + + public bool DownsampleFinerClipMaps; + + public Xenko.Graphics.Texture ClipMaps = null; + public Xenko.Graphics.Texture MipMaps = null; + public Xenko.Graphics.Texture[] TempMipMaps = null; + + public Vector4[] PerMapOffsetScale = new Vector4[20]; + public Vector4[] PerMapOffsetScaleCurrent = new Vector4[20]; + public Vector3[] MippingOffset = new Vector3[20]; + + ShaderClassSource sampler = new ShaderClassSource("VoxelStorageTextureClipmapShader"); + + public void UpdateVoxelizationLayout(string compositionName) + { + + } + public void ApplyVoxelizationParameters(ObjectParameterKey MainKey, ParameterCollection parameters) + { + parameters.Set(MainKey, ClipMaps); + } + string curMipMapShader = ""; + Xenko.Rendering.ComputeEffect.ComputeEffectShader VoxelMipmapSimple; + //Memory leaks if the ThreadGroupCounts/Numbers changes (I suppose due to recompiles...?) + //so instead cache them as seperate shaders. + Xenko.Rendering.ComputeEffect.ComputeEffectShader[] VoxelMipmapSimpleGroups; + + Int3 ToInt3(Vector3 v) + { + return new Int3((int)v.X, (int)v.Y, (int)v.Z); + } + + float Mod(float v, float m) + { + return ((v % m) + m) % m;//Proper modulo + } + Vector3 Mod(Vector3 v, Vector3 m) + { + return new Vector3(Mod(v.X, m.X), Mod(v.Y, m.Y), Mod(v.Z, m.Z)); + } + + public void PostProcess(RenderDrawContext drawContext, string MipMapShader) + { + if (VoxelMipmapSimple == null || curMipMapShader != MipMapShader) + { + if (VoxelMipmapSimple != null) + VoxelMipmapSimple.Dispose(); + VoxelMipmapSimple = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = MipMapShader }; + } + if (VoxelMipmapSimpleGroups == null || VoxelMipmapSimpleGroups.Length != TempMipMaps.Length || curMipMapShader != MipMapShader) + { + if (VoxelMipmapSimpleGroups != null) + { + foreach (var shader in VoxelMipmapSimpleGroups) + { + shader.Dispose(); + } + } + VoxelMipmapSimpleGroups = new Xenko.Rendering.ComputeEffect.ComputeEffectShader[TempMipMaps.Length]; + for (int i = 0; i < VoxelMipmapSimpleGroups.Length; i++) + { + VoxelMipmapSimpleGroups[i] = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = MipMapShader }; + } + } + curMipMapShader = MipMapShader; + + int offsetIndex = 0; + //Mipmap detailed clipmaps into less detailed ones + Vector3 totalResolution = ClipMapResolution * new Vector3(1,LayoutSize,1); + Int3 threadGroupCounts = new Int3(32, 32, 32); + if (DownsampleFinerClipMaps) + { + for (int i = 0; i < ClipMapCount - 1; i++) + { + Vector3 Offset = MippingOffset[offsetIndex]; + VoxelMipmapSimple.ThreadGroupCounts = threadGroupCounts; + VoxelMipmapSimple.ThreadNumbers = new Int3((int)totalResolution.X / threadGroupCounts.X, (int)totalResolution.Y / threadGroupCounts.Y, (int)totalResolution.Z / threadGroupCounts.Z); + + VoxelMipmapSimple.Parameters.Set(VoxelMipmapSimpleKeys.ReadTex, ClipMaps); + VoxelMipmapSimple.Parameters.Set(VoxelMipmapSimpleKeys.WriteTex, TempMipMaps[0]); + VoxelMipmapSimple.Parameters.Set(VoxelMipmapSimpleKeys.ReadOffset, -(Mod(Offset,new Vector3(2))) + new Vector3(0, (int)totalResolution.Y * i, 0)); + ((RendererBase)VoxelMipmapSimple).Draw(drawContext); + + Offset -= Mod(Offset, new Vector3(2)); + //Copy each axis, ignoring the top and bottom plane + for (int axis = 0; axis < LayoutSize; axis++) + { + int axisOffset = axis * (int)ClipMapResolution.Y; + + Int3 CopySize = new Int3((int)ClipMapResolution.X / 2 - 2, (int)ClipMapResolution.Y / 2 - 2, (int)ClipMapResolution.Z / 2 - 2); + + + Int3 DstMinBound = new Int3((int)ClipMapResolution.X / 4 + (int)Offset.X / 2 + 1, (int)totalResolution.Y * (i + 1) + axisOffset + (int)ClipMapResolution.Y / 4 + 1 + (int)Offset.Y / 2, (int)ClipMapResolution.Z / 4 + (int)Offset.Z / 2 + 1); + Int3 DstMaxBound = DstMinBound + CopySize; + + DstMaxBound = Int3.Min(DstMaxBound, new Int3((int)totalResolution.X, (int)totalResolution.Y * (i + 2), (int)totalResolution.Z)); + DstMinBound = Int3.Min(DstMinBound, new Int3((int)totalResolution.X, (int)totalResolution.Y * (i + 2), (int)totalResolution.Z)); + DstMaxBound = Int3.Max(DstMaxBound, new Int3(0, (int)totalResolution.Y * (i + 1), 0)); + DstMinBound = Int3.Max(DstMinBound, new Int3(0, (int)totalResolution.Y * (i + 1), 0)); + + Int3 SizeBound = DstMaxBound - DstMinBound; + + Int3 SrcMinBound = new Int3(1, axisOffset / 2 + 1, 1); + Int3 SrcMaxBound = SrcMinBound + SizeBound; + + if (SizeBound.X > 0 && SizeBound.Y > 0 && SizeBound.Z > 0) + { + drawContext.CommandList.CopyRegion(TempMipMaps[0], 0, + new ResourceRegion( + SrcMinBound.X, SrcMinBound.Y, SrcMinBound.Z, + SrcMaxBound.X, SrcMaxBound.Y, SrcMaxBound.Z + ), + ClipMaps, 0, + DstMinBound.X, DstMinBound.Y, DstMinBound.Z); + } + } + offsetIndex++; + } + } + Vector3 resolution = ClipMapResolution; + resolution.Y *= LayoutSize; + offsetIndex = ClipMapCount-1; + //Mipmaps for the largest clipmap + for (int i = 0; i < TempMipMaps.Length - 1; i++) + { + Vector3 Offset = MippingOffset[offsetIndex]; + var mipmapShader = VoxelMipmapSimpleGroups[i]; + resolution /= 2; + + Vector3 threadNums = Vector3.Min(resolution, new Vector3(8)); + mipmapShader.ThreadNumbers = ToInt3(threadNums); + mipmapShader.ThreadGroupCounts = ToInt3(resolution / threadNums); + + if (i == 0) + { + mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadTex, ClipMaps); + mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadOffset, -Offset + new Vector3(0, (int)ClipMapResolution.Y * LayoutSize * (ClipMapCount - 1), 0)); + } + else + { + mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadTex, TempMipMaps[i - 1]); + mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadOffset, -Offset + new Vector3(0, 0, 0)); + } + mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.WriteTex, TempMipMaps[i]); + ((RendererBase)mipmapShader).Draw(drawContext); + //Don't seem to be able to read and write to the same texture, even if the views + //point to different mipmaps. + drawContext.CommandList.CopyRegion(TempMipMaps[i], 0, null, MipMaps, i); + offsetIndex++; + } + Array.Copy(PerMapOffsetScale, PerMapOffsetScaleCurrent, PerMapOffsetScale.Length); + } + + + private ObjectParameterKey ClipMapskey; + private ObjectParameterKey MipMapskey; + private ValueParameterKey perMapOffsetScaleKey; + public void UpdateSamplingLayout(string compositionName) + { + ClipMapskey = VoxelStorageTextureClipmapShaderKeys.clipMaps.ComposeWith(compositionName); + MipMapskey = VoxelStorageTextureClipmapShaderKeys.mipMaps.ComposeWith(compositionName); + perMapOffsetScaleKey = VoxelStorageTextureClipmapShaderKeys.perMapOffsetScale.ComposeWith(compositionName); + } + public ShaderClassSource GetSamplingShader() + { + sampler = new ShaderClassSource("VoxelStorageTextureClipmapShader", VoxelSize, ClipMapCount, LayoutSize, ClipMapResolution.Y/2.0f); + return sampler; + } + public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + parameters.Set(ClipMapskey, ClipMaps); + parameters.Set(MipMapskey, MipMaps); + parameters.Set(perMapOffsetScaleKey, viewContext.IsVoxelView? PerMapOffsetScaleCurrent : PerMapOffsetScale); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/IVoxelStorer.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/IVoxelStorer.cs new file mode 100644 index 0000000000..271fbef62a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/IVoxelStorer.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using Xenko.Graphics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelStorer + { + void PostProcess(VoxelStorageContext context, RenderDrawContext drawContext, ProcessedVoxelVolume data); + + ShaderSource GetVoxelizationShader(VoxelizationPass pass, ProcessedVoxelVolume data); + void ApplyVoxelizationParameters(ParameterCollection param); + void UpdateVoxelizationLayout(string compositionName); + + bool RequireGeometryShader(); + int GeometryShaderOutputCount(); + bool CanShareRenderStage(IVoxelStorer storer); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs new file mode 100644 index 0000000000..b8de8a12bf --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs @@ -0,0 +1,162 @@ +using System; +using System.Collections.Generic; +using Xenko.Core.Mathematics; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Graphics; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public class VoxelStorerClipmap : IVoxelStorer + { + public VoxelStorageClipmaps.UpdateMethods UpdatesPerFrame; + + public int storageUints; + public Xenko.Graphics.Buffer FragmentsBuffer = null; + + public int ClipMapCount; + public int ClipMapCurrent = -1; + public Vector3 ClipMapResolution; + + public Vector4[] PerMapOffsetScale = new Vector4[20]; + + public bool UpdatesOneClipPerFrame() + { + return UpdatesPerFrame == VoxelStorageClipmaps.UpdateMethods.SingleClipmap || ClipMapCount <= 1; + } + + + public bool CanShareRenderStage(IVoxelStorer storer) + { + VoxelStorerClipmap storerClipmap = storer as VoxelStorerClipmap; + if (storerClipmap == null) + { + return false; + } + + bool singleClipA = UpdatesOneClipPerFrame(); + bool singleClipB = storerClipmap.UpdatesOneClipPerFrame(); + + return singleClipA == singleClipB; + } + public override bool Equals(object obj) + { + VoxelStorerClipmap storerClipmap = obj as VoxelStorerClipmap; + if (storerClipmap == null) + { + return false; + } + + bool singleClipA = UpdatesOneClipPerFrame(); + bool singleClipB = storerClipmap.UpdatesOneClipPerFrame(); + bool sameClipSet = (storerClipmap.UpdatesPerFrame == VoxelStorageClipmaps.UpdateMethods.SingleClipmap && storerClipmap.ClipMapCurrent == ClipMapCurrent); + + return singleClipA == singleClipB && (!singleClipA || sameClipSet); + } + public override int GetHashCode() + { + return 0; + } + + + ObjectParameterKey fragmentsBufferKey; + ValueParameterKey clipMapResolutionKey; + ValueParameterKey storageUintsKey; + + ValueParameterKey clipMapCountKey; + + ValueParameterKey clipScaleKey; + ValueParameterKey clipPosKey; + ValueParameterKey clipOffsetKey; + ValueParameterKey perClipMapOffsetScaleKey; + public void UpdateVoxelizationLayout(string compositionName) + { + fragmentsBufferKey = VoxelStorageClipmapShaderKeys.fragmentsBuffer.ComposeWith(compositionName); + clipMapResolutionKey = VoxelStorageClipmapShaderKeys.clipMapResolution.ComposeWith(compositionName); + storageUintsKey = VoxelStorageClipmapShaderKeys.storageUints.ComposeWith(compositionName); + + if (UpdatesOneClipPerFrame()) + { + clipScaleKey = VoxelStorageClipmapShaderKeys.clipScale.ComposeWith(compositionName); + clipOffsetKey = VoxelStorageClipmapShaderKeys.clipOffset.ComposeWith(compositionName); + clipPosKey = VoxelStorageClipmapShaderKeys.clipPos.ComposeWith(compositionName); + } + else + { + clipMapCountKey = VoxelStorageClipmapShaderKeys.clipMapCount.ComposeWith(compositionName); + perClipMapOffsetScaleKey = VoxelStorageClipmapShaderKeys.perClipMapOffsetScale.ComposeWith(compositionName); + } + } + public void ApplyVoxelizationParameters(ParameterCollection param) + { + param.Set(fragmentsBufferKey, FragmentsBuffer); + param.Set(clipMapResolutionKey, ClipMapResolution); + param.Set(storageUintsKey, storageUints); + + if (UpdatesOneClipPerFrame()) + { + param.Set(clipScaleKey, new Vector3(PerMapOffsetScale[ClipMapCurrent].W)); + param.Set(clipOffsetKey, PerMapOffsetScale[ClipMapCurrent].XYZ()); + param.Set(clipPosKey, ClipMapCurrent * ClipMapResolution.X * ClipMapResolution.Y * ClipMapResolution.Z); + } + else + { + param.Set(clipMapCountKey, ClipMapCount); + param.Set(perClipMapOffsetScaleKey, PerMapOffsetScale); + } + } + + ShaderClassSource storage = new ShaderClassSource("VoxelStorageClipmapShader"); + + public ShaderSource GetVoxelizationShader(VoxelizationPass pass, ProcessedVoxelVolume data) + { + bool singleClip = UpdatesOneClipPerFrame(); + ShaderSource VoxelizationMethodSource = pass.method.GetVoxelizationShader(); + ShaderMixinSource cachedMixin = new ShaderMixinSource(); + cachedMixin.Mixins.Add(storage); + cachedMixin.AddComposition("method", VoxelizationMethodSource); + if (singleClip) + { + cachedMixin.AddMacro("singleClip", true); + } + + string IndirectStoreMacro = ""; + for (int i = 0; i < pass.AttributesIndirect.Count; i++) + { + string iStr = i.ToString(); + IndirectStoreMacro += "AttributesIndirect[" + iStr + "].IndirectWrite(fragmentsBuffer, writeindex + " + pass.AttributesIndirect[i].GetBufferOffset().ToString() + ");\n"; + } + + cachedMixin.AddMacro("IndirectStoreMacro", IndirectStoreMacro); + + foreach (var attr in pass.AttributesTemp) + { + cachedMixin.AddCompositionToArray("AttributesTemp", attr.GetVoxelizationShader()); + } + foreach (var attr in pass.AttributesDirect) + { + cachedMixin.AddCompositionToArray("AttributesDirect", attr.GetVoxelizationShader()); + } + foreach (var attr in pass.AttributesIndirect) + { + cachedMixin.AddCompositionToArray("AttributesIndirect", attr.GetVoxelizationShader()); + } + + return cachedMixin; + } + + public bool RequireGeometryShader() + { + return UpdatesPerFrame == VoxelStorageClipmaps.UpdateMethods.AllClipmapsGeometryShader && !UpdatesOneClipPerFrame(); + } + public int GeometryShaderOutputCount() + { + return UpdatesPerFrame == VoxelStorageClipmaps.UpdateMethods.SingleClipmap ? 1 : ClipMapCount; + } + + public void PostProcess(VoxelStorageContext context, RenderDrawContext drawContext, ProcessedVoxelVolume data) + { + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs new file mode 100644 index 0000000000..eebc9b992f --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Engine.Design; +using Xenko.Engine.Processors; +using Xenko.Rendering.Voxels.Debug; + +namespace Xenko.Rendering.Voxels +{ + /// + /// Voxelizes a region. + /// + [DataContract("VoxelVolumeComponent")] + [DefaultEntityComponentRenderer(typeof(VoxelVolumeProcessor))] + [Display("Voxel Volume")] + [ComponentCategory("Lights")] + public class VoxelVolumeComponent : ActivableEntityComponent + { + private bool enabled = true; + + public override bool Enabled + { + get { return enabled; } + set { enabled = value; Changed?.Invoke(this, null); } + } + + [DataMember(1)] + public bool Voxelize = true; + + [DataMember(5)] + [NotNull] + public IVoxelizationMethod VoxelizationMethod { get; set; } = new VoxelizationMethodDominantAxis(); + + [DataMember(10)] + [NotNull] + public IVoxelStorage Storage { get; set; } = new VoxelStorageClipmaps(); + + [DataMember(20)] + [Category] + public List Attributes { get; set; } = new List(); + + + [DataMember(30)] + public float AproximateVoxelSize { get; set; } = 0.15f; + [DataMember(34)] + public bool VoxelGridSnapping { get; set; } = true; + + [DataMember(40)] + [Category] + public bool VoxelVisualization { get; set; } = false;//Unused, toggle doesn't show if category + [DataMember(50)] + public bool VisualizeVoxels { get; set; } = false; + [DataMember(55)] + public int VisualizeIndex { get; set; } = 0; + [DataMember(60)] + public IVoxelVisualization Visualization { get; set; } = null; + + public event EventHandler Changed; + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs new file mode 100644 index 0000000000..d2272cfd8f --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Engine; +using Xenko.Games; +using Xenko.Extensions; +using Xenko.Core.Mathematics; +using Xenko.Graphics; +using Xenko.Graphics.GeometricPrimitives; +using Xenko.Rendering; +using Xenko.Rendering.Voxels; +using Xenko.Rendering.Shadows; +using Xenko.Rendering.Materials; +using Xenko.Rendering.Materials.ComputeColors; + +namespace Xenko.Engine.Processors +{ + public class VoxelVolumeProcessor : EntityProcessor, IEntityComponentRenderProcessor + { + private Dictionary renderVoxelVolumes = new Dictionary(); + public Dictionary processedVoxelVolumes = new Dictionary(); + bool isDirty; + SceneSystem sceneSystem; + GraphicsDevice graphicsDevice; + CommandList commandList; + + public VisibilityGroup VisibilityGroup { get; set; } + public RenderGroup RenderGroup { get; set; } + protected override void OnSystemAdd() + { + base.OnSystemAdd(); + + VisibilityGroup.Tags.Set(VoxelRenderer.CurrentRenderVoxelVolumes, renderVoxelVolumes); + VisibilityGroup.Tags.Set(VoxelRenderer.CurrentProcessedVoxelVolumes, processedVoxelVolumes); + VisibilityGroup.Tags.Set(VoxelRenderFeature.CurrentProcessedVoxelVolumes, processedVoxelVolumes); + sceneSystem = Services.GetService(); + graphicsDevice = Services.GetService().GraphicsDevice; + commandList = Services.GetService(); + } + public override void Update(GameTime time) + { + RegenerateVoxelVolumes(); + } + public override void Draw(RenderContext context) + { + + } + + public ProcessedVoxelVolume GetProcessedVolumeForComponent(VoxelVolumeComponent component) + { + if (!processedVoxelVolumes.TryGetValue(component, out var data)) + return null; + return data; + } + public DataVoxelVolume GetRenderVolumeForComponent(VoxelVolumeComponent component) + { + if (!renderVoxelVolumes.TryGetValue(component, out var data)) + return null; + return data; + } + + protected override void OnEntityComponentAdding(Entity entity, VoxelVolumeComponent component, VoxelVolumeComponent data) + { + component.Changed += ComponentChanged; + } + protected override void OnEntityComponentRemoved(Entity entity, VoxelVolumeComponent component, VoxelVolumeComponent data) + { + component.Changed -= ComponentChanged; + } + private void ComponentChanged(object sender, EventArgs eventArgs) + { + isDirty = true; + } + private void RegenerateVoxelVolumes() + { + //if (!isDirty) + // return; + renderVoxelVolumes.Clear(); + processedVoxelVolumes.Clear(); + foreach (var pair in ComponentDatas) + { + if (!pair.Key.Enabled) + continue; + + var volume = pair.Key; + + DataVoxelVolume data; + renderVoxelVolumes.Add(volume, data = new DataVoxelVolume()); + processedVoxelVolumes.Add(volume, new ProcessedVoxelVolume()); + + data.VolumeTranslation = volume.Entity.Transform.LocalMatrix.TranslationVector; + //data.VolumeSize = volume.Entity.Transform.Scale; + //TODO: Get non cube volumes working again + //Temporarily force to cube + float largestSide = Math.Max(volume.Entity.Transform.Scale.X, Math.Max(volume.Entity.Transform.Scale.Y, volume.Entity.Transform.Scale.Z)); + data.VolumeSize = new Vector3(largestSide); + + + data.Voxelize = volume.Voxelize; + data.AproxVoxelSize = volume.AproximateVoxelSize; + + data.VoxelGridSnapping = volume.VoxelGridSnapping; + data.VisualizeVoxels = volume.VisualizeVoxels; + data.VoxelVisualization = volume.Visualization; + data.Attributes = volume.Attributes; + data.Storage = volume.Storage; + data.VoxelizationMethod = volume.VoxelizationMethod; + + if (volume.Attributes.Count > volume.VisualizeIndex) + { + data.VisualizationAttribute = volume.Attributes[volume.VisualizeIndex]; + } + else + { + data.VisualizationAttribute = null; + } + } + + + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs new file mode 100644 index 0000000000..e160d2abf5 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Xenko.Core; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Shaders; +using Xenko.Graphics; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Voxels; +using Xenko.Core.Extensions; +using Xenko.Rendering; + +namespace Xenko.Rendering.Voxels +{ + public interface IVoxelizationMethod + { + void Reset(); + void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows); + void Render(VoxelStorageContext storageContext, RenderDrawContext drawContext, RenderView view); + + bool RequireGeometryShader(); + int GeometryShaderOutputCount(); + + ShaderSource GetVoxelizationShader(); + bool CanShareRenderStage(IVoxelizationMethod method); + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.xksl new file mode 100644 index 0000000000..ea59cedea4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.xksl @@ -0,0 +1,17 @@ +shader VoxelizationMethod : VoxelPositionStream, PositionStream4, ShaderBaseStream +{ + void PrepareFragment(){ } + void PrepareVertex(){ } + + void InitializeFromTriangle(triangle Input input[3]) { } + + void Append(inout TriangleStream triangleStream) + { + streams.ShadingPosition.z = streams.ShadingPosition.z * 0.5 + 0.5; + triangleStream.Append(streams); + } + void RestartStrip(inout TriangleStream triangleStream) + { + triangleStream.RestartStrip(); + } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl new file mode 100644 index 0000000000..0b1942bd15 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl @@ -0,0 +1,48 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +namespace Xenko.Rendering.Voxels +{ + /// + /// Voxelization, projects to axis of largest area and writes fragments to buffer + /// + shader VoxelizationMethodDominantAxis : VoxelizationMethod, Math, Transformation, ShaderBase, NormalStream, PositionStream4, VoxelPositionStream + { + centroid stream float3 centroidPositionWS; + centroid stream float3 centroidNormalWS; + override void PrepareFragment() + { + streams.PositionWS = float4(streams.centroidPositionWS,1); + streams.normalWS = streams.centroidNormalWS; + } + override void PrepareVertex() + { + streams.centroidPositionWS = streams.PositionWS.xyz; + streams.centroidNormalWS = streams.normalWS.xyz; + } + stream int dominantAxis; + override void InitializeFromTriangle(triangle Input input[3]) + { + float3 nor = abs(cross((input[1].ShadingPosition.xyz - input[0].ShadingPosition.xyz), (input[2].ShadingPosition.xyz - input[0].ShadingPosition.xyz))); + streams.dominantAxis = nor.x > nor.y ? 0 : 1; + streams.dominantAxis = nor.z > nor.y && nor.z > nor.x ? 2 : streams.dominantAxis; + } + void TransformPoint(inout float4 v1) + { + if (streams.dominantAxis == 0) + { + v1.xyz = float3(v1.yzx); + } + else if (streams.dominantAxis == 1) + { + v1.xyz = float3(v1.xzy); + } + v1.w = 1; + } + override void Append(inout TriangleStream triangleStream) + { + TransformPoint(streams.ShadingPosition); + streams.ShadingPosition.z = streams.ShadingPosition.z * 0.5 + 0.5; + triangleStream.Append(streams); + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.xksl new file mode 100644 index 0000000000..7b805a49be --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.xksl @@ -0,0 +1,20 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +namespace Xenko.Rendering.Voxels +{ + /// + /// Voxelization, projects to axis of largest area and writes fragments to buffer + /// + shader VoxelizationMethodSingleAxis : VoxelizationMethod, Math, Transformation, ShaderBase, NormalStream, PositionStream4, VoxelPositionStream + { + centroid stream float3 centroidPositionWS; + override void PrepareFragment() + { + streams.PositionWS = float4(streams.centroidPositionWS,1); + } + override void PrepareVertex() + { + streams.centroidPositionWS = streams.PositionWS.xyz; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs new file mode 100644 index 0000000000..e3f577e0b1 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs @@ -0,0 +1,144 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Xenko.Core; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Shaders; +using Xenko.Graphics; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Voxels; +using Xenko.Core.Extensions; +using Xenko.Rendering; + + +namespace Xenko.Rendering.Voxels +{ + //Uses a geometry shader to project each triangle to the axis + //of maximum coverage, and lets the pipeline generate fragments from there + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Dominant Axis (Geometry Shader)")] + public class VoxelizationMethodDominantAxis : IVoxelizationMethod + { + [DataMemberIgnore] + List VoxelizationViews { get; } = new List(); + [DataMemberIgnore] + Dictionary VoxelizationViewSizes { get; } = new Dictionary(); + int currentViewIndex = 0; + + public MultisampleCount MultisampleCount = MultisampleCount.X8; + + public override bool Equals(object obj) + { + VoxelizationMethodDominantAxis method = obj as VoxelizationMethodDominantAxis; + if (method == null) + { + return false; + } + if (method.MultisampleCount != MultisampleCount) + { + return false; + } + return true; + } + + public bool CanShareRenderStage(IVoxelizationMethod obj) + { + VoxelizationMethodDominantAxis method = obj as VoxelizationMethodDominantAxis; + if (method == null) + { + return false; + } + return true; + } + public override int GetHashCode() + { + return 0; + } + + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + { + while (VoxelizationViews.Count <= currentViewIndex) + { + VoxelizationViews.Add(new RenderView()); + VoxelizationViewSizes[VoxelizationViews[VoxelizationViews.Count-1]] = new Int2(); + } + RenderView voxelizationView = VoxelizationViews[currentViewIndex]; + + voxelizationView.View = Matrix.Identity; + voxelizationView.Projection = view; + voxelizationView.ViewProjection = view; + + float maxRes = Math.Max(resolution.X, Math.Max(resolution.Y, resolution.Z)); + Matrix aspectScale = Matrix.Scaling(resolution / maxRes); + voxelizationView.Projection *= aspectScale; + voxelizationView.ViewProjection = voxelizationView.View * voxelizationView.Projection; + + voxelizationView.ViewSize = new Vector2(maxRes * 8, maxRes * 8); + VoxelizationViewSizes[voxelizationView] = new Int2((int)maxRes, (int)maxRes); + + + //The BoundingFrustum constructor doesn't end up calculating the correct Near Plane for the symmetric matrix, squish it so the Z is from 0 to 1 + Matrix SquishedMatrix = voxelizationView.ViewProjection * Matrix.Scaling(1f, 1f, 0.5f) * Matrix.Translation(new Vector3(0, 0, 0.5f)); + voxelizationView.Frustum = new BoundingFrustum(ref SquishedMatrix); + + voxelizationView.CullingMode = CameraCullingMode.None; + voxelizationView.NearClipPlane = 0.1f; + voxelizationView.FarClipPlane = 1000.0f; + + currentViewIndex++; + + passList.AddDirect(storer, this, voxelizationView, attr, stage, output, shadows); + } + + Xenko.Graphics.Texture MSAARenderTarget = null; + + public void Render(VoxelStorageContext storageContext, RenderDrawContext drawContext, RenderView view) + { + RenderView voxelizationView = view; + Int2 ViewSize = VoxelizationViewSizes[view]; + + if (VoxelUtils.DisposeTextureBySpecs(MSAARenderTarget, new Vector3(ViewSize.X, ViewSize.Y, 1), PixelFormat.R8G8B8A8_UNorm, MultisampleCount)) + { + MSAARenderTarget = Texture.New(storageContext.device, TextureDescription.New2D(ViewSize.X, ViewSize.Y, new MipMapCount(false), PixelFormat.R8G8B8A8_UNorm, TextureFlags.RenderTarget, 1, GraphicsResourceUsage.Default, MultisampleCount), null); + } + + drawContext.CommandList.ResetTargets(); + if (MSAARenderTarget != null) + drawContext.CommandList.SetRenderTarget(null, MSAARenderTarget); + + var renderSystem = drawContext.RenderContext.RenderSystem; + + drawContext.CommandList.SetViewport(new Viewport(0, 0, ViewSize.X, ViewSize.Y)); + + renderSystem.Draw(drawContext, voxelizationView, renderSystem.RenderStages[voxelizationView.RenderStages[0].Index]); + } + public void Reset() + { + currentViewIndex = 0; + } + + ShaderClassSource method = new ShaderClassSource("VoxelizationMethodDominantAxis"); + ShaderMixinSource methodmixin = null; + public ShaderSource GetVoxelizationShader() + { + if (methodmixin == null) + { + methodmixin = new ShaderMixinSource(); + methodmixin.Mixins.Add(method); + } + return methodmixin; + } + public bool RequireGeometryShader() + { + return true; + } + public int GeometryShaderOutputCount() + { + return 3; + } + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs new file mode 100644 index 0000000000..596b3dc237 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs @@ -0,0 +1,151 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Xenko.Core; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Shaders; +using Xenko.Graphics; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Voxels; +using Xenko.Core.Extensions; +using Xenko.Rendering; + + +namespace Xenko.Rendering.Voxels +{ + //Uses a geometry shader to project each triangle to the axis + //of maximum coverage, and lets the pipeline generate fragments from there + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Single Axis")] + public class VoxelizationMethodSingleAxis : IVoxelizationMethod + { + [DataMemberIgnore] + List VoxelizationViews { get; } = new List(); + [DataMemberIgnore] + Dictionary VoxelizationViewSizes { get; } = new Dictionary(); + int currentViewIndex = 0; + + public enum Axis {X, Y, Z}; + public Axis VoxelizationAxis = Axis.Y; + + public MultisampleCount MultisampleCount = MultisampleCount.X8; + + public override bool Equals(object obj) + { + VoxelizationMethodSingleAxis method = obj as VoxelizationMethodSingleAxis; + if (method == null) + { + return false; + } + if (method.MultisampleCount != MultisampleCount) + { + return false; + } + return true; + } + public bool CanShareRenderStage(IVoxelizationMethod obj) + { + return Equals(obj); + } + public override int GetHashCode() + { + return 0; + } + + + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + { + var actualView = Matrix.Identity; + if (VoxelizationAxis == Axis.Y) + { + actualView.ExchangeRows(1, 2); + } + if (VoxelizationAxis == Axis.X) + { + actualView.ExchangeRows(0, 2); + } + + while (VoxelizationViews.Count <= currentViewIndex) + { + VoxelizationViews.Add(new RenderView()); + VoxelizationViewSizes[VoxelizationViews[VoxelizationViews.Count-1]] = new Int2(); + } + RenderView voxelizationView = VoxelizationViews[currentViewIndex]; + + float maxRes = Math.Max(resolution.X, Math.Max(resolution.Y, resolution.Z)); + Matrix aspectScale = Matrix.Scaling(new Vector3(resolution.X, resolution.Z, resolution.Y) / maxRes); + + VoxelizationViewSizes[voxelizationView] = new Int2((int)maxRes, (int)maxRes); + + voxelizationView.View = actualView; + voxelizationView.Projection = view * aspectScale; + voxelizationView.ViewProjection = voxelizationView.View * voxelizationView.Projection; + voxelizationView.ViewSize = new Vector2(maxRes * 8, maxRes * 8); + + + //The BoundingFrustum constructor doesn't end up calculating the correct Near Plane for the symmetric matrix, squish it so the Z is from 0 to 1 + Matrix SquishedMatrix = voxelizationView.ViewProjection * Matrix.Scaling(1f, 1f, 0.5f) * Matrix.Translation(new Vector3(0, 0, 0.5f)); + voxelizationView.Frustum = new BoundingFrustum(ref SquishedMatrix); + + voxelizationView.CullingMode = CameraCullingMode.None; + voxelizationView.NearClipPlane = 0.1f; + voxelizationView.FarClipPlane = 1000.0f; + + currentViewIndex++; + + passList.AddDirect(storer, this, voxelizationView, attr, stage, output, shadows); + } + + Xenko.Graphics.Texture MSAARenderTarget = null; + + public void Render(VoxelStorageContext storageContext, RenderDrawContext drawContext, RenderView view) + { + RenderView voxelizationView = view; + Int2 ViewSize = VoxelizationViewSizes[view]; + + if (VoxelUtils.DisposeTextureBySpecs(MSAARenderTarget, new Vector3(ViewSize.X, ViewSize.Y, 1), PixelFormat.R8G8B8A8_UNorm, MultisampleCount)) + { + MSAARenderTarget = Texture.New(storageContext.device, TextureDescription.New2D(ViewSize.X, ViewSize.Y, new MipMapCount(false), PixelFormat.R8G8B8A8_UNorm, TextureFlags.RenderTarget, 1, GraphicsResourceUsage.Default, MultisampleCount), null); + } + + drawContext.CommandList.ResetTargets(); + if (MSAARenderTarget != null) + drawContext.CommandList.SetRenderTarget(null, MSAARenderTarget); + + var renderSystem = drawContext.RenderContext.RenderSystem; + + drawContext.CommandList.SetViewport(new Viewport(0, 0, ViewSize.X, ViewSize.Y)); + + renderSystem.Draw(drawContext, voxelizationView, renderSystem.RenderStages[voxelizationView.RenderStages[0].Index]); + drawContext.CommandList.ResetTargets(); + } + public void Reset() + { + currentViewIndex = 0; + } + + ShaderClassSource method = new ShaderClassSource("VoxelizationMethodSingleAxis"); + ShaderMixinSource methodmixin = null; + public ShaderSource GetVoxelizationShader() + { + if (methodmixin == null) + { + methodmixin = new ShaderMixinSource(); + methodmixin.Mixins.Add(method); + } + return methodmixin; + } + public bool RequireGeometryShader() + { + return false; + } + public int GeometryShaderOutputCount() + { + return 3; + } + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs new file mode 100644 index 0000000000..9c396faf81 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Text; + +using Xenko.Core; +using Xenko.Core.Collections; +using Xenko.Core.Diagnostics; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Shaders; +using Xenko.Graphics; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Voxels; +using Xenko.Core.Extensions; +using Xenko.Rendering; + +namespace Xenko.Rendering.Voxels +{ + //Renders the scene 3 times from different axis to generate all the fragments, no geometry shader needed. Shadows don't work currently. + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Tri Axis")] + public class VoxelizationMethodTriAxis : IVoxelizationMethod + { + VoxelizationMethodSingleAxis axisX = new VoxelizationMethodSingleAxis + { + VoxelizationAxis = VoxelizationMethodSingleAxis.Axis.X + }; + VoxelizationMethodSingleAxis axisY = new VoxelizationMethodSingleAxis + { + VoxelizationAxis = VoxelizationMethodSingleAxis.Axis.Y + }; + VoxelizationMethodSingleAxis axisZ = new VoxelizationMethodSingleAxis + { + VoxelizationAxis = VoxelizationMethodSingleAxis.Axis.Z + }; + + public MultisampleCount MultisampleCount = MultisampleCount.X8; + + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + { + axisX.MultisampleCount = MultisampleCount; + axisY.MultisampleCount = MultisampleCount; + axisZ.MultisampleCount = MultisampleCount; + + axisX.CollectVoxelizationPasses(passList, storer, view, resolution, attr, stage, output, shadows); + axisY.CollectVoxelizationPasses(passList, storer, view, resolution, attr, stage, output, shadows); + axisZ.CollectVoxelizationPasses(passList, storer, view, resolution, attr, stage, output, shadows); + } + public void Render(VoxelStorageContext storageContext, RenderDrawContext drawContext, RenderView view) + { + } + public void Reset() + { + } + public ShaderSource GetVoxelizationShader() + { + return null; + } + public bool RequireGeometryShader() + { + return false; + } + public int GeometryShaderOutputCount() + { + return 3; + } + public bool CanShareRenderStage(IVoxelizationMethod obj) + { + VoxelizationMethodSingleAxis method = obj as VoxelizationMethodSingleAxis; + if (method == null) + { + return false; + } + if (method.MultisampleCount != MultisampleCount) + { + return false; + } + return true; + } + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs new file mode 100644 index 0000000000..74262994cc --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core.Mathematics; +using Xenko.Rendering; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public class VoxelizationPass + { + public RenderView view; + public IVoxelStorer storer; + public IVoxelizationMethod method; + //Stage1 + public List AttributesTemp = new List(); + public List AttributesDirect = new List(); + public List AttributesIndirect = new List(); + + public ShaderSource source; + + public bool requireShadows = false; + public RenderStage renderStage = null; + + + public void Add(IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + { + if (stage == VoxelizationStage.Initial) + { + if (output) + { + AttributesDirect.Add(attr); + } + else + { + AttributesTemp.Add(attr); + } + } + else if (stage == VoxelizationStage.Post) + { + AttributesIndirect.Add(attr); + } + + requireShadows |= shadows; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs new file mode 100644 index 0000000000..8a62135245 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core.Mathematics; + +namespace Xenko.Rendering.Voxels +{ + public class VoxelizationPassList + { + public List passes = new List(); + public IVoxelizationMethod defaultVoxelizationMethod; + public void AddDirect(IVoxelStorer storer, IVoxelizationMethod method, RenderView view, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + { + bool toAdd = true; + foreach (VoxelizationPass pass in passes) + { + if (pass.storer.Equals(storer) && pass.method.Equals(method) && pass.view.ViewProjection == view.ViewProjection) + { + pass.Add(attr, stage, output, shadows); + toAdd = false; + break; + } + } + if (toAdd) + { + VoxelizationPass pass = new VoxelizationPass + { + storer = storer, + method = method, + view = view + }; + pass.Add(attr, stage, output, shadows); + passes.Add(pass); + } + } + public void Clear() + { + passes.Clear(); + defaultVoxelizationMethod = null; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.xksl new file mode 100644 index 0000000000..3aa7cc4857 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.xksl @@ -0,0 +1,35 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +namespace Xenko.Rendering.Voxels +{ + /// + /// Voxelization, projects to axis of largest area and writes fragments to buffer + /// + shader VoxelizeToFragments : Math, Transformation, ShaderBase, Texturing, NormalStream, PositionStream4, VoxelPositionStream, MaterialPixelStream, MaterialPixelShadingStream + { + compose VoxelStorageShader Storage; + override stage void PSMain() + { + Storage.PrepareFragments(); + streams.IsFrontFace = true; + if (Storage.MightStoreFragments()) + { + base.PSMain(); + Storage.StoreFragments(); + streams.ColorTarget = float4(0,0,0,0); + } + } + override stage void VSMain() + { + base.VSMain(); + Storage.PrepareVertex(); + } + #ifdef RequireGeometryShader + [maxvertexcount(GeometryShaderMaxVertexCount)] + void GSMain(triangle Input input[3], inout TriangleStream triangleStream) + { + Storage.GenerateTriangles(input, triangleStream); + } + #endif + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.cs new file mode 100644 index 0000000000..55774d5373 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.cs @@ -0,0 +1,54 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +using Xenko.Rendering.Materials; +using Xenko.Rendering.Voxels; +namespace Xenko.Rendering.Voxels +{ + internal static partial class ShaderMixins + { + internal partial class VoxelizeToFragmentsEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "VoxelizeToFragments"); + if (context.GetParam(VoxelizeToFragmentsKeys.Storage) != null) + { + + { + var __mixinToCompose__ = (context.GetParam(VoxelizeToFragmentsKeys.Storage)); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "Storage", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + if (context.GetParam(VoxelizeToFragmentsKeys.RequireGeometryShader) == true) + { + mixin.AddMacro("RequireGeometryShader", true); + mixin.AddMacro("GeometryShaderMaxVertexCount", context.GetParam(VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount)); + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("VoxelizeToFragmentsEffect", new VoxelizeToFragmentsEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.xksl new file mode 100644 index 0000000000..b0e12cd37d --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.xksl @@ -0,0 +1,24 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Rendering.Materials; +using Xenko.Rendering.Voxels; + +namespace Xenko.Rendering.Voxels +{ + partial effect VoxelizeToFragmentsEffect + { + using params MaterialKeys; + using params VoxelizeToFragmentsKeys; + + mixin VoxelizeToFragments; + if (VoxelizeToFragmentsKeys.Storage!=null) + { + mixin compose Storage = (VoxelizeToFragmentsKeys.Storage); + } + if (VoxelizeToFragmentsKeys.RequireGeometryShader == true) + { + mixin macro RequireGeometryShader = true; + mixin macro VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsKeys.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsKeys.cs new file mode 100644 index 0000000000..c152c60597 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsKeys.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using Xenko.Rendering.Voxels; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + public static partial class VoxelizeToFragmentsKeys + { + public static readonly PermutationParameterKey Storage = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey RequireGeometryShader = ParameterKeys.NewPermutation(); + public static readonly PermutationParameterKey GeometryShaderMaxVertexCount = ParameterKeys.NewPermutation(); + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj b/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj new file mode 100644 index 0000000000..92f52efdd8 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj @@ -0,0 +1,715 @@ + + + true + true + true + + + + + true + true + * + true + + + + Properties\SharedAssemblyInfo.cs + + + + + + + + + + + + + + True + True + True + VoxelVisualizationRawEffect.xksl + + + True + True + True + VoxelVisualizationRawShader.xksl + + + True + True + True + VoxelVisualizationViewEffect.xksl + + + True + True + True + VoxelVisualizationViewShader.xksl + + + True + True + True + LightVoxelEffect.xksl + + + True + True + True + LightVoxelShader.xksl + + + True + True + True + VoxelMarchSet.xksl + + + True + True + True + VoxelMarchSetHemisphere12.xksl + + + True + True + True + VoxelMarchSetHemisphere6.xksl + + + True + True + True + MarchAttributes.xksl + + + True + True + True + MarchAttributesEffect.xksl + + + True + True + True + VoxelMarchBeam.xksl + + + True + True + True + VoxelMarchCone.xksl + + + True + True + True + VoxelMarchConeFast.xksl + + + True + True + True + VoxelMarchConePerMipmap.xksl + + + True + True + True + VoxelMarchMethod.xksl + + + True + True + True + VoxelRadiusMarchMethod.xksl + + + True + True + True + VoxelAttribute.xksl + + + True + True + True + VoxelAttributeDirectionalCoverageSampler.xksl + + + True + True + True + VoxelAttributeDirectionalCoverageShader.xksl + + + True + True + True + VoxelAttributeEmissionOpacityShader.xksl + + + True + True + True + VoxelAttributeSoliditySampler.xksl + + + True + True + True + VoxelAttributeSolidityShader.xksl + + + True + True + True + VoxelBufferWriteAssign.xksl + + + True + True + True + VoxelBufferWriteMax.xksl + + + True + True + True + VoxelBufferWriter.xksl + + + True + True + True + DataPacking.xksl + + + True + True + True + VoxelFragmentPacker.xksl + + + True + True + True + VoxelFragmentPackFloat16.xksl + + + True + True + True + VoxelFragmentPackFloat32.xksl + + + True + True + True + VoxelFragmentPackFloatR11G11B10.xksl + + + True + True + True + VoxelAnisotropicPairedSampler.xksl + + + True + True + True + VoxelAnisotropicPairedWriter_Float4.xksl + + + True + True + True + VoxelAnisotropicSampler.xksl + + + True + True + True + VoxelAnisotropicWriter_Float4.xksl + + + True + True + True + VoxelIsotropicSampler.xksl + + + True + True + True + VoxelIsotropicWriter_Float4.xksl + + + True + True + True + VoxelLayout_Float4.xksl + + + True + True + True + VoxelModifierApplierOpacifyAnisotropicPaired.xksl + + + True + True + True + VoxelModifierApplierSolidifyAnisotropicPaired.xksl + + + True + True + True + VoxelModifierApplierAnisotropic.xksl + + + True + True + True + VoxelModifierApplierAntiAliasingAnisotropic.xksl + + + True + True + True + VoxelModifierApplierOpacifyAnisotropic.xksl + + + True + True + True + VoxelModifierApplierSolidifyAnisotropic.xksl + + + True + True + True + VoxelModifierApplierAntiAliasingIsotropic.xksl + + + True + True + True + VoxelModifierApplierIsotropic.xksl + + + True + True + True + VoxelModifierApplierOpacifyIsotropic.xksl + + + True + True + True + VoxelModifierApplierSolidifyIsotropic.xksl + + + True + True + True + VoxelModifier.xksl + + + True + True + True + VoxelizationMethod.xksl + + + True + True + True + VoxelizationMethodDominantAxis.xksl + + + True + True + True + VoxelizationMethodSingleAxis.xksl + + + True + True + True + VoxelizeToFragments.xksl + + + True + True + True + VoxelizeToFragmentsEffect.xksl + + + True + True + True + VoxelPositionStream.xksl + + + True + True + True + LocalSamples.xksl + + + True + True + True + VoxelMipmapHeuristic.xksl + + + True + True + True + VoxelMipmapPhysicallyBased.xksl + + + True + True + True + VoxelMipmapSimple.xksl + + + True + True + True + BufferToTexture.xksl + + + True + True + True + BufferToTextureColumns.xksl + + + True + True + True + BufferToTextureColumnsEffect.xksl + + + True + True + True + BufferToTextureEffect.xksl + + + True + True + True + ClearBuffer.xksl + + + True + True + True + VoxelStorageClipmapShader.xksl + + + True + True + True + VoxelStorageShader.xksl + + + True + True + True + VoxelStorageTextureClipmapShader.xksl + + + True + True + True + VoxelStorageTextureShader.xksl + + + + + XenkoShaderKeyGenerator + VoxelVisualizationRawEffect.cs + + + XenkoShaderKeyGenerator + VoxelVisualizationRawShader.cs + + + XenkoShaderKeyGenerator + VoxelVisualizationViewEffect.cs + + + XenkoShaderKeyGenerator + VoxelVisualizationViewShader.cs + + + XenkoShaderKeyGenerator + LightVoxelEffect.cs + + + XenkoShaderKeyGenerator + LightVoxelShader.cs + + + XenkoShaderKeyGenerator + VoxelMarchSet.cs + + + XenkoShaderKeyGenerator + VoxelMarchSetHemisphere12.cs + + + XenkoShaderKeyGenerator + VoxelMarchSetHemisphere6.cs + + + XenkoShaderKeyGenerator + MarchAttributes.cs + + + XenkoShaderKeyGenerator + MarchAttributesEffect.cs + + + XenkoShaderKeyGenerator + VoxelMarchBeam.cs + + + XenkoShaderKeyGenerator + VoxelMarchCone.cs + + + XenkoShaderKeyGenerator + VoxelMarchConeFast.cs + + + XenkoShaderKeyGenerator + VoxelMarchConePerMipmap.cs + + + XenkoShaderKeyGenerator + VoxelMarchMethod.cs + + + XenkoShaderKeyGenerator + VoxelRadiusMarchMethod.cs + + + XenkoShaderKeyGenerator + VoxelAttribute.cs + + + XenkoShaderKeyGenerator + VoxelAttributeDirectionalCoverageSampler.cs + + + XenkoShaderKeyGenerator + VoxelAttributeDirectionalCoverageShader.cs + + + XenkoShaderKeyGenerator + VoxelAttributeEmissionOpacityShader.cs + + + XenkoShaderKeyGenerator + VoxelAttributeSoliditySampler.cs + + + XenkoShaderKeyGenerator + VoxelAttributeSolidityShader.cs + + + XenkoShaderKeyGenerator + VoxelBufferWriteAssign.cs + + + XenkoShaderKeyGenerator + VoxelBufferWriteMax.cs + + + XenkoShaderKeyGenerator + VoxelBufferWriter.cs + + + XenkoShaderKeyGenerator + DataPacking.cs + + + XenkoShaderKeyGenerator + VoxelFragmentPacker.cs + + + XenkoShaderKeyGenerator + VoxelFragmentPackFloat16.cs + + + XenkoShaderKeyGenerator + VoxelFragmentPackFloat32.cs + + + XenkoShaderKeyGenerator + VoxelFragmentPackFloatR11G11B10.cs + + + XenkoShaderKeyGenerator + VoxelAnisotropicPairedSampler.cs + + + XenkoShaderKeyGenerator + VoxelAnisotropicPairedWriter_Float4.cs + + + XenkoShaderKeyGenerator + VoxelAnisotropicSampler.cs + + + XenkoShaderKeyGenerator + VoxelAnisotropicWriter_Float4.cs + + + XenkoShaderKeyGenerator + VoxelIsotropicSampler.cs + + + XenkoShaderKeyGenerator + VoxelIsotropicWriter_Float4.cs + + + XenkoShaderKeyGenerator + VoxelLayout_Float4.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierOpacifyAnisotropicPaired.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierSolidifyAnisotropicPaired.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierAnisotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierAntiAliasingAnisotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierOpacifyAnisotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierSolidifyAnisotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierAntiAliasingIsotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierIsotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierOpacifyIsotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifierApplierSolidifyIsotropic.cs + + + XenkoShaderKeyGenerator + VoxelModifier.cs + + + XenkoShaderKeyGenerator + VoxelizationMethod.cs + + + XenkoShaderKeyGenerator + VoxelizationMethodDominantAxis.cs + + + XenkoShaderKeyGenerator + VoxelizationMethodSingleAxis.cs + + + XenkoShaderKeyGenerator + VoxelizeToFragments.cs + + + XenkoShaderKeyGenerator + VoxelizeToFragmentsEffect.cs + + + XenkoShaderKeyGenerator + VoxelPositionStream.cs + + + XenkoShaderKeyGenerator + LocalSamples.cs + + + XenkoShaderKeyGenerator + VoxelMipmapHeuristic.cs + + + XenkoShaderKeyGenerator + VoxelMipmapPhysicallyBased.cs + + + XenkoShaderKeyGenerator + VoxelMipmapSimple.cs + + + XenkoShaderKeyGenerator + BufferToTexture.cs + + + XenkoShaderKeyGenerator + BufferToTextureColumns.cs + + + XenkoShaderKeyGenerator + BufferToTextureColumnsEffect.cs + + + XenkoShaderKeyGenerator + BufferToTextureEffect.cs + + + XenkoShaderKeyGenerator + ClearBuffer.cs + + + XenkoShaderKeyGenerator + VoxelStorageClipmapShader.cs + + + XenkoShaderKeyGenerator + VoxelStorageShader.cs + + + XenkoShaderKeyGenerator + VoxelStorageTextureClipmapShader.cs + + + XenkoShaderKeyGenerator + VoxelStorageTextureShader.cs + + + + + \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Xenko.Voxels.xkpkg b/sources/engine/Xenko.Voxels/Xenko.Voxels.xkpkg new file mode 100644 index 0000000000..bc07889ca4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Xenko.Voxels.xkpkg @@ -0,0 +1,5 @@ +!Package +SerializedVersion: {Assets: 3.1.0.0} +AssetFolders: + - Path: !dir Voxels +RootAssets: [] From 83790a0298e9fbc7501c1399659b0f728a9a9cff Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 15 Jan 2020 09:44:30 -0500 Subject: [PATCH 0631/2038] Voxel GI: adjustment for this fork (more efficient data structures) --- .../Voxels/Voxelization/VoxelVolumeProcessor.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs index d2272cfd8f..0c036209e2 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Xenko.Engine; @@ -77,12 +77,12 @@ private void RegenerateVoxelVolumes() // return; renderVoxelVolumes.Clear(); processedVoxelVolumes.Clear(); - foreach (var pair in ComponentDatas) + for (int i=0; i Date: Wed, 15 Jan 2020 16:19:07 -0500 Subject: [PATCH 0632/2038] Audio: fix issues with replaying and repositioning lots of music tracks --- .../engine/Xenko.Audio/DynamicSoundSource.cs | 72 +++++++++++++------ sources/engine/Xenko.Audio/SoundInstance.cs | 11 +-- 2 files changed, 52 insertions(+), 31 deletions(-) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index f0cd57fcbd..5360639bb5 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -74,12 +74,6 @@ protected enum AsyncCommand ///
protected volatile bool playingQueued; - /// - /// If the source is actually playing sound - /// this takes into account multiple factors: Playing, Ended task, and Audio layer playing state - /// - private volatile bool isSourcePausedOrPlaying = false; - /// /// Initializes a new instance of the class. /// Sub classes can implement their own streaming sources. @@ -164,7 +158,7 @@ public void Stop() /// /// Gets if this instance is in the playing state. /// - public bool IsPausedOrPlaying => playingQueued || state != PlayState.Stopped || isSourcePausedOrPlaying; + public bool IsPausedOrPlaying => playingQueued || state != PlayState.Stopped; /// /// Gets or sets the region of time to play from the audio clip. @@ -207,6 +201,7 @@ protected virtual void UpdateInternal() { } /// protected virtual void RestartInternal() { + AudioLayer.SourceFlushBuffers(soundInstance.Source); ReadyToPlay.TrySetResult(false); ReadyToPlay = new TaskCompletionSource(); readyToPlay = false; @@ -249,6 +244,7 @@ protected virtual void StopInternal(bool ignoreQueuedBuffer = true) { Ended.TrySetResult(true); state = PlayState.Stopped; + soundInstance.playState = PlayState.Stopped; if (ignoreQueuedBuffer) AudioLayer.SourceStop(soundInstance.Source); RestartInternal(); @@ -272,6 +268,24 @@ protected virtual void DisposeInternal() isInitialized = false; } + private void Rebuffer() + { + int numberOfBuffers = deviceBuffers.Count; + + for (int i = 0; i < numberOfBuffers; i++) + AudioLayer.BufferDestroy(deviceBuffers[i]); + + deviceBuffers.Clear(); + freeBuffers.Clear(); + + for (var i = 0; i < numberOfBuffers; i++) + { + var buffer = AudioLayer.BufferCreate(nativeBufferSizeBytes); + deviceBuffers.Add(buffer); + freeBuffers.Enqueue(deviceBuffers[i]); + } + } + /// /// If CanFillis true with this method you can fill the next free buffer /// @@ -327,11 +341,8 @@ protected unsafe void FillBuffer(byte[] pcm, int bufferSize, AudioLayer.BufferTy private static unsafe void Worker() { - var toRemove = new List(); while (true) { - toRemove.Clear(); - while (!NewSources.IsEmpty) { if (!NewSources.TryTake(out var source)) @@ -344,11 +355,14 @@ private static unsafe void Worker() Sources.Add(source); } - foreach (var source in Sources) + for (int i=0; i /// % of when to start, 0.5 is starting at the exact middle /// % of when to end. 1 is default (100%) - public void SetRangePercent(double startPercent, double endPercent = 1f) + public void SetRangePercent(double startPercent, double endPercent = 1.0) { if (engine.State == AudioEngineState.Invalidated) return; @@ -441,7 +436,7 @@ public void SetRangePercent(double startPercent, double endPercent = 1f) soundSource.PlayRange = new PlayRange( new TimeSpan((long)Math.Round((double)sound.TotalLength.Ticks * startPercent)), - new TimeSpan((long)Math.Round((double)sound.TotalLength.Ticks * endPercent))); + endPercent >= 1.0 ? TimeSpan.Zero : new TimeSpan((long)Math.Round((double)sound.TotalLength.Ticks * endPercent))); } if (state == PlayState.Playing) From 97279042daf8f3c5e0a5d0af07ee9ff30be7e4e6 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 15 Jan 2020 16:33:20 -0500 Subject: [PATCH 0633/2038] Audio: add a master volume to the Global Sound Manager --- sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index bd87ff3d28..d0715fa9de 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -37,13 +37,16 @@ private struct PositionalSound [DataMember] public int MaxSameSoundOverlaps = 8; + [DataMember] + public float MasterVolume = 1f; + public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume = 1f, float pan = 0.5f, bool looped = false) { SoundInstance s = getFreeInstance(url, false); if (s != null) { s.Pitch = pitch; - s.Volume = volume; + s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; s.Play(); @@ -58,7 +61,7 @@ public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch SoundInstance s = getFreeInstance(url, true); if (s == null) return null; s.Pitch = pitch; - s.Volume = volume; + s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; s.Apply3D(position, null, null, distanceScale); @@ -74,7 +77,7 @@ public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = SoundInstance s = getFreeInstance(url, true); if (s == null) return null; s.Pitch = pitch; - s.Volume = volume; + s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; s.Apply3D(pos, null, null, distanceScale); From e5aa3020a757fa56ae744e651859acb06fa332e4 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 15 Jan 2020 20:58:28 -0500 Subject: [PATCH 0634/2038] Audio: shortcut for having random sound pitches --- sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index d0715fa9de..267f8f652e 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -45,7 +45,7 @@ public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume SoundInstance s = getFreeInstance(url, false); if (s != null) { - s.Pitch = pitch; + s.Pitch = pitch < 0f ? RandomPitch() : pitch; s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; @@ -60,7 +60,7 @@ public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; SoundInstance s = getFreeInstance(url, true); if (s == null) return null; - s.Pitch = pitch; + s.Pitch = pitch < 0f ? RandomPitch() : pitch; s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; @@ -76,7 +76,7 @@ public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; SoundInstance s = getFreeInstance(url, true); if (s == null) return null; - s.Pitch = pitch; + s.Pitch = pitch < 0f ? RandomPitch() : pitch; s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; From d67a83bd4916b8b911293b88b8070ecab511bb99 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 15 Jan 2020 20:59:03 -0500 Subject: [PATCH 0635/2038] Audio: better automatic picking of listener in scene (with option to override) --- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 267f8f652e..c6cf57d912 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -172,12 +172,12 @@ private Game game } } - [DataMember] - public AudioListenerComponent Listener + [DataMemberIgnore] + private AudioListenerComponent Listener { get { - if (_listener == null || _listener.Entity.Scene == null) + if (_listener == null || _listener.Entity.Scene == null || _listener.Enabled == false) { Game g = game; @@ -186,10 +186,16 @@ public AudioListenerComponent Listener // find a valid listener! foreach (AudioListenerComponent alc in g.Audio.Listeners.Keys) { - _listener = alc; - break; + if (alc.Enabled) + { + _listener = alc; + break; + } } } + + if (_listener == null) + throw new InvalidOperationException("Could not find an Audio Listener Component in scene!"); } return _listener; } @@ -202,6 +208,11 @@ public AudioListenerComponent Listener } } + public void OverrideListener(AudioListenerComponent listener) + { + Listener = listener; + } + private Dictionary Sounds = new Dictionary(); private Dictionary> instances = new Dictionary>(); private List currentAttached = new List(); From 1e4e02b8b6c0d1e4818d33eaad76dcda7eba994b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 15 Jan 2020 21:55:14 -0500 Subject: [PATCH 0636/2038] Audio: fixes for audio listener picking between scene changes --- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index c6cf57d912..00a41356f6 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -177,20 +177,20 @@ private AudioListenerComponent Listener { get { - if (_listener == null || _listener.Entity.Scene == null || _listener.Enabled == false) - { - Game g = game; + Game g = game; + + if (g == null) + throw new InvalidOperationException("No Game object has been fully initialized yet!"); - if (g != null) + if (_listener == null || _listener.Enabled == false || g.Audio.Listeners.ContainsKey(_listener) == false) + { + // find a valid listener! + foreach (AudioListenerComponent alc in g.Audio.Listeners.Keys) { - // find a valid listener! - foreach (AudioListenerComponent alc in g.Audio.Listeners.Keys) + if (alc.Enabled) { - if (alc.Enabled) - { - _listener = alc; - break; - } + _listener = alc; + break; } } From 277051347d808e96f18e3600a54cea46bfe41c3c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 16 Jan 2020 13:07:30 -0500 Subject: [PATCH 0637/2038] UI Slider: more visual options and consistent sizing --- sources/engine/Xenko.UI/Controls/Slider.cs | 41 +++++++++++++++++++ .../Renderers/DefaultSliderRenderer.cs | 34 +++++++-------- 2 files changed, 55 insertions(+), 20 deletions(-) diff --git a/sources/engine/Xenko.UI/Controls/Slider.cs b/sources/engine/Xenko.UI/Controls/Slider.cs index 07835b9336..58ca9c56e1 100644 --- a/sources/engine/Xenko.UI/Controls/Slider.cs +++ b/sources/engine/Xenko.UI/Controls/Slider.cs @@ -131,6 +131,47 @@ public float Step } } + [DataMember] + [Display(category: AppearanceCategory)] + public Color TrackBackgroundTint { get; set; } = Color.White; + + [DataMember] + [Display(category: AppearanceCategory)] + [DefaultValue(1.3f)] + public float TrackForegroundHeightScale { get; set; } = 1.3f; + + [DataMember] + [Display(category: AppearanceCategory)] + public Color TrackForegroundTint { get; set; } = Color.White; + + [DataMember] + [Display(category: AppearanceCategory)] + public Color TickTint { get; set; } = Color.White; + + [DataMember] + [Display(category: AppearanceCategory)] + [DefaultValue(0.4f)] + public float TickHeightScale { get; set; } = 0.4f; + + [DataMember] + [Display(category: AppearanceCategory)] + [DefaultValue(0.01f)] + public float TickWidthScale { get; set; } = 0.01f; + + [DataMember] + [Display(category: AppearanceCategory)] + [DefaultValue(1.3f)] + public float ThumbHeightScale { get; set; } = 1.3f; + + [DataMember] + [Display(category: AppearanceCategory)] + [DefaultValue(1.3f)] + public float ThumbWidthScale { get; set; } = 0.1f; + + [DataMember] + [Display(category: AppearanceCategory)] + public Color ThumbTint { get; set; } = Color.White; + /// /// Gets or sets the image to display as Track background. /// diff --git a/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs index 4ac3041f92..8f7b64b8c1 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs @@ -29,14 +29,12 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var axis = (int)slider.Orientation; var axisPrime = (axis + 1) % 2; - var color = slider.RenderOpacity * Color.White; var isGaugeReverted = axis == 1 ? !slider.IsDirectionReversed : slider.IsDirectionReversed; // we want the track going up from the bottom in vertical mode by default var sliderRatio = MathUtil.InverseLerp(slider.Minimum, slider.Maximum, slider.Value); var trackOffsets = new Vector2(slider.TrackStartingOffsets[axis], slider.TrackStartingOffsets[axisPrime]); var fullGaugeSize = slider.RenderSizeInternal[axis] - trackOffsets.X - trackOffsets.Y; var image = slider.TrackBackgroundImage?.GetSprite(); - var trackIdealSize = image != null ? new Vector2?(image.SizeInPixels) : null; // draws the track background if (image?.Texture != null) { @@ -44,7 +42,8 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var imageOrientation = (ImageOrientation)(axis ^ imageAxis); var worldMatrix = GetAdjustedWorldMatrix(ref slider.WorldMatrixInternal, (axis & imageAxis) == 1); - Batch.DrawImage(image.Texture, ref worldMatrix, ref image.RegionInternal, ref slider.RenderSizeInternal, ref image.BordersInternal, ref color, context.DepthBias, imageOrientation); + Color tbt = slider.TrackBackgroundTint * slider.RenderOpacity; + Batch.DrawImage(image.Texture, ref worldMatrix, ref image.RegionInternal, ref slider.RenderSizeInternal, ref image.BordersInternal, ref tbt, context.DepthBias, imageOrientation); context.DepthBias += 1; } @@ -58,9 +57,7 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var size = new Vector3(); size[axis] = sliderRatio * fullGaugeSize; - size[axisPrime] = image.SizeInPixels.Y; - if (trackIdealSize.HasValue) - size[axisPrime] *= slider.RenderSizeInternal[axisPrime] / trackIdealSize.Value.Y; + size[axisPrime] = slider.TrackForegroundHeightScale * slider.RenderSizeInternal[axisPrime]; var worldMatrix = GetAdjustedWorldMatrix(ref slider.WorldMatrixInternal, shouldRotate180Degrees); var halfSizeLeft = (slider.RenderSizeInternal[axis] - size[axis]) / 2; @@ -87,7 +84,8 @@ public override void RenderColor(UIElement element, UIRenderingContext context) } var region = new RectangleF(position.X, position.Y, newRegionSize.X, newRegionSize.Y); - Batch.DrawImage(image.Texture, ref worldMatrix, ref region, ref size, ref borders, ref color, context.DepthBias, imageOrientation); + Color tft = slider.TrackForegroundTint * slider.RenderOpacity; + Batch.DrawImage(image.Texture, ref worldMatrix, ref region, ref size, ref borders, ref tft, context.DepthBias, imageOrientation); context.DepthBias += 1; } @@ -100,15 +98,11 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var shouldRotate180Degrees = (axis & imageAxis) == 1; var size = new Vector3(); - size[axis] = image.SizeInPixels.X; - size[axisPrime] = image.SizeInPixels.Y; - if (trackIdealSize.HasValue) - size[axisPrime] *= slider.RenderSizeInternal[axisPrime] / trackIdealSize.Value.Y; + size[axis] = slider.RenderSizeInternal[axis] * slider.TickWidthScale; + size[axisPrime] = slider.RenderSizeInternal[axisPrime] * slider.TickHeightScale; var startOffset = new Vector2(GetAdjustedTranslation(slider.TickOffset, shouldRotate180Degrees)); startOffset[axis] = GetAdjustedTranslation(- fullGaugeSize / 2, shouldRotate180Degrees); - if (trackIdealSize.HasValue) - startOffset[axisPrime] *= slider.RenderSizeInternal[axisPrime] / trackIdealSize.Value.Y; var stepOffset = GetAdjustedTranslation(fullGaugeSize / slider.TickFrequency, shouldRotate180Degrees); @@ -116,10 +110,11 @@ public override void RenderColor(UIElement element, UIRenderingContext context) worldMatrix.M41 += startOffset[axis] * worldMatrix[(axis << 2) + 0] + startOffset[axisPrime] * worldMatrix[(axisPrime << 2) + 0]; worldMatrix.M42 += startOffset[axis] * worldMatrix[(axis << 2) + 1] + startOffset[axisPrime] * worldMatrix[(axisPrime << 2) + 1]; worldMatrix.M43 += startOffset[axis] * worldMatrix[(axis << 2) + 2] + startOffset[axisPrime] * worldMatrix[(axisPrime << 2) + 2]; - + + Color tclr = slider.TickTint * slider.RenderOpacity; for (var i = 0; i < slider.TickFrequency + 1; i++) { - Batch.DrawImage(image.Texture, ref worldMatrix, ref image.RegionInternal, ref size, ref image.BordersInternal, ref color, context.DepthBias, imageOrientation, SwizzleMode.None, true); + Batch.DrawImage(image.Texture, ref worldMatrix, ref image.RegionInternal, ref size, ref image.BordersInternal, ref tclr, context.DepthBias, imageOrientation, SwizzleMode.None, true); worldMatrix.M41 += stepOffset * worldMatrix[(axis << 2) + 0]; worldMatrix.M42 += stepOffset * worldMatrix[(axis << 2) + 1]; @@ -137,10 +132,8 @@ public override void RenderColor(UIElement element, UIRenderingContext context) var shouldRotate180Degrees = (axis & imageAxis) == 1; var size = new Vector3(); - size[axis] = image.SizeInPixels.X; - size[axisPrime] = image.SizeInPixels.Y; - if (trackIdealSize.HasValue) - size[axisPrime] *= slider.RenderSizeInternal[axisPrime] / trackIdealSize.Value.Y; + size[axis] = slider.RenderSizeInternal[axis] * slider.ThumbWidthScale; + size[axisPrime] = slider.RenderSizeInternal[axisPrime] * slider.ThumbHeightScale; var revertedRatio = isGaugeReverted ? 1 - sliderRatio : sliderRatio; var offset = GetAdjustedTranslation((revertedRatio - 0.5f) * fullGaugeSize, shouldRotate180Degrees); @@ -149,7 +142,8 @@ public override void RenderColor(UIElement element, UIRenderingContext context) worldMatrix.M42 += offset * worldMatrix[(axis << 2) + 1]; worldMatrix.M43 += offset * worldMatrix[(axis << 2) + 2]; - Batch.DrawImage(image.Texture, ref worldMatrix, ref image.RegionInternal, ref size, ref image.BordersInternal, ref color, context.DepthBias, imageOrientation); + Color tc = slider.ThumbTint * slider.RenderOpacity; + Batch.DrawImage(image.Texture, ref worldMatrix, ref image.RegionInternal, ref size, ref image.BordersInternal, ref tc, context.DepthBias, imageOrientation); context.DepthBias += 1; } From 33b849be228bfbb6bc3fd61976581a43abf9fd2e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 16 Jan 2020 19:27:58 -0500 Subject: [PATCH 0638/2038] PulldownList UI: will hide itself if clicking elsewhere --- sources/engine/Xenko.UI/PulldownList.cs | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/sources/engine/Xenko.UI/PulldownList.cs b/sources/engine/Xenko.UI/PulldownList.cs index b64863b82d..d61cb464fd 100644 --- a/sources/engine/Xenko.UI/PulldownList.cs +++ b/sources/engine/Xenko.UI/PulldownList.cs @@ -2,7 +2,9 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using Xenko.Core; using Xenko.Engine; +using Xenko.Input; using Xenko.UI.Controls; using Xenko.UI.Panels; @@ -104,8 +106,14 @@ public PulldownList(Grid grid, UILibrary entryTemplate, UIElement pulldownIndica scroll = grid.Parent as ScrollViewer; if (scroll == null) throw new ArgumentException("Grid needs a ScrollViewer as Parent"); scroll.ScrollMode = ScrollingMode.Vertical; + myGrid.Height = entryHeight; this.pulldownIndicator = pulldownIndicator; + + listener = new ClickHandler(); + listener.mouseOverCheck = this; + + inputManager = ServiceRegistry.instance.GetService(); } public override UIElement AddEntry(string displayName, object value = null, bool rebuildVisualListAfter = true) @@ -127,6 +135,32 @@ override public void RebuildVisualList() if (pulldownIndicator != null) pulldownIndicator.Visibility = _currentlyExpanded ? Visibility.Hidden : Visibility.Visible; scroll.Height = _currentlyExpanded ? entryHeight * Math.Min(entryElements.Count, _optionsToShow + 0.5f) : entryHeight; myGrid.Height = _currentlyExpanded ? entryHeight * entryElements.Count : entryHeight; + + if (_currentlyExpanded) + { + inputManager.AddListener(listener); + } + else + { + inputManager.RemoveListener(listener); + } + } + + private InputManager inputManager; + private ClickHandler listener; + + private class ClickHandler : IInputEventListener + { + public PulldownList mouseOverCheck; + + public void ProcessEvent(PointerEvent inputEvent) + { + if (inputEvent.EventType == PointerEventType.Pressed && + mouseOverCheck.scroll.MouseOverState == MouseOverState.MouseOverNone) + { + mouseOverCheck.CurrentlyExpanded = false; + } + } } } } From 914ba0c92db3a9460a4e48dc8dba56ad5239784c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 16 Jan 2020 20:54:25 -0500 Subject: [PATCH 0639/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ac7c16af25..1ba3497897 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ My games require the engine to be developed at a faster pace than Xenko. I'm in ## What is different? -Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. +Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. However, I do not maintain different languages, Android support or the Launcher to "Focus" on things like: * Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. See https://github.com/phr00t/FOVTester2 for a super simple example of how easy a VR project is. * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. From cd5e44180d8c12acd98a7e016fcc6b33ee4be0e9 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 16 Jan 2020 21:37:04 -0500 Subject: [PATCH 0640/2038] Slider UI: snap to end if dragging off end, even quickly --- sources/engine/Xenko.UI/Controls/Slider.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/sources/engine/Xenko.UI/Controls/Slider.cs b/sources/engine/Xenko.UI/Controls/Slider.cs index 58ca9c56e1..5ad6f0b71f 100644 --- a/sources/engine/Xenko.UI/Controls/Slider.cs +++ b/sources/engine/Xenko.UI/Controls/Slider.cs @@ -447,6 +447,20 @@ protected override void OnTouchLeave(TouchEventArgs args) { base.OnTouchLeave(args); + // check and see if we were dragging off the edge + Vector2 leaveDir = Vector2.Normalize(args.ScreenTranslation); + + if (leaveDir.X > 0.7f && Orientation == Orientation.Horizontal || + leaveDir.Y > 0.7f && Orientation == Orientation.Vertical) + { + if (Value > Maximum * 0.85f) Value = Maximum; + } + else if (leaveDir.X < -0.7f && Orientation == Orientation.Horizontal || + leaveDir.Y < -0.7f && Orientation == Orientation.Vertical) + { + if (Value < Maximum * 0.15f) Value = Minimum; + } + IsTouchedDown = false; } From 3155a7042d9779f46ef82bd20bc313d3a573dfa5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 17 Jan 2020 13:37:37 -0500 Subject: [PATCH 0641/2038] Audio: fix for stopping non-streaming audio --- sources/engine/Xenko.Audio/SoundInstance.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index c4543bde6c..bfbd1993b4 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -369,6 +369,12 @@ public PlayState PlayState if (engine.State == AudioEngineState.Invalidated) return PlayState.Stopped; + if (soundSource == null && playState == PlayState.Playing && AudioLayer.SourceIsPlaying(Source) == false) + { + // non-streamed sound stopped playing + playState = PlayState.Stopped; + } + return playState; } } From 4315583c31b37da6c431a2b298db898e7b4369b2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 17 Jan 2020 13:38:25 -0500 Subject: [PATCH 0642/2038] UI: Fixed EditText sizing for static fonts --- .../engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs index 5af786400a..94ff3c853e 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs @@ -44,7 +44,7 @@ private void RenderSelection(EditText editText, UIRenderingContext context, int } var scaleRatio = editText.ActualTextSize / font.Size; - if (font.FontType == SpriteFontType.SDF) + if (font.FontType != SpriteFontType.Dynamic) { offsetTextStart *= scaleRatio; selectionSize *= scaleRatio; @@ -58,8 +58,7 @@ private void RenderSelection(EditText editText, UIRenderingContext context, int var textWidth = font.MeasureString(editText.TextToDisplay, ref fontSize).X; if (font.FontType == SpriteFontType.Dynamic) textWidth /= fontScale.X; - if (font.FontType == SpriteFontType.SDF) - textWidth *= scaleRatio; + else textWidth *= scaleRatio; offsetAlignment = editText.TextAlignment == TextAlignment.Center ? -textWidth / 2 : -textRegionSize.X / 2f + (textRegionSize.X - textWidth); } @@ -148,7 +147,7 @@ public override void RenderColor(UIElement element, UIRenderingContext context) if (editText.IsCaretVisible) { var lineSpacing = editText.Font.GetTotalLineSpacing(editText.ActualTextSize); - if (editText.Font.FontType == SpriteFontType.SDF) + if (editText.Font.FontType != SpriteFontType.Dynamic) lineSpacing *= editText.ActualTextSize / font.Size; var sizeCaret = editText.CaretWidth / fontScale.X; From 0537e5fa442f335cb425a3058c6ceea6cb1140d0 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 17 Jan 2020 20:06:43 -0500 Subject: [PATCH 0643/2038] UI: EditText sizing and selection fixes for non-dynamic fonts --- sources/engine/Xenko.UI/Controls/EditText.Direct.cs | 12 ++++++------ sources/engine/Xenko.UI/Controls/EditText.cs | 5 ++--- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/sources/engine/Xenko.UI/Controls/EditText.Direct.cs b/sources/engine/Xenko.UI/Controls/EditText.Direct.cs index d007c97f07..ddfb0ba926 100644 --- a/sources/engine/Xenko.UI/Controls/EditText.Direct.cs +++ b/sources/engine/Xenko.UI/Controls/EditText.Direct.cs @@ -58,24 +58,24 @@ protected virtual int FindNearestCharacterIndex(Vector2 position) if (TextAlignment != TextAlignment.Left) { var textWidth = Font.MeasureString(TextToDisplay, ref fontSize).X; - if (Font.FontType == SpriteFontType.Dynamic) - textWidth /= fontScale.X; + textWidth /= fontScale.X; + if (Font.FontType != SpriteFontType.Dynamic) textWidth *= fontSize.X / Font.Size; alignmentOffset = TextAlignment == TextAlignment.Center ? -textWidth / 2 : -textRegionSize / 2f + (textRegionSize - textWidth); } var touchInText = position.X - alignmentOffset; // Find the first character starting after the click - var characterIndex = 1; + var characterIndex = 0; var previousCharacterOffset = 0f; - var currentCharacterOffset = Font.MeasureString(TextToDisplay, ref fontSize, characterIndex).X; + var currentCharacterOffset = 0f; while (currentCharacterOffset < touchInText && characterIndex < textToDisplay.Length) { ++characterIndex; previousCharacterOffset = currentCharacterOffset; currentCharacterOffset = Font.MeasureString(TextToDisplay, ref fontSize, characterIndex).X; - if (Font.FontType == SpriteFontType.Dynamic) - currentCharacterOffset /= fontScale.X; + currentCharacterOffset /= fontScale.X; + if (Font.FontType != SpriteFontType.Dynamic) currentCharacterOffset *= fontSize.X / Font.Size; } // determine the caret position. diff --git a/sources/engine/Xenko.UI/Controls/EditText.cs b/sources/engine/Xenko.UI/Controls/EditText.cs index bc90bff986..f3c11cd94c 100644 --- a/sources/engine/Xenko.UI/Controls/EditText.cs +++ b/sources/engine/Xenko.UI/Controls/EditText.cs @@ -784,8 +784,7 @@ protected Vector2 CalculateTextSize(string textToMeasure) realSize.X /= sizeRatio.X; realSize.Y /= sizeRatio.Y; } - - if (Font.FontType == SpriteFontType.SDF) + else { var scaleRatio = ActualTextSize / Font.Size; realSize.X *= scaleRatio; @@ -802,7 +801,7 @@ protected override Vector3 MeasureOverride(Vector3 availableSizeWithoutMargins) { // take the maximum between the text size and the minimum visible line size as text desired size var fontLineSpacing = Font.GetTotalLineSpacing(ActualTextSize); - if (Font.FontType == SpriteFontType.SDF) + if (Font.FontType != SpriteFontType.Dynamic) fontLineSpacing *= ActualTextSize / Font.Size; var currentTextSize = new Vector3(CalculateTextSize(), 0); desiredSize = new Vector3(currentTextSize.X, Math.Min(Math.Max(currentTextSize.Y, fontLineSpacing * MinLines), fontLineSpacing * MaxLines), currentTextSize.Z); From c415d2260bb6a800b42fafb029c7b30742d7686c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 17 Jan 2020 20:07:17 -0500 Subject: [PATCH 0644/2038] UI: Get rid of OriginalFont reference, which isn't used and causes errors when deleting the original font --- .../Xenko.Assets/SpriteFont/PrecompiledSpriteFontAsset.cs | 7 ------- .../Xenko.Assets/SpriteFont/SpriteFontAssetExtensions.cs | 2 -- 2 files changed, 9 deletions(-) diff --git a/sources/engine/Xenko.Assets/SpriteFont/PrecompiledSpriteFontAsset.cs b/sources/engine/Xenko.Assets/SpriteFont/PrecompiledSpriteFontAsset.cs index cb6f928752..5c2abec102 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/PrecompiledSpriteFontAsset.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/PrecompiledSpriteFontAsset.cs @@ -47,13 +47,6 @@ public partial class PrecompiledSpriteFontAsset : Asset [Display(Browsable = false)] public float Size = 16; // a random non-null value for font created by users - /// - /// The reference to the original source asset. - /// - /// The sprite font asset that has been used to generate this precompiled font. - [DataMember(0)] - public AssetReference OriginalFont; - /// /// The file containing the font data. /// diff --git a/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAssetExtensions.cs b/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAssetExtensions.cs index 0d76d9cbf1..81d40bb60e 100644 --- a/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAssetExtensions.cs +++ b/sources/engine/Xenko.Assets/SpriteFont/SpriteFontAssetExtensions.cs @@ -48,7 +48,6 @@ public static PrecompiledSpriteFontAsset GeneratePrecompiledSpriteFont(this Spri Glyphs = glyphs, Size = asset.FontType.Size, Style = asset.FontSource.Style, - OriginalFont = referenceToSourceFont, FontDataFile = textureFileName, BaseOffset = staticFont.BaseOffsetY, DefaultLineSpacing = staticFont.DefaultLineSpacing, @@ -96,7 +95,6 @@ public static PrecompiledSpriteFontAsset GeneratePrecompiledSDFSpriteFont(this S Glyphs = glyphs, Size = asset.FontType.Size, Style = asset.FontSource.Style, - OriginalFont = referenceToSourceFont, FontDataFile = textureFileName, BaseOffset = scalableFont.BaseOffsetY, DefaultLineSpacing = scalableFont.DefaultLineSpacing, From b0887985b75e876ccd7a2939063e886acc48006d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 17 Jan 2020 20:33:46 -0500 Subject: [PATCH 0645/2038] UI: Add optional Action method when Enter is pressed on an EditText --- sources/engine/Xenko.UI/Controls/EditText.Direct.cs | 8 +++++++- sources/engine/Xenko.UI/Controls/EditText.cs | 2 ++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.UI/Controls/EditText.Direct.cs b/sources/engine/Xenko.UI/Controls/EditText.Direct.cs index ddfb0ba926..542794e55e 100644 --- a/sources/engine/Xenko.UI/Controls/EditText.Direct.cs +++ b/sources/engine/Xenko.UI/Controls/EditText.Direct.cs @@ -233,7 +233,13 @@ private void InterpretKey(Keys key, InputManager input) } // validate the text with "enter" or "escape" - if (key == Keys.Enter || key == Keys.Escape || key == Keys.NumPadEnter) + if (key == Keys.Enter || key == Keys.NumPadEnter) + { + IsSelectionActive = false; + if (EnterAction != null) EnterAction(text); + return; + } + else if (key == Keys.Escape) { IsSelectionActive = false; return; diff --git a/sources/engine/Xenko.UI/Controls/EditText.cs b/sources/engine/Xenko.UI/Controls/EditText.cs index f3c11cd94c..879a6c2e03 100644 --- a/sources/engine/Xenko.UI/Controls/EditText.cs +++ b/sources/engine/Xenko.UI/Controls/EditText.cs @@ -133,6 +133,8 @@ public EditText() private SpriteFont font; private bool isReadOnly; + public Action EnterAction; + /// /// Gets a value that indicates whether the text box has focus and selected text. /// From ea3caeb481ab46b1e5ea9be13cfaa6f09ee504ff Mon Sep 17 00:00:00 2001 From: EternalTamago <13661631+EternalTamago@users.noreply.github.com> Date: Mon, 13 Jan 2020 06:36:25 +0900 Subject: [PATCH 0646/2038] Renew Heightfield desc and Heightmap asset # Conflicts: # sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs --- .../Navigation/NavigationMeshAssetCompiler.cs | 4 +- ...ByteHeightmapHeightConversionParameters.cs | 28 +++++++++ .../Physics/ColliderShapeAssetCompiler.cs | 2 +- ...FloatHeightmapHeightConversionParamters.cs | 25 ++++++++ .../Xenko.Assets/Physics/HeightmapAsset.cs | 12 ++-- .../Physics/HeightmapAssetCompiler.cs | 58 +++++++++++++---- .../Physics}/HeightmapResizingParameters.cs | 2 +- .../IHeightmapHeightConversionParameters.cs | 10 +++ ...hortHeightmapHeightConversionParameters.cs | 28 +++++++++ .../Data/HeightfieldColliderShapeDesc.cs | 62 +++++-------------- .../EmptyByteHeightfieldHeightData.cs | 54 ++++++++++++++++ ....cs => EmptyFloatHeightfieldHeightData.cs} | 26 +++++--- .../EmptyShortHeightfieldHeightData.cs | 54 ++++++++++++++++ .../engine/Xenko.Physics/Engine/Heightmap.cs | 16 ++++- sources/engine/Xenko.Physics/HeightScale.cs | 32 ---------- .../HeightScaleFromHeightRange.cs | 54 ---------------- ... => HeightfieldHeightDataFromHeightmap.cs} | 20 +++--- .../HeightfieldHeightScaleCalculator.cs | 39 ++++++++++++ ...ightfieldHeightScaleCalculatorWithValue.cs | 16 +++++ .../IHeightfieldHeightDescription.cs | 15 +++++ ...s => IHeightfieldHeightScaleCalculator.cs} | 6 +- ...ta.cs => IInitialHeightfieldHeightData.cs} | 4 +- 22 files changed, 387 insertions(+), 180 deletions(-) create mode 100644 sources/engine/Xenko.Assets/Physics/ByteHeightmapHeightConversionParameters.cs create mode 100644 sources/engine/Xenko.Assets/Physics/FloatHeightmapHeightConversionParamters.cs rename sources/engine/{Xenko.Physics => Xenko.Assets/Physics}/HeightmapResizingParameters.cs (94%) create mode 100644 sources/engine/Xenko.Assets/Physics/IHeightmapHeightConversionParameters.cs create mode 100644 sources/engine/Xenko.Assets/Physics/ShortHeightmapHeightConversionParameters.cs create mode 100644 sources/engine/Xenko.Physics/EmptyByteHeightfieldHeightData.cs rename sources/engine/Xenko.Physics/{EmptyHeightData.cs => EmptyFloatHeightfieldHeightData.cs} (52%) create mode 100644 sources/engine/Xenko.Physics/EmptyShortHeightfieldHeightData.cs delete mode 100644 sources/engine/Xenko.Physics/HeightScale.cs delete mode 100644 sources/engine/Xenko.Physics/HeightScaleFromHeightRange.cs rename sources/engine/Xenko.Physics/{HeightDataFromHeightmap.cs => HeightfieldHeightDataFromHeightmap.cs} (64%) create mode 100644 sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculator.cs create mode 100644 sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculatorWithValue.cs create mode 100644 sources/engine/Xenko.Physics/IHeightfieldHeightDescription.cs rename sources/engine/Xenko.Physics/{IHeightScale.cs => IHeightfieldHeightScaleCalculator.cs} (59%) rename sources/engine/Xenko.Physics/{IInitialHeightData.cs => IInitialHeightfieldHeightData.cs} (82%) diff --git a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs index 5916140db7..4b71e2f313 100644 --- a/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Navigation/NavigationMeshAssetCompiler.cs @@ -67,7 +67,7 @@ public override IEnumerable GetInputFiles(AssetItem assetItem) else if (desc is HeightfieldColliderShapeDesc) { var heightfieldDesc = desc as HeightfieldColliderShapeDesc; - var initialHeights = heightfieldDesc?.InitialHeights as HeightDataFromHeightmap; + var initialHeights = heightfieldDesc?.InitialHeights as HeightfieldHeightDataFromHeightmap; if (initialHeights?.Heightmap != null) { @@ -324,7 +324,7 @@ private void EnsureClonedSceneAndHash() else if (desc is HeightfieldColliderShapeDesc) { var heightfieldDesc = desc as HeightfieldColliderShapeDesc; - var initialHeights = heightfieldDesc?.InitialHeights as HeightDataFromHeightmap; + var initialHeights = heightfieldDesc?.InitialHeights as HeightfieldHeightDataFromHeightmap; if (initialHeights?.Heightmap != null) { diff --git a/sources/engine/Xenko.Assets/Physics/ByteHeightmapHeightConversionParameters.cs b/sources/engine/Xenko.Assets/Physics/ByteHeightmapHeightConversionParameters.cs new file mode 100644 index 0000000000..e92513a649 --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/ByteHeightmapHeightConversionParameters.cs @@ -0,0 +1,28 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Mathematics; +using Xenko.Physics; + +namespace Xenko.Assets.Physics +{ + [DataContract] + [Display("Byte")] + public class ByteHeightmapHeightConversionParameters : IHeightmapHeightConversionParameters + { + [DataMemberIgnore] + public HeightfieldTypes HeightType => HeightfieldTypes.Byte; + + [DataMember(10)] + public Vector2 HeightRange { get; set; } = new Vector2(0, 10); + + [DataMemberIgnore] + public float HeightScale => HeightScaleCalculator.Calculate(this); + + [DataMember(20)] + [NotNull] + [Display("HeightScale", Expand = ExpandRule.Always)] + public IHeightfieldHeightScaleCalculator HeightScaleCalculator { get; set; } = new HeightfieldHeightScaleCalculator(); + } +} diff --git a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs index 3644443e35..5c690f5bdb 100644 --- a/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/ColliderShapeAssetCompiler.cs @@ -65,7 +65,7 @@ public override IEnumerable GetInputFiles(AssetItem assetItem) { else if (desc is HeightfieldColliderShapeDesc) { var heightfieldDesc = desc as HeightfieldColliderShapeDesc; - var initialHeights = heightfieldDesc?.InitialHeights as HeightDataFromHeightmap; + var initialHeights = heightfieldDesc?.InitialHeights as HeightfieldHeightDataFromHeightmap; if (initialHeights?.Heightmap != null) { diff --git a/sources/engine/Xenko.Assets/Physics/FloatHeightmapHeightConversionParamters.cs b/sources/engine/Xenko.Assets/Physics/FloatHeightmapHeightConversionParamters.cs new file mode 100644 index 0000000000..d393eeceef --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/FloatHeightmapHeightConversionParamters.cs @@ -0,0 +1,25 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Physics; + +namespace Xenko.Assets.Physics +{ + [DataContract] + [Display("Float")] + public class FloatHeightmapHeightConversionParamters : IHeightmapHeightConversionParameters + { + [DataMemberIgnore] + public HeightfieldTypes HeightType => HeightfieldTypes.Float; + + [DataMember(10)] + public Vector2 HeightRange { get; set; } = new Vector2(-10, 10); + + [DataMemberIgnore] + public float HeightScale => 1f; + + [DataMember(20)] + public bool ScaleToFit { get; set; } = true; + } +} diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs index b5598ec856..d770de34ce 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAsset.cs @@ -18,17 +18,13 @@ public partial class HeightmapAsset : AssetWithSource public const string FileExtension = ".xkhmap"; - [DataMember(20)] - [Display(category: "Convert")] + [DataMember(10)] + [Display("Height", category: "Convert", Expand = ExpandRule.Always)] [NotNull] - public HeightfieldTypes HeightType { get; set; } = HeightfieldTypes.Float; + public IHeightmapHeightConversionParameters HeightParameters { get; set; } = new FloatHeightmapHeightConversionParamters(); - [DataMember(30)] + [DataMember(20, "Resize")] [Display(category: "Convert")] - public float HeightScale { get; set; } = 1f; - - [DataMember(40, "Resize")] - [Display(category: "Convert", Expand = ExpandRule.Always)] [NotNull] public HeightmapResizingParameters Resizing { get; set; } = new HeightmapResizingParameters(); diff --git a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs index 05c680050a..ddc9642de0 100644 --- a/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapAssetCompiler.cs @@ -1,6 +1,8 @@ // Copyright (c) Xenko contributors (https://xenko.com) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Xenko.Assets.Textures; using Xenko.Core.Assets; @@ -80,7 +82,7 @@ protected override Task DoCommandOverride(ICommandContext commandC // Convert pixel format of the image - var heightfieldType = Parameters.HeightType; + var heightfieldType = Parameters.HeightParameters.HeightType; switch (heightfieldType) { @@ -179,36 +181,68 @@ protected override Task DoCommandOverride(ICommandContext commandC continue; } + // Range + + var heightRange = Parameters.HeightParameters.HeightRange; + + if (heightRange.Y < heightRange.X) + { + continue; + } + // Read, scale and set heights + var heightScale = Parameters.HeightParameters.HeightScale; + + if (Math.Abs(heightScale) < float.Epsilon) + { + continue; + } + using (var image = textureTool.ConvertToXenkoImage(texImage)) { var pixelBuffer = image.PixelBuffer[0]; - var scale = Parameters.HeightScale; switch (heightfieldType) { case HeightfieldTypes.Float: - heightmap.Floats = pixelBuffer.GetPixels(); - for (int i = 0; i < heightmap.Floats.Length; ++i) { - heightmap.Floats[i] *= scale; + heightmap.Floats = pixelBuffer.GetPixels(); + + var floatConversionParameters = Parameters.HeightParameters as FloatHeightmapHeightConversionParamters; + if (floatConversionParameters == null) + { + continue; + } + + float scale = 1f; + + if (floatConversionParameters.ScaleToFit) + { + var max = heightmap.Floats.Max(h => Math.Abs(h)); + if ((max - 1f) < float.Epsilon) + { + max = 1f; + } + scale = Math.Max(Math.Abs(heightRange.X), Math.Abs(heightRange.Y)) / max; + } + + for (int i = 0; i < heightmap.Floats.Length; ++i) + { + heightmap.Floats[i] = MathUtil.Clamp(heightmap.Floats[i] * scale, heightRange.X, heightRange.Y); + } } break; case HeightfieldTypes.Short: - heightmap.Shorts = pixelBuffer.GetPixels(); - for (int i = 0; i < heightmap.Shorts.Length; ++i) { - heightmap.Shorts[i] = (short)MathUtil.Clamp(heightmap.Shorts[i] * scale, short.MinValue, short.MaxValue); + heightmap.Shorts = pixelBuffer.GetPixels(); } break; case HeightfieldTypes.Byte: - heightmap.Bytes = pixelBuffer.GetPixels(); - for (int i = 0; i < heightmap.Bytes.Length; ++i) { - heightmap.Bytes[i] = (byte)MathUtil.Clamp(heightmap.Bytes[i] * scale, byte.MinValue, byte.MaxValue); + heightmap.Bytes = pixelBuffer.GetPixels(); } break; @@ -220,6 +254,8 @@ protected override Task DoCommandOverride(ICommandContext commandC heightmap.HeightType = heightfieldType; heightmap.Size = size; + heightmap.HeightRange = heightRange; + heightmap.HeightScale = heightScale; } } } diff --git a/sources/engine/Xenko.Physics/HeightmapResizingParameters.cs b/sources/engine/Xenko.Assets/Physics/HeightmapResizingParameters.cs similarity index 94% rename from sources/engine/Xenko.Physics/HeightmapResizingParameters.cs rename to sources/engine/Xenko.Assets/Physics/HeightmapResizingParameters.cs index 64608e6251..4c964bd8e5 100644 --- a/sources/engine/Xenko.Physics/HeightmapResizingParameters.cs +++ b/sources/engine/Xenko.Assets/Physics/HeightmapResizingParameters.cs @@ -5,7 +5,7 @@ using Xenko.Core.Annotations; using Xenko.Core.Mathematics; -namespace Xenko.Physics +namespace Xenko.Assets.Physics { [DataContract] public class HeightmapResizingParameters diff --git a/sources/engine/Xenko.Assets/Physics/IHeightmapHeightConversionParameters.cs b/sources/engine/Xenko.Assets/Physics/IHeightmapHeightConversionParameters.cs new file mode 100644 index 0000000000..9757e057c6 --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/IHeightmapHeightConversionParameters.cs @@ -0,0 +1,10 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Physics; + +namespace Xenko.Assets.Physics +{ + public interface IHeightmapHeightConversionParameters : IHeightfieldHeightDescription + { + } +} diff --git a/sources/engine/Xenko.Assets/Physics/ShortHeightmapHeightConversionParameters.cs b/sources/engine/Xenko.Assets/Physics/ShortHeightmapHeightConversionParameters.cs new file mode 100644 index 0000000000..b346f3337d --- /dev/null +++ b/sources/engine/Xenko.Assets/Physics/ShortHeightmapHeightConversionParameters.cs @@ -0,0 +1,28 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Mathematics; +using Xenko.Physics; + +namespace Xenko.Assets.Physics +{ + [DataContract] + [Display("Short")] + public class ShortHeightmapHeightConversionParameters : IHeightmapHeightConversionParameters + { + [DataMemberIgnore] + public HeightfieldTypes HeightType => HeightfieldTypes.Short; + + [DataMember(10)] + public Vector2 HeightRange { get; set; } = new Vector2(-10, 10); + + [DataMemberIgnore] + public float HeightScale => HeightScaleCalculator.Calculate(this); + + [DataMember(20)] + [NotNull] + [Display("HeightScale", Expand = ExpandRule.Always)] + public IHeightfieldHeightScaleCalculator HeightScaleCalculator { get; set; } = new HeightfieldHeightScaleCalculator(); + } +} diff --git a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs index fe08b3b5e8..f53c5ffa94 100644 --- a/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs +++ b/sources/engine/Xenko.Physics/Data/HeightfieldColliderShapeDesc.cs @@ -17,37 +17,20 @@ public class HeightfieldColliderShapeDesc : IInlineColliderShapeDesc [DataMember(10)] [NotNull] [Display(Expand = ExpandRule.Always)] - public IInitialHeightData InitialHeights { get; set; } = new HeightDataFromHeightmap(); - - [DataMember(50)] - public Vector2 HeightRange; - - [DataMember(60)] - [NotNull] - [Display("Height Scale for Short or Byte", Expand = ExpandRule.Always)] - public IHeightScale HeightScale { get; set; } + public IInitialHeightfieldHeightData InitialHeights { get; set; } = new HeightfieldHeightDataFromHeightmap(); [DataMember(70)] - public bool FlipQuadEdges; + public bool FlipQuadEdges = false; [DataMember(80)] - public bool IsRecenteringOffsetted; + [Display("Center height 0")] + public bool CenterHeightZero = true; [DataMember(100)] public Vector3 LocalOffset; [DataMember(110)] - public Quaternion LocalRotation; - - public HeightfieldColliderShapeDesc() - { - HeightRange = new Vector2(-10, 10); - HeightScale = new HeightScaleFromHeightRange(); - FlipQuadEdges = false; - IsRecenteringOffsetted = true; - LocalOffset = new Vector3(0, 0, 0); - LocalRotation = Quaternion.Identity; - } + public Quaternion LocalRotation = Quaternion.Identity; public bool Match(object obj) { @@ -63,15 +46,11 @@ public bool Match(object obj) return false; } - var heightScaleComparison = other.HeightScale?.Match(HeightScale) ?? HeightScale == null; - var initialHeightsComparison = other.InitialHeights?.Match(InitialHeights) ?? InitialHeights == null; return initialHeightsComparison && - other.HeightRange == HeightRange && - heightScaleComparison && other.FlipQuadEdges == FlipQuadEdges && - other.IsRecenteringOffsetted == IsRecenteringOffsetted; + other.CenterHeightZero == CenterHeightZero; } public static bool IsValidHeightStickSize(Int2 size) @@ -109,16 +88,9 @@ public ColliderShape CreateShape() { if (InitialHeights == null || !IsValidHeightStickSize(InitialHeights.HeightStickSize) || - HeightRange.Y < HeightRange.X || - Math.Abs(HeightRange.Y - HeightRange.X) < float.Epsilon || - HeightScale == null) - { - return null; - } - - float heightScale = InitialHeights.HeightType == HeightfieldTypes.Float ? 1f : HeightScale.CalculateHeightScale(this); - - if (Math.Abs(heightScale) < float.Epsilon) + InitialHeights.HeightRange.Y < InitialHeights.HeightRange.X || + Math.Abs(InitialHeights.HeightRange.Y - InitialHeights.HeightRange.X) < float.Epsilon || + Math.Abs(InitialHeights.HeightScale) < float.Epsilon) { return null; } @@ -149,7 +121,7 @@ public ColliderShape CreateShape() return null; } - var offsetToCancelRecenter = IsRecenteringOffsetted ? HeightRange.X + ((HeightRange.Y - HeightRange.X) * 0.5f) : 0f; + var offsetToCenterHeightZero = CenterHeightZero ? InitialHeights.HeightRange.X + ((InitialHeights.HeightRange.Y - InitialHeights.HeightRange.X) * 0.5f) : 0f; var shape = new HeightfieldColliderShape ( @@ -157,15 +129,15 @@ public ColliderShape CreateShape() InitialHeights.HeightStickSize.Y, InitialHeights.HeightType, unmanagedArray, - heightScale, - HeightRange.X, - HeightRange.Y, + InitialHeights.HeightScale, + InitialHeights.HeightRange.X, + InitialHeights.HeightRange.Y, FlipQuadEdges ) - { - LocalOffset = LocalOffset + new Vector3(0, offsetToCancelRecenter, 0), - LocalRotation = LocalRotation, - }; + { + LocalOffset = LocalOffset + new Vector3(0, offsetToCenterHeightZero, 0), + LocalRotation = LocalRotation, + }; return shape; } diff --git a/sources/engine/Xenko.Physics/EmptyByteHeightfieldHeightData.cs b/sources/engine/Xenko.Physics/EmptyByteHeightfieldHeightData.cs new file mode 100644 index 0000000000..55ccef6c8d --- /dev/null +++ b/sources/engine/Xenko.Physics/EmptyByteHeightfieldHeightData.cs @@ -0,0 +1,54 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Mathematics; + +namespace Xenko.Physics +{ + [DataContract] + [Display("Byte")] + public class EmptyByteHeightfieldHeightData : IInitialHeightfieldHeightData + { + [DataMemberIgnore] + public HeightfieldTypes HeightType => HeightfieldTypes.Byte; + + [DataMember(10)] + public Int2 HeightStickSize { get; set; } = new Int2(65, 65); + + [DataMember(20)] + public Vector2 HeightRange { get; set; } = new Vector2(0, 10); + + [DataMemberIgnore] + public float HeightScale => HeightScaleCalculator.Calculate(this); + + [DataMember(30)] + [NotNull] + [Display("HeightScale", Expand = ExpandRule.Always)] + public IHeightfieldHeightScaleCalculator HeightScaleCalculator { get; set; } = new HeightfieldHeightScaleCalculator(); + + [DataMemberIgnore] + public float[] Floats => null; + + [DataMemberIgnore] + public short[] Shorts => null; + + [DataMemberIgnore] + public byte[] Bytes => null; + + public bool Match(object obj) + { + var other = obj as EmptyByteHeightfieldHeightData; + + if (other == null) + { + return false; + } + + return other.HeightStickSize == HeightStickSize && + other.HeightRange == HeightRange && + Math.Abs(other.HeightScale - HeightScale) < float.Epsilon; + } + } +} diff --git a/sources/engine/Xenko.Physics/EmptyHeightData.cs b/sources/engine/Xenko.Physics/EmptyFloatHeightfieldHeightData.cs similarity index 52% rename from sources/engine/Xenko.Physics/EmptyHeightData.cs rename to sources/engine/Xenko.Physics/EmptyFloatHeightfieldHeightData.cs index 9391d36f9b..931a74314b 100644 --- a/sources/engine/Xenko.Physics/EmptyHeightData.cs +++ b/sources/engine/Xenko.Physics/EmptyFloatHeightfieldHeightData.cs @@ -6,35 +6,41 @@ namespace Xenko.Physics { [DataContract] - [Display("Empty")] - public class EmptyHeightData : IInitialHeightData + [Display("Float")] + public class EmptyFloatHeightfieldHeightData : IInitialHeightfieldHeightData { + [DataMemberIgnore] + public HeightfieldTypes HeightType => HeightfieldTypes.Float; + [DataMember(10)] - public HeightfieldTypes HeightType { get; set; } = HeightfieldTypes.Float; + public Int2 HeightStickSize { get; set; } = new Int2(65, 65); [DataMember(20)] - public Int2 HeightStickSize { get; set; } = new Int2(65, 65); + public Vector2 HeightRange { get; set; } = new Vector2(-10, 10); + + [DataMemberIgnore] + public float HeightScale => 1f; - [Display(Browsable = false)] + [DataMemberIgnore] public float[] Floats => null; - [Display(Browsable = false)] + [DataMemberIgnore] public short[] Shorts => null; - [Display(Browsable = false)] + [DataMemberIgnore] public byte[] Bytes => null; public bool Match(object obj) { - var other = obj as EmptyHeightData; + var other = obj as EmptyFloatHeightfieldHeightData; if (other == null) { return false; } - return other.HeightType == HeightType && - other.HeightStickSize == HeightStickSize; + return other.HeightStickSize == HeightStickSize && + other.HeightRange == HeightRange; } } } diff --git a/sources/engine/Xenko.Physics/EmptyShortHeightfieldHeightData.cs b/sources/engine/Xenko.Physics/EmptyShortHeightfieldHeightData.cs new file mode 100644 index 0000000000..435e3efeef --- /dev/null +++ b/sources/engine/Xenko.Physics/EmptyShortHeightfieldHeightData.cs @@ -0,0 +1,54 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Core.Mathematics; + +namespace Xenko.Physics +{ + [DataContract] + [Display("Short")] + public class EmptyShortHeightfieldHeightData : IInitialHeightfieldHeightData + { + [DataMemberIgnore] + public HeightfieldTypes HeightType => HeightfieldTypes.Short; + + [DataMember(10)] + public Int2 HeightStickSize { get; set; } = new Int2(65, 65); + + [DataMember(20)] + public Vector2 HeightRange { get; set; } = new Vector2(-10, 10); + + [DataMemberIgnore] + public float HeightScale => HeightScaleCalculator.Calculate(this); + + [DataMember(30)] + [NotNull] + [Display("HeightScale", Expand = ExpandRule.Always)] + public IHeightfieldHeightScaleCalculator HeightScaleCalculator { get; set; } = new HeightfieldHeightScaleCalculator(); + + [DataMemberIgnore] + public float[] Floats => null; + + [DataMemberIgnore] + public short[] Shorts => null; + + [DataMemberIgnore] + public byte[] Bytes => null; + + public bool Match(object obj) + { + var other = obj as EmptyShortHeightfieldHeightData; + + if (other == null) + { + return false; + } + + return other.HeightStickSize == HeightStickSize && + other.HeightRange == HeightRange && + Math.Abs(other.HeightScale - HeightScale) < float.Epsilon; + } + } +} diff --git a/sources/engine/Xenko.Physics/Engine/Heightmap.cs b/sources/engine/Xenko.Physics/Engine/Heightmap.cs index df872c2199..c72b3b1907 100644 --- a/sources/engine/Xenko.Physics/Engine/Heightmap.cs +++ b/sources/engine/Xenko.Physics/Engine/Heightmap.cs @@ -31,9 +31,15 @@ public class Heightmap public HeightfieldTypes HeightType; [DataMember(50)] - public Int2 Size { get; set; } + public Int2 Size; - public static Heightmap Create(Int2 size, T[] data) where T : struct + [DataMember(60)] + public Vector2 HeightRange; + + [DataMember(70)] + public float HeightScale; + + public static Heightmap Create(Int2 size, Vector2 range, float scale, T[] data) where T : struct { if (!HeightfieldColliderShapeDesc.IsValidHeightStickSize(size) || data == null) { @@ -48,6 +54,8 @@ public static Heightmap Create(Int2 size, T[] data) where T : struct { HeightType = HeightfieldTypes.Float, Size = size, + HeightRange = range, + HeightScale = scale, Floats = data as float[], }; } @@ -57,6 +65,8 @@ public static Heightmap Create(Int2 size, T[] data) where T : struct { HeightType = HeightfieldTypes.Short, Size = size, + HeightRange = range, + HeightScale = scale, Shorts = data as short[], }; } @@ -66,6 +76,8 @@ public static Heightmap Create(Int2 size, T[] data) where T : struct { HeightType = HeightfieldTypes.Byte, Size = size, + HeightRange = range, + HeightScale = scale, Bytes = data as byte[], }; } diff --git a/sources/engine/Xenko.Physics/HeightScale.cs b/sources/engine/Xenko.Physics/HeightScale.cs deleted file mode 100644 index 330d90672d..0000000000 --- a/sources/engine/Xenko.Physics/HeightScale.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; -using Xenko.Core; - -namespace Xenko.Physics -{ - [DataContract] - [Display("Value")] - public class HeightScale : IHeightScale - { - [DataMember(10)] - public float Scale { get; set; } = 1f; - - public float CalculateHeightScale(HeightfieldColliderShapeDesc desc) - { - return Scale; - } - - public bool Match(object obj) - { - var other = obj as HeightScale; - - if (other == null) - { - return false; - } - - return Math.Abs(other.Scale - Scale) < float.Epsilon; - } - } -} diff --git a/sources/engine/Xenko.Physics/HeightScaleFromHeightRange.cs b/sources/engine/Xenko.Physics/HeightScaleFromHeightRange.cs deleted file mode 100644 index 73ee33a19e..0000000000 --- a/sources/engine/Xenko.Physics/HeightScaleFromHeightRange.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; -using Xenko.Core; - -namespace Xenko.Physics -{ - [DataContract] - [Display("Adjust in range")] - public class HeightScaleFromHeightRange : IHeightScale - { - public float CalculateHeightScale(HeightfieldColliderShapeDesc desc) - { - if (desc.InitialHeights == null) - { - return 0; - } - - switch (desc.InitialHeights.HeightType) - { - case HeightfieldTypes.Float: - return 1f; - - case HeightfieldTypes.Short: - return Math.Max(Math.Abs(desc.HeightRange.X), Math.Abs(desc.HeightRange.Y)) / short.MaxValue; - - case HeightfieldTypes.Byte: - if (Math.Abs(desc.HeightRange.X) <= Math.Abs(desc.HeightRange.Y)) - { - return desc.HeightRange.Y / byte.MaxValue; - } - else - { - return desc.HeightRange.X / byte.MaxValue; - } - - default: - return 0f; - } - } - - public bool Match(object obj) - { - var other = obj as HeightScaleFromHeightRange; - - if (other == null) - { - return false; - } - - return true; - } - } -} diff --git a/sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs b/sources/engine/Xenko.Physics/HeightfieldHeightDataFromHeightmap.cs similarity index 64% rename from sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs rename to sources/engine/Xenko.Physics/HeightfieldHeightDataFromHeightmap.cs index ebe3f6e56d..cf1d24a6fe 100644 --- a/sources/engine/Xenko.Physics/HeightDataFromHeightmap.cs +++ b/sources/engine/Xenko.Physics/HeightfieldHeightDataFromHeightmap.cs @@ -7,29 +7,35 @@ namespace Xenko.Physics { [DataContract] [Display("Heightmap")] - public class HeightDataFromHeightmap : IInitialHeightData + public class HeightfieldHeightDataFromHeightmap : IInitialHeightfieldHeightData { [DataMember(10)] public Heightmap Heightmap { get; set; } - [Display(Browsable = false)] + [DataMemberIgnore] public HeightfieldTypes HeightType => Heightmap?.HeightType ?? default; - [Display(Browsable = false)] + [DataMemberIgnore] public Int2 HeightStickSize => Heightmap?.Size ?? default; - [Display(Browsable = false)] + [DataMemberIgnore] + public Vector2 HeightRange => Heightmap?.HeightRange ?? default; + + [DataMemberIgnore] + public float HeightScale => Heightmap?.HeightScale ?? default; + + [DataMemberIgnore] public float[] Floats => Heightmap?.Floats; - [Display(Browsable = false)] + [DataMemberIgnore] public short[] Shorts => Heightmap?.Shorts; - [Display(Browsable = false)] + [DataMemberIgnore] public byte[] Bytes => Heightmap?.Bytes; public bool Match(object obj) { - var other = obj as HeightDataFromHeightmap; + var other = obj as HeightfieldHeightDataFromHeightmap; if (other == null) { diff --git a/sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculator.cs b/sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculator.cs new file mode 100644 index 0000000000..6e18f14f65 --- /dev/null +++ b/sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculator.cs @@ -0,0 +1,39 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core; + +namespace Xenko.Physics +{ + [DataContract] + [Display("Fit in range")] + public class HeightfieldHeightScaleCalculator : IHeightfieldHeightScaleCalculator + { + public float Calculate(IHeightfieldHeightDescription heightDescription) + { + var heightRange = heightDescription.HeightRange; + + switch (heightDescription.HeightType) + { + case HeightfieldTypes.Float: + return 1f; + + case HeightfieldTypes.Short: + return Math.Max(Math.Abs(heightRange.X), Math.Abs(heightRange.Y)) / short.MaxValue; + + case HeightfieldTypes.Byte: + if (Math.Abs(heightRange.X) <= Math.Abs(heightRange.Y)) + { + return heightRange.Y / byte.MaxValue; + } + else + { + return heightRange.X / byte.MaxValue; + } + + default: + return 1f; + } + } + } +} diff --git a/sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculatorWithValue.cs b/sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculatorWithValue.cs new file mode 100644 index 0000000000..9eefaa16a2 --- /dev/null +++ b/sources/engine/Xenko.Physics/HeightfieldHeightScaleCalculatorWithValue.cs @@ -0,0 +1,16 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core; + +namespace Xenko.Physics +{ + [DataContract] + [Display("Value")] + public class HeightfieldHeightScaleCalculatorWithValue : IHeightfieldHeightScaleCalculator + { + [DataMember(10)] + public float Value { get; set; } = 1f; + + public float Calculate(IHeightfieldHeightDescription heightDescription) => Value; + } +} diff --git a/sources/engine/Xenko.Physics/IHeightfieldHeightDescription.cs b/sources/engine/Xenko.Physics/IHeightfieldHeightDescription.cs new file mode 100644 index 0000000000..6f96a69298 --- /dev/null +++ b/sources/engine/Xenko.Physics/IHeightfieldHeightDescription.cs @@ -0,0 +1,15 @@ +// Copyright (c) Xenko contributors (https://xenko.com) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core.Mathematics; + +namespace Xenko.Physics +{ + public interface IHeightfieldHeightDescription + { + HeightfieldTypes HeightType { get; } + + Vector2 HeightRange { get; } + + float HeightScale { get; } + } +} diff --git a/sources/engine/Xenko.Physics/IHeightScale.cs b/sources/engine/Xenko.Physics/IHeightfieldHeightScaleCalculator.cs similarity index 59% rename from sources/engine/Xenko.Physics/IHeightScale.cs rename to sources/engine/Xenko.Physics/IHeightfieldHeightScaleCalculator.cs index 701411aa2b..7794d50f44 100644 --- a/sources/engine/Xenko.Physics/IHeightScale.cs +++ b/sources/engine/Xenko.Physics/IHeightfieldHeightScaleCalculator.cs @@ -3,10 +3,8 @@ namespace Xenko.Physics { - public interface IHeightScale + public interface IHeightfieldHeightScaleCalculator { - float CalculateHeightScale(HeightfieldColliderShapeDesc desc); - - bool Match(object obj); + float Calculate(IHeightfieldHeightDescription heightDescription); } } diff --git a/sources/engine/Xenko.Physics/IInitialHeightData.cs b/sources/engine/Xenko.Physics/IInitialHeightfieldHeightData.cs similarity index 82% rename from sources/engine/Xenko.Physics/IInitialHeightData.cs rename to sources/engine/Xenko.Physics/IInitialHeightfieldHeightData.cs index 32087fb40a..5610a3c7fe 100644 --- a/sources/engine/Xenko.Physics/IInitialHeightData.cs +++ b/sources/engine/Xenko.Physics/IInitialHeightfieldHeightData.cs @@ -4,10 +4,8 @@ namespace Xenko.Physics { - public interface IInitialHeightData + public interface IInitialHeightfieldHeightData : IHeightfieldHeightDescription { - HeightfieldTypes HeightType { get; } - Int2 HeightStickSize { get; } float[] Floats { get; } From 4a20931a880ac9ab092a973728739c2b77a199c7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 19 Jan 2020 12:03:25 -0500 Subject: [PATCH 0647/2038] Audio: fixes, including reusing listeners between scene changes --- .../engine/Xenko.Audio/DynamicSoundSource.cs | 23 ------------------- sources/engine/Xenko.Audio/SoundInstance.cs | 10 +++++++- .../Audio/AudioListenerProcessor.cs | 18 +++++++++++++-- .../Engine/AudioListenerComponent.cs | 3 +++ .../Xenko.Engine/Engine/GlobalSoundManager.cs | 20 +++++++++------- 5 files changed, 40 insertions(+), 34 deletions(-) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 5360639bb5..43e29366dd 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -268,24 +268,6 @@ protected virtual void DisposeInternal() isInitialized = false; } - private void Rebuffer() - { - int numberOfBuffers = deviceBuffers.Count; - - for (int i = 0; i < numberOfBuffers; i++) - AudioLayer.BufferDestroy(deviceBuffers[i]); - - deviceBuffers.Clear(); - freeBuffers.Clear(); - - for (var i = 0; i < numberOfBuffers; i++) - { - var buffer = AudioLayer.BufferCreate(nativeBufferSizeBytes); - deviceBuffers.Add(buffer); - freeBuffers.Enqueue(deviceBuffers[i]); - } - } - /// /// If CanFillis true with this method you can fill the next free buffer /// @@ -423,11 +405,6 @@ private static unsafe void Worker() { source.ExtractAndFillData(); } - else if (AudioLayer.SourceIsPlaying(source.soundInstance.Source) == false) - { - // hmm, state and source do not match up.. lets try and get it playing! - source.Rebuffer(); - } } } diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index bfbd1993b4..9eb415ae09 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -127,6 +127,8 @@ public float Pan get => pan; set { + if (pan == value) return; + pan = value; if (engine.State == AudioEngineState.Invalidated) @@ -145,6 +147,8 @@ public float Volume get => volume; set { + if (volume == value) return; + volume = value; if (engine.State == AudioEngineState.Invalidated) @@ -162,6 +166,8 @@ public float Pitch get => pitch; set { + if (pitch == value) return; + pitch = value; if (engine.State == AudioEngineState.Invalidated) @@ -369,9 +375,11 @@ public PlayState PlayState if (engine.State == AudioEngineState.Invalidated) return PlayState.Stopped; - if (soundSource == null && playState == PlayState.Playing && AudioLayer.SourceIsPlaying(Source) == false) + if (soundSource == null && playState == PlayState.Playing && isLooping == false && + AudioLayer.SourceIsPlaying(Source) == false) { // non-streamed sound stopped playing + AudioLayer.SourceStop(Source); playState = PlayState.Stopped; } diff --git a/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs b/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs index b5106a9723..a5ce5a521d 100644 --- a/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs +++ b/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs @@ -47,7 +47,14 @@ protected internal override void OnSystemRemove() protected override void OnEntityComponentAdding(Entity entity, AudioListenerComponent component, AudioListenerComponent data) { - component.Listener = new AudioListener(audioSystem.AudioEngine); + if (component.Listener == null) + { + component.Listener = new AudioListener(audioSystem.AudioEngine); + } + else + { + AudioLayer.ListenerEnable(component.Listener.Listener); + } audioSystem.Listeners.Add(component, component.Listener); } @@ -56,7 +63,14 @@ protected override void OnEntityComponentRemoved(Entity entity, AudioListenerCom { audioSystem.Listeners.Remove(component); - component.Listener.Dispose(); + if (component.DoNotDispose) + { + AudioLayer.ListenerDisable(component.Listener.Listener); + } + else + { + component.Listener.Dispose(); + } } public override void Draw(RenderContext context) diff --git a/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs b/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs index f599d5ae07..905a2085bb 100644 --- a/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs @@ -25,5 +25,8 @@ public sealed class AudioListenerComponent : ActivableEntityComponent { [DataMemberIgnore] internal AudioListener Listener; + + [DataMember] + public bool DoNotDispose = false; } } diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 00a41356f6..a6c7706b0f 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -23,14 +23,6 @@ namespace Xenko.Engine [ComponentCategory("Audio")] public sealed class GlobalSoundManager : ActivableEntityComponent { - private struct PositionalSound - { - public SoundInstance soundInstance; - public Entity entity; - public Vector3 pos; - public float distance_scale; - } - [DataMember] public float MaxSoundDistance = 48f; @@ -196,7 +188,11 @@ private AudioListenerComponent Listener if (_listener == null) throw new InvalidOperationException("Could not find an Audio Listener Component in scene!"); + + // make sure this listener is set to recycle itself + _listener.DoNotDispose = true; } + return _listener; } set @@ -267,5 +263,13 @@ private SoundInstance getFreeInstance(string url, bool spatialized) Sounds[url] = snd2; return si; } + + private struct PositionalSound + { + public SoundInstance soundInstance; + public Entity entity; + public Vector3 pos; + public float distance_scale; + } } } From fdeeb0361d78301d2b34dabe95dc2f52e76a9da5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 19 Jan 2020 19:11:05 -0500 Subject: [PATCH 0648/2038] Audio: more fixes for listeners being used across scenes --- sources/engine/Xenko.Audio/SoundInstance.cs | 2 -- .../Audio/AudioListenerProcessor.cs | 20 ++++++++---- .../Engine/AudioListenerComponent.cs | 6 ++-- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 32 +++++-------------- 4 files changed, 25 insertions(+), 35 deletions(-) diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index 9eb415ae09..41a717b271 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -231,8 +231,6 @@ public void Apply3D(Vector3 Position, Vector3? velocity = null, Quaternion? dire if (engine.State == AudioEngineState.Invalidated) return; - if (!spatialized) return; - AudioLayer.SourcePush3D(Source, ref Position, ref dir, ref up, ref vel, ref m); } diff --git a/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs b/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs index a5ce5a521d..80d61363ff 100644 --- a/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs +++ b/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs @@ -47,25 +47,33 @@ protected internal override void OnSystemRemove() protected override void OnEntityComponentAdding(Entity entity, AudioListenerComponent component, AudioListenerComponent data) { - if (component.Listener == null) + if (AudioListenerComponent.UseSharedListener) { - component.Listener = new AudioListener(audioSystem.AudioEngine); + if (AudioListenerComponent.SharedListener == null) + AudioListenerComponent.SharedListener = new AudioListener(audioSystem.AudioEngine); + else + AudioLayer.ListenerEnable(AudioListenerComponent.SharedListener.Listener); + + component.Listener = AudioListenerComponent.SharedListener; } else { - AudioLayer.ListenerEnable(component.Listener.Listener); + component.Listener = new AudioListener(audioSystem.AudioEngine); } - audioSystem.Listeners.Add(component, component.Listener); + audioSystem.Listeners[component] = component.Listener; } protected override void OnEntityComponentRemoved(Entity entity, AudioListenerComponent component, AudioListenerComponent data) { audioSystem.Listeners.Remove(component); - if (component.DoNotDispose) + if (AudioListenerComponent.UseSharedListener) { - AudioLayer.ListenerDisable(component.Listener.Listener); + if (AudioListenerComponent.SharedListener == null) + AudioListenerComponent.SharedListener = component.Listener; + + AudioLayer.ListenerDisable(AudioListenerComponent.SharedListener.Listener); } else { diff --git a/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs b/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs index 905a2085bb..e11b6a8dfd 100644 --- a/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs @@ -23,10 +23,10 @@ namespace Xenko.Engine [ComponentCategory("Audio")] public sealed class AudioListenerComponent : ActivableEntityComponent { + public static AudioListener SharedListener { get; internal set; } + public static bool UseSharedListener; + [DataMemberIgnore] internal AudioListener Listener; - - [DataMember] - public bool DoNotDispose = false; } } diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index a6c7706b0f..68cbeb8130 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -3,13 +3,9 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; using Xenko.Audio; using Xenko.Core; -using Xenko.Core.Annotations; -using Xenko.Core.Collections; using Xenko.Core.Mathematics; -using Xenko.Engine.Design; using Xenko.Games; namespace Xenko.Engine @@ -152,16 +148,12 @@ public void Reset() instances.Clear(); } - private Game game + public GlobalSoundManager() { - get - { - // don't have this sound... try loading it! - if (internalGame == null) - internalGame = ServiceRegistry.instance?.GetService() as Game; - - return internalGame; - } + // global sound manager relies on listeners being shared, so everything can be + // safely reused + AudioListenerComponent.UseSharedListener = true; + internalGame = ServiceRegistry.instance?.GetService() as Game; } [DataMemberIgnore] @@ -169,15 +161,10 @@ private AudioListenerComponent Listener { get { - Game g = game; - - if (g == null) - throw new InvalidOperationException("No Game object has been fully initialized yet!"); - - if (_listener == null || _listener.Enabled == false || g.Audio.Listeners.ContainsKey(_listener) == false) + if (_listener == null || _listener.Enabled == false || internalGame.Audio.Listeners.ContainsKey(_listener) == false) { // find a valid listener! - foreach (AudioListenerComponent alc in g.Audio.Listeners.Keys) + foreach (AudioListenerComponent alc in internalGame.Audio.Listeners.Keys) { if (alc.Enabled) { @@ -188,9 +175,6 @@ private AudioListenerComponent Listener if (_listener == null) throw new InvalidOperationException("Could not find an Audio Listener Component in scene!"); - - // make sure this listener is set to recycle itself - _listener.DoNotDispose = true; } return _listener; @@ -251,7 +235,7 @@ private SoundInstance getFreeInstance(string url, bool spatialized) } // this might throw an exception if you provided a bad url - Sound snd2 = game.Content.Load(url); + Sound snd2 = internalGame.Content.Load(url); if (!snd2.Spatialized && spatialized) throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); From 925a29f181b33689fd1b632734e5690d88e1a079 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 20 Jan 2020 11:03:38 -0500 Subject: [PATCH 0649/2038] Audio: more specific/limited use of SourceFlushBuffers (stability fix) --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 43e29366dd..dd5fb310d8 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -201,7 +201,6 @@ protected virtual void UpdateInternal() { } /// protected virtual void RestartInternal() { - AudioLayer.SourceFlushBuffers(soundInstance.Source); ReadyToPlay.TrySetResult(false); ReadyToPlay = new TaskCompletionSource(); readyToPlay = false; @@ -247,6 +246,7 @@ protected virtual void StopInternal(bool ignoreQueuedBuffer = true) soundInstance.playState = PlayState.Stopped; if (ignoreQueuedBuffer) AudioLayer.SourceStop(soundInstance.Source); + else AudioLayer.SourceFlushBuffers(soundInstance.Source); RestartInternal(); } From 5936aff641e4935ad9c4132d6f90c0e35da1065f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 21 Jan 2020 14:57:39 -0500 Subject: [PATCH 0650/2038] Physics: better handling of multithreaded physics --- deps/bepuphysics2/BepuPhysics.dll | 4 +- deps/bepuphysics2/BepuPhysics.pdb | 4 +- deps/bepuphysics2/Debug/BepuPhysics.dll | 4 +- deps/bepuphysics2/Debug/BepuPhysics.pdb | 4 +- deps/bepuphysics2/Release/BepuPhysics.dll | 4 +- deps/bepuphysics2/Release/BepuPhysics.pdb | 4 +- .../Bepu/BepuRigidbodyComponent.cs | 109 ++++++++++++++---- .../Xenko.Physics/Bepu/BepuShapeTest.cs | 15 ++- sources/engine/Xenko.Physics/PhysicsSystem.cs | 18 ++- 9 files changed, 126 insertions(+), 40 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index a03b571685..58b9319470 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:db5d18c30b319d663a660c6b0fa4bb4c0fd0252f77594e399c04909225520425 -size 714240 +oid sha256:6c60bd89b4ac7f5fdf18b5f09f0dc978366a7613b38b166837cc7a499b9dde01 +size 708608 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index 2e37787389..0c6e873277 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c732eae915202c17c79c0367da9ecb579b5a2fcf8059d3f819be1f128768b559 -size 309228 +oid sha256:4b638db41da657824628fec05bcfe03cdebda786e51afccc7f35e8af1891640d +size 307480 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.dll b/deps/bepuphysics2/Debug/BepuPhysics.dll index 45255e949a..3bbf79f35b 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.dll +++ b/deps/bepuphysics2/Debug/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:9d5001dfc4427d2bdd6b0379111543f1c643db5fcf2c9bae994f694799f2860e -size 815104 +oid sha256:96a22f075a7faa9f3701c95aaba0888d3cc3f8d9a19be6c8ac3a52f8fa626321 +size 811008 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.pdb b/deps/bepuphysics2/Debug/BepuPhysics.pdb index b8d502102b..a8a4c5b7a4 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.pdb +++ b/deps/bepuphysics2/Debug/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:13917b9e6a0a63719b062f10ec7f124c6cc6c0515b9cb140f685858959420743 -size 404008 +oid sha256:3766cee8f17df38ebfa762c388acb0c46454f8adb36a16f5d36cab3573de5753 +size 401520 diff --git a/deps/bepuphysics2/Release/BepuPhysics.dll b/deps/bepuphysics2/Release/BepuPhysics.dll index a03b571685..58b9319470 100644 --- a/deps/bepuphysics2/Release/BepuPhysics.dll +++ b/deps/bepuphysics2/Release/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:db5d18c30b319d663a660c6b0fa4bb4c0fd0252f77594e399c04909225520425 -size 714240 +oid sha256:6c60bd89b4ac7f5fdf18b5f09f0dc978366a7613b38b166837cc7a499b9dde01 +size 708608 diff --git a/deps/bepuphysics2/Release/BepuPhysics.pdb b/deps/bepuphysics2/Release/BepuPhysics.pdb index 2e37787389..0c6e873277 100644 --- a/deps/bepuphysics2/Release/BepuPhysics.pdb +++ b/deps/bepuphysics2/Release/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:c732eae915202c17c79c0367da9ecb579b5a2fcf8059d3f819be1f128768b559 -size 309228 +oid sha256:4b638db41da657824628fec05bcfe03cdebda786e51afccc7f35e8af1891640d +size 307480 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index aafe50a980..9a074a551f 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -16,6 +16,7 @@ using BepuPhysics.Constraints; using System.Runtime.CompilerServices; using Xenko.Core.Threading; +using System.Threading; namespace Xenko.Physics.Bepu { @@ -55,6 +56,24 @@ public ref BodyReference InternalBody [DataMemberIgnore] public Action ActionPerSimulationTick; + internal bool wasAwake; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private void SafeRun(Action dome) + { + if (PhysicsSystem.IsSimulationThread(Thread.CurrentThread)) + { + dome(); + } + else + { + BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue((time) => + { + dome(); + }); + } + } + /// /// Gets a value indicating whether this instance is active (awake). /// @@ -66,16 +85,14 @@ public bool IsActive { get { - return AddedToScene && InternalBody.Awake; + return AddedToScene && (PhysicsSystem.IsSimulationThread(Thread.CurrentThread) ? InternalBody.Awake : wasAwake); } set { if (IsActive == value) return; - BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue((time) => - { - InternalBody.Awake = value; - }); + wasAwake = value; + SafeRun(delegate { InternalBody.Awake = value; }); } } @@ -98,7 +115,9 @@ public float CcdMotionThreshold bodyDescription.Collidable.Continuity.MinimumSweepTimestep = value > 0 ? 1e-3f : 0f; if (AddedToScene) - InternalBody.SetCollidable(bodyDescription.Collidable); + { + SafeRun(delegate { InternalBody.Collidable.Continuity = bodyDescription.Collidable.Continuity; }); + } } } @@ -149,6 +168,12 @@ public bool CollectCollisions } } + /// + /// If we are storing collisions, which one is the strongest one? This uses normals and velocity to determine. + /// + [DataMemberIgnore] + public int StrongestCollisionIndex; + [DataMemberIgnore] private bool _collectCollisions = false; @@ -243,7 +268,9 @@ public float SleepThreshold bodyDescription.Activity.SleepThreshold = value; if (AddedToScene) - InternalBody.SetActivity(bodyDescription.Activity); + { + SafeRun(delegate { InternalBody.Activity.SleepThreshold = value; }); + } } } @@ -323,7 +350,9 @@ private void UpdateInertia(bool skipset = false) } if (skipset == false && AddedToScene) - InternalBody.LocalInertia = bodyDescription.LocalInertia; + { + SafeRun(delegate { InternalBody.LocalInertia = bodyDescription.LocalInertia; }); + } } [DataMember] @@ -337,7 +366,9 @@ public override float SpeculativeMargin bodyDescription.Collidable.SpeculativeMargin = value; if (AddedToScene) - InternalBody.SetCollidable(bodyDescription.Collidable); + { + SafeRun(delegate { InternalBody.Collidable.SpeculativeMargin = value; }); + } } } @@ -355,8 +386,7 @@ public override IShape ColliderShape UpdateInertia(true); - BepuSimulation.instance.ActionsBeforeSimulationStep.Enqueue((time) => - { + SafeRun(delegate { BepuSimulation bs = BepuSimulation.instance; // don't worry about switching if we are to be removed @@ -502,7 +532,7 @@ public override bool AddedToScene public void ApplyImpulse(Vector3 impulse) { if (AddedToScene) - InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); + SafeRun(delegate { InternalBody.ApplyLinearImpulse(BepuHelpers.ToBepu(impulse)); }); } /// @@ -513,7 +543,7 @@ public void ApplyImpulse(Vector3 impulse) public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) { if (AddedToScene) - InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); + SafeRun(delegate { InternalBody.ApplyImpulse(BepuHelpers.ToBepu(impulse), BepuHelpers.ToBepu(localOffset)); }); } /// @@ -523,7 +553,7 @@ public void ApplyImpulse(Vector3 impulse, Vector3 localOffset) public void ApplyTorqueImpulse(Vector3 torque) { if (AddedToScene) - InternalBody.ApplyAngularImpulse(BepuHelpers.ToBepu(torque)); + SafeRun(delegate { InternalBody.ApplyAngularImpulse(BepuHelpers.ToBepu(torque)); }); } [DataMemberIgnore] @@ -531,7 +561,7 @@ public override Vector3 Position { get { - return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Pose.Position : bodyDescription.Pose.Position); + return BepuHelpers.ToXenko(AddedToScene && PhysicsSystem.IsSimulationThread(Thread.CurrentThread) ? InternalBody.Pose.Position : bodyDescription.Pose.Position); } set { @@ -542,7 +572,11 @@ public override Vector3 Position bodyDescription.Pose.Position.Z = value.Z; if (AddedToScene) - InternalBody.SetPosition(bodyDescription.Pose.Position); + SafeRun(delegate { + InternalBody.Pose.Position.X = value.X; + InternalBody.Pose.Position.Y = value.Y; + InternalBody.Pose.Position.Z = value.Z; + }); } } @@ -551,7 +585,7 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { get { - return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); + return BepuHelpers.ToXenko(AddedToScene && PhysicsSystem.IsSimulationThread(Thread.CurrentThread) ? InternalBody.Pose.Orientation : bodyDescription.Pose.Orientation); } set { @@ -563,7 +597,12 @@ public override Xenko.Core.Mathematics.Quaternion Rotation bodyDescription.Pose.Orientation.W = value.W; if (AddedToScene) - InternalBody.SetRotation(bodyDescription.Pose.Orientation); + SafeRun(delegate { + InternalBody.Pose.Orientation.X = value.X; + InternalBody.Pose.Orientation.Y = value.Y; + InternalBody.Pose.Orientation.Z = value.Z; + InternalBody.Pose.Orientation.W = value.W; + }); } } @@ -578,7 +617,7 @@ public Vector3 AngularVelocity { get { - return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Velocity.Angular : bodyDescription.Velocity.Angular); + return BepuHelpers.ToXenko(AddedToScene && PhysicsSystem.IsSimulationThread(Thread.CurrentThread) ? InternalBody.Velocity.Angular : bodyDescription.Velocity.Angular); } set { @@ -589,7 +628,11 @@ public Vector3 AngularVelocity bodyDescription.Velocity.Angular.Z = value.Z; if (AddedToScene) - InternalBody.SetAngularVelocity(bodyDescription.Velocity.Angular); + SafeRun(delegate { + InternalBody.Velocity.Angular.X = value.X; + InternalBody.Velocity.Angular.Y = value.Y; + InternalBody.Velocity.Angular.Z = value.Z; + }); } } @@ -604,7 +647,7 @@ public Vector3 LinearVelocity { get { - return BepuHelpers.ToXenko(AddedToScene ? InternalBody.Velocity.Linear : bodyDescription.Velocity.Linear); + return BepuHelpers.ToXenko(AddedToScene && PhysicsSystem.IsSimulationThread(Thread.CurrentThread) ? InternalBody.Velocity.Linear : bodyDescription.Velocity.Linear); } set { @@ -615,7 +658,11 @@ public Vector3 LinearVelocity bodyDescription.Velocity.Linear.Z = value.Z; if (AddedToScene) - InternalBody.SetLinearVelocity(bodyDescription.Velocity.Linear); + SafeRun(delegate { + InternalBody.Velocity.Linear.X = value.X; + InternalBody.Velocity.Linear.Y = value.Y; + InternalBody.Velocity.Linear.Z = value.Z; + }); } } @@ -628,10 +675,28 @@ public Vector3 LinearVelocity [DataMemberIgnore] public Vector3? LocalPhysicsOffset = null; + [DataMemberIgnore] + public Vector3 VelocityLinearChange { get; private set; } + + [DataMemberIgnore] + public Vector3 VelocityAngularChange { get; private set; } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal void UpdateCachedPoseAndVelocity() + { + ref BodyVelocity bv = ref InternalBody.Velocity; + VelocityLinearChange = BepuHelpers.ToXenko(bv.Linear - bodyDescription.Velocity.Linear); + VelocityAngularChange = BepuHelpers.ToXenko(bv.Angular - bodyDescription.Velocity.Angular); + bodyDescription.Velocity = bv; + bodyDescription.Pose = InternalBody.Pose; + wasAwake = InternalBody.Awake; + } + /// /// Updades the graphics transformation from the given physics transformation /// /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void UpdateTransformationComponent() { var entity = Entity; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs index 2da8c8c373..2ac73f6715 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs @@ -83,20 +83,28 @@ public bool LoopBody(CollidableReference reference) /// Pose of the query shape. /// Id to use to refer to this query when the collision batcher finishes processing it. /// Batcher to add the query's tests to. - static private unsafe void AddQueryToBatch(int queryShapeType, void* queryShapeData, int queryShapeSize, in Vector3 queryBoundsMin, + static private unsafe void RunQuery(int queryShapeType, void* queryShapeData, int queryShapeSize, in Vector3 queryBoundsMin, in Vector3 queryBoundsMax, Vector3 queryPos, BepuUtilities.Quaternion queryRot, ref CollisionBatcher batcher, CollisionFilterGroupFlags lookingFor) { var broadPhaseEnumerator = new BroadPhaseOverlapEnumerator { components = new List(), lookingFor = (uint)lookingFor }; BepuSimulation.instance.internalSimulation.BroadPhase.GetOverlaps(queryBoundsMin, queryBoundsMax, ref broadPhaseEnumerator); + BepuUtilities.Memory.Buffer[] shapeMemories = new BepuUtilities.Memory.Buffer[broadPhaseEnumerator.components.Count]; for (int overlapIndex = 0; overlapIndex < broadPhaseEnumerator.components.Count; ++overlapIndex) { BepuPhysicsComponent bpc = broadPhaseEnumerator.components[overlapIndex]; batcher.CacheShapeB(bpc.ColliderShape.TypeId, queryShapeType, queryShapeData, queryShapeSize, out var cachedQueryShapeData); + batcher.Pool.Take(bpc.ColliderShape.GetSize(), out shapeMemories[overlapIndex]); + bpc.ColliderShape.CopyData(shapeMemories[overlapIndex].Memory); batcher.AddDirectly(bpc.ColliderShape.TypeId, queryShapeType, - bpc.ColliderShape.GetPointer(), cachedQueryShapeData, + shapeMemories[overlapIndex].Memory, cachedQueryShapeData, queryPos - BepuHelpers.ToBepu(bpc.Position), queryRot, BepuHelpers.ToBepu(bpc.Rotation), 0, new PairContinuation(0)); } + // do it if we haven't already + batcher.Flush(); + // free memory used + for (int i = 0; i < shapeMemories.Length; i++) + batcher.Pool.Return(ref shapeMemories[i]); } /// @@ -119,8 +127,7 @@ static public unsafe List SingleQuery(TShape shape, Xenko.C boundingBoxMax += v; using(BepuSimulation.instance.simulationLocker.ReadLock()) { - AddQueryToBatch(shape.TypeId, Unsafe.AsPointer(ref shape), shape.GetSize(), boundingBoxMin, boundingBoxMax, v, q, ref batcher, lookingFor); - batcher.Flush(); + RunQuery(shape.TypeId, Unsafe.AsPointer(ref shape), shape.GetSize(), boundingBoxMin, boundingBoxMax, v, q, ref batcher, lookingFor); } return contacts; } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index b2feb3d852..bd908d6376 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.CompilerServices; using System.Threading; using Xenko.Core; using Xenko.Engine; @@ -25,6 +26,7 @@ private class PhysicsScene private bool runThread; private ManualResetEventSlim doUpdateEvent; private Thread physicsThread; + private static Thread simulationThread; public static int MaxSubSteps = 2; public static float MaximumSimulationTime = 0.025f; @@ -49,6 +51,12 @@ public bool isMultithreaded } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsSimulationThread(Thread t) + { + return t == simulationThread; + } + public override void Initialize() { physicsConfiguration = Game?.Settings != null ? Game.Settings.Configurations.Get() : new PhysicsSettings(); @@ -62,8 +70,13 @@ public override void Initialize() physicsThread = new Thread(new ThreadStart(PhysicsProcessingThreadBody)); physicsThread.Name = "BulletPhysics Processing Thread"; physicsThread.IsBackground = true; + simulationThread = physicsThread; physicsThread.Start(); } + else + { + simulationThread = Thread.CurrentThread; + } } private void EndThread() @@ -188,18 +201,19 @@ private void RunPhysicsSimulation(float time) } // update all rigidbodies - for (int j = 0; j < physicsScene.BepuSimulation.AllRigidbodies.Count; j++) + Xenko.Core.Threading.Dispatcher.For(0, physicsScene.BepuSimulation.AllRigidbodies.Count, (j) => { BepuRigidbodyComponent rb = physicsScene.BepuSimulation.AllRigidbodies[j]; rb.swapProcessingContactsList(); + rb.UpdateCachedPoseAndVelocity(); // per-rigidbody update if (rb.ActionPerSimulationTick != null) rb.ActionPerSimulationTick(rb, time); rb.UpdateTransformationComponent(); - } + }); } } } From a6d3072fc92208fdc7e22273da12bed898a3f5f2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 22 Jan 2020 12:30:19 -0500 Subject: [PATCH 0651/2038] Physics: Bepu physics now uses Xenko's thread dispatcher --- .../core/Xenko.Core/Threading/ThreadPool.cs | 4 +- .../Bepu/BepuSimpleThreadDispatcher.cs | 99 +++---------------- .../Xenko.Physics/Bepu/BepuSimulation.cs | 3 +- 3 files changed, 21 insertions(+), 85 deletions(-) diff --git a/sources/core/Xenko.Core/Threading/ThreadPool.cs b/sources/core/Xenko.Core/Threading/ThreadPool.cs index cdc96ca12d..d550720d19 100644 --- a/sources/core/Xenko.Core/Threading/ThreadPool.cs +++ b/sources/core/Xenko.Core/Threading/ThreadPool.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Xenko.Core.Annotations; @@ -12,7 +13,7 @@ namespace Xenko.Core.Threading /// /// Thread pool for scheduling actions. /// - internal class ThreadPool + public class ThreadPool { public static readonly ThreadPool Instance = new ThreadPool(); @@ -30,6 +31,7 @@ public ThreadPool() new Task(cachedTaskLoop, null, TaskCreationOptions.LongRunning).Start(); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void QueueWorkItem([NotNull] [Pooled] Action workItem) { PooledDelegateHelper.AddReference(workItem); diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs index b952e1dea9..426e70f904 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimpleThreadDispatcher.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text; using System.Threading; using BepuUtilities; @@ -9,107 +10,39 @@ namespace Xenko.Physics.Engine { internal class BepuSimpleThreadDispatcher : IThreadDispatcher, IDisposable { - int threadCount; - public int ThreadCount => threadCount; - struct Worker - { - public Thread Thread; - public AutoResetEvent Signal; - } - - Worker[] workers; - AutoResetEvent finished; - - BufferPool[] bufferPools; - - public BepuSimpleThreadDispatcher(int threadCount) - { - this.threadCount = threadCount; - workers = new Worker[threadCount - 1]; - for (int i = 0; i < workers.Length; ++i) - { - workers[i] = new Worker { Thread = new Thread(WorkerLoop), Signal = new AutoResetEvent(false) }; - workers[i].Thread.IsBackground = true; - workers[i].Thread.Start(workers[i].Signal); - } - finished = new AutoResetEvent(false); - bufferPools = new BufferPool[threadCount]; - for (int i = 0; i < bufferPools.Length; ++i) - { - bufferPools[i] = new BufferPool(); - } - } - - void DispatchThread(int workerIndex) - { - //Debug.Assert(workerBody != null); - workerBody(workerIndex); - - if (Interlocked.Increment(ref completedWorkerCounter) == threadCount) - { - finished.Set(); - } - } - - volatile Action workerBody; - int workerIndex; - int completedWorkerCounter; + public int ThreadCount => Environment.ProcessorCount; + private BepuUtilities.Memory.BufferPool[] buffers; - void WorkerLoop(object untypedSignal) + public BepuSimpleThreadDispatcher() { - var signal = (AutoResetEvent)untypedSignal; - while (true) + buffers = new BufferPool[ThreadCount]; + for (int i=0; i workerBody) { - //Debug.Assert(this.workerBody == null); - workerIndex = 1; //Just make the inline thread worker 0. While the other threads might start executing first, the user should never rely on the dispatch order. - completedWorkerCounter = 0; - this.workerBody = workerBody; - SignalThreads(); - //Calling thread does work. No reason to spin up another worker and block this one! - DispatchThread(0); - finished.WaitOne(); - this.workerBody = null; + Xenko.Core.Threading.Dispatcher.For(0, ThreadCount, workerBody); } - volatile bool disposed; public void Dispose() { - if (!disposed) + for (int i = 0; i < buffers.Length; i++) { - disposed = true; - SignalThreads(); - for (int i = 0; i < bufferPools.Length; ++i) - { - bufferPools[i].Clear(); - } - foreach (var worker in workers) - { - worker.Thread.Join(); - worker.Signal.Dispose(); - } + buffers[i].Clear(); + buffers[i] = null; } + + buffers = null; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public BufferPool GetThreadMemoryPool(int workerIndex) { - return bufferPools[workerIndex]; + return buffers[workerIndex]; } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index b8b21d9001..ef4b099aaf 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -66,6 +66,7 @@ private set /// public static BufferPool safeBufferPool { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (threadStaticPool == null) @@ -82,7 +83,7 @@ public static BufferPool safeBufferPool private static List allBufferPools = new List(); internal int clearRequested; - private BepuSimpleThreadDispatcher threadDispatcher = new BepuSimpleThreadDispatcher(Environment.ProcessorCount); + private BepuSimpleThreadDispatcher threadDispatcher = new BepuSimpleThreadDispatcher(); #if DEBUG private static readonly Logger Log = GlobalLogger.GetLogger(typeof(Simulation).FullName); From 6e42a0987550486c4b94bea118b40a1585729164 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 22 Jan 2020 12:30:51 -0500 Subject: [PATCH 0652/2038] Audio: significantly reduced overhead of streaming music thread --- .../Xenko.Audio/CompressedSoundSource.cs | 4 +-- .../engine/Xenko.Audio/DynamicSoundSource.cs | 28 ++++++++----------- .../Xenko.Audio/StreamedBufferSoundSource.cs | 2 +- 3 files changed, 15 insertions(+), 19 deletions(-) diff --git a/sources/engine/Xenko.Audio/CompressedSoundSource.cs b/sources/engine/Xenko.Audio/CompressedSoundSource.cs index 915d8a8f21..6869948a5f 100644 --- a/sources/engine/Xenko.Audio/CompressedSoundSource.cs +++ b/sources/engine/Xenko.Audio/CompressedSoundSource.cs @@ -64,7 +64,7 @@ public CompressedSoundSource(SoundInstance instance, byte[] byteBuffer, int numb this.samples = numberOfSamples; playRange = new PlayRange(TimeSpan.Zero, TimeSpan.Zero); - NewSources.Add(this); + NewSources.Enqueue(this); } //========================================================================================== @@ -93,7 +93,7 @@ public CompressedSoundSource(SoundInstance instance, IVirtualFileProvider filePr this.samples = numberOfSamples; playRange = new PlayRange(TimeSpan.Zero, TimeSpan.Zero); - NewSources.Add(this); + NewSources.Enqueue(this); } /// diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index dd5fb310d8..ff55ec9533 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; using Xenko.Core; using Xenko.Core.Diagnostics; @@ -14,9 +15,9 @@ public abstract class DynamicSoundSource : IDisposable { public static Logger Logger = GlobalLogger.GetLogger(nameof(DynamicSoundSource)); - private static Task readFromDiskWorker; + private static Thread readFromDiskWorker; - protected static readonly ConcurrentBag NewSources = new ConcurrentBag(); + protected static readonly ConcurrentQueue NewSources = new ConcurrentQueue(); protected static readonly List Sources = new List(); /// @@ -95,7 +96,12 @@ protected DynamicSoundSource(SoundInstance soundInstance, int numberOfBuffers, i } if (readFromDiskWorker == null) - readFromDiskWorker = Task.Factory.StartNew(Worker, TaskCreationOptions.LongRunning); + { + readFromDiskWorker = new Thread(new ThreadStart(Worker)); + readFromDiskWorker.Priority = ThreadPriority.Lowest; + readFromDiskWorker.IsBackground = true; + readFromDiskWorker.Start(); + } } /// @@ -327,7 +333,7 @@ private static unsafe void Worker() { while (!NewSources.IsEmpty) { - if (!NewSources.TryTake(out var source)) + if (!NewSources.TryDequeue(out var source)) continue; if (!source.isInitialized) @@ -408,18 +414,8 @@ private static unsafe void Worker() } } - var buffersShouldBeFill = false; - for (int i=0; i Commands.IsEmpty && base.CanFill; From 88b8ff44d865ecc9a3c2afe5e38f6839a304eaf2 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Wed, 22 Jan 2020 12:32:13 +0100 Subject: [PATCH 0653/2038] [Core] Display info about ReflectionTypeLoadException.LoaderExceptions --- .../Xenko.Core/Diagnostics/ExceptionInfo.cs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/sources/core/Xenko.Core/Diagnostics/ExceptionInfo.cs b/sources/core/Xenko.Core/Diagnostics/ExceptionInfo.cs index 43657ed26a..e5eecc8193 100644 --- a/sources/core/Xenko.Core/Diagnostics/ExceptionInfo.cs +++ b/sources/core/Xenko.Core/Diagnostics/ExceptionInfo.cs @@ -1,6 +1,8 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using System.Linq; +using System.Reflection; using System.Text; using Xenko.Core.Annotations; @@ -12,6 +14,8 @@ namespace Xenko.Core.Diagnostics [DataContract] public sealed class ExceptionInfo { + private static readonly ExceptionInfo[] EmptyExceptions = new ExceptionInfo[0]; + /// /// Initializes a new instance of the class with default values for its properties /// @@ -30,7 +34,15 @@ public ExceptionInfo([NotNull] Exception exception) StackTrace = exception.StackTrace; TypeFullName = exception.GetType().FullName; TypeName = exception.GetType().Name; - InnerException = exception.InnerException != null ? new ExceptionInfo(exception.InnerException) : null; + + if (exception.InnerException != null) + { + InnerExceptions = new ExceptionInfo[] { new ExceptionInfo(exception.InnerException) }; + } + else if (exception is ReflectionTypeLoadException reflectionException) + { + InnerExceptions = reflectionException.LoaderExceptions.Select(x => new ExceptionInfo(x)).ToArray(); + } } /// @@ -56,7 +68,7 @@ public ExceptionInfo([NotNull] Exception exception) /// /// Gets or sets the of the inner exception. /// - public ExceptionInfo InnerException { get; set; } + public ExceptionInfo[] InnerExceptions { get; set; } = EmptyExceptions; /// public override string ToString() @@ -65,8 +77,10 @@ public override string ToString() sb.AppendLine(Message); if (StackTrace != null) sb.AppendLine(StackTrace); - if (InnerException != null) - sb.AppendFormat("Inner exception: {0}{1}", InnerException, Environment.NewLine); + foreach (var innerException in InnerExceptions) + { + sb.AppendFormat("Inner/Loader Exception: {0}{1}", innerException, Environment.NewLine); + } return sb.ToString(); } } From 82db8af2ee411f1a4d1b728a737ca9076aa00c8b Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Wed, 22 Jan 2020 22:12:56 +1100 Subject: [PATCH 0654/2038] Various fixups - See pull request conversation for details --- .../VoxelVisualizationRaw.cs | 2 +- .../VoxelVisualizationView.cs | 2 +- .../ForwardRendererVoxels.cs | 2 +- .../GraphicsCompositor/VoxelRenderFeature.cs | 61 ++++---- .../GraphicsCompositor/VoxelViewContext.cs | 18 ++- .../Voxels/Light/LightVoxelRenderer.cs | 38 +++-- .../Attributes/IVoxelAttribute.cs | 7 +- .../Attributes/VoxelAttributeBase.cs | 24 ++++ .../VoxelAttributeDirectionalCoverage.cs | 28 +--- .../VoxelAttributeEmissionOpacity.cs | 49 +++---- .../Attributes/VoxelAttributeSolidity.cs | 35 ++--- .../Shaders/VoxelAnisotropicPairedSampler.cs | 16 ++- .../VoxelAnisotropicPairedSampler.xksl | 34 +++-- .../VoxelAnisotropicPairedWriter_Float4.cs | 1 + .../VoxelAnisotropicPairedWriter_Float4.xksl | 12 +- .../Layout/Shaders/VoxelAnisotropicSampler.cs | 16 ++- .../Shaders/VoxelAnisotropicSampler.xksl | 19 ++- .../Shaders/VoxelAnisotropicWriter_Float4.cs | 1 + .../VoxelAnisotropicWriter_Float4.xksl | 18 ++- .../Layout/Shaders/VoxelIsotropicSampler.xksl | 4 - .../Layout/VoxelLayoutAnisotropic.cs | 78 ++-------- .../Layout/VoxelLayoutAnisotropicPaired.cs | 74 ++-------- .../Voxelization/Layout/VoxelLayoutBase.cs | 133 ++++++++++++++++++ .../Layout/VoxelLayoutIsotropic.cs | 110 +-------------- ...oxelModifierEmissionOpacityAntiAliasing.cs | 41 +++--- .../VoxelModifierEmissionOpacityOpacify.cs | 44 +++--- .../VoxelModifierEmissionOpacitySolidify.cs | 44 +++--- .../Voxelization/Modifiers/IVoxelModifier.cs | 18 +-- .../Modifiers/VoxelModifierBase.cs | 18 ++- .../Voxels/Voxelization/RenderVoxelVolume.cs | 8 +- .../Processing/BufferToTexture.xksl | 36 ++++- .../Processing/BufferToTextureEffect.cs | 32 +++++ .../Processing/BufferToTextureEffect.xksl | 17 +++ .../VoxelStorage/VoxelStorageClipmaps.cs | 61 ++++---- .../VoxelStorers/VoxelStorerClipmap.cs | 4 +- .../Voxelization/VoxelVolumeComponent.cs | 26 ++-- .../Voxelization/VoxelVolumeProcessor.cs | 7 +- .../VoxelizationMethodDominantAxis.cs | 4 +- .../VoxelizationMethodSingleAxis.cs | 4 +- 39 files changed, 599 insertions(+), 547 deletions(-) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs index 822821bf18..b55de5abcb 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs @@ -17,7 +17,7 @@ public class VoxelVisualizationRaw : IVoxelVisualization private ImageEffectShader voxelDebugEffectShader = new ImageEffectShader("VoxelVisualizationRawEffect"); public ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr) { - VoxelViewContext viewContext = new VoxelViewContext(context, 0); + VoxelViewContext viewContext = new VoxelViewContext(false); attr.UpdateSamplingLayout("Attribute"); attr.ApplySamplingParameters(viewContext, voxelDebugEffectShader.Parameters); voxelDebugEffectShader.Parameters.Set(VoxelVisualizationRawShaderKeys.Attribute, attr.GetSamplingShader()); diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs index cf3dca0d6c..88ee3e2631 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs @@ -22,7 +22,7 @@ public class VoxelVisualizationView : IVoxelVisualization private ImageEffectShader voxelDebugEffectShader = new ImageEffectShader("VoxelVisualizationViewEffect"); public ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr) { - VoxelViewContext viewContext = new VoxelViewContext(context, 0); + VoxelViewContext viewContext = new VoxelViewContext(false); Matrix ViewProjection = context.RenderContext.RenderView.ViewProjection; voxelDebugEffectShader.Parameters.Set(VoxelVisualizationViewShaderKeys.view, ViewProjection); diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs index d1fafc34d1..0bf2f9f3e9 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/ForwardRendererVoxels.cs @@ -39,7 +39,7 @@ protected override void InitializeCore() ShadowMapRenderer_notPrivate = Context.RenderSystem.RenderFeatures.OfType().FirstOrDefault()?.RenderFeatures.OfType().FirstOrDefault()?.ShadowMapRenderer; base.InitializeCore(); } - protected override unsafe void CollectCore(RenderContext context) + protected override void CollectCore(RenderContext context) { VoxelRenderer?.Collect(Context, ShadowMapRenderer_notPrivate); base.CollectCore(context); diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs index 55aab9b7d8..b2cdce555d 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs @@ -23,9 +23,6 @@ public class VoxelRenderFeature : SubRenderFeature public static readonly PropertyKey> CurrentProcessedVoxelVolumes = new PropertyKey>("VoxelRenderFeature.CurrentProcessedVoxelVolumes", typeof(VoxelRenderFeature)); private Dictionary renderVoxelVolumeData; - - [DataMember] - public RenderStage VoxelizerRenderStage { get; set; } private LogicalGroupReference VoxelizerStorerCasterKey; private StaticObjectPropertyKey renderEffectKey; @@ -55,48 +52,42 @@ public override void PrepareEffectPermutations(RenderDrawContext context) { var processedVolume = processedVolumeKeyValue.Value; - if (processedVolume == null) continue; - foreach (VoxelizationPass pass in processedVolume.passList.passes) { - var viewFeature = pass.view.Features[RootRenderFeature.Index]; - if (processedVolume == null) - continue; - pass.storer.UpdateVoxelizationLayout("Storage"); - for (int i = 0; i < pass.AttributesIndirect.Count; i++) + for (int i = 0; i < pass.AttributesIndirect.Count; i++) { var attr = pass.AttributesIndirect[i]; - attr.UpdateVoxelizationLayout("AttributesIndirect["+i+"]"); + attr.UpdateVoxelizationLayout($"AttributesIndirect[{i}]"); } + } + foreach (var group in processedVolume.groupedPasses) + { + //Each pass in a group should have identical shaders + var pass = group[0]; - var effectSlot = rootEffectRenderFeature.GetEffectPermutationSlot(RenderSystem.RenderStages[pass.view.RenderStages[0].Index]); - - foreach (var renderObject in pass.view.RenderObjects) + Dispatcher.ForEach(RootRenderFeature.RenderObjects, renderObject => { - var staticObjectNode = renderObject.StaticObjectNode; - if (staticObjectNode == null) - continue; + var renderMesh = (RenderMesh)renderObject; - var staticEffectObjectNode = staticObjectNode * effectSlotCount + effectSlot.Index; - if (staticEffectObjectNode == null) - continue; + var staticObjectNode = renderMesh.StaticObjectNode; - RenderEffect renderEffect = null; - try - { - renderEffect = renderEffects[staticEffectObjectNode]; - } - catch - { - } - if (renderEffect != null) + + var effectSlot = rootEffectRenderFeature.GetEffectPermutationSlot(RenderSystem.RenderStages[pass.view.RenderStages[0].Index]); { - renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.Storage, pass.source); - renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.RequireGeometryShader, pass.storer.RequireGeometryShader() || pass.method.RequireGeometryShader()); - renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount, pass.storer.GeometryShaderOutputCount() * pass.method.GeometryShaderOutputCount()); + + var staticEffectObjectNode = staticObjectNode * effectSlotCount + effectSlot.Index; + var renderEffect = renderEffects[staticEffectObjectNode]; + + // Skip effects not used during this frame + if (renderEffect != null) + { + renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.Storage, pass.source); + renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.RequireGeometryShader, pass.storer.RequireGeometryShader() || pass.method.RequireGeometryShader()); + renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount, pass.storer.GeometryShaderOutputCount() * pass.method.GeometryShaderOutputCount()); + } } - } + }); } } } @@ -113,7 +104,6 @@ public override void Prepare(RenderDrawContext context) var viewFeature = pass.view.Features[RootRenderFeature.Index]; - var viewParameters = new ParameterCollection(); // Find a PerView layout from an effect in normal state ViewResourceGroupLayout firstViewLayout = null; foreach (var viewLayout in viewFeature.Layouts) @@ -134,6 +124,7 @@ public override void Prepare(RenderDrawContext context) if (firstViewLayout == null) continue; + var viewParameters = new ParameterCollection(); var firstViewLighting = firstViewLayout.GetLogicalGroup(VoxelizerStorerCasterKey); @@ -159,8 +150,6 @@ public override void Prepare(RenderDrawContext context) foreach (var viewLayout in viewFeature.Layouts) { - - if (viewLayout.State != RenderEffectState.Normal) continue; diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs index e32bbc26e4..9acb215886 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelViewContext.cs @@ -6,12 +6,22 @@ namespace Xenko.Rendering.Voxels { public struct VoxelViewContext { - public int ViewIndex; public bool IsVoxelView; - public VoxelViewContext(RenderDrawContext context, int viewIndex) + public VoxelViewContext(VoxelizationPassList passes, int viewIndex) { - ViewIndex = viewIndex; - IsVoxelView = ViewIndex != 0; + IsVoxelView = false; + foreach (var pass in passes.passes) + { + if (pass.view.Index == viewIndex) + { + IsVoxelView = true; + break; + } + } + } + public VoxelViewContext(bool voxelView) + { + IsVoxelView = voxelView; } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs index 0a424f4aec..1d881f31c0 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs @@ -90,22 +90,34 @@ private class LightVoxelShaderGroup : LightShaderGroup public RenderLight Light { get; set; } + IVoxelAttribute traceAttribute = null; + public LightVoxelShaderGroup(ShaderSource mixin) : base(mixin) { HasEffectPermutations = true; + traceAttribute = null; } - IVoxelAttribute GetTraceAttr() + + ProcessedVoxelVolume GetProcessedVolume() { var lightVoxel = ((LightVoxel)Light.Type); if (lightVoxel.Volume == null) { throw new ArgumentNullException("No Voxel Volume Component selected for voxel light."); } - //ProcessedVoxelVolume processedVolume = Voxels.VoxelRenderer.GetDataForComponent(lightVoxel.Volume); var voxelVolumeProcessor = lightVoxel.Volume.Entity.EntityManager.GetProcessor(); if (voxelVolumeProcessor == null) return null; + ProcessedVoxelVolume processedVolume = voxelVolumeProcessor.GetProcessedVolumeForComponent(lightVoxel.Volume); + return processedVolume; + } + + IVoxelAttribute GetTraceAttr() + { + var lightVoxel = ((LightVoxel)Light.Type); + + ProcessedVoxelVolume processedVolume = GetProcessedVolume(); if (processedVolume == null) return null; @@ -122,6 +134,8 @@ public override void UpdateLayout(string compositionName) { base.UpdateLayout(compositionName); + traceAttribute = GetTraceAttr(); + intensityKey = LightVoxelShaderKeys.Intensity.ComposeWith(compositionName); specularIntensityKey = LightVoxelShaderKeys.SpecularIntensity.ComposeWith(compositionName); @@ -129,23 +143,23 @@ public override void UpdateLayout(string compositionName) specularMarcherKey = LightVoxelShaderKeys.specularMarcher.ComposeWith(compositionName); attributeSamplersKey = MarchAttributesKeys.AttributeSamplers.ComposeWith(compositionName); - if (GetTraceAttr() != null) + if (traceAttribute != null) { if (((LightVoxel)Light.Type).DiffuseMarcher != null) ((LightVoxel)Light.Type).DiffuseMarcher.UpdateMarchingLayout("diffuseMarcher." + compositionName); if (((LightVoxel)Light.Type).SpecularMarcher != null) ((LightVoxel)Light.Type).SpecularMarcher.UpdateMarchingLayout("specularMarcher." + compositionName); - GetTraceAttr().UpdateSamplingLayout("AttributeSamplers[0]." + compositionName); + traceAttribute.UpdateSamplingLayout("AttributeSamplers[0]." + compositionName); } } public override void ApplyEffectPermutations(RenderEffect renderEffect) { - if (GetTraceAttr() != null) + if (traceAttribute != null) { ShaderSourceCollection collection = new ShaderSourceCollection { - GetTraceAttr().GetSamplingShader() + traceAttribute.GetSamplingShader() }; renderEffect.EffectValidator.ValidateParameter(attributeSamplersKey, collection); @@ -158,32 +172,32 @@ public override void ApplyEffectPermutations(RenderEffect renderEffect) public override void ApplyViewParameters(RenderDrawContext context, int viewIndex, ParameterCollection parameters) { - VoxelViewContext viewContext = new VoxelViewContext(context, viewIndex); base.ApplyViewParameters(context, viewIndex, parameters); var lightVoxel = ((LightVoxel)Light.Type); + if (lightVoxel.Volume == null) + return; + var intensity = Light.Intensity; var intensityBounceScale = lightVoxel.BounceIntensityScale; var specularIntensity = lightVoxel.SpecularIntensityScale * intensity; + VoxelViewContext viewContext = new VoxelViewContext(GetProcessedVolume().passList, viewIndex); if (viewContext.IsVoxelView) { intensity *= intensityBounceScale / 3.141592f; specularIntensity = 0.0f; } - if (lightVoxel.Volume == null) - return; - parameters.Set(intensityKey, intensity); parameters.Set(specularIntensityKey, specularIntensity); - if (GetTraceAttr() != null) + if (traceAttribute != null) { lightVoxel.DiffuseMarcher?.ApplyMarchingParameters(parameters); lightVoxel.SpecularMarcher?.ApplyMarchingParameters(parameters); - GetTraceAttr().ApplySamplingParameters(viewContext, parameters); + traceAttribute.ApplySamplingParameters(viewContext, parameters); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs index 88c247e0be..b58ab02242 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs @@ -16,6 +16,7 @@ public interface IVoxelAttribute void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output); void CollectAttributes(List attributes, VoxelizationStage stage, bool output); + bool RequiresColumns(); void PostProcess(RenderDrawContext drawContext); //Writing @@ -23,16 +24,14 @@ public interface IVoxelAttribute void UpdateVoxelizationLayout(string compositionName); void ApplyVoxelizationParameters(ParameterCollection parameters); - void SetBufferOffset(int id); - int GetBufferOffset(); + int BufferOffset { get; set; } //Sampling ShaderSource GetSamplingShader(); void UpdateSamplingLayout(string compositionName); void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); - void SetLocalSamplerID(int id); - int GetLocalSamplerID(); + int LocalSamplerID { get; set; } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs new file mode 100644 index 0000000000..80ee3085da --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; +using Xenko.Core.Mathematics; + +namespace Xenko.Rendering.Voxels +{ + public abstract class VoxelAttributeBase + { + [DataMemberIgnore] + public int BufferOffset { get; set; } = -1; + [DataMemberIgnore] + public int LocalSamplerID { get; set; } = -1; + + virtual public bool RequiresColumns() + { + return false; + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs index 7bd97dd107..8e9724a240 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Xenko.Core; @@ -11,13 +11,13 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Directional Coverage")] - public class VoxelAttributeDirectionalCoverage : IVoxelAttribute + public class VoxelAttributeDirectionalCoverage : VoxelAttributeBase, IVoxelAttribute { IVoxelStorageTexture CoverageTex; public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) { - SetBufferOffset(storage.RequestTempStorage(32)); + BufferOffset = storage.RequestTempStorage(32); } public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) { @@ -66,17 +66,6 @@ public void ApplyVoxelizationParameters(ParameterCollection parameters) CoverageTex?.ApplyVoxelizationParameters(DirectOutput, parameters); } - int bufferOffset; - - public void SetBufferOffset(int bo) - { - bufferOffset = bo; - } - public int GetBufferOffset() - { - return bufferOffset; - } - @@ -98,16 +87,5 @@ public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterColle { CoverageTex?.ApplySamplingParameters(viewContext, parameters); } - - int samplerLocalID; - - public void SetLocalSamplerID(int id) - { - samplerLocalID = id; - } - public int GetLocalSamplerID() - { - return samplerLocalID; - } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs index a6163a264d..535c8ac66b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Xenko.Core; @@ -11,7 +11,7 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Emission+Opacity")] - public class VoxelAttributeEmissionOpacity : IVoxelAttribute + public class VoxelAttributeEmissionOpacity : VoxelAttributeBase, IVoxelAttribute { public enum LightFalloffs { @@ -30,7 +30,7 @@ public enum LightFalloffs public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) { - SetBufferOffset(VoxelLayout.PrepareLocalStorage(context, storage)); + BufferOffset = VoxelLayout.PrepareLocalStorage(context, storage); } public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) { @@ -52,11 +52,24 @@ public void CollectAttributes(List attributes, VoxelizationStag { foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) { + if (!modifier.Enabled) continue; + modifier.CollectAttributes(attributes, VoxelizationStage.Post, false); } attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); } + override public bool RequiresColumns() + { + foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + { + if (!modifier.Enabled) continue; + + if (modifier.RequiresColumns()) + return true; + } + return false; + } public void PostProcess(RenderDrawContext drawContext) { switch (LightFalloff) @@ -67,6 +80,8 @@ public void PostProcess(RenderDrawContext drawContext) VoxelLayout.PostProcess(drawContext, "VoxelMipmapPhysicallyBased"); break; case LightFalloffs.Heuristic: VoxelLayout.PostProcess(drawContext, "VoxelMipmapHeuristic"); break; + default: + throw new InvalidOperationException("Cannot call PostProcess on voxel texture with unknown LightFalloff type."); } } @@ -87,7 +102,9 @@ public void UpdateVoxelizationLayout(string compositionName) int i = 0; foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) { - modifier.UpdateVoxelizationLayout("Modifiers[" + i.ToString() + "].layout." + compositionName); + if (!modifier.Enabled) continue; + + modifier.UpdateVoxelizationLayout($"Modifiers[{i}].layout.{compositionName}"); i++; } VoxelLayout.UpdateVoxelizationLayout("layout." + compositionName, Modifiers); @@ -96,22 +113,13 @@ public void ApplyVoxelizationParameters(ParameterCollection parameters) { foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) { + if (!modifier.Enabled) continue; + modifier.ApplyVoxelizationParameters(parameters); } VoxelLayout.ApplyVoxelizationParameters(parameters, Modifiers); } - int bufferOffset; - - public void SetBufferOffset(int bo) - { - bufferOffset = bo; - } - public int GetBufferOffset() - { - return bufferOffset; - } - @@ -127,16 +135,5 @@ public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterColle { VoxelLayout.ApplySamplingParameters(viewContext, parameters); } - - int samplerLocalID; - - public void SetLocalSamplerID(int id) - { - samplerLocalID = id; - } - public int GetLocalSamplerID() - { - return samplerLocalID; - } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs index e6e220377b..1bc0450a10 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Xenko.Core; @@ -11,13 +11,13 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Solidity")] - public class VoxelAttributeSolidity : IVoxelAttribute + public class VoxelAttributeSolidity : VoxelAttributeBase, IVoxelAttribute { IVoxelStorageTexture SolidityTex; public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) { - SetBufferOffset(storage.RequestTempStorage(64)); + BufferOffset = storage.RequestTempStorage(64); } public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) { @@ -45,9 +45,14 @@ public void CollectAttributes(List attributes, VoxelizationStag attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); } + override public bool RequiresColumns() + { + return false; + } + public void PostProcess(RenderDrawContext drawContext) { - SolidityTex?.PostProcess(drawContext, "VoxelMipmapSimple"); + SolidityTex.PostProcess(drawContext, "VoxelMipmapSimple"); } @@ -71,17 +76,6 @@ public void ApplyVoxelizationParameters(ParameterCollection parameters) SolidityTex?.ApplyVoxelizationParameters(DirectOutput, parameters); } - int bufferOffset; - - public void SetBufferOffset(int bo) - { - bufferOffset = bo; - } - public int GetBufferOffset() - { - return bufferOffset; - } - @@ -106,16 +100,5 @@ public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterColle parameters.Set(BrightnessKey, 1.0f); SolidityTex?.ApplySamplingParameters(viewContext, parameters); } - - int samplerLocalID; - - public void SetLocalSamplerID(int id) - { - samplerLocalID = id; - } - public int GetLocalSamplerID() - { - return samplerLocalID; - } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs index 274fe38f51..3944efc478 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs @@ -6,4 +6,18 @@ // and re-save the associated .xkfx. // -// Nothing to generate +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class VoxelAnisotropicPairedSamplerKeys + { + public static readonly ValueParameterKey maxBrightness = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl index cd72d604fa..ea019e9fcc 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl @@ -2,25 +2,39 @@ { shader VoxelAnisotropicPairedSampler : IVoxelSampler, Texturing { - compose VoxelStorageTextureShader storage; + cbuffer PerView.Lighting + { + float maxBrightness; + } + + float4 applyMaxBrightness(float4 col) + { + return float4(col.rgb * maxBrightness, col.a); + } override float4 Sample(float3 position, float3 normal, float diameter) { - return storage.Sample(position, diameter, 0)*abs(normal.x)+ - storage.Sample(position, diameter, 1)*abs(normal.y)+ - storage.Sample(position, diameter, 2)*abs(normal.z); + return applyMaxBrightness( + storage.Sample(position, diameter, 0) * abs(normal.x) + + storage.Sample(position, diameter, 1) * abs(normal.y) + + storage.Sample(position, diameter, 2) * abs(normal.z) + ); } override float4 SampleNearestMip(float3 position, float3 normal, float diameter) { - return storage.SampleNearestMip(position, diameter, 0) * abs(normal.x) + + return applyMaxBrightness( + storage.SampleNearestMip(position, diameter, 0) * abs(normal.x) + storage.SampleNearestMip(position, diameter, 1) * abs(normal.y) + - storage.SampleNearestMip(position, diameter, 2) * abs(normal.z); + storage.SampleNearestMip(position, diameter, 2) * abs(normal.z) + ); } override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) { - return storage.SampleByMipNearestMip(position, diameter, 0) * abs(normal.x) + + return applyMaxBrightness( + storage.SampleByMipNearestMip(position, diameter, 0) * abs(normal.x) + storage.SampleByMipNearestMip(position, diameter, 1) * abs(normal.y) + - storage.SampleByMipNearestMip(position, diameter, 2) * abs(normal.z); + storage.SampleByMipNearestMip(position, diameter, 2) * abs(normal.z) + ); } override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) { @@ -30,9 +44,5 @@ { return storage.VoxelSize(); } - override float4 Test() - { - return float4(0,1,0,1); - } }; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs index c663c7a6ce..9244be84a2 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs @@ -19,5 +19,6 @@ namespace Xenko.Rendering public static partial class VoxelAnisotropicPairedWriter_Float4Keys { public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + public static readonly ValueParameterKey maxBrightnessInv = ParameterKeys.NewValue(); } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl index 80f41faac8..335dd8a0b2 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl @@ -5,6 +5,8 @@ shader VoxelAnisotropicPairedWriter_Float4 : VoxelLayout_Float4, NormalStream stream float4 axisZ; RWTexture3D DirectOutput; compose VoxelFragmentPacker writer; + + float maxBrightnessInv; compose VoxelModifierApplierAnisotropicPaired Modifiers[]; override void InitializeDummy() @@ -19,6 +21,10 @@ shader VoxelAnisotropicPairedWriter_Float4 : VoxelLayout_Float4, NormalStream streams.axisY = original * abs(streams.normalWS.y); streams.axisZ = original * abs(streams.normalWS.z); } + float4 applyMaxBrightness(float4 col) + { + return float4(col.rgb * maxBrightnessInv, col.a); + } override void DirectWrite(uint3 address, uint strideIndex, uint stride) { address.y += strideIndex * stride * 3; @@ -33,9 +39,9 @@ shader VoxelAnisotropicPairedWriter_Float4 : VoxelLayout_Float4, NormalStream streams.axisY = tempAxisY; streams.axisZ = tempAxisZ; - DirectOutput[address] = streams.axisX;address.y += stride; - DirectOutput[address] = streams.axisY;address.y += stride; - DirectOutput[address] = streams.axisZ; + DirectOutput[address] = applyMaxBrightness(streams.axisX);address.y += stride; + DirectOutput[address] = applyMaxBrightness(streams.axisY);address.y += stride; + DirectOutput[address] = applyMaxBrightness(streams.axisZ); } override void IndirectWrite(RWBuffer buffer, uint address) { diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs index 274fe38f51..b085b45427 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs @@ -6,4 +6,18 @@ // and re-save the associated .xkfx. // -// Nothing to generate +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class VoxelAnisotropicSamplerKeys + { + public static readonly ValueParameterKey maxBrightness = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl index 5b8280a95b..8d7345f1a4 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl @@ -3,6 +3,15 @@ shader VoxelAnisotropicSampler : IVoxelSampler, Texturing { compose VoxelStorageTextureShader storage; + cbuffer PerView.Lighting + { + float maxBrightness; + } + + float4 applyMaxBrightness(float4 col) + { + return float4(col.rgb * maxBrightness, col.a); + } override float4 Sample(float3 position, float3 normal, float diameter) { float4 sum = float4(0,0,0,0); @@ -11,7 +20,7 @@ sum += storage.Sample(position, diameter, normal.y > 0 ? 2 : 3) * abs(normal.y); sum += storage.Sample(position, diameter, normal.z > 0 ? 4 : 5) * abs(normal.z); - return sum; + return applyMaxBrightness(sum); } override float4 SampleNearestMip(float3 position, float3 normal, float diameter) { @@ -21,7 +30,7 @@ sum += storage.SampleNearestMip(position, diameter, normal.y > 0 ? 2 : 3) * abs(normal.y); sum += storage.SampleNearestMip(position, diameter, normal.z > 0 ? 4 : 5) * abs(normal.z); - return sum; + return applyMaxBrightness(sum); } override float4 SampleByMipNearestMip(float3 position, float3 normal, float diameter) { @@ -31,7 +40,7 @@ sum += storage.SampleByMipNearestMip(position, diameter, normal.y > 0 ? 2 : 3) * abs(normal.y); sum += storage.SampleByMipNearestMip(position, diameter, normal.z > 0 ? 4 : 5) * abs(normal.z); - return sum; + return applyMaxBrightness(sum); } override float4 SampleRaw(float3 pos, float mipmap, int textureID, int axis) { @@ -41,9 +50,5 @@ { return storage.VoxelSize(); } - override float4 Test() - { - return float4(0,1,0,1); - } }; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs index 68eb016b55..5666019642 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs @@ -19,5 +19,6 @@ namespace Xenko.Rendering public static partial class VoxelAnisotropicWriter_Float4Keys { public static readonly ObjectParameterKey DirectOutput = ParameterKeys.NewObject(); + public static readonly ValueParameterKey maxBrightnessInv = ParameterKeys.NewValue(); } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl index ebe9a906ee..48216de75a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl @@ -8,6 +8,8 @@ shader VoxelAnisotropicWriter_Float4 : VoxelLayout_Float4, NormalStream stream float4 axisZN; RWTexture3D DirectOutput; compose VoxelFragmentPacker writer; + + float maxBrightnessInv; compose VoxelModifierApplierAnisotropic Modifiers[]; override void InitializeDummy() @@ -36,6 +38,10 @@ shader VoxelAnisotropicWriter_Float4 : VoxelLayout_Float4, NormalStream else streams.axisZN = original * -streams.normalWS.z; } + float4 applyMaxBrightness(float4 col) + { + return float4(col.rgb * maxBrightnessInv, col.a); + } override void DirectWrite(uint3 address, uint strideIndex, uint stride) { address.y += strideIndex * stride * 6; @@ -55,17 +61,17 @@ shader VoxelAnisotropicWriter_Float4 : VoxelLayout_Float4, NormalStream streams.axisYN = tempAxisYN; streams.axisZP = tempAxisZP; streams.axisZN = tempAxisZN; - DirectOutput[address] = streams.axisXP; + DirectOutput[address] = applyMaxBrightness(streams.axisXP); address.y += stride; - DirectOutput[address] = streams.axisXN; + DirectOutput[address] = applyMaxBrightness(streams.axisXN); address.y += stride; - DirectOutput[address] = streams.axisYP; + DirectOutput[address] = applyMaxBrightness(streams.axisYP); address.y += stride; - DirectOutput[address] = streams.axisYN; + DirectOutput[address] = applyMaxBrightness(streams.axisYN); address.y += stride; - DirectOutput[address] = streams.axisZP; + DirectOutput[address] = applyMaxBrightness(streams.axisZP); address.y += stride; - DirectOutput[address] = streams.axisZN; + DirectOutput[address] = applyMaxBrightness(streams.axisZN); } override void IndirectWrite(RWBuffer buffer, uint address) { diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl index 0d76247213..fa45ba1c46 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl @@ -32,9 +32,5 @@ { return storage.VoxelSize(); } - override float4 Test() - { - return float4(0,1,0,1); - } }; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs index 1b1b585e4d..266328ef9a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs @@ -1,90 +1,32 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Xenko.Core; using Xenko.Core.Annotations; using Xenko.Shaders; using Xenko.Rendering.Materials; +using static Xenko.Rendering.Voxels.VoxelAttributeEmissionOpacity; namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Anisotropic (6 sided)")] - public class VoxelLayoutAnisotropic : IVoxelLayout + public class VoxelLayoutAnisotropic : VoxelLayoutBase, IVoxelLayout { - [NotNull] - public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); + protected override int LayoutCount { get; set; } = 6; + protected override ShaderClassSource Writer { get; set; } = new ShaderClassSource("VoxelAnisotropicWriter_Float4"); + protected override ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelAnisotropicSampler"); + protected override string ApplierKey { get; set; } = "Anisotropic"; - - - - IVoxelStorageTexture IsotropicTex; - - public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) - { - return StorageMethod.PrepareLocalStorage(context, storage, 4, 6); - } - public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) - { - storage.UpdateTexture(context, ref IsotropicTex, Graphics.PixelFormat.R16G16B16A16_Float, 6); - } - public void ClearOutputStorage() - { - IsotropicTex = null; - } - - public void PostProcess(RenderDrawContext drawContext, string MipMapShader) - { - IsotropicTex.PostProcess(drawContext, MipMapShader); - } - - - - - ShaderClassSource writer = new ShaderClassSource("VoxelAnisotropicWriter_Float4"); - ObjectParameterKey DirectOutput; - - public ShaderSource GetVoxelizationShader(List modifiers) - { - var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(writer); - StorageMethod.Apply(mixin); - foreach (var attr in modifiers) - { - ShaderSource applier = attr.GetApplier("Anisotropic"); - if (applier != null) - mixin.AddCompositionToArray("Modifiers", applier); - } - return mixin; - } public void UpdateVoxelizationLayout(string compositionName, List modifier) { DirectOutput = VoxelAnisotropicWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); - } - public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifier) - { - IsotropicTex.ApplyVoxelizationParameters(DirectOutput, parameters); - } - - - - - ShaderClassSource sampler = new ShaderClassSource("VoxelAnisotropicSampler"); - - public ShaderSource GetSamplingShader() - { - var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(sampler); - mixin.AddComposition("storage", IsotropicTex.GetSamplingShader()); - return mixin; + BrightnessInvKey = VoxelAnisotropicWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); } public void UpdateSamplingLayout(string compositionName) { - IsotropicTex.UpdateSamplingLayout("storage." + compositionName); - } - public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) - { - IsotropicTex.ApplySamplingParameters(viewContext, parameters); + BrightnessKey = VoxelAnisotropicSamplerKeys.maxBrightness.ComposeWith(compositionName); + storageTex.UpdateSamplingLayout("storage." + compositionName); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs index 775535611f..9c234ba67b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs @@ -10,80 +10,22 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Anisotropic (3 sided)")] - public class VoxelLayoutAnisotropicPaired : IVoxelLayout + public class VoxelLayoutAnisotropicPaired : VoxelLayoutBase, IVoxelLayout { - [NotNull] - public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); + protected override int LayoutCount { get; set; } = 3; + protected override ShaderClassSource Writer { get; set; } = new ShaderClassSource("VoxelAnisotropicPairedWriter_Float4"); + protected override ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelAnisotropicPairedSampler"); + protected override string ApplierKey { get; set; } = "AnisotropicPaired"; - - - IVoxelStorageTexture IsotropicTex; - - public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) - { - return StorageMethod.PrepareLocalStorage(context, storage, 4, 3); - } - public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) - { - storage.UpdateTexture(context, ref IsotropicTex, Graphics.PixelFormat.R16G16B16A16_Float, 3); - } - public void ClearOutputStorage() - { - IsotropicTex = null; - } - - public void PostProcess(RenderDrawContext drawContext, string MipMapShader) - { - IsotropicTex.PostProcess(drawContext, MipMapShader); - } - - - - - ShaderClassSource writer = new ShaderClassSource("VoxelAnisotropicPairedWriter_Float4"); - ObjectParameterKey DirectOutput; - - public ShaderSource GetVoxelizationShader(List modifiers) - { - var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(writer); - StorageMethod.Apply(mixin); - foreach (var attr in modifiers) - { - ShaderSource applier = attr.GetApplier("AnisotropicPaired"); - if (applier != null) - mixin.AddCompositionToArray("Modifiers", applier); - } - return mixin; - } public void UpdateVoxelizationLayout(string compositionName, List modifier) { DirectOutput = VoxelAnisotropicPairedWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); - } - public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) - { - IsotropicTex.ApplyVoxelizationParameters(DirectOutput, parameters); - } - - - - - ShaderClassSource sampler = new ShaderClassSource("VoxelAnisotropicPairedSampler"); - - public ShaderSource GetSamplingShader() - { - var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(sampler); - mixin.AddComposition("storage", IsotropicTex.GetSamplingShader()); - return mixin; + BrightnessInvKey = VoxelAnisotropicPairedWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); } public void UpdateSamplingLayout(string compositionName) { - IsotropicTex.UpdateSamplingLayout("storage."+compositionName); - } - public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) - { - IsotropicTex.ApplySamplingParameters(viewContext, parameters); + BrightnessKey = VoxelAnisotropicPairedSamplerKeys.maxBrightness.ComposeWith(compositionName); + storageTex.UpdateSamplingLayout("storage." + compositionName); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs new file mode 100644 index 0000000000..c474f90586 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; +using static Xenko.Rendering.Voxels.VoxelAttributeEmissionOpacity; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public class VoxelLayoutBase + { + public enum StorageFormats + { + R10G10B10A2, + RGBA8, + RGBA16F, + }; + + [NotNull] + public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); + + public StorageFormats StorageFormat { get; set; } = StorageFormats.RGBA16F; + + Graphics.PixelFormat StorageFormatToPixelFormat() + { + Graphics.PixelFormat format = Graphics.PixelFormat.R16G16B16A16_Float; + switch (StorageFormat) + { + case StorageFormats.RGBA8: + format = Graphics.PixelFormat.R8G8B8A8_UNorm; + break; + case StorageFormats.R10G10B10A2: + format = Graphics.PixelFormat.R10G10B10A2_UNorm; + break; + case StorageFormats.RGBA16F: + format = Graphics.PixelFormat.R16G16B16A16_Float; + break; + } + return format; + } + + [Display("Max Brightness (non float format)")] + public float maxBrightness = 10.0f; + + + + + //Per-Layout Settings + protected virtual int LayoutCount { get; set; } = 1; + protected virtual ShaderClassSource Writer { get; set; } = new ShaderClassSource("VoxelIsotropicWriter_Float4"); + protected virtual ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelIsotropicSampler"); + protected virtual string ApplierKey { get; set; } = "Isotropic"; + + + + + protected IVoxelStorageTexture storageTex; + + virtual public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + { + return StorageMethod.PrepareLocalStorage(context, storage, 4, LayoutCount); + } + virtual public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + { + storage.UpdateTexture(context, ref storageTex, StorageFormatToPixelFormat(), LayoutCount); + } + virtual public void ClearOutputStorage() + { + storageTex = null; + } + + virtual public void PostProcess(RenderDrawContext drawContext, string shader) + { + storageTex.PostProcess(drawContext, shader); + } + + + + + protected ValueParameterKey BrightnessInvKey; + protected ObjectParameterKey DirectOutput; + + virtual public ShaderSource GetVoxelizationShader(List modifiers) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(Writer); + StorageMethod.Apply(mixin); + foreach (var modifier in modifiers) + { + if (!modifier.Enabled) continue; + + ShaderSource applier = modifier.GetApplier(ApplierKey); + if (applier != null) + mixin.AddCompositionToArray("Modifiers", applier); + } + return mixin; + } + virtual public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) + { + if (StorageFormat != StorageFormats.RGBA16F) + parameters.Set(BrightnessInvKey, 1.0f / maxBrightness); + else + parameters.Set(BrightnessInvKey, 1.0f); + + storageTex.ApplyVoxelizationParameters(DirectOutput, parameters); + } + + + + + protected ValueParameterKey BrightnessKey; + + virtual public ShaderSource GetSamplingShader() + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(Sampler); + mixin.AddComposition("storage", storageTex.GetSamplingShader()); + return mixin; + } + virtual public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + { + if (StorageFormat != StorageFormats.RGBA16F) + parameters.Set(BrightnessKey, maxBrightness); + else + parameters.Set(BrightnessKey, 1.0f); + + storageTex.ApplySamplingParameters(viewContext, parameters); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs index 2bfa26c21e..6da560a7ab 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; using Xenko.Core; @@ -10,118 +10,22 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Isotropic (single)")] - public class VoxelLayoutIsotropic : IVoxelLayout + public class VoxelLayoutIsotropic : VoxelLayoutBase, IVoxelLayout { - public enum StorageFormats - { - R10G10B10A2, - RGBA8, - RGBA16F, - }; - - [NotNull] - public IVoxelStorageMethod StorageMethod { get; set; } = new VoxelStorageMethodIndirect(); - - public StorageFormats StorageFormat { get; set; } = StorageFormats.RGBA16F; - - [Display("Max Brightness (non float format)")] - public float maxBrightness = 10.0f; - - - - - IVoxelStorageTexture IsotropicTex; - - public int PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) - { - return StorageMethod.PrepareLocalStorage(context, storage, 4, 1); - } - public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) - { - Graphics.PixelFormat format = Graphics.PixelFormat.R16G16B16A16_Float; - switch (StorageFormat) - { - case StorageFormats.RGBA8: - format = Graphics.PixelFormat.R8G8B8A8_UNorm; - break; - case StorageFormats.R10G10B10A2: - format = Graphics.PixelFormat.R10G10B10A2_UNorm; - break; - case StorageFormats.RGBA16F: - format = Graphics.PixelFormat.R16G16B16A16_Float; - break; - } - storage.UpdateTexture(context, ref IsotropicTex, format, 1); - } - public void ClearOutputStorage() - { - IsotropicTex = null; - } - - public void PostProcess(RenderDrawContext drawContext, string MipMapShader) - { - IsotropicTex.PostProcess(drawContext, MipMapShader); - } + protected override int LayoutCount { get; set; } = 1; + protected override ShaderClassSource Writer { get; set; } = new ShaderClassSource("VoxelIsotropicWriter_Float4"); + protected override ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelIsotropicSampler"); + protected override string ApplierKey { get; set; } = "Isotropic"; - - - - ShaderClassSource writer = new ShaderClassSource("VoxelIsotropicWriter_Float4"); - ValueParameterKey BrightnessInvKey; - ObjectParameterKey DirectOutput; - - public ShaderSource GetVoxelizationShader(List modifiers) - { - var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(writer); - StorageMethod.Apply(mixin); - foreach (var attr in modifiers) - { - ShaderSource applier = attr.GetApplier("Isotropic"); - if (applier != null) - mixin.AddCompositionToArray("Modifiers", applier); - } - return mixin; - } public void UpdateVoxelizationLayout(string compositionName, List modifiers) { DirectOutput = VoxelIsotropicWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); BrightnessInvKey = VoxelIsotropicWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); } - public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) - { - if (StorageFormat != StorageFormats.RGBA16F) - parameters.Set(BrightnessInvKey, 1.0f / maxBrightness); - else - parameters.Set(BrightnessInvKey, 1.0f); - IsotropicTex.ApplyVoxelizationParameters(DirectOutput, parameters); - } - - - - - ValueParameterKey BrightnessKey; - ShaderClassSource sampler = new ShaderClassSource("VoxelIsotropicSampler"); - - public ShaderSource GetSamplingShader() - { - var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(sampler); - mixin.AddComposition("storage", IsotropicTex.GetSamplingShader()); - return mixin; - } public void UpdateSamplingLayout(string compositionName) { BrightnessKey = VoxelIsotropicSamplerKeys.maxBrightness.ComposeWith(compositionName); - IsotropicTex.UpdateSamplingLayout("storage."+compositionName); - } - public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) - { - if (StorageFormat != StorageFormats.RGBA16F) - parameters.Set(BrightnessKey, maxBrightness); - else - parameters.Set(BrightnessKey, 1.0f); - IsotropicTex.ApplySamplingParameters(viewContext, parameters); + storageTex.UpdateSamplingLayout("storage." + compositionName); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs index 88f5c44753..dd1890f501 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs @@ -2,32 +2,27 @@ using System.Collections.Generic; using System.Text; using Xenko.Core; -using Xenko.Rendering; -using Xenko.Rendering.Voxels; using Xenko.Shaders; -[DataContract(DefaultMemberMode = DataMemberMode.Default)] -[Display("Anti Aliasing")] -public class VoxelModifierEmissionOpacityAntiAliasing : VoxelModifierBase, IVoxelModifierEmissionOpacity +namespace Xenko.Rendering.Voxels { - VoxelAttributeDirectionalCoverage directionalCoverage = new VoxelAttributeDirectionalCoverage(); - - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) - { - if (!Enabled) return; - directionalCoverage.CollectAttributes(attributes, stage, output); - } - public bool RequiresColumns() - { - if (!Enabled) return false; - return true; - } - public ShaderSource GetApplier(string layout) + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Anti Aliasing")] + public class VoxelModifierEmissionOpacityAntiAliasing : VoxelModifierBase, IVoxelModifierEmissionOpacity { - if (!Enabled) return null; - return new ShaderClassSource("VoxelModifierApplierAntiAliasing" + layout, directionalCoverage.GetLocalSamplerID()); - } + VoxelAttributeDirectionalCoverage directionalCoverage = new VoxelAttributeDirectionalCoverage(); + + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + { + directionalCoverage.CollectAttributes(attributes, stage, output); + } - public void UpdateVoxelizationLayout(string compositionName) { } - public void ApplyVoxelizationParameters(ParameterCollection parameters) { } + public ShaderSource GetApplier(string layout) + { + return new ShaderClassSource("VoxelModifierApplierAntiAliasing" + layout, directionalCoverage.LocalSamplerID); + } + + public void UpdateVoxelizationLayout(string compositionName) { } + public void ApplyVoxelizationParameters(ParameterCollection parameters) { } + } } \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs index 26e2c712e0..47c6746fee 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs @@ -2,35 +2,31 @@ using System.Collections.Generic; using System.Text; using Xenko.Core; -using Xenko.Rendering; -using Xenko.Rendering.Voxels; using Xenko.Shaders; -[DataContract(DefaultMemberMode = DataMemberMode.Default)] -[Display("Opacify")] -public class VoxelModifierEmissionOpacityOpacify : VoxelModifierBase, IVoxelModifierEmissionOpacity +namespace Xenko.Rendering.Voxels { - public float Amount = 2.0f; - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { } - public bool RequiresColumns() + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Opacify")] + public class VoxelModifierEmissionOpacityOpacify : VoxelModifierBase, IVoxelModifierEmissionOpacity { - if (!Enabled) return false; - return true; - } - public ShaderSource GetApplier(string layout) - { - if (!Enabled) return null; - return new ShaderClassSource("VoxelModifierApplierOpacify" + layout); - } + public float Amount = 2.0f; + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { } - ValueParameterKey AmountKey; - public void UpdateVoxelizationLayout(string compositionName) - { - AmountKey = VoxelModifierApplierOpacifyIsotropicKeys.Amount.ComposeWith(compositionName); - } + public ShaderSource GetApplier(string layout) + { + return new ShaderClassSource("VoxelModifierApplierOpacify" + layout); + } - public void ApplyVoxelizationParameters(ParameterCollection parameters) - { - parameters.Set(AmountKey, Amount); + ValueParameterKey AmountKey; + public void UpdateVoxelizationLayout(string compositionName) + { + AmountKey = VoxelModifierApplierOpacifyIsotropicKeys.Amount.ComposeWith(compositionName); + } + + public void ApplyVoxelizationParameters(ParameterCollection parameters) + { + parameters.Set(AmountKey, Amount); + } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs index 0f7ee4b7d2..a6dc08db6a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs @@ -2,31 +2,29 @@ using System.Collections.Generic; using System.Text; using Xenko.Core; -using Xenko.Rendering; -using Xenko.Rendering.Voxels; using Xenko.Shaders; -[DataContract(DefaultMemberMode = DataMemberMode.Default)] -[Display("Solidify")] -public class VoxelModifierEmissionOpacitySolidify : VoxelModifierBase, IVoxelModifierEmissionOpacity +namespace Xenko.Rendering.Voxels { - VoxelAttributeSolidity solidityAttribute = new VoxelAttributeSolidity(); - - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) - { - if (!Enabled) return; - solidityAttribute.CollectAttributes(attributes, stage, output); - } - public bool RequiresColumns() + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Solidify")] + public class VoxelModifierEmissionOpacitySolidify : VoxelModifierBase, IVoxelModifierEmissionOpacity { - if (!Enabled) return false; - return true; - } - public ShaderSource GetApplier(string layout) - { - if (!Enabled) return null; - return new ShaderClassSource("VoxelModifierApplierSolidify" + layout, solidityAttribute.GetLocalSamplerID()); + VoxelAttributeSolidity solidityAttribute = new VoxelAttributeSolidity(); + + public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + { + solidityAttribute.CollectAttributes(attributes, stage, output); + } + override public bool RequiresColumns() + { + return true; + } + public ShaderSource GetApplier(string layout) + { + return new ShaderClassSource("VoxelModifierApplierSolidify" + layout, solidityAttribute.LocalSamplerID); + } + public void UpdateVoxelizationLayout(string compositionName) { } + public void ApplyVoxelizationParameters(ParameterCollection parameters) { } } - public void UpdateVoxelizationLayout(string compositionName) { } - public void ApplyVoxelizationParameters(ParameterCollection parameters) { } -} +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs index f7041a8c56..bc9f5f67f1 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs @@ -3,15 +3,17 @@ using System.ComponentModel; using System.Text; using Xenko.Core; -using Xenko.Rendering; -using Xenko.Rendering.Voxels; using Xenko.Shaders; -public interface IVoxelModifier +namespace Xenko.Rendering.Voxels { - bool RequiresColumns(); - void CollectAttributes(List attributes, VoxelizationStage stage, bool output); - void UpdateVoxelizationLayout(string compositionName); - void ApplyVoxelizationParameters(ParameterCollection parameters); - ShaderSource GetApplier(string layout); + public interface IVoxelModifier + { + bool Enabled { get; set; } + bool RequiresColumns(); + void CollectAttributes(List attributes, VoxelizationStage stage, bool output); + void UpdateVoxelizationLayout(string compositionName); + void ApplyVoxelizationParameters(ParameterCollection parameters); + ShaderSource GetApplier(string layout); + } } \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs index e82ef355d9..42f4793a7e 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs @@ -5,10 +5,18 @@ using Xenko.Core; using Xenko.Shaders; -[DataContract(DefaultMemberMode = DataMemberMode.Default)] -public abstract class VoxelModifierBase +namespace Xenko.Rendering.Voxels { - [DataMember(-20)] - [DefaultValue(true)] - public bool Enabled { get; set; } = true; + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public abstract class VoxelModifierBase + { + [DataMember(-20)] + [DefaultValue(true)] + public bool Enabled { get; set; } = true; + + public virtual bool RequiresColumns() + { + return true; + } + } } \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs index 0ed6c31ae4..10531e8072 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs @@ -36,11 +36,11 @@ public struct AttributeStream public IVoxelAttribute Attribute; public VoxelizationStage Stage; public bool Output; - public AttributeStream(IVoxelAttribute a, VoxelizationStage s, bool o) + public AttributeStream(IVoxelAttribute attribute, VoxelizationStage stage, bool output) { - Attribute = a; - Stage = s; - Output = o; + Attribute = attribute; + Stage = stage; + Output = output; } } public class ProcessedVoxelVolume diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl index f9ab74619c..2736bd5409 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl @@ -1,6 +1,5 @@ namespace Xenko.Rendering.Voxels { - //TODO: Currently broken, is being kept around for its shader keys shader BufferToTexture : LocalSamples, ComputeShaderBase, VoxelPositionStream, DataPacking { stage RWBuffer VoxelFragments; @@ -11,9 +10,42 @@ namespace Xenko.Rendering.Voxels stage uint clipOffset; + compose VoxelAttribute AttributesTemp[]; + compose VoxelAttribute AttributesIndirect[]; + + #ifndef IndirectStoreMacro + #define IndirectStoreMacro + #define IndirectReadAndStoreMacro + #endif + override void Compute() { - //TODO + int3 clipMapResolutionI = (int3)clipMapResolution; + + uint3 pos = streams.DispatchThreadId.xyz; + uint clipIndex = clipOffset; + + streams.PositionVXPS = pos; + streams.VoxelVolumeSize = clipMapResolutionI; + + uint wStride = clipMapResolutionI.x * clipMapResolutionI.y * clipMapResolutionI.z; + uint VoxelFragmentsIndex = clipIndex * wStride + pos.x + pos.y * clipMapResolutionI.x + pos.z * clipMapResolutionI.x * clipMapResolutionI.y; + VoxelFragmentsIndex *= (uint)storageUints; + + uint yStride = clipMapResolutionI.x * (uint)storageUints; + uint initialVoxelFragmentsIndex = VoxelFragmentsIndex; + + + + foreach (var attr in AttributesTemp) + attr.InitializeDummy(); + foreach (var attr in AttributesIndirect) + attr.InitializeDummy(); + + IndirectReadAndStoreMacro + + foreach (var attr in AttributesIndirect) + attr.DirectWrite(streams.PositionVXPS, clipIndex, (int)clipMapResolutionI.y); } }; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs index 837a586525..eff136c507 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs @@ -23,6 +23,38 @@ internal partial class BufferToTextureEffect : IShaderMixinBuilder public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) { context.Mixin(mixin, "BufferToTexture"); + if (context.GetParam(BufferToTextureKeys.AttributesIndirect) != null) + { + foreach(var attr in context.GetParam(BufferToTextureKeys.AttributesIndirect)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributesIndirect", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + if (context.GetParam(BufferToTextureKeys.AttributesTemp) != null) + { + foreach(var attr in context.GetParam(BufferToTextureKeys.AttributesTemp)) + + { + + { + var __mixinToCompose__ = (attr); + var __subMixin = new ShaderMixinSource(); + context.PushCompositionArray(mixin, "AttributesTemp", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + mixin.AddMacro("IndirectReadAndStoreMacro", context.GetParam(BufferToTextureKeys.IndirectReadAndStoreMacro)); + mixin.AddMacro("IndirectStoreMacro", context.GetParam(BufferToTextureKeys.IndirectStoreMacro)); } [ModuleInitializer] diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl index 1685893276..925c11bae3 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl @@ -5,5 +5,22 @@ namespace Xenko.Rendering.Voxels using params BufferToTextureKeys; mixin BufferToTexture; + if (BufferToTextureKeys.AttributesIndirect!=null) + { + foreach (var attr in BufferToTextureKeys.AttributesIndirect) + { + mixin compose AttributesIndirect += (attr); + } + } + if (BufferToTextureKeys.AttributesTemp!=null) + { + foreach (var attr in BufferToTextureKeys.AttributesTemp) + { + mixin compose AttributesTemp += (attr); + } + } + + mixin macro BufferToTextureKeys.IndirectReadAndStoreMacro; + mixin macro BufferToTextureKeys.IndirectStoreMacro; }; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs index 4cdf4f1744..373ee33a46 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs @@ -240,6 +240,7 @@ public void CollectVoxelizationPasses(ProcessedVoxelVolume data, VoxelStorageCon } } + Xenko.Rendering.ComputeEffect.ComputeEffectShader BufferToTexture; Xenko.Rendering.ComputeEffect.ComputeEffectShader BufferToTextureColumns; Xenko.Rendering.ComputeEffect.ComputeEffectShader ClearBuffer; @@ -253,14 +254,27 @@ public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext dr if (ClearBuffer == null) { ClearBuffer = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(context) { ShaderSourceName = "ClearBuffer" }; - //BufferToTexture = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(Context) { ShaderSourceName = "BufferToTextureEffect" }; + BufferToTexture = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(context) { ShaderSourceName = "BufferToTextureEffect" }; BufferToTextureColumns = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(context) { ShaderSourceName = "BufferToTextureColumnsEffect" }; } + bool VoxelsAreIndependent = true; + List IndirectVoxels = new List(); List TempVoxels = new List(); ShaderSourceCollection Indirect = new ShaderSourceCollection(); ShaderSourceCollection Temp = new ShaderSourceCollection(); + + //Assign sample indices and check whether voxels can be calculated independently + int sampleIndex = 0; + foreach (var attr in data.Attributes) + { + attr.Attribute.LocalSamplerID = sampleIndex; + VoxelsAreIndependent &= !attr.Attribute.RequiresColumns(); + sampleIndex++; + } + + //Populate ShaderSourceCollections and temp lists foreach (var attr in data.Attributes) { if (attr.Stage != VoxelizationStage.Post) continue; @@ -276,17 +290,17 @@ public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext dr } } + var BufferWriter = VoxelsAreIndependent ? BufferToTexture : BufferToTextureColumns; - var BufferWriter = BufferToTextureColumns; for (int i = 0; i < IndirectVoxels.Count; i++) { var attr = IndirectVoxels[i]; - attr.UpdateVoxelizationLayout("AttributesIndirect[" + i + "]"); + attr.UpdateVoxelizationLayout($"AttributesIndirect[{i}]"); } for (int i = 0; i < TempVoxels.Count; i++) { var attr = TempVoxels[i]; - attr.UpdateVoxelizationLayout("AttributesTemp[" + i + "]"); + attr.UpdateVoxelizationLayout($"AttributesTemp[{i}]"); } foreach (var attr in data.Attributes) { @@ -294,15 +308,11 @@ public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext dr } - BufferWriter.ThreadGroupCounts = new Int3(32, 1, 32); - if (UpdatesPerFrame == UpdateMethods.SingleClipmap) - { - BufferWriter.ThreadNumbers = new Int3((int)ClipMapResolution.X / BufferWriter.ThreadGroupCounts.X, 1 / BufferWriter.ThreadGroupCounts.Y, (int)ClipMapResolution.Z / BufferWriter.ThreadGroupCounts.Z); - } - else - { - BufferWriter.ThreadNumbers = new Int3((int)ClipMapResolution.X / BufferWriter.ThreadGroupCounts.X, ClipMapCount / BufferWriter.ThreadGroupCounts.Y, (int)ClipMapResolution.Z / BufferWriter.ThreadGroupCounts.Z); - } + int processYSize = VoxelsAreIndependent ? (int)ClipMapResolution.Y : 1; + processYSize *= (UpdatesPerFrame == UpdateMethods.SingleClipmap) ? 1 : ClipMapCount; + + BufferWriter.ThreadGroupCounts = VoxelsAreIndependent ? new Int3(32, 32, 32) : new Int3(32, 1, 32); + BufferWriter.ThreadNumbers = new Int3((int)ClipMapResolution.X / BufferWriter.ThreadGroupCounts.X, processYSize / BufferWriter.ThreadGroupCounts.Y, (int)ClipMapResolution.Z / BufferWriter.ThreadGroupCounts.Z); BufferWriter.Parameters.Set(BufferToTextureKeys.VoxelFragments, FragmentsBuffer); BufferWriter.Parameters.Set(BufferToTextureKeys.clipMapResolution, ClipMapResolution); @@ -317,28 +327,25 @@ public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext dr //makes it difficult to access the results array (AttributeLocalSamples) by index. So instead it's just all done through this macro... string IndirectReadAndStoreMacro = ""; string IndirectStoreMacro = ""; - int sampleIndex = 0; for (int i = 0; i < Temp.Count; i ++) { string iStr = i.ToString(); - string sampleIndexStr = sampleIndex.ToString(); - IndirectReadAndStoreMacro += "AttributesTemp[" + iStr + "].InitializeFromBuffer(VoxelFragments, VoxelFragmentsIndex + " + TempVoxels[i].GetBufferOffset().ToString() + ", uint2(" + TempVoxels[i].GetBufferOffset().ToString() + " + initialVoxelFragmentsIndex, yStride));\n" + - "streams.LocalSample[" + sampleIndexStr + "] = AttributesTemp[" + iStr + "].SampleLocal();\n\n"; - IndirectStoreMacro += "streams.LocalSample[" + sampleIndexStr + "] = AttributesTemp[" + iStr + "].SampleLocal();\n"; - TempVoxels[i].SetLocalSamplerID(sampleIndex); - sampleIndex++; + string sampleIndexStr = TempVoxels[i].LocalSamplerID.ToString(); + IndirectReadAndStoreMacro += $"AttributesTemp[{iStr}].InitializeFromBuffer(VoxelFragments, VoxelFragmentsIndex + {TempVoxels[i].BufferOffset}, uint2({TempVoxels[i].BufferOffset} + initialVoxelFragmentsIndex, yStride));\n" + + $"streams.LocalSample[{sampleIndexStr}] = AttributesTemp[{iStr}].SampleLocal();\n\n"; + IndirectStoreMacro += $"streams.LocalSample[{sampleIndexStr}] = AttributesTemp[{iStr}].SampleLocal();\n"; } for (int i = 0; i < Indirect.Count; i++) { string iStr = i.ToString(); - string sampleIndexStr = sampleIndex.ToString(); - IndirectReadAndStoreMacro += "AttributesIndirect[" + iStr + "].InitializeFromBuffer(VoxelFragments, VoxelFragmentsIndex + " + IndirectVoxels[i].GetBufferOffset().ToString() + ", uint2(" + IndirectVoxels[i].GetBufferOffset().ToString() + " + initialVoxelFragmentsIndex, yStride));\n" + - "streams.LocalSample[" + sampleIndexStr + "] = AttributesIndirect[" + iStr + "].SampleLocal();\n\n"; - IndirectStoreMacro += "streams.LocalSample[" + sampleIndexStr + "] = AttributesIndirect[" + iStr + "].SampleLocal();\n"; - IndirectVoxels[i].SetLocalSamplerID(sampleIndex); - sampleIndex++; + string sampleIndexStr = IndirectVoxels[i].LocalSamplerID.ToString(); + IndirectReadAndStoreMacro += $"AttributesIndirect[{iStr}].InitializeFromBuffer(VoxelFragments, VoxelFragmentsIndex + {IndirectVoxels[i].BufferOffset}, uint2({IndirectVoxels[i].BufferOffset} + initialVoxelFragmentsIndex, yStride));\n" + + $"streams.LocalSample[{sampleIndexStr}] = AttributesIndirect[{iStr}].SampleLocal();\n\n"; + IndirectStoreMacro += $"streams.LocalSample[{sampleIndexStr}] = AttributesIndirect[{iStr}].SampleLocal();\n"; } + + BufferWriter.Parameters.Set(BufferToTextureKeys.AttributesIndirect, Indirect); BufferWriter.Parameters.Set(BufferToTextureKeys.AttributesTemp, Temp); BufferWriter.Parameters.Set(BufferToTextureKeys.IndirectReadAndStoreMacro, IndirectReadAndStoreMacro); @@ -346,6 +353,8 @@ public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext dr ((RendererBase)BufferWriter).Draw(drawContext); + + ClearBuffer.Parameters.Set(ClearBufferKeys.buffer, FragmentsBuffer); if (UpdatesPerFrame != UpdateMethods.SingleClipmap) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs index b8de8a12bf..8e4b0cd7ef 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorers/VoxelStorerClipmap.cs @@ -56,7 +56,7 @@ public override bool Equals(object obj) } public override int GetHashCode() { - return 0; + return UpdatesOneClipPerFrame().GetHashCode(); } @@ -125,7 +125,7 @@ public ShaderSource GetVoxelizationShader(VoxelizationPass pass, ProcessedVoxelV for (int i = 0; i < pass.AttributesIndirect.Count; i++) { string iStr = i.ToString(); - IndirectStoreMacro += "AttributesIndirect[" + iStr + "].IndirectWrite(fragmentsBuffer, writeindex + " + pass.AttributesIndirect[i].GetBufferOffset().ToString() + ");\n"; + IndirectStoreMacro += $"AttributesIndirect[{iStr}].IndirectWrite(fragmentsBuffer, writeindex + {pass.AttributesIndirect[i].BufferOffset});\n"; } cachedMixin.AddMacro("IndirectStoreMacro", IndirectStoreMacro); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs index eebc9b992f..4963006d63 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs @@ -17,8 +17,10 @@ namespace Xenko.Rendering.Voxels /// [DataContract("VoxelVolumeComponent")] [DefaultEntityComponentRenderer(typeof(VoxelVolumeProcessor))] - [Display("Voxel Volume")] + [Display("Voxel Volume", Expand = ExpandRule.Once)] [ComponentCategory("Lights")] + [CategoryOrder(10, "Attributes")] + [CategoryOrder(60, "Visualization/Debug")] public class VoxelVolumeComponent : ActivableEntityComponent { private bool enabled = true; @@ -32,32 +34,32 @@ public override bool Enabled [DataMember(1)] public bool Voxelize = true; - [DataMember(5)] + [DataMember(10)] [NotNull] public IVoxelizationMethod VoxelizationMethod { get; set; } = new VoxelizationMethodDominantAxis(); - [DataMember(10)] + [DataMember(20)] [NotNull] public IVoxelStorage Storage { get; set; } = new VoxelStorageClipmaps(); - [DataMember(20)] + [DataMember(30)] [Category] public List Attributes { get; set; } = new List(); - [DataMember(30)] + [DataMember(40)] public float AproximateVoxelSize { get; set; } = 0.15f; - [DataMember(34)] + [DataMember(50)] public bool VoxelGridSnapping { get; set; } = true; - [DataMember(40)] - [Category] - public bool VoxelVisualization { get; set; } = false;//Unused, toggle doesn't show if category - [DataMember(50)] + [DataMember(60)] + [Display(category: "Visualization/Debug")] public bool VisualizeVoxels { get; set; } = false; - [DataMember(55)] + [DataMember(70)] + [Display(category: "Visualization/Debug")] public int VisualizeIndex { get; set; } = 0; - [DataMember(60)] + [DataMember(80)] + [Display(category: "Visualization/Debug")] public IVoxelVisualization Visualization { get; set; } = null; public event EventHandler Changed; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs index 0c036209e2..146c0102e1 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs @@ -39,11 +39,10 @@ protected override void OnSystemAdd() } public override void Update(GameTime time) { - RegenerateVoxelVolumes(); } public override void Draw(RenderContext context) { - + RegenerateVoxelVolumes(); } public ProcessedVoxelVolume GetProcessedVolumeForComponent(VoxelVolumeComponent component) @@ -73,8 +72,6 @@ private void ComponentChanged(object sender, EventArgs eventArgs) } private void RegenerateVoxelVolumes() { - //if (!isDirty) - // return; renderVoxelVolumes.Clear(); processedVoxelVolumes.Clear(); for (int i=0; i VoxelizationViews { get; } = new List(); - [DataMemberIgnore] Dictionary VoxelizationViewSizes { get; } = new Dictionary(); int currentViewIndex = 0; @@ -56,7 +54,7 @@ public bool CanShareRenderStage(IVoxelizationMethod obj) } public override int GetHashCode() { - return 0; + return MultisampleCount.GetHashCode(); } public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs index 596b3dc237..ef8bd86505 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs @@ -23,9 +23,7 @@ namespace Xenko.Rendering.Voxels [Display("Single Axis")] public class VoxelizationMethodSingleAxis : IVoxelizationMethod { - [DataMemberIgnore] List VoxelizationViews { get; } = new List(); - [DataMemberIgnore] Dictionary VoxelizationViewSizes { get; } = new Dictionary(); int currentViewIndex = 0; @@ -53,7 +51,7 @@ public bool CanShareRenderStage(IVoxelizationMethod obj) } public override int GetHashCode() { - return 0; + return MultisampleCount.GetHashCode(); } From 9ef60abfa2f782317d881354e9a0c81fc4d646cf Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Wed, 22 Jan 2020 22:59:51 +1100 Subject: [PATCH 0655/2038] Anisotropic Mipmapping + Improved Marchers and March Sets --- .../Shaders/VoxelVisualizationRawShader.xksl | 4 +- .../Shaders/VoxelVisualizationViewEffect.xksl | 4 +- .../Shaders/VoxelVisualizationViewShader.xksl | 4 +- .../Shaders/VoxelMarchSetHemisphere12.cs | 16 +- .../Shaders/VoxelMarchSetHemisphere12.xksl | 37 +++-- .../Shaders/VoxelMarchSetHemisphere6.cs | 16 +- .../Shaders/VoxelMarchSetHemisphere6.xksl | 33 +++-- .../Shaders/VoxelMarchSetRandomHemisphere.cs | 24 +++ .../VoxelMarchSetRandomHemisphere.xksl | 44 ++++++ .../Marching/MarchSets/VoxelMarchSetBase.cs | 34 +++++ .../MarchSets/VoxelMarchSetHemisphere12.cs | 13 +- .../MarchSets/VoxelMarchSetHemisphere6.cs | 13 +- .../VoxelMarchSetRandomHemisphere.cs | 53 +++++++ .../Marching/Shaders/VoxelMarchBeam.xksl | 3 + .../Marching/Shaders/VoxelMarchCone.xksl | 23 ++- .../Shaders/VoxelMarchConeEditMode.cs | 27 ++++ .../Shaders/VoxelMarchConeEditMode.xksl | 45 ++++++ .../Marching/Shaders/VoxelMarchConeFast.xksl | 27 ---- .../Shaders/VoxelMarchConePerMipmap.cs | 17 ++- .../Shaders/VoxelMarchConePerMipmap.xksl | 11 +- .../Voxels/Marching/VoxelMarchCone.cs | 42 +++++- .../Marching/VoxelMarchConePerMipmap.cs | 18 ++- .../VoxelAttributeDirectionalCoverage.cs | 3 +- .../VoxelAttributeEmissionOpacity.cs | 12 +- .../Attributes/VoxelAttributeSolidity.cs | 3 +- .../Voxelization/Layout/IVoxelLayout.cs | 3 +- .../Layout/VoxelLayoutAnisotropic.cs | 21 +++ .../Voxelization/Layout/VoxelLayoutBase.cs | 38 ++++- .../VoxelStorage/IVoxelStorageTexture.cs | 2 +- .../Voxel2x2x2Mipmapper_AnisoXN.cs} | 0 .../Voxel2x2x2Mipmapper_AnisoXN.xksl | 14 ++ .../Voxel2x2x2Mipmapper_AnisoXP.cs} | 0 .../Voxel2x2x2Mipmapper_AnisoXP.xksl | 14 ++ .../Voxel2x2x2Mipmapper_AnisoYN.cs} | 0 .../Voxel2x2x2Mipmapper_AnisoYN.xksl | 14 ++ .../Voxel2x2x2Mipmapper_AnisoYP.cs | 9 ++ .../Voxel2x2x2Mipmapper_AnisoYP.xksl | 14 ++ .../Voxel2x2x2Mipmapper_AnisoZN.cs | 9 ++ .../Voxel2x2x2Mipmapper_AnisoZN.xksl | 14 ++ .../Voxel2x2x2Mipmapper_AnisoZP.cs | 9 ++ .../Voxel2x2x2Mipmapper_AnisoZP.xksl | 14 ++ ...xelMipmapSimple.cs => Voxel2x2x2Mipmap.cs} | 3 +- .../Mipmapping/Voxel2x2x2Mipmap.xksl | 32 ++++ .../Mipmapping/Voxel2x2x2MipmapEffect.cs | 47 ++++++ .../Mipmapping/Voxel2x2x2MipmapEffect.xksl | 13 ++ .../Mipmapping/Voxel2x2x2MipmapKeys.cs | 15 ++ .../Mipmapping/Voxel2x2x2Mipmapper.cs | 9 ++ .../Mipmapping/Voxel2x2x2Mipmapper.xksl | 10 ++ .../Voxel2x2x2MipmapperHeuristic.cs | 9 ++ .../Voxel2x2x2MipmapperHeuristic.xksl | 25 ++++ .../Voxel2x2x2MipmapperPhysicallyBased.cs | 9 ++ .../Voxel2x2x2MipmapperPhysicallyBased.xksl | 21 +++ ...oxel2x2x2MipmapperPhysicallyBased.xksl.cs} | 0 .../Mipmapping/Voxel2x2x2MipmapperSimple.cs | 9 ++ .../Mipmapping/Voxel2x2x2MipmapperSimple.xksl | 10 ++ .../Mipmapping/VoxelMipmapHeuristic.xksl | 52 ------- .../VoxelMipmapPhysicallyBased.xksl | 39 ----- .../Mipmapping/VoxelMipmapSimple.xksl | 26 ---- .../VoxelStorageTextureClipmap.cs | 67 +++++---- .../engine/Xenko.Voxels/Xenko.Voxels.csproj | 140 ++++++++++++++++++ 60 files changed, 984 insertions(+), 253 deletions(-) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetBase.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetRandomHemisphere.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.xksl delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl rename sources/engine/Xenko.Voxels/Voxels/{Marching/Shaders/VoxelMarchConeFast.cs => Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.cs} (100%) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{VoxelMipmapHeuristic.cs => Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.cs} (100%) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.xksl rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{VoxelMipmapPhysicallyBased.cs => Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.cs} (100%) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.xksl rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{VoxelMipmapSimple.cs => Voxel2x2x2Mipmap.cs} (83%) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapKeys.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.xksl create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.xksl rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{VoxelMipmapPhysicallyBased.xksl.cs => Voxel2x2x2MipmapperPhysicallyBased.xksl.cs} (100%) create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.xksl delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl index 2dbfaff317..7960f6c214 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl @@ -1,4 +1,4 @@ -namespace Xenko.Rendering.Voxels.Debug +namespace Xenko.Rendering.Voxels.Debug { shader VoxelVisualizationRawShader : ImageEffectShader { @@ -25,4 +25,4 @@ return color.xyzz + float4(0.1, 0.1, 0.1, 1.0) * (1.0 - color.a); } }; -} \ No newline at end of file +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl index 3c1d647c24..9a8587f798 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl @@ -1,4 +1,4 @@ -namespace Xenko.Rendering.Voxels.Debug +namespace Xenko.Rendering.Voxels.Debug { effect VoxelVisualizationViewEffect { @@ -18,4 +18,4 @@ } } } -} \ No newline at end of file +} diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl index b089a1b9ac..ae6d9816c9 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl @@ -1,4 +1,4 @@ -namespace Xenko.Rendering.Voxels.Debug +namespace Xenko.Rendering.Voxels.Debug { shader VoxelVisualizationViewShader : MarchAttributes, ImageEffectShader { @@ -25,4 +25,4 @@ return color.xyzz + background * saturate(1.0-color.a); } }; -} \ No newline at end of file +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs index 274fe38f51..cffe88dae3 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs @@ -6,4 +6,18 @@ // and re-save the associated .xkfx. // -// Nothing to generate +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelMarchSetHemisphere12Keys + { + public static readonly ValueParameterKey offset = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl index 87d7e21c39..68e8c5f2ec 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl @@ -1,5 +1,9 @@ shader VoxelMarchSetHemisphere12 : VoxelMarchSet { + cbuffer PerView.Lighting + { + float offset; + } compose VoxelMarchMethod Marcher; override float4 March(float3 rayPos, float3 rayDir) { @@ -7,35 +11,42 @@ float3 bitan = cross(tan, rayDir); float3x3 tangentMatrix = float3x3(tan, bitan, rayDir); - float3 startPos = rayPos + rayDir * Marcher.StepSize(); + float3 startPos = rayPos + rayDir * Marcher.StepSize() * offset; float4 reflLighting = float4(0, 0, 0, 0); + + //Dot products of rays + float central = 0.84; + float outer = 0.22; + float sum = (central*4+outer*8); + central /= sum; + outer /= sum; rayDir = mul(float3(-0.38, -0.37, 0.84), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + reflLighting += Marcher.March(startPos, rayDir) * central; rayDir = mul(float3(-0.31, 0.43, 0.84), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + reflLighting += Marcher.March(startPos, rayDir) * central; rayDir = mul(float3(0.36, 0.39, 0.84), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + reflLighting += Marcher.March(startPos, rayDir) * central; rayDir = mul(float3(0.36, -0.39, 0.84), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.1475; + reflLighting += Marcher.March(startPos, rayDir) * central; rayDir = mul(float3(-0.87, 0.41, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(-0.35, 0.90, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(0.40, 0.88, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(0.92, 0.31, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(0.87, -0.43, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(0.30, -0.92, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(-0.43, -0.87, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(float3(-0.93, -0.28, 0.22), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * 0.0512; + reflLighting += Marcher.March(startPos, rayDir) * outer; return reflLighting; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs index 274fe38f51..3029fdfba2 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs @@ -6,4 +6,18 @@ // and re-save the associated .xkfx. // -// Nothing to generate +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelMarchSetHemisphere6Keys + { + public static readonly ValueParameterKey offset = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl index f2f74d081e..2589695b91 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl @@ -1,5 +1,9 @@ -shader VoxelMarchSetHemisphere6 : VoxelMarchSet +shader VoxelMarchSetHemisphere6 : VoxelMarchSet, ShaderBase { + cbuffer PerView.Lighting + { + float offset; + } compose VoxelMarchMethod Marcher; override float4 March(float3 rayPos, float3 rayDir) { @@ -7,33 +11,34 @@ float3 bitan = cross(tan, rayDir); float3x3 tangentMatrix = float3x3(tan, bitan, rayDir); - float3 startPos = rayPos + rayDir * Marcher.StepSize(); + float3 startPos = rayPos + rayDir * Marcher.StepSize() * offset; float4 reflLighting = float4(0, 0, 0, 0); - - float mainDot = 1.0; - float sideDot = dot(normalize(float3(0.527, -0.723, 0.445)), float3(0, 0, 1)); - float divisor = mainDot + sideDot * 5; - mainDot /= divisor; - sideDot /= divisor; + + //Dot products of rays + float central = 1.0; + float outer = 0.445; + float sum = central + outer * 5; + central /= sum; + outer /= sum; rayDir = mul(float3(0, 0, 1), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * mainDot; + reflLighting += Marcher.March(startPos, rayDir) * central; rayDir = mul(normalize(float3(0.85, 0.278, 0.445)), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * sideDot; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(normalize(float3(0.527, -0.723, 0.445)), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * sideDot; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(normalize(float3(-0.526, -0.724, 0.445)), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * sideDot; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(normalize(float3(-0.851, 0.277, 0.445)), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * sideDot; + reflLighting += Marcher.March(startPos, rayDir) * outer; rayDir = mul(normalize(float3(0.895, 0.445, 0.445)), tangentMatrix); - reflLighting += Marcher.March(startPos, rayDir) * sideDot; + reflLighting += Marcher.March(startPos, rayDir) * outer; return reflLighting; } diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.cs new file mode 100644 index 0000000000..aa8474f0db --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.cs @@ -0,0 +1,24 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelMarchSetRandomHemisphereKeys + { + public static readonly ValueParameterKey marchCount = ParameterKeys.NewValue(); + public static readonly ValueParameterKey time = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.xksl new file mode 100644 index 0000000000..c32b0085e2 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.xksl @@ -0,0 +1,44 @@ +shader VoxelMarchSetRandomHemisphere : VoxelMarchSet, ShaderBase +{ + cbuffer PerView.Lighting + { + int marchCount; + float time; + } + float Random(in float2 uv) + { + float2 noise = (frac(sin(dot(uv,float2(12.9898,78.233)*2.0)) * 43758.5453)); + return abs(noise.x + noise.y) * 0.5; + } + float3 CosineWeightedPointOnHemisphere(float2 uv) { + float u = Random(uv) * 6.28; + float v = Random(uv + 0.1); + + v = sqrt(v); + + float2 pos = float2(sin(u),cos(u)) * v; + + return float3(pos, sqrt(1-pos.x*pos.x-pos.y*pos.y)); + } + + compose VoxelMarchMethod Marcher; + override float4 March(float3 rayPos, float3 rayDir) + { + float3 tan = normalize(cross(rayDir, normalize(float3(1,1,1)))); + float3 bitan = cross(tan, rayDir); + float3x3 tangentMatrix = float3x3(tan, bitan, rayDir); + + float3 startPos = rayPos + rayDir * Marcher.StepSize(); + + float4 reflLighting = float4(0, 0, 0, 0); + + for(int i = 0; i < marchCount; i ++) + { + float3 dir = CosineWeightedPointOnHemisphere(streams.ShadingPosition.xy + i*1.73 + time); + dir = mul(dir, tangentMatrix); + reflLighting += Marcher.March(startPos, dir); + } + + return reflLighting/(float)marchCount; + } +}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetBase.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetBase.cs new file mode 100644 index 0000000000..274c81df20 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetBase.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public class VoxelMarchSetBase + { + public IVoxelMarchMethod Marcher { set; get; } = new VoxelMarchConePerMipmap(); + public float Offset { set; get; } = 1.0f; + public VoxelMarchSetBase() + { + + } + public VoxelMarchSetBase(IVoxelMarchMethod marcher) + { + Marcher = marcher; + } + + protected ValueParameterKey OffsetKey; + public virtual void UpdateMarchingLayout(string compositionName) + { + Marcher.UpdateMarchingLayout("Marcher." + compositionName); + } + public virtual void ApplyMarchingParameters(ParameterCollection parameters) + { + Marcher.ApplyMarchingParameters(parameters); + parameters.Set(OffsetKey, Offset); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs index 42437b7ac9..91f7f5f68e 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere12.cs @@ -8,9 +8,8 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Hemisphere (12)")] - public class VoxelMarchSetHemisphere12 : IVoxelMarchSet + public class VoxelMarchSetHemisphere12 : VoxelMarchSetBase, IVoxelMarchSet { - public IVoxelMarchMethod Marcher { set; get; } = new VoxelMarchCone(9, 1.0f, 1.0f); public VoxelMarchSetHemisphere12() { @@ -19,6 +18,7 @@ public VoxelMarchSetHemisphere12(IVoxelMarchMethod marcher) { Marcher = marcher; } + public ShaderSource GetMarchingShader(int attrID) { var mixin = new ShaderMixinSource(); @@ -27,13 +27,10 @@ public ShaderSource GetMarchingShader(int attrID) return mixin; } - public void UpdateMarchingLayout(string compositionName) - { - Marcher.UpdateMarchingLayout("Marcher."+compositionName); - } - public void ApplyMarchingParameters(ParameterCollection parameters) + public override void UpdateMarchingLayout(string compositionName) { - Marcher.ApplyMarchingParameters(parameters); + base.UpdateMarchingLayout(compositionName); + OffsetKey = VoxelMarchSetHemisphere12Keys.offset.ComposeWith(compositionName); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs index 80e753da34..85c341d16b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetHemisphere6.cs @@ -8,9 +8,8 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Hemisphere (6)")] - public class VoxelMarchSetHemisphere6 : IVoxelMarchSet + public class VoxelMarchSetHemisphere6 : VoxelMarchSetBase, IVoxelMarchSet { - public IVoxelMarchMethod Marcher { set; get; } = new VoxelMarchCone(9, 1.0f, 1.7f); public VoxelMarchSetHemisphere6() { @@ -19,6 +18,7 @@ public VoxelMarchSetHemisphere6(IVoxelMarchMethod marcher) { Marcher = marcher; } + public ShaderSource GetMarchingShader(int attrID) { var mixin = new ShaderMixinSource(); @@ -27,13 +27,10 @@ public ShaderSource GetMarchingShader(int attrID) return mixin; } - public void UpdateMarchingLayout(string compositionName) - { - Marcher.UpdateMarchingLayout("Marcher." + compositionName); - } - public void ApplyMarchingParameters(ParameterCollection parameters) + public override void UpdateMarchingLayout(string compositionName) { - Marcher.ApplyMarchingParameters(parameters); + base.UpdateMarchingLayout(compositionName); + OffsetKey = VoxelMarchSetHemisphere6Keys.offset.ComposeWith(compositionName); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetRandomHemisphere.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetRandomHemisphere.cs new file mode 100644 index 0000000000..44d088537c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/VoxelMarchSetRandomHemisphere.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + [Display("Random Hemisphere")] + public class VoxelMarchSetRandomHemisphere : IVoxelMarchSet + { + public IVoxelMarchMethod Marcher { set; get; } = new VoxelMarchConePerMipmap(); + public int Count = 6; + public bool AnimateNoise = false; + + float time = 0f; + + public VoxelMarchSetRandomHemisphere() + { + + } + public VoxelMarchSetRandomHemisphere(IVoxelMarchMethod marcher) + { + Marcher = marcher; + } + public ShaderSource GetMarchingShader(int attrID) + { + var mixin = new ShaderMixinSource(); + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchSetRandomHemisphere")); + mixin.AddComposition("Marcher", Marcher.GetMarchingShader(attrID)); + return mixin; + } + + ValueParameterKey CountKey; + ValueParameterKey TimeKey; + public void UpdateMarchingLayout(string compositionName) + { + Marcher.UpdateMarchingLayout("Marcher." + compositionName); + CountKey = VoxelMarchSetRandomHemisphereKeys.marchCount.ComposeWith(compositionName); + TimeKey = VoxelMarchSetRandomHemisphereKeys.time.ComposeWith(compositionName); + } + public void ApplyMarchingParameters(ParameterCollection parameters) + { + time += Count * 3.73f; + if (time > 4000f) time = 0f; + + Marcher.ApplyMarchingParameters(parameters); + parameters.Set(CountKey, Count); + parameters.Set(TimeKey, AnimateNoise ? time : 0f); + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl index 66c71fbbc3..086d27d401 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl @@ -1,5 +1,8 @@ shader VoxelMarchBeam : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes { + #ifndef AttributeID + #define AttributeID 0 + #endif override float4 March(float3 rayPos, float3 rayDir) { return MarchRadius(rayPos, rayDir, 1.0); diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl index 23bc6c3171..80a505e58c 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl @@ -1,27 +1,34 @@ -shader VoxelMarchCone : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes +shader VoxelMarchCone : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes { + #ifndef sampleFunction + #define sampleFunction Sample + #define AttributeID 0 + #endif override float4 March(float3 rayPos, float3 rayDir) { return MarchRadius(rayPos, rayDir, 1.0); } override float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale) { + float finalRatio = coneRatio.x * radiusScale; float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); - float dist = 0; + + float dist = voxelSize / max(1,finalRatio); + float4 light = float4(0.0, 0.0, 0.0, 0.0); - rayPos += voxelSize * rayDir; + rayPos += offset * voxelSize * rayDir; + for (int i = 0; i < steps; i ++) { - float size = max(voxelSize, coneRatio * radiusScale * dist); + float diameter = max(voxelSize, finalRatio * dist); float3 pos = rayPos + rayDir * dist; - light += AttributeSamplers[AttributeID].Sample(pos, -rayDir, size) * saturate(1.0 - light.a); + light += AttributeSamplers[AttributeID].sampleFunction(pos, -rayDir, diameter) * saturate(1.0 - light.a); - dist += size * stepScale; + dist += diameter * stepScale; } return light; } - override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } override float StepSizeRadius(float radiusScale) { return radiusScale * AttributeSamplers[AttributeID].VoxelSize(); } -}; \ No newline at end of file +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.cs new file mode 100644 index 0000000000..f3a6eac004 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.cs @@ -0,0 +1,27 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelMarchConeEditModeKeys + { + public static readonly ValueParameterKey steps = ParameterKeys.NewValue(); + public static readonly ValueParameterKey stepScale = ParameterKeys.NewValue(); + public static readonly ValueParameterKey coneRatio = ParameterKeys.NewValue(); + public static readonly ValueParameterKey fast = ParameterKeys.NewValue(); + public static readonly ValueParameterKey offset = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.xksl new file mode 100644 index 0000000000..9b48ac83ef --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.xksl @@ -0,0 +1,45 @@ +shader VoxelMarchConeEditMode : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes +{ + #ifndef AttributeID + #define AttributeID 0 + #endif + cbuffer PerView.Lighting + { + int steps; + float stepScale; + float coneRatio; + int fast; + float offset; + } + override float4 March(float3 rayPos, float3 rayDir) + { + return MarchRadius(rayPos, rayDir, 1.0); + } + override float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale) + { + float finalRatio = coneRatio.x * radiusScale; + float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); + + float dist = voxelSize / max(1,finalRatio); + + float4 light = float4(0.0, 0.0, 0.0, 0.0); + rayPos += offset * voxelSize * rayDir; + + for (int i = 0; i < steps; i ++) + { + float diameter = max(voxelSize, finalRatio * dist); + float3 pos = rayPos + rayDir * dist; + + if (fast) + light += AttributeSamplers[AttributeID].SampleNearestMip(pos, -rayDir, diameter) * saturate(1.0 - light.a); + else + light += AttributeSamplers[AttributeID].Sample(pos, -rayDir, diameter) * saturate(1.0 - light.a); + + dist += diameter * stepScale; + } + return light; + } + + override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } + override float StepSizeRadius(float radiusScale) { return radiusScale * AttributeSamplers[AttributeID].VoxelSize(); } +}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl deleted file mode 100644 index 8fcbe3e343..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.xksl +++ /dev/null @@ -1,27 +0,0 @@ -shader VoxelMarchConeFast : VoxelMarchMethod, VoxelRadiusMarchMethod, MarchAttributes -{ - override float4 March(float3 rayPos, float3 rayDir) - { - return MarchRadius(rayPos, rayDir, 1.0); - } - override float4 MarchRadius(float3 rayPos, float3 rayDir, float radiusScale) - { - float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); - float dist = 0; - float4 light = float4(0.0, 0.0, 0.0, 0.0); - rayPos += voxelSize * rayDir; - for (int i = 0; i < steps; i++) - { - float size = max(voxelSize, coneRatio * radiusScale * dist); - float3 pos = rayPos + rayDir * dist; - - light += AttributeSamplers[AttributeID].SampleNearestMip(pos, -rayDir, size) * saturate(1.0 - light.a); - - dist += size * stepScale; - } - return light; - } - - override float StepSize() { return AttributeSamplers[AttributeID].VoxelSize(); } - override float StepSizeRadius(float radiusScale) { return radiusScale * AttributeSamplers[AttributeID].VoxelSize(); } -}; \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs index 274fe38f51..6454801c7b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs @@ -6,4 +6,19 @@ // and re-save the associated .xkfx. // -// Nothing to generate +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering +{ + public static partial class VoxelMarchConePerMipmapKeys + { + public static readonly ValueParameterKey offset = ParameterKeys.NewValue(); + public static readonly ValueParameterKey coneRatioInv = ParameterKeys.NewValue(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl index 00d5153ff3..98f0381d6a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl @@ -1,9 +1,18 @@ shader VoxelMarchConePerMipmap : VoxelMarchMethod, MarchAttributes { + #ifndef AttributeID + #define AttributeID 0 + #endif + cbuffer PerView.Lighting + { + float offset; + float coneRatioInv; + } override float4 March(float3 rayPos, float3 rayDir) { float voxelSize = AttributeSamplers[AttributeID].VoxelSize(); - float dist = voxelSize; + rayPos += rayDir * voxelSize * offset; + float dist = voxelSize * coneRatioInv; float size = 0; float4 light = float4(0.0, 0.0, 0.0, 0.0); for (int i = 0; i < steps; i++) diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs index 2f8ffa4c9e..c05ddf2b91 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchCone.cs @@ -10,10 +10,18 @@ namespace Xenko.Rendering.Voxels [Display("Cone")] public class VoxelMarchCone : IVoxelMarchMethod { + [DataMember(0)] + public bool EditMode = true; + [DataMember(10)] public bool Fast = false; + [DataMember(20)] public int Steps = 9; + [DataMember(30)] public float StepScale = 1.0f; + [DataMember(40)] public float ConeRatio = 1.0f; + [DataMember(50)] + public float StartOffset = 1.0f; public VoxelMarchCone() { @@ -24,19 +32,51 @@ public VoxelMarchCone(int steps, float stepScale, float ratio) Steps = steps; StepScale = stepScale; ConeRatio = ratio; + EditMode = false; } public ShaderSource GetMarchingShader(int attrID) { var mixin = new ShaderMixinSource(); - mixin.Mixins.Add(new ShaderClassSource(Fast? "VoxelMarchConeFast" : "VoxelMarchCone", Steps, StepScale, ConeRatio)); + if (EditMode) + { + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchConeEditMode")); + } + else + { + mixin.Mixins.Add(new ShaderClassSource("VoxelMarchCone", Steps, StepScale, ConeRatio, StartOffset)); + mixin.Macros.Add(new ShaderMacro("sampleFunction", Fast ? "SampleNearestMip" : "Sample")); + } mixin.Macros.Add(new ShaderMacro("AttributeID", attrID)); + return mixin; } + + ValueParameterKey StepsKey; + ValueParameterKey StepScaleKey; + ValueParameterKey ConeRatioKey; + ValueParameterKey FastKey; + ValueParameterKey OffsetKey; public void UpdateMarchingLayout(string compositionName) { + if (EditMode) + { + StepsKey = VoxelMarchConeEditModeKeys.steps.ComposeWith(compositionName); + StepScaleKey = VoxelMarchConeEditModeKeys.stepScale.ComposeWith(compositionName); + ConeRatioKey = VoxelMarchConeEditModeKeys.coneRatio.ComposeWith(compositionName); + FastKey = VoxelMarchConeEditModeKeys.fast.ComposeWith(compositionName); + OffsetKey = VoxelMarchConeEditModeKeys.offset.ComposeWith(compositionName); + } } public void ApplyMarchingParameters(ParameterCollection parameters) { + if (EditMode) + { + parameters.Set(StepsKey, Steps); + parameters.Set(StepScaleKey, StepScale); + parameters.Set(ConeRatioKey, ConeRatio); + parameters.Set(FastKey, Fast ? 1 : 0); + parameters.Set(OffsetKey, StartOffset); + } } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs index 4da56d0e39..67c7721d2c 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Marching/VoxelMarchConePerMipmap.cs @@ -10,14 +10,22 @@ namespace Xenko.Rendering.Voxels [Display("Cone (Mipmap Exact)")] public class VoxelMarchConePerMipmap : IVoxelMarchMethod { - public int Steps = 7; + [DataMember(0)] + public int Steps { get; set; } = 7; + + [DataMember(10)] + public float ConeRatio { get; set; } = 1f; + + [DataMember(20)] + public float StartOffset { get; set; } = 0.5f; public VoxelMarchConePerMipmap() { } - public VoxelMarchConePerMipmap(int steps) + public VoxelMarchConePerMipmap(float ratio, int steps) { + ConeRatio = ratio; Steps = steps; } public ShaderSource GetMarchingShader(int attrID) @@ -27,11 +35,17 @@ public ShaderSource GetMarchingShader(int attrID) mixin.Macros.Add(new ShaderMacro("AttributeID", attrID)); return mixin; } + ValueParameterKey OffsetKey; + ValueParameterKey ConeRatioInvKey; public void UpdateMarchingLayout(string compositionName) { + OffsetKey = VoxelMarchConePerMipmapKeys.offset.ComposeWith(compositionName); + ConeRatioInvKey = VoxelMarchConePerMipmapKeys.coneRatioInv.ComposeWith(compositionName); } public void ApplyMarchingParameters(ParameterCollection parameters) { + parameters.Set(OffsetKey, StartOffset); + parameters.Set(ConeRatioInvKey, 1.0f/ConeRatio); } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs index 8e9724a240..a1786a855c 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs @@ -40,9 +40,10 @@ public void CollectAttributes(List attributes, VoxelizationStag attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); } + ShaderSource[] mipmapper = { new ShaderClassSource("Voxel2x2x2MipmapperSimple") }; public void PostProcess(RenderDrawContext drawContext) { - CoverageTex.PostProcess(drawContext, "VoxelMipmapSimple"); + CoverageTex.PostProcess(drawContext, mipmapper); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs index 535c8ac66b..f5f48adc89 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs @@ -72,17 +72,7 @@ override public bool RequiresColumns() } public void PostProcess(RenderDrawContext drawContext) { - switch (LightFalloff) - { - case LightFalloffs.Sharp: - VoxelLayout.PostProcess(drawContext, "VoxelMipmapSimple"); break; - case LightFalloffs.PhysicallyBased: - VoxelLayout.PostProcess(drawContext, "VoxelMipmapPhysicallyBased"); break; - case LightFalloffs.Heuristic: - VoxelLayout.PostProcess(drawContext, "VoxelMipmapHeuristic"); break; - default: - throw new InvalidOperationException("Cannot call PostProcess on voxel texture with unknown LightFalloff type."); - } + VoxelLayout.PostProcess(drawContext, LightFalloff); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs index 1bc0450a10..5fd0a454a8 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs @@ -49,10 +49,11 @@ override public bool RequiresColumns() { return false; } + ShaderSource[] mipmapper = { new ShaderClassSource("Voxel2x2x2MipmapperSimple") }; public void PostProcess(RenderDrawContext drawContext) { - SolidityTex.PostProcess(drawContext, "VoxelMipmapSimple"); + SolidityTex.PostProcess(drawContext, mipmapper); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs index a5fe847841..041d5d8cf9 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using Xenko.Shaders; +using static Xenko.Rendering.Voxels.VoxelAttributeEmissionOpacity; namespace Xenko.Rendering.Voxels { @@ -10,7 +11,7 @@ public interface IVoxelLayout void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage); void ClearOutputStorage(); - void PostProcess(RenderDrawContext drawContext, string MipMapShader); + void PostProcess(RenderDrawContext drawContext, LightFalloffs LightFalloff); //Writing ShaderSource GetVoxelizationShader(List modifiers); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs index 266328ef9a..a425e04fb5 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs @@ -28,5 +28,26 @@ public void UpdateSamplingLayout(string compositionName) BrightnessKey = VoxelAnisotropicSamplerKeys.maxBrightness.ComposeWith(compositionName); storageTex.UpdateSamplingLayout("storage." + compositionName); } + + ShaderClassSource mipmapXP = new ShaderClassSource("Voxel2x2x2Mipmapper_AnisoXP"); + ShaderClassSource mipmapXN = new ShaderClassSource("Voxel2x2x2Mipmapper_AnisoXN"); + ShaderClassSource mipmapYP = new ShaderClassSource("Voxel2x2x2Mipmapper_AnisoYP"); + ShaderClassSource mipmapYN = new ShaderClassSource("Voxel2x2x2Mipmapper_AnisoYN"); + ShaderClassSource mipmapZP = new ShaderClassSource("Voxel2x2x2Mipmapper_AnisoZP"); + ShaderClassSource mipmapZN = new ShaderClassSource("Voxel2x2x2Mipmapper_AnisoZN"); + override public void PostProcess(RenderDrawContext drawContext, LightFalloffs LightFalloff) + { + if (mipmapperSharp == null) + { + PrepareMipmapShaders(); + mipmapperHeuristic[0] = mipmapXP; + mipmapperHeuristic[1] = mipmapXN; + mipmapperHeuristic[2] = mipmapYP; + mipmapperHeuristic[3] = mipmapYN; + mipmapperHeuristic[4] = mipmapZP; + mipmapperHeuristic[5] = mipmapZN; + } + base.PostProcess(drawContext, LightFalloff); + } } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs index c474f90586..c69fc27b89 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs @@ -72,9 +72,43 @@ virtual public void ClearOutputStorage() storageTex = null; } - virtual public void PostProcess(RenderDrawContext drawContext, string shader) + protected ShaderSource[] mipmapperSharp = null; + protected ShaderSource[] mipmapperPhysicallyBased = null; + protected ShaderSource[] mipmapperHeuristic = null; + + virtual public void PrepareMipmapShaders() + { + mipmapperSharp = new ShaderSource[LayoutCount]; + mipmapperPhysicallyBased = new ShaderSource[LayoutCount]; + mipmapperHeuristic = new ShaderSource[LayoutCount]; + + ShaderSource sharp = new ShaderClassSource("Voxel2x2x2MipmapperSimple"); + ShaderSource physicallybased = new ShaderClassSource("Voxel2x2x2MipmapperPhysicallyBased"); + ShaderSource heuristic = new ShaderClassSource("Voxel2x2x2MipmapperHeuristic"); + for (int i = 0; i < LayoutCount; i++) + { + mipmapperSharp[i] = sharp; + mipmapperPhysicallyBased[i] = physicallybased; + mipmapperHeuristic[i] = heuristic; + } + } + virtual public void PostProcess(RenderDrawContext drawContext, LightFalloffs LightFalloff) { - storageTex.PostProcess(drawContext, shader); + if (mipmapperSharp == null) + { + PrepareMipmapShaders(); + } + switch (LightFalloff) + { + case LightFalloffs.Sharp: + storageTex.PostProcess(drawContext, mipmapperSharp); break; + case LightFalloffs.PhysicallyBased: + storageTex.PostProcess(drawContext, mipmapperPhysicallyBased); break; + case LightFalloffs.Heuristic: + storageTex.PostProcess(drawContext, mipmapperHeuristic); break; + default: + throw new InvalidOperationException("Cannot call PostProcess on voxel texture with unknown LightFalloff type."); + } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs index 5792306f65..6766e83f25 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/IVoxelStorageTexture.cs @@ -11,7 +11,7 @@ public interface IVoxelStorageTexture void UpdateVoxelizationLayout(string compositionName); void UpdateSamplingLayout(string compositionName); void ApplyVoxelizationParameters(ObjectParameterKey MainKey, ParameterCollection parameters); - void PostProcess(RenderDrawContext drawContext, string MipMapShader); + void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShaders); ShaderClassSource GetSamplingShader(); void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeFast.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl new file mode 100644 index 0000000000..501cc17314 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl @@ -0,0 +1,14 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper_AnisoXN : Voxel2x2x2Mipmapper + { + float4 blend(float4 s0, float4 s1) + { + return s0*(1-s1.a) + s1; + } + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (blend(s100,s000) + blend(s110,s010) + blend(s111,s011) + blend(s101,s001))/4; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.xksl new file mode 100644 index 0000000000..d94e0c513c --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.xksl @@ -0,0 +1,14 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper_AnisoXP : Voxel2x2x2Mipmapper + { + float4 blend(float4 s0, float4 s1) + { + return s0*(1-s1.a) + s1; + } + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (blend(s000,s100) + blend(s010,s110) + blend(s011,s111) + blend(s001,s101))/4; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.xksl new file mode 100644 index 0000000000..59ceee258e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.xksl @@ -0,0 +1,14 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper_AnisoYN : Voxel2x2x2Mipmapper + { + float4 blend(float4 s0, float4 s1) + { + return s0*(1-s1.a) + s1; + } + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (blend(s010,s000) + blend(s110,s100) + blend(s111,s101) + blend(s011,s001))/4; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.xksl new file mode 100644 index 0000000000..9ac80a4fa5 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.xksl @@ -0,0 +1,14 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper_AnisoYP : Voxel2x2x2Mipmapper + { + float4 blend(float4 s0, float4 s1) + { + return s0*(1-s1.a) + s1; + } + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (blend(s000,s010) + blend(s100,s110) + blend(s101,s111) + blend(s001,s011))/4; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.xksl new file mode 100644 index 0000000000..7f0532cca4 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.xksl @@ -0,0 +1,14 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper_AnisoZN : Voxel2x2x2Mipmapper + { + float4 blend(float4 s0, float4 s1) + { + return s0*(1-s1.a) + s1; + } + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (blend(s001,s000) + blend(s101,s100) + blend(s111,s110) + blend(s011,s010))/4; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.xksl new file mode 100644 index 0000000000..757df9eeb7 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.xksl @@ -0,0 +1,14 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper_AnisoZP : Voxel2x2x2Mipmapper + { + float4 blend(float4 s0, float4 s1) + { + return s0*(1-s1.a) + s1; + } + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (blend(s000,s001) + blend(s100,s101) + blend(s110,s111) + blend(s010,s011))/4; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.cs similarity index 83% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.cs index 7d29a660ef..58b90e89db 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.cs @@ -16,9 +16,10 @@ namespace Xenko.Rendering.Voxels { - public static partial class VoxelMipmapSimpleKeys + public static partial class Voxel2x2x2MipmapKeys { public static readonly ValueParameterKey ReadOffset = ParameterKeys.NewValue(); + public static readonly ValueParameterKey WriteOffset = ParameterKeys.NewValue(); public static readonly ObjectParameterKey ReadTex = ParameterKeys.NewObject(); public static readonly ObjectParameterKey WriteTex = ParameterKeys.NewObject(); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.xksl new file mode 100644 index 0000000000..3bccf7faca --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.xksl @@ -0,0 +1,32 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmap : Math, Texturing, ComputeShaderBase + { + stage float3 ReadOffset; + stage float3 WriteOffset; + stage Texture3D ReadTex; + stage RWTexture3D WriteTex; + + compose Voxel2x2x2Mipmapper mipmapper; + + override void Compute() + { + uint3 pos = streams.DispatchThreadId; + + uint3 posR = pos * 2 + (int3)ReadOffset; + + float4 fragmentSum = mipmapper.Mipmap( + ReadTex.Load(int4(posR, 0)), + ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)), + ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)), + ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)), + ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)), + ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)), + ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)), + ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) + ); + + WriteTex[pos + WriteOffset] = fragmentSum; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.cs new file mode 100644 index 0000000000..620e818b4e --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.cs @@ -0,0 +1,47 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + internal static partial class ShaderMixins + { + internal partial class Voxel2x2x2MipmapEffect : IShaderMixinBuilder + { + public void Generate(ShaderMixinSource mixin, ShaderMixinContext context) + { + context.Mixin(mixin, "Voxel2x2x2Mipmap"); + if (context.GetParam(Voxel2x2x2MipmapKeys.mipmapper) != null) + { + + { + var __mixinToCompose__ = context.GetParam(Voxel2x2x2MipmapKeys.mipmapper); + var __subMixin = new ShaderMixinSource(); + context.PushComposition(mixin, "mipmapper", __subMixin); + context.Mixin(__subMixin, __mixinToCompose__); + context.PopComposition(); + } + } + } + + [ModuleInitializer] + internal static void __Initialize__() + + { + ShaderMixinManager.Register("Voxel2x2x2MipmapEffect", new Voxel2x2x2MipmapEffect()); + } + } + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.xksl new file mode 100644 index 0000000000..66510bf7cf --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.xksl @@ -0,0 +1,13 @@ +namespace Xenko.Rendering.Voxels +{ + partial effect Voxel2x2x2MipmapEffect + { + using params Voxel2x2x2MipmapKeys; + + mixin Voxel2x2x2Mipmap; + if (Voxel2x2x2MipmapKeys.mipmapper!=null) + { + mixin compose mipmapper = Voxel2x2x2MipmapKeys.mipmapper; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapKeys.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapKeys.cs new file mode 100644 index 0000000000..88b9c35dfd --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapKeys.cs @@ -0,0 +1,15 @@ +using System; +using Xenko.Core; +using Xenko.Rendering; +using Xenko.Graphics; +using Xenko.Shaders; +using Xenko.Core.Mathematics; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Rendering.Voxels +{ + public static partial class Voxel2x2x2MipmapKeys + { + public static readonly PermutationParameterKey mipmapper = ParameterKeys.NewPermutation(); + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.xksl new file mode 100644 index 0000000000..ff6e00e285 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.xksl @@ -0,0 +1,10 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2Mipmapper : Math, Texturing, ComputeShaderBase + { + float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return float4(1,0,0,1); + } + }; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.xksl new file mode 100644 index 0000000000..b84a3334f7 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.xksl @@ -0,0 +1,25 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2MipmapperHeuristic : Voxel2x2x2Mipmapper + { + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + float filledSum = ceil(s000.a) + ceil(s100.a) + ceil(s110.a) + ceil(s101.a) + ceil(s011.a) + ceil(s010.a) + ceil(s001.a) + ceil(s111.a); + float4 fragmentSum = (s000 + s100 + s110 + s101 + s011 + s010 + s001 + s111); + fragmentSum.rgb /= max(filledSum, 4); + fragmentSum.a /= 8; + return fragmentSum; + //Rather than divide by 8... + //I figure that since the visible surface of the + //emitter is a 2D projection, it should decrease + //by 2 dimensions rather than 3 (i.e divide by 4 rather than 8). + + //This makes the lighting fall-off much more realistic, + //but I find the opacity coverage too strong then. + //so keep that dividing by 8. + + //Of course, then the brightness in areas with clusters of voxels + //becomes too high, so instead divide by the number of filled voxels, minimum 4 + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.xksl new file mode 100644 index 0000000000..569cb093ac --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.xksl @@ -0,0 +1,21 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2MipmapperPhysicallyBased : Voxel2x2x2Mipmapper + { + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + float4 fragmentSum = (s000 + s100 + s110 + s101 + s011 + s010 + s001 + s111); + fragmentSum.rgb /= 4; + fragmentSum.a /= 8; + return fragmentSum; + //Rather than divide by 8... + //I figure that since the visible surface of the + //emitter is a 2D projection, it should decrease + //by 2 dimensions rather than 3 (i.e divide by 4 rather than 8). + + //This makes the lighting fall-off much more realistic, + //but I find the opacity coverage too strong then. + //so keep that dividing by 8. + } + }; +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.cs new file mode 100644 index 0000000000..274fe38f51 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.cs @@ -0,0 +1,9 @@ +// +// Do not edit this file yourself! +// +// This code was generated by Xenko Shader Mixin Code Generator. +// To generate it yourself, please install Xenko.VisualStudio.Package .vsix +// and re-save the associated .xkfx. +// + +// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.xksl new file mode 100644 index 0000000000..bd575c19c6 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.xksl @@ -0,0 +1,10 @@ +namespace Xenko.Rendering.Voxels +{ + shader Voxel2x2x2MipmapperSimple : Voxel2x2x2Mipmapper + { + override float4 Mipmap(float4 s000, float4 s100, float4 s110, float4 s101, float4 s011, float4 s010, float4 s001, float4 s111) + { + return (s000 + s100 + s110 + s101 + s011 + s010 + s001 + s111)/8; + } + }; +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl deleted file mode 100644 index 0c167d133e..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapHeuristic.xksl +++ /dev/null @@ -1,52 +0,0 @@ -namespace Xenko.Rendering.Voxels -{ - shader VoxelMipmapHeuristic : Math, Texturing, ComputeShaderBase - { - [Link("VoxelMipmapSimple.ReadOffset")] - stage float3 ReadOffset; - [Link("VoxelMipmapSimple.ReadTex")] - stage Texture3D ReadTex; - [Link("VoxelMipmapSimple.WriteTex")] - stage RWTexture3D WriteTex; - override void Compute() - { - uint3 pos = streams.DispatchThreadId; - - uint3 posR = pos * 2 + (int3)ReadOffset; - float4 fragmentSum = ( - ReadTex.Load(int4(posR, 0)) + - ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)) + - ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)) + - ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)) + - ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)) + - ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)) + - ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)) + - ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) - ); - float filledSum = ( - ceil(ReadTex.Load(int4(posR, 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)).a) + - ceil(ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)).a) - ); - fragmentSum.rgb /= max(filledSum, 4); - fragmentSum.a /= 8; - WriteTex[pos] = (fragmentSum); - //Rather than divide by 8... - //I figure that since the visible surface of the - //emitter is a 2D projection, it should decrease - //by 2 dimensions rather than 3 (i.e divide by 4 rather than 8). - - //This makes the lighting fall-off much more realistic, - //but I find the opacity coverage too strong then. - //so keep that dividing by 8. - - //Of course, then the brightness in areas with clusters of voxels - //becomes too high, so instead divide by the number of filled voxels, minimum 4 - } - }; -} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl deleted file mode 100644 index bd309ba38e..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapPhysicallyBased.xksl +++ /dev/null @@ -1,39 +0,0 @@ -namespace Xenko.Rendering.Voxels -{ - shader VoxelMipmapPhysicallyBased : Math, Texturing, ComputeShaderBase - { - [Link("VoxelMipmapSimple.ReadOffset")] - stage float3 ReadOffset; - [Link("VoxelMipmapSimple.ReadTex")] - stage Texture3D ReadTex; - [Link("VoxelMipmapSimple.WriteTex")] - stage RWTexture3D WriteTex; - override void Compute() - { - uint3 pos = streams.DispatchThreadId; - - uint3 posR = pos * 2 + (int3)ReadOffset; - float4 fragmentSum = ( - ReadTex.Load(int4(posR, 0)) + - ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)) + - ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)) + - ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)) + - ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)) + - ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)) + - ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)) + - ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) - ); - fragmentSum.rgb /= 4; - fragmentSum.a /= 8; - WriteTex[pos] = (fragmentSum); - //Rather than divide by 8... - //I figure that since the visible surface of the - //emitter is a 2D projection, it should decrease - //by 2 dimensions rather than 3 (i.e divide by 4 rather than 8). - - //This makes the lighting fall-off much more realistic, - //but I find the opacity coverage too strong then. - //so keep that dividing by 8. - } - }; -} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl deleted file mode 100644 index ae25ba3f05..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/VoxelMipmapSimple.xksl +++ /dev/null @@ -1,26 +0,0 @@ -namespace Xenko.Rendering.Voxels -{ - shader VoxelMipmapSimple : Math, Texturing, ComputeShaderBase - { - stage float3 ReadOffset; - stage Texture3D ReadTex; - stage RWTexture3D WriteTex; - override void Compute() - { - uint3 pos = streams.DispatchThreadId; - - uint3 posR = pos * 2 + (int3)ReadOffset; - float4 fragmentSum = ( - ReadTex.Load(int4(posR, 0)) + - ReadTex.Load(int4(posR + uint3(1, 0, 0), 0)) + - ReadTex.Load(int4(posR + uint3(1, 1, 0), 0)) + - ReadTex.Load(int4(posR + uint3(1, 0, 1), 0)) + - ReadTex.Load(int4(posR + uint3(0, 1, 1), 0)) + - ReadTex.Load(int4(posR + uint3(0, 1, 0), 0)) + - ReadTex.Load(int4(posR + uint3(0, 0, 1), 0)) + - ReadTex.Load(int4(posR + uint3(1, 1, 1), 0)) - ); - WriteTex[pos] = (fragmentSum / 8.0); - } - }; -} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs index 5d53d410a7..4d3ec62bf4 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using Xenko.Core.Mathematics; using Xenko.Graphics; @@ -35,7 +35,6 @@ public void ApplyVoxelizationParameters(ObjectParameterKey MainKey, Par { parameters.Set(MainKey, ClipMaps); } - string curMipMapShader = ""; Xenko.Rendering.ComputeEffect.ComputeEffectShader VoxelMipmapSimple; //Memory leaks if the ThreadGroupCounts/Numbers changes (I suppose due to recompiles...?) //so instead cache them as seperate shaders. @@ -55,15 +54,19 @@ Vector3 Mod(Vector3 v, Vector3 m) return new Vector3(Mod(v.X, m.X), Mod(v.Y, m.Y), Mod(v.Z, m.Z)); } - public void PostProcess(RenderDrawContext drawContext, string MipMapShader) + public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShaders) { - if (VoxelMipmapSimple == null || curMipMapShader != MipMapShader) + if (mipmapShaders.Length != LayoutSize) { - if (VoxelMipmapSimple != null) - VoxelMipmapSimple.Dispose(); - VoxelMipmapSimple = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = MipMapShader }; + return; } - if (VoxelMipmapSimpleGroups == null || VoxelMipmapSimpleGroups.Length != TempMipMaps.Length || curMipMapShader != MipMapShader) + + if (VoxelMipmapSimple == null) + { + VoxelMipmapSimple = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = "Voxel2x2x2MipmapEffect" }; + } + + if (VoxelMipmapSimpleGroups == null || VoxelMipmapSimpleGroups.Length != TempMipMaps.Length) { if (VoxelMipmapSimpleGroups != null) { @@ -75,10 +78,9 @@ public void PostProcess(RenderDrawContext drawContext, string MipMapShader) VoxelMipmapSimpleGroups = new Xenko.Rendering.ComputeEffect.ComputeEffectShader[TempMipMaps.Length]; for (int i = 0; i < VoxelMipmapSimpleGroups.Length; i++) { - VoxelMipmapSimpleGroups[i] = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = MipMapShader }; + VoxelMipmapSimpleGroups[i] = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = "Voxel2x2x2MipmapEffect" }; } } - curMipMapShader = MipMapShader; int offsetIndex = 0; //Mipmap detailed clipmaps into less detailed ones @@ -89,13 +91,19 @@ public void PostProcess(RenderDrawContext drawContext, string MipMapShader) for (int i = 0; i < ClipMapCount - 1; i++) { Vector3 Offset = MippingOffset[offsetIndex]; - VoxelMipmapSimple.ThreadGroupCounts = threadGroupCounts; - VoxelMipmapSimple.ThreadNumbers = new Int3((int)totalResolution.X / threadGroupCounts.X, (int)totalResolution.Y / threadGroupCounts.Y, (int)totalResolution.Z / threadGroupCounts.Z); - VoxelMipmapSimple.Parameters.Set(VoxelMipmapSimpleKeys.ReadTex, ClipMaps); - VoxelMipmapSimple.Parameters.Set(VoxelMipmapSimpleKeys.WriteTex, TempMipMaps[0]); - VoxelMipmapSimple.Parameters.Set(VoxelMipmapSimpleKeys.ReadOffset, -(Mod(Offset,new Vector3(2))) + new Vector3(0, (int)totalResolution.Y * i, 0)); - ((RendererBase)VoxelMipmapSimple).Draw(drawContext); + VoxelMipmapSimple.ThreadNumbers = new Int3(8); + VoxelMipmapSimple.ThreadGroupCounts = ToInt3((ClipMapResolution / 2f) / (Vector3)VoxelMipmapSimple.ThreadNumbers); + + for (int axis = 0; axis < LayoutSize; axis++) + { + VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.ReadTex, ClipMaps); + VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.WriteTex, TempMipMaps[0]); + VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.ReadOffset, -(Mod(Offset, new Vector3(2))) + new Vector3(0, (int)totalResolution.Y * i + (int)ClipMapResolution.Y * axis, 0)); + VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.WriteOffset, new Vector3(0, ClipMapResolution.Y / 2 * axis, 0)); + VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.mipmapper, mipmapShaders[axis]); + ((RendererBase)VoxelMipmapSimple).Draw(drawContext); + } Offset -= Mod(Offset, new Vector3(2)); //Copy each axis, ignoring the top and bottom plane @@ -134,7 +142,6 @@ public void PostProcess(RenderDrawContext drawContext, string MipMapShader) } } Vector3 resolution = ClipMapResolution; - resolution.Y *= LayoutSize; offsetIndex = ClipMapCount-1; //Mipmaps for the largest clipmap for (int i = 0; i < TempMipMaps.Length - 1; i++) @@ -147,18 +154,24 @@ public void PostProcess(RenderDrawContext drawContext, string MipMapShader) mipmapShader.ThreadNumbers = ToInt3(threadNums); mipmapShader.ThreadGroupCounts = ToInt3(resolution / threadNums); - if (i == 0) - { - mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadTex, ClipMaps); - mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadOffset, -Offset + new Vector3(0, (int)ClipMapResolution.Y * LayoutSize * (ClipMapCount - 1), 0)); - } - else + for (int axis = 0; axis < LayoutSize; axis++) { - mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadTex, TempMipMaps[i - 1]); - mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.ReadOffset, -Offset + new Vector3(0, 0, 0)); + if (i == 0) + { + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.ReadTex, ClipMaps); + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.ReadOffset, -Offset + new Vector3(0, (int)ClipMapResolution.Y * LayoutSize * (ClipMapCount - 1) + (int)ClipMapResolution.Y * axis, 0)); + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.WriteOffset, new Vector3(0, resolution.Y * axis, 0)); + } + else + { + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.ReadTex, TempMipMaps[i - 1]); + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.ReadOffset, -Offset + new Vector3(0, resolution.Y * axis * 2, 0)); + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.WriteOffset, new Vector3(0, resolution.Y * axis, 0)); + } + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.WriteTex, TempMipMaps[i]); + mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.mipmapper, mipmapShaders[axis]); + ((RendererBase)mipmapShader).Draw(drawContext); } - mipmapShader.Parameters.Set(VoxelMipmapSimpleKeys.WriteTex, TempMipMaps[i]); - ((RendererBase)mipmapShader).Draw(drawContext); //Don't seem to be able to read and write to the same texture, even if the views //point to different mipmaps. drawContext.CommandList.CopyRegion(TempMipMaps[i], 0, null, MipMaps, i); diff --git a/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj b/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj index 92f52efdd8..702538bdf0 100644 --- a/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj +++ b/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj @@ -81,6 +81,12 @@ True VoxelMarchSetHemisphere6.xksl + + True + True + True + VoxelMarchSetRandomHemisphere.xksl + True True @@ -105,6 +111,12 @@ True VoxelMarchCone.xksl + + True + True + True + VoxelMarchConeEditMode.xksl + True True @@ -363,6 +375,78 @@ True LocalSamples.xksl + + True + True + True + Voxel2x2x2Mipmapper_AnisoXN.xksl + + + True + True + True + Voxel2x2x2Mipmapper_AnisoXP.xksl + + + True + True + True + Voxel2x2x2Mipmapper_AnisoYN.xksl + + + True + True + True + Voxel2x2x2Mipmapper_AnisoYP.xksl + + + True + True + True + Voxel2x2x2Mipmapper_AnisoZN.xksl + + + True + True + True + Voxel2x2x2Mipmapper_AnisoZP.xksl + + + True + True + True + Voxel2x2x2Mipmap.xksl + + + True + True + True + Voxel2x2x2MipmapEffect.xksl + + + True + True + True + Voxel2x2x2Mipmapper.xksl + + + True + True + True + Voxel2x2x2MipmapperHeuristic.xksl + + + True + True + True + Voxel2x2x2MipmapperPhysicallyBased.xksl + + + True + True + True + Voxel2x2x2MipmapperSimple.xksl + True True @@ -473,6 +557,10 @@ XenkoShaderKeyGenerator VoxelMarchSetHemisphere6.cs + + XenkoShaderKeyGenerator + VoxelMarchSetRandomHemisphere.cs + XenkoShaderKeyGenerator MarchAttributes.cs @@ -489,6 +577,10 @@ XenkoShaderKeyGenerator VoxelMarchCone.cs + + XenkoShaderKeyGenerator + VoxelMarchConeEditMode.cs + XenkoShaderKeyGenerator VoxelMarchConeFast.cs @@ -661,6 +753,54 @@ XenkoShaderKeyGenerator LocalSamples.cs + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper_AnisoXN.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper_AnisoXP.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper_AnisoYN.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper_AnisoYP.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper_AnisoZN.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper_AnisoZP.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmap.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2MipmapEffect.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2Mipmapper.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2MipmapperHeuristic.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2MipmapperPhysicallyBased.cs + + + XenkoShaderKeyGenerator + Voxel2x2x2MipmapperSimple.cs + XenkoShaderKeyGenerator VoxelMipmapHeuristic.cs From 374b7fabbf5ffa8b805b02a97e151577f93da81d Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Wed, 22 Jan 2020 23:37:44 +1100 Subject: [PATCH 0656/2038] Moved math functions into Xenko.Core.Mathematics - MathUtil.Mod - Vector3.Mod - Vector3 explicit cast to Int3 --- .../core/Xenko.Core.Mathematics/MathUtil.cs | 11 ++++++ .../core/Xenko.Core.Mathematics/Vector3.cs | 38 +++++++++++++++++++ .../VoxelStorageTextureClipmap.cs | 24 +++--------- 3 files changed, 54 insertions(+), 19 deletions(-) diff --git a/sources/core/Xenko.Core.Mathematics/MathUtil.cs b/sources/core/Xenko.Core.Mathematics/MathUtil.cs index cc0c5f165a..868000fafa 100644 --- a/sources/core/Xenko.Core.Mathematics/MathUtil.cs +++ b/sources/core/Xenko.Core.Mathematics/MathUtil.cs @@ -681,5 +681,16 @@ public static Vector4 Snap(Vector4 value, float gap) (float)Math.Round((value.Z / gap), MidpointRounding.AwayFromZero) * gap, (float)Math.Round((value.W / gap), MidpointRounding.AwayFromZero) * gap); } + + /// + /// Computes standard mathematical modulo (as opposed to remainder). + /// + /// The value. + /// The divisor. + /// A value between 0 and divisor. The result will have the same sign as divisor. + public static float Mod(float value, float divisor) + { + return ((value % divisor) + divisor) % divisor; + } } } diff --git a/sources/core/Xenko.Core.Mathematics/Vector3.cs b/sources/core/Xenko.Core.Mathematics/Vector3.cs index 427ef4605c..7f4a74b234 100644 --- a/sources/core/Xenko.Core.Mathematics/Vector3.cs +++ b/sources/core/Xenko.Core.Mathematics/Vector3.cs @@ -809,6 +809,34 @@ public static Vector3 CatmullRom(Vector3 value1, Vector3 value2, Vector3 value3, return result; } + /// + /// Performs mathematical modulo component-wise (see MathUtil.Mod). + /// + /// The first source vector. + /// The second source vector. + /// When the method completes, contains an new vector composed of each component's modulo. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void Mod(ref Vector3 left, ref Vector3 right, out Vector3 result) + { + result.X = MathUtil.Mod(left.X, right.X); + result.Y = MathUtil.Mod(left.Y, right.Y); + result.Z = MathUtil.Mod(left.Z, right.Z); + } + + /// + /// Performs mathematical modulo component-wise (see MathUtil.Mod). + /// + /// The first source vector. + /// The second source vector. + /// When the method completes, contains an new vector composed of each component's modulo. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static Vector3 Mod(Vector3 left, Vector3 right) + { + Vector3 result; + Mod(ref left, ref right, out result); + return result; + } + /// /// Returns a vector containing the smallest components of the specified vectors. /// @@ -1579,6 +1607,16 @@ public static explicit operator Vector4(Vector3 value) return new Vector4(value, 0.0f); } + /// + /// Performs an explicit conversion from to . + /// + /// The value. + /// The result of the conversion. + public static explicit operator Int3(Vector3 value) + { + return new Int3((int)value.X, (int)value.Y, (int)value.Z); + } + /// /// Tests whether one 3D vector is near another 3D vector. /// diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs index 4d3ec62bf4..db8583d8fb 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs @@ -40,20 +40,6 @@ public void ApplyVoxelizationParameters(ObjectParameterKey MainKey, Par //so instead cache them as seperate shaders. Xenko.Rendering.ComputeEffect.ComputeEffectShader[] VoxelMipmapSimpleGroups; - Int3 ToInt3(Vector3 v) - { - return new Int3((int)v.X, (int)v.Y, (int)v.Z); - } - - float Mod(float v, float m) - { - return ((v % m) + m) % m;//Proper modulo - } - Vector3 Mod(Vector3 v, Vector3 m) - { - return new Vector3(Mod(v.X, m.X), Mod(v.Y, m.Y), Mod(v.Z, m.Z)); - } - public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShaders) { if (mipmapShaders.Length != LayoutSize) @@ -93,19 +79,19 @@ public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShad Vector3 Offset = MippingOffset[offsetIndex]; VoxelMipmapSimple.ThreadNumbers = new Int3(8); - VoxelMipmapSimple.ThreadGroupCounts = ToInt3((ClipMapResolution / 2f) / (Vector3)VoxelMipmapSimple.ThreadNumbers); + VoxelMipmapSimple.ThreadGroupCounts = (Int3)((ClipMapResolution / 2f) / (Vector3)VoxelMipmapSimple.ThreadNumbers); for (int axis = 0; axis < LayoutSize; axis++) { VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.ReadTex, ClipMaps); VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.WriteTex, TempMipMaps[0]); - VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.ReadOffset, -(Mod(Offset, new Vector3(2))) + new Vector3(0, (int)totalResolution.Y * i + (int)ClipMapResolution.Y * axis, 0)); + VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.ReadOffset, -(Vector3.Mod(Offset, new Vector3(2))) + new Vector3(0, (int)totalResolution.Y * i + (int)ClipMapResolution.Y * axis, 0)); VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.WriteOffset, new Vector3(0, ClipMapResolution.Y / 2 * axis, 0)); VoxelMipmapSimple.Parameters.Set(Voxel2x2x2MipmapKeys.mipmapper, mipmapShaders[axis]); ((RendererBase)VoxelMipmapSimple).Draw(drawContext); } - Offset -= Mod(Offset, new Vector3(2)); + Offset -= Vector3.Mod(Offset, new Vector3(2)); //Copy each axis, ignoring the top and bottom plane for (int axis = 0; axis < LayoutSize; axis++) { @@ -151,8 +137,8 @@ public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShad resolution /= 2; Vector3 threadNums = Vector3.Min(resolution, new Vector3(8)); - mipmapShader.ThreadNumbers = ToInt3(threadNums); - mipmapShader.ThreadGroupCounts = ToInt3(resolution / threadNums); + mipmapShader.ThreadNumbers = (Int3)(threadNums); + mipmapShader.ThreadGroupCounts = (Int3)(resolution / threadNums); for (int axis = 0; axis < LayoutSize; axis++) { From b83e8f273e8ed4db1a6e4da116d5acc12cb254d0 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 22 Jan 2020 19:23:00 -0500 Subject: [PATCH 0657/2038] Rendering: more threading performance (and safety check) --- sources/engine/Xenko.Rendering/Rendering/Properties.cs | 8 ++++++++ .../Rendering/RootEffectRenderFeature.cs | 10 ++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Properties.cs b/sources/engine/Xenko.Rendering/Rendering/Properties.cs index 4a5d83be90..13362134d1 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Properties.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Properties.cs @@ -5,6 +5,8 @@ #pragma warning disable SA1649 // File name must match first type name #pragma warning disable SA1402 // File may only contain a single class +using System.Runtime.CompilerServices; + namespace Xenko.Rendering { public enum DataType @@ -591,6 +593,12 @@ internal StaticObjectPropertyData(T[] data) Data = data; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public bool IsValidIndex(StaticObjectNodeReference index) + { + return index.Index >= 0 && index.Index < Data.Length; + } + public ref T this[StaticObjectNodeReference index] => ref Data[index.Index]; } diff --git a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs index b2e057a380..6beab62ca5 100644 --- a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs @@ -359,25 +359,23 @@ private void PrepareRenderTargetExtensionsMixins(RenderDrawContext context) var renderEffectKey = RenderEffectKey; var renderEffects = RenderData.GetData(renderEffectKey); - // TODO dispatcher - foreach (var node in RenderNodes) + Xenko.Core.Threading.Dispatcher.ForEach(RenderNodes, (renderNode) => { - var renderNode = node; var renderObject = renderNode.RenderObject; // Get RenderEffect var staticObjectNode = renderObject.StaticObjectNode; var staticEffectObjectNode = staticObjectNode * EffectPermutationSlotCount + effectSlots[renderNode.RenderStage.Index].Index; - var renderEffect = renderEffects[staticEffectObjectNode]; + RenderEffect renderEffect; - if (renderEffect != null) + if (renderEffects.IsValidIndex(staticEffectObjectNode) && (renderEffect = renderEffects[staticEffectObjectNode]) != null) { var renderStage = renderNode.RenderStage; var renderStageShaderSource = renderStage.OutputValidator.ShaderSource; if (renderStageShaderSource != null) renderEffect.EffectValidator.ValidateParameter(XenkoEffectBaseKeys.RenderTargetExtensions, renderStageShaderSource); } - } + }); } /// From 21cf507a5acdefb865973538858e8fb3d31762bb Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 23 Jan 2020 11:21:51 -0500 Subject: [PATCH 0658/2038] Rendering: various minor performance improvements and safety checks --- .../SceneEditor/HighlightRenderFeature.cs | 4 ++-- .../SceneEditor/MaterialFilterRenderFeature.cs | 3 ++- .../SceneEditor/PickingRenderFeature.cs | 2 +- .../SceneEditor/WireframeRenderFeature.cs | 4 ++-- .../Rendering/ParticleEmitterRenderFeature.cs | 6 ++++-- .../SubsurfaceScatteringRenderFeature.cs | 2 +- .../Rendering/Lights/ForwardLightingRenderFeature.cs | 4 ++-- .../Rendering/Materials/MaterialRenderFeature.cs | 4 ++-- .../engine/Xenko.Rendering/Rendering/MeshRenderFeature.cs | 2 +- .../Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs | 2 +- sources/engine/Xenko.Rendering/Rendering/Properties.cs | 6 ------ .../Xenko.Rendering/Rendering/RootEffectRenderFeature.cs | 4 ++-- .../Xenko.Rendering/Rendering/SkinningRenderFeature.cs | 2 +- sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs | 4 ++-- 14 files changed, 23 insertions(+), 26 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/SceneEditor/HighlightRenderFeature.cs b/sources/editor/Xenko.Assets.Presentation/SceneEditor/HighlightRenderFeature.cs index 3358701c22..f1e0d669e7 100644 --- a/sources/editor/Xenko.Assets.Presentation/SceneEditor/HighlightRenderFeature.cs +++ b/sources/editor/Xenko.Assets.Presentation/SceneEditor/HighlightRenderFeature.cs @@ -62,7 +62,7 @@ public override unsafe void Prepare(RenderDrawContext context) foreach (var renderNode in ((RootEffectRenderFeature)RootRenderFeature).RenderNodes) { - var perDrawLayout = renderNode.RenderEffect.Reflection?.PerDrawLayout; + var perDrawLayout = renderNode.RenderEffect?.Reflection?.PerDrawLayout; if (perDrawLayout == null) continue; @@ -83,7 +83,7 @@ public override void ProcessPipelineState(RenderContext context, RenderNodeRefer base.ProcessPipelineState(context, renderNodeReference, ref renderNode, renderObject, pipelineState); // Check if this is a highlight rendering - var perDrawLayout = renderNode.RenderEffect.Reflection?.PerDrawLayout; + var perDrawLayout = renderNode.RenderEffect?.Reflection?.PerDrawLayout; if (perDrawLayout == null) return; diff --git a/sources/editor/Xenko.Assets.Presentation/SceneEditor/MaterialFilterRenderFeature.cs b/sources/editor/Xenko.Assets.Presentation/SceneEditor/MaterialFilterRenderFeature.cs index 9c6f2d0638..c3db72b3b8 100644 --- a/sources/editor/Xenko.Assets.Presentation/SceneEditor/MaterialFilterRenderFeature.cs +++ b/sources/editor/Xenko.Assets.Presentation/SceneEditor/MaterialFilterRenderFeature.cs @@ -32,8 +32,9 @@ public override void PrepareEffectPermutations(RenderDrawContext context) var renderEffects = RootRenderFeature.RenderData.GetData(renderEffectKey); int effectSlotCount = ((RootEffectRenderFeature)RootRenderFeature).EffectPermutationSlotCount; - foreach (var renderObject in RootRenderFeature.RenderObjects) + for (int j=0; j // TODO: PERFORMANCE: Use this instead? foreach (RenderNode renderNode in ((RootEffectRenderFeature)RootRenderFeature).RenderNodes) { - var perDrawLayout = renderNode.RenderEffect.Reflection?.PerDrawLayout; + var perDrawLayout = renderNode.RenderEffect?.Reflection?.PerDrawLayout; if (perDrawLayout == null) { continue; diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs index 6d97640240..98350c89e2 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs @@ -410,10 +410,10 @@ public override void Prepare(RenderDrawContext context) var renderNode = RootRenderFeature.GetRenderNode(renderNodeReference); // Ignore fallback effects - if (renderNode.RenderEffect.State != RenderEffectState.Normal) + if (renderNode.RenderEffect?.State != RenderEffectState.Normal) return; - var drawLayout = renderNode.RenderEffect.Reflection?.PerDrawLayout; + var drawLayout = renderNode.RenderEffect?.Reflection?.PerDrawLayout; if (drawLayout == null) return; diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs index 906724e769..5c3b0665e2 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs @@ -278,7 +278,7 @@ public override void Prepare(RenderDrawContext context) var renderMesh = (RenderMesh)renderNode.RenderObject; // Ignore fallback effects - if (renderNode.RenderEffect.State != RenderEffectState.Normal) + if (renderNode.RenderEffect?.State != RenderEffectState.Normal) return; // Collect materials and create associated MaterialInfo (includes reflection) first time @@ -325,7 +325,7 @@ public override void Draw(RenderDrawContext context, RenderView renderView, Rend public static unsafe bool UpdateMaterial(RenderSystem renderSystem, RenderDrawContext context, MaterialInfoBase materialInfo, int materialSlotIndex, RenderEffect renderEffect, ParameterCollection materialParameters) { - if (renderEffect.Reflection == null) + if (renderEffect?.Reflection == null) return false; var resourceGroupDescription = renderEffect.Reflection.ResourceGroupDescriptions[materialSlotIndex]; diff --git a/sources/engine/Xenko.Rendering/Rendering/MeshRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/MeshRenderFeature.cs index 73bebfae95..d95b03f743 100644 --- a/sources/engine/Xenko.Rendering/Rendering/MeshRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/MeshRenderFeature.cs @@ -183,7 +183,7 @@ public override void Draw(RenderDrawContext context, RenderView renderView, Rend // Get effect // TODO: Use real effect slot var renderEffect = renderNode.RenderEffect; - if (renderEffect.Effect == null || renderEffect.Reflection == null) + if (renderEffect?.Effect == null || renderEffect.Reflection == null) continue; // Bind VB diff --git a/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs index f7cc26cc66..8d541d9896 100644 --- a/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs @@ -149,7 +149,7 @@ public override unsafe void Prepare(RenderDrawContext context) // Update cbuffer for previous WVP matrix Dispatcher.ForEach(((RootEffectRenderFeature)RootRenderFeature).RenderNodes, (ref RenderNode renderNode) => { - var perDrawLayout = renderNode.RenderEffect.Reflection?.PerDrawLayout; + var perDrawLayout = renderNode.RenderEffect?.Reflection?.PerDrawLayout; if (perDrawLayout == null) return; diff --git a/sources/engine/Xenko.Rendering/Rendering/Properties.cs b/sources/engine/Xenko.Rendering/Rendering/Properties.cs index 13362134d1..5bab5dadd1 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Properties.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Properties.cs @@ -593,12 +593,6 @@ internal StaticObjectPropertyData(T[] data) Data = data; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public bool IsValidIndex(StaticObjectNodeReference index) - { - return index.Index >= 0 && index.Index < Data.Length; - } - public ref T this[StaticObjectNodeReference index] => ref Data[index.Index]; } diff --git a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs index 6beab62ca5..e3d63c33d1 100644 --- a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs @@ -366,9 +366,9 @@ private void PrepareRenderTargetExtensionsMixins(RenderDrawContext context) // Get RenderEffect var staticObjectNode = renderObject.StaticObjectNode; var staticEffectObjectNode = staticObjectNode * EffectPermutationSlotCount + effectSlots[renderNode.RenderStage.Index].Index; - RenderEffect renderEffect; + RenderEffect renderEffect = renderEffects[staticEffectObjectNode]; - if (renderEffects.IsValidIndex(staticEffectObjectNode) && (renderEffect = renderEffects[staticEffectObjectNode]) != null) + if (renderEffect != null) { var renderStage = renderNode.RenderStage; var renderStageShaderSource = renderStage.OutputValidator.ShaderSource; diff --git a/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs index a5ec9978ad..6703a21e4e 100644 --- a/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs @@ -114,7 +114,7 @@ public override unsafe void Prepare(RenderDrawContext context) Dispatcher.ForEach(((RootEffectRenderFeature)RootRenderFeature).RenderNodes, (ref RenderNode renderNode) => { - var perDrawLayout = renderNode.RenderEffect.Reflection?.PerDrawLayout; + var perDrawLayout = renderNode.RenderEffect?.Reflection?.PerDrawLayout; if (perDrawLayout == null) return; diff --git a/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs b/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs index 399842e267..4c60bf01aa 100644 --- a/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs +++ b/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs @@ -79,9 +79,9 @@ public void Dispose() public void Reset() { // Clear object data - foreach (var renderObject in RenderObjects) + for (int i=0; i Date: Thu, 23 Jan 2020 14:48:45 -0500 Subject: [PATCH 0659/2038] Vulkan: tweak to threading synchronization --- sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs index 4317f026b9..12f07686a3 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs @@ -241,12 +241,6 @@ public unsafe void Recreate(IntPtr dataPointer) var bufferMemoryBarrier = new BufferMemoryBarrier(NativeBuffer, AccessFlags.TransferWrite, NativeAccessMask); commandBuffer.PipelineBarrier(PipelineStageFlags.Transfer, PipelineStageFlags.AllCommands, DependencyFlags.None, 0, null, 1, &bufferMemoryBarrier, 0, null); - // Close and submit - using (GraphicsDevice.QueueLock.ReadLock()) - { - commandBuffer.End(); - } - var submitInfo = new SubmitInfo { StructureType = StructureType.SubmitInfo, @@ -257,8 +251,10 @@ public unsafe void Recreate(IntPtr dataPointer) var fenceCreateInfo = new FenceCreateInfo { StructureType = StructureType.FenceCreateInfo }; var fence = GraphicsDevice.NativeDevice.CreateFence(ref fenceCreateInfo); + // Close and submit using (GraphicsDevice.QueueLock.WriteLock()) { + commandBuffer.End(); GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, fence); GraphicsDevice.NativeDevice.WaitForFences(1, &fence, true, ulong.MaxValue); } From 6998d66941a1c20843bfe21bce158db14df019db Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 23 Jan 2020 16:28:51 -0500 Subject: [PATCH 0660/2038] Physics: fixes to position/rotation initialization for bodies --- .../Xenko.Physics/Bepu/BepuPhysicsComponent.cs | 2 ++ .../Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 4 ++++ .../engine/Xenko.Physics/Bepu/BepuSimulation.cs | 16 ++++++++++++++-- .../Bepu/BepuStaticColliderComponent.cs | 4 ++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 1d13264dec..3439d3a3a5 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -145,6 +145,8 @@ internal void DerivePhysicsTransform(Vector3? worldPosition, Matrix? worldRotati Matrix.Multiply(ref rotation, ref translationMatrix, out outMatrix); } + internal bool useComponentPose; + [DataMemberIgnore] public virtual Vector3 Position { get; set; } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 9a074a551f..b8fe53ee2b 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -567,6 +567,8 @@ public override Vector3 Position { if (bodyDescription.Pose.Position == BepuHelpers.ToBepu(value)) return; + useComponentPose = true; + bodyDescription.Pose.Position.X = value.X; bodyDescription.Pose.Position.Y = value.Y; bodyDescription.Pose.Position.Z = value.Z; @@ -591,6 +593,8 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { if (bodyDescription.Pose.Orientation == BepuHelpers.ToBepu(value)) return; + useComponentPose = true; + bodyDescription.Pose.Orientation.X = value.X; bodyDescription.Pose.Orientation.Y = value.Y; bodyDescription.Pose.Orientation.Z = value.Z; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index ef4b099aaf..ea1afe5ac2 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -420,6 +420,12 @@ internal void ProcessAdds() if (component.AddedHandle > -1) continue; // already added if (component is BepuStaticColliderComponent scc) { + // static stuff needs positions set first + if (!component.useComponentPose) + { + component.Position = component.Entity.Transform.WorldPosition(); + component.Rotation = component.Entity.Transform.WorldRotation(); + } using (simulationLocker.WriteLock()) { scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation, scc.SpeculativeMargin); @@ -436,9 +442,15 @@ internal void ProcessAdds() rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); RigidMappings[rigidBody.AddedHandle] = rigidBody; } + // after rigids are added, then set position to entity transform if needed + if (!component.useComponentPose) + { + component.Position = component.Entity.Transform.WorldPosition(); + component.Rotation = component.Entity.Transform.WorldRotation(); + } } - component.Position = component.Entity.Transform.WorldPosition(); - component.Rotation = component.Entity.Transform.WorldRotation(); + // clear flag + component.useComponentPose = false; } ToBeAdded.Clear(); } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index 4b3558fa7c..23173cd64a 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -45,6 +45,8 @@ public override Xenko.Core.Mathematics.Vector3 Position } set { + useComponentPose = true; + staticDescription.Pose.Position.X = value.X; staticDescription.Pose.Position.Y = value.Y; staticDescription.Pose.Position.Z = value.Z; @@ -63,6 +65,8 @@ public override Xenko.Core.Mathematics.Quaternion Rotation } set { + useComponentPose = true; + staticDescription.Pose.Orientation.X = value.X; staticDescription.Pose.Orientation.Y = value.Y; staticDescription.Pose.Orientation.Z = value.Z; From dd2ffdd58c619ef5192bf5268e7b011138a4be4c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 23 Jan 2020 17:50:15 -0500 Subject: [PATCH 0661/2038] Vulkan: restructure PipelineState for synchronization organization --- .../Vulkan/PipelineState.Vulkan.cs | 423 +++++++++--------- 1 file changed, 202 insertions(+), 221 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/PipelineState.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/PipelineState.Vulkan.cs index 2dcaab5cb8..c162132d8b 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/PipelineState.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/PipelineState.Vulkan.cs @@ -69,9 +69,158 @@ private unsafe void Recreate() PipelineShaderStageCreateInfo[] stages; - CreateRenderPass(Description); + // create render pass + bool hasDepthStencilAttachment = Description.Output.DepthStencilFormat != PixelFormat.None; - CreatePipelineLayout(Description); + var renderTargetCount = Description.Output.RenderTargetCount; + + var attachmentCount = renderTargetCount; + if (hasDepthStencilAttachment) + attachmentCount++; + + var attachments = new AttachmentDescription[attachmentCount]; + var colorAttachmentReferences = new AttachmentReference[renderTargetCount]; + + fixed (PixelFormat* renderTargetFormat = &Description.Output.RenderTargetFormat0) + fixed (BlendStateRenderTargetDescription* blendDescription = &Description.BlendState.RenderTarget0) + { + for (int i = 0; i < renderTargetCount; i++) + { + var currentBlendDesc = Description.BlendState.IndependentBlendEnable ? (blendDescription + i) : blendDescription; + + attachments[i] = new AttachmentDescription + { + Format = VulkanConvertExtensions.ConvertPixelFormat(*(renderTargetFormat + i)), + Samples = SampleCountFlags.Sample1, + LoadOperation = currentBlendDesc->BlendEnable ? AttachmentLoadOperation.Load : AttachmentLoadOperation.DontCare, // TODO VULKAN: Only if any destination blend? + StoreOperation = AttachmentStoreOperation.Store, + StencilLoadOperation = AttachmentLoadOperation.DontCare, + StencilStoreOperation = AttachmentStoreOperation.DontCare, + InitialLayout = ImageLayout.ColorAttachmentOptimal, + FinalLayout = ImageLayout.ColorAttachmentOptimal, + }; + + colorAttachmentReferences[i] = new AttachmentReference + { + Attachment = (uint)i, + Layout = ImageLayout.ColorAttachmentOptimal, + }; + } + } + + if (hasDepthStencilAttachment) + { + attachments[attachmentCount - 1] = new AttachmentDescription + { + Format = Texture.GetFallbackDepthStencilFormat(GraphicsDevice, VulkanConvertExtensions.ConvertPixelFormat(Description.Output.DepthStencilFormat)), + Samples = SampleCountFlags.Sample1, + LoadOperation = AttachmentLoadOperation.Load, // TODO VULKAN: Only if depth read enabled? + StoreOperation = AttachmentStoreOperation.Store, // TODO VULKAN: Only if depth write enabled? + StencilLoadOperation = AttachmentLoadOperation.DontCare, // TODO VULKAN: Handle stencil + StencilStoreOperation = AttachmentStoreOperation.DontCare, + InitialLayout = ImageLayout.DepthStencilAttachmentOptimal, + FinalLayout = ImageLayout.DepthStencilAttachmentOptimal, + }; + } + + var depthAttachmentReference = new AttachmentReference + { + Attachment = (uint)attachments.Length - 1, + Layout = ImageLayout.DepthStencilAttachmentOptimal, + }; + + var subpass = new SubpassDescription + { + PipelineBindPoint = PipelineBindPoint.Graphics, + ColorAttachmentCount = (uint)renderTargetCount, + ColorAttachments = colorAttachmentReferences.Length > 0 ? new IntPtr(Interop.Fixed(colorAttachmentReferences)) : IntPtr.Zero, + DepthStencilAttachment = hasDepthStencilAttachment ? new IntPtr(&depthAttachmentReference) : IntPtr.Zero, + }; + + var renderPassCreateInfo = new RenderPassCreateInfo + { + StructureType = StructureType.RenderPassCreateInfo, + AttachmentCount = (uint)attachmentCount, + Attachments = attachments.Length > 0 ? new IntPtr(Interop.Fixed(attachments)) : IntPtr.Zero, + SubpassCount = 1, + Subpasses = new IntPtr(&subpass) + }; + + // create pipeline layout + // Remap descriptor set indices to those in the shader. This ordering generated by the ShaderCompiler + var resourceGroups = Description.EffectBytecode.Reflection.ResourceBindings.Select(x => x.ResourceGroup ?? "Globals").Distinct().ToList(); + ResourceGroupCount = resourceGroups.Count; + + var layouts = Description.RootSignature.EffectDescriptorSetReflection.Layouts; + + // Get binding indices used by the shader + var destinationBindings = Description.EffectBytecode.Stages + .SelectMany(x => BinarySerialization.Read(x.Data).ResourceBindings) + .GroupBy(x => x.Key, x => x.Value) + .ToDictionary(x => x.Key, x => x.First()); + + var maxBindingIndex = destinationBindings.Max(x => x.Value); + var destinationEntries = new DescriptorSetLayoutBuilder.Entry[maxBindingIndex + 1]; + + DescriptorBindingMapping = new List(); + + for (int i = 0; i < resourceGroups.Count; i++) + { + var resourceGroupName = resourceGroups[i] == "Globals" ? Description.RootSignature.EffectDescriptorSetReflection.DefaultSetSlot : resourceGroups[i]; + var layoutIndex = resourceGroups[i] == null ? 0 : layouts.FindIndex(x => x.Name == resourceGroupName); + + // Check if the resource group is used by the shader + if (layoutIndex == -1) + continue; + + var sourceEntries = layouts[layoutIndex].Layout.Entries; + + for (int sourceBinding = 0; sourceBinding < sourceEntries.Count; sourceBinding++) + { + var sourceEntry = sourceEntries[sourceBinding]; + + int destinationBinding; + if (destinationBindings.TryGetValue(sourceEntry.Key.Name, out destinationBinding)) + { + destinationEntries[destinationBinding] = sourceEntry; + + // No need to umpdate immutable samplers + if (sourceEntry.Class == EffectParameterClass.Sampler && sourceEntry.ImmutableSampler != null) + { + continue; + } + + DescriptorBindingMapping.Add(new DescriptorSetInfo + { + SourceSet = layoutIndex, + SourceBinding = sourceBinding, + DestinationBinding = destinationBinding, + DescriptorType = VulkanConvertExtensions.ConvertDescriptorType(sourceEntry.Class, sourceEntry.Type) + }); + } + } + } + + // Create default sampler, used by texture and buffer loads + destinationEntries[0] = new DescriptorSetLayoutBuilder.Entry + { + Class = EffectParameterClass.Sampler, + Type = EffectParameterType.Sampler, + ImmutableSampler = GraphicsDevice.SamplerStates.PointWrap, + ArraySize = 1, + }; + + // Create descriptor set layout + NativeDescriptorSetLayout = DescriptorSetLayout.CreateNativeDescriptorSetLayout(GraphicsDevice, destinationEntries, out DescriptorTypeCounts); + + // Create pipeline layout + var nativeDescriptorSetLayout = NativeDescriptorSetLayout; + var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo + { + StructureType = StructureType.PipelineLayoutCreateInfo, + SetLayoutCount = 1, + SetLayouts = new IntPtr(&nativeDescriptorSetLayout) + }; // Create shader stages Dictionary inputAttributeNames; @@ -139,13 +288,53 @@ private unsafe void Recreate() //var tessellationState = new PipelineTessellationStateCreateInfo(); - var rasterizationState = CreateRasterizationState(Description.RasterizerState); + var rasterizationState = new PipelineRasterizationStateCreateInfo + { + StructureType = StructureType.PipelineRasterizationStateCreateInfo, + CullMode = VulkanConvertExtensions.ConvertCullMode(Description.RasterizerState.CullMode), + FrontFace = Description.RasterizerState.FrontFaceCounterClockwise ? FrontFace.CounterClockwise : FrontFace.Clockwise, + PolygonMode = VulkanConvertExtensions.ConvertFillMode(Description.RasterizerState.FillMode), + DepthBiasEnable = true, // TODO VULKAN + DepthBiasConstantFactor = Description.RasterizerState.DepthBias, + DepthBiasSlopeFactor = Description.RasterizerState.SlopeScaleDepthBias, + DepthBiasClamp = Description.RasterizerState.DepthBiasClamp, + LineWidth = 1.0f, + DepthClampEnable = !Description.RasterizerState.DepthClipEnable, + RasterizerDiscardEnable = false, + }; + + var depthStencilState = new PipelineDepthStencilStateCreateInfo + { + StructureType = StructureType.PipelineDepthStencilStateCreateInfo, + DepthTestEnable = Description.DepthStencilState.DepthBufferEnable, + StencilTestEnable = Description.DepthStencilState.StencilEnable, + DepthWriteEnable = Description.DepthStencilState.DepthBufferWriteEnable, - var depthStencilState = CreateDepthStencilState(Description); + MinDepthBounds = 0.0f, + MaxDepthBounds = 1.0f, + DepthCompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.DepthBufferFunction), + Front = new StencilOperationState + { + CompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.FrontFace.StencilFunction), + DepthFailOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilDepthBufferFail), + FailOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilFail), + PassOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.FrontFace.StencilPass), + CompareMask = Description.DepthStencilState.StencilMask, + WriteMask = Description.DepthStencilState.StencilWriteMask + }, + Back = new StencilOperationState + { + CompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(Description.DepthStencilState.BackFace.StencilFunction), + DepthFailOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilDepthBufferFail), + FailOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilFail), + PassOperation = VulkanConvertExtensions.ConvertStencilOperation(Description.DepthStencilState.BackFace.StencilPass), + CompareMask = Description.DepthStencilState.StencilMask, + WriteMask = Description.DepthStencilState.StencilWriteMask + } + }; var description = Description.BlendState; - var renderTargetCount = Description.Output.RenderTargetCount; var colorBlendAttachments = new PipelineColorBlendAttachmentState[renderTargetCount]; var renderTargetBlendState = &description.RenderTarget0; @@ -202,11 +391,10 @@ private unsafe void Recreate() DynamicStateCount = (uint)dynamicStates.Length, DynamicStates = (IntPtr)dynamicStatesPointer, }; - + var createInfo = new GraphicsPipelineCreateInfo { StructureType = StructureType.GraphicsPipelineCreateInfo, - Layout = NativeLayout, StageCount = (uint)stages.Length, Stages = (IntPtr)stagesPointer, //TessellationState = new IntPtr(&tessellationState), @@ -218,12 +406,17 @@ private unsafe void Recreate() ColorBlendState = new IntPtr(&colorBlendState), DynamicState = new IntPtr(&dynamicState), ViewportState = new IntPtr(&viewportState), - RenderPass = NativeRenderPass, Subpass = 0, }; - + using (GraphicsDevice.QueueLock.ReadLock()) { + NativeRenderPass = GraphicsDevice.NativeDevice.CreateRenderPass(ref renderPassCreateInfo); + NativeLayout = GraphicsDevice.NativeDevice.CreatePipelineLayout(ref pipelineLayoutCreateInfo); + + createInfo.Layout = NativeLayout; + createInfo.RenderPass = NativeRenderPass; + try { NativePipeline = GraphicsDevice.NativeDevice.CreateGraphicsPipelines(PipelineCache.Null, 1, &createInfo); } catch (Exception e) { @@ -248,86 +441,6 @@ protected internal override bool OnRecreate() return true; } - private unsafe void CreateRenderPass(PipelineStateDescription pipelineStateDescription) - { - bool hasDepthStencilAttachment = pipelineStateDescription.Output.DepthStencilFormat != PixelFormat.None; - - var renderTargetCount = pipelineStateDescription.Output.RenderTargetCount; - - var attachmentCount = renderTargetCount; - if (hasDepthStencilAttachment) - attachmentCount++; - - var attachments = new AttachmentDescription[attachmentCount]; - var colorAttachmentReferences = new AttachmentReference[renderTargetCount]; - - fixed (PixelFormat* renderTargetFormat = &pipelineStateDescription.Output.RenderTargetFormat0) - fixed (BlendStateRenderTargetDescription* blendDescription = &pipelineStateDescription.BlendState.RenderTarget0) - { - for (int i = 0; i < renderTargetCount; i++) - { - var currentBlendDesc = pipelineStateDescription.BlendState.IndependentBlendEnable ? (blendDescription + i) : blendDescription; - - attachments[i] = new AttachmentDescription - { - Format = VulkanConvertExtensions.ConvertPixelFormat(*(renderTargetFormat + i)), - Samples = SampleCountFlags.Sample1, - LoadOperation = currentBlendDesc->BlendEnable ? AttachmentLoadOperation.Load : AttachmentLoadOperation.DontCare, // TODO VULKAN: Only if any destination blend? - StoreOperation = AttachmentStoreOperation.Store, - StencilLoadOperation = AttachmentLoadOperation.DontCare, - StencilStoreOperation = AttachmentStoreOperation.DontCare, - InitialLayout = ImageLayout.ColorAttachmentOptimal, - FinalLayout = ImageLayout.ColorAttachmentOptimal, - }; - - colorAttachmentReferences[i] = new AttachmentReference - { - Attachment = (uint)i, - Layout = ImageLayout.ColorAttachmentOptimal, - }; - } - } - - if (hasDepthStencilAttachment) - { - attachments[attachmentCount - 1] = new AttachmentDescription - { - Format = Texture.GetFallbackDepthStencilFormat(GraphicsDevice, VulkanConvertExtensions.ConvertPixelFormat(pipelineStateDescription.Output.DepthStencilFormat)), - Samples = SampleCountFlags.Sample1, - LoadOperation = AttachmentLoadOperation.Load, // TODO VULKAN: Only if depth read enabled? - StoreOperation = AttachmentStoreOperation.Store, // TODO VULKAN: Only if depth write enabled? - StencilLoadOperation = AttachmentLoadOperation.DontCare, // TODO VULKAN: Handle stencil - StencilStoreOperation = AttachmentStoreOperation.DontCare, - InitialLayout = ImageLayout.DepthStencilAttachmentOptimal, - FinalLayout = ImageLayout.DepthStencilAttachmentOptimal, - }; - } - - var depthAttachmentReference = new AttachmentReference - { - Attachment = (uint)attachments.Length - 1, - Layout = ImageLayout.DepthStencilAttachmentOptimal, - }; - - var subpass = new SubpassDescription - { - PipelineBindPoint = PipelineBindPoint.Graphics, - ColorAttachmentCount = (uint)renderTargetCount, - ColorAttachments = colorAttachmentReferences.Length > 0 ? new IntPtr(Interop.Fixed(colorAttachmentReferences)) : IntPtr.Zero, - DepthStencilAttachment = hasDepthStencilAttachment ? new IntPtr(&depthAttachmentReference) : IntPtr.Zero, - }; - - var renderPassCreateInfo = new RenderPassCreateInfo - { - StructureType = StructureType.RenderPassCreateInfo, - AttachmentCount = (uint)attachmentCount, - Attachments = attachments.Length > 0 ? new IntPtr(Interop.Fixed(attachments)) : IntPtr.Zero, - SubpassCount = 1, - Subpasses = new IntPtr(&subpass) - }; - NativeRenderPass = GraphicsDevice.NativeDevice.CreateRenderPass(ref renderPassCreateInfo); - } - /// protected internal override unsafe void OnDestroyed() { @@ -355,85 +468,6 @@ internal struct DescriptorSetInfo internal List DescriptorBindingMapping; - private unsafe void CreatePipelineLayout(PipelineStateDescription pipelineStateDescription) - { - // Remap descriptor set indices to those in the shader. This ordering generated by the ShaderCompiler - var resourceGroups = pipelineStateDescription.EffectBytecode.Reflection.ResourceBindings.Select(x => x.ResourceGroup ?? "Globals").Distinct().ToList(); - ResourceGroupCount = resourceGroups.Count; - - var layouts = pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.Layouts; - - // Get binding indices used by the shader - var destinationBindings = pipelineStateDescription.EffectBytecode.Stages - .SelectMany(x => BinarySerialization.Read(x.Data).ResourceBindings) - .GroupBy(x => x.Key, x => x.Value) - .ToDictionary(x => x.Key, x => x.First()); - - var maxBindingIndex = destinationBindings.Max(x => x.Value); - var destinationEntries = new DescriptorSetLayoutBuilder.Entry[maxBindingIndex + 1]; - - DescriptorBindingMapping = new List(); - - for (int i = 0; i < resourceGroups.Count; i++) - { - var resourceGroupName = resourceGroups[i] == "Globals" ? pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.DefaultSetSlot : resourceGroups[i]; - var layoutIndex = resourceGroups[i] == null ? 0 : layouts.FindIndex(x => x.Name == resourceGroupName); - - // Check if the resource group is used by the shader - if (layoutIndex == -1) - continue; - - var sourceEntries = layouts[layoutIndex].Layout.Entries; - - for (int sourceBinding = 0; sourceBinding < sourceEntries.Count; sourceBinding++) - { - var sourceEntry = sourceEntries[sourceBinding]; - - int destinationBinding; - if (destinationBindings.TryGetValue(sourceEntry.Key.Name, out destinationBinding)) - { - destinationEntries[destinationBinding] = sourceEntry; - - // No need to umpdate immutable samplers - if (sourceEntry.Class == EffectParameterClass.Sampler && sourceEntry.ImmutableSampler != null) - { - continue; - } - - DescriptorBindingMapping.Add(new DescriptorSetInfo - { - SourceSet = layoutIndex, - SourceBinding = sourceBinding, - DestinationBinding = destinationBinding, - DescriptorType = VulkanConvertExtensions.ConvertDescriptorType(sourceEntry.Class, sourceEntry.Type) - }); - } - } - } - - // Create default sampler, used by texture and buffer loads - destinationEntries[0] = new DescriptorSetLayoutBuilder.Entry - { - Class = EffectParameterClass.Sampler, - Type = EffectParameterType.Sampler, - ImmutableSampler = GraphicsDevice.SamplerStates.PointWrap, - ArraySize = 1, - }; - - // Create descriptor set layout - NativeDescriptorSetLayout = DescriptorSetLayout.CreateNativeDescriptorSetLayout(GraphicsDevice, destinationEntries, out DescriptorTypeCounts); - - // Create pipeline layout - var nativeDescriptorSetLayout = NativeDescriptorSetLayout; - var pipelineLayoutCreateInfo = new PipelineLayoutCreateInfo - { - StructureType = StructureType.PipelineLayoutCreateInfo, - SetLayoutCount = 1, - SetLayouts = new IntPtr(&nativeDescriptorSetLayout) - }; - NativeLayout = GraphicsDevice.NativeDevice.CreatePipelineLayout(ref pipelineLayoutCreateInfo); - } - private unsafe PipelineShaderStageCreateInfo[] CreateShaderStages(PipelineStateDescription pipelineStateDescription, out Dictionary inputAttributeNames) { var stages = pipelineStateDescription.EffectBytecode.Stages; @@ -471,59 +505,6 @@ private unsafe PipelineShaderStageCreateInfo[] CreateShaderStages(PipelineStateD return nativeStages; } - - private PipelineRasterizationStateCreateInfo CreateRasterizationState(RasterizerStateDescription description) - { - return new PipelineRasterizationStateCreateInfo - { - StructureType = StructureType.PipelineRasterizationStateCreateInfo, - CullMode = VulkanConvertExtensions.ConvertCullMode(description.CullMode), - FrontFace = description.FrontFaceCounterClockwise ? FrontFace.CounterClockwise : FrontFace.Clockwise, - PolygonMode = VulkanConvertExtensions.ConvertFillMode(description.FillMode), - DepthBiasEnable = true, // TODO VULKAN - DepthBiasConstantFactor = description.DepthBias, - DepthBiasSlopeFactor = description.SlopeScaleDepthBias, - DepthBiasClamp = description.DepthBiasClamp, - LineWidth = 1.0f, - DepthClampEnable = !description.DepthClipEnable, - RasterizerDiscardEnable = false, - }; - } - - private PipelineDepthStencilStateCreateInfo CreateDepthStencilState(PipelineStateDescription pipelineStateDescription) - { - var description = pipelineStateDescription.DepthStencilState; - - return new PipelineDepthStencilStateCreateInfo - { - StructureType = StructureType.PipelineDepthStencilStateCreateInfo, - DepthTestEnable = description.DepthBufferEnable, - StencilTestEnable = description.StencilEnable, - DepthWriteEnable = description.DepthBufferWriteEnable, - - MinDepthBounds = 0.0f, - MaxDepthBounds = 1.0f, - DepthCompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(description.DepthBufferFunction), - Front = new StencilOperationState - { - CompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(description.FrontFace.StencilFunction), - DepthFailOperation = VulkanConvertExtensions.ConvertStencilOperation(description.FrontFace.StencilDepthBufferFail), - FailOperation = VulkanConvertExtensions.ConvertStencilOperation(description.FrontFace.StencilFail), - PassOperation = VulkanConvertExtensions.ConvertStencilOperation(description.FrontFace.StencilPass), - CompareMask = description.StencilMask, - WriteMask = description.StencilWriteMask - }, - Back = new StencilOperationState - { - CompareOperation = VulkanConvertExtensions.ConvertComparisonFunction(description.BackFace.StencilFunction), - DepthFailOperation = VulkanConvertExtensions.ConvertStencilOperation(description.BackFace.StencilDepthBufferFail), - FailOperation = VulkanConvertExtensions.ConvertStencilOperation(description.BackFace.StencilFail), - PassOperation = VulkanConvertExtensions.ConvertStencilOperation(description.BackFace.StencilPass), - CompareMask = description.StencilMask, - WriteMask = description.StencilWriteMask - } - }; - } } } From a37b589b268131c18c8ceec02a433e16e0144aa1 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 25 Jan 2020 13:11:00 -0500 Subject: [PATCH 0662/2038] Audio: add Task functions to avoid lag in playing sounds (especially the first time) --- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 68cbeb8130..9a64cadbea 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using Xenko.Audio; using Xenko.Core; using Xenko.Core.Mathematics; @@ -80,6 +81,30 @@ public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = return s; } + public Task PlayCentralSoundTask(string url, float pitch = 1f, float volume = 1f, float pan = 0.5f, bool looped = false) + { + return Task.Factory.StartNew(() => + { + return PlayCentralSound(url, pitch, volume, pan, looped); + }); + } + + public Task PlayPositionSoundTask(string url, Vector3 position, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + { + return Task.Factory.StartNew(() => + { + return PlayPositionSound(url, position, pitch, volume, pan, distanceScale, looped); + }); + } + + public Task PlayAttachedSoundTask(string url, Entity parent, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + { + return Task.Factory.StartNew(() => + { + return PlayAttachedSound(url, parent, pitch, volume, pan, distanceScale, looped); + }); + } + public void UpdatePlayingSoundPositions() { for (int i = 0; i < currentAttached.Count; i++) From 32b71cc2334cc99b739c0d75bc1845953c79966f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 25 Jan 2020 14:14:57 -0500 Subject: [PATCH 0663/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1ba3497897..40198edf50 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, has an easier API, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. See https://github.com/phr00t/FocusEngine/tree/master/sources/engine/Xenko.Physics/Bepu. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors, importing multiple audio files at once, or rendering 3D text from multiple cameras. -* SimpleAudioPool: easily play all sound effects for your whole project from a single object, which handles loading and pooling sound instances automatically. If you use positional sounds, make sure you call UpdatePlayingSoundPositions every frame! See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/SimpleAudioPool.cs +* GlobalSoundManager: easily play all sound effects for your whole project from a single object, which handles loading and pooling sound instances automatically (even asynchronously). If you use positional sounds, make sure you call UpdatePlayingSoundPositions every frame! See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs * CinematicAction: Simple system for performing cinematic actions on objects and calling functions at certain times. Can build a simple timeline for things to move, rotate and execute. See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). From badd7f75b6406e32b4aedbfdd2bd82dd7b6c3c6e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 25 Jan 2020 15:44:01 -0500 Subject: [PATCH 0664/2038] Graphics: force fullscreen if picking a resolution higher or equal to native fixes a Vulkan edge case crash --- sources/engine/Xenko.Engine/Engine/Game.cs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/Game.cs b/sources/engine/Xenko.Engine/Engine/Game.cs index 09007bda20..c3728c17a3 100644 --- a/sources/engine/Xenko.Engine/Engine/Game.cs +++ b/sources/engine/Xenko.Engine/Engine/Game.cs @@ -250,14 +250,27 @@ public void GetDefaultSettings(out int width, out int height, out bool fullscree string[] vals = File.ReadAllLines("DefaultResolution.txt"); width = int.Parse(vals[0].Trim()); height = int.Parse(vals[1].Trim()); - fullscreen = vals[2].Trim().ToLower() == "full"; + fullscreen = vals[2].Trim().ToLower().StartsWith("full"); } catch (Exception e) { } } try { // cap values to native resolution Graphics.SDL.Window.GetDisplayInformation(out int native_width, out int native_height, out int refresh_rate); - if (width > native_width) width = native_width; - if (height > native_height) height = native_height; + if (width >= native_width && + height >= native_height) + { + // force fullscreen if using native or higher, + // as crashes can happen on some hardware if using this big of a window + width = native_width; + height = native_height; + fullscreen = true; + } + else + { + // smaller than native, lets make sure we are still within each bound though + if (width > native_width) width = native_width; + if (height > native_height) height = native_height; + } } catch(Exception e) { // something went wrong... just use a window width = 1280; From 44150882de5906ab04cb3f0bcf92363764841561 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 25 Jan 2020 15:44:45 -0500 Subject: [PATCH 0665/2038] GameStudio: automatically generate scene/prefab backups you can restore from sometimes, rarely, GameStudio loses components from scenes and prefabs. This might rescue yourself! --- .../ViewModel/EditorViewModel.cs | 32 +++++++++++++++++++ .../ViewModel/SessionViewModel.cs | 18 +++++++++++ .../Xenko.GameStudio/GameStudioWindow.xaml | 1 + 3 files changed, 51 insertions(+) diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/EditorViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/EditorViewModel.cs index 1312acdb92..631667264c 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/EditorViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/EditorViewModel.cs @@ -36,6 +36,7 @@ protected EditorViewModel(IViewModelServiceProvider serviceProvider, MostRecentl ClearMRUCommand = new AnonymousCommand(serviceProvider, () => ClearRecentFiles()); OpenSettingsWindowCommand = new AnonymousCommand(serviceProvider, OpenSettingsWindow); OpenWebPageCommand = new AnonymousTaskCommand(serviceProvider, OpenWebPage); + RestoreFromBackup = new AnonymousTaskCommand(serviceProvider, RestoreFromBackupFunction); #if DEBUG DebugCommand = new AnonymousCommand(serviceProvider, DebugFunction); #endif @@ -94,6 +95,8 @@ private void MostRecentlyUsedFiles_CollectionChanged(object sender, System.Colle public ICommandBase OpenWebPageCommand { get; } + public ICommandBase RestoreFromBackup { get; } + #if DEBUG public ICommandBase DebugCommand { get; } #endif @@ -221,6 +224,35 @@ public async Task OpenFile(string filePath, bool tryEdit) protected abstract Task RestartAndOpenSession(UFile sessionPath); + internal string projectPath; + + private async Task RestoreFromBackupFunction() + { + if (projectPath == null || projectPath.Length == 0) return; + + int restoreCount = 0; + string[] files = Directory.GetFiles(projectPath, "*.xk*", SearchOption.AllDirectories); + for (int i = 0; i < files.Length; i++) + { + string filename = files[i]; + // if we are a scene file or prefab, back us up + if (filename.EndsWith("scene") || filename.EndsWith("prefab")) + { + string backupfile = filename + ".backup"; + + if (File.Exists(backupfile)) + { + File.Copy(filename, filename + ".old", true); + File.Copy(filename + ".backup", filename, true); + restoreCount++; + } + } + } + + var message = "Restored " + restoreCount + " scene and prefab files from last run. Any files overwritten have an '.old' backup. Try reloading the project now."; + await ServiceProvider.Get().MessageBox(message, MessageBoxButton.OK, MessageBoxImage.Information); + } + private async Task OpenWebPage(string url) { try diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs index 49df488aec..d2f0a07fbb 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs @@ -343,6 +343,21 @@ public static async Task CreateNewSession(EditorViewModel edit return sessionViewModel; } + private static void BackupProjectFiles(string path) + { + EditorViewModel.Instance.projectPath = path; + string[] files = Directory.GetFiles(path, "*.xk*", SearchOption.AllDirectories); + for (int i=0; i OpenSession(string path, IViewModelServiceProvider serviceProvider, EditorViewModel editor, PackageSessionResult sessionResult) { if (path == null) throw new ArgumentNullException(nameof(path)); @@ -409,6 +424,9 @@ public static async Task OpenSession(string path, IViewModelSe return null; } + // project loaded OK, lets backup the prefabs and scene files + BackupProjectFiles(Path.GetDirectoryName(path)); + // Register the node container to the copy/paste service. sessionViewModel.ServiceProvider.Get().PropertyGraphContainer = sessionViewModel.GraphContainer; diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index 9730f83307..ad1a639c84 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -273,6 +273,7 @@ + From ef154914895398f8e1a5c2c01a968348c276bd6c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 25 Jan 2020 17:04:20 -0500 Subject: [PATCH 0666/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 40198edf50..35877c7e45 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * More Post Processing Effects: Fog and Outline post processing shaders work, out of the box. * Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. * Easy generating procedural meshes: StagedMeshDraw takes a list of verticies and indicies, no "buffer binding" or "GraphicsDevice" needed. Also will actually upload the mesh when it tries to get rendered automatically, saving time and resources if the mesh doesn't actually ever get viewed. -* Less likely to lose work: files are not actually deleted from GameStudio, just moved to the Recylce Bin. +* Less likely to lose work: files are not actually deleted from GameStudio, just moved to the Recylce Bin. If you mess up a prefab or entity in a scene, or if you notice corruption in your project, select Help -> Restore Scene/Prefabs to return your scene and prefab files to the last time to opened your project. * Performance: lots of tweaks have been made throughout the engine to maximize performance. This includes reducing locks and enumeration reduction, for example. * Easy adding/removing entities from the scene: Just do myEntity.Scene = myScene (to add it) or myEntity.Scene = null (to remove it). * Includes dfkeenan's toolkit designed for this fork (from https://github.com/dfkeenan/XenkoToolkit). May need to add the Toolkit Nuget package to use. From 9118a7c54fa5240f6fbdcaa47226879bd11e3345 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 25 Jan 2020 22:28:12 -0500 Subject: [PATCH 0667/2038] Audio: threading synchronization added for task-based GlobalSoundManager playing --- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 9a64cadbea..a7b1b225c8 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -71,13 +71,15 @@ public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = s.Pan = pan; s.Apply3D(pos, null, null, distanceScale); s.Play(); - currentAttached.Add(new PositionalSound() - { + var posSnd = new PositionalSound() { pos = pos, soundInstance = s, entity = parent, distance_scale = distanceScale - }); + }; + lock (currentAttached) { + currentAttached.Add(posSnd); + } return s; } @@ -138,7 +140,10 @@ public void StopAllSounds() si[i].Stop(); } } - currentAttached.Clear(); + lock (currentAttached) + { + currentAttached.Clear(); + } } public void StopSound(string url) From c455a04b59377af41b7d8524b8cac1cc558c7812 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Sun, 26 Jan 2020 16:55:59 +1100 Subject: [PATCH 0668/2038] Merge IVoxelAttribute & VoxelAttributeBase and IVoxelModifier & VoxelModifierBase --- .../IVoxelVisualization.cs | 2 +- .../VoxelVisualizationRaw.cs | 2 +- .../VoxelVisualizationView.cs | 2 +- .../Voxels/Light/LightVoxelRenderer.cs | 4 +- .../Attributes/IVoxelAttribute.cs | 38 ----------------- .../Voxelization/Attributes/VoxelAttribute.cs | 41 +++++++++++++++++++ .../Attributes/VoxelAttributeBase.cs | 24 ----------- .../VoxelAttributeDirectionalCoverage.cs | 28 ++++++------- .../VoxelAttributeEmissionOpacity.cs | 38 ++++++++--------- .../Attributes/VoxelAttributeSolidity.cs | 32 +++++++-------- .../Voxelization/Layout/IVoxelLayout.cs | 6 +-- .../Layout/VoxelLayoutAnisotropic.cs | 2 +- .../Layout/VoxelLayoutAnisotropicPaired.cs | 2 +- .../Voxelization/Layout/VoxelLayoutBase.cs | 4 +- .../Layout/VoxelLayoutIsotropic.cs | 2 +- .../IVoxelModifierEmissionOpacity.cs | 8 ---- .../VoxelModifierEmissionOpacity.cs | 13 ++++++ ...oxelModifierEmissionOpacityAntiAliasing.cs | 10 ++--- .../VoxelModifierEmissionOpacityOpacify.cs | 10 ++--- .../VoxelModifierEmissionOpacitySolidify.cs | 12 +++--- .../Voxelization/Modifiers/IVoxelModifier.cs | 19 --------- .../Voxelization/Modifiers/VoxelModifier.cs | 30 ++++++++++---- .../Voxelization/Modifiers/VoxelModifier.xksl | 10 ----- .../Modifiers/VoxelModifierBase.cs | 22 ---------- .../Voxels/Voxelization/RenderVoxelVolume.cs | 12 +++--- .../Processing/BufferToTexture.xksl | 3 +- .../VoxelStorage/VoxelStorageClipmaps.cs | 4 +- .../Voxelization/VoxelVolumeComponent.cs | 2 +- .../VoxelizationMethod/IVoxelizationMethod.cs | 2 +- .../VoxelizationMethodDominantAxis.cs | 2 +- .../VoxelizationMethodSingleAxis.cs | 2 +- .../VoxelizationMethodTriAxis.cs | 2 +- .../Voxels/Voxelization/VoxelizationPass.cs | 8 ++-- .../Voxelization/VoxelizationPassList.cs | 2 +- 34 files changed, 174 insertions(+), 226 deletions(-) delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttribute.cs delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs create mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacity.cs delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs index 82241541cc..c7010f37ac 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/IVoxelVisualization.cs @@ -7,6 +7,6 @@ namespace Xenko.Rendering.Voxels.Debug { public interface IVoxelVisualization { - ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr); + ImageEffectShader GetShader(RenderDrawContext context, VoxelAttribute attr); } } diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs index b55de5abcb..3ac6d09723 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationRaw.cs @@ -15,7 +15,7 @@ public class VoxelVisualizationRaw : IVoxelVisualization public Vector2 Range = new Vector2(0.0f,1.0f); public int RangeOffset = 0; private ImageEffectShader voxelDebugEffectShader = new ImageEffectShader("VoxelVisualizationRawEffect"); - public ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr) + public ImageEffectShader GetShader(RenderDrawContext context, VoxelAttribute attr) { VoxelViewContext viewContext = new VoxelViewContext(false); attr.UpdateSamplingLayout("Attribute"); diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs index 88ee3e2631..e2e362e699 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/VoxelVisualizationView.cs @@ -20,7 +20,7 @@ public class VoxelVisualizationView : IVoxelVisualization public Color Background = new Color(0.1f,0.1f,0.1f,1.0f); private ImageEffectShader voxelDebugEffectShader = new ImageEffectShader("VoxelVisualizationViewEffect"); - public ImageEffectShader GetShader(RenderDrawContext context, IVoxelAttribute attr) + public ImageEffectShader GetShader(RenderDrawContext context, VoxelAttribute attr) { VoxelViewContext viewContext = new VoxelViewContext(false); Matrix ViewProjection = context.RenderContext.RenderView.ViewProjection; diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs index 1d881f31c0..6c7143217a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs @@ -90,7 +90,7 @@ private class LightVoxelShaderGroup : LightShaderGroup public RenderLight Light { get; set; } - IVoxelAttribute traceAttribute = null; + VoxelAttribute traceAttribute = null; public LightVoxelShaderGroup(ShaderSource mixin) : base(mixin) { @@ -113,7 +113,7 @@ ProcessedVoxelVolume GetProcessedVolume() return processedVolume; } - IVoxelAttribute GetTraceAttr() + VoxelAttribute GetTraceAttr() { var lightVoxel = ((LightVoxel)Light.Type); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs deleted file mode 100644 index b58ab02242..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/IVoxelAttribute.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Xenko.Core; -using Xenko.Core.Mathematics; -using Xenko.Shaders; - -namespace Xenko.Rendering.Voxels -{ - public interface IVoxelAttribute - { - void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage); - void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage); - void ClearOutputStorage(); - - void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output); - void CollectAttributes(List attributes, VoxelizationStage stage, bool output); - - bool RequiresColumns(); - void PostProcess(RenderDrawContext drawContext); - - //Writing - ShaderSource GetVoxelizationShader(); - void UpdateVoxelizationLayout(string compositionName); - void ApplyVoxelizationParameters(ParameterCollection parameters); - - int BufferOffset { get; set; } - - //Sampling - ShaderSource GetSamplingShader(); - void UpdateSamplingLayout(string compositionName); - void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); - - int LocalSamplerID { get; set; } - - - } -} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttribute.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttribute.cs new file mode 100644 index 0000000000..9c57606b7a --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttribute.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Core.Annotations; +using Xenko.Shaders; +using Xenko.Rendering.Materials; +using Xenko.Core.Mathematics; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public abstract class VoxelAttribute + { + public abstract void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage); + public abstract void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage); + public abstract void ClearOutputStorage(); + + public abstract void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output); + public abstract void CollectAttributes(List attributes, VoxelizationStage stage, bool output); + + public virtual bool RequiresColumns() => false; + public abstract void PostProcess(RenderDrawContext drawContext); + + //Writing + public abstract ShaderSource GetVoxelizationShader(); + public abstract void UpdateVoxelizationLayout(string compositionName); + public abstract void ApplyVoxelizationParameters(ParameterCollection parameters); + + [DataMemberIgnore] + public virtual int BufferOffset { get; set; } = -1; + + //Sampling + public abstract ShaderSource GetSamplingShader(); + public abstract void UpdateSamplingLayout(string compositionName); + public abstract void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters); + + [DataMemberIgnore] + public virtual int LocalSamplerID { get; set; } = -1; + } +} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs deleted file mode 100644 index 80ee3085da..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeBase.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Xenko.Core; -using Xenko.Core.Annotations; -using Xenko.Shaders; -using Xenko.Rendering.Materials; -using Xenko.Core.Mathematics; - -namespace Xenko.Rendering.Voxels -{ - public abstract class VoxelAttributeBase - { - [DataMemberIgnore] - public int BufferOffset { get; set; } = -1; - [DataMemberIgnore] - public int LocalSamplerID { get; set; } = -1; - - virtual public bool RequiresColumns() - { - return false; - } - } -} diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs index a1786a855c..b97dc6d52e 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeDirectionalCoverage.cs @@ -11,37 +11,37 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Directional Coverage")] - public class VoxelAttributeDirectionalCoverage : VoxelAttributeBase, IVoxelAttribute + public class VoxelAttributeDirectionalCoverage : VoxelAttribute { IVoxelStorageTexture CoverageTex; - public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + public override void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) { BufferOffset = storage.RequestTempStorage(32); } - public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + public override void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) { storage.UpdateTexture(context, ref CoverageTex, Graphics.PixelFormat.R11G11B10_Float, 1); } - public void ClearOutputStorage() + public override void ClearOutputStorage() { CoverageTex = null; } - - public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) + + public override void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) { passList.defaultVoxelizationMethod.CollectVoxelizationPasses(passList, storer, view, resolution, this, stage, output, false); } - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + public override void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); } ShaderSource[] mipmapper = { new ShaderClassSource("Voxel2x2x2MipmapperSimple") }; - public void PostProcess(RenderDrawContext drawContext) + public override void PostProcess(RenderDrawContext drawContext) { CoverageTex.PostProcess(drawContext, mipmapper); } @@ -52,17 +52,17 @@ public void PostProcess(RenderDrawContext drawContext) ShaderClassSource source = new ShaderClassSource("VoxelAttributeDirectionalCoverageShader"); ObjectParameterKey DirectOutput; - public ShaderSource GetVoxelizationShader() + public override ShaderSource GetVoxelizationShader() { var mixin = new ShaderMixinSource(); mixin.Mixins.Add(source); return mixin; } - public void UpdateVoxelizationLayout(string compositionName) + public override void UpdateVoxelizationLayout(string compositionName) { DirectOutput = VoxelAttributeDirectionalCoverageShaderKeys.DirectOutput.ComposeWith(compositionName); } - public void ApplyVoxelizationParameters(ParameterCollection parameters) + public override void ApplyVoxelizationParameters(ParameterCollection parameters) { CoverageTex?.ApplyVoxelizationParameters(DirectOutput, parameters); } @@ -72,7 +72,7 @@ public void ApplyVoxelizationParameters(ParameterCollection parameters) ShaderClassSource sampler = new ShaderClassSource("VoxelAttributeDirectionalCoverageSampler"); - public ShaderSource GetSamplingShader() + public override ShaderSource GetSamplingShader() { var mixin = new ShaderMixinSource(); mixin.Mixins.Add(sampler); @@ -80,11 +80,11 @@ public ShaderSource GetSamplingShader() mixin.AddComposition("storage", CoverageTex.GetSamplingShader()); return mixin; } - public void UpdateSamplingLayout(string compositionName) + public override void UpdateSamplingLayout(string compositionName) { CoverageTex?.UpdateSamplingLayout("storage." + compositionName); } - public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + public override void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) { CoverageTex?.ApplySamplingParameters(viewContext, parameters); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs index f5f48adc89..cfa4426163 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeEmissionOpacity.cs @@ -11,7 +11,7 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Emission+Opacity")] - public class VoxelAttributeEmissionOpacity : VoxelAttributeBase, IVoxelAttribute + public class VoxelAttributeEmissionOpacity : VoxelAttribute { public enum LightFalloffs { @@ -23,20 +23,20 @@ public enum LightFalloffs [NotNull] public IVoxelLayout VoxelLayout { get; set; } = new VoxelLayoutIsotropic(); - public List Modifiers { get; set; } = new List(); + public List Modifiers { get; set; } = new List(); public LightFalloffs LightFalloff { get; set; } = LightFalloffs.Heuristic; - public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + public override void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) { BufferOffset = VoxelLayout.PrepareLocalStorage(context, storage); } - public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + public override void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) { VoxelLayout.PrepareOutputStorage(context, storage); } - public void ClearOutputStorage() + public override void ClearOutputStorage() { VoxelLayout.ClearOutputStorage(); } @@ -44,13 +44,13 @@ public void ClearOutputStorage() - public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) + public override void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) { passList.defaultVoxelizationMethod.CollectVoxelizationPasses(passList, storer, view, resolution, this, stage, output, true); } - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + public override void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { - foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + foreach (VoxelModifierEmissionOpacity modifier in Modifiers) { if (!modifier.Enabled) continue; @@ -59,9 +59,9 @@ public void CollectAttributes(List attributes, VoxelizationStag attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); } - override public bool RequiresColumns() + public override bool RequiresColumns() { - foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + foreach (VoxelModifierEmissionOpacity modifier in Modifiers) { if (!modifier.Enabled) continue; @@ -70,7 +70,7 @@ override public bool RequiresColumns() } return false; } - public void PostProcess(RenderDrawContext drawContext) + public override void PostProcess(RenderDrawContext drawContext) { VoxelLayout.PostProcess(drawContext, LightFalloff); } @@ -80,17 +80,17 @@ public void PostProcess(RenderDrawContext drawContext) ShaderClassSource source = new ShaderClassSource("VoxelAttributeEmissionOpacityShader"); - public ShaderSource GetVoxelizationShader() + public override ShaderSource GetVoxelizationShader() { var mixin = new ShaderMixinSource(); mixin.Mixins.Add(source); mixin.AddComposition("layout", VoxelLayout.GetVoxelizationShader(Modifiers)); return mixin; } - public void UpdateVoxelizationLayout(string compositionName) + public override void UpdateVoxelizationLayout(string compositionName) { int i = 0; - foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + foreach (VoxelModifierEmissionOpacity modifier in Modifiers) { if (!modifier.Enabled) continue; @@ -99,9 +99,9 @@ public void UpdateVoxelizationLayout(string compositionName) } VoxelLayout.UpdateVoxelizationLayout("layout." + compositionName, Modifiers); } - public void ApplyVoxelizationParameters(ParameterCollection parameters) + public override void ApplyVoxelizationParameters(ParameterCollection parameters) { - foreach (IVoxelModifierEmissionOpacity modifier in Modifiers) + foreach (VoxelModifierEmissionOpacity modifier in Modifiers) { if (!modifier.Enabled) continue; @@ -113,15 +113,15 @@ public void ApplyVoxelizationParameters(ParameterCollection parameters) - public ShaderSource GetSamplingShader() + public override ShaderSource GetSamplingShader() { return VoxelLayout.GetSamplingShader(); } - public void UpdateSamplingLayout(string compositionName) + public override void UpdateSamplingLayout(string compositionName) { VoxelLayout.UpdateSamplingLayout(compositionName); } - public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + public override void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) { VoxelLayout.ApplySamplingParameters(viewContext, parameters); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs index 5fd0a454a8..3921861966 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/VoxelAttributeSolidity.cs @@ -11,19 +11,19 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Solidity")] - public class VoxelAttributeSolidity : VoxelAttributeBase, IVoxelAttribute + public class VoxelAttributeSolidity : VoxelAttribute { IVoxelStorageTexture SolidityTex; - public void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) + public override void PrepareLocalStorage(VoxelStorageContext context, IVoxelStorage storage) { BufferOffset = storage.RequestTempStorage(64); } - public void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) + public override void PrepareOutputStorage(VoxelStorageContext context, IVoxelStorage storage) { storage.UpdateTexture(context, ref SolidityTex, Graphics.PixelFormat.R8_UNorm, 1); } - public void ClearOutputStorage() + public override void ClearOutputStorage() { SolidityTex = null; } @@ -36,22 +36,22 @@ public void ClearOutputStorage() MultisampleCount = Graphics.MultisampleCount.None, VoxelizationAxis = VoxelizationMethodSingleAxis.Axis.Y }; - public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) + public override void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelizationStage stage, bool output) { method.CollectVoxelizationPasses(passList, storer, view, resolution, this, stage, output, false); } - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + public override void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { attributes.Add(new AttributeStream(this, VoxelizationStage.Post, output)); } - override public bool RequiresColumns() + public override bool RequiresColumns() { - return false; + return true; } ShaderSource[] mipmapper = { new ShaderClassSource("Voxel2x2x2MipmapperSimple") }; - - public void PostProcess(RenderDrawContext drawContext) + + public override void PostProcess(RenderDrawContext drawContext) { SolidityTex.PostProcess(drawContext, mipmapper); } @@ -62,17 +62,17 @@ public void PostProcess(RenderDrawContext drawContext) ShaderClassSource source = new ShaderClassSource("VoxelAttributeSolidityShader"); ObjectParameterKey DirectOutput; - public ShaderSource GetVoxelizationShader() + public override ShaderSource GetVoxelizationShader() { var mixin = new ShaderMixinSource(); mixin.Mixins.Add(source); return mixin; } - public void UpdateVoxelizationLayout(string compositionName) + public override void UpdateVoxelizationLayout(string compositionName) { DirectOutput = VoxelAttributeSolidityShaderKeys.DirectOutput.ComposeWith(compositionName); } - public void ApplyVoxelizationParameters(ParameterCollection parameters) + public override void ApplyVoxelizationParameters(ParameterCollection parameters) { SolidityTex?.ApplyVoxelizationParameters(DirectOutput, parameters); } @@ -83,7 +83,7 @@ public void ApplyVoxelizationParameters(ParameterCollection parameters) ValueParameterKey BrightnessKey; ShaderClassSource sampler = new ShaderClassSource("VoxelAttributeSoliditySampler"); - public ShaderSource GetSamplingShader() + public override ShaderSource GetSamplingShader() { var mixin = new ShaderMixinSource(); mixin.Mixins.Add(sampler); @@ -91,12 +91,12 @@ public ShaderSource GetSamplingShader() mixin.AddComposition("storage", SolidityTex.GetSamplingShader()); return mixin; } - public void UpdateSamplingLayout(string compositionName) + public override void UpdateSamplingLayout(string compositionName) { BrightnessKey = VoxelIsotropicSamplerKeys.maxBrightness.ComposeWith(compositionName); SolidityTex?.UpdateSamplingLayout("storage." + compositionName); } - public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) + public override void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) { parameters.Set(BrightnessKey, 1.0f); SolidityTex?.ApplySamplingParameters(viewContext, parameters); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs index 041d5d8cf9..0ba99a926a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/IVoxelLayout.cs @@ -14,9 +14,9 @@ public interface IVoxelLayout void PostProcess(RenderDrawContext drawContext, LightFalloffs LightFalloff); //Writing - ShaderSource GetVoxelizationShader(List modifiers); - void UpdateVoxelizationLayout(string compositionName, List modifiers); - void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers); + ShaderSource GetVoxelizationShader(List modifiers); + void UpdateVoxelizationLayout(string compositionName, List modifiers); + void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers); //Sampling ShaderSource GetSamplingShader(); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs index a425e04fb5..2317fa44a3 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs @@ -18,7 +18,7 @@ public class VoxelLayoutAnisotropic : VoxelLayoutBase, IVoxelLayout protected override ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelAnisotropicSampler"); protected override string ApplierKey { get; set; } = "Anisotropic"; - public void UpdateVoxelizationLayout(string compositionName, List modifier) + public void UpdateVoxelizationLayout(string compositionName, List modifier) { DirectOutput = VoxelAnisotropicWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); BrightnessInvKey = VoxelAnisotropicWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs index 9c234ba67b..e779ee0591 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropicPaired.cs @@ -17,7 +17,7 @@ public class VoxelLayoutAnisotropicPaired : VoxelLayoutBase, IVoxelLayout protected override ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelAnisotropicPairedSampler"); protected override string ApplierKey { get; set; } = "AnisotropicPaired"; - public void UpdateVoxelizationLayout(string compositionName, List modifier) + public void UpdateVoxelizationLayout(string compositionName, List modifier) { DirectOutput = VoxelAnisotropicPairedWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); BrightnessInvKey = VoxelAnisotropicPairedWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs index c69fc27b89..3ad9623242 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutBase.cs @@ -117,7 +117,7 @@ virtual public void PostProcess(RenderDrawContext drawContext, LightFalloffs Lig protected ValueParameterKey BrightnessInvKey; protected ObjectParameterKey DirectOutput; - virtual public ShaderSource GetVoxelizationShader(List modifiers) + virtual public ShaderSource GetVoxelizationShader(List modifiers) { var mixin = new ShaderMixinSource(); mixin.Mixins.Add(Writer); @@ -132,7 +132,7 @@ virtual public ShaderSource GetVoxelizationShader(List modifiers) + virtual public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) { if (StorageFormat != StorageFormats.RGBA16F) parameters.Set(BrightnessInvKey, 1.0f / maxBrightness); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs index 6da560a7ab..fea12b545b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutIsotropic.cs @@ -17,7 +17,7 @@ public class VoxelLayoutIsotropic : VoxelLayoutBase, IVoxelLayout protected override ShaderClassSource Sampler { get; set; } = new ShaderClassSource("VoxelIsotropicSampler"); protected override string ApplierKey { get; set; } = "Isotropic"; - public void UpdateVoxelizationLayout(string compositionName, List modifiers) + public void UpdateVoxelizationLayout(string compositionName, List modifiers) { DirectOutput = VoxelIsotropicWriter_Float4Keys.DirectOutput.ComposeWith(compositionName); BrightnessInvKey = VoxelIsotropicWriter_Float4Keys.maxBrightnessInv.ComposeWith(compositionName); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs deleted file mode 100644 index 0fb2da2e3a..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/IVoxelModifierEmissionOpacity.cs +++ /dev/null @@ -1,8 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Xenko.Rendering.Voxels; - -public interface IVoxelModifierEmissionOpacity : IVoxelModifier -{ -} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacity.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacity.cs new file mode 100644 index 0000000000..f8ac33cb74 --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacity.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Xenko.Core; +using Xenko.Rendering.Voxels; + +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public abstract class VoxelModifierEmissionOpacity : VoxelModifier + { + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs index dd1890f501..3204b9855c 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityAntiAliasing.cs @@ -8,21 +8,21 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Anti Aliasing")] - public class VoxelModifierEmissionOpacityAntiAliasing : VoxelModifierBase, IVoxelModifierEmissionOpacity + public class VoxelModifierEmissionOpacityAntiAliasing : VoxelModifierEmissionOpacity { VoxelAttributeDirectionalCoverage directionalCoverage = new VoxelAttributeDirectionalCoverage(); - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + public override void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { directionalCoverage.CollectAttributes(attributes, stage, output); } - public ShaderSource GetApplier(string layout) + public override ShaderSource GetApplier(string layout) { return new ShaderClassSource("VoxelModifierApplierAntiAliasing" + layout, directionalCoverage.LocalSamplerID); } - public void UpdateVoxelizationLayout(string compositionName) { } - public void ApplyVoxelizationParameters(ParameterCollection parameters) { } + public override void UpdateVoxelizationLayout(string compositionName) { } + public override void ApplyVoxelizationParameters(ParameterCollection parameters) { } } } \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs index 47c6746fee..90435919e4 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacityOpacify.cs @@ -8,23 +8,23 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Opacify")] - public class VoxelModifierEmissionOpacityOpacify : VoxelModifierBase, IVoxelModifierEmissionOpacity + public class VoxelModifierEmissionOpacityOpacify : VoxelModifierEmissionOpacity { public float Amount = 2.0f; - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { } + public override void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { } - public ShaderSource GetApplier(string layout) + public override ShaderSource GetApplier(string layout) { return new ShaderClassSource("VoxelModifierApplierOpacify" + layout); } ValueParameterKey AmountKey; - public void UpdateVoxelizationLayout(string compositionName) + public override void UpdateVoxelizationLayout(string compositionName) { AmountKey = VoxelModifierApplierOpacifyIsotropicKeys.Amount.ComposeWith(compositionName); } - public void ApplyVoxelizationParameters(ParameterCollection parameters) + public override void ApplyVoxelizationParameters(ParameterCollection parameters) { parameters.Set(AmountKey, Amount); } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs index a6dc08db6a..55d20caa42 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/EmissionOpacityFilters/VoxelModifierEmissionOpacitySolidify.cs @@ -8,23 +8,23 @@ namespace Xenko.Rendering.Voxels { [DataContract(DefaultMemberMode = DataMemberMode.Default)] [Display("Solidify")] - public class VoxelModifierEmissionOpacitySolidify : VoxelModifierBase, IVoxelModifierEmissionOpacity + public class VoxelModifierEmissionOpacitySolidify : VoxelModifierEmissionOpacity { VoxelAttributeSolidity solidityAttribute = new VoxelAttributeSolidity(); - public void CollectAttributes(List attributes, VoxelizationStage stage, bool output) + public override void CollectAttributes(List attributes, VoxelizationStage stage, bool output) { solidityAttribute.CollectAttributes(attributes, stage, output); } - override public bool RequiresColumns() + public override bool RequiresColumns() { return true; } - public ShaderSource GetApplier(string layout) + public override ShaderSource GetApplier(string layout) { return new ShaderClassSource("VoxelModifierApplierSolidify" + layout, solidityAttribute.LocalSamplerID); } - public void UpdateVoxelizationLayout(string compositionName) { } - public void ApplyVoxelizationParameters(ParameterCollection parameters) { } + public override void UpdateVoxelizationLayout(string compositionName) { } + public override void ApplyVoxelizationParameters(ParameterCollection parameters) { } } } \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs deleted file mode 100644 index bc9f5f67f1..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/IVoxelModifier.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; -using Xenko.Core; -using Xenko.Shaders; - -namespace Xenko.Rendering.Voxels -{ - public interface IVoxelModifier - { - bool Enabled { get; set; } - bool RequiresColumns(); - void CollectAttributes(List attributes, VoxelizationStage stage, bool output); - void UpdateVoxelizationLayout(string compositionName); - void ApplyVoxelizationParameters(ParameterCollection parameters); - ShaderSource GetApplier(string layout); - } -} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs index 274fe38f51..ecc64d6e6d 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.cs @@ -1,9 +1,23 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Text; +using Xenko.Core; +using Xenko.Shaders; -// Nothing to generate +namespace Xenko.Rendering.Voxels +{ + [DataContract(DefaultMemberMode = DataMemberMode.Default)] + public abstract class VoxelModifier + { + [DataMember(-20)] + [DefaultValue(true)] + public bool Enabled { get; set; } = true; + + public virtual bool RequiresColumns() => false; + public abstract void CollectAttributes(List attributes, VoxelizationStage stage, bool output); + public abstract void UpdateVoxelizationLayout(string compositionName); + public abstract void ApplyVoxelizationParameters(ParameterCollection parameters); + public abstract ShaderSource GetApplier(string layout); + } +} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl deleted file mode 100644 index a9bc28f824..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifier.xksl +++ /dev/null @@ -1,10 +0,0 @@ -shader VoxelModifier -{ - void SetupStreamsDummy(){} - void SetupStreams(){} - float4 VoxelizeDirect(uint3 address, uint stride){} - void VoxelizeIndirectWrite(RWBuffer buffer, inout uint address){} - void VoxelizeIndirectRead(RWBuffer buffer, inout uint address, uint2 base_stride){} - - void Apply(inout float4 color){return float4(0,0,0,0);} -}; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs deleted file mode 100644 index 42f4793a7e..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/VoxelModifierBase.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Text; -using Xenko.Core; -using Xenko.Shaders; - -namespace Xenko.Rendering.Voxels -{ - [DataContract(DefaultMemberMode = DataMemberMode.Default)] - public abstract class VoxelModifierBase - { - [DataMember(-20)] - [DefaultValue(true)] - public bool Enabled { get; set; } = true; - - public virtual bool RequiresColumns() - { - return true; - } - } -} \ No newline at end of file diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs index 10531e8072..d6abc7fc9a 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/RenderVoxelVolume.cs @@ -18,10 +18,10 @@ public class DataVoxelVolume public bool VoxelGridSnapping; public bool VisualizeVoxels; - public IVoxelAttribute VisualizationAttribute; + public VoxelAttribute VisualizationAttribute; public IVoxelVisualization VoxelVisualization; - public List Attributes = new List(); + public List Attributes = new List(); public IVoxelStorage Storage; public IVoxelizationMethod VoxelizationMethod; @@ -33,10 +33,10 @@ public enum VoxelizationStage } public struct AttributeStream { - public IVoxelAttribute Attribute; + public VoxelAttribute Attribute; public VoxelizationStage Stage; public bool Output; - public AttributeStream(IVoxelAttribute attribute, VoxelizationStage stage, bool output) + public AttributeStream(VoxelAttribute attribute, VoxelizationStage stage, bool output) { Attribute = attribute; Stage = stage; @@ -47,7 +47,7 @@ public class ProcessedVoxelVolume { public bool Voxelize; public bool VisualizeVoxels; - public IVoxelAttribute VisualizationAttribute; + public VoxelAttribute VisualizationAttribute; public IVoxelVisualization VoxelVisualization; public IVoxelStorage Storage; @@ -58,7 +58,7 @@ public class ProcessedVoxelVolume public List> groupedPasses = new List>(); - public List OutputAttributes = new List(); + public List OutputAttributes = new List(); public List Attributes = new List(); } } diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl index 2736bd5409..797efcc1b0 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl @@ -23,7 +23,8 @@ namespace Xenko.Rendering.Voxels int3 clipMapResolutionI = (int3)clipMapResolution; uint3 pos = streams.DispatchThreadId.xyz; - uint clipIndex = clipOffset; + pos.y = pos.y % clipMapResolutionI.y; + uint clipIndex = clipOffset + streams.DispatchThreadId.y/clipMapResolutionI.y; streams.PositionVXPS = pos; streams.VoxelVolumeSize = clipMapResolutionI; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs index 373ee33a46..f31135d8cf 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageClipmaps.cs @@ -260,8 +260,8 @@ public void PostProcess(VoxelStorageContext storageContext, RenderDrawContext dr bool VoxelsAreIndependent = true; - List IndirectVoxels = new List(); - List TempVoxels = new List(); + List IndirectVoxels = new List(); + List TempVoxels = new List(); ShaderSourceCollection Indirect = new ShaderSourceCollection(); ShaderSourceCollection Temp = new ShaderSourceCollection(); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs index 4963006d63..5b5b97c30e 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs @@ -44,7 +44,7 @@ public override bool Enabled [DataMember(30)] [Category] - public List Attributes { get; set; } = new List(); + public List Attributes { get; set; } = new List(); [DataMember(40)] diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs index e160d2abf5..c852b12847 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/IVoxelizationMethod.cs @@ -19,7 +19,7 @@ namespace Xenko.Rendering.Voxels public interface IVoxelizationMethod { void Reset(); - void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows); + void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows); void Render(VoxelStorageContext storageContext, RenderDrawContext drawContext, RenderView view); bool RequireGeometryShader(); diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs index 4edb6fa8a1..a152683c9c 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodDominantAxis.cs @@ -57,7 +57,7 @@ public override int GetHashCode() return MultisampleCount.GetHashCode(); } - public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) { while (VoxelizationViews.Count <= currentViewIndex) { diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs index ef8bd86505..725b98b266 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodSingleAxis.cs @@ -55,7 +55,7 @@ public override int GetHashCode() } - public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) { var actualView = Matrix.Identity; if (VoxelizationAxis == Axis.Y) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs index 9c396faf81..5b0bd26da5 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/VoxelizationMethodTriAxis.cs @@ -36,7 +36,7 @@ public class VoxelizationMethodTriAxis : IVoxelizationMethod public MultisampleCount MultisampleCount = MultisampleCount.X8; - public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + public void CollectVoxelizationPasses(VoxelizationPassList passList, IVoxelStorer storer, Matrix view, Vector3 resolution, VoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) { axisX.MultisampleCount = MultisampleCount; axisY.MultisampleCount = MultisampleCount; diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs index 74262994cc..2976418a91 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPass.cs @@ -13,9 +13,9 @@ public class VoxelizationPass public IVoxelStorer storer; public IVoxelizationMethod method; //Stage1 - public List AttributesTemp = new List(); - public List AttributesDirect = new List(); - public List AttributesIndirect = new List(); + public List AttributesTemp = new List(); + public List AttributesDirect = new List(); + public List AttributesIndirect = new List(); public ShaderSource source; @@ -23,7 +23,7 @@ public class VoxelizationPass public RenderStage renderStage = null; - public void Add(IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + public void Add(VoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) { if (stage == VoxelizationStage.Initial) { diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs index 8a62135245..e1b78e3f09 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationPassList.cs @@ -9,7 +9,7 @@ public class VoxelizationPassList { public List passes = new List(); public IVoxelizationMethod defaultVoxelizationMethod; - public void AddDirect(IVoxelStorer storer, IVoxelizationMethod method, RenderView view, IVoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) + public void AddDirect(IVoxelStorer storer, IVoxelizationMethod method, RenderView view, VoxelAttribute attr, VoxelizationStage stage, bool output, bool shadows) { bool toAdd = true; foreach (VoxelizationPass pass in passes) From 5263602cc769ee83a7bb349e709b52e74cf7a2ed Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Sun, 26 Jan 2020 16:56:11 +1100 Subject: [PATCH 0669/2038] Fix mipmapping memory leak --- .../VoxelStorageTextureClipmap.cs | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs index db8583d8fb..2b2ed2d703 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/VoxelStorageTextureClipmap.cs @@ -35,10 +35,11 @@ public void ApplyVoxelizationParameters(ObjectParameterKey MainKey, Par { parameters.Set(MainKey, ClipMaps); } + Xenko.Rendering.ComputeEffect.ComputeEffectShader VoxelMipmapSimple; - //Memory leaks if the ThreadGroupCounts/Numbers changes (I suppose due to recompiles...?) + //Memory leaks if the ThreadGroupCounts/Numbers/Composition changes (I suppose due to recompiles...?) //so instead cache them as seperate shaders. - Xenko.Rendering.ComputeEffect.ComputeEffectShader[] VoxelMipmapSimpleGroups; + Xenko.Rendering.ComputeEffect.ComputeEffectShader[][] VoxelMipmapSimpleGroups; public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShaders) { @@ -52,19 +53,29 @@ public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShad VoxelMipmapSimple = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = "Voxel2x2x2MipmapEffect" }; } - if (VoxelMipmapSimpleGroups == null || VoxelMipmapSimpleGroups.Length != TempMipMaps.Length) + if (VoxelMipmapSimpleGroups == null || VoxelMipmapSimpleGroups.Length != LayoutSize || VoxelMipmapSimpleGroups[0].Length != TempMipMaps.Length) { if (VoxelMipmapSimpleGroups != null) { - foreach (var shader in VoxelMipmapSimpleGroups) + for (int axis = 0; axis < LayoutSize; axis++) { - shader.Dispose(); + if (VoxelMipmapSimpleGroups[axis] != null) + { + foreach (var shader in VoxelMipmapSimpleGroups[axis]) + { + shader.Dispose(); + } + } } } - VoxelMipmapSimpleGroups = new Xenko.Rendering.ComputeEffect.ComputeEffectShader[TempMipMaps.Length]; - for (int i = 0; i < VoxelMipmapSimpleGroups.Length; i++) + VoxelMipmapSimpleGroups = new Xenko.Rendering.ComputeEffect.ComputeEffectShader[LayoutSize][]; + for (int axis = 0; axis < LayoutSize; axis++) { - VoxelMipmapSimpleGroups[i] = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = "Voxel2x2x2MipmapEffect" }; + VoxelMipmapSimpleGroups[axis] = new Xenko.Rendering.ComputeEffect.ComputeEffectShader[TempMipMaps.Length]; + for (int i = 0; i < VoxelMipmapSimpleGroups[axis].Length; i++) + { + VoxelMipmapSimpleGroups[axis][i] = new Xenko.Rendering.ComputeEffect.ComputeEffectShader(drawContext.RenderContext) { ShaderSourceName = "Voxel2x2x2MipmapEffect" }; + } } } @@ -133,15 +144,15 @@ public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShad for (int i = 0; i < TempMipMaps.Length - 1; i++) { Vector3 Offset = MippingOffset[offsetIndex]; - var mipmapShader = VoxelMipmapSimpleGroups[i]; resolution /= 2; Vector3 threadNums = Vector3.Min(resolution, new Vector3(8)); - mipmapShader.ThreadNumbers = (Int3)(threadNums); - mipmapShader.ThreadGroupCounts = (Int3)(resolution / threadNums); for (int axis = 0; axis < LayoutSize; axis++) { + var mipmapShader = VoxelMipmapSimpleGroups[axis][i]; + mipmapShader.ThreadNumbers = (Int3)(threadNums); + mipmapShader.ThreadGroupCounts = (Int3)(resolution / threadNums); if (i == 0) { mipmapShader.Parameters.Set(Voxel2x2x2MipmapKeys.ReadTex, ClipMaps); @@ -167,6 +178,8 @@ public void PostProcess(RenderDrawContext drawContext, ShaderSource[] mipmapShad } + + private ObjectParameterKey ClipMapskey; private ObjectParameterKey MipMapskey; private ValueParameterKey perMapOffsetScaleKey; From bad8289ab780b349b0fec0284ef25b38d1d30243 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Sun, 26 Jan 2020 17:23:07 +1100 Subject: [PATCH 0670/2038] Remove Update override --- .../Voxels/Voxelization/VoxelVolumeProcessor.cs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs index 146c0102e1..2616a9c71b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs @@ -37,9 +37,7 @@ protected override void OnSystemAdd() graphicsDevice = Services.GetService().GraphicsDevice; commandList = Services.GetService(); } - public override void Update(GameTime time) - { - } + public override void Draw(RenderContext context) { RegenerateVoxelVolumes(); @@ -70,6 +68,7 @@ private void ComponentChanged(object sender, EventArgs eventArgs) { isDirty = true; } + private void RegenerateVoxelVolumes() { renderVoxelVolumes.Clear(); @@ -112,8 +111,6 @@ private void RegenerateVoxelVolumes() data.VisualizationAttribute = null; } } - - } } } From 7ec768cd0ae902ec8076985cacf99def62ec8dcf Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 26 Jan 2020 17:47:31 -0500 Subject: [PATCH 0671/2038] Version: update version to 3.5 --- sources/shared/SharedAssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 16faa10ea2..df2b94cacc 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -25,7 +25,7 @@ internal class XenkoVersion /// /// The version used by editor for display purpose. 4th digit needs to be at least 1 if used (due to NuGet special cases). /// - public const string PublicVersion = "3.4.1"; + public const string PublicVersion = "3.5"; /// /// The current assembly version as text, currently same as . @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = "-beta01"; + public const string NuGetVersionSuffix = ""; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From 7cde1387e2d3751a73b8a6e9b1a0ea3040ae4de5 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Fri, 16 Aug 2019 21:30:19 +1000 Subject: [PATCH 0672/2038] Added SV_Coverage as exclusive to the pixel stage input --- .../engine/Xenko.Shaders.Parser/Mixins/XenkoStreamCreator.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Shaders.Parser/Mixins/XenkoStreamCreator.cs b/sources/engine/Xenko.Shaders.Parser/Mixins/XenkoStreamCreator.cs index 5d4367e71e..58e542495c 100644 --- a/sources/engine/Xenko.Shaders.Parser/Mixins/XenkoStreamCreator.cs +++ b/sources/engine/Xenko.Shaders.Parser/Mixins/XenkoStreamCreator.cs @@ -463,7 +463,7 @@ private void BubbleUpStreamUsages(List streamStageUsages) if (!prevStreamUsage.OutStreamList.Contains(variable)) { var sem = ((Variable)variable).Qualifiers.OfType().FirstOrDefault(); - if (sem != null && (sem.Name.Text == "SV_IsFrontFace" || sem.Name.Text == "VFACE")) // PS input only + if (sem != null && (sem.Name.Text == "SV_Coverage" || sem.Name.Text == "SV_IsFrontFace" || sem.Name.Text == "VFACE")) // PS input only { stageExclusiveInputStreams.Add(variable); continue; From 2e59d0e598a108e970e48a199665de4711f28a1a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 27 Jan 2020 11:39:12 -0500 Subject: [PATCH 0673/2038] Bump version number for next release --- sources/shared/SharedAssemblyInfo.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index df2b94cacc..d683b1c235 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -25,7 +25,7 @@ internal class XenkoVersion /// /// The version used by editor for display purpose. 4th digit needs to be at least 1 if used (due to NuGet special cases). /// - public const string PublicVersion = "3.5"; + public const string PublicVersion = "3.6"; /// /// The current assembly version as text, currently same as . @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = ""; + public const string NuGetVersionSuffix = "-beta01"; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From 5f188b30e914819c7431863a2e85fe2182b457cb Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 27 Jan 2020 11:40:09 -0500 Subject: [PATCH 0674/2038] Physics: fix issues with contact testing results (Position is now just an Offset) --- .../engine/Xenko.Physics/Bepu/BepuContact.cs | 2 +- .../Bepu/BepuRigidbodyComponent.cs | 66 +++++-------------- .../Xenko.Physics/Bepu/BepuShapeTest.cs | 5 +- .../Xenko.Physics/Bepu/BepuSimulation.cs | 18 ++--- 4 files changed, 28 insertions(+), 63 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuContact.cs b/sources/engine/Xenko.Physics/Bepu/BepuContact.cs index 4261edef19..312446d23c 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuContact.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuContact.cs @@ -8,6 +8,6 @@ namespace Xenko.Physics.Bepu public struct BepuContact { public BepuPhysicsComponent A, B; - public Xenko.Core.Mathematics.Vector3 Normal, Position; + public Xenko.Core.Mathematics.Vector3 Normal, Offset; } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index b8fe53ee2b..3d5ab653ed 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -24,8 +24,6 @@ namespace Xenko.Physics.Bepu [Display("Bepu Rigidbody")] public sealed class BepuRigidbodyComponent : BepuPhysicsComponent { - internal const int CONTACT_LIST_LENGTH = 4; - /// /// Description of the body to be created when added to the scene /// @@ -152,16 +150,21 @@ public bool CollectCollisions { if (processingPhysicalContacts == null) { - processingPhysicalContacts = new List[CONTACT_LIST_LENGTH]; - for (int i=0; i< CONTACT_LIST_LENGTH; i++) processingPhysicalContacts[i] = new List(); - _currentContacts = new List(); + processingPhysicalContacts = new List(); } } - else if (processingPhysicalContacts != null) + else { - _currentContacts.Clear(); - _currentContacts = null; - processingPhysicalContacts = null; + if (processingPhysicalContacts != null) + { + processingPhysicalContacts.Clear(); + processingPhysicalContacts = null; + } + if (currentContactList != null) + { + currentContactList.Clear(); + currentContactList = null; + } } _collectCollisions = value; @@ -177,59 +180,22 @@ public bool CollectCollisions [DataMemberIgnore] private bool _collectCollisions = false; - [DataMemberIgnore] - private List _currentContacts; - /// /// If we are using ProcessCollisionSlim, this list will maintain all current collisions /// [DataMemberIgnore] - public List CurrentContacts - { - get - { - if (_currentContacts == null) return null; - - _currentContacts.Clear(); - - List getFrom = processingPhysicalContacts[(processingPhysicalContactsIndex+1)%CONTACT_LIST_LENGTH]; - - // make sure to only add legit contact points, and to not crash if threading blips happen - try - { - for (int i = 0; i < getFrom.Count; i++) - { - BepuContact bc = getFrom[i]; - if (bc.A != null && bc.B != null) _currentContacts.Add(bc); - } - } - catch (Exception e) { } - - return _currentContacts; - } - } + public List CurrentContacts => currentContactList; internal void swapProcessingContactsList() { if (processingPhysicalContacts == null || IsActive == false) return; - if (processingPhysicalContactsIndex == 0) - { - processingPhysicalContactsIndex = CONTACT_LIST_LENGTH - 1; - } - else - { - processingPhysicalContactsIndex--; - } - - processingPhysicalContacts[processingPhysicalContactsIndex].Clear(); + currentContactList = processingPhysicalContacts; + processingPhysicalContacts = new List(); } [DataMemberIgnore] - internal List[] processingPhysicalContacts; - - [DataMemberIgnore] - internal int processingPhysicalContactsIndex; + internal List processingPhysicalContacts, currentContactList; private static readonly BodyInertia KinematicInertia = new BodyInertia() { diff --git a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs index 2ac73f6715..e50027b357 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs @@ -25,7 +25,6 @@ public class BepuShapeTest public struct BatcherCallbacks : ICollisionCallbacks { public List contactList; - public Xenko.Core.Mathematics.Vector3 position; //These callbacks provide filtering and reporting for pairs being processed by the collision batcher. //"Pair id" refers to the identifier given to the pair when it was added to the batcher. @@ -50,7 +49,7 @@ public void OnPairCompleted(int pairId, ref TManifold manifold) where contactList.Add(new BepuContact() { Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), - Position = BepuHelpers.ToXenko(manifold.SimpleGetOffset()) + position + Offset = BepuHelpers.ToXenko(manifold.SimpleGetOffset()) }); } } @@ -119,7 +118,7 @@ static public unsafe List SingleQuery(TShape shape, Xenko.C { List contacts = new List(); var batcher = new CollisionBatcher(BepuSimulation.safeBufferPool, BepuSimulation.instance.internalSimulation.Shapes, - BepuSimulation.instance.internalSimulation.NarrowPhase.CollisionTaskRegistry, 0f, new BatcherCallbacks() { contactList = contacts, position = position }); + BepuSimulation.instance.internalSimulation.NarrowPhase.CollisionTaskRegistry, 0f, new BatcherCallbacks() { contactList = contacts }); BepuUtilities.Quaternion q = BepuHelpers.ToBepu(rotation); Vector3 v = BepuHelpers.ToBepu(position); shape.ComputeBounds(q, out var boundingBoxMin, out var boundingBoxMax); diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index ea1afe5ac2..54dbfeecdb 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -225,8 +225,8 @@ public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponen BepuRigidbodyComponent ar = (A as BepuRigidbodyComponent); BepuRigidbodyComponent br = (B as BepuRigidbodyComponent); - bool Acollect = ar == null ? false : ar.CollectCollisions && ar.CollectCollisionMaximumCount > ar.processingPhysicalContacts[ar.processingPhysicalContactsIndex].Count; - bool Bcollect = br == null ? false : br.CollectCollisions && br.CollectCollisionMaximumCount > br.processingPhysicalContacts[br.processingPhysicalContactsIndex].Count; + bool Acollect = ar == null ? false : ar.CollectCollisions && ar.CollectCollisionMaximumCount > ar.processingPhysicalContacts.Count; + bool Bcollect = br == null ? false : br.CollectCollisions && br.CollectCollisionMaximumCount > br.processingPhysicalContacts.Count; // do we want to store this collision? if (Acollect || Bcollect) { @@ -235,10 +235,10 @@ public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponen A = A, B = B, Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), - Position = B.Position - BepuHelpers.ToXenko(manifold.SimpleGetOffset()) + Offset = BepuHelpers.ToXenko(manifold.SimpleGetOffset()) }; - if (Acollect) ar.processingPhysicalContacts[ar.processingPhysicalContactsIndex].Add(bc); - if (Bcollect) br.processingPhysicalContacts[br.processingPhysicalContactsIndex].Add(bc); + if (Acollect) ar.processingPhysicalContacts.Add(bc); + if (Bcollect) br.processingPhysicalContacts.Add(bc); } } @@ -481,10 +481,10 @@ internal void ProcessRemovals() } if (rigidBody.processingPhysicalContacts != null) - { - for (int i = 0; i < rigidBody.processingPhysicalContacts.Length; i++) - rigidBody.processingPhysicalContacts[i].Clear(); - } + rigidBody.processingPhysicalContacts.Clear(); + + if (rigidBody.currentContactList != null) + rigidBody.currentContactList.Clear(); } } ToBeRemoved.Clear(); From 50678d2f04e54ab3bf2044788817b6bee177f33d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 27 Jan 2020 20:59:35 -0500 Subject: [PATCH 0675/2038] Version bump --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index d683b1c235..aa39bf8f65 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = "-beta01"; + public const string NuGetVersionSuffix = "-beta02"; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From 657e28a24a480cd4bfe68af8620268f9ff705257 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 27 Jan 2020 21:00:05 -0500 Subject: [PATCH 0676/2038] Physics: fix initialization of static pose after being reloaded --- .../Bepu/BepuPhysicsComponent.cs | 2 -- .../Bepu/BepuRigidbodyComponent.cs | 4 --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 16 ++------- .../Bepu/BepuStaticColliderComponent.cs | 35 +++++++++---------- 4 files changed, 19 insertions(+), 38 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs index 3439d3a3a5..1d13264dec 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuPhysicsComponent.cs @@ -145,8 +145,6 @@ internal void DerivePhysicsTransform(Vector3? worldPosition, Matrix? worldRotati Matrix.Multiply(ref rotation, ref translationMatrix, out outMatrix); } - internal bool useComponentPose; - [DataMemberIgnore] public virtual Vector3 Position { get; set; } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 3d5ab653ed..6ac9612c31 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -533,8 +533,6 @@ public override Vector3 Position { if (bodyDescription.Pose.Position == BepuHelpers.ToBepu(value)) return; - useComponentPose = true; - bodyDescription.Pose.Position.X = value.X; bodyDescription.Pose.Position.Y = value.Y; bodyDescription.Pose.Position.Z = value.Z; @@ -559,8 +557,6 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { if (bodyDescription.Pose.Orientation == BepuHelpers.ToBepu(value)) return; - useComponentPose = true; - bodyDescription.Pose.Orientation.X = value.X; bodyDescription.Pose.Orientation.Y = value.Y; bodyDescription.Pose.Orientation.Z = value.Z; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 54dbfeecdb..d79f01bce8 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -421,11 +421,7 @@ internal void ProcessAdds() if (component is BepuStaticColliderComponent scc) { // static stuff needs positions set first - if (!component.useComponentPose) - { - component.Position = component.Entity.Transform.WorldPosition(); - component.Rotation = component.Entity.Transform.WorldRotation(); - } + scc.preparePose(); using (simulationLocker.WriteLock()) { scc.staticDescription.Collidable = scc.ColliderShape.GenerateDescription(internalSimulation, scc.SpeculativeMargin); @@ -442,15 +438,9 @@ internal void ProcessAdds() rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); RigidMappings[rigidBody.AddedHandle] = rigidBody; } - // after rigids are added, then set position to entity transform if needed - if (!component.useComponentPose) - { - component.Position = component.Entity.Transform.WorldPosition(); - component.Rotation = component.Entity.Transform.WorldRotation(); - } + component.Position = component.Entity.Transform.WorldPosition(); + component.Rotation = component.Entity.Transform.WorldRotation(); } - // clear flag - component.useComponentPose = false; } ToBeAdded.Clear(); } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs index 23173cd64a..71150cf691 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuStaticColliderComponent.cs @@ -36,23 +36,22 @@ public BepuStaticColliderComponent() : base () staticDescription.Pose.Orientation.W = 1f; } + [DataMember] + private Xenko.Core.Mathematics.Vector3? usePosition; + + [DataMember] + private Xenko.Core.Mathematics.Quaternion? useRotation; + [DataMemberIgnore] public override Xenko.Core.Mathematics.Vector3 Position { get { - return BepuHelpers.ToXenko(AddedToScene ? InternalStatic.Pose.Position : staticDescription.Pose.Position); + return usePosition ?? Entity.Transform.WorldPosition(); } set { - useComponentPose = true; - - staticDescription.Pose.Position.X = value.X; - staticDescription.Pose.Position.Y = value.Y; - staticDescription.Pose.Position.Z = value.Z; - - if (AddedToScene) - InternalStatic.Pose.Position = staticDescription.Pose.Position; + usePosition = value; } } @@ -61,22 +60,20 @@ public override Xenko.Core.Mathematics.Quaternion Rotation { get { - return BepuHelpers.ToXenko(AddedToScene ? InternalStatic.Pose.Orientation : staticDescription.Pose.Orientation); + return useRotation ?? Entity.Transform.WorldRotation(); } set { - useComponentPose = true; - - staticDescription.Pose.Orientation.X = value.X; - staticDescription.Pose.Orientation.Y = value.Y; - staticDescription.Pose.Orientation.Z = value.Z; - staticDescription.Pose.Orientation.W = value.W; - - if (AddedToScene) - InternalStatic.Pose.Orientation = staticDescription.Pose.Orientation; + useRotation = value; } } + internal void preparePose() + { + staticDescription.Pose.Position = BepuHelpers.ToBepu(Position); + staticDescription.Pose.Orientation = BepuHelpers.ToBepu(Rotation); + } + [DataMember] public override float SpeculativeMargin { From cd9584e595690b58409432825adcf1a783ae1787 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 13:17:31 -0500 Subject: [PATCH 0677/2038] Audio: further reduce audio thread overhead --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index ff55ec9533..5d9d5fa6f0 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -415,7 +415,7 @@ private static unsafe void Worker() } // sleep after going through the music - Thread.Sleep(10); + Thread.Sleep(100); } } } From 4678d0d1e51b1f77c901e5467200d74b19bf47f7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 13:17:53 -0500 Subject: [PATCH 0678/2038] Version bump --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index aa39bf8f65..f6d104811c 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -49,7 +49,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = "-beta02"; + public const string NuGetVersionSuffix = "-beta03"; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From 5c35fe9edf3abbf530b973cb8e2113b094227a62 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 13:19:23 -0500 Subject: [PATCH 0679/2038] Physics: make contact collection and processing more multithreaded friendly --- .../Bepu/BepuRigidbodyComponent.cs | 30 +++++++++---------- .../Xenko.Physics/Bepu/BepuSimulation.cs | 10 +++---- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 6ac9612c31..c1eb54166e 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -17,6 +17,7 @@ using System.Runtime.CompilerServices; using Xenko.Core.Threading; using System.Threading; +using System.Collections.Concurrent; namespace Xenko.Physics.Bepu { @@ -149,22 +150,12 @@ public bool CollectCollisions if (value) { if (processingPhysicalContacts == null) - { - processingPhysicalContacts = new List(); - } + processingPhysicalContacts = new ConcurrentQueue(); } else { - if (processingPhysicalContacts != null) - { - processingPhysicalContacts.Clear(); - processingPhysicalContacts = null; - } - if (currentContactList != null) - { - currentContactList.Clear(); - currentContactList = null; - } + processingPhysicalContacts = null; + currentContactList = null; } _collectCollisions = value; @@ -190,12 +181,19 @@ internal void swapProcessingContactsList() { if (processingPhysicalContacts == null || IsActive == false) return; - currentContactList = processingPhysicalContacts; - processingPhysicalContacts = new List(); + List buildList = new List(processingPhysicalContacts.Count); + + while (processingPhysicalContacts.TryDequeue(out BepuContact res)) + if (res.A != null && res.B != null) buildList.Add(res); + + currentContactList = buildList; } [DataMemberIgnore] - internal List processingPhysicalContacts, currentContactList; + internal ConcurrentQueue processingPhysicalContacts; + + [DataMemberIgnore] + internal List currentContactList; private static readonly BodyInertia KinematicInertia = new BodyInertia() { diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index d79f01bce8..7363bfd8f6 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -237,8 +237,8 @@ public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponen Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), Offset = BepuHelpers.ToXenko(manifold.SimpleGetOffset()) }; - if (Acollect) ar.processingPhysicalContacts.Add(bc); - if (Bcollect) br.processingPhysicalContacts.Add(bc); + if (Acollect) ar.processingPhysicalContacts.Enqueue(bc); + if (Bcollect) br.processingPhysicalContacts.Enqueue(bc); } } @@ -470,11 +470,11 @@ internal void ProcessRemovals() AllRigidbodies.Remove(rigidBody); } - if (rigidBody.processingPhysicalContacts != null) - rigidBody.processingPhysicalContacts.Clear(); + if (rigidBody.processingPhysicalContacts != null); + while(rigidBody.processingPhysicalContacts.TryDequeue(out var _)); if (rigidBody.currentContactList != null) - rigidBody.currentContactList.Clear(); + rigidBody.currentContactList.Clear(); ; } } ToBeRemoved.Clear(); From 628e37dd0dd50d2e5ab1cc77358b1ce804f63df9 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 15:04:10 -0500 Subject: [PATCH 0680/2038] Physics: fix some breaking leftover semicolons --- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 7363bfd8f6..e7e0fb7121 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -470,11 +470,11 @@ internal void ProcessRemovals() AllRigidbodies.Remove(rigidBody); } - if (rigidBody.processingPhysicalContacts != null); + if (rigidBody.processingPhysicalContacts != null) while(rigidBody.processingPhysicalContacts.TryDequeue(out var _)); if (rigidBody.currentContactList != null) - rigidBody.currentContactList.Clear(); ; + rigidBody.currentContactList.Clear(); } } ToBeRemoved.Clear(); From d3ba2a5937889735623ec0a178d7e21cb39b715d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 15:06:01 -0500 Subject: [PATCH 0681/2038] NuGet: I officially hate NuGet versioning, so I'm using fixed nuget files and displaying a version number separately Visual Studio and GameStudio want to upgrade and restrict libraries based on nuget versions, which breaks more often than helps. Just use a fixed "beta" nuget version, so it always uses the latest nuget packages instead now. GameStudio will have another variable to display the real version. --- sources/editor/Xenko.GameStudio/Program.cs | 2 +- sources/editor/Xenko.GameStudio/XenkoGameStudio.cs | 6 +++--- sources/shared/SharedAssemblyInfo.cs | 6 ++++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/sources/editor/Xenko.GameStudio/Program.cs b/sources/editor/Xenko.GameStudio/Program.cs index 2e17641d96..0ee64f3f1d 100644 --- a/sources/editor/Xenko.GameStudio/Program.cs +++ b/sources/editor/Xenko.GameStudio/Program.cs @@ -54,7 +54,7 @@ namespace Xenko.GameStudio public static class Program { public const string EngineName = "Focus"; - public const string GameStudioName = "Game Studio"; + public const string GameStudioName = "GameStudio"; private static App app; private static IntPtr windowHandle; diff --git a/sources/editor/Xenko.GameStudio/XenkoGameStudio.cs b/sources/editor/Xenko.GameStudio/XenkoGameStudio.cs index 1364f809b6..cf742411d8 100644 --- a/sources/editor/Xenko.GameStudio/XenkoGameStudio.cs +++ b/sources/editor/Xenko.GameStudio/XenkoGameStudio.cs @@ -19,12 +19,12 @@ public static class XenkoGameStudio public static string EditorName => Program.EngineName + " " + Program.GameStudioName + " " + EditorVersion; [NotNull] - public static string EditorVersion => XenkoVersion.NuGetVersion; + public static string EditorVersion => XenkoVersion.VersionToShowInEditor; [NotNull] - public static string EditorVersionWithMetadata => XenkoVersion.NuGetVersion + XenkoVersion.BuildMetadata; + public static string EditorVersionWithMetadata => EditorVersion; - public static string EditorVersionMajor => new System.Version(XenkoVersion.PublicVersion).ToString(2); + public static string EditorVersionMajor => new System.Version(EditorVersion).ToString(2); [NotNull] public static string AnswersUrl => "http://answers.xenko.com/"; diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index f6d104811c..1c440249a6 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -25,7 +25,9 @@ internal class XenkoVersion /// /// The version used by editor for display purpose. 4th digit needs to be at least 1 if used (due to NuGet special cases). /// - public const string PublicVersion = "3.6"; + public const string PublicVersion = "9.9.1"; + + public const string VersionToShowInEditor = "3.5.1"; /// /// The current assembly version as text, currently same as . @@ -49,7 +51,7 @@ internal class XenkoVersion /// - -betaXX: development version (XX should corespond to development asset versioning) /// - -betaXX-YYYY: beta release (YYYY is the git height since current version has been bumped) /// - public const string NuGetVersionSuffix = "-beta03"; + public const string NuGetVersionSuffix = "-nugt99"; /// /// The build metadata, usually +g[git_hash] during package. Automatically set by Xenko.GitVersioning.GenerateVersionFile. From a30c62693438eac1cae302ff216826da7467f0d6 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 15:33:34 -0500 Subject: [PATCH 0682/2038] Better explain NuGet versioning frustrations :) --- sources/shared/SharedAssemblyInfo.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 1c440249a6..a63264bd2e 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -23,10 +23,13 @@ namespace Xenko internal class XenkoVersion { /// - /// The version used by editor for display purpose. 4th digit needs to be at least 1 if used (due to NuGet special cases). + /// The version used by nuget whatever the heck it needs. 4th digit needs to be at least 1 if used (due to stupid NuGet special cases). /// public const string PublicVersion = "9.9.1"; + /// + /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. + /// public const string VersionToShowInEditor = "3.5.1"; /// From 6ca5269f7a910523005e876b2ec9feaab642123c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 15:55:47 -0500 Subject: [PATCH 0683/2038] Vulkan: razor-thin Buffer locking for performance and stability --- .../Xenko.Graphics/Vulkan/Buffer.Vulkan.cs | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs index 12f07686a3..e37a145678 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/Buffer.Vulkan.cs @@ -12,6 +12,7 @@ namespace Xenko.Graphics { public partial class Buffer { + internal static object BufferLocker = new object(); internal SharpVulkan.Buffer NativeBuffer; internal BufferView NativeBufferView; internal AccessFlags NativeAccessMask; @@ -171,7 +172,10 @@ public unsafe void Recreate(IntPtr dataPointer) if (NativeMemory != DeviceMemory.Null) { - GraphicsDevice.NativeDevice.BindBufferMemory(NativeBuffer, NativeMemory, 0); + lock (BufferLocker) + { + GraphicsDevice.NativeDevice.BindBufferMemory(NativeBuffer, NativeMemory, 0); + } } if (SizeInBytes > 0) @@ -188,12 +192,13 @@ public unsafe void Recreate(IntPtr dataPointer) CommandBuffer commandBuffer; - using (GraphicsDevice.QueueLock.ReadLock()) + lock (BufferLocker) { GraphicsDevice.NativeDevice.AllocateCommandBuffers(ref commandBufferAllocateInfo, &commandBuffer); - commandBuffer.Begin(ref beginInfo); } + commandBuffer.Begin(ref beginInfo); + // Copy to upload buffer if (dataPointer != IntPtr.Zero) { @@ -201,7 +206,7 @@ public unsafe void Recreate(IntPtr dataPointer) { var uploadMemory = GraphicsDevice.NativeDevice.MapMemory(NativeMemory, 0, (ulong)SizeInBytes, MemoryMapFlags.None); Utilities.CopyMemory(uploadMemory, dataPointer, SizeInBytes); - using (GraphicsDevice.QueueLock.ReadLock()) + lock (BufferLocker) { GraphicsDevice.NativeDevice.UnmapMemory(NativeMemory); } @@ -226,10 +231,8 @@ public unsafe void Recreate(IntPtr dataPointer) DestinationOffset = 0, Size = (uint)sizeInBytes }; - using (GraphicsDevice.QueueLock.ReadLock()) - { - commandBuffer.CopyBuffer(uploadResource, NativeBuffer, 1, &bufferCopy); - } + + commandBuffer.CopyBuffer(uploadResource, NativeBuffer, 1, &bufferCopy); } } else @@ -252,12 +255,10 @@ public unsafe void Recreate(IntPtr dataPointer) var fence = GraphicsDevice.NativeDevice.CreateFence(ref fenceCreateInfo); // Close and submit - using (GraphicsDevice.QueueLock.WriteLock()) - { - commandBuffer.End(); - GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, fence); - GraphicsDevice.NativeDevice.WaitForFences(1, &fence, true, ulong.MaxValue); - } + commandBuffer.End(); + + GraphicsDevice.NativeCommandQueue.Submit(1, &submitInfo, fence); + GraphicsDevice.NativeDevice.WaitForFences(1, &fence, true, ulong.MaxValue); GraphicsDevice.NativeDevice.FreeCommandBuffers(GraphicsDevice.NativeCopyCommandPool, 1, &commandBuffer); GraphicsDevice.NativeDevice.DestroyFence(fence); From 86a50449140e2821cc4005876db89069f05cee4f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 28 Jan 2020 22:07:35 -0500 Subject: [PATCH 0684/2038] UI Editor: Always expand Appearance on UI Elements, so something useful is shown --- sources/engine/Xenko.UI/UIElement.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.UI/UIElement.cs b/sources/engine/Xenko.UI/UIElement.cs index 6b0552e159..0e1414de57 100644 --- a/sources/engine/Xenko.UI/UIElement.cs +++ b/sources/engine/Xenko.UI/UIElement.cs @@ -18,7 +18,7 @@ namespace Xenko.UI /// Provides a base class for all the User Interface elements in Xenko applications. /// [DataContract(Inherited = true)] - [CategoryOrder(10, AppearanceCategory, Expand = ExpandRule.Auto)] + [CategoryOrder(10, AppearanceCategory, Expand = ExpandRule.Always)] [CategoryOrder(20, BehaviorCategory, Expand = ExpandRule.Auto)] [CategoryOrder(30, LayoutCategory, Expand = ExpandRule.Auto)] [CategoryOrder(100, MiscCategory, Expand = ExpandRule.Auto)] From dd104b08ecae81443ff6fa519beb119bcd912d3e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 29 Jan 2020 09:31:06 -0500 Subject: [PATCH 0685/2038] Physics: update BepuPhysics to latest version --- deps/bepuphysics2/BepuPhysics.dll | 4 +-- deps/bepuphysics2/BepuPhysics.pdb | 4 +-- deps/bepuphysics2/BepuUtilities.dll | 4 +-- deps/bepuphysics2/BepuUtilities.pdb | 4 +-- deps/bepuphysics2/Debug/BepuPhysics.dll | 4 +-- deps/bepuphysics2/Debug/BepuPhysics.pdb | 4 +-- deps/bepuphysics2/Debug/BepuUtilities.dll | 4 +-- deps/bepuphysics2/Debug/BepuUtilities.pdb | 4 +-- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 29 ++++++++++++++++--- .../Xenko.Physics/Bepu/BepuShapeTest.cs | 4 +-- .../Xenko.Physics/Bepu/BepuSimulation.cs | 8 ++--- 11 files changed, 47 insertions(+), 26 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index 58b9319470..38f8f05582 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6c60bd89b4ac7f5fdf18b5f09f0dc978366a7613b38b166837cc7a499b9dde01 -size 708608 +oid sha256:3eb5bd1d5f9eb3f9033b161503653104ad08d2a032f872489abb27778c4206b8 +size 710144 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index 0c6e873277..53ca81fdd9 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4b638db41da657824628fec05bcfe03cdebda786e51afccc7f35e8af1891640d -size 307480 +oid sha256:79bffd15e34bff276f85291be5824a00fde10e29314b2b9f853a58f5bb9acfe5 +size 307176 diff --git a/deps/bepuphysics2/BepuUtilities.dll b/deps/bepuphysics2/BepuUtilities.dll index a2032b96bb..7bf8aa1513 100644 --- a/deps/bepuphysics2/BepuUtilities.dll +++ b/deps/bepuphysics2/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5ac84baa3473b17780872f49177367a23b6e569e2b91e133f85bf210a5acc949 -size 126464 +oid sha256:69fb2eb7a0391839b4fcc41c882c46b15dc17ff29fbde81902f782b89b6c9d94 +size 125952 diff --git a/deps/bepuphysics2/BepuUtilities.pdb b/deps/bepuphysics2/BepuUtilities.pdb index bdcbe8f6e4..1b09444ce0 100644 --- a/deps/bepuphysics2/BepuUtilities.pdb +++ b/deps/bepuphysics2/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:afb1853b76f3fbd9fc9e1455afb2280b4a7d3c0f52ec2f7cdaea195658b681a5 -size 51596 +oid sha256:bc15cf51b2337c8e83075fe829cee5e764f7ab0ffbd2db7429b9507125273d95 +size 51092 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.dll b/deps/bepuphysics2/Debug/BepuPhysics.dll index 3bbf79f35b..b9a3a5b043 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.dll +++ b/deps/bepuphysics2/Debug/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:96a22f075a7faa9f3701c95aaba0888d3cc3f8d9a19be6c8ac3a52f8fa626321 -size 811008 +oid sha256:b1f6eb22b121333288a3683b555e3070238536cd76ae0d9b7f1efa429c9f60fb +size 812032 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.pdb b/deps/bepuphysics2/Debug/BepuPhysics.pdb index a8a4c5b7a4..f02fe041b0 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.pdb +++ b/deps/bepuphysics2/Debug/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3766cee8f17df38ebfa762c388acb0c46454f8adb36a16f5d36cab3573de5753 -size 401520 +oid sha256:acecf201f1e7aa5e4eeb79ac9e9073507cae6db2edcdd5fa1d85e8f11fe4a4b5 +size 401264 diff --git a/deps/bepuphysics2/Debug/BepuUtilities.dll b/deps/bepuphysics2/Debug/BepuUtilities.dll index 247df3637e..2e7f4d3b42 100644 --- a/deps/bepuphysics2/Debug/BepuUtilities.dll +++ b/deps/bepuphysics2/Debug/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:32c4db783dd1936c8d4ea236596e53c697f6a81fedfdf834651f894d239305a5 -size 150016 +oid sha256:cde4de526cded1667c63a0338a58bb2f902a5c131105beee6f50d25ae95ea9d7 +size 149504 diff --git a/deps/bepuphysics2/Debug/BepuUtilities.pdb b/deps/bepuphysics2/Debug/BepuUtilities.pdb index 3cfcf64a34..dad90b4a3c 100644 --- a/deps/bepuphysics2/Debug/BepuUtilities.pdb +++ b/deps/bepuphysics2/Debug/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:373ebad5e6a12de3573d2642837d607ab489c2be1d675c61bb341d666b9e3c44 -size 68484 +oid sha256:a4cef340b7c15923f11cbbaa2ab9e319f95243eb3f88988d6f63d2b9394eb5d7 +size 67884 diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index ac8cb37f12..34bd5f934f 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -489,15 +489,36 @@ public static unsafe Xenko.Core.Mathematics.Vector3 ToXenko(System.Numerics.Vect } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe Xenko.Core.Mathematics.Quaternion ToXenko(BepuUtilities.Quaternion q) + public static Xenko.Core.Mathematics.Quaternion ToXenko(System.Numerics.Quaternion q) { - return *((Xenko.Core.Mathematics.Quaternion*)(void*)&q); + return new Quaternion(q.X, q.Y, q.Z, q.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static unsafe BepuUtilities.Quaternion ToBepu(Xenko.Core.Mathematics.Quaternion q) + public static System.Numerics.Quaternion ToBepu(Xenko.Core.Mathematics.Quaternion q) { - return *((BepuUtilities.Quaternion*)(void*)&q); + return new System.Numerics.Quaternion(q.X, q.Y, q.Z, q.W); } + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToXenko(ref System.Numerics.Quaternion qin, ref Xenko.Core.Mathematics.Quaternion qout) + { + qout.X = qin.X; + qout.Y = qin.Y; + qout.Z = qin.Z; + qout.W = qin.W; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void ToBepu(ref Xenko.Core.Mathematics.Quaternion qin, ref Xenko.Core.Mathematics.Quaternion qout) + { + qout.X = qin.X; + qout.Y = qin.Y; + qout.Z = qin.Z; + qout.W = qin.W; + } + + } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs index e50027b357..9b1b64ca41 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuShapeTest.cs @@ -83,7 +83,7 @@ public bool LoopBody(CollidableReference reference) /// Id to use to refer to this query when the collision batcher finishes processing it. /// Batcher to add the query's tests to. static private unsafe void RunQuery(int queryShapeType, void* queryShapeData, int queryShapeSize, in Vector3 queryBoundsMin, - in Vector3 queryBoundsMax, Vector3 queryPos, BepuUtilities.Quaternion queryRot, + in Vector3 queryBoundsMax, Vector3 queryPos, System.Numerics.Quaternion queryRot, ref CollisionBatcher batcher, CollisionFilterGroupFlags lookingFor) { var broadPhaseEnumerator = new BroadPhaseOverlapEnumerator { components = new List(), lookingFor = (uint)lookingFor }; @@ -119,7 +119,7 @@ static public unsafe List SingleQuery(TShape shape, Xenko.C List contacts = new List(); var batcher = new CollisionBatcher(BepuSimulation.safeBufferPool, BepuSimulation.instance.internalSimulation.Shapes, BepuSimulation.instance.internalSimulation.NarrowPhase.CollisionTaskRegistry, 0f, new BatcherCallbacks() { contactList = contacts }); - BepuUtilities.Quaternion q = BepuHelpers.ToBepu(rotation); + System.Numerics.Quaternion q = BepuHelpers.ToBepu(rotation); Vector3 v = BepuHelpers.ToBepu(position); shape.ComputeBounds(q, out var boundingBoxMin, out var boundingBoxMax); boundingBoxMin += v; diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index e7e0fb7121..deb5b0c59d 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -756,7 +756,7 @@ public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) /// The collision group that this shape sweep can collide with /// /// This kind of shape cannot be used for a ShapeSweep. - public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) + public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) where TShape : unmanaged, IConvexShape { Vector3 diff = endpoint - position; float length = diff.Length(); @@ -777,7 +777,7 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core /// The collision group that this shape sweep can collide with /// /// This kind of shape cannot be used for a ShapeSweep. - public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) + public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) where TShape : unmanaged, IConvexShape { SweepTestFirst sshh = new SweepTestFirst() { @@ -811,7 +811,7 @@ public BepuHitResult ShapeSweep(IConvexShape shape, Vector3 position, Xenko.Core /// The collision group of this shape sweep /// The collision group that this shape sweep can collide with /// This kind of shape cannot be used for a ShapeSweep. - public void ShapeSweepPenetrating(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) + public void ShapeSweepPenetrating(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) where TShape : unmanaged, IConvexShape { Vector3 diff = endpoint - position; float length = diff.Length(); @@ -832,7 +832,7 @@ public void ShapeSweepPenetrating(IConvexShape shape, Vector3 position, Xenko.Co /// The collision group of this shape sweep /// The collision group that this shape sweep can collide with /// This kind of shape cannot be used for a ShapeSweep. - public void ShapeSweepPenetrating(IConvexShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) + public void ShapeSweepPenetrating(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, List output, CollisionFilterGroupFlags hitGroups = DefaultFlags) where TShape : unmanaged, IConvexShape { SweepTestAll sshh = new SweepTestAll() { From 76827af073a54a0648d3a8a75ef793ee4511ebf5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 29 Jan 2020 11:09:14 -0500 Subject: [PATCH 0686/2038] Physics: fix collider mesh generation helper function --- sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs | 4 ++-- sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 34bd5f934f..341ad58115 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -330,7 +330,7 @@ private static unsafe bool getMeshOutputs(Xenko.Rendering.Mesh modelMesh, out Li for (var k = 0; k < numIndices; k++) { // Offset indices - indicies[k] = (int)dst[k]; + indicies.Add((int)dst[k]); } } else @@ -342,7 +342,7 @@ private static unsafe bool getMeshOutputs(Xenko.Rendering.Mesh modelMesh, out Li for (var k = 0; k < numIndices; k++) { // Offset indices - indicies[k] = dst[k]; + indicies.Add(dst[k]); } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index c1eb54166e..8a8cceb020 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -553,7 +553,10 @@ public override Xenko.Core.Mathematics.Quaternion Rotation } set { - if (bodyDescription.Pose.Orientation == BepuHelpers.ToBepu(value)) return; + if (bodyDescription.Pose.Orientation.X == value.X && + bodyDescription.Pose.Orientation.Y == value.Y && + bodyDescription.Pose.Orientation.Z == value.Z && + bodyDescription.Pose.Orientation.W == value.W) return; bodyDescription.Pose.Orientation.X = value.X; bodyDescription.Pose.Orientation.Y = value.Y; From db40ea3ee3e07b45841f8dfeb9ba7ef061197574 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 29 Jan 2020 12:02:40 -0500 Subject: [PATCH 0687/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35877c7e45..1db05dc404 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Easy setting game resolution: Game.SetDefaultSettings(width, height, fullscreen) and Game.OverrideDefaultSettings to set and save resolution of your game. * Easy generating procedural meshes: StagedMeshDraw takes a list of verticies and indicies, no "buffer binding" or "GraphicsDevice" needed. Also will actually upload the mesh when it tries to get rendered automatically, saving time and resources if the mesh doesn't actually ever get viewed. * Less likely to lose work: files are not actually deleted from GameStudio, just moved to the Recylce Bin. If you mess up a prefab or entity in a scene, or if you notice corruption in your project, select Help -> Restore Scene/Prefabs to return your scene and prefab files to the last time to opened your project. -* Performance: lots of tweaks have been made throughout the engine to maximize performance. This includes reducing locks and enumeration reduction, for example. +* Performance: lots of tweaks have been made throughout the engine to maximize performance. This includes reducing locks and enumeration reduction, for example. GameStudio editor itself runs much smoother and can handle multiple tabs much better. * Easy adding/removing entities from the scene: Just do myEntity.Scene = myScene (to add it) or myEntity.Scene = null (to remove it). * Includes dfkeenan's toolkit designed for this fork (from https://github.com/dfkeenan/XenkoToolkit). May need to add the Toolkit Nuget package to use. * Takes good things from many different Xenko forks, including the original Xenko branch when it gets updated. May not get everything, like some of the tutorials, sample, non-PC platforms or launcher updates, which I don't maintain. From a51f0437d4fc98bde16f4d4186f5c4910b2f12a2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 29 Jan 2020 20:53:29 -0500 Subject: [PATCH 0688/2038] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1db05dc404..13d8bf7671 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ My games require the engine to be developed at a faster pace than Xenko. I'm in Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. However, I do not maintain different languages, Android support or the Launcher to "Focus" on things like: * Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. See https://github.com/phr00t/FOVTester2 for a super simple example of how easy a VR project is. -* Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. +* Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. Vulkan works on MacOSX using MoltenVK and Linux. DirectX is deprecated and unsupported on this fork. * BepuPhysics2 and Physics: Focus has an additional physics library integrated, which is much faster, has an easier API, multithreaded and pure C#. It isn't integrated with GameStudio though, like Bullet physics is. See https://github.com/phr00t/FocusEngine/tree/master/sources/engine/Xenko.Physics/Bepu. If you decide to still use Bullet, this fork can handle Bullet running in another thread with interpolation. * API Ease: TransformComponents have nice shortcuts like WorldPosition and WorldRotation. There are also other very useful shortcuts, like Material.Clone to easily clone materials. * Lots of bugfixes: Lots of issues, and even GameStudio crashes and project corruption, have been fixed/improved in this fork. Some specific examples is crashes when entering invalid data into a color field, particle colors, importing multiple audio files at once, or rendering 3D text from multiple cameras. From c80a1832c1ea4bf005c394c4943e67a774c99d49 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 29 Jan 2020 21:11:33 -0500 Subject: [PATCH 0689/2038] Audio: maybe I made the music thread too lazy, let's bring it back a notch... --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 5d9d5fa6f0..43b5e435d5 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -98,7 +98,7 @@ protected DynamicSoundSource(SoundInstance soundInstance, int numberOfBuffers, i if (readFromDiskWorker == null) { readFromDiskWorker = new Thread(new ThreadStart(Worker)); - readFromDiskWorker.Priority = ThreadPriority.Lowest; + readFromDiskWorker.Priority = ThreadPriority.BelowNormal; readFromDiskWorker.IsBackground = true; readFromDiskWorker.Start(); } From ac17e30959f6e4e5f8cf70ca846eddb43f4a1d6b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 29 Jan 2020 21:12:06 -0500 Subject: [PATCH 0690/2038] Physics: turns out we can use fast methods for converting Quaternions --- .../engine/Xenko.Physics/Bepu/BepuHelpers.cs | 29 +++---------------- 1 file changed, 4 insertions(+), 25 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs index 341ad58115..c7328faee4 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuHelpers.cs @@ -489,36 +489,15 @@ public static unsafe Xenko.Core.Mathematics.Vector3 ToXenko(System.Numerics.Vect } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static Xenko.Core.Mathematics.Quaternion ToXenko(System.Numerics.Quaternion q) + public static unsafe Xenko.Core.Mathematics.Quaternion ToXenko(System.Numerics.Quaternion q) { - return new Quaternion(q.X, q.Y, q.Z, q.W); + return *((Xenko.Core.Mathematics.Quaternion*)(void*)&q); } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static System.Numerics.Quaternion ToBepu(Xenko.Core.Mathematics.Quaternion q) + public static unsafe System.Numerics.Quaternion ToBepu(Xenko.Core.Mathematics.Quaternion q) { - return new System.Numerics.Quaternion(q.X, q.Y, q.Z, q.W); + return *((System.Numerics.Quaternion*)(void*)&q); } - - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ToXenko(ref System.Numerics.Quaternion qin, ref Xenko.Core.Mathematics.Quaternion qout) - { - qout.X = qin.X; - qout.Y = qin.Y; - qout.Z = qin.Z; - qout.W = qin.W; - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void ToBepu(ref Xenko.Core.Mathematics.Quaternion qin, ref Xenko.Core.Mathematics.Quaternion qout) - { - qout.X = qin.X; - qout.Y = qin.Y; - qout.Z = qin.Z; - qout.W = qin.W; - } - - } } From 8a054e554b3212d6b045f9f897306664b5b90c82 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 30 Jan 2020 09:27:34 -0500 Subject: [PATCH 0691/2038] Project loading: allow projects to load even if some fields can't be shown in the inspector --- sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs b/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs index 5d702dc41a..20633145b8 100644 --- a/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs +++ b/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs @@ -124,7 +124,7 @@ public override void VisitObject(object obj, ObjectDescriptor descriptor, bool v public override void VisitCollection(IEnumerable collection, CollectionDescriptor descriptor) { if (!descriptor.HasIndexerAccessors) - throw new NotSupportedException("Collections that do not have indexer accessors are not supported in Quantum."); + return; // HashSet or some other set, skip this (don't crash loading the project though, geez!) // Don't visit items unless they are primitive or enumerable (collections within collections) if (IsCollection(descriptor.ElementType)) From f484c3e24854a78a6119d6c2dc0b3e541a5f74cf Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 30 Jan 2020 09:30:59 -0500 Subject: [PATCH 0692/2038] Project loading: allow loading even if dictionary type isn't supported to display in the inspector --- sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs b/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs index 20633145b8..09684777ef 100644 --- a/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs +++ b/sources/presentation/Xenko.Core.Quantum/DefaultNodeBuilder.cs @@ -137,7 +137,7 @@ public override void VisitCollection(IEnumerable collection, CollectionDescripto public override void VisitDictionary(object dictionary, DictionaryDescriptor descriptor) { if (!IsPrimitiveType(descriptor.KeyType)) - throw new InvalidOperationException("The type of dictionary key must be a primary type."); + return; // unsupported dictionary, skip this (don't crash loading the project though, geez!) // Don't visit items unless they are primitive or enumerable (collections within collections) if (IsCollection(descriptor.ValueType)) From a9f766fdbf87c15088c159e4e5d2371637c30c27 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 30 Jan 2020 13:03:09 -0500 Subject: [PATCH 0693/2038] FBX Loading: handle bad material indicies with grace --- sources/tools/Xenko.Importer.FBX/MeshConverter.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp b/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp index 6d37b87198..cb5f983c26 100644 --- a/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp +++ b/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp @@ -425,6 +425,12 @@ public ref class MeshConverter materialIndex = materialIndices->GetAt(i); } + // if we get a bad material index, make a new slot for it + if (materialIndex < 0) { + materialIndex = buildMeshes->Count + 1; + materialIndices->SetAt(i, materialIndex); + } + // Equivalent to std::vector::resize() while (materialIndex >= buildMeshes->Count) { @@ -1744,6 +1750,12 @@ public ref class MeshConverter materialIndex = materialIndices->GetAt(0); } + // if we get a bad material index, make a new slot for it + if (materialIndex < 0) { + materialIndex = buildMeshes->Count + 1; + materialIndices->SetAt(i, materialIndex); + } + // Equivalent to std::vector::resize() while (materialIndex >= buildMeshes->Count) { From 3a3a80c8f930ab9726196da7717327c41d9960c0 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 30 Jan 2020 13:33:58 -0500 Subject: [PATCH 0694/2038] FBX Loading: better handling of negative material indicies --- .../Xenko.Importer.FBX/MeshConverter.cpp | 88 ++++++++++++++----- 1 file changed, 66 insertions(+), 22 deletions(-) diff --git a/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp b/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp index cb5f983c26..1b4cb05915 100644 --- a/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp +++ b/sources/tools/Xenko.Importer.FBX/MeshConverter.cpp @@ -416,6 +416,36 @@ public ref class MeshConverter auto buildMeshes = gcnew List(); + // count material indicies + int maxMaterialIndex = 0; + bool hasBadIndex = false; + for (int i = 0; i < polygonCount; i++) { + int materialIndex = 0; + if (materialMappingMode == FbxGeometryElement::eByPolygon) + { + materialIndex = materialIndices->GetAt(i); + } + else if (materialMappingMode == FbxGeometryElement::eAllSame) + { + materialIndex = materialIndices->GetAt(0); + } + + if (materialIndex > maxMaterialIndex) + maxMaterialIndex = materialIndex; + + if (materialIndex < 0) + hasBadIndex = true; + } + + if (hasBadIndex) maxMaterialIndex++; + + // Equivalent to std::vector::resize() + for (int i = 0; i <= maxMaterialIndex; i++) + { + buildMeshes->Add(nullptr); + buildMeshes[i] = gcnew BuildMesh(); + } + // Count polygon per materials for (int i = 0; i < polygonCount; i++) { @@ -424,22 +454,16 @@ public ref class MeshConverter { materialIndex = materialIndices->GetAt(i); } + else if (materialMappingMode == FbxGeometryElement::eAllSame) + { + materialIndex = materialIndices->GetAt(0); + } - // if we get a bad material index, make a new slot for it if (materialIndex < 0) { - materialIndex = buildMeshes->Count + 1; + materialIndex = maxMaterialIndex; materialIndices->SetAt(i, materialIndex); } - // Equivalent to std::vector::resize() - while (materialIndex >= buildMeshes->Count) - { - buildMeshes->Add(nullptr); - } - - if (buildMeshes[materialIndex] == nullptr) - buildMeshes[materialIndex] = gcnew BuildMesh(); - int polygonSize = pMesh->GetPolygonSize(i) - 2; if (polygonSize > 0) buildMeshes[materialIndex]->polygonCount += polygonSize; @@ -1737,6 +1761,36 @@ public ref class MeshConverter auto buildMeshes = gcnew List(); + // count material indicies + int maxMaterialIndex = 0; + bool hasBadIndex = false; + for (int i = 0; i < polygonCount; i++) { + int materialIndex = 0; + if (materialMappingMode == FbxGeometryElement::eByPolygon) + { + materialIndex = materialIndices->GetAt(i); + } + else if (materialMappingMode == FbxGeometryElement::eAllSame) + { + materialIndex = materialIndices->GetAt(0); + } + + if (materialIndex > maxMaterialIndex) + maxMaterialIndex = materialIndex; + + if (materialIndex < 0) + hasBadIndex = true; + } + + if (hasBadIndex) maxMaterialIndex++; + + // Equivalent to std::vector::resize() + for (int i = 0; i <= maxMaterialIndex; i++) + { + buildMeshes->Add(nullptr); + buildMeshes[i] = gcnew BuildMesh(); + } + // Count polygon per materials for (int i = 0; i < polygonCount; i++) { @@ -1750,21 +1804,11 @@ public ref class MeshConverter materialIndex = materialIndices->GetAt(0); } - // if we get a bad material index, make a new slot for it if (materialIndex < 0) { - materialIndex = buildMeshes->Count + 1; + materialIndex = maxMaterialIndex; materialIndices->SetAt(i, materialIndex); } - // Equivalent to std::vector::resize() - while (materialIndex >= buildMeshes->Count) - { - buildMeshes->Add(nullptr); - } - - if (buildMeshes[materialIndex] == nullptr) - buildMeshes[materialIndex] = gcnew BuildMesh(); - int polygonSize = pMesh->GetPolygonSize(i) - 2; if (polygonSize > 0) buildMeshes[materialIndex]->polygonCount += polygonSize; From 1148dfbd06c8485186d79843b27af6cdcfcb97c6 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 30 Jan 2020 21:57:43 -0500 Subject: [PATCH 0695/2038] Physics: assure B is always the "other" physics body in a BepuContact result --- sources/engine/Xenko.Physics/Bepu/BepuContact.cs | 13 +++++++++++++ .../Xenko.Physics/Bepu/BepuRigidbodyComponent.cs | 8 +++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuContact.cs b/sources/engine/Xenko.Physics/Bepu/BepuContact.cs index 312446d23c..c8bed7386d 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuContact.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuContact.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text; using Xenko.Engine; @@ -9,5 +10,17 @@ public struct BepuContact { public BepuPhysicsComponent A, B; public Xenko.Core.Mathematics.Vector3 Normal, Offset; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void Swap() + { + Normal.X = -Normal.X; + Normal.Y = -Normal.Y; + Normal.Z = -Normal.Z; + Offset = B.Position - (A.Position + Offset); + var C = A; + A = B; + B = C; + } } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 8a8cceb020..62a9ee2ddd 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -184,7 +184,13 @@ internal void swapProcessingContactsList() List buildList = new List(processingPhysicalContacts.Count); while (processingPhysicalContacts.TryDequeue(out BepuContact res)) - if (res.A != null && res.B != null) buildList.Add(res); + { + if (res.A != null && res.B != null) + { + if (res.A != this) res.Swap(); + buildList.Add(res); + } + } currentContactList = buildList; } From c3c1f0bfdb621f7f207a4165699e354f8b7d069c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 1 Feb 2020 20:07:05 -0500 Subject: [PATCH 0696/2038] Audio: fix OpenAL deadlocks on Mac/Linux, also provide OpenAL Windows libraries --- deps/OpenAL/Windows/OpenAL.dll | 3 + deps/OpenAL/Windows/OpenAL32.dll | 3 + sources/engine/Xenko.Audio/Native/OpenAL.cpp | 82 +------------------ sources/engine/Xenko.Audio/Xenko.Audio.csproj | 12 +++ sources/shared/SharedAssemblyInfo.cs | 2 +- 5 files changed, 21 insertions(+), 81 deletions(-) create mode 100644 deps/OpenAL/Windows/OpenAL.dll create mode 100644 deps/OpenAL/Windows/OpenAL32.dll diff --git a/deps/OpenAL/Windows/OpenAL.dll b/deps/OpenAL/Windows/OpenAL.dll new file mode 100644 index 0000000000..70e620a236 --- /dev/null +++ b/deps/OpenAL/Windows/OpenAL.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5eee04c029b6564b6a3ff00388212e4380dc89391dd4bd9ba8cf7109c6b764a5 +size 727040 diff --git a/deps/OpenAL/Windows/OpenAL32.dll b/deps/OpenAL/Windows/OpenAL32.dll new file mode 100644 index 0000000000..dd03536e85 --- /dev/null +++ b/deps/OpenAL/Windows/OpenAL32.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:741f4f01699c551b16adb810be8790ac691765f9a84543869092dd38e9ac01b9 +size 640000 diff --git a/sources/engine/Xenko.Audio/Native/OpenAL.cpp b/sources/engine/Xenko.Audio/Native/OpenAL.cpp index 2ab6469a96..c4b4ba41a1 100644 --- a/sources/engine/Xenko.Audio/Native/OpenAL.cpp +++ b/sources/engine/Xenko.Audio/Native/OpenAL.cpp @@ -76,43 +76,6 @@ extern "C" { void* OpenALLibrary = NULL; - class ContextState - { - public: - ContextState(ALCcontext* context) - { - sOpenAlLock.Lock(); - - mOldContext = GetCurrentContext(); - if (context != mOldContext) - { - MakeContextCurrent(context); - swap = true; - } - else - { - swap = false; - } - } - - ~ContextState() - { - if (swap) - { - MakeContextCurrent(mOldContext); - } - - sOpenAlLock.Unlock(); - } - - private: - bool swap; - ALCcontext* mOldContext; - static SpinLock sOpenAlLock; - }; - - SpinLock ContextState::sOpenAlLock; - DLL_EXPORT_API npBool xnAudioInit() { if (OpenALLibrary) return true; @@ -124,13 +87,11 @@ extern "C" { //PC - Windows if(sizeof(intptr_t) == 4) { - if (!OpenALLibrary) OpenALLibrary = LoadDynamicLibrary("x86\\OpenAL"); - if (!OpenALLibrary) OpenALLibrary = LoadDynamicLibrary("x86/OpenAL"); + if (!OpenALLibrary) OpenALLibrary = LoadDynamicLibrary("OpenAL32"); } else { - if (!OpenALLibrary) OpenALLibrary = LoadDynamicLibrary("x64\\OpenAL"); - if (!OpenALLibrary) OpenALLibrary = LoadDynamicLibrary("x64/OpenAL"); + if (!OpenALLibrary) OpenALLibrary = LoadDynamicLibrary("OpenAL64"); } //iOS @@ -275,8 +236,6 @@ extern "C" { for (auto listener : device->listeners) { - ContextState lock(listener->context); - for(auto source : listener->sources) { if (source->streamed) @@ -352,7 +311,6 @@ extern "C" { device->deviceLock.Lock(); for(auto listener : device->listeners) { - ContextState lock(listener->context); ListenerF(AL_GAIN, volume); } device->deviceLock.Unlock(); @@ -382,8 +340,6 @@ extern "C" { res->mono = mono; res->streamed = streamed; - ContextState lock(listener->context); - GenSources(1, &res->source); AL_ERROR; SourceF(res->source, AL_REFERENCE_DISTANCE, 1.0f); @@ -407,8 +363,6 @@ extern "C" { DLL_EXPORT_API void xnAudioSourceDestroy(xnAudioSource* source) { - ContextState lock(source->listener->context); - DeleteSources(1, &source->source); AL_ERROR; @@ -419,8 +373,6 @@ extern "C" { DLL_EXPORT_API double xnAudioSourceGetPosition(xnAudioSource* source) { - ContextState lock(source->listener->context); - ALfloat offset; GetSourceF(source->source, AL_SEC_OFFSET, &offset); @@ -440,15 +392,11 @@ extern "C" { alpan[1] = sqrt(1.0f - clampedPan*clampedPan); alpan[2] = 0.0f; - ContextState lock(source->listener->context); - SourceFV(source->source, AL_POSITION, alpan); } DLL_EXPORT_API void xnAudioSourceSetLooping(xnAudioSource* source, npBool looping) { - ContextState lock(source->listener->context); - SourceI(source->source, AL_LOOPING, looping ? AL_TRUE : AL_FALSE); } @@ -459,8 +407,6 @@ extern "C" { return; } - ContextState lock(source->listener->context); - ALint playing; GetSourceI(source->source, AL_SOURCE_STATE, &playing); if (playing == AL_PLAYING) SourceStop(source->source); @@ -502,30 +448,22 @@ extern "C" { DLL_EXPORT_API void xnAudioSourceSetGain(xnAudioSource* source, float gain) { - ContextState lock(source->listener->context); - SourceF(source->source, AL_GAIN, gain); } DLL_EXPORT_API void xnAudioSourceSetPitch(xnAudioSource* source, float pitch) { - ContextState lock(source->listener->context); - SourceF(source->source, AL_PITCH, pitch); } DLL_EXPORT_API void xnAudioSourceSetBuffer(xnAudioSource* source, xnAudioBuffer* buffer) { - ContextState lock(source->listener->context); - source->singleBuffer = buffer; SourceI(source->source, AL_BUFFER, buffer->buffer); } DLL_EXPORT_API void xnAudioSourceQueueBuffer(xnAudioSource* source, xnAudioBuffer* buffer, short* pcm, int bufferSize, BufferType type) { - ContextState lock(source->listener->context); - buffer->type = type; buffer->size = bufferSize; BufferData(buffer->buffer, source->mono ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, pcm, bufferSize, source->sampleRate); @@ -535,8 +473,6 @@ extern "C" { DLL_EXPORT_API xnAudioBuffer* xnAudioSourceGetFreeBuffer(xnAudioSource* source) { - ContextState lock(source->listener->context); - if(source->freeBuffers.size() > 0) { auto buffer = source->freeBuffers.back(); @@ -549,22 +485,16 @@ extern "C" { DLL_EXPORT_API void xnAudioSourcePlay(xnAudioSource* source) { - ContextState lock(source->listener->context); - SourcePlay(source->source); } DLL_EXPORT_API void xnAudioSourcePause(xnAudioSource* source) { - ContextState lock(source->listener->context); - SourcePause(source->source); } DLL_EXPORT_API void xnAudioSourceFlushBuffers(xnAudioSource* source) { - ContextState lock(source->listener->context); - if (source->streamed) { //flush all buffers @@ -590,8 +520,6 @@ extern "C" { DLL_EXPORT_API void xnAudioSourceStop(xnAudioSource* source) { - ContextState lock(source->listener->context); - SourceStop(source->source); xnAudioSourceFlushBuffers(source); @@ -602,8 +530,6 @@ extern "C" { DLL_EXPORT_API void xnAudioListenerPush3D(xnAudioListener* listener, float* pos, float* forward, float* up, float* vel, Matrix* worldTransform) { - ContextState lock(listener->context); - if (forward && up) { float ori[6]; @@ -637,8 +563,6 @@ extern "C" { DLL_EXPORT_API void xnAudioSourcePush3D(xnAudioSource* source, float* pos, float* forward, float* up, float* vel, Matrix* worldTransform) { - ContextState lock(source->listener->context); - if (forward && up) { float ori[6]; @@ -672,8 +596,6 @@ extern "C" { DLL_EXPORT_API npBool xnAudioSourceIsPlaying(xnAudioSource* source) { - ContextState lock(source->listener->context); - ALint value; GetSourceI(source->source, AL_SOURCE_STATE, &value); return value == AL_PLAYING || value == AL_PAUSED; diff --git a/sources/engine/Xenko.Audio/Xenko.Audio.csproj b/sources/engine/Xenko.Audio/Xenko.Audio.csproj index 266a19d67b..bbd8dec9b1 100644 --- a/sources/engine/Xenko.Audio/Xenko.Audio.csproj +++ b/sources/engine/Xenko.Audio/Xenko.Audio.csproj @@ -54,4 +54,16 @@ + + + + + %(RecursiveDir)%(Filename)%(Extension) + %(RecursiveDir)%(Filename)%(Extension) + PreserveNewest + + + + + \ No newline at end of file diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index a63264bd2e..1a764686ac 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.1"; + public const string VersionToShowInEditor = "3.5.2"; /// /// The current assembly version as text, currently same as . From 9464f2779906abbaa625d698d9a298375b4ec77b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 1 Feb 2020 21:09:28 -0500 Subject: [PATCH 0697/2038] VR: Update OpenVR to 1.9.16 --- deps/OpenVR/Linux/libopenvr_api.so | 4 +- deps/OpenVR/Windows/x64/openvr_api.dll | 4 +- deps/OpenVR/Windows/x86/openvr_api.dll | 4 +- .../Xenko.VirtualReality/OpenVR/openvr_api.cs | 485 +++++++++++------- 4 files changed, 311 insertions(+), 186 deletions(-) diff --git a/deps/OpenVR/Linux/libopenvr_api.so b/deps/OpenVR/Linux/libopenvr_api.so index 5729c63480..2ca4816ef7 100644 --- a/deps/OpenVR/Linux/libopenvr_api.so +++ b/deps/OpenVR/Linux/libopenvr_api.so @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3d5a73c48d98ca3ceba196c19af2b8769776cfd81beaeae24760fcd3a54658f4 -size 307641 +oid sha256:297c539d48f7544cde6a566fe5294272eefb12009adaa180563f22fb45e9918f +size 324888 diff --git a/deps/OpenVR/Windows/x64/openvr_api.dll b/deps/OpenVR/Windows/x64/openvr_api.dll index f16bace45f..d4400209a5 100644 --- a/deps/OpenVR/Windows/x64/openvr_api.dll +++ b/deps/OpenVR/Windows/x64/openvr_api.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:f8dd871beb832b50cbc63ed9e86b0359cd46564a2a61e9faa0a49a452c36adfd -size 598816 +oid sha256:d421bbaf847361e4129e25f20f9e8575e72e404cbca73405b5569a8db4807658 +size 815568 diff --git a/deps/OpenVR/Windows/x86/openvr_api.dll b/deps/OpenVR/Windows/x86/openvr_api.dll index 96f14e9de2..59d5b60e92 100644 --- a/deps/OpenVR/Windows/x86/openvr_api.dll +++ b/deps/OpenVR/Windows/x86/openvr_api.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5bcb02e79218d06c33eddd117a3ebdf1ef58623b3098914d60ebb9af32baf852 -size 490784 +oid sha256:49197856f32c0d90c86d772713d10c220c89320afa0d44f88a0718ac3a424b2b +size 619472 diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs b/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs index f96ad80b36..2f30de399d 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/openvr_api.cs @@ -9,6 +9,10 @@ using System.Runtime.InteropServices; using Valve.VR; +#if UNITY_5_3_OR_NEWER +using UnityEngine; +#endif + namespace Valve.VR { @@ -240,11 +244,6 @@ public struct IVRSystem [MarshalAs(UnmanagedType.FunctionPtr)] internal _AcknowledgeQuit_Exiting AcknowledgeQuit_Exiting; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate void _AcknowledgeQuit_UserPrompt(); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _AcknowledgeQuit_UserPrompt AcknowledgeQuit_UserPrompt; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetAppContainerFilePaths(System.Text.StringBuilder pchBuffer, uint unBufferSize); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -340,6 +339,16 @@ public struct IVRTrackedCamera [MarshalAs(UnmanagedType.FunctionPtr)] internal _ReleaseVideoStreamTextureGL ReleaseVideoStreamTextureGL; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _SetCameraTrackingSpace(ETrackingUniverseOrigin eUniverse); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetCameraTrackingSpace SetCameraTrackingSpace; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate ETrackingUniverseOrigin _GetCameraTrackingSpace(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetCameraTrackingSpace GetCameraTrackingSpace; + } [StructLayout(LayoutKind.Sequential)] @@ -471,9 +480,9 @@ public struct IVRApplications internal _GetStartingApplication GetStartingApplication; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVRApplicationTransitionState _GetTransitionState(); + internal delegate EVRSceneApplicationState _GetSceneApplicationState(); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetTransitionState GetTransitionState; + internal _GetSceneApplicationState GetSceneApplicationState; [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _PerformApplicationPrelaunchCheck(string pchAppKey); @@ -481,14 +490,9 @@ public struct IVRApplications internal _PerformApplicationPrelaunchCheck PerformApplicationPrelaunchCheck; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate IntPtr _GetApplicationsTransitionStateNameFromEnum(EVRApplicationTransitionState state); + internal delegate IntPtr _GetSceneApplicationStateNameFromEnum(EVRSceneApplicationState state); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetApplicationsTransitionStateNameFromEnum GetApplicationsTransitionStateNameFromEnum; - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _IsQuitUserPromptRequested(); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _IsQuitUserPromptRequested IsQuitUserPromptRequested; + internal _GetSceneApplicationStateNameFromEnum GetSceneApplicationStateNameFromEnum; [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVRApplicationError _LaunchInternalProcess(string pchBinaryPath, string pchArguments, string pchWorkingDirectory); @@ -885,6 +889,16 @@ public struct IVRCompositor [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsCurrentSceneFocusAppLoading IsCurrentSceneFocusAppLoading; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRCompositorError _SetStageOverride_Async(string pchRenderModelPath, ref HmdMatrix34_t pTransform, ref Compositor_StageRenderSettings pRenderSettings, uint nSizeOfRenderSettings); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetStageOverride_Async SetStageOverride_Async; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate void _ClearStageOverride(); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _ClearStageOverride ClearStageOverride; + } [StructLayout(LayoutKind.Sequential)] @@ -905,16 +919,6 @@ public struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _DestroyOverlay DestroyOverlay; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetHighQualityOverlay(ulong ulOverlayHandle); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetHighQualityOverlay SetHighQualityOverlay; - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate ulong _GetHighQualityOverlay(); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetHighQualityOverlay GetHighQualityOverlay; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate uint _GetOverlayKey(ulong ulOverlayHandle, System.Text.StringBuilder pchValue, uint unBufferSize, ref EVROverlayError pError); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -960,6 +964,11 @@ public struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetOverlayFlag GetOverlayFlag; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _GetOverlayFlags(ulong ulOverlayHandle, ref uint pFlags); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOverlayFlags GetOverlayFlags; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayColor(ulong ulOverlayHandle, float fRed, float fGreen, float fBlue); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1011,14 +1020,14 @@ public struct IVROverlay internal _GetOverlayWidthInMeters GetOverlayWidthInMeters; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle, float fMinDistanceInMeters, float fMaxDistanceInMeters); + internal delegate EVROverlayError _SetOverlayCurvature(ulong ulOverlayHandle, float fCurvature); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetOverlayAutoCurveDistanceRangeInMeters SetOverlayAutoCurveDistanceRangeInMeters; + internal _SetOverlayCurvature SetOverlayCurvature; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _GetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle, ref float pfMinDistanceInMeters, ref float pfMaxDistanceInMeters); + internal delegate EVROverlayError _GetOverlayCurvature(ulong ulOverlayHandle, ref float pfCurvature); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetOverlayAutoCurveDistanceRangeInMeters GetOverlayAutoCurveDistanceRangeInMeters; + internal _GetOverlayCurvature GetOverlayCurvature; [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTextureColorSpace(ulong ulOverlayHandle, EColorSpace eTextureColorSpace); @@ -1095,6 +1104,16 @@ public struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayTransformOverlayRelative SetOverlayTransformOverlayRelative; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _SetOverlayTransformCursor(ulong ulCursorOverlayHandle, ref HmdVector2_t pvHotspot); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _SetOverlayTransformCursor SetOverlayTransformCursor; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _GetOverlayTransformCursor(ulong ulOverlayHandle, ref HmdVector2_t pvHotspot); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _GetOverlayTransformCursor GetOverlayTransformCursor; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _ShowOverlay(ulong ulOverlayHandle); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1151,34 +1170,39 @@ public struct IVROverlay internal _IsHoverTargetOverlay IsHoverTargetOverlay; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate ulong _GetGamepadFocusOverlay(); + internal delegate EVROverlayError _SetOverlayDualAnalogTransform(ulong ulOverlay, EDualAnalogWhich eWhich, ref HmdVector2_t pvCenter, float fRadius); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetGamepadFocusOverlay GetGamepadFocusOverlay; + internal _SetOverlayDualAnalogTransform SetOverlayDualAnalogTransform; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetGamepadFocusOverlay(ulong ulNewFocusOverlay); + internal delegate EVROverlayError _GetOverlayDualAnalogTransform(ulong ulOverlay, EDualAnalogWhich eWhich, ref HmdVector2_t pvCenter, ref float pfRadius); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetGamepadFocusOverlay SetGamepadFocusOverlay; + internal _GetOverlayDualAnalogTransform GetOverlayDualAnalogTransform; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetOverlayNeighbor(EOverlayDirection eDirection, ulong ulFrom, ulong ulTo); + internal delegate EVROverlayError _SetOverlayIntersectionMask(ulong ulOverlayHandle, ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives, uint unNumMaskPrimitives, uint unPrimitiveSize); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetOverlayNeighbor SetOverlayNeighbor; + internal _SetOverlayIntersectionMask SetOverlayIntersectionMask; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _MoveGamepadFocusToNeighbor(EOverlayDirection eDirection, ulong ulFrom); + internal delegate EVROverlayError _TriggerLaserMouseHapticVibration(ulong ulOverlayHandle, float fDurationSeconds, float fFrequency, float fAmplitude); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _MoveGamepadFocusToNeighbor MoveGamepadFocusToNeighbor; + internal _TriggerLaserMouseHapticVibration TriggerLaserMouseHapticVibration; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetOverlayDualAnalogTransform(ulong ulOverlay, EDualAnalogWhich eWhich, ref HmdVector2_t pvCenter, float fRadius); + internal delegate EVROverlayError _SetOverlayCursor(ulong ulOverlayHandle, ulong ulCursorHandle); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetOverlayDualAnalogTransform SetOverlayDualAnalogTransform; + internal _SetOverlayCursor SetOverlayCursor; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _GetOverlayDualAnalogTransform(ulong ulOverlay, EDualAnalogWhich eWhich, ref HmdVector2_t pvCenter, ref float pfRadius); + internal delegate EVROverlayError _SetOverlayCursorPositionOverride(ulong ulOverlayHandle, ref HmdVector2_t pvCursor); [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetOverlayDualAnalogTransform GetOverlayDualAnalogTransform; + internal _SetOverlayCursorPositionOverride SetOverlayCursorPositionOverride; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVROverlayError _ClearOverlayCursorPositionOverride(ulong ulOverlayHandle); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _ClearOverlayCursorPositionOverride ClearOverlayCursorPositionOverride; [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate EVROverlayError _SetOverlayTexture(ulong ulOverlayHandle, ref Texture_t pTexture); @@ -1191,7 +1215,7 @@ public struct IVROverlay internal _ClearOverlayTexture ClearOverlayTexture; [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetOverlayRaw(ulong ulOverlayHandle, IntPtr pvBuffer, uint unWidth, uint unHeight, uint unDepth); + internal delegate EVROverlayError _SetOverlayRaw(ulong ulOverlayHandle, IntPtr pvBuffer, uint unWidth, uint unHeight, uint unBytesPerPixel); [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetOverlayRaw SetOverlayRaw; @@ -1280,16 +1304,6 @@ public struct IVROverlay [MarshalAs(UnmanagedType.FunctionPtr)] internal _SetKeyboardPositionForOverlay SetKeyboardPositionForOverlay; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _SetOverlayIntersectionMask(ulong ulOverlayHandle, ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives, uint unNumMaskPrimitives, uint unPrimitiveSize); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _SetOverlayIntersectionMask SetOverlayIntersectionMask; - - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate EVROverlayError _GetOverlayFlags(ulong ulOverlayHandle, ref uint pFlags); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _GetOverlayFlags GetOverlayFlags; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate VRMessageOverlayResponse _ShowMessageOverlay(string pchText, string pchCaption, string pchButton0Text, string pchButton1Text, string pchButton2Text, string pchButton3Text); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1425,11 +1439,6 @@ public struct IVRSettings [MarshalAs(UnmanagedType.FunctionPtr)] internal _GetSettingsErrorNameFromEnum GetSettingsErrorNameFromEnum; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] - internal delegate bool _Sync(bool bForce, ref EVRSettingsError peError); - [MarshalAs(UnmanagedType.FunctionPtr)] - internal _Sync Sync; - [UnmanagedFunctionPointer(CallingConvention.StdCall)] internal delegate void _SetBool(string pchSection, string pchSettingsKey, bool bValue, ref EVRSettingsError peError); [MarshalAs(UnmanagedType.FunctionPtr)] @@ -1700,6 +1709,11 @@ public struct IVRInput [MarshalAs(UnmanagedType.FunctionPtr)] internal _IsUsingLegacyInput IsUsingLegacyInput; + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + internal delegate EVRInputError _OpenBindingUI(string pchAppKey, ulong ulActionSetHandle, ulong ulDeviceHandle, bool bShowOnDesktop); + [MarshalAs(UnmanagedType.FunctionPtr)] + internal _OpenBindingUI OpenBindingUI; + } [StructLayout(LayoutKind.Sequential)] @@ -2099,10 +2113,6 @@ public void AcknowledgeQuit_Exiting() { FnTable.AcknowledgeQuit_Exiting(); } - public void AcknowledgeQuit_UserPrompt() - { - FnTable.AcknowledgeQuit_UserPrompt(); - } public uint GetAppContainerFilePaths(System.Text.StringBuilder pchBuffer,uint unBufferSize) { uint result = FnTable.GetAppContainerFilePaths(pchBuffer,unBufferSize); @@ -2223,6 +2233,15 @@ public EVRTrackedCameraError ReleaseVideoStreamTextureGL(ulong hTrackedCamera,ui EVRTrackedCameraError result = FnTable.ReleaseVideoStreamTextureGL(hTrackedCamera,glTextureId); return result; } + public void SetCameraTrackingSpace(ETrackingUniverseOrigin eUniverse) + { + FnTable.SetCameraTrackingSpace(eUniverse); + } + public ETrackingUniverseOrigin GetCameraTrackingSpace() + { + ETrackingUniverseOrigin result = FnTable.GetCameraTrackingSpace(); + return result; + } } @@ -2358,9 +2377,9 @@ public EVRApplicationError GetStartingApplication(System.Text.StringBuilder pchA EVRApplicationError result = FnTable.GetStartingApplication(pchAppKeyBuffer,unAppKeyBufferLen); return result; } - public EVRApplicationTransitionState GetTransitionState() + public EVRSceneApplicationState GetSceneApplicationState() { - EVRApplicationTransitionState result = FnTable.GetTransitionState(); + EVRSceneApplicationState result = FnTable.GetSceneApplicationState(); return result; } public EVRApplicationError PerformApplicationPrelaunchCheck(string pchAppKey) @@ -2368,16 +2387,11 @@ public EVRApplicationError PerformApplicationPrelaunchCheck(string pchAppKey) EVRApplicationError result = FnTable.PerformApplicationPrelaunchCheck(pchAppKey); return result; } - public string GetApplicationsTransitionStateNameFromEnum(EVRApplicationTransitionState state) + public string GetSceneApplicationStateNameFromEnum(EVRSceneApplicationState state) { - IntPtr result = FnTable.GetApplicationsTransitionStateNameFromEnum(state); + IntPtr result = FnTable.GetSceneApplicationStateNameFromEnum(state); return Marshal.PtrToStringAnsi(result); } - public bool IsQuitUserPromptRequested() - { - bool result = FnTable.IsQuitUserPromptRequested(); - return result; - } public EVRApplicationError LaunchInternalProcess(string pchBinaryPath,string pchArguments,string pchWorkingDirectory) { EVRApplicationError result = FnTable.LaunchInternalProcess(pchBinaryPath,pchArguments,pchWorkingDirectory); @@ -2766,6 +2780,15 @@ public bool IsCurrentSceneFocusAppLoading() bool result = FnTable.IsCurrentSceneFocusAppLoading(); return result; } + public EVRCompositorError SetStageOverride_Async(string pchRenderModelPath,ref HmdMatrix34_t pTransform,ref Compositor_StageRenderSettings pRenderSettings,uint nSizeOfRenderSettings) + { + EVRCompositorError result = FnTable.SetStageOverride_Async(pchRenderModelPath,ref pTransform,ref pRenderSettings,nSizeOfRenderSettings); + return result; + } + public void ClearStageOverride() + { + FnTable.ClearStageOverride(); + } } @@ -2793,16 +2816,6 @@ public EVROverlayError DestroyOverlay(ulong ulOverlayHandle) EVROverlayError result = FnTable.DestroyOverlay(ulOverlayHandle); return result; } - public EVROverlayError SetHighQualityOverlay(ulong ulOverlayHandle) - { - EVROverlayError result = FnTable.SetHighQualityOverlay(ulOverlayHandle); - return result; - } - public ulong GetHighQualityOverlay() - { - ulong result = FnTable.GetHighQualityOverlay(); - return result; - } public uint GetOverlayKey(ulong ulOverlayHandle,System.Text.StringBuilder pchValue,uint unBufferSize,ref EVROverlayError pError) { uint result = FnTable.GetOverlayKey(ulOverlayHandle,pchValue,unBufferSize,ref pError); @@ -2851,6 +2864,12 @@ public EVROverlayError GetOverlayFlag(ulong ulOverlayHandle,VROverlayFlags eOver EVROverlayError result = FnTable.GetOverlayFlag(ulOverlayHandle,eOverlayFlag,ref pbEnabled); return result; } + public EVROverlayError GetOverlayFlags(ulong ulOverlayHandle,ref uint pFlags) + { + pFlags = 0; + EVROverlayError result = FnTable.GetOverlayFlags(ulOverlayHandle,ref pFlags); + return result; + } public EVROverlayError SetOverlayColor(ulong ulOverlayHandle,float fRed,float fGreen,float fBlue) { EVROverlayError result = FnTable.SetOverlayColor(ulOverlayHandle,fRed,fGreen,fBlue); @@ -2908,16 +2927,15 @@ public EVROverlayError GetOverlayWidthInMeters(ulong ulOverlayHandle,ref float p EVROverlayError result = FnTable.GetOverlayWidthInMeters(ulOverlayHandle,ref pfWidthInMeters); return result; } - public EVROverlayError SetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle,float fMinDistanceInMeters,float fMaxDistanceInMeters) + public EVROverlayError SetOverlayCurvature(ulong ulOverlayHandle,float fCurvature) { - EVROverlayError result = FnTable.SetOverlayAutoCurveDistanceRangeInMeters(ulOverlayHandle,fMinDistanceInMeters,fMaxDistanceInMeters); + EVROverlayError result = FnTable.SetOverlayCurvature(ulOverlayHandle,fCurvature); return result; } - public EVROverlayError GetOverlayAutoCurveDistanceRangeInMeters(ulong ulOverlayHandle,ref float pfMinDistanceInMeters,ref float pfMaxDistanceInMeters) + public EVROverlayError GetOverlayCurvature(ulong ulOverlayHandle,ref float pfCurvature) { - pfMinDistanceInMeters = 0; - pfMaxDistanceInMeters = 0; - EVROverlayError result = FnTable.GetOverlayAutoCurveDistanceRangeInMeters(ulOverlayHandle,ref pfMinDistanceInMeters,ref pfMaxDistanceInMeters); + pfCurvature = 0; + EVROverlayError result = FnTable.GetOverlayCurvature(ulOverlayHandle,ref pfCurvature); return result; } public EVROverlayError SetOverlayTextureColorSpace(ulong ulOverlayHandle,EColorSpace eTextureColorSpace) @@ -2998,6 +3016,16 @@ public EVROverlayError SetOverlayTransformOverlayRelative(ulong ulOverlayHandle, EVROverlayError result = FnTable.SetOverlayTransformOverlayRelative(ulOverlayHandle,ulOverlayHandleParent,ref pmatParentOverlayToOverlayTransform); return result; } + public EVROverlayError SetOverlayTransformCursor(ulong ulCursorOverlayHandle,ref HmdVector2_t pvHotspot) + { + EVROverlayError result = FnTable.SetOverlayTransformCursor(ulCursorOverlayHandle,ref pvHotspot); + return result; + } + public EVROverlayError GetOverlayTransformCursor(ulong ulOverlayHandle,ref HmdVector2_t pvHotspot) + { + EVROverlayError result = FnTable.GetOverlayTransformCursor(ulOverlayHandle,ref pvHotspot); + return result; + } public EVROverlayError ShowOverlay(ulong ulOverlayHandle) { EVROverlayError result = FnTable.ShowOverlay(ulOverlayHandle); @@ -3079,35 +3107,40 @@ public bool IsHoverTargetOverlay(ulong ulOverlayHandle) bool result = FnTable.IsHoverTargetOverlay(ulOverlayHandle); return result; } - public ulong GetGamepadFocusOverlay() + public EVROverlayError SetOverlayDualAnalogTransform(ulong ulOverlay,EDualAnalogWhich eWhich,ref HmdVector2_t pvCenter,float fRadius) { - ulong result = FnTable.GetGamepadFocusOverlay(); + EVROverlayError result = FnTable.SetOverlayDualAnalogTransform(ulOverlay,eWhich,ref pvCenter,fRadius); return result; } - public EVROverlayError SetGamepadFocusOverlay(ulong ulNewFocusOverlay) + public EVROverlayError GetOverlayDualAnalogTransform(ulong ulOverlay,EDualAnalogWhich eWhich,ref HmdVector2_t pvCenter,ref float pfRadius) { - EVROverlayError result = FnTable.SetGamepadFocusOverlay(ulNewFocusOverlay); + pfRadius = 0; + EVROverlayError result = FnTable.GetOverlayDualAnalogTransform(ulOverlay,eWhich,ref pvCenter,ref pfRadius); return result; } - public EVROverlayError SetOverlayNeighbor(EOverlayDirection eDirection,ulong ulFrom,ulong ulTo) + public EVROverlayError SetOverlayIntersectionMask(ulong ulOverlayHandle,ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives,uint unNumMaskPrimitives,uint unPrimitiveSize) { - EVROverlayError result = FnTable.SetOverlayNeighbor(eDirection,ulFrom,ulTo); + EVROverlayError result = FnTable.SetOverlayIntersectionMask(ulOverlayHandle,ref pMaskPrimitives,unNumMaskPrimitives,unPrimitiveSize); return result; } - public EVROverlayError MoveGamepadFocusToNeighbor(EOverlayDirection eDirection,ulong ulFrom) + public EVROverlayError TriggerLaserMouseHapticVibration(ulong ulOverlayHandle,float fDurationSeconds,float fFrequency,float fAmplitude) { - EVROverlayError result = FnTable.MoveGamepadFocusToNeighbor(eDirection,ulFrom); + EVROverlayError result = FnTable.TriggerLaserMouseHapticVibration(ulOverlayHandle,fDurationSeconds,fFrequency,fAmplitude); return result; } - public EVROverlayError SetOverlayDualAnalogTransform(ulong ulOverlay,EDualAnalogWhich eWhich,ref HmdVector2_t pvCenter,float fRadius) + public EVROverlayError SetOverlayCursor(ulong ulOverlayHandle,ulong ulCursorHandle) { - EVROverlayError result = FnTable.SetOverlayDualAnalogTransform(ulOverlay,eWhich,ref pvCenter,fRadius); + EVROverlayError result = FnTable.SetOverlayCursor(ulOverlayHandle,ulCursorHandle); return result; } - public EVROverlayError GetOverlayDualAnalogTransform(ulong ulOverlay,EDualAnalogWhich eWhich,ref HmdVector2_t pvCenter,ref float pfRadius) + public EVROverlayError SetOverlayCursorPositionOverride(ulong ulOverlayHandle,ref HmdVector2_t pvCursor) { - pfRadius = 0; - EVROverlayError result = FnTable.GetOverlayDualAnalogTransform(ulOverlay,eWhich,ref pvCenter,ref pfRadius); + EVROverlayError result = FnTable.SetOverlayCursorPositionOverride(ulOverlayHandle,ref pvCursor); + return result; + } + public EVROverlayError ClearOverlayCursorPositionOverride(ulong ulOverlayHandle) + { + EVROverlayError result = FnTable.ClearOverlayCursorPositionOverride(ulOverlayHandle); return result; } public EVROverlayError SetOverlayTexture(ulong ulOverlayHandle,ref Texture_t pTexture) @@ -3120,9 +3153,9 @@ public EVROverlayError ClearOverlayTexture(ulong ulOverlayHandle) EVROverlayError result = FnTable.ClearOverlayTexture(ulOverlayHandle); return result; } - public EVROverlayError SetOverlayRaw(ulong ulOverlayHandle,IntPtr pvBuffer,uint unWidth,uint unHeight,uint unDepth) + public EVROverlayError SetOverlayRaw(ulong ulOverlayHandle,IntPtr pvBuffer,uint unWidth,uint unHeight,uint unBytesPerPixel) { - EVROverlayError result = FnTable.SetOverlayRaw(ulOverlayHandle,pvBuffer,unWidth,unHeight,unDepth); + EVROverlayError result = FnTable.SetOverlayRaw(ulOverlayHandle,pvBuffer,unWidth,unHeight,unBytesPerPixel); return result; } public EVROverlayError SetOverlayFromFile(ulong ulOverlayHandle,string pchFilePath) @@ -3214,17 +3247,6 @@ public void SetKeyboardPositionForOverlay(ulong ulOverlayHandle,HmdRect2_t avoid { FnTable.SetKeyboardPositionForOverlay(ulOverlayHandle,avoidRect); } - public EVROverlayError SetOverlayIntersectionMask(ulong ulOverlayHandle,ref VROverlayIntersectionMaskPrimitive_t pMaskPrimitives,uint unNumMaskPrimitives,uint unPrimitiveSize) - { - EVROverlayError result = FnTable.SetOverlayIntersectionMask(ulOverlayHandle,ref pMaskPrimitives,unNumMaskPrimitives,unPrimitiveSize); - return result; - } - public EVROverlayError GetOverlayFlags(ulong ulOverlayHandle,ref uint pFlags) - { - pFlags = 0; - EVROverlayError result = FnTable.GetOverlayFlags(ulOverlayHandle,ref pFlags); - return result; - } public VRMessageOverlayResponse ShowMessageOverlay(string pchText,string pchCaption,string pchButton0Text,string pchButton1Text,string pchButton2Text,string pchButton3Text) { VRMessageOverlayResponse result = FnTable.ShowMessageOverlay(pchText,pchCaption,pchButton0Text,pchButton1Text,pchButton2Text,pchButton3Text); @@ -3398,11 +3420,6 @@ public string GetSettingsErrorNameFromEnum(EVRSettingsError eError) IntPtr result = FnTable.GetSettingsErrorNameFromEnum(eError); return Marshal.PtrToStringAnsi(result); } - public bool Sync(bool bForce,ref EVRSettingsError peError) - { - bool result = FnTable.Sync(bForce,ref peError); - return result; - } public void SetBool(string pchSection,string pchSettingsKey,bool bValue,ref EVRSettingsError peError) { FnTable.SetBool(pchSection,pchSettingsKey,bValue,ref peError); @@ -3694,6 +3711,11 @@ public bool IsUsingLegacyInput() bool result = FnTable.IsUsingLegacyInput(); return result; } + public EVRInputError OpenBindingUI(string pchAppKey,ulong ulActionSetHandle,ulong ulDeviceHandle,bool bShowOnDesktop) + { + EVRInputError result = FnTable.OpenBindingUI(pchAppKey,ulActionSetHandle,ulDeviceHandle,bShowOnDesktop); + return result; + } } @@ -3817,6 +3839,8 @@ public class OpenVRInterop internal static extern bool IsRuntimeInstalled(); [DllImportAttribute("openvr_api", EntryPoint = "VR_RuntimePath", CallingConvention = CallingConvention.Cdecl)] internal static extern string RuntimePath(); + [DllImportAttribute("openvr_api", EntryPoint = "VR_GetRuntimePath", CallingConvention = CallingConvention.Cdecl)] + internal static extern bool GetRuntimePath(System.Text.StringBuilder pchPathBuffer, uint unBufferSize, ref uint punRequiredBufferSize); [DllImportAttribute("openvr_api", EntryPoint = "VR_GetStringForHmdError", CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr GetStringForHmdError(EVRInitError error); [DllImportAttribute("openvr_api", EntryPoint = "VR_GetGenericInterface", CallingConvention = CallingConvention.Cdecl)] @@ -3876,6 +3900,7 @@ public enum ETrackedControllerRole RightHand = 2, OptOut = 3, Treadmill = 4, + Stylus = 5, Max = 5, } public enum ETrackingUniverseOrigin @@ -3942,6 +3967,10 @@ public enum ETrackedDeviceProperty Prop_AdditionalSystemReportData_String = 1045, Prop_CompositeFirmwareVersion_String = 1046, Prop_Firmware_RemindUpdate_Bool = 1047, + Prop_PeripheralApplicationVersion_Uint64 = 1048, + Prop_ManufacturerSerialNumber_String = 1049, + Prop_ComputedSerialNumber_String = 1050, + Prop_EstimatedDeviceFirstUseTime_Int32 = 1051, Prop_ReportsTimeSinceVSync_Bool = 2000, Prop_SecondsFromVsyncToPhotons_Float = 2001, Prop_DisplayFrequency_Float = 2002, @@ -4016,11 +4045,20 @@ public enum ETrackedDeviceProperty Prop_ExpectedControllerType_String = 2074, Prop_HmdTrackingStyle_Int32 = 2075, Prop_DriverProvidedChaperoneVisibility_Bool = 2076, + Prop_HmdColumnCorrectionSettingPrefix_String = 2077, + Prop_CameraSupportsCompatibilityModes_Bool = 2078, Prop_DisplayAvailableFrameRates_Float_Array = 2080, Prop_DisplaySupportsMultipleFramerates_Bool = 2081, Prop_DisplayColorMultLeft_Vector3 = 2082, Prop_DisplayColorMultRight_Vector3 = 2083, + Prop_DisplaySupportsRuntimeFramerateChange_Bool = 2084, + Prop_DisplaySupportsAnalogGain_Bool = 2085, + Prop_DisplayMinAnalogGain_Float = 2086, + Prop_DisplayMaxAnalogGain_Float = 2087, Prop_DashboardLayoutPathName_String = 2090, + Prop_DashboardScale_Float = 2091, + Prop_IpdUIRangeMinMeters_Float = 2100, + Prop_IpdUIRangeMaxMeters_Float = 2101, Prop_DriverRequestedMuraCorrectionMode_Int32 = 2200, Prop_DriverRequestedMuraFeather_InnerLeft_Int32 = 2201, Prop_DriverRequestedMuraFeather_InnerRight_Int32 = 2202, @@ -4030,6 +4068,9 @@ public enum ETrackedDeviceProperty Prop_DriverRequestedMuraFeather_OuterRight_Int32 = 2206, Prop_DriverRequestedMuraFeather_OuterTop_Int32 = 2207, Prop_DriverRequestedMuraFeather_OuterBottom_Int32 = 2208, + Prop_Audio_DefaultPlaybackDeviceId_String = 2300, + Prop_Audio_DefaultRecordingDeviceId_String = 2301, + Prop_Audio_DefaultPlaybackDeviceVolume_Float = 2302, Prop_AttachedDeviceId_String = 3000, Prop_SupportedButtons_Uint64 = 3001, Prop_Axis0Type_Int32 = 3002, @@ -4056,9 +4097,11 @@ public enum ETrackedDeviceProperty Prop_NamedIconPathDeviceNotReady_String = 5006, Prop_NamedIconPathDeviceStandby_String = 5007, Prop_NamedIconPathDeviceAlertLow_String = 5008, + Prop_NamedIconPathDeviceStandbyAlert_String = 5009, Prop_DisplayHiddenArea_Binary_Start = 5100, Prop_DisplayHiddenArea_Binary_End = 5150, Prop_ParentContainer = 5151, + Prop_OverrideContainer_Uint64 = 5152, Prop_UserConfigPath_String = 6000, Prop_InstallPath_String = 6001, Prop_HasDisplayComponent_Bool = 6002, @@ -4089,6 +4132,8 @@ public enum ETrackedPropertyError TrackedProp_InvalidOperation = 11, TrackedProp_CannotWriteToWildcards = 12, TrackedProp_IPCReadFailure = 13, + TrackedProp_OutOfMemory = 14, + TrackedProp_InvalidContainer = 15, } public enum EHmdTrackingStyle { @@ -4159,16 +4204,14 @@ public enum EVREventType VREvent_ScrollSmooth = 309, VREvent_InputFocusCaptured = 400, VREvent_InputFocusReleased = 401, - VREvent_SceneFocusLost = 402, - VREvent_SceneFocusGained = 403, VREvent_SceneApplicationChanged = 404, VREvent_SceneFocusChanged = 405, VREvent_InputFocusChanged = 406, - VREvent_SceneApplicationSecondaryRenderingStarted = 407, VREvent_SceneApplicationUsingWrongGraphicsAdapter = 408, VREvent_ActionBindingReloaded = 409, VREvent_HideRenderModels = 410, VREvent_ShowRenderModels = 411, + VREvent_SceneApplicationStateChanged = 412, VREvent_ConsoleOpened = 420, VREvent_ConsoleClosed = 421, VREvent_OverlayShown = 500, @@ -4204,7 +4247,6 @@ public enum EVREventType VREvent_Notification_Destroyed = 603, VREvent_Quit = 700, VREvent_ProcessQuit = 701, - VREvent_QuitAborted_UserPrompt = 702, VREvent_QuitAcknowledged = 703, VREvent_DriverRequestedQuit = 704, VREvent_RestartRequested = 705, @@ -4236,6 +4278,7 @@ public enum EVREventType VREvent_TrackersSectionSettingChanged = 866, VREvent_LastKnownSectionSettingChanged = 867, VREvent_DismissedWarningsSectionSettingChanged = 868, + VREvent_GpuSpeedSectionSettingChanged = 869, VREvent_StatusUpdate = 900, VREvent_WebInterface_InstallDriverCompleted = 950, VREvent_MCImageUpdated = 1000, @@ -4244,16 +4287,10 @@ public enum EVREventType VREvent_KeyboardClosed = 1200, VREvent_KeyboardCharInput = 1201, VREvent_KeyboardDone = 1202, - VREvent_ApplicationTransitionStarted = 1300, - VREvent_ApplicationTransitionAborted = 1301, - VREvent_ApplicationTransitionNewAppStarted = 1302, VREvent_ApplicationListUpdated = 1303, VREvent_ApplicationMimeTypeLoad = 1304, - VREvent_ApplicationTransitionNewAppLaunchComplete = 1305, VREvent_ProcessConnected = 1306, VREvent_ProcessDisconnected = 1307, - VREvent_Compositor_MirrorWindowShown = 1400, - VREvent_Compositor_MirrorWindowHidden = 1401, VREvent_Compositor_ChaperoneBoundsShown = 1410, VREvent_Compositor_ChaperoneBoundsHidden = 1411, VREvent_Compositor_DisplayDisconnected = 1412, @@ -4262,6 +4299,8 @@ public enum EVREventType VREvent_Compositor_ApplicationNotResponding = 1415, VREvent_Compositor_ApplicationResumed = 1416, VREvent_Compositor_OutOfVideoMemory = 1417, + VREvent_Compositor_DisplayModeNotSupported = 1418, + VREvent_Compositor_StageOverrideReady = 1419, VREvent_TrackedCamera_StartVideoStream = 1500, VREvent_TrackedCamera_StopVideoStream = 1501, VREvent_TrackedCamera_PauseVideoStream = 1502, @@ -4280,11 +4319,14 @@ public enum EVREventType VREvent_Input_ProgressUpdate = 1705, VREvent_Input_TrackerActivated = 1706, VREvent_Input_BindingsUpdated = 1707, + VREvent_Input_BindingSubscriptionChanged = 1708, VREvent_SpatialAnchors_PoseUpdated = 1800, VREvent_SpatialAnchors_DescriptorUpdated = 1801, VREvent_SpatialAnchors_RequestPoseUpdate = 1802, VREvent_SpatialAnchors_RequestDescriptorUpdate = 1803, VREvent_SystemReport_Started = 1900, + VREvent_Monitor_ShowHeadsetView = 2000, + VREvent_Monitor_HideHeadsetView = 2001, VREvent_VendorSpecific_Reserved_Start = 10000, VREvent_VendorSpecific_Reserved_End = 19999, } @@ -4295,6 +4337,7 @@ public enum EDeviceActivityLevel k_EDeviceActivityLevel_UserInteraction = 1, k_EDeviceActivityLevel_UserInteraction_Timeout = 2, k_EDeviceActivityLevel_Standby = 3, + k_EDeviceActivityLevel_Idle_Timeout = 4, } public enum EVRButtonId { @@ -4338,6 +4381,7 @@ public enum EShowUIType ShowUI_Pairing = 3, ShowUI_Settings = 4, ShowUI_DebugCommands = 5, + ShowUI_FullControllerBinding = 6, } public enum EHDCPError { @@ -4530,6 +4574,7 @@ public enum EVRInitError Init_AlreadyRunning = 143, Init_FailedForVrMonitor = 144, Init_PropertyManagerInitFailed = 145, + Init_WebServerFailed = 146, Driver_Failed = 200, Driver_Unknown = 201, Driver_HmdUnknown = 202, @@ -4641,6 +4686,7 @@ public enum EVRInitError Compositor_CreateLastFrameRenderTexture = 484, Compositor_CreateMirrorOverlay = 485, Compositor_FailedToCreateVirtualDisplayBackbuffer = 486, + Compositor_DisplayModeNotSupported = 487, VendorSpecific_UnableToConnectToOculusRuntime = 1000, VendorSpecific_WindowsNotInDevMode = 1001, VendorSpecific_HmdFound_CantOpenDevice = 1101, @@ -4777,14 +4823,16 @@ public enum EVRApplicationProperty IsInstanced_Bool = 62, IsInternal_Bool = 63, WantsCompositorPauseInStandby_Bool = 64, + IsHidden_Bool = 65, LastLaunchTime_Uint64 = 70, } -public enum EVRApplicationTransitionState +public enum EVRSceneApplicationState { - VRApplicationTransition_None = 0, - VRApplicationTransition_OldAppQuitSent = 10, - VRApplicationTransition_WaitingForExternalLaunch = 11, - VRApplicationTransition_NewAppLaunched = 20, + None = 0, + Starting = 1, + Quitting = 2, + Running = 3, + Waiting = 4, } public enum ChaperoneCalibrationState { @@ -4822,6 +4870,7 @@ public enum EVRCompositorError IndexOutOfRange = 107, AlreadySubmitted = 108, InvalidBounds = 109, + AlreadySet = 110, } public enum EVRCompositorTimingMode { @@ -4837,32 +4886,32 @@ public enum VROverlayInputMethod } public enum VROverlayTransformType { + VROverlayTransform_Invalid = -1, VROverlayTransform_Absolute = 0, VROverlayTransform_TrackedDeviceRelative = 1, VROverlayTransform_SystemOverlay = 2, VROverlayTransform_TrackedComponent = 3, + VROverlayTransform_Cursor = 4, + VROverlayTransform_DashboardTab = 5, + VROverlayTransform_DashboardThumb = 6, } public enum VROverlayFlags { - None = 0, - Curved = 1, - RGSS4X = 2, - NoDashboardTab = 3, - AcceptsGamepadEvents = 4, - ShowGamepadFocus = 5, - SendVRDiscreteScrollEvents = 6, - SendVRTouchpadEvents = 7, - ShowTouchPadScrollWheel = 8, - TransferOwnershipToInternalProcess = 9, - SideBySide_Parallel = 10, - SideBySide_Crossed = 11, - Panorama = 12, - StereoPanorama = 13, - SortWithNonSceneOverlays = 14, - VisibleInDashboard = 15, - MakeOverlaysInteractiveIfVisible = 16, - SendVRSmoothScrollEvents = 17, - ProtectedContent = 18, + NoDashboardTab = 8, + SendVRDiscreteScrollEvents = 64, + SendVRTouchpadEvents = 128, + ShowTouchPadScrollWheel = 256, + TransferOwnershipToInternalProcess = 512, + SideBySide_Parallel = 1024, + SideBySide_Crossed = 2048, + Panorama = 4096, + StereoPanorama = 8192, + SortWithNonSceneOverlays = 16384, + VisibleInDashboard = 32768, + MakeOverlaysInteractiveIfVisible = 65536, + SendVRSmoothScrollEvents = 131072, + ProtectedContent = 262144, + HideLaserIntersection = 524288, } public enum VRMessageOverlayResponse { @@ -4885,14 +4934,6 @@ public enum EGamepadTextInputLineMode k_EGamepadTextInputLineModeSingleLine = 0, k_EGamepadTextInputLineModeMultipleLines = 1, } -public enum EOverlayDirection -{ - Up = 0, - Down = 1, - Left = 2, - Right = 3, - Count = 4, -} public enum EVROverlayIntersectionMaskPrimitiveType { OverlayIntersectionPrimitiveType_Rectangle = 0, @@ -5077,6 +5118,42 @@ public enum EVRDebugError public float m9; public float m10; public float m11; +#if UNITY_5_3_OR_NEWER + + public Vector3 GetPosition() + { + return new Vector3(m3, m7, -m11); + } + + public bool IsRotationValid() + { + return ((m2 != 0 || m6 != 0 || m10 != 0) && (m1 != 0 || m5 != 0 || m9 != 0)); + } + + public Quaternion GetRotation() + { + if (IsRotationValid()) + { + float w = Mathf.Sqrt(Mathf.Max(0, 1 + m0 + m5 + m10)) / 2; + float x = Mathf.Sqrt(Mathf.Max(0, 1 + m0 - m5 - m10)) / 2; + float y = Mathf.Sqrt(Mathf.Max(0, 1 - m0 + m5 - m10)) / 2; + float z = Mathf.Sqrt(Mathf.Max(0, 1 - m0 - m5 + m10)) / 2; + + _copysign(ref x, -m9 - -m6); + _copysign(ref y, -m2 - -m8); + _copysign(ref z, m4 - m1); + + return new Quaternion(x, y, z, w); + } + return Quaternion.identity; + } + + private static void _copysign(ref float sizeval, float signval) + { + if (signval > 0 != sizeval > 0) + sizeval = -sizeval; + } +#endif } [StructLayout(LayoutKind.Sequential)] public struct HmdMatrix33_t { @@ -5536,7 +5613,7 @@ public void Unpack(ref VRControllerState_t unpacked) public uint nHeight; public uint nBytesPerPixel; public uint nFrameSequence; - public TrackedDevicePose_t standingTrackedDevicePose; + public TrackedDevicePose_t trackedDevicePose; public ulong ulFrameExposureTime; } [StructLayout(LayoutKind.Sequential)] public struct Compositor_FrameTiming @@ -5606,6 +5683,20 @@ public void Unpack(ref VRControllerState_t unpacked) public uint m_nNumDroppedFramesTimedOut; public uint m_nNumReprojectedFramesTimedOut; } +[StructLayout(LayoutKind.Sequential)] public struct Compositor_StageRenderSettings +{ + public HmdColor_t m_PrimaryColor; + public HmdColor_t m_SecondaryColor; + public float m_flVignetteInnerRadius; + public float m_flVignetteOuterRadius; + public float m_flFresnelStrength; + [MarshalAs(UnmanagedType.I1)] + public bool m_bBackfaceCulling; + [MarshalAs(UnmanagedType.I1)] + public bool m_bGreyscale; + [MarshalAs(UnmanagedType.I1)] + public bool m_bWireframe; +} [StructLayout(LayoutKind.Sequential)] public struct VROverlayIntersectionParams_t { public HmdVector3_t vSource; @@ -6530,7 +6621,22 @@ public static bool IsRuntimeInstalled() public static string RuntimePath() { - return OpenVRInterop.RuntimePath(); + try + { + uint pathSize = 512; + uint requiredPathSize = 512; + System.Text.StringBuilder path = new System.Text.StringBuilder((int)pathSize); + bool success = OpenVRInterop.GetRuntimePath(path, pathSize, ref requiredPathSize); + if (success == false) + { + return null; + } + + return path.ToString(); + } catch + { + return OpenVRInterop.RuntimePath(); //this api is deprecated but here to support older unity versions + } } public static string GetStringForHmdError(EVRInitError error) @@ -6567,6 +6673,7 @@ public static uint GetInitToken() public const uint k_unUint64PropertyTag = 3; public const uint k_unBoolPropertyTag = 4; public const uint k_unStringPropertyTag = 5; + public const uint k_unErrorPropertyTag = 6; public const uint k_unHmdMatrix34PropertyTag = 20; public const uint k_unHmdMatrix44PropertyTag = 21; public const uint k_unHmdVector3PropertyTag = 22; @@ -6593,21 +6700,21 @@ public static uint GetInitToken() public const ulong k_ulOverlayHandleInvalid = 0; public const uint k_unMaxDistortionFunctionParameters = 8; public const uint k_unScreenshotHandleInvalid = 0; - public const string IVRSystem_Version = "IVRSystem_020"; + public const string IVRSystem_Version = "IVRSystem_021"; public const string IVRExtendedDisplay_Version = "IVRExtendedDisplay_001"; - public const string IVRTrackedCamera_Version = "IVRTrackedCamera_005"; + public const string IVRTrackedCamera_Version = "IVRTrackedCamera_006"; public const uint k_unMaxApplicationKeyLength = 128; public const string k_pch_MimeType_HomeApp = "vr/home"; public const string k_pch_MimeType_GameTheater = "vr/game_theater"; - public const string IVRApplications_Version = "IVRApplications_006"; + public const string IVRApplications_Version = "IVRApplications_007"; public const string IVRChaperone_Version = "IVRChaperone_003"; public const string IVRChaperoneSetup_Version = "IVRChaperoneSetup_006"; - public const string IVRCompositor_Version = "IVRCompositor_022"; + public const string IVRCompositor_Version = "IVRCompositor_024"; public const uint k_unVROverlayMaxKeyLength = 128; public const uint k_unVROverlayMaxNameLength = 128; - public const uint k_unMaxOverlayCount = 64; + public const uint k_unMaxOverlayCount = 128; public const uint k_unMaxOverlayIntersectionMaskPrimitivesCount = 32; - public const string IVROverlay_Version = "IVROverlay_019"; + public const string IVROverlay_Version = "IVROverlay_022"; public const string k_pch_Controller_Component_GDC2015 = "gdc2015"; public const string k_pch_Controller_Component_Base = "base"; public const string k_pch_Controller_Component_Tip = "tip"; @@ -6617,7 +6724,7 @@ public static uint GetInitToken() public const uint k_unNotificationTextMaxSize = 256; public const string IVRNotifications_Version = "IVRNotifications_002"; public const uint k_unMaxSettingsKeyLength = 128; - public const string IVRSettings_Version = "IVRSettings_002"; + public const string IVRSettings_Version = "IVRSettings_003"; public const string k_pch_SteamVR_Section = "steamvr"; public const string k_pch_SteamVR_RequireHmd_String = "requireHmd"; public const string k_pch_SteamVR_ForcedDriverKey_String = "forcedDriver"; @@ -6635,21 +6742,28 @@ public static uint GetInitToken() public const string k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius"; public const string k_pch_SteamVR_GridColor_String = "gridColor"; public const string k_pch_SteamVR_PlayAreaColor_String = "playAreaColor"; + public const string k_pch_SteamVR_TrackingLossColor_String = "trackingLossColor"; public const string k_pch_SteamVR_ShowStage_Bool = "showStage"; public const string k_pch_SteamVR_ActivateMultipleDrivers_Bool = "activateMultipleDrivers"; public const string k_pch_SteamVR_UsingSpeakers_Bool = "usingSpeakers"; public const string k_pch_SteamVR_SpeakersForwardYawOffsetDegrees_Float = "speakersForwardYawOffsetDegrees"; public const string k_pch_SteamVR_BaseStationPowerManagement_Int32 = "basestationPowerManagement"; + public const string k_pch_SteamVR_ShowBaseStationPowerManagementTip_Int32 = "ShowBaseStationPowerManagementTip"; public const string k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses"; public const string k_pch_SteamVR_SupersampleScale_Float = "supersampleScale"; public const string k_pch_SteamVR_MaxRecommendedResolution_Int32 = "maxRecommendedResolution"; public const string k_pch_SteamVR_MotionSmoothing_Bool = "motionSmoothing"; public const string k_pch_SteamVR_MotionSmoothingOverride_Int32 = "motionSmoothingOverride"; + public const string k_pch_SteamVR_DisableAsyncReprojection_Bool = "disableAsync"; public const string k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking"; public const string k_pch_SteamVR_DefaultMirrorView_Int32 = "mirrorView"; - public const string k_pch_SteamVR_ShowMirrorView_Bool = "showMirrorView"; + public const string k_pch_SteamVR_ShowLegacyMirrorView_Bool = "showLegacyMirrorView"; + public const string k_pch_SteamVR_MirrorViewVisibility_Bool = "showMirrorView"; + public const string k_pch_SteamVR_MirrorViewDisplayMode_Int32 = "mirrorViewDisplayMode"; + public const string k_pch_SteamVR_MirrorViewEye_Int32 = "mirrorViewEye"; public const string k_pch_SteamVR_MirrorViewGeometry_String = "mirrorViewGeometry"; public const string k_pch_SteamVR_MirrorViewGeometryMaximized_String = "mirrorViewGeometryMaximized"; + public const string k_pch_SteamVR_PerfGraphVisibility_Bool = "showPerfGraph"; public const string k_pch_SteamVR_StartMonitorFromAppLaunch = "startMonitorFromAppLaunch"; public const string k_pch_SteamVR_StartCompositorFromAppLaunch_Bool = "startCompositorFromAppLaunch"; public const string k_pch_SteamVR_StartDashboardFromAppLaunch_Bool = "startDashboardFromAppLaunch"; @@ -6664,7 +6778,6 @@ public static uint GetInitToken() public const string k_pch_SteamVR_AllowDisplayLockedMode_Bool = "allowDisplayLockedMode"; public const string k_pch_SteamVR_HaveStartedTutorialForNativeChaperoneDriver_Bool = "haveStartedTutorialForNativeChaperoneDriver"; public const string k_pch_SteamVR_ForceWindows32bitVRMonitor = "forceWindows32BitVRMonitor"; - public const string k_pch_SteamVR_DebugInput = "debugInput"; public const string k_pch_SteamVR_DebugInputBinding = "debugInputBinding"; public const string k_pch_SteamVR_DoNotFadeToGrid = "doNotFadeToGrid"; public const string k_pch_SteamVR_RenderCameraMode = "renderCameraMode"; @@ -6676,6 +6789,9 @@ public static uint GetInitToken() public const string k_pch_SteamVR_HmdDisplayColorGainR_Float = "hmdDisplayColorGainR"; public const string k_pch_SteamVR_HmdDisplayColorGainG_Float = "hmdDisplayColorGainG"; public const string k_pch_SteamVR_HmdDisplayColorGainB_Float = "hmdDisplayColorGainB"; + public const string k_pch_SteamVR_CustomIconStyle_String = "customIconStyle"; + public const string k_pch_SteamVR_CustomOffIconStyle_String = "customOffIconStyle"; + public const string k_pch_SteamVR_CustomIconForceUpdate_String = "customIconForceUpdate"; public const string k_pch_DirectMode_Section = "direct_mode"; public const string k_pch_DirectMode_Enable_Bool = "enable"; public const string k_pch_DirectMode_Count_Int32 = "count"; @@ -6693,7 +6809,6 @@ public static uint GetInitToken() public const string k_pch_Lighthouse_PowerManagedBaseStations2_String = "PowerManagedBaseStations2"; public const string k_pch_Lighthouse_InactivityTimeoutForBaseStations_Int32 = "InactivityTimeoutForBaseStations"; public const string k_pch_Lighthouse_EnableImuFallback_Bool = "enableImuFallback"; - public const string k_pch_Lighthouse_NewPairing_Bool = "newPairing"; public const string k_pch_Null_Section = "driver_null"; public const string k_pch_Null_SerialNumber_String = "serialNumber"; public const string k_pch_Null_ModelNumber_String = "modelNumber"; @@ -6737,6 +6852,7 @@ public static uint GetInitToken() public const string k_pch_CollisionBounds_ColorGammaG_Int32 = "CollisionBoundsColorGammaG"; public const string k_pch_CollisionBounds_ColorGammaB_Int32 = "CollisionBoundsColorGammaB"; public const string k_pch_CollisionBounds_ColorGammaA_Int32 = "CollisionBoundsColorGammaA"; + public const string k_pch_CollisionBounds_EnableDriverImport = "enableDriverBoundsImport"; public const string k_pch_Camera_Section = "camera"; public const string k_pch_Camera_EnableCamera_Bool = "enableCamera"; public const string k_pch_Camera_EnableCameraInDashboard_Bool = "enableCameraInDashboard"; @@ -6749,11 +6865,19 @@ public static uint GetInitToken() public const string k_pch_Camera_BoundsStrength_Int32 = "cameraBoundsStrength"; public const string k_pch_Camera_RoomViewMode_Int32 = "cameraRoomViewMode"; public const string k_pch_audio_Section = "audio"; - public const string k_pch_audio_OnPlaybackDevice_String = "onPlaybackDevice"; - public const string k_pch_audio_OnRecordDevice_String = "onRecordDevice"; - public const string k_pch_audio_OnPlaybackMirrorDevice_String = "onPlaybackMirrorDevice"; - public const string k_pch_audio_OffPlaybackDevice_String = "offPlaybackDevice"; - public const string k_pch_audio_OffRecordDevice_String = "offRecordDevice"; + public const string k_pch_audio_SetOsDefaultPlaybackDevice_Bool = "setOsDefaultPlaybackDevice"; + public const string k_pch_audio_EnablePlaybackDeviceOverride_Bool = "enablePlaybackDeviceOverride"; + public const string k_pch_audio_PlaybackDeviceOverride_String = "playbackDeviceOverride"; + public const string k_pch_audio_PlaybackDeviceOverrideName_String = "playbackDeviceOverrideName"; + public const string k_pch_audio_SetOsDefaultRecordingDevice_Bool = "setOsDefaultRecordingDevice"; + public const string k_pch_audio_EnableRecordingDeviceOverride_Bool = "enableRecordingDeviceOverride"; + public const string k_pch_audio_RecordingDeviceOverride_String = "recordingDeviceOverride"; + public const string k_pch_audio_RecordingDeviceOverrideName_String = "recordingDeviceOverrideName"; + public const string k_pch_audio_EnablePlaybackMirror_Bool = "enablePlaybackMirror"; + public const string k_pch_audio_PlaybackMirrorDevice_String = "playbackMirrorDevice"; + public const string k_pch_audio_PlaybackMirrorDeviceName_String = "playbackMirrorDeviceName"; + public const string k_pch_audio_OldPlaybackMirrorDevice_String = "onPlaybackMirrorDevice"; + public const string k_pch_audio_LastHmdPlaybackDeviceId_String = "lastHmdPlaybackDeviceId"; public const string k_pch_audio_VIVEHDMIGain = "viveHDMIGain"; public const string k_pch_Power_Section = "power"; public const string k_pch_Power_PowerOffOnExit_Bool = "powerOffOnExit"; @@ -6765,22 +6889,22 @@ public static uint GetInitToken() public const string k_pch_Dashboard_Section = "dashboard"; public const string k_pch_Dashboard_EnableDashboard_Bool = "enableDashboard"; public const string k_pch_Dashboard_ArcadeMode_Bool = "arcadeMode"; - public const string k_pch_Dashboard_UseWebDashboard = "useWebDashboard"; + public const string k_pch_Dashboard_UseWebKeyboard = "useWebKeyboard"; public const string k_pch_Dashboard_UseWebSettings = "useWebSettings"; - public const string k_pch_Dashboard_UseWebIPD = "useWebIPD"; - public const string k_pch_Dashboard_UseWebPowerMenu = "useWebPowerMenu"; + public const string k_pch_Dashboard_Position = "position"; + public const string k_pch_Dashboard_DesktopScale = "desktopScale"; + public const string k_pch_Dashboard_DashboardScale = "dashboardScale"; public const string k_pch_modelskin_Section = "modelskins"; public const string k_pch_Driver_Enable_Bool = "enable"; public const string k_pch_Driver_LoadPriority_Int32 = "loadPriority"; public const string k_pch_WebInterface_Section = "WebInterface"; - public const string k_pch_WebInterface_WebEnable_Bool = "WebEnable"; - public const string k_pch_WebInterface_WebPort_String = "WebPort"; public const string k_pch_VRWebHelper_Section = "VRWebHelper"; public const string k_pch_VRWebHelper_DebuggerEnabled_Bool = "DebuggerEnabled"; public const string k_pch_VRWebHelper_DebuggerPort_Int32 = "DebuggerPort"; public const string k_pch_TrackingOverride_Section = "TrackingOverrides"; public const string k_pch_App_BindingAutosaveURLSuffix_String = "AutosaveURL"; public const string k_pch_App_BindingCurrentURLSuffix_String = "CurrentURL"; + public const string k_pch_App_BindingPreviousURLSuffix_String = "PreviousURL"; public const string k_pch_App_NeedToUpdateAutosaveSuffix_Bool = "NeedToUpdateAutosave"; public const string k_pch_Trackers_Section = "trackers"; public const string k_pch_DesktopUI_Section = "DesktopUI"; @@ -6792,6 +6916,7 @@ public static uint GetInitToken() public const string k_pch_Input_LeftThumbstickRotation_Float = "leftThumbstickRotation"; public const string k_pch_Input_RightThumbstickRotation_Float = "rightThumbstickRotation"; public const string k_pch_Input_ThumbstickDeadzone_Float = "thumbstickDeadzone"; + public const string k_pch_GpuSpeed_Section = "GpuSpeed"; public const string IVRScreenshots_Version = "IVRScreenshots_001"; public const string IVRResources_Version = "IVRResources_001"; public const string IVRDriverManager_Version = "IVRDriverManager_001"; From 11f3f17f0ba43f3ea1f0b45947998534b379f2d2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 1 Feb 2020 21:25:19 -0500 Subject: [PATCH 0698/2038] VR: Easy swapping hands option --- sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs index 66de877aa7..446910625c 100644 --- a/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs +++ b/sources/engine/Xenko.VirtualReality/VRDeviceSystem.cs @@ -27,6 +27,11 @@ public static bool VRActive } } + /// + /// Swap hands at a low level? Easy way to have right hand act like the left hand and vice versa. + /// + public bool GetControllerSwapped; + /// /// Which VR button to activate UI? Defaults to trigger. /// @@ -39,12 +44,14 @@ public static bool VRActive /// TouchController object, otherwise null public TouchController GetController(TouchControllerHand hand) { + if (Device == null) return null; + switch(hand) { case TouchControllerHand.Left: - return Device?.LeftHand; + return GetControllerSwapped ? Device.RightHand : Device.LeftHand; case TouchControllerHand.Right: - return Device?.RightHand; + return GetControllerSwapped ? Device.LeftHand : Device.RightHand; default: return null; } From 9806823d6ad265b2c557dde22eac4d9249dcec83 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 2 Feb 2020 11:03:58 -0500 Subject: [PATCH 0699/2038] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 13d8bf7671..cbf1399f5b 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * CinematicAction: Simple system for performing cinematic actions on objects and calling functions at certain times. Can build a simple timeline for things to move, rotate and execute. See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Cinematics/CinematicAnimation.cs * EntityPool: Makes it really easy to reuse entities and prefabs. This can save lots of memory and processing, instead of recreating things that come and go (like enemies or projectiles). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/EntityPool.cs * UI improvements: View frustum is implemented in this fork, so UI elements outside of view won't be drawn for performance reasons. ScrollViewers can work with mouse wheels out of the box. Easily get UI elements to access in code from a Page using GatherUIDictionary. Easily make Lists and Pulldown selection boxes using GridList and PulldownList (not integrated with GameStudio yet, though). +* Particle System improvements: Colored particles work, which is pretty important! Also added EmitSpecificParticle to a ParticleEmitter, so you can emit individual particles at certain position, speeds and colors (like using EmitParams in Unity). * Better UI Editor: Selecting things in the editor works more intuitively, like hidden things are skipped and smaller things are easier to click. * UI Text features: vertically align text or use \ tags to dynamically change text colors. Use \
tags to have multiline text set straight from GameStudio. Need text shadows, outlines or bevels? Precompile a font (right click it in the asset view) that has a Glyph Margin > 0, which will generate a PNG with room to edit in effects right into the glyphs. * ModelBatcher: Easily make batched models using lots of individual models (think grass and rocks for your whole terrain batched into one draw call and entity). See https://github.com/phr00t/FocusEngine/blob/master/sources/engine/Xenko.Engine/Engine/ModelBatcher.cs From 22bb0c07ef853624570df6b3f06989ef93df0464 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 3 Feb 2020 15:33:12 -0500 Subject: [PATCH 0700/2038] VR: more sane axis switch statement --- .../engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index 5bb08aee89..2d82f535b0 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -137,14 +137,13 @@ public Controller(int controllerIndex) public Vector2 GetAxis(ButtonId buttonId = ButtonId.ButtonSteamVrTouchpad) { - var axisId = (uint)buttonId - (uint)EVRButtonId.k_EButton_Axis0; - switch (axisId) + switch (buttonId) { - case 0: return new Vector2(State.rAxis0.x, State.rAxis0.y); - case 1: return new Vector2(State.rAxis1.x, State.rAxis1.y); - case 2: return new Vector2(State.rAxis2.x, State.rAxis2.y); - case 3: return new Vector2(State.rAxis3.x, State.rAxis3.y); - case 4: return new Vector2(State.rAxis4.x, State.rAxis4.y); + case ButtonId.ButtonAxis0: return new Vector2(State.rAxis0.x, State.rAxis0.y); // also touchpad + case ButtonId.ButtonAxis1: return new Vector2(State.rAxis1.x, State.rAxis1.y); // also trigger + case ButtonId.ButtonAxis2: return new Vector2(State.rAxis2.x, State.rAxis2.y); + case ButtonId.ButtonAxis3: return new Vector2(State.rAxis3.x, State.rAxis3.y); // index joystick + case ButtonId.ButtonAxis4: return new Vector2(State.rAxis4.x, State.rAxis4.y); } return Vector2.Zero; } From a66ad033961cfe5ad24acb739c8235aa38c86379 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 3 Feb 2020 21:45:41 -0500 Subject: [PATCH 0701/2038] VR: Remove unsupported / unused VR plugins --- .../engine/Xenko.VirtualReality/Fove/Fove.cpp | 194 ------ .../engine/Xenko.VirtualReality/Fove/Fove.cs | 64 -- .../Xenko.VirtualReality/Fove/FoveHmd.cs | 147 ----- .../GoogleVR/GoogleVR.cpp | 487 -------------- .../Xenko.VirtualReality/GoogleVR/GoogleVR.cs | 145 ----- .../GoogleVR/GoogleVrHmd.cs | 140 ----- .../OculusOVR/OculusOVR.cpp | 592 ------------------ .../OculusOVR/OculusOVR.cs | 230 ------- .../OculusOVR/OculusOverlay.cs | 56 -- .../OculusOVR/OculusOvrHmd.cs | 225 ------- .../OculusOVR/OculusTouchController.cs | 409 ------------ .../SystemNumericsExtensions.cs | 50 -- .../WindowsMixedRealityHmd.cs | 201 ------ .../WindowsMixedRealityTouchController.cs | 162 ----- .../Xenko.VirtualReality.csproj | 5 - 15 files changed, 3107 deletions(-) delete mode 100644 sources/engine/Xenko.VirtualReality/Fove/Fove.cpp delete mode 100644 sources/engine/Xenko.VirtualReality/Fove/Fove.cs delete mode 100644 sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs delete mode 100644 sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cpp delete mode 100644 sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cs delete mode 100644 sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVrHmd.cs delete mode 100644 sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cpp delete mode 100644 sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cs delete mode 100644 sources/engine/Xenko.VirtualReality/OculusOVR/OculusOverlay.cs delete mode 100644 sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs delete mode 100644 sources/engine/Xenko.VirtualReality/OculusOVR/OculusTouchController.cs delete mode 100644 sources/engine/Xenko.VirtualReality/WindowsMixedReality/SystemNumericsExtensions.cs delete mode 100644 sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityHmd.cs delete mode 100644 sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityTouchController.cs diff --git a/sources/engine/Xenko.VirtualReality/Fove/Fove.cpp b/sources/engine/Xenko.VirtualReality/Fove/Fove.cpp deleted file mode 100644 index 95cfed200f..0000000000 --- a/sources/engine/Xenko.VirtualReality/Fove/Fove.cpp +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#include "../../../deps/NativePath/NativePath.h" -#include "../../Xenko.Native/XenkoNative.h" - -#if defined(WINDOWS_DESKTOP) || !defined(__clang__) - -#include "../../../deps/NativePath/NativeDynamicLinking.h" -#include "../../../../deps/Fove/IFVRCompositor.h" -#include "../../../../deps/Fove/IFVRHeadset.h" - -extern "C" -{ - void* __libFove = NULL; - - static bool sFoveInitialized = false; - - static Fove::IFVRHeadset* sHeadSet = NULL; - static Fove::IFVRCompositor* sCompositor = NULL; - - typedef Fove::IFVRHeadset* (*GetFVRHeadsetPtr)(); - typedef Fove::IFVRCompositor* (*CGetFVRCompositorPtr)(); - - DLL_EXPORT_API npBool xnFoveStartup() - { - if (!__libFove) - { - __libFove = LoadDynamicLibrary("FoveClient"); - if (!__libFove) __libFove = LoadDynamicLibrary("x86\\FoveClient"); - if (!__libFove) __libFove = LoadDynamicLibrary("x64\\FoveClient"); - if (!__libFove) __libFove = LoadDynamicLibrary("x64/FoveClient"); - if (!__libFove) __libFove = LoadDynamicLibrary("x64/FoveClient"); - if (!__libFove) - { - return false; - } - - GetFVRHeadsetPtr get_fvr_headset_ptr = (GetFVRHeadsetPtr)GetSymbolAddress(__libFove, "CGetFVRHeadset"); - if (!get_fvr_headset_ptr) return false; - sHeadSet = get_fvr_headset_ptr(); - - CGetFVRCompositorPtr get_fvr_compositor_ptr = (CGetFVRCompositorPtr)GetSymbolAddress(__libFove, "CGetFVRCompositor"); - if (!get_fvr_compositor_ptr) return false; - sCompositor = get_fvr_compositor_ptr(); - } - - if(sHeadSet && !sFoveInitialized) - { - sFoveInitialized = sHeadSet->Initialise(); - } - - return sFoveInitialized; - } - - DLL_EXPORT_API void xnFoveShutdown() - { - if (sCompositor) sCompositor->Shutdown(); - if (sHeadSet) sHeadSet->Destroy(); - if(__libFove) - { - FreeDynamicLibrary(__libFove); - __libFove = NULL; - } - } - - DLL_EXPORT_API npBool xnFoveSubmit(void* texture, float* bounds, int eyeIndex) - { - if (!sCompositor) return false; - - Fove::SFVR_TextureBounds fbounds; - fbounds.left = bounds[0]; - fbounds.bottom = bounds[1]; - fbounds.right = bounds[2]; - fbounds.top = bounds[3]; - - return sCompositor->Submit(texture, - Fove::EFVR_GraphicsAPI::DirectX, - eyeIndex == 0 ? Fove::EFVR_Eye::Left : Fove::EFVR_Eye::Right, - fbounds) - == Fove::EFVR_CompositorError::None; - } - - DLL_EXPORT_API void xnFoveCommit() - { - if (sCompositor) - { - sCompositor->WaitForRenderPose(); - //sCompositor->SignalFrameComplete(); - } - } - - DLL_EXPORT_API npBool xnFoveGetLeftEyePoint(float* point) - { - if(sHeadSet) - { - auto eyePoint = sHeadSet->GetGazePoint(); - point[0] = eyePoint.coord.x; - point[1] = eyePoint.coord.y; - - return eyePoint.error == Fove::EFVR_ErrorCode::None; - } - - return false; - } - -#pragma pack(push, 4) - struct xnOvrFrameProperties - { - //Camera properties - float Near; - float Far; - float ProjLeft[16]; - float ProjRight[16]; - float Pos[3]; - float Rot[4]; - }; -#pragma pack(pop) - - DLL_EXPORT_API void xnFovePrepareRender(xnOvrFrameProperties* properties) - { - auto matrixL = sHeadSet->GetProjectionMatrixRH(Fove::EFVR_Eye::Left, properties->Near, properties->Far); - auto matrixR = sHeadSet->GetProjectionMatrixRH(Fove::EFVR_Eye::Right, properties->Near, properties->Far); - memcpy(properties->ProjLeft, &matrixL, sizeof(float) * 16); - memcpy(properties->ProjRight, &matrixR, sizeof(float) * 16); - - auto pose = sHeadSet->GetHMDPose(); - memcpy(properties->Pos, &pose.position, sizeof(float) * 3); - memcpy(properties->Rot, &pose.orientation, sizeof(float) * 4); - properties->Pos[2] = -properties->Pos[2]; //flip Z - } - - DLL_EXPORT_API void xnFoveRecenter() - { - if(sHeadSet) - { - sHeadSet->TareOrientationSensor(); - sHeadSet->TarePositionSensors(); - } - } - - DLL_EXPORT_API npBool xnFoveIsHardwareReady() - { - if(sHeadSet) - { - return sHeadSet->IsHardwareConnected() && sHeadSet->IsHardwareReady(); - } - - return false; - } -} - -#else - -extern "C" -{ - DLL_EXPORT_API npBool xnFoveStartup() - { - return false; - } - - DLL_EXPORT_API void xnFoveShutdown() - { - } - - DLL_EXPORT_API npBool xnFoveSubmit(void* texture, float* bounds, int eyeIndex) - { - return false; - } - - DLL_EXPORT_API void xnFoveCommit() - { - } - - DLL_EXPORT_API void xnFovePrepareRender(void* properties) - { - } - - DLL_EXPORT_API npBool xnFoveGetLeftEyePoint(float* point) - { - return false; - } - - DLL_EXPORT_API void xnFoveRecenter() - { - } - - DLL_EXPORT_API bool xnFoveIsHardwareReady() - { - return false; - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/Fove/Fove.cs b/sources/engine/Xenko.VirtualReality/Fove/Fove.cs deleted file mode 100644 index e1b5eda02f..0000000000 --- a/sources/engine/Xenko.VirtualReality/Fove/Fove.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security; -using Xenko.Core; -using Xenko.Core.Mathematics; - -namespace Xenko.VirtualReality -{ - public static class Fove - { - static Fove() - { -#if XENKO_PLATFORM_WINDOWS - NativeLibrary.PreloadLibrary(NativeInvoke.Library + ".dll", typeof(Fove)); -#endif - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveStartup", CallingConvention = CallingConvention.Cdecl)] - public static extern bool Startup(); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveShutdown", CallingConvention = CallingConvention.Cdecl)] - public static extern void Shutdown(); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveSubmit", CallingConvention = CallingConvention.Cdecl)] - public static extern bool Submit(IntPtr texture, ref Vector4 bounds, int eyeIndex); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveCommit", CallingConvention = CallingConvention.Cdecl)] - public static extern void Commit(); - - [StructLayout(LayoutKind.Sequential, Pack = 4)] - public struct FrameProperties - { - public float Near; - public float Far; - public Matrix ProjLeft; - public Matrix ProjRight; - public Vector3 Pos; - public Quaternion Rot; - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFovePrepareRender", CallingConvention = CallingConvention.Cdecl)] - public static extern void PrepareRender(ref FrameProperties properties); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveGetLeftEyePoint", CallingConvention = CallingConvention.Cdecl)] - public static extern bool GetLeftEyePoint(ref Vector2 point); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveRecenter", CallingConvention = CallingConvention.Cdecl)] - public static extern void Recenter(); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnFoveIsHardwareReady", CallingConvention = CallingConvention.Cdecl)] - public static extern bool IsHardwareReady(); - } -} diff --git a/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs b/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs deleted file mode 100644 index b0feff855a..0000000000 --- a/sources/engine/Xenko.VirtualReality/Fove/FoveHmd.cs +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 - -using Xenko.Core; -using Xenko.Core.Mathematics; -using Xenko.Games; -using Xenko.Graphics; - -//TODO - -namespace Xenko.VirtualReality -{ - internal class FoveHmd : VRDevice - { - //private Texture nonSrgbFrame; - private readonly Matrix referenceMatrix = Matrix.RotationZ(MathUtil.Pi); - private Matrix referenceMatrixInv; - - private const float HalfIpd = 0.06f; - private const float EyeHeight = 0.08f; - private const float EyeForward = -0.04f; - - public override ulong PoseCount => 0; - - internal FoveHmd() - { - referenceMatrixInv = Matrix.RotationZ(MathUtil.Pi); - referenceMatrixInv.Invert(); - } - - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror) - { -// RenderFrame = Texture.New2D(device, RenderFrameSize.Width, RenderFrameSize.Height, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource); -// nonSrgbFrame = Texture.New2D(device, RenderFrameSize.Width, RenderFrameSize.Height, PixelFormat.R8G8B8A8_UNorm, TextureFlags.RenderTarget | TextureFlags.ShaderResource); -// if (requireMirror) -// { -// MirrorTexture = RenderFrame; //assign the surface we submit as mirror if needed -// } - -// var compositor = (SceneGraphicsCompositorLayers)Game.SceneSystem.SceneInstance.RootScene.Settings.GraphicsCompositor; -// compositor.Master.Add(new SceneDelegateRenderer((x, y) => -// { -// x.CommandList.Copy(RenderFrameProvider.RenderFrame.RenderTargets[0], nonSrgbFrame); -// //send to hmd -// var bounds0 = new Vector4(0.0f, 1.0f, 0.5f, 0.0f); -// var bounds1 = new Vector4(0.5f, 1.0f, 1.0f, 0.0f); -// if (!Fove.Submit(nonSrgbFrame.NativeResource.NativePointer, ref bounds0, 0) || -// !Fove.Submit(nonSrgbFrame.NativeResource.NativePointer, ref bounds1, 1)) -// { -// //failed... -// } -// -// Fove.Commit(); -// })); - } - - public override void ReadEyeParameters(Eyes eye, float near, float far, ref Vector3 cameraPosition, ref Matrix cameraRotation, bool ignoreHeadRotation, bool ignoreHeadPosition, out Matrix view, out Matrix projection) - { - throw new System.NotImplementedException(); - } - - public override void Commit(CommandList commandList, Texture renderFrame) - { - throw new System.NotImplementedException(); - } - - public override void Update(GameTime gameTime) - { - throw new System.NotImplementedException(); - } - - public override void Draw(GameTime gameTime) - { - throw new System.NotImplementedException(); - } - -// public override void Draw(GameTime gameTime) -// { -// var properties = new Fove.FrameProperties -// { -// Near = LeftCameraComponent.NearClipPlane, -// Far = LeftCameraComponent.FarClipPlane -// }; -// Fove.PrepareRender(ref properties); -// -// properties.ProjLeft.Transpose(); -// properties.ProjRight.Transpose(); -// -// Vector3 scale, camPos; -// Quaternion camRot; -// -// //have to make sure it's updated now -// CameraRootEntity.Transform.UpdateWorldMatrix(); -// CameraRootEntity.Transform.WorldMatrix.Decompose(out scale, out camRot, out camPos); -// -// LeftCameraComponent.ProjectionMatrix = properties.ProjLeft; -// -// var pos = camPos + (new Vector3(-HalfIpd * 0.5f, EyeHeight, EyeForward) * ViewScaling); -// var posV = pos + Vector3.Transform(properties.Pos * ViewScaling, camRot); -// var rotV = referenceMatrix * Matrix.RotationQuaternion(properties.Rot) * referenceMatrixInv * Matrix.Scaling(ViewScaling) * Matrix.RotationQuaternion(camRot); -// var finalUp = Vector3.TransformCoordinate(new Vector3(0, 1, 0), rotV); -// var finalForward = Vector3.TransformCoordinate(new Vector3(0, 0, -1), rotV); -// var view = Matrix.LookAtRH(posV, posV + finalForward, finalUp); -// LeftCameraComponent.ViewMatrix = view; -// -// RightCameraComponent.ProjectionMatrix = properties.ProjRight; -// -// pos = camPos + (new Vector3(HalfIpd * 0.5f, EyeHeight, EyeForward) * ViewScaling); -// posV = pos + Vector3.Transform(properties.Pos * ViewScaling, camRot); -// rotV = referenceMatrix * Matrix.RotationQuaternion(properties.Rot) * referenceMatrixInv * Matrix.Scaling(ViewScaling) * Matrix.RotationQuaternion(camRot); -// finalUp = Vector3.TransformCoordinate(new Vector3(0, 1, 0), rotV); -// finalForward = Vector3.TransformCoordinate(new Vector3(0, 0, -1), rotV); -// view = Matrix.LookAtRH(posV, posV + finalForward, finalUp); -// RightCameraComponent.ViewMatrix = view; -// -// base.Draw(gameTime); -// } - - public override Size2 OptimalRenderFrameSize => new Size2(2560, 1440); - public override Size2 ActualRenderFrameSize { get; protected set; } - - public override Texture MirrorTexture { get; protected set; } - - public override float RenderFrameScaling { get; set; } = 1.2f; - - public override DeviceState State => DeviceState.Valid; - - public override Vector3 HeadPosition { get; } - - public override Quaternion HeadRotation { get; } - - public override Vector3 HeadLinearVelocity { get; } - - public override Vector3 HeadAngularVelocity { get; } - - public override TouchController LeftHand => null; - - public override TouchController RightHand => null; - - public override TrackedItem[] TrackedItems => new TrackedItem[0]; - - public override bool CanInitialize => Fove.Startup() && Fove.IsHardwareReady(); - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cpp b/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cpp deleted file mode 100644 index a84305fbe8..0000000000 --- a/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cpp +++ /dev/null @@ -1,487 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if defined(DONT_BUILD_FOR_NOW) && (defined(ANDROID) || defined(IOS)) || !defined(__clang__) - -#if !defined(__clang__) -#define size_t unsigned long //shutup a error on resharper -#endif - -#if defined(IOS) -#define NP_STATIC_LINKING -#endif - -#include "../../../common/core/Xenko.Core.Native/CoreNative.h" -#include "../../../deps/NativePath/NativeDynamicLinking.h" -#include "../../../deps/NativePath/NativePath.h" - -#define GVR_NO_CPP_WRAPPER -#include "../../../../deps/GoogleVR/vr/gvr/capi/include/gvr_types.h" -#include "../../../../deps/GoogleVR/vr/gvr/capi/include/gvr.h" - -extern "C" { - void* gGvrLibrary = NULL; - void* gGvrGLESv2 = NULL; - gvr_context* gGvrContext = NULL; - -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_BLEND 0x0BE2 -#define GL_CULL_FACE 0x0B44 -#define GL_DEPTH_TEST 0x0B71 -#define GL_BLEND_EQUATION_RGB 0x8009 -#define GL_BLEND_EQUATION_ALPHA 0x883D -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_VIEWPORT 0x0BA2 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A -#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645 -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 - -#define M_PI 3.14159265358979323846 - - typedef unsigned char GLboolean; - typedef unsigned int GLenum; - typedef unsigned int GLuint; - typedef int GLint; - typedef int GLsizei; - typedef void GLvoid; - - NP_IMPORT(void, glColorMask, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); - NP_IMPORT(void, glDisable, GLenum cap); - NP_IMPORT(void, glEnable, GLenum cap); - NP_IMPORT(void, glGetBooleanv, GLenum pname, GLboolean* data); - NP_IMPORT(void, glGetIntegerv, GLenum pname, GLint* data); - NP_IMPORT(void, glBlendEquationSeparate, GLenum modeRGB, GLenum modeAlpha); - NP_IMPORT(void, glBlendFuncSeparate, GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); - NP_IMPORT(void, glViewport, GLint x, GLint y, GLsizei width, GLsizei height); - NP_IMPORT(void, glDisableVertexAttribArray, GLuint index); - NP_IMPORT(void, glGetVertexAttribiv, GLuint index, GLenum pname, GLint *params); - NP_IMPORT(void, glVertexAttribPointer, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); - NP_IMPORT(void, glGetVertexAttribPointerv, GLuint index, GLenum pname, GLvoid** pointer); - NP_IMPORT(void, glBindBuffer, GLenum target, GLuint buffer); - - NP_IMPORT(void, gvr_initialize_gl, gvr_context* gvr); - NP_IMPORT(int32_t, gvr_clear_error, gvr_context* gvr); - NP_IMPORT(int32_t, gvr_get_error, gvr_context* gvr); - NP_IMPORT(gvr_buffer_viewport_list*, gvr_buffer_viewport_list_create, const gvr_context* gvr); - NP_IMPORT(void, gvr_get_recommended_buffer_viewports, const gvr_context* gvr, gvr_buffer_viewport_list* viewport_list); - NP_IMPORT(void, gvr_buffer_viewport_list_get_item, const gvr_buffer_viewport_list* viewport_list, size_t index, gvr_buffer_viewport* viewport); - NP_IMPORT(gvr_buffer_viewport*, gvr_buffer_viewport_create, gvr_context* gvr); - NP_IMPORT(gvr_sizei, gvr_get_maximum_effective_render_target_size, const gvr_context* gvr); - NP_IMPORT(gvr_buffer_spec*, gvr_buffer_spec_create, gvr_context* gvr); - NP_IMPORT(void, gvr_buffer_spec_destroy, gvr_buffer_spec** spec); - NP_IMPORT(void, gvr_buffer_spec_set_size, gvr_buffer_spec* spec, gvr_sizei size); - NP_IMPORT(void, gvr_buffer_spec_set_samples, gvr_buffer_spec* spec, int32_t num_samples); - NP_IMPORT(gvr_frame*, gvr_swap_chain_acquire_frame, gvr_swap_chain* swap_chain); - NP_IMPORT(int32_t, gvr_frame_get_framebuffer_object, const gvr_frame* frame, int32_t index); - NP_IMPORT(void, gvr_swap_chain_resize_buffer, gvr_swap_chain* swap_chain, int32_t index, gvr_sizei size); - NP_IMPORT(void, gvr_frame_submit, gvr_frame** frame, const gvr_buffer_viewport_list* list, gvr_mat4f head_space_from_start_space); - NP_IMPORT(gvr_mat4f, gvr_get_head_space_from_start_space_rotation ,const gvr_context* gvr, const gvr_clock_time_point time); - NP_IMPORT(gvr_clock_time_point, gvr_get_time_point_now); - NP_IMPORT(gvr_rectf, gvr_buffer_viewport_get_source_uv, const gvr_buffer_viewport* viewport); - NP_IMPORT(void, gvr_refresh_viewer_profile, gvr_context* gvr); - NP_IMPORT(void, gvr_frame_bind_buffer, gvr_frame* frame, int32_t index); - NP_IMPORT(void, gvr_frame_unbind, gvr_frame* frame); - NP_IMPORT(gvr_context*, gvr_create); - NP_IMPORT(void, gvr_set_surface_size, gvr_context* gvr, gvr_sizei surface_size_pixels); - NP_IMPORT(void, gvr_buffer_spec_set_color_format, gvr_buffer_spec* spec, int32_t color_format); - NP_IMPORT(void, gvr_buffer_spec_set_depth_stencil_format, gvr_buffer_spec* spec, int32_t depth_stencil_format); - NP_IMPORT(gvr_swap_chain*, gvr_swap_chain_create, gvr_context* gvr, const gvr_buffer_spec** buffers, int32_t count); - NP_IMPORT(gvr_mat4f, gvr_get_eye_from_head_matrix, const gvr_context* gvr, const int32_t eye); - NP_IMPORT(gvr_rectf, gvr_buffer_viewport_get_source_fov, const gvr_buffer_viewport* viewport); - - gvr_buffer_viewport_list* xnGvr_ViewportsList = NULL; - gvr_buffer_viewport* xnGvr_LeftVieport = NULL; - gvr_buffer_viewport* xnGvr_RightVieport = NULL; - - gvr_swap_chain* xnGvr_swap_chain = NULL; - - gvr_sizei xnGvr_size; - - uint64_t kPredictionTimeWithoutVsyncNanos = 50000000; - - int xnGvrStartup(gvr_context* context) - { - //cnDebugPrintLine("xnGvrStartup"); - - if (!gGvrLibrary) - { -#if defined(ANDROID) - gGvrLibrary = LoadDynamicLibrary("libgvr"); - gGvrGLESv2 = LoadDynamicLibrary("libGLESv2"); - auto core = LoadDynamicLibrary("libcore"); - cnDebugPrintLine = (CnPrintDebugFunc)GetSymbolAddress(core, "cnDebugPrintLine"); -#else - gGvrLibrary = LoadDynamicLibrary(NULL); - gGvrGLESv2 = LoadDynamicLibrary(NULL); -#endif - - if (!gGvrLibrary) return 1; - - NP_LOAD(gGvrGLESv2, glColorMask); - NP_CHECK(glColorMask, return false); - NP_LOAD(gGvrGLESv2, glDisable); - NP_CHECK(glDisable, return false); - NP_LOAD(gGvrGLESv2, glEnable); - NP_CHECK(glEnable, return false); - NP_LOAD(gGvrGLESv2, glGetBooleanv); - NP_CHECK(glGetBooleanv, return false); - NP_LOAD(gGvrGLESv2, glGetIntegerv); - NP_CHECK(glGetIntegerv, return false); - NP_LOAD(gGvrGLESv2, glBlendEquationSeparate); - NP_CHECK(glBlendEquationSeparate, return false); - NP_LOAD(gGvrGLESv2, glBlendFuncSeparate); - NP_CHECK(glBlendFuncSeparate, return false); - NP_LOAD(gGvrGLESv2, glViewport); - NP_CHECK(glViewport, return false); - NP_LOAD(gGvrGLESv2, glDisableVertexAttribArray); - NP_CHECK(glDisableVertexAttribArray, return false); - NP_LOAD(gGvrGLESv2, glGetVertexAttribiv); - NP_CHECK(glGetVertexAttribiv, return false); - NP_LOAD(gGvrGLESv2, glVertexAttribPointer); - NP_CHECK(glVertexAttribPointer, return false); - NP_LOAD(gGvrGLESv2, glGetVertexAttribPointerv); - NP_CHECK(glGetVertexAttribPointerv, return false); - NP_LOAD(gGvrGLESv2, glBindBuffer); - NP_CHECK(glBindBuffer, return false); - - NP_LOAD(gGvrLibrary, gvr_refresh_viewer_profile); - NP_CHECK(gvr_refresh_viewer_profile, return 2); - } - - if(context) - { - gGvrContext = context; - } - else - { - NP_LOAD(gGvrLibrary, gvr_create); - NP_CHECK(gvr_create, return 3); - gGvrContext = NP_CALL(gvr_create); - - if (gGvrContext == NULL) return 4; - } - - NP_LOAD(gGvrLibrary, gvr_get_maximum_effective_render_target_size); - NP_CHECK(gvr_get_maximum_effective_render_target_size, return 5); - - NP_CALL(gvr_refresh_viewer_profile, gGvrContext); - - NP_LOAD(gGvrLibrary, gvr_set_surface_size); - NP_CHECK(gvr_set_surface_size, return 6); - - return 0; - } - - void xnGvrGetMaxRenderSize(int* outWidth, int* outHeight) - { - auto maxSize = NP_CALL(gvr_get_maximum_effective_render_target_size, gGvrContext); - *outHeight = maxSize.height; - *outWidth = maxSize.width; - } - - npBool xnGvrInit(int width, int height) - { - xnGvr_size.width = width; - xnGvr_size.height = height; - - NP_CALL(gvr_set_surface_size, gGvrContext, xnGvr_size); - - NP_LOAD(gGvrLibrary, gvr_initialize_gl); - NP_CHECK(gvr_initialize_gl, return false); - NP_LOAD(gGvrLibrary, gvr_clear_error); - NP_CHECK(gvr_clear_error, return false); - NP_LOAD(gGvrLibrary, gvr_get_error); - NP_CHECK(gvr_get_error, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_viewport_list_create); - NP_CHECK(gvr_buffer_viewport_list_create, return false); - NP_LOAD(gGvrLibrary, gvr_get_recommended_buffer_viewports); - NP_CHECK(gvr_get_recommended_buffer_viewports, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_viewport_list_get_item); - NP_CHECK(gvr_buffer_viewport_list_get_item, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_viewport_create); - NP_CHECK(gvr_buffer_viewport_create, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_spec_create); - NP_CHECK(gvr_buffer_spec_create, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_spec_destroy); - NP_CHECK(gvr_buffer_spec_destroy, return false); - NP_LOAD(gGvrLibrary, gvr_swap_chain_acquire_frame); - NP_CHECK(gvr_swap_chain_acquire_frame, return false); - NP_LOAD(gGvrLibrary, gvr_frame_get_framebuffer_object); - NP_CHECK(gvr_frame_get_framebuffer_object, return false); - NP_LOAD(gGvrLibrary, gvr_swap_chain_resize_buffer); - NP_CHECK(gvr_swap_chain_resize_buffer, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_spec_set_color_format); - NP_CHECK(gvr_buffer_spec_set_color_format, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_spec_set_depth_stencil_format); - NP_CHECK(gvr_buffer_spec_set_depth_stencil_format, return false); - NP_LOAD(gGvrLibrary, gvr_swap_chain_create); - NP_CHECK(gvr_swap_chain_create, return false); - NP_LOAD(gGvrLibrary, gvr_frame_submit); - NP_CHECK(gvr_frame_submit, return false); - NP_LOAD(gGvrLibrary, gvr_get_head_space_from_start_space_rotation); - NP_CHECK(gvr_get_head_space_from_start_space_rotation, return false); - NP_LOAD(gGvrLibrary, gvr_get_time_point_now); - NP_CHECK(gvr_get_time_point_now, return false); - NP_LOAD(gGvrLibrary, gvr_frame_bind_buffer); - NP_CHECK(gvr_frame_bind_buffer, return false); - NP_LOAD(gGvrLibrary, gvr_frame_unbind); - NP_CHECK(gvr_frame_unbind, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_viewport_get_source_uv); - NP_CHECK(gvr_buffer_viewport_get_source_uv, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_spec_set_size); - NP_CHECK(gvr_buffer_spec_set_size, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_spec_set_samples); - NP_CHECK(gvr_buffer_spec_set_samples, return false); - NP_LOAD(gGvrLibrary, gvr_get_eye_from_head_matrix); - NP_CHECK(gvr_get_eye_from_head_matrix, return false); - NP_LOAD(gGvrLibrary, gvr_buffer_viewport_get_source_fov); - NP_CHECK(gvr_buffer_viewport_get_source_fov, return false); - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_initialize_gl, gGvrContext); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - xnGvr_ViewportsList = NP_CALL(gvr_buffer_viewport_list_create, gGvrContext); - NP_CALL(gvr_get_recommended_buffer_viewports, gGvrContext, xnGvr_ViewportsList); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - xnGvr_LeftVieport = NP_CALL(gvr_buffer_viewport_create, gGvrContext); - xnGvr_RightVieport = NP_CALL(gvr_buffer_viewport_create, gGvrContext); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_buffer_viewport_list_get_item, xnGvr_ViewportsList, 0, xnGvr_LeftVieport); - NP_CALL(gvr_buffer_viewport_list_get_item, xnGvr_ViewportsList, 1, xnGvr_RightVieport); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - auto bufferSpec = NP_CALL(gvr_buffer_spec_create, gGvrContext); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_buffer_spec_set_size, bufferSpec, xnGvr_size); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_buffer_spec_set_samples, bufferSpec, 1); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_buffer_spec_set_color_format, bufferSpec, GVR_COLOR_FORMAT_RGBA_8888); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_buffer_spec_set_depth_stencil_format, bufferSpec, GVR_DEPTH_STENCIL_FORMAT_NONE); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE) return false; - - NP_CALL(gvr_clear_error, gGvrContext); - const gvr_buffer_spec* specs[] = { bufferSpec }; - xnGvr_swap_chain = NP_CALL(gvr_swap_chain_create, gGvrContext, specs, 1); - if (NP_CALL(gvr_get_error, gGvrContext) != GVR_ERROR_NONE || xnGvr_swap_chain == NULL) return false; - - NP_CALL(gvr_buffer_spec_destroy, &bufferSpec); - - NP_CALL(gvr_clear_error, gGvrContext); - NP_CALL(gvr_swap_chain_resize_buffer, xnGvr_swap_chain, 0, xnGvr_size); - if (NP_CALL(gvr_get_error, gGvrContext)) return false; - - return true; - } - - void xnGvrGetPerspectiveMatrix(int eyeIndex, float near_clip, float far_clip, gvr_mat4f* outResult) - { -#ifdef IOS - //eyeIndex = eyeIndex == 0 ? 1 : 0; -#endif - - auto fov = NP_CALL(gvr_buffer_viewport_get_source_fov, eyeIndex == 0 ? xnGvr_LeftVieport : xnGvr_RightVieport); - float x_left = -tan(fov.left * M_PI / 180.0f) * near_clip; - float x_right = tan(fov.right * M_PI / 180.0f) * near_clip; - float y_bottom = -tan(fov.bottom * M_PI / 180.0f) * near_clip; - float y_top = tan(fov.top * M_PI / 180.0f) * near_clip; - - const auto X = (2 * near_clip) / (x_right - x_left); - const auto Y = (2 * near_clip) / (y_top - y_bottom); - const auto A = (x_right + x_left) / (x_right - x_left); - const auto B = (y_top + y_bottom) / (y_top - y_bottom); - const auto C = (near_clip + far_clip) / (near_clip - far_clip); - const auto D = (2 * near_clip * far_clip) / (near_clip - far_clip); - - for (auto i = 0; i < 4; ++i) - { - for (auto j = 0; j < 4; ++j) - { - outResult->m[i][j] = 0.0f; - } - } - - outResult->m[0][0] = X; - outResult->m[0][2] = A; - outResult->m[1][1] = Y; - outResult->m[1][2] = B; - outResult->m[2][2] = C; - outResult->m[2][3] = D; - outResult->m[3][2] = -1; - } - - void xnGvrGetHeadMatrix(float* outMatrix) - { - auto time = NP_CALL(gvr_get_time_point_now); - time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; - auto gvrMat4 = reinterpret_cast(outMatrix); - *gvrMat4 = NP_CALL(gvr_get_head_space_from_start_space_rotation, gGvrContext, time); - } - - void xnGvrGetEyeMatrix(int eyeIndex, float* outMatrix) - { -#ifdef IOS - //eyeIndex = eyeIndex == 0 ? 1 : 0; -#endif - - auto gvrMat4 = reinterpret_cast(outMatrix); - *gvrMat4 = NP_CALL(gvr_get_eye_from_head_matrix, gGvrContext, eyeIndex); - } - - void* xnGvrGetNextFrame() - { - NP_CALL(gvr_clear_error, gGvrContext); - auto frame = NP_CALL(gvr_swap_chain_acquire_frame, xnGvr_swap_chain); - auto err = NP_CALL(gvr_get_error, gGvrContext); - return err == GVR_ERROR_NONE ? frame : NULL; - } - - int xnGvrGetFBOIndex(gvr_frame* frame, int index) - { - return NP_CALL(gvr_frame_get_framebuffer_object, frame, index); - } - - npBool xnGvrSubmitFrame(gvr_frame* frame, float* headMatrix) - { - GLboolean masks[4]; - NP_CALL(glGetBooleanv, GL_COLOR_WRITEMASK, masks); - NP_CALL(glColorMask, true, true, true, true); // This was the super major headache and it's needed - - GLboolean scissor; - NP_CALL(glGetBooleanv, GL_SCISSOR_TEST, &scissor); - - GLboolean blend; - NP_CALL(glGetBooleanv, GL_BLEND, &blend); - - GLboolean cullFace; - NP_CALL(glGetBooleanv, GL_CULL_FACE, &cullFace); - - GLboolean depthTest; - NP_CALL(glGetBooleanv, GL_DEPTH_TEST, &depthTest); - - GLint eqRgb; - NP_CALL(glGetIntegerv, GL_BLEND_EQUATION_RGB, &eqRgb); - GLint eqAlpha; - NP_CALL(glGetIntegerv, GL_BLEND_EQUATION_ALPHA, &eqAlpha); - - GLint dstRgb; - NP_CALL(glGetIntegerv, GL_BLEND_DST_RGB, &dstRgb); - GLint dstAlpha; - NP_CALL(glGetIntegerv, GL_BLEND_DST_ALPHA, &dstAlpha); - GLint srcRgb; - NP_CALL(glGetIntegerv, GL_BLEND_SRC_RGB, &srcRgb); - GLint srcAlpha; - NP_CALL(glGetIntegerv, GL_BLEND_SRC_ALPHA, &srcAlpha); - - GLint viewport[4]; - NP_CALL(glGetIntegerv, GL_VIEWPORT, viewport); - - GLint index0Vert, index1Vert; - NP_CALL(glGetVertexAttribiv, 0, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &index0Vert); - NP_CALL(glGetVertexAttribiv, 1, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &index1Vert); - - GLint index0Size, index1Size; - NP_CALL(glGetVertexAttribiv, 0, GL_VERTEX_ATTRIB_ARRAY_SIZE, &index0Size); - NP_CALL(glGetVertexAttribiv, 1, GL_VERTEX_ATTRIB_ARRAY_SIZE, &index1Size); - - GLint index0Type, index1Type; - NP_CALL(glGetVertexAttribiv, 0, GL_VERTEX_ATTRIB_ARRAY_TYPE, &index0Type); - NP_CALL(glGetVertexAttribiv, 1, GL_VERTEX_ATTRIB_ARRAY_TYPE, &index1Type); - - GLint index0Normalized, index1Normalized; - NP_CALL(glGetVertexAttribiv, 0, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &index0Normalized); - NP_CALL(glGetVertexAttribiv, 1, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &index1Normalized); - - GLint index0Stride, index1Stride; - NP_CALL(glGetVertexAttribiv, 0, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &index0Stride); - NP_CALL(glGetVertexAttribiv, 1, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &index1Stride); - - GLvoid* index0Ptr; - GLvoid* index1Ptr; - NP_CALL(glGetVertexAttribPointerv, 0, GL_VERTEX_ATTRIB_ARRAY_POINTER, &index0Ptr); - NP_CALL(glGetVertexAttribPointerv, 1, GL_VERTEX_ATTRIB_ARRAY_POINTER, &index1Ptr); - - GLint indexBuffer; - NP_CALL(glGetIntegerv, GL_ELEMENT_ARRAY_BUFFER_BINDING, &indexBuffer); - - NP_CALL(gvr_clear_error, gGvrContext); - gvr_mat4f* gvrMat4 = reinterpret_cast(headMatrix); - NP_CALL(gvr_frame_submit, &frame, xnGvr_ViewportsList, *gvrMat4); - auto err = NP_CALL(gvr_get_error, gGvrContext); - - NP_CALL(glViewport, viewport[0], viewport[1], viewport[2], viewport[3]); - - NP_CALL(glColorMask, masks[0], masks[1], masks[2], masks[3]); - - if (scissor) - { - NP_CALL(glEnable, GL_SCISSOR_TEST); - } - - if(!blend) - { - NP_CALL(glDisable, GL_BLEND); - } - - if(cullFace) - { - NP_CALL(glEnable, GL_CULL_FACE); - } - - if(depthTest) - { - NP_CALL(glEnable, GL_DEPTH_TEST); - } - - NP_CALL(glBlendEquationSeparate, eqRgb, eqAlpha); - - NP_CALL(glBlendFuncSeparate, srcRgb, dstRgb, srcAlpha, dstAlpha); - - NP_CALL(glVertexAttribPointer, 0, index0Size, index0Type, index0Normalized, index0Stride, index0Ptr); - NP_CALL(glVertexAttribPointer, 1, index1Size, index1Type, index1Normalized, index1Stride, index1Ptr); - - if(!index0Vert) - { - NP_CALL(glDisableVertexAttribArray, 0); - } - - if (!index1Vert) - { - NP_CALL(glDisableVertexAttribArray, 1); - } - - NP_CALL(glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, indexBuffer); - - return err == GVR_ERROR_NONE; - } -} - -#else - -#endif diff --git a/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cs b/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cs deleted file mode 100644 index 485c7d0a90..0000000000 --- a/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVR.cs +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if DONT_BUILD_FOR_NOW && (XENKO_PLATFORM_IOS || XENKO_PLATFORM_ANDROID) - -using System; -using System.Runtime.InteropServices; -using System.Security; -using OpenTK.Graphics.ES20; -using Xenko.Core.Mathematics; -using Xenko.Graphics; - -#if XENKO_PLATFORM_ANDROID -using Java.Lang; -using Android.App; -using Android.Views; -using Com.Google.VR.Ndk.Base; -using Xenko.Games; -#endif - -namespace Xenko.VirtualReality -{ - public static class GoogleVr - { - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrStartup", CallingConvention = CallingConvention.Cdecl)] - private static extern int InternalStartup(IntPtr ctx); - -#if XENKO_PLATFORM_ANDROID - - public static void Startup(Game game, Activity androidActivity) - { - game.WindowCreated += (sender1, args1) => - { - var androidWindow = (GameWindowAndroid)game.Window; - - // Setup VR layout - var layout = new GvrLayout(androidActivity); - if (layout.SetAsyncReprojectionEnabled(true)) - { - AndroidCompat.SetSustainedPerformanceMode(androidActivity, true); - } - AndroidCompat.SetVrModeEnabled(androidActivity, true); - - ((ViewGroup)androidWindow.XenkoGameForm.Parent).RemoveView(androidWindow.XenkoGameForm); - layout.SetPresentationView(androidWindow.XenkoGameForm); - androidActivity.SetContentView(layout); - - // Init native, we need to reflect some methods that xamarin failed to wrap - var classGvrLayout = Class.ForName("com.google.vr.ndk.base.GvrLayout"); - var getGvrApiMethod = classGvrLayout.GetMethod("getGvrApi"); - var gvrApi = getGvrApiMethod.Invoke(layout); - var classGvrApi = Class.ForName("com.google.vr.ndk.base.GvrApi"); - var getNativeGvrContextMethod = classGvrApi.GetMethod("getNativeGvrContext"); - var nativeContextLong = (long)getNativeGvrContextMethod.Invoke(gvrApi); - var nativeCtx = new IntPtr(nativeContextLong); - - if (InternalStartup(nativeCtx) != 0) - { - throw new System.Exception("Failed to Startup Google VR SDK"); - } - }; - } - -#elif XENKO_PLATFORM_IOS - - public static void Startup(Game game) - { - game.WindowCreated += (sender1, args1) => - { - var res = InternalStartup(IntPtr.Zero); - if (res != 0) - { - throw new Exception("Failed to init Google cardboad SDK."); - } - }; - } - -#endif - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrGetMaxRenderSize", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetMaxRenderSize(out int width, out int height); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrInit", CallingConvention = CallingConvention.Cdecl)] - public static extern bool Init(int width, int height); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrGetPerspectiveMatrix", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetPerspectiveMatrix(int eyeIndex, float near, float far, out Matrix headMatrix); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrGetHeadMatrix", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetHeadMatrix(out Matrix headMatrix); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrGetEyeMatrix", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetEyeMatrix(int eyeIndex, out Matrix headMatrix); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrGetNextFrame", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr GetNextFrame(); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrGetFBOIndex", CallingConvention = CallingConvention.Cdecl)] - private static extern int GetFBOIndex(IntPtr frame, int index); - - public static void SubmitRenderTarget(GraphicsContext context, Texture renderTarget, IntPtr vrFrame, int index) - { - int currentFrameBuffer; - GL.GetInteger(GetPName.FramebufferBinding, out currentFrameBuffer); - - //TODO add proper destination values - GL.BindFramebuffer(FramebufferTarget.Framebuffer, GetFBOIndex(vrFrame, index)); - // The next call will write straight to the previously bound buffer - context.CommandList.CopyScaler2D(renderTarget, - new Rectangle(0, 0, renderTarget.Width, renderTarget.Height), - new Rectangle(0, 0, renderTarget.Width, renderTarget.Height) - ); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, currentFrameBuffer); - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnGvrSubmitFrame", CallingConvention = CallingConvention.Cdecl)] - private static extern bool InternalSubmitFrame(IntPtr frame, ref Matrix headMatrix); - - public static bool SubmitFrame(GraphicsDevice graphicsDevice, IntPtr frame, ref Matrix headMatrix) - { - int currentFrameBuffer; - GL.GetInteger(GetPName.FramebufferBinding, out currentFrameBuffer); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, graphicsDevice.FindOrCreateFBO(graphicsDevice.Presenter.BackBuffer)); - - var res = InternalSubmitFrame(frame, ref headMatrix);; - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, currentFrameBuffer); - - return res; - } - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVrHmd.cs b/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVrHmd.cs deleted file mode 100644 index 06e2c3bcd5..0000000000 --- a/sources/engine/Xenko.VirtualReality/GoogleVR/GoogleVrHmd.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if DONT_BUILD_FOR_NOW && (XENKO_PLATFORM_IOS || XENKO_PLATFORM_ANDROID) - -using System; -#if XENKO_PLATFORM_ANDROID -using Android.App; -#endif -using Xenko.Core; -using Xenko.Core.Mathematics; -using Xenko.Engine; -using Xenko.Games; -using Xenko.Graphics; -using Xenko.Rendering; -using Xenko.Rendering.Composers; - -namespace Xenko.VirtualReality -{ - internal class GoogleVrHmd : Hmd - { - private Matrix headMatrix; - - public GoogleVrHmd(IServiceRegistry registry) : base(registry) - { -#if XENKO_PLATFORM_ANDROID - GoogleVr.Startup(Game, (Activity)PlatformAndroid.Context); -#else - GoogleVr.Startup(Game); -#endif - } - - public override void Initialize(Entity cameraRoot, CameraComponent leftCamera, CameraComponent rightCamera, bool requireMirror = false) - { - var size = RenderFrameSize; - if (!GoogleVr.Init(size.Width, size.Height)) - { - throw new Exception("Failed to Init Google VR SDK"); - } - - RenderFrameProvider = new DirectRenderFrameProvider(RenderFrame.FromTexture( - Texture.New2D(GraphicsDevice, size.Width, size.Height, PixelFormat.R8G8B8A8_UNorm_SRgb, TextureFlags.RenderTarget | TextureFlags.ShaderResource) - )); - - var compositor = (SceneGraphicsCompositorLayers)Game.SceneSystem.SceneInstance.RootScene.Settings.GraphicsCompositor; - compositor.Master.Add(new SceneDelegateRenderer((x, y) => - { - var frame = GoogleVr.GetNextFrame(); - GoogleVr.SubmitRenderTarget(x.GraphicsContext, RenderFrameProvider.RenderFrame.RenderTargets[0], frame, 0); - if (!GoogleVr.SubmitFrame(GraphicsDevice, frame, ref headMatrix)) - { - throw new Exception("Failed to SubmitFrame to Google VR SDK"); - } - })); - - leftCamera.UseCustomProjectionMatrix = true; - rightCamera.UseCustomProjectionMatrix = true; - leftCamera.UseCustomViewMatrix = true; - rightCamera.UseCustomViewMatrix = true; - leftCamera.NearClipPlane *= ViewScaling; - rightCamera.NearClipPlane *= ViewScaling; - - if (requireMirror) - { - MirrorTexture = RenderFrameProvider.RenderFrame.RenderTargets[0]; //we don't really have a mirror in this case but avoid crashes - } - - base.Initialize(cameraRoot, leftCamera, rightCamera, requireMirror); - } - - public override void Draw(GameTime gameTime) - { - GoogleVr.GetHeadMatrix(out headMatrix); - var headMatrixTr = headMatrix; - headMatrixTr.Transpose(); - - Matrix leftEyeMatrix, rightEyeMatrix; - GoogleVr.GetEyeMatrix(0, out leftEyeMatrix); - GoogleVr.GetEyeMatrix(1, out rightEyeMatrix); - - Matrix projLeft, projRight; - GoogleVr.GetPerspectiveMatrix(0, LeftCameraComponent.NearClipPlane, LeftCameraComponent.FarClipPlane, out projLeft); - GoogleVr.GetPerspectiveMatrix(1, LeftCameraComponent.NearClipPlane, LeftCameraComponent.FarClipPlane, out projRight); - -// var iosRotL = Matrix.RotationYawPitchRoll(0, 0, MathUtil.Pi); -// var iosRotR = Matrix.RotationYawPitchRoll(0, 0, MathUtil.Pi); -// projLeft *= iosRotL; -// projRight *= iosRotR; - - Vector3 scale, camPos; - Quaternion camRot; - - //have to make sure it's updated now - CameraRootEntity.Transform.UpdateWorldMatrix(); - CameraRootEntity.Transform.WorldMatrix.Decompose(out scale, out camRot, out camPos); - - LeftCameraComponent.ProjectionMatrix = projLeft; - - var pos = camPos + leftEyeMatrix.TranslationVector * ViewScaling; - var rotV = headMatrixTr * Matrix.Scaling(ViewScaling) * Matrix.RotationQuaternion(camRot); - var finalUp = Vector3.TransformCoordinate(new Vector3(0, 1, 0), rotV); - var finalForward = Vector3.TransformCoordinate(new Vector3(0, 0, -1), rotV); - var view = Matrix.LookAtRH(pos, pos + finalForward, finalUp); - LeftCameraComponent.ViewMatrix = view; - - RightCameraComponent.ProjectionMatrix = projRight; - - pos = camPos + rightEyeMatrix.TranslationVector * ViewScaling; - rotV = headMatrixTr * Matrix.Scaling(ViewScaling) * Matrix.RotationQuaternion(camRot); - finalUp = Vector3.TransformCoordinate(new Vector3(0, 1, 0), rotV); - finalForward = Vector3.TransformCoordinate(new Vector3(0, 0, -1), rotV); - view = Matrix.LookAtRH(pos, pos + finalForward, finalUp); - RightCameraComponent.ViewMatrix = view; - - base.Draw(gameTime); - } - - public override Size2 OptimalRenderFrameSize - { - get - { - int width, height; - GoogleVr.GetMaxRenderSize(out width, out height); - return new Size2(width, height); - } - } - - public override DirectRenderFrameProvider RenderFrameProvider { get; protected set; } - - public override Texture MirrorTexture { get; protected set; } - - public override float RenderFrameScaling { get; set; } = 0.5f; - - public override DeviceState State => DeviceState.Valid; - - public override bool CanInitialize => true; - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cpp b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cpp deleted file mode 100644 index 6c886ec99f..0000000000 --- a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cpp +++ /dev/null @@ -1,592 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#include "../../../deps/NativePath/NativePath.h" -#include "../../Xenko.Native/XenkoNative.h" - -#if defined(WINDOWS_DESKTOP) || !defined(__clang__) - -#ifndef __clang__ -//Make resharper work! -#define OVR_ALIGNAS(n) -#error "The compiler must be clang!" -#endif - -#include "../../../../deps/OculusOVR/Include/OVR_CAPI.h" - -typedef struct _GUID { - unsigned long Data1; - unsigned short Data2; - unsigned short Data3; - unsigned char Data4[8]; -} GUID; - -#define OVR_AUDIO_MAX_DEVICE_STR_SIZE 128 - -extern "C" { - //DX specific stuff - extern ovrResult ovr_CreateTextureSwapChainDX(ovrSession session, void* d3dPtr, const ovrTextureSwapChainDesc* desc, ovrTextureSwapChain* out_TextureSwapChain); - extern ovrResult ovr_CreateMirrorTextureDX(ovrSession session, void* d3dPtr, const ovrMirrorTextureDesc* desc, ovrMirrorTexture* out_MirrorTexture); - extern ovrResult ovr_GetTextureSwapChainBufferDX(ovrSession session, ovrTextureSwapChain chain, int index, GUID iid, void** out_Buffer); - extern ovrResult ovr_GetMirrorTextureBufferDX(ovrSession session, ovrMirrorTexture mirrorTexture, GUID iid, void** out_Buffer); - extern ovrResult ovr_GetAudioDeviceOutGuidStr(wchar_t deviceOutStrBuffer[OVR_AUDIO_MAX_DEVICE_STR_SIZE]); - - DLL_EXPORT_API npBool xnOvrStartup() - { - ovrResult result = ovr_Initialize(NULL); - return OVR_SUCCESS(result); - } - - DLL_EXPORT_API void xnOvrShutdown() - { - ovr_Shutdown(); - } - - DLL_EXPORT_API int xnOvrGetError(char* errorString) - { - ovrErrorInfo errInfo; - ovr_GetLastErrorInfo(&errInfo); - strcpy(errorString, errInfo.ErrorString); - return errInfo.Result; - } - - struct xnOvrSession - { - ovrSession Session; - ovrMirrorTexture Mirror; - ovrHmdDesc HmdDesc; - ovrEyeRenderDesc EyeRenderDesc[2]; - ovrVector3f HmdToEyeViewOffset[2]; - - ovrTextureSwapChain SwapChain; - ovrLayerEyeFov Layer; - ovrTrackingState CurrentState; - }; - - DLL_EXPORT_API xnOvrSession* xnOvrCreateSessionDx(int64_t* luidOut) - { - ovrSession session; - ovrGraphicsLuid luid; - ovrResult result = ovr_Create(&session, &luid); - - bool success = OVR_SUCCESS(result); - if(success) - { - auto sessionOut = new xnOvrSession(); - sessionOut->Session = session; - sessionOut->SwapChain = NULL; - - *luidOut = *((int64_t*)luid.Reserved); - return sessionOut; - } - - return NULL; - } - - DLL_EXPORT_API void xnOvrDestroySession(xnOvrSession* session) - { - ovr_Destroy(session->Session); - } - - DLL_EXPORT_API npBool xnOvrCreateTexturesDx(xnOvrSession* session, void* dxDevice, int* outTextureCount, float pixelPerDisplayPixel, int mirrorBufferWidth, int mirrorBufferHeight) - { - session->HmdDesc = ovr_GetHmdDesc(session->Session); - ovrSizei sizel = ovr_GetFovTextureSize(session->Session, ovrEye_Left, session->HmdDesc.DefaultEyeFov[0], pixelPerDisplayPixel); - ovrSizei sizer = ovr_GetFovTextureSize(session->Session, ovrEye_Right, session->HmdDesc.DefaultEyeFov[1], pixelPerDisplayPixel); - ovrSizei bufferSize; - bufferSize.w = sizel.w + sizer.w; - bufferSize.h = fmax(sizel.h, sizer.h); - - ovrTextureSwapChainDesc texDesc = {}; - texDesc.Type = ovrTexture_2D; - texDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; - texDesc.ArraySize = 1; - texDesc.Width = bufferSize.w; - texDesc.Height = bufferSize.h; - texDesc.MipLevels = 1; - texDesc.SampleCount = 1; - texDesc.StaticImage = ovrFalse; - texDesc.MiscFlags = ovrTextureMisc_None; - texDesc.BindFlags = ovrTextureBind_DX_RenderTarget; - - if(!OVR_SUCCESS(ovr_CreateTextureSwapChainDX(session->Session, dxDevice, &texDesc, &session->SwapChain))) - { - return false; - } - - auto count = 0; - ovr_GetTextureSwapChainLength(session->Session, session->SwapChain, &count); - *outTextureCount = count; - - //init structures - session->EyeRenderDesc[0] = ovr_GetRenderDesc(session->Session, ovrEye_Left, session->HmdDesc.DefaultEyeFov[0]); - session->EyeRenderDesc[1] = ovr_GetRenderDesc(session->Session, ovrEye_Right, session->HmdDesc.DefaultEyeFov[1]); - session->HmdToEyeViewOffset[0] = session->EyeRenderDesc[0].HmdToEyeOffset; - session->HmdToEyeViewOffset[1] = session->EyeRenderDesc[1].HmdToEyeOffset; - - session->Layer.Header.Type = ovrLayerType_EyeFov; - session->Layer.Header.Flags = 0; - session->Layer.ColorTexture[0] = session->SwapChain; - session->Layer.ColorTexture[1] = session->SwapChain; - session->Layer.Fov[0] = session->EyeRenderDesc[0].Fov; - session->Layer.Fov[1] = session->EyeRenderDesc[1].Fov; - session->Layer.Viewport[0].Pos.x = 0; - session->Layer.Viewport[0].Pos.y = 0; - session->Layer.Viewport[0].Size.w = bufferSize.w / 2; - session->Layer.Viewport[0].Size.h = bufferSize.h; - session->Layer.Viewport[1].Pos.x = bufferSize.w / 2; - session->Layer.Viewport[1].Pos.y = 0; - session->Layer.Viewport[1].Size.w = bufferSize.w / 2; - session->Layer.Viewport[1].Size.h = bufferSize.h; - - //create mirror as well - if (mirrorBufferHeight != 0 && mirrorBufferWidth != 0) - { - ovrMirrorTextureDesc mirrorDesc = {}; - mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; - mirrorDesc.Width = mirrorBufferWidth; - mirrorDesc.Height = mirrorBufferHeight; - if (!OVR_SUCCESS(ovr_CreateMirrorTextureDX(session->Session, dxDevice, &mirrorDesc, &session->Mirror))) - { - return false; - } - } - - return true; - } - - struct xnOvrQuadLayer - { - ovrTextureSwapChain SwapChain; - ovrLayerQuad Layer; - }; - - DLL_EXPORT_API xnOvrQuadLayer* xnOvrCreateQuadLayerTexturesDx(xnOvrSession* session, void* dxDevice, int* outTextureCount, int width, int height, int mipLevels, int sampleCount) - { - auto layer = new xnOvrQuadLayer; - - ovrTextureSwapChainDesc texDesc = {}; - texDesc.Type = ovrTexture_2D; - texDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; - texDesc.ArraySize = 1; - texDesc.Width = width; - texDesc.Height = height; - texDesc.MipLevels = mipLevels; - texDesc.SampleCount = sampleCount; - texDesc.StaticImage = ovrFalse; - texDesc.MiscFlags = ovrTextureMisc_None; - texDesc.BindFlags = ovrTextureBind_DX_RenderTarget; - - if (!OVR_SUCCESS(ovr_CreateTextureSwapChainDX(session->Session, dxDevice, &texDesc, &layer->SwapChain))) - { - delete layer; - return NULL; - } - - auto count = 0; - ovr_GetTextureSwapChainLength(session->Session, layer->SwapChain, &count); - *outTextureCount = count; - - layer->Layer.Header.Type = ovrLayerType_Quad; - layer->Layer.Header.Flags = ovrLayerFlag_HighQuality; - layer->Layer.ColorTexture = layer->SwapChain; - layer->Layer.Viewport.Pos.x = 0; - layer->Layer.Viewport.Pos.y = 0; - layer->Layer.Viewport.Size.w = width; - layer->Layer.Viewport.Size.h = height; - layer->Layer.QuadPoseCenter.Orientation.x = 0; - layer->Layer.QuadPoseCenter.Orientation.y = 0; - layer->Layer.QuadPoseCenter.Orientation.z = 0; - layer->Layer.QuadPoseCenter.Orientation.w = 1; - layer->Layer.QuadPoseCenter.Position.x = 0; - layer->Layer.QuadPoseCenter.Position.y = 0; - layer->Layer.QuadPoseCenter.Position.z = -1; - layer->Layer.QuadSize.x = 2; - layer->Layer.QuadSize.y = 2; - - return layer; - } - - DLL_EXPORT_API void xnOvrSetQuadLayerParams(xnOvrQuadLayer* layer, float* position, float* orientation, float* size, npBool headLocked) - { - memcpy(&layer->Layer.QuadPoseCenter.Orientation, orientation, sizeof(float) * 4); - memcpy(&layer->Layer.QuadPoseCenter.Position, position, sizeof(float) * 3); - memcpy(&layer->Layer.QuadSize, size, sizeof(float) * 2); - layer->Layer.Header.Flags = headLocked ? ovrLayerFlag_HeadLocked | ovrLayerFlag_HighQuality : ovrLayerFlag_HighQuality; - } - - DLL_EXPORT_API void* xnOvrGetTextureAtIndexDx(xnOvrSession* session, GUID textureGuid, int index) - { - void* texture = NULL; - if (!OVR_SUCCESS(ovr_GetTextureSwapChainBufferDX(session->Session, session->SwapChain, index, textureGuid, &texture))) - { - return NULL; - } - return texture; - } - - DLL_EXPORT_API void* xnOvrGetQuadLayerTextureAtIndexDx(xnOvrSession* session, xnOvrQuadLayer* layer, GUID textureGuid, int index) - { - void* texture = NULL; - if (!OVR_SUCCESS(ovr_GetTextureSwapChainBufferDX(session->Session, layer->SwapChain, index, textureGuid, &texture))) - { - return NULL; - } - return texture; - } - - DLL_EXPORT_API void* xnOvrGetMirrorTextureDx(xnOvrSession* session, GUID textureGuid) - { - void* texture = NULL; - if (!OVR_SUCCESS(ovr_GetMirrorTextureBufferDX(session->Session, session->Mirror, textureGuid, &texture))) - { - return NULL; - } - return texture; - } - - DLL_EXPORT_API int xnOvrGetCurrentTargetIndex(xnOvrSession* session) - { - int index; - ovr_GetTextureSwapChainCurrentIndex(session->Session, session->SwapChain, &index); - return index; - } - - DLL_EXPORT_API int xnOvrGetCurrentQuadLayerTargetIndex(xnOvrSession* session, xnOvrQuadLayer* layer) - { - int index; - ovr_GetTextureSwapChainCurrentIndex(session->Session, layer->SwapChain, &index); - return index; - } - -#pragma pack(push, 4) - struct xnOvrFrameProperties - { - //Camera properties - float Near; - float Far; - float ProjLeft[16]; - float ProjRight[16]; - float PosLeft[3]; - float PosRight[3]; - float RotLeft[4]; - float RotRight[4]; - }; - - struct xnOvrPosesProperties - { - //Head - float PosHead[3]; - float RotHead[4]; - float AngularVelocityHead[3]; - float AngularAccelerationHead[3]; - float LinearVelocityHead[3]; - float LinearAccelerationHead[3]; - - //Left hand - float PosLeftHand[3]; - float RotLeftHand[4]; - float AngularVelocityLeftHand[3]; - float AngularAccelerationLeftHand[3]; - float LinearVelocityLeftHand[3]; - float LinearAccelerationLeftHand[3]; - int StateLeftHand; - - //Right hand - float PosRightHand[3]; - float RotRightHand[4]; - float AngularVelocityRightHand[3]; - float AngularAccelerationRightHand[3]; - float LinearVelocityRightHand[3]; - float LinearAccelerationRightHand[3]; - int StateRightHand; - }; - - struct xnOvrInputProperties - { - unsigned int Buttons; - unsigned int Touches; - float IndexTriggerLeft; - float IndexTriggerRight; - float HandTriggerLeft; - float HandTriggerRight; - float ThumbstickLeft[2]; - float ThumbstickRight[2]; - npBool Valid; - }; -#pragma pack(pop) - - DLL_EXPORT_API void xnOvrUpdate(xnOvrSession* session) - { - session->EyeRenderDesc[0] = ovr_GetRenderDesc(session->Session, ovrEye_Left, session->HmdDesc.DefaultEyeFov[0]); - session->EyeRenderDesc[1] = ovr_GetRenderDesc(session->Session, ovrEye_Right, session->HmdDesc.DefaultEyeFov[1]); - session->HmdToEyeViewOffset[0] = session->EyeRenderDesc[0].HmdToEyeOffset; - session->HmdToEyeViewOffset[1] = session->EyeRenderDesc[1].HmdToEyeOffset; - - session->Layer.SensorSampleTime = ovr_GetPredictedDisplayTime(session->Session, 0); - session->CurrentState = ovr_GetTrackingState(session->Session, session->Layer.SensorSampleTime, ovrTrue); - ovr_CalcEyePoses(session->CurrentState.HeadPose.ThePose, session->HmdToEyeViewOffset, session->Layer.RenderPose); - } - - DLL_EXPORT_API void xnOvrGetFrameProperties(xnOvrSession* session, xnOvrFrameProperties* properties) - { - auto leftProj = ovrMatrix4f_Projection(session->Layer.Fov[0], properties->Near, properties->Far, 0); - auto rightProj = ovrMatrix4f_Projection(session->Layer.Fov[1], properties->Near, properties->Far, 0); - - memcpy(properties->ProjLeft, &leftProj, sizeof(float) * 16); - memcpy(properties->PosLeft, &session->Layer.RenderPose[0].Position, sizeof(float) * 3); - memcpy(properties->RotLeft, &session->Layer.RenderPose[0].Orientation, sizeof(float) * 4); - - memcpy(properties->ProjRight, &rightProj, sizeof(float) * 16); - memcpy(properties->PosRight, &session->Layer.RenderPose[1].Position, sizeof(float) * 3); - memcpy(properties->RotRight, &session->Layer.RenderPose[1].Orientation, sizeof(float) * 4); - } - - DLL_EXPORT_API void xnOvrGetPosesProperties(xnOvrSession* session, xnOvrPosesProperties* properties) - { - memcpy(properties->PosHead, &session->CurrentState.HeadPose.ThePose.Position, sizeof(float) * 3); - memcpy(properties->RotHead, &session->CurrentState.HeadPose.ThePose.Orientation, sizeof(float) * 4); - memcpy(properties->AngularVelocityHead, &session->CurrentState.HeadPose.AngularVelocity, sizeof(float) * 3); - memcpy(properties->AngularAccelerationHead, &session->CurrentState.HeadPose.AngularAcceleration, sizeof(float) * 3); - memcpy(properties->LinearVelocityHead, &session->CurrentState.HeadPose.LinearVelocity, sizeof(float) * 3); - memcpy(properties->LinearAccelerationHead, &session->CurrentState.HeadPose.LinearAcceleration, sizeof(float) * 3); - - memcpy(properties->PosLeftHand, &session->CurrentState.HandPoses[0].ThePose.Position, sizeof(float) * 3); - memcpy(properties->RotLeftHand, &session->CurrentState.HandPoses[0].ThePose.Orientation, sizeof(float) * 4); - memcpy(properties->AngularVelocityLeftHand, &session->CurrentState.HandPoses[0].AngularVelocity, sizeof(float) * 3); - memcpy(properties->AngularAccelerationLeftHand, &session->CurrentState.HandPoses[0].AngularAcceleration, sizeof(float) * 3); - memcpy(properties->LinearVelocityLeftHand, &session->CurrentState.HandPoses[0].LinearVelocity, sizeof(float) * 3); - memcpy(properties->LinearAccelerationLeftHand, &session->CurrentState.HandPoses[0].LinearAcceleration, sizeof(float) * 3); - properties->StateLeftHand = session->CurrentState.HandStatusFlags[0]; - - memcpy(properties->PosRightHand, &session->CurrentState.HandPoses[1].ThePose.Position, sizeof(float) * 3); - memcpy(properties->RotRightHand, &session->CurrentState.HandPoses[1].ThePose.Orientation, sizeof(float) * 4); - memcpy(properties->AngularVelocityRightHand, &session->CurrentState.HandPoses[1].AngularVelocity, sizeof(float) * 3); - memcpy(properties->AngularAccelerationRightHand, &session->CurrentState.HandPoses[1].AngularAcceleration, sizeof(float) * 3); - memcpy(properties->LinearVelocityRightHand, &session->CurrentState.HandPoses[1].LinearVelocity, sizeof(float) * 3); - memcpy(properties->LinearAccelerationRightHand, &session->CurrentState.HandPoses[1].LinearAcceleration, sizeof(float) * 3); - properties->StateRightHand = session->CurrentState.HandStatusFlags[1]; - } - - DLL_EXPORT_API void xnOvrGetInputProperties(xnOvrSession* session, xnOvrInputProperties* properties) - { - ovrInputState state; - auto res = ovr_GetInputState(session->Session, ovrControllerType_Touch, &state); - if(OVR_SUCCESS(res)) - { - properties->Valid = true; - properties->Buttons = state.Buttons; - properties->Touches = state.Touches; - properties->HandTriggerLeft = state.HandTrigger[0]; - properties->HandTriggerRight = state.HandTrigger[1]; - properties->IndexTriggerLeft = state.IndexTrigger[0]; - properties->IndexTriggerRight = state.IndexTrigger[1]; - properties->ThumbstickLeft[0] = state.Thumbstick[0].x; - properties->ThumbstickLeft[1] = state.Thumbstick[0].y; - properties->ThumbstickRight[0] = state.Thumbstick[1].x; - properties->ThumbstickRight[1] = state.Thumbstick[1].y; - } - else - { - properties->Valid = false; - } - } - - DLL_EXPORT_API npBool xnOvrCommitFrame(xnOvrSession* session, int numberOfExtraLayers, xnOvrQuadLayer** extraLayers) - { - ovrLayerHeader* layers[1 + numberOfExtraLayers]; - //add the default layer first - layers[0] = &session->Layer.Header; - //commit the default fov layer - ovr_CommitTextureSwapChain(session->Session, session->SwapChain); - for (auto i = 0; i < numberOfExtraLayers; i++) - { - //add further quad layers - layers[i + 1] = &extraLayers[i]->Layer.Header; - //also commit the quad layer - ovr_CommitTextureSwapChain(session->Session, extraLayers[i]->SwapChain); - } - - if(!OVR_SUCCESS(ovr_SubmitFrame(session->Session, 0, NULL, layers, 1 + numberOfExtraLayers))) - { - return false; - } - - ovrSessionStatus status; - if (!OVR_SUCCESS(ovr_GetSessionStatus(session->Session, &status))) - { - return false; - } - - if(status.ShouldRecenter) - { - ovr_RecenterTrackingOrigin(session->Session); - } - - return true; - } - -#pragma pack(push, 4) - struct xnOvrSessionStatus - { - npBool IsVisible; ///< True if the process has VR focus and thus is visible in the HMD. - npBool HmdPresent; ///< True if an HMD is present. - npBool HmdMounted; ///< True if the HMD is on the user's head. - npBool DisplayLost; ///< True if the session is in a display-lost state. See ovr_SubmitFrame. - npBool ShouldQuit; ///< True if the application should initiate shutdown. - npBool ShouldRecenter; ///< True if UX has requested re-centering. Must call ovr_ClearShouldRecenterFlag or ovr_RecenterTrackingOrigin. - }; -#pragma pack(pop) - - DLL_EXPORT_API void xnOvrGetStatus(xnOvrSession* session, xnOvrSessionStatus* statusOut) - { - ovrSessionStatus status; - if (!OVR_SUCCESS(ovr_GetSessionStatus(session->Session, &status))) - { - return; - } - - statusOut->IsVisible = status.IsVisible; - statusOut->HmdPresent = status.HmdPresent; - statusOut->HmdMounted = status.HmdMounted; - statusOut->DisplayLost = status.DisplayLost; - statusOut->ShouldQuit = status.ShouldQuit; - statusOut->ShouldRecenter = status.ShouldRecenter; - } - - DLL_EXPORT_API void xnOvrRecenter(xnOvrSession* session) - { - ovr_RecenterTrackingOrigin(session->Session); - } - - DLL_EXPORT_API void xnOvrGetAudioDeviceID(wchar_t* deviceString) - { - ovr_GetAudioDeviceOutGuidStr(deviceString); - } -} - -#else - -extern "C" { - typedef struct _GUID { - unsigned long Data1; - unsigned short Data2; - unsigned short Data3; - unsigned char Data4[8]; - } GUID; - - DLL_EXPORT_API npBool xnOvrStartup() - { - return true; - } - - DLL_EXPORT_API void xnOvrShutdown() - { - - } - - DLL_EXPORT_API int xnOvrGetError(char* errorString) - { - return 0; - } - - DLL_EXPORT_API void* xnOvrCreateSessionDx(void* luidOut) - { - return 0; - } - - DLL_EXPORT_API void xnOvrDestroySession(void* session) - { - - } - - DLL_EXPORT_API npBool xnOvrCreateTexturesDx(void* session, void* dxDevice, int* outTextureCount) - { - return true; - } - - DLL_EXPORT_API void* xnOvrGetTextureAtIndexDx(void* session, GUID textureGuid, int index) - { - return 0; - } - - DLL_EXPORT_API void* xnOvrGetMirrorTextureDx(void* session, GUID textureGuid) - { - return 0; - } - - DLL_EXPORT_API int xnOvrGetCurrentTargetIndex(void* session) - { - return 0; - } - - DLL_EXPORT_API void xnOvrUpdate(void* session) - { - - } - - DLL_EXPORT_API void xnOvrGetFrameProperties(void* session, void* params) - { - - } - - DLL_EXPORT_API void xnOvrGetPosesProperties(void* session, void* params) - { - - } - - DLL_EXPORT_API void xnOvrGetInputProperties(void* session, void* properties) - { - - } - - DLL_EXPORT_API npBool xnOvrCommitFrame(void* session, int numberOfExtraLayers, void** extraLayers) - { - return true; - } - -#pragma pack(push, 4) - DLL_EXPORT_API struct xnOvrSessionStatus - { - npBool IsVisible; ///< True if the process has VR focus and thus is visible in the HMD. - npBool HmdPresent; ///< True if an HMD is present. - npBool HmdMounted; ///< True if the HMD is on the user's head. - npBool DisplayLost; ///< True if the session is in a display-lost state. See ovr_SubmitFrame. - npBool ShouldQuit; ///< True if the application should initiate shutdown. - npBool ShouldRecenter; ///< True if UX has requested re-centering. Must call ovr_ClearShouldRecenterFlag or ovr_RecenterTrackingOrigin. - }; -#pragma pack(pop) - - DLL_EXPORT_API void xnOvrGetStatus(void* session, void* statusOut) - { - } - - DLL_EXPORT_API void xnOvrRecenter(void* session) - { - } - - DLL_EXPORT_API void xnOvrGetAudioDeviceID(wchar_t* deviceString) - { - } - - DLL_EXPORT_API void* xnOvrCreateQuadLayerTexturesDx(void* session, void* dxDevice, int* outTextureCount, int width, int height, int mipLevels, int sampleCount) - { - return NULL; - } - - DLL_EXPORT_API int xnOvrGetCurrentQuadLayerTargetIndex(void* session, void* layer) - { - return 0; - } - - DLL_EXPORT_API void* xnOvrGetQuadLayerTextureAtIndexDx(void* session, void* layer, GUID textureGuid, int index) - { - return NULL; - } - - DLL_EXPORT_API void xnOvrSetQuadLayerParams(void* layer, float* position, float* orientation, float* size, npBool headLocked) - { - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cs b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cs deleted file mode 100644 index a4ca10dedb..0000000000 --- a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOVR.cs +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; -using Xenko.Core; -using Xenko.Core.Mathematics; - -namespace Xenko.VirtualReality -{ - internal static class OculusOvr - { - static OculusOvr() - { -#if XENKO_PLATFORM_WINDOWS - NativeLibrary.PreloadLibrary(NativeInvoke.Library + ".dll", typeof(OculusOvr)); -#endif - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrStartup", CallingConvention = CallingConvention.Cdecl)] - public static extern bool Startup(); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrShutdown", CallingConvention = CallingConvention.Cdecl)] - public static extern void Shutdown(); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrCreateSessionDx", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr CreateSessionDx(out long adapterLuidStr); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrDestroySession", CallingConvention = CallingConvention.Cdecl)] - public static extern void DestroySession(IntPtr outSessionPtr); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrCreateTexturesDx", CallingConvention = CallingConvention.Cdecl)] - public static extern bool CreateTexturesDx(IntPtr session, IntPtr dxDevice, out int outTextureCount, float pixelPerScreenPixel, int mirrorBufferWidth = 0, int mirrorBufferHeight = 0); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrCreateQuadLayerTexturesDx", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr CreateQuadLayerTexturesDx(IntPtr session, IntPtr dxDevice, out int outTextureCount, int width, int height, int mipLevels, int sampleCount); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrSetQuadLayerParams", CallingConvention = CallingConvention.Cdecl)] - public static extern void SetQuadLayerParams(IntPtr layer, ref Vector3 position, ref Quaternion rotation, ref Vector2 size, bool headLocked); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetTextureAtIndexDx", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr GetTextureDx(IntPtr session, Guid textureGuid, int index); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetQuadLayerTextureAtIndexDx", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr GetQuadLayerTextureDx(IntPtr session, IntPtr layer, Guid textureGuid, int index); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetMirrorTextureDx", CallingConvention = CallingConvention.Cdecl)] - public static extern IntPtr GetMirrorTexture(IntPtr session, Guid textureGuid); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetCurrentTargetIndex", CallingConvention = CallingConvention.Cdecl)] - public static extern int GetCurrentTargetIndex(IntPtr session); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetCurrentQuadLayerTargetIndex", CallingConvention = CallingConvention.Cdecl)] - public static extern int GetCurrentQuadLayerTargetIndex(IntPtr session, IntPtr layer); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrCommitFrame", CallingConvention = CallingConvention.Cdecl)] - public static extern bool CommitFrame(IntPtr session, int numberOfExtraLayers, [MarshalAs(UnmanagedType.LPArray)] IntPtr[] extraLayer); - - [StructLayout(LayoutKind.Sequential, Pack = 4)] - public struct FrameProperties - { - public float Near; - public float Far; - public Matrix ProjLeft; - public Matrix ProjRight; - public Vector3 PosLeft; - public Vector3 PosRight; - public Quaternion RotLeft; - public Quaternion RotRight; - } - - [StructLayout(LayoutKind.Sequential, Pack = 4)] - public struct PosesProperties - { - public Vector3 PosHead; - public Quaternion RotHead; - public Vector3 AngularVelocityHead; - public Vector3 AngularAccelerationHead; - public Vector3 LinearVelocityHead; - public Vector3 LinearAccelerationHead; - - public Vector3 PosLeftHand; - public Quaternion RotLeftHand; - public Vector3 AngularVelocityLeftHand; - public Vector3 AngularAccelerationLeftHand; - public Vector3 LinearVelocityLeftHand; - public Vector3 LinearAccelerationLeftHand; - public int StateLeftHand; - - public Vector3 PosRightHand; - public Quaternion RotRightHand; - public Vector3 AngularVelocityRightHand; - public Vector3 AngularAccelerationRightHand; - public Vector3 LinearVelocityRightHand; - public Vector3 LinearAccelerationRightHand; - public int StateRightHand; - } - - [StructLayout(LayoutKind.Sequential, Pack = 4)] - public struct InputProperties - { - public uint Buttons; - public uint Touches; - public float IndexTriggerLeft; - public float IndexTriggerRight; - public float HandTriggerLeft; - public float HandTriggerRight; - public Vector2 ThumbstickLeft; - public Vector2 ThumbstickRight; - public bool Valid; - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrUpdate", CallingConvention = CallingConvention.Cdecl)] - public static extern void Update(IntPtr session); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetFrameProperties", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetFrameProperties(IntPtr session, ref FrameProperties properties); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetPosesProperties", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetPosesProperties(IntPtr session, out PosesProperties properties); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetInputProperties", CallingConvention = CallingConvention.Cdecl)] - public static extern void GetInputProperties(IntPtr session, out InputProperties properties); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetError", CallingConvention = CallingConvention.Cdecl)] - private static extern int GetError(IntPtr errorString); - - public static unsafe string GetError() - { - var buffer = stackalloc char[256]; - var errorCStr = new IntPtr(buffer); - var error = GetError(errorCStr); - var errorStr = Marshal.PtrToStringAnsi(errorCStr); - return $"OculusOVR-Error({error}): {errorStr}"; - } - - [StructLayout(LayoutKind.Sequential, Pack = 4)] - private struct SessionStatusInternal - { - public int IsVisible; - public int HmdPresent; - public int HmdMounted; - public int DisplayLost; - public int ShouldQuit; - public int ShouldRecenter; - } - - public struct SessionStatus - { - /// - /// True if the process has VR focus and thus is visible in the HMD. - /// - public bool IsVisible; - /// - /// True if an HMD is present. - /// - public bool HmdPresent; - /// - /// True if the HMD is on the user's head. - /// - public bool HmdMounted; - /// - /// True if the session is in a display-lost state. See ovr_SubmitFrame. - /// - public bool DisplayLost; - /// - /// True if the application should initiate shutdown. - /// - public bool ShouldQuit; - /// - /// True if UX has requested re-centering. - /// - public bool ShouldRecenter; - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetStatus", CallingConvention = CallingConvention.Cdecl)] - private static extern void GetStatus(IntPtr session, ref SessionStatusInternal status); - - public static SessionStatus GetStatus(IntPtr session) - { - var statusInternal = new SessionStatusInternal { DisplayLost = 0, IsVisible = 0, ShouldQuit = 0, HmdMounted = 0, HmdPresent = 0, ShouldRecenter = 0 }; - GetStatus(session, ref statusInternal); - return new SessionStatus - { - DisplayLost = statusInternal.DisplayLost == 1, - HmdMounted = statusInternal.HmdMounted == 1, - HmdPresent = statusInternal.HmdPresent == 1, - IsVisible = statusInternal.IsVisible == 1, - ShouldQuit = statusInternal.ShouldQuit == 1, - ShouldRecenter = statusInternal.ShouldRecenter == 1, - }; - } - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrRecenter", CallingConvention = CallingConvention.Cdecl)] - public static extern void Recenter(IntPtr session); - - [SuppressUnmanagedCodeSecurity] - [DllImport(NativeInvoke.Library, EntryPoint = "xnOvrGetAudioDeviceID", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] - public static extern void GetAudioDeviceID(StringBuilder deviceName); - - public static string GetAudioDeviceFullName() - { - var deviceName = new StringBuilder(128); - GetAudioDeviceID(deviceName); - return $"\\\\?\\SWD#MMDEVAPI#{deviceName}#{{e6327cad-dcec-4949-ae8a-991e976a79d2}}"; //this should not change the guid is related to audio device type - } - } -} diff --git a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOverlay.cs b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOverlay.cs deleted file mode 100644 index 995718477a..0000000000 --- a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOverlay.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 - -using System; -using SharpDX.Direct3D11; -using Xenko.Graphics; -using CommandList = Xenko.Graphics.CommandList; - -namespace Xenko.VirtualReality -{ - internal class OculusOverlay : VROverlay, IDisposable - { - private readonly IntPtr ovrSession; - internal IntPtr OverlayPtr; - private readonly Texture[] textures; - - public OculusOverlay(IntPtr ovrSession, GraphicsDevice device, int width, int height, int mipLevels, int sampleCount) - { - int textureCount; - this.ovrSession = ovrSession; - - OverlayPtr = OculusOvr.CreateQuadLayerTexturesDx(ovrSession, device.NativeDevice.NativePointer, out textureCount, width, height, mipLevels, sampleCount); - if (OverlayPtr == null) - { - throw new Exception(OculusOvr.GetError()); - } - - textures = new Texture[textureCount]; - for (var i = 0; i < textureCount; i++) - { - var ptr = OculusOvr.GetQuadLayerTextureDx(ovrSession, OverlayPtr, OculusOvrHmd.Dx11Texture2DGuid, i); - if (ptr == IntPtr.Zero) - { - throw new Exception(OculusOvr.GetError()); - } - - textures[i] = new Texture(device); - textures[i].InitializeFromImpl(new Texture2D(ptr), false); - } - } - - public override void Dispose() - { - } - - public override void UpdateSurface(CommandList commandList, Texture texture) - { - OculusOvr.SetQuadLayerParams(OverlayPtr, ref Position, ref Rotation, ref SurfaceSize, FollowHeadRotation); - var index = OculusOvr.GetCurrentQuadLayerTargetIndex(ovrSession, OverlayPtr); - commandList.Copy(texture, textures[index]); - } - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs deleted file mode 100644 index f1c04df722..0000000000 --- a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusOvrHmd.cs +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D11 - -using System; -using System.Collections.Generic; -using System.Linq; -using SharpDX.Direct3D11; -using Xenko.Core.Mathematics; -using Xenko.Games; -using Xenko.Graphics; -using CommandList = Xenko.Graphics.CommandList; - -namespace Xenko.VirtualReality -{ - internal class OculusOvrHmd : VRDevice - { - private static bool initDone; - - //private static readonly Guid dx12ResourceGuid = new Guid("696442be-a72e-4059-bc79-5b5c98040fad"); - internal static readonly Guid Dx11Texture2DGuid = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c"); - - private IntPtr ovrSession; - private Texture[] textures; - - public override ulong PoseCount => 0; - - private OculusTouchController leftHandController; - private OculusTouchController rightHandController; - private readonly List overlays = new List(); - private IntPtr[] overlayPtrs = new IntPtr[0]; - - internal OculusOvrHmd() - { - SupportsOverlays = true; - //VRApi = VRApi.Oculus; - } - - public override void Dispose() - { - foreach (var oculusOverlay in overlays) - { - oculusOverlay.Dispose(); - } - - if (ovrSession != IntPtr.Zero) - { - OculusOvr.DestroySession(ovrSession); - ovrSession = IntPtr.Zero; - } - } - - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror) - { - /*graphicsDevice = device; - long adapterId; - ovrSession = OculusOvr.CreateSessionDx(out adapterId); - //Game.GraphicsDeviceManager.RequiredAdapterUid = adapterId.ToString(); //should not be needed - - int texturesCount; - if (!OculusOvr.CreateTexturesDx(ovrSession, device.NativeDevice.NativePointer, out texturesCount, RenderFrameScaling, requireMirror ? mirrorWidth : 0, requireMirror ? mirrorHeight : 0)) - { - throw new Exception(OculusOvr.GetError()); - } - - if (requireMirror) - { - var mirrorTex = OculusOvr.GetMirrorTexture(ovrSession, Dx11Texture2DGuid); - MirrorTexture = new Texture(device); - MirrorTexture.InitializeFromImpl(new Texture2D(mirrorTex), false); - } - - textures = new Texture[texturesCount]; - for (var i = 0; i < texturesCount; i++) - { - var ptr = OculusOvr.GetTextureDx(ovrSession, Dx11Texture2DGuid, i); - if (ptr == IntPtr.Zero) - { - throw new Exception(OculusOvr.GetError()); - } - - textures[i] = new Texture(device); - textures[i].InitializeFromImpl(new Texture2D(ptr), false); - } - - ActualRenderFrameSize = new Size2(textures[0].Width, textures[0].Height); - - leftHandController = new OculusTouchController(TouchControllerHand.Left); - rightHandController = new OculusTouchController(TouchControllerHand.Right);*/ - } - - private OculusOvr.PosesProperties currentPoses; - private GraphicsDevice graphicsDevice; - - public override void Update(GameTime gameTime) - { - OculusOvr.InputProperties properties; - OculusOvr.GetInputProperties(ovrSession, out properties); - leftHandController.UpdateInputs(ref properties); - rightHandController.UpdateInputs(ref properties); - } - - public override void Draw(GameTime gameTime) - { - OculusOvr.Update(ovrSession); - OculusOvr.GetPosesProperties(ovrSession, out currentPoses); - leftHandController.UpdatePoses(ref currentPoses); - rightHandController.UpdatePoses(ref currentPoses); - } - - public override Size2 OptimalRenderFrameSize => new Size2(2160, 1200); - - public override Size2 ActualRenderFrameSize { get; protected set; } - - public override Texture MirrorTexture { get; protected set; } - - public override float RenderFrameScaling { get; set; } = 1.2f; - - public override DeviceState State - { - get - { - var deviceStatus = OculusOvr.GetStatus(ovrSession); - if (deviceStatus.DisplayLost || !deviceStatus.HmdPresent) return DeviceState.Invalid; - if (deviceStatus.HmdMounted && deviceStatus.IsVisible) return DeviceState.Valid; - return DeviceState.OutOfRange; - } - } - - public override Vector3 HeadPosition => currentPoses.PosHead; - - public override Quaternion HeadRotation => currentPoses.RotHead; - - public override Vector3 HeadLinearVelocity => currentPoses.LinearVelocityHead; - - public override Vector3 HeadAngularVelocity => currentPoses.AngularVelocityHead; - - public override TouchController LeftHand => leftHandController; - - public override TouchController RightHand => rightHandController; - - public override TrackedItem[] TrackedItems => new TrackedItem[0]; - - public override bool CanInitialize - { - get - { - if (initDone) return true; - initDone = OculusOvr.Startup(); - if (initDone) - { - long deviceId; - var tempSession = OculusOvr.CreateSessionDx(out deviceId); - if (tempSession != IntPtr.Zero) - { - OculusOvr.DestroySession(tempSession); - initDone = true; - } - else - { - initDone = false; - } - } - return initDone; - } - } - - public override void Recenter() - { - OculusOvr.Recenter(ovrSession); - } - - public override void ReadEyeParameters(Eyes eye, float near, float far, ref Vector3 cameraPosition, ref Matrix cameraRotation, bool ignoreHeadRotation, bool ignoreHeadPosition, out Matrix view, out Matrix projection) - { - var frameProperties = new OculusOvr.FrameProperties - { - Near = near, - Far = far, - }; - OculusOvr.GetFrameProperties(ovrSession, ref frameProperties); - - var isLeftEye = eye == Eyes.Left; - var camRot = Quaternion.RotationMatrix(cameraRotation); - projection = isLeftEye ? frameProperties.ProjLeft : frameProperties.ProjRight; - - var eyePosition = isLeftEye ? frameProperties.PosLeft : frameProperties.PosRight; - if (ignoreHeadPosition) - eyePosition -= (frameProperties.PosLeft + frameProperties.PosRight) / 2f; - - var eyeRotation = isLeftEye ? frameProperties.RotLeft : frameProperties.RotRight; - if (ignoreHeadRotation) - eyeRotation = Quaternion.Identity; - - var position = cameraPosition + Vector3.Transform(eyePosition * ViewScaling, camRot); - var rotation = Matrix.RotationQuaternion(eyeRotation) * Matrix.Scaling(ViewScaling) * Matrix.RotationQuaternion(camRot); - var finalUp = Vector3.TransformCoordinate(new Vector3(0, 1, 0), rotation); - var finalForward = Vector3.TransformCoordinate(new Vector3(0, 0, -1), rotation); - view = Matrix.LookAtRH(position, position + finalForward, finalUp); - } - - public override void Commit(CommandList commandList, Texture renderFrame) - { - var index = OculusOvr.GetCurrentTargetIndex(ovrSession); - commandList.Copy(renderFrame, textures[index]); - overlayPtrs = overlays.Where(x => x.Enabled).Select(x => x.OverlayPtr).ToArray(); - OculusOvr.CommitFrame(ovrSession, overlayPtrs.Length, overlayPtrs); - } - - public override VROverlay CreateOverlay(int width, int height, int mipLevels, int sampleCount) - { - var overlay = new OculusOverlay(ovrSession, graphicsDevice, width, height, mipLevels, sampleCount); - overlays.Add(overlay); - return overlay; - } - - public override void ReleaseOverlay(VROverlay overlay) - { - var oculusOverlay = (OculusOverlay)overlay; - oculusOverlay.Dispose(); - overlays.Remove(oculusOverlay); - } - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusTouchController.cs b/sources/engine/Xenko.VirtualReality/OculusOVR/OculusTouchController.cs deleted file mode 100644 index dc4802bb8c..0000000000 --- a/sources/engine/Xenko.VirtualReality/OculusOVR/OculusTouchController.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; -using Xenko.Core.Mathematics; - -namespace Xenko.VirtualReality -{ - internal class OculusTouchController : TouchController - { - private readonly TouchControllerHand hand; - private Vector3 currentPos; - private Vector3 currentLinearVelocity; - private Vector3 currentAngularVelocity; - private Quaternion currentRot; - private DeviceState currentState; - private float currentTrigger; - private float currentGrip; - private float previousTrigger; - private float previousGrip; - private uint currentTouchesState; - private uint previousTouchesState; - private uint currentButtonsState; - private uint previousButtonsState; - private Vector2 currentThumbstick; - private const float TriggerAndGripDeadzone = 0.00001f; - - public override Vector3 Position => currentPos; - - public override Quaternion Rotation => currentRot; - - public override Vector3 LinearVelocity => currentLinearVelocity; - - public override Vector3 AngularVelocity => currentAngularVelocity; - - public override DeviceState State => currentState; - - public override float Trigger => currentTrigger; - - public override float Grip => currentGrip; - - public override bool IndexPointing - { - get - { - if (hand == TouchControllerHand.Left) - { - //ovrTouch_LIndexPointing - if ((currentTouchesState & 0x00002000) == 0x00002000) - { - return true; - } - } - else if (hand == TouchControllerHand.Right) - { - //ovrTouch_RIndexPointing - if ((currentTouchesState & 0x00000020) == 0x00000020) - { - return true; - } - } - return false; - } - } - - public override bool IndexResting - { - get - { - if (hand == TouchControllerHand.Left) - { - //ovrTouch_LIndexTrigger - if ((currentTouchesState & 0x00001000) == 0x00001000) - { - return true; - } - } - else if (hand == TouchControllerHand.Right) - { - //ovrTouch_RIndexTrigger - if ((currentTouchesState & 0x00000010) == 0x00000010) - { - return true; - } - } - return false; - } - } - - public override bool ThumbUp - { - get - { - if (hand == TouchControllerHand.Left) - { - //ovrTouch_LThumbUp - if ((currentTouchesState & 0x00004000) == 0x00004000) - { - return true; - } - } - else if (hand == TouchControllerHand.Right) - { - //ovrTouch_RThumbUp - if ((currentTouchesState & 0x00000040) == 0x00000040) - { - return true; - } - } - return false; - } - } - - public override bool ThumbResting - { - get - { - if (hand == TouchControllerHand.Left) - { - //ovrTouch_LThumbRest - if ((currentTouchesState & 0x00000800) == 0x00000800) - { - return true; - } - } - else if (hand == TouchControllerHand.Right) - { - //ovrTouch_RThumbRest - if ((currentTouchesState & 0x00000008) == 0x00000008) - { - return true; - } - } - return false; - } - } - - public override Vector2 ThumbAxis => currentThumbstick; - - public override Vector2 ThumbstickAxis => currentThumbstick; - - public OculusTouchController(TouchControllerHand hand) - { - this.hand = hand; - currentState = DeviceState.Invalid; - } - - internal void UpdateInputs(ref OculusOvr.InputProperties properties) - { - previousTouchesState = currentTouchesState; - previousButtonsState = currentButtonsState; - previousTrigger = currentTrigger; - previousGrip = currentGrip; - - if (!properties.Valid) - { - currentTrigger = 0.0f; - currentGrip = 0.0f; - currentTouchesState = 0; - currentButtonsState = 0; - currentThumbstick = Vector2.Zero; - currentTrigger = 0.0f; - currentGrip = 0.0f; - return; - } - - currentTrigger = hand == TouchControllerHand.Left ? properties.IndexTriggerLeft : properties.IndexTriggerRight; - currentGrip = hand == TouchControllerHand.Left ? properties.HandTriggerLeft : properties.HandTriggerRight; - currentTouchesState = properties.Touches; - currentButtonsState = properties.Buttons; - currentThumbstick = hand == TouchControllerHand.Left ? properties.ThumbstickLeft : properties.ThumbstickRight; - } - - internal void UpdatePoses(ref OculusOvr.PosesProperties properties) - { - if (hand == TouchControllerHand.Left) - { - currentPos = properties.PosLeftHand; - currentRot = properties.RotLeftHand; - currentLinearVelocity = properties.LinearVelocityLeftHand; - currentAngularVelocity = new Vector3(MathUtil.DegreesToRadians(properties.AngularVelocityLeftHand.X), MathUtil.DegreesToRadians(properties.AngularVelocityLeftHand.Y), MathUtil.DegreesToRadians(properties.AngularVelocityLeftHand.Z)); - if ((properties.StateLeftHand & 0x0001) == 0x0001) - { - currentState = DeviceState.OutOfRange; - - if ((properties.StateLeftHand & 0x0002) == 0x0002) - { - currentState = DeviceState.Valid; - } - } - else - { - currentState = DeviceState.Invalid; - } - } - else - { - currentPos = properties.PosRightHand; - currentRot = properties.RotRightHand; - currentLinearVelocity = properties.LinearVelocityRightHand; - currentAngularVelocity = new Vector3(MathUtil.DegreesToRadians(properties.AngularVelocityRightHand.X), MathUtil.DegreesToRadians(properties.AngularVelocityRightHand.Y), MathUtil.DegreesToRadians(properties.AngularVelocityRightHand.Z)); - if ((properties.StateRightHand & 0x0001) == 0x0001) - { - currentState = DeviceState.OutOfRange; - - if ((properties.StateRightHand & 0x0002) == 0x0002) - { - currentState = DeviceState.Valid; - } - } - else - { - currentState = DeviceState.Invalid; - } - } - } - - public override bool IsPressedDown(TouchControllerButton button) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - var thumbFlag = hand == TouchControllerHand.Left ? 0x00000400 : 0x00000004; - //ovrButton_RThumb - return (previousButtonsState & thumbFlag) != thumbFlag && (currentButtonsState & thumbFlag) == thumbFlag; - case TouchControllerButton.A: - //ovrButton_A - return (previousButtonsState & 0x00000001) != 0x00000001 && (currentButtonsState & 0x00000001) == 0x00000001; - case TouchControllerButton.B: - //ovrButton_B - return (previousButtonsState & 0x00000002) != 0x00000002 && (currentButtonsState & 0x00000002) == 0x00000002; - case TouchControllerButton.X: - //ovrButton_X - return (previousButtonsState & 0x00000100) != 0x00000100 && (currentButtonsState & 0x00000100) == 0x00000100; - case TouchControllerButton.Y: - //ovrButton_Y - return (previousButtonsState & 0x00000200) != 0x00000200 && (currentButtonsState & 0x00000200) == 0x00000200; - case TouchControllerButton.Trigger: - return previousTrigger <= TriggerAndGripDeadzone && currentTrigger > TriggerAndGripDeadzone; - case TouchControllerButton.Grip: - return previousGrip <= TriggerAndGripDeadzone && currentGrip > TriggerAndGripDeadzone; - case TouchControllerButton.Menu: - return (previousButtonsState & 0x00100000) != 0x00100000 && (currentButtonsState & 0x00100000) == 0x00100000; - default: - return false; - } - } - - public override bool IsTouchedDown(TouchControllerButton button) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - var thumbFlag = hand == TouchControllerHand.Left ? 0x00000400 : 0x00000004; - //ovrButton_RThumb - return (previousTouchesState & thumbFlag) != thumbFlag && (currentTouchesState & thumbFlag) == thumbFlag; - case TouchControllerButton.A: - //ovrButton_A - return (previousTouchesState & 0x00000001) != 0x00000001 && (currentTouchesState & 0x00000001) == 0x00000001; - case TouchControllerButton.B: - //ovrButton_B - return (previousTouchesState & 0x00000002) != 0x00000002 && (currentTouchesState & 0x00000002) == 0x00000002; - case TouchControllerButton.X: - //ovrButton_X - return (previousTouchesState & 0x00000100) != 0x00000100 && (currentTouchesState & 0x00000100) == 0x00000100; - case TouchControllerButton.Y: - //ovrButton_Y - return (previousTouchesState & 0x00000200) != 0x00000200 && (currentTouchesState & 0x00000200) == 0x00000200; - case TouchControllerButton.Trigger: - return previousTrigger <= TriggerAndGripDeadzone && currentTrigger > TriggerAndGripDeadzone; - case TouchControllerButton.Grip: - return previousGrip <= TriggerAndGripDeadzone && currentGrip > TriggerAndGripDeadzone; - case TouchControllerButton.Menu: - return (previousTouchesState & 0x00100000) != 0x00100000 && (currentTouchesState & 0x00100000) == 0x00100000; - default: - return false; - } - } - - public override bool IsPressed(TouchControllerButton button) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - var thumbFlag = hand == TouchControllerHand.Left ? 0x00000400 : 0x00000004; - //ovrButton_RThumb - return (currentButtonsState & thumbFlag) == thumbFlag; - case TouchControllerButton.A: - //ovrButton_A - return (currentButtonsState & 0x00000001) == 0x00000001; - case TouchControllerButton.B: - //ovrButton_B - return (currentButtonsState & 0x00000002) == 0x00000002; - case TouchControllerButton.X: - //ovrButton_X - return (currentButtonsState & 0x00000100) == 0x00000100; - case TouchControllerButton.Y: - //ovrButton_Y - return (currentButtonsState & 0x00000200) == 0x00000200; - case TouchControllerButton.Trigger: - return currentTrigger > TriggerAndGripDeadzone; - case TouchControllerButton.Grip: - return currentGrip > TriggerAndGripDeadzone; - case TouchControllerButton.Menu: - return (currentButtonsState & 0x00100000) == 0x00100000; - default: - return false; - } - } - - public override bool IsTouched(TouchControllerButton button) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - var thumbFlag = hand == TouchControllerHand.Left ? 0x00000400 : 0x00000004; - //ovrButton_RThumb - return (currentTouchesState & thumbFlag) == thumbFlag; - case TouchControllerButton.A: - //ovrButton_A - return (currentTouchesState & 0x00000001) == 0x00000001; - case TouchControllerButton.B: - //ovrButton_B - return (currentTouchesState & 0x00000002) == 0x00000002; - case TouchControllerButton.X: - //ovrButton_X - return (currentTouchesState & 0x00000100) == 0x00000100; - case TouchControllerButton.Y: - //ovrButton_Y - return (currentTouchesState & 0x00000200) == 0x00000200; - case TouchControllerButton.Trigger: - return currentTrigger > TriggerAndGripDeadzone; - case TouchControllerButton.Grip: - return currentGrip > TriggerAndGripDeadzone; - case TouchControllerButton.Menu: - return (currentTouchesState & 0x00100000) == 0x00100000; - default: - return false; - } - } - - public override bool IsPressReleased(TouchControllerButton button) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - var thumbFlag = hand == TouchControllerHand.Left ? 0x00000400 : 0x00000004; - //ovrButton_RThumb - return (previousButtonsState & thumbFlag) == thumbFlag && (currentButtonsState & thumbFlag) != thumbFlag; - case TouchControllerButton.A: - //ovrButton_A - return (previousButtonsState & 0x00000001) == 0x00000001 && (currentButtonsState & 0x00000001) != 0x00000001; - case TouchControllerButton.B: - //ovrButton_B - return (previousButtonsState & 0x00000002) == 0x00000002 && (currentButtonsState & 0x00000002) != 0x00000002; - case TouchControllerButton.X: - //ovrButton_X - return (previousButtonsState & 0x00000100) == 0x00000100 && (currentButtonsState & 0x00000100) != 0x00000100; - case TouchControllerButton.Y: - //ovrButton_Y - return (previousButtonsState & 0x00000200) == 0x00000200 && (currentButtonsState & 0x00000200) != 0x00000200; - case TouchControllerButton.Trigger: - return previousTrigger > TriggerAndGripDeadzone && currentTrigger <= TriggerAndGripDeadzone; - case TouchControllerButton.Grip: - return previousGrip > TriggerAndGripDeadzone && currentGrip <= TriggerAndGripDeadzone; - case TouchControllerButton.Menu: - return (previousButtonsState & 0x00100000) == 0x00100000 && (currentButtonsState & 0x00100000) != 0x00100000; - default: - return false; - } - } - - public override bool IsTouchReleased(TouchControllerButton button) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - var thumbFlag = hand == TouchControllerHand.Left ? 0x00000400 : 0x00000004; - //ovrButton_RThumb - return (previousTouchesState & thumbFlag) == thumbFlag && (currentTouchesState & thumbFlag) != thumbFlag; - case TouchControllerButton.A: - //ovrButton_A - return (previousTouchesState & 0x00000001) == 0x00000001 && (currentTouchesState & 0x00000001) != 0x00000001; - case TouchControllerButton.B: - //ovrButton_B - return (previousTouchesState & 0x00000002) == 0x00000002 && (currentTouchesState & 0x00000002) != 0x00000002; - case TouchControllerButton.X: - //ovrButton_X - return (previousTouchesState & 0x00000100) == 0x00000100 && (currentTouchesState & 0x00000100) != 0x00000100; - case TouchControllerButton.Y: - //ovrButton_Y - return (previousTouchesState & 0x00000200) == 0x00000200 && (currentTouchesState & 0x00000200) != 0x00000200; - case TouchControllerButton.Trigger: - return previousTrigger > TriggerAndGripDeadzone && currentTrigger <= TriggerAndGripDeadzone; - case TouchControllerButton.Grip: - return previousGrip > TriggerAndGripDeadzone && currentGrip <= TriggerAndGripDeadzone; - case TouchControllerButton.Menu: - return (previousTouchesState & 0x00100000) == 0x00100000 && (currentTouchesState & 0x00100000) != 0x00100000; - default: - return false; - } - } - - public override bool Vibrate(float amount = 1f) - { - // not implemented for oculus SDK (use OpenVR instead) - return false; - } - } -} diff --git a/sources/engine/Xenko.VirtualReality/WindowsMixedReality/SystemNumericsExtensions.cs b/sources/engine/Xenko.VirtualReality/WindowsMixedReality/SystemNumericsExtensions.cs deleted file mode 100644 index f578d012e5..0000000000 --- a/sources/engine/Xenko.VirtualReality/WindowsMixedReality/SystemNumericsExtensions.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_PLATFORM_UWP - -using Xenko.Core.Mathematics; - -namespace Xenko.VirtualReality -{ - internal static class SystemNumericsExtensions - { - /// - /// Performs a conversion from to . - /// - /// The value. - /// The result of the conversion. - public static Matrix ToMatrix(this System.Numerics.Matrix4x4 value) - { - return new Matrix() - { - M11 = value.M11, M12 = value.M12, M13 = value.M13, M14 = value.M14, - M21 = value.M21, M22 = value.M22, M23 = value.M23, M24 = value.M24, - M31 = value.M31, M32 = value.M32, M33 = value.M33, M34 = value.M34, - M41 = value.M41, M42 = value.M42, M43 = value.M43, M44 = value.M44 - }; - } - - /// - /// Performs a conversion from to . - /// - /// The value. - /// The result of the conversion. - public static Quaternion ToQuaternion(this System.Numerics.Quaternion value) - { - return new Quaternion(value.X, value.Y, value.Z, value.W); - } - - /// - /// Performs a conversion from to . - /// - /// The value. - /// The result of the conversion. - public static Vector3 ToVector3(this System.Numerics.Vector3 value) - { - return new Vector3(value.X, value.Y, value.Z); - } - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityHmd.cs b/sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityHmd.cs deleted file mode 100644 index c16f652020..0000000000 --- a/sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityHmd.cs +++ /dev/null @@ -1,201 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_DIRECT3D11 && XENKO_PLATFORM_UWP - -using Windows.Graphics.DirectX.Direct3D11; -using Windows.Graphics.Holographic; -using Windows.Perception.Spatial; -using Windows.UI.Input.Spatial; -using Xenko.Core.Mathematics; -using Xenko.Games; -using Xenko.Graphics; - -namespace Xenko.VirtualReality -{ - internal class WindowsMixedRealityHmd : VRDevice - { - private Matrix currentView = Matrix.Identity; - private WindowsMixedRealityGraphicsPresenter graphicsPresenter; - private HolographicCamera holographicCamera; - private HolographicSpace holographicSpace; - private SpatialInteractionManager interactionManager; - private DeviceState internalState; - private WindowsMixedRealityTouchController leftHandController; - private WindowsMixedRealityTouchController rightHandController; - private SpatialLocation spatialLocation; - private SpatialLocator spatialLocator; - private SpatialStationaryFrameOfReference stationaryReferenceFrame; - - public WindowsMixedRealityHmd() - { - VRApi = VRApi.WindowsMixedReality; - SupportsOverlays = false; - } - - public override Size2 OptimalRenderFrameSize => ActualRenderFrameSize; - - public override Size2 ActualRenderFrameSize - { - get => new Size2((int)holographicCamera.RenderTargetSize.Width * 2, (int)holographicCamera.RenderTargetSize.Height); - protected set { } - } - - public override Texture MirrorTexture { get; protected set; } - - public override float RenderFrameScaling - { - get => (float)holographicCamera.ViewportScaleFactor; - set { if (holographicCamera != null) holographicCamera.ViewportScaleFactor = value; } - } - - public override DeviceState State => internalState; - - public override Vector3 HeadPosition => spatialLocation.Position.ToVector3(); - - public override Quaternion HeadRotation => spatialLocation.Orientation.ToQuaternion(); - - public override Vector3 HeadLinearVelocity => spatialLocation.AbsoluteLinearVelocity.ToVector3(); - - public override Vector3 HeadAngularVelocity => spatialLocation.AbsoluteAngularVelocity.ToQuaternion().YawPitchRoll; - - public override TouchController LeftHand => leftHandController; - - public override TouchController RightHand => rightHandController; - - public override TrackedItem[] TrackedItems => new TrackedItem[0]; - - public override bool CanInitialize => true; - - public override void Commit(CommandList commandList, Texture renderFrame) - { - // On versions of the platform that support the CommitDirect3D11DepthBuffer API, we can - // provide the depth buffer to the system, and it will use depth information to stabilize - // the image at a per-pixel level. - var pose = graphicsPresenter.HolographicFrame.CurrentPrediction.CameraPoses[0]; - HolographicCameraRenderingParameters renderingParameters = graphicsPresenter.HolographicFrame.GetRenderingParameters(pose); - SharpDX.Direct3D11.Texture2D depthBuffer = new SharpDX.Direct3D11.Texture2D(commandList.DepthStencilBuffer.NativeResource.NativePointer); - - // Direct3D interop APIs are used to provide the buffer to the WinRT API. - SharpDX.DXGI.Resource1 depthStencilResource = depthBuffer.QueryInterface(); - SharpDX.DXGI.Surface2 depthDxgiSurface = new SharpDX.DXGI.Surface2(depthStencilResource, 0); - IDirect3DSurface depthD3DSurface = WindowsMixedRealityGraphicsPresenter.CreateDirect3DSurface(depthDxgiSurface.NativePointer); - - if (depthD3DSurface != null) - { - // Calling CommitDirect3D11DepthBuffer causes the system to queue Direct3D commands to - // read the depth buffer. It will then use that information to stabilize the image as - // the HolographicFrame is presented. - renderingParameters.CommitDirect3D11DepthBuffer(depthD3DSurface); - } - } - - public override void Draw(GameTime gameTime) - { - } - - public override void Enable(GraphicsDevice device, GraphicsDeviceManager graphicsDeviceManager, bool requireMirror, int mirrorWidth, int mirrorHeight) - { - HolographicSpace.IsAvailableChanged += HolographicSpace_IsAvailableChanged; - HolographicSpace_IsAvailableChanged(null, null); - - graphicsPresenter = device.Presenter as WindowsMixedRealityGraphicsPresenter; - - holographicSpace = graphicsPresenter.NativePresenter as HolographicSpace; - holographicCamera = graphicsPresenter.HolographicFrame.CurrentPrediction.CameraPoses[0].HolographicCamera; - - interactionManager = SpatialInteractionManager.GetForCurrentView(); - - leftHandController = new WindowsMixedRealityTouchController(TouchControllerHand.Left, interactionManager); - rightHandController = new WindowsMixedRealityTouchController(TouchControllerHand.Right, interactionManager); - - MirrorTexture = graphicsPresenter.BackBuffer; - } - - public override void ReadEyeParameters(Eyes eye, float near, float far, ref Vector3 cameraPosition, ref Matrix cameraRotation, bool ignoreHeadRotation, bool ignoreHeadPosition, out Matrix view, out Matrix projection) - { - var cameraPose = graphicsPresenter.HolographicFrame.CurrentPrediction.CameraPoses[0]; - - cameraPose.HolographicCamera.SetNearPlaneDistance(near); - cameraPose.HolographicCamera.SetFarPlaneDistance(far); - - var viewTransform = cameraPose.TryGetViewTransform(stationaryReferenceFrame.CoordinateSystem); - - if (viewTransform.HasValue) - { - currentView = eye == Eyes.Left - ? viewTransform.Value.Left.ToMatrix() - : viewTransform.Value.Right.ToMatrix(); - } - - if (ignoreHeadPosition) - { - currentView.TranslationVector = Vector3.Zero; - } - - if (ignoreHeadRotation) - { - // keep the scale just in case - currentView.Row1 = new Vector4(currentView.Row1.Length(), 0, 0, 0); - currentView.Row2 = new Vector4(0, currentView.Row2.Length(), 0, 0); - currentView.Row3 = new Vector4(0, 0, currentView.Row3.Length(), 0); - } - - view = Matrix.Translation(-cameraPosition) * cameraRotation * currentView; - - projection = eye == Eyes.Left - ? cameraPose.ProjectionTransform.Left.ToMatrix() - : cameraPose.ProjectionTransform.Right.ToMatrix(); - } - - public override void Update(GameTime gameTime) - { - HolographicFramePrediction prediction = graphicsPresenter.HolographicFrame.CurrentPrediction; - - SpatialCoordinateSystem coordinateSystem = stationaryReferenceFrame.CoordinateSystem; - spatialLocation = spatialLocator.TryLocateAtTimestamp(prediction.Timestamp, coordinateSystem); - - leftHandController.Update(prediction.Timestamp, coordinateSystem); - rightHandController.Update(prediction.Timestamp, coordinateSystem); - } - - private void HolographicSpace_IsAvailableChanged(object sender, object e) - { - internalState = HolographicSpace.IsAvailable ? DeviceState.Valid : DeviceState.Invalid; - - HolographicDisplay holographicDisplay = HolographicDisplay.GetDefault(); - SpatialLocator newSpatialLocator = holographicDisplay?.SpatialLocator; - - if (spatialLocator != newSpatialLocator) - { - if (spatialLocator != null) - { - spatialLocator.LocatabilityChanged -= SpatialLocator_LocatabilityChanged; - spatialLocator = null; - } - - if (newSpatialLocator != null) - { - spatialLocator = newSpatialLocator; - spatialLocator.LocatabilityChanged += SpatialLocator_LocatabilityChanged; - stationaryReferenceFrame = spatialLocator.CreateStationaryFrameOfReferenceAtCurrentLocation(); - } - } - } - - private void SpatialLocator_LocatabilityChanged(SpatialLocator sender, object args) - { - switch (sender.Locatability) - { - case SpatialLocatability.Unavailable: - internalState = DeviceState.Invalid; - break; - default: - internalState = DeviceState.Valid; - break; - } - } - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityTouchController.cs b/sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityTouchController.cs deleted file mode 100644 index db24da438e..0000000000 --- a/sources/engine/Xenko.VirtualReality/WindowsMixedReality/WindowsMixedRealityTouchController.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_DIRECT3D11 && XENKO_PLATFORM_UWP - -using Windows.Perception; -using Windows.Perception.Spatial; -using Windows.UI.Input.Spatial; -using Xenko.Core.Mathematics; - -namespace Xenko.VirtualReality -{ - internal class WindowsMixedRealityTouchController : TouchController - { - private readonly SpatialInteractionSourceHandedness hand; - private readonly SpatialInteractionManager interactionManager; - - private Vector3 currentAngularVelocity; - private Vector3 currentLinearVelocity; - private Vector3 currentPosition; - private Quaternion currentRotation = Quaternion.Identity; - private SpatialInteractionSourceState currentState; - private DeviceState internalState; - private SpatialInteractionSourceState previousState; - - internal WindowsMixedRealityTouchController(TouchControllerHand hand, SpatialInteractionManager interactionManager) - { - this.hand = (SpatialInteractionSourceHandedness)(hand + 1); - this.interactionManager = interactionManager; - - interactionManager.SourceLost += InteractionManager_SourceLost; - } - - public override Vector3 Position => currentPosition; - - public override Quaternion Rotation => currentRotation; - - public override Vector3 LinearVelocity => currentLinearVelocity; - - public override Vector3 AngularVelocity => currentAngularVelocity; - - public override DeviceState State => internalState; - - public override float Trigger => (float)currentState.SelectPressedValue; - - public override float Grip => currentState.IsGrasped ? 1.0f : 0.0f; - - public override bool IndexPointing => false; - - public override bool IndexResting => true; - - public override bool ThumbUp => !currentState.ControllerProperties.IsTouchpadTouched; - - public override bool ThumbResting => currentState.ControllerProperties.IsTouchpadTouched; - - public override Vector2 ThumbAxis => new Vector2((float)currentState.ControllerProperties.TouchpadX, (float)currentState.ControllerProperties.TouchpadY); - - public override Vector2 ThumbstickAxis => new Vector2((float)currentState.ControllerProperties.ThumbstickX, (float)currentState.ControllerProperties.ThumbstickY); - - public override bool IsPressed(TouchControllerButton button) => IsButtonPressed(button, currentState); - - public override bool IsPressedDown(TouchControllerButton button) => !IsButtonPressed(button, previousState) ? IsButtonPressed(button, currentState) : false; - - public override bool IsPressReleased(TouchControllerButton button) => IsButtonPressed(button, previousState) ? !IsButtonPressed(button, currentState) : false; - - public override bool IsTouched(TouchControllerButton button) => !IsButtonTouched(button, currentState); - - public override bool IsTouchedDown(TouchControllerButton button) => !IsButtonTouched(button, previousState) ? IsButtonTouched(button, currentState) : false; - - public override bool IsTouchReleased(TouchControllerButton button) => IsButtonTouched(button, previousState) ? !IsButtonTouched(button, currentState) : false; - - public void Update(PerceptionTimestamp timeStamp, SpatialCoordinateSystem coordinateSystem) - { - var states = interactionManager.GetDetectedSourcesAtTimestamp(timeStamp); - - foreach (SpatialInteractionSourceState state in states) - { - if (state.Source.Handedness == hand) - { - SpatialInteractionSourceLocation location = state.Properties.TryGetLocation(coordinateSystem); - - if (location != null) - { - SetSpatialInteractionSourceLocation(location); - } - - previousState = currentState; - currentState = state; - - internalState = previousState != null ? DeviceState.Valid : DeviceState.Invalid; - } - } - } - - private bool IsButtonPressed(TouchControllerButton button, SpatialInteractionSourceState state) - { - switch (button) - { - case TouchControllerButton.Thumbstick: - return state.ControllerProperties.IsThumbstickPressed; - case TouchControllerButton.Touchpad: - return state.ControllerProperties.IsTouchpadPressed; - case TouchControllerButton.A when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Right: - return ThumbAxis.X >= 0.0f; - case TouchControllerButton.B when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Right: - return ThumbAxis.X < 0.0f; - case TouchControllerButton.X when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Left: - return ThumbAxis.X < 0.0f; - case TouchControllerButton.Y when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Left: - return ThumbAxis.X >= 0.0f; - case TouchControllerButton.Trigger: - return state.IsSelectPressed; - case TouchControllerButton.Grip: - return state.IsGrasped; - case TouchControllerButton.Menu: - return state.IsMenuPressed; - default: - return false; - } - } - - private bool IsButtonTouched(TouchControllerButton button, SpatialInteractionSourceState state) - { - switch (button) - { - case TouchControllerButton.Touchpad: - return state.ControllerProperties.IsTouchpadTouched; - case TouchControllerButton.A when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Right: - return ThumbAxis.X >= 0.0f; - case TouchControllerButton.B when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Right: - return ThumbAxis.X < 0.0f; - case TouchControllerButton.X when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Left: - return ThumbAxis.X < 0.0f; - case TouchControllerButton.Y when state.ControllerProperties.IsTouchpadPressed && hand == SpatialInteractionSourceHandedness.Left: - return ThumbAxis.X >= 0.0f; - default: - return false; - } - } - - private void InteractionManager_SourceLost(SpatialInteractionManager sender, SpatialInteractionSourceEventArgs args) - { - if (args.State.Source.Handedness == hand) - { - internalState = DeviceState.Invalid; - - previousState = null; - currentState = null; - } - } - - private void SetSpatialInteractionSourceLocation(SpatialInteractionSourceLocation location) - { - currentPosition = location.Position?.ToVector3() ?? currentPosition; - currentRotation = location.Orientation?.ToQuaternion() ?? currentRotation; - currentLinearVelocity = location.Velocity?.ToVector3() ?? currentLinearVelocity; - currentAngularVelocity = location.AngularVelocity?.ToVector3() ?? currentAngularVelocity; - } - } -} - -#endif diff --git a/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj b/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj index dfaa06fe0d..ab5b0b4a2a 100644 --- a/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj +++ b/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj @@ -83,11 +83,6 @@ Designer - - - - - From 830765d972380319f0c39a400239f7d832453f2c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 3 Feb 2020 21:46:19 -0500 Subject: [PATCH 0702/2038] VR: More direct access to VR controller axis information --- .../OpenVR/OpenVrTouchController.cs | 13 +++++++++++-- .../engine/Xenko.VirtualReality/TouchController.cs | 12 ++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs index 94bf457a19..c6eae182eb 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs @@ -3,6 +3,7 @@ #if XENKO_GRAPHICS_API_VULKAN || XENKO_GRAPHICS_API_DIRECT3D11 using System; +using System.Runtime.CompilerServices; using Xenko.Core.Mathematics; using Xenko.Games; @@ -62,7 +63,7 @@ public override void Update(GameTime gameTime) public override float Trigger => controller?.GetAxis(OpenVR.Controller.ButtonId.ButtonSteamVrTrigger).X ?? 0.0f; - public override float Grip => controller?.GetPress(OpenVR.Controller.ButtonId.ButtonGrip) ?? false ? 1.0f : 0.0f; + public override float Grip => controller?.GetAxis(OpenVR.Controller.ButtonId.ButtonGrip).X ?? 0.0f; public override bool IndexPointing => !controller?.GetTouch(OpenVR.Controller.ButtonId.ButtonSteamVrTrigger) ?? false; //not so accurate @@ -74,7 +75,9 @@ public override void Update(GameTime gameTime) public override Vector2 ThumbAxis => controller?.GetAxis() ?? Vector2.Zero; - public override Vector2 ThumbstickAxis => controller?.GetAxis() ?? Vector2.Zero; + public override Vector2 ThumbstickAxis => controller?.GetAxis(OpenVR.Controller.ButtonId.ButtonAxis3) ?? Vector2.Zero; + + public override Vector2 CombinedThumbAxis => ThumbAxis + ThumbstickAxis; private OpenVR.Controller.ButtonId ToOpenVrButton(TouchControllerButton button) { @@ -130,6 +133,12 @@ public override bool Vibrate(float amount = 1f) return true; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public override Vector2 GetAxis(OpenVR.Controller.ButtonId button) + { + return controller?.GetAxis(button) ?? Vector2.Zero; + } + public override Vector3 Position => currentPos; public override Quaternion Rotation => currentRot; diff --git a/sources/engine/Xenko.VirtualReality/TouchController.cs b/sources/engine/Xenko.VirtualReality/TouchController.cs index b4db402ea7..f340b05558 100644 --- a/sources/engine/Xenko.VirtualReality/TouchController.cs +++ b/sources/engine/Xenko.VirtualReality/TouchController.cs @@ -38,6 +38,8 @@ public virtual void Update(GameTime time) public abstract Vector2 ThumbstickAxis { get; } + public abstract Vector2 CombinedThumbAxis { get; } + /// /// Vibrate the controller /// @@ -80,6 +82,16 @@ public virtual void Update(GameTime time) /// public abstract bool IsTouched(TouchControllerButton button); +#if XENKO_GRAPHICS_API_VULKAN || XENKO_GRAPHICS_API_DIRECT3D11 + + /// + /// Get a general axis result of the controller + /// + /// + /// + public abstract Vector2 GetAxis(OpenVR.Controller.ButtonId button); +#endif + /// /// Returns true if in this frame the button was released /// From 9f091bbf70b125b4ff09d56fb170ae86a6bdf755 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 3 Feb 2020 17:23:07 +0900 Subject: [PATCH 0703/2038] [Build] Updated Xenko.Voxels to use auto include for xksl/xkfx --- ...cs => VoxelVisualizationRawEffect.xksl.cs} | 0 ...cs => VoxelVisualizationRawShader.xksl.cs} | 0 ...s => VoxelVisualizationViewEffect.xksl.cs} | 0 ...s => VoxelVisualizationViewShader.xksl.cs} | 0 ... => XenkoForwardShadingEffectVXGI.xksl.cs} | 0 ...oxelEffect.cs => LightVoxelEffect.xksl.cs} | 0 ...oxelShader.cs => LightVoxelShader.xksl.cs} | 0 ...IVoxelSampler.cs => IVoxelSampler.xksl.cs} | 0 ...VoxelMarchSet.cs => VoxelMarchSet.xksl.cs} | 0 ...2.cs => VoxelMarchSetHemisphere12.xksl.cs} | 0 ...e6.cs => VoxelMarchSetHemisphere6.xksl.cs} | 0 ... => VoxelMarchSetRandomHemisphere.xksl.cs} | 0 ...hAttributes.cs => MarchAttributes.xksl.cs} | 0 ...ffect.cs => MarchAttributesEffect.xksl.cs} | 0 ...xelMarchBeam.cs => VoxelMarchBeam.xksl.cs} | 0 ...xelMarchCone.cs => VoxelMarchCone.xksl.cs} | 0 ...Mode.cs => VoxelMarchConeEditMode.xksl.cs} | 0 ...map.cs => VoxelMarchConePerMipmap.xksl.cs} | 0 ...archMethod.cs => VoxelMarchMethod.xksl.cs} | 0 ...thod.cs => VoxelRadiusMarchMethod.xksl.cs} | 0 ...xelAttribute.cs => VoxelAttribute.xksl.cs} | 0 ...tributeDirectionalCoverageSampler.xksl.cs} | 0 ...ttributeDirectionalCoverageShader.xksl.cs} | 0 ...xelAttributeEmissionOpacityShader.xksl.cs} | 0 ... => VoxelAttributeSoliditySampler.xksl.cs} | 0 ...s => VoxelAttributeSolidityShader.xksl.cs} | 0 ...sign.cs => VoxelBufferWriteAssign.xksl.cs} | 0 ...riteMax.cs => VoxelBufferWriteMax.xksl.cs} | 0 ...ferWriter.cs => VoxelBufferWriter.xksl.cs} | 0 .../{DataPacking.cs => DataPacking.xksl.cs} | 0 ...16.cs => VoxelFragmentPackFloat16.xksl.cs} | 0 ...32.cs => VoxelFragmentPackFloat32.xksl.cs} | 0 ...> VoxelFragmentPackFloatR11G11B10.xksl.cs} | 0 ...tPacker.cs => VoxelFragmentPacker.xksl.cs} | 0 ... => VoxelAnisotropicPairedSampler.xksl.cs} | 0 ...xelAnisotropicPairedWriter_Float4.xksl.cs} | 0 ...ler.cs => VoxelAnisotropicSampler.xksl.cs} | 0 ... => VoxelAnisotropicWriter_Float4.xksl.cs} | 0 ...mpler.cs => VoxelIsotropicSampler.xksl.cs} | 0 ...cs => VoxelIsotropicWriter_Float4.xksl.cs} | 0 ...t_Float4.cs => VoxelLayout_Float4.xksl.cs} | 0 ...> VoxelModifierApplierAnisotropic.xksl.cs} | 0 ...ierApplierAntiAliasingAnisotropic.xksl.cs} | 0 ...ModifierApplierOpacifyAnisotropic.xksl.cs} | 0 ...odifierApplierSolidifyAnisotropic.xksl.cs} | 0 ...lModifierApplierAnisotropicPaired.xksl.cs} | 0 ...lierAntiAliasingAnisotropicPaired.xksl.cs} | 0 ...rApplierSolidifyAnisotropicPaired.xksl.cs} | 0 ...ifierApplierAntiAliasingIsotropic.xksl.cs} | 0 ... => VoxelModifierApplierIsotropic.xksl.cs} | 0 ...elModifierApplierOpacifyIsotropic.xksl.cs} | 0 ...lModifierApplierSolidifyIsotropic.xksl.cs} | 0 ...otropic.cs => VoxelPositionStream.xksl.cs} | 0 .../LocalSamples.xksl.cs} | 0 .../Voxel2x2x2Mipmapper_AnisoXN.xksl.cs} | 0 ...cs => Voxel2x2x2Mipmapper_AnisoXP.xksl.cs} | 0 ...cs => Voxel2x2x2Mipmapper_AnisoYN.xksl.cs} | 0 ...cs => Voxel2x2x2Mipmapper_AnisoYP.xksl.cs} | 0 ...cs => Voxel2x2x2Mipmapper_AnisoZN.xksl.cs} | 0 ...cs => Voxel2x2x2Mipmapper_AnisoZP.xksl.cs} | 0 ...x2x2Mipmap.cs => Voxel2x2x2Mipmap.xksl.cs} | 0 ...fect.cs => Voxel2x2x2MipmapEffect.xksl.cs} | 0 ...AnisoZP.cs => Voxel2x2x2Mipmapper.xksl.cs} | 0 ...s => Voxel2x2x2MipmapperHeuristic.xksl.cs} | 0 ...c.cs => Voxel2x2x2MipmapperSimple.xksl.cs} | 0 ...erToTexture.cs => BufferToTexture.xksl.cs} | 0 .../BufferToTextureColumns.xksl.cs} | 0 ...s => BufferToTextureColumnsEffect.xksl.cs} | 0 ...ffect.cs => BufferToTextureEffect.xksl.cs} | 0 .../{ClearBuffer.cs => ClearBuffer.xksl.cs} | 0 ...r.cs => VoxelStorageClipmapShader.xksl.cs} | 0 .../VoxelStorageShader.xksl.cs} | 0 ... VoxelStorageTextureClipmapShader.xksl.cs} | 0 .../VoxelStorageTextureShader.xksl.cs} | 0 .../Shader/VoxelizationMethod.xksl.cs} | 0 .../VoxelizationMethodDominantAxis.xksl.cs} | 0 .../Shader/VoxelizationMethodSingleAxis.cs | 9 - ...s => VoxelizationMethodSingleAxis.xksl.cs} | 0 .../Voxelization/VoxelizeToFragments.cs | 9 - ...antAxis.cs => VoxelizeToFragments.xksl.cs} | 0 ...t.cs => VoxelizeToFragmentsEffect.xksl.cs} | 0 .../engine/Xenko.Voxels/Xenko.Voxels.csproj | 826 +----------------- 82 files changed, 1 insertion(+), 843 deletions(-) rename sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/{VoxelVisualizationRawEffect.cs => VoxelVisualizationRawEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/{VoxelVisualizationRawShader.cs => VoxelVisualizationRawShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/{VoxelVisualizationViewEffect.cs => VoxelVisualizationViewEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/{VoxelVisualizationViewShader.cs => VoxelVisualizationViewShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/{XenkoForwardShadingEffectVXGI.cs => XenkoForwardShadingEffectVXGI.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Light/{LightVoxelEffect.cs => LightVoxelEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Light/{LightVoxelShader.cs => LightVoxelShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/{IVoxelSampler.cs => IVoxelSampler.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/{VoxelMarchSet.cs => VoxelMarchSet.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/{VoxelMarchSetHemisphere12.cs => VoxelMarchSetHemisphere12.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/{VoxelMarchSetHemisphere6.cs => VoxelMarchSetHemisphere6.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/{VoxelMarchSetRandomHemisphere.cs => VoxelMarchSetRandomHemisphere.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{MarchAttributes.cs => MarchAttributes.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{MarchAttributesEffect.cs => MarchAttributesEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{VoxelMarchBeam.cs => VoxelMarchBeam.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{VoxelMarchCone.cs => VoxelMarchCone.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{VoxelMarchConeEditMode.cs => VoxelMarchConeEditMode.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{VoxelMarchConePerMipmap.cs => VoxelMarchConePerMipmap.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{VoxelMarchMethod.cs => VoxelMarchMethod.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/{VoxelRadiusMarchMethod.cs => VoxelRadiusMarchMethod.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/{VoxelAttribute.cs => VoxelAttribute.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/{VoxelAttributeDirectionalCoverageSampler.cs => VoxelAttributeDirectionalCoverageSampler.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/{VoxelAttributeDirectionalCoverageShader.cs => VoxelAttributeDirectionalCoverageShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/{VoxelAttributeEmissionOpacityShader.cs => VoxelAttributeEmissionOpacityShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/{VoxelAttributeSoliditySampler.cs => VoxelAttributeSoliditySampler.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/{VoxelAttributeSolidityShader.cs => VoxelAttributeSolidityShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/{VoxelBufferWriteAssign.cs => VoxelBufferWriteAssign.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/{VoxelBufferWriteMax.cs => VoxelBufferWriteMax.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/{VoxelBufferWriter.cs => VoxelBufferWriter.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/{DataPacking.cs => DataPacking.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/{VoxelFragmentPackFloat16.cs => VoxelFragmentPackFloat16.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/{VoxelFragmentPackFloat32.cs => VoxelFragmentPackFloat32.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/{VoxelFragmentPackFloatR11G11B10.cs => VoxelFragmentPackFloatR11G11B10.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/{VoxelFragmentPacker.cs => VoxelFragmentPacker.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelAnisotropicPairedSampler.cs => VoxelAnisotropicPairedSampler.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelAnisotropicPairedWriter_Float4.cs => VoxelAnisotropicPairedWriter_Float4.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelAnisotropicSampler.cs => VoxelAnisotropicSampler.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelAnisotropicWriter_Float4.cs => VoxelAnisotropicWriter_Float4.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelIsotropicSampler.cs => VoxelIsotropicSampler.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelIsotropicWriter_Float4.cs => VoxelIsotropicWriter_Float4.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/{VoxelLayout_Float4.cs => VoxelLayout_Float4.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/{VoxelModifierApplierAnisotropic.cs => VoxelModifierApplierAnisotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/{VoxelModifierApplierAntiAliasingAnisotropic.cs => VoxelModifierApplierAntiAliasingAnisotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/{VoxelModifierApplierOpacifyAnisotropic.cs => VoxelModifierApplierOpacifyAnisotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/{VoxelModifierApplierSolidifyAnisotropic.cs => VoxelModifierApplierSolidifyAnisotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/{VoxelModifierApplierAnisotropicPaired.cs => VoxelModifierApplierAnisotropicPaired.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/{VoxelModifierApplierAntiAliasingAnisotropicPaired.cs => VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/{VoxelModifierApplierOpacifyAnisotropicPaired.cs => VoxelModifierApplierSolidifyAnisotropicPaired.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/{AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs => Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/{VoxelModifierApplierAntiAliasingIsotropic.cs => VoxelModifierApplierIsotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/{VoxelModifierApplierOpacifyIsotropic.cs => VoxelModifierApplierOpacifyIsotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/{VoxelModifierApplierIsotropic.cs => VoxelModifierApplierSolidifyIsotropic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/{Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs => VoxelPositionStream.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/{VoxelPositionStream.cs => VoxelStorage/LocalSamples.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/{LocalSamples.cs => Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/{Voxel2x2x2Mipmapper_AnisoXN.cs => Voxel2x2x2Mipmapper_AnisoXP.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/{Voxel2x2x2Mipmapper_AnisoXP.cs => Voxel2x2x2Mipmapper_AnisoYN.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/{Voxel2x2x2Mipmapper_AnisoYN.cs => Voxel2x2x2Mipmapper_AnisoYP.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/{Voxel2x2x2Mipmapper_AnisoYP.cs => Voxel2x2x2Mipmapper_AnisoZN.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/{Voxel2x2x2Mipmapper_AnisoZN.cs => Voxel2x2x2Mipmapper_AnisoZP.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{Voxel2x2x2Mipmap.cs => Voxel2x2x2Mipmap.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{Voxel2x2x2MipmapEffect.cs => Voxel2x2x2MipmapEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs => Voxel2x2x2Mipmapper.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{Voxel2x2x2Mipmapper.cs => Voxel2x2x2MipmapperHeuristic.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/{Voxel2x2x2MipmapperHeuristic.cs => Voxel2x2x2MipmapperSimple.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/{BufferToTexture.cs => BufferToTexture.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/{Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs => Processing/BufferToTextureColumns.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/{BufferToTextureColumnsEffect.cs => BufferToTextureColumnsEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/{BufferToTextureEffect.cs => BufferToTextureEffect.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/{ClearBuffer.cs => ClearBuffer.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/{VoxelStorageClipmapShader.cs => VoxelStorageClipmapShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/{Mipmapping/Voxel2x2x2MipmapperSimple.cs => Shaders/VoxelStorageShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/{VoxelStorageTextureClipmapShader.cs => VoxelStorageTextureClipmapShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/{Processing/BufferToTextureColumns.cs => Shaders/VoxelStorageTextureShader.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/{VoxelStorage/Shaders/VoxelStorageShader.cs => VoxelizationMethod/Shader/VoxelizationMethod.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/{VoxelStorage/Shaders/VoxelStorageTextureShader.cs => VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs rename sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/{VoxelizationMethod.cs => VoxelizationMethodSingleAxis.xksl.cs} (100%) delete mode 100644 sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs rename sources/engine/Xenko.Voxels/Voxels/Voxelization/{VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs => VoxelizeToFragments.xksl.cs} (100%) rename sources/engine/Xenko.Voxels/Voxels/Voxelization/{VoxelizeToFragmentsEffect.cs => VoxelizeToFragmentsEffect.xksl.cs} (100%) diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.cs rename to sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationRawShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.cs rename to sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DebugVisualizations/Shaders/VoxelVisualizationViewShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.cs rename to sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/XenkoForwardShadingEffectVXGI.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/IVoxelSampler.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSet.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere12.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetHemisphere6.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/MarchSets/Shaders/VoxelMarchSetRandomHemisphere.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributes.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/MarchAttributesEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchBeam.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchCone.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConeEditMode.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchConePerMipmap.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelMarchMethod.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.cs rename to sources/engine/Xenko.Voxels/Voxels/Marching/Shaders/VoxelRadiusMarchMethod.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttribute.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageSampler.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeDirectionalCoverageShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeEmissionOpacityShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSoliditySampler.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Attributes/Shaders/VoxelAttributeSolidityShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteAssign.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriteMax.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/BufferWriters/Shaders/VoxelBufferWriter.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/DataPacking.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat16.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloat32.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPackFloatR11G11B10.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/FragmentPackers/Shaders/VoxelFragmentPacker.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedSampler.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicPairedWriter_Float4.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicSampler.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelAnisotropicWriter_Float4.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicSampler.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelIsotropicWriter_Float4.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/Shaders/VoxelLayout_Float4.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAnisotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierAntiAliasingAnisotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierOpacifyAnisotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Anisotropic/VoxelModifierApplierSolidifyAnisotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAnisotropicPaired.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierAntiAliasingAnisotropicPaired.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierOpacifyAnisotropicPaired.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/AnisotropicPaired/VoxelModifierApplierSolidifyAnisotropicPaired.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierAntiAliasingIsotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierOpacifyIsotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierIsotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/Modifiers/Appliers/Isotropic/VoxelModifierApplierSolidifyIsotropic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelPositionStream.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/LocalSamples.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXN.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoXP.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYN.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoYP.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZN.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmap.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Anisotropic/Voxel2x2x2Mipmapper_AnisoZP.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2Mipmapper.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperHeuristic.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTexture.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperPhysicallyBased.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumnsEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/ClearBuffer.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageClipmapShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Mipmapping/Voxel2x2x2MipmapperSimple.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureClipmapShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Processing/BufferToTextureColumns.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelStorage/Shaders/VoxelStorageTextureShader.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs deleted file mode 100644 index 274fe38f51..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethod.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodSingleAxis.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs deleted file mode 100644 index 274fe38f51..0000000000 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// Do not edit this file yourself! -// -// This code was generated by Xenko Shader Mixin Code Generator. -// To generate it yourself, please install Xenko.VisualStudio.Package .vsix -// and re-save the associated .xkfx. -// - -// Nothing to generate diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizationMethod/Shader/VoxelizationMethodDominantAxis.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragments.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.xksl.cs similarity index 100% rename from sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.cs rename to sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelizeToFragmentsEffect.xksl.cs diff --git a/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj b/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj index 702538bdf0..6c5c5749ba 100644 --- a/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj +++ b/sources/engine/Xenko.Voxels/Xenko.Voxels.csproj @@ -1,4 +1,4 @@ - + true true @@ -26,830 +26,6 @@ - - - True - True - True - VoxelVisualizationRawEffect.xksl - - - True - True - True - VoxelVisualizationRawShader.xksl - - - True - True - True - VoxelVisualizationViewEffect.xksl - - - True - True - True - VoxelVisualizationViewShader.xksl - - - True - True - True - LightVoxelEffect.xksl - - - True - True - True - LightVoxelShader.xksl - - - True - True - True - VoxelMarchSet.xksl - - - True - True - True - VoxelMarchSetHemisphere12.xksl - - - True - True - True - VoxelMarchSetHemisphere6.xksl - - - True - True - True - VoxelMarchSetRandomHemisphere.xksl - - - True - True - True - MarchAttributes.xksl - - - True - True - True - MarchAttributesEffect.xksl - - - True - True - True - VoxelMarchBeam.xksl - - - True - True - True - VoxelMarchCone.xksl - - - True - True - True - VoxelMarchConeEditMode.xksl - - - True - True - True - VoxelMarchConeFast.xksl - - - True - True - True - VoxelMarchConePerMipmap.xksl - - - True - True - True - VoxelMarchMethod.xksl - - - True - True - True - VoxelRadiusMarchMethod.xksl - - - True - True - True - VoxelAttribute.xksl - - - True - True - True - VoxelAttributeDirectionalCoverageSampler.xksl - - - True - True - True - VoxelAttributeDirectionalCoverageShader.xksl - - - True - True - True - VoxelAttributeEmissionOpacityShader.xksl - - - True - True - True - VoxelAttributeSoliditySampler.xksl - - - True - True - True - VoxelAttributeSolidityShader.xksl - - - True - True - True - VoxelBufferWriteAssign.xksl - - - True - True - True - VoxelBufferWriteMax.xksl - - - True - True - True - VoxelBufferWriter.xksl - - - True - True - True - DataPacking.xksl - - - True - True - True - VoxelFragmentPacker.xksl - - - True - True - True - VoxelFragmentPackFloat16.xksl - - - True - True - True - VoxelFragmentPackFloat32.xksl - - - True - True - True - VoxelFragmentPackFloatR11G11B10.xksl - - - True - True - True - VoxelAnisotropicPairedSampler.xksl - - - True - True - True - VoxelAnisotropicPairedWriter_Float4.xksl - - - True - True - True - VoxelAnisotropicSampler.xksl - - - True - True - True - VoxelAnisotropicWriter_Float4.xksl - - - True - True - True - VoxelIsotropicSampler.xksl - - - True - True - True - VoxelIsotropicWriter_Float4.xksl - - - True - True - True - VoxelLayout_Float4.xksl - - - True - True - True - VoxelModifierApplierOpacifyAnisotropicPaired.xksl - - - True - True - True - VoxelModifierApplierSolidifyAnisotropicPaired.xksl - - - True - True - True - VoxelModifierApplierAnisotropic.xksl - - - True - True - True - VoxelModifierApplierAntiAliasingAnisotropic.xksl - - - True - True - True - VoxelModifierApplierOpacifyAnisotropic.xksl - - - True - True - True - VoxelModifierApplierSolidifyAnisotropic.xksl - - - True - True - True - VoxelModifierApplierAntiAliasingIsotropic.xksl - - - True - True - True - VoxelModifierApplierIsotropic.xksl - - - True - True - True - VoxelModifierApplierOpacifyIsotropic.xksl - - - True - True - True - VoxelModifierApplierSolidifyIsotropic.xksl - - - True - True - True - VoxelModifier.xksl - - - True - True - True - VoxelizationMethod.xksl - - - True - True - True - VoxelizationMethodDominantAxis.xksl - - - True - True - True - VoxelizationMethodSingleAxis.xksl - - - True - True - True - VoxelizeToFragments.xksl - - - True - True - True - VoxelizeToFragmentsEffect.xksl - - - True - True - True - VoxelPositionStream.xksl - - - True - True - True - LocalSamples.xksl - - - True - True - True - Voxel2x2x2Mipmapper_AnisoXN.xksl - - - True - True - True - Voxel2x2x2Mipmapper_AnisoXP.xksl - - - True - True - True - Voxel2x2x2Mipmapper_AnisoYN.xksl - - - True - True - True - Voxel2x2x2Mipmapper_AnisoYP.xksl - - - True - True - True - Voxel2x2x2Mipmapper_AnisoZN.xksl - - - True - True - True - Voxel2x2x2Mipmapper_AnisoZP.xksl - - - True - True - True - Voxel2x2x2Mipmap.xksl - - - True - True - True - Voxel2x2x2MipmapEffect.xksl - - - True - True - True - Voxel2x2x2Mipmapper.xksl - - - True - True - True - Voxel2x2x2MipmapperHeuristic.xksl - - - True - True - True - Voxel2x2x2MipmapperPhysicallyBased.xksl - - - True - True - True - Voxel2x2x2MipmapperSimple.xksl - - - True - True - True - VoxelMipmapHeuristic.xksl - - - True - True - True - VoxelMipmapPhysicallyBased.xksl - - - True - True - True - VoxelMipmapSimple.xksl - - - True - True - True - BufferToTexture.xksl - - - True - True - True - BufferToTextureColumns.xksl - - - True - True - True - BufferToTextureColumnsEffect.xksl - - - True - True - True - BufferToTextureEffect.xksl - - - True - True - True - ClearBuffer.xksl - - - True - True - True - VoxelStorageClipmapShader.xksl - - - True - True - True - VoxelStorageShader.xksl - - - True - True - True - VoxelStorageTextureClipmapShader.xksl - - - True - True - True - VoxelStorageTextureShader.xksl - - - - - XenkoShaderKeyGenerator - VoxelVisualizationRawEffect.cs - - - XenkoShaderKeyGenerator - VoxelVisualizationRawShader.cs - - - XenkoShaderKeyGenerator - VoxelVisualizationViewEffect.cs - - - XenkoShaderKeyGenerator - VoxelVisualizationViewShader.cs - - - XenkoShaderKeyGenerator - LightVoxelEffect.cs - - - XenkoShaderKeyGenerator - LightVoxelShader.cs - - - XenkoShaderKeyGenerator - VoxelMarchSet.cs - - - XenkoShaderKeyGenerator - VoxelMarchSetHemisphere12.cs - - - XenkoShaderKeyGenerator - VoxelMarchSetHemisphere6.cs - - - XenkoShaderKeyGenerator - VoxelMarchSetRandomHemisphere.cs - - - XenkoShaderKeyGenerator - MarchAttributes.cs - - - XenkoShaderKeyGenerator - MarchAttributesEffect.cs - - - XenkoShaderKeyGenerator - VoxelMarchBeam.cs - - - XenkoShaderKeyGenerator - VoxelMarchCone.cs - - - XenkoShaderKeyGenerator - VoxelMarchConeEditMode.cs - - - XenkoShaderKeyGenerator - VoxelMarchConeFast.cs - - - XenkoShaderKeyGenerator - VoxelMarchConePerMipmap.cs - - - XenkoShaderKeyGenerator - VoxelMarchMethod.cs - - - XenkoShaderKeyGenerator - VoxelRadiusMarchMethod.cs - - - XenkoShaderKeyGenerator - VoxelAttribute.cs - - - XenkoShaderKeyGenerator - VoxelAttributeDirectionalCoverageSampler.cs - - - XenkoShaderKeyGenerator - VoxelAttributeDirectionalCoverageShader.cs - - - XenkoShaderKeyGenerator - VoxelAttributeEmissionOpacityShader.cs - - - XenkoShaderKeyGenerator - VoxelAttributeSoliditySampler.cs - - - XenkoShaderKeyGenerator - VoxelAttributeSolidityShader.cs - - - XenkoShaderKeyGenerator - VoxelBufferWriteAssign.cs - - - XenkoShaderKeyGenerator - VoxelBufferWriteMax.cs - - - XenkoShaderKeyGenerator - VoxelBufferWriter.cs - - - XenkoShaderKeyGenerator - DataPacking.cs - - - XenkoShaderKeyGenerator - VoxelFragmentPacker.cs - - - XenkoShaderKeyGenerator - VoxelFragmentPackFloat16.cs - - - XenkoShaderKeyGenerator - VoxelFragmentPackFloat32.cs - - - XenkoShaderKeyGenerator - VoxelFragmentPackFloatR11G11B10.cs - - - XenkoShaderKeyGenerator - VoxelAnisotropicPairedSampler.cs - - - XenkoShaderKeyGenerator - VoxelAnisotropicPairedWriter_Float4.cs - - - XenkoShaderKeyGenerator - VoxelAnisotropicSampler.cs - - - XenkoShaderKeyGenerator - VoxelAnisotropicWriter_Float4.cs - - - XenkoShaderKeyGenerator - VoxelIsotropicSampler.cs - - - XenkoShaderKeyGenerator - VoxelIsotropicWriter_Float4.cs - - - XenkoShaderKeyGenerator - VoxelLayout_Float4.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierOpacifyAnisotropicPaired.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierSolidifyAnisotropicPaired.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierAnisotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierAntiAliasingAnisotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierOpacifyAnisotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierSolidifyAnisotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierAntiAliasingIsotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierIsotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierOpacifyIsotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifierApplierSolidifyIsotropic.cs - - - XenkoShaderKeyGenerator - VoxelModifier.cs - - - XenkoShaderKeyGenerator - VoxelizationMethod.cs - - - XenkoShaderKeyGenerator - VoxelizationMethodDominantAxis.cs - - - XenkoShaderKeyGenerator - VoxelizationMethodSingleAxis.cs - - - XenkoShaderKeyGenerator - VoxelizeToFragments.cs - - - XenkoShaderKeyGenerator - VoxelizeToFragmentsEffect.cs - - - XenkoShaderKeyGenerator - VoxelPositionStream.cs - - - XenkoShaderKeyGenerator - LocalSamples.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper_AnisoXN.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper_AnisoXP.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper_AnisoYN.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper_AnisoYP.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper_AnisoZN.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper_AnisoZP.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmap.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2MipmapEffect.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2Mipmapper.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2MipmapperHeuristic.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2MipmapperPhysicallyBased.cs - - - XenkoShaderKeyGenerator - Voxel2x2x2MipmapperSimple.cs - - - XenkoShaderKeyGenerator - VoxelMipmapHeuristic.cs - - - XenkoShaderKeyGenerator - VoxelMipmapPhysicallyBased.cs - - - XenkoShaderKeyGenerator - VoxelMipmapSimple.cs - - - XenkoShaderKeyGenerator - BufferToTexture.cs - - - XenkoShaderKeyGenerator - BufferToTextureColumns.cs - - - XenkoShaderKeyGenerator - BufferToTextureColumnsEffect.cs - - - XenkoShaderKeyGenerator - BufferToTextureEffect.cs - - - XenkoShaderKeyGenerator - ClearBuffer.cs - - - XenkoShaderKeyGenerator - VoxelStorageClipmapShader.cs - - - XenkoShaderKeyGenerator - VoxelStorageShader.cs - - - XenkoShaderKeyGenerator - VoxelStorageTextureClipmapShader.cs - - - XenkoShaderKeyGenerator - VoxelStorageTextureShader.cs - - \ No newline at end of file From 2b92b7908a1194d509b98503d9dc712e20d6a3c7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 4 Feb 2020 10:18:21 -0500 Subject: [PATCH 0704/2038] VR: fix build by cleaning up unused, removed library artifacts --- .../Xenko.VirtualReality/NativeInvoke.cs | 30 ----------------- .../OpenVR/OpenVrTouchController.cs | 4 +-- .../Xenko.VirtualReality/TouchController.cs | 5 +-- .../Xenko.Native.Libs.targets | 14 -------- .../Xenko.VirtualReality.csproj | 33 +------------------ .../Xenko.VirtualReality.dll.config | 4 --- 6 files changed, 4 insertions(+), 86 deletions(-) delete mode 100644 sources/engine/Xenko.VirtualReality/NativeInvoke.cs delete mode 100644 sources/engine/Xenko.VirtualReality/Xenko.Native.Libs.targets delete mode 100644 sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.dll.config diff --git a/sources/engine/Xenko.VirtualReality/NativeInvoke.cs b/sources/engine/Xenko.VirtualReality/NativeInvoke.cs deleted file mode 100644 index 0b0ea9e194..0000000000 --- a/sources/engine/Xenko.VirtualReality/NativeInvoke.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using Xenko.Core; - -namespace Xenko.VirtualReality -{ - internal static class NativeInvoke - { -#if XENKO_PLATFORM_IOS - internal const string Library = "__Internal"; -#else - internal const string Library = "libxenkovr"; -#endif - - internal static void PreLoad() - { -#if XENKO_PLATFORM_WINDOWS - NativeLibrary.PreloadLibrary(Library + ".dll", typeof(NativeInvoke)); -#else - NativeLibrary.PreloadLibrary(Library + ".so", typeof(NativeInvoke)); -#endif - } - - static NativeInvoke() - { - PreLoad(); - } - } -} diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs index c6eae182eb..a710e7ffcb 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs @@ -134,9 +134,9 @@ public override bool Vibrate(float amount = 1f) } [MethodImpl(MethodImplOptions.AggressiveInlining)] - public override Vector2 GetAxis(OpenVR.Controller.ButtonId button) + public override Vector2 GetAxis(int index) { - return controller?.GetAxis(button) ?? Vector2.Zero; + return controller?.GetAxis((OpenVR.Controller.ButtonId)(index + (int)OpenVR.Controller.ButtonId.ButtonAxis0)) ?? Vector2.Zero; } public override Vector3 Position => currentPos; diff --git a/sources/engine/Xenko.VirtualReality/TouchController.cs b/sources/engine/Xenko.VirtualReality/TouchController.cs index f340b05558..49b4be2e65 100644 --- a/sources/engine/Xenko.VirtualReality/TouchController.cs +++ b/sources/engine/Xenko.VirtualReality/TouchController.cs @@ -82,15 +82,12 @@ public virtual void Update(GameTime time) /// public abstract bool IsTouched(TouchControllerButton button); -#if XENKO_GRAPHICS_API_VULKAN || XENKO_GRAPHICS_API_DIRECT3D11 - /// /// Get a general axis result of the controller /// /// /// - public abstract Vector2 GetAxis(OpenVR.Controller.ButtonId button); -#endif + public abstract Vector2 GetAxis(int index); /// /// Returns true if in this frame the button was released diff --git a/sources/engine/Xenko.VirtualReality/Xenko.Native.Libs.targets b/sources/engine/Xenko.VirtualReality/Xenko.Native.Libs.targets deleted file mode 100644 index d6d394f1b3..0000000000 --- a/sources/engine/Xenko.VirtualReality/Xenko.Native.Libs.targets +++ /dev/null @@ -1,14 +0,0 @@ - - - - LibOVR.lib - - - - diff --git a/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj b/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj index ab5b0b4a2a..87ca7f9b82 100644 --- a/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj +++ b/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.csproj @@ -1,9 +1,8 @@ - + true true true - libxenkovr @@ -16,21 +15,6 @@ * true - - - - - - ..\..\..\deps\GoogleVR\lib\Android\GoogleVRJava.dll - - - - - - - - - @@ -77,21 +61,6 @@ Xenko.Input - - - - Designer - - - - - $(TargetsForTfmSpecificBuildOutput);IncludeExtraAssemblies - - - - - - \ No newline at end of file diff --git a/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.dll.config b/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.dll.config deleted file mode 100644 index bb70bca1d5..0000000000 --- a/sources/engine/Xenko.VirtualReality/Xenko.VirtualReality.dll.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - From 75640823ab2bff1c783d4f65f132baef70ae70c1 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 4 Feb 2020 15:31:09 -0500 Subject: [PATCH 0705/2038] Physics: instead of "skip at zero" option, have "skip a physics component" option "Zero" hits were not reliable or specific enough --- .../Xenko.Physics/Bepu/BepuSimulation.cs | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index deb5b0c59d..13b882cb1f 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -485,7 +485,7 @@ struct RayHitClosestHandler : IRayHitHandler public CollisionFilterGroupFlags findGroups; public float furthestHitSoFar, startLength; public BepuHitResult HitCollidable; - public bool skipAtZero; + public BepuPhysicsComponent skipComponent; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowTest(CollidableReference collidable) @@ -502,10 +502,11 @@ public bool AllowTest(CollidableReference collidable, int childIndex) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Numerics.Vector3 normal, CollidableReference collidable, int childIndex) { - if (skipAtZero && t <= float.Epsilon) return; - if (t < furthestHitSoFar) { + var component = getFromReference(collidable); + if (component == skipComponent) return; + //Cache the earliest impact. furthestHitSoFar = t; HitCollidable.HitFraction = t / startLength; @@ -515,7 +516,7 @@ public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Nume HitCollidable.Point.X = ray.Origin.X + ray.Direction.X * t; HitCollidable.Point.Y = ray.Origin.Y + ray.Direction.Y * t; HitCollidable.Point.Z = ray.Origin.Z + ray.Direction.Z * t; - HitCollidable.Collider = getFromReference(collidable); + HitCollidable.Collider = component; HitCollidable.Succeeded = true; } @@ -568,7 +569,7 @@ public void OnRayHit(in RayData ray, ref float maximumT, float t, in System.Nume /// The collision group of this raycast /// The collision group that this raycast can collide with /// The list with hit results. - public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) + public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags hitGroups = DefaultFlags, BepuPhysicsComponent skipComponent = null) { Vector3 diff = to - from; float length = diff.Length(); @@ -576,7 +577,7 @@ public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags diff.X *= inv; diff.Y *= inv; diff.Z *= inv; - return Raycast(from, diff, length, hitGroups, skipAtZero); + return Raycast(from, diff, length, hitGroups, skipComponent); } /// @@ -587,14 +588,14 @@ public BepuHitResult Raycast(Vector3 from, Vector3 to, CollisionFilterGroupFlags /// The collision group of this raycast /// The collision group that this raycast can collide with /// The list with hit results. - public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) + public BepuHitResult Raycast(Vector3 from, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, BepuPhysicsComponent skipComponent = null) { RayHitClosestHandler rhch = new RayHitClosestHandler() { findGroups = hitGroups, startLength = length, furthestHitSoFar = float.MaxValue, - skipAtZero = skipAtZero + skipComponent = skipComponent }; using(simulationLocker.ReadLock()) { @@ -651,7 +652,7 @@ struct SweepTestFirst : ISweepHitHandler public CollisionFilterGroupFlags hitGroups; public BepuHitResult result; public float furthestHitSoFar, startLength; - public bool skipAtZero; + public BepuPhysicsComponent skipComponent; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AllowTest(CollidableReference collidable) @@ -668,13 +669,14 @@ public bool AllowTest(CollidableReference collidable, int child) [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLocation, in System.Numerics.Vector3 hitNormal, CollidableReference collidable) { - if (skipAtZero && t <= float.Epsilon) return; - if (t < furthestHitSoFar) { + var component = getFromReference(collidable); + if (component == skipComponent) return; + furthestHitSoFar = t; result.Succeeded = true; - result.Collider = getFromReference(collidable); + result.Collider = component; result.Normal.X = hitNormal.X; result.Normal.Y = hitNormal.Y; result.Normal.Z = hitNormal.Z; @@ -693,10 +695,11 @@ public void OnHit(ref float maximumT, float t, in System.Numerics.Vector3 hitLoc [MethodImpl(MethodImplOptions.AggressiveInlining)] public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) { - if (skipAtZero) return; + var component = getFromReference(collidable); + if (component == skipComponent) return; result.Succeeded = true; - result.Collider = getFromReference(collidable); + result.Collider = component; maximumT = 0; furthestHitSoFar = 0; } @@ -756,7 +759,7 @@ public void OnHitAtZeroT(ref float maximumT, CollidableReference collidable) /// The collision group that this shape sweep can collide with /// /// This kind of shape cannot be used for a ShapeSweep. - public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) where TShape : unmanaged, IConvexShape + public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 endpoint, CollisionFilterGroupFlags hitGroups = DefaultFlags, BepuPhysicsComponent skipComponent = null) where TShape : unmanaged, IConvexShape { Vector3 diff = endpoint - position; float length = diff.Length(); @@ -764,7 +767,7 @@ public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Co diff.X *= inv; diff.Y *= inv; diff.Z *= inv; - return ShapeSweep(shape, position, rotation, diff, length, hitGroups, skipAtZero); + return ShapeSweep(shape, position, rotation, diff, length, hitGroups, skipComponent); } /// @@ -777,14 +780,14 @@ public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Co /// The collision group that this shape sweep can collide with /// /// This kind of shape cannot be used for a ShapeSweep. - public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, bool skipAtZero = false) where TShape : unmanaged, IConvexShape + public BepuHitResult ShapeSweep(TShape shape, Vector3 position, Xenko.Core.Mathematics.Quaternion rotation, Vector3 direction, float length, CollisionFilterGroupFlags hitGroups = DefaultFlags, BepuPhysicsComponent skipComponent = null) where TShape : unmanaged, IConvexShape { SweepTestFirst sshh = new SweepTestFirst() { hitGroups = hitGroups, startLength = length, furthestHitSoFar = float.MaxValue, - skipAtZero = skipAtZero + skipComponent = skipComponent }; RigidPose rp = new RigidPose(); rp.Position.X = position.X; From 1e35a49d914a92f3c6ea0f47ceb14f0915d905bf Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 5 Feb 2020 11:21:24 -0500 Subject: [PATCH 0706/2038] VR: restore Grip property --- .../engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs index a710e7ffcb..6b9e592562 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs @@ -63,7 +63,7 @@ public override void Update(GameTime gameTime) public override float Trigger => controller?.GetAxis(OpenVR.Controller.ButtonId.ButtonSteamVrTrigger).X ?? 0.0f; - public override float Grip => controller?.GetAxis(OpenVR.Controller.ButtonId.ButtonGrip).X ?? 0.0f; + public override float Grip => controller?.GetPress(OpenVR.Controller.ButtonId.ButtonGrip) ?? false ? 1f : 0f; public override bool IndexPointing => !controller?.GetTouch(OpenVR.Controller.ButtonId.ButtonSteamVrTrigger) ?? false; //not so accurate From 7a85eefccdfe4960e734f549507d121a1f6d75b2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 5 Feb 2020 11:21:54 -0500 Subject: [PATCH 0707/2038] VR: Implement more buttons --- sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs | 2 +- .../Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs index 2d82f535b0..3bea96b472 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVR.cs @@ -141,7 +141,7 @@ public Vector2 GetAxis(ButtonId buttonId = ButtonId.ButtonSteamVrTouchpad) { case ButtonId.ButtonAxis0: return new Vector2(State.rAxis0.x, State.rAxis0.y); // also touchpad case ButtonId.ButtonAxis1: return new Vector2(State.rAxis1.x, State.rAxis1.y); // also trigger - case ButtonId.ButtonAxis2: return new Vector2(State.rAxis2.x, State.rAxis2.y); + case ButtonId.ButtonAxis2: return new Vector2(State.rAxis2.x, State.rAxis2.y); // hand trigger..? case ButtonId.ButtonAxis3: return new Vector2(State.rAxis3.x, State.rAxis3.y); // index joystick case ButtonId.ButtonAxis4: return new Vector2(State.rAxis4.x, State.rAxis4.y); } diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs index 6b9e592562..0e89914c56 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs @@ -83,12 +83,17 @@ private OpenVR.Controller.ButtonId ToOpenVrButton(TouchControllerButton button) { switch (button) { + case TouchControllerButton.A: + case TouchControllerButton.X: + return OpenVR.Controller.ButtonId.ButtonA; case TouchControllerButton.Thumbstick: return OpenVR.Controller.ButtonId.ButtonSteamVrTouchpad; case TouchControllerButton.Trigger: return OpenVR.Controller.ButtonId.ButtonSteamVrTrigger; case TouchControllerButton.Grip: return OpenVR.Controller.ButtonId.ButtonGrip; + case TouchControllerButton.B: + case TouchControllerButton.Y: case TouchControllerButton.Menu: return OpenVR.Controller.ButtonId.ButtonApplicationMenu; default: From 7d217c53134379e71bee9050b3f1b617de8a5851 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 5 Feb 2020 11:22:35 -0500 Subject: [PATCH 0708/2038] VR: Implement UI dragging events and hand swapping option --- .../Rendering/UI/UIRenderFeature.Picking.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs index 3f64847b5d..61b2a35f73 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs @@ -235,11 +235,6 @@ private void UpdateTouchEvents(ref Viewport viewport, ref Matrix worldViewProj, } } - /// - /// If a VR controller is pointing at a UIElement, this will be set with it. null otherwise. - /// - public static UIElement UIElementVivePointed { get; private set; } - /// /// If a pointer is pointed at an UIElement, it will be set here /// @@ -261,18 +256,20 @@ private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, Re { for (int i=0; i<2; i++) { - TransformComponent useHand = i == 0 ? (TransformComponent.OverrideRightHandUIPointer ?? TransformComponent.LastRightHandTracked) : - (TransformComponent.OverrideLeftHandUIPointer ?? TransformComponent.LastLeftHandTracked); + TransformComponent useHand = (VirtualReality.VRDeviceSystem.GetSystem.GetControllerSwapped ? (i ^ 1): i) == 0 ? + (TransformComponent.OverrideRightHandUIPointer ?? TransformComponent.LastRightHandTracked) : + (TransformComponent.OverrideLeftHandUIPointer ?? TransformComponent.LastLeftHandTracked); if (useHand != null) { Ray uiRay = new Ray(useHand.WorldPosition(), useHand.Forward(true)); - UIElementVivePointed = UIElementUnderMouseCursor = GetElementAtWorldPosition(rootElement, ref uiRay, ref worldViewProj, ref intersectionPoint); + UIElementUnderMouseCursor = GetElementAtWorldPosition(rootElement, ref uiRay, ref worldViewProj, ref intersectionPoint); if (UIElementUnderMouseCursor != null) { // wait, are we selecting this element? + // GetController already checks GetControllerSwapped VirtualReality.TouchController tc = VirtualReality.VRDeviceSystem.GetSystem.GetController(i == 0 ? VirtualReality.TouchControllerHand.Right : VirtualReality.TouchControllerHand.Left); if (tc != null) @@ -285,6 +282,10 @@ private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, Re { MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Released, Vector2.Zero, Vector2.Zero, intersectionPoint, intersectionPoint - state.LastIntersectionPoint, time); } + else if (tc.IsPressed(VirtualReality.VRDeviceSystem.UIActivationButton)) + { + MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Moved, Vector2.Zero, Vector2.Zero, intersectionPoint, intersectionPoint - state.LastIntersectionPoint, time); + } } break; From 295f07a740b07bb577ec1e61fcfb7918bc8d7fec Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 5 Feb 2020 11:40:31 -0500 Subject: [PATCH 0709/2038] GameProfiler: update keys --- .../Templates/Assets/Scripts/Utility/GameProfiler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/GameProfiler.cs b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/GameProfiler.cs index 237550403b..305ea80989 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/GameProfiler.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Scripts/Utility/GameProfiler.cs @@ -119,11 +119,11 @@ public override async Task Execute() } // update the refreshing speed - if (Input.IsKeyPressed(Keys.Subtract) || Input.IsKeyPressed(Keys.OemMinus)) + if (Input.IsKeyPressed(Keys.Subtract) || Input.IsKeyPressed(Keys.Minus)) { RefreshTime = Math.Min(RefreshTime * 2, 10000); } - else if (Input.IsKeyPressed(Keys.Add) || Input.IsKeyPressed(Keys.OemPlus)) + else if (Input.IsKeyPressed(Keys.Add) || Input.IsKeyPressed(Keys.Plus)) { RefreshTime = Math.Max(RefreshTime / 2, 100); } From d066ffb0ec81a561f046c0982172642f96f860c8 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 5 Feb 2020 22:02:40 -0500 Subject: [PATCH 0710/2038] VR: Fix UI VR interactions (selecting buttons and dragging) --- sources/engine/Xenko.UI/GridList.cs | 1 + .../Rendering/UI/UIRenderFeature.Picking.cs | 24 ++++++++++--------- sources/engine/Xenko.UI/UIElement.cs | 15 +++++++----- 3 files changed, 23 insertions(+), 17 deletions(-) diff --git a/sources/engine/Xenko.UI/GridList.cs b/sources/engine/Xenko.UI/GridList.cs index 91b22daf62..0971543785 100644 --- a/sources/engine/Xenko.UI/GridList.cs +++ b/sources/engine/Xenko.UI/GridList.cs @@ -322,6 +322,7 @@ public List GetEntries(bool onlyChecked = false) protected void AddToList(UIElement uie) { uie.Margin = new Thickness(0f, uie.Height * myGrid.Children.Count, 0f, 0f); + uie.SetPanelZIndex(myGrid.GetPanelZIndex() + 1); myGrid.Children.Add(uie); } diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs index 61b2a35f73..da4190e033 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs @@ -276,18 +276,20 @@ private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, Re { if (tc.IsPressedDown(VirtualReality.VRDeviceSystem.UIActivationButton)) { - MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Pressed, Vector2.Zero, Vector2.Zero, intersectionPoint, intersectionPoint - state.LastIntersectionPoint, time); + MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Pressed, Vector2.Zero, Vector2.Zero, intersectionPoint, Vector3.Zero, time); } else if (tc.IsPressReleased(VirtualReality.VRDeviceSystem.UIActivationButton)) { - MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Released, Vector2.Zero, Vector2.Zero, intersectionPoint, intersectionPoint - state.LastIntersectionPoint, time); + MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Released, Vector2.Zero, Vector2.Zero, intersectionPoint, Vector3.Zero, time); } else if (tc.IsPressed(VirtualReality.VRDeviceSystem.UIActivationButton)) { - MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Moved, Vector2.Zero, Vector2.Zero, intersectionPoint, intersectionPoint - state.LastIntersectionPoint, time); + MakeTouchEvent(UIElementUnderMouseCursor, lastMouseOverElement, PointerEventType.Moved, Vector2.Zero, Vector2.Zero, intersectionPoint, (state.LastIntersectionPoint - intersectionPoint) / state.WorldMatrix3D.ScaleVector, time); } } + state.LastIntersectionPoint = intersectionPoint; + break; } } @@ -458,16 +460,16 @@ private static void PerformRecursiveHitTest(UIElement element, ref Ray ray, ref if (element.ClipToBounds && !intersect) return; - // Calculate the depth of the element with the depth bias so that hit test corresponds to visuals. - Vector4 projectedIntersection; - var intersection4 = new Vector4(intersection, 1); - Vector4.Transform(ref intersection4, ref worldViewProj, out projectedIntersection); - var depth = projectedIntersection.Z/projectedIntersection.W; - - // update the closest element hit if (canBeHit && intersect) { - if (depth < smallestDepth || (depth == smallestDepth && element.DepthBias > highestDepthBias)) + // Calculate the depth of the element with the depth bias so that hit test corresponds to visuals. + Vector4 projectedIntersection; + var intersection4 = new Vector4(intersection, 1); + Vector4.Transform(ref intersection4, ref worldViewProj, out projectedIntersection); + var depth = projectedIntersection.Z / projectedIntersection.W; + + // update the closest element hit + if (depth < smallestDepth || (element.DepthBias > highestDepthBias && Math.Abs(depth - smallestDepth) < 0.00001f)) { smallestDepth = depth; highestDepthBias = element.DepthBias; diff --git a/sources/engine/Xenko.UI/UIElement.cs b/sources/engine/Xenko.UI/UIElement.cs index 0e1414de57..57ff2e0ec6 100644 --- a/sources/engine/Xenko.UI/UIElement.cs +++ b/sources/engine/Xenko.UI/UIElement.cs @@ -1153,7 +1153,7 @@ protected static void SetVisualParent([NotNull] UIElement child, [CanBeNull] UIE /// /// Variation on Ray vs Rectangle /// - internal bool RayIntersectsRectangle(ref Ray ray, ref Vector3 topLeftCorner, ref Vector3 topRightCorner, ref Vector3 bottomLeftCorner) + internal bool RayIntersectsRectangle(ref Ray ray, ref Vector3 topLeftCorner, ref Vector3 topRightCorner, ref Vector3 bottomLeftCorner, out Vector3 intersectionPoint) { // from https://stackoverflow.com/questions/21114796/3d-ray-quad-intersection-test-in-java @@ -1167,15 +1167,19 @@ internal bool RayIntersectsRectangle(ref Ray ray, ref Vector3 topLeftCorner, ref Vector3.Dot(ref n, ref dR, out float ndotdR); - if (ndotdR < 1e-6f) return false; + if (ndotdR < 1e-6f) + { + intersectionPoint = Vector3.Zero; + return false; + } Vector3 posDiff = ray.Position - topLeftCorner; float t = Vector3.Dot(-n, posDiff) / ndotdR; - Vector3 M = ray.Position + dR * t; + intersectionPoint = ray.Position + dR * t; // 3. - Vector3 dMS1 = M - topLeftCorner; + Vector3 dMS1 = intersectionPoint - topLeftCorner; Vector3.Dot(ref dMS1, ref dS21, out float u); Vector3.Dot(ref dMS1, ref dS31, out float v); @@ -1199,7 +1203,6 @@ protected internal virtual bool Intersects(ref Ray ray, out Vector3 intersection Matrix worldMatrix = WorldMatrixPickingInternal; worldMatrix.M42 = -worldMatrix.M42; // for some reason Y translation needs to be flipped worldMatrix *= WorldMatrix3D.Value; - intersectionPoint = worldMatrix.TranslationVector; Vector3 topLeft = Vector3.Transform(new Vector3(-RenderSizeInternal.X * 0.5f, RenderSizeInternal.Y * 0.5f, 0f), worldMatrix).XYZ(); @@ -1209,7 +1212,7 @@ protected internal virtual bool Intersects(ref Ray ray, out Vector3 intersection Vector3 bottomLeft = Vector3.Transform(new Vector3(-RenderSizeInternal.X * 0.5f, -RenderSizeInternal.Y * 0.5f, 0f), worldMatrix).XYZ(); - intersects = RayIntersectsRectangle(ref ray, ref topLeft, ref topRight, ref bottomLeft); + intersects = RayIntersectsRectangle(ref ray, ref topLeft, ref topRight, ref bottomLeft, out intersectionPoint); } else { From 4ac83420d24b24443ffc67fdd1bb5f02d5fd2a88 Mon Sep 17 00:00:00 2001 From: Basewq Date: Wed, 5 Feb 2020 19:11:29 +1300 Subject: [PATCH 0711/2038] [Editor] Component properties with ExpandRule.Auto or ExpandRule.Once will remember their expand/collapsed states for the whole session (fixes #358) --- .../PropertyViewAutoExpandNodesBehavior.cs | 49 ++++++++++++------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/PropertyViewAutoExpandNodesBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/PropertyViewAutoExpandNodesBehavior.cs index 5f99dc9617..bd74af4457 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/PropertyViewAutoExpandNodesBehavior.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/PropertyViewAutoExpandNodesBehavior.cs @@ -21,14 +21,15 @@ namespace Xenko.Core.Assets.Editor.View.Behaviors public class PropertyViewAutoExpandNodesBehavior : Behavior { private readonly List expandedItems = new List(); - private readonly HashSet expandedPropertyPaths = new HashSet(); - private readonly HashSet collapsedPropertyPaths = new HashSet(); + // These are static so that we remember their state for the entire session. + private static readonly HashSet expandedPropertyPaths = new HashSet(); + private static readonly HashSet collapsedPropertyPaths = new HashSet(); /// /// Identifies the dependency property. /// public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(nameof(ViewModel), typeof(GraphViewModel), typeof(PropertyViewAutoExpandNodesBehavior), new PropertyMetadata(null, OnViewModelChanged)); - + /// /// Gets or sets the associated to this behavior. /// @@ -166,27 +167,37 @@ private void ExpandSingleProperties(PropertyViewItem item) item.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, false); break; case ExpandRule.Once: - // Expand nodes that have this rule only if they have never been collapsed previously - var propertyPath = GetNode(item).DisplayPath; - if (!collapsedPropertyPaths.Contains(propertyPath)) { - item.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, true); - break; + // Expand nodes that have this rule only if they have never been collapsed previously + var propertyPath = GetNode(item).DisplayPath; + if (!collapsedPropertyPaths.Contains(propertyPath)) + { + item.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, true); + break; + } } goto default; default: - // If the node is an only child, let's expand it - if (node.Parent.Children.Count == 1) - { - item.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, true); - // And keep a track of it, in case it has some siblings incoming - expandedItems.Add(item); - } - else { - // If one of its siblings has been expanded because it was an only child at the time it was created, let's unexpand it. - // This will prevent to always have the first item expanded since the property items are generated as soon as a child is added. - expandedItems.Where(x => GetNode(x).Parent == node.Parent).ForEach(x => x.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, false)); + // If the node was saved as expanded, persist this behavior + var propertyPath = GetNode(item).DisplayPath; + if (expandedPropertyPaths.Contains(propertyPath)) + { + item.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, true); + } + else if (node.Parent.Children.Count == 1) + { + // If the node is an only child, let's expand it + item.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, true); + // And keep a track of it, in case it has some siblings incoming + expandedItems.Add(item); + } + else + { + // If one of its siblings has been expanded because it was an only child at the time it was created, let's unexpand it. + // This will prevent to always have the first item expanded since the property items are generated as soon as a child is added. + expandedItems.Where(x => GetNode(x).Parent == node.Parent).ForEach(x => x.SetCurrentValue(ExpandableItemsControl.IsExpandedProperty, false)); + } } break; } From 7097219e8cfc68a9bece8da45217e3c878bd3dd5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 6 Feb 2020 09:01:05 -0500 Subject: [PATCH 0712/2038] Revert "UI Editor: Always expand Appearance on UI Elements, so something useful is shown" This reverts commit 86a50449140e2821cc4005876db89069f05cee4f. --- sources/engine/Xenko.UI/UIElement.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.UI/UIElement.cs b/sources/engine/Xenko.UI/UIElement.cs index 57ff2e0ec6..b4be2b6397 100644 --- a/sources/engine/Xenko.UI/UIElement.cs +++ b/sources/engine/Xenko.UI/UIElement.cs @@ -18,7 +18,7 @@ namespace Xenko.UI /// Provides a base class for all the User Interface elements in Xenko applications. /// [DataContract(Inherited = true)] - [CategoryOrder(10, AppearanceCategory, Expand = ExpandRule.Always)] + [CategoryOrder(10, AppearanceCategory, Expand = ExpandRule.Auto)] [CategoryOrder(20, BehaviorCategory, Expand = ExpandRule.Auto)] [CategoryOrder(30, LayoutCategory, Expand = ExpandRule.Auto)] [CategoryOrder(100, MiscCategory, Expand = ExpandRule.Auto)] From 20d8a023f70d62aa97e8ec03090ff01af2bc36a7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 6 Feb 2020 09:52:35 -0500 Subject: [PATCH 0713/2038] Rendering: minor performance tweaks (and a little safety check) --- .../Xenko.Rendering/Rendering/RootEffectRenderFeature.cs | 5 +++-- sources/engine/Xenko/Effects/ParameterKey.cs | 9 ++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs index e3d63c33d1..81124886b6 100644 --- a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs @@ -494,9 +494,10 @@ public override void PrepareEffectPermutations(RenderDrawContext context) if (staticCompilerParameters == null) staticCompilerParameters = new CompilerParameters(); - foreach (var effectValue in renderEffect.EffectValidator.EffectValues) + for (int k=0; k asyncEffect; diff --git a/sources/engine/Xenko/Effects/ParameterKey.cs b/sources/engine/Xenko/Effects/ParameterKey.cs index 7f99814105..048fe6b2c7 100644 --- a/sources/engine/Xenko/Effects/ParameterKey.cs +++ b/sources/engine/Xenko/Effects/ParameterKey.cs @@ -3,6 +3,7 @@ #pragma warning disable SA1402 // File may only contain a single type using System; using System.Reflection; +using System.Runtime.CompilerServices; using Xenko.Core; using Xenko.Core.Serialization; using Xenko.Core.Storage; @@ -64,14 +65,14 @@ internal void SetOwnerType(Type ownerType) /// /// true if the specified is equal to this instance; otherwise, false. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object obj) { //return ReferenceEquals(this, obj); if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - var against = obj as ParameterKey; - if (against == null) return false; - return (Equals(against.Name, Name)); + if (obj is ParameterKey pk) return Equals(pk.Name, Name); + return false; } /// @@ -93,6 +94,7 @@ public override int GetHashCode() /// /// The result of the operator. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ParameterKey left, ParameterKey right) { return Equals(left, right); @@ -106,6 +108,7 @@ public override int GetHashCode() /// /// The result of the operator. /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(ParameterKey left, ParameterKey right) { return !Equals(left, right); From bd48a43b7a8b618d692248945566dbbbde4de12f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 6 Feb 2020 14:27:52 -0500 Subject: [PATCH 0714/2038] VR: check which VR VirtualButton is on which hand --- sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs b/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs index 00d37a2423..d704da006f 100644 --- a/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs +++ b/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs @@ -124,6 +124,8 @@ protected VRButtons(string name, int id, bool isPositiveAndNegative = false) { } + public bool IsRightHand => ((Index & (1 << 16)) != 0) == !VRDeviceSystem.GetSystem.GetControllerSwapped; + public override float GetValue() { TouchController tc = VRDeviceSystem.GetSystem?.GetController((Index & (1 << 16)) != 0 ? TouchControllerHand.Right : TouchControllerHand.Left); From 868c7ad35358b3568f2629809d0c417ec7c1c900 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 7 Feb 2020 11:56:46 -0500 Subject: [PATCH 0715/2038] VR: threading protection when rendering multiple views --- .../Rendering/EffectValidator.cs | 37 ++++++++++++++++++- .../Lights/ForwardLightingRenderFeature.cs | 4 +- .../Rendering/Lights/LightSkyboxRenderer.cs | 4 +- .../Materials/MaterialRenderFeature.cs | 18 ++++----- .../Rendering/MeshVelocityRenderFeature.cs | 2 +- .../Rendering/RootEffectRenderFeature.cs | 2 +- .../Rendering/SkinningRenderFeature.cs | 8 ++-- .../GraphicsCompositor/VoxelRenderFeature.cs | 6 +-- .../Voxels/Light/LightVoxelRenderer.cs | 6 +-- 9 files changed, 60 insertions(+), 27 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/EffectValidator.cs b/sources/engine/Xenko.Rendering/Rendering/EffectValidator.cs index aaeb1ec19f..fd7537f407 100644 --- a/sources/engine/Xenko.Rendering/Rendering/EffectValidator.cs +++ b/sources/engine/Xenko.Rendering/Rendering/EffectValidator.cs @@ -31,7 +31,8 @@ public struct EffectValidator public void Initialize() { EffectValues = new FastListStruct(4); - + addLocker = new object(); + // Add a dummy value so that an effect without parameter fails validation first time EffectValues.Add(new EffectParameterEntry()); } @@ -43,6 +44,8 @@ public void BeginEffectValidation() ShouldSkip = false; } + private object addLocker; + [RemoveInitLocals] public void ValidateParameter(PermutationParameterKey key, T value) { @@ -68,7 +71,37 @@ public void ValidateParameter(PermutationParameterKey key, T value) effectChanged = true; } } - + + [RemoveInitLocals] + public void ValidateParameterThreaded(PermutationParameterKey key, T value) + { + // Check if value was existing and/or same + var index = effectValuesValidated++; + if (index < EffectValues.Count) + { + var currentEffectValue = EffectValues.Items[index]; + if (currentEffectValue.Key == key && EqualityComparer.Default.Equals((T)currentEffectValue.Value, value)) + { + // Everything same, let's keep going + return; + } + + // Something was different, let's replace item and clear end of list + EffectValues[index] = new EffectParameterEntry(key, value); + EffectValues.Count = effectValuesValidated; + effectChanged = true; + } + else + { + var epe = new EffectParameterEntry(key, value); + lock (addLocker) + { + EffectValues.Add(epe); + } + effectChanged = true; + } + } + public bool EndEffectValidation() { if (effectValuesValidated < EffectValues.Count) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs index 98350c89e2..ad3a845da3 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/ForwardLightingRenderFeature.cs @@ -302,8 +302,8 @@ public override void PrepareEffectPermutations(RenderDrawContext context) if (renderEffect == null || !renderEffect.IsUsedDuringThisFrame(RenderSystem)) continue; - renderEffect.EffectValidator.ValidateParameter(LightingKeys.DirectLightGroups, directLightShaders); - renderEffect.EffectValidator.ValidateParameter(LightingKeys.EnvironmentLights, environmentLightShaders); + renderEffect.EffectValidator.ValidateParameterThreaded(LightingKeys.DirectLightGroups, directLightShaders); + renderEffect.EffectValidator.ValidateParameterThreaded(LightingKeys.EnvironmentLights, environmentLightShaders); // Some light groups have additional effect permutation foreach (var lightGroup in shaderPermutation.PermutationLightGroups) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxRenderer.cs index 37ac4bfce3..028c0a399e 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightSkyboxRenderer.cs @@ -122,8 +122,8 @@ public override void ApplyEffectPermutations(RenderEffect renderEffect) var lightDiffuseColorShader = diffuseParameters.Get(SkyboxKeys.Shader) ?? EmptyComputeEnvironmentColorSource; var lightSpecularColorShader = specularParameters.Get(SkyboxKeys.Shader) ?? EmptyComputeEnvironmentColorSource; - renderEffect.EffectValidator.ValidateParameter(lightDiffuseColorKey, lightDiffuseColorShader); - renderEffect.EffectValidator.ValidateParameter(lightSpecularColorKey, lightSpecularColorShader); + renderEffect.EffectValidator.ValidateParameterThreaded(lightDiffuseColorKey, lightDiffuseColorShader); + renderEffect.EffectValidator.ValidateParameterThreaded(lightSpecularColorKey, lightSpecularColorShader); } public override void ApplyViewParameters(RenderDrawContext context, int viewIndex, ParameterCollection parameters) diff --git a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs index 5c3b0665e2..2c86263fca 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Materials/MaterialRenderFeature.cs @@ -236,29 +236,29 @@ public override void PrepareEffectPermutations(RenderDrawContext context) // VS if (materialInfo.VertexStageSurfaceShaders != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.VertexStageSurfaceShaders, materialInfo.VertexStageSurfaceShaders); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.VertexStageSurfaceShaders, materialInfo.VertexStageSurfaceShaders); if (materialInfo.VertexStageStreamInitializer != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.VertexStageStreamInitializer, materialInfo.VertexStageStreamInitializer); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.VertexStageStreamInitializer, materialInfo.VertexStageStreamInitializer); // DS if (materialInfo.DomainStageSurfaceShaders != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.DomainStageSurfaceShaders, materialInfo.DomainStageSurfaceShaders); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.DomainStageSurfaceShaders, materialInfo.DomainStageSurfaceShaders); if (materialInfo.DomainStageStreamInitializer != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.DomainStageStreamInitializer, materialInfo.DomainStageStreamInitializer); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.DomainStageStreamInitializer, materialInfo.DomainStageStreamInitializer); // Tessellation if (materialInfo.TessellationShader != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.TessellationShader, materialInfo.TessellationShader); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.TessellationShader, materialInfo.TessellationShader); // PS if (materialInfo.PixelStageSurfaceShaders != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.PixelStageSurfaceShaders, materialInfo.PixelStageSurfaceShaders); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.PixelStageSurfaceShaders, materialInfo.PixelStageSurfaceShaders); if (materialInfo.PixelStageStreamInitializer != null) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.PixelStageStreamInitializer, materialInfo.PixelStageStreamInitializer); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.PixelStageStreamInitializer, materialInfo.PixelStageStreamInitializer); if (materialInfo.HasNormalMap) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.HasNormalMap, materialInfo.HasNormalMap); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.HasNormalMap, materialInfo.HasNormalMap); if (materialInfo.UsePixelShaderWithDepthPass) - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.UsePixelShaderWithDepthPass, materialInfo.UsePixelShaderWithDepthPass); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.UsePixelShaderWithDepthPass, materialInfo.UsePixelShaderWithDepthPass); } }); diff --git a/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs index 8d541d9896..54b204cc28 100644 --- a/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/MeshVelocityRenderFeature.cs @@ -75,7 +75,7 @@ public override void PrepareEffectPermutations(RenderDrawContext context) if (renderEffect != null) { - renderEffect.EffectValidator.ValidateParameter(XenkoEffectBaseKeys.ComputeVelocityShader, new ShaderClassSource("MeshVelocity")); + renderEffect.EffectValidator.ValidateParameterThreaded(XenkoEffectBaseKeys.ComputeVelocityShader, new ShaderClassSource("MeshVelocity")); } } }); diff --git a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs index 81124886b6..b5d628978c 100644 --- a/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/RootEffectRenderFeature.cs @@ -373,7 +373,7 @@ private void PrepareRenderTargetExtensionsMixins(RenderDrawContext context) var renderStage = renderNode.RenderStage; var renderStageShaderSource = renderStage.OutputValidator.ShaderSource; if (renderStageShaderSource != null) - renderEffect.EffectValidator.ValidateParameter(XenkoEffectBaseKeys.RenderTargetExtensions, renderStageShaderSource); + renderEffect.EffectValidator.ValidateParameterThreaded(XenkoEffectBaseKeys.RenderTargetExtensions, renderStageShaderSource); } }); } diff --git a/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs b/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs index 6703a21e4e..37303453b9 100644 --- a/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs +++ b/sources/engine/Xenko.Rendering/Rendering/SkinningRenderFeature.cs @@ -81,12 +81,12 @@ public override void PrepareEffectPermutations(RenderDrawContext context) if (renderMesh.Mesh.Skinning != null) { - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.HasSkinningPosition, skinningInfo.HasSkinningPosition); - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.HasSkinningNormal, skinningInfo.HasSkinningNormal); - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.HasSkinningTangent, skinningInfo.HasSkinningTangent); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.HasSkinningPosition, skinningInfo.HasSkinningPosition); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.HasSkinningNormal, skinningInfo.HasSkinningNormal); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.HasSkinningTangent, skinningInfo.HasSkinningTangent); var skinningBones = Math.Max(MaxBones, renderMesh.Mesh.Skinning.Bones.Length); - renderEffect.EffectValidator.ValidateParameter(MaterialKeys.SkinningMaxBones, skinningBones); + renderEffect.EffectValidator.ValidateParameterThreaded(MaterialKeys.SkinningMaxBones, skinningBones); } } }); diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs index b2cdce555d..88e1ace8a1 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderFeature.cs @@ -82,9 +82,9 @@ public override void PrepareEffectPermutations(RenderDrawContext context) // Skip effects not used during this frame if (renderEffect != null) { - renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.Storage, pass.source); - renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.RequireGeometryShader, pass.storer.RequireGeometryShader() || pass.method.RequireGeometryShader()); - renderEffect.EffectValidator.ValidateParameter(VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount, pass.storer.GeometryShaderOutputCount() * pass.method.GeometryShaderOutputCount()); + renderEffect.EffectValidator.ValidateParameterThreaded(VoxelizeToFragmentsKeys.Storage, pass.source); + renderEffect.EffectValidator.ValidateParameterThreaded(VoxelizeToFragmentsKeys.RequireGeometryShader, pass.storer.RequireGeometryShader() || pass.method.RequireGeometryShader()); + renderEffect.EffectValidator.ValidateParameterThreaded(VoxelizeToFragmentsKeys.GeometryShaderMaxVertexCount, pass.storer.GeometryShaderOutputCount() * pass.method.GeometryShaderOutputCount()); } } }); diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs index 6c7143217a..0d7edb63c5 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs @@ -161,12 +161,12 @@ public override void ApplyEffectPermutations(RenderEffect renderEffect) { traceAttribute.GetSamplingShader() }; - renderEffect.EffectValidator.ValidateParameter(attributeSamplersKey, collection); + renderEffect.EffectValidator.ValidateParameterThreaded(attributeSamplersKey, collection); if (((LightVoxel)Light.Type).DiffuseMarcher != null) - renderEffect.EffectValidator.ValidateParameter(diffuseMarcherKey, ((LightVoxel)Light.Type).DiffuseMarcher.GetMarchingShader(0)); + renderEffect.EffectValidator.ValidateParameterThreaded(diffuseMarcherKey, ((LightVoxel)Light.Type).DiffuseMarcher.GetMarchingShader(0)); if (((LightVoxel)Light.Type).SpecularMarcher != null) - renderEffect.EffectValidator.ValidateParameter(specularMarcherKey, ((LightVoxel)Light.Type).SpecularMarcher.GetMarchingShader(0)); + renderEffect.EffectValidator.ValidateParameterThreaded(specularMarcherKey, ((LightVoxel)Light.Type).SpecularMarcher.GetMarchingShader(0)); } } From 3f53ed9669a8c2cd3fadc2f70580f7e8f3eb1791 Mon Sep 17 00:00:00 2001 From: tebjan Date: Thu, 16 Jan 2020 20:21:10 +0100 Subject: [PATCH 0716/2038] [Assets] updated Microsoft.CodeAnalysis.CSharp.Workspaces and Microsoft.CodeAnalysis.Workspaces.MSBuild to 3.3.1 to be in sync with vvvv --- .../Xenko.Assets.Presentation.csproj | 10 +++++----- sources/engine/Xenko.Assets/Xenko.Assets.csproj | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj index c141b1815c..2e5966a2c5 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj @@ -1,4 +1,4 @@ - + @@ -21,8 +21,8 @@ - - + + $(XenkoCommonDependenciesDir)RoslynPad\net462\RoslynPad.Editor.Windows.dll @@ -70,8 +70,8 @@ Settings.Designer.cs - - + + diff --git a/sources/engine/Xenko.Assets/Xenko.Assets.csproj b/sources/engine/Xenko.Assets/Xenko.Assets.csproj index 4d9638ab71..6c97b2fc3b 100644 --- a/sources/engine/Xenko.Assets/Xenko.Assets.csproj +++ b/sources/engine/Xenko.Assets/Xenko.Assets.csproj @@ -1,4 +1,4 @@ - + @@ -19,8 +19,8 @@ - - + + False ..\..\..\deps\SSH.NET\Renci.SshNet.dll From ef05a43a07b71e4fa3137f78baffada3c87e4eb7 Mon Sep 17 00:00:00 2001 From: tebjan Date: Mon, 3 Feb 2020 22:24:17 +0100 Subject: [PATCH 0717/2038] [Assets] updated RoslyPad and Scripting to use Microsoft.CodeAnalysis 3.4.0 # Conflicts: # deps/RoslynPad/checkout.bat # deps/RoslynPad/net462/RoslynPad.Editor.Windows.dll # deps/RoslynPad/net462/RoslynPad.Editor.Windows.pdb # deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.dll # deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.pdb # deps/RoslynPad/net462/RoslynPad.Roslyn.dll # deps/RoslynPad/net462/RoslynPad.Roslyn.pdb --- deps/RoslynPad/checkout.bat | 2 +- .../net462/RoslynPad.Editor.Windows.dll | 2 +- .../net462/RoslynPad.Editor.Windows.pdb | 4 ++-- .../net462/RoslynPad.Roslyn.Windows.dll | 2 +- .../net462/RoslynPad.Roslyn.Windows.pdb | 4 ++-- deps/RoslynPad/net462/RoslynPad.Roslyn.dll | 4 ++-- deps/RoslynPad/net462/RoslynPad.Roslyn.pdb | 4 ++-- .../AssetEditors/ScriptEditor/RoslynHost.cs | 20 +++++++++++++++++++ .../Xenko.Assets.Presentation.csproj | 4 ++-- .../engine/Xenko.Assets/Xenko.Assets.csproj | 4 ++-- 10 files changed, 35 insertions(+), 15 deletions(-) diff --git a/deps/RoslynPad/checkout.bat b/deps/RoslynPad/checkout.bat index 8da86bb97b..5e59cacf7b 100644 --- a/deps/RoslynPad/checkout.bat +++ b/deps/RoslynPad/checkout.bat @@ -8,6 +8,6 @@ IF NOT ERRORLEVEL 0 ( ) %GIT_CMD% clone --recursive https://github.com/aelij/RoslynPad -b master ../../externals/RoslynPad pushd ..\..\externals\RoslynPad -%GIT_CMD% checkout c2f1c48 +%GIT_CMD% checkout 0d576ca5d18d67d447bce5d078f0a568a69a677d popd if ERRORLEVEL 1 echo "Could not checkout RoslynPad" && pause diff --git a/deps/RoslynPad/net462/RoslynPad.Editor.Windows.dll b/deps/RoslynPad/net462/RoslynPad.Editor.Windows.dll index 026ea9d064..edf8b5faba 100644 --- a/deps/RoslynPad/net462/RoslynPad.Editor.Windows.dll +++ b/deps/RoslynPad/net462/RoslynPad.Editor.Windows.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:151a332a47e1d02ded557cdb59c84fb54a1b96c996105adf683b24925999df3b +oid sha256:937a9d57d5e9b02cb3a5dde21de11f23855819c08d442daa5607b1c4fcb02adf size 135168 diff --git a/deps/RoslynPad/net462/RoslynPad.Editor.Windows.pdb b/deps/RoslynPad/net462/RoslynPad.Editor.Windows.pdb index 15652eade9..039cd2fb60 100644 --- a/deps/RoslynPad/net462/RoslynPad.Editor.Windows.pdb +++ b/deps/RoslynPad/net462/RoslynPad.Editor.Windows.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a7ca0bb907a9947929c0c87a3f040c1d825bd41708f11fb2069d71058d1c2cb7 -size 30868 +oid sha256:79561d808b37820493355dda5588f7adcd29f14b482a35f94787f930d69ec86a +size 31684 diff --git a/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.dll b/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.dll index 6ab2505f33..22bd11f3f8 100644 --- a/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.dll +++ b/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:06ec6d39e1c7d1ba2982507ca16f40405cd950709d2994f5a0a73ea8f6f9752d +oid sha256:0185d84ddae43b09f20ab9901d078694c4f2d2d47e03adae84c11f519c009436 size 105984 diff --git a/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.pdb b/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.pdb index e2f0d9dac7..39650ee2d7 100644 --- a/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.pdb +++ b/deps/RoslynPad/net462/RoslynPad.Roslyn.Windows.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3aae08ca945a291612771575c0ad1f0c7605d1a336aaf2d6974bd650e86ad73b -size 8608 +oid sha256:30033c04274b6f2961d2a49dc250af9692c0c79cc9806c43aec506184b9bb883 +size 9192 diff --git a/deps/RoslynPad/net462/RoslynPad.Roslyn.dll b/deps/RoslynPad/net462/RoslynPad.Roslyn.dll index 9cd335a6cb..17d44ded89 100644 --- a/deps/RoslynPad/net462/RoslynPad.Roslyn.dll +++ b/deps/RoslynPad/net462/RoslynPad.Roslyn.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:df33644a44e654542444d7c85d0b99f1c3e15cb7328faa6368d1d9e298a48bd8 -size 185344 +oid sha256:d1bef64c63600015c3b07dfaea4e0997c122ddb769ed30f2a0f592ceacc9a6ae +size 189952 diff --git a/deps/RoslynPad/net462/RoslynPad.Roslyn.pdb b/deps/RoslynPad/net462/RoslynPad.Roslyn.pdb index 6b50868d15..7ebf380973 100644 --- a/deps/RoslynPad/net462/RoslynPad.Roslyn.pdb +++ b/deps/RoslynPad/net462/RoslynPad.Roslyn.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:59aca313e793e56db1cc2994809bab325fc58214ad5d6f9a657a601aff775992 -size 46816 +oid sha256:fc1112362e02b6f36a166d042e2a93186e5fd37b9721308442c9fef675b57be0 +size 48936 diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/ScriptEditor/RoslynHost.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/ScriptEditor/RoslynHost.cs index b831a41ffe..5e5e8cba0b 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/ScriptEditor/RoslynHost.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/ScriptEditor/RoslynHost.cs @@ -13,12 +13,14 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Collections.Immutable; using System.Composition.Convention; using System.Composition.Hosting; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host.Mef; using RoslynPad.Editor; using RoslynPad.Roslyn; @@ -49,6 +51,8 @@ public RoslynHost() workspace.EnableDiagnostics(DiagnosticOptions.Semantic | DiagnosticOptions.Syntax); GetService().DiagnosticsUpdated += OnDiagnosticsUpdated; + + ParseOptions = CreateDefaultParseOptions(); } private static CompositionHost CreateCompositionContext() @@ -74,6 +78,15 @@ private static CompositionHost CreateCompositionContext() .CreateContainer(); } + internal static readonly ImmutableArray PreprocessorSymbols = + ImmutableArray.CreateRange(new[] { "TRACE", "DEBUG" }); + + protected virtual ParseOptions CreateDefaultParseOptions() + { + return new CSharpParseOptions(kind: SourceCodeKind.Regular, + preprocessorSymbols: PreprocessorSymbols, languageVersion: LanguageVersion.Latest); + } + /// /// The roslyn workspace. /// @@ -84,6 +97,8 @@ private static CompositionHost CreateCompositionContext() /// public MefHostServices HostServices => hostServices; + public ParseOptions ParseOptions { get; } + /// /// Gets a specific service. /// @@ -120,5 +135,10 @@ public void CloseDocument(DocumentId documentId) { workspace.CloseDocument(documentId); } + + public MetadataReference CreateMetadataReference(string location) + { + throw new NotImplementedException(); + } } } diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj index 2e5966a2c5..fa5412f45d 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.csproj @@ -21,8 +21,8 @@ - - + + $(XenkoCommonDependenciesDir)RoslynPad\net462\RoslynPad.Editor.Windows.dll diff --git a/sources/engine/Xenko.Assets/Xenko.Assets.csproj b/sources/engine/Xenko.Assets/Xenko.Assets.csproj index 6c97b2fc3b..f8b2c1b2d4 100644 --- a/sources/engine/Xenko.Assets/Xenko.Assets.csproj +++ b/sources/engine/Xenko.Assets/Xenko.Assets.csproj @@ -19,8 +19,8 @@ - - + + False ..\..\..\deps\SSH.NET\Renci.SshNet.dll From f960ef733e63cb548b5902b256f184eb220f74ab Mon Sep 17 00:00:00 2001 From: tebjan Date: Fri, 24 Jan 2020 19:48:10 +0100 Subject: [PATCH 0718/2038] [Core] increased version of Microsoft.NETCore.Platforms to 2.2.3 --- sources/core/Xenko.Core/Xenko.Core.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/core/Xenko.Core/Xenko.Core.csproj b/sources/core/Xenko.Core/Xenko.Core.csproj index a8e42a4880..7331d9f754 100644 --- a/sources/core/Xenko.Core/Xenko.Core.csproj +++ b/sources/core/Xenko.Core/Xenko.Core.csproj @@ -50,7 +50,7 @@ - + From 3c8a0a74246491d901bc02a534085cd0e6b89f7d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 7 Feb 2020 11:58:48 -0500 Subject: [PATCH 0719/2038] Physics: get rid of duplicate time setting and add setting to disable Bullet completely --- sources/engine/Xenko.Engine/Engine/EntityManager.cs | 4 ++++ sources/engine/Xenko.Engine/Engine/EntityProcessor.cs | 2 ++ sources/engine/Xenko.Physics/PhysicsSettings.cs | 4 ++-- sources/engine/Xenko.Physics/PhysicsSystem.cs | 3 ++- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/EntityManager.cs b/sources/engine/Xenko.Engine/Engine/EntityManager.cs index 0e874fc22b..3dc4e4685f 100644 --- a/sources/engine/Xenko.Engine/Engine/EntityManager.cs +++ b/sources/engine/Xenko.Engine/Engine/EntityManager.cs @@ -24,6 +24,7 @@ namespace Xenko.Engine public abstract class EntityManager : ComponentBase, IReadOnlySet { // TODO: Make this class threadsafe (current locks aren't sufficients) + static internal bool preventPhysicsProcessor; public ExecutionMode ExecutionMode { get; protected set; } = ExecutionMode.Runtime; @@ -625,6 +626,9 @@ protected override void AddItem(EntityProcessor processor) if (processor == null) throw new ArgumentNullException(nameof(processor)); if (!Contains(processor)) { + if (preventPhysicsProcessor && processor.MainTypeName == "PhysicsComponent") + return; // don't use Bullet physics, bepu only! + base.AddItem(processor); manager.OnProcessorAdded(processor); } diff --git a/sources/engine/Xenko.Engine/Engine/EntityProcessor.cs b/sources/engine/Xenko.Engine/Engine/EntityProcessor.cs index 3f1ad814d5..e524415c85 100644 --- a/sources/engine/Xenko.Engine/Engine/EntityProcessor.cs +++ b/sources/engine/Xenko.Engine/Engine/EntityProcessor.cs @@ -41,6 +41,8 @@ public abstract class EntityProcessor /// public ProfilingState DrawProfilingState; + public string MainTypeName => mainTypeInfo.Name; + /// /// Initializes a new instance of the class. /// diff --git a/sources/engine/Xenko.Physics/PhysicsSettings.cs b/sources/engine/Xenko.Physics/PhysicsSettings.cs index 97aeded148..0cc7959b77 100644 --- a/sources/engine/Xenko.Physics/PhysicsSettings.cs +++ b/sources/engine/Xenko.Physics/PhysicsSettings.cs @@ -26,9 +26,9 @@ public class PhysicsSettings : Configuration public float FixedTimeStep = 1.0f / 60.0f; /// - /// Default maximum time to simulate per frame. + /// If set to true, forcefully disable any Bullet physics processing. /// [DataMember] - public float MaxSimulationTime = 0.025f; + public bool OnlyUseBepu = false; } } diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index bd908d6376..b470708f2a 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -61,7 +61,8 @@ public override void Initialize() { physicsConfiguration = Game?.Settings != null ? Game.Settings.Configurations.Get() : new PhysicsSettings(); - MaximumSimulationTime = physicsConfiguration.MaxSimulationTime; + MaximumSimulationTime = physicsConfiguration.FixedTimeStep; + EntityManager.preventPhysicsProcessor = physicsConfiguration.OnlyUseBepu; if (isMultithreaded) { From efc577be76dfcefdb71958a2290a7b4cd993b250 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 7 Feb 2020 12:29:01 -0500 Subject: [PATCH 0720/2038] Audio: correct pan --- sources/engine/Xenko.Audio/SoundInstance.cs | 6 +++--- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 20 +++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index 41a717b271..3da2363a45 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -300,9 +300,9 @@ public void Stop() internal void ResetStateToDefault() { - Pan = 0; - Pitch = 1; - Volume = 1; + Pan = 0f; + Pitch = 1f; + Volume = 1f; IsLooping = false; Stop(); } diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index a7b1b225c8..b6149ef847 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -29,7 +29,7 @@ public sealed class GlobalSoundManager : ActivableEntityComponent [DataMember] public float MasterVolume = 1f; - public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume = 1f, float pan = 0.5f, bool looped = false) + public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume = 1f, float pan = 0f, bool looped = false) { SoundInstance s = getFreeInstance(url, false); if (s != null) @@ -43,7 +43,7 @@ public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume return s; } - public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch = 1f, float volume = 1f, float distanceScale = 1f, bool looped = false) { float sqrDist = (position - Listener.Listener.Position).LengthSquared(); if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; @@ -52,13 +52,13 @@ public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch s.Pitch = pitch < 0f ? RandomPitch() : pitch; s.Volume = volume * MasterVolume; s.IsLooping = looped; - s.Pan = pan; + s.Pan = 0f; s.Apply3D(position, null, null, distanceScale); s.Play(); return s; } - public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = 1f, float volume = 1f, float distanceScale = 1f, bool looped = false) { Vector3 pos = parent.Transform.WorldPosition(); float sqrDist = (pos - Listener.Listener.Position).LengthSquared(); @@ -68,7 +68,7 @@ public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = s.Pitch = pitch < 0f ? RandomPitch() : pitch; s.Volume = volume * MasterVolume; s.IsLooping = looped; - s.Pan = pan; + s.Pan = 0f; s.Apply3D(pos, null, null, distanceScale); s.Play(); var posSnd = new PositionalSound() { @@ -83,7 +83,7 @@ public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = return s; } - public Task PlayCentralSoundTask(string url, float pitch = 1f, float volume = 1f, float pan = 0.5f, bool looped = false) + public Task PlayCentralSoundTask(string url, float pitch = 1f, float volume = 1f, float pan = 0f, bool looped = false) { return Task.Factory.StartNew(() => { @@ -91,19 +91,19 @@ public Task PlayCentralSoundTask(string url, float pitch = 1f, fl }); } - public Task PlayPositionSoundTask(string url, Vector3 position, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + public Task PlayPositionSoundTask(string url, Vector3 position, float pitch = 1f, float volume = 1f, float distanceScale = 1f, bool looped = false) { return Task.Factory.StartNew(() => { - return PlayPositionSound(url, position, pitch, volume, pan, distanceScale, looped); + return PlayPositionSound(url, position, pitch, volume, distanceScale, looped); }); } - public Task PlayAttachedSoundTask(string url, Entity parent, float pitch = 1f, float volume = 1f, float pan = 0.5f, float distanceScale = 1f, bool looped = false) + public Task PlayAttachedSoundTask(string url, Entity parent, float pitch = 1f, float volume = 1f, float distanceScale = 1f, bool looped = false) { return Task.Factory.StartNew(() => { - return PlayAttachedSound(url, parent, pitch, volume, pan, distanceScale, looped); + return PlayAttachedSound(url, parent, pitch, volume, distanceScale, looped); }); } From a92a494e98b07554deac71e5d2d775a1851caf4b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 7 Feb 2020 14:52:16 -0500 Subject: [PATCH 0721/2038] VR: fix and add more virtual buttons --- .../Xenko.VirtualReality/VirtualButton.VR.cs | 228 ++++++++++-------- 1 file changed, 128 insertions(+), 100 deletions(-) diff --git a/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs b/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs index d704da006f..18fcffc091 100644 --- a/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs +++ b/sources/engine/Xenko.VirtualReality/VirtualButton.VR.cs @@ -1,5 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core.Mathematics; using Xenko.Input; namespace Xenko.VirtualReality @@ -9,115 +10,61 @@ namespace Xenko.VirtualReality /// public class VRButtons : VirtualButton { - /// - /// Right VR trigger. - /// public static readonly VirtualButton RightTrigger = new VRButtons("RightTrigger", (int)TouchControllerButton.Trigger | (1 << 16)); - /// - /// Right VR X. - /// - public static readonly VirtualButton RightX = new VRButtons("RightX", (int)TouchControllerButton.X | (1 << 16)); - - /// - /// Right VR Y. - /// - public static readonly VirtualButton RightY = new VRButtons("RightY", (int)TouchControllerButton.Y | (1 << 16)); - - /// - /// Right VR A. - /// - public static readonly VirtualButton RightA = new VRButtons("RightA", (int)TouchControllerButton.A | (1 << 16)); - - /// - /// Right VR B. - /// - public static readonly VirtualButton RightB = new VRButtons("RightB", (int)TouchControllerButton.B | (1 << 16)); - - /// - /// Right VR Grip. - /// + public static readonly VirtualButton RightXA = new VRButtons("RightXA", (int)TouchControllerButton.X | (1 << 16)); + + public static readonly VirtualButton RightBYMenu = new VRButtons("RightBYMenu", (int)TouchControllerButton.Menu | (1 << 16)); + public static readonly VirtualButton RightGrip = new VRButtons("RightGrip", (int)TouchControllerButton.Grip | (1 << 16)); - /// - /// Right VR Thumbstick Y axis - /// - public static readonly VirtualButton RightThumbstickY = new VRButtons("RightThumbstickY", (int)TouchControllerButton.Thumbstick | (1 << 16) | (1 << 17), true); - - /// - /// Right VR Thumbstick X axis - /// - public static readonly VirtualButton RightThumbstickX = new VRButtons("RightThumbstickX", (int)TouchControllerButton.Thumbstick | (1 << 16), true); - - /// - /// Right VR Touchpad Y axis. - /// - public static readonly VirtualButton RightTouchpadY = new VRButtons("RightTouchpadY", (int)TouchControllerButton.Touchpad | (1 << 16) | (1 << 17), true); - - /// - /// Right VR Touchpad X axis. - /// - public static readonly VirtualButton RightTouchpadX = new VRButtons("RightTouchpadX", (int)TouchControllerButton.Touchpad | (1 << 16), true); - - /// - /// Right VR Menu. - /// - public static readonly VirtualButton RightMenu = new VRButtons("RightMenu", (int)TouchControllerButton.Menu | (1 << 16)); - - /// - /// Left VR trigger. - /// + public static readonly VirtualButton RightThumbstickUp = new VRButtons("RightThumbstickUp", (int)TouchControllerButton.Thumbstick | (1 << 16) | (0 << 17), true); + + public static readonly VirtualButton RightThumbstickDown = new VRButtons("RightThumbstickDown", (int)TouchControllerButton.Thumbstick | (1 << 16) | (1 << 17), true); + + public static readonly VirtualButton RightThumbstickLeft = new VRButtons("RightThumbstickLeft", (int)TouchControllerButton.Thumbstick | (1 << 16) | (2 << 17), true); + + public static readonly VirtualButton RightThumbstickRight = new VRButtons("RightThumbstickRight", (int)TouchControllerButton.Thumbstick | (1 << 16) | (3 << 17), true); + + public static readonly VirtualButton RightThumbstickCenter = new VRButtons("RightThumbstickCenter", (int)TouchControllerButton.Thumbstick | (1 << 16) | (4 << 17), true); + + public static readonly VirtualButton RightTouchpadUp = new VRButtons("RightTouchpadUp", (int)TouchControllerButton.Touchpad | (1 << 16) | (0 << 17), true); + + public static readonly VirtualButton RightTouchpadDown = new VRButtons("RightTouchpadDown", (int)TouchControllerButton.Touchpad | (1 << 16) | (1 << 17), true); + + public static readonly VirtualButton RightTouchpadLeft = new VRButtons("RightTouchpadLeft", (int)TouchControllerButton.Touchpad | (1 << 16) | (2 << 17), true); + + public static readonly VirtualButton RightTouchpadRight = new VRButtons("RightTouchpadRight", (int)TouchControllerButton.Touchpad | (1 << 16) | (3 << 17), true); + + public static readonly VirtualButton RightTouchpadCenter = new VRButtons("RightTouchpadCenter", (int)TouchControllerButton.Touchpad | (1 << 16) | (4 << 17), true); + public static readonly VirtualButton LeftTrigger = new VRButtons("LeftTrigger", (int)TouchControllerButton.Trigger); - /// - /// Left VR X. - /// - public static readonly VirtualButton LeftX = new VRButtons("LeftX", (int)TouchControllerButton.X); - - /// - /// Left VR Y. - /// - public static readonly VirtualButton LeftY = new VRButtons("LeftY", (int)TouchControllerButton.Y); - - /// - /// Left VR A. - /// - public static readonly VirtualButton LeftA = new VRButtons("LeftA", (int)TouchControllerButton.A); - - /// - /// Left VR B. - /// - public static readonly VirtualButton LeftB = new VRButtons("LeftB", (int)TouchControllerButton.B); - - /// - /// Left VR Grip. - /// + public static readonly VirtualButton LeftXA = new VRButtons("LeftXA", (int)TouchControllerButton.X); + + public static readonly VirtualButton LeftBYMenu = new VRButtons("LeftBYMenu", (int)TouchControllerButton.Menu); + public static readonly VirtualButton LeftGrip = new VRButtons("LeftGrip", (int)TouchControllerButton.Grip); - /// - /// Left VR Thumbstick Y axis - /// - public static readonly VirtualButton LeftThumbstickY = new VRButtons("LeftThumbstickY", (int)TouchControllerButton.Thumbstick | (1 << 17), true); + public static readonly VirtualButton LeftThumbstickUp = new VRButtons("LeftThumbstickUp", (int)TouchControllerButton.Thumbstick | (0 << 17), true); + + public static readonly VirtualButton LeftThumbstickDown = new VRButtons("LeftThumbstickDown", (int)TouchControllerButton.Thumbstick | (1 << 17), true); - /// - /// Left VR Thumbstick X axis - /// - public static readonly VirtualButton LeftThumbstickX = new VRButtons("LeftThumbstickX", (int)TouchControllerButton.Thumbstick, true); + public static readonly VirtualButton LeftThumbstickLeft = new VRButtons("LeftThumbstickLeft", (int)TouchControllerButton.Thumbstick | (2 << 17), true); - /// - /// Left VR Touchpad Y axis. - /// - public static readonly VirtualButton LeftTouchpadY = new VRButtons("LeftTouchpadY", (int)TouchControllerButton.Touchpad | (1 << 17), true); + public static readonly VirtualButton LeftThumbstickRight = new VRButtons("LeftThumbstickRight", (int)TouchControllerButton.Thumbstick | (3 << 17), true); - /// - /// Left VR Touchpad X axis. - /// - public static readonly VirtualButton LeftTouchpadX = new VRButtons("LeftTouchpadX", (int)TouchControllerButton.Touchpad, true); + public static readonly VirtualButton LeftThumbstickCenter = new VRButtons("LeftThumbstickCenter", (int)TouchControllerButton.Thumbstick | (4 << 17), true); - /// - /// Left VR Menu. - /// - public static readonly VirtualButton LeftMenu = new VRButtons("LeftMenu", (int)TouchControllerButton.Menu); + public static readonly VirtualButton LeftTouchpadUp = new VRButtons("LeftTouchpadUp", (int)TouchControllerButton.Touchpad | (0 << 17), true); + + public static readonly VirtualButton LeftTouchpadDown = new VRButtons("LeftTouchpadDown", (int)TouchControllerButton.Touchpad | (1 << 17), true); + + public static readonly VirtualButton LeftTouchpadLeft = new VRButtons("LeftTouchpadLeft", (int)TouchControllerButton.Touchpad | (2 << 17), true); + + public static readonly VirtualButton LeftTouchpadRight = new VRButtons("LeftTouchpadRight", (int)TouchControllerButton.Touchpad | (3 << 17), true); + + public static readonly VirtualButton LeftTouchpadCenter = new VRButtons("LeftTouchpadCenter", (int)TouchControllerButton.Touchpad | (4 << 17), true); protected VRButtons(string name, int id, bool isPositiveAndNegative = false) : base(name, VirtualButtonType.VR, id, isPositiveAndNegative) @@ -150,21 +97,102 @@ public override bool IsDown() { TouchController tc = VRDeviceSystem.GetSystem?.GetController((Index & (1 << 16)) != 0 ? TouchControllerHand.Right : TouchControllerHand.Left); if (tc == null) return false; - return tc.IsPressed((TouchControllerButton)(Index & 0xFF)); + TouchControllerButton strippedButton = (TouchControllerButton)(Index & 0xFF); + if (tc.IsPressed(strippedButton) == false) return false; + Vector2 axis; + switch (strippedButton) + { + default: + return true; + case TouchControllerButton.Thumbstick: + axis = tc.ThumbstickAxis; + break; + case TouchControllerButton.Touchpad: + axis = tc.ThumbAxis; + break; + } + switch (Index >> 17) + { + case 0: // up + return axis.Y > 0.5f; + case 1: // down + return axis.Y < -0.5f; + case 2: // left + return axis.X < -0.5f; + case 3: // right + return axis.X > 0.5f; + case 4: // center + return axis.X > -0.5f && axis.X < 0.5f && axis.Y < 0.5f && axis.Y > -0.5f; + } + return false; } public override bool IsPressed() { TouchController tc = VRDeviceSystem.GetSystem?.GetController((Index & (1 << 16)) != 0 ? TouchControllerHand.Right : TouchControllerHand.Left); if (tc == null) return false; - return tc.IsPressedDown((TouchControllerButton)(Index & 0xFF)); + TouchControllerButton strippedButton = (TouchControllerButton)(Index & 0xFF); + if (tc.IsPressedDown(strippedButton) == false) return false; + Vector2 axis; + switch (strippedButton) + { + default: + return true; + case TouchControllerButton.Thumbstick: + axis = tc.ThumbstickAxis; + break; + case TouchControllerButton.Touchpad: + axis = tc.ThumbAxis; + break; + } + switch (Index >> 17) + { + case 0: // up + return axis.Y > 0.5f; + case 1: // down + return axis.Y < -0.5f; + case 2: // left + return axis.X < -0.5f; + case 3: // right + return axis.X > 0.5f; + case 4: // center + return axis.X > -0.5f && axis.X < 0.5f && axis.Y < 0.5f && axis.Y > -0.5f; + } + return false; } public override bool IsReleased() { TouchController tc = VRDeviceSystem.GetSystem?.GetController((Index & (1 << 16)) != 0 ? TouchControllerHand.Right : TouchControllerHand.Left); if (tc == null) return false; - return tc.IsPressReleased((TouchControllerButton)(Index & 0xFF)); + TouchControllerButton strippedButton = (TouchControllerButton)(Index & 0xFF); + if (tc.IsPressReleased(strippedButton) == false) return false; + Vector2 axis; + switch (strippedButton) + { + default: + return true; + case TouchControllerButton.Thumbstick: + axis = tc.ThumbstickAxis; + break; + case TouchControllerButton.Touchpad: + axis = tc.ThumbAxis; + break; + } + switch (Index >> 17) + { + case 0: // up + return axis.Y > 0.5f; + case 1: // down + return axis.Y < -0.5f; + case 2: // left + return axis.X < -0.5f; + case 3: // right + return axis.X > 0.5f; + case 4: // center + return axis.X > -0.5f && axis.X < 0.5f && axis.Y < 0.5f && axis.Y > -0.5f; + } + return false; } } } From 141be6bdb7aad52dbecda6e0dc62ef48defd52d7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 8 Feb 2020 19:16:22 -0500 Subject: [PATCH 0722/2038] Vulkan: assure frames are presented in order --- .../SwapChainGraphicsPresenter.Vulkan.cs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs index da8b7ebd33..16e3371a29 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if XENKO_GRAPHICS_API_VULKAN using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; @@ -22,6 +23,8 @@ public class SwapChainGraphicsPresenter : GraphicsPresenter private Swapchain swapChain = Swapchain.Null; private Surface surface; + private ConcurrentQueue toPresent = new ConcurrentQueue(); + private Texture backbuffer; private SwapChainImageInfo[] swapchainImages; private volatile uint currentBufferIndex; @@ -67,7 +70,6 @@ public override object NativePresenter private ManualResetEventSlim presentWaiter = new ManualResetEventSlim(false); private Thread presenterThread; private bool runPresenter; - private volatile uint presentingIndex; private unsafe void PresenterThread() { Swapchain swapChainCopy = swapChain; @@ -82,14 +84,15 @@ private unsafe void PresenterThread() { while (runPresenter) { // wait until we have a frame to present presentWaiter.Wait(); - currentBufferIndexCopy = presentingIndex; - + // are we still OK to present? if (runPresenter == false) return; - using (GraphicsDevice.QueueLock.WriteLock()) - { - GraphicsDevice.NativeCommandQueue.Present(ref presentInfo); + while (toPresent.TryDequeue(out currentBufferIndexCopy)) { + using (GraphicsDevice.QueueLock.WriteLock()) + { + GraphicsDevice.NativeCommandQueue.Present(ref presentInfo); + } } presentWaiter.Reset(); @@ -99,7 +102,7 @@ private unsafe void PresenterThread() { public override unsafe void Present() { // collect and let presenter thread know to present - presentingIndex = currentBufferIndex; + toPresent.Enqueue(currentBufferIndex); presentWaiter.Set(); // Get next image @@ -109,7 +112,8 @@ public override unsafe void Present() // re-create and do a "lite" re-present // unfortunately this will likely crash, since recreating swapchains isn't stable CreateSwapChain(); - presentingIndex = currentBufferIndex; + while (toPresent.IsEmpty == false) toPresent.TryDequeue(out _); + toPresent.Enqueue(currentBufferIndex); presentWaiter.Set(); return; } From 7d871e0753418167ac08f5de2c5cd531581d384d Mon Sep 17 00:00:00 2001 From: tebjan Date: Sat, 1 Feb 2020 06:18:28 +0100 Subject: [PATCH 0723/2038] [Games] Added Closing event to GameWindow --- .../Xenko.Games/Desktop/GameWindowWinforms.cs | 1 + sources/engine/Xenko.Games/GameWindow.cs | 17 ++++++++++++++--- .../Xenko.Games/OpenTK/GameWindowOpenTK.cs | 1 + sources/engine/Xenko.Games/SDL/GameWindowSDL.cs | 6 ++++++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.Games/Desktop/GameWindowWinforms.cs b/sources/engine/Xenko.Games/Desktop/GameWindowWinforms.cs index 0a75e943e6..a70534c3a1 100644 --- a/sources/engine/Xenko.Games/Desktop/GameWindowWinforms.cs +++ b/sources/engine/Xenko.Games/Desktop/GameWindowWinforms.cs @@ -172,6 +172,7 @@ protected override void Initialize(GameContext gameContext) //gameForm.AppDeactivated += OnDeactivated; gameForm.UserResized += OnClientSizeChanged; gameForm.FullscreenToggle += OnFullscreenToggle; + gameForm.FormClosing += OnClosing; } else { diff --git a/sources/engine/Xenko.Games/GameWindow.cs b/sources/engine/Xenko.Games/GameWindow.cs index 706da15758..2cfa6dcedb 100644 --- a/sources/engine/Xenko.Games/GameWindow.cs +++ b/sources/engine/Xenko.Games/GameWindow.cs @@ -54,7 +54,7 @@ public abstract class GameWindow : ComponentBase public event EventHandler Activated; /// - /// Occurs, when device client size is changed. + /// Occurs when device client size is changed. /// public event EventHandler ClientSizeChanged; @@ -64,15 +64,20 @@ public abstract class GameWindow : ComponentBase public event EventHandler Deactivated; /// - /// Occurs, when device orientation is changed. + /// Occurs when device orientation is changed. /// public event EventHandler OrientationChanged; /// - /// Occurs, when device full screen mode is toggled. + /// Occurs when device full screen mode is toggled. /// public event EventHandler FullscreenToggle; + /// + /// Occurs before the window gets destroyed. + /// + public event EventHandler Closing; + #endregion #region Public Properties @@ -245,6 +250,12 @@ protected void OnFullscreenToggle(object source, EventArgs e) handler?.Invoke(this, e); } + protected void OnClosing(object source, EventArgs e) + { + var handler = Closing; + handler?.Invoke(this, e); + } + protected abstract void SetTitle(string title); #endregion diff --git a/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs b/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs index e94cd0a2a7..3f06b47c78 100644 --- a/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs +++ b/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs @@ -92,6 +92,7 @@ protected override void Initialize(GameContext gameContext) gameForm.MouseLeave += GameWindowForm_MouseLeave; gameForm.Resize += OnClientSizeChanged; + gameForm.Unload += OnClosing; } internal override void Run() diff --git a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs index b58ebc04ff..730434fd26 100644 --- a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs +++ b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs @@ -86,6 +86,7 @@ protected override void Initialize(GameContext gameContext) gameForm.AppActivated += OnActivated; gameForm.AppDeactivated += OnDeactivated; gameForm.UserResized += OnClientSizeChanged; + gameForm.CloseActions += GameForm_CloseActions; } else { @@ -93,6 +94,11 @@ protected override void Initialize(GameContext gameContext) } } + private void GameForm_CloseActions() + { + OnClosing(this, new EventArgs()); + } + internal override void Run() { Debug.Assert(InitCallback != null, $"{nameof(InitCallback)} is null"); From f1c941d8acf9ea525c1cde7796dbce16f9def378 Mon Sep 17 00:00:00 2001 From: yangguosdxl Date: Sun, 9 Feb 2020 06:38:50 +0800 Subject: [PATCH 0724/2038] fix bug: Android Resource error #553 (#595) --- sources/engine/Xenko.Engine/Starter/AndroidXenkoActivity.cs | 2 ++ sources/engine/Xenko.Engine/Xenko.Engine.csproj | 2 ++ 2 files changed, 4 insertions(+) diff --git a/sources/engine/Xenko.Engine/Starter/AndroidXenkoActivity.cs b/sources/engine/Xenko.Engine/Starter/AndroidXenkoActivity.cs index 65aa27d047..8af6a59838 100644 --- a/sources/engine/Xenko.Engine/Starter/AndroidXenkoActivity.cs +++ b/sources/engine/Xenko.Engine/Starter/AndroidXenkoActivity.cs @@ -21,6 +21,8 @@ namespace Xenko.Starter { + using Resource = Xenko.Engine.Resource; + // NOTE: the class should implement View.IOnSystemUiVisibilityChangeListener but doing so will prevent the engine to work on Android below 3.0 (API Level 11 is mandatory). // So the methods are implemented but the class does not implement View.IOnSystemUiVisibilityChangeListener. // Maybe this will change when support for API Level 10 is dropped diff --git a/sources/engine/Xenko.Engine/Xenko.Engine.csproj b/sources/engine/Xenko.Engine/Xenko.Engine.csproj index 1fab3a9786..23451104c1 100644 --- a/sources/engine/Xenko.Engine/Xenko.Engine.csproj +++ b/sources/engine/Xenko.Engine/Xenko.Engine.csproj @@ -20,6 +20,8 @@ Xenko true true + + Xenko.Engine From 08181218f87f530c1874e9398b733c0cd564998c Mon Sep 17 00:00:00 2001 From: tebjan Date: Thu, 30 Jan 2020 20:15:51 +0100 Subject: [PATCH 0725/2038] [Core] Binary directory can be one level below calling executable. This allows for a /bin or /lib folder next to the exe with all assemblies and data inside --- sources/core/Xenko.Core/PlatformFolders.cs | 29 ++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/sources/core/Xenko.Core/PlatformFolders.cs b/sources/core/Xenko.Core/PlatformFolders.cs index 364c769a8f..49f7c0d50a 100644 --- a/sources/core/Xenko.Core/PlatformFolders.cs +++ b/sources/core/Xenko.Core/PlatformFolders.cs @@ -182,6 +182,11 @@ private static string GetApplicationTemporaryDirectory() [NotNull] private static string GetApplicationBinaryDirectory() { + return FindCoreAssemblyDirectory(GetApplicationExecutableDiretory()); + } + + private static string GetApplicationExecutableDiretory() + { #if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_MONO_MOBILE || XENKO_PLATFORM_UNIX var executableName = GetApplicationExecutablePath(); if (!string.IsNullOrEmpty(executableName)) @@ -200,6 +205,30 @@ private static string GetApplicationBinaryDirectory() #endif } + static string FindCoreAssemblyDirectory(string entryDirectory) + { + //simple case + var corePath = Path.Combine(entryDirectory, "Xenko.Core.dll"); + if (File.Exists(corePath)) + { + return entryDirectory; + } + else //search one level down + { + foreach (var subfolder in Directory.GetDirectories(entryDirectory)) + { + corePath = Path.Combine(subfolder, "Xenko.Core.dll"); + if (File.Exists(corePath)) + { + return subfolder; + } + } + } + + //if nothing found, return input + return entryDirectory; + } + [NotNull] private static string GetApplicationDataDirectory() { From 527afb871f43a8aaacf71269fe30ba9a2296ee5a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 8 Feb 2020 21:56:17 -0500 Subject: [PATCH 0726/2038] VR: Fix VR touchpad pressed check --- .../Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs index 0e89914c56..ef7e79517d 100644 --- a/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs +++ b/sources/engine/Xenko.VirtualReality/OpenVR/OpenVrTouchController.cs @@ -83,10 +83,12 @@ private OpenVR.Controller.ButtonId ToOpenVrButton(TouchControllerButton button) { switch (button) { + case TouchControllerButton.Thumbstick: + return OpenVR.Controller.ButtonId.ButtonAxis3; case TouchControllerButton.A: case TouchControllerButton.X: return OpenVR.Controller.ButtonId.ButtonA; - case TouchControllerButton.Thumbstick: + case TouchControllerButton.Touchpad: return OpenVR.Controller.ButtonId.ButtonSteamVrTouchpad; case TouchControllerButton.Trigger: return OpenVR.Controller.ButtonId.ButtonSteamVrTrigger; From 1270e654d20fe3506fcb2d7708149971aa07116d Mon Sep 17 00:00:00 2001 From: Tebjan Halm Date: Mon, 10 Feb 2020 07:26:49 +0100 Subject: [PATCH 0727/2038] [Games] Fix external main loop support on windows (#594) # Conflicts: # sources/engine/Xenko.Games/GameBase.cs --- sources/engine/Xenko.Games/GameBase.cs | 11 +++++++---- sources/engine/Xenko.Games/GameContext.cs | 5 +++++ sources/engine/Xenko.Games/GameContextWinforms.cs | 5 ----- sources/engine/Xenko.Games/GamePlatform.cs | 6 ++++++ 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/sources/engine/Xenko.Games/GameBase.cs b/sources/engine/Xenko.Games/GameBase.cs index 762d44ed10..84d1d9ceb8 100644 --- a/sources/engine/Xenko.Games/GameBase.cs +++ b/sources/engine/Xenko.Games/GameBase.cs @@ -682,10 +682,13 @@ private void TickInternal() bool focusMinimized = focused == false && TreatNotFocusedLikeMinimized; bool visible = minimized == false && gamePlatform.MainWindow.Visible && (gamePlatform.MainWindow.IsFullscreen == false || focused); EndDraw(visible); - if (visible == false || minimized || focusMinimized) - MinimizedMinimumUpdateRate.Throttle(out _); - else - WindowMinimumUpdateRate.Throttle(out _); + if (gamePlatform.IsBlockingRun) + { + if (visible == false || minimized || focusMinimized) + MinimizedMinimumUpdateRate.Throttle(out _); + else + WindowMinimumUpdateRate.Throttle(out _); + } } } diff --git a/sources/engine/Xenko.Games/GameContext.cs b/sources/engine/Xenko.Games/GameContext.cs index 5e6d2f3d17..c26323dad2 100644 --- a/sources/engine/Xenko.Games/GameContext.cs +++ b/sources/engine/Xenko.Games/GameContext.cs @@ -38,6 +38,11 @@ public abstract class GameContext /// public AppContextType ContextType { get; protected set; } + /// + /// Indicating whether the user will call the main loop. E.g. Xenko is used as a library. + /// + public bool IsUserManagingRun { get; protected set; } + // TODO: remove these requested values. /// diff --git a/sources/engine/Xenko.Games/GameContextWinforms.cs b/sources/engine/Xenko.Games/GameContextWinforms.cs index 48ea0049d0..c1c215577a 100644 --- a/sources/engine/Xenko.Games/GameContextWinforms.cs +++ b/sources/engine/Xenko.Games/GameContextWinforms.cs @@ -40,11 +40,6 @@ public GameContextWinforms(Control control, int requestedWidth = 0, int requeste IsUserManagingRun = isUserManagingRun; } - /// - /// The is running delegate - /// - public bool IsUserManagingRun { get; protected set; } - /// /// Gets the run loop to be called when is true. /// diff --git a/sources/engine/Xenko.Games/GamePlatform.cs b/sources/engine/Xenko.Games/GamePlatform.cs index c2fc8a64d4..0f915599d5 100644 --- a/sources/engine/Xenko.Games/GamePlatform.cs +++ b/sources/engine/Xenko.Games/GamePlatform.cs @@ -102,10 +102,16 @@ public virtual GameWindow CreateWindow(GameContext gameContext) throw new ArgumentException("Game Window context not supported on this platform"); } + /// + /// If true, is blocking until the game is exited, i.e. internal main loop is used. + /// If false, returns immediately and the caller has to manage the main loop by invoking the . + /// public bool IsBlockingRun { get; protected set; } public void Run(GameContext gameContext) { + IsBlockingRun = !gameContext.IsUserManagingRun; + gameWindow = CreateWindow(gameContext); // Register on Activated From 60cdc0bed8a9931fda6676942348c2fa31736e04 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 11 Feb 2020 09:55:55 -0500 Subject: [PATCH 0728/2038] Update README.md --- README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cbf1399f5b..647de667f1 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ My games require the engine to be developed at a faster pace than Xenko. I'm in ## What is different? -Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. However, I do not maintain different languages, Android support or the Launcher to "Focus" on things like: +Most of Focus is similar to Xenko and there shouldn't be any loss of functionality over the original. Changes are focused on fixes, performance improvements and new features. However, I do not maintain different languages, Android support or the Launcher. The following is a rough list of "major" changes, but might not accurately reflect the current state of differences (since both githubs are moving targets which are hopefully improving): * Virtual Reality: frame rate management, resolution detection, Vulkan support, and automatic UI interaction are some of the VR improvements you'll get "out of the box". Pretty much just need to enable OpenVR in your Graphics Compositor's Forward Renderer and you'll be good to go. Tracking hands is much easier, as you can simply select which hand to track right from GameStudio. Support for multiple forward renderers in VR, with post processing. See https://github.com/phr00t/FOVTester2 for a super simple example of how easy a VR project is. * Vulkan: Focus primarily uses Vulkan, which has been significantly overhauled to provide more performance you'd expect from the newer API. Vulkan works on MacOSX using MoltenVK and Linux. DirectX is deprecated and unsupported on this fork. @@ -43,6 +43,12 @@ Most of Focus is similar to Xenko and there shouldn't be any loss of functionali * Simple binary distribution: No launcher needed. Just download and run the latest release (after making sure you have all of the Visual Studio build prerequisites, see https://github.com/phr00t/FocusEngine/releases. * Probably lots of other stuff: haven't kept that great of track of improvements, I usually fix things as needed and keep moving forward! +## What is worse in this fork? + +Android and mobile support, different languages, Universal Windows Platform support. I also work very little with DirectX, which is maintained just for the editor. Some changes I make to improve Vulkan might cause a (hopefully minor) bug in the DirectX API, which will be of low priority to fix. Vulkan isn't as fully featured as DirectX yet, so GPU instancing doesn't work on Vulkan (although you may find the ModelBatcher works in many cases). + +Creating templates with this fork is semi broken (you'll get an error, but it still gets created). Just browse for it next time you open Focus. There is an issue for it on the issues tab. + ## License Focus is covered by [MIT](LICENSE.md), unless stated otherwise (i.e. for some files that are copied from other projects). @@ -61,7 +67,7 @@ Find explanations and information about Xenko: ## Community Ask for help or report issues: -* [Chat with the community on Discord](https://discord.gg/f6aerfE) [![Join the chat at https://discord.gg/f6aerfE](https://img.shields.io/discord/500285081265635328.svg?style=flat&logo=discord&label=discord)](https://discord.gg/f6aerfE) +* [Chat with the community on Discord](https://discord.gg/k563cUH) * [Discuss topics on our forums](http://forums.xenko.com/) * [Report engine issues](https://github.com/phr00t/xenko/issues) * [Donate to support the project](https://www.patreon.com/phr00tssoftware) From c927d924ae161a34664f3c383200218739e4d8f1 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 11 Feb 2020 09:56:31 -0500 Subject: [PATCH 0729/2038] Update README.md --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 647de667f1..6dea4d206b 100644 --- a/README.md +++ b/README.md @@ -55,8 +55,6 @@ Focus is covered by [MIT](LICENSE.md), unless stated otherwise (i.e. for some fi You can find the list of third party projects [here](THIRD%20PARTY.md). -Contributors need to sign the following [Contribution License Agreement](docs/ContributorLicenseAgreement.md). - ## Documentation Find explanations and information about Xenko: From 1f0c9c3f451d9770f80b842ce63fa0af9e69458e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 11 Feb 2020 12:54:49 -0500 Subject: [PATCH 0730/2038] Audio: disable Xaudio2, so all platforms use the same OpenAL library Easier to assure cross platform compatibility --- .../engine/Xenko.Audio/DynamicSoundSource.cs | 4 +- sources/engine/Xenko.Audio/Native/OpenAL.cpp | 2 +- sources/engine/Xenko.Audio/Native/XAudio2.cpp | 2182 ----------------- sources/engine/Xenko.Audio/Xenko.Audio.csproj | 5 +- 4 files changed, 3 insertions(+), 2190 deletions(-) delete mode 100644 sources/engine/Xenko.Audio/Native/XAudio2.cpp diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 43b5e435d5..a5e64b4093 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -250,9 +250,7 @@ protected virtual void StopInternal(bool ignoreQueuedBuffer = true) Ended.TrySetResult(true); state = PlayState.Stopped; soundInstance.playState = PlayState.Stopped; - if (ignoreQueuedBuffer) - AudioLayer.SourceStop(soundInstance.Source); - else AudioLayer.SourceFlushBuffers(soundInstance.Source); + if (ignoreQueuedBuffer) AudioLayer.SourceStop(soundInstance.Source); RestartInternal(); } diff --git a/sources/engine/Xenko.Audio/Native/OpenAL.cpp b/sources/engine/Xenko.Audio/Native/OpenAL.cpp index c4b4ba41a1..8f6f58a255 100644 --- a/sources/engine/Xenko.Audio/Native/OpenAL.cpp +++ b/sources/engine/Xenko.Audio/Native/OpenAL.cpp @@ -3,7 +3,7 @@ #include "Common.h" -#if defined(PLATFORM_LINUX) || defined(PLATFORM_MACOS) || defined(IOS) || !defined(__clang__) +#if defined(WINDOWS_DESKTOP) || defined(PLATFORM_LINUX) || defined(PLATFORM_MACOS) || defined(IOS) || !defined(__clang__) #include "../../../deps/NativePath/NativePath.h" #include "../../../deps/NativePath/NativeDynamicLinking.h" diff --git a/sources/engine/Xenko.Audio/Native/XAudio2.cpp b/sources/engine/Xenko.Audio/Native/XAudio2.cpp deleted file mode 100644 index bb3057b3ba..0000000000 --- a/sources/engine/Xenko.Audio/Native/XAudio2.cpp +++ /dev/null @@ -1,2182 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#include "Common.h" - -#if defined(WINDOWS_DESKTOP) || defined(UWP) || defined(WINDOWS_STORE) || defined(WINDOWS_PHONE) || !defined(__clang__) - -#include "../../../deps/NativePath/NativePath.h" -#include "../../../deps/NativePath/NativeThreading.h" -#include "../../../deps/NativePath/NativeDynamicLinking.h" -#include "../../Xenko.Native/XenkoNative.h" - -extern "C" { - class SpinLock - { - public: - SpinLock(); - - void Lock(); - - void Unlock(); - - private: - volatile bool mLocked; - }; - - namespace XAudio2 - { - typedef struct _GUID { - unsigned long Data1; - unsigned short Data2; - unsigned short Data3; - unsigned char Data4[8]; - } GUID; - - typedef GUID IID; - - typedef unsigned long DWORD; - typedef int BOOL; - typedef unsigned char BYTE; - typedef unsigned short WORD; - typedef float FLOAT; - typedef FLOAT *PFLOAT; - typedef int INT; - typedef unsigned int UINT; - typedef unsigned int *PUINT; - -#define REFIID const IID & -#define HRESULT long -#define UINT32 unsigned int -#define ULONG unsigned long -#define THIS_ -#define THIS void -#define PURE = 0; -#define _Outptr_ -#define _In_ -#define _In_opt_ -#define _Out_ -#define X2DEFAULT(x) =x -#define _Reserved_ -#define _In_reads_bytes_(_xxx_) -#define _Out_writes_bytes_(_xxx_) -#define _Out_writes_(_xxx_) -#define _In_reads_(_xxx_) -#define STDMETHOD(method) virtual HRESULT __stdcall method -#define STDMETHOD_(type,method) virtual type __stdcall method -#define XAUDIO2_COMMIT_NOW 0 // Used as an OperationSet argument -#define XAUDIO2_COMMIT_ALL 0 // Used in IXAudio2::CommitChanges -#define XAUDIO2_INVALID_OPSET (UINT32)(-1) // Not allowed for OperationSet arguments -#define XAUDIO2_NO_LOOP_REGION 0 // Used in XAUDIO2_BUFFER.LoopCount -#define XAUDIO2_LOOP_INFINITE 255 // Used in XAUDIO2_BUFFER.LoopCount -#define XAUDIO2_DEFAULT_CHANNELS 0 // Used in CreateMasteringVoice -#define XAUDIO2_DEFAULT_SAMPLERATE 0 // Used in CreateMasteringVoice -#define BYTE char -#define UINT64 unsigned __int64 -#define _In_opt_z_ -#define FAILED(hr) (((HRESULT)(hr)) < 0) -#define _Inout_ - -#define X3DAUDIO_PI 3.141592654f -#define X3DAUDIO_2PI 6.283185307f - -#if !defined(_SPEAKER_POSITIONS_) -#define _SPEAKER_POSITIONS_ -#define SPEAKER_FRONT_LEFT 0x00000001 -#define SPEAKER_FRONT_RIGHT 0x00000002 -#define SPEAKER_FRONT_CENTER 0x00000004 -#define SPEAKER_LOW_FREQUENCY 0x00000008 -#define SPEAKER_BACK_LEFT 0x00000010 -#define SPEAKER_BACK_RIGHT 0x00000020 -#define SPEAKER_FRONT_LEFT_OF_CENTER 0x00000040 -#define SPEAKER_FRONT_RIGHT_OF_CENTER 0x00000080 -#define SPEAKER_BACK_CENTER 0x00000100 -#define SPEAKER_SIDE_LEFT 0x00000200 -#define SPEAKER_SIDE_RIGHT 0x00000400 -#define SPEAKER_TOP_CENTER 0x00000800 -#define SPEAKER_TOP_FRONT_LEFT 0x00001000 -#define SPEAKER_TOP_FRONT_CENTER 0x00002000 -#define SPEAKER_TOP_FRONT_RIGHT 0x00004000 -#define SPEAKER_TOP_BACK_LEFT 0x00008000 -#define SPEAKER_TOP_BACK_CENTER 0x00010000 -#define SPEAKER_TOP_BACK_RIGHT 0x00020000 -#define SPEAKER_RESERVED 0x7FFC0000 // bit mask locations reserved for future use -#define SPEAKER_ALL 0x80000000 // used to specify that any possible permutation of speaker configurations -#endif - - // standard speaker geometry configurations, used with X3DAudioInitialize -#if !defined(SPEAKER_MONO) -#define SPEAKER_MONO SPEAKER_FRONT_CENTER -#define SPEAKER_STEREO (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT) -#define SPEAKER_2POINT1 (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY) -#define SPEAKER_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER) -#define SPEAKER_QUAD (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT) -#define SPEAKER_4POINT1 (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT) -#define SPEAKER_5POINT1 (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT) -#define SPEAKER_7POINT1 (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER) -#define SPEAKER_5POINT1_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT) -#define SPEAKER_7POINT1_SURROUND (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT) -#endif - -#define X3DAUDIO_CALCULATE_MATRIX 0x00000001 // enable matrix coefficient table calculation -#define X3DAUDIO_CALCULATE_DELAY 0x00000002 // enable delay time array calculation (stereo final mix only) -#define X3DAUDIO_CALCULATE_LPF_DIRECT 0x00000004 // enable LPF direct-path coefficient calculation -#define X3DAUDIO_CALCULATE_LPF_REVERB 0x00000008 // enable LPF reverb-path coefficient calculation -#define X3DAUDIO_CALCULATE_REVERB 0x00000010 // enable reverb send level calculation -#define X3DAUDIO_CALCULATE_DOPPLER 0x00000020 // enable doppler shift factor calculation -#define X3DAUDIO_CALCULATE_EMITTER_ANGLE 0x00000040 // enable emitter-to-listener interior angle calculation - -#define HRTF_MAX_GAIN_LIMIT 12.0f -#define HRTF_MIN_GAIN_LIMIT -96.0f -#define HRTF_MIN_UNITY_GAIN_DISTANCE 0.05f -#define HRTF_DEFAULT_UNITY_GAIN_DISTANCE 1.0f -#define HRTF_DEFAULT_CUTOFF_DISTANCE FLT_MAX - - struct IUnknown - { - // NAME: IXAudio2::QueryInterface - // DESCRIPTION: Queries for a given COM interface on the XAudio2 object. - // Only IID_IUnknown and IID_IXAudio2 are supported. - // - // ARGUMENTS: - // riid - IID of the interface to be obtained. - // ppvInterface - Returns a pointer to the requested interface. - // - STDMETHOD(QueryInterface) (THIS_ REFIID riid, _Outptr_ void** ppvInterface) PURE; - - // NAME: IXAudio2::AddRef - // DESCRIPTION: Adds a reference to the XAudio2 object. - // - STDMETHOD_(ULONG, AddRef) (THIS) PURE; - - // NAME: IXAudio2::Release - // DESCRIPTION: Releases a reference to the XAudio2 object. - // - STDMETHOD_(ULONG, Release) (THIS) PURE; - }; - - //! Represents a position in 3D space, using a right-handed coordinate system. - typedef struct HrtfPosition - { - float x; - float y; - float z; - } HrtfPosition; - - //! Indicates the orientation of an HRTF directivity object. This is a row-major 3x3 rotation matrix. - typedef struct HrtfOrientation - { - float element[9]; - } HrtfOrientation; - - //! Indicates one of several stock directivity patterns. - typedef enum HrtfDirectivityType - { - //! The sound emission is in all directions. - OmniDirectional = 0, - //! The sound emission is a cardiod shape. - Cardioid, - //! The sound emission is a cone. - Cone - } HrtfDirectivityType; - - //! Indicates one of several stock environment types. - typedef enum HrtfEnvironment - { - //! A small room. - Small = 0, - //! A medium-sized room. - Medium, - //! A large enclosed space. - Large, - //! An outdoor space. - Outdoors, - } HrtfEnvironment; - - // - //! Base directivity pattern descriptor. Describes the type of directivity applied to a sound. - //! The scaling parameter is used to interpolate between directivity behavior and omnidirectional; it determines how much attenuation is applied to the source outside of the directivity pattern and controls how directional the source is. - // - typedef struct HrtfDirectivity - { - //! Indicates the type of directivity. - HrtfDirectivityType type; - //! A normalized value between zero and one. Specifies the amount of linear interpolation between omnidirectional sound and the full directivity pattern, where 0 is fully omnidirectional and 1 is fully directional. - float scaling; - } HrtfDirectivity; - - //! Describes a cardioid directivity pattern. - typedef struct HrtfDirectivityCardioid - { - //! Descriptor for the cardioid pattern. The type parameter must be set to HrtfDirectivityType.Cardioid. - HrtfDirectivity directivity; - //! Order controls the shape of the cardioid. The higher order the shape, the narrower it is. Must be greater than 0 and less than or equal to 32. - float order; - } HrtfDirectivityCardioid; - - // - //! Describes a cone directivity. - //! Attenuation is 0 inside the inner cone. - //! Attenuation is linearly interpolated between the inner cone, which is defined by innerAngle, and the outer cone, which is defined by outerAngle. - // - typedef struct HrtfDirectivityCone - { - //! Descriptor for the cone pattern. The type parameter must be set to HrtfDirectivityType.Cone. - HrtfDirectivity directivity; - //! Angle, in radians, that defines the inner cone. Must be between 0 and 2 * pi. - float innerAngle; - //! Angle, in radians, that defines the outer cone. Must be between 0 and 2 * pi. - float outerAngle; - } HrtfDirectivityCone; - - // - //! Indicates a distance-based decay type applied to a sound. - // - typedef enum HrtfDistanceDecayType - { - //! Simulates natural decay with distance, as constrained by minimum and maximum gain distance limits. Drops to silence at rolloff distance. - NaturalDecay = 0, - //! Used to set up a custom gain curve, within the maximum and minimum gain limit. - CustomDecay - } HrtfDistanceDecayType; - - // - //! Describes a distance-based decay behavior. - // - typedef struct HrtfDistanceDecay - { - //! The type of decay behavior, natural or custom. - HrtfDistanceDecayType type; - //! The maximum gain limit applied at any distance. Applies to both natural and custom decay. This value is specified in dB, with a range from -96 to 12 inclusive. The default value is 12 dB. - float maxGain; - //! The minimum gain limit applied at any distance. Applies to both natural and custom decay. This value is specified in dB, with a range from -96 to 12 inclusive. The default value is -96 dB. - float minGain; - //! The distance at which the gain is 0dB. Applies to natural decay only. This value is specified in meters, with a range from 0.05 to infinity (FLT_MAX). The default value is 1 meter. - float unityGainDistance; - //! The distance at which output is silent. Applies to natural decay only. This value is specified in meters, with a range from zero (non-inclusive) to infinity (FLT_MAX). The default value is infinity. - float cutoffDistance; - } HrtfDistanceDecay; - - // - //! Specifies parameters used to initialize HRTF. - //! - //! Instances of the XAPO interface are created by using the CreateHrtfApo() API: - //! ```STDAPI CreateHrtfApo(_In_ const HrtfApoInit* pInit, _Outptr_ IXAPO** ppXapo);``` - //! - // - typedef struct HrtfApoInit - { - //! The decay type. If you pass in nullptr, the default value will be used. The default is natural decay. - HrtfDistanceDecay* distanceDecay; - //! The directivity type. If you pass in nullptr, the default value will be used. The default directivity is omni-directional. - HrtfDirectivity* directivity; - } HrtfApoInit; - - struct XMFLOAT3 - { - float x; - float y; - float z; - - XMFLOAT3(); - - XMFLOAT3(float _x, float _y, float _z); - - explicit XMFLOAT3(_In_reads_(3) const float* pArray); - - XMFLOAT3& operator=(const XMFLOAT3& Float3); - }; - - typedef float FLOAT32; // 32-bit IEEE float - typedef XMFLOAT3 X3DAUDIO_VECTOR; // float 3D vector - -#pragma pack(push, 1) - - typedef struct X3DAUDIO_CONE - { - FLOAT32 InnerAngle; // inner cone angle in radians, must be within [0.0f, X3DAUDIO_2PI] - FLOAT32 OuterAngle; // outer cone angle in radians, must be within [InnerAngle, X3DAUDIO_2PI] - - FLOAT32 InnerVolume; // volume level scaler on/within inner cone, used only for matrix calculations, must be within [0.0f, 2.0f] when used - FLOAT32 OuterVolume; // volume level scaler on/beyond outer cone, used only for matrix calculations, must be within [0.0f, 2.0f] when used - FLOAT32 InnerLPF; // LPF (both direct and reverb paths) coefficient subtrahend on/within inner cone, used only for LPF (both direct and reverb paths) calculations, must be within [0.0f, 1.0f] when used - FLOAT32 OuterLPF; // LPF (both direct and reverb paths) coefficient subtrahend on/beyond outer cone, used only for LPF (both direct and reverb paths) calculations, must be within [0.0f, 1.0f] when used - FLOAT32 InnerReverb; // reverb send level scaler on/within inner cone, used only for reverb calculations, must be within [0.0f, 2.0f] when used - FLOAT32 OuterReverb; // reverb send level scaler on/beyond outer cone, used only for reverb calculations, must be within [0.0f, 2.0f] when used - } X3DAUDIO_CONE, *LPX3DAUDIO_CONE; - static const X3DAUDIO_CONE X3DAudioDefault_DirectionalCone = { X3DAUDIO_PI / 2, X3DAUDIO_PI, 1.0f, 0.708f, 0.0f, 0.25f, 0.708f, 1.0f }; - - typedef struct X3DAUDIO_LISTENER - { - X3DAUDIO_VECTOR OrientFront; // orientation of front direction, used only for matrix and delay calculations or listeners with cones for matrix, LPF (both direct and reverb paths), and reverb calculations, must be normalized when used - X3DAUDIO_VECTOR OrientTop; // orientation of top direction, used only for matrix and delay calculations, must be orthonormal with OrientFront when used - - X3DAUDIO_VECTOR Position; // position in user-defined world units, does not affect Velocity - X3DAUDIO_VECTOR Velocity; // velocity vector in user-defined world units/second, used only for doppler calculations, does not affect Position - - X3DAUDIO_CONE* pCone; // sound cone, used only for matrix, LPF (both direct and reverb paths), and reverb calculations, NULL specifies omnidirectionality - } X3DAUDIO_LISTENER, *LPX3DAUDIO_LISTENER; - - typedef struct X3DAUDIO_DISTANCE_CURVE_POINT - { - FLOAT32 Distance; // normalized distance, must be within [0.0f, 1.0f] - FLOAT32 DSPSetting; // DSP setting - } X3DAUDIO_DISTANCE_CURVE_POINT, *LPX3DAUDIO_DISTANCE_CURVE_POINT; - - typedef struct X3DAUDIO_DISTANCE_CURVE - { - X3DAUDIO_DISTANCE_CURVE_POINT* pPoints; // distance curve point array, must have at least PointCount elements with no duplicates and be sorted in ascending order with respect to Distance - UINT32 PointCount; // number of distance curve points, must be >= 2 as all distance curves must have at least two endpoints, defining DSP settings at 0.0f and 1.0f normalized distance - } X3DAUDIO_DISTANCE_CURVE, *LPX3DAUDIO_DISTANCE_CURVE; - static const X3DAUDIO_DISTANCE_CURVE_POINT X3DAudioDefault_LinearCurvePoints[2] = { {0.0f, 1.0f}, {1.0f, 0.0f} }; - static const X3DAUDIO_DISTANCE_CURVE X3DAudioDefault_LinearCurve = { (X3DAUDIO_DISTANCE_CURVE_POINT*)&X3DAudioDefault_LinearCurvePoints[0], 2 }; - - typedef struct X3DAUDIO_EMITTER - { - X3DAUDIO_CONE* pCone; // sound cone, used only with single-channel emitters for matrix, LPF (both direct and reverb paths), and reverb calculations, NULL specifies omnidirectionality - X3DAUDIO_VECTOR OrientFront; // orientation of front direction, used only for emitter angle calculations or with multi-channel emitters for matrix calculations or single-channel emitters with cones for matrix, LPF (both direct and reverb paths), and reverb calculations, must be normalized when used - X3DAUDIO_VECTOR OrientTop; // orientation of top direction, used only with multi-channel emitters for matrix calculations, must be orthonormal with OrientFront when used - - X3DAUDIO_VECTOR Position; // position in user-defined world units, does not affect Velocity - X3DAUDIO_VECTOR Velocity; // velocity vector in user-defined world units/second, used only for doppler calculations, does not affect Position - - FLOAT32 InnerRadius; // inner radius, must be within [0.0f, FLT_MAX] - FLOAT32 InnerRadiusAngle; // inner radius angle, must be within [0.0f, X3DAUDIO_PI/4.0) - - UINT32 ChannelCount; // number of sound channels, must be > 0 - FLOAT32 ChannelRadius; // channel radius, used only with multi-channel emitters for matrix calculations, must be >= 0.0f when used - FLOAT32* pChannelAzimuths; // channel azimuth array, used only with multi-channel emitters for matrix calculations, contains positions of each channel expressed in radians along the channel radius with respect to the front orientation vector in the plane orthogonal to the top orientation vector, or X3DAUDIO_2PI to specify an LFE channel, must have at least ChannelCount elements, all within [0.0f, X3DAUDIO_2PI] when used - - X3DAUDIO_DISTANCE_CURVE* pVolumeCurve; // volume level distance curve, used only for matrix calculations, NULL specifies a default curve that conforms to the inverse square law, calculated in user-defined world units with distances <= CurveDistanceScaler clamped to no attenuation - X3DAUDIO_DISTANCE_CURVE* pLFECurve; // LFE level distance curve, used only for matrix calculations, NULL specifies a default curve that conforms to the inverse square law, calculated in user-defined world units with distances <= CurveDistanceScaler clamped to no attenuation - X3DAUDIO_DISTANCE_CURVE* pLPFDirectCurve; // LPF direct-path coefficient distance curve, used only for LPF direct-path calculations, NULL specifies the default curve: [0.0f,1.0f], [1.0f,0.75f] - X3DAUDIO_DISTANCE_CURVE* pLPFReverbCurve; // LPF reverb-path coefficient distance curve, used only for LPF reverb-path calculations, NULL specifies the default curve: [0.0f,0.75f], [1.0f,0.75f] - X3DAUDIO_DISTANCE_CURVE* pReverbCurve; // reverb send level distance curve, used only for reverb calculations, NULL specifies the default curve: [0.0f,1.0f], [1.0f,0.0f] - - FLOAT32 CurveDistanceScaler; // curve distance scaler, used to scale normalized distance curves to user-defined world units and/or exaggerate their effect, used only for matrix, LPF (both direct and reverb paths), and reverb calculations, must be within [FLT_MIN, FLT_MAX] when used - FLOAT32 DopplerScaler; // doppler shift scaler, used to exaggerate doppler shift effect, used only for doppler calculations, must be within [0.0f, FLT_MAX] when used - } X3DAUDIO_EMITTER, *LPX3DAUDIO_EMITTER; - - typedef struct X3DAUDIO_DSP_SETTINGS - { - FLOAT32* pMatrixCoefficients; // [inout] matrix coefficient table, receives an array representing the volume level used to send from source channel S to destination channel D, stored as pMatrixCoefficients[SrcChannelCount * D + S], must have at least SrcChannelCount*DstChannelCount elements - FLOAT32* pDelayTimes; // [inout] delay time array, receives delays for each destination channel in milliseconds, must have at least DstChannelCount elements (stereo final mix only) - UINT32 SrcChannelCount; // [in] number of source channels, must equal number of channels in respective emitter - UINT32 DstChannelCount; // [in] number of destination channels, must equal number of channels of the final mix - - FLOAT32 LPFDirectCoefficient; // [out] LPF direct-path coefficient - FLOAT32 LPFReverbCoefficient; // [out] LPF reverb-path coefficient - FLOAT32 ReverbLevel; // [out] reverb send level - FLOAT32 DopplerFactor; // [out] doppler shift factor, scales resampler ratio for doppler shift effect, where the effective frequency = DopplerFactor * original frequency - FLOAT32 EmitterToListenerAngle; // [out] emitter-to-listener interior angle, expressed in radians with respect to the emitter's front orientation - - FLOAT32 EmitterToListenerDistance; // [out] distance in user-defined world units from the emitter base to listener position, always calculated - FLOAT32 EmitterVelocityComponent; // [out] component of emitter velocity vector projected onto emitter->listener vector in user-defined world units/second, calculated only for doppler - FLOAT32 ListenerVelocityComponent; // [out] component of listener velocity vector projected onto emitter->listener vector in user-defined world units/second, calculated only for doppler - } X3DAUDIO_DSP_SETTINGS, *LPX3DAUDIO_DSP_SETTINGS; - -#define X3DAUDIO_HANDLE_BYTESIZE 20 - typedef BYTE X3DAUDIO_HANDLE[X3DAUDIO_HANDLE_BYTESIZE]; - -#define SPEED_OF_SOUND 343.5f - - extern HRESULT __stdcall CoInitializeEx(void* ppXAudio2, DWORD dwCoInit); - - typedef HRESULT (__stdcall * XAudio2CreatePtr)(void** ppXAudio2, UINT32 flags, UINT32 processor); - typedef HRESULT (_cdecl * X3DAudioInitializePtr)(UINT32 SpeakerChannelMask, float SpeedOfSound, _Out_writes_bytes_(X3DAUDIO_HANDLE_BYTESIZE) X3DAUDIO_HANDLE Instance); - typedef void (_cdecl * X3DAudioCalculatePtr)(_In_reads_bytes_(X3DAUDIO_HANDLE_BYTESIZE) const X3DAUDIO_HANDLE Instance, _In_ const X3DAUDIO_LISTENER* pListener, _In_ const X3DAUDIO_EMITTER* pEmitter, UINT32 Flags, _Inout_ X3DAUDIO_DSP_SETTINGS* pDSPSettings); - - typedef HRESULT(__stdcall * CreateHrtfApoPtr)(const HrtfApoInit* init, IUnknown** xApo); - CreateHrtfApoPtr CreateHrtfApoFunc = NULL; - -#ifndef WINDOWS_DESKTOP - extern HRESULT __stdcall XAudio2Create(void** ppXAudio2, UINT32 flags, UINT32 processor); - XAudio2CreatePtr XAudio2CreateFunc = XAudio2Create; - extern HRESULT _cdecl X3DAudioInitialize(UINT32 SpeakerChannelMask, float SpeedOfSound, _Out_writes_bytes_(X3DAUDIO_HANDLE_BYTESIZE) X3DAUDIO_HANDLE Instance); - X3DAudioInitializePtr X3DAudioInitializeFunc = X3DAudioInitialize; - extern void _cdecl X3DAudioCalculate(_In_reads_bytes_(X3DAUDIO_HANDLE_BYTESIZE) const X3DAUDIO_HANDLE Instance, _In_ const X3DAUDIO_LISTENER* pListener, _In_ const X3DAUDIO_EMITTER* pEmitter, UINT32 Flags, _Inout_ X3DAUDIO_DSP_SETTINGS* pDSPSettings); - X3DAudioCalculatePtr X3DAudioCalculateFunc = X3DAudioCalculate; -#else - XAudio2CreatePtr XAudio2CreateFunc = NULL; - X3DAudioInitializePtr X3DAudioInitializeFunc = NULL; - X3DAudioCalculatePtr X3DAudioCalculateFunc = NULL; -#endif - - struct IXAudio2Voice; - - typedef struct XAUDIO2_VOICE_DETAILS - { - UINT32 CreationFlags; // Flags the voice was created with. - UINT32 ActiveFlags; // Flags currently active. - UINT32 InputChannels; // Channels in the voice's input audio. - UINT32 InputSampleRate; // Sample rate of the voice's input audio. - } XAUDIO2_VOICE_DETAILS; - - typedef struct XAUDIO2_SEND_DESCRIPTOR - { - UINT32 Flags; // Either 0 or XAUDIO2_SEND_USEFILTER. - IXAudio2Voice* pOutputVoice; // This send's destination voice. - } XAUDIO2_SEND_DESCRIPTOR; - - typedef struct XAUDIO2_VOICE_SENDS - { - UINT32 SendCount; // Number of sends from this voice. - XAUDIO2_SEND_DESCRIPTOR* pSends; // Array of SendCount send descriptors. - } XAUDIO2_VOICE_SENDS; - - typedef struct XAUDIO2_EFFECT_DESCRIPTOR - { - IUnknown* pEffect; // Pointer to the effect object's IUnknown interface. - BOOL InitialState; // TRUE if the effect should begin in the enabled state. - UINT32 OutputChannels; // How many output channels the effect should produce. - } XAUDIO2_EFFECT_DESCRIPTOR; - - typedef struct XAUDIO2_EFFECT_CHAIN - { - UINT32 EffectCount; // Number of effects in this voice's effect chain. - XAUDIO2_EFFECT_DESCRIPTOR* pEffectDescriptors; // Array of effect descriptors. - } XAUDIO2_EFFECT_CHAIN; - - typedef enum XAUDIO2_FILTER_TYPE - { - LowPassFilter, // Attenuates frequencies above the cutoff frequency (state-variable filter). - BandPassFilter, // Attenuates frequencies outside a given range (state-variable filter). - HighPassFilter, // Attenuates frequencies below the cutoff frequency (state-variable filter). - NotchFilter, // Attenuates frequencies inside a given range (state-variable filter). - LowPassOnePoleFilter, // Attenuates frequencies above the cutoff frequency (one-pole filter, XAUDIO2_FILTER_PARAMETERS.OneOverQ has no effect) - HighPassOnePoleFilter // Attenuates frequencies below the cutoff frequency (one-pole filter, XAUDIO2_FILTER_PARAMETERS.OneOverQ has no effect) - } XAUDIO2_FILTER_TYPE; - - typedef struct XAUDIO2_FILTER_PARAMETERS - { - XAUDIO2_FILTER_TYPE Type; // Filter type. - float Frequency; // Filter coefficient. - // must be >= 0 and <= XAUDIO2_MAX_FILTER_FREQUENCY - // See XAudio2CutoffFrequencyToRadians() for state-variable filter types and - // XAudio2CutoffFrequencyToOnePoleCoefficient() for one-pole filter types. - float OneOverQ; // Reciprocal of the filter's quality factor Q; - // must be > 0 and <= XAUDIO2_MAX_FILTER_ONEOVERQ. - // Has no effect for one-pole filters. - } XAUDIO2_FILTER_PARAMETERS; - - struct IXAPOHrtfParameters : IUnknown - { - // HRTF params - //! The position of the sound relative to the listener. - STDMETHOD(SetSourcePosition)(THIS_ _In_ const HrtfPosition* position); - //! The rotation matrix for the source orientation, with respect to the listener's frame of reference (the listener's coordinate system). - STDMETHOD(SetSourceOrientation)(THIS_ _In_ const HrtfOrientation* orientation); - //! The custom direct path gain value for the current source position. Valid only for sounds played with the HrtfDistanceDecayType. Custom decay type. - STDMETHOD(SetSourceGain)(THIS_ _In_ float gain); - - // Distance cue params - //! Selects the acoustic environment to simulate. - STDMETHOD(SetEnvironment)(THIS_ _In_ HrtfEnvironment environment); - }; - - struct IXAudio2EngineCallback - { - // Called by XAudio2 just before an audio processing pass begins. - STDMETHOD_(void, OnProcessingPassStart) (THIS) PURE; - - // Called just after an audio processing pass ends. - STDMETHOD_(void, OnProcessingPassEnd) (THIS) PURE; - - // Called in the event of a critical system error which requires XAudio2 - // to be closed down and restarted. The error code is given in Error. - STDMETHOD_(void, OnCriticalError) (THIS_ HRESULT Error) PURE; - }; - - struct IXAudio2Voice - { - /* NAME: IXAudio2Voice::GetVoiceDetails - // DESCRIPTION: Returns the basic characteristics of this voice. - // - // ARGUMENTS: - // pVoiceDetails - Returns the voice's details. - */ - STDMETHOD_(void, GetVoiceDetails) (THIS_ _Out_ XAUDIO2_VOICE_DETAILS* pVoiceDetails) PURE; - - /* NAME: IXAudio2Voice::SetOutputVoices - // DESCRIPTION: Replaces the set of submix/mastering voices that receive - // this voice's output. - // - // ARGUMENTS: - // pSendList - Optional list of voices this voice should send audio to. - */ - STDMETHOD(SetOutputVoices) (THIS_ _In_opt_ const XAUDIO2_VOICE_SENDS* pSendList) PURE; - - /* NAME: IXAudio2Voice::SetEffectChain - // DESCRIPTION: Replaces this voice's current effect chain with a new one. - // - // ARGUMENTS: - // pEffectChain - Structure describing the new effect chain to be used. - */ - STDMETHOD(SetEffectChain) (THIS_ _In_opt_ const XAUDIO2_EFFECT_CHAIN* pEffectChain) PURE; - - /* NAME: IXAudio2Voice::EnableEffect - // DESCRIPTION: Enables an effect in this voice's effect chain. - // - // ARGUMENTS: - // EffectIndex - Index of an effect within this voice's effect chain. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(EnableEffect) (THIS_ UINT32 EffectIndex, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::DisableEffect - // DESCRIPTION: Disables an effect in this voice's effect chain. - // - // ARGUMENTS: - // EffectIndex - Index of an effect within this voice's effect chain. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(DisableEffect) (THIS_ UINT32 EffectIndex, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::GetEffectState - // DESCRIPTION: Returns the running state of an effect. - // - // ARGUMENTS: - // EffectIndex - Index of an effect within this voice's effect chain. - // pEnabled - Returns the enabled/disabled state of the given effect. - */ - STDMETHOD_(void, GetEffectState) (THIS_ UINT32 EffectIndex, _Out_ BOOL* pEnabled) PURE; - - /* NAME: IXAudio2Voice::SetEffectParameters - // DESCRIPTION: Sets effect-specific parameters. - // - // REMARKS: Unlike IXAPOParameters::SetParameters, this method may - // be called from any thread. XAudio2 implements - // appropriate synchronization to copy the parameters to the - // realtime audio processing thread. - // - // ARGUMENTS: - // EffectIndex - Index of an effect within this voice's effect chain. - // pParameters - Pointer to an effect-specific parameters block. - // ParametersByteSize - Size of the pParameters array in bytes. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(SetEffectParameters) (THIS_ UINT32 EffectIndex, - _In_reads_bytes_(ParametersByteSize) const void* pParameters, - UINT32 ParametersByteSize, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::GetEffectParameters - // DESCRIPTION: Obtains the current effect-specific parameters. - // - // ARGUMENTS: - // EffectIndex - Index of an effect within this voice's effect chain. - // pParameters - Returns the current values of the effect-specific parameters. - // ParametersByteSize - Size of the pParameters array in bytes. - */ - STDMETHOD(GetEffectParameters) (THIS_ UINT32 EffectIndex, - _Out_writes_bytes_(ParametersByteSize) void* pParameters, - UINT32 ParametersByteSize) PURE; - - /* NAME: IXAudio2Voice::SetFilterParameters - // DESCRIPTION: Sets this voice's filter parameters. - // - // ARGUMENTS: - // pParameters - Pointer to the filter's parameter structure. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(SetFilterParameters) (THIS_ _In_ const XAUDIO2_FILTER_PARAMETERS* pParameters, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::GetFilterParameters - // DESCRIPTION: Returns this voice's current filter parameters. - // - // ARGUMENTS: - // pParameters - Returns the filter parameters. - */ - STDMETHOD_(void, GetFilterParameters) (THIS_ _Out_ XAUDIO2_FILTER_PARAMETERS* pParameters) PURE; - - /* NAME: IXAudio2Voice::SetOutputFilterParameters - // DESCRIPTION: Sets the filter parameters on one of this voice's sends. - // - // ARGUMENTS: - // pDestinationVoice - Destination voice of the send whose filter parameters will be set. - // pParameters - Pointer to the filter's parameter structure. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(SetOutputFilterParameters) (THIS_ _In_opt_ IXAudio2Voice* pDestinationVoice, - _In_ const XAUDIO2_FILTER_PARAMETERS* pParameters, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::GetOutputFilterParameters - // DESCRIPTION: Returns the filter parameters from one of this voice's sends. - // - // ARGUMENTS: - // pDestinationVoice - Destination voice of the send whose filter parameters will be read. - // pParameters - Returns the filter parameters. - */ - STDMETHOD_(void, GetOutputFilterParameters) (THIS_ _In_opt_ IXAudio2Voice* pDestinationVoice, - _Out_ XAUDIO2_FILTER_PARAMETERS* pParameters) PURE; - - /* NAME: IXAudio2Voice::SetVolume - // DESCRIPTION: Sets this voice's overall volume level. - // - // ARGUMENTS: - // Volume - New overall volume level to be used, as an amplitude factor. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(SetVolume) (THIS_ float Volume, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::GetVolume - // DESCRIPTION: Obtains this voice's current overall volume level. - // - // ARGUMENTS: - // pVolume: Returns the voice's current overall volume level. - */ - STDMETHOD_(void, GetVolume) (THIS_ _Out_ float* pVolume) PURE; - - /* NAME: IXAudio2Voice::SetChannelVolumes - // DESCRIPTION: Sets this voice's per-channel volume levels. - // - // ARGUMENTS: - // Channels - Used to confirm the voice's channel count. - // pVolumes - Array of per-channel volume levels to be used. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(SetChannelVolumes) (THIS_ UINT32 Channels, _In_reads_(Channels) const float* pVolumes, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; \ - - /* NAME: IXAudio2Voice::GetChannelVolumes - // DESCRIPTION: Returns this voice's current per-channel volume levels. - // - // ARGUMENTS: - // Channels - Used to confirm the voice's channel count. - // pVolumes - Returns an array of the current per-channel volume levels. - */ - STDMETHOD_(void, GetChannelVolumes) (THIS_ UINT32 Channels, _Out_writes_(Channels) float* pVolumes) PURE; - - /* NAME: IXAudio2Voice::SetOutputMatrix - // DESCRIPTION: Sets the volume levels used to mix from each channel of this - // voice's output audio to each channel of a given destination - // voice's input audio. - // - // ARGUMENTS: - // pDestinationVoice - The destination voice whose mix matrix to change. - // SourceChannels - Used to confirm this voice's output channel count - // (the number of channels produced by the last effect in the chain). - // DestinationChannels - Confirms the destination voice's input channels. - // pLevelMatrix - Array of [SourceChannels * DestinationChannels] send - // levels. The level used to send from source channel S to destination - // channel D should be in pLevelMatrix[S + SourceChannels * D]. - // OperationSet - Used to identify this call as part of a deferred batch. - */ - STDMETHOD(SetOutputMatrix) (THIS_ _In_opt_ IXAudio2Voice* pDestinationVoice, - UINT32 SourceChannels, UINT32 DestinationChannels, - _In_reads_(SourceChannels * DestinationChannels) const float* pLevelMatrix, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - /* NAME: IXAudio2Voice::GetOutputMatrix - // DESCRIPTION: Obtains the volume levels used to send each channel of this - // voice's output audio to each channel of a given destination - // voice's input audio. - // - // ARGUMENTS: - // pDestinationVoice - The destination voice whose mix matrix to obtain. - // SourceChannels - Used to confirm this voice's output channel count - // (the number of channels produced by the last effect in the chain). - // DestinationChannels - Confirms the destination voice's input channels. - // pLevelMatrix - Array of send levels, as above. - */ - STDMETHOD_(void, GetOutputMatrix) (THIS_ _In_opt_ IXAudio2Voice* pDestinationVoice, - UINT32 SourceChannels, UINT32 DestinationChannels, - _Out_writes_(SourceChannels * DestinationChannels) float* pLevelMatrix) PURE; - /* NAME: IXAudio2Voice::DestroyVoice - // DESCRIPTION: Destroys this voice, stopping it if necessary and removing - // it from the XAudio2 graph. - */ - STDMETHOD_(void, DestroyVoice) (THIS) PURE; - }; - - typedef struct XAUDIO2_BUFFER - { - UINT32 Flags; // Either 0 or XAUDIO2_END_OF_STREAM. - UINT32 AudioBytes; // Size of the audio data buffer in bytes. - const BYTE* pAudioData; // Pointer to the audio data buffer. - UINT32 PlayBegin; // First sample in this buffer to be played. - UINT32 PlayLength; // Length of the region to be played in samples, - // or 0 to play the whole buffer. - UINT32 LoopBegin; // First sample of the region to be looped. - UINT32 LoopLength; // Length of the desired loop region in samples, - // or 0 to loop the entire buffer. - UINT32 LoopCount; // Number of times to repeat the loop region, - // or XAUDIO2_LOOP_INFINITE to loop forever. - void* pContext; // Context value to be passed back in callbacks. - } XAUDIO2_BUFFER; - - typedef struct XAUDIO2_BUFFER_WMA - { - const UINT32* pDecodedPacketCumulativeBytes; // Decoded packet's cumulative size array. - // Each element is the number of bytes accumulated - // when the corresponding XWMA packet is decoded in - // order. The array must have PacketCount elements. - UINT32 PacketCount; // Number of XWMA packets submitted. Must be >= 1 and - // divide evenly into XAUDIO2_BUFFER.AudioBytes. - } XAUDIO2_BUFFER_WMA; - - typedef struct XAUDIO2_VOICE_STATE - { - void* pCurrentBufferContext; // The pContext value provided in the XAUDIO2_BUFFER - // that is currently being processed, or NULL if - // there are no buffers in the queue. - UINT32 BuffersQueued; // Number of buffers currently queued on the voice - // (including the one that is being processed). - UINT64 SamplesPlayed; // Total number of samples produced by the voice since - // it began processing the current audio stream. - // If XAUDIO2_VOICE_NOSAMPLESPLAYED is specified - // in the call to IXAudio2SourceVoice::GetState, - // this member will not be calculated, saving CPU. - } XAUDIO2_VOICE_STATE; - - struct IXAudio2SourceVoice : IXAudio2Voice - { - // NAME: IXAudio2SourceVoice::Start - // DESCRIPTION: Makes this voice start consuming and processing audio. - // - // ARGUMENTS: - // Flags - Flags controlling how the voice should be started. - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(Start) (THIS_ UINT32 Flags X2DEFAULT(0), UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::Stop - // DESCRIPTION: Makes this voice stop consuming audio. - // - // ARGUMENTS: - // Flags - Flags controlling how the voice should be stopped. - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(Stop) (THIS_ UINT32 Flags X2DEFAULT(0), UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::SubmitSourceBuffer - // DESCRIPTION: Adds a new audio buffer to this voice's input queue. - // - // ARGUMENTS: - // pBuffer - Pointer to the buffer structure to be queued. - // pBufferWMA - Additional structure used only when submitting XWMA data. - // - STDMETHOD(SubmitSourceBuffer) (THIS_ _In_ const XAUDIO2_BUFFER* pBuffer, _In_opt_ const XAUDIO2_BUFFER_WMA* pBufferWMA X2DEFAULT(NULL)) PURE; - - // NAME: IXAudio2SourceVoice::FlushSourceBuffers - // DESCRIPTION: Removes all pending audio buffers from this voice's queue. - // - STDMETHOD(FlushSourceBuffers) (THIS) PURE; - - // NAME: IXAudio2SourceVoice::Discontinuity - // DESCRIPTION: Notifies the voice of an intentional break in the stream of - // audio buffers (e.g. the end of a sound), to prevent XAudio2 - // from interpreting an empty buffer queue as a glitch. - // - STDMETHOD(Discontinuity) (THIS) PURE; - - // NAME: IXAudio2SourceVoice::ExitLoop - // DESCRIPTION: Breaks out of the current loop when its end is reached. - // - // ARGUMENTS: - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(ExitLoop) (THIS_ UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::GetState - // DESCRIPTION: Returns the number of buffers currently queued on this voice, - // the pContext value associated with the currently processing - // buffer (if any), and other voice state information. - // - // ARGUMENTS: - // pVoiceState - Returns the state information. - // Flags - Flags controlling what voice state is returned. - // - STDMETHOD_(void, GetState) (THIS_ _Out_ XAUDIO2_VOICE_STATE* pVoiceState, UINT32 Flags X2DEFAULT(0)) PURE; - - // NAME: IXAudio2SourceVoice::SetFrequencyRatio - // DESCRIPTION: Sets this voice's frequency adjustment, i.e. its pitch. - // - // ARGUMENTS: - // Ratio - Frequency change, expressed as source frequency / target frequency. - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(SetFrequencyRatio) (THIS_ float Ratio, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::GetFrequencyRatio - // DESCRIPTION: Returns this voice's current frequency adjustment ratio. - // - // ARGUMENTS: - // pRatio - Returns the frequency adjustment. - // - STDMETHOD_(void, GetFrequencyRatio) (THIS_ _Out_ float* pRatio) PURE; - - // NAME: IXAudio2SourceVoice::SetSourceSampleRate - // DESCRIPTION: Reconfigures this voice to treat its source data as being - // at a different sample rate than the original one specified - // in CreateSourceVoice's pSourceFormat argument. - // - // ARGUMENTS: - // UINT32 - The intended sample rate of further submitted source data. - // - STDMETHOD(SetSourceSampleRate) (THIS_ UINT32 NewSourceSampleRate) PURE; - }; - - struct IXAudio2SourceVoice1 : IXAudio2Voice - { - // NAME: IXAudio2SourceVoice::Start - // DESCRIPTION: Makes this voice start consuming and processing audio. - // - // ARGUMENTS: - // Flags - Flags controlling how the voice should be started. - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(Start) (THIS_ UINT32 Flags X2DEFAULT(0), UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::Stop - // DESCRIPTION: Makes this voice stop consuming audio. - // - // ARGUMENTS: - // Flags - Flags controlling how the voice should be stopped. - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(Stop) (THIS_ UINT32 Flags X2DEFAULT(0), UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::SubmitSourceBuffer - // DESCRIPTION: Adds a new audio buffer to this voice's input queue. - // - // ARGUMENTS: - // pBuffer - Pointer to the buffer structure to be queued. - // pBufferWMA - Additional structure used only when submitting XWMA data. - // - STDMETHOD(SubmitSourceBuffer) (THIS_ const XAUDIO2_BUFFER* pBuffer, const XAUDIO2_BUFFER_WMA* pBufferWMA X2DEFAULT(NULL)) PURE; - - // NAME: IXAudio2SourceVoice::FlushSourceBuffers - // DESCRIPTION: Removes all pending audio buffers from this voice's queue. - // - STDMETHOD(FlushSourceBuffers) (THIS) PURE; - - // NAME: IXAudio2SourceVoice::Discontinuity - // DESCRIPTION: Notifies the voice of an intentional break in the stream of - // audio buffers (e.g. the end of a sound), to prevent XAudio2 - // from interpreting an empty buffer queue as a glitch. - // - STDMETHOD(Discontinuity) (THIS) PURE; - - // NAME: IXAudio2SourceVoice::ExitLoop - // DESCRIPTION: Breaks out of the current loop when its end is reached. - // - // ARGUMENTS: - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(ExitLoop) (THIS_ UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::GetState - // DESCRIPTION: Returns the number of buffers currently queued on this voice, - // the pContext value associated with the currently processing - // buffer (if any), and other voice state information. - // - // ARGUMENTS: - // pVoiceState - Returns the state information. - // - STDMETHOD_(void, GetState) (THIS_ XAUDIO2_VOICE_STATE* pVoiceState) PURE; - - // NAME: IXAudio2SourceVoice::SetFrequencyRatio - // DESCRIPTION: Sets this voice's frequency adjustment, i.e. its pitch. - // - // ARGUMENTS: - // Ratio - Frequency change, expressed as source frequency / target frequency. - // OperationSet - Used to identify this call as part of a deferred batch. - // - STDMETHOD(SetFrequencyRatio) (THIS_ float Ratio, - UINT32 OperationSet X2DEFAULT(XAUDIO2_COMMIT_NOW)) PURE; - - // NAME: IXAudio2SourceVoice::GetFrequencyRatio - // DESCRIPTION: Returns this voice's current frequency adjustment ratio. - // - // ARGUMENTS: - // pRatio - Returns the frequency adjustment. - // - STDMETHOD_(void, GetFrequencyRatio) (THIS_ float* pRatio) PURE; - - // NAME: IXAudio2SourceVoice::SetSourceSampleRate - // DESCRIPTION: Reconfigures this voice to treat its source data as being - // at a different sample rate than the original one specified - // in CreateSourceVoice's pSourceFormat argument. - // - // ARGUMENTS: - // UINT32 - The intended sample rate of further submitted source data. - // - STDMETHOD(SetSourceSampleRate) (THIS_ UINT32 NewSourceSampleRate) PURE; - }; - - struct IXAudio2SubmixVoice : IXAudio2SourceVoice - { - }; - - typedef struct tWAVEFORMATEX - { - WORD wFormatTag; /* format type */ - WORD nChannels; /* number of channels (i.e. mono, stereo...) */ - DWORD nSamplesPerSec; /* sample rate */ - DWORD nAvgBytesPerSec; /* for buffer estimation */ - WORD nBlockAlign; /* block size of data */ - WORD wBitsPerSample; /* number of bits per sample of mono data */ - WORD cbSize; /* the count in bytes of the size of */ - /* extra information (after cbSize) */ - } WAVEFORMATEX; - -#define XAUDIO2_MAX_BUFFER_BYTES 0x80000000 // Maximum bytes allowed in a source buffer -#define XAUDIO2_MAX_QUEUED_BUFFERS 64 // Maximum buffers allowed in a voice queue -#define XAUDIO2_MAX_BUFFERS_SYSTEM 2 // Maximum buffers allowed for system threads (Xbox 360 only) -#define XAUDIO2_MAX_AUDIO_CHANNELS 64 // Maximum channels in an audio stream -#define XAUDIO2_MIN_SAMPLE_RATE 1000 // Minimum audio sample rate supported -#define XAUDIO2_MAX_SAMPLE_RATE 200000 // Maximum audio sample rate supported -#define XAUDIO2_MAX_VOLUME_LEVEL 16777216.0f // Maximum acceptable volume level (2^24) -#define XAUDIO2_MIN_FREQ_RATIO (1/1024.0f) // Minimum SetFrequencyRatio argument -#define XAUDIO2_MAX_FREQ_RATIO 1024.0f // Maximum MaxFrequencyRatio argument -#define XAUDIO2_DEFAULT_FREQ_RATIO 2.0f // Default MaxFrequencyRatio argument -#define XAUDIO2_MAX_FILTER_ONEOVERQ 1.5f // Maximum XAUDIO2_FILTER_PARAMETERS.OneOverQ -#define XAUDIO2_MAX_FILTER_FREQUENCY 1.0f // Maximum XAUDIO2_FILTER_PARAMETERS.Frequency -#define XAUDIO2_MAX_LOOP_COUNT 254 // Maximum non-infinite XAUDIO2_BUFFER.LoopCount -#define XAUDIO2_MAX_INSTANCES 8 // Maximum simultaneous XAudio2 objects on Xbox 360 - -#define XAUDIO2_DEBUG_ENGINE 0x0001 // Used in XAudio2Create -#define XAUDIO2_VOICE_NOPITCH 0x0002 // Used in IXAudio2::CreateSourceVoice -#define XAUDIO2_VOICE_NOSRC 0x0004 // Used in IXAudio2::CreateSourceVoice -#define XAUDIO2_VOICE_USEFILTER 0x0008 // Used in IXAudio2::CreateSource/SubmixVoice -#define XAUDIO2_PLAY_TAILS 0x0020 // Used in IXAudio2SourceVoice::Stop -#define XAUDIO2_END_OF_STREAM 0x0040 // Used in XAUDIO2_BUFFER.Flags -#define XAUDIO2_SEND_USEFILTER 0x0080 // Used in XAUDIO2_SEND_DESCRIPTOR.Flags -#define XAUDIO2_VOICE_NOSAMPLESPLAYED 0x0100 // Used in IXAudio2SourceVoice::GetState -#define XAUDIO2_STOP_ENGINE_WHEN_IDLE 0x2000 // Used in XAudio2Create to force the engine to Stop when no source voices are Started, and Start when a voice is Started -#define XAUDIO2_1024_QUANTUM 0x8000 // Used in XAudio2Create to specify nondefault processing quantum of 21.33 ms (1024 samples at 48KHz) -#define XAUDIO2_NO_VIRTUAL_AUDIO_CLIENT 0x10000 // Used in CreateMasteringVoice to create a virtual audio client - -#define WAVE_FORMAT_PCM 1 - - struct IXAudio2MasteringVoice : IXAudio2Voice - { - // NAME: IXAudio2MasteringVoice::GetChannelMask - // DESCRIPTION: Returns the channel mask for this voice - // - // ARGUMENTS: - // pChannelMask - returns the channel mask for this voice. This corresponds - // to the dwChannelMask member of WAVEFORMATEXTENSIBLE. - // - STDMETHOD(GetChannelMask) (THIS_ _Out_ DWORD* pChannelmask) PURE; - }; - - struct IXAudio2VoiceCallback - { - // Called just before this voice's processing pass begins. - STDMETHOD_(void, OnVoiceProcessingPassStart) (THIS_ UINT32 BytesRequired) PURE; - - // Called just after this voice's processing pass ends. - STDMETHOD_(void, OnVoiceProcessingPassEnd) (THIS) PURE; - - // Called when this voice has just finished playing a buffer stream - // (as marked with the XAUDIO2_END_OF_STREAM flag on the last buffer). - STDMETHOD_(void, OnStreamEnd) (THIS) PURE; - - // Called when this voice is about to start processing a new buffer. - STDMETHOD_(void, OnBufferStart) (THIS_ void* pBufferContext) PURE; - - // Called when this voice has just finished processing a buffer. - // The buffer can now be reused or destroyed. - STDMETHOD_(void, OnBufferEnd) (THIS_ void* pBufferContext) PURE; - - // Called when this voice has just reached the end position of a loop. - STDMETHOD_(void, OnLoopEnd) (THIS_ void* pBufferContext) PURE; - - // Called in the event of a critical error during voice processing, - // such as a failing xAPO or an error from the hardware XMA decoder. - // The voice may have to be destroyed and re-created to recover from - // the error. The callback arguments report which buffer was being - // processed when the error occurred, and its HRESULT code. - STDMETHOD_(void, OnVoiceError) (THIS_ void* pBufferContext, HRESULT Error) PURE; - }; - - typedef enum _AUDIO_STREAM_CATEGORY - { - AudioCategory_Other = 0, - AudioCategory_ForegroundOnlyMedia, - AudioCategory_BackgroundCapableMedia, - AudioCategory_Communications, - AudioCategory_Alerts, - AudioCategory_SoundEffects, - AudioCategory_GameEffects, - AudioCategory_GameMedia, - } AUDIO_STREAM_CATEGORY; - - typedef struct XAUDIO2_PERFORMANCE_DATA - { - // CPU usage information - UINT64 AudioCyclesSinceLastQuery; // CPU cycles spent on audio processing since the - // last call to StartEngine or GetPerformanceData. - UINT64 TotalCyclesSinceLastQuery; // Total CPU cycles elapsed since the last call - // (only counts the CPU XAudio2 is running on). - UINT32 MinimumCyclesPerQuantum; // Fewest CPU cycles spent processing any one - // audio quantum since the last call. - UINT32 MaximumCyclesPerQuantum; // Most CPU cycles spent processing any one - // audio quantum since the last call. - - // Memory usage information - UINT32 MemoryUsageInBytes; // Total heap space currently in use. - - // Audio latency and glitching information - UINT32 CurrentLatencyInSamples; // Minimum delay from when a sample is read from a - // source buffer to when it reaches the speakers. - UINT32 GlitchesSinceEngineStarted; // Audio dropouts since the engine was started. - - // Data about XAudio2's current workload - UINT32 ActiveSourceVoiceCount; // Source voices currently playing. - UINT32 TotalSourceVoiceCount; // Source voices currently existing. - UINT32 ActiveSubmixVoiceCount; // Submix voices currently playing/existing. - - UINT32 ActiveResamplerCount; // Resample xAPOs currently active. - UINT32 ActiveMatrixMixCount; // MatrixMix xAPOs currently active. - - // Usage of the hardware XMA decoder (Xbox 360 only) - UINT32 ActiveXmaSourceVoices; // Number of source voices decoding XMA data. - UINT32 ActiveXmaStreams; // A voice can use more than one XMA stream. - } XAUDIO2_PERFORMANCE_DATA; - - typedef struct XAUDIO2_DEBUG_CONFIGURATION - { - UINT32 TraceMask; // Bitmap of enabled debug message types. - UINT32 BreakMask; // Message types that will break into the debugger. - BOOL LogThreadID; // Whether to log the thread ID with each message. - BOOL LogFileline; // Whether to log the source file and line number. - BOOL LogFunctionName; // Whether to log the function name. - BOOL LogTiming; // Whether to log message timestamps. - } XAUDIO2_DEBUG_CONFIGURATION; - - struct IXAudio2 : IUnknown - { - // NAME: IXAudio2::RegisterForCallbacks - // DESCRIPTION: Adds a new client to receive XAudio2's engine callbacks. - // - // ARGUMENTS: - // pCallback - Callback interface to be called during each processing pass. - // - STDMETHOD(RegisterForCallbacks) (_In_ IXAudio2EngineCallback* pCallback) PURE; - - // NAME: IXAudio2::UnregisterForCallbacks - // DESCRIPTION: Removes an existing receiver of XAudio2 engine callbacks. - // - // ARGUMENTS: - // pCallback - Previously registered callback interface to be removed. - // - STDMETHOD_(void, UnregisterForCallbacks) (_In_ IXAudio2EngineCallback* pCallback) PURE; - - // NAME: IXAudio2::CreateSourceVoice - // DESCRIPTION: Creates and configures a source voice. - // - // ARGUMENTS: - // ppSourceVoice - Returns the new object's IXAudio2SourceVoice interface. - // pSourceFormat - Format of the audio that will be fed to the voice. - // Flags - XAUDIO2_VOICE flags specifying the source voice's behavior. - // MaxFrequencyRatio - Maximum SetFrequencyRatio argument to be allowed. - // pCallback - Optional pointer to a client-provided callback interface. - // pSendList - Optional list of voices this voice should send audio to. - // pEffectChain - Optional list of effects to apply to the audio data. - // - STDMETHOD(CreateSourceVoice) (THIS_ _Outptr_ IXAudio2SourceVoice** ppSourceVoice, - _In_ const WAVEFORMATEX* pSourceFormat, - UINT32 Flags X2DEFAULT(0), - float MaxFrequencyRatio X2DEFAULT(XAUDIO2_DEFAULT_FREQ_RATIO), - _In_opt_ IXAudio2VoiceCallback* pCallback X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_VOICE_SENDS* pSendList X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_EFFECT_CHAIN* pEffectChain X2DEFAULT(NULL)) PURE; - - // NAME: IXAudio2::CreateSubmixVoice - // DESCRIPTION: Creates and configures a submix voice. - // - // ARGUMENTS: - // ppSubmixVoice - Returns the new object's IXAudio2SubmixVoice interface. - // InputChannels - Number of channels in this voice's input audio data. - // InputSampleRate - Sample rate of this voice's input audio data. - // Flags - XAUDIO2_VOICE flags specifying the submix voice's behavior. - // ProcessingStage - Arbitrary number that determines the processing order. - // pSendList - Optional list of voices this voice should send audio to. - // pEffectChain - Optional list of effects to apply to the audio data. - // - STDMETHOD(CreateSubmixVoice) (THIS_ _Outptr_ IXAudio2SubmixVoice** ppSubmixVoice, - UINT32 InputChannels, UINT32 InputSampleRate, - UINT32 Flags X2DEFAULT(0), UINT32 ProcessingStage X2DEFAULT(0), - _In_opt_ const XAUDIO2_VOICE_SENDS* pSendList X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_EFFECT_CHAIN* pEffectChain X2DEFAULT(NULL)) PURE; - - - // NAME: IXAudio2::CreateMasteringVoice - // DESCRIPTION: Creates and configures a mastering voice. - // - // ARGUMENTS: - // ppMasteringVoice - Returns the new object's IXAudio2MasteringVoice interface. - // InputChannels - Number of channels in this voice's input audio data. - // InputSampleRate - Sample rate of this voice's input audio data. - // Flags - XAUDIO2_VOICE flags specifying the mastering voice's behavior. - // szDeviceId - Identifier of the device to receive the output audio. - // pEffectChain - Optional list of effects to apply to the audio data. - // StreamCategory - The audio stream category to use for this mastering voice - // - STDMETHOD(CreateMasteringVoice) (THIS_ _Outptr_ IXAudio2MasteringVoice** ppMasteringVoice, - UINT32 InputChannels X2DEFAULT(XAUDIO2_DEFAULT_CHANNELS), - UINT32 InputSampleRate X2DEFAULT(XAUDIO2_DEFAULT_SAMPLERATE), - UINT32 Flags X2DEFAULT(0), _In_opt_z_ void* szDeviceId X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_EFFECT_CHAIN* pEffectChain X2DEFAULT(NULL), - _In_ AUDIO_STREAM_CATEGORY StreamCategory X2DEFAULT(AudioCategory_GameEffects)) PURE; - - // NAME: IXAudio2::StartEngine - // DESCRIPTION: Creates and starts the audio processing thread. - // - STDMETHOD(StartEngine) (THIS) PURE; - - // NAME: IXAudio2::StopEngine - // DESCRIPTION: Stops and destroys the audio processing thread. - // - STDMETHOD_(void, StopEngine) (THIS) PURE; - - // NAME: IXAudio2::CommitChanges - // DESCRIPTION: Atomically applies a set of operations previously tagged - // with a given identifier. - // - // ARGUMENTS: - // OperationSet - Identifier of the set of operations to be applied. - // - STDMETHOD(CommitChanges) (THIS_ UINT32 OperationSet) PURE; - - // NAME: IXAudio2::GetPerformanceData - // DESCRIPTION: Returns current resource usage details: memory, CPU, etc. - // - // ARGUMENTS: - // pPerfData - Returns the performance data structure. - // - STDMETHOD_(void, GetPerformanceData) (THIS_ _Out_ XAUDIO2_PERFORMANCE_DATA* pPerfData) PURE; - - // NAME: IXAudio2::SetDebugConfiguration - // DESCRIPTION: Configures XAudio2's debug output (in debug builds only). - // - // ARGUMENTS: - // pDebugConfiguration - Structure describing the debug output behavior. - // pReserved - Optional parameter; must be NULL. - // - STDMETHOD_(void, SetDebugConfiguration) (THIS_ _In_opt_ const XAUDIO2_DEBUG_CONFIGURATION* pDebugConfiguration, - _Reserved_ void* pReserved X2DEFAULT(NULL)) PURE; - }; - - struct IXAudio2_7 : IUnknown - { - - // NAME: IXAudio2::GetDeviceCount - // DESCRIPTION: Returns the number of audio output devices available. - // - // ARGUMENTS: - // pCount - Returns the device count. - // - STDMETHOD(GetDeviceCount) (THIS_ UINT32* pCount) PURE; - - // NAME: IXAudio2::GetDeviceDetails - // DESCRIPTION: Returns information about the device with the given index. - // - // ARGUMENTS: - // Index - Index of the device to be queried. - // pDeviceDetails - Returns the device details. - // - STDMETHOD(GetDeviceDetails) (THIS_ UINT32 Index, void* pDeviceDetails) PURE; - - // NAME: IXAudio2::Initialize - // DESCRIPTION: Sets global XAudio2 parameters and prepares it for use. - // - // ARGUMENTS: - // Flags - Flags specifying the XAudio2 object's behavior. Currently unused. - // XAudio2Processor - An XAUDIO2_PROCESSOR enumeration value that specifies - // the hardware thread (Xbox) or processor (Windows) that XAudio2 will use. - // The enumeration values are platform-specific; platform-independent code - // can use XAUDIO2_DEFAULT_PROCESSOR to use the default on each platform. - // - STDMETHOD(Initialize) (THIS_ UINT32 Flags X2DEFAULT(0), UINT32 XAudio2Processor = 0x00000001) PURE; - - // NAME: IXAudio2::RegisterForCallbacks - // DESCRIPTION: Adds a new client to receive XAudio2's engine callbacks. - // - // ARGUMENTS: - // pCallback - Callback interface to be called during each processing pass. - // - STDMETHOD(RegisterForCallbacks) (_In_ IXAudio2EngineCallback* pCallback) PURE; - - // NAME: IXAudio2::UnregisterForCallbacks - // DESCRIPTION: Removes an existing receiver of XAudio2 engine callbacks. - // - // ARGUMENTS: - // pCallback - Previously registered callback interface to be removed. - // - STDMETHOD_(void, UnregisterForCallbacks) (_In_ IXAudio2EngineCallback* pCallback) PURE; - - // NAME: IXAudio2::CreateSourceVoice - // DESCRIPTION: Creates and configures a source voice. - // - // ARGUMENTS: - // ppSourceVoice - Returns the new object's IXAudio2SourceVoice interface. - // pSourceFormat - Format of the audio that will be fed to the voice. - // Flags - XAUDIO2_VOICE flags specifying the source voice's behavior. - // MaxFrequencyRatio - Maximum SetFrequencyRatio argument to be allowed. - // pCallback - Optional pointer to a client-provided callback interface. - // pSendList - Optional list of voices this voice should send audio to. - // pEffectChain - Optional list of effects to apply to the audio data. - // - STDMETHOD(CreateSourceVoice) (THIS_ _Outptr_ IXAudio2SourceVoice** ppSourceVoice, - _In_ const WAVEFORMATEX* pSourceFormat, - UINT32 Flags X2DEFAULT(0), - float MaxFrequencyRatio X2DEFAULT(XAUDIO2_DEFAULT_FREQ_RATIO), - _In_opt_ IXAudio2VoiceCallback* pCallback X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_VOICE_SENDS* pSendList X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_EFFECT_CHAIN* pEffectChain X2DEFAULT(NULL)) PURE; - - // NAME: IXAudio2::CreateSubmixVoice - // DESCRIPTION: Creates and configures a submix voice. - // - // ARGUMENTS: - // ppSubmixVoice - Returns the new object's IXAudio2SubmixVoice interface. - // InputChannels - Number of channels in this voice's input audio data. - // InputSampleRate - Sample rate of this voice's input audio data. - // Flags - XAUDIO2_VOICE flags specifying the submix voice's behavior. - // ProcessingStage - Arbitrary number that determines the processing order. - // pSendList - Optional list of voices this voice should send audio to. - // pEffectChain - Optional list of effects to apply to the audio data. - // - STDMETHOD(CreateSubmixVoice) (THIS_ _Outptr_ IXAudio2Voice** ppSubmixVoice, - UINT32 InputChannels, UINT32 InputSampleRate, - UINT32 Flags X2DEFAULT(0), UINT32 ProcessingStage X2DEFAULT(0), - _In_opt_ const XAUDIO2_VOICE_SENDS* pSendList X2DEFAULT(NULL), - _In_opt_ const XAUDIO2_EFFECT_CHAIN* pEffectChain X2DEFAULT(NULL)) PURE; - - - // NAME: IXAudio2::CreateMasteringVoice - // DESCRIPTION: Creates and configures a mastering voice. - // - // ARGUMENTS: - // ppMasteringVoice - Returns the new object's IXAudio2MasteringVoice interface. - // InputChannels - Number of channels in this voice's input audio data. - // InputSampleRate - Sample rate of this voice's input audio data. - // Flags - XAUDIO2_VOICE flags specifying the mastering voice's behavior. - // DeviceIndex - Identifier of the device to receive the output audio. - // pEffectChain - Optional list of effects to apply to the audio data. - // - STDMETHOD(CreateMasteringVoice) (THIS_ IXAudio2MasteringVoice** ppMasteringVoice, - UINT32 InputChannels X2DEFAULT(XAUDIO2_DEFAULT_CHANNELS), - UINT32 InputSampleRate X2DEFAULT(XAUDIO2_DEFAULT_SAMPLERATE), - UINT32 Flags X2DEFAULT(0), UINT32 DeviceIndex X2DEFAULT(0), - const XAUDIO2_EFFECT_CHAIN* pEffectChain X2DEFAULT(NULL)) PURE; - - // NAME: IXAudio2::StartEngine - // DESCRIPTION: Creates and starts the audio processing thread. - // - STDMETHOD(StartEngine) (THIS) PURE; - - // NAME: IXAudio2::StopEngine - // DESCRIPTION: Stops and destroys the audio processing thread. - // - STDMETHOD_(void, StopEngine) (THIS) PURE; - - // NAME: IXAudio2::CommitChanges - // DESCRIPTION: Atomically applies a set of operations previously tagged - // with a given identifier. - // - // ARGUMENTS: - // OperationSet - Identifier of the set of operations to be applied. - // - STDMETHOD(CommitChanges) (THIS_ UINT32 OperationSet) PURE; - - // NAME: IXAudio2::GetPerformanceData - // DESCRIPTION: Returns current resource usage details: memory, CPU, etc. - // - // ARGUMENTS: - // pPerfData - Returns the performance data structure. - // - STDMETHOD_(void, GetPerformanceData) (THIS_ _Out_ XAUDIO2_PERFORMANCE_DATA* pPerfData) PURE; - - // NAME: IXAudio2::SetDebugConfiguration - // DESCRIPTION: Configures XAudio2's debug output (in debug builds only). - // - // ARGUMENTS: - // pDebugConfiguration - Structure describing the debug output behavior. - // pReserved - Optional parameter; must be NULL. - // - STDMETHOD_(void, SetDebugConfiguration) (THIS_ _In_opt_ const XAUDIO2_DEBUG_CONFIGURATION* pDebugConfiguration, - _Reserved_ void* pReserved X2DEFAULT(NULL)) PURE; - }; - -#pragma pack(pop) - -#define AUDIO_CHANNELS 2 - - //Windows 7 has no XAudio by default , it is taken from DX sdk and its loaded using COM... - bool xnAudioWindows7Hacks = false; - - void* xnHrtfApoLib; - - typedef IID *LPIID; - IID xnHrtfParamsIID; - -#ifdef WINDOWS_DESKTOP - void* xnXAudioLib; - typedef /* [unique] */ IUnknown *LPUNKNOWN; - typedef void *LPVOID; - typedef GUID IID; -#define REFCLSID const IID & - extern HRESULT __stdcall CoCreateInstance(_In_ REFCLSID rclsid, _In_opt_ LPUNKNOWN pUnkOuter, _In_ DWORD dwClsContext, _In_ REFIID riid, LPVOID* ppv); - - typedef IID *LPIID; - typedef wchar_t WCHAR; - typedef WCHAR OLECHAR; - typedef /* [string] */ const OLECHAR *LPCOLESTR; - - extern HRESULT __stdcall IIDFromString(_In_ LPCOLESTR lpsz, _Out_ LPIID lpiid); -#endif - - DLL_EXPORT_API npBool xnAudioInit() - { - CoInitializeEx(NULL, 0x0); - - //On Windows, not desktop platforms we are using XAudio2.lib - //On Windows Desktop it's more complicated specially because Windows 7, we try from 2.9 to 2.7 (COM loaded) - -#ifdef WINDOWS_DESKTOP - xnXAudioLib = LoadDynamicLibrary("XAudio2_9"); //win10+ - xnHrtfApoLib = LoadDynamicLibrary("HrtfApo"); //win10+ - - if (!xnXAudioLib) xnXAudioLib = LoadDynamicLibrary("XAudio2_8"); //win8+ - - if(xnXAudioLib) - { - XAudio2CreateFunc = (XAudio2CreatePtr)GetSymbolAddress(xnXAudioLib, "XAudio2Create"); - if (!XAudio2CreateFunc) return false; - - if(xnHrtfApoLib) - { - CreateHrtfApoFunc = (CreateHrtfApoPtr)GetSymbolAddress(xnHrtfApoLib, "CreateHrtfApo"); - IIDFromString(L"{15B3CD66-E9DE-4464-B6E6-2BC3CF63D455}", &xnHrtfParamsIID); - } - } - else - { - xnAudioWindows7Hacks = true; - - //also load X3daudio - xnXAudioLib = LoadDynamicLibrary("X3DAudio1_7"); - if (!xnXAudioLib) return false; - } - - if (!xnXAudioLib) return false; - - X3DAudioInitializeFunc = (X3DAudioInitializePtr)GetSymbolAddress(xnXAudioLib, "X3DAudioInitialize"); - if (!X3DAudioInitializeFunc) return false; - X3DAudioCalculateFunc = (X3DAudioCalculatePtr)GetSymbolAddress(xnXAudioLib, "X3DAudioCalculate"); - if (!X3DAudioCalculateFunc) return false; -#endif - - return true; - } - - struct xnAudioDevice - { - IXAudio2* x_audio2_; - IXAudio2_7* x_audio2_7_; - X3DAUDIO_HANDLE x3_audio_; - IXAudio2MasteringVoice* mastering_voice_; - bool hrtf_; - }; - - struct xnAudioSource; - DLL_EXPORT_API void xnAudioSourceStop(xnAudioSource* source); - - struct xnAudioBuffer - { - XAUDIO2_BUFFER buffer_; - int length_; - BufferType type_; - }; - - struct xnAudioListener - { - xnAudioDevice* device_; - X3DAUDIO_LISTENER listener_; - Matrix worldTransform_; - }; - - enum xnAudioDeviceFlags - { - xnAudioDeviceFlagsNone, - xnAudioDeviceFlagsHrtf - }; - - DLL_EXPORT_API xnAudioDevice* xnAudioCreate(void* deviceName, xnAudioDeviceFlags flags) //Device name is actually LPCWSTR, on C# side encoding is Unicode! - { - xnAudioDevice* res = new xnAudioDevice; - - HRESULT result; - -#ifdef WINDOWS_DESKTOP - if(xnAudioWindows7Hacks) - { -#define CLSCTX_INPROC_SERVER 0x1 - IID cid, iid; - IIDFromString(L"{5a508685-a254-4fba-9b82-9a24b00306af}", &cid); - IIDFromString(L"{8bcf1f58-9fe7-4583-8ac6-e2adc465c8bb}", &iid); - result = CoCreateInstance(cid, NULL, CLSCTX_INPROC_SERVER, iid, (void**)&res->x_audio2_7_); - if (FAILED(result)) - { - printf("CoCreateInstance failed to create XAudio2 instance.\n"); - delete res; - return NULL; - } - - result = res->x_audio2_7_->Initialize(0, 0x00000001); - if (FAILED(result)) - { - printf("Failed to init XAudio2 instance.\n"); - delete res; - return NULL; - } - - result = res->x_audio2_7_->CreateMasteringVoice(&res->mastering_voice_, AUDIO_CHANNELS); - if (FAILED(result)) - { - printf("Failed to create XAudio2 MasteringVoice.\n"); - delete res; - return NULL; - } - - result = res->x_audio2_7_->StartEngine(); - if (FAILED(result)) - { - printf("Failed to create start XAudio2 engine.\n"); - delete res; - return NULL; - } - } - else -#endif - { - res->hrtf_ = xnHrtfApoLib && (flags & xnAudioDeviceFlagsHrtf); - - //XAudio2, no flags, processor 1 - result = XAudio2CreateFunc(reinterpret_cast(&res->x_audio2_), res->hrtf_ ? XAUDIO2_1024_QUANTUM : 0, 0x00000001); - if (FAILED(result)) - { - delete res; - return NULL; - } - - //this means opening the real audio device, which will be virtual actually so in the case of default device change Xaudio will deal with it for us. - result = res->x_audio2_->CreateMasteringVoice(&res->mastering_voice_, AUDIO_CHANNELS, 0, 0, deviceName); - if (FAILED(result)) - { - delete res; - return NULL; - } - - //start audio rendering - result = res->x_audio2_->StartEngine(); - if (FAILED(result)) - { - delete res; - return NULL; - } - } - - //X3DAudio - result = X3DAudioInitializeFunc(SPEAKER_STEREO, SPEED_OF_SOUND, res->x3_audio_); - if (FAILED(result)) - { - delete res; - return NULL; - } - - return res; - } - - DLL_EXPORT_API void xnAudioDestroy(xnAudioDevice* device) - { - if(xnAudioWindows7Hacks) - { - device->x_audio2_7_->StopEngine(); - } - else - { - device->x_audio2_->StopEngine(); - } - - device->mastering_voice_->DestroyVoice(); - - delete device; - } - - DLL_EXPORT_API void xnAudioUpdate(xnAudioDevice* device) - { - } - - DLL_EXPORT_API void xnAudioSetMasterVolume(xnAudioDevice* device, float volume) - { - device->mastering_voice_->SetVolume(volume); - } - - DLL_EXPORT_API xnAudioListener* xnAudioListenerCreate(xnAudioDevice* device) - { - auto res = new xnAudioListener; - res->device_ = device; - memset(&res->listener_, 0x0, sizeof(X3DAUDIO_LISTENER)); - return res; - } - - DLL_EXPORT_API void xnAudioListenerDestroy(xnAudioListener* listener) - { - delete listener; - } - - DLL_EXPORT_API npBool xnAudioListenerEnable(xnAudioListener* listener) - { - //unused in Xaudio2 - (void)listener; - return true; - } - - DLL_EXPORT_API void xnAudioListenerDisable(xnAudioListener* listener) - { - //unused in Xaudio2 - (void)listener; - } - - struct xnAudioSource : IXAudio2VoiceCallback - { - IXAudio2MasteringVoice* mastering_voice_; - IXAudio2SourceVoice* source_voice_; - X3DAUDIO_EMITTER* emitter_; - X3DAUDIO_DSP_SETTINGS* dsp_settings_; - IXAPOHrtfParameters* hrtf_params_; - xnAudioListener* listener_; - volatile bool playing_; - volatile bool pause_; - volatile bool looped_; - int sampleRate_; - bool mono_; - bool streamed_; - volatile float pitch_ = 1.0f; - volatile float doppler_pitch_ = 1.0f; - - SpinLock bufferLock_; - SpinLock apply3DLock_; - xnAudioBuffer** freeBuffers_; - int freeBuffersMax_; - - XAUDIO2_BUFFER single_buffer_; - - volatile int samplesAtBegin = 0; - - void __stdcall OnVoiceProcessingPassStart(UINT32 BytesRequired) override; - - void __stdcall OnVoiceProcessingPassEnd() override; - - void __stdcall OnStreamEnd() override; - - void __stdcall OnBufferStart(void* context) override; - - void __stdcall OnBufferEnd(void* context) override; - - void __stdcall OnLoopEnd(void* context) override; - - void __stdcall OnVoiceError(void* context, HRESULT error) override; - - void GetState(XAUDIO2_VOICE_STATE* state) - { - if (xnAudioWindows7Hacks) - { - auto win7Voice = reinterpret_cast(source_voice_); - win7Voice->GetState(state); - } - else - { - source_voice_->GetState(state, 0); - } - } - }; - - DLL_EXPORT_API xnAudioSource* xnAudioSourceCreate(xnAudioListener* listener, int sampleRate, int maxNBuffers, npBool mono, npBool spatialized, npBool streamed, npBool hrtf, float directionFactor, HrtfEnvironment environment) - { - (void)streamed; - - auto res = new xnAudioSource; - res->hrtf_params_ = NULL; - res->listener_ = listener; - res->playing_ = false; - res->sampleRate_ = sampleRate; - res->mono_ = mono; - res->streamed_ = streamed; - res->looped_ = false; - res->mastering_voice_ = listener->device_->mastering_voice_; - if((spatialized && !hrtf) || (hrtf && !res->listener_->device_->hrtf_)) - { - //if spatialized we also need those structures to calculate 3D audio - res->emitter_ = new X3DAUDIO_EMITTER; - memset(res->emitter_, 0x0, sizeof(X3DAUDIO_EMITTER)); - res->emitter_->ChannelCount = 1; - res->emitter_->CurveDistanceScaler = 1; - res->emitter_->DopplerScaler = 1; - - res->dsp_settings_ = new X3DAUDIO_DSP_SETTINGS; - memset(res->dsp_settings_, 0x0, sizeof(X3DAUDIO_DSP_SETTINGS)); - res->dsp_settings_->SrcChannelCount = 1; - res->dsp_settings_->DstChannelCount = AUDIO_CHANNELS; - res->dsp_settings_->pMatrixCoefficients = new float[AUDIO_CHANNELS]; - res->dsp_settings_->pDelayTimes = new float[AUDIO_CHANNELS]; - } - else - { - res->emitter_ = NULL; - res->dsp_settings_ = NULL; - } - - //we could have used a tinystl vector but it did not link properly on ARM windows... so we just use an array - res->freeBuffers_ = new xnAudioBuffer*[maxNBuffers]; - res->freeBuffersMax_ = maxNBuffers; - for (auto i = 0; i < maxNBuffers; i++) - { - res->freeBuffers_[i] = NULL; - } - - //Normal PCM formal 16 bit shorts - WAVEFORMATEX pcmWaveFormat = {}; - pcmWaveFormat.wFormatTag = WAVE_FORMAT_PCM; - pcmWaveFormat.nChannels = mono ? 1 : 2; - pcmWaveFormat.nSamplesPerSec = sampleRate; - pcmWaveFormat.nAvgBytesPerSec = sampleRate * pcmWaveFormat.nChannels * sizeof(short); - pcmWaveFormat.wBitsPerSample = 16; - pcmWaveFormat.nBlockAlign = pcmWaveFormat.nChannels * pcmWaveFormat.wBitsPerSample / 8; - - if(xnAudioWindows7Hacks) - { - HRESULT result = listener->device_->x_audio2_7_->CreateSourceVoice(&res->source_voice_, &pcmWaveFormat, 0, XAUDIO2_MAX_FREQ_RATIO, res); - if (FAILED(result)) - { - delete res; - return NULL; - } - } - else - { - HRESULT result = listener->device_->x_audio2_->CreateSourceVoice(&res->source_voice_, &pcmWaveFormat, 0, XAUDIO2_MAX_FREQ_RATIO, res); - if (FAILED(result)) - { - delete res; - return NULL; - } - } - - if (spatialized && res->listener_->device_->hrtf_ && hrtf) - { - IXAudio2SubmixVoice* submixVoice = NULL; - - HrtfApoInit params = {}; - HrtfDirectivity directivity; - directivity.type = OmniDirectional; - directivity.scaling = directionFactor; - params.directivity = &directivity; - - IUnknown* apoRoot; - HRESULT result = CreateHrtfApoFunc(¶ms, &apoRoot); - if (FAILED(result)) - { - delete res; - return NULL; - } - - apoRoot->QueryInterface(xnHrtfParamsIID, reinterpret_cast(&res->hrtf_params_)); - - XAUDIO2_EFFECT_DESCRIPTOR fxDesc{}; - fxDesc.InitialState = true; - fxDesc.OutputChannels = 2; // Stereo output - fxDesc.pEffect = res->hrtf_params_; // HRTF xAPO set as the effect. - - XAUDIO2_EFFECT_CHAIN fxChain{}; - fxChain.EffectCount = 1; - fxChain.pEffectDescriptors = &fxDesc; - - XAUDIO2_VOICE_SENDS sends = {}; - XAUDIO2_SEND_DESCRIPTOR sendDesc = {}; - sendDesc.pOutputVoice = res->mastering_voice_; - sends.SendCount = 1; - sends.pSends = &sendDesc; - - // HRTF APO expects mono 48kHz input, so we configure the submix voice for that format. - result = listener->device_->x_audio2_->CreateSubmixVoice(&submixVoice, 1, 48000, 0, 0, &sends, &fxChain); - if (FAILED(result)) - { - delete res; - return NULL; - } - - res->hrtf_params_->SetEnvironment(environment); - - XAUDIO2_VOICE_SENDS voice_sends = {}; - XAUDIO2_SEND_DESCRIPTOR voice_sendDesc = {}; - voice_sendDesc.pOutputVoice = submixVoice; - voice_sends.SendCount = 1; - voice_sends.pSends = &voice_sendDesc; - result = res->source_voice_->SetOutputVoices(&voice_sends); - if (FAILED(result)) - { - delete res; - return NULL; - } - } - - return res; - } - - DLL_EXPORT_API void xnAudioSourceDestroy(xnAudioSource* source) - { - source->source_voice_->Stop(); - source->source_voice_->DestroyVoice(); - if (source->emitter_) delete source->emitter_; - if (source->dsp_settings_) - { - delete[] source->dsp_settings_->pMatrixCoefficients; - delete[] source->dsp_settings_->pDelayTimes; - delete source->dsp_settings_; - } - delete source; - } - - DLL_EXPORT_API void xnAudioSourceSetLooping(xnAudioSource* source, npBool looping) - { - source->looped_ = looping; - - if (!source->streamed_) - { - if (!source->looped_) - { - source->single_buffer_.LoopBegin = 0; - source->single_buffer_.LoopLength = 0; - source->single_buffer_.LoopCount = 0; - source->single_buffer_.Flags = XAUDIO2_END_OF_STREAM; - } - else - { - source->single_buffer_.LoopBegin = source->single_buffer_.PlayBegin; - source->single_buffer_.LoopLength = source->single_buffer_.PlayLength; - source->single_buffer_.LoopCount = XAUDIO2_LOOP_INFINITE; - source->single_buffer_.Flags = 0; - } - - source->source_voice_->FlushSourceBuffers(); - source->source_voice_->SubmitSourceBuffer(&source->single_buffer_, NULL); - } - } - - DLL_EXPORT_API void xnAudioSourceSetBuffer(xnAudioSource* source, xnAudioBuffer* buffer) - { - //this function is called only when the audio source is acutally fully cached in memory, so we deal only with the first buffer - source->streamed_ = false; - source->freeBuffers_[0] = buffer; - memcpy(&source->single_buffer_, &buffer->buffer_, sizeof(XAUDIO2_BUFFER)); - source->source_voice_->SubmitSourceBuffer(&source->single_buffer_, NULL); - } - - DLL_EXPORT_API xnAudioBuffer* xnAudioSourceGetFreeBuffer(xnAudioSource* source) - { - //this is used only when we are streaming audio, to fetch the next free buffer to fill - source->bufferLock_.Lock(); - - xnAudioBuffer* buffer = NULL; - for (int i = 0; i < source->freeBuffersMax_; i++) - { - if (source->freeBuffers_[i] != NULL) - { - buffer = source->freeBuffers_[i]; - source->freeBuffers_[i] = NULL; - break; - } - } - - source->bufferLock_.Unlock(); - - return buffer; - } - - DLL_EXPORT_API void xnAudioSourcePlay(xnAudioSource* source) - { - source->source_voice_->Start(); - source->playing_ = true; - - if(!source->streamed_ && !source->pause_) - { - XAUDIO2_VOICE_STATE state; - source->GetState(&state); - source->samplesAtBegin = state.SamplesPlayed; - } - - source->pause_ = false; - } - - DLL_EXPORT_API void xnAudioSourceSetPan(xnAudioSource* source, float pan) - { - if (source->mono_) - { - float panning[2]; - if (pan < 0) - { - panning[0] = 1.0f; - panning[1] = 1.0f + pan; - } - else - { - panning[0] = 1.0f - pan; - panning[1] = 1.0f; - } - source->source_voice_->SetOutputMatrix(source->mastering_voice_, 1, AUDIO_CHANNELS, panning); - } - else - { - float panning[4]; - if (pan < 0) - { - panning[0] = 1.0f; - panning[1] = 0.0f; - panning[2] = 0.0f; - panning[3] = 1.0f + pan; - } - else - { - panning[0] = 1.0f - pan; - panning[1] = 0.0f; - panning[2] = 0.0f; - panning[3] = 1.0f; - } - source->source_voice_->SetOutputMatrix(source->mastering_voice_, 2, AUDIO_CHANNELS, panning); - } - } - - DLL_EXPORT_API double xnAudioSourceGetPosition(xnAudioSource* source) - { - XAUDIO2_VOICE_STATE state; - source->GetState(&state); - - if (!source->streamed_) - return double(source->single_buffer_.PlayBegin + state.SamplesPlayed - source->samplesAtBegin) / double(source->sampleRate_); - - //things work different for streamed sources, but anyway we simply subtract the snapshotted samples at begin of the stream ( could be the begin of the loop ) - return double(state.SamplesPlayed - source->samplesAtBegin) / double(source->sampleRate_); - } - - DLL_EXPORT_API void xnAudioSourceSetRange(xnAudioSource* source, double startTime, double stopTime) - { - if(!source->streamed_) - { - auto singleBuffer = source->freeBuffers_[0]; - if(startTime == 0 && stopTime == 0) - { - source->single_buffer_.PlayBegin = 0; - source->single_buffer_.PlayLength = singleBuffer->length_; - } - else - { - auto sampleStart = int(double(source->sampleRate_) * startTime); - auto sampleStop = int(double(source->sampleRate_) * stopTime); - - if (sampleStart > singleBuffer->length_) - { - return; //the starting position must be less then the total length of the buffer - } - - if (sampleStop > singleBuffer->length_) //if the end point is more then the length of the buffer fix the value - { - sampleStop = singleBuffer->length_; - } - - auto len = sampleStop - sampleStart; - if (len > 0) - { - source->single_buffer_.PlayBegin = sampleStart; - source->single_buffer_.PlayLength = len; - } - } - - //sort looping properties and re-submit buffer - source->source_voice_->Stop(); - xnAudioSourceSetLooping(source, source->looped_); - } - } - - DLL_EXPORT_API void xnAudioSourceSetGain(xnAudioSource* source, float gain) - { - source->source_voice_->SetVolume(gain); - } - - DLL_EXPORT_API void xnAudioSourceSetPitch(xnAudioSource* source, float pitch) - { - source->pitch_ = pitch; - source->source_voice_->SetFrequencyRatio(source->doppler_pitch_ * source->pitch_); - } - - void xnAudioSource::OnVoiceProcessingPassStart(unsigned BytesRequired) - { - } - - void xnAudioSource::OnVoiceProcessingPassEnd() - { - } - - void xnAudioSource::OnStreamEnd() - { - if (playing_) - { - if (streamed_) - { - //buffer was flagged as end of stream - //looping is handled by the streamer, in the top level layer - xnAudioSourceStop(this); - } - else if (!looped_) - { - playing_ = false; - pause_ = false; - } - } - } - - void xnAudioSource::OnBufferStart(void* context) - { - if (streamed_) - { - auto buffer = static_cast(context); - - if (buffer->type_ == BeginOfStream) - { - //we need this info to compute position of stream - XAUDIO2_VOICE_STATE state; - GetState(&state); - - samplesAtBegin = state.SamplesPlayed; - } - } - } - - void xnAudioSource::OnBufferEnd(void* context) - { - if (streamed_) - { - auto buffer = static_cast(context); - - bufferLock_.Lock(); - - for (int i = 0; i < freeBuffersMax_; i++) - { - if (freeBuffers_[i] == NULL) - { - freeBuffers_[i] = buffer; - break; - } - } - - bufferLock_.Unlock(); - } - } - - void xnAudioSource::OnLoopEnd(void* context) - { - if (!streamed_) - { - XAUDIO2_VOICE_STATE state; - GetState(&state); - - samplesAtBegin = state.SamplesPlayed; - } - } - - DLL_EXPORT_API void xnAudioSourceQueueBuffer(xnAudioSource* source, xnAudioBuffer* buffer, short* pcm, int bufferSize, BufferType type) - { - //used only when streaming, to fill a buffer, often.. - source->streamed_ = true; - - //flag the stream - buffer->buffer_.Flags = type == EndOfStream ? XAUDIO2_END_OF_STREAM : 0; - buffer->type_ = type; - - buffer->length_ = buffer->buffer_.AudioBytes = bufferSize; - memcpy(const_cast(buffer->buffer_.pAudioData), pcm, bufferSize); - source->source_voice_->SubmitSourceBuffer(&buffer->buffer_); - } - - DLL_EXPORT_API void xnAudioSourcePause(xnAudioSource* source) - { - source->source_voice_->Stop(); - source->playing_ = false; - source->pause_ = true; - } - - XMFLOAT3::XMFLOAT3(): x(0), y(0), z(0) - { - } - - XMFLOAT3::XMFLOAT3(float _x, float _y, float _z): x(_x), y(_y), z(_z) - { - } - - XMFLOAT3::XMFLOAT3(const float* pArray): x(pArray[0]), y(pArray[1]), z(pArray[2]) - { - } - - XMFLOAT3& XMFLOAT3::operator=(const XMFLOAT3& Float3) - { - x = Float3.x; - y = Float3.y; - z = Float3.z; - return *this; - } - - DLL_EXPORT_API void xnAudioSourceFlushBuffers(xnAudioSource* source) - { - source->apply3DLock_.Lock(); - - source->source_voice_->FlushSourceBuffers(); - - source->apply3DLock_.Unlock(); - } - - DLL_EXPORT_API void xnAudioSourceStop(xnAudioSource* source) - { - source->apply3DLock_.Lock(); - - source->source_voice_->Stop(); - source->source_voice_->FlushSourceBuffers(); - source->playing_ = false; - source->pause_ = false; - - //since we flush we also rebuffer in this case - if (!source->streamed_) - { - source->source_voice_->SubmitSourceBuffer(&source->single_buffer_, NULL); - } - - source->apply3DLock_.Unlock(); - } - - DLL_EXPORT_API void xnAudioListenerPush3D(xnAudioListener* listener, float* pos, float* forward, float* up, float* vel, Matrix* worldTransform) - { - memcpy(&listener->listener_.Position, pos, sizeof(float) * 3); - memcpy(&listener->listener_.Velocity, vel, sizeof(float) * 3); - memcpy(&listener->listener_.OrientFront, forward, sizeof(float) * 3); - memcpy(&listener->listener_.OrientTop, up, sizeof(float) * 3); - memcpy(&listener->worldTransform_, worldTransform, sizeof(Matrix)); - } - - DLL_EXPORT_API void xnAudioSourcePush3D(xnAudioSource* source, float* pos, float* forward, float* up, float* vel, Matrix* worldTransform) - { - if(source->hrtf_params_) - { - Matrix localTransform; - Matrix invListener; - memcpy(&invListener, &source->listener_->worldTransform_, sizeof(Matrix)); - xnMatrixInvert(&invListener); - xnMatrixMultiply(worldTransform, &invListener, &localTransform); - - HrtfPosition hrtfEmitterPos{ localTransform.Flat.M41, localTransform.Flat.M42, localTransform.Flat.M43 }; - source->hrtf_params_->SetSourcePosition(&hrtfEmitterPos); - - //set orientation, relative to head, already computed c# side, todo c++ side - HrtfOrientation hrtfEmitterRot { - localTransform.Flat.M11, localTransform.Flat.M12, localTransform.Flat.M13, - localTransform.Flat.M21, localTransform.Flat.M22, localTransform.Flat.M23, - localTransform.Flat.M31, localTransform.Flat.M32, localTransform.Flat.M33 }; - source->hrtf_params_->SetSourceOrientation(&hrtfEmitterRot); - } - else - { - if (!source->emitter_) return; - - memcpy(&source->emitter_->Position, pos, sizeof(float) * 3); - memcpy(&source->emitter_->Velocity, vel, sizeof(float) * 3); - memcpy(&source->emitter_->OrientFront, forward, sizeof(float) * 3); - memcpy(&source->emitter_->OrientTop, up, sizeof(float) * 3); - - source->apply3DLock_.Lock(); //todo is that really needed? - - //everything is calculated by Xaudio for us - X3DAudioCalculateFunc(source->listener_->device_->x3_audio_, &source->listener_->listener_, source->emitter_, - X3DAUDIO_CALCULATE_MATRIX | X3DAUDIO_CALCULATE_DOPPLER | X3DAUDIO_CALCULATE_LPF_DIRECT | X3DAUDIO_CALCULATE_REVERB, source->dsp_settings_); - - source->source_voice_->SetOutputMatrix(source->mastering_voice_, 1, AUDIO_CHANNELS, source->dsp_settings_->pMatrixCoefficients); - source->doppler_pitch_ = source->dsp_settings_->DopplerFactor; - source->source_voice_->SetFrequencyRatio(source->dsp_settings_->DopplerFactor * source->pitch_); - XAUDIO2_FILTER_PARAMETERS filter_parameters = { LowPassFilter, 2.0f * (float)sin(X3DAUDIO_PI / 6.0f * source->dsp_settings_->LPFDirectCoefficient), 1.0f }; - if (!xnAudioWindows7Hacks) source->source_voice_->SetFilterParameters(&filter_parameters); - - source->apply3DLock_.Unlock(); - } - } - - DLL_EXPORT_API npBool xnAudioSourceIsPlaying(xnAudioSource* source) - { - return source->playing_ || source->pause_; - } - - DLL_EXPORT_API xnAudioBuffer* xnAudioBufferCreate(int maxBufferSize) - { - auto buffer = new xnAudioBuffer; - buffer->length_ = 0; - buffer->buffer_ = {}; - buffer->buffer_.pContext = buffer; - buffer->buffer_.PlayBegin = 0; - buffer->buffer_.PlayLength = 0; - buffer->buffer_.LoopBegin = 0; - buffer->buffer_.LoopLength = 0; - buffer->buffer_.LoopCount = 0; - buffer->buffer_.pAudioData = new BYTE[maxBufferSize]; - return buffer; - } - - DLL_EXPORT_API void xnAudioBufferDestroy(xnAudioBuffer* buffer) - { - delete[] buffer->buffer_.pAudioData; - delete buffer; - } - - DLL_EXPORT_API void xnAudioBufferFill(xnAudioBuffer* buffer, short* pcm, int bufferSize, int sampleRate, npBool mono) - { - (void)sampleRate; - - buffer->buffer_.AudioBytes = bufferSize; - - buffer->buffer_.PlayBegin = 0; - buffer->buffer_.PlayLength = buffer->length_ = (bufferSize / sizeof(short)) / (mono ? 1 : 2); - - memcpy(const_cast(buffer->buffer_.pAudioData), pcm, bufferSize); - } - - void xnAudioSource::OnVoiceError(void* context, long error) - { - } - } -} - -SpinLock::SpinLock() -{ - mLocked = false; -} - -void SpinLock::Lock() -{ - while (!__sync_bool_compare_and_swap(&mLocked, false, true)) - { - } -} - -void SpinLock::Unlock() -{ - mLocked = false; -} - -#endif diff --git a/sources/engine/Xenko.Audio/Xenko.Audio.csproj b/sources/engine/Xenko.Audio/Xenko.Audio.csproj index bbd8dec9b1..c5dee3a11d 100644 --- a/sources/engine/Xenko.Audio/Xenko.Audio.csproj +++ b/sources/engine/Xenko.Audio/Xenko.Audio.csproj @@ -1,4 +1,4 @@ - + true @@ -48,9 +48,6 @@ - - - From b6abf2b2803f5321a76e35864f96add9e19299bd Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 12 Feb 2020 12:24:32 -0500 Subject: [PATCH 0731/2038] Lighting: make clustered lighting multithreaded --- .../LightClusteredPointSpotGroupRenderer.cs | 260 +++++++++--------- 1 file changed, 129 insertions(+), 131 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index 0d5c3014a7..8d0f4bcd3e 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -2,10 +2,14 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Runtime.CompilerServices; +using System.Threading; using Xenko.Core; using Xenko.Core.Collections; using Xenko.Core.Mathematics; +using Xenko.Core.Threading; using Xenko.Engine; using Xenko.Graphics; using Xenko.Rendering.Shadows; @@ -159,8 +163,7 @@ internal class PointLightShaderGroupData : LightShaderGroupDynamic // Artifically increase range of first slice to not waste too much slices in very short area public float SpecialNearPlane = 2.0f; - private FastListStruct lightNodes = new FastListStruct(8); - private FastListStruct clusterInfos = new FastListStruct(8); + private List> lightNodes = new List>(); private RenderViewInfo[] renderViewInfos; private Int2 maxClusterCount; //private Plane[] zPlanes; @@ -280,15 +283,6 @@ public void ComputeViewParameter(int viewIndex) // zPlanes[z].Normalize(); //} - // Initialize cluster with no light (-1) - for (int i = 0; i < maxClusterCount.X * maxClusterCount.Y * ClusterSlices; ++i) - { - lightNodes.Add(new LightClusterLinkedNode(InternalLightType.Point, -1, -1)); - } - - // List of clusters moved by this light - var movedClusters = new Dictionary(); - // Try to use SpecialNearPlane to not waste too much slices in very small depth // Make sure we don't go to more than 10% of max depth var nearPlane = Math.Max(Math.Min(SpecialNearPlane, renderView.FarClipPlane * 0.1f), renderView.NearClipPlane); @@ -301,33 +295,44 @@ public void ComputeViewParameter(int viewIndex) float clusterDepthScale = renderViewInfo.ClusterDepthScale = (float)(Math.Pow(2.0f, ClusterSlices) - 2.0f) / (renderView.FarClipPlane - nearPlane); float clusterDepthBias = renderViewInfo.ClusterDepthBias = 2.0f - clusterDepthScale * nearPlane; - //---------------- SPOT LIGHTS ------------------- - var lightRange = clusteredGroupRenderer.spotGroup.LightRanges[viewIndex]; - for (int i = lightRange.Start; i < lightRange.End; ++i) + // make sure we have enough lists + while (lightNodes.Count < totalClusterCount) + lightNodes.Add(new ConcurrentQueue()); + + //---------------- POINT LIGHTS ------------------- + var lightRange = lightRanges[viewIndex]; + + // make point light data + for (int i=lightRange.Start; i + { + var light = lights[i].Light; + var pointLight = (LightPoint)light.Type; + var pointLightData = renderViewInfos[viewIndex].PointLights[i]; - var radius = UseLinearLighting ? spotLightData.AngleOffsetAndInvSquareRadius.Z : (float)Math.Sqrt(1.0f / spotLightData.AngleOffsetAndInvSquareRadius.Z); + var radius = LightClusteredPointSpotGroupRenderer.UseLinearLighting ? pointLightData.InvSquareRadius : (float)Math.Sqrt(1.0f / pointLightData.InvSquareRadius); Vector3 positionVS; - Vector3.TransformCoordinate(ref spotLightData.PositionWS, ref renderView.View, out positionVS); + Vector3.TransformCoordinate(ref pointLightData.PositionWS, ref renderView.View, out positionVS); + + //Vector3 positionScreen; + //Vector3.TransformCoordinate(ref pointLightData.PositionWS, ref renderView.ViewProjection, out positionScreen); - // TODO: culling (first do it on PointLight, then backport it to SpotLight and improve for SpotLight case) // Find x/y ranges Vector2 clipMin, clipMax; ComputeClipRegion(positionVS, radius, ref renderView.Projection, out clipMin, out clipMax); @@ -341,49 +346,64 @@ public void ComputeViewParameter(int viewIndex) var startZ = -positionVS.Z - radius; var endZ = -positionVS.Z + radius; + //var centerZ = (int)(positionVS.Z * ClusterDepthScale + ClusterDepthBias); var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); for (int z = tileStartZ; z < tileEndZ; ++z) { + // TODO: Additional culling on x/y (to remove corner clusters) + // See "Practical Clustered Shading" for details + //if (z != centerZ) + //{ + // var plane = z < centerZ ? zPlanes[z + 1] : -zPlanes[z]; + // + // positionScreen = Plane.DotCoordinate(ref plane, ref positionScreen, out ) + //} + for (int y = tileStartY; y < tileEndY; ++y) { for (int x = tileStartX; x < tileEndX; ++x) { - AddLightToCluster(movedClusters, InternalLightType.Spot, i - lightRange.Start, x + (y + z * clusterCountY) * clusterCountX); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(new LightClusterLinkedNode(InternalLightType.Point, i - lightRange.Start)); } } } - } + }); - //---------------- POINT LIGHTS ------------------- - lightRange = lightRanges[viewIndex]; - for (int i = lightRange.Start; i < lightRange.End; ++i) + //---------------- SPOT LIGHTS ------------------- + lightRange = clusteredGroupRenderer.spotGroup.LightRanges[viewIndex]; + + // make spotlight data + for (int i=lightRange.Start; i + { + var light = clusteredGroupRenderer.spotGroup.Lights[i].Light; + var spotLight = (LightSpot)light.Type; + var spotLightData = renderViewInfos[viewIndex].SpotLights[i]; - var radius = LightClusteredPointSpotGroupRenderer.UseLinearLighting ? pointLightData.InvSquareRadius : (float)Math.Sqrt(1.0f / pointLightData.InvSquareRadius); + var radius = UseLinearLighting ? spotLightData.AngleOffsetAndInvSquareRadius.Z : (float)Math.Sqrt(1.0f / spotLightData.AngleOffsetAndInvSquareRadius.Z); Vector3 positionVS; - Vector3.TransformCoordinate(ref pointLightData.PositionWS, ref renderView.View, out positionVS); - - //Vector3 positionScreen; - //Vector3.TransformCoordinate(ref pointLightData.PositionWS, ref renderView.ViewProjection, out positionScreen); + Vector3.TransformCoordinate(ref spotLightData.PositionWS, ref renderView.View, out positionVS); + // TODO: culling (first do it on PointLight, then backport it to SpotLight and improve for SpotLight case) // Find x/y ranges Vector2 clipMin, clipMax; ComputeClipRegion(positionVS, radius, ref renderView.Projection, out clipMin, out clipMax); @@ -397,48 +417,26 @@ public void ComputeViewParameter(int viewIndex) var startZ = -positionVS.Z - radius; var endZ = -positionVS.Z + radius; - //var centerZ = (int)(positionVS.Z * ClusterDepthScale + ClusterDepthBias); var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); for (int z = tileStartZ; z < tileEndZ; ++z) { - // TODO: Additional culling on x/y (to remove corner clusters) - // See "Practical Clustered Shading" for details - //if (z != centerZ) - //{ - // var plane = z < centerZ ? zPlanes[z + 1] : -zPlanes[z]; - // - // positionScreen = Plane.DotCoordinate(ref plane, ref positionScreen, out ) - //} - for (int y = tileStartY; y < tileEndY; ++y) { for (int x = tileStartX; x < tileEndX; ++x) { - AddLightToCluster(movedClusters, InternalLightType.Point, i - lightRange.Start, x + (y + z * clusterCountY) * clusterCountX); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(new LightClusterLinkedNode(InternalLightType.Spot, i - lightRange.Start)); } } } - } + }); - // Finish clusters by making their last element unique and building clusterInfos - movedClusters.Clear(); + var grouping = new Dictionary(); for (int i = 0; i < totalClusterCount; ++i) { - FinishCluster(movedClusters, ref renderViewInfo.LightIndices, i); + renderViewInfo.LightClusters[i] = FinishCluster(grouping, ref renderViewInfo.LightIndices, i); } - - // Prepare light clusters - for (int i = 0; i < totalClusterCount; ++i) - { - var clusterId = lightNodes[i].NextNode; - renderViewInfo.LightClusters[i] = clusterId != -1 ? clusterInfos[clusterId] : new Int2(0, 0); - } - - // Clear data - lightNodes.Clear(); - clusterInfos.Clear(); } public unsafe void ComputeViewsParameter(RenderDrawContext drawContext) @@ -570,74 +568,76 @@ public override unsafe void UpdateViewResources(RenderDrawContext context, int v #endif } - private void FinishCluster(Dictionary movedClusters, ref FastListStruct lightIndices, int clusterIndex) + private struct IndexPattern : IEquatable { - var clusterId = -1; - if (lightNodes.Items[clusterIndex].LightIndex != -1) - { - var movedCluster = lightNodes.Items[clusterIndex]; + public List pattern; - // Try to check if same linked-list doesn't already exist - if (!movedClusters.TryGetValue(movedCluster, out clusterId)) - { - // First time, let's add it - clusterId = movedClusters.Count; - movedClusters.Add(movedCluster, clusterId); - - int lightIndex = lightNodes.Count; - lightNodes.Add(movedCluster); - - // Build light indices - int pointLightCounter = 0; - int spotLightCounter = 0; + public bool Equals(IndexPattern other) + { + if (other.pattern.Count != pattern.Count) return false; + for (int i = 0; i < pattern.Count; i++) + if (pattern[i] != other.pattern[i]) return false; + return true; + } - while (lightIndex != -1) - { - movedCluster = lightNodes[lightIndex]; - lightIndices.Add(movedCluster.LightIndex); - switch (movedCluster.LightType) - { - case InternalLightType.Point: - pointLightCounter++; - break; - case InternalLightType.Spot: - spotLightCounter++; - break; - } - lightIndex = movedCluster.NextNode; - } + public override bool Equals(object obj) + { + return obj is IndexPattern ip && Equals(ip); + } - // Add new light cluster range - // Stored in the format: - // x = start_index - // y & 0xFFFF = point_light_count - // y >> 16 = spot_light_count - clusterInfos.Add(new Int2(lightIndices.Count - pointLightCounter - spotLightCounter, pointLightCounter | (spotLightCounter << 16))); + public override int GetHashCode() + { + unchecked + { + int res = pattern.Count * 857; + for (int i = 0; i < pattern.Count; i++) + res ^= pattern[i] * 257 * (i + 1); + return res; } } - - // Last pass: store cluster id (instead of next node) - lightNodes.Items[clusterIndex] = new LightClusterLinkedNode(InternalLightType.Point, -1, clusterId); } - private void AddLightToCluster(Dictionary movedClusters, InternalLightType lightType, int lightIndex, int clusterIndex) + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private Int2 FinishCluster(Dictionary grouping, ref FastListStruct lightIndices, int clusterIndex) { - var nextNode = -1; - var movedCluster = lightNodes.Items[clusterIndex]; - if (movedCluster.LightIndex != -1) + if (lightNodes[clusterIndex].IsEmpty) return Int2.Zero; + + // Build light indices + int pointLightCounter = 0; + int spotLightCounter = 0; + + IndexPattern ip = new IndexPattern(); + ip.pattern = new List(); + + while (lightNodes[clusterIndex].TryDequeue(out var cluster)) { - // Try to check if same linked-list doesn't already exist - if (!movedClusters.TryGetValue(movedCluster, out nextNode)) + ip.pattern.Add(cluster.LightIndex); + + switch (cluster.LightType) { - // First time, let's add it - nextNode = lightNodes.Count; - movedClusters.Add(movedCluster, nextNode); - lightNodes.Add(movedCluster); + case InternalLightType.Point: + pointLightCounter++; + break; + case InternalLightType.Spot: + spotLightCounter++; + break; } } - // Replace new linked-list head - lightNodes.Items[clusterIndex] = new LightClusterLinkedNode(lightType, lightIndex, nextNode); + if (grouping.TryGetValue(ip, out int startingIndex) == false) + { + for (int i=0; i> 16 = spot_light_count + return new Int2(startingIndex, pointLightCounter | (spotLightCounter << 16)); } private static void UpdateClipRegionRoot( @@ -708,20 +708,18 @@ private static void ComputeClipRegion(Vector3 lightPosView, float lightRadius, r // Single linked list of lights (stored in an array) private struct LightClusterLinkedNode : IEquatable { - public readonly InternalLightType LightType; - public readonly int LightIndex; - public readonly int NextNode; + public InternalLightType LightType; + public int LightIndex; - public LightClusterLinkedNode(InternalLightType lightType, int lightIndex, int nextNode) + public LightClusterLinkedNode(InternalLightType lightType, int lightIndex) { LightType = lightType; LightIndex = lightIndex; - NextNode = nextNode; } public bool Equals(LightClusterLinkedNode other) { - return LightType == other.LightType && LightIndex == other.LightIndex && NextNode == other.NextNode; + return LightType == other.LightType && LightIndex == other.LightIndex; } public override bool Equals(object obj) @@ -733,7 +731,7 @@ public override int GetHashCode() { unchecked { - return (int)LightType ^ (LightIndex * 397) ^ (NextNode * 827); + return (int)LightType ^ (LightIndex * 397); } } } From 3eabcdd4ab76913f14f19d67323c3d46d65d312f Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 12 Feb 2020 14:54:58 -0500 Subject: [PATCH 0732/2038] Version bump --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 1a764686ac..9c4a336032 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.2"; + public const string VersionToShowInEditor = "3.5.3"; /// /// The current assembly version as text, currently same as . From 75e1702a3513f15679e9321bac40a21d0452e3be Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 12 Feb 2020 16:32:48 -0500 Subject: [PATCH 0733/2038] Lighting: minor performance tweaks to multithreading system --- .../Lights/LightClusteredPointSpotGroupRenderer.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index 8d0f4bcd3e..cd4b61fc33 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -350,6 +350,8 @@ public void ComputeViewParameter(int viewIndex) var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); + var myNode = new LightClusterLinkedNode(InternalLightType.Point, i - lightRange.Start); + for (int z = tileStartZ; z < tileEndZ; ++z) { // TODO: Additional culling on x/y (to remove corner clusters) @@ -365,7 +367,7 @@ public void ComputeViewParameter(int viewIndex) { for (int x = tileStartX; x < tileEndX; ++x) { - lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(new LightClusterLinkedNode(InternalLightType.Point, i - lightRange.Start)); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(myNode); } } } @@ -420,13 +422,15 @@ public void ComputeViewParameter(int viewIndex) var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); + var myNode = new LightClusterLinkedNode(InternalLightType.Spot, i - lightRange.Start); + for (int z = tileStartZ; z < tileEndZ; ++z) { for (int y = tileStartY; y < tileEndY; ++y) { for (int x = tileStartX; x < tileEndX; ++x) { - lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(new LightClusterLinkedNode(InternalLightType.Spot, i - lightRange.Start)); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(myNode); } } } From 2c2875662d6bd246ff33b71d64165dfd10dd0712 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 12 Feb 2020 19:00:45 -0500 Subject: [PATCH 0734/2038] Lighting: fix for light index --- .../Lights/LightClusteredPointSpotGroupRenderer.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index cd4b61fc33..1bad65e57d 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -323,7 +323,8 @@ public void ComputeViewParameter(int viewIndex) { var light = lights[i].Light; var pointLight = (LightPoint)light.Type; - var pointLightData = renderViewInfos[viewIndex].PointLights[i]; + int lightIndex = i - lightRange.Start; + var pointLightData = renderViewInfos[viewIndex].PointLights[lightIndex]; var radius = LightClusteredPointSpotGroupRenderer.UseLinearLighting ? pointLightData.InvSquareRadius : (float)Math.Sqrt(1.0f / pointLightData.InvSquareRadius); @@ -350,7 +351,7 @@ public void ComputeViewParameter(int viewIndex) var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); - var myNode = new LightClusterLinkedNode(InternalLightType.Point, i - lightRange.Start); + var myNode = new LightClusterLinkedNode(InternalLightType.Point, lightIndex); for (int z = tileStartZ; z < tileEndZ; ++z) { @@ -398,7 +399,8 @@ public void ComputeViewParameter(int viewIndex) { var light = clusteredGroupRenderer.spotGroup.Lights[i].Light; var spotLight = (LightSpot)light.Type; - var spotLightData = renderViewInfos[viewIndex].SpotLights[i]; + int lightIndex = i - lightRange.Start; + var spotLightData = renderViewInfos[viewIndex].SpotLights[lightIndex]; var radius = UseLinearLighting ? spotLightData.AngleOffsetAndInvSquareRadius.Z : (float)Math.Sqrt(1.0f / spotLightData.AngleOffsetAndInvSquareRadius.Z); @@ -422,7 +424,7 @@ public void ComputeViewParameter(int viewIndex) var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); - var myNode = new LightClusterLinkedNode(InternalLightType.Spot, i - lightRange.Start); + var myNode = new LightClusterLinkedNode(InternalLightType.Spot, lightIndex); for (int z = tileStartZ; z < tileEndZ; ++z) { From 20eeaad3c1c3a399242595d52fa3df28081da9dd Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 13 Feb 2020 11:46:32 -0500 Subject: [PATCH 0735/2038] Core: only copy over source items when expanding FastListStruct --- sources/core/Xenko.Core/Collections/FastListStruct.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/core/Xenko.Core/Collections/FastListStruct.cs b/sources/core/Xenko.Core/Collections/FastListStruct.cs index 6027e69dcf..6385431d1b 100644 --- a/sources/core/Xenko.Core/Collections/FastListStruct.cs +++ b/sources/core/Xenko.Core/Collections/FastListStruct.cs @@ -109,7 +109,7 @@ public void Clear() public T[] ToArray() { var destinationArray = new T[Count]; - Array.Copy(Items, 0, destinationArray, 0, Count); + Array.Copy(Items, 0, destinationArray, 0, Items.Length); return destinationArray; } @@ -122,7 +122,7 @@ public void EnsureCapacity(int newCapacity) newSize = newCapacity; var destinationArray = new T[newSize]; - Array.Copy(Items, 0, destinationArray, 0, Count); + Array.Copy(Items, 0, destinationArray, 0, Items.Length); Items = destinationArray; } } From 4c3e657bea7cebfadcaff167b6c905f696310410 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 13 Feb 2020 11:46:55 -0500 Subject: [PATCH 0736/2038] Lighting: more significant performance improvements to clustered light rendering --- .../LightClusteredPointSpotGroupRenderer.cs | 125 +++++++++--------- 1 file changed, 66 insertions(+), 59 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index 1bad65e57d..3f152bad70 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -153,6 +153,12 @@ public override void UpdateShaderPermutationEntry(ForwardLightingRenderFeature.L shaderEntry.DirectLightGroups.Add(spotGroup); } + private enum InternalLightType + { + Point, + Spot, + } + internal class PointLightShaderGroupData : LightShaderGroupDynamic { private readonly LightClusteredPointSpotGroupRenderer clusteredGroupRenderer; @@ -163,7 +169,7 @@ internal class PointLightShaderGroupData : LightShaderGroupDynamic // Artifically increase range of first slice to not waste too much slices in very short area public float SpecialNearPlane = 2.0f; - private List> lightNodes = new List>(); + private List> lightNodes = new List>(); private RenderViewInfo[] renderViewInfos; private Int2 maxClusterCount; //private Plane[] zPlanes; @@ -297,13 +303,15 @@ public void ComputeViewParameter(int viewIndex) // make sure we have enough lists while (lightNodes.Count < totalClusterCount) - lightNodes.Add(new ConcurrentQueue()); + lightNodes.Add(new ConcurrentCollector()); + int totalLights = 0; //---------------- POINT LIGHTS ------------------- var lightRange = lightRanges[viewIndex]; + totalLights += lightRange.End - lightRange.Start; // make point light data - for (int i=lightRange.Start; i(); - for (int i = 0; i < totalClusterCount; ++i) + // setup for a fast indicies calculation (makes for a bigger indicies list, but it is super fast generating it) + int clustersPerThread = 1 + (totalClusterCount / Xenko.Core.Threading.Dispatcher.MaxDegreeOfParallelism); + renderViewInfo.LightIndices.Count = totalClusterCount * totalLights; + renderViewInfo.LightIndices.EnsureCapacity(renderViewInfo.LightIndices.Count); + + Xenko.Core.Threading.Dispatcher.For(0, Xenko.Core.Threading.Dispatcher.MaxDegreeOfParallelism, (thread) => { - renderViewInfo.LightClusters[i] = FinishCluster(grouping, ref renderViewInfo.LightIndices, i); - } + for (int clusterIndex = thread * clustersPerThread; clusterIndex < (thread + 1) * clustersPerThread && clusterIndex < totalClusterCount; clusterIndex++) + { + ref var rvinfo = ref renderViewInfos[viewIndex]; + + if (lightNodes[clusterIndex].Count == 0) + { + rvinfo.LightClusters[clusterIndex] = Int2.Zero; + continue; + } + + lightNodes[clusterIndex].Close(); + + // Build light indices + int pointLightCounter = 0; + int spotLightCounter = 0; + int indexStart = clusterIndex * totalLights; + + for (int i = 0; i < lightNodes[clusterIndex].Count; i++) + { + var cluster = lightNodes[clusterIndex][i]; + + rvinfo.LightIndices[indexStart + i] = cluster.LightIndex; + + switch (cluster.LightType) + { + case InternalLightType.Point: + pointLightCounter++; + break; + case InternalLightType.Spot: + spotLightCounter++; + break; + } + } + + lightNodes[clusterIndex].Clear(true); + + // Add new light cluster range + // Stored in the format: + // x = start_index + // y & 0xFFFF = point_light_count + // y >> 16 = spot_light_count + rvinfo.LightClusters[clusterIndex].X = indexStart; + rvinfo.LightClusters[clusterIndex].Y = pointLightCounter | (spotLightCounter << 16); + } + }); } public unsafe void ComputeViewsParameter(RenderDrawContext drawContext) @@ -603,49 +659,6 @@ public override int GetHashCode() } } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private Int2 FinishCluster(Dictionary grouping, ref FastListStruct lightIndices, int clusterIndex) - { - if (lightNodes[clusterIndex].IsEmpty) return Int2.Zero; - - // Build light indices - int pointLightCounter = 0; - int spotLightCounter = 0; - - IndexPattern ip = new IndexPattern(); - ip.pattern = new List(); - - while (lightNodes[clusterIndex].TryDequeue(out var cluster)) - { - ip.pattern.Add(cluster.LightIndex); - - switch (cluster.LightType) - { - case InternalLightType.Point: - pointLightCounter++; - break; - case InternalLightType.Spot: - spotLightCounter++; - break; - } - } - - if (grouping.TryGetValue(ip, out int startingIndex) == false) - { - for (int i=0; i> 16 = spot_light_count - return new Int2(startingIndex, pointLightCounter | (spotLightCounter << 16)); - } - private static void UpdateClipRegionRoot( float nc, // Tangent plane x/y normal coordinate (view space) float lc, // Light x/y coordinate (view space) @@ -770,11 +783,5 @@ public PointSpotShaderGroupData(RenderContext renderContext) public FastListStruct Lights => lights; } - - private enum InternalLightType - { - Point, - Spot, - } } } From 312622ad64333debd61db052f6cd0fde05f29cfb Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Wed, 12 Feb 2020 19:45:14 +1100 Subject: [PATCH 0737/2038] Fix anisotropic brightness --- .../Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs index 2317fa44a3..aaa2992076 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs @@ -49,5 +49,14 @@ override public void PostProcess(RenderDrawContext drawContext, LightFalloffs Li } base.PostProcess(drawContext, LightFalloff); } + override public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) + { + if (StorageFormat != StorageFormats.RGBA16F) + parameters.Set(BrightnessInvKey, (float)Math.PI / maxBrightness); + else + parameters.Set(BrightnessInvKey, (float)Math.PI); + + storageTex.ApplyVoxelizationParameters(DirectOutput, parameters); + } } } From 2e8ee4cb67e73d2253a147259c6bae6999783728 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 11:52:18 +1100 Subject: [PATCH 0738/2038] Decouple voxel volume size from entity scale --- .../Voxels/Voxelization/VoxelVolumeComponent.cs | 2 ++ .../Voxels/Voxelization/VoxelVolumeProcessor.cs | 6 +----- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs index 5b5b97c30e..d175748da8 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeComponent.cs @@ -47,6 +47,8 @@ public override bool Enabled public List Attributes { get; set; } = new List(); + [DataMember(35)] + public float VoxelVolumeSize { get; set; } = 20f; [DataMember(40)] public float AproximateVoxelSize { get; set; } = 0.15f; [DataMember(50)] diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs index 2616a9c71b..332dba32e1 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/VoxelVolumeProcessor.cs @@ -85,11 +85,7 @@ private void RegenerateVoxelVolumes() processedVoxelVolumes.Add(volume, new ProcessedVoxelVolume()); data.VolumeTranslation = volume.Entity.Transform.WorldMatrix.TranslationVector; - //data.VolumeSize = volume.Entity.Transform.Scale; - //TODO: Get non cube volumes working again - //Temporarily force to cube - float largestSide = Math.Max(volume.Entity.Transform.Scale.X, Math.Max(volume.Entity.Transform.Scale.Y, volume.Entity.Transform.Scale.Z)); - data.VolumeSize = new Vector3(largestSide); + data.VolumeSize = new Vector3(volume.VoxelVolumeSize); data.Voxelize = volume.Voxelize; From a6584da78244eccdbcbbd466a708bd3bc2b67262 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 14:15:57 +1100 Subject: [PATCH 0739/2038] Throw when graphics profile is too low --- .../Voxels/GraphicsCompositor/VoxelRenderer.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs index 8413b16658..f2a048d4f1 100644 --- a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/VoxelRenderer.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Text; @@ -46,6 +46,11 @@ public virtual void Collect(RenderContext Context, Shadows.IShadowMapRenderer Sh if (renderVoxelVolumes == null || renderVoxelVolumes.Count == 0) return; + if (Context.RenderSystem.GraphicsDevice.Features.CurrentProfile < GraphicsProfile.Level_11_0) + { + throw new ArgumentOutOfRangeException("Graphics Profile Level 11 or higher required for Voxelization."); + } + //Setup per volume passes and texture allocations foreach ( var pair in renderVoxelVolumes ) { @@ -193,6 +198,9 @@ public virtual void Draw(RenderDrawContext drawContext, Shadows.IShadowMapRender if (renderVoxelVolumes == null || renderVoxelVolumes.Count == 0) return; + if (drawContext.GraphicsDevice.Features.CurrentProfile < GraphicsProfile.Level_11_0) + return; + var context = drawContext; using (drawContext.PushRenderTargetsAndRestore()) From 12d4a43b9ebf96e63b4c81f97026eee9494c84a0 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 15:09:53 +1100 Subject: [PATCH 0740/2038] Fix anisotropic brightness - change where --- .../Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs index aaa2992076..aba1a4be96 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Voxelization/Layout/VoxelLayoutAnisotropic.cs @@ -49,14 +49,14 @@ override public void PostProcess(RenderDrawContext drawContext, LightFalloffs Li } base.PostProcess(drawContext, LightFalloff); } - override public void ApplyVoxelizationParameters(ParameterCollection parameters, List modifiers) + override public void ApplySamplingParameters(VoxelViewContext viewContext, ParameterCollection parameters) { if (StorageFormat != StorageFormats.RGBA16F) - parameters.Set(BrightnessInvKey, (float)Math.PI / maxBrightness); + parameters.Set(BrightnessKey, maxBrightness * (float)Math.PI); else - parameters.Set(BrightnessInvKey, (float)Math.PI); + parameters.Set(BrightnessKey, (float)Math.PI); - storageTex.ApplyVoxelizationParameters(DirectOutput, parameters); + storageTex.ApplySamplingParameters(viewContext, parameters); } } } From e8d06853f9e181163023cc3f3f0274569093efc9 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 15:10:31 +1100 Subject: [PATCH 0741/2038] Make LightVoxelRenderer ignore unprocessed volumes --- .../engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs index 0d7edb63c5..412386553b 100644 --- a/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs +++ b/sources/engine/Xenko.Voxels/Voxels/Light/LightVoxelRenderer.cs @@ -178,12 +178,15 @@ public override void ApplyViewParameters(RenderDrawContext context, int viewInde if (lightVoxel.Volume == null) return; + ProcessedVoxelVolume processedVolume = GetProcessedVolume(); + if (processedVolume == null) + return; var intensity = Light.Intensity; var intensityBounceScale = lightVoxel.BounceIntensityScale; var specularIntensity = lightVoxel.SpecularIntensityScale * intensity; - VoxelViewContext viewContext = new VoxelViewContext(GetProcessedVolume().passList, viewIndex); + VoxelViewContext viewContext = new VoxelViewContext(processedVolume.passList, viewIndex); if (viewContext.IsVoxelView) { intensity *= intensityBounceScale / 3.141592f; From 26e2502b3feba88721b7a78687ae60d5d5c8d1b2 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 15:13:08 +1100 Subject: [PATCH 0742/2038] Include Voxels in Editor dependencies --- sources/editor/Xenko.Editor/Xenko.Editor.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/sources/editor/Xenko.Editor/Xenko.Editor.csproj b/sources/editor/Xenko.Editor/Xenko.Editor.csproj index c6084e2dd8..e93b147778 100644 --- a/sources/editor/Xenko.Editor/Xenko.Editor.csproj +++ b/sources/editor/Xenko.Editor/Xenko.Editor.csproj @@ -35,6 +35,7 @@ + From b794aecbec69bd96ca7a326f153a8d334877b310 Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 15:13:22 +1100 Subject: [PATCH 0743/2038] Add voxel volume gizmo --- .../AssetEditors/Gizmos/VoxelVolumeGizmo.cs | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/VoxelVolumeGizmo.cs diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/VoxelVolumeGizmo.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/VoxelVolumeGizmo.cs new file mode 100644 index 0000000000..b8f5ab9c58 --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/VoxelVolumeGizmo.cs @@ -0,0 +1,150 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using Xenko.Core; +using Xenko.Core.Mathematics; +using Xenko.Engine; +using Xenko.Graphics; +using Xenko.Rendering; +using Xenko.Rendering.Lights; +using Xenko.Rendering.Voxels; +using Buffer = Xenko.Graphics.Buffer; + +namespace Xenko.Assets.Presentation.AssetEditors.Gizmos +{ + /// + /// A gizmo to display the bounding boxes for voxel volumes inside the editor as a gizmo. + /// this gizmo uses volume scale as the extent of the bounding box and is not affected by rotation + /// + [GizmoComponent(typeof(VoxelVolumeComponent), false)] + public class VoxelVolumeGizmo : EntityGizmo + { + private BoxMesh box; + private Material material; + private Entity debugRootEntity; + private Entity debugEntity; + + public VoxelVolumeGizmo(EntityComponent component) : base(component) + { + } + + protected override Entity Create() + { + debugRootEntity = new Entity($"Voxel volume of {Component.Entity.Name}"); + + material = GizmoUniformColorMaterial.Create(GraphicsDevice, Color.CornflowerBlue); + + box = new BoxMesh(GraphicsDevice); + box.Build(); + + debugEntity = new Entity($"Voxel volume mesh of {Component.Entity.Name}") + { + new ModelComponent + { + Model = new Model + { + material, + new Mesh { Draw = box.MeshDraw }, + }, + RenderGroup = RenderGroup, + } + }; + + return debugRootEntity; + } + + public override void Update() + { + if (ContentEntity == null || GizmoRootEntity == null) + return; + + // calculate the world matrix of the gizmo so that it is positioned exactly as the corresponding scene entity + // except the scale that is re-adjusted to the gizmo desired size (gizmo are insert at scene root so LocalMatrix = WorldMatrix) + Vector3 scale; + Quaternion rotation; + Vector3 translation; + ContentEntity.Transform.WorldMatrix.Decompose(out scale, out rotation, out translation); + + // Translation and Scale but no rotation on bounding boxes + GizmoRootEntity.Transform.Position = translation; + GizmoRootEntity.Transform.Scale = new Vector3(Component.VoxelVolumeSize * 0.5f); + GizmoRootEntity.Transform.UpdateWorldMatrix(); + } + + public override bool IsSelected + { + set + { + bool hasChanged = IsSelected != value; + base.IsSelected = value; + + if (hasChanged) + { + if (IsSelected) + GizmoRootEntity.AddChild(debugEntity); + else + GizmoRootEntity.RemoveChild(debugEntity); + } + } + } + + class BoxMesh + { + public MeshDraw MeshDraw; + + private Buffer vertexBuffer; + + private readonly GraphicsDevice graphicsDevice; + + public BoxMesh(GraphicsDevice graphicsDevice) + { + this.graphicsDevice = graphicsDevice; + } + + public void Build() + { + var indices = new int[12 * 2]; + var vertices = new VertexPositionNormalTexture[8]; + + vertices[0] = new VertexPositionNormalTexture(new Vector3(-1, 1, -1), Vector3.UnitY, Vector2.Zero); + vertices[1] = new VertexPositionNormalTexture(new Vector3(-1, 1, 1), Vector3.UnitY, Vector2.Zero); + vertices[2] = new VertexPositionNormalTexture(new Vector3(1, 1, 1), Vector3.UnitY, Vector2.Zero); + vertices[3] = new VertexPositionNormalTexture(new Vector3(1, 1, -1), Vector3.UnitY, Vector2.Zero); + + int indexOffset = 0; + // Top sides + for (int i = 0; i < 4; i++) + { + indices[indexOffset++] = i; + indices[indexOffset++] = (i + 1) % 4; + } + + // Duplicate vertices and indices to bottom part + for (int i = 0; i < 4; i++) + { + vertices[i + 4] = vertices[i]; + vertices[i + 4].Position.Y = -vertices[i + 4].Position.Y; + + indices[indexOffset++] = indices[i * 2] + 4; + indices[indexOffset++] = indices[i * 2 + 1] + 4; + } + + // Sides + for (int i = 0; i < 4; i++) + { + indices[indexOffset++] = i; + indices[indexOffset++] = i + 4; + } + + vertexBuffer = Buffer.Vertex.New(graphicsDevice, vertices); + MeshDraw = new MeshDraw + { + PrimitiveType = PrimitiveType.LineList, + DrawCount = indices.Length, + IndexBuffer = new IndexBufferBinding(Buffer.Index.New(graphicsDevice, indices), true, indices.Length), + VertexBuffers = new[] { new VertexBufferBinding(vertexBuffer, VertexPositionNormalTexture.Layout, vertexBuffer.ElementCount) }, + }; + } + } + } +} From 2d738b0e45bb9f5300ab16ec4654473c169ae1dd Mon Sep 17 00:00:00 2001 From: WhyPenguins Date: Thu, 13 Feb 2020 15:33:11 +1100 Subject: [PATCH 0744/2038] Fix RenderViews not collecting after graphics compositor reset. --- sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs b/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs index 4c60bf01aa..a12a935c50 100644 --- a/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs +++ b/sources/engine/Xenko.Rendering/Rendering/VisibilityGroup.cs @@ -92,7 +92,7 @@ public void Reset() public void TryCollect(RenderView view) { // Already colleted this frame? - if (view.LastFrameCollected >= RenderSystem.FrameCounter) + if (view.LastFrameCollected == RenderSystem.FrameCounter) return; view.LastFrameCollected = RenderSystem.FrameCounter; From 5fe902ad3187b1d24f4f6fe50817eaf231f2cd5b Mon Sep 17 00:00:00 2001 From: Anon Date: Thu, 13 Feb 2020 21:40:07 -0600 Subject: [PATCH 0745/2038] Add additional comment on datagridex # Conflicts: # sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs --- .../editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs index 7b3f26f8f2..b800174215 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs @@ -15,6 +15,14 @@ namespace Xenko.Core.Assets.Editor.View { + /// + /// Xenko generic wpf data grid. Left empty for future development on a generic datagrid. + /// + public class DataGridEx : DataGrid + { + + } + /// /// This class wraps the class, making accessible all members that are required to make the feature work. /// is massively internal, making this feature impossible to implement by default on custom controls. From c77d7f9961bf1996559f5aa1f1160a66af04b562 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 14 Feb 2020 10:45:07 -0500 Subject: [PATCH 0746/2038] Physics: fix rare crash when getting buffer pools --- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 13b882cb1f..cfc6b3662b 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -72,7 +72,7 @@ public static BufferPool safeBufferPool if (threadStaticPool == null) { threadStaticPool = new BufferPool(); - allBufferPools.Add(threadStaticPool); + allBufferPools.Enqueue(threadStaticPool); } return threadStaticPool; } @@ -80,7 +80,7 @@ public static BufferPool safeBufferPool private PoseIntegratorCallbacks poseCallbacks; - private static List allBufferPools = new List(); + private static ConcurrentQueue allBufferPools = new ConcurrentQueue(); internal int clearRequested; private BepuSimpleThreadDispatcher threadDispatcher = new BepuSimpleThreadDispatcher(); @@ -116,8 +116,8 @@ public void Clear(bool clearBuffers = true, bool forceRightNow = false) if (clearBuffers) { - for (int i = 0; i < allBufferPools.Count; i++) - allBufferPools[i].Clear(); + while(allBufferPools.TryDequeue(out var pool)) + pool.Clear(); } for (int i = 0; i < AllRigidbodies.Count; i++) From 74ce18cafd5fc821e4d5af5fa7c0b63672e26107 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 14 Feb 2020 10:46:26 -0500 Subject: [PATCH 0747/2038] UI: Multithreading work in progress (currently doesn't work when mixing fullscreen and 3D UI) --- .../Thumbnails/ThumbnailGenerator.cs | 2 +- sources/engine/Xenko.Graphics/BatchBase.cs | 3 + sources/engine/Xenko.Graphics/UIBatch.cs | 7 +- .../Renderers/DefaultBorderRenderer.cs | 31 +++---- .../Renderers/DefaultButtonRenderer.cs | 5 +- .../DefaultContentDecoratorRenderer.cs | 5 +- .../Renderers/DefaultEditTextRenderer.cs | 10 +-- .../Renderers/DefaultImageRenderer.cs | 5 +- .../Renderers/DefaultModalElementRenderer.cs | 4 +- .../Renderers/DefaultScrollBarRenderer.cs | 5 +- .../Renderers/DefaultScrollingTextRenderer.cs | 4 +- .../Renderers/DefaultSliderRenderer.cs | 4 +- .../Renderers/DefaultTextBlockRenderer.cs | 4 +- .../Renderers/DefaultToggleButtonRenderer.cs | 4 +- .../Xenko.UI/Renderers/ElementRenderer.cs | 10 +-- .../Rendering/UI/UIRenderFeature.Picking.cs | 35 +++----- .../Xenko.UI/Rendering/UI/UIRenderFeature.cs | 90 ++++++++----------- sources/engine/Xenko.UI/UISystem.cs | 5 -- 18 files changed, 103 insertions(+), 130 deletions(-) diff --git a/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs b/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs index 8d7074bd25..d9ceeee1c9 100644 --- a/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs +++ b/sources/editor/Xenko.Editor/Thumbnails/ThumbnailGenerator.cs @@ -153,7 +153,7 @@ public ThumbnailGenerator(EffectCompilerBase effectCompiler) // create utility members nullGameTime = new GameTime(); SpriteBatch = new SpriteBatch(GraphicsDevice); - UIBatch = new UIBatch(GraphicsDevice); + UIBatch = new UIBatch(GraphicsDevice, null, null); // create the pipeline SetUpPipeline(); diff --git a/sources/engine/Xenko.Graphics/BatchBase.cs b/sources/engine/Xenko.Graphics/BatchBase.cs index c0537607c6..b6f7e0db2a 100644 --- a/sources/engine/Xenko.Graphics/BatchBase.cs +++ b/sources/engine/Xenko.Graphics/BatchBase.cs @@ -405,6 +405,8 @@ private void DrawBatchPerTexture(Texture texture, ElementInfo[] sprites, int off DrawBatchPerTextureAndPass(sprites, offset, count); } + private object batchLocker = new object(); + private void DrawBatchPerTextureAndPass(ElementInfo[] sprites, int offset, int count) { while (count > 0) @@ -487,6 +489,7 @@ private void DrawBatchPerTextureAndPass(ElementInfo[] sprites, int offset, int c // resourceContext.VertexBuffer.SetData(GraphicsDevice, new DataPointer(x64TempBuffer.DataPointer, batchSize * VerticesPerSprite * Utilities.SizeOf()), offsetInBytes, noOverwrite); //} //else + lock (batchLocker) { var mappedIndices = new MappedResource(); var mappedVertices = GraphicsContext.CommandList.MapSubresource(ResourceContext.VertexBuffer, 0, MapMode.WriteNoOverwrite, false, offsetVertexInBytes, vertexCount * vertexStructSize); diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index 64cf6d725e..536a4a849c 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -37,6 +37,8 @@ public class UIBatch : BatchBase private Vector4 vector4LeftTop = new Vector4(-0.5f, -0.5f, -0.5f, 1); + public object renderingContext, layoutingContext; + private readonly Vector4[] shiftVectorX = new Vector4[4]; private readonly Vector4[] shiftVectorY = new Vector4[4]; @@ -141,7 +143,7 @@ static UIBatch() /// Initializes a new instance of the class. /// /// A valid instance of . - public UIBatch(GraphicsDevice device) + public UIBatch(GraphicsDevice device, object context, object layout) : base(device, UIEffect.Bytecode, UIEffect.BytecodeSRgb, ResourceBufferInfo.CreateDynamicIndexBufferInfo("UIBatch.VertexIndexBuffers", MaxIndicesCount, MaxVerticesCount), VertexPositionColorTextureSwizzle.Layout) @@ -149,6 +151,9 @@ public UIBatch(GraphicsDevice device) // Create a 1x1 pixel white texture whiteTexture = graphicsDevice.GetSharedWhiteTexture(); + renderingContext = context; + layoutingContext = layout; + // Load custom font rendering effects here // For signed distance field font rendering diff --git a/sources/engine/Xenko.UI/Renderers/DefaultBorderRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultBorderRenderer.cs index f32790466d..e8b4183fa9 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultBorderRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultBorderRenderer.cs @@ -4,6 +4,7 @@ using Xenko.Core; using Xenko.Core.Mathematics; +using Xenko.Graphics; using Xenko.UI.Controls; namespace Xenko.UI.Renderers @@ -18,9 +19,9 @@ public DefaultBorderRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); Vector3 offsets; Vector3 borderSize; @@ -40,22 +41,22 @@ public override void RenderColor(UIElement element, UIRenderingContext context) // left/front offsets = new Vector3(-elementHalfSize.X + elementHalfBorders.Left, 0, -elementHalfSize.Z + elementHalfBorders.Front); borderSize = new Vector3(borderThickness.Left, elementSize.Y, borderThickness.Front); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // right/front offsets = new Vector3(elementHalfSize.X - elementHalfBorders.Right, 0, -elementHalfSize.Z + elementHalfBorders.Front); borderSize = new Vector3(borderThickness.Right, elementSize.Y, borderThickness.Front); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // top/front offsets = new Vector3(0, -elementHalfSize.Y + elementHalfBorders.Top, -elementHalfSize.Z + elementHalfBorders.Front); borderSize = new Vector3(elementSize.X, borderThickness.Top, borderThickness.Front); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // bottom/front offsets = new Vector3(0, elementHalfSize.Y - elementHalfBorders.Bottom, -elementHalfSize.Z + elementHalfBorders.Front); borderSize = new Vector3(elementSize.X, borderThickness.Bottom, borderThickness.Back); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // if the element is 3D draw the extra borders if (element.ActualDepth > MathUtil.ZeroTolerance) @@ -63,46 +64,46 @@ public override void RenderColor(UIElement element, UIRenderingContext context) // left/back offsets = new Vector3(-elementHalfSize.X + elementHalfBorders.Left, 0, elementHalfSize.Z - elementHalfBorders.Back); borderSize = new Vector3(borderThickness.Left, elementSize.Y, borderThickness.Back); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // right/back offsets = new Vector3(elementHalfSize.X - elementHalfBorders.Right, 0, elementHalfSize.Z - elementHalfBorders.Back); borderSize = new Vector3(borderThickness.Right, elementSize.Y, borderThickness.Back); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // top/back offsets = new Vector3(0, -elementHalfSize.Y + elementHalfBorders.Top, elementHalfSize.Z - elementHalfBorders.Back); borderSize = new Vector3(elementSize.X, borderThickness.Top, borderThickness.Back); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // bottom/back offsets = new Vector3(0, elementHalfSize.Y - elementHalfBorders.Bottom, elementHalfSize.Z - elementHalfBorders.Back); borderSize = new Vector3(elementSize.X, borderThickness.Bottom, borderThickness.Back); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // left/top offsets = new Vector3(-elementHalfSize.X + elementHalfBorders.Left, -elementHalfSize.Y + elementHalfBorders.Top, 0); borderSize = new Vector3(borderThickness.Left, borderThickness.Top, elementSize.Z); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // right/top offsets = new Vector3(elementHalfSize.X - elementHalfBorders.Right, -elementHalfSize.Y + elementHalfBorders.Top, 0); borderSize = new Vector3(borderThickness.Right, borderThickness.Top, elementSize.Z); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // left/bottom offsets = new Vector3(-elementHalfSize.X + elementHalfBorders.Left, elementHalfSize.Y - elementHalfBorders.Bottom, 0); borderSize = new Vector3(borderThickness.Left, borderThickness.Bottom, elementSize.Z); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); // right/bottom offsets = new Vector3(elementHalfSize.X - elementHalfBorders.Right, elementHalfSize.Y - elementHalfBorders.Bottom, 0); borderSize = new Vector3(borderThickness.Right, borderThickness.Bottom, elementSize.Z); - DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context); + DrawBorder(border, ref offsets, ref borderSize, ref borderColor, context, Batch); } } - private void DrawBorder(Border border, ref Vector3 offsets, ref Vector3 borderSize, ref Color borderColor, UIRenderingContext context) + private void DrawBorder(Border border, ref Vector3 offsets, ref Vector3 borderSize, ref Color borderColor, UIRenderingContext context, UIBatch Batch) { var worldMatrix = border.WorldMatrixInternal; worldMatrix.M41 += worldMatrix.M11 * offsets.X + worldMatrix.M21 * offsets.Y + worldMatrix.M31 * offsets.Z; diff --git a/sources/engine/Xenko.UI/Renderers/DefaultButtonRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultButtonRenderer.cs index 76c402ee1f..858a2f67b9 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultButtonRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultButtonRenderer.cs @@ -3,6 +3,7 @@ using Xenko.Core; using Xenko.Core.Mathematics; +using Xenko.Graphics; using Xenko.UI.Controls; namespace Xenko.UI.Renderers @@ -17,9 +18,9 @@ public DefaultButtonRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var button = (Button)element; var sprite = button.ButtonImage; diff --git a/sources/engine/Xenko.UI/Renderers/DefaultContentDecoratorRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultContentDecoratorRenderer.cs index 1c9c274624..0b6fd57d8b 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultContentDecoratorRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultContentDecoratorRenderer.cs @@ -3,6 +3,7 @@ using Xenko.Core; using Xenko.Core.Mathematics; +using Xenko.Graphics; using Xenko.UI.Controls; namespace Xenko.UI.Renderers @@ -17,9 +18,9 @@ public DefaultContentDecoratorRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var decorator = (ContentDecorator)element; var sprite = decorator.BackgroundImage?.GetSprite(); diff --git a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs index 94ff3c853e..eccb99b1db 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs @@ -20,7 +20,7 @@ public DefaultEditTextRenderer(IServiceRegistry services) { } - private void RenderSelection(EditText editText, UIRenderingContext context, int start, int length, Color color, out float offsetTextStart, out float offsetAlignment, out float selectionSize) + private void RenderSelection(EditText editText, UIRenderingContext context, int start, int length, Color color, out float offsetTextStart, out float offsetAlignment, out float selectionSize, UIBatch Batch) { // calculate the size of the text region by removing padding var textRegionSize = new Vector2(editText.ActualWidth - editText.Padding.Left - editText.Padding.Right, @@ -69,9 +69,9 @@ private void RenderSelection(EditText editText, UIRenderingContext context, int Batch.DrawRectangle(ref selectionWorldMatrix, ref selectionScaleVector, ref color, context.DepthBias + 1); } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var editText = (EditText)element; @@ -104,13 +104,13 @@ public override void RenderColor(UIElement element, UIRenderingContext context) if (editText.Composition.Length > 0) { var imeSelectionColor = editText.RenderOpacity * editText.IMESelectionColor; - RenderSelection(editText, context, editText.SelectionStart, editText.Composition.Length, imeSelectionColor, out offsetTextStart, out offsetAlignment, out selectionSize); + RenderSelection(editText, context, editText.SelectionStart, editText.Composition.Length, imeSelectionColor, out offsetTextStart, out offsetAlignment, out selectionSize, Batch); } // Draw the regular selection else if (editText.IsSelectionActive) { var selectionColor = editText.RenderOpacity * editText.SelectionColor; - RenderSelection(editText, context, editText.SelectionStart, editText.SelectionLength, selectionColor, out offsetTextStart, out offsetAlignment, out selectionSize); + RenderSelection(editText, context, editText.SelectionStart, editText.SelectionLength, selectionColor, out offsetTextStart, out offsetAlignment, out selectionSize, Batch); } // create the text draw command diff --git a/sources/engine/Xenko.UI/Renderers/DefaultImageRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultImageRenderer.cs index d333f265db..d0d15b285d 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultImageRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultImageRenderer.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using Xenko.Core; +using Xenko.Graphics; using Xenko.UI.Controls; namespace Xenko.UI.Renderers @@ -16,9 +17,9 @@ public DefaultImageRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var image = (ImageElement)element; var sprite = image.Source?.GetSprite(); diff --git a/sources/engine/Xenko.UI/Renderers/DefaultModalElementRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultModalElementRenderer.cs index da3a371110..0bd39c49b5 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultModalElementRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultModalElementRenderer.cs @@ -22,7 +22,7 @@ public DefaultModalElementRenderer(IServiceRegistry services) noStencilNoDepth = new DepthStencilStateDescription(false, false); } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { var modalElement = (ModalElement)element; @@ -39,7 +39,7 @@ public override void RenderColor(UIElement element, UIRenderingContext context) context.DepthBias += 1; - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); } protected override void Destroy() diff --git a/sources/engine/Xenko.UI/Renderers/DefaultScrollBarRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultScrollBarRenderer.cs index c9a1ccd331..beee3e986c 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultScrollBarRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultScrollBarRenderer.cs @@ -3,6 +3,7 @@ using System; using Xenko.Core; +using Xenko.Graphics; using Xenko.UI.Controls; namespace Xenko.UI.Renderers @@ -17,9 +18,9 @@ public DefaultScrollBarRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var bar = (ScrollBar)element; diff --git a/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs index 99164dd357..3b5519b9de 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs @@ -20,9 +20,9 @@ public DefaultScrollingTextRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var scrollingText = (ScrollingText)element; diff --git a/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs index 8f7b64b8c1..9732792289 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultSliderRenderer.cs @@ -19,9 +19,9 @@ public DefaultSliderRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var slider = (Slider)element; if (slider.Orientation == Orientation.InDepth) diff --git a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs index 94676fa7fa..d31a8b9adb 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs @@ -18,9 +18,9 @@ public DefaultTextBlockRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var textBlock = (TextBlock)element; diff --git a/sources/engine/Xenko.UI/Renderers/DefaultToggleButtonRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultToggleButtonRenderer.cs index 303e721285..713548a02f 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultToggleButtonRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultToggleButtonRenderer.cs @@ -20,9 +20,9 @@ public DefaultToggleButtonRenderer(IServiceRegistry services) { } - public override void RenderColor(UIElement element, UIRenderingContext context) + public override void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { - base.RenderColor(element, context); + base.RenderColor(element, context, Batch); var toggleButton = (ToggleButton)element; var sprite = GetToggleStateImage(toggleButton); diff --git a/sources/engine/Xenko.UI/Renderers/ElementRenderer.cs b/sources/engine/Xenko.UI/Renderers/ElementRenderer.cs index 0d6b8164d5..5529dee4e7 100644 --- a/sources/engine/Xenko.UI/Renderers/ElementRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/ElementRenderer.cs @@ -1,6 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; using Xenko.Core; using Xenko.Core.Mathematics; using Xenko.Core.Serialization.Contents; @@ -30,11 +31,6 @@ public class ElementRenderer : ComponentBase /// public GraphicsDevice GraphicsDevice => GraphicsDeviceService?.GraphicsDevice; - /// - /// Gets a reference to the UI image drawer. - /// - public UIBatch Batch => UI.Batch; - /// /// A depth stencil state that keep the stencil value in any cases. /// @@ -76,7 +72,7 @@ public ElementRenderer(IServiceRegistry services) /// The rendering context containing information how to draw the element. /// The render target, the depth stencil buffer and the depth stencil state are already correctly set when entering this function. /// If the user wants to perform some intermediate rendering, it is his responsibility to bind them back correctly before the final rendering. - public virtual void RenderColor(UIElement element, UIRenderingContext context) + public virtual void RenderColor(UIElement element, UIRenderingContext context, UIBatch Batch) { var backgroundColor = element.RenderOpacity * element.BackgroundColor; @@ -101,7 +97,7 @@ public virtual void RenderColor(UIElement element, UIRenderingContext context) /// The rendering context containing information how to draw the element. /// The render target, the depth stencil buffer and the depth stencil state are already correctly set when entering this function. /// If the user wants to perform some intermediate rendering, it is his responsibility to bind them back correctly before the final rendering. - public virtual void RenderClipping(UIElement element, UIRenderingContext context) + public virtual void RenderClipping(UIElement element, UIRenderingContext context, UIBatch Batch) { // Default implementation: render an back-face cube Batch.DrawBackground(ref element.WorldMatrixInternal, ref element.RenderSizeInternal, ref blackColor, context.DepthBias); diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs index da4190e033..852715a506 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs @@ -17,9 +17,7 @@ public partial class UIRenderFeature // object to avoid allocation at each element leave event private readonly HashSet newlySelectedElementParents = new HashSet(); - private readonly List compactedPointerEvents = new List(); - - partial void PickingUpdate(RenderUIElement renderUIElement, Viewport viewport, ref Matrix worldViewProj, GameTime drawTime) + partial void PickingUpdate(RenderUIElement renderUIElement, Viewport viewport, ref Matrix worldViewProj, GameTime drawTime, List events) { if (renderUIElement.Page?.RootElement == null) return; @@ -29,24 +27,13 @@ partial void PickingUpdate(RenderUIElement renderUIElement, Viewport viewport, r if (UpdateMouseOver(ref viewport, ref inverseZViewProj, renderUIElement, drawTime)) { - UpdateTouchEvents(ref viewport, ref inverseZViewProj, renderUIElement, drawTime); + UpdateTouchEvents(ref viewport, ref inverseZViewProj, renderUIElement, drawTime, events); } } - partial void PickingClear() - { - // clear the list of compacted pointer events of time frame - ClearPointerEvents(); - } - - partial void PickingPrepare() + partial void PickingPrepare(List compactedPointerEvents) { // compact all the pointer events that happened since last frame to avoid performing useless hit tests. - CompactPointerEvents(); - } - - private void CompactPointerEvents() - { if (input == null) // no input for thumbnails return; @@ -72,11 +59,8 @@ private void CompactPointerEvents() compactedPointerEvents.Add(compactedMoveEvent); } } - } - private void ClearPointerEvents() - { - compactedPointerEvents.Clear(); + return; } /// @@ -196,15 +180,17 @@ private void MakeTouchEvent(UIElement currentTouchedElement, UIElement lastTouch } } - private void UpdateTouchEvents(ref Viewport viewport, ref Matrix worldViewProj, RenderUIElement state, GameTime gameTime) + private void UpdateTouchEvents(ref Viewport viewport, ref Matrix worldViewProj, RenderUIElement state, GameTime gameTime, List compactedPointerEvents) { var rootElement = state.Page.RootElement; var intersectionPoint = Vector3.Zero; var lastTouchPosition = new Vector2(float.NegativeInfinity); // analyze pointer event input and trigger UI touch events depending on hit Tests - foreach (var pointerEvent in compactedPointerEvents) + for (int i=0; i /// If a pointer is pointed at an UIElement, it will be set here /// - public UIElement UIElementUnderMouseCursor { get; private set; } + [ThreadStatic] + private static UIElement UIElementUnderMouseCursor; private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, RenderUIElement state, GameTime time) { @@ -359,7 +346,7 @@ private UIElement FindCommonParent(UIElement element1, UIElement element2) // find the common element into the previously and newly selected element hierarchy var commonElement = element2; - while (commonElement != null && !newlySelectedElementParents.Contains(commonElement)) + while (commonElement != null && !(newlySelectedElementParents.Count > 0 && newlySelectedElementParents.Contains(commonElement))) commonElement = commonElement.VisualParent; return commonElement; diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs index 350763f65f..e45c273d7a 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using System.Collections.Concurrent; using System.Collections.Generic; using Xenko.Core; using Xenko.Core.Diagnostics; @@ -24,15 +25,7 @@ public partial class UIRenderFeature : RootRenderFeature private RendererManager rendererManager; - private readonly UIRenderingContext renderingContext = new UIRenderingContext(); - - private UIBatch batch; - - private readonly object drawLock = new object(); - - private readonly LayoutingContext layoutingContext = new LayoutingContext(); - - private readonly List uiElementStates = new List(); + private static ConcurrentQueue batches = new ConcurrentQueue(); public override Type SupportedRenderObjectType => typeof(RenderUIElement); @@ -55,24 +48,17 @@ protected override void InitializeCore() } rendererManager = new RendererManager(new DefaultRenderersFactory(RenderSystem.Services)); - - batch = uiSystem.Batch; } - partial void PickingPrepare(); - - partial void PickingUpdate(RenderUIElement renderUIElement, Viewport viewport, ref Matrix worldViewProj, GameTime drawTime); + partial void PickingPrepare(List compactedPointerEvents); - partial void PickingClear(); + partial void PickingUpdate(RenderUIElement renderUIElement, Viewport viewport, ref Matrix worldViewProj, GameTime drawTime, List compactedPointerEvents); public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { - lock (drawLock) + using (context.PushRenderTargetsAndRestore()) { - using (context.PushRenderTargetsAndRestore()) - { - DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); - } + DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); } } @@ -80,13 +66,19 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend { base.Draw(context, renderView, renderViewStage, startIndex, endIndex); + if (batches.TryDequeue(out UIBatch batch) == false) + batch = new UIBatch(context.GraphicsDevice, new UIRenderingContext(), new LayoutingContext()); + + var renderingContext = batch.renderingContext as UIRenderingContext; + var layoutingContext = batch.layoutingContext as LayoutingContext; + var uiProcessor = SceneInstance.GetCurrent(context.RenderContext).GetProcessor(); if (uiProcessor == null) return; // build the list of the UI elements to render - uiElementStates.Clear(); + List uiElementStates = new List(); for (var index = startIndex; index < endIndex; index++) { var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; @@ -105,24 +97,14 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend renderingContext.RenderTarget = context.CommandList.RenderTargets[0]; // TODO: avoid hardcoded index 0 // Prepare content required for Picking and MouseOver events - PickingPrepare(); - - // allocate temporary graphics resources if needed - Texture scopedDepthBuffer = null; - foreach (var uiElement in uiElementStates) - { - if (uiElement.RenderObject.IsFullScreen) - { - var renderTarget = renderingContext.RenderTarget; - var description = TextureDescription.New2D(renderTarget.Width, renderTarget.Height, PixelFormat.D24_UNorm_S8_UInt, TextureFlags.DepthStencil); - scopedDepthBuffer = context.RenderContext.Allocator.GetTemporaryTexture(description); - break; - } - } + List events = new List(); + PickingPrepare(events); // update view parameters and perform UI picking - foreach (var uiElementState in uiElementStates) + for (int j = 0; j < uiElementStates.Count; j++) { + var uiElementState = uiElementStates[j]; + var renderObject = uiElementState.RenderObject; var rootElement = renderObject.Page?.RootElement; if (rootElement == null) @@ -155,17 +137,18 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend // Check if the current UI component is being picked based on the current ViewParameters (used to draw this element) using (Profiler.Begin(UIProfilerKeys.TouchEventsUpdate)) { - PickingUpdate(uiElementState.RenderObject, context.CommandList.Viewport, ref uiElementState.WorldViewProjectionMatrix, drawTime); + PickingUpdate(uiElementState.RenderObject, context.CommandList.Viewport, ref uiElementState.WorldViewProjectionMatrix, drawTime, events); } } // render the UI elements of all the entities - foreach (var uiElementState in uiElementStates) + for(int j=0; j public class UISystem : GameSystemBase { - internal UIBatch Batch { get; private set; } - internal DepthStencilStateDescription KeepStencilValueState { get; private set; } internal DepthStencilStateDescription IncreaseStencilValueState { get; private set; } @@ -65,9 +63,6 @@ protected override void LoadContent() { base.LoadContent(); - // create effect and geometric primitives - Batch = new UIBatch(GraphicsDevice); - // create depth stencil states var depthStencilDescription = new DepthStencilStateDescription(true, false) { From ef00226004571eb2097196bf9a15d8c6f1b25639 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Fri, 14 Feb 2020 15:16:54 +0900 Subject: [PATCH 0748/2038] Merge pull request #512 from CharlesWoodhill/master [UI/INPUT] bugfix & commenting UIRenderFeature.UIElementUnderMouseCursor # Conflicts: # sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs # sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs --- .../Xenko.Core.AssemblyProcessor.Packed.exe | 3 +++ .../Xenko.UI/Rendering/UI/UIRenderFeature.cs | 15 +++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed.exe diff --git a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed.exe b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed.exe new file mode 100644 index 0000000000..5ccb1f868b --- /dev/null +++ b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed.exe @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d823c469184eadc6a6dbc322104e6c75ec290b48d704135811a184b4df1de5b +size 688128 diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs index e45c273d7a..85a3e9dd89 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs @@ -29,6 +29,13 @@ public partial class UIRenderFeature : RootRenderFeature public override Type SupportedRenderObjectType => typeof(RenderUIElement); + /// + /// Represents the UI-element thats currently under the mouse cursor. + /// Only elements with CanBeHitByUser == true are taken into account. + /// Last processed element_state / ?UIComponent? with a valid element will be used. + /// + public UIElement UIElementUnderMouseCursor { get; private set; } + protected override void InitializeCore() { base.InitializeCore(); @@ -100,6 +107,10 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend List events = new List(); PickingPrepare(events); + // see UIElementUnderMouseCursor property + UIElement elementUnderMouseCursor = null; + + // update view parameters and perform UI picking for (int j = 0; j < uiElementStates.Count; j++) { @@ -110,6 +121,8 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend if (rootElement == null) continue; + UIElement loopedElementUnderMouseCursor = null; + // calculate the size of the virtual resolution depending on target size (UI canvas) var virtualResolution = renderObject.Resolution; @@ -134,12 +147,14 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend ref renderView.View, ref renderView.Projection, cameraComponent.Entity.Transform.WorldPosition()); } + // Check if the current UI component is being picked based on the current ViewParameters (used to draw this element) using (Profiler.Begin(UIProfilerKeys.TouchEventsUpdate)) { PickingUpdate(uiElementState.RenderObject, context.CommandList.Viewport, ref uiElementState.WorldViewProjectionMatrix, drawTime, events); } } + UIElementUnderMouseCursor = elementUnderMouseCursor; // render the UI elements of all the entities for(int j=0; j Date: Fri, 14 Feb 2020 18:18:24 +0900 Subject: [PATCH 0749/2038] Merge pull request #601 from makotech222/XceedDatagrid --- .../Views/FixAssetReferencesWindow.xaml | 53 +- .../Resources/Common.Resources.xaml | 278 +-- .../ExpressionDark.normalcolor.Resources.xaml | 28 +- ...w.ExpressionDark.normalcolor.Graphics.xaml | 13 +- .../TableViewScrollViewer.generic.xaml | 171 -- ...leflowView.ExpressionDark.normalcolor.xaml | 2040 +---------------- .../TableflowView.GridElementTemplates.xaml | 1466 +----------- .../Themes/generic.xaml | 96 +- .../View/AssetViewUserControl.xaml | 76 - .../View/AssetViewUserControl.xaml.cs | 11 +- .../DragDrop/XceedDataGridDragDropBehavior.cs | 22 - ...edDataGridBindableSelectedItemsBehavior.cs | 38 - .../XceedDataGridResizableColumnsBehavior.cs | 114 - ...DataGridThumbnailPrioritizationBehavior.cs | 44 - .../View/CommonResources.xaml | 13 + .../View/Controls/GridLogViewer.cs | 269 +-- .../View/DataGridEx.cs | 76 - .../Xenko.Core.Assets.Editor.csproj | 5 +- .../Xenko.GameStudio/GameStudioWindow.xaml | 1 - 19 files changed, 109 insertions(+), 4705 deletions(-) delete mode 100644 sources/editor/Xenko.Core.Assets.Editor/Themes/ExpressionDark/TableViewScrollViewer.generic.xaml delete mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs delete mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs delete mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs delete mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs diff --git a/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml b/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml index 81a4def3b1..476d5d5c76 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml @@ -4,10 +4,9 @@ xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:xk="http://schemas.xenko.com/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" + xmlns:view="clr-namespace:Xenko.Core.Assets.Editor.View" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:valueConverters="clr-namespace:Xenko.Core.Assets.Editor.View.ValueConverters" - xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid" - xmlns:behaviors="clr-namespace:Xenko.Core.Assets.Editor.View.Behaviors" xmlns:far="clr-namespace:Xenko.Core.Assets.Editor.Components.FixAssetReferences" mc:Ignorable="d" ShowInTaskbar="False" @@ -45,37 +44,33 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs b/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs index 8e11238e97..130c2c2f0d 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs @@ -5,13 +5,12 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Input; - +using Xceed.Wpf.Toolkit.Core; using Xenko.Core.Assets.Editor.View.Controls; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Presentation.Collections; using Xenko.Core.Presentation.Extensions; -using Xceed.Wpf.DataGrid; namespace Xenko.Core.Assets.Editor.View { @@ -126,8 +125,6 @@ public AssetViewUserControl() { InitializeComponent(); - Loaded += (s, e) => AddHandler(Row.EditBeginningEvent, (CancelRoutedEventHandler)CanBeginEditEvent); - Unloaded += (s, e) => RemoveHandler(Row.EditBeginningEvent, (CancelRoutedEventHandler)CanBeginEditEvent); } /// @@ -215,7 +212,7 @@ public void BeginEdit() var listBox = AssetViewPresenter.FindVisualChildOfType(); listBox?.BeginEdit(); - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); gridView?.BeginEdit(); } @@ -231,7 +228,7 @@ private void ZoomIn() } } - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); if (gridView != null) { GridThumbnailSize += ThumbnailZoomIncrement; @@ -254,7 +251,7 @@ private void ZoomOut() } } - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); if (gridView != null) { GridThumbnailSize -= ThumbnailZoomIncrement; diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs deleted file mode 100644 index 6d58dc1e52..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Collections.Generic; -using System.Linq; -using Xenko.Core.Extensions; -using Xceed.Wpf.DataGrid; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - public class XceedDataGridDragDropBehavior : DragDropBehavior - { - protected override IEnumerable GetItemsToDrag(DataRow container) - { - if (container != null) - { - var sourceItem = container.DataContext; - return AssociatedObject.SelectedItems.Contains(sourceItem) ? AssociatedObject.SelectedItems.Cast() : sourceItem.ToEnumerable(); - } - return Enumerable.Empty(); - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs deleted file mode 100644 index 49344c751a..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using Xenko.Core.Presentation.Behaviors; - -using Xceed.Wpf.DataGrid; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - public class XceedDataGridBindableSelectedItemsBehavior : BindableSelectedItemsBehavior - { - protected override void OnAttached() - { - SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems; - AssociatedObject.SelectionChanged += XceedDataGridSelectionChanged; - base.OnAttached(); - } - - protected override void OnDetaching() - { - base.OnDetaching(); - AssociatedObject.SelectionChanged -= XceedDataGridSelectionChanged; - SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems; - } - - protected override void ScrollIntoView(object dataItem) - { - AssociatedObject.BringItemIntoView(dataItem); - } - - private void XceedDataGridSelectionChanged(object sender, DataGridSelectionChangedEventArgs e) - { - foreach (var selectionInfo in e.SelectionInfos) - { - ControlSelectionChanged(selectionInfo.AddedItems, selectionInfo.RemovedItems); - } - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs deleted file mode 100644 index 625e8fb398..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; -using System.Linq; -using System.Windows; -using System.Windows.Controls; - -using Xenko.Core.Extensions; -using Xenko.Core.Presentation.Behaviors; -using Xenko.Core.Presentation.Extensions; - -using Xceed.Wpf.DataGrid; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - /// - /// This behavior allows to have resizable columns in a while being able to define default widths using star notation. - /// It also prevent the columns do be resized below the viewport width - /// - public class XceedDataGridResizableColumnsBehavior : DeferredBehaviorBase - { - private ScrollContentPresenter scrollContentPresenter; - private bool updatingColumns; - private bool itemsSourceChanged; - private bool initialized; - - protected override void OnAttachedAndLoaded() - { - base.OnAttachedAndLoaded(); - - AssociatedObject.Columns.ForEach(x => x.Width = x.ActualWidth); - - scrollContentPresenter = AssociatedObject.FindVisualChildOfType(); - - // This occurs when closing a session - it is harmless to ignore it in this case - if (scrollContentPresenter == null) - return; - - AssociatedObject.ItemsSourceChangeCompleted += ItemsSourceChanged; - AssociatedObject.LayoutUpdated += LayoutUpdated; - AssociatedObject.SizeChanged += SizeChanged; - itemsSourceChanged = true; - // Prevent the selection of the first item - AssociatedObject.SelectedItems.Clear(); - initialized = true; - } - - protected override void OnDetachingAndUnloaded() - { - if (initialized) - { - var columnManagerRow = AssociatedObject.FindVisualChildOfType(); - if (columnManagerRow != null) - { - var cells = columnManagerRow.FindVisualChildrenOfType(); - cells.ForEach(x => x.SizeChanged -= ColumnSizeChanged); - AssociatedObject.SizeChanged -= SizeChanged; - } - } - base.OnDetachingAndUnloaded(); - } - - private void ItemsSourceChanged(object sender, EventArgs e) - { - // cells update is defered to after the next layout update - itemsSourceChanged = true; - // Prevent the selection of the first item - AssociatedObject.SelectedItems.Clear(); - } - - private void LayoutUpdated(object sender, EventArgs e) - { - if (itemsSourceChanged) - { - var columnManagerRow = AssociatedObject.FindVisualChildOfType(); - if (columnManagerRow != null) - { - var cells = columnManagerRow.FindVisualChildrenOfType(); - cells.ForEach(x => x.SizeChanged += ColumnSizeChanged); - } - itemsSourceChanged = false; - } - } - - private void ColumnSizeChanged(object sender, SizeChangedEventArgs e) - { - if (updatingColumns) - return; - - updatingColumns = true; - - double total = AssociatedObject.Columns.Sum(x => x.ActualWidth); - if (total < scrollContentPresenter.ActualWidth) - { - foreach (var column in AssociatedObject.Columns) - { - column.Width = column.ActualWidth * scrollContentPresenter.ActualWidth / total; - } - } - - updatingColumns = false; - } - - private void SizeChanged(object sender, SizeChangedEventArgs e) - { - double total = AssociatedObject.Columns.Sum(x => x.ActualWidth); - var offset = e.NewSize.Width - e.PreviousSize.Width; - foreach (var column in AssociatedObject.Columns) - { - column.Width = column.ActualWidth * (total + offset) / total; - } - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs deleted file mode 100644 index 1febb52b4a..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Linq; -using System.Windows.Controls; - -using Xenko.Core.Assets.Editor.ViewModel; -using Xenko.Core.Extensions; -using Xenko.Core.Presentation.Behaviors; -using Xenko.Core.Presentation.Extensions; - -using Xceed.Wpf.DataGrid; -using Xceed.Wpf.DataGrid.Views; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - public class XceedDataGridThumbnailPrioritizationBehavior : DeferredBehaviorBase - { - private TableViewScrollViewer scrollViewer; - - protected override void OnAttachedAndLoaded() - { - scrollViewer = AssociatedObject.FindVisualChildOfType(); - scrollViewer.ScrollChanged += ScrollChanged; - base.OnAttachedAndLoaded(); - } - - protected override void OnDetachingAndUnloaded() - { - scrollViewer.ScrollChanged -= ScrollChanged; - scrollViewer = null; - base.OnDetachingAndUnloaded(); - } - - private void ScrollChanged(object sender, ScrollChangedEventArgs e) - { - var session = AssociatedObject.ItemsSource?.Cast().FirstOrDefault()?.Session; - if (session == null) - return; - - var visibleAssets = AssociatedObject.FindVisualChildrenOfType().NotNull().Select(x => x.DataContext).OfType().Where(x => x != null); - session.Thumbnails.IncreaseThumbnailPriority(visibleAssets); - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml index 36141887c3..e701157a21 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml @@ -14,6 +14,19 @@ + + + + + diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs index a1e8c6a66c..bb84569c76 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Controls; @@ -12,36 +13,20 @@ using Xenko.Core.Assets.Diagnostics; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Diagnostics; - -using Xceed.Wpf.DataGrid; +using Xenko.Core.Presentation.Collections; namespace Xenko.Core.Assets.Editor.View.Controls { /// /// This control displays a collection of in a grid. /// - [TemplatePart(Name = "PART_LogGridView", Type = typeof(DataGridControl))] - [TemplatePart(Name = "PART_PreviousResult", Type = typeof(ButtonBase))] - [TemplatePart(Name = "PART_NextResult", Type = typeof(ButtonBase))] - [TemplatePart(Name = "PART_GridLogViewerCollectionSourceContainer", Type = typeof(FrameworkElement))] + [TemplatePart(Name = "PART_LogGridView", Type = typeof(DataGridEx))] public class GridLogViewer : Control { - private int currentResult; - /// /// The used to display log messages. /// - private DataGridControl logGridView; - - /// - /// The used to navigate to the previous search result. - /// - private ButtonBase previousResultButton; - - /// - /// The used to navigate to the next search result. - /// - private ButtonBase nextResultButton; + private DataGridEx logGridView; static GridLogViewer() { @@ -51,38 +36,13 @@ static GridLogViewer() /// /// Identifies the dependency property. /// - public static readonly DependencyProperty LogMessagesProperty = DependencyProperty.Register("LogMessages", typeof(ICollection), typeof(GridLogViewer), new PropertyMetadata(null)); + public static readonly DependencyProperty LogMessagesProperty = DependencyProperty.Register("LogMessages", typeof(ObservableList), typeof(GridLogViewer), new PropertyMetadata(null)); /// /// Identifies the dependency property. /// public static readonly DependencyProperty IsToolBarVisibleProperty = DependencyProperty.Register("IsToolBarVisible", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty CanFilterLogProperty = DependencyProperty.Register("CanFilterLog", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty CanSearchLogProperty = DependencyProperty.Register("CanSearchLog", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty SearchTokenProperty = DependencyProperty.Register("SearchToken", typeof(string), typeof(GridLogViewer), new PropertyMetadata("", SearchTokenChanged)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty SearchMatchCaseProperty = DependencyProperty.Register("SearchMatchCase", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(false, SearchTokenChanged)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty SearchMatchWordProperty = DependencyProperty.Register("SearchMatchWord", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(false, SearchTokenChanged)); - /// /// Identifies the dependency property. /// @@ -126,38 +86,15 @@ static GridLogViewer() /// /// Gets or sets the collection of to display. /// - public ICollection LogMessages { get { return (ICollection)GetValue(LogMessagesProperty); } set { SetValue(LogMessagesProperty, value); } } + public ObservableList LogMessages { get { return (ObservableList)GetValue(LogMessagesProperty); } set { SetValue(LogMessagesProperty, value); } } + + public ObservableList FilteredLogMessages { get; set; } = new ObservableList(); /// /// Gets or sets whether the tool bar should be visible. /// public bool IsToolBarVisible { get { return (bool)GetValue(IsToolBarVisibleProperty); } set { SetValue(IsToolBarVisibleProperty, value); } } - /// - /// Gets or sets whether it is possible to filter the log text. - /// - public bool CanFilterLog { get { return (bool)GetValue(CanFilterLogProperty); } set { SetValue(CanFilterLogProperty, value); } } - - /// - /// Gets or sets whether it is possible to search the log text. - /// - public bool CanSearchLog { get { return (bool)GetValue(CanSearchLogProperty); } set { SetValue(CanSearchLogProperty, value); } } - - /// - /// Gets or sets the current search token. - /// - public string SearchToken { get { return (string)GetValue(SearchTokenProperty); } set { SetValue(SearchTokenProperty, value); } } - - /// - /// Gets or sets whether the search result should match the case. - /// - public bool SearchMatchCase { get { return (bool)GetValue(SearchMatchCaseProperty); } set { SetValue(SearchMatchCaseProperty, value); } } - - /// - /// Gets or sets whether the search result should match whole words only. - /// - public bool SearchMatchWord { get { return (bool)GetValue(SearchMatchWordProperty); } set { SetValue(SearchMatchWordProperty, value); } } - /// /// Gets or sets whether the log viewer should display debug messages. /// @@ -203,35 +140,11 @@ public override void OnApplyTemplate() { base.OnApplyTemplate(); - logGridView = GetTemplateChild("PART_LogGridView") as DataGridControl; + logGridView = GetTemplateChild("PART_LogGridView") as DataGridEx; if (logGridView == null) throw new InvalidOperationException("A part named 'PART_LogGridView' must be present in the ControlTemplate, and must be of type 'DataGridControl'."); - previousResultButton = GetTemplateChild("PART_PreviousResult") as ButtonBase; - if (previousResultButton == null) - throw new InvalidOperationException("A part named 'PART_PreviousResult' must be present in the ControlTemplate, and must be of type 'ButtonBase'."); - - nextResultButton = GetTemplateChild("PART_NextResult") as ButtonBase; - if (nextResultButton == null) - throw new InvalidOperationException("A part named 'PART_NextResult' must be present in the ControlTemplate, and must be of type 'ButtonBase'."); - - var sourceContainer = GetTemplateChild("PART_GridLogViewerCollectionSourceContainer") as FrameworkElement; - if (sourceContainer == null) - throw new InvalidOperationException("A part named 'PART_GridLogViewerCollectionSourceContainer' must be present in the ControlTemplate, and must be of type 'FrameworkElement'."); - - var source = sourceContainer.Resources["GridLogViewerCollectionSource"]; - if (!(source is DataGridCollectionViewSourceBase)) - throw new InvalidOperationException("The 'PART_GridLogViewerCollectionSourceContainer' must be contain a 'GridLogViewerCollectionSource' resource that is the source of the collection view for the DataGridControl."); - - ((DataGridCollectionViewSourceBase)source).Filter += FilterHandler; logGridView.MouseDoubleClick += GridMouseDoubleClick; - previousResultButton.Click += PreviousResultClicked; - nextResultButton.Click += NextResultClicked; - } - - private void FilterHandler(object value, FilterEventArgs e) - { - e.Accepted = FilterMethod(e.Item); } private void GridMouseDoubleClick(object sender, MouseButtonEventArgs e) @@ -254,173 +167,27 @@ private void GridMouseDoubleClick(object sender, MouseButtonEventArgs e) if (asset != null) Session.ActiveAssetView.SelectAssetCommand.Execute(asset); } - } - private void SelectFirstOccurrence() - { - currentResult = 0; - var token = SearchToken; - if (!string.IsNullOrEmpty(token)) - { - var message = LogMessages.FirstOrDefault(Match); - logGridView.SelectedItem = message; - if (message != null) - { - logGridView.BringItemIntoView(message); - } - } } - - private void SelectPreviousOccurrence() - { - var token = SearchToken; - if (!string.IsNullOrEmpty(token)) - { - var message = FindPreviousMessage(); - logGridView.SelectedItem = message; - if (message != null) - { - logGridView.BringItemIntoView(message); - } - else - logGridView.SelectedItem = null; - } - } - - private void SelectNextOccurrence() - { - var token = SearchToken; - if (!string.IsNullOrEmpty(token)) - { - var message = FindNextMessage(); - logGridView.SelectedItem = message; - if (message != null) - { - logGridView.BringItemIntoView(message); - } - } - } - - private ILogMessage FindPreviousMessage() - { - int count = 0; - ILogMessage lastMessage = null; - --currentResult; - foreach (var message in LogMessages.Where(Match)) - { - lastMessage = message; - - if (count == currentResult) - { - return message; - } - ++count; - } - currentResult = Math.Max(0, count - 1); - return lastMessage; - } - - private ILogMessage FindNextMessage() - { - int count = 0; - ILogMessage firstMessage = null; - ++currentResult; - foreach (var message in LogMessages.Where(Match)) - { - if (firstMessage == null) - firstMessage = message; - - if (count == currentResult) - { - return message; - } - ++count; - } - currentResult = 0; - return firstMessage; - } - - private bool Match(ILogMessage message) - { - if (Match(message.Text)) - return true; - - var assetMessage = message as AssetSerializableLogMessage; - return assetMessage != null && Match(assetMessage.AssetUrl.FullPath); - } - - private bool Match(string text) - { - var token = SearchToken; - var stringComparison = SearchMatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; - int index = text.IndexOf(token, stringComparison); - if (index < 0) - return false; - - if (SearchMatchWord && text.Length > 1) - { - if (index > 0) - { - char c = text[index - 1]; - if (char.IsLetterOrDigit(c)) - return false; - } - if (index + token.Length < text.Length) - { - char c = text[index + token.Length]; - if (char.IsLetterOrDigit(c)) - return false; - } - } - return true; - } - private static void FilterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var logViewer = (GridLogViewer)d; logViewer.ApplyFilters(); } - /// - /// Raised when the property is changed. - /// - private static void SearchTokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - var logViewer = (GridLogViewer)d; - logViewer.SelectFirstOccurrence(); - } - - private void PreviousResultClicked(object sender, RoutedEventArgs e) - { - SelectPreviousOccurrence(); - } - - private void NextResultClicked(object sender, RoutedEventArgs e) - { - SelectNextOccurrence(); - } - + private void ApplyFilters() { if (logGridView == null || logGridView.ItemsSource == null) return; - - if (!(logGridView.ItemsSource is DataGridCollectionView)) - throw new InvalidOperationException("The item source of the part 'PART_LogGridView' must be a 'DataGridCollectionView'."); - - var view = (DataGridCollectionView)logGridView.ItemsSource; - view.Refresh(); - } - - private bool FilterMethod(object msg) - { - var message = (ILogMessage)msg; - return (ShowDebugMessages && message.Type == LogMessageType.Debug) - || (ShowVerboseMessages && message.Type == LogMessageType.Verbose) - || (ShowInfoMessages && message.Type == LogMessageType.Info) - || (ShowWarningMessages && message.Type == LogMessageType.Warning) - || (ShowErrorMessages && message.Type == LogMessageType.Error) - || (ShowFatalMessages && message.Type == LogMessageType.Fatal); + this.FilteredLogMessages.Clear(); + this.FilteredLogMessages.AddRange(this.LogMessages.Where(x => + x.IsDebug() && ShowDebugMessages || + x.IsError() && ShowErrorMessages || + x.IsFatal() && ShowFatalMessages || + x.IsInfo() && ShowInfoMessages || + x.IsVerbose() && ShowVerboseMessages || + x.IsWarning() && ShowWarningMessages)); } } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs index b800174215..3ba586eb5e 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs @@ -11,8 +11,6 @@ using Xenko.Core.Extensions; using Xenko.Core.Presentation.Extensions; -using Xceed.Wpf.DataGrid; - namespace Xenko.Core.Assets.Editor.View { /// @@ -103,14 +101,6 @@ public static string GetPrimaryTextPath(ItemsControl itemsControl) } - public static int FindMatchingPrefix(DataGridEx dataGridEx, string primaryTextPath, string prefix, string nextChar, int startItemIndex, bool lookForFallbackMatchToo, ref bool wasNewCharUsed) - { - var parameters = new object[] { dataGridEx, primaryTextPath, prefix, nextChar, startItemIndex, lookForFallbackMatchToo, wasNewCharUsed }; - var result = (int)FindMatchingPrefixMethod.Invoke(null, parameters); - wasNewCharUsed = (bool)parameters[6]; - return result; - } - public void AddCharToPrefix(string nextChar) { AddCharToPrefixMethod.Invoke(textSearch, new object[] { nextChar }); @@ -121,70 +111,4 @@ public void ResetTimeout() ResetTimeoutMethod.Invoke(textSearch, new object[] { }); } } - - /// - /// An implementation of DataGrid class that inherits from Xceed DataGridControl and add support for . - /// - public class DataGridEx : DataGridControl - { - /// - protected override void OnTextInput(TextCompositionEventArgs e) - { - base.OnTextInput(e); - if (string.IsNullOrEmpty(e.Text) || !IsTextSearchEnabled || !Equals(e.Source, this) && !Equals(ItemsControlFromItemContainer(e.Source as DependencyObject), this)) - return; - - var textSearch = TextSearchWrapper.EnsureInstance(this); - if (textSearch == null) - return; - - DoSearch(textSearch, e.Text); - e.Handled = true; - } - - /// - /// This method reimplements DoSearch from . - /// - /// - /// - private void DoSearch(TextSearchWrapper textSearch, string nextChar) - { - bool lookForFallbackMatchToo = false; - int startItemIndex = 0; - ItemCollection items = Items; - if (textSearch.IsActive) - startItemIndex = textSearch.MatchedItemIndex; - if (textSearch._charsEntered.Count > 0 && string.Compare(textSearch._charsEntered[textSearch._charsEntered.Count - 1], nextChar, true, TextSearchWrapper.GetCulture(this)) == 0) - lookForFallbackMatchToo = true; - string primaryTextPath = TextSearchWrapper.GetPrimaryTextPath(this); - bool wasNewCharUsed = false; - int matchingPrefix = TextSearchWrapper.FindMatchingPrefix(this, primaryTextPath, textSearch.Prefix, nextChar, startItemIndex, lookForFallbackMatchToo, ref wasNewCharUsed); - if (matchingPrefix != -1) - { - if (!textSearch.IsActive || matchingPrefix != startItemIndex) - { - if (SelectedItem != items[matchingPrefix]) - { - SelectedItem = items[matchingPrefix]; - BringItemIntoView(SelectedItem); - UpdateLayout(); - var container = GetContainerFromItem(SelectedItem) as DataRow; - if (container != null) - { - var cellToFocus = container.FindVisualChildrenOfType().FirstOrDefault(x => x.Focusable); - if (cellToFocus != null) - Keyboard.Focus(cellToFocus); - } - } - textSearch.MatchedItemIndex = matchingPrefix; - } - if (wasNewCharUsed) - textSearch.AddCharToPrefix(nextChar); - if (!textSearch.IsActive) - textSearch.IsActive = true; - } - if (textSearch.IsActive) - textSearch.ResetTimeout(); - } - } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj index 69c6238a5d..9a4ff5dafb 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj +++ b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj @@ -1,4 +1,4 @@ - + @@ -10,7 +10,7 @@ - + @@ -82,7 +82,6 @@ - diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index ad1a639c84..dac78a4298 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -21,7 +21,6 @@ - From 8e36f0de5e42c04b3f16b460c28b3fe66c6564fe Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 14 Feb 2020 10:54:22 -0500 Subject: [PATCH 0750/2038] Revert "Merge pull request #601 from makotech222/XceedDatagrid" This reverts commit 97ee42fe3627dd874641ab9a8564dab22a965222. --- .../Views/FixAssetReferencesWindow.xaml | 53 +- .../Resources/Common.Resources.xaml | 278 ++- .../ExpressionDark.normalcolor.Resources.xaml | 28 +- ...w.ExpressionDark.normalcolor.Graphics.xaml | 13 +- .../TableViewScrollViewer.generic.xaml | 171 ++ ...leflowView.ExpressionDark.normalcolor.xaml | 2040 ++++++++++++++++- .../TableflowView.GridElementTemplates.xaml | 1466 +++++++++++- .../Themes/generic.xaml | 96 +- .../View/AssetViewUserControl.xaml | 76 + .../View/AssetViewUserControl.xaml.cs | 11 +- .../DragDrop/XceedDataGridDragDropBehavior.cs | 22 + ...edDataGridBindableSelectedItemsBehavior.cs | 38 + .../XceedDataGridResizableColumnsBehavior.cs | 114 + ...DataGridThumbnailPrioritizationBehavior.cs | 44 + .../View/CommonResources.xaml | 13 - .../View/Controls/GridLogViewer.cs | 269 ++- .../View/DataGridEx.cs | 76 + .../Xenko.Core.Assets.Editor.csproj | 5 +- .../Xenko.GameStudio/GameStudioWindow.xaml | 1 + 19 files changed, 4705 insertions(+), 109 deletions(-) create mode 100644 sources/editor/Xenko.Core.Assets.Editor/Themes/ExpressionDark/TableViewScrollViewer.generic.xaml create mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs create mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs create mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs create mode 100644 sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs diff --git a/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml b/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml index 476d5d5c76..81a4def3b1 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/Components/FixAssetReferences/Views/FixAssetReferencesWindow.xaml @@ -4,9 +4,10 @@ xmlns:i="http://schemas.microsoft.com/xaml/behaviors" xmlns:xk="http://schemas.xenko.com/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - xmlns:view="clr-namespace:Xenko.Core.Assets.Editor.View" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:valueConverters="clr-namespace:Xenko.Core.Assets.Editor.View.ValueConverters" + xmlns:xcdg="http://schemas.xceed.com/wpf/xaml/datagrid" + xmlns:behaviors="clr-namespace:Xenko.Core.Assets.Editor.View.Behaviors" xmlns:far="clr-namespace:Xenko.Core.Assets.Editor.Components.FixAssetReferences" mc:Ignorable="d" ShowInTaskbar="False" @@ -44,33 +45,37 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs b/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs index 130c2c2f0d..8e11238e97 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs @@ -5,12 +5,13 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Input; -using Xceed.Wpf.Toolkit.Core; + using Xenko.Core.Assets.Editor.View.Controls; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Presentation.Collections; using Xenko.Core.Presentation.Extensions; +using Xceed.Wpf.DataGrid; namespace Xenko.Core.Assets.Editor.View { @@ -125,6 +126,8 @@ public AssetViewUserControl() { InitializeComponent(); + Loaded += (s, e) => AddHandler(Row.EditBeginningEvent, (CancelRoutedEventHandler)CanBeginEditEvent); + Unloaded += (s, e) => RemoveHandler(Row.EditBeginningEvent, (CancelRoutedEventHandler)CanBeginEditEvent); } /// @@ -212,7 +215,7 @@ public void BeginEdit() var listBox = AssetViewPresenter.FindVisualChildOfType(); listBox?.BeginEdit(); - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); gridView?.BeginEdit(); } @@ -228,7 +231,7 @@ private void ZoomIn() } } - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); if (gridView != null) { GridThumbnailSize += ThumbnailZoomIncrement; @@ -251,7 +254,7 @@ private void ZoomOut() } } - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); if (gridView != null) { GridThumbnailSize -= ThumbnailZoomIncrement; diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs new file mode 100644 index 0000000000..6d58dc1e52 --- /dev/null +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs @@ -0,0 +1,22 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Collections.Generic; +using System.Linq; +using Xenko.Core.Extensions; +using Xceed.Wpf.DataGrid; + +namespace Xenko.Core.Assets.Editor.View.Behaviors +{ + public class XceedDataGridDragDropBehavior : DragDropBehavior + { + protected override IEnumerable GetItemsToDrag(DataRow container) + { + if (container != null) + { + var sourceItem = container.DataContext; + return AssociatedObject.SelectedItems.Contains(sourceItem) ? AssociatedObject.SelectedItems.Cast() : sourceItem.ToEnumerable(); + } + return Enumerable.Empty(); + } + } +} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs new file mode 100644 index 0000000000..49344c751a --- /dev/null +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs @@ -0,0 +1,38 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using Xenko.Core.Presentation.Behaviors; + +using Xceed.Wpf.DataGrid; + +namespace Xenko.Core.Assets.Editor.View.Behaviors +{ + public class XceedDataGridBindableSelectedItemsBehavior : BindableSelectedItemsBehavior + { + protected override void OnAttached() + { + SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems; + AssociatedObject.SelectionChanged += XceedDataGridSelectionChanged; + base.OnAttached(); + } + + protected override void OnDetaching() + { + base.OnDetaching(); + AssociatedObject.SelectionChanged -= XceedDataGridSelectionChanged; + SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems; + } + + protected override void ScrollIntoView(object dataItem) + { + AssociatedObject.BringItemIntoView(dataItem); + } + + private void XceedDataGridSelectionChanged(object sender, DataGridSelectionChangedEventArgs e) + { + foreach (var selectionInfo in e.SelectionInfos) + { + ControlSelectionChanged(selectionInfo.AddedItems, selectionInfo.RemovedItems); + } + } + } +} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs new file mode 100644 index 0000000000..625e8fb398 --- /dev/null +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs @@ -0,0 +1,114 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System; +using System.Linq; +using System.Windows; +using System.Windows.Controls; + +using Xenko.Core.Extensions; +using Xenko.Core.Presentation.Behaviors; +using Xenko.Core.Presentation.Extensions; + +using Xceed.Wpf.DataGrid; + +namespace Xenko.Core.Assets.Editor.View.Behaviors +{ + /// + /// This behavior allows to have resizable columns in a while being able to define default widths using star notation. + /// It also prevent the columns do be resized below the viewport width + /// + public class XceedDataGridResizableColumnsBehavior : DeferredBehaviorBase + { + private ScrollContentPresenter scrollContentPresenter; + private bool updatingColumns; + private bool itemsSourceChanged; + private bool initialized; + + protected override void OnAttachedAndLoaded() + { + base.OnAttachedAndLoaded(); + + AssociatedObject.Columns.ForEach(x => x.Width = x.ActualWidth); + + scrollContentPresenter = AssociatedObject.FindVisualChildOfType(); + + // This occurs when closing a session - it is harmless to ignore it in this case + if (scrollContentPresenter == null) + return; + + AssociatedObject.ItemsSourceChangeCompleted += ItemsSourceChanged; + AssociatedObject.LayoutUpdated += LayoutUpdated; + AssociatedObject.SizeChanged += SizeChanged; + itemsSourceChanged = true; + // Prevent the selection of the first item + AssociatedObject.SelectedItems.Clear(); + initialized = true; + } + + protected override void OnDetachingAndUnloaded() + { + if (initialized) + { + var columnManagerRow = AssociatedObject.FindVisualChildOfType(); + if (columnManagerRow != null) + { + var cells = columnManagerRow.FindVisualChildrenOfType(); + cells.ForEach(x => x.SizeChanged -= ColumnSizeChanged); + AssociatedObject.SizeChanged -= SizeChanged; + } + } + base.OnDetachingAndUnloaded(); + } + + private void ItemsSourceChanged(object sender, EventArgs e) + { + // cells update is defered to after the next layout update + itemsSourceChanged = true; + // Prevent the selection of the first item + AssociatedObject.SelectedItems.Clear(); + } + + private void LayoutUpdated(object sender, EventArgs e) + { + if (itemsSourceChanged) + { + var columnManagerRow = AssociatedObject.FindVisualChildOfType(); + if (columnManagerRow != null) + { + var cells = columnManagerRow.FindVisualChildrenOfType(); + cells.ForEach(x => x.SizeChanged += ColumnSizeChanged); + } + itemsSourceChanged = false; + } + } + + private void ColumnSizeChanged(object sender, SizeChangedEventArgs e) + { + if (updatingColumns) + return; + + updatingColumns = true; + + double total = AssociatedObject.Columns.Sum(x => x.ActualWidth); + if (total < scrollContentPresenter.ActualWidth) + { + foreach (var column in AssociatedObject.Columns) + { + column.Width = column.ActualWidth * scrollContentPresenter.ActualWidth / total; + } + } + + updatingColumns = false; + } + + private void SizeChanged(object sender, SizeChangedEventArgs e) + { + double total = AssociatedObject.Columns.Sum(x => x.ActualWidth); + var offset = e.NewSize.Width - e.PreviousSize.Width; + foreach (var column in AssociatedObject.Columns) + { + column.Width = column.ActualWidth * (total + offset) / total; + } + } + } +} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs new file mode 100644 index 0000000000..1febb52b4a --- /dev/null +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs @@ -0,0 +1,44 @@ +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. +using System.Linq; +using System.Windows.Controls; + +using Xenko.Core.Assets.Editor.ViewModel; +using Xenko.Core.Extensions; +using Xenko.Core.Presentation.Behaviors; +using Xenko.Core.Presentation.Extensions; + +using Xceed.Wpf.DataGrid; +using Xceed.Wpf.DataGrid.Views; + +namespace Xenko.Core.Assets.Editor.View.Behaviors +{ + public class XceedDataGridThumbnailPrioritizationBehavior : DeferredBehaviorBase + { + private TableViewScrollViewer scrollViewer; + + protected override void OnAttachedAndLoaded() + { + scrollViewer = AssociatedObject.FindVisualChildOfType(); + scrollViewer.ScrollChanged += ScrollChanged; + base.OnAttachedAndLoaded(); + } + + protected override void OnDetachingAndUnloaded() + { + scrollViewer.ScrollChanged -= ScrollChanged; + scrollViewer = null; + base.OnDetachingAndUnloaded(); + } + + private void ScrollChanged(object sender, ScrollChangedEventArgs e) + { + var session = AssociatedObject.ItemsSource?.Cast().FirstOrDefault()?.Session; + if (session == null) + return; + + var visibleAssets = AssociatedObject.FindVisualChildrenOfType().NotNull().Select(x => x.DataContext).OfType().Where(x => x != null); + session.Thumbnails.IncreaseThumbnailPriority(visibleAssets); + } + } +} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml index e701157a21..36141887c3 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml @@ -14,19 +14,6 @@ - - - - - diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs index bb84569c76..a1e8c6a66c 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs @@ -2,7 +2,6 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Controls; @@ -13,20 +12,36 @@ using Xenko.Core.Assets.Diagnostics; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Diagnostics; -using Xenko.Core.Presentation.Collections; + +using Xceed.Wpf.DataGrid; namespace Xenko.Core.Assets.Editor.View.Controls { /// /// This control displays a collection of in a grid. /// - [TemplatePart(Name = "PART_LogGridView", Type = typeof(DataGridEx))] + [TemplatePart(Name = "PART_LogGridView", Type = typeof(DataGridControl))] + [TemplatePart(Name = "PART_PreviousResult", Type = typeof(ButtonBase))] + [TemplatePart(Name = "PART_NextResult", Type = typeof(ButtonBase))] + [TemplatePart(Name = "PART_GridLogViewerCollectionSourceContainer", Type = typeof(FrameworkElement))] public class GridLogViewer : Control { + private int currentResult; + /// /// The used to display log messages. /// - private DataGridEx logGridView; + private DataGridControl logGridView; + + /// + /// The used to navigate to the previous search result. + /// + private ButtonBase previousResultButton; + + /// + /// The used to navigate to the next search result. + /// + private ButtonBase nextResultButton; static GridLogViewer() { @@ -36,13 +51,38 @@ static GridLogViewer() /// /// Identifies the dependency property. /// - public static readonly DependencyProperty LogMessagesProperty = DependencyProperty.Register("LogMessages", typeof(ObservableList), typeof(GridLogViewer), new PropertyMetadata(null)); + public static readonly DependencyProperty LogMessagesProperty = DependencyProperty.Register("LogMessages", typeof(ICollection), typeof(GridLogViewer), new PropertyMetadata(null)); /// /// Identifies the dependency property. /// public static readonly DependencyProperty IsToolBarVisibleProperty = DependencyProperty.Register("IsToolBarVisible", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty CanFilterLogProperty = DependencyProperty.Register("CanFilterLog", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty CanSearchLogProperty = DependencyProperty.Register("CanSearchLog", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty SearchTokenProperty = DependencyProperty.Register("SearchToken", typeof(string), typeof(GridLogViewer), new PropertyMetadata("", SearchTokenChanged)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty SearchMatchCaseProperty = DependencyProperty.Register("SearchMatchCase", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(false, SearchTokenChanged)); + + /// + /// Identifies the dependency property. + /// + public static readonly DependencyProperty SearchMatchWordProperty = DependencyProperty.Register("SearchMatchWord", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(false, SearchTokenChanged)); + /// /// Identifies the dependency property. /// @@ -86,15 +126,38 @@ static GridLogViewer() /// /// Gets or sets the collection of to display. /// - public ObservableList LogMessages { get { return (ObservableList)GetValue(LogMessagesProperty); } set { SetValue(LogMessagesProperty, value); } } - - public ObservableList FilteredLogMessages { get; set; } = new ObservableList(); + public ICollection LogMessages { get { return (ICollection)GetValue(LogMessagesProperty); } set { SetValue(LogMessagesProperty, value); } } /// /// Gets or sets whether the tool bar should be visible. /// public bool IsToolBarVisible { get { return (bool)GetValue(IsToolBarVisibleProperty); } set { SetValue(IsToolBarVisibleProperty, value); } } + /// + /// Gets or sets whether it is possible to filter the log text. + /// + public bool CanFilterLog { get { return (bool)GetValue(CanFilterLogProperty); } set { SetValue(CanFilterLogProperty, value); } } + + /// + /// Gets or sets whether it is possible to search the log text. + /// + public bool CanSearchLog { get { return (bool)GetValue(CanSearchLogProperty); } set { SetValue(CanSearchLogProperty, value); } } + + /// + /// Gets or sets the current search token. + /// + public string SearchToken { get { return (string)GetValue(SearchTokenProperty); } set { SetValue(SearchTokenProperty, value); } } + + /// + /// Gets or sets whether the search result should match the case. + /// + public bool SearchMatchCase { get { return (bool)GetValue(SearchMatchCaseProperty); } set { SetValue(SearchMatchCaseProperty, value); } } + + /// + /// Gets or sets whether the search result should match whole words only. + /// + public bool SearchMatchWord { get { return (bool)GetValue(SearchMatchWordProperty); } set { SetValue(SearchMatchWordProperty, value); } } + /// /// Gets or sets whether the log viewer should display debug messages. /// @@ -140,11 +203,35 @@ public override void OnApplyTemplate() { base.OnApplyTemplate(); - logGridView = GetTemplateChild("PART_LogGridView") as DataGridEx; + logGridView = GetTemplateChild("PART_LogGridView") as DataGridControl; if (logGridView == null) throw new InvalidOperationException("A part named 'PART_LogGridView' must be present in the ControlTemplate, and must be of type 'DataGridControl'."); + previousResultButton = GetTemplateChild("PART_PreviousResult") as ButtonBase; + if (previousResultButton == null) + throw new InvalidOperationException("A part named 'PART_PreviousResult' must be present in the ControlTemplate, and must be of type 'ButtonBase'."); + + nextResultButton = GetTemplateChild("PART_NextResult") as ButtonBase; + if (nextResultButton == null) + throw new InvalidOperationException("A part named 'PART_NextResult' must be present in the ControlTemplate, and must be of type 'ButtonBase'."); + + var sourceContainer = GetTemplateChild("PART_GridLogViewerCollectionSourceContainer") as FrameworkElement; + if (sourceContainer == null) + throw new InvalidOperationException("A part named 'PART_GridLogViewerCollectionSourceContainer' must be present in the ControlTemplate, and must be of type 'FrameworkElement'."); + + var source = sourceContainer.Resources["GridLogViewerCollectionSource"]; + if (!(source is DataGridCollectionViewSourceBase)) + throw new InvalidOperationException("The 'PART_GridLogViewerCollectionSourceContainer' must be contain a 'GridLogViewerCollectionSource' resource that is the source of the collection view for the DataGridControl."); + + ((DataGridCollectionViewSourceBase)source).Filter += FilterHandler; logGridView.MouseDoubleClick += GridMouseDoubleClick; + previousResultButton.Click += PreviousResultClicked; + nextResultButton.Click += NextResultClicked; + } + + private void FilterHandler(object value, FilterEventArgs e) + { + e.Accepted = FilterMethod(e.Item); } private void GridMouseDoubleClick(object sender, MouseButtonEventArgs e) @@ -167,27 +254,173 @@ private void GridMouseDoubleClick(object sender, MouseButtonEventArgs e) if (asset != null) Session.ActiveAssetView.SelectAssetCommand.Execute(asset); } + } + private void SelectFirstOccurrence() + { + currentResult = 0; + var token = SearchToken; + if (!string.IsNullOrEmpty(token)) + { + var message = LogMessages.FirstOrDefault(Match); + logGridView.SelectedItem = message; + if (message != null) + { + logGridView.BringItemIntoView(message); + } + } } + + private void SelectPreviousOccurrence() + { + var token = SearchToken; + if (!string.IsNullOrEmpty(token)) + { + var message = FindPreviousMessage(); + logGridView.SelectedItem = message; + if (message != null) + { + logGridView.BringItemIntoView(message); + } + else + logGridView.SelectedItem = null; + } + } + + private void SelectNextOccurrence() + { + var token = SearchToken; + if (!string.IsNullOrEmpty(token)) + { + var message = FindNextMessage(); + logGridView.SelectedItem = message; + if (message != null) + { + logGridView.BringItemIntoView(message); + } + } + } + + private ILogMessage FindPreviousMessage() + { + int count = 0; + ILogMessage lastMessage = null; + --currentResult; + foreach (var message in LogMessages.Where(Match)) + { + lastMessage = message; + + if (count == currentResult) + { + return message; + } + ++count; + } + currentResult = Math.Max(0, count - 1); + return lastMessage; + } + + private ILogMessage FindNextMessage() + { + int count = 0; + ILogMessage firstMessage = null; + ++currentResult; + foreach (var message in LogMessages.Where(Match)) + { + if (firstMessage == null) + firstMessage = message; + + if (count == currentResult) + { + return message; + } + ++count; + } + currentResult = 0; + return firstMessage; + } + + private bool Match(ILogMessage message) + { + if (Match(message.Text)) + return true; + + var assetMessage = message as AssetSerializableLogMessage; + return assetMessage != null && Match(assetMessage.AssetUrl.FullPath); + } + + private bool Match(string text) + { + var token = SearchToken; + var stringComparison = SearchMatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + int index = text.IndexOf(token, stringComparison); + if (index < 0) + return false; + + if (SearchMatchWord && text.Length > 1) + { + if (index > 0) + { + char c = text[index - 1]; + if (char.IsLetterOrDigit(c)) + return false; + } + if (index + token.Length < text.Length) + { + char c = text[index + token.Length]; + if (char.IsLetterOrDigit(c)) + return false; + } + } + return true; + } + private static void FilterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var logViewer = (GridLogViewer)d; logViewer.ApplyFilters(); } - + /// + /// Raised when the property is changed. + /// + private static void SearchTokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var logViewer = (GridLogViewer)d; + logViewer.SelectFirstOccurrence(); + } + + private void PreviousResultClicked(object sender, RoutedEventArgs e) + { + SelectPreviousOccurrence(); + } + + private void NextResultClicked(object sender, RoutedEventArgs e) + { + SelectNextOccurrence(); + } + private void ApplyFilters() { if (logGridView == null || logGridView.ItemsSource == null) return; - this.FilteredLogMessages.Clear(); - this.FilteredLogMessages.AddRange(this.LogMessages.Where(x => - x.IsDebug() && ShowDebugMessages || - x.IsError() && ShowErrorMessages || - x.IsFatal() && ShowFatalMessages || - x.IsInfo() && ShowInfoMessages || - x.IsVerbose() && ShowVerboseMessages || - x.IsWarning() && ShowWarningMessages)); + + if (!(logGridView.ItemsSource is DataGridCollectionView)) + throw new InvalidOperationException("The item source of the part 'PART_LogGridView' must be a 'DataGridCollectionView'."); + + var view = (DataGridCollectionView)logGridView.ItemsSource; + view.Refresh(); + } + + private bool FilterMethod(object msg) + { + var message = (ILogMessage)msg; + return (ShowDebugMessages && message.Type == LogMessageType.Debug) + || (ShowVerboseMessages && message.Type == LogMessageType.Verbose) + || (ShowInfoMessages && message.Type == LogMessageType.Info) + || (ShowWarningMessages && message.Type == LogMessageType.Warning) + || (ShowErrorMessages && message.Type == LogMessageType.Error) + || (ShowFatalMessages && message.Type == LogMessageType.Fatal); } } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs index 3ba586eb5e..b800174215 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs @@ -11,6 +11,8 @@ using Xenko.Core.Extensions; using Xenko.Core.Presentation.Extensions; +using Xceed.Wpf.DataGrid; + namespace Xenko.Core.Assets.Editor.View { /// @@ -101,6 +103,14 @@ public static string GetPrimaryTextPath(ItemsControl itemsControl) } + public static int FindMatchingPrefix(DataGridEx dataGridEx, string primaryTextPath, string prefix, string nextChar, int startItemIndex, bool lookForFallbackMatchToo, ref bool wasNewCharUsed) + { + var parameters = new object[] { dataGridEx, primaryTextPath, prefix, nextChar, startItemIndex, lookForFallbackMatchToo, wasNewCharUsed }; + var result = (int)FindMatchingPrefixMethod.Invoke(null, parameters); + wasNewCharUsed = (bool)parameters[6]; + return result; + } + public void AddCharToPrefix(string nextChar) { AddCharToPrefixMethod.Invoke(textSearch, new object[] { nextChar }); @@ -111,4 +121,70 @@ public void ResetTimeout() ResetTimeoutMethod.Invoke(textSearch, new object[] { }); } } + + /// + /// An implementation of DataGrid class that inherits from Xceed DataGridControl and add support for . + /// + public class DataGridEx : DataGridControl + { + /// + protected override void OnTextInput(TextCompositionEventArgs e) + { + base.OnTextInput(e); + if (string.IsNullOrEmpty(e.Text) || !IsTextSearchEnabled || !Equals(e.Source, this) && !Equals(ItemsControlFromItemContainer(e.Source as DependencyObject), this)) + return; + + var textSearch = TextSearchWrapper.EnsureInstance(this); + if (textSearch == null) + return; + + DoSearch(textSearch, e.Text); + e.Handled = true; + } + + /// + /// This method reimplements DoSearch from . + /// + /// + /// + private void DoSearch(TextSearchWrapper textSearch, string nextChar) + { + bool lookForFallbackMatchToo = false; + int startItemIndex = 0; + ItemCollection items = Items; + if (textSearch.IsActive) + startItemIndex = textSearch.MatchedItemIndex; + if (textSearch._charsEntered.Count > 0 && string.Compare(textSearch._charsEntered[textSearch._charsEntered.Count - 1], nextChar, true, TextSearchWrapper.GetCulture(this)) == 0) + lookForFallbackMatchToo = true; + string primaryTextPath = TextSearchWrapper.GetPrimaryTextPath(this); + bool wasNewCharUsed = false; + int matchingPrefix = TextSearchWrapper.FindMatchingPrefix(this, primaryTextPath, textSearch.Prefix, nextChar, startItemIndex, lookForFallbackMatchToo, ref wasNewCharUsed); + if (matchingPrefix != -1) + { + if (!textSearch.IsActive || matchingPrefix != startItemIndex) + { + if (SelectedItem != items[matchingPrefix]) + { + SelectedItem = items[matchingPrefix]; + BringItemIntoView(SelectedItem); + UpdateLayout(); + var container = GetContainerFromItem(SelectedItem) as DataRow; + if (container != null) + { + var cellToFocus = container.FindVisualChildrenOfType().FirstOrDefault(x => x.Focusable); + if (cellToFocus != null) + Keyboard.Focus(cellToFocus); + } + } + textSearch.MatchedItemIndex = matchingPrefix; + } + if (wasNewCharUsed) + textSearch.AddCharToPrefix(nextChar); + if (!textSearch.IsActive) + textSearch.IsActive = true; + } + if (textSearch.IsActive) + textSearch.ResetTimeout(); + } + } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj index 9a4ff5dafb..69c6238a5d 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj +++ b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj @@ -1,4 +1,4 @@ - + @@ -10,7 +10,7 @@ - + @@ -82,6 +82,7 @@ + diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index dac78a4298..ad1a639c84 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -21,6 +21,7 @@ + From 8f8bb48fa48179d75268a09ce755f1fbb4715ca7 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 14 Feb 2020 10:54:33 -0500 Subject: [PATCH 0751/2038] Revert "Add additional comment on datagridex" This reverts commit 5fe902ad3187b1d24f4f6fe50817eaf231f2cd5b. --- .../editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs | 8 -------- 1 file changed, 8 deletions(-) diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs index b800174215..7b3f26f8f2 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs @@ -15,14 +15,6 @@ namespace Xenko.Core.Assets.Editor.View { - /// - /// Xenko generic wpf data grid. Left empty for future development on a generic datagrid. - /// - public class DataGridEx : DataGrid - { - - } - /// /// This class wraps the class, making accessible all members that are required to make the feature work. /// is massively internal, making this feature impossible to implement by default on custom controls. From 7c450b929e7ff4fc2d88f80be38893ddf6003577 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 14 Feb 2020 11:56:12 -0500 Subject: [PATCH 0752/2038] UI: Get rid of duplicate / unused variables --- sources/engine/Xenko.Graphics/SpriteFont.cs | 2 +- .../Xenko.UI/Renderers/DefaultEditTextRenderer.cs | 1 - .../Renderers/DefaultScrollingTextRenderer.cs | 1 - .../Xenko.UI/Renderers/DefaultTextBlockRenderer.cs | 1 - .../Xenko.UI/Rendering/UI/UIRenderFeature.cs | 14 -------------- 5 files changed, 1 insertion(+), 18 deletions(-) diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 1241bd16d9..304cef963a 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -911,7 +911,7 @@ internal struct InternalUIDrawCommand public int DepthBias; - public bool SnapText, IsFullscreen; + public bool SnapText; } } } diff --git a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs index eccb99b1db..9fb96a0f5d 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultEditTextRenderer.cs @@ -117,7 +117,6 @@ public override void RenderColor(UIElement element, UIRenderingContext context, var drawCommand = new SpriteFont.InternalUIDrawCommand { Color = editText.RenderOpacity * editText.TextColor, - IsFullscreen = context.IsFullscreen, DepthBias = context.DepthBias + 2, RealVirtualResolutionRatio = fontScale, RequestedFontSize = editText.ActualTextSize, diff --git a/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs index 3b5519b9de..5ae3937f09 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultScrollingTextRenderer.cs @@ -47,7 +47,6 @@ public override void RenderColor(UIElement element, UIRenderingContext context, RequestedFontSize = scrollingText.ActualTextSize, Batch = Batch, SnapText = context.ShouldSnapText && !scrollingText.DoNotSnapText, - IsFullscreen = context.IsFullscreen, Matrix = textWorldMatrix, Alignment = TextAlignment.Left, TextBoxSize = new Vector2(scrollingText.ActualWidth, scrollingText.ActualHeight) diff --git a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs index d31a8b9adb..1a9bb5f903 100644 --- a/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs +++ b/sources/engine/Xenko.UI/Renderers/DefaultTextBlockRenderer.cs @@ -39,7 +39,6 @@ public override void RenderColor(UIElement element, UIRenderingContext context, VertAlignment = textBlock.TextVerticalAlignment, LineSpacingAdjustment = textBlock.LineSpacingAdjustment, TextBoxSize = new Vector2(textBlock.ActualWidth, textBlock.ActualHeight), - IsFullscreen = context.IsFullscreen }; if (textBlock.Font.FontType == SpriteFontType.SDF) diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs index 85a3e9dd89..8e6ff35ff5 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs @@ -29,13 +29,6 @@ public partial class UIRenderFeature : RootRenderFeature public override Type SupportedRenderObjectType => typeof(RenderUIElement); - /// - /// Represents the UI-element thats currently under the mouse cursor. - /// Only elements with CanBeHitByUser == true are taken into account. - /// Last processed element_state / ?UIComponent? with a valid element will be used. - /// - public UIElement UIElementUnderMouseCursor { get; private set; } - protected override void InitializeCore() { base.InitializeCore(); @@ -107,10 +100,6 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend List events = new List(); PickingPrepare(events); - // see UIElementUnderMouseCursor property - UIElement elementUnderMouseCursor = null; - - // update view parameters and perform UI picking for (int j = 0; j < uiElementStates.Count; j++) { @@ -120,8 +109,6 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend var rootElement = renderObject.Page?.RootElement; if (rootElement == null) continue; - - UIElement loopedElementUnderMouseCursor = null; // calculate the size of the virtual resolution depending on target size (UI canvas) var virtualResolution = renderObject.Resolution; @@ -154,7 +141,6 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend PickingUpdate(uiElementState.RenderObject, context.CommandList.Viewport, ref uiElementState.WorldViewProjectionMatrix, drawTime, events); } } - UIElementUnderMouseCursor = elementUnderMouseCursor; // render the UI elements of all the entities for(int j=0; j Date: Fri, 14 Feb 2020 21:51:45 -0500 Subject: [PATCH 0753/2038] UI: Significant UI performance improvement, mostly only in Vulkan made drawing UI benefit from multithreading --- sources/engine/Xenko.Graphics/UIBatch.cs | 8 +- .../Rendering/UI/UIRenderFeature.Picking.cs | 11 +- .../Xenko.UI/Rendering/UI/UIRenderFeature.cs | 204 +++++++++++------- 3 files changed, 140 insertions(+), 83 deletions(-) diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index 536a4a849c..b95f7798f6 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -570,6 +570,8 @@ private unsafe void CalculateBorderRectangleVertices(UIImageDrawInfo* drawInfo, Vector4 currentRowPosition; Vector4.Add(ref drawInfo->LeftTopCornerWorld, ref shiftVectorY[r], out currentRowPosition); + float uvYr = uvY[r]; // grab it out here + for (var c = 0; c < 4; c++) { Vector4 currentPosition; @@ -584,7 +586,7 @@ private unsafe void CalculateBorderRectangleVertices(UIImageDrawInfo* drawInfo, vertex->ColorAdd = drawInfo->ColorAdd; vertex->TextureCoordinate.X = uvX[c]; - vertex->TextureCoordinate.Y = uvY[r]; + vertex->TextureCoordinate.Y = uvYr; vertex->Swizzle = (int)drawInfo->Swizzle; @@ -618,13 +620,15 @@ private unsafe void CalculateRectangleVertices(UIImageDrawInfo* drawInfo, Vertex // set the two first line of vertices for (var r = 0; r < 2; r++) { + float tcYr = textureCoordY[r]; // grab it out here + for (var c = 0; c < 2; c++) { vertex->ColorScale = drawInfo->ColorScale; vertex->ColorAdd = drawInfo->ColorAdd; vertex->Swizzle = (int)drawInfo->Swizzle; vertex->TextureCoordinate.X = textureCoordX[c]; - vertex->TextureCoordinate.Y = textureCoordY[r]; + vertex->TextureCoordinate.Y = tcYr; vertex->Position.X = currentPosition.X; vertex->Position.Y = currentPosition.Y; diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs index 852715a506..c98f6a318b 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs @@ -15,7 +15,8 @@ namespace Xenko.Rendering.UI public partial class UIRenderFeature { // object to avoid allocation at each element leave event - private readonly HashSet newlySelectedElementParents = new HashSet(); + [ThreadStatic] + private static HashSet newlySelectedElementParents = new HashSet(); partial void PickingUpdate(RenderUIElement renderUIElement, Viewport viewport, ref Matrix worldViewProj, GameTime drawTime, List events) { @@ -336,7 +337,11 @@ private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, Re private UIElement FindCommonParent(UIElement element1, UIElement element2) { // build the list of the parents of the newly selected element - newlySelectedElementParents.Clear(); + if (newlySelectedElementParents == null) + newlySelectedElementParents = new HashSet(); + else + newlySelectedElementParents.Clear(); + var newElementParent = element1; while (newElementParent != null) { @@ -346,7 +351,7 @@ private UIElement FindCommonParent(UIElement element1, UIElement element2) // find the common element into the previously and newly selected element hierarchy var commonElement = element2; - while (commonElement != null && !(newlySelectedElementParents.Count > 0 && newlySelectedElementParents.Contains(commonElement))) + while (commonElement != null && !newlySelectedElementParents.Contains(commonElement)) commonElement = commonElement.VisualParent; return commonElement; diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs index 8e6ff35ff5..185f1f9951 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs @@ -48,6 +48,8 @@ protected override void InitializeCore() } rendererManager = new RendererManager(new DefaultRenderersFactory(RenderSystem.Services)); + + } partial void PickingPrepare(List compactedPointerEvents); @@ -56,27 +58,35 @@ protected override void InitializeCore() public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { - using (context.PushRenderTargetsAndRestore()) + if (GraphicsDevice.Platform == GraphicsPlatform.Vulkan) { - DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); + using (context.PushRenderTargetsAndRestore()) + { + DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); + } + } + else + { + lock (locker) + { + using (context.PushRenderTargetsAndRestore()) + { + DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); + } + } } } + private object locker = new object(); + private void DrawInternal(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { base.Draw(context, renderView, renderViewStage, startIndex, endIndex); - if (batches.TryDequeue(out UIBatch batch) == false) - batch = new UIBatch(context.GraphicsDevice, new UIRenderingContext(), new LayoutingContext()); - - var renderingContext = batch.renderingContext as UIRenderingContext; - var layoutingContext = batch.layoutingContext as LayoutingContext; - var uiProcessor = SceneInstance.GetCurrent(context.RenderContext).GetProcessor(); if (uiProcessor == null) return; - // build the list of the UI elements to render List uiElementStates = new List(); for (var index = startIndex; index < endIndex; index++) @@ -91,11 +101,6 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend // evaluate the current draw time (game instance is null for thumbnails) var drawTime = game != null ? game.DrawTime : new GameTime(); - // update the rendering context - renderingContext.GraphicsContext = context.GraphicsContext; - renderingContext.Time = drawTime; - renderingContext.RenderTarget = context.CommandList.RenderTargets[0]; // TODO: avoid hardcoded index 0 - // Prepare content required for Picking and MouseOver events List events = new List(); PickingPrepare(events); @@ -109,14 +114,14 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend var rootElement = renderObject.Page?.RootElement; if (rootElement == null) continue; - + // calculate the size of the virtual resolution depending on target size (UI canvas) var virtualResolution = renderObject.Resolution; if (renderObject.IsFullScreen) { //var targetSize = viewportSize; - var targetSize = new Vector2(renderingContext.RenderTarget.Width, renderingContext.RenderTarget.Height); + var targetSize = new Vector2(context.CommandList.RenderTargets[0].Width, context.CommandList.RenderTargets[0].Height); // update the virtual resolution of the renderer if (renderObject.ResolutionStretch == ResolutionStretch.FixedWidthAdaptableHeight) @@ -143,86 +148,129 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend } // render the UI elements of all the entities - for(int j=0; j { - transformedVirtualWidth[i] = virtualWidth[0] * uiElementState.WorldViewProjectionMatrix[0 + i] + uiElementState.WorldViewProjectionMatrix[12 + i]; - transformedVirtualHeight[i] = virtualHeight[1] * uiElementState.WorldViewProjectionMatrix[4 + i] + uiElementState.WorldViewProjectionMatrix[12 + i]; + drawUIElement(context, renderView, uiElementStates, j, drawTime); + }); + } + else + { + for (int j=0; j uiElementStates, int j, GameTime drawTime) + { + var uiElementState = uiElementStates[j]; - // perform the time-based updates of the UI element - updatableRootElement.Update(drawTime); + var renderObject = uiElementState.RenderObject; + var rootElement = renderObject.Page?.RootElement; + if (rootElement == null) return; - // update the UI element disposition - rootElement.Measure(virtualResolution); - rootElement.Arrange(virtualResolution, false); + var updatableRootElement = (IUIElementUpdate)rootElement; + var virtualResolution = renderObject.Resolution; - // update the UI element hierarchical properties - var rootMatrix = Matrix.Translation(-virtualResolution / 2); // UI world is translated by a half resolution compared to its quad, which is centered around the origin - updatableRootElement.UpdateWorldMatrix(ref rootMatrix, rootMatrix != uiElementState.RenderObject.LastRootMatrix); - updatableRootElement.UpdateElementState(0); - uiElementState.RenderObject.LastRootMatrix = rootMatrix; + UIBatch batch; + if (GraphicsDevice.Platform == GraphicsPlatform.Vulkan) + { + if (batches.TryDequeue(out batch) == false) + batch = new UIBatch(context.GraphicsDevice, new UIRenderingContext(), new LayoutingContext()); + } + else + { + if (directXBatch == null) directXBatch = new UIBatch(context.GraphicsDevice, new UIRenderingContext(), new LayoutingContext()); + batch = directXBatch; + } - // set the depth buffer, although we are probably not writing to it - context.CommandList.SetRenderTarget(renderingContext.DepthStencilBuffer, renderingContext.RenderTarget); + var renderingContext = batch.renderingContext as UIRenderingContext; + var layoutingContext = batch.layoutingContext as LayoutingContext; - // start the image draw session - renderingContext.StencilTestReferenceValue = 0; - batch.Begin(context.GraphicsContext, ref uiElementState.WorldViewProjectionMatrix, BlendStates.AlphaBlend, uiSystem.KeepStencilValueState, renderingContext.StencilTestReferenceValue); + // update the rendering context values specific to this element + renderingContext.Resolution = virtualResolution; + renderingContext.ViewProjectionMatrix = uiElementState.WorldViewProjectionMatrix; + renderingContext.DepthStencilBuffer = context.CommandList.DepthStencilBuffer; + renderingContext.ShouldSnapText = renderObject.SnapText; + renderingContext.IsFullscreen = renderObject.IsFullScreen; + renderingContext.WorldMatrix3D = renderObject.WorldMatrix3D; - // Render the UI elements in the final render target - RecursiveDrawWithClipping(context, rootElement, ref uiElementState.WorldViewProjectionMatrix, batch); + // update the rendering context + renderingContext.GraphicsContext = context.GraphicsContext; + renderingContext.Time = drawTime; + renderingContext.RenderTarget = context.CommandList.RenderTargets[0]; // TODO: avoid hardcoded index 0 - // end the image draw session - batch.End(); + // calculate an estimate of the UI real size by projecting the element virtual resolution on the screen + var virtualOrigin = uiElementState.WorldViewProjectionMatrix.Row4; + var virtualWidth = new Vector4(virtualResolution.X / 2, 0, 0, 1); + var virtualHeight = new Vector4(0, virtualResolution.Y / 2, 0, 1); + var transformedVirtualWidth = Vector4.Zero; + var transformedVirtualHeight = Vector4.Zero; + for (var i = 0; i < 4; i++) + { + transformedVirtualWidth[i] = virtualWidth[0] * uiElementState.WorldViewProjectionMatrix[0 + i] + uiElementState.WorldViewProjectionMatrix[12 + i]; + transformedVirtualHeight[i] = virtualHeight[1] * uiElementState.WorldViewProjectionMatrix[4 + i] + uiElementState.WorldViewProjectionMatrix[12 + i]; } - batches.Enqueue(batch); + var viewportSize = context.CommandList.Viewport.Size; + var projectedOrigin = virtualOrigin.XY() / virtualOrigin.W; + var projectedVirtualWidth = viewportSize * (transformedVirtualWidth.XY() / transformedVirtualWidth.W - projectedOrigin); + var projectedVirtualHeight = viewportSize * (transformedVirtualHeight.XY() / transformedVirtualHeight.W - projectedOrigin); - events.Clear(); + // Set default services + rootElement.UIElementServices = new UIElementServices { Services = RenderSystem.Services }; - // revert the depth stencil buffer to the default value - context.CommandList.SetRenderTargets(context.CommandList.DepthStencilBuffer, context.CommandList.RenderTargetCount, context.CommandList.RenderTargets); + // set default resource dictionary + + // update layouting context. + layoutingContext.VirtualResolution = virtualResolution; + layoutingContext.RealResolution = viewportSize; + layoutingContext.RealVirtualResolutionRatio = new Vector2(projectedVirtualWidth.Length() / virtualResolution.X, projectedVirtualHeight.Length() / virtualResolution.Y); + rootElement.LayoutingContext = layoutingContext; + + // perform the time-based updates of the UI element + updatableRootElement.Update(drawTime); + + // update the UI element disposition + rootElement.Measure(virtualResolution); + rootElement.Arrange(virtualResolution, false); + + // update the UI element hierarchical properties + var rootMatrix = Matrix.Translation(-virtualResolution / 2); // UI world is translated by a half resolution compared to its quad, which is centered around the origin + updatableRootElement.UpdateWorldMatrix(ref rootMatrix, rootMatrix != uiElementState.RenderObject.LastRootMatrix); + updatableRootElement.UpdateElementState(0); + uiElementState.RenderObject.LastRootMatrix = rootMatrix; + + // set the depth buffer, although we are probably not writing to it + context.CommandList.SetRenderTarget(renderingContext.DepthStencilBuffer, renderingContext.RenderTarget); + + // start the image draw session + renderingContext.StencilTestReferenceValue = 0; + batch.Begin(context.GraphicsContext, ref uiElementState.WorldViewProjectionMatrix, BlendStates.AlphaBlend, uiSystem.KeepStencilValueState, renderingContext.StencilTestReferenceValue); + + // Render the UI elements in the final render target + RecursiveDrawWithClipping(context, rootElement, ref uiElementState.WorldViewProjectionMatrix, batch); + + if (GraphicsDevice.Platform == GraphicsPlatform.Vulkan) + { + lock (locker) + { + batch.End(); + } + } + else batch.End(); + + batches.Enqueue(batch); } private void RecursiveDrawWithClipping(RenderDrawContext context, UIElement element, ref Matrix worldViewProj, UIBatch batch) From fde7a6f84e19ffee0f36f5f05bf11faa89a54236 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 15 Feb 2020 11:16:08 -0500 Subject: [PATCH 0754/2038] Lighting: use packed bytes for smaller light indices buffer --- .../Lights/LightClusteredPointGroup.xksl | 2 +- .../LightClusteredPointGroupLinear.xksl | 2 +- .../LightClusteredPointSpotGroupRenderer.cs | 24 +++++++++---------- .../Lights/LightClusteredSpotGroup.xksl | 2 +- .../Lights/LightClusteredSpotGroupLinear.xksl | 2 +- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.xksl b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.xksl index d55ee2af11..dbdfd5f1f3 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.xksl +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroup.xksl @@ -34,7 +34,7 @@ namespace Xenko.Rendering.Lights { // What we had so far was just a loop index // Note: we have lightIndex as a parameter but we ignore it since we want to preserve it between point and spot lights - int realLightIndex = LightIndices.Load(streams.lightIndex); + int realLightIndex = (LightIndices.Load(streams.lightIndex >> 2) >> ((streams.lightIndex & 3) << 3)) & 0xFF; // grab the right byte streams.lightIndex++; // Build PointLightData diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroupLinear.xksl b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroupLinear.xksl index 49a93e97c1..21c560e475 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroupLinear.xksl +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointGroupLinear.xksl @@ -14,7 +14,7 @@ namespace Xenko.Rendering.Lights { // What we had so far was just a loop index // Note: we have lightIndex as a parameter but we ignore it since we want to preserve it between point and spot lights - int realLightIndex = LightIndices.Load(streams.lightIndex); + int realLightIndex = (LightIndices.Load(streams.lightIndex >> 2) >> ((streams.lightIndex & 3) << 3)) & 0xFF; // grab the right byte streams.lightIndex++; // Build PointLightData diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index 3f152bad70..bc1568c118 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -209,7 +209,6 @@ public override void Reset() { renderViewInfos[i].PointLights.Clear(); renderViewInfos[i].SpotLights.Clear(); - renderViewInfos[i].LightIndices.Clear(); } } } @@ -229,7 +228,6 @@ public override void SetViews(FastList views) // first time renderViewInfos[i].PointLights = new FastListStruct(8); renderViewInfos[i].SpotLights = new FastListStruct(8); - renderViewInfos[i].LightIndices = new FastListStruct(8); } renderViewInfos[i].RenderView = views[i]; @@ -449,8 +447,9 @@ public void ComputeViewParameter(int viewIndex) // setup for a fast indicies calculation (makes for a bigger indicies list, but it is super fast generating it) int clustersPerThread = 1 + (totalClusterCount / Xenko.Core.Threading.Dispatcher.MaxDegreeOfParallelism); - renderViewInfo.LightIndices.Count = totalClusterCount * totalLights; - renderViewInfo.LightIndices.EnsureCapacity(renderViewInfo.LightIndices.Count); + renderViewInfo.LightIndicesCount = totalClusterCount * totalLights; + if (renderViewInfo.LightIndices == null || renderViewInfo.LightIndices.Length < renderViewInfo.LightIndicesCount) + renderViewInfo.LightIndices = new byte[renderViewInfo.LightIndicesCount]; Xenko.Core.Threading.Dispatcher.For(0, Xenko.Core.Threading.Dispatcher.MaxDegreeOfParallelism, (thread) => { @@ -475,7 +474,7 @@ public void ComputeViewParameter(int viewIndex) { var cluster = lightNodes[clusterIndex][i]; - rvinfo.LightIndices[indexStart + i] = cluster.LightIndex; + rvinfo.LightIndices[indexStart + i] = (byte)cluster.LightIndex; switch (cluster.LightType) { @@ -518,16 +517,16 @@ public unsafe void ComputeViewsParameter(RenderDrawContext drawContext) var renderViewInfo = renderViewInfos[viewIndex]; // Update sizes - maxLightIndicesCount = Math.Max(maxLightIndicesCount, renderViewInfo.LightIndices.Count); + maxLightIndicesCount = Math.Max(maxLightIndicesCount, renderViewInfo.LightIndicesCount); maxPointLightsCount = Math.Max(maxPointLightsCount, renderViewInfo.PointLights.Count); maxSpotLightsCount = Math.Max(maxSpotLightsCount, renderViewInfo.SpotLights.Count); } // (Re)allocate buffers if necessary - if (maxLightIndicesCount > 0 && (clusteredGroupRenderer.lightIndicesBuffer == null || clusteredGroupRenderer.lightIndicesBuffer.SizeInBytes < maxLightIndicesCount * sizeof(int))) + if (maxLightIndicesCount > 0 && (clusteredGroupRenderer.lightIndicesBuffer == null || clusteredGroupRenderer.lightIndicesBuffer.SizeInBytes < maxLightIndicesCount * sizeof(byte))) { clusteredGroupRenderer.lightIndicesBuffer?.Dispose(); - clusteredGroupRenderer.lightIndicesBuffer = Buffer.New(drawContext.GraphicsDevice, MathUtil.NextPowerOfTwo(maxLightIndicesCount * sizeof(int)), 0, BufferFlags.ShaderResource, PixelFormat.R32_UInt); + clusteredGroupRenderer.lightIndicesBuffer = Buffer.New(drawContext.GraphicsDevice, MathUtil.NextPowerOfTwo(maxLightIndicesCount * sizeof(byte)), 0, BufferFlags.ShaderResource, PixelFormat.R32_UInt); } if (maxPointLightsCount > 0 && (clusteredGroupRenderer.pointLightsBuffer == null || clusteredGroupRenderer.pointLightsBuffer.SizeInBytes < maxPointLightsCount * sizeof(PointLightData))) { @@ -615,10 +614,10 @@ public override unsafe void UpdateViewResources(RenderDrawContext context, int v } #endif // LightIndices: Ensure size and update - if (renderViewInfo.LightIndices.Count > 0) + if (renderViewInfo.LightIndicesCount > 0) { - fixed (int* lightIndicesPtr = renderViewInfo.LightIndices.Items) - context.CommandList.UpdateSubresource(clusteredGroupRenderer.lightIndicesBuffer, 0, new DataBox((IntPtr)lightIndicesPtr, 0, 0), new ResourceRegion(0, 0, 0, renderViewInfo.LightIndices.Count * sizeof(int), 1, 1)); + fixed (byte* lightIndicesPtr = renderViewInfo.LightIndices) + context.CommandList.UpdateSubresource(clusteredGroupRenderer.lightIndicesBuffer, 0, new DataBox((IntPtr)lightIndicesPtr, 0, 0), new ResourceRegion(0, 0, 0, renderViewInfo.LightIndicesCount * sizeof(byte), 1, 1)); } #if XENKO_PLATFORM_MACOS // See previous macOS comment. @@ -764,7 +763,8 @@ private struct RenderViewInfo public FastListStruct PointLights; public FastListStruct SpotLights; - public FastListStruct LightIndices; + public byte[] LightIndices; + public int LightIndicesCount; public Int2[] LightClusters; public Int2 ClusterCount; } diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.xksl b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.xksl index 201b0db9a9..f2143f73d7 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.xksl +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroup.xksl @@ -33,7 +33,7 @@ namespace Xenko.Rendering.Lights { // What we had so far was just a loop index // Note: we have lightIndex as a parameter but we ignore it since we want to preserve it between point and spot lights - int realLightIndex = LightIndices.Load(streams.lightIndex); + int realLightIndex = (LightIndices.Load(streams.lightIndex >> 2) >> ((streams.lightIndex & 3) << 3)) & 0xFF; // grab the right byte streams.lightIndex++; // Build SpotLightData diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroupLinear.xksl b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroupLinear.xksl index 5b8ea8e341..19e0ad2c9c 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroupLinear.xksl +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredSpotGroupLinear.xksl @@ -19,7 +19,7 @@ namespace Xenko.Rendering.Lights { // What we had so far was just a loop index // Note: we have lightIndex as a parameter but we ignore it since we want to preserve it between point and spot lights - int realLightIndex = LightIndices.Load(streams.lightIndex); + int realLightIndex = (LightIndices.Load(streams.lightIndex >> 2) >> ((streams.lightIndex & 3) << 3)) & 0xFF; // grab the right byte streams.lightIndex++; // Build SpotLightData From 62ba66111933b1cce1510d07b9a10b62e57b79cc Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 15 Feb 2020 18:22:45 -0500 Subject: [PATCH 0755/2038] UI: More significant restructuring of UI rendering for multithreading, performance and stability --- .../Xenko.UI/Rendering/UI/UIRenderFeature.cs | 277 +++++++++--------- 1 file changed, 133 insertions(+), 144 deletions(-) diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs index 185f1f9951..e95d1910ca 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.cs @@ -7,6 +7,7 @@ using Xenko.Core; using Xenko.Core.Diagnostics; using Xenko.Core.Mathematics; +using Xenko.Core.Threading; using Xenko.Engine; using Xenko.Games; using Xenko.Graphics; @@ -58,65 +59,75 @@ protected override void InitializeCore() public override void Draw(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { - if (GraphicsDevice.Platform == GraphicsPlatform.Vulkan) - { - using (context.PushRenderTargetsAndRestore()) - { - DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); - } - } - else + using (context.PushRenderTargetsAndRestore()) { - lock (locker) - { - using (context.PushRenderTargetsAndRestore()) - { - DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); - } - } + DrawInternal(context, renderView, renderViewStage, startIndex, endIndex); } } - private object locker = new object(); + private object drawLocker = new object(), pickingLocker = new object(); - private void DrawInternal(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) + private void initUIElementStates(RenderDrawContext context, RenderView renderView, + RenderViewStage renderViewStage, ConcurrentCollector uiElementStates, + int index, GameTime drawTime, List events) { - base.Draw(context, renderView, renderViewStage, startIndex, endIndex); + var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; + var renderNode = GetRenderNode(renderNodeReference); + var renderElement = (RenderUIElement)renderNode.RenderObject; - var uiProcessor = SceneInstance.GetCurrent(context.RenderContext).GetProcessor(); - if (uiProcessor == null) - return; + var uiElementState = new UIElementState(renderElement); + uiElementStates.Add(uiElementState); - // build the list of the UI elements to render - List uiElementStates = new List(); - for (var index = startIndex; index < endIndex; index++) + var renderObject = uiElementState.RenderObject; + var rootElement = renderObject.Page?.RootElement; + + if (rootElement != null) { - var renderNodeReference = renderViewStage.SortedRenderNodes[index].RenderNode; - var renderNode = GetRenderNode(renderNodeReference); - var renderElement = (RenderUIElement)renderNode.RenderObject; + UIBatch batch = getFreeBatch(context); - uiElementStates.Add(new UIElementState(renderElement)); - } + var virtualResolution = renderObject.Resolution; + var updatableRootElement = (IUIElementUpdate)rootElement; + + // calculate an estimate of the UI real size by projecting the element virtual resolution on the screen + var virtualOrigin = uiElementState.WorldViewProjectionMatrix.Row4; + var virtualWidth = new Vector4(virtualResolution.X / 2, 0, 0, 1); + var virtualHeight = new Vector4(0, virtualResolution.Y / 2, 0, 1); + var transformedVirtualWidth = Vector4.Zero; + var transformedVirtualHeight = Vector4.Zero; + for (var i = 0; i < 4; i++) + { + transformedVirtualWidth[i] = virtualWidth[0] * uiElementState.WorldViewProjectionMatrix[0 + i] + uiElementState.WorldViewProjectionMatrix[12 + i]; + transformedVirtualHeight[i] = virtualHeight[1] * uiElementState.WorldViewProjectionMatrix[4 + i] + uiElementState.WorldViewProjectionMatrix[12 + i]; + } - // evaluate the current draw time (game instance is null for thumbnails) - var drawTime = game != null ? game.DrawTime : new GameTime(); + var viewportSize = context.CommandList.Viewport.Size; + var projectedOrigin = virtualOrigin.XY() / virtualOrigin.W; + var projectedVirtualWidth = viewportSize * (transformedVirtualWidth.XY() / transformedVirtualWidth.W - projectedOrigin); + var projectedVirtualHeight = viewportSize * (transformedVirtualHeight.XY() / transformedVirtualHeight.W - projectedOrigin); - // Prepare content required for Picking and MouseOver events - List events = new List(); - PickingPrepare(events); + // Set default services + rootElement.UIElementServices = new UIElementServices { Services = RenderSystem.Services }; - // update view parameters and perform UI picking - for (int j = 0; j < uiElementStates.Count; j++) - { - var uiElementState = uiElementStates[j]; + // perform the time-based updates of the UI element + updatableRootElement.Update(drawTime); - var renderObject = uiElementState.RenderObject; - var rootElement = renderObject.Page?.RootElement; - if (rootElement == null) - continue; + // update the UI element hierarchical properties + var rootMatrix = Matrix.Translation(-virtualResolution / 2); // UI world is translated by a half resolution compared to its quad, which is centered around the origin + updatableRootElement.UpdateWorldMatrix(ref rootMatrix, rootMatrix != uiElementState.RenderObject.LastRootMatrix); + updatableRootElement.UpdateElementState(0); + uiElementState.RenderObject.LastRootMatrix = rootMatrix; + // set default resource dictionary - // calculate the size of the virtual resolution depending on target size (UI canvas) - var virtualResolution = renderObject.Resolution; + // update layouting context. + var layoutingContext = batch.layoutingContext as LayoutingContext; + layoutingContext.VirtualResolution = virtualResolution; + layoutingContext.RealResolution = viewportSize; + layoutingContext.RealVirtualResolutionRatio = new Vector2(projectedVirtualWidth.Length() / virtualResolution.X, projectedVirtualHeight.Length() / virtualResolution.Y); + rootElement.LayoutingContext = layoutingContext; + + // update the UI element disposition + rootElement.Measure(renderObject.Resolution); + rootElement.Arrange(renderObject.Resolution, false); if (renderObject.IsFullScreen) { @@ -139,138 +150,116 @@ private void DrawInternal(RenderDrawContext context, RenderView renderView, Rend ref renderView.View, ref renderView.Projection, cameraComponent.Entity.Transform.WorldPosition()); } - - // Check if the current UI component is being picked based on the current ViewParameters (used to draw this element) - using (Profiler.Begin(UIProfilerKeys.TouchEventsUpdate)) - { - PickingUpdate(uiElementState.RenderObject, context.CommandList.Viewport, ref uiElementState.WorldViewProjectionMatrix, drawTime, events); - } - } + PickingUpdate(uiElementState.RenderObject, context.CommandList.Viewport, ref uiElementState.WorldViewProjectionMatrix, drawTime, events); - // render the UI elements of all the entities - if (GraphicsDevice.Platform == GraphicsPlatform.Vulkan) - { - Xenko.Core.Threading.Dispatcher.For(0, uiElementStates.Count, (j) => - { - drawUIElement(context, renderView, uiElementStates, j, drawTime); - }); + ReturnBatch(batch); } - else - { - for (int j=0; j uiElementStates, int j, GameTime drawTime) + private void DrawInternal(RenderDrawContext context, RenderView renderView, RenderViewStage renderViewStage, int startIndex, int endIndex) { - var uiElementState = uiElementStates[j]; + base.Draw(context, renderView, renderViewStage, startIndex, endIndex); - var renderObject = uiElementState.RenderObject; - var rootElement = renderObject.Page?.RootElement; - if (rootElement == null) return; + var uiProcessor = SceneInstance.GetCurrent(context.RenderContext).GetProcessor(); + if (uiProcessor == null) + return; - var updatableRootElement = (IUIElementUpdate)rootElement; - var virtualResolution = renderObject.Resolution; + // evaluate the current draw time (game instance is null for thumbnails) + var drawTime = game != null ? game.DrawTime : new GameTime(); - UIBatch batch; + // Prepare content required for Picking and MouseOver events + List events = new List(); + PickingPrepare(events); + + // build the list of the UI elements to render + ConcurrentCollector uiElementStates = new ConcurrentCollector(); if (GraphicsDevice.Platform == GraphicsPlatform.Vulkan) { - if (batches.TryDequeue(out batch) == false) - batch = new UIBatch(context.GraphicsDevice, new UIRenderingContext(), new LayoutingContext()); + Xenko.Core.Threading.Dispatcher.For(startIndex, endIndex, (index) => + { + initUIElementStates(context, renderView, renderViewStage, uiElementStates, index, drawTime, events); + }); } else { - if (directXBatch == null) directXBatch = new UIBatch(context.GraphicsDevice, new UIRenderingContext(), new LayoutingContext()); - batch = directXBatch; + for(int i=startIndex; i Date: Sun, 16 Feb 2020 10:42:09 -0500 Subject: [PATCH 0756/2038] Audio: assure streaming music is playing --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index a5e64b4093..9eae150a20 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -409,6 +409,10 @@ private static unsafe void Worker() { source.ExtractAndFillData(); } + else if (AudioLayer.SourceIsPlaying(source.soundInstance.Source) == false) + { + AudioLayer.SourcePlay(source.soundInstance.Source); + } } } From 58c9b110e56668d4920b58fbc174a602a9a2eac8 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 16 Feb 2020 10:44:59 -0500 Subject: [PATCH 0757/2038] Version bump to 3.5.4 --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 9c4a336032..72c56d9e9d 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.3"; + public const string VersionToShowInEditor = "3.5.4"; /// /// The current assembly version as text, currently same as . From 3408e075158d6271795f0e81c3238f64367af200 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 16 Feb 2020 20:04:55 -0500 Subject: [PATCH 0758/2038] UI: more performance improvements --- sources/engine/Xenko.Graphics/BatchBase.cs | 3 -- sources/engine/Xenko.Graphics/UIBatch.cs | 40 ++++++++++++++-------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/sources/engine/Xenko.Graphics/BatchBase.cs b/sources/engine/Xenko.Graphics/BatchBase.cs index b6f7e0db2a..c0537607c6 100644 --- a/sources/engine/Xenko.Graphics/BatchBase.cs +++ b/sources/engine/Xenko.Graphics/BatchBase.cs @@ -405,8 +405,6 @@ private void DrawBatchPerTexture(Texture texture, ElementInfo[] sprites, int off DrawBatchPerTextureAndPass(sprites, offset, count); } - private object batchLocker = new object(); - private void DrawBatchPerTextureAndPass(ElementInfo[] sprites, int offset, int count) { while (count > 0) @@ -489,7 +487,6 @@ private void DrawBatchPerTextureAndPass(ElementInfo[] sprites, int offset, int c // resourceContext.VertexBuffer.SetData(GraphicsDevice, new DataPointer(x64TempBuffer.DataPointer, batchSize * VerticesPerSprite * Utilities.SizeOf()), offsetInBytes, noOverwrite); //} //else - lock (batchLocker) { var mappedIndices = new MappedResource(); var mappedVertices = GraphicsContext.CommandList.MapSubresource(ResourceContext.VertexBuffer, 0, MapMode.WriteNoOverwrite, false, offsetVertexInBytes, vertexCount * vertexStructSize); diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index b95f7798f6..0848650b79 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -502,7 +502,11 @@ protected override unsafe void UpdateBufferValuesFromElementInfo(ref ElementInfo private static unsafe void CalculateCubeVertices(UIImageDrawInfo* drawInfo, VertexPositionColorTextureSwizzle* vertex) { var currentPosition = drawInfo->LeftTopCornerWorld; - + + // convert colors here instead of in the loop + Color4 colorScale = drawInfo->ColorScale.ToColor4(); + Color4 colorAdd = drawInfo->ColorAdd.ToColor4(); + // set the two first line of vertices for (var l = 0; l < 2; ++l) { @@ -510,8 +514,8 @@ private static unsafe void CalculateCubeVertices(UIImageDrawInfo* drawInfo, Vert { for (var c = 0; c < 2; c++) { - vertex->ColorScale = drawInfo->ColorScale; - vertex->ColorAdd = drawInfo->ColorAdd; + vertex->ColorScale = colorScale; + vertex->ColorAdd = colorAdd; vertex->Swizzle = (int)drawInfo->Swizzle; vertex->TextureCoordinate.X = 0; // cubes are used only for color @@ -565,6 +569,10 @@ private unsafe void CalculateBorderRectangleVertices(UIImageDrawInfo* drawInfo, Vector4.Multiply(ref drawInfo->UnitYWorld, drawInfo->VertexShift.W, out shiftVectorY[2]); shiftVectorY[3] = drawInfo->UnitYWorld; + // convert colors here instead of in the loop + Color4 colorScale = drawInfo->ColorScale.ToColor4(); + Color4 colorAdd = drawInfo->ColorAdd.ToColor4(); + for (var r = 0; r < 4; r++) { Vector4 currentRowPosition; @@ -582,10 +590,10 @@ private unsafe void CalculateBorderRectangleVertices(UIImageDrawInfo* drawInfo, vertex->Position.Z = currentPosition.Z - currentPosition.W * drawInfo->DepthBias * DepthBiasShiftOneUnit; vertex->Position.W = currentPosition.W; - vertex->ColorScale = drawInfo->ColorScale; - vertex->ColorAdd = drawInfo->ColorAdd; + vertex->ColorScale = colorScale; + vertex->ColorAdd = colorAdd; - vertex->TextureCoordinate.X = uvX[c]; + vertex->TextureCoordinate.X = c == 0 ? uvX.X : uvX.Y; vertex->TextureCoordinate.Y = uvYr; vertex->Swizzle = (int)drawInfo->Swizzle; @@ -614,21 +622,25 @@ private unsafe void CalculateRectangleVertices(UIImageDrawInfo* drawInfo, Vertex currentPosition.Y *= currentPosition.W; } - var textureCoordX = new Vector2(drawInfo->Source.Left, drawInfo->Source.Right); - var textureCoordY = new Vector2(drawInfo->Source.Top, drawInfo->Source.Bottom); + float tcx0 = drawInfo->Source.Left; + float tcx1 = drawInfo->Source.Right; + float tcy0 = drawInfo->Source.Top; + float tcy1 = drawInfo->Source.Bottom; + + // convert colors here instead of in the loop + Color4 colorScale = drawInfo->ColorScale.ToColor4(); + Color4 colorAdd = drawInfo->ColorAdd.ToColor4(); // set the two first line of vertices for (var r = 0; r < 2; r++) { - float tcYr = textureCoordY[r]; // grab it out here - for (var c = 0; c < 2; c++) { - vertex->ColorScale = drawInfo->ColorScale; - vertex->ColorAdd = drawInfo->ColorAdd; + vertex->ColorScale = colorScale; + vertex->ColorAdd = colorAdd; vertex->Swizzle = (int)drawInfo->Swizzle; - vertex->TextureCoordinate.X = textureCoordX[c]; - vertex->TextureCoordinate.Y = tcYr; + vertex->TextureCoordinate.X = c == 0 ? tcx0 : tcx1; + vertex->TextureCoordinate.Y = r == 0 ? tcy0 : tcy1; vertex->Position.X = currentPosition.X; vertex->Position.Y = currentPosition.Y; From 7693fe95a8dc73339071448d6844f2884d60ca2e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 16 Feb 2020 20:05:09 -0500 Subject: [PATCH 0759/2038] Lighting: more performance improvements --- .../LightClusteredPointSpotGroupRenderer.cs | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index bc1568c118..ac6fd85bb5 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -169,7 +169,7 @@ internal class PointLightShaderGroupData : LightShaderGroupDynamic // Artifically increase range of first slice to not waste too much slices in very short area public float SpecialNearPlane = 2.0f; - private List> lightNodes = new List>(); + private ConcurrentQueue[] lightNodes; private RenderViewInfo[] renderViewInfos; private Int2 maxClusterCount; //private Plane[] zPlanes; @@ -300,8 +300,13 @@ public void ComputeViewParameter(int viewIndex) float clusterDepthBias = renderViewInfo.ClusterDepthBias = 2.0f - clusterDepthScale * nearPlane; // make sure we have enough lists - while (lightNodes.Count < totalClusterCount) - lightNodes.Add(new ConcurrentCollector()); + if (lightNodes == null || lightNodes.Length < totalClusterCount) + { + lightNodes = new ConcurrentQueue[totalClusterCount]; + for (int i = 0; i < totalClusterCount; i++) + lightNodes[i] = new ConcurrentQueue(); + } + int totalLights = 0; //---------------- POINT LIGHTS ------------------- @@ -374,7 +379,7 @@ public void ComputeViewParameter(int viewIndex) { for (int x = tileStartX; x < tileEndX; ++x) { - lightNodes[x + (y + z * clusterCountY) * clusterCountX].Add(myNode); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(myNode); } } } @@ -439,7 +444,7 @@ public void ComputeViewParameter(int viewIndex) { for (int x = tileStartX; x < tileEndX; ++x) { - lightNodes[x + (y + z * clusterCountY) * clusterCountX].Add(myNode); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(myNode); } } } @@ -456,25 +461,24 @@ public void ComputeViewParameter(int viewIndex) for (int clusterIndex = thread * clustersPerThread; clusterIndex < (thread + 1) * clustersPerThread && clusterIndex < totalClusterCount; clusterIndex++) { ref var rvinfo = ref renderViewInfos[viewIndex]; + ref var lnds = ref lightNodes[clusterIndex]; - if (lightNodes[clusterIndex].Count == 0) + if (lnds.Count == 0) { rvinfo.LightClusters[clusterIndex] = Int2.Zero; continue; } - lightNodes[clusterIndex].Close(); - // Build light indices int pointLightCounter = 0; int spotLightCounter = 0; int indexStart = clusterIndex * totalLights; + int i = 0; - for (int i = 0; i < lightNodes[clusterIndex].Count; i++) + while(lnds.TryDequeue(out var cluster)) { - var cluster = lightNodes[clusterIndex][i]; - rvinfo.LightIndices[indexStart + i] = (byte)cluster.LightIndex; + i++; switch (cluster.LightType) { @@ -487,8 +491,6 @@ public void ComputeViewParameter(int viewIndex) } } - lightNodes[clusterIndex].Clear(true); - // Add new light cluster range // Stored in the format: // x = start_index From b7b3d8d506a36a819d47bee82c6c51a8af8b3a88 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Mon, 17 Feb 2020 18:42:15 +0900 Subject: [PATCH 0760/2038] [Voxels] Added a graphics compositor template preconfigured for voxel cone tracing --- .../DefaultGraphicsCompositorVoxels.xktpl | 10 + .../GraphicsCompositorTemplateGenerator.cs | 13 +- .../Xenko.Assets.Presentation.xkpkg | 1 + .../DefaultGraphicsCompositorVoxels.xkgfxcomp | 231 ++++++++++++++++++ 4 files changed, 250 insertions(+), 5 deletions(-) create mode 100644 sources/editor/Xenko.Assets.Presentation/Templates/Assets/Misc/DefaultGraphicsCompositorVoxels.xktpl create mode 100644 sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DefaultGraphicsCompositorVoxels.xkgfxcomp diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Misc/DefaultGraphicsCompositorVoxels.xktpl b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Misc/DefaultGraphicsCompositorVoxels.xktpl new file mode 100644 index 0000000000..25a5d6df93 --- /dev/null +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Assets/Misc/DefaultGraphicsCompositorVoxels.xktpl @@ -0,0 +1,10 @@ +!TemplateAssetFactory +Id: 4BC182D7-69D5-4BE2-9AF3-1C82F67B629D +AssetTypeName: GraphicsCompositorAsset +Name: Graphics compositor (Voxel Cone Tracing) +Scope: Asset +Description: A graphics compositor specifically setup for Voxel Cone Tracing +Group: Miscellaneous +Order: -100 +Icon: ..\.xktpl\GraphicsCompositor.png +DefaultOutputName: GraphicsCompositor diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/GraphicsCompositorTemplateGenerator.cs b/sources/editor/Xenko.Assets.Presentation/Templates/GraphicsCompositorTemplateGenerator.cs index 88d2a8bd53..e0810286f6 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/GraphicsCompositorTemplateGenerator.cs +++ b/sources/editor/Xenko.Assets.Presentation/Templates/GraphicsCompositorTemplateGenerator.cs @@ -13,20 +13,23 @@ public class GraphicsCompositorTemplateGenerator : AssetFactoryTemplateGenerator { public new static readonly GraphicsCompositorTemplateGenerator Default = new GraphicsCompositorTemplateGenerator(); - public static readonly Guid Level9TemplateId = new Guid("20947F4A-7B50-4716-AC85-D10EFF58CD33"); - public static readonly Guid Level10TemplateId = new Guid("D4EE3BD3-9B06-460E-9175-D6AFB2459463"); + public static readonly Dictionary SupportedTemplatesToUrl = new Dictionary + { + { new Guid("20947F4A-7B50-4716-AC85-D10EFF58CD33"), XenkoPackageUpgrader.DefaultGraphicsCompositorLevel9Url }, + { new Guid("D4EE3BD3-9B06-460E-9175-D6AFB2459463"), XenkoPackageUpgrader.DefaultGraphicsCompositorLevel10Url }, + { new Guid("4BC182D7-69D5-4BE2-9AF3-1C82F67B629D"), "GraphicsCompositor/DefaultGraphicsCompositorVoxels" }, + }; public override bool IsSupportingTemplate(TemplateDescription templateDescription) { if (templateDescription == null) throw new ArgumentNullException(nameof(templateDescription)); - return templateDescription.Id == Level9TemplateId || templateDescription.Id == Level10TemplateId; + return SupportedTemplatesToUrl.ContainsKey(templateDescription.Id); } protected override IEnumerable CreateAssets(AssetTemplateGeneratorParameters parameters) { // Find default graphics compositor to create a derived asset from - var graphicsCompositorUrl = parameters.Description.Id == Level9TemplateId ? XenkoPackageUpgrader.DefaultGraphicsCompositorLevel9Url : XenkoPackageUpgrader.DefaultGraphicsCompositorLevel10Url; - var graphicsCompositor = parameters.Package.FindAsset(graphicsCompositorUrl); + var graphicsCompositor = SupportedTemplatesToUrl.TryGetValue(parameters.Description.Id, out var graphicsCompositorUrl) ? parameters.Package.FindAsset(graphicsCompositorUrl) : null; // Something went wrong, create an empty asset if (graphicsCompositor == null) diff --git a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg index ae338c8fb7..2c04441615 100644 --- a/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg +++ b/sources/editor/Xenko.Assets.Presentation/Xenko.Assets.Presentation.xkpkg @@ -32,6 +32,7 @@ TemplateFolders: - !file Templates/Assets/Misc/DefaultGameSettings.xktpl - !file Templates/Assets/Misc/DefaultGraphicsCompositorLevel10.xktpl - !file Templates/Assets/Misc/DefaultGraphicsCompositorLevel9.xktpl + - !file Templates/Assets/Misc/DefaultGraphicsCompositorVoxels.xktpl - !file Templates/Assets/Misc/DefaultRawAsset.xktpl - !file Templates/Assets/Misc/DefaultSkybox.xktpl - !file Templates/Assets/Models/DefaultModel.xktpl diff --git a/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DefaultGraphicsCompositorVoxels.xkgfxcomp b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DefaultGraphicsCompositorVoxels.xkgfxcomp new file mode 100644 index 0000000000..a92253cd2b --- /dev/null +++ b/sources/engine/Xenko.Voxels/Voxels/GraphicsCompositor/DefaultGraphicsCompositorVoxels.xkgfxcomp @@ -0,0 +1,231 @@ +!GraphicsCompositorAsset +Id: 472e6944-3ddc-47db-8d6f-2e0a987475ec +SerializedVersion: {Xenko: 3.1.0.1} +Tags: [] +Archetype: 823a81bf-bac0-4552-9267-aeed499c40df:DefaultGraphicsCompositorLevel10 +Cameras: + de2e75c3b2b23e54162686363f3f138e: + Id: 0ad0a331-55d2-4a3d-8909-05a4493a7d24 + Name: Main +RenderStages: + 47116750c1a5d449b4ad3625f71439b3: + Id: 4a600aa5-eda0-4861-a9b4-d200df85da1e + Name: Opaque + EffectSlotName: Main + SortMode: !SortModeStateChange {} + 9105a30fee026d4893472b6aee83d035: + Id: 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + Name: Transparent + EffectSlotName: Main + SortMode: !BackToFrontSortMode {} + 554e52c061404d4684dd7c4c70f70e0e: + Id: 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + Name: ShadowMapCaster + EffectSlotName: ShadowMapCaster + SortMode: !FrontToBackSortMode {} + 5a50638f5c514dc490c8c4f57cc88b57: + Id: 7cebf9d3-bf10-4e25-939e-e36c465efecf + Name: ShadowMapCasterParaboloid + EffectSlotName: ShadowMapCasterParaboloid + SortMode: !FrontToBackSortMode {} + bc1a77d2ab254a6e920f86cff65cd75e: + Id: aeb202d1-2b31-4082-916c-1faee73ad2ad + Name: ShadowMapCasterCubeMap + EffectSlotName: ShadowMapCasterCubeMap + SortMode: !FrontToBackSortMode {} + 33d9d311a1a65601da9ef56775477f95: + Id: 259cf50a-634a-4ac6-846e-4f843be0a38f + Name: GBuffer + EffectSlotName: GBuffer + SortMode: !FrontToBackSortMode {} + 54e148fa49ca18c6b30f86e89ec95388*: + Id: ffa492d9-b8a2-4d74-abe8-d82c542fc526 + Name: VoxelizationPassFirst + EffectSlotName: Voxelizer + eb9689239718d7dab8a56c2ce49b59d3*: + Id: ba28c12c-261f-45e6-bd4e-02cf38141f06 + Name: VoxelizationPassSecond + EffectSlotName: Voxelizer2 +RenderFeatures: + d8fb80b0e7995140a46bca8dc36ee8a2: !Xenko.Rendering.MeshRenderFeature,Xenko.Rendering + RenderStageSelectors: + 44cf4a95ef82544e9ce3c6507d5569a9: !Xenko.Rendering.MeshTransparentRenderStageSelector,Xenko.Rendering + OpaqueRenderStage: ref!! 4a600aa5-eda0-4861-a9b4-d200df85da1e + TransparentRenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + EffectName: XenkoForwardShadingEffect + 6f7224048750e7260ea87c444f74b32c: !Xenko.Rendering.Shadows.ShadowMapRenderStageSelector,Xenko.Rendering + ShadowMapRenderStage: ref!! 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + EffectName: XenkoForwardShadingEffect.ShadowMapCaster + b60663d7cb46417a94341a39c3bc1a12: !Xenko.Rendering.Shadows.ShadowMapRenderStageSelector,Xenko.Rendering + ShadowMapRenderStage: ref!! 7cebf9d3-bf10-4e25-939e-e36c465efecf + EffectName: XenkoForwardShadingEffect.ShadowMapCasterParaboloid + f5533b1249b942df8a8aba311cd79532: !Xenko.Rendering.Shadows.ShadowMapRenderStageSelector,Xenko.Rendering + ShadowMapRenderStage: ref!! aeb202d1-2b31-4082-916c-1faee73ad2ad + EffectName: XenkoForwardShadingEffect.ShadowMapCasterCubeMap + 106341b76db9fcda6a033dad16aa708b: !Xenko.Rendering.MeshTransparentRenderStageSelector,Xenko.Rendering + OpaqueRenderStage: ref!! 259cf50a-634a-4ac6-846e-4f843be0a38f + EffectName: XenkoForwardShadingEffect.ShadowMapCaster + 1cd2eaa455053c4bb2b0e1b2c156cb3a*: !Xenko.Rendering.MeshTransparentRenderStageSelector,Xenko.Rendering + OpaqueRenderStage: ref!! ffa492d9-b8a2-4d74-abe8-d82c542fc526 + TransparentRenderStage: ref!! ffa492d9-b8a2-4d74-abe8-d82c542fc526 + EffectName: XenkoForwardShadingEffectVXGI.VoxelizeToFragmentsEffect + 3a8978fa14c861d9a85751a80428226a*: !Xenko.Rendering.MeshTransparentRenderStageSelector,Xenko.Rendering + OpaqueRenderStage: ref!! ba28c12c-261f-45e6-bd4e-02cf38141f06 + TransparentRenderStage: ref!! ba28c12c-261f-45e6-bd4e-02cf38141f06 + EffectName: XenkoForwardShadingEffectVXGI.VoxelizeToFragmentsEffect + PipelineProcessors: + d70f5aee0616e4ab25081ceaf643290c: !Xenko.Rendering.MeshPipelineProcessor,Xenko.Rendering + TransparentRenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + 26c899b17f88c21ab13bf60a7220ccd1: !Xenko.Rendering.ShadowMeshPipelineProcessor,Xenko.Rendering + ShadowMapRenderStage: ref!! 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + ff51170a7d1a4761b73ef6a5c9f0cba2: !Xenko.Rendering.ShadowMeshPipelineProcessor,Xenko.Rendering + ShadowMapRenderStage: ref!! 7cebf9d3-bf10-4e25-939e-e36c465efecf + DepthClipping: true + ae4336b0a9514e8488e8e0ccbcef25f4: !Xenko.Rendering.ShadowMeshPipelineProcessor,Xenko.Rendering + ShadowMapRenderStage: ref!! aeb202d1-2b31-4082-916c-1faee73ad2ad + DepthClipping: true + 371dd885d403a507d2e779f9d9f0c277*: !Xenko.Rendering.Voxels.VoxelPipelineProcessor,Xenko.Voxels + VoxelRenderStage: + ec88b51356d469c565289d94b1a68908: ref!! ffa492d9-b8a2-4d74-abe8-d82c542fc526 + 991d03d23b97ee4e131f40890c642eeb: ref!! ba28c12c-261f-45e6-bd4e-02cf38141f06 + RenderFeatures: + 86b959cbdf51a1438d4973177c77c627: !Xenko.Rendering.TransformRenderFeature,Xenko.Rendering {} + 8e0351fee9883922648a11016224b195: !Xenko.Rendering.SkinningRenderFeature,Xenko.Rendering {} + f5a2017030ba4b28784e804807ce7628: !Xenko.Rendering.Materials.MaterialRenderFeature,Xenko.Rendering {} + 83fea7526ebe4893a5bad953d0502bfd: !Xenko.Rendering.Shadows.ShadowCasterRenderFeature,Xenko.Rendering {} + 65743b4380f4cc43b2b4bdc23cd0c07c: !Xenko.Rendering.Lights.ForwardLightingRenderFeature,Xenko.Rendering + LightRenderers: + 7ac2775468f53c4399b2f3f6357c85c9: !Xenko.Rendering.Lights.LightAmbientRenderer,Xenko.Rendering {} + 7b68f9cd17404a4ba9e5f7df72e3b48d: !Xenko.Rendering.Lights.LightDirectionalGroupRenderer,Xenko.Rendering {} + 411fdcfb9fc388449a0443173dfa3f27: !Xenko.Rendering.Lights.LightSkyboxRenderer,Xenko.Rendering {} + facdcd5b543cf1c6bdf2138aab6cc473: !Xenko.Rendering.Lights.LightClusteredPointSpotGroupRenderer,Xenko.Rendering {} + 79582329a9cf466e960f8920f579de9b: !Xenko.Rendering.Lights.LightPointGroupRenderer,Xenko.Rendering {} + cf0c6bd4198b4cc4aaaab5b54870bdfd: !Xenko.Rendering.Lights.LightSpotGroupRenderer,Xenko.Rendering {} + 451af18f3f5c4187cf3fe5f33feb46b1: !Xenko.Rendering.LightProbes.LightProbeRenderer,Xenko.Rendering {} + e658234519ffb99a3f45f76c2ac5a918*: !Xenko.Rendering.Voxels.VoxelGI.LightVoxelRenderer,Xenko.Voxels {} + ShadowMapRenderer: !Xenko.Rendering.Shadows.ShadowMapRenderer,Xenko.Rendering + Renderers: + 7c3d3d4c86834c3551bacde2527b3836: !Xenko.Rendering.Shadows.LightDirectionalShadowMapRenderer,Xenko.Rendering + ShadowCasterRenderStage: ref!! 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + 1c204b09435636256a3fcfd6f9ddb347: !Xenko.Rendering.Shadows.LightSpotShadowMapRenderer,Xenko.Rendering + ShadowCasterRenderStage: ref!! 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + 7c8c69ce27034b4c8bbcab0bcdfe954b: !Xenko.Rendering.Shadows.LightPointShadowMapRendererParaboloid,Xenko.Rendering + ShadowCasterRenderStage: ref!! 7cebf9d3-bf10-4e25-939e-e36c465efecf + d59ef45dd99e49d3af3887763d153aa7: !Xenko.Rendering.Shadows.LightPointShadowMapRendererCubeMap,Xenko.Rendering + ShadowCasterRenderStage: ref!! aeb202d1-2b31-4082-916c-1faee73ad2ad + 2731c76697c106b6878b9c989a1b6527*: !Xenko.Rendering.Voxels.VoxelRenderFeature,Xenko.Voxels {} + 28e9bf54a5adbe063f59fb17acb2723e: !Xenko.Rendering.Sprites.SpriteRenderFeature,Xenko.Rendering + RenderStageSelectors: + d74665cff080638a2439c4422e542d85: !Xenko.Rendering.Sprites.SpriteTransparentRenderStageSelector,Xenko.Rendering + OpaqueRenderStage: ref!! 4a600aa5-eda0-4861-a9b4-d200df85da1e + TransparentRenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + EffectName: Test + 60780391e205770513fdd53e07279a01: !Xenko.Rendering.Background.BackgroundRenderFeature,Xenko.Rendering + RenderStageSelectors: + 11c8b8ccb522e3cd1dd6688016062a6d: !Xenko.Rendering.SimpleGroupToRenderStageSelector,Xenko.Rendering + RenderStage: ref!! 4a600aa5-eda0-4861-a9b4-d200df85da1e + EffectName: Test + 93933ad00d0c357d4915ad462cbfd04c: !Xenko.Rendering.UI.UIRenderFeature,Xenko.UI + RenderStageSelectors: + 14a071694411235038a102ac3794bb4d: !Xenko.Rendering.SimpleGroupToRenderStageSelector,Xenko.Rendering + RenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + EffectName: Test + 9013eab3ea0ef6c98bf133b86c173d45: !Xenko.Particles.Rendering.ParticleEmitterRenderFeature,Xenko.Particles + RenderStageSelectors: + af1bd241305893ef8ff7952184e1cb0b: !Xenko.Particles.Rendering.ParticleEmitterTransparentRenderStageSelector,Xenko.Particles + OpaqueRenderStage: ref!! 4a600aa5-eda0-4861-a9b4-d200df85da1e + TransparentRenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + EffectName: null + PipelineProcessors: {} +SharedRenderers: + d5b2e71c088247e21556decdce138d96: !Xenko.Rendering.Compositing.ForwardRenderer,Xenko.Engine + Id: 9b1e5aa4-7a90-46b6-b05e-e1877d016a47 + Clear: + Id: 66a42307-1985-4316-871a-768449238c11 + Color: {R: 0.40491876, G: 0.411895424, B: 0.43775, A: 1.0} + LightProbes: true + OpaqueRenderStage: ref!! 4a600aa5-eda0-4861-a9b4-d200df85da1e + TransparentRenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + ShadowMapRenderStages: + 2323a99a8a983e182f318e55604659b0: ref!! 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + GBufferRenderStage: ref!! 259cf50a-634a-4ac6-846e-4f843be0a38f + PostEffects: null + LightShafts: null + VRSettings: + Enabled: false + RequiredApis: {} + Overlays: {} + SubsurfaceScatteringBlurEffect: null + MSAALevel: None + MSAAResolver: {} + 34ecb9b2633eacfc439ba8744fe05102: !PostProcessingEffects + Id: dbb783b1-cca8-44b3-8e10-48deaf86f59f + AmbientOcclusion: + Enabled: false + LocalReflections: + Enabled: false + ResolvePassResolution: Full + DepthResolution: Half + DepthOfField: + Enabled: false + DOFAreas: {X: 0.5, Y: 6.0, Z: 50.0, W: 200.0} + BrightFilter: + Color: {R: 1.0, G: 1.0, B: 1.0} + Bloom: + Distortion: {X: 1.0, Y: 1.0} + Afterimage: + Enabled: false + LightStreak: + Attenuation: 0.7 + LensFlare: {} + ColorTransforms: + Transforms: + 1e06f805f8b2e949a06c30d45fe413ef: !ToneMap + Operator: !ToneMapHejl2Operator {} + c57351444609d14ea258b3f511ec8a74: !FilmGrain + Enabled: false + e86e22e9a5d65545b8b55fca26e0afee: !Vignetting + Enabled: false + Color: {R: 0.0, G: 0.0, B: 0.0} + Antialiasing: !FXAAEffect {} + ee80a20a9bd99f2d70711114e15fe7ca: !Xenko.Rendering.Compositing.DebugRenderer,Xenko.Rendering + Id: 998158f8-004d-4a1d-b97d-c9f408967d94 + DebugRenderStages: {} + 1e613773efe82ecea16a632365e3dbf7*: !Xenko.Rendering.Voxels.ForwardRendererVoxels,Xenko.Voxels + Id: af83e982-9eed-45f6-be56-1df2674f9859 + Clear: + Id: cdb52f17-46cb-481e-8800-2f4d647bc6cd + Color: {R: 0.403921574, G: 0.4117647, B: 0.435294122, A: 1.0} + LightProbes: true + OpaqueRenderStage: ref!! 4a600aa5-eda0-4861-a9b4-d200df85da1e + TransparentRenderStage: ref!! 0d98fb34-5f41-4cc2-b2e2-a1081aae70c4 + ShadowMapRenderStages: + ddf97afe25e23f1680daedd5e5bd5eee: ref!! 5a47fa2e-0966-479a-8ebe-5d2c0dad2be5 + GBufferRenderStage: ref!! 259cf50a-634a-4ac6-846e-4f843be0a38f + PostEffects: !PostProcessingEffects ref!! dbb783b1-cca8-44b3-8e10-48deaf86f59f + LightShafts: null + VRSettings: + Enabled: false + RequiredApis: {} + Overlays: {} + SubsurfaceScatteringBlurEffect: null + MSAALevel: None + MSAAResolver: {} + VoxelRenderer: !Xenko.Rendering.Voxels.VoxelRenderer,Xenko.Voxels + VoxelStages: + ebc6da9e9cc380a03b62962f06cf721e: ref!! ffa492d9-b8a2-4d74-abe8-d82c542fc526 + 357b97f2667196c0f2740c021ab0a92e: ref!! ba28c12c-261f-45e6-bd4e-02cf38141f06 + VoxelVisualization: {} + 60459475d3a3adaf2d1ba5d99913ca75: ~(Deleted) +Game: !Xenko.Rendering.Compositing.SceneCameraRenderer,Xenko.Engine + Id: 76fe87cf-f574-4ad6-85b8-e9a9586be0e2 + Camera: ref!! 0ad0a331-55d2-4a3d-8909-05a4493a7d24 + Child: !Xenko.Rendering.Compositing.SceneRendererCollection,Xenko.Rendering + Id: 82568e46-92e7-421a-8dca-114a74e0cd69 + Children: + d39c5ddbf8b7d5ca02bafb6496b1cc3c*: !Xenko.Rendering.Voxels.ForwardRendererVoxels,Xenko.Voxels ref!! af83e982-9eed-45f6-be56-1df2674f9859 + 01d338078e9b21121ead0868932613dd: !Xenko.Rendering.Compositing.DebugRenderer,Xenko.Rendering ref!! 998158f8-004d-4a1d-b97d-c9f408967d94 + RenderMask: All +SingleView: !Xenko.Rendering.Compositing.ForwardRenderer,Xenko.Engine ref!! 9b1e5aa4-7a90-46b6-b05e-e1877d016a47 +Editor*: !Xenko.Rendering.Voxels.ForwardRendererVoxels,Xenko.Voxels ref!! af83e982-9eed-45f6-be56-1df2674f9859 +BlockPositions: {} From e79e97ccbfc5406963133bc6ed3e724434cbbd41 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 17 Feb 2020 11:56:44 -0500 Subject: [PATCH 0761/2038] Audio: more reliable recovery of music not playing --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 9eae150a20..cd1d17cf16 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -411,6 +411,7 @@ private static unsafe void Worker() } else if (AudioLayer.SourceIsPlaying(source.soundInstance.Source) == false) { + AudioLayer.SourceFlushBuffers(source.soundInstance.Source); AudioLayer.SourcePlay(source.soundInstance.Source); } } From 966f990819b83bf823620daab69c376774458505 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 17 Feb 2020 14:02:32 -0500 Subject: [PATCH 0762/2038] UI: more performance improvements --- sources/engine/Xenko.Graphics/UIBatch.cs | 64 ++++++++++++++++-------- 1 file changed, 42 insertions(+), 22 deletions(-) diff --git a/sources/engine/Xenko.Graphics/UIBatch.cs b/sources/engine/Xenko.Graphics/UIBatch.cs index 0848650b79..18a05daea2 100644 --- a/sources/engine/Xenko.Graphics/UIBatch.cs +++ b/sources/engine/Xenko.Graphics/UIBatch.cs @@ -634,35 +634,55 @@ private unsafe void CalculateRectangleVertices(UIImageDrawInfo* drawInfo, Vertex // set the two first line of vertices for (var r = 0; r < 2; r++) { - for (var c = 0; c < 2; c++) + // unroll this loop + // c = 0 + vertex->ColorScale = colorScale; + vertex->ColorAdd = colorAdd; + vertex->Swizzle = (int)drawInfo->Swizzle; + vertex->TextureCoordinate.X = tcx0; + vertex->TextureCoordinate.Y = r == 0 ? tcy0 : tcy1; + + vertex->Position.X = currentPosition.X; + vertex->Position.Y = currentPosition.Y; + vertex->Position.Z = currentPosition.Z - currentPosition.W * drawInfo->DepthBias * DepthBiasShiftOneUnit; + vertex->Position.W = currentPosition.W; + + if (drawInfo->SnapImage) { - vertex->ColorScale = colorScale; - vertex->ColorAdd = colorAdd; - vertex->Swizzle = (int)drawInfo->Swizzle; - vertex->TextureCoordinate.X = c == 0 ? tcx0 : tcx1; - vertex->TextureCoordinate.Y = r == 0 ? tcy0 : tcy1; + var backBufferHalfWidth = GraphicsContext.CommandList.RenderTarget.ViewWidth / 2; + var backBufferHalfHeight = GraphicsContext.CommandList.RenderTarget.ViewHeight / 2; + vertex->Position.X = (float)(Math.Round(vertex->Position.X * backBufferHalfWidth) / backBufferHalfWidth); + vertex->Position.Y = (float)(Math.Round(vertex->Position.Y * backBufferHalfHeight) / backBufferHalfHeight); + } - vertex->Position.X = currentPosition.X; - vertex->Position.Y = currentPosition.Y; - vertex->Position.Z = currentPosition.Z - currentPosition.W * drawInfo->DepthBias * DepthBiasShiftOneUnit; - vertex->Position.W = currentPosition.W; + vertex++; - if (drawInfo->SnapImage) - { - var backBufferHalfWidth = GraphicsContext.CommandList.RenderTarget.ViewWidth / 2; - var backBufferHalfHeight = GraphicsContext.CommandList.RenderTarget.ViewHeight / 2; - vertex->Position.X = (float)(Math.Round(vertex->Position.X * backBufferHalfWidth) / backBufferHalfWidth); - vertex->Position.Y = (float)(Math.Round(vertex->Position.Y * backBufferHalfHeight) / backBufferHalfHeight); - } + Vector4.Add(ref currentPosition, ref drawInfo->UnitXWorld, out currentPosition); - vertex++; + // c = 1 + vertex->ColorScale = colorScale; + vertex->ColorAdd = colorAdd; + vertex->Swizzle = (int)drawInfo->Swizzle; + vertex->TextureCoordinate.X = tcx1; + vertex->TextureCoordinate.Y = r == 0 ? tcy0 : tcy1; - if (c == 0) - Vector4.Add(ref currentPosition, ref drawInfo->UnitXWorld, out currentPosition); - else - Vector4.Subtract(ref currentPosition, ref drawInfo->UnitXWorld, out currentPosition); + vertex->Position.X = currentPosition.X; + vertex->Position.Y = currentPosition.Y; + vertex->Position.Z = currentPosition.Z - currentPosition.W * drawInfo->DepthBias * DepthBiasShiftOneUnit; + vertex->Position.W = currentPosition.W; + + if (drawInfo->SnapImage) + { + var backBufferHalfWidth = GraphicsContext.CommandList.RenderTarget.ViewWidth / 2; + var backBufferHalfHeight = GraphicsContext.CommandList.RenderTarget.ViewHeight / 2; + vertex->Position.X = (float)(Math.Round(vertex->Position.X * backBufferHalfWidth) / backBufferHalfWidth); + vertex->Position.Y = (float)(Math.Round(vertex->Position.Y * backBufferHalfHeight) / backBufferHalfHeight); } + vertex++; + + Vector4.Subtract(ref currentPosition, ref drawInfo->UnitXWorld, out currentPosition); + Vector4.Add(ref currentPosition, ref drawInfo->UnitYWorld, out currentPosition); } } From 4c64a1f833f2b798d9ca4d0ca94b1cd8fec2677e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 17 Feb 2020 15:51:32 -0500 Subject: [PATCH 0763/2038] Audio: if playing something central that was positional, set position to listener position --- sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index b6149ef847..1fe98de8b6 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -38,6 +38,7 @@ public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; + if (s.IsSpatialized) s.Apply3D(Listener.Listener.Position); s.Play(); } return s; From b1605a0c6226e2f80f6619b51cacf9da1eea80a3 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 17 Feb 2020 15:52:02 -0500 Subject: [PATCH 0764/2038] Audio: hopefully done assuring music plays if stopped for some reason --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index cd1d17cf16..1cdfbb3b14 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -411,7 +411,11 @@ private static unsafe void Worker() } else if (AudioLayer.SourceIsPlaying(source.soundInstance.Source) == false) { + // get music playing again + AudioLayer.SourceStop(source.soundInstance.Source); AudioLayer.SourceFlushBuffers(source.soundInstance.Source); + source.PrepareInternal(); + if (source.CanFill) source.ExtractAndFillData(); AudioLayer.SourcePlay(source.soundInstance.Source); } } From bcc3942a4671781493a81ab64ac3fc350046a2e2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 17 Feb 2020 17:09:48 -0500 Subject: [PATCH 0765/2038] Audio: this may work better for audio restarting --- sources/engine/Xenko.Audio/DynamicSoundSource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 1cdfbb3b14..67a18f9d38 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -414,7 +414,7 @@ private static unsafe void Worker() // get music playing again AudioLayer.SourceStop(source.soundInstance.Source); AudioLayer.SourceFlushBuffers(source.soundInstance.Source); - source.PrepareInternal(); + source.RestartInternal(); if (source.CanFill) source.ExtractAndFillData(); AudioLayer.SourcePlay(source.soundInstance.Source); } From b9f9f905243cb66c5008df8486091f0807dd6a6c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 17 Feb 2020 17:40:21 -0500 Subject: [PATCH 0766/2038] UI: Make sure fullscreen UI draws over stuff in the scene --- sources/engine/Xenko.UI/Rendering/UI/UIRenderProcessor.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderProcessor.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderProcessor.cs index 334860c9bc..a856f8f433 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderProcessor.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderProcessor.cs @@ -44,7 +44,7 @@ public override void Draw(RenderContext gameTime) renderUIElement.WorldMatrix = uiComponent.Entity.Transform.WorldMatrix; renderUIElement.RenderGroup = uiComponent.RenderGroup; - renderUIElement.DistanceSortFudge = uiComponent.DistanceSortFudge; + renderUIElement.DistanceSortFudge = uiComponent.IsFullScreen ? -10000f : uiComponent.DistanceSortFudge; renderUIElement.Page = uiComponent.Page; renderUIElement.IsFullScreen = uiComponent.IsFullScreen; From f94305e07e67a85243624c733a5c07fcfc56d46e Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Tue, 18 Feb 2020 07:39:12 +0900 Subject: [PATCH 0767/2038] Merge pull request #610 from makotech222/master Fix WPF resource dictionary errors. --- .../TableflowView.ExpressionDark.normalcolor.xaml | 4 +--- .../Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/sources/editor/Xenko.Core.Assets.Editor/Themes/ExpressionDark/TableflowView.ExpressionDark.normalcolor.xaml b/sources/editor/Xenko.Core.Assets.Editor/Themes/ExpressionDark/TableflowView.ExpressionDark.normalcolor.xaml index 46f6779cbd..0007c1280d 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Themes/ExpressionDark/TableflowView.ExpressionDark.normalcolor.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/Themes/ExpressionDark/TableflowView.ExpressionDark.normalcolor.xaml @@ -22,9 +22,7 @@ - - - + diff --git a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj index 69c6238a5d..0783d8d1a6 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj +++ b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj @@ -45,6 +45,7 @@ + From 3b348d239bfe1df8f29d95cf055d3fd6dcf5296f Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 18:58:22 +1300 Subject: [PATCH 0768/2038] [Engine] UpdateKey & EdgeKeyAEN structs to implement IEquatable to avoid boxing due to usage as Dictionary key --- .../Xenko.Engine/Updater/UpdateEngine.cs | 23 ++++++++++++++++++- .../Extensions/IndexExtensions.cs | 13 ++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs b/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs index 01df3b3240..ed0f522d56 100644 --- a/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs +++ b/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs @@ -723,7 +723,7 @@ private struct Blittable16 /// /// Internally used as key to register members. /// - private struct UpdateKey + private struct UpdateKey : IEquatable { public readonly Type Owner; public readonly string Name; @@ -738,6 +738,27 @@ public override string ToString() { return $"{Owner.Name}.{Name}"; } + + public bool Equals(UpdateKey other) + { + return Owner == other.Owner && Name == other.Name; + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + return obj is UpdateKey && Equals((UpdateKey)obj); + } + + public override int GetHashCode() + { + unchecked + { + int hashCode = Owner.GetHashCode(); + hashCode = (hashCode * 397) ^ Name.GetHashCode(); + return hashCode; + } + } } /// diff --git a/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs b/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs index 3b931c2585..db35dd044d 100644 --- a/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs +++ b/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs @@ -293,7 +293,7 @@ public static unsafe void GenerateIndexBufferAEN(this MeshDraw meshData) meshData.PrimitiveType = PrimitiveType.PatchList.ControlPointCount(12); } - private struct EdgeKeyAEN + private struct EdgeKeyAEN : IEquatable { public readonly int PositionIndex0; public readonly int PositionIndex1; @@ -309,6 +309,17 @@ public EdgeKeyAEN(EdgeAEN edge) { } + public bool Equals(EdgeKeyAEN other) + { + return PositionIndex0 == other.PositionIndex0 && PositionIndex1 == other.PositionIndex1; + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + return obj is EdgeKeyAEN && Equals((EdgeKeyAEN)obj); + } + public override int GetHashCode() { unchecked From 3d37b6befa2eb0f4d6db4c1730a55f0492d76879 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 18:59:23 +1300 Subject: [PATCH 0769/2038] [Graphics] Avoid unnecessary IntPtr boxing for equality test since it doesn't implement IEquatable --- sources/engine/Xenko/Graphics/DataBox.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko/Graphics/DataBox.cs b/sources/engine/Xenko/Graphics/DataBox.cs index 383113ae95..75ea0d37d2 100644 --- a/sources/engine/Xenko/Graphics/DataBox.cs +++ b/sources/engine/Xenko/Graphics/DataBox.cs @@ -102,7 +102,7 @@ public override int GetHashCode() private bool EqualsByRef(ref DataBox other) { - return DataPointer.Equals(other.DataPointer) && RowPitch == other.RowPitch && SlicePitch == other.SlicePitch; + return DataPointer == other.DataPointer && RowPitch == other.RowPitch && SlicePitch == other.SlicePitch; } } } From dcd38819d421d4f12c927e80bfde132565f7a58f Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 19:11:25 +1300 Subject: [PATCH 0770/2038] [Core] Add concrete classes for list comparisons to avoid enumerator object allocation. These are used by ShaderMixinSource --- sources/core/Xenko.Core/Utilities.cs | 61 ++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/sources/core/Xenko.Core/Utilities.cs b/sources/core/Xenko.Core/Utilities.cs index c6fa495fc4..2181b3d676 100644 --- a/sources/core/Xenko.Core/Utilities.cs +++ b/sources/core/Xenko.Core/Utilities.cs @@ -651,6 +651,31 @@ public static bool Compare(IDictionary first, IDicti return second.Keys.All(first.ContainsKey); } + /// + /// Compares two collection, element by elements. + /// + /// The collection to compare from. + /// The colllection to compare to. + /// True if lists are identical (but not necessarily in the same order). False otherwise. + /// Concrete SortedList is favored over interface to avoid enumerator object allocation. + public static bool Compare(Collections.SortedList first, Collections.SortedList second) + { + if (ReferenceEquals(first, second)) return true; + if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) return false; + if (first.Count != second.Count) return false; + + var comparer = EqualityComparer.Default; + + foreach (var keyValue in first) + { + TValue secondValue; + if (!second.TryGetValue(keyValue.Key, out secondValue)) return false; + if (!comparer.Equals(keyValue.Value, secondValue)) return false; + } + + return true; + } + public static bool Compare(T[] left, T[] right) { if (ReferenceEquals(left, right)) @@ -706,6 +731,42 @@ public static bool Compare(ICollection left, ICollection right) return true; } + /// + /// Compares two list, element by elements. + /// + /// The list to compare from. + /// The colllection to compare to. + /// True if lists are sequentially equal. False otherwise. + /// Concrete List is favored over interface to avoid enumerator object allocation. + public static bool Compare(List left, List right) + { + if (ReferenceEquals(left, right)) + return true; + if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) + return false; + + if (left.Count != right.Count) + return false; + + var count = 0; + var leftIt = left.GetEnumerator(); + var rightIt = right.GetEnumerator(); + var comparer = EqualityComparer.Default; + while (leftIt.MoveNext() && rightIt.MoveNext()) + { + if (!comparer.Equals(leftIt.Current, rightIt.Current)) + return false; + count++; + } + + // Just double check to make sure that the iterator actually returns + // the exact number of elements + if (count != left.Count) + return false; + + return true; + } + /// /// Swaps the value between two references. /// From febbc29096147d39baae9f08346c1d948c822e65 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 19:12:10 +1300 Subject: [PATCH 0771/2038] [Rendering] Avoid value type boxing when value was already found equal in ParameterCollection --- sources/engine/Xenko/Rendering/ParameterCollection.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko/Rendering/ParameterCollection.cs b/sources/engine/Xenko/Rendering/ParameterCollection.cs index f320fd7189..299c0b488c 100644 --- a/sources/engine/Xenko/Rendering/ParameterCollection.cs +++ b/sources/engine/Xenko/Rendering/ParameterCollection.cs @@ -377,10 +377,17 @@ public void Set(ValueParameter parameter, int count, ref T firstValue) whe /// public void Set(PermutationParameter parameter, T value) { - if (!EqualityComparer.Default.Equals((T)ObjectValues[parameter.BindingSlot], value)) + bool isSame = EqualityComparer.Default.Equals((T)ObjectValues[parameter.BindingSlot], value); + if (!isSame) + { PermutationCounter++; + } - ObjectValues[parameter.BindingSlot] = value; + // For value types, we don't assign again because this causes boxing. + if (!typeof(T).IsValueType || !isSame) + { + ObjectValues[parameter.BindingSlot] = value; + } } /// From 40328dc392883fe47590752a574b34334c39f765 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 19:12:43 +1300 Subject: [PATCH 0772/2038] [Rendering] Fix mesh regeneration logic when material has multiple passes --- .../engine/Xenko.Engine/Rendering/ModelRenderProcessor.cs | 3 ++- sources/engine/Xenko.Rendering/Rendering/RenderModel.cs | 8 +++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Engine/Rendering/ModelRenderProcessor.cs b/sources/engine/Xenko.Engine/Rendering/ModelRenderProcessor.cs index 1545cc0c93..f7aa4bdcbd 100644 --- a/sources/engine/Xenko.Engine/Rendering/ModelRenderProcessor.cs +++ b/sources/engine/Xenko.Engine/Rendering/ModelRenderProcessor.cs @@ -148,7 +148,7 @@ private void CheckMeshes(ModelComponent modelComponent, RenderModel renderModel) if (model != null) { // Number of meshes changed in the model? - if (model.Meshes.Count != renderModel.Meshes.Length) + if (model.Meshes.Count != renderModel.UniqueMeshCount) goto RegenerateMeshes; if (modelComponent.Enabled) @@ -236,6 +236,7 @@ private void CheckMeshes(ModelComponent modelComponent, RenderModel renderModel) } renderModel.Meshes = renderMeshes; + renderModel.UniqueMeshCount = model.Meshes.Count; // Update before first add so that RenderGroup is properly set UpdateRenderModel(modelComponent, renderModel); diff --git a/sources/engine/Xenko.Rendering/Rendering/RenderModel.cs b/sources/engine/Xenko.Rendering/Rendering/RenderModel.cs index 5bf2ad0142..7587b67d73 100644 --- a/sources/engine/Xenko.Rendering/Rendering/RenderModel.cs +++ b/sources/engine/Xenko.Rendering/Rendering/RenderModel.cs @@ -12,9 +12,15 @@ public class RenderModel { public Model Model; public RenderMesh[] Meshes; + /// + /// The number of es when was generated. + /// + /// + /// A single mesh may be split into multiple RenderMeshes due to multiple material passes. + /// + public int UniqueMeshCount; public MaterialInfo[] Materials; - public struct MaterialInfo { public Material Material; From 1b6cc7cfb07413c629c591b0ffde4ae810238490 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 22:43:21 +1300 Subject: [PATCH 0773/2038] [Engine] Simplify Equals(object) logic in UpdateKey & EdgeKeyAEN structs. --- sources/engine/Xenko.Engine/Updater/UpdateEngine.cs | 3 +-- sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs b/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs index ed0f522d56..b8c48b8a86 100644 --- a/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs +++ b/sources/engine/Xenko.Engine/Updater/UpdateEngine.cs @@ -746,8 +746,7 @@ public bool Equals(UpdateKey other) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - return obj is UpdateKey && Equals((UpdateKey)obj); + return obj is UpdateKey key && Equals(key); } public override int GetHashCode() diff --git a/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs b/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs index db35dd044d..10f2a564ca 100644 --- a/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs +++ b/sources/engine/Xenko.Rendering/Extensions/IndexExtensions.cs @@ -316,8 +316,7 @@ public bool Equals(EdgeKeyAEN other) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; - return obj is EdgeKeyAEN && Equals((EdgeKeyAEN)obj); + return obj is EdgeKeyAEN key && Equals(key); } public override int GetHashCode() From f4459496f870f444e714ca9449ecd9689f725e9f Mon Sep 17 00:00:00 2001 From: Basewq Date: Sun, 16 Feb 2020 12:25:13 +1300 Subject: [PATCH 0774/2038] [Core] List comparison can use for loop instead of iterator --- sources/core/Xenko.Core/Utilities.cs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/sources/core/Xenko.Core/Utilities.cs b/sources/core/Xenko.Core/Utilities.cs index 2181b3d676..923a1749ea 100644 --- a/sources/core/Xenko.Core/Utilities.cs +++ b/sources/core/Xenko.Core/Utilities.cs @@ -748,22 +748,13 @@ public static bool Compare(List left, List right) if (left.Count != right.Count) return false; - var count = 0; - var leftIt = left.GetEnumerator(); - var rightIt = right.GetEnumerator(); var comparer = EqualityComparer.Default; - while (leftIt.MoveNext() && rightIt.MoveNext()) + for (int i = 0; i < left.Count; i ++) { - if (!comparer.Equals(leftIt.Current, rightIt.Current)) + if (!comparer.Equals(left[i], right[i])) return false; - count++; } - // Just double check to make sure that the iterator actually returns - // the exact number of elements - if (count != left.Count) - return false; - return true; } From ab85857464b1c10e0db388cb452af502a7536497 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 18 Feb 2020 17:52:00 -0500 Subject: [PATCH 0775/2038] VR: fix swapping hands and UI interaction --- .../engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs index c98f6a318b..22e4df6a67 100644 --- a/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs +++ b/sources/engine/Xenko.UI/Rendering/UI/UIRenderFeature.Picking.cs @@ -244,7 +244,8 @@ private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, Re { for (int i=0; i<2; i++) { - TransformComponent useHand = (VirtualReality.VRDeviceSystem.GetSystem.GetControllerSwapped ? (i ^ 1): i) == 0 ? + int swappedIndex = VirtualReality.VRDeviceSystem.GetSystem.GetControllerSwapped ? (i ^ 1) : i; + TransformComponent useHand = swappedIndex == 0 ? (TransformComponent.OverrideRightHandUIPointer ?? TransformComponent.LastRightHandTracked) : (TransformComponent.OverrideLeftHandUIPointer ?? TransformComponent.LastLeftHandTracked); @@ -257,8 +258,7 @@ private bool UpdateMouseOver(ref Viewport viewport, ref Matrix worldViewProj, Re if (UIElementUnderMouseCursor != null) { // wait, are we selecting this element? - // GetController already checks GetControllerSwapped - VirtualReality.TouchController tc = VirtualReality.VRDeviceSystem.GetSystem.GetController(i == 0 ? VirtualReality.TouchControllerHand.Right : VirtualReality.TouchControllerHand.Left); + VirtualReality.TouchController tc = VirtualReality.VRDeviceSystem.GetSystem.GetController(swappedIndex == 0 ? VirtualReality.TouchControllerHand.Right : VirtualReality.TouchControllerHand.Left); if (tc != null) { From 03df19791842d0d5824ec127d4c87aa6a4001376 Mon Sep 17 00:00:00 2001 From: Basewq Date: Wed, 19 Feb 2020 19:39:03 +1300 Subject: [PATCH 0776/2038] [Engine] Fix Matrix.Multiply usage in TransformComponent due to quirk --- sources/engine/Xenko.Engine/Engine/TransformComponent.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Engine/Engine/TransformComponent.cs b/sources/engine/Xenko.Engine/Engine/TransformComponent.cs index a6be9dbc56..84f36ce392 100644 --- a/sources/engine/Xenko.Engine/Engine/TransformComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/TransformComponent.cs @@ -429,7 +429,8 @@ internal void UpdateWorldMatrixInternal(bool recursive) scene.UpdateWorldMatrix(); } - Matrix.Multiply(ref WorldMatrix, ref scene.WorldMatrix, out WorldMatrix); + var curWorldMatrix = WorldMatrix; // Must make a copy to use as the ref parameter, otherwise matrix will not be calculated correctly + Matrix.Multiply(ref curWorldMatrix, ref scene.WorldMatrix, out WorldMatrix); } } From 931b782211f1dedf60191fdcec0b8b5716e3e0f5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 19 Feb 2020 15:20:38 -0500 Subject: [PATCH 0777/2038] Memory: allocation reductions across lighting, UI and physics processing --- .../Threading/ConcurrentCollector.cs | 14 +++- sources/engine/Xenko.Graphics/SpriteFont.cs | 7 +- .../Bepu/BepuRigidbodyComponent.cs | 64 ++++++++--------- .../Xenko.Physics/Bepu/BepuSimulation.cs | 37 +++++----- sources/engine/Xenko.Physics/PhysicsSystem.cs | 2 +- .../LightClusteredPointSpotGroupRenderer.cs | 69 +++++-------------- .../Controls/EditText.Direct.Default.cs | 8 ++- 7 files changed, 93 insertions(+), 108 deletions(-) diff --git a/sources/core/Xenko.Core/Threading/ConcurrentCollector.cs b/sources/core/Xenko.Core/Threading/ConcurrentCollector.cs index a828e84120..7196e0407c 100644 --- a/sources/core/Xenko.Core/Threading/ConcurrentCollector.cs +++ b/sources/core/Xenko.Core/Threading/ConcurrentCollector.cs @@ -5,6 +5,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Threading; using Xenko.Core.Annotations; @@ -85,11 +86,9 @@ public ConcurrentCollector(int capacity = DefaultCapacity) public T[] Items { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { - if (head != tail) - throw new InvalidOperationException(); - return head.Items; } } @@ -117,6 +116,7 @@ public void Close() } } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Add(T item) { var index = Interlocked.Increment(ref count) - 1; @@ -208,6 +208,12 @@ public void Clear(bool fastClear) count = 0; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public void UnsafeClear() + { + count = 0; + } + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); @@ -227,10 +233,12 @@ public Enumerator GetEnumerator() public T this[int index] { + [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Items[index]; } + [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Items[index] = value; diff --git a/sources/engine/Xenko.Graphics/SpriteFont.cs b/sources/engine/Xenko.Graphics/SpriteFont.cs index 304cef963a..4b660d537a 100644 --- a/sources/engine/Xenko.Graphics/SpriteFont.cs +++ b/sources/engine/Xenko.Graphics/SpriteFont.cs @@ -798,7 +798,12 @@ internal struct StringProxy public int LineCount { get { - if (linecount == -1 && textString != null) linecount = textString.Split('\n').Length; + if (linecount == -1 && textString != null) + { + linecount = textString.Length > 0 ? 1 : 0; + for (int i = 0; i < textString.Length; i++) + if (textString[i] == '\n') linecount++; + } return linecount; } } diff --git a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs index 62a9ee2ddd..ee8c687b1f 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuRigidbodyComponent.cs @@ -124,7 +124,23 @@ public float CcdMotionThreshold /// If we are collecting collisions, how many to store before we stop storing them? Defaults to 32. Prevents crazy counts when objects are heavily overlapping. /// [DataMember] - public int CollectCollisionMaximumCount = 32; + public int CollectCollisionMaximumCount + { + get + { + return CurrentPhysicalContacts == null ? 0 : CurrentPhysicalContacts.Length; + } + set + { + if (value <= 0) + { + CurrentPhysicalContacts = null; + return; + } + + CurrentPhysicalContacts = new BepuContact[value]; + } + } /// /// Gets or sets if this element will store collisions in CurrentPhysicalContacts. Uses less CPU than ProcessCollisions @@ -149,57 +165,37 @@ public bool CollectCollisions if (value) { - if (processingPhysicalContacts == null) - processingPhysicalContacts = new ConcurrentQueue(); + if (CurrentPhysicalContacts == null) + CurrentPhysicalContacts = new BepuContact[32]; } else { - processingPhysicalContacts = null; - currentContactList = null; + CurrentPhysicalContacts = null; } _collectCollisions = value; } } - /// - /// If we are storing collisions, which one is the strongest one? This uses normals and velocity to determine. - /// - [DataMemberIgnore] - public int StrongestCollisionIndex; - [DataMemberIgnore] private bool _collectCollisions = false; - /// - /// If we are using ProcessCollisionSlim, this list will maintain all current collisions - /// - [DataMemberIgnore] - public List CurrentContacts => currentContactList; - - internal void swapProcessingContactsList() + internal void resetProcessingContactsList() { - if (processingPhysicalContacts == null || IsActive == false) return; - - List buildList = new List(processingPhysicalContacts.Count); - - while (processingPhysicalContacts.TryDequeue(out BepuContact res)) - { - if (res.A != null && res.B != null) - { - if (res.A != this) res.Swap(); - buildList.Add(res); - } - } + if (CurrentPhysicalContacts == null || IsActive == false) return; - currentContactList = buildList; + CurrentPhysicalContactsCount = Math.Min(CurrentPhysicalContacts.Length, processingPhysicalContactCount); + processingPhysicalContactCount = 0; } [DataMemberIgnore] - internal ConcurrentQueue processingPhysicalContacts; - + public BepuContact[] CurrentPhysicalContacts; + + [DataMemberIgnore] + public int CurrentPhysicalContactsCount; + [DataMemberIgnore] - internal List currentContactList; + internal int processingPhysicalContactCount; private static readonly BodyInertia KinematicInertia = new BodyInertia() { diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index cfc6b3662b..28e742d7d8 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -225,20 +225,28 @@ public void RecordContact(BepuPhysicsComponent A, BepuPhysicsComponen BepuRigidbodyComponent ar = (A as BepuRigidbodyComponent); BepuRigidbodyComponent br = (B as BepuRigidbodyComponent); - bool Acollect = ar == null ? false : ar.CollectCollisions && ar.CollectCollisionMaximumCount > ar.processingPhysicalContacts.Count; - bool Bcollect = br == null ? false : br.CollectCollisions && br.CollectCollisionMaximumCount > br.processingPhysicalContacts.Count; // do we want to store this collision? - if (Acollect || Bcollect) + if ((ar?.CollectCollisions ?? false)) { - BepuContact bc = new BepuContact() + int index = Interlocked.Increment(ref ar.processingPhysicalContactCount) - 1; + if (index < ar.CurrentPhysicalContacts.Length) { - A = A, - B = B, - Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()), - Offset = BepuHelpers.ToXenko(manifold.SimpleGetOffset()) - }; - if (Acollect) ar.processingPhysicalContacts.Enqueue(bc); - if (Bcollect) br.processingPhysicalContacts.Enqueue(bc); + ar.CurrentPhysicalContacts[index].A = A; + ar.CurrentPhysicalContacts[index].B = B; + ar.CurrentPhysicalContacts[index].Normal = BepuHelpers.ToXenko(manifold.SimpleGetNormal()); + ar.CurrentPhysicalContacts[index].Offset = BepuHelpers.ToXenko(manifold.SimpleGetOffset()); + } + } + if ((br?.CollectCollisions ?? false)) + { + int index = Interlocked.Increment(ref br.processingPhysicalContactCount) - 1; + if (index < br.CurrentPhysicalContacts.Length) + { + br.CurrentPhysicalContacts[index].A = B; + br.CurrentPhysicalContacts[index].B = A; + br.CurrentPhysicalContacts[index].Normal = -BepuHelpers.ToXenko(manifold.SimpleGetNormal()); + br.CurrentPhysicalContacts[index].Offset = B.Position - (A.Position + BepuHelpers.ToXenko(manifold.SimpleGetOffset())); + } } } @@ -470,11 +478,8 @@ internal void ProcessRemovals() AllRigidbodies.Remove(rigidBody); } - if (rigidBody.processingPhysicalContacts != null) - while(rigidBody.processingPhysicalContacts.TryDequeue(out var _)); - - if (rigidBody.currentContactList != null) - rigidBody.currentContactList.Clear(); + rigidBody.processingPhysicalContactCount = 0; + rigidBody.CurrentPhysicalContactsCount = 0; } } ToBeRemoved.Clear(); diff --git a/sources/engine/Xenko.Physics/PhysicsSystem.cs b/sources/engine/Xenko.Physics/PhysicsSystem.cs index b470708f2a..205e6c9d49 100644 --- a/sources/engine/Xenko.Physics/PhysicsSystem.cs +++ b/sources/engine/Xenko.Physics/PhysicsSystem.cs @@ -206,7 +206,7 @@ private void RunPhysicsSimulation(float time) { BepuRigidbodyComponent rb = physicsScene.BepuSimulation.AllRigidbodies[j]; - rb.swapProcessingContactsList(); + rb.resetProcessingContactsList(); rb.UpdateCachedPoseAndVelocity(); // per-rigidbody update diff --git a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs index ac6fd85bb5..300795390e 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Lights/LightClusteredPointSpotGroupRenderer.cs @@ -153,12 +153,6 @@ public override void UpdateShaderPermutationEntry(ForwardLightingRenderFeature.L shaderEntry.DirectLightGroups.Add(spotGroup); } - private enum InternalLightType - { - Point, - Spot, - } - internal class PointLightShaderGroupData : LightShaderGroupDynamic { private readonly LightClusteredPointSpotGroupRenderer clusteredGroupRenderer; @@ -169,7 +163,7 @@ internal class PointLightShaderGroupData : LightShaderGroupDynamic // Artifically increase range of first slice to not waste too much slices in very short area public float SpecialNearPlane = 2.0f; - private ConcurrentQueue[] lightNodes; + private ConcurrentCollector[] lightNodes; private RenderViewInfo[] renderViewInfos; private Int2 maxClusterCount; //private Plane[] zPlanes; @@ -302,9 +296,9 @@ public void ComputeViewParameter(int viewIndex) // make sure we have enough lists if (lightNodes == null || lightNodes.Length < totalClusterCount) { - lightNodes = new ConcurrentQueue[totalClusterCount]; + lightNodes = new ConcurrentCollector[totalClusterCount]; for (int i = 0; i < totalClusterCount; i++) - lightNodes[i] = new ConcurrentQueue(); + lightNodes[i] = new ConcurrentCollector(128); } int totalLights = 0; @@ -362,7 +356,7 @@ public void ComputeViewParameter(int viewIndex) var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); - var myNode = new LightClusterLinkedNode(InternalLightType.Point, lightIndex); + int myNode = lightIndex << 1; for (int z = tileStartZ; z < tileEndZ; ++z) { @@ -379,7 +373,7 @@ public void ComputeViewParameter(int viewIndex) { for (int x = tileStartX; x < tileEndX; ++x) { - lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(myNode); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Add(myNode); } } } @@ -436,7 +430,7 @@ public void ComputeViewParameter(int viewIndex) var tileStartZ = MathUtil.Clamp((int)Math.Log(startZ * clusterDepthScale + clusterDepthBias, 2.0f), 0, ClusterSlices); var tileEndZ = MathUtil.Clamp((int)Math.Log(endZ * clusterDepthScale + clusterDepthBias, 2.0f) + 1, 0, ClusterSlices); - var myNode = new LightClusterLinkedNode(InternalLightType.Spot, lightIndex); + var myNode = 1 | (lightIndex << 1); for (int z = tileStartZ; z < tileEndZ; ++z) { @@ -444,7 +438,7 @@ public void ComputeViewParameter(int viewIndex) { for (int x = tileStartX; x < tileEndX; ++x) { - lightNodes[x + (y + z * clusterCountY) * clusterCountX].Enqueue(myNode); + lightNodes[x + (y + z * clusterCountY) * clusterCountX].Add(myNode); } } } @@ -469,28 +463,32 @@ public void ComputeViewParameter(int viewIndex) continue; } + lnds.Close(); + // Build light indices int pointLightCounter = 0; int spotLightCounter = 0; int indexStart = clusterIndex * totalLights; - int i = 0; - while(lnds.TryDequeue(out var cluster)) + for (int i=0; i> 1); + + switch (cluster & 1) { - case InternalLightType.Point: + case 0: pointLightCounter++; break; - case InternalLightType.Spot: + case 1: spotLightCounter++; break; } } + lnds.UnsafeClear(); + // Add new light cluster range // Stored in the format: // x = start_index @@ -725,37 +723,6 @@ private static void ComputeClipRegion(Vector3 lightPosView, float lightRadius, r UpdateClipRegion(lightPosView.Y, -lightPosView.Z, lightRadius, projection.M22, projection.M32, ref clipMin.Y, ref clipMax.Y); } - // Single linked list of lights (stored in an array) - private struct LightClusterLinkedNode : IEquatable - { - public InternalLightType LightType; - public int LightIndex; - - public LightClusterLinkedNode(InternalLightType lightType, int lightIndex) - { - LightType = lightType; - LightIndex = lightIndex; - } - - public bool Equals(LightClusterLinkedNode other) - { - return LightType == other.LightType && LightIndex == other.LightIndex; - } - - public override bool Equals(object obj) - { - return obj != null && obj is LightClusterLinkedNode && Equals((LightClusterLinkedNode)obj); - } - - public override int GetHashCode() - { - unchecked - { - return (int)LightType ^ (LightIndex * 397); - } - } - } - private struct RenderViewInfo { public RenderView RenderView; diff --git a/sources/engine/Xenko.UI/Controls/EditText.Direct.Default.cs b/sources/engine/Xenko.UI/Controls/EditText.Direct.Default.cs index 89fedffd39..c93bda71ea 100644 --- a/sources/engine/Xenko.UI/Controls/EditText.Direct.Default.cs +++ b/sources/engine/Xenko.UI/Controls/EditText.Direct.Default.cs @@ -1,4 +1,4 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. #if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX @@ -20,7 +20,11 @@ private int GetLineCountImpl() if (Font == null) return 1; - return text.Split('\n').Length; + int cnt = text.Length > 0 ? 1 : 0; + for (int i = 0; i < text.Length; i++) + if (text[i] == '\n') cnt++; + + return cnt; } private void OnMaxLinesChangedImpl() From f898bc1a2efb001e2277d1cca1b3f944af5ade2b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 19 Feb 2020 15:21:32 -0500 Subject: [PATCH 0778/2038] Version bump to 3.5.5 --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 72c56d9e9d..1d39350464 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.4"; + public const string VersionToShowInEditor = "3.5.5"; /// /// The current assembly version as text, currently same as . From d2f4d4f2da8fb530cc1f7fe128e4c7e5339a851e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 19 Feb 2020 18:51:01 -0500 Subject: [PATCH 0779/2038] Physics: fix initial positioning with offset rigidbody --- sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs index 28e742d7d8..8568de3f64 100644 --- a/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs +++ b/sources/engine/Xenko.Physics/Bepu/BepuSimulation.cs @@ -446,7 +446,7 @@ internal void ProcessAdds() rigidBody.AddedHandle = internalSimulation.Bodies.Add(rigidBody.bodyDescription); RigidMappings[rigidBody.AddedHandle] = rigidBody; } - component.Position = component.Entity.Transform.WorldPosition(); + component.Position = component.Entity.Transform.WorldPosition() - (rigidBody.LocalPhysicsOffset ?? Vector3.Zero); component.Rotation = component.Entity.Transform.WorldRotation(); } } From 8d070472e6a1c52deebe3c7606ca40ca2cf5173d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 20 Feb 2020 11:18:13 -0500 Subject: [PATCH 0780/2038] Linux: don't crash on trying to lock a file --- sources/core/Xenko.Core.IO/NativeLockFile.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/sources/core/Xenko.Core.IO/NativeLockFile.cs b/sources/core/Xenko.Core.IO/NativeLockFile.cs index c0ab13299e..03e8aff0e2 100644 --- a/sources/core/Xenko.Core.IO/NativeLockFile.cs +++ b/sources/core/Xenko.Core.IO/NativeLockFile.cs @@ -48,6 +48,10 @@ public static void LockFile(FileStream fileStream, long offset, long count, bool throw new IOException("Couldn't lock file."); } #else + // some OSes can't lock a file that can't be written too + // (looking at you, Linux) + if (fileStream.CanWrite == false) return; + bool tryAgain; do { @@ -89,6 +93,10 @@ public static void UnlockFile(FileStream fileStream, long offset, long count) throw new IOException("Couldn't unlock file."); } #else + // some OSes can't (un)lock a file that can't be written too + // (looking at you, Linux) + if (fileStream.CanWrite == false) return; + fileStream.Unlock(offset, count); #endif } From afb6b8395a2c823d3b213937ee976982f4997481 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 20 Feb 2020 14:50:47 -0500 Subject: [PATCH 0781/2038] Backup: better handling of project files for backup / restore --- .../ViewModel/SessionViewModel.cs | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs index d2f0a07fbb..2cc5c80769 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs @@ -343,9 +343,9 @@ public static async Task CreateNewSession(EditorViewModel edit return sessionViewModel; } - private static void BackupProjectFiles(string path) + private static void BackupProjectFiles() { - EditorViewModel.Instance.projectPath = path; + var path = Path.GetDirectoryName(EditorViewModel.Instance.projectPath); string[] files = Directory.GetFiles(path, "*.xk*", SearchOption.AllDirectories); for (int i=0; i TimeSpan.TicksPerDay * 3) + { + // either the backup is old (more than 3 days) + // or the backup is smaller + File.Copy(filename, backupFile, true); + } + } } } } @@ -424,8 +444,8 @@ public static async Task OpenSession(string path, IViewModelSe return null; } - // project loaded OK, lets backup the prefabs and scene files - BackupProjectFiles(Path.GetDirectoryName(path)); + // grab path for backup/restore + EditorViewModel.Instance.projectPath = path; // Register the node container to the copy/paste service. sessionViewModel.ServiceProvider.Get().PropertyGraphContainer = sessionViewModel.GraphContainer; @@ -1020,6 +1040,9 @@ public async Task Close() if (result == 2) return false; } + // assume we were OK with our project, lets backup everything + BackupProjectFiles(); + return true; } From 203272bc682c3e3e50be956828697c1c4cf2ca01 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Thu, 20 Feb 2020 21:59:54 -0500 Subject: [PATCH 0782/2038] Remove unsupported / old / slow graphics APIs --- deps/OpenTK/.gitignore | 2 - deps/OpenTK/Android/OpenTK-1.1.dll | 3 - deps/OpenTK/CoreCLR/Linux/OpenTK.dll | 3 - deps/OpenTK/CoreCLR/Windows/OpenTK.dll | 3 - deps/OpenTK/CoreCLR/macOS/OpenTK.dll | 3 - deps/OpenTK/Linux/OpenTK.dll | 3 - deps/OpenTK/Linux/OpenTK.dll.config | 25 - deps/OpenTK/OpenTK.dll | 3 - deps/OpenTK/OpenTK.dll.config | 25 - deps/OpenTK/Xenko.OpenTK.nuspec | 19 - deps/OpenTK/build-debug.bat | 10 - deps/OpenTK/build.bat | 28 - deps/OpenTK/checkout.bat | 15 - deps/OpenTK/iOS/OpenTK-1.1.dll | 3 - deps/OpenTK/iOS/link.bat | 5 - deps/OpenTK/license.txt | 27 - deps/OpenTK/macOS/OpenTK.dll | 3 - .../$ProjectName$.csproj.t4 | 3 +- .../Xenko.Assets.Models/ModelAssetCompiler.cs | 2 +- .../AssetCompilerContextExtensions.cs | 13 +- .../EffectByteCodeToSourceCodeWriter.cs | 9 +- .../Xenko.Assets/Textures/TextureHelper.cs | 63 +- .../WindowsGameSettingsProfile.cs | 2 +- .../Rendering/Compositing/ForwardRenderer.cs | 4 +- .../engine/Xenko.Games/GameContextFactory.cs | 3 - .../engine/Xenko.Games/GameContextOpenTK.cs | 126 -- .../Xenko.Games/OpenTK/GamePlatformOpenTK.cs | 26 - .../Xenko.Games/OpenTK/GameWindowOpenTK.cs | 292 --- sources/engine/Xenko.Games/Xenko.Games.csproj | 1 - .../engine/Xenko.Graphics/AppContextType.cs | 5 - .../Direct3D12/Buffer.Direct3D12.cs | 267 --- .../Direct3D12/CommandList.Direct3D12.cs | 1115 --------- .../CompiledCommandList.Direct3D12.cs | 19 - .../Direct3D12/DescriptorPool.Direct3D12.cs | 70 - .../Direct3D12/DescriptorSet.Direct3D12.cs | 129 -- .../DescriptorSetLayout.Direct3D12.cs | 39 - .../Direct3D12/GraphicsDevice.Direct3D12.cs | 714 ------ .../GraphicsDeviceFeatures.Direct3D12.cs | 120 - .../Direct3D12/GraphicsOutput.Direct3D12.cs | 232 -- .../Direct3D12/GraphicsResource.Direct3D12.cs | 39 - .../GraphicsResourceBase.Direct3D12.cs | 91 - .../Direct3D12/MappedResource.Direct3D12.cs | 13 - .../Direct3D12/PipelineState.Direct3D12.cs | 381 ---- .../Direct3D12/QueryPool.Direct3D12.cs | 86 - .../Direct3D12/SamplerState.Direct3D12.cs | 59 - .../Direct3D12/Texture.Direct3D12.cs | 891 -------- .../OpenGL/BlendState.OpenGL.cs | 158 -- .../Xenko.Graphics/OpenGL/Buffer.OpenGL.cs | 276 --- .../OpenGL/CommandList.OpenGL.cs | 2011 ----------------- .../OpenGL/DepthStencilState.OpenGL.cs | 158 -- .../OpenGL/EffectProgram.OpenGL.cs | 1043 --------- .../OpenGL/GraphicsAdapter.OpenGL.cs | 105 - .../OpenGL/GraphicsAdapterFactory.OpenGL.cs | 15 - .../OpenGL/GraphicsDevice.OpenGL.cs | 1292 ----------- .../OpenGL/GraphicsDeviceFeatures.OpenGL.cs | 187 -- .../OpenGL/GraphicsOutput.OpenGL.cs | 31 - .../OpenGL/GraphicsResource.OpenGL.cs | 34 - .../OpenGL/GraphicsResourceBase.OpenGL.cs | 35 - .../OpenGL/MappedResource.OpenGL.cs | 12 - .../OpenGL/OpenGLConvertExtensions.cs | 728 ------ .../OpenGL/OpenGLShaderBytecodeData.cs | 47 - .../Xenko.Graphics/OpenGL/OpenGLUtils.cs | 180 -- .../OpenGL/PipelineState.OpenGL.cs | 270 --- .../Xenko.Graphics/OpenGL/QueryPool.OpenGL.cs | 73 - .../OpenGL/RasterizerState.OpenGL.cs | 144 -- .../OpenGL/SamplerState.OpenGL.cs | 157 -- .../SwapChainGraphicsPresenter.Android.cs | 100 - .../SwapChainGraphicsPresenter.OpenTK.cs | 88 - .../OpenGL/SwapChainGraphicsPresenter.iOS.cs | 96 - .../Xenko.Graphics/OpenGL/Texture.OpenGL.cs | 743 ------ .../OpenGL/UseOpenGLCreationContext.cs | 125 - .../Xenko.Graphics/OpenGL/VertexAttrib.cs | 184 -- .../engine/Xenko.Graphics/OpenGL/apply.bat | 10 - .../Xenko.Graphics/Xenko.Graphics.csproj | 4 +- .../Rendering/Compositing/MSAAResolver.cs | 4 +- .../Xenko.Shaders.Compiler/EffectCompiler.cs | 20 - .../OpenGL/ShaderCompiler.cs | 43 +- .../engine/Xenko/Graphics/GraphicsPlatform.cs | 15 - sources/engine/Xenko/runtime.json | 195 +- sources/engine/Xenko/runtime.tt | 2 +- sources/targets/Xenko.GlobalSettings.targets | 38 +- 81 files changed, 22 insertions(+), 13595 deletions(-) delete mode 100644 deps/OpenTK/.gitignore delete mode 100644 deps/OpenTK/Android/OpenTK-1.1.dll delete mode 100644 deps/OpenTK/CoreCLR/Linux/OpenTK.dll delete mode 100644 deps/OpenTK/CoreCLR/Windows/OpenTK.dll delete mode 100644 deps/OpenTK/CoreCLR/macOS/OpenTK.dll delete mode 100644 deps/OpenTK/Linux/OpenTK.dll delete mode 100644 deps/OpenTK/Linux/OpenTK.dll.config delete mode 100644 deps/OpenTK/OpenTK.dll delete mode 100644 deps/OpenTK/OpenTK.dll.config delete mode 100644 deps/OpenTK/Xenko.OpenTK.nuspec delete mode 100644 deps/OpenTK/build-debug.bat delete mode 100644 deps/OpenTK/build.bat delete mode 100644 deps/OpenTK/checkout.bat delete mode 100644 deps/OpenTK/iOS/OpenTK-1.1.dll delete mode 100644 deps/OpenTK/iOS/link.bat delete mode 100644 deps/OpenTK/license.txt delete mode 100644 deps/OpenTK/macOS/OpenTK.dll delete mode 100644 sources/engine/Xenko.Games/GameContextOpenTK.cs delete mode 100644 sources/engine/Xenko.Games/OpenTK/GamePlatformOpenTK.cs delete mode 100644 sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/Buffer.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/CommandList.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/CompiledCommandList.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/DescriptorPool.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/DescriptorSet.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/DescriptorSetLayout.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/GraphicsDevice.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/GraphicsDeviceFeatures.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/GraphicsOutput.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/GraphicsResource.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/GraphicsResourceBase.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/MappedResource.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/PipelineState.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/QueryPool.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/SamplerState.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/Direct3D12/Texture.Direct3D12.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/BlendState.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/Buffer.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/CommandList.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/DepthStencilState.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/EffectProgram.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapter.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapterFactory.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsDevice.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsDeviceFeatures.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsOutput.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsResource.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/GraphicsResourceBase.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/MappedResource.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/OpenGLConvertExtensions.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/OpenGLShaderBytecodeData.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/OpenGLUtils.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/PipelineState.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/QueryPool.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/RasterizerState.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/SamplerState.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.Android.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.OpenTK.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.iOS.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/Texture.OpenGL.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/UseOpenGLCreationContext.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/VertexAttrib.cs delete mode 100644 sources/engine/Xenko.Graphics/OpenGL/apply.bat diff --git a/deps/OpenTK/.gitignore b/deps/OpenTK/.gitignore deleted file mode 100644 index 348b3e3568..0000000000 --- a/deps/OpenTK/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -*.pdb -*.nupkg \ No newline at end of file diff --git a/deps/OpenTK/Android/OpenTK-1.1.dll b/deps/OpenTK/Android/OpenTK-1.1.dll deleted file mode 100644 index 7d6ead3ef5..0000000000 --- a/deps/OpenTK/Android/OpenTK-1.1.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d21d9811e85755709093f047afdd015af2407b1d09fa326e0337962993fd8412 -size 1732096 diff --git a/deps/OpenTK/CoreCLR/Linux/OpenTK.dll b/deps/OpenTK/CoreCLR/Linux/OpenTK.dll deleted file mode 100644 index db135da8e2..0000000000 --- a/deps/OpenTK/CoreCLR/Linux/OpenTK.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:02727386ebfacb0c7702ee9742116ccf9bebd83dced385163c59110326607a32 -size 4407808 diff --git a/deps/OpenTK/CoreCLR/Windows/OpenTK.dll b/deps/OpenTK/CoreCLR/Windows/OpenTK.dll deleted file mode 100644 index fb041afb12..0000000000 --- a/deps/OpenTK/CoreCLR/Windows/OpenTK.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b72c6c6d110a9f4fbeffbe25d45172e96aea96137d881fe05b4277d7e88bd3d5 -size 4408320 diff --git a/deps/OpenTK/CoreCLR/macOS/OpenTK.dll b/deps/OpenTK/CoreCLR/macOS/OpenTK.dll deleted file mode 100644 index 1b7e7ac45b..0000000000 --- a/deps/OpenTK/CoreCLR/macOS/OpenTK.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f15eee117c1aa3656b3fc642bb6e79819bec9b52dfdf638f9f551b2a1241f335 -size 4407808 diff --git a/deps/OpenTK/Linux/OpenTK.dll b/deps/OpenTK/Linux/OpenTK.dll deleted file mode 100644 index 20f71da264..0000000000 --- a/deps/OpenTK/Linux/OpenTK.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f106371b9971f518e74173e815009a15aff3a0a71377c532dd30727183c497c6 -size 4406272 diff --git a/deps/OpenTK/Linux/OpenTK.dll.config b/deps/OpenTK/Linux/OpenTK.dll.config deleted file mode 100644 index 7098d39e9c..0000000000 --- a/deps/OpenTK/Linux/OpenTK.dll.config +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/deps/OpenTK/OpenTK.dll b/deps/OpenTK/OpenTK.dll deleted file mode 100644 index 9ceff79153..0000000000 --- a/deps/OpenTK/OpenTK.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e96b4f836d579244f0ee90a5603a20561417daae942a534600a62ee20fc6aca3 -size 4616192 diff --git a/deps/OpenTK/OpenTK.dll.config b/deps/OpenTK/OpenTK.dll.config deleted file mode 100644 index 7098d39e9c..0000000000 --- a/deps/OpenTK/OpenTK.dll.config +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/deps/OpenTK/Xenko.OpenTK.nuspec b/deps/OpenTK/Xenko.OpenTK.nuspec deleted file mode 100644 index a8b293282d..0000000000 --- a/deps/OpenTK/Xenko.OpenTK.nuspec +++ /dev/null @@ -1,19 +0,0 @@ - - - - Xenko.OpenTK - 1.0.2 - Xenko contributors and OpenTK team - Xenko contributors and OpenTK team - false - OpenTK for Xenko - - - - - - - - - - \ No newline at end of file diff --git a/deps/OpenTK/build-debug.bat b/deps/OpenTK/build-debug.bat deleted file mode 100644 index 5af814a99c..0000000000 --- a/deps/OpenTK/build-debug.bat +++ /dev/null @@ -1,10 +0,0 @@ -@echo off - -rem If not already loaded, setup VisualStudio -if "%VisualStudioVersion%" EQ "" call "%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\vc\vcvarsall.bat" x86 - -msbuild ..\..\externals\opentk\OpenTK.sln /Property:Configuration=Debug;Platform="Any CPU" -copy ..\..\externals\opentk\Binaries\OpenTK\Debug\OpenTK.dll . -copy ..\..\externals\opentk\Binaries\OpenTK\Debug\OpenTK.pdb . -copy ..\..\externals\opentk\Binaries\OpenTK\Debug\OpenTK.GLControl.dll . -copy ..\..\externals\opentk\Binaries\OpenTK\Debug\OpenTK.GLControl.pdb . diff --git a/deps/OpenTK/build.bat b/deps/OpenTK/build.bat deleted file mode 100644 index 0e9c06ed5b..0000000000 --- a/deps/OpenTK/build.bat +++ /dev/null @@ -1,28 +0,0 @@ -@echo off - -rem If not already loaded, setup VisualStudio -call "%ProgramFiles(x86)%\Microsoft Visual Studio 14.0\vc\vcvarsall.bat" x86 - -set opentk=..\..\externals\opentk - -pushd %opentk% -..\..\build\.nuget\NuGet.exe restore OpenTK.sln -..\..\build\.nuget\NuGet.exe restore source\OpenTK\OpenTK.NETStandard.csproj -popd - -REM NET Standard -msbuild %opentk%\source\OpenTK\OpenTK.NETStandard.csproj /Property:Configuration=Release;Platform="AnyCPU" -copy /Y %opentk%\Binaries\OpenTK\Release\netstandard2.0\OpenTK.dll . -copy /Y %opentk%\Binaries\OpenTK\Release\netstandard2.0\OpenTK.pdb . - -REM Android -msbuild %opentk%\OpenTK.Android.sln /Property:Configuration=Release;Platform="Any CPU" -if not exist Android mkdir Android -copy /Y %opentk%\Binaries\Android\Release\OpenTK-1.1.dll Android -copy /Y %opentk%\Binaries\Android\Release\OpenTK-1.1.dll.mdb Android - -REM iOS -msbuild %opentk%\OpenTK.iOS.sln /Property:Configuration=Release;Platform="Any CPU" -if not exist iOS mkdir iOS -copy /Y %opentk%\Binaries\iOS\Release\OpenTK-1.1.dll iOS -copy /Y %opentk%\Binaries\iOS\Release\OpenTK-1.1.dll.mdb iOS diff --git a/deps/OpenTK/checkout.bat b/deps/OpenTK/checkout.bat deleted file mode 100644 index b9e0aa72e6..0000000000 --- a/deps/OpenTK/checkout.bat +++ /dev/null @@ -1,15 +0,0 @@ -@echo OFF -setlocal -set HOME=%USERPROFILE% -CALL ..\find_git.cmd -IF NOT ERRORLEVEL 0 ( - ECHO "Could not find git.exe" - EXIT /B %ERRORLEVEL% -) -%GIT_CMD% clone git@github.com:xenko3d/opentk ../../externals/opentk -b develop -if NOT ERRORLEVEL 0 pause -pushd ..\..\externals\opentk -%GIT_CMD% remote add upstream git@github.com:opentk/opentk.git -%GIT_CMD% fetch --all -popd -if NOT ERRORLEVEL 0 pause \ No newline at end of file diff --git a/deps/OpenTK/iOS/OpenTK-1.1.dll b/deps/OpenTK/iOS/OpenTK-1.1.dll deleted file mode 100644 index a2366ee942..0000000000 --- a/deps/OpenTK/iOS/OpenTK-1.1.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ce8fb17099a496a07a4481b9663b06da7ce02f7e065fe177b82551f8b2136ba4 -size 457216 diff --git a/deps/OpenTK/iOS/link.bat b/deps/OpenTK/iOS/link.bat deleted file mode 100644 index 687f486ae7..0000000000 --- a/deps/OpenTK/iOS/link.bat +++ /dev/null @@ -1,5 +0,0 @@ -pushd ..\..\..\bin\iOS-OpenGLES -..\..\deps\monolinker\monolinker -a Xenko.Engine.dll -a Xenko.Games.dll -a Xenko.Input.dll -a Xenko.Graphics.dll -p link OpenTK-1.1 -u copy -b true -d "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\Xamarin.iOS\v1.0" -popd - -copy ..\..\..\bin\iOS-OpenGLES\output\OpenTK-1.1.dll . \ No newline at end of file diff --git a/deps/OpenTK/license.txt b/deps/OpenTK/license.txt deleted file mode 100644 index 61edfe258f..0000000000 --- a/deps/OpenTK/license.txt +++ /dev/null @@ -1,27 +0,0 @@ -Source: http://www.opentk.com/project/license - -The Open Toolkit library license -Copyright (c) 2006 - 2013 Stefanos Apostolopoulos (stapostol@gmail.com) for the Open Toolkit library. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -Third parties -OpenTK.Platform.Windows and OpenTK.Platform.X11 include portions of the Mono class library. These portions are covered by the following license: -Copyright (c) 2004 Novell, Inc. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -OpenTK.Compatibility includes portions of the Tao Framework library (Tao.OpenGl, Tao.OpenAl and Tao.Platform.Windows.SimpleOpenGlControl). These portions are covered by the following license: -Copyright (c) 2003-2007 Tao Framework Team -http://www.taoframework.com -All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -OpenTK.Half offers Half-to-Single and Single-to-Half conversions based on OpenEXR source code, which is covered by the following license: -Copyright (c) 2002, Industrial Light & Magic, a division of Lucas Digital Ltd. LLC. All rights reserved. -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -* Neither the name of Industrial Light & Magic nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/deps/OpenTK/macOS/OpenTK.dll b/deps/OpenTK/macOS/OpenTK.dll deleted file mode 100644 index a2d08f1eb0..0000000000 --- a/deps/OpenTK/macOS/OpenTK.dll +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:57989c07a4d16349d83da90644d1d42315c484536dfa3c70db6ba8a5af922b6a -size 4406784 diff --git a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 index ae9f74b0e1..a21536567c 100644 --- a/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 +++ b/sources/editor/Xenko.Assets.Presentation/Templates/Core/ProjectExecutable.Linux/$ProjectName$.csproj.t4 @@ -3,7 +3,8 @@ netcoreapp2.2 - linux-vulkan-x64 + linux-x64 + old Resources\Icon.ico WinExe <#= Properties.Namespace #> diff --git a/sources/engine/Xenko.Assets.Models/ModelAssetCompiler.cs b/sources/engine/Xenko.Assets.Models/ModelAssetCompiler.cs index 51af0a3c10..075be42fdc 100644 --- a/sources/engine/Xenko.Assets.Models/ModelAssetCompiler.cs +++ b/sources/engine/Xenko.Assets.Models/ModelAssetCompiler.cs @@ -41,7 +41,7 @@ protected override void Prepare(AssetCompilerContext context, AssetItem assetIte var renderingSettings = gameSettingsAsset.GetOrCreate(); var allow32BitIndex = renderingSettings.DefaultGraphicsProfile >= GraphicsProfile.Level_9_2; var maxInputSlots = renderingSettings.DefaultGraphicsProfile >= GraphicsProfile.Level_10_1 ? 32 : 16; - var allowUnsignedBlendIndices = context.GetGraphicsPlatform(assetItem.Package) != GraphicsPlatform.OpenGLES; + var allowUnsignedBlendIndices = true; //context.GetGraphicsPlatform(assetItem.Package) != GraphicsPlatform.OpenGLES; var extension = asset.Source.GetFileExtension(); // Find skeleton asset, if any diff --git a/sources/engine/Xenko.Assets/AssetCompilerContextExtensions.cs b/sources/engine/Xenko.Assets/AssetCompilerContextExtensions.cs index c64fe72e76..41e3ef062d 100644 --- a/sources/engine/Xenko.Assets/AssetCompilerContextExtensions.cs +++ b/sources/engine/Xenko.Assets/AssetCompilerContextExtensions.cs @@ -40,13 +40,6 @@ public static GraphicsPlatform GetGraphicsPlatform(this AssetCompilerContext con { if (runtimeIdentifier.Contains("-d3d11")) return GraphicsPlatform.Direct3D11; - else if (runtimeIdentifier.Contains("-d3d12")) - return GraphicsPlatform.Direct3D12; - // Note: testing opengles before opengl since one string contains another - else if (runtimeIdentifier.Contains("-opengles")) - return GraphicsPlatform.OpenGLES; - else if (runtimeIdentifier.Contains("-opengl")) - return GraphicsPlatform.OpenGL; else if (runtimeIdentifier.Contains("-vulkan")) return GraphicsPlatform.Vulkan; } @@ -60,13 +53,9 @@ public static GraphicsPlatform GetDefaultGraphicsPlatform(this PlatformType plat switch (platformType) { case PlatformType.Windows: - case PlatformType.UWP: return GraphicsPlatform.Direct3D11; - case PlatformType.Android: - case PlatformType.iOS: - return GraphicsPlatform.OpenGLES; case PlatformType.Linux: - return GraphicsPlatform.OpenGL; + return GraphicsPlatform.Vulkan; case PlatformType.macOS: return GraphicsPlatform.Vulkan; default: diff --git a/sources/engine/Xenko.Assets/Effect/EffectByteCodeToSourceCodeWriter.cs b/sources/engine/Xenko.Assets/Effect/EffectByteCodeToSourceCodeWriter.cs index d0bae8c459..740b6ebe22 100644 --- a/sources/engine/Xenko.Assets/Effect/EffectByteCodeToSourceCodeWriter.cs +++ b/sources/engine/Xenko.Assets/Effect/EffectByteCodeToSourceCodeWriter.cs @@ -1,4 +1,4 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) +// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.IO; @@ -67,15 +67,8 @@ namespace {1} switch (graphicsPlatform) { case GraphicsPlatform.Direct3D11: - case GraphicsPlatform.Direct3D12: xenkoDefine = "XENKO_GRAPHICS_API_DIRECT3D"; break; - case GraphicsPlatform.OpenGL: - xenkoDefine = "XENKO_GRAPHICS_API_OPENGLCORE"; - break; - case GraphicsPlatform.OpenGLES: - xenkoDefine = "XENKO_GRAPHICS_API_OPENGLES"; - break; case GraphicsPlatform.Vulkan: xenkoDefine = "XENKO_GRAPHICS_API_VULKAN"; break; diff --git a/sources/engine/Xenko.Assets/Textures/TextureHelper.cs b/sources/engine/Xenko.Assets/Textures/TextureHelper.cs index 2c7c22c035..d25d058e50 100644 --- a/sources/engine/Xenko.Assets/Textures/TextureHelper.cs +++ b/sources/engine/Xenko.Assets/Textures/TextureHelper.cs @@ -280,8 +280,6 @@ public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Siz switch (parameters.GraphicsPlatform) { case GraphicsPlatform.Direct3D11: - case GraphicsPlatform.Direct3D12: - case GraphicsPlatform.OpenGL: case GraphicsPlatform.Vulkan: // https://msdn.microsoft.com/en-us/library/windows/desktop/hh308955%28v=vs.85%29.aspx @@ -320,11 +318,11 @@ public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Siz // Support some specific optimized formats based on the hint or input type if (parameters.GraphicsProfile >= GraphicsProfile.Level_10_0) { - if (parameters.GraphicsPlatform != GraphicsPlatform.OpenGL && hint == TextureHint.NormalMap) + if (hint == TextureHint.NormalMap) { outputFormat = PixelFormat.BC5_UNorm; } - else if (parameters.GraphicsPlatform != GraphicsPlatform.OpenGL && hint == TextureHint.Grayscale) + else if (hint == TextureHint.Grayscale) { outputFormat = PixelFormat.BC4_UNorm; } @@ -337,37 +335,6 @@ public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Siz // TODO support the BC6/BC7 but they are so slow to compile that we can't use them right now } break; - case GraphicsPlatform.OpenGLES: // OpenGLES on Windows - if (inputImageFormat.IsHDR()) - { - outputFormat = inputImageFormat; - } - else if (parameters.IsSRgb) - { - outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; - } - else - { - switch (parameters.GraphicsProfile) - { - case GraphicsProfile.Level_9_1: - case GraphicsProfile.Level_9_2: - case GraphicsProfile.Level_9_3: - outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.R8G8B8A8_UNorm; - break; - case GraphicsProfile.Level_10_0: - case GraphicsProfile.Level_10_1: - case GraphicsProfile.Level_11_0: - case GraphicsProfile.Level_11_1: - case GraphicsProfile.Level_11_2: - // GLES3.0 starting from Level_10_0, this profile enables ETC2 compression on Android - outputFormat = alphaMode == AlphaFormat.None ? PixelFormat.ETC1 : PixelFormat.ETC2_RGBA; - break; - default: - throw new ArgumentOutOfRangeException("GraphicsProfile"); - } - } - break; default: // OpenGL on Windows // TODO: Need to handle OpenGL Desktop compression @@ -387,32 +354,6 @@ public static PixelFormat DetermineOutputFormat(ImportParameters parameters, Siz throw new ArgumentOutOfRangeException(); } - // OpenGLES: avoid BGRA (optional extension) - if (parameters.GraphicsPlatform == GraphicsPlatform.OpenGLES) - { - switch (outputFormat) - { - case PixelFormat.B8G8R8A8_UNorm: - outputFormat = PixelFormat.R8G8B8A8_UNorm; - break; - case PixelFormat.B8G8R8A8_UNorm_SRgb: - outputFormat = PixelFormat.R8G8B8A8_UNorm_SRgb; - break; - } - } - - // OpenGL and OpenGLES: avoid R5G6B5 (not implemented) - if (parameters.GraphicsPlatform == GraphicsPlatform.OpenGLES || parameters.GraphicsPlatform == GraphicsPlatform.OpenGL) - { - switch (outputFormat) - { - case PixelFormat.B5G5R5A1_UNorm: - case PixelFormat.B5G6R5_UNorm: - outputFormat = PixelFormat.R8G8B8A8_UNorm; - break; - } - } - return outputFormat; } diff --git a/sources/engine/Xenko.Assets/WindowsGameSettingsProfile.cs b/sources/engine/Xenko.Assets/WindowsGameSettingsProfile.cs index 831b9905e2..87203e9742 100644 --- a/sources/engine/Xenko.Assets/WindowsGameSettingsProfile.cs +++ b/sources/engine/Xenko.Assets/WindowsGameSettingsProfile.cs @@ -21,7 +21,7 @@ public WindowsGameSettingsProfile() public override IEnumerable GetSupportedGraphicsPlatforms() { - return new[] { GraphicsPlatform.Direct3D11, GraphicsPlatform.OpenGL, GraphicsPlatform.OpenGLES, }; + return new[] { GraphicsPlatform.Direct3D11, GraphicsPlatform.Vulkan, }; } } } diff --git a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs index 6880a38664..380aab04f4 100644 --- a/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs +++ b/sources/engine/Xenko.Engine/Rendering/Compositing/ForwardRenderer.cs @@ -132,9 +132,7 @@ protected override void InitializeCore() actualMultisampleCount = (MultisampleCount)Math.Min((int)actualMultisampleCount, (int)GraphicsDevice.Features[DepthBufferFormat].MultisampleCountMax); // Note: we cannot support MSAA on DX10 now - if (GraphicsDevice.Features.HasMultisampleDepthAsSRV == false && // TODO: Try enabling MSAA on DX9! - GraphicsDevice.Platform != GraphicsPlatform.OpenGL && - GraphicsDevice.Platform != GraphicsPlatform.OpenGLES) + if (GraphicsDevice.Features.HasMultisampleDepthAsSRV == false) { // OpenGL has MSAA support on every version. // OpenGL ES has MSAA support starting from version 3.0. diff --git a/sources/engine/Xenko.Games/GameContextFactory.cs b/sources/engine/Xenko.Games/GameContextFactory.cs index 07d6833a76..bee20aa583 100644 --- a/sources/engine/Xenko.Games/GameContextFactory.cs +++ b/sources/engine/Xenko.Games/GameContextFactory.cs @@ -54,9 +54,6 @@ public static GameContext NewGameContext(AppContextType type) case AppContextType.Desktop: res = NewGameContextDesktop(); break; - case AppContextType.DesktopOpenTK: - res = NewGameContextOpenTK(); - break; case AppContextType.DesktopSDL: res = NewGameContextSDL(); break; diff --git a/sources/engine/Xenko.Games/GameContextOpenTK.cs b/sources/engine/Xenko.Games/GameContextOpenTK.cs deleted file mode 100644 index dc46605174..0000000000 --- a/sources/engine/Xenko.Games/GameContextOpenTK.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -// -// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -#if (XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX) && XENKO_GRAPHICS_API_OPENGL && XENKO_UI_OPENTK -using System; -using OpenTK; -using OpenTK.Graphics; -using Xenko.Graphics.OpenGL; - -namespace Xenko.Games -{ - /// - /// A to use for rendering to an existing OpenTK Window. - /// - public class GameContextOpenTK : GameContextWindows - { - /// - public GameContextOpenTK(OpenTK.GameWindow control, int requestedWidth = 0, int requestedHeight = 0) - : base(control, requestedWidth, requestedHeight) - { - ContextType = AppContextType.DesktopOpenTK; - if (requestedWidth == 0 || requestedHeight == 0) - { - requestedWidth = 1280; - requestedHeight = 720; - } - - var creationFlags = GraphicsContextFlags.Default; -#if XENKO_GRAPHICS_API_OPENGLES - creationFlags |= GraphicsContextFlags.Embedded; -#endif - if ((this.DeviceCreationFlags & Graphics.DeviceCreationFlags.Debug) != 0) - creationFlags |= GraphicsContextFlags.Debug; - - // force the stencil buffer to be not null. - var defaultMode = GraphicsMode.Default; - var graphicMode = new GraphicsMode(defaultMode.ColorFormat, 0, 0, defaultMode.Samples, defaultMode.AccumulatorFormat, defaultMode.Buffers, defaultMode.Stereo); - - GraphicsContext.ShareContexts = true; - - if (control == null) - { - int version; - if (RequestedGraphicsProfile == null || RequestedGraphicsProfile.Length == 0) - { -#if XENKO_GRAPHICS_API_OPENGLES - version = 300; -#else - // PC: 4.3 is commonly available (= compute shaders) - // MacOS X: 4.1 maximum - version = 410; -#endif - Control = TryGameWindow(requestedWidth, requestedHeight, graphicMode, version / 100, (version % 100) / 10, creationFlags); - } - else - { - foreach (var profile in RequestedGraphicsProfile) - { - OpenGLUtils.GetGLVersion(profile, out version); - var gameWindow = TryGameWindow(requestedWidth, requestedHeight, graphicMode, version / 100, (version % 100) / 10, creationFlags); - if (gameWindow != null) - { - Control = gameWindow; - break; - } - } - } - } - - if (Control == null) - { - throw new Exception("Unable to initialize graphics context."); - } - } - - /// - /// Try to create the graphics context. - /// - /// The requested width. - /// The requested height. - /// The graphics mode. - /// The major version of OpenGL. - /// The minor version of OpenGL. - /// The creation flags. - /// The created GameWindow. - private static OpenTK.GameWindow TryGameWindow(int requestedWidth, int requestedHeight, GraphicsMode graphicMode, int versionMajor, int versionMinor, GraphicsContextFlags creationFlags) - { - try - { -#if XENKO_GRAPHICS_API_OPENGL || XENKO_GRAPHICS_API_OPENGLES - // Preload proper SDL native library (depending on CPU type) - // This is for OpenGL ES on desktop - Core.NativeLibrary.PreloadLibrary("SDL2.dll", typeof(GameContextOpenTK)); -#endif - - var gameWindow = new OpenTK.GameWindow(requestedWidth, requestedHeight, graphicMode, GameContext.ProductName, GameWindowFlags.Default, DisplayDevice.Default, versionMajor, versionMinor, - creationFlags); - return gameWindow; - } - catch (Exception) - { - return null; - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Games/OpenTK/GamePlatformOpenTK.cs b/sources/engine/Xenko.Games/OpenTK/GamePlatformOpenTK.cs deleted file mode 100644 index 88c962ea68..0000000000 --- a/sources/engine/Xenko.Games/OpenTK/GamePlatformOpenTK.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_PLATFORM_WINDOWS_DESKTOP && XENKO_GRAPHICS_API_OPENGL && (XENKO_UI_WINFORMS || XENKO_UI_WPF) && XENKO_UI_OPENTK -using System; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using Xenko.Graphics; - -namespace Xenko.Games -{ - internal class GamePlatformOpenTK : GamePlatformWindows, IGraphicsDeviceFactory - { - public GamePlatformOpenTK(GameBase game) : base(game) - { - } - - public virtual void DeviceChanged(GraphicsDevice currentDevice, GraphicsDeviceInformation deviceInformation) - { - // TODO: Check when it needs to be disabled on iOS (OpenGL)? - // Force to resize the gameWindow - //gameWindow.Resize(deviceInformation.PresentationParameters.BackBufferWidth, deviceInformation.PresentationParameters.BackBufferHeight); - } - } -} -#endif diff --git a/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs b/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs deleted file mode 100644 index 3f06b47c78..0000000000 --- a/sources/engine/Xenko.Games/OpenTK/GameWindowOpenTK.cs +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if (XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX) && XENKO_GRAPHICS_API_OPENGL && XENKO_UI_OPENTK -using System.Diagnostics; -using Xenko.Core.Mathematics; -using Xenko.Graphics; - -namespace Xenko.Games -{ - /// - /// An abstract window. - /// - internal class GameWindowOpenTK : GameWindow - { - private bool isMouseVisible; - - private bool isMouseCurrentlyHidden; - - private OpenTK.GameWindow gameForm; - private WindowHandle nativeWindow; - - internal GameWindowOpenTK() - { - } - - public override WindowHandle NativeWindow - { - get - { - return nativeWindow; - } - } - - public override Int2 Position - { - get - { - if (gameForm == null) - return base.Position; - - return new Int2(gameForm.X, gameForm.Y); - } - set - { - if (gameForm != null) - { - gameForm.X = value.X; - gameForm.Y = value.Y; - } - - base.Position = value; - } - } - - public override void BeginScreenDeviceChange(bool willBeFullScreen) - { - - } - - public override void EndScreenDeviceChange(int clientWidth, int clientHeight) - { - - } - - protected internal override void SetSupportedOrientations(DisplayOrientation orientations) - { - // Desktop doesn't have orientation (unless on Windows 8?) - } - - protected override void Initialize(GameContext gameContext) - { - gameForm = gameContext.Control; - nativeWindow = new WindowHandle(AppContextType.DesktopOpenTK, gameForm, gameForm.WindowInfo.Handle); - - // Setup the initial size of the window - var width = gameContext.RequestedWidth; - if (width == 0) - { - width = gameForm.Width; - } - - var height = gameContext.RequestedHeight; - if (height == 0) - { - height = gameForm.Height; - } - - // Update gameForm.ClientSize with (width, height) - Resize(width, height); - - gameForm.MouseEnter += GameWindowForm_MouseEnter; - gameForm.MouseLeave += GameWindowForm_MouseLeave; - - gameForm.Resize += OnClientSizeChanged; - gameForm.Unload += OnClosing; - } - - internal override void Run() - { - Debug.Assert(InitCallback != null); - Debug.Assert(RunCallback != null); - - // Initialize the init callback - InitCallback(); - - // Make the window visible - gameForm.Visible = true; - - // Run the rendering loop - try - { - while (!Exiting) - { - gameForm.ProcessEvents(); - - RunCallback(); - } - - if (gameForm != null) - { - if (OpenTK.Graphics.GraphicsContext.CurrentContext == gameForm.Context) - gameForm.Context.MakeCurrent(null); - gameForm.Close(); - gameForm.Dispose(); - gameForm = null; - } - } - finally - { - if (ExitCallback != null) - { - ExitCallback(); - } - } - } - - private void GameWindowForm_MouseEnter(object sender, System.EventArgs e) - { - if (!isMouseVisible && !isMouseCurrentlyHidden) - { - gameForm.CursorVisible = false; - isMouseCurrentlyHidden = true; - } - } - - private void GameWindowForm_MouseLeave(object sender, System.EventArgs e) - { - if (isMouseCurrentlyHidden) - { - gameForm.CursorVisible = true; - isMouseCurrentlyHidden = false; - } - } - - public override bool IsMouseVisible - { - get - { - return isMouseVisible; - } - set - { - if (isMouseVisible != value) - { - isMouseVisible = value; - if (isMouseVisible) - { - if (isMouseCurrentlyHidden) - { - gameForm.CursorVisible = true; - isMouseCurrentlyHidden = false; - } - } - else if (!isMouseCurrentlyHidden) - { - gameForm.CursorVisible = false; - isMouseCurrentlyHidden = true; - } - } - } - } - - /// - /// Gets or sets a value indicating whether this is visible. - /// - /// true if visible; otherwise, false. - public override bool Visible - { - get - { - return gameForm.Visible; - } - set - { - gameForm.Visible = value; - } - } - - protected override void SetTitle(string title) - { - gameForm.Title = title; - } - - public override bool IsFullscreen { - get { - return false; // TODO: is this supported? - } - set { - // TODO: is this supported? - } - } - - public override void Resize(int width, int height) - { - // Unfortunately on OpenTK, depending on how you compile it, it may use System.Drawing.Size or - // OpenTK.Size. To avoid having to put the exact type, we will use C# inference to guess the right - // type at compile time which will depend on the OpenTK.dll used to compile this code. - var size = gameForm.ClientSize; - size.Width = width; - size.Height = height; - gameForm.ClientSize = size; - } - - public override bool IsBorderLess - { - get - { - return true; - } - set - { - } - } - - public override bool AllowUserResizing - { - get - { - return true; - } - set - { - } - } - - public override Rectangle ClientBounds - { - get - { - return new Rectangle(0, 0, gameForm.ClientSize.Width, gameForm.ClientSize.Height); - } - } - - public override DisplayOrientation CurrentOrientation - { - get - { - return DisplayOrientation.Default; - } - } - - public override bool IsMinimized - { - get - { - return gameForm.WindowState == OpenTK.WindowState.Minimized; - } - } - - public override bool Focused - { - get - { - return gameForm.Focused; - } - } - - protected override void Destroy() - { - if (gameForm != null) - { - gameForm.Context.MakeCurrent(null); - gameForm.Close(); - gameForm.Dispose(); - gameForm = null; - } - - base.Destroy(); - } - } -} -#endif diff --git a/sources/engine/Xenko.Games/Xenko.Games.csproj b/sources/engine/Xenko.Games/Xenko.Games.csproj index 1766c8ced5..73c43dfcb3 100644 --- a/sources/engine/Xenko.Games/Xenko.Games.csproj +++ b/sources/engine/Xenko.Games/Xenko.Games.csproj @@ -29,7 +29,6 @@ Properties\SharedAssemblyInfo.cs - True True diff --git a/sources/engine/Xenko.Graphics/AppContextType.cs b/sources/engine/Xenko.Graphics/AppContextType.cs index 5c6d343542..902060b40e 100644 --- a/sources/engine/Xenko.Graphics/AppContextType.cs +++ b/sources/engine/Xenko.Graphics/AppContextType.cs @@ -43,11 +43,6 @@ public enum AppContextType /// DesktopWpf, - /// - /// Game running on desktop in an OpenTK form. - /// - DesktopOpenTK, - /// /// Game running on Android in an AndroidXenkoGameView. /// diff --git a/sources/engine/Xenko.Graphics/Direct3D12/Buffer.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/Buffer.Direct3D12.cs deleted file mode 100644 index fae5325c23..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/Buffer.Direct3D12.cs +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using System.Collections.Generic; - -using SharpDX; -using SharpDX.DXGI; -using SharpDX.Direct3D12; -using Xenko.Core.Mathematics; - -namespace Xenko.Graphics -{ - public partial class Buffer - { - private SharpDX.Direct3D12.ResourceDescription nativeDescription; - internal long GPUVirtualAddress; - - /// - /// Initializes a new instance of the class. - /// - /// The description. - /// Type of the buffer. - /// The view format. - /// The data pointer. - protected Buffer InitializeFromImpl(BufferDescription description, BufferFlags viewFlags, PixelFormat viewFormat, IntPtr dataPointer) - { - bufferDescription = description; - nativeDescription = ConvertToNativeDescription(GraphicsDevice, Description); - ViewFlags = viewFlags; - InitCountAndViewFormat(out this.elementCount, ref viewFormat); - ViewFormat = viewFormat; - Recreate(dataPointer); - - if (GraphicsDevice != null) - { - GraphicsDevice.RegisterBufferMemoryUsage(SizeInBytes); - } - - return this; - } - - /// - protected internal override void OnDestroyed() - { - if (GraphicsDevice != null) - { - GraphicsDevice.RegisterBufferMemoryUsage(-SizeInBytes); - } - - base.OnDestroyed(); - } - - /// - protected internal override bool OnRecreate() - { - base.OnRecreate(); - - if (Description.Usage == GraphicsResourceUsage.Immutable - || Description.Usage == GraphicsResourceUsage.Default) - return false; - - Recreate(IntPtr.Zero); - - return true; - } - - /// - /// Explicitly recreate buffer with given data. Usually called after a reset. - /// - /// - /// - public void Recreate(IntPtr dataPointer) - { - // TODO D3D12 where should that go longer term? should it be precomputed for future use? (cost would likely be additional check on SetDescriptorSets/Draw) - NativeResourceState = ResourceStates.Common; - var bufferFlags = bufferDescription.BufferFlags; - - if ((bufferFlags & BufferFlags.ConstantBuffer) != 0) - NativeResourceState |= ResourceStates.VertexAndConstantBuffer; - - if ((bufferFlags & BufferFlags.IndexBuffer) != 0) - NativeResourceState |= ResourceStates.IndexBuffer; - - if ((bufferFlags & BufferFlags.VertexBuffer) != 0) - NativeResourceState |= ResourceStates.VertexAndConstantBuffer; - - if ((bufferFlags & BufferFlags.ShaderResource) != 0) - NativeResourceState |= ResourceStates.PixelShaderResource | ResourceStates.NonPixelShaderResource; - - if ((bufferFlags & BufferFlags.StructuredBuffer) != 0) - { - if (bufferDescription.StructureByteStride <= 0) - throw new ArgumentException("Element size cannot be less or equal 0 for structured buffer"); - } - - if ((bufferFlags & BufferFlags.ArgumentBuffer) == BufferFlags.ArgumentBuffer) - NativeResourceState |= ResourceStates.IndirectArgument; - - var heapType = HeapType.Default; - if (Usage == GraphicsResourceUsage.Staging) - { - if (dataPointer != IntPtr.Zero) - throw new NotImplementedException("D3D12: Staging buffers can't be created with initial data."); - - heapType = HeapType.Readback; - NativeResourceState = ResourceStates.CopyDestination; - } - else if (Usage == GraphicsResourceUsage.Dynamic) - { - heapType = HeapType.Upload; - NativeResourceState = ResourceStates.GenericRead; - } - - // TODO D3D12 move that to a global allocator in bigger committed resources - NativeDeviceChild = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, nativeDescription, dataPointer != IntPtr.Zero ? ResourceStates.CopyDestination : NativeResourceState); - GPUVirtualAddress = NativeResource.GPUVirtualAddress; - - if (dataPointer != IntPtr.Zero) - { - if (heapType == HeapType.Upload) - { - var uploadMemory = NativeResource.Map(0); - Utilities.CopyMemory(uploadMemory, dataPointer, SizeInBytes); - NativeResource.Unmap(0); - } - else - { - // Copy data in upload heap for later copy - // TODO D3D12 move that to a shared upload heap - SharpDX.Direct3D12.Resource uploadResource; - int uploadOffset; - var uploadMemory = GraphicsDevice.AllocateUploadBuffer(SizeInBytes, out uploadResource, out uploadOffset); - Utilities.CopyMemory(uploadMemory, dataPointer, SizeInBytes); - - // TODO D3D12 lock NativeCopyCommandList usages - var commandList = GraphicsDevice.NativeCopyCommandList; - commandList.Reset(GraphicsDevice.NativeCopyCommandAllocator, null); - // Copy from upload heap to actual resource - commandList.CopyBufferRegion(NativeResource, 0, uploadResource, uploadOffset, SizeInBytes); - - // Switch resource to proper read state - commandList.ResourceBarrierTransition(NativeResource, 0, ResourceStates.CopyDestination, NativeResourceState); - - commandList.Close(); - - GraphicsDevice.WaitCopyQueue(); - } - } - - NativeShaderResourceView = GetShaderResourceView(ViewFormat); - NativeUnorderedAccessView = GetUnorderedAccessView(ViewFormat); - } - - /// - /// Gets a for a particular . - /// - /// The view format. - /// A for the particular view format. - /// - /// The buffer must have been declared with . - /// The ShaderResourceView instance is kept by this buffer and will be disposed when this buffer is disposed. - /// - internal CpuDescriptorHandle GetShaderResourceView(PixelFormat viewFormat) - { - var srv = new CpuDescriptorHandle(); - if ((ViewFlags & BufferFlags.ShaderResource) != 0) - { - var description = new ShaderResourceViewDescription - { - Shader4ComponentMapping = 0x00001688, - Format = (SharpDX.DXGI.Format)viewFormat, - Dimension = SharpDX.Direct3D12.ShaderResourceViewDimension.Buffer, - Buffer = - { - ElementCount = this.ElementCount, - FirstElement = 0, - Flags = BufferShaderResourceViewFlags.None, - StructureByteStride = StructureByteStride, - } - }; - - if (((ViewFlags & BufferFlags.RawBuffer) == BufferFlags.RawBuffer)) - description.Buffer.Flags |= BufferShaderResourceViewFlags.Raw; - - srv = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1); - NativeDevice.CreateShaderResourceView(NativeResource, description, srv); - } - return srv; - } - - internal CpuDescriptorHandle GetUnorderedAccessView(PixelFormat viewFormat) - { - var uav = new CpuDescriptorHandle(); - if ((ViewFlags & BufferFlags.UnorderedAccess) != 0) - { - var description = new UnorderedAccessViewDescription - { - Format = (SharpDX.DXGI.Format)viewFormat, - Dimension = SharpDX.Direct3D12.UnorderedAccessViewDimension.Buffer, - Buffer = - { - ElementCount = this.ElementCount, - FirstElement = 0, - Flags = BufferUnorderedAccessViewFlags.None, - StructureByteStride = StructureByteStride, - CounterOffsetInBytes = 0, - } - }; - - if ((ViewFlags & BufferFlags.RawBuffer) == BufferFlags.RawBuffer) - { - description.Buffer.Flags |= BufferUnorderedAccessViewFlags.Raw; - description.Format = Format.R32_Typeless; - } - - uav = GraphicsDevice.UnorderedAccessViewAllocator.Allocate(1); - - // TODO: manage counter value here if buffer has 'Counter' or 'Append' flag - // if (Flags == BufferFlags.StructuredAppendBuffer || Flags == BufferFlags.StructuredCounterBuffer)) - NativeDevice.CreateUnorderedAccessView(NativeResource, null, description, uav); - } - return uav; - } - - private void InitCountAndViewFormat(out int count, ref PixelFormat viewFormat) - { - if (Description.StructureByteStride == 0) - { - // TODO: The way to calculate the count is not always correct depending on the ViewFlags...etc. - if ((ViewFlags & BufferFlags.RawBuffer) != 0) - { - count = Description.SizeInBytes / sizeof(int); - } - else if ((ViewFlags & BufferFlags.ShaderResource) != 0) - { - count = Description.SizeInBytes / viewFormat.SizeInBytes(); - } - else - { - count = 0; - } - } - else - { - // For structured buffer - count = Description.SizeInBytes / Description.StructureByteStride; - viewFormat = PixelFormat.None; - } - } - - private static SharpDX.Direct3D12.ResourceDescription ConvertToNativeDescription(GraphicsDevice graphicsDevice, BufferDescription bufferDescription) - { - var flags = ResourceFlags.None; - var size = bufferDescription.SizeInBytes; - - // TODO D3D12 for now, ensure size is multiple of ConstantBufferDataPlacementAlignment (for cbuffer views) - size = MathUtil.AlignUp(size, graphicsDevice.ConstantBufferDataPlacementAlignment); - - if ((bufferDescription.BufferFlags & BufferFlags.UnorderedAccess) != 0) - flags |= ResourceFlags.AllowUnorderedAccess; - - return SharpDX.Direct3D12.ResourceDescription.Buffer(size, flags); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/CommandList.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/CommandList.Direct3D12.cs deleted file mode 100644 index 4728db8d93..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/CommandList.Direct3D12.cs +++ /dev/null @@ -1,1115 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using System.Collections.Generic; -using System.Threading; -using SharpDX; -using SharpDX.Direct3D12; -using SharpDX.Mathematics.Interop; -using Xenko.Core.Mathematics; -using Utilities = Xenko.Core.Utilities; - -namespace Xenko.Graphics -{ - public partial class CommandList - { - private DescriptorHeapCache srvHeap; - private int srvHeapOffset = GraphicsDevice.SrvHeapSize; - private DescriptorHeapCache samplerHeap; - private int samplerHeapOffset = GraphicsDevice.SamplerHeapSize; - - private PipelineState boundPipelineState; - private readonly DescriptorHeap[] descriptorHeaps = new DescriptorHeap[2]; - private readonly List resourceBarriers = new List(16); - - private readonly Dictionary srvMapping = new Dictionary(); - private readonly Dictionary samplerMapping = new Dictionary(); - - internal readonly Queue NativeCommandLists = new Queue(); - - private CompiledCommandList currentCommandList; - - private bool IsComputePipelineStateBound => boundPipelineState != null && boundPipelineState.IsCompute; - - public static CommandList New(GraphicsDevice device) - { - return new CommandList(device); - } - - private CommandList(GraphicsDevice device) : base(device) - { - Reset(); - } - - private void ResetCommandList() - { - if (NativeCommandLists.Count > 0) - { - currentCommandList.NativeCommandList = NativeCommandLists.Dequeue(); - currentCommandList.NativeCommandList.Reset(currentCommandList.NativeCommandAllocator, null); - } - else - { - currentCommandList.NativeCommandList = GraphicsDevice.NativeDevice.CreateCommandList(CommandListType.Direct, currentCommandList.NativeCommandAllocator, null); - } - - currentCommandList.NativeCommandList.SetDescriptorHeaps(2, descriptorHeaps); - } - - /// - protected internal override void OnDestroyed() - { - // Recycle heaps - ResetSrvHeap(false); - ResetSamplerHeap(false); - - // Available right now (NextFenceValue - 1) - // TODO: Note that it won't be available right away because CommandAllocators is currently not using a PriorityQueue but a simple Queue - if (currentCommandList.NativeCommandAllocator != null) - { - GraphicsDevice.CommandAllocators.RecycleObject(GraphicsDevice.NextFenceValue - 1, currentCommandList.NativeCommandAllocator); - currentCommandList.NativeCommandAllocator = null; - } - - if (currentCommandList.NativeCommandList != null) - { - NativeCommandLists.Enqueue(currentCommandList.NativeCommandList); - currentCommandList.NativeCommandList = null; - } - - while (NativeCommandLists.Count > 0) - { - NativeCommandLists.Dequeue().Dispose(); - } - - base.OnDestroyed(); - } - - public void Reset() - { - if (currentCommandList.Builder != null) - return; - - FlushResourceBarriers(); - ResetSrvHeap(true); - ResetSamplerHeap(true); - - // Clear descriptor mappings - srvMapping.Clear(); - samplerMapping.Clear(); - - currentCommandList.Builder = this; - currentCommandList.SrvHeaps = GraphicsDevice.DescriptorHeapLists.Acquire(); - currentCommandList.SamplerHeaps = GraphicsDevice.DescriptorHeapLists.Acquire(); - currentCommandList.StagingResources = GraphicsDevice.StagingResourceLists.Acquire(); - - // Get a new allocator and unused command list - currentCommandList.NativeCommandAllocator = GraphicsDevice.CommandAllocators.GetObject(); - ResetCommandList(); - - boundPipelineState = null; - } - - /// - /// Closes the command list for recording and returns an executable token. - /// - /// The executable command list. - public CompiledCommandList Close() - { - FlushResourceBarriers(); - - currentCommandList.NativeCommandList.Close(); - - // Staging resources not updated anymore - foreach (var stagingResource in currentCommandList.StagingResources) - { - stagingResource.StagingBuilder = null; - } - - // Recycle heaps - ResetSrvHeap(false); - ResetSamplerHeap(false); - - var result = currentCommandList; - currentCommandList = default(CompiledCommandList); - return result; - } - - /// - /// Closes and executes the command list. - /// - public void Flush() - { - GraphicsDevice.ExecuteCommandList(Close()); - } - - private void FlushInternal(bool wait) - { - var fenceValue = GraphicsDevice.ExecuteCommandListInternal(Close()); - - if (wait) - GraphicsDevice.WaitForFenceInternal(fenceValue); - - Reset(); - - // Restore states - if (boundPipelineState != null) - SetPipelineState(boundPipelineState); - currentCommandList.NativeCommandList.SetDescriptorHeaps(2, descriptorHeaps); - SetRenderTargetsImpl(depthStencilBuffer, renderTargetCount, renderTargets); - } - - private void ClearStateImpl() - { - } - - /// - /// Unbinds all depth-stencil buffer and render targets from the output-merger stage. - /// - private void ResetTargetsImpl() - { - } - - /// - /// Binds a depth-stencil buffer and a set of render targets to the output-merger stage. See to learn how to use it. - /// - /// The depth stencil buffer. - /// The render targets. - /// renderTargetViews - private void SetRenderTargetsImpl(Texture depthStencilBuffer, int renderTargetCount, Texture[] renderTargets) - { - var renderTargetHandles = new CpuDescriptorHandle[renderTargetCount]; - for (int i = 0; i < renderTargetHandles.Length; ++i) - { - renderTargetHandles[i] = renderTargets[i].NativeRenderTargetView; - } - currentCommandList.NativeCommandList.SetRenderTargets(renderTargetHandles, depthStencilBuffer?.NativeDepthStencilView); - } - - /// - /// Sets the stream targets. - /// - /// The buffers. - public void SetStreamTargets(params Buffer[] buffers) - { - } - - /// - /// Gets or sets the 1st viewport. See to learn how to use it. - /// - /// The viewport. - private void SetViewportImpl() - { - if (!viewportDirty && !scissorsDirty) - return; - - var viewport = viewports[0]; - if (viewportDirty) - { - currentCommandList.NativeCommandList.SetViewport(new RawViewportF { Width = viewport.Width, Height = viewport.Height, X = viewport.X, Y = viewport.Y, MinDepth = viewport.MinDepth, MaxDepth = viewport.MaxDepth }); - currentCommandList.NativeCommandList.SetScissorRectangles(new RawRectangle { Left = (int)viewport.X, Right = (int)viewport.X + (int)viewport.Width, Top = (int)viewport.Y, Bottom = (int)viewport.Y + (int)viewport.Height }); - viewportDirty = false; - } - - if (boundPipelineState?.HasScissorEnabled ?? false) - { - if (scissorsDirty) - { - // Use manual scissor - var scissor = scissors[0]; - currentCommandList.NativeCommandList.SetScissorRectangles(new RawRectangle { Left = scissor.Left, Right = scissor.Right, Top = scissor.Top, Bottom = scissor.Bottom }); - } - } - else - { - // Use viewport - // Always update, because either scissor or viewport was dirty and we use viewport size - currentCommandList.NativeCommandList.SetScissorRectangles(new RawRectangle { Left = (int)viewport.X, Right = (int)viewport.X + (int)viewport.Width, Top = (int)viewport.Y, Bottom = (int)viewport.Y + (int)viewport.Height }); - } - - scissorsDirty = false; - } - - /// - /// Prepares a draw call. This method is called before each Draw() method to setup the correct Primitive, InputLayout and VertexBuffers. - /// - /// Cannot GraphicsDevice.Draw*() without an effect being previously applied with Effect.Apply() method - private void PrepareDraw() - { - FlushResourceBarriers(); - SetViewportImpl(); - } - - public void SetStencilReference(int stencilReference) - { - currentCommandList.NativeCommandList.StencilReference = stencilReference; - } - - public void SetBlendFactor(Color4 blendFactor) - { - currentCommandList.NativeCommandList.BlendFactor = ColorHelper.ConvertToVector4(blendFactor); - } - - public void SetPipelineState(PipelineState pipelineState) - { - if (boundPipelineState != pipelineState && pipelineState?.CompiledState != null) - { - // If scissor state changed, force a refresh - scissorsDirty |= (boundPipelineState?.HasScissorEnabled ?? false) != pipelineState.HasScissorEnabled; - - currentCommandList.NativeCommandList.PipelineState = pipelineState.CompiledState; - if (pipelineState.IsCompute) - currentCommandList.NativeCommandList.SetComputeRootSignature(pipelineState.RootSignature); - else - currentCommandList.NativeCommandList.SetGraphicsRootSignature(pipelineState.RootSignature); - boundPipelineState = pipelineState; - currentCommandList.NativeCommandList.PrimitiveTopology = pipelineState.PrimitiveTopology; - } - } - - public void SetVertexBuffer(int index, Buffer buffer, int offset, int stride) - { - currentCommandList.NativeCommandList.SetVertexBuffer(index, new VertexBufferView - { - BufferLocation = buffer.NativeResource.GPUVirtualAddress + offset, - StrideInBytes = stride, - SizeInBytes = buffer.SizeInBytes - offset - }); - } - - public void SetIndexBuffer(Buffer buffer, int offset, bool is32Bits) - { - currentCommandList.NativeCommandList.SetIndexBuffer(buffer != null ? (IndexBufferView?)new IndexBufferView - { - BufferLocation = buffer.NativeResource.GPUVirtualAddress + offset, - Format = is32Bits ? SharpDX.DXGI.Format.R32_UInt : SharpDX.DXGI.Format.R16_UInt, - SizeInBytes = buffer.SizeInBytes - offset - } : null); - } - - public void ResourceBarrierTransition(GraphicsResource resource, GraphicsResourceState newState) - { - // Find parent resource - if (resource.ParentResource != null) - resource = resource.ParentResource; - - var targetState = (ResourceStates)newState; - if (resource.IsTransitionNeeded(targetState)) - { - resourceBarriers.Add(new ResourceTransitionBarrier(resource.NativeResource, -1, resource.NativeResourceState, targetState)); - resource.NativeResourceState = targetState; - } - } - - private unsafe void FlushResourceBarriers() - { - int count = resourceBarriers.Count; - if (count == 0) - return; - - var barriers = stackalloc ResourceBarrier[count]; - for (int i = 0; i < count; i++) - barriers[i] = resourceBarriers[i]; - resourceBarriers.Clear(); - - currentCommandList.NativeCommandList.ResourceBarrier(*barriers); - } - - public void SetDescriptorSets(int index, DescriptorSet[] descriptorSets) - { - RestartWithNewHeap: - var descriptorTableIndex = 0; - for (int i = 0; i < descriptorSets.Length; ++i) - { - // Find what is already mapped - var descriptorSet = descriptorSets[i]; - - var srvBindCount = boundPipelineState.SrvBindCounts[i]; - var samplerBindCount = boundPipelineState.SamplerBindCounts[i]; - - if (srvBindCount > 0 && (IntPtr)descriptorSet.SrvStart.Ptr != IntPtr.Zero) - { - GpuDescriptorHandle gpuSrvStart; - - // Check if we need to copy them to shader visible descriptor heap - if (!srvMapping.TryGetValue(descriptorSet.SrvStart.Ptr, out gpuSrvStart)) - { - var srvCount = descriptorSet.Description.SrvCount; - - // Make sure heap is big enough - if (srvHeapOffset + srvCount > GraphicsDevice.SrvHeapSize) - { - ResetSrvHeap(true); - currentCommandList.NativeCommandList.SetDescriptorHeaps(2, descriptorHeaps); - goto RestartWithNewHeap; - } - - // Copy - NativeDevice.CopyDescriptorsSimple(srvCount, srvHeap.CPUDescriptorHandleForHeapStart + srvHeapOffset * GraphicsDevice.SrvHandleIncrementSize, descriptorSet.SrvStart, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - - // Store mapping - srvMapping.Add(descriptorSet.SrvStart.Ptr, gpuSrvStart = srvHeap.GPUDescriptorHandleForHeapStart + srvHeapOffset * GraphicsDevice.SrvHandleIncrementSize); - - // Bump - srvHeapOffset += srvCount; - } - - // Bind resource tables (note: once per using stage, until we solve how to choose shader registers effect-wide at compile time) - if (IsComputePipelineStateBound) - { - for (int j = 0; j < srvBindCount; ++j) - currentCommandList.NativeCommandList.SetComputeRootDescriptorTable(descriptorTableIndex++, gpuSrvStart); - } - else - { - for (int j = 0; j < srvBindCount; ++j) - currentCommandList.NativeCommandList.SetGraphicsRootDescriptorTable(descriptorTableIndex++, gpuSrvStart); - } - } - - if (samplerBindCount > 0 && (IntPtr)descriptorSet.SamplerStart.Ptr != IntPtr.Zero) - { - GpuDescriptorHandle gpuSamplerStart; - - // Check if we need to copy them to shader visible descriptor heap - if (!samplerMapping.TryGetValue(descriptorSet.SamplerStart.Ptr, out gpuSamplerStart)) - { - var samplerCount = descriptorSet.Description.SamplerCount; - - // Make sure heap is big enough - if (samplerHeapOffset + samplerCount > GraphicsDevice.SamplerHeapSize) - { - ResetSamplerHeap(true); - currentCommandList.NativeCommandList.SetDescriptorHeaps(2, descriptorHeaps); - goto RestartWithNewHeap; - } - - // Copy - NativeDevice.CopyDescriptorsSimple(samplerCount, samplerHeap.CPUDescriptorHandleForHeapStart + samplerHeapOffset * GraphicsDevice.SamplerHandleIncrementSize, descriptorSet.SamplerStart, DescriptorHeapType.Sampler); - - // Store mapping - samplerMapping.Add(descriptorSet.SamplerStart.Ptr, gpuSamplerStart = samplerHeap.GPUDescriptorHandleForHeapStart + samplerHeapOffset * GraphicsDevice.SamplerHandleIncrementSize); - - // Bump - samplerHeapOffset += samplerCount; - } - - // Bind resource tables (note: once per using stage, until we solve how to choose shader registers effect-wide at compile time) - if (IsComputePipelineStateBound) - { - for (int j = 0; j < samplerBindCount; ++j) - currentCommandList.NativeCommandList.SetComputeRootDescriptorTable(descriptorTableIndex++, gpuSamplerStart); - } - else - { - for (int j = 0; j < samplerBindCount; ++j) - currentCommandList.NativeCommandList.SetGraphicsRootDescriptorTable(descriptorTableIndex++, gpuSamplerStart); - } - } - } - } - - private void ResetSrvHeap(bool createNewHeap) - { - if (srvHeap.Heap != null) - { - currentCommandList.SrvHeaps.Add(srvHeap.Heap); - srvHeap.Heap = null; - } - - if (createNewHeap) - { - srvHeap = new DescriptorHeapCache(GraphicsDevice.SrvHeaps.GetObject()); - srvHeapOffset = 0; - srvMapping.Clear(); - } - - descriptorHeaps[0] = srvHeap.Heap; - } - - private void ResetSamplerHeap(bool createNewHeap) - { - if (samplerHeap.Heap != null) - { - currentCommandList.SamplerHeaps.Add(samplerHeap.Heap); - samplerHeap.Heap = null; - } - - if (createNewHeap) - { - samplerHeap = new DescriptorHeapCache(GraphicsDevice.SamplerHeaps.GetObject()); - samplerHeapOffset = 0; - samplerMapping.Clear(); - } - - descriptorHeaps[1] = samplerHeap.Heap; - } - - /// - public void Dispatch(int threadCountX, int threadCountY, int threadCountZ) - { - PrepareDraw(); - - currentCommandList.NativeCommandList.Dispatch(threadCountX, threadCountY, threadCountZ); - } - - /// - /// Dispatches the specified indirect buffer. - /// - /// The indirect buffer. - /// The offset information bytes. - public void Dispatch(Buffer indirectBuffer, int offsetInBytes) - { - throw new NotImplementedException(); - } - - /// - /// Draw non-indexed, non-instanced primitives. - /// - /// Number of vertices to draw. - /// Index of the first vertex, which is usually an offset in a vertex buffer; it could also be used as the first vertex id generated for a shader parameter marked with the SV_TargetId system-value semantic. - public void Draw(int vertexCount, int startVertexLocation = 0) - { - PrepareDraw(); - - currentCommandList.NativeCommandList.DrawInstanced(vertexCount, 1, startVertexLocation, 0); - - GraphicsDevice.FrameTriangleCount += (uint)vertexCount; - GraphicsDevice.FrameDrawCalls++; - } - - /// - /// Draw geometry of an unknown size. - /// - public void DrawAuto() - { - PrepareDraw(); - - throw new NotImplementedException(); - } - - /// - /// Draw indexed, non-instanced primitives. - /// - /// Number of indices to draw. - /// The location of the first index read by the GPU from the index buffer. - /// A value added to each index before reading a vertex from the vertex buffer. - public void DrawIndexed(int indexCount, int startIndexLocation = 0, int baseVertexLocation = 0) - { - PrepareDraw(); - - currentCommandList.NativeCommandList.DrawIndexedInstanced(indexCount, 1, startIndexLocation, baseVertexLocation, 0); - - GraphicsDevice.FrameDrawCalls++; - GraphicsDevice.FrameTriangleCount += (uint)indexCount; - } - - /// - /// Draw indexed, instanced primitives. - /// - /// Number of indices read from the index buffer for each instance. - /// Number of instances to draw. - /// The location of the first index read by the GPU from the index buffer. - /// A value added to each index before reading a vertex from the vertex buffer. - /// A value added to each index before reading per-instance data from a vertex buffer. - public void DrawIndexedInstanced(int indexCountPerInstance, int instanceCount, int startIndexLocation = 0, int baseVertexLocation = 0, int startInstanceLocation = 0) - { - PrepareDraw(); - - currentCommandList.NativeCommandList.DrawIndexedInstanced(indexCountPerInstance, instanceCount, startIndexLocation, baseVertexLocation, startInstanceLocation); - - GraphicsDevice.FrameDrawCalls++; - GraphicsDevice.FrameTriangleCount += (uint)(indexCountPerInstance * instanceCount); - } - - /// - /// Draw indexed, instanced, GPU-generated primitives. - /// - /// A buffer containing the GPU generated primitives. - /// Offset in pBufferForArgs to the start of the GPU generated primitives. - public void DrawIndexedInstanced(Buffer argumentsBuffer, int alignedByteOffsetForArgs = 0) - { - if (argumentsBuffer == null) throw new ArgumentNullException("argumentsBuffer"); - - PrepareDraw(); - - //NativeDeviceContext.DrawIndexedInstancedIndirect(argumentsBuffer.NativeBuffer, alignedByteOffsetForArgs); - throw new NotImplementedException(); - - GraphicsDevice.FrameDrawCalls++; - } - - /// - /// Draw non-indexed, instanced primitives. - /// - /// Number of vertices to draw. - /// Number of instances to draw. - /// Index of the first vertex. - /// A value added to each index before reading per-instance data from a vertex buffer. - public void DrawInstanced(int vertexCountPerInstance, int instanceCount, int startVertexLocation = 0, int startInstanceLocation = 0) - { - PrepareDraw(); - - currentCommandList.NativeCommandList.DrawInstanced(vertexCountPerInstance, instanceCount, startVertexLocation, startInstanceLocation); - - GraphicsDevice.FrameDrawCalls++; - GraphicsDevice.FrameTriangleCount += (uint)(vertexCountPerInstance * instanceCount); - } - - /// - /// Draw instanced, GPU-generated primitives. - /// - /// An arguments buffer - /// Offset in pBufferForArgs to the start of the GPU generated primitives. - public void DrawInstanced(Buffer argumentsBuffer, int alignedByteOffsetForArgs = 0) - { - if (argumentsBuffer == null) throw new ArgumentNullException("argumentsBuffer"); - - PrepareDraw(); - - //NativeDeviceContext.DrawIndexedInstancedIndirect(argumentsBuffer.NativeBuffer, alignedByteOffsetForArgs); - throw new NotImplementedException(); - - GraphicsDevice.FrameDrawCalls++; - } - - /// - /// Begins profiling. - /// - /// Color of the profile. - /// The name. - public void BeginProfile(Color4 profileColor, string name) - { - //currentCommandList.NativeCommandList.BeginEvent(); - } - - /// - /// Ends profiling. - /// - public void EndProfile() - { - //currentCommandList.NativeCommandList.EndEvent(); - } - - /// - /// Submit a timestamp query. - /// - /// The QueryPool owning the query. - /// The query index. - public void WriteTimestamp(QueryPool queryPool, int index) - { - currentCommandList.NativeCommandList.EndQuery(queryPool.NativeQueryHeap, SharpDX.Direct3D12.QueryType.Timestamp, index); - queryPool.PendingValue = queryPool.CompletedValue + 1; - } - - public void ResetQueryPool(QueryPool queryPool) - { - } - - /// - /// Clears the specified depth stencil buffer. See to learn how to use it. - /// - /// The depth stencil buffer. - /// The options. - /// The depth. - /// The stencil. - /// - public void Clear(Texture depthStencilBuffer, DepthStencilClearOptions options, float depth = 1, byte stencil = 0) - { - ResourceBarrierTransition(GraphicsDevice.Presenter.DepthStencilBuffer, GraphicsResourceState.DepthWrite); - FlushResourceBarriers(); - currentCommandList.NativeCommandList.ClearDepthStencilView(depthStencilBuffer.NativeDepthStencilView, (ClearFlags)options, depth, stencil); - } - - /// - /// Clears the specified render target. See to learn how to use it. - /// - /// The render target. - /// The color. - /// renderTarget - public unsafe void Clear(Texture renderTarget, Color4 color) - { - ResourceBarrierTransition(renderTarget, GraphicsResourceState.RenderTarget); - FlushResourceBarriers(); - currentCommandList.NativeCommandList.ClearRenderTargetView(renderTarget.NativeRenderTargetView, *(RawColor4*)&color); - } - - /// - /// Clears a read-write Buffer. This buffer must have been created with read-write/unordered access. - /// - /// The buffer. - /// The value. - /// buffer - /// Expecting buffer supporting UAV;buffer - public unsafe void ClearReadWrite(Buffer buffer, Vector4 value) - { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); - if (buffer.NativeUnorderedAccessView.Ptr == PointerSize.Zero) throw new ArgumentException("Expecting buffer supporting UAV", nameof(buffer)); - - var cpuHandle = buffer.NativeUnorderedAccessView; - var gpuHandle = GetGpuDescriptorHandle(cpuHandle); - currentCommandList.NativeCommandList.ClearUnorderedAccessViewFloat(gpuHandle, cpuHandle, buffer.NativeResource, *(RawVector4*)&value, 0, null); - } - - /// - /// Clears a read-write Buffer. This buffer must have been created with read-write/unordered access. - /// - /// The buffer. - /// The value. - /// buffer - /// Expecting buffer supporting UAV;buffer - public unsafe void ClearReadWrite(Buffer buffer, Int4 value) - { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); - if (buffer.NativeUnorderedAccessView.Ptr == PointerSize.Zero) throw new ArgumentException("Expecting buffer supporting UAV", nameof(buffer)); - - var cpuHandle = buffer.NativeUnorderedAccessView; - var gpuHandle = GetGpuDescriptorHandle(cpuHandle); - currentCommandList.NativeCommandList.ClearUnorderedAccessViewUint(gpuHandle, cpuHandle, buffer.NativeResource, *(RawInt4*)&value, 0, null); - } - - /// - /// Clears a read-write Buffer. This buffer must have been created with read-write/unordered access. - /// - /// The buffer. - /// The value. - /// buffer - /// Expecting buffer supporting UAV;buffer - public unsafe void ClearReadWrite(Buffer buffer, UInt4 value) - { - if (buffer == null) throw new ArgumentNullException(nameof(buffer)); - if (buffer.NativeUnorderedAccessView.Ptr == PointerSize.Zero) throw new ArgumentException("Expecting buffer supporting UAV", nameof(buffer)); - - var cpuHandle = buffer.NativeUnorderedAccessView; - var gpuHandle = GetGpuDescriptorHandle(cpuHandle); - currentCommandList.NativeCommandList.ClearUnorderedAccessViewUint(gpuHandle, cpuHandle, buffer.NativeResource, *(RawInt4*)&value, 0, null); - } - - /// - /// Clears a read-write Texture. This texture must have been created with read-write/unordered access. - /// - /// The texture. - /// The value. - /// texture - /// Expecting texture supporting UAV;texture - public unsafe void ClearReadWrite(Texture texture, Vector4 value) - { - if (texture == null) throw new ArgumentNullException(nameof(texture)); - if (texture.NativeUnorderedAccessView.Ptr == PointerSize.Zero) throw new ArgumentException("Expecting texture supporting UAV", nameof(texture)); - - var cpuHandle = texture.NativeUnorderedAccessView; - var gpuHandle = GetGpuDescriptorHandle(cpuHandle); - currentCommandList.NativeCommandList.ClearUnorderedAccessViewFloat(gpuHandle, cpuHandle, texture.NativeResource, *(RawVector4*)&value, 0, null); - } - - /// - /// Clears a read-write Texture. This texture must have been created with read-write/unordered access. - /// - /// The texture. - /// The value. - /// texture - /// Expecting texture supporting UAV;texture - public unsafe void ClearReadWrite(Texture texture, Int4 value) - { - if (texture == null) throw new ArgumentNullException(nameof(texture)); - if (texture.NativeUnorderedAccessView.Ptr == PointerSize.Zero) throw new ArgumentException("Expecting texture supporting UAV", nameof(texture)); - - var cpuHandle = texture.NativeUnorderedAccessView; - var gpuHandle = GetGpuDescriptorHandle(cpuHandle); - currentCommandList.NativeCommandList.ClearUnorderedAccessViewUint(gpuHandle, cpuHandle, texture.NativeResource, *(RawInt4*)&value, 0, null); - } - - /// - /// Clears a read-write Texture. This texture must have been created with read-write/unordered access. - /// - /// The texture. - /// The value. - /// texture - /// Expecting texture supporting UAV;texture - public unsafe void ClearReadWrite(Texture texture, UInt4 value) - { - if (texture == null) throw new ArgumentNullException(nameof(texture)); - if (texture.NativeUnorderedAccessView.Ptr == PointerSize.Zero) throw new ArgumentException("Expecting texture supporting UAV", nameof(texture)); - - var cpuHandle = texture.NativeUnorderedAccessView; - var gpuHandle = GetGpuDescriptorHandle(cpuHandle); - currentCommandList.NativeCommandList.ClearUnorderedAccessViewUint(gpuHandle, cpuHandle, texture.NativeResource, *(RawInt4*)&value, 0, null); - } - - private GpuDescriptorHandle GetGpuDescriptorHandle(CpuDescriptorHandle cpuHandle) - { - GpuDescriptorHandle result; - if (!srvMapping.TryGetValue(cpuHandle.Ptr, out result)) - { - var srvCount = 1; - - // Make sure heap is big enough - if (srvHeapOffset + srvCount > GraphicsDevice.SrvHeapSize) - { - ResetSrvHeap(true); - currentCommandList.NativeCommandList.SetDescriptorHeaps(2, descriptorHeaps); - } - - // Copy - NativeDevice.CopyDescriptorsSimple(srvCount, srvHeap.CPUDescriptorHandleForHeapStart + srvHeapOffset * GraphicsDevice.SrvHandleIncrementSize, cpuHandle, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - - // Store mapping - srvMapping.Add(cpuHandle.Ptr, result = srvHeap.GPUDescriptorHandleForHeapStart + srvHeapOffset * GraphicsDevice.SrvHandleIncrementSize); - - // Bump - srvHeapOffset += srvCount; - } - - return result; - } - - public void Copy(GraphicsResource source, GraphicsResource destination) - { - // Copy texture -> texture - if (source is Texture sourceTexture && destination is Texture destinationTexture) - { - var sourceParent = sourceTexture.ParentTexture ?? sourceTexture; - var destinationParent = destinationTexture.ParentTexture ?? destinationTexture; - - if (destinationTexture.Usage == GraphicsResourceUsage.Staging) - { - // Copy staging texture -> staging texture - if (sourceTexture.Usage == GraphicsResourceUsage.Staging) - { - var size = destinationTexture.ComputeBufferTotalSize(); - var destinationMapped = destinationTexture.NativeResource.Map(0); - var sourceMapped = sourceTexture.NativeResource.Map(0, new Range { Begin = 0, End = size }); - - Utilities.CopyMemory(destinationMapped, sourceMapped, size); - - sourceTexture.NativeResource.Unmap(0); - destinationTexture.NativeResource.Unmap(0); - } - else - { - ResourceBarrierTransition(sourceTexture, GraphicsResourceState.CopySource); - ResourceBarrierTransition(destinationTexture, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - - int copyOffset = 0; - for (int arraySlice = 0; arraySlice < sourceParent.ArraySize; ++arraySlice) - { - for (int mipLevel = 0; mipLevel < sourceParent.MipLevels; ++mipLevel) - { - currentCommandList.NativeCommandList.CopyTextureRegion(new TextureCopyLocation(destinationTexture.NativeResource, - new PlacedSubResourceFootprint - { - Footprint = - { - Width = Texture.CalculateMipSize(destinationTexture.Width, mipLevel), - Height = Texture.CalculateMipSize(destinationTexture.Height, mipLevel), - Depth = Texture.CalculateMipSize(destinationTexture.Depth, mipLevel), - Format = (SharpDX.DXGI.Format)destinationTexture.Format, - RowPitch = destinationTexture.ComputeRowPitch(mipLevel), - }, - Offset = copyOffset, - }), 0, 0, 0, new TextureCopyLocation(sourceTexture.NativeResource, arraySlice * sourceParent.MipLevels + mipLevel), null); - - copyOffset += destinationTexture.ComputeSubresourceSize(mipLevel); - } - } - } - - // Fence for host access - destinationParent.StagingFenceValue = null; - destinationParent.StagingBuilder = this; - currentCommandList.StagingResources.Add(destinationParent); - } - else - { - ResourceBarrierTransition(sourceTexture, GraphicsResourceState.CopySource); - ResourceBarrierTransition(destinationTexture, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - - currentCommandList.NativeCommandList.CopyResource(destinationTexture.NativeResource, sourceTexture.NativeResource); - } - } - // Copy buffer -> buffer - else if (source is Buffer sourceBuffer && destination is Buffer destinationBuffer) - { - ResourceBarrierTransition(sourceBuffer, GraphicsResourceState.CopySource); - ResourceBarrierTransition(destinationBuffer, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - - currentCommandList.NativeCommandList.CopyResource(destinationBuffer.NativeResource, sourceBuffer.NativeResource); - - if (destinationBuffer.Usage == GraphicsResourceUsage.Staging) - { - // Fence for host access - destinationBuffer.StagingFenceValue = null; - destinationBuffer.StagingBuilder = this; - currentCommandList.StagingResources.Add(destinationBuffer); - } - } - else - { - throw new NotImplementedException(); - } - } - - public void CopyMultisample(Texture sourceMultisampleTexture, int sourceSubResource, Texture destTexture, int destSubResource, PixelFormat format = PixelFormat.None) - { - if (sourceMultisampleTexture == null) throw new ArgumentNullException(nameof(sourceMultisampleTexture)); - if (destTexture == null) throw new ArgumentNullException(nameof(destTexture)); - if (!sourceMultisampleTexture.IsMultisample) throw new ArgumentOutOfRangeException(nameof(sourceMultisampleTexture), "Source texture is not a MSAA texture"); - - currentCommandList.NativeCommandList.ResolveSubresource(sourceMultisampleTexture.NativeResource, sourceSubResource, destTexture.NativeResource, destSubResource, (SharpDX.DXGI.Format)(format == PixelFormat.None ? destTexture.Format : format)); - } - - public void CopyRegion(GraphicsResource source, int sourceSubresource, ResourceRegion? sourceRegion, GraphicsResource destination, int destinationSubResource, int dstX = 0, int dstY = 0, int dstZ = 0) - { - if (source is Texture sourceTexture && destination is Texture destinationTexture) - { - if (sourceTexture.Usage == GraphicsResourceUsage.Staging || destinationTexture.Usage == GraphicsResourceUsage.Staging) - { - throw new NotImplementedException("Copy region of staging resources is not supported yet"); - } - - ResourceBarrierTransition(source, GraphicsResourceState.CopySource); - ResourceBarrierTransition(destination, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - - currentCommandList.NativeCommandList.CopyTextureRegion( - new TextureCopyLocation(destination.NativeResource, destinationSubResource), - dstX, dstY, dstZ, - new TextureCopyLocation(source.NativeResource, sourceSubresource), - sourceRegion.HasValue - ? (SharpDX.Direct3D12.ResourceRegion?)new SharpDX.Direct3D12.ResourceRegion - { - Left = sourceRegion.Value.Left, - Top = sourceRegion.Value.Top, - Front = sourceRegion.Value.Front, - Right = sourceRegion.Value.Right, - Bottom = sourceRegion.Value.Bottom, - Back = sourceRegion.Value.Back - } - : null); - } - else if (source is Buffer && destination is Buffer) - { - ResourceBarrierTransition(source, GraphicsResourceState.CopySource); - ResourceBarrierTransition(destination, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - - currentCommandList.NativeCommandList.CopyBufferRegion(destination.NativeResource, dstX, - source.NativeResource, sourceRegion?.Left ?? 0, sourceRegion.HasValue ? sourceRegion.Value.Right - sourceRegion.Value.Left : ((Buffer)source).SizeInBytes); - } - else - { - throw new InvalidOperationException("Cannot copy data between buffer and texture."); - } - } - - /// - public void CopyCount(Buffer sourceBuffer, Buffer destBuffer, int offsetInBytes) - { - if (sourceBuffer == null) throw new ArgumentNullException(nameof(sourceBuffer)); - if (destBuffer == null) throw new ArgumentNullException(nameof(destBuffer)); - - currentCommandList.NativeCommandList.CopyBufferRegion(destBuffer.NativeResource, offsetInBytes, sourceBuffer.NativeResource, 0, 4); - } - - internal void UpdateSubresource(GraphicsResource resource, int subResourceIndex, DataBox databox) - { - ResourceRegion region; - var texture = resource as Texture; - if (texture != null) - { - region = new ResourceRegion(0, 0, 0, texture.Width, texture.Height, texture.Depth); - } - else - { - var buffer = resource as Buffer; - if (buffer != null) - { - region = new ResourceRegion(0, 0, 0, buffer.SizeInBytes, 1, 1); - } - else - { - throw new InvalidOperationException("Unknown resource type"); - } - } - - UpdateSubresource(resource, subResourceIndex, databox, region); - } - - internal void UpdateSubresource(GraphicsResource resource, int subResourceIndex, DataBox databox, ResourceRegion region) - { - var texture = resource as Texture; - if (texture != null) - { - var width = region.Right - region.Left; - var height = region.Bottom - region.Top; - var depth = region.Back - region.Front; - - ResourceDescription resourceDescription; - switch (texture.Dimension) - { - case TextureDimension.Texture1D: - resourceDescription = ResourceDescription.Texture1D((SharpDX.DXGI.Format)texture.Format, width, 1, 1); - break; - case TextureDimension.Texture2D: - case TextureDimension.TextureCube: - resourceDescription = ResourceDescription.Texture2D((SharpDX.DXGI.Format)texture.Format, width, height, 1, 1); - break; - case TextureDimension.Texture3D: - resourceDescription = ResourceDescription.Texture3D((SharpDX.DXGI.Format)texture.Format, width, height, (short)depth, 1); - break; - default: - throw new ArgumentOutOfRangeException(); - } - - // TODO D3D12 allocate in upload heap (placed resources?) - var nativeUploadTexture = NativeDevice.CreateCommittedResource(new HeapProperties(CpuPageProperty.WriteBack, MemoryPool.L0), HeapFlags.None, - resourceDescription, - ResourceStates.GenericRead); - - GraphicsDevice.TemporaryResources.Enqueue(new KeyValuePair(GraphicsDevice.NextFenceValue, nativeUploadTexture)); - - nativeUploadTexture.WriteToSubresource(0, null, databox.DataPointer, databox.RowPitch, databox.SlicePitch); - - // Trigger copy - ResourceBarrierTransition(resource, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - currentCommandList.NativeCommandList.CopyTextureRegion(new TextureCopyLocation(resource.NativeResource, subResourceIndex), region.Left, region.Top, region.Front, new TextureCopyLocation(nativeUploadTexture, 0), null); - } - else - { - var buffer = resource as Buffer; - if (buffer != null) - { - Resource uploadResource; - int uploadOffset; - var uploadSize = region.Right - region.Left; - var uploadMemory = GraphicsDevice.AllocateUploadBuffer(region.Right - region.Left, out uploadResource, out uploadOffset); - - Utilities.CopyMemory(uploadMemory, databox.DataPointer, uploadSize); - - ResourceBarrierTransition(resource, GraphicsResourceState.CopyDestination); - FlushResourceBarriers(); - currentCommandList.NativeCommandList.CopyBufferRegion(resource.NativeResource, region.Left, uploadResource, uploadOffset, uploadSize); - } - else - { - throw new InvalidOperationException("Unknown resource type"); - } - } - } - - // TODO GRAPHICS REFACTOR what should we do with this? - /// - /// Maps a subresource. - /// - /// The resource. - /// Index of the sub resource. - /// The map mode. - /// if set to true this method will return immediately if the resource is still being used by the GPU for writing. Default is false - /// The offset information in bytes. - /// The length information in bytes. - /// Pointer to the sub resource to map. - public MappedResource MapSubresource(GraphicsResource resource, int subResourceIndex, MapMode mapMode, bool doNotWait = false, int offsetInBytes = 0, int lengthInBytes = 0) - { - if (resource == null) throw new ArgumentNullException("resource"); - - var rowPitch = 0; - var depthStride = 0; - var usage = GraphicsResourceUsage.Default; - - var texture = resource as Texture; - if (texture != null) - { - usage = texture.Usage; - if (lengthInBytes == 0) - lengthInBytes = texture.ComputeSubresourceSize(subResourceIndex); - - rowPitch = texture.ComputeRowPitch(subResourceIndex % texture.MipLevels); - depthStride = texture.ComputeSlicePitch(subResourceIndex % texture.MipLevels); - - if (texture.Usage == GraphicsResourceUsage.Staging) - { - // Internally it's a buffer, so adapt resource index and offset - offsetInBytes = texture.ComputeBufferOffset(subResourceIndex, 0); - subResourceIndex = 0; - } - } - else - { - var buffer = resource as Buffer; - if (buffer != null) - { - usage = buffer.Usage; - if (lengthInBytes == 0) - lengthInBytes = buffer.SizeInBytes; - } - } - - if (mapMode == MapMode.Read || mapMode == MapMode.ReadWrite || mapMode == MapMode.Write) - { - // Is non-staging ever possible for Read/Write? - if (usage != GraphicsResourceUsage.Staging) - throw new InvalidOperationException(); - } - - if (mapMode == MapMode.WriteDiscard) - { - throw new InvalidOperationException("Can't use WriteDiscard on Graphics API that don't support renaming"); - } - - if (mapMode != MapMode.WriteNoOverwrite) - { - // Need to wait? - if (!resource.StagingFenceValue.HasValue || !GraphicsDevice.IsFenceCompleteInternal(resource.StagingFenceValue.Value)) - { - if (doNotWait) - { - return new MappedResource(resource, subResourceIndex, new DataBox(IntPtr.Zero, 0, 0)); - } - - // Need to flush? (i.e. part of) - if (resource.StagingBuilder == this) - FlushInternal(false); - - if (!resource.StagingFenceValue.HasValue) - throw new InvalidOperationException("CommandList updating the staging resource has not been submitted"); - - GraphicsDevice.WaitForFenceInternal(resource.StagingFenceValue.Value); - } - } - - var mappedMemory = resource.NativeResource.Map(subResourceIndex) + offsetInBytes; - return new MappedResource(resource, subResourceIndex, new DataBox(mappedMemory, rowPitch, depthStride), offsetInBytes, lengthInBytes); - } - - // TODO GRAPHICS REFACTOR what should we do with this? - public void UnmapSubresource(MappedResource unmapped) - { - unmapped.Resource.NativeResource.Unmap(unmapped.SubResourceIndex); - } - - // Contains a DescriptorHeap and cache its GPU and CPU pointers - struct DescriptorHeapCache - { - public DescriptorHeapCache(DescriptorHeap heap) : this() - { - Heap = heap; - if (heap != null) - { - CPUDescriptorHandleForHeapStart = heap.CPUDescriptorHandleForHeapStart; - GPUDescriptorHandleForHeapStart = heap.GPUDescriptorHandleForHeapStart; - } - } - - public DescriptorHeap Heap; - public CpuDescriptorHandle CPUDescriptorHandleForHeapStart; - public GpuDescriptorHandle GPUDescriptorHandleForHeapStart; - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/CompiledCommandList.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/CompiledCommandList.Direct3D12.cs deleted file mode 100644 index b47788bce2..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/CompiledCommandList.Direct3D12.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System.Collections.Generic; -using SharpDX.Direct3D12; - -namespace Xenko.Graphics -{ - public partial struct CompiledCommandList - { - internal CommandList Builder; - internal GraphicsCommandList NativeCommandList; - internal CommandAllocator NativeCommandAllocator; - internal List SrvHeaps; - internal List SamplerHeaps; - internal List StagingResources; - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/DescriptorPool.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/DescriptorPool.Direct3D12.cs deleted file mode 100644 index 1cfc06744d..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/DescriptorPool.Direct3D12.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using SharpDX.Direct3D12; -using Xenko.Shaders; - -namespace Xenko.Graphics -{ - public partial class DescriptorPool - { - internal DescriptorHeap SrvHeap; - internal DescriptorHeap SamplerHeap; - - internal CpuDescriptorHandle SrvStart; - internal int SrvOffset; - internal int SrvCount; - internal CpuDescriptorHandle SamplerStart; - internal int SamplerOffset; - internal int SamplerCount; - - public void Reset() - { - SrvOffset = 0; - SamplerOffset = 0; - } - - private DescriptorPool(GraphicsDevice graphicsDevice, DescriptorTypeCount[] counts) : base(graphicsDevice) - { - // For now, we put everything together so let's compute total count - foreach (var count in counts) - { - if (count.Type == EffectParameterClass.Sampler) - SamplerCount += count.Count; - else - SrvCount += count.Count; - } - - if (SrvCount > 0) - { - SrvHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription - { - DescriptorCount = SrvCount, - Flags = DescriptorHeapFlags.None, - Type = DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView, - }); - SrvStart = SrvHeap.CPUDescriptorHandleForHeapStart; - } - - if (SamplerCount > 0) - { - SamplerHeap = graphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription - { - DescriptorCount = SamplerCount, - Flags = DescriptorHeapFlags.None, - Type = DescriptorHeapType.Sampler, - }); - SamplerStart = SamplerHeap.CPUDescriptorHandleForHeapStart; - } - } - - protected internal override void OnDestroyed() - { - ReleaseComObject(ref SrvHeap); - ReleaseComObject(ref SamplerHeap); - - base.OnDestroyed(); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/DescriptorSet.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/DescriptorSet.Direct3D12.cs deleted file mode 100644 index 40d4adb0ce..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/DescriptorSet.Direct3D12.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using SharpDX; -using SharpDX.Direct3D12; -using Xenko.Shaders; - -namespace Xenko.Graphics -{ - public partial struct DescriptorSet - { - internal readonly GraphicsDevice Device; - internal readonly int[] BindingOffsets; - internal readonly DescriptorSetLayout Description; - - internal readonly CpuDescriptorHandle SrvStart; - internal readonly CpuDescriptorHandle SamplerStart; - - public bool IsValid => Description != null; - - private DescriptorSet(GraphicsDevice graphicsDevice, DescriptorPool pool, DescriptorSetLayout desc) - { - if (pool.SrvOffset + desc.SrvCount > pool.SrvCount || pool.SamplerOffset + desc.SamplerCount > pool.SamplerCount) - { - // Eearly exit if OOM, IsValid should return false (TODO: different mechanism?) - Device = null; - BindingOffsets = null; - Description = null; - SrvStart = new CpuDescriptorHandle(); - SamplerStart = new CpuDescriptorHandle(); - return; - } - - Device = graphicsDevice; - BindingOffsets = desc.BindingOffsets; - Description = desc; - - // Store start CpuDescriptorHandle - SrvStart = desc.SrvCount > 0 ? (pool.SrvStart + graphicsDevice.SrvHandleIncrementSize * pool.SrvOffset) : new CpuDescriptorHandle(); - SamplerStart = desc.SamplerCount > 0 ? (pool.SamplerStart + graphicsDevice.SamplerHandleIncrementSize * pool.SamplerOffset) : new CpuDescriptorHandle(); - - // Allocation is done, bump offsets - // TODO D3D12 thread safety? - pool.SrvOffset += desc.SrvCount; - pool.SamplerOffset += desc.SamplerCount; - } - - /// - /// Sets a descriptor. - /// - /// The slot. - /// The descriptor. - public void SetValue(int slot, object value) - { - var srv = value as GraphicsResource; - if (srv != null) - { - SetShaderResourceView(slot, srv); - } - else - { - var sampler = value as SamplerState; - if (sampler != null) - { - SetSamplerState(slot, sampler); - } - } - } - - /// - /// Sets a shader resource view descriptor. - /// - /// The slot. - /// The shader resource view. - public void SetShaderResourceView(int slot, GraphicsResource shaderResourceView) - { - if (shaderResourceView.NativeShaderResourceView.Ptr == PointerSize.Zero) - return; - Device.NativeDevice.CopyDescriptorsSimple(1, SrvStart + BindingOffsets[slot], shaderResourceView.NativeShaderResourceView, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - } - - /// - /// Sets a sampler state descriptor. - /// - /// The slot. - /// The sampler state. - public void SetSamplerState(int slot, SamplerState samplerState) - { - // For now, immutable samplers appears in the descriptor set and should be ignored - // TODO GRAPHICS REFACTOR can't we just hide them somehow? - var bindingSlot = BindingOffsets[slot]; - if (bindingSlot == -1) - return; - - Device.NativeDevice.CopyDescriptorsSimple(1, SamplerStart + BindingOffsets[slot], samplerState.NativeSampler, DescriptorHeapType.Sampler); - } - - /// - /// Sets a constant buffer view descriptor. - /// - /// The slot. - /// The constant buffer. - /// The constant buffer view start offset. - /// The constant buffer view size. - public void SetConstantBuffer(int slot, Buffer buffer, int offset, int size) - { - var constantBufferDataPlacementAlignment = Device.ConstantBufferDataPlacementAlignment; - Device.NativeDevice.CreateConstantBufferView(new ConstantBufferViewDescription - { - BufferLocation = buffer.GPUVirtualAddress + offset, - SizeInBytes = (size + constantBufferDataPlacementAlignment) / constantBufferDataPlacementAlignment * constantBufferDataPlacementAlignment, // CB size needs to be 256-byte aligned - }, SrvStart + BindingOffsets[slot]); - } - - /// - /// Sets an unordered access view descriptor. - /// - /// The slot. - /// The unordered access view. - public void SetUnorderedAccessView(int slot, GraphicsResource unorderedAccessView) - { - if (unorderedAccessView.NativeUnorderedAccessView.Ptr == PointerSize.Zero) - throw new ArgumentException($"Resource \'{unorderedAccessView}\' has missing Unordered Access View."); - Device.NativeDevice.CopyDescriptorsSimple(1, SrvStart + BindingOffsets[slot], unorderedAccessView.NativeUnorderedAccessView, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/DescriptorSetLayout.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/DescriptorSetLayout.Direct3D12.cs deleted file mode 100644 index 919d2ced53..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/DescriptorSetLayout.Direct3D12.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using Xenko.Shaders; - -#if XENKO_GRAPHICS_API_DIRECT3D12 - -namespace Xenko.Graphics -{ - public partial class DescriptorSetLayout - { - internal int SrvCount; - internal int SamplerCount; - - // Need to remap for proper separation of samplers from the rest - internal int[] BindingOffsets; - - private DescriptorSetLayout(GraphicsDevice device, DescriptorSetLayoutBuilder builder) - { - BindingOffsets = new int[builder.ElementCount]; - int currentBindingOffset = 0; - foreach (var entry in builder.Entries) - { - // We will both setup BindingOffsets and increment SamplerCount/SrvCount at the same time - if (entry.Class == EffectParameterClass.Sampler) - { - for (int i = 0; i < entry.ArraySize; ++i) - BindingOffsets[currentBindingOffset++] = entry.ImmutableSampler != null ? -1 : SamplerCount++ * device.SamplerHandleIncrementSize; - } - else - { - for (int i = 0; i < entry.ArraySize; ++i) - BindingOffsets[currentBindingOffset++] = SrvCount++ * device.SrvHandleIncrementSize; - } - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsDevice.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/GraphicsDevice.Direct3D12.cs deleted file mode 100644 index f6dd62ec47..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsDevice.Direct3D12.cs +++ /dev/null @@ -1,714 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Threading; -using SharpDX.Direct3D12; -using Xenko.Core.Collections; -using Xenko.Core.Threading; - -namespace Xenko.Graphics -{ - public partial class GraphicsDevice - { - // D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT (not exposed by SharpDX) - internal readonly int ConstantBufferDataPlacementAlignment = 256; - - private const GraphicsPlatform GraphicPlatform = GraphicsPlatform.Direct3D12; - - internal readonly ConcurrentPool> StagingResourceLists = new ConcurrentPool>(() => new List()); - internal readonly ConcurrentPool> DescriptorHeapLists = new ConcurrentPool>(() => new List()); - - private bool simulateReset = false; - private string rendererName; - - private SharpDX.Direct3D12.Device nativeDevice; - internal CommandQueue NativeCommandQueue; - - internal GraphicsProfile RequestedProfile; - internal SharpDX.Direct3D.FeatureLevel CurrentFeatureLevel; - - internal CommandQueue NativeCopyCommandQueue; - internal CommandAllocator NativeCopyCommandAllocator; - internal GraphicsCommandList NativeCopyCommandList; - private Fence nativeCopyFence; - private long nextCopyFenceValue = 1; - - internal CommandAllocatorPool CommandAllocators; - internal HeapPool SrvHeaps; - internal HeapPool SamplerHeaps; - internal const int SrvHeapSize = 2048; - internal const int SamplerHeapSize = 64; - - internal DescriptorAllocator SamplerAllocator; - internal DescriptorAllocator ShaderResourceViewAllocator; - internal DescriptorAllocator UnorderedAccessViewAllocator => ShaderResourceViewAllocator; - internal DescriptorAllocator DepthStencilViewAllocator; - internal DescriptorAllocator RenderTargetViewAllocator; - - private SharpDX.Direct3D12.Resource nativeUploadBuffer; - private IntPtr nativeUploadBufferStart; - private int nativeUploadBufferOffset; - - internal int SrvHandleIncrementSize; - internal int SamplerHandleIncrementSize; - - private Fence nativeFence; - private long lastCompletedFence; - internal long NextFenceValue = 1; - private AutoResetEvent fenceEvent = new AutoResetEvent(false); - - // Temporary or destroyed resources kept around until the GPU doesn't need them anymore - internal Queue> TemporaryResources = new Queue>(); - - private readonly FastList nativeCommandLists = new FastList(); - - /// - /// The tick frquency of timestamp queries in Hertz. - /// - public long TimestampFrequency { get; private set; } - - /// - /// Gets the status of this device. - /// - /// The graphics device status. - public GraphicsDeviceStatus GraphicsDeviceStatus - { - get - { - if (simulateReset) - { - simulateReset = false; - return GraphicsDeviceStatus.Reset; - } - - var result = NativeDevice.DeviceRemovedReason; - if (result == SharpDX.DXGI.ResultCode.DeviceRemoved) - { - return GraphicsDeviceStatus.Removed; - } - - if (result == SharpDX.DXGI.ResultCode.DeviceReset) - { - return GraphicsDeviceStatus.Reset; - } - - if (result == SharpDX.DXGI.ResultCode.DeviceHung) - { - return GraphicsDeviceStatus.Hung; - } - - if (result == SharpDX.DXGI.ResultCode.DriverInternalError) - { - return GraphicsDeviceStatus.InternalError; - } - - if (result == SharpDX.DXGI.ResultCode.InvalidCall) - { - return GraphicsDeviceStatus.InvalidCall; - } - - if (result.Code < 0) - { - return GraphicsDeviceStatus.Reset; - } - - return GraphicsDeviceStatus.Normal; - } - } - - /// - /// Gets the native device. - /// - /// The native device. - internal SharpDX.Direct3D12.Device NativeDevice - { - get - { - return nativeDevice; - } - } - - /// - /// Marks context as active on the current thread. - /// - public void Begin() - { - FrameTriangleCount = 0; - FrameDrawCalls = 0; - } - - /// - /// Enables profiling. - /// - /// if set to true [enabled flag]. - public void EnableProfile(bool enabledFlag) - { - } - - /// - /// Unmarks context as active on the current thread. - /// - public void End() - { - } - - /// - /// Executes a deferred command list. - /// - /// The deferred command list. - public void ExecuteCommandList(CompiledCommandList commandList) - { - ExecuteCommandListInternal(commandList); - } - - /// - /// Executes multiple deferred command lists. - /// - /// Number of command lists to execute. - /// The deferred command lists. - public void ExecuteCommandLists(int count, CompiledCommandList[] commandLists) - { - if (commandLists == null) throw new ArgumentNullException(nameof(commandLists)); - if (count > commandLists.Length) throw new ArgumentOutOfRangeException(nameof(count)); - - var fenceValue = NextFenceValue++; - - // Recycle resources - for (int index = 0; index < count; index++) - { - var commandList = commandLists[index]; - nativeCommandLists.Add(commandList.NativeCommandList); - RecycleCommandListResources(commandList, fenceValue); - } - - // Submit and signal fence - NativeCommandQueue.ExecuteCommandLists(count, nativeCommandLists.Items); - NativeCommandQueue.Signal(nativeFence, fenceValue); - - ReleaseTemporaryResources(); - - nativeCommandLists.Clear(); - } - - public void SimulateReset() - { - simulateReset = true; - } - - private void InitializePostFeatures() - { - } - - private string GetRendererName() - { - return rendererName; - } - - /// - /// Initializes the specified device. - /// - /// The graphics profiles. - /// The device creation flags. - /// The window handle. - private void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, object windowHandle) - { - if (nativeDevice != null) - { - // Destroy previous device - ReleaseDevice(); - } - - rendererName = Adapter.NativeAdapter.Description.Description; - - // Profiling is supported through pix markers - IsProfilingSupported = true; - - // Command lists are thread-safe and execute deferred - IsDeferred = true; - - bool isDebug = (deviceCreationFlags & DeviceCreationFlags.Debug) != 0; - if (isDebug) - { - SharpDX.Direct3D12.DebugInterface.Get().EnableDebugLayer(); - } - - // Default fallback - if (graphicsProfiles.Length == 0) - graphicsProfiles = new[] { GraphicsProfile.Level_11_0 }; - - // Create Device D3D12 with feature Level based on profile - for (int index = 0; index < graphicsProfiles.Length; index++) - { - var graphicsProfile = graphicsProfiles[index]; - try - { - // D3D12 supports only feature level 11+ - var level = graphicsProfile.ToFeatureLevel(); - if (level < SharpDX.Direct3D.FeatureLevel.Level_11_0) - level = SharpDX.Direct3D.FeatureLevel.Level_11_0; - - nativeDevice = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, level); - - RequestedProfile = graphicsProfile; - CurrentFeatureLevel = level; - break; - } - catch (Exception) - { - if (index == graphicsProfiles.Length - 1) - throw; - } - } - - // Describe and create the command queue. - var queueDesc = new SharpDX.Direct3D12.CommandQueueDescription(SharpDX.Direct3D12.CommandListType.Direct); - NativeCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); - //queueDesc.Type = CommandListType.Copy; - NativeCopyCommandQueue = nativeDevice.CreateCommandQueue(queueDesc); - TimestampFrequency = NativeCommandQueue.TimestampFrequency; - - SrvHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - SamplerHandleIncrementSize = NativeDevice.GetDescriptorHandleIncrementSize(DescriptorHeapType.Sampler); - - if (isDebug) - { - var debugDevice = nativeDevice.QueryInterfaceOrNull(); - if (debugDevice != null) - { - var infoQueue = debugDevice.QueryInterfaceOrNull(); - if (infoQueue != null) - { - MessageId[] disabledMessages = - { - // This happens when render target or depth stencil clear value is diffrent - // than provided during resource allocation. - MessageId.CleardepthstencilviewMismatchingclearvalue, - MessageId.ClearrendertargetviewMismatchingclearvalue, - - // This occurs when there are uninitialized descriptors in a descriptor table, - // even when a shader does not access the missing descriptors. - MessageId.InvalidDescriptorHandle, - - // These happen when capturing with VS diagnostics - MessageId.MapInvalidNullRange, - MessageId.UnmapInvalidNullRange, - }; - - // Disable irrelevant debug layer warnings - InfoQueueFilter filter = new InfoQueueFilter - { - DenyList = new InfoQueueFilterDescription - { - Ids = disabledMessages - } - }; - infoQueue.AddStorageFilterEntries(filter); - - //infoQueue.SetBreakOnSeverity(MessageSeverity.Error, true); - //infoQueue.SetBreakOnSeverity(MessageSeverity.Warning, true); - - infoQueue.Dispose(); - } - debugDevice.Dispose(); - } - } - - // Prepare pools - CommandAllocators = new CommandAllocatorPool(this); - SrvHeaps = new HeapPool(this, SrvHeapSize, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - SamplerHeaps = new HeapPool(this, SamplerHeapSize, DescriptorHeapType.Sampler); - - // Prepare descriptor allocators - SamplerAllocator = new DescriptorAllocator(this, DescriptorHeapType.Sampler); - ShaderResourceViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.ConstantBufferViewShaderResourceViewUnorderedAccessView); - DepthStencilViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.DepthStencilView); - RenderTargetViewAllocator = new DescriptorAllocator(this, DescriptorHeapType.RenderTargetView); - - // Prepare copy command list (start it closed, so that every new use start with a Reset) - NativeCopyCommandAllocator = NativeDevice.CreateCommandAllocator(CommandListType.Direct); - NativeCopyCommandList = NativeDevice.CreateCommandList(CommandListType.Direct, NativeCopyCommandAllocator, null); - NativeCopyCommandList.Close(); - - // Fence for next frame and resource cleaning - nativeFence = NativeDevice.CreateFence(0, FenceFlags.None); - nativeCopyFence = NativeDevice.CreateFence(0, FenceFlags.None); - } - - internal IntPtr AllocateUploadBuffer(int size, out SharpDX.Direct3D12.Resource resource, out int offset, int alignment = 0) - { - // TODO D3D12 thread safety, should we simply use locks? - - // Align - if (alignment > 0) - nativeUploadBufferOffset = (nativeUploadBufferOffset + alignment - 1) / alignment * alignment; - - if (nativeUploadBuffer == null || nativeUploadBufferOffset + size > nativeUploadBuffer.Description.Width) - { - if (nativeUploadBuffer != null) - { - nativeUploadBuffer.Unmap(0); - TemporaryResources.Enqueue(new KeyValuePair(NextFenceValue, nativeUploadBuffer)); - } - - // Allocate new buffer - // TODO D3D12 recycle old ones (using fences to know when GPU is done with them) - // TODO D3D12 ResourceStates.CopySource not working? - var bufferSize = Math.Max(4 * 1024*1024, size); - nativeUploadBuffer = NativeDevice.CreateCommittedResource(new HeapProperties(HeapType.Upload), HeapFlags.None, ResourceDescription.Buffer(bufferSize), ResourceStates.GenericRead); - nativeUploadBufferStart = nativeUploadBuffer.Map(0, new Range()); - nativeUploadBufferOffset = 0; - } - - // Bump allocate - resource = nativeUploadBuffer; - offset = nativeUploadBufferOffset; - nativeUploadBufferOffset += size; - return nativeUploadBufferStart + offset; - } - - internal void WaitCopyQueue() - { - NativeCommandQueue.ExecuteCommandList(NativeCopyCommandList); - NativeCommandQueue.Signal(nativeCopyFence, nextCopyFenceValue); - NativeCommandQueue.Wait(nativeCopyFence, nextCopyFenceValue); - nextCopyFenceValue++; - } - - internal void ReleaseTemporaryResources() - { - lock (TemporaryResources) - { - // Release previous frame resources - while (TemporaryResources.Count > 0 && IsFenceCompleteInternal(TemporaryResources.Peek().Key)) - { - var temporaryResource = TemporaryResources.Dequeue().Value; - //temporaryResource.Value.Dispose(); - var comObject = temporaryResource as SharpDX.ComObject; - if (comObject != null) - ((SharpDX.IUnknown)comObject).Release(); - else - { - var referenceLink = temporaryResource as GraphicsResourceLink; - if (referenceLink != null) - { - referenceLink.ReferenceCount--; - } - } - } - } - } - - private void AdjustDefaultPipelineStateDescription(ref PipelineStateDescription pipelineStateDescription) - { - } - - protected void DestroyPlatformDevice() - { - ReleaseDevice(); - } - - private void ReleaseDevice() - { - // Wait for completion of everything queued - NativeCommandQueue.Signal(nativeFence, NextFenceValue); - NativeCommandQueue.Wait(nativeFence, NextFenceValue); - - // Release command queue - NativeCommandQueue.Dispose(); - NativeCommandQueue = null; - - NativeCopyCommandQueue.Dispose(); - NativeCopyCommandQueue = null; - - NativeCopyCommandAllocator.Dispose(); - NativeCopyCommandList.Dispose(); - - nativeUploadBuffer.Dispose(); - - // Release temporary resources - ReleaseTemporaryResources(); - nativeFence.Dispose(); - nativeFence = null; - nativeCopyFence.Dispose(); - nativeCopyFence = null; - - // Release pools - CommandAllocators.Dispose(); - SrvHeaps.Dispose(); - SamplerHeaps.Dispose(); - - // Release allocators - SamplerAllocator.Dispose(); - ShaderResourceViewAllocator.Dispose(); - DepthStencilViewAllocator.Dispose(); - RenderTargetViewAllocator.Dispose(); - - if (IsDebugMode) - { - var debugDevice = NativeDevice.QueryInterfaceOrNull(); - if (debugDevice != null) - { - debugDevice.ReportLiveDeviceObjects(SharpDX.Direct3D12.ReportingLevel.Detail); - debugDevice.Dispose(); - } - } - - nativeDevice.Dispose(); - nativeDevice = null; - } - - internal void OnDestroyed() - { - } - - internal long ExecuteCommandListInternal(CompiledCommandList commandList) - { - var fenceValue = NextFenceValue++; - - // Submit and signal fence - NativeCommandQueue.ExecuteCommandList(commandList.NativeCommandList); - NativeCommandQueue.Signal(nativeFence, fenceValue); - - // Recycle resources - RecycleCommandListResources(commandList, fenceValue); - - return fenceValue; - } - - private void RecycleCommandListResources(CompiledCommandList commandList, long fenceValue) - { - // Set fence on staging textures - foreach (var stagingResource in commandList.StagingResources) - { - stagingResource.StagingFenceValue = fenceValue; - } - - StagingResourceLists.Release(commandList.StagingResources); - commandList.StagingResources.Clear(); - - // Recycle resources - foreach (var heap in commandList.SrvHeaps) - { - SrvHeaps.RecycleObject(fenceValue, heap); - } - commandList.SrvHeaps.Clear(); - DescriptorHeapLists.Release(commandList.SrvHeaps); - - foreach (var heap in commandList.SamplerHeaps) - { - SamplerHeaps.RecycleObject(fenceValue, heap); - } - commandList.SamplerHeaps.Clear(); - DescriptorHeapLists.Release(commandList.SamplerHeaps); - - commandList.Builder.NativeCommandLists.Enqueue(commandList.NativeCommandList); - CommandAllocators.RecycleObject(fenceValue, commandList.NativeCommandAllocator); - } - - internal bool IsFenceCompleteInternal(long fenceValue) - { - // Try to avoid checking the fence if possible - if (fenceValue > lastCompletedFence) - lastCompletedFence = Math.Max(lastCompletedFence, nativeFence.CompletedValue); // Protect against race conditions - - return fenceValue <= lastCompletedFence; - } - - internal void WaitForFenceInternal(long fenceValue) - { - if (IsFenceCompleteInternal(fenceValue)) - return; - - // TODO D3D12 in case of concurrency, this lock could end up blocking too long a second thread with lower fenceValue then first one - lock (nativeFence) - { - nativeFence.SetEventOnCompletion(fenceValue, fenceEvent.SafeWaitHandle.DangerousGetHandle()); - fenceEvent.WaitOne(); - lastCompletedFence = fenceValue; - } - } - - internal void TagResource(GraphicsResourceLink resourceLink) - { - var texture = resourceLink.Resource as Texture; - if (texture != null && texture.Usage == GraphicsResourceUsage.Dynamic) - { - // Increase the reference count until GPU is done with the resource - resourceLink.ReferenceCount++; - TemporaryResources.Enqueue(new KeyValuePair(NextFenceValue, resourceLink)); - } - - var buffer = resourceLink.Resource as Buffer; - if (buffer != null && buffer.Usage == GraphicsResourceUsage.Dynamic) - { - // Increase the reference count until GPU is done with the resource - resourceLink.ReferenceCount++; - TemporaryResources.Enqueue(new KeyValuePair(NextFenceValue, resourceLink)); - } - } - - internal abstract class ResourcePool : IDisposable where T : Pageable - { - protected readonly GraphicsDevice GraphicsDevice; - private readonly Queue> liveObjects = new Queue>(); - - protected ResourcePool(GraphicsDevice graphicsDevice) - { - GraphicsDevice = graphicsDevice; - } - - public void Dispose() - { - lock (liveObjects) - { - foreach (var liveObject in liveObjects) - { - liveObject.Value.Dispose(); - } - liveObjects.Clear(); - } - } - - public T GetObject() - { - // TODO D3D12: SpinLock - lock (liveObjects) - { - // Check if first allocator is ready for reuse - if (liveObjects.Count > 0) - { - var firstAllocator = liveObjects.Peek(); - if (firstAllocator.Key <= GraphicsDevice.nativeFence.CompletedValue) - { - liveObjects.Dequeue(); - ResetObject(firstAllocator.Value); - - if (firstAllocator.Value == null) - { - - } - - return firstAllocator.Value; - } - } - - return CreateObject(); - } - } - - protected abstract T CreateObject(); - - protected abstract void ResetObject(T obj); - - public void RecycleObject(long fenceValue, T obj) - { - // TODO D3D12: SpinLock - lock (liveObjects) - { - liveObjects.Enqueue(new KeyValuePair(fenceValue, obj)); - } - } - } - - internal class CommandAllocatorPool : ResourcePool - { - public CommandAllocatorPool(GraphicsDevice graphicsDevice) : base(graphicsDevice) - { - } - - protected override CommandAllocator CreateObject() - { - // No allocator ready to be used, let's create a new one - return GraphicsDevice.NativeDevice.CreateCommandAllocator(CommandListType.Direct); - } - - protected override void ResetObject(CommandAllocator obj) - { - obj.Reset(); - } - } - - internal class HeapPool : ResourcePool - { - private readonly int heapSize; - private readonly DescriptorHeapType heapType; - - public HeapPool(GraphicsDevice graphicsDevice, int heapSize, DescriptorHeapType heapType) : base(graphicsDevice) - { - this.heapSize = heapSize; - this.heapType = heapType; - } - - protected override DescriptorHeap CreateObject() - { - // No allocator ready to be used, let's create a new one - return GraphicsDevice.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription - { - DescriptorCount = heapSize, - Flags = DescriptorHeapFlags.ShaderVisible, - Type = heapType, - }); - } - - protected override void ResetObject(DescriptorHeap obj) - { - } - } - - /// - /// Allocate descriptor handles. For now a simple bump alloc, but at some point we will have to make a real allocator with free - /// - internal class DescriptorAllocator : IDisposable - { - private const int DescriptorPerHeap = 256; - - private GraphicsDevice device; - private DescriptorHeapType descriptorHeapType; - private DescriptorHeap currentHeap; - private CpuDescriptorHandle currentHandle; - private int remainingHandles; - private readonly int descriptorSize; - - public DescriptorAllocator(GraphicsDevice device, DescriptorHeapType descriptorHeapType) - { - this.device = device; - this.descriptorHeapType = descriptorHeapType; - this.descriptorSize = device.NativeDevice.GetDescriptorHandleIncrementSize(descriptorHeapType); - } - - public void Dispose() - { - currentHeap?.Dispose(); - currentHeap = null; - } - - public CpuDescriptorHandle Allocate(int count) - { - if (currentHeap == null || remainingHandles < count) - { - currentHeap = device.NativeDevice.CreateDescriptorHeap(new DescriptorHeapDescription - { - Flags = DescriptorHeapFlags.None, - Type = descriptorHeapType, - DescriptorCount = DescriptorPerHeap, - NodeMask = 1, - }); - remainingHandles = DescriptorPerHeap; - currentHandle = currentHeap.CPUDescriptorHandleForHeapStart; - } - - var result = currentHandle; - - currentHandle.Ptr += descriptorSize; - remainingHandles -= count; - - return result; - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsDeviceFeatures.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/GraphicsDeviceFeatures.Direct3D12.cs deleted file mode 100644 index b4909754b5..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsDeviceFeatures.Direct3D12.cs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using SharpDX.DXGI; -using SharpDX.Direct3D; -using SharpDX.Direct3D11; -using SharpDX.Direct3D12; - -namespace Xenko.Graphics -{ - /// - /// Features supported by a . - /// - /// - /// This class gives also features for a particular format, using the operator this[dxgiFormat] on this structure. - /// - public partial struct GraphicsDeviceFeatures - { - private static readonly List ObsoleteFormatToExcludes = new List() { Format.R1_UNorm, Format.B5G6R5_UNorm, Format.B5G5R5A1_UNorm }; - - internal GraphicsDeviceFeatures(GraphicsDevice deviceRoot) - { - var nativeDevice = deviceRoot.NativeDevice; - - HasSRgb = true; - - mapFeaturesPerFormat = new FeaturesPerFormat[256]; - - // Set back the real GraphicsProfile that is used - // TODO D3D12 - RequestedProfile = deviceRoot.RequestedProfile; - CurrentProfile = GraphicsProfileHelper.FromFeatureLevel(deviceRoot.CurrentFeatureLevel); - - // TODO D3D12 - HasComputeShaders = true; - HasDoublePrecision = nativeDevice.D3D12Options.DoublePrecisionFloatShaderOps; - - // TODO D3D12 Confirm these are correct - // Some docs: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476876(v=vs.85).aspx - HasDepthAsSRV = true; - HasDepthAsReadOnlyRT = true; - HasMultisampleDepthAsSRV = true; - - HasResourceRenaming = false; - - HasMultiThreadingConcurrentResources = true; - HasDriverCommandLists = true; - - // Check features for each DXGI.Format - foreach (var format in Enum.GetValues(typeof(SharpDX.DXGI.Format))) - { - var dxgiFormat = (SharpDX.DXGI.Format)format; - var maximumMultisampleCount = MultisampleCount.None; - var formatSupport = FormatSupport.None; - - if (!ObsoleteFormatToExcludes.Contains(dxgiFormat)) - { - SharpDX.Direct3D12.FeatureDataFormatSupport formatSupportData; - formatSupportData.Format = dxgiFormat; - formatSupportData.Support1 = FormatSupport1.None; - formatSupportData.Support2 = FormatSupport2.None; - if (nativeDevice.CheckFeatureSupport(SharpDX.Direct3D12.Feature.FormatSupport, ref formatSupportData)) - formatSupport = (FormatSupport)formatSupportData.Support1; - maximumMultisampleCount = GetMaximumMultisampleCount(nativeDevice, dxgiFormat); - } - - mapFeaturesPerFormat[(int)dxgiFormat] = new FeaturesPerFormat((PixelFormat)dxgiFormat, maximumMultisampleCount, formatSupport); - } - } - - /// - /// Gets the maximum multisample count for a particular . - /// - /// The device. - /// The pixelFormat. - /// The maximum multisample count for this pixel pixelFormat - private static MultisampleCount GetMaximumMultisampleCount(SharpDX.Direct3D12.Device device, SharpDX.DXGI.Format pixelFormat) - { - SharpDX.Direct3D12.FeatureDataMultisampleQualityLevels qualityLevels; - qualityLevels.Format = pixelFormat; - qualityLevels.Flags = MultisampleQualityLevelFlags.None; - qualityLevels.QualityLevelCount = 0; - - int maxCount = 1; - for (int i = 8; i >= 1; i /= 2) - { - qualityLevels.SampleCount = i; - if (device.CheckFeatureSupport(SharpDX.Direct3D12.Feature.MultisampleQualityLevels, ref qualityLevels)) - { - maxCount = i; - break; - } - } - return (MultisampleCount)maxCount; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsOutput.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/GraphicsOutput.Direct3D12.cs deleted file mode 100644 index 1a6f041ff3..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsOutput.Direct3D12.cs +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 - -// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using SharpDX.Direct3D; -using SharpDX.Direct3D11; -using SharpDX.DXGI; - -using Xenko.Core; -using Xenko.Core.Mathematics; - -using ResultCode = SharpDX.DXGI.ResultCode; - -namespace Xenko.Graphics -{ - /// - /// Provides methods to retrieve and manipulate an graphics output (a monitor), it is equivalent to . - /// - /// bb174546 - /// IDXGIOutput - /// IDXGIOutput - public partial class GraphicsOutput - { - private readonly int outputIndex; - private readonly Output output; - private readonly OutputDescription outputDescription; - - /// - /// Initializes a new instance of . - /// - /// The adapter. - /// Index of the output. - /// output - /// output - internal GraphicsOutput(GraphicsAdapter adapter, int outputIndex) - { - if (adapter == null) throw new ArgumentNullException("adapter"); - - this.outputIndex = outputIndex; - this.adapter = adapter; - this.output = adapter.NativeAdapter.GetOutput(outputIndex).DisposeBy(this); - outputDescription = output.Description; - - unsafe - { - var rectangle = outputDescription.DesktopBounds; - desktopBounds = *(Rectangle*)&rectangle; - } - } - - /// - /// Find the display mode that most closely matches the requested display mode. - /// - /// The target profile, as available formats are different depending on the feature level.. - /// The mode. - /// Returns the closes display mode. - /// HRESULT IDXGIOutput::FindClosestMatchingMode([In] const DXGI_MODE_DESC* pModeToMatch,[Out] DXGI_MODE_DESC* pClosestMatch,[In, Optional] IUnknown* pConcernedDevice) - /// Direct3D devices require UNORM formats. This method finds the closest matching available display mode to the mode specified in pModeToMatch. Similarly ranked fields (i.e. all specified, or all unspecified, etc) are resolved in the following order. ScanlineOrdering Scaling Format Resolution RefreshRate When determining the closest value for a particular field, previously matched fields are used to filter the display mode list choices, and other fields are ignored. For example, when matching Resolution, the display mode list will have already been filtered by a certain ScanlineOrdering, Scaling, and Format, while RefreshRate is ignored. This ordering doesn't define the absolute ordering for every usage scenario of FindClosestMatchingMode, because the application can choose some values initially, effectively changing the order that fields are chosen. Fields of the display mode are matched one at a time, generally in a specified order. If a field is unspecified, FindClosestMatchingMode gravitates toward the values for the desktop related to this output. If this output is not part of the desktop, then the default desktop output is used to find values. If an application uses a fully unspecified display mode, FindClosestMatchingMode will typically return a display mode that matches the desktop settings for this output. Unspecified fields are lower priority than specified fields and will be resolved later than specified fields. - public DisplayMode FindClosestMatchingDisplayMode(GraphicsProfile[] targetProfiles, DisplayMode mode) - { - if (targetProfiles == null) throw new ArgumentNullException("targetProfiles"); - - ModeDescription closestDescription; - SharpDX.Direct3D12.Device deviceTemp = null; - for (int i = 0; i < targetProfiles.Length; i++) - { - // Create Device D3D12 with feature Level based on profile - try - { - deviceTemp = new SharpDX.Direct3D12.Device(Adapter.NativeAdapter, (FeatureLevel)targetProfiles[i]); - break; - } - catch (Exception) - { - } - } - - if (deviceTemp == null) - throw new InvalidOperationException("Could not create D3D12 graphics device"); - - var description = new SharpDX.DXGI.ModeDescription() - { - Width = mode.Width, - Height = mode.Height, - RefreshRate = mode.RefreshRate.ToSharpDX(), - Format = (SharpDX.DXGI.Format)mode.Format, - Scaling = DisplayModeScaling.Unspecified, - ScanlineOrdering = DisplayModeScanlineOrder.Unspecified - }; - using (var device = deviceTemp) - output.GetClosestMatchingMode(device, description, out closestDescription); - - return DisplayMode.FromDescription(closestDescription); - } - - /// - /// Retrieves the handle of the monitor associated with this . - /// - /// bb173068 - /// HMONITOR Monitor - /// HMONITOR Monitor - public IntPtr MonitorHandle { get { return outputDescription.MonitorHandle; } } - - /// - /// Gets the native output. - /// - /// The native output. - internal Output NativeOutput - { - get - { - return output; - } - } - - /// - /// Enumerates all available display modes for this output and stores them in . - /// - private void InitializeSupportedDisplayModes() - { - var modesAvailable = new List(); - var modesMap = new Dictionary(); - -#if DIRECTX11_1 - var output1 = output.QueryInterface(); -#endif - - try - { - const DisplayModeEnumerationFlags displayModeEnumerationFlags = DisplayModeEnumerationFlags.Interlaced | DisplayModeEnumerationFlags.Scaling; - - foreach (var format in Enum.GetValues(typeof(SharpDX.DXGI.Format))) - { - var dxgiFormat = (Format)format; -#if DIRECTX11_1 - var modes = output1.GetDisplayModeList1(dxgiFormat, displayModeEnumerationFlags); -#else - var modes = output.GetDisplayModeList(dxgiFormat, displayModeEnumerationFlags); -#endif - - foreach (var mode in modes) - { - if (mode.Scaling == DisplayModeScaling.Unspecified) - { - var key = format + ";" + mode.Width + ";" + mode.Height + ";" + mode.RefreshRate.Numerator + ";" + mode.RefreshRate.Denominator; - - DisplayMode oldMode; - if (!modesMap.TryGetValue(key, out oldMode)) - { - var displayMode = DisplayMode.FromDescription(mode); - - modesMap.Add(key, displayMode); - modesAvailable.Add(displayMode); - } - } - } - } - } - catch (SharpDX.SharpDXException dxgiException) - { - if (dxgiException.ResultCode != ResultCode.NotCurrentlyAvailable) - throw; - } - -#if DIRECTX11_1 - output1.Dispose(); -#endif - supportedDisplayModes = modesAvailable.ToArray(); - } - - /// - /// Initializes with the most appropiate mode from . - /// - /// It checks first for a mode with , - /// if it is not found - it checks for . - private void InitializeCurrentDisplayMode() - { - currentDisplayMode = TryFindMatchingDisplayMode(Format.R8G8B8A8_UNorm) - ?? TryFindMatchingDisplayMode(Format.B8G8R8A8_UNorm); - } - - /// - /// Tries to find a display mode that has the same size as the current associated with this instance - /// of the specified format. - /// - /// The format to match with. - /// A matched or null if nothing is found. - private DisplayMode TryFindMatchingDisplayMode(Format format) - { - var desktopBounds = outputDescription.DesktopBounds; - - foreach (var supportedDisplayMode in SupportedDisplayModes) - { - var width = desktopBounds.Right - desktopBounds.Left; - var height = desktopBounds.Bottom - desktopBounds.Top; - - if (supportedDisplayMode.Width == width - && supportedDisplayMode.Height == height - && (Format)supportedDisplayMode.Format == format) - { - // Stupid DXGI, there is no way to get the DXGI.Format, nor the refresh rate. - return new DisplayMode((PixelFormat)format, width, height, supportedDisplayMode.RefreshRate); - } - } - - return null; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsResource.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/GraphicsResource.Direct3D12.cs deleted file mode 100644 index e5d4b8d6e7..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsResource.Direct3D12.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using SharpDX.Direct3D12; - -namespace Xenko.Graphics -{ - /// - /// GraphicsResource class - /// - public abstract partial class GraphicsResource - { - internal GraphicsResource ParentResource; - - internal long? StagingFenceValue; - internal CommandList StagingBuilder; - internal CpuDescriptorHandle NativeShaderResourceView; - internal CpuDescriptorHandle NativeUnorderedAccessView; - internal ResourceStates NativeResourceState; - - protected bool IsDebugMode => GraphicsDevice != null && GraphicsDevice.IsDebugMode; - - /// - /// Returns true if resource state transition is needed in order to use resource in given state - /// - /// Destination resource state - /// True if need to perform a transition, otherwsie false - internal bool IsTransitionNeeded(ResourceStates targeState) - { - // If 'targeState' is a subset of 'before', then there's no need for a transition - // Note: COMMON is an oddball state that doesn't follow the RESOURE_STATE pattern of - // having exactly one bit set so we need to special case these - return NativeResourceState != targeState && ((NativeResourceState | targeState) != NativeResourceState || targeState == ResourceStates.Common); - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsResourceBase.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/GraphicsResourceBase.Direct3D12.cs deleted file mode 100644 index eaa455cbd5..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/GraphicsResourceBase.Direct3D12.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using System.Collections.Generic; -using System.Diagnostics; - -using SharpDX; - -namespace Xenko.Graphics -{ - /// - /// GraphicsResource class - /// - public abstract partial class GraphicsResourceBase - { - private SharpDX.Direct3D12.DeviceChild nativeDeviceChild; - - protected internal SharpDX.Direct3D12.Resource NativeResource { get; private set; } - - private void Initialize() - { - } - - /// - /// Gets or sets the device child. - /// - /// The device child. - protected internal SharpDX.Direct3D12.DeviceChild NativeDeviceChild - { - get - { - return nativeDeviceChild; - } - set - { - nativeDeviceChild = value; - NativeResource = nativeDeviceChild as SharpDX.Direct3D12.Resource; - // Associate PrivateData to this DeviceResource - SetDebugName(GraphicsDevice, nativeDeviceChild, Name); - } - } - - /// - /// Associates the private data to the device child, useful to get the name in PIX debugger. - /// - internal static void SetDebugName(GraphicsDevice graphicsDevice, SharpDX.Direct3D12.DeviceChild deviceChild, string name) - { - } - - /// - /// Called when graphics device has been detected to be internally destroyed. - /// - protected internal virtual void OnDestroyed() - { - if (nativeDeviceChild != null) - { - // Schedule the resource for destruction (as soon as we are done with it) - GraphicsDevice.TemporaryResources.Enqueue(new KeyValuePair(GraphicsDevice.NextFenceValue, nativeDeviceChild)); - nativeDeviceChild = null; - } - NativeResource = null; - } - - /// - /// Called when graphics device has been recreated. - /// - /// True if item transitioned to a state. - protected internal virtual bool OnRecreate() - { - return false; - } - - protected SharpDX.Direct3D12.Device NativeDevice - { - get - { - return GraphicsDevice != null ? GraphicsDevice.NativeDevice : null; - } - } - - internal static void ReleaseComObject(ref T comObject) where T : class, IUnknown - { - // We can't put IUnknown as a constraint on the generic as it would break compilation (trying to import SharpDX in projects with InternalVisibleTo) - var refCountResult = comObject.Release(); - comObject = null; - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/MappedResource.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/MappedResource.Direct3D12.cs deleted file mode 100644 index a7873cc37b..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/MappedResource.Direct3D12.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_DIRECT3D12 -namespace Xenko.Graphics -{ - public partial struct MappedResource - { - internal SharpDX.Direct3D12.Resource UploadResource; - internal int UploadOffset; - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/PipelineState.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/PipelineState.Direct3D12.cs deleted file mode 100644 index f06f589f8b..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/PipelineState.Direct3D12.cs +++ /dev/null @@ -1,381 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using System.Collections.Generic; -using System.Linq; -using SharpDX.Direct3D; -using SharpDX.Direct3D12; -using SharpDX.DXGI; -using Xenko.Core; -using Xenko.Core.Storage; -using Xenko.Shaders; - -namespace Xenko.Graphics -{ - public partial class PipelineState - { - internal SharpDX.Direct3D12.PipelineState CompiledState; - internal SharpDX.Direct3D12.RootSignature RootSignature; - internal PrimitiveTopology PrimitiveTopology; - internal bool HasScissorEnabled; - internal bool IsCompute; - internal int[] SrvBindCounts; - internal int[] SamplerBindCounts; - - public PIPELINE_STATE CurrentState() { - if (RootSignature != null) return PIPELINE_STATE.READY; - return PIPELINE_STATE.LOADING; - } - - internal PipelineState(GraphicsDevice graphicsDevice) : base(graphicsDevice) { - // just return a memory address to Prepare later - } - - internal void Prepare(PipelineStateDescription pipelineStateDescription) - { - if (pipelineStateDescription.RootSignature != null) - { - var effectReflection = pipelineStateDescription.EffectBytecode.Reflection; - - var computeShader = pipelineStateDescription.EffectBytecode.Stages.FirstOrDefault(e => e.Stage == ShaderStage.Compute); - IsCompute = computeShader != null; - - var rootSignatureParameters = new List(); - var immutableSamplers = new List(); - SrvBindCounts = new int[pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.Layouts.Count]; - SamplerBindCounts = new int[pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.Layouts.Count]; - for (int layoutIndex = 0; layoutIndex < pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.Layouts.Count; layoutIndex++) - { - var layout = pipelineStateDescription.RootSignature.EffectDescriptorSetReflection.Layouts[layoutIndex]; - if (layout.Layout == null) - continue; - - // TODO D3D12 for now, we don't control register so we simply generate one resource table per shader stage and per descriptor set layout - // we should switch to a model where we make sure VS/PS don't overlap for common descriptors so that they can be shared - var srvDescriptorRanges = new Dictionary>(); - var samplerDescriptorRanges = new Dictionary>(); - - int descriptorSrvOffset = 0; - int descriptorSamplerOffset = 0; - foreach (var item in layout.Layout.Entries) - { - var isSampler = item.Class == EffectParameterClass.Sampler; - - // Find matching resource bindings - foreach (var binding in effectReflection.ResourceBindings) - { - if (binding.Stage == ShaderStage.None || binding.KeyInfo.Key != item.Key) - continue; - - List descriptorRanges; - { - var dictionary = isSampler ? samplerDescriptorRanges : srvDescriptorRanges; - if (dictionary.TryGetValue(binding.Stage, out descriptorRanges) == false) - { - descriptorRanges = dictionary[binding.Stage] = new List(); - } - } - - if (isSampler) - { - if (item.ImmutableSampler != null) - { - immutableSamplers.Add(new StaticSamplerDescription(ShaderStage2ShaderVisibility(binding.Stage), binding.SlotStart, 0) - { - // TODO D3D12 ImmutableSampler should only be a state description instead of a GPU object? - Filter = (Filter)item.ImmutableSampler.Description.Filter, - ComparisonFunc = (Comparison)item.ImmutableSampler.Description.CompareFunction, - BorderColor = ColorHelper.ConvertStatic(item.ImmutableSampler.Description.BorderColor), - AddressU = (SharpDX.Direct3D12.TextureAddressMode)item.ImmutableSampler.Description.AddressU, - AddressV = (SharpDX.Direct3D12.TextureAddressMode)item.ImmutableSampler.Description.AddressV, - AddressW = (SharpDX.Direct3D12.TextureAddressMode)item.ImmutableSampler.Description.AddressW, - MinLOD = item.ImmutableSampler.Description.MinMipLevel, - MaxLOD = item.ImmutableSampler.Description.MaxMipLevel, - MipLODBias = item.ImmutableSampler.Description.MipMapLevelOfDetailBias, - MaxAnisotropy = item.ImmutableSampler.Description.MaxAnisotropy, - }); - } - else - { - // Add descriptor range - descriptorRanges.Add(new DescriptorRange(DescriptorRangeType.Sampler, item.ArraySize, binding.SlotStart, 0, descriptorSamplerOffset)); - } - } - else - { - DescriptorRangeType descriptorRangeType; - switch (binding.Class) - { - case EffectParameterClass.ConstantBuffer: - descriptorRangeType = DescriptorRangeType.ConstantBufferView; - break; - case EffectParameterClass.ShaderResourceView: - descriptorRangeType = DescriptorRangeType.ShaderResourceView; - break; - case EffectParameterClass.UnorderedAccessView: - descriptorRangeType = DescriptorRangeType.UnorderedAccessView; - break; - default: - throw new NotImplementedException(); - } - - // Add descriptor range - descriptorRanges.Add(new DescriptorRange(descriptorRangeType, item.ArraySize, binding.SlotStart, 0, descriptorSrvOffset)); - } - } - - // Move to next element (mirror what is done in DescriptorSetLayout) - if (isSampler) - { - if (item.ImmutableSampler == null) - descriptorSamplerOffset += item.ArraySize; - } - else - { - descriptorSrvOffset += item.ArraySize; - } - } - - foreach (var stage in srvDescriptorRanges) - { - if (stage.Value.Count > 0) - { - rootSignatureParameters.Add(new RootParameter(ShaderStage2ShaderVisibility(stage.Key), stage.Value.ToArray())); - SrvBindCounts[layoutIndex]++; - } - } - foreach (var stage in samplerDescriptorRanges) - { - if (stage.Value.Count > 0) - { - rootSignatureParameters.Add(new RootParameter(ShaderStage2ShaderVisibility(stage.Key), stage.Value.ToArray())); - SamplerBindCounts[layoutIndex]++; - } - } - } - var rootSignatureDesc = new RootSignatureDescription(RootSignatureFlags.AllowInputAssemblerInputLayout, rootSignatureParameters.ToArray(), immutableSamplers.ToArray()); - - var rootSignature = NativeDevice.CreateRootSignature(0, rootSignatureDesc.Serialize()); - - InputElement[] inputElements = null; - if (pipelineStateDescription.InputElements != null) - { - inputElements = new InputElement[pipelineStateDescription.InputElements.Length]; - for (int i = 0; i < inputElements.Length; ++i) - { - var inputElement = pipelineStateDescription.InputElements[i]; - inputElements[i] = new InputElement - { - Format = (SharpDX.DXGI.Format)inputElement.Format, - AlignedByteOffset = inputElement.AlignedByteOffset, - SemanticName = inputElement.SemanticName, - SemanticIndex = inputElement.SemanticIndex, - Slot = inputElement.InputSlot, - Classification = (SharpDX.Direct3D12.InputClassification)inputElement.InputSlotClass, - InstanceDataStepRate = inputElement.InstanceDataStepRate, - }; - } - } - - PrimitiveTopologyType primitiveTopologyType; - switch (pipelineStateDescription.PrimitiveType) - { - case PrimitiveType.Undefined: - primitiveTopologyType = PrimitiveTopologyType.Undefined; - break; - case PrimitiveType.PointList: - primitiveTopologyType = PrimitiveTopologyType.Point; - break; - case PrimitiveType.LineList: - case PrimitiveType.LineStrip: - case PrimitiveType.LineListWithAdjacency: - case PrimitiveType.LineStripWithAdjacency: - primitiveTopologyType = PrimitiveTopologyType.Line; - break; - case PrimitiveType.TriangleList: - case PrimitiveType.TriangleStrip: - case PrimitiveType.TriangleListWithAdjacency: - case PrimitiveType.TriangleStripWithAdjacency: - primitiveTopologyType = PrimitiveTopologyType.Triangle; - break; - default: - if (pipelineStateDescription.PrimitiveType >= PrimitiveType.PatchList && pipelineStateDescription.PrimitiveType < PrimitiveType.PatchList + 32) - primitiveTopologyType = PrimitiveTopologyType.Patch; - else - throw new ArgumentOutOfRangeException("pipelineStateDescription.PrimitiveType"); - break; - } - - // Check if it should use compute pipeline state - if (IsCompute) - { - var nativePipelineStateDescription = new ComputePipelineStateDescription - { - ComputeShader = computeShader.Data, - Flags = PipelineStateFlags.None, - RootSignaturePointer = rootSignature, - }; - - CompiledState = NativeDevice.CreateComputePipelineState(nativePipelineStateDescription); - } - else - { - var nativePipelineStateDescription = new GraphicsPipelineStateDescription - { - InputLayout = new InputLayoutDescription(inputElements), - RootSignature = rootSignature, - RasterizerState = CreateRasterizerState(pipelineStateDescription.RasterizerState), - BlendState = CreateBlendState(pipelineStateDescription.BlendState), - SampleMask = (int)pipelineStateDescription.SampleMask, - DepthStencilFormat = (SharpDX.DXGI.Format)pipelineStateDescription.Output.DepthStencilFormat, - DepthStencilState = CreateDepthStencilState(pipelineStateDescription.DepthStencilState), - RenderTargetCount = pipelineStateDescription.Output.RenderTargetCount, - // TODO D3D12 hardcoded - StreamOutput = new StreamOutputDescription(), - PrimitiveTopologyType = primitiveTopologyType, - // TODO D3D12 hardcoded - SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0), - }; - - // Disable depth buffer if no format specified - if (nativePipelineStateDescription.DepthStencilFormat == Format.Unknown) - nativePipelineStateDescription.DepthStencilState.IsDepthEnabled = false; - - fixed (PixelFormat* renderTargetFormats = &pipelineStateDescription.Output.RenderTargetFormat0) - { - for (int i = 0; i < pipelineStateDescription.Output.RenderTargetCount; ++i) - nativePipelineStateDescription.RenderTargetFormats[i] = (SharpDX.DXGI.Format)renderTargetFormats[i]; - } - - foreach (var stage in pipelineStateDescription.EffectBytecode.Stages) - { - switch (stage.Stage) - { - case ShaderStage.Vertex: - nativePipelineStateDescription.VertexShader = stage.Data; - break; - case ShaderStage.Hull: - nativePipelineStateDescription.HullShader = stage.Data; - break; - case ShaderStage.Domain: - nativePipelineStateDescription.DomainShader = stage.Data; - break; - case ShaderStage.Geometry: - nativePipelineStateDescription.GeometryShader = stage.Data; - break; - case ShaderStage.Pixel: - nativePipelineStateDescription.PixelShader = stage.Data; - break; - default: - throw new ArgumentOutOfRangeException(); - } - } - - CompiledState = NativeDevice.CreateGraphicsPipelineState(nativePipelineStateDescription); - } - - RootSignature = rootSignature; - PrimitiveTopology = (PrimitiveTopology)pipelineStateDescription.PrimitiveType; - HasScissorEnabled = pipelineStateDescription.RasterizerState.ScissorTestEnable; - } - } - - protected internal override void OnDestroyed() - { - RootSignature?.Dispose(); - RootSignature = null; - - CompiledState?.Dispose(); - CompiledState = null; - - base.OnDestroyed(); - } - - private unsafe SharpDX.Direct3D12.BlendStateDescription CreateBlendState(BlendStateDescription description) - { - var nativeDescription = new SharpDX.Direct3D12.BlendStateDescription(); - - nativeDescription.AlphaToCoverageEnable = description.AlphaToCoverageEnable; - nativeDescription.IndependentBlendEnable = description.IndependentBlendEnable; - - var renderTargets = &description.RenderTarget0; - for (int i = 0; i < 8; ++i) - { - nativeDescription.RenderTarget[i].IsBlendEnabled = renderTargets[i].BlendEnable; - nativeDescription.RenderTarget[i].SourceBlend = (BlendOption)renderTargets[i].ColorSourceBlend; - nativeDescription.RenderTarget[i].DestinationBlend = (BlendOption)renderTargets[i].ColorDestinationBlend; - nativeDescription.RenderTarget[i].BlendOperation = (BlendOperation)renderTargets[i].ColorBlendFunction; - nativeDescription.RenderTarget[i].SourceAlphaBlend = (BlendOption)renderTargets[i].AlphaSourceBlend; - nativeDescription.RenderTarget[i].DestinationAlphaBlend = (BlendOption)renderTargets[i].AlphaDestinationBlend; - nativeDescription.RenderTarget[i].AlphaBlendOperation = (BlendOperation)renderTargets[i].AlphaBlendFunction; - nativeDescription.RenderTarget[i].RenderTargetWriteMask = (ColorWriteMaskFlags)renderTargets[i].ColorWriteChannels; - } - - return nativeDescription; - } - - private SharpDX.Direct3D12.RasterizerStateDescription CreateRasterizerState(RasterizerStateDescription description) - { - SharpDX.Direct3D12.RasterizerStateDescription nativeDescription; - - nativeDescription.CullMode = (SharpDX.Direct3D12.CullMode)description.CullMode; - nativeDescription.FillMode = (SharpDX.Direct3D12.FillMode)description.FillMode; - nativeDescription.IsFrontCounterClockwise = description.FrontFaceCounterClockwise; - nativeDescription.DepthBias = description.DepthBias; - nativeDescription.SlopeScaledDepthBias = description.SlopeScaleDepthBias; - nativeDescription.DepthBiasClamp = description.DepthBiasClamp; - nativeDescription.IsDepthClipEnabled = description.DepthClipEnable; - //nativeDescription.IsScissorEnabled = description.ScissorTestEnable; - nativeDescription.IsMultisampleEnabled = description.MultisampleCount >= MultisampleCount.None; - nativeDescription.IsAntialiasedLineEnabled = description.MultisampleAntiAliasLine; - - nativeDescription.ConservativeRaster = ConservativeRasterizationMode.Off; - nativeDescription.ForcedSampleCount = 0; - - return nativeDescription; - } - - private SharpDX.Direct3D12.DepthStencilStateDescription CreateDepthStencilState(DepthStencilStateDescription description) - { - SharpDX.Direct3D12.DepthStencilStateDescription nativeDescription; - - nativeDescription.IsDepthEnabled = description.DepthBufferEnable; - nativeDescription.DepthComparison = (Comparison)description.DepthBufferFunction; - nativeDescription.DepthWriteMask = description.DepthBufferWriteEnable ? SharpDX.Direct3D12.DepthWriteMask.All : SharpDX.Direct3D12.DepthWriteMask.Zero; - - nativeDescription.IsStencilEnabled = description.StencilEnable; - nativeDescription.StencilReadMask = description.StencilMask; - nativeDescription.StencilWriteMask = description.StencilWriteMask; - - nativeDescription.FrontFace.FailOperation = (SharpDX.Direct3D12.StencilOperation)description.FrontFace.StencilFail; - nativeDescription.FrontFace.PassOperation = (SharpDX.Direct3D12.StencilOperation)description.FrontFace.StencilPass; - nativeDescription.FrontFace.DepthFailOperation = (SharpDX.Direct3D12.StencilOperation)description.FrontFace.StencilDepthBufferFail; - nativeDescription.FrontFace.Comparison = (SharpDX.Direct3D12.Comparison)description.FrontFace.StencilFunction; - - nativeDescription.BackFace.FailOperation = (SharpDX.Direct3D12.StencilOperation)description.BackFace.StencilFail; - nativeDescription.BackFace.PassOperation = (SharpDX.Direct3D12.StencilOperation)description.BackFace.StencilPass; - nativeDescription.BackFace.DepthFailOperation = (SharpDX.Direct3D12.StencilOperation)description.BackFace.StencilDepthBufferFail; - nativeDescription.BackFace.Comparison = (SharpDX.Direct3D12.Comparison)description.BackFace.StencilFunction; - - return nativeDescription; - } - - private static ShaderVisibility ShaderStage2ShaderVisibility(ShaderStage stage) - { - switch (stage) - { - case ShaderStage.Vertex: return ShaderVisibility.Vertex; - case ShaderStage.Hull: return ShaderVisibility.Hull; - case ShaderStage.Domain: return ShaderVisibility.Domain; - case ShaderStage.Geometry: return ShaderVisibility.Geometry; - case ShaderStage.Pixel: return ShaderVisibility.Pixel; - case ShaderStage.Compute: return ShaderVisibility.All; - default: - throw new ArgumentOutOfRangeException(nameof(stage), stage, null); - } - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/QueryPool.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/QueryPool.Direct3D12.cs deleted file mode 100644 index 9ebccbd4e7..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/QueryPool.Direct3D12.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using SharpDX.Direct3D12; -using Xenko.Core; - -namespace Xenko.Graphics -{ - public partial class QueryPool - { - private Resource readbackBuffer; - private Fence readbackFence; - - internal long CompletedValue; - internal long PendingValue; - internal QueryHeap NativeQueryHeap; - - public unsafe bool TryGetData(long[] dataArray) - { - // If readback has completed, return the data from the staging buffer - if (readbackFence.CompletedValue == PendingValue) - { - CompletedValue = PendingValue; - - var mappedData = readbackBuffer.Map(0); - fixed (long* dataPointer = &dataArray[0]) - { - Utilities.CopyMemory(new IntPtr(dataPointer), mappedData, QueryCount * 8); - } - readbackBuffer.Unmap(0); - return true; - } - - // Otherwise, queue readback - var commandList = GraphicsDevice.NativeCopyCommandList; - - commandList.Reset(GraphicsDevice.NativeCopyCommandAllocator, null); - commandList.ResolveQueryData(NativeQueryHeap, SharpDX.Direct3D12.QueryType.Timestamp, 0, QueryCount, readbackBuffer, 0); - commandList.Close(); - - GraphicsDevice.NativeCommandQueue.ExecuteCommandList(GraphicsDevice.NativeCopyCommandList); - GraphicsDevice.NativeCommandQueue.Signal(readbackFence, PendingValue); - - return false; - } - - private void Recreate() - { - var description = new QueryHeapDescription { Count = QueryCount }; - - switch (QueryType) - { - case QueryType.Timestamp: - description.Type = QueryHeapType.Timestamp; - break; - - default: - throw new NotImplementedException(); - } - - NativeQueryHeap = NativeDevice.CreateQueryHeap(description); - readbackBuffer = NativeDevice.CreateCommittedResource(new HeapProperties(HeapType.Readback), HeapFlags.None, ResourceDescription.Buffer(QueryCount * 8), ResourceStates.CopyDestination); - readbackFence = NativeDevice.CreateFence(0, FenceFlags.None); - CompletedValue = 0; - PendingValue = 0; - } - - /// - protected internal override void OnDestroyed() - { - NativeQueryHeap.Dispose(); - readbackBuffer.Dispose(); - readbackFence.Dispose(); - - base.OnDestroyed(); - } - - internal void ResetInternal() - { - if (CompletedValue <= readbackFence.CompletedValue) - CompletedValue = readbackFence.CompletedValue + 1; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/SamplerState.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/SamplerState.Direct3D12.cs deleted file mode 100644 index 090706986a..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/SamplerState.Direct3D12.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_DIRECT3D12 -using System; -using SharpDX; -using SharpDX.Direct3D12; -using Xenko.Core.Mathematics; - -namespace Xenko.Graphics -{ - /// - /// Describes a sampler state used for texture sampling. - /// - public partial class SamplerState - { - internal CpuDescriptorHandle NativeSampler; - - /// - /// Initializes a new instance of the class. - /// - /// The device. - /// The name. - /// The sampler state description. - private SamplerState(GraphicsDevice device, SamplerStateDescription samplerStateDescription) : base(device) - { - Description = samplerStateDescription; - - CreateNativeDeviceChild(); - } - - /// - protected internal override bool OnRecreate() - { - base.OnRecreate(); - CreateNativeDeviceChild(); - return true; - } - - private void CreateNativeDeviceChild() - { - SharpDX.Direct3D12.SamplerStateDescription nativeDescription; - - nativeDescription.AddressU = (SharpDX.Direct3D12.TextureAddressMode)Description.AddressU; - nativeDescription.AddressV = (SharpDX.Direct3D12.TextureAddressMode)Description.AddressV; - nativeDescription.AddressW = (SharpDX.Direct3D12.TextureAddressMode)Description.AddressW; - nativeDescription.BorderColor = ColorHelper.Convert(Description.BorderColor); - nativeDescription.ComparisonFunction = (SharpDX.Direct3D12.Comparison)Description.CompareFunction; - nativeDescription.Filter = (SharpDX.Direct3D12.Filter)Description.Filter; - nativeDescription.MaximumAnisotropy = Description.MaxAnisotropy; - nativeDescription.MaximumLod = Description.MaxMipLevel; - nativeDescription.MinimumLod = Description.MinMipLevel; - nativeDescription.MipLodBias = Description.MipMapLevelOfDetailBias; - - NativeSampler = GraphicsDevice.SamplerAllocator.Allocate(1); - GraphicsDevice.NativeDevice.CreateSampler(nativeDescription, NativeSampler); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/Direct3D12/Texture.Direct3D12.cs b/sources/engine/Xenko.Graphics/Direct3D12/Texture.Direct3D12.cs deleted file mode 100644 index 1e7f5243ec..0000000000 --- a/sources/engine/Xenko.Graphics/Direct3D12/Texture.Direct3D12.cs +++ /dev/null @@ -1,891 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_DIRECT3D12 -// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using System.Linq; -using SharpDX.Direct3D12; -using SharpDX.Mathematics.Interop; -using Xenko.Core; - -namespace Xenko.Graphics -{ - public partial class Texture - { - internal CpuDescriptorHandle NativeRenderTargetView; - internal CpuDescriptorHandle NativeDepthStencilView; - public bool HasStencil; - - private int TexturePixelSize => Format.SizeInBytes(); - // D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (not exposed by SharpDX) - private const int TextureRowPitchAlignment = 256; - // D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT (not exposed by SharpDX) - private const int TextureSubresourceAlignment = 512; - - public void Recreate(DataBox[] dataBoxes = null) - { - InitializeFromImpl(dataBoxes); - } - - public static bool IsDepthStencilReadOnlySupported(GraphicsDevice device) - { - return device.Features.CurrentProfile >= GraphicsProfile.Level_11_0; - } - - internal void SwapInternal(Texture other) - { - var deviceChild = NativeDeviceChild; - NativeDeviceChild = other.NativeDeviceChild; - other.NativeDeviceChild = deviceChild; - // - var srv = NativeShaderResourceView; - NativeShaderResourceView = other.NativeShaderResourceView; - other.NativeShaderResourceView = srv; - // - var uav = NativeUnorderedAccessView; - NativeUnorderedAccessView = other.NativeUnorderedAccessView; - other.NativeUnorderedAccessView = uav; - // - Utilities.Swap(ref StagingFenceValue, ref other.StagingFenceValue); - Utilities.Swap(ref StagingBuilder, ref other.StagingBuilder); - Utilities.Swap(ref NativeResourceState, ref other.NativeResourceState); - Utilities.Swap(ref NativeRenderTargetView, ref other.NativeRenderTargetView); - Utilities.Swap(ref NativeDepthStencilView, ref other.NativeDepthStencilView); - Utilities.Swap(ref HasStencil, ref other.HasStencil); - } - - /// - /// Initializes from a native SharpDX.Texture - /// - /// The texture. - internal Texture InitializeFromImpl(SharpDX.Direct3D12.Resource texture, bool isSrgb) - { - NativeDeviceChild = texture; - var newTextureDescription = ConvertFromNativeDescription(texture.Description); - - // We might have created the swapchain as a non-srgb format (esp on Win10&RT) but we want it to behave like it is (esp. for the view and render target) - if (isSrgb) - newTextureDescription.Format = newTextureDescription.Format.ToSRgb(); - - return InitializeFrom(newTextureDescription); - } - - private void InitializeFromImpl(DataBox[] dataBoxes = null) - { - bool hasInitData = dataBoxes != null && dataBoxes.Length > 0; - - if (ParentTexture != null) - { - ParentResource = ParentTexture; - NativeDeviceChild = ParentTexture.NativeDeviceChild; - } - - if (NativeDeviceChild == null) - { - ClearValue? clearValue = GetClearValue(); - - ResourceDescription nativeDescription; - switch (Dimension) - { - case TextureDimension.Texture1D: - nativeDescription = ConvertToNativeDescription1D(); - break; - case TextureDimension.Texture2D: - case TextureDimension.TextureCube: - nativeDescription = ConvertToNativeDescription2D(); - break; - case TextureDimension.Texture3D: - nativeDescription = ConvertToNativeDescription3D(); - break; - default: - throw new ArgumentOutOfRangeException(); - } - - var initialResourceState = ResourceStates.GenericRead; - - var heapType = HeapType.Default; - var currentResourceState = initialResourceState; - if (Usage == GraphicsResourceUsage.Staging) - { - heapType = HeapType.Readback; - NativeResourceState = ResourceStates.CopyDestination; - int totalSize = ComputeBufferTotalSize(); - nativeDescription = ResourceDescription.Buffer(totalSize); - - // Staging textures on DirectX 12 use buffer internally - NativeDeviceChild = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, nativeDescription, NativeResourceState); - - if (hasInitData) - { - var commandList = GraphicsDevice.NativeCopyCommandList; - commandList.Reset(GraphicsDevice.NativeCopyCommandAllocator, null); - - Resource uploadResource; - int uploadOffset; - var uploadMemory = GraphicsDevice.AllocateUploadBuffer(totalSize, out uploadResource, out uploadOffset, TextureSubresourceAlignment); - - // Copy data to the upload buffer - int dataBoxIndex = 0; - var uploadMemoryMipStart = uploadMemory; - for (int arraySlice = 0; arraySlice < ArraySize; arraySlice++) - { - for (int mipLevel = 0; mipLevel < MipLevels; mipLevel++) - { - var databox = dataBoxes[dataBoxIndex++]; - var mipHeight = CalculateMipSize(Width, mipLevel); - var mipRowPitch = ComputeRowPitch(mipLevel); - - var uploadMemoryCurrent = uploadMemoryMipStart; - var dataPointerCurrent = databox.DataPointer; - for (int rowIndex = 0; rowIndex < mipHeight; rowIndex++) - { - Utilities.CopyMemory(uploadMemoryCurrent, dataPointerCurrent, mipRowPitch); - uploadMemoryCurrent += mipRowPitch; - dataPointerCurrent += databox.RowPitch; - } - - uploadMemoryMipStart += ComputeSubresourceSize(mipLevel); - } - } - - // Copy from upload heap to actual resource - commandList.CopyBufferRegion(NativeResource, 0, uploadResource, uploadOffset, totalSize); - - commandList.Close(); - - StagingFenceValue = 0; - GraphicsDevice.WaitCopyQueue(); - } - - return; - } - - if (hasInitData) - currentResourceState = ResourceStates.CopyDestination; - - // TODO D3D12 move that to a global allocator in bigger committed resources - NativeDeviceChild = GraphicsDevice.NativeDevice.CreateCommittedResource(new HeapProperties(heapType), HeapFlags.None, nativeDescription, currentResourceState, clearValue); - GraphicsDevice.RegisterTextureMemoryUsage(SizeInBytes); - - if (hasInitData) - { - // Trigger copy - var commandList = GraphicsDevice.NativeCopyCommandList; - commandList.Reset(GraphicsDevice.NativeCopyCommandAllocator, null); - - long textureCopySize; - var placedSubresources = new PlacedSubResourceFootprint[dataBoxes.Length]; - var rowCounts = new int[dataBoxes.Length]; - var rowSizeInBytes = new long[dataBoxes.Length]; - GraphicsDevice.NativeDevice.GetCopyableFootprints(ref nativeDescription, 0, dataBoxes.Length, 0, placedSubresources, rowCounts, rowSizeInBytes, out textureCopySize); - - SharpDX.Direct3D12.Resource uploadResource; - int uploadOffset; - var uploadMemory = GraphicsDevice.AllocateUploadBuffer((int)textureCopySize, out uploadResource, out uploadOffset, TextureSubresourceAlignment); - - for (int i = 0; i < dataBoxes.Length; ++i) - { - var databox = dataBoxes[i]; - var dataPointer = databox.DataPointer; - - var rowCount = rowCounts[i]; - var sliceCount = placedSubresources[i].Footprint.Depth; - var rowSize = (int)rowSizeInBytes[i]; - var destRowPitch = placedSubresources[i].Footprint.RowPitch; - - // Memcpy data - for (int z = 0; z < sliceCount; ++z) - { - var uploadMemoryCurrent = uploadMemory + (int)placedSubresources[i].Offset + z * destRowPitch * rowCount; - var dataPointerCurrent = dataPointer + z * databox.SlicePitch; - for (int y = 0; y < rowCount; ++y) - { - Utilities.CopyMemory(uploadMemoryCurrent, dataPointerCurrent, rowSize); - uploadMemoryCurrent += destRowPitch; - dataPointerCurrent += databox.RowPitch; - } - } - - // Adjust upload offset (circular dependency between GetCopyableFootprints and AllocateUploadBuffer) - placedSubresources[i].Offset += uploadOffset; - - commandList.CopyTextureRegion(new TextureCopyLocation(NativeResource, i), 0, 0, 0, new TextureCopyLocation(uploadResource, placedSubresources[i]), null); - } - - commandList.ResourceBarrierTransition(NativeResource, ResourceStates.CopyDestination, initialResourceState); - commandList.Close(); - - GraphicsDevice.WaitCopyQueue(); - } - - NativeResourceState = initialResourceState; - } - - NativeShaderResourceView = GetShaderResourceView(ViewType, ArraySlice, MipLevel); - NativeRenderTargetView = GetRenderTargetView(ViewType, ArraySlice, MipLevel); - NativeDepthStencilView = GetDepthStencilView(out HasStencil); - NativeUnorderedAccessView = GetUnorderedAccessView(ViewType, ArraySlice, MipLevel); - } - - protected internal override void OnDestroyed() - { - // If it was a View, do not release reference - if (ParentTexture != null) - { - NativeDeviceChild = null; - } - else if (GraphicsDevice != null) - { - GraphicsDevice.RegisterTextureMemoryUsage(-SizeInBytes); - } - - base.OnDestroyed(); - } - - private void OnRecreateImpl() - { - // Dependency: wait for underlying texture to be recreated - if (ParentTexture != null && ParentTexture.LifetimeState != GraphicsResourceLifetimeState.Active) - return; - - // Render Target / Depth Stencil are considered as "dynamic" - if ((Usage == GraphicsResourceUsage.Immutable - || Usage == GraphicsResourceUsage.Default) - && !IsRenderTarget && !IsDepthStencil) - return; - - if (ParentTexture == null && GraphicsDevice != null) - { - GraphicsDevice.RegisterTextureMemoryUsage(-SizeInBytes); - } - - InitializeFromImpl(); - } - - /// - /// Gets a specific from this texture. - /// - /// Type of the view slice. - /// The texture array slice index. - /// The mip map slice index. - /// An - private CpuDescriptorHandle GetShaderResourceView(ViewType viewType, int arrayOrDepthSlice, int mipIndex) - { - if (!IsShaderResource) - return new CpuDescriptorHandle(); - - int arrayCount; - int mipCount; - GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount); - - // Create the view - // TODO D3D12 Shader4ComponentMapping is now set to default value D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING (0x00001688); need better control - var srvDescription = new ShaderResourceViewDescription() { Shader4ComponentMapping = 0x00001688, Format = ComputeShaderResourceViewFormat() }; - - // Initialize for texture arrays or texture cube - if (this.ArraySize > 1) - { - // If texture cube - if (this.Dimension == TextureDimension.TextureCube && viewType == ViewType.Full) - { - srvDescription.Dimension = ShaderResourceViewDimension.TextureCube; - srvDescription.TextureCube.MipLevels = mipCount; - srvDescription.TextureCube.MostDetailedMip = mipIndex; - } - else - { - // Else regular Texture array - // Multisample? - if (IsMultisample) - { - if (Dimension != TextureDimension.Texture2D) - { - throw new NotSupportedException("Multisample is only supported for 2D Textures"); - } - - srvDescription.Dimension = ShaderResourceViewDimension.Texture2DMultisampledArray; - srvDescription.Texture2DMSArray.ArraySize = arrayCount; - srvDescription.Texture2DMSArray.FirstArraySlice = arrayOrDepthSlice; - } - else - { - srvDescription.Dimension = Dimension == TextureDimension.Texture2D || Dimension == TextureDimension.TextureCube ? ShaderResourceViewDimension.Texture2DArray : ShaderResourceViewDimension.Texture1DArray; - srvDescription.Texture2DArray.ArraySize = arrayCount; - srvDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice; - srvDescription.Texture2DArray.MipLevels = mipCount; - srvDescription.Texture2DArray.MostDetailedMip = mipIndex; - } - } - } - else - { - if (IsMultisample) - { - if (Dimension != TextureDimension.Texture2D) - { - throw new NotSupportedException("Multisample is only supported for 2D Textures"); - } - - srvDescription.Dimension = ShaderResourceViewDimension.Texture2DMultisampled; - } - else - { - switch (Dimension) - { - case TextureDimension.Texture1D: - srvDescription.Dimension = ShaderResourceViewDimension.Texture1D; - break; - case TextureDimension.Texture2D: - srvDescription.Dimension = ShaderResourceViewDimension.Texture2D; - break; - case TextureDimension.Texture3D: - srvDescription.Dimension = ShaderResourceViewDimension.Texture3D; - break; - case TextureDimension.TextureCube: - throw new NotSupportedException("TextureCube dimension is expecting an arraysize > 1"); - } - // Use srvDescription.Texture as it matches also Texture and Texture3D memory layout - srvDescription.Texture1D.MipLevels = mipCount; - srvDescription.Texture1D.MostDetailedMip = mipIndex; - } - } - - // Default ShaderResourceView - var descriptorHandle = GraphicsDevice.ShaderResourceViewAllocator.Allocate(1); - NativeDevice.CreateShaderResourceView(NativeResource, srvDescription, descriptorHandle); - return descriptorHandle; - } - - /// - /// Gets a specific from this texture. - /// - /// Type of the view slice. - /// The texture array slice index. - /// Index of the mip. - /// An - /// ViewSlice.MipBand is not supported for render targets - private CpuDescriptorHandle GetRenderTargetView(ViewType viewType, int arrayOrDepthSlice, int mipIndex) - { - if (!IsRenderTarget) - return new CpuDescriptorHandle(); - - if (viewType == ViewType.MipBand) - throw new NotSupportedException("ViewSlice.MipBand is not supported for render targets"); - - int arrayCount; - int mipCount; - GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount); - - // Create the render target view - var rtvDescription = new RenderTargetViewDescription() { Format = (SharpDX.DXGI.Format)ViewFormat }; - - if (this.ArraySize > 1) - { - if (this.MultisampleCount > MultisampleCount.None) - { - if (Dimension != TextureDimension.Texture2D) - { - throw new NotSupportedException("Multisample is only supported for 2D Textures"); - } - - rtvDescription.Dimension = RenderTargetViewDimension.Texture2DMultisampledArray; - rtvDescription.Texture2DMSArray.ArraySize = arrayCount; - rtvDescription.Texture2DMSArray.FirstArraySlice = arrayOrDepthSlice; - } - else - { - if (Dimension == TextureDimension.Texture3D) - { - throw new NotSupportedException("Texture Array is not supported for Texture3D"); - } - - rtvDescription.Dimension = Dimension == TextureDimension.Texture2D || Dimension == TextureDimension.TextureCube ? RenderTargetViewDimension.Texture2DArray : RenderTargetViewDimension.Texture1DArray; - - // Use rtvDescription.Texture1DArray as it matches also Texture memory layout - rtvDescription.Texture1DArray.ArraySize = arrayCount; - rtvDescription.Texture1DArray.FirstArraySlice = arrayOrDepthSlice; - rtvDescription.Texture1DArray.MipSlice = mipIndex; - } - } - else - { - if (IsMultisample) - { - if (Dimension != TextureDimension.Texture2D) - { - throw new NotSupportedException("Multisample is only supported for 2D RenderTarget Textures"); - } - - rtvDescription.Dimension = RenderTargetViewDimension.Texture2DMultisampled; - } - else - { - switch (Dimension) - { - case TextureDimension.Texture1D: - rtvDescription.Dimension = RenderTargetViewDimension.Texture1D; - rtvDescription.Texture1D.MipSlice = mipIndex; - break; - case TextureDimension.Texture2D: - rtvDescription.Dimension = RenderTargetViewDimension.Texture2D; - rtvDescription.Texture2D.MipSlice = mipIndex; - break; - case TextureDimension.Texture3D: - rtvDescription.Dimension = RenderTargetViewDimension.Texture3D; - rtvDescription.Texture3D.DepthSliceCount = arrayCount; - rtvDescription.Texture3D.FirstDepthSlice = arrayOrDepthSlice; - rtvDescription.Texture3D.MipSlice = mipIndex; - break; - case TextureDimension.TextureCube: - throw new NotSupportedException("TextureCube dimension is expecting an arraysize > 1"); - } - } - } - - var descriptorHandle = GraphicsDevice.RenderTargetViewAllocator.Allocate(1); - NativeDevice.CreateRenderTargetView(NativeResource, rtvDescription, descriptorHandle); - return descriptorHandle; - } - - private CpuDescriptorHandle GetDepthStencilView(out bool hasStencil) - { - hasStencil = false; - if (!IsDepthStencil) - return new CpuDescriptorHandle(); - - // Check that the format is supported - if (ComputeShaderResourceFormatFromDepthFormat(ViewFormat) == PixelFormat.None) - throw new NotSupportedException("Depth stencil format [{0}] not supported".ToFormat(ViewFormat)); - - // Setup the HasStencil flag - hasStencil = IsStencilFormat(ViewFormat); - - // Create a Depth stencil view on this texture2D - var depthStencilViewDescription = new DepthStencilViewDescription - { - Format = ComputeDepthViewFormatFromTextureFormat(ViewFormat), - Flags = DepthStencilViewFlags.None, - }; - - if (ArraySize > 1) - { - depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DArray; - depthStencilViewDescription.Texture2DArray.ArraySize = ArraySize; - depthStencilViewDescription.Texture2DArray.FirstArraySlice = 0; - depthStencilViewDescription.Texture2DArray.MipSlice = 0; - } - else - { - depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2D; - depthStencilViewDescription.Texture2D.MipSlice = 0; - } - - if (MultisampleCount > MultisampleCount.None) - depthStencilViewDescription.Dimension = DepthStencilViewDimension.Texture2DMultisampled; - - if (IsDepthStencilReadOnly) - { - if (!IsDepthStencilReadOnlySupported(GraphicsDevice)) - throw new NotSupportedException("Cannot instantiate ReadOnly DepthStencilBuffer. Not supported on this device."); - - // Create a Depth stencil view on this texture2D - depthStencilViewDescription.Flags = DepthStencilViewFlags.ReadOnlyDepth; - if (HasStencil) - depthStencilViewDescription.Flags |= DepthStencilViewFlags.ReadOnlyStencil; - } - - var descriptorHandle = GraphicsDevice.DepthStencilViewAllocator.Allocate(1); - NativeDevice.CreateDepthStencilView(NativeResource, depthStencilViewDescription, descriptorHandle); - return descriptorHandle; - } - - private CpuDescriptorHandle GetUnorderedAccessView(ViewType viewType, int arrayOrDepthSlice, int mipIndex) - { - if (!IsUnorderedAccess) - return new CpuDescriptorHandle(); - - if (IsMultisample) - throw new NotSupportedException("Multisampling is not supported for unordered access views"); - - int arrayCount; - int mipCount; - GetViewSliceBounds(viewType, ref arrayOrDepthSlice, ref mipIndex, out arrayCount, out mipCount); - - // Create a Unordered Access view on this texture2D - var uavDescription = new UnorderedAccessViewDescription - { - Format = (SharpDX.DXGI.Format)ViewFormat - }; - - if (ArraySize > 1) - { - switch (Dimension) - { - case TextureDimension.Texture1D: - uavDescription.Dimension = UnorderedAccessViewDimension.Texture1DArray; - break; - case TextureDimension.TextureCube: - case TextureDimension.Texture2D: - uavDescription.Dimension = UnorderedAccessViewDimension.Texture2DArray; - break; - case TextureDimension.Texture3D: - throw new NotSupportedException("Texture 3D is not supported for Texture Arrays"); - - } - - uavDescription.Texture2DArray.ArraySize = arrayCount; - uavDescription.Texture2DArray.FirstArraySlice = arrayOrDepthSlice; - uavDescription.Texture2DArray.MipSlice = mipIndex; - } - else - { - switch (Dimension) - { - case TextureDimension.Texture1D: - uavDescription.Dimension = UnorderedAccessViewDimension.Texture1D; - uavDescription.Texture1D.MipSlice = mipIndex; - break; - case TextureDimension.Texture2D: - uavDescription.Dimension = UnorderedAccessViewDimension.Texture2D; - uavDescription.Texture2D.MipSlice = mipIndex; - break; - case TextureDimension.Texture3D: - uavDescription.Dimension = UnorderedAccessViewDimension.Texture3D; - uavDescription.Texture3D.FirstWSlice = arrayOrDepthSlice; - uavDescription.Texture3D.MipSlice = mipIndex; - uavDescription.Texture3D.WSize = arrayCount; - break; - case TextureDimension.TextureCube: - throw new NotSupportedException("TextureCube dimension is expecting an array size > 1"); - } - } - - var descriptorHandle = GraphicsDevice.UnorderedAccessViewAllocator.Allocate(1); - NativeDevice.CreateUnorderedAccessView(NativeResource, null, uavDescription, descriptorHandle); - return descriptorHandle; - } - - internal static ResourceFlags GetBindFlagsFromTextureFlags(TextureFlags flags) - { - var result = ResourceFlags.None; - - if ((flags & TextureFlags.RenderTarget) != 0) - result |= ResourceFlags.AllowRenderTarget; - - if ((flags & TextureFlags.UnorderedAccess) != 0) - result |= ResourceFlags.AllowUnorderedAccess; - - if ((flags & TextureFlags.DepthStencil) != 0) - { - result |= ResourceFlags.AllowDepthStencil; - if ((flags & TextureFlags.ShaderResource) == 0) - result |= ResourceFlags.DenyShaderResource; - } - - return result; - } - - internal static unsafe SharpDX.DataBox[] ConvertDataBoxes(DataBox[] dataBoxes) - { - if (dataBoxes == null || dataBoxes.Length == 0) - return null; - - var sharpDXDataBoxes = new SharpDX.DataBox[dataBoxes.Length]; - fixed (void* pDataBoxes = sharpDXDataBoxes) - Utilities.Write((IntPtr)pDataBoxes, dataBoxes, 0, dataBoxes.Length); - - return sharpDXDataBoxes; - } - - private bool IsFlipped() - { - return false; - } - - private ResourceDescription ConvertToNativeDescription1D() - { - return ResourceDescription.Texture1D((SharpDX.DXGI.Format)textureDescription.Format, textureDescription.Width, (short)textureDescription.ArraySize, (short)textureDescription.MipLevels, GetBindFlagsFromTextureFlags(textureDescription.Flags)); - } - - private SharpDX.DXGI.Format ComputeShaderResourceViewFormat() - { - // Special case for DepthStencil ShaderResourceView that are bound as Float - var viewFormat = (SharpDX.DXGI.Format)ViewFormat; - if (IsDepthStencil) - { - viewFormat = (SharpDX.DXGI.Format)ComputeShaderResourceFormatFromDepthFormat(ViewFormat); - } - - return viewFormat; - } - - private static TextureDescription ConvertFromNativeDescription(ResourceDescription description, bool isShaderResource = false) - { - var desc = new TextureDescription() - { - Dimension = TextureDimension.Texture2D, - Width = (int)description.Width, - Height = description.Height, - Depth = 1, - MultisampleCount = (MultisampleCount)description.SampleDescription.Count, - Format = (PixelFormat)description.Format, - MipLevels = description.MipLevels, - Usage = GraphicsResourceUsage.Default, - ArraySize = description.DepthOrArraySize, - Flags = TextureFlags.None - }; - - if ((description.Flags & ResourceFlags.AllowRenderTarget) != 0) - desc.Flags |= TextureFlags.RenderTarget; - if ((description.Flags & ResourceFlags.AllowUnorderedAccess) != 0) - desc.Flags |= TextureFlags.UnorderedAccess; - if ((description.Flags & ResourceFlags.AllowDepthStencil) != 0) - desc.Flags |= TextureFlags.DepthStencil; - if ((description.Flags & ResourceFlags.DenyShaderResource) == 0 && isShaderResource) - desc.Flags |= TextureFlags.ShaderResource; - - return desc; - } - - private ResourceDescription ConvertToNativeDescription2D() - { - var format = (SharpDX.DXGI.Format)textureDescription.Format; - var flags = textureDescription.Flags; - - // If the texture is going to be bound on the depth stencil, for to use TypeLess format - if (IsDepthStencil) - { - if (IsShaderResource && GraphicsDevice.Features.CurrentProfile < GraphicsProfile.Level_10_0) - { - throw new NotSupportedException(String.Format("ShaderResourceView for DepthStencil Textures are not supported for Graphics profile < 10.0 (Current: [{0}])", GraphicsDevice.Features.CurrentProfile)); - } - else - { - // Determine TypeLess Format and ShaderResourceView Format - if (GraphicsDevice.Features.CurrentProfile < GraphicsProfile.Level_10_0) - { - switch (textureDescription.Format) - { - case PixelFormat.D16_UNorm: - format = SharpDX.DXGI.Format.D16_UNorm; - break; - case PixelFormat.D32_Float: - format = SharpDX.DXGI.Format.D32_Float; - break; - case PixelFormat.D24_UNorm_S8_UInt: - format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt; - break; - case PixelFormat.D32_Float_S8X24_UInt: - format = SharpDX.DXGI.Format.D32_Float_S8X24_UInt; - break; - default: - throw new NotSupportedException(String.Format("Unsupported DepthFormat [{0}] for depth buffer", textureDescription.Format)); - } - } - else - { - switch (textureDescription.Format) - { - case PixelFormat.D16_UNorm: - format = SharpDX.DXGI.Format.R16_Typeless; - break; - case PixelFormat.D32_Float: - format = SharpDX.DXGI.Format.R32_Typeless; - break; - case PixelFormat.D24_UNorm_S8_UInt: - //format = SharpDX.DXGI.Format.D24_UNorm_S8_UInt; - format = SharpDX.DXGI.Format.R24G8_Typeless; - break; - case PixelFormat.D32_Float_S8X24_UInt: - format = SharpDX.DXGI.Format.R32G8X24_Typeless; - break; - default: - throw new NotSupportedException(String.Format("Unsupported DepthFormat [{0}] for depth buffer", textureDescription.Format)); - } - } - } - } - - return ResourceDescription.Texture2D(format, textureDescription.Width, textureDescription.Height, (short)textureDescription.ArraySize, (short)textureDescription.MipLevels, (short)textureDescription.MultisampleCount, 0, GetBindFlagsFromTextureFlags(flags)); - } - - internal ClearValue? GetClearValue() - { - if (IsDepthStencil) - { - return new ClearValue - { - Format = ComputeDepthViewFormatFromTextureFormat(ViewFormat), - DepthStencil = new DepthStencilValue - { - Depth = 1.0f, - Stencil = 0, - } - }; - } - - if (IsRenderTarget) - { - return new ClearValue - { - Format = (SharpDX.DXGI.Format)textureDescription.Format, - Color = new RawVector4(0, 0, 0, 1), - }; - } - - return null; - } - - internal static PixelFormat ComputeShaderResourceFormatFromDepthFormat(PixelFormat format) - { - PixelFormat viewFormat; - - // Determine TypeLess Format and ShaderResourceView Format - switch (format) - { - case PixelFormat.D16_UNorm: - viewFormat = PixelFormat.R16_Float; - break; - case PixelFormat.D32_Float: - viewFormat = PixelFormat.R32_Float; - break; - case PixelFormat.D24_UNorm_S8_UInt: - viewFormat = PixelFormat.R24_UNorm_X8_Typeless; - break; - case PixelFormat.D32_Float_S8X24_UInt: - viewFormat = PixelFormat.R32_Float_X8X24_Typeless; - break; - default: - viewFormat = PixelFormat.None; - break; - } - - return viewFormat; - } - - internal static SharpDX.DXGI.Format ComputeDepthViewFormatFromTextureFormat(PixelFormat format) - { - SharpDX.DXGI.Format viewFormat; - - switch (format) - { - case PixelFormat.R16_Typeless: - case PixelFormat.D16_UNorm: - viewFormat = SharpDX.DXGI.Format.D16_UNorm; - break; - case PixelFormat.R32_Typeless: - case PixelFormat.D32_Float: - viewFormat = SharpDX.DXGI.Format.D32_Float; - break; - case PixelFormat.R24G8_Typeless: - case PixelFormat.D24_UNorm_S8_UInt: - viewFormat = SharpDX.DXGI.Format.D24_UNorm_S8_UInt; - break; - case PixelFormat.R32G8X24_Typeless: - case PixelFormat.D32_Float_S8X24_UInt: - viewFormat = SharpDX.DXGI.Format.D32_Float_S8X24_UInt; - break; - default: - throw new NotSupportedException(String.Format("Unsupported depth format [{0}]", format)); - } - - return viewFormat; - } - - private ResourceDescription ConvertToNativeDescription3D() - { - return ResourceDescription.Texture3D((SharpDX.DXGI.Format)textureDescription.Format, textureDescription.Width, textureDescription.Height, (short)textureDescription.Depth, (short)textureDescription.MipLevels, GetBindFlagsFromTextureFlags(textureDescription.Flags)); - } - - /// - /// Check and modify if necessary the mipmap levels of the image (Troubles with DXT images whose resolution in less than 4x4 in DX9.x). - /// - /// The graphics device. - /// The texture description. - /// The updated texture description. - private static TextureDescription CheckMipLevels(GraphicsDevice device, ref TextureDescription description) - { - if (device.Features.CurrentProfile < GraphicsProfile.Level_10_0 && (description.Flags & TextureFlags.DepthStencil) == 0 && description.Format.IsCompressed()) - { - description.MipLevels = Math.Min(CalculateMipCount(description.Width, description.Height), description.MipLevels); - } - return description; - } - - /// - /// Calculates the mip level from a specified size. - /// - /// The size. - /// The minimum size of the last mip. - /// The mip level. - /// Value must be > 0;size - private static int CalculateMipCountFromSize(int size, int minimumSizeLastMip = 4) - { - if (size <= 0) - { - throw new ArgumentOutOfRangeException("Value must be > 0", "size"); - } - - if (minimumSizeLastMip <= 0) - { - throw new ArgumentOutOfRangeException("Value must be > 0", "minimumSizeLastMip"); - } - - int level = 1; - while ((size / 2) >= minimumSizeLastMip) - { - size = Math.Max(1, size / 2); - level++; - } - return level; - } - - /// - /// Calculates the mip level from a specified width,height,depth. - /// - /// The width. - /// The height. - /// The minimum size of the last mip. - /// The mip level. - /// Value must be > 0;size - private static int CalculateMipCount(int width, int height, int minimumSizeLastMip = 4) - { - return Math.Min(CalculateMipCountFromSize(width, minimumSizeLastMip), CalculateMipCountFromSize(height, minimumSizeLastMip)); - } - - internal static bool IsStencilFormat(PixelFormat format) - { - switch (format) - { - case PixelFormat.R24G8_Typeless: - case PixelFormat.D24_UNorm_S8_UInt: - case PixelFormat.R32G8X24_Typeless: - case PixelFormat.D32_Float_S8X24_UInt: - return true; - } - - return false; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/BlendState.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/BlendState.OpenGL.cs deleted file mode 100644 index 64d5fd2920..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/BlendState.OpenGL.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using OpenTK.Graphics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - class BlendState - { - internal readonly ColorWriteChannels ColorWriteChannels; - - private readonly bool blendEnable; - private readonly BlendEquationMode blendEquationModeColor; - private readonly BlendEquationMode blendEquationModeAlpha; - private readonly BlendingFactorSrc blendFactorSrcColor; - private readonly BlendingFactorSrc blendFactorSrcAlpha; - private readonly BlendingFactorDest blendFactorDestColor; - private readonly BlendingFactorDest blendFactorDestAlpha; - private readonly uint blendEquationHash; - private readonly uint blendFuncHash; - - internal unsafe BlendState(BlendStateDescription blendStateDescription, bool hasRenderTarget) - { - var renderTargets = &blendStateDescription.RenderTarget0; - for (int i = 1; i < 8; ++i) - { - if (renderTargets[i].BlendEnable || renderTargets[i].ColorWriteChannels != ColorWriteChannels.All) - throw new NotSupportedException(); - } - - ColorWriteChannels = blendStateDescription.RenderTarget0.ColorWriteChannels; - if (!hasRenderTarget) - ColorWriteChannels = 0; - - blendEnable = blendStateDescription.RenderTarget0.BlendEnable; - - blendEquationModeColor = ToOpenGL(blendStateDescription.RenderTarget0.ColorBlendFunction); - blendEquationModeAlpha = ToOpenGL(blendStateDescription.RenderTarget0.AlphaBlendFunction); - blendFactorSrcColor = ToOpenGL(blendStateDescription.RenderTarget0.ColorSourceBlend); - blendFactorSrcAlpha = ToOpenGL(blendStateDescription.RenderTarget0.AlphaSourceBlend); - blendFactorDestColor = (BlendingFactorDest)ToOpenGL(blendStateDescription.RenderTarget0.ColorDestinationBlend); - blendFactorDestAlpha = (BlendingFactorDest)ToOpenGL(blendStateDescription.RenderTarget0.AlphaDestinationBlend); - - blendEquationHash = (uint)blendStateDescription.RenderTarget0.ColorBlendFunction - | ((uint)blendStateDescription.RenderTarget0.AlphaBlendFunction << 8); - - blendFuncHash = (uint)blendStateDescription.RenderTarget0.ColorSourceBlend - | ((uint)blendStateDescription.RenderTarget0.AlphaSourceBlend << 8) - | ((uint)blendStateDescription.RenderTarget0.ColorDestinationBlend << 16) - | ((uint)blendStateDescription.RenderTarget0.AlphaDestinationBlend << 24); - } - - public static BlendEquationMode ToOpenGL(BlendFunction blendFunction) - { - switch (blendFunction) - { - case BlendFunction.Subtract: - return BlendEquationMode.FuncSubtract; - case BlendFunction.Add: - return BlendEquationMode.FuncAdd; -#if !XENKO_GRAPHICS_API_OPENGLES - case BlendFunction.Max: - return BlendEquationMode.Max; - case BlendFunction.Min: - return BlendEquationMode.Min; -#endif - case BlendFunction.ReverseSubtract: - return BlendEquationMode.FuncReverseSubtract; - default: - throw new NotSupportedException(); - } - } - - public static BlendingFactorSrc ToOpenGL(Blend blend) - { - switch (blend) - { - case Blend.Zero: - return BlendingFactorSrc.Zero; - case Blend.One: - return BlendingFactorSrc.One; - case Blend.SourceColor: - return (BlendingFactorSrc)BlendingFactorDest.SrcColor; - case Blend.InverseSourceColor: - return (BlendingFactorSrc)BlendingFactorDest.OneMinusSrcColor; - case Blend.SourceAlpha: - return BlendingFactorSrc.SrcAlpha; - case Blend.InverseSourceAlpha: - return BlendingFactorSrc.OneMinusSrcAlpha; - case Blend.DestinationAlpha: - return BlendingFactorSrc.DstAlpha; - case Blend.InverseDestinationAlpha: - return BlendingFactorSrc.OneMinusDstAlpha; - case Blend.DestinationColor: - return BlendingFactorSrc.DstColor; - case Blend.InverseDestinationColor: - return BlendingFactorSrc.OneMinusDstColor; - case Blend.SourceAlphaSaturate: - return BlendingFactorSrc.SrcAlphaSaturate; - case Blend.BlendFactor: - return BlendingFactorSrc.ConstantColor; - case Blend.InverseBlendFactor: - return BlendingFactorSrc.OneMinusConstantColor; - case Blend.SecondarySourceColor: - case Blend.InverseSecondarySourceColor: - case Blend.SecondarySourceAlpha: - case Blend.InverseSecondarySourceAlpha: - throw new NotSupportedException(); - default: - throw new ArgumentOutOfRangeException("blend"); - } - } - - public void Apply(CommandList commandList, BlendState oldBlendState) - { - // note: need to update blend equation, blend function and color mask even when the blend state is disable in order to keep the hash based caching system valid - - if (blendEnable && !oldBlendState.blendEnable) - GL.Enable(EnableCap.Blend); - - if (blendEquationHash != oldBlendState.blendEquationHash) - GL.BlendEquationSeparate(blendEquationModeColor, blendEquationModeAlpha); - - if (blendFuncHash != oldBlendState.blendFuncHash) - GL.BlendFuncSeparate(blendFactorSrcColor, blendFactorDestColor, blendFactorSrcAlpha, blendFactorDestAlpha); - - if (commandList.NewBlendFactor != commandList.BoundBlendFactor) - { - commandList.BoundBlendFactor = commandList.NewBlendFactor; - GL.BlendColor(commandList.NewBlendFactor.R, commandList.NewBlendFactor.G, commandList.NewBlendFactor.B, commandList.NewBlendFactor.A); - } - - if (ColorWriteChannels != oldBlendState.ColorWriteChannels) - { - RestoreColorMask(); - } - - if (!blendEnable && oldBlendState.blendEnable) - GL.Disable(EnableCap.Blend); - } - - internal void RestoreColorMask() - { - GL.ColorMask( - (ColorWriteChannels & ColorWriteChannels.Red) != 0, - (ColorWriteChannels & ColorWriteChannels.Green) != 0, - (ColorWriteChannels & ColorWriteChannels.Blue) != 0, - (ColorWriteChannels & ColorWriteChannels.Alpha) != 0); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/Buffer.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/Buffer.OpenGL.cs deleted file mode 100644 index 288d41cc4b..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/Buffer.OpenGL.cs +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Diagnostics; -using System.Runtime.InteropServices; -using Xenko.Core; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -using PixelFormatGl = OpenTK.Graphics.OpenGL.PixelFormat; -using TextureTarget2d = OpenTK.Graphics.OpenGL.TextureTarget; -#endif - -namespace Xenko.Graphics -{ - public partial class Buffer - { - internal const int BufferTextureEmulatedWidth = 4096; - - internal int BufferId; - internal BufferTarget BufferTarget; - internal BufferUsageHint BufferUsageHint; - - private int bufferTextureElementSize; - - // Special case: ConstantBuffer are faked with a byte array on OpenGL ES 2.0. - internal IntPtr StagingData { get; set; } - - /// - /// Initializes a new instance of the class. - /// - /// The description. - /// Type of the buffer. - /// The view format. - /// The data pointer. - protected Buffer InitializeFromImpl(BufferDescription description, BufferFlags viewFlags, PixelFormat viewFormat, IntPtr dataPointer) - { - bufferDescription = description; - ViewFlags = viewFlags; - - bool isCompressed; - OpenGLConvertExtensions.ConvertPixelFormat(GraphicsDevice, ref viewFormat, out TextureInternalFormat, out TextureFormat, out TextureType, out bufferTextureElementSize, out isCompressed); - - ViewFormat = viewFormat; - - Recreate(dataPointer); - - if (GraphicsDevice != null) - { - GraphicsDevice.RegisterBufferMemoryUsage(SizeInBytes); - } - - return this; - } - - public void Recreate(IntPtr dataPointer) - { - if ((ViewFlags & BufferFlags.VertexBuffer) == BufferFlags.VertexBuffer) - { - BufferTarget = BufferTarget.ArrayBuffer; - } - else if ((ViewFlags & BufferFlags.IndexBuffer) == BufferFlags.IndexBuffer) - { - BufferTarget = BufferTarget.ElementArrayBuffer; - } - else if ((ViewFlags & BufferFlags.UnorderedAccess) == BufferFlags.UnorderedAccess) - { -#if XENKO_GRAPHICS_API_OPENGLES - throw new NotSupportedException("GLES not support UnorderedAccess buffer"); -#else - BufferTarget = BufferTarget.ShaderStorageBuffer; -#endif - } - else if ((ViewFlags & BufferFlags.ShaderResource) == BufferFlags.ShaderResource && GraphicsDevice.HasTextureBuffers) - { -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - BufferTarget = BufferTarget.TextureBuffer; -#endif - } - - if ((ViewFlags & BufferFlags.ConstantBuffer) == BufferFlags.ConstantBuffer) - { - BufferTarget = BufferTarget.UniformBuffer; - - // Special case: ConstantBuffer are stored CPU side - StagingData = Marshal.AllocHGlobal(Description.SizeInBytes); - } - else if (Description.Usage == GraphicsResourceUsage.Dynamic) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - { - // OpenGL ES might not always support MapBuffer (TODO: Use MapBufferOES if available) - StagingData = Marshal.AllocHGlobal(Description.SizeInBytes); - } -#endif - } - - Init(dataPointer); - } - - /// - protected internal override bool OnRecreate() - { - base.OnRecreate(); - - if (Description.Usage == GraphicsResourceUsage.Immutable - || Description.Usage == GraphicsResourceUsage.Default) - return false; - - Recreate(IntPtr.Zero); - - return true; - } - - /// - protected internal override void OnDestroyed() - { - if (StagingData != IntPtr.Zero) - { - Marshal.FreeHGlobal(StagingData); - StagingData = IntPtr.Zero; - } - - using (GraphicsDevice.UseOpenGLCreationContext()) - { - GL.DeleteTextures(1, ref TextureId); - GL.DeleteBuffers(1, ref BufferId); - } - - BufferId = 0; - - if (GraphicsDevice != null) - { - GraphicsDevice.RegisterBufferMemoryUsage(-SizeInBytes); - } - - base.OnDestroyed(); - } - - protected void Init(IntPtr dataPointer) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2 - && ((Description.BufferFlags & BufferFlags.ConstantBuffer) == BufferFlags.ConstantBuffer - || Description.Usage == GraphicsResourceUsage.Dynamic)) - { - if (dataPointer != IntPtr.Zero) - { - // Special case: ConstantBuffer are faked with a byte array on OpenGL ES 2.0. - unsafe - { - Utilities.CopyMemory(StagingData, dataPointer, Description.SizeInBytes); - } - } - return; - } -#endif - switch (Description.Usage) - { - case GraphicsResourceUsage.Default: - case GraphicsResourceUsage.Immutable: - BufferUsageHint = BufferUsageHint.StaticDraw; - break; - case GraphicsResourceUsage.Dynamic: - case GraphicsResourceUsage.Staging: - BufferUsageHint = BufferUsageHint.DynamicDraw; - break; - default: - throw new ArgumentOutOfRangeException("description.Usage"); - } - - using (var openglContext = GraphicsDevice.UseOpenGLCreationContext()) - { - if ((Flags & BufferFlags.ShaderResource) != 0 && !GraphicsDevice.HasTextureBuffers) - { - // Create a texture instead of a buffer on platforms where it's not supported - elementCount = SizeInBytes / bufferTextureElementSize; - TextureTarget = TextureTarget.Texture2D; - GL.GenTextures(1, out TextureId); - GL.BindTexture(TextureTarget, TextureId); - - GL.TexParameter(TextureTarget, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); - GL.TexParameter(TextureTarget, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); - GL.TexParameter(TextureTarget, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); - - UpdateTextureSubresource(dataPointer, 0, 0, SizeInBytes); - - GL.BindTexture(TextureTarget, 0); - - if (openglContext.CommandList != null) - { - // If we messed up with some states of a command list, mark dirty states - openglContext.CommandList.boundShaderResourceViews[openglContext.CommandList.activeTexture] = null; - } - } - else - { - // If we're on main context, unbind VAO before binding context. - // It will be bound again on next draw. - //if (!creationContext.UseDeviceCreationContext) - // GraphicsDevice.UnbindVertexArrayObject(); - - GL.GenBuffers(1, out BufferId); - GL.BindBuffer(BufferTarget, BufferId); - GL.BufferData(BufferTarget, (IntPtr)Description.SizeInBytes, dataPointer, BufferUsageHint); - GL.BindBuffer(BufferTarget, 0); - - if ((Flags & BufferFlags.ShaderResource) != 0) - { -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - TextureTarget = TextureTarget.TextureBuffer; - GL.GenTextures(1, out TextureId); - GL.BindTexture(TextureTarget, TextureId); - // TODO: Check if this is really valid to cast PixelInternalFormat to SizedInternalFormat in all cases? - GL.TexBuffer(TextureBufferTarget.TextureBuffer, (SizedInternalFormat)TextureInternalFormat, BufferId); -#endif - } - } - } - } - - internal void UpdateTextureSubresource(IntPtr dataPointer, int subresouceLevel, int offset, int count) - { - // If overwriting everything, create a new texture - if (offset == 0 && count == SizeInBytes) - GL.TexImage2D((TextureTarget2d)TextureTarget, subresouceLevel, TextureInternalFormat, Math.Min(BufferTextureEmulatedWidth, elementCount), (elementCount + BufferTextureEmulatedWidth - 1) / BufferTextureEmulatedWidth, 0, TextureFormat, TextureType, IntPtr.Zero); - - // Work with full elements - Debug.Assert(offset % bufferTextureElementSize == 0 && count % bufferTextureElementSize == 0, "When updating a buffer texture, offset and count should be a multiple of the element size"); - offset /= bufferTextureElementSize; - count /= bufferTextureElementSize; - - // Upload data - if (dataPointer != IntPtr.Zero) - { - // First line - if (offset % BufferTextureEmulatedWidth != 0) - { - var firstLineSize = Math.Min(count, BufferTextureEmulatedWidth - (offset % BufferTextureEmulatedWidth)); - - GL.TexSubImage2D((TextureTarget2d)TextureTarget, 0, - offset % BufferTextureEmulatedWidth, offset / BufferTextureEmulatedWidth, // coordinates - BufferTextureEmulatedWidth - (offset % BufferTextureEmulatedWidth), 1, // size - TextureFormat, TextureType, dataPointer); - - offset += firstLineSize; - count -= firstLineSize; - dataPointer += firstLineSize * bufferTextureElementSize; - } - - // Middle lines - if (count / BufferTextureEmulatedWidth > 0) - GL.TexSubImage2D((TextureTarget2d)TextureTarget, 0, - 0, offset / BufferTextureEmulatedWidth, // coordinates - BufferTextureEmulatedWidth, count / BufferTextureEmulatedWidth, // size - TextureFormat, TextureType, dataPointer); - - // Last line is done separately (to avoid buffer overrun if last line is not multiple of BufferTextureEmulatedWidth) - if (count % BufferTextureEmulatedWidth != 0) - GL.TexSubImage2D((TextureTarget2d)TextureTarget, 0, - 0, count / BufferTextureEmulatedWidth, // coordinates - count % BufferTextureEmulatedWidth, 1, // size - TextureFormat, TextureType, dataPointer + (count/ BufferTextureEmulatedWidth * BufferTextureEmulatedWidth) * bufferTextureElementSize); - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/CommandList.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/CommandList.OpenGL.cs deleted file mode 100644 index b56134fc79..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/CommandList.OpenGL.cs +++ /dev/null @@ -1,2011 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL - -using System; -using System.Threading; -using OpenTK.Graphics; -using Xenko.Core; -using Xenko.Core.Mathematics; -using Xenko; -using Xenko.Shaders; -using Color4 = Xenko.Core.Mathematics.Color4; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using PixelFormatGl = OpenTK.Graphics.ES30.PixelFormat; -using PrimitiveTypeGl = OpenTK.Graphics.ES30.PrimitiveType; -using DebugSourceExternal = OpenTK.Graphics.ES30.All; -using QueryCounterTarget = OpenTK.Graphics.ES30.All; -#else -using OpenTK.Graphics.OpenGL; -using PrimitiveTypeGl = OpenTK.Graphics.OpenGL.PrimitiveType; -using TextureTarget2d = OpenTK.Graphics.OpenGL.TextureTarget; -using TextureTarget3d = OpenTK.Graphics.OpenGL.TextureTarget; -#endif - -namespace Xenko.Graphics -{ - public partial class CommandList - { - // How many frames to wait before allowing non-blocking texture readbacks - private const int ReadbackFrameDelay = 2; - private const int MaxBoundRenderTargets = 16; - - internal uint enabledVertexAttribArrays; - private int boundProgram = 0; - - internal int BoundStencilReference; - internal int NewStencilReference; - internal Color4 BoundBlendFactor; - internal Color4 NewBlendFactor; - - private bool vboDirty = true; - - private GraphicsDevice.FBOTexture boundDepthStencilBuffer; - private int boundRenderTargetCount = 0; - private GraphicsDevice.FBOTexture[] boundRenderTargets = new GraphicsDevice.FBOTexture[MaxBoundRenderTargets]; - internal GraphicsResource[] boundShaderResourceViews = new GraphicsResource[64]; - private GraphicsResource[] shaderResourceViews = new GraphicsResource[64]; - private SamplerState[] samplerStates = new SamplerState[64]; - - internal DepthStencilBoundState DepthStencilBoundState; - internal RasterizerBoundState RasterizerBoundState; - - private Buffer[] constantBuffers = new Buffer[64]; - - private int boundFBO; - private bool needUpdateFBO = true; - - private PipelineState newPipelineState; - private PipelineState currentPipelineState; - - private DescriptorSet[] currentDescriptorSets = new DescriptorSet[32]; - - internal int activeTexture = 0; - - private IndexBufferView indexBuffer; - - private VertexBufferView[] vertexBuffers = new VertexBufferView[8]; - -#if !XENKO_GRAPHICS_API_OPENGLES - private readonly float[] nativeViewports = new float[4 * MaxViewportAndScissorRectangleCount]; - private readonly int[] nativeScissorRectangles = new int[4 * MaxViewportAndScissorRectangleCount]; -#endif - - public static CommandList New(GraphicsDevice device) - { - if (device.InternalMainCommandList != null) - { - throw new InvalidOperationException("Can't create multiple command lists with OpenGL"); - } - return new CommandList(device); - } - - private CommandList(GraphicsDevice device) : base(device) - { - device.InternalMainCommandList = this; - - // Default state - DepthStencilBoundState.DepthBufferWriteEnable = true; - DepthStencilBoundState.StencilWriteMask = 0xFF; - RasterizerBoundState.FrontFaceDirection = FrontFaceDirection.Ccw; -#if !XENKO_GRAPHICS_API_OPENGLES - RasterizerBoundState.PolygonMode = PolygonMode.Fill; -#endif - - ClearState(); - } - - public void Reset() - { - } - - public void Flush() - { - - } - - public CompiledCommandList Close() - { - return default(CompiledCommandList); - } - - public void Clear(Texture depthStencilBuffer, DepthStencilClearOptions options, float depth = 1, byte stencil = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_PLATFORM_ANDROID - // Device with no background loading context: check if some loading is pending - if (GraphicsDevice.AsyncPendingTaskWaiting) - GraphicsDevice.ExecutePendingTasks(); -#endif - - var clearFBO = GraphicsDevice.FindOrCreateFBO(depthStencilBuffer); - if (clearFBO != boundFBO) - GL.BindFramebuffer(FramebufferTarget.Framebuffer, clearFBO); - - ClearBufferMask clearBufferMask = - ((options & DepthStencilClearOptions.DepthBuffer) == DepthStencilClearOptions.DepthBuffer ? ClearBufferMask.DepthBufferBit : 0) - | ((options & DepthStencilClearOptions.Stencil) == DepthStencilClearOptions.Stencil ? ClearBufferMask.StencilBufferBit : 0); - GL.ClearDepth(depth); - GL.ClearStencil(stencil); - - // Check if we need to change depth mask - var currentDepthMask = DepthStencilBoundState.DepthBufferWriteEnable; - - if (!currentDepthMask) - GL.DepthMask(true); - GL.Clear(clearBufferMask); - if (!currentDepthMask) - GL.DepthMask(false); - - if (clearFBO != boundFBO) - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - } - - public void Clear(Texture renderTarget, Color4 color) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - var clearFBO = GraphicsDevice.FindOrCreateFBO(renderTarget); - if (clearFBO != boundFBO) - GL.BindFramebuffer(FramebufferTarget.Framebuffer, clearFBO); - - // Check if we need to change color mask - var blendState = currentPipelineState.BlendState; - var needColorMaskOverride = blendState.ColorWriteChannels != ColorWriteChannels.All; - - if (needColorMaskOverride) - GL.ColorMask(true, true, true, true); - - GL.ClearColor(color.R, color.G, color.B, color.A); - GL.Clear(ClearBufferMask.ColorBufferBit); - - // revert the color mask value as it was before - if (needColorMaskOverride) - blendState.RestoreColorMask(); - - if (clearFBO != boundFBO) - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - } - - public unsafe void ClearReadWrite(Buffer buffer, Vector4 value) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - if ((buffer.ViewFlags & BufferFlags.UnorderedAccess) != BufferFlags.UnorderedAccess) - throw new ArgumentException("Buffer does not support unordered access"); - - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - GL.ClearBufferData(buffer.BufferTarget, buffer.TextureInternalFormat, buffer.TextureFormat, All.UnsignedInt8888, ref value); - GL.BindBuffer(buffer.BufferTarget, 0); -#endif - } - - public unsafe void ClearReadWrite(Buffer buffer, Int4 value) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - if ((buffer.ViewFlags & BufferFlags.UnorderedAccess) != BufferFlags.UnorderedAccess) - throw new ArgumentException("Buffer does not support unordered access"); - - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - GL.ClearBufferData(buffer.BufferTarget, buffer.TextureInternalFormat, buffer.TextureFormat, All.UnsignedInt8888, ref value); - GL.BindBuffer(buffer.BufferTarget, 0); -#endif - } - - public unsafe void ClearReadWrite(Buffer buffer, UInt4 value) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - if ((buffer.ViewFlags & BufferFlags.UnorderedAccess) != BufferFlags.UnorderedAccess) - throw new ArgumentException("Buffer does not support unordered access"); - - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - GL.ClearBufferData(buffer.BufferTarget, buffer.TextureInternalFormat, buffer.TextureFormat, All.UnsignedInt8888, ref value); - GL.BindBuffer(buffer.BufferTarget, 0); -#endif - } - - public unsafe void ClearReadWrite(Texture texture, Vector4 value) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - GL.BindTexture(texture.TextureTarget, texture.TextureId); - - GL.ClearTexImage(texture.TextureId, 0, texture.TextureFormat, texture.TextureType, ref value); - - GL.BindTexture(texture.TextureTarget, 0); - boundShaderResourceViews[0] = null; -#endif - } - - public unsafe void ClearReadWrite(Texture texture, Int4 value) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - GL.BindTexture(texture.TextureTarget, texture.TextureId); - - GL.ClearTexImage(texture.TextureId, 0, texture.TextureFormat, texture.TextureType, ref value); - - GL.BindTexture(texture.TextureTarget, 0); - boundShaderResourceViews[0] = null; -#endif - } - - public unsafe void ClearReadWrite(Texture texture, UInt4 value) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - GL.BindTexture(texture.TextureTarget, texture.TextureId); - - GL.ClearTexImage(texture.TextureId, 0, texture.TextureFormat, texture.TextureType, ref value); - - GL.BindTexture(texture.TextureTarget, 0); - boundShaderResourceViews[0] = null; -#endif - } - - private void ClearStateImpl() - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - // Clear sampler states - for (int i = 0; i < samplerStates.Length; ++i) - samplerStates[i] = null; - - for (int i = 0; i < boundShaderResourceViews.Length; ++i) - { - shaderResourceViews[i] = null; - } - - // Clear active texture state - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - - // set default states - currentPipelineState = GraphicsDevice.DefaultPipelineState; - newPipelineState = GraphicsDevice.DefaultPipelineState; - - // Actually reset states - //currentPipelineState.BlendState.Apply(); - GL.Disable(EnableCap.Blend); - GL.ColorMask(true, true, true, true); - currentPipelineState.DepthStencilState.Apply(this); - currentPipelineState.RasterizerState.Apply(this); - -#if XENKO_GRAPHICS_API_OPENGLCORE - GL.Enable(EnableCap.FramebufferSrgb); -#endif - } - - /// - /// Copy a region of a into another. - /// - /// The source from which to copy the data - /// The region of the source to copy. - /// The destination into which to copy the data - /// This might alter some states such as currently bound texture. - public void CopyRegion(GraphicsResource source, int sourceSubresource, ResourceRegion? regionSource, GraphicsResource destination, int destinationSubResource, int dstX = 0, int dstY = 0, int dstZ = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - var sourceTexture = source as Texture; - var destTexture = destination as Texture; - - if (sourceTexture == null || destTexture == null) - { - throw Internal.Refactor.NewNotImplementedException("Copy is only implemented for Texture objects."); - } - - // Get parent texture - if (sourceTexture.ParentTexture != null) - sourceTexture = sourceTexture.ParentTexture; - if (destTexture.ParentTexture != null) - destTexture = sourceTexture.ParentTexture; - - var sourceWidth = Texture.CalculateMipSize(sourceTexture.Description.Width, sourceSubresource % sourceTexture.MipLevels); - var sourceHeight = Texture.CalculateMipSize(sourceTexture.Description.Height, sourceSubresource % sourceTexture.MipLevels); - var sourceDepth = Texture.CalculateMipSize(sourceTexture.Description.Depth, sourceSubresource % sourceTexture.MipLevels); - - var sourceRegion = regionSource.HasValue ? regionSource.Value : new ResourceRegion(0, 0, 0, sourceWidth, sourceHeight, sourceDepth); - var sourceRectangle = new Rectangle(sourceRegion.Left, sourceRegion.Top, sourceRegion.Right - sourceRegion.Left, sourceRegion.Bottom - sourceRegion.Top); - - if (sourceRectangle.Width == 0 || sourceRectangle.Height == 0) - return; - - - if (destTexture.Description.Usage == GraphicsResourceUsage.Staging) - { - if (sourceTexture.Description.Usage == GraphicsResourceUsage.Staging) - { - // Staging => Staging - if (sourceRegion.Left != 0 || sourceRegion.Top != 0 || sourceRegion.Front != 0 - || sourceRegion.Right != sourceWidth || sourceRegion.Bottom != sourceHeight || sourceRegion.Back != sourceDepth) - { - throw new NotSupportedException("ReadPixels from staging texture to staging texture only support full copy of subresource"); - } - -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - { - Utilities.CopyMemory(destTexture.StagingData + destTexture.ComputeBufferOffset(destinationSubResource, 0), - sourceTexture.StagingData + sourceTexture.ComputeBufferOffset(sourceSubresource, 0), - destTexture.ComputeSubresourceSize(destinationSubResource)); - } - else -#endif - { - GL.BindBuffer(BufferTarget.CopyReadBuffer, sourceTexture.PixelBufferObjectId); - GL.BindBuffer(BufferTarget.CopyWriteBuffer, destTexture.PixelBufferObjectId); - GL.CopyBufferSubData(BufferTarget.CopyReadBuffer, BufferTarget.CopyWriteBuffer, - (IntPtr)sourceTexture.ComputeBufferOffset(sourceSubresource, 0), - (IntPtr)destTexture.ComputeBufferOffset(destinationSubResource, 0), - (IntPtr)destTexture.ComputeSubresourceSize(destinationSubResource)); - } - } - else - { - // GPU => Staging - if (dstX != 0 || dstY != 0 || dstZ != 0) - throw new NotSupportedException("ReadPixels from staging texture using non-zero destination is not supported"); - - GL.Viewport(0, 0, sourceWidth, sourceHeight); - - var isDepthBuffer = Texture.InternalIsDepthStencilFormat(sourceTexture.Format); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, isDepthBuffer ? GraphicsDevice.CopyDepthSourceFBO : GraphicsDevice.CopyColorSourceFBO); - var attachmentType = FramebufferAttachment.ColorAttachment0; - - for (int depthSlice = sourceRegion.Front; depthSlice < sourceRegion.Back; ++depthSlice) - { - attachmentType = GraphicsDevice.UpdateFBO(FramebufferTarget.Framebuffer, new GraphicsDevice.FBOTexture(sourceTexture, sourceSubresource / sourceTexture.MipLevels + depthSlice, sourceSubresource % sourceTexture.MipLevels)); - -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - { - var format = destTexture.TextureFormat; - var type = destTexture.TextureType; - - var srcFormat = sourceTexture.Description.Format; - var destFormat = destTexture.Description.Format; - - if (srcFormat == destFormat && destFormat.SizeInBytes() == 4) // in this case we just want to copy the data we don't care about format conversion. - { // RGBA/Unsigned-byte is always a working combination whatever is the internal format (sRGB, etc...) - format = PixelFormatGl.Rgba; - type = PixelType.UnsignedByte; - } - - GL.ReadPixels(sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width, sourceRectangle.Height, format, type, destTexture.StagingData + destTexture.ComputeBufferOffset(destinationSubResource, depthSlice)); - } - else -#endif - { - GL.BindBuffer(BufferTarget.PixelPackBuffer, destTexture.PixelBufferObjectId); - GL.ReadPixels(sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width, sourceRectangle.Height, destTexture.TextureFormat, destTexture.TextureType, (IntPtr)destTexture.ComputeBufferOffset(destinationSubResource, depthSlice)); - GL.BindBuffer(BufferTarget.PixelPackBuffer, 0); - - destTexture.PixelBufferFrame = GraphicsDevice.FrameCounter; - } - } - - // Unbind attachment - GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, attachmentType, TextureTarget2d.Texture2D, 0, 0); - - // Restore FBO and viewport - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - GL.Viewport((int)viewports[0].X, (int)viewports[0].Y, (int)viewports[0].Width, (int)viewports[0].Height); - } - return; - } - - // GPU => GPU - { - var isDepthBuffer = Texture.InternalIsDepthStencilFormat(sourceTexture.Format); - - // Use our temporary mutable FBO - GL.BindFramebuffer(FramebufferTarget.Framebuffer, isDepthBuffer ? GraphicsDevice.CopyDepthSourceFBO : GraphicsDevice.CopyColorSourceFBO); - - var attachmentType = FramebufferAttachment.ColorAttachment0; - - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - GL.Viewport(0, 0, sourceWidth, sourceHeight); - - GL.BindTexture(destTexture.TextureTarget, destTexture.TextureId); - - for (int depthSlice = sourceRegion.Front; depthSlice < sourceRegion.Back; ++depthSlice) - { - // Note: In practice, either it's a 2D texture array and its arrayslice can be non zero, or it's a 3D texture and it's depthslice can be non-zero, but not both at the same time - attachmentType = GraphicsDevice.UpdateFBO(FramebufferTarget.Framebuffer, new GraphicsDevice.FBOTexture(sourceTexture, sourceSubresource / sourceTexture.MipLevels + depthSlice, sourceSubresource % sourceTexture.MipLevels)); - - var arraySlice = destinationSubResource / destTexture.MipLevels; - var mipLevel = destinationSubResource % destTexture.MipLevels; - - switch (destTexture.TextureTarget) - { -#if !XENKO_GRAPHICS_API_OPENGLES - case TextureTarget.Texture1D: - GL.CopyTexSubImage1D(TextureTarget2d.Texture1D, mipLevel, dstX, sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width); - break; -#endif - case TextureTarget.Texture2D: - GL.CopyTexSubImage2D(TextureTarget2d.Texture2D, mipLevel, dstX, dstY, sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width, sourceRectangle.Height); - break; - case TextureTarget.Texture2DArray: - GL.CopyTexSubImage3D(TextureTarget3d.Texture2DArray, mipLevel, dstX, dstY, arraySlice, sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width, sourceRectangle.Height); - break; - case TextureTarget.Texture3D: - GL.CopyTexSubImage3D(TextureTarget3d.Texture3D, mipLevel, dstX, dstY, depthSlice, sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width, sourceRectangle.Height); - break; - case TextureTarget.TextureCubeMap: - GL.CopyTexSubImage2D(Texture.GetTextureTargetForDataSet2D(destTexture.TextureTarget, arraySlice), mipLevel, dstX, dstY, sourceRectangle.Left, sourceRectangle.Top, sourceRectangle.Width, sourceRectangle.Height); - break; - default: - throw new NotSupportedException("Invalid texture target: " + destTexture.TextureTarget); - } - } - - // Unbind texture and force it to be set again next draw call - GL.BindTexture(destTexture.TextureTarget, 0); - boundShaderResourceViews[0] = null; - - // Unbind attachment - GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, attachmentType, TextureTarget2d.Texture2D, 0, 0); - - // Restore FBO and viewport - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - GL.Viewport((int)viewports[0].X, (int)viewports[0].Y, (int)viewports[0].Width, (int)viewports[0].Height); - } - } - - internal void CopyScaler2D(Texture sourceTexture, Texture destTexture, Rectangle sourceRectangle, Rectangle destRectangle, bool flipY = false) - { - // Use rendering - GL.Viewport(0, 0, destTexture.Description.Width, destTexture.Description.Height); - GL.BindFramebuffer(FramebufferTarget.Framebuffer, GraphicsDevice.FindOrCreateFBO(destTexture)); - - var sourceRegionSize = new Vector2(sourceRectangle.Width, sourceRectangle.Height); - var destRegionSize = new Vector2(destRectangle.Width, destRectangle.Height); - - // Source - var sourceSize = new Vector2(sourceTexture.Width, sourceTexture.Height); - var sourceRegionLeftTop = new Vector2(sourceRectangle.Left, sourceRectangle.Top); - var sourceScale = new Vector2(sourceRegionSize.X / sourceSize.X, sourceRegionSize.Y / sourceSize.Y); - var sourceOffset = new Vector2(sourceRegionLeftTop.X / sourceSize.X, sourceRegionLeftTop.Y / sourceSize.Y); - - // Dest - var destSize = new Vector2(destTexture.Width, destTexture.Height); - var destRegionLeftTop = new Vector2(destRectangle.X, flipY ? destRectangle.Bottom : destRectangle.Y); - var destScale = new Vector2(destRegionSize.X / destSize.X, destRegionSize.Y / destSize.Y); - var destOffset = new Vector2(destRegionLeftTop.X / destSize.X, destRegionLeftTop.Y / destSize.Y); - - if (flipY) - destScale.Y = -destScale.Y; - - var enabledColors = new bool[4]; - GL.GetBoolean(GetPName.ColorWritemask, enabledColors); - var isDepthTestEnabled = GL.IsEnabled(EnableCap.DepthTest); - var isCullFaceEnabled = GL.IsEnabled(EnableCap.CullFace); - var isBlendEnabled = GL.IsEnabled(EnableCap.Blend); - var isStencilEnabled = GL.IsEnabled(EnableCap.StencilTest); - GL.Disable(EnableCap.DepthTest); - GL.Disable(EnableCap.CullFace); - GL.Disable(EnableCap.Blend); - GL.Disable(EnableCap.StencilTest); - GL.ColorMask(true, true, true, true); - - // TODO find a better way to detect if sRGB conversion is needed (need to detect if main frame buffer is sRGB or not at init time) -#if XENKO_GRAPHICS_API_OPENGLES - // If we are copying from an SRgb texture to a non SRgb texture, we use a special SRGb copy shader - bool needSRgbConversion = sourceTexture.Description.Format.IsSRgb() && destTexture == GraphicsDevice.WindowProvidedRenderTexture; -#else - bool needSRgbConversion = false; -#endif - int offsetLocation, scaleLocation; - var program = GraphicsDevice.GetCopyProgram(needSRgbConversion, out offsetLocation, out scaleLocation); - - GL.UseProgram(program); - - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - GL.BindTexture(TextureTarget.Texture2D, sourceTexture.TextureId); - boundShaderResourceViews[0] = null; - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); - sourceTexture.BoundSamplerState = GraphicsDevice.SamplerStates.PointClamp; - - vboDirty = true; - enabledVertexAttribArrays |= 1 << 0; - GL.EnableVertexAttribArray(0); - GL.BindBuffer(BufferTarget.ArrayBuffer, GraphicsDevice.GetSquareBuffer().BufferId); - GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, 0, 0); - GL.Uniform4(offsetLocation, sourceOffset.X, sourceOffset.Y, destOffset.X, destOffset.Y); - GL.Uniform4(scaleLocation, sourceScale.X, sourceScale.Y, destScale.X, destScale.Y); - GL.Viewport(0, 0, destTexture.Width, destTexture.Height); - GL.DrawArrays(PrimitiveTypeGl.TriangleStrip, 0, 4); - GL.UseProgram(boundProgram); - - // Restore context - if (isDepthTestEnabled) - GL.Enable(EnableCap.DepthTest); - if (isCullFaceEnabled) - GL.Enable(EnableCap.CullFace); - if (isBlendEnabled) - GL.Enable(EnableCap.Blend); - if (isStencilEnabled) - GL.Enable(EnableCap.StencilTest); - GL.ColorMask(enabledColors[0], enabledColors[1], enabledColors[2], enabledColors[3]); - - // Restore FBO and viewport - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - GL.Viewport((int)viewports[0].X, (int)viewports[0].Y, (int)viewports[0].Width, (int)viewports[0].Height); - } - - internal void CopyScaler2D(Texture sourceTexture, Rectangle sourceRectangle, Rectangle destRectangle, bool needSRgbConversion = false, bool flipY = false) - { - // Use rendering - GL.Viewport(0, 0, sourceTexture.Description.Width, sourceTexture.Description.Height); - - var sourceRegionSize = new Vector2(sourceRectangle.Width, sourceRectangle.Height); - var destRegionSize = new Vector2(destRectangle.Width, destRectangle.Height); - - // Source - var sourceSize = new Vector2(sourceTexture.Width, sourceTexture.Height); - var sourceRegionLeftTop = new Vector2(sourceRectangle.Left, sourceRectangle.Top); - var sourceScale = new Vector2(sourceRegionSize.X / sourceSize.X, sourceRegionSize.Y / sourceSize.Y); - var sourceOffset = new Vector2(sourceRegionLeftTop.X / sourceSize.X, sourceRegionLeftTop.Y / sourceSize.Y); - - // Dest - var destSize = new Vector2(sourceTexture.Width, sourceTexture.Height); - var destRegionLeftTop = new Vector2(destRectangle.X, flipY ? destRectangle.Bottom : destRectangle.Y); - var destScale = new Vector2(destRegionSize.X / destSize.X, destRegionSize.Y / destSize.Y); - var destOffset = new Vector2(destRegionLeftTop.X / destSize.X, destRegionLeftTop.Y / destSize.Y); - - if (flipY) - destScale.Y = -destScale.Y; - - var enabledColors = new bool[4]; - GL.GetBoolean(GetPName.ColorWritemask, enabledColors); - var isDepthTestEnabled = GL.IsEnabled(EnableCap.DepthTest); - var isCullFaceEnabled = GL.IsEnabled(EnableCap.CullFace); - var isBlendEnabled = GL.IsEnabled(EnableCap.Blend); - var isStencilEnabled = GL.IsEnabled(EnableCap.StencilTest); - GL.Disable(EnableCap.DepthTest); - GL.Disable(EnableCap.CullFace); - GL.Disable(EnableCap.Blend); - GL.Disable(EnableCap.StencilTest); - GL.ColorMask(true, true, true, true); - - int offsetLocation, scaleLocation; - var program = GraphicsDevice.GetCopyProgram(needSRgbConversion, out offsetLocation, out scaleLocation); - - GL.UseProgram(program); - - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - GL.BindTexture(TextureTarget.Texture2D, sourceTexture.TextureId); - boundShaderResourceViews[0] = null; - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); - sourceTexture.BoundSamplerState = GraphicsDevice.SamplerStates.PointClamp; - - vboDirty = true; - enabledVertexAttribArrays |= 1 << 0; - GL.EnableVertexAttribArray(0); - GL.BindBuffer(BufferTarget.ArrayBuffer, GraphicsDevice.GetSquareBuffer().BufferId); - GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, 0, 0); - GL.Uniform4(offsetLocation, sourceOffset.X, sourceOffset.Y, destOffset.X, destOffset.Y); - GL.Uniform4(scaleLocation, sourceScale.X, sourceScale.Y, destScale.X, destScale.Y); - GL.Viewport(0, 0, sourceTexture.Width, sourceTexture.Height); - GL.DrawArrays(PrimitiveTypeGl.TriangleStrip, 0, 4); - GL.UseProgram(boundProgram); - - // Restore context - if (isDepthTestEnabled) - GL.Enable(EnableCap.DepthTest); - if (isCullFaceEnabled) - GL.Enable(EnableCap.CullFace); - if (isBlendEnabled) - GL.Enable(EnableCap.Blend); - if (isStencilEnabled) - GL.Enable(EnableCap.StencilTest); - GL.ColorMask(enabledColors[0], enabledColors[1], enabledColors[2], enabledColors[3]); - - // Restore viewport - GL.Viewport((int)viewports[0].X, (int)viewports[0].Y, (int)viewports[0].Width, (int)viewports[0].Height); - } - - /// - /// Copy a into another. - /// - /// The source from which to copy the data - /// The destination into which to copy the data - /// This might alter some states such as currently bound texture. - public void Copy(GraphicsResource source, GraphicsResource destination) - { - // Count subresources - var subresourceCount = 1; - var sourceTexture = source as Texture; - if (sourceTexture != null) - { - subresourceCount = sourceTexture.ArraySize * sourceTexture.MipLevels; - } - - // Copy each subresource - for (int i = 0; i < subresourceCount; ++i) - { - CopyRegion(source, i, null, destination, i); - } - } - - public void CopyMultisample(Texture sourceMultisampleTexture, int sourceSubResource, Texture destTexture, int destSubResource, PixelFormat format = PixelFormat.None) - { - // Check if the source and destination are compatible: - if (sourceMultisampleTexture.Width != destTexture.Width && - sourceMultisampleTexture.Height != destTexture.Height && - sourceMultisampleTexture.Format != destTexture.Format) // TODO: Blitting seems to be okay even if the sizes don't match, but only in case of non-MSAA buffers. - { - throw new InvalidOperationException("sourceMultisampleTexture and destTexture don't match in size and format!"); - } - - // Set up the read (source) buffer to use for the blitting operation: - int readFBOID = GraphicsDevice.FindOrCreateFBO(sourceMultisampleTexture); // Find the FBO that the sourceMultisampleTexture is bound to. - GL.BindFramebuffer(FramebufferTarget.ReadFramebuffer, readFBOID); - - // Set up the draw (destination) buffer to use for the blitting operation: - int drawFBOID = GraphicsDevice.FindOrCreateFBO(destTexture); // Find the FBO that the destTexture is bound to. - GL.BindFramebuffer(FramebufferTarget.DrawFramebuffer, drawFBOID); - - ClearBufferMask clearBufferMask; - BlitFramebufferFilter blitFramebufferFilter; - - // TODO: PERFORMANCE: We could copy the depth buffer AND color buffer at the same time by doing "ClearBufferMask.DepthBufferBit | ClearBufferMask.ColorBufferBit". - if (sourceMultisampleTexture.IsDepthBuffer && destTexture.IsDepthBuffer) - { - clearBufferMask = ClearBufferMask.DepthBufferBit; - blitFramebufferFilter = BlitFramebufferFilter.Nearest; // Must be set to nearest for depth buffers according to the spec: "GL_INVALID_OPERATION is generated if mask contains any of the GL_DEPTH_BUFFER_BIT or GL_STENCIL_BUFFER_BIT and filter is not GL_NEAREST." - } - else - { - clearBufferMask = ClearBufferMask.ColorBufferBit; - blitFramebufferFilter = BlitFramebufferFilter.Linear; // TODO: STABILITY: For integer formats this has to be set to Nearest. - } - -#if !XENKO_PLATFORM_IOS - // MSAA is not supported on iOS currently because OpenTK doesn't expose "GL.BlitFramebuffer()" on iOS for some reason. - // Do the actual blitting operation: - GL.BlitFramebuffer(0, 0, sourceMultisampleTexture.Width, sourceMultisampleTexture.Height, 0, 0, destTexture.Width, destTexture.Height, clearBufferMask, blitFramebufferFilter); -#endif - } - - public void CopyCount(Buffer sourceBuffer, Buffer destBuffer, int offsetToDest) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - Internal.Refactor.ThrowNotImplementedException(); - } - - public void Dispatch(int threadCountX, int threadCountY, int threadCountZ) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if !XENKO_GRAPHICS_API_OPENGLES - GL.DispatchCompute(threadCountX, threadCountY, threadCountZ); -#else - Internal.Refactor.ThrowNotImplementedException(); -#endif - } - - public void Dispatch(Buffer indirectBuffer, int offsetInBytes) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if !XENKO_GRAPHICS_API_OPENGLES - GL.BindBuffer(BufferTarget.DispatchIndirectBuffer, indirectBuffer.BufferId); - - GL.DispatchComputeIndirect((IntPtr)offsetInBytes); - - GL.BindBuffer(BufferTarget.DispatchIndirectBuffer, 0); -#else - Internal.Refactor.ThrowNotImplementedException(); -#endif - } - - public void Draw(int vertexCount, int startVertex = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - PreDraw(); - - GL.DrawArrays(newPipelineState.PrimitiveType, startVertex, vertexCount); - - GraphicsDevice.FrameTriangleCount += (uint)vertexCount; - GraphicsDevice.FrameDrawCalls++; - } - - public void DrawAuto(PrimitiveType primitiveType) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - PreDraw(); - - //GL.DrawArraysIndirect(newPipelineState.PrimitiveType, (IntPtr)0); - //GraphicsDevice.FrameDrawCalls++; - Internal.Refactor.ThrowNotImplementedException(); - } - - /// - /// Draw indexed, non-instanced primitives. - /// - /// Number of indices to draw. - /// The location of the first index read by the GPU from the index buffer. - /// A value added to each index before reading a vertex from the vertex buffer. - public void DrawIndexed(int indexCount, int startIndexLocation = 0, int baseVertexLocation = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - PreDraw(); - -#if XENKO_GRAPHICS_API_OPENGLES - if (baseVertexLocation != 0) - throw new NotSupportedException("DrawIndexed with no null baseVertexLocation is not supported on OpenGL ES."); - GL.DrawElements(newPipelineState.PrimitiveType, indexCount, indexBuffer.Type, indexBuffer.Buffer.StagingData + indexBuffer.Offset + (startIndexLocation * indexBuffer.ElementSize)); // conversion to IntPtr required on Android -#else - GL.DrawElementsBaseVertex(newPipelineState.PrimitiveType, indexCount, indexBuffer.Type, indexBuffer.Buffer.StagingData + indexBuffer.Offset + (startIndexLocation * indexBuffer.ElementSize), baseVertexLocation); -#endif - - GraphicsDevice.FrameDrawCalls++; - GraphicsDevice.FrameTriangleCount += (uint)indexCount; - } - - /// - /// Draw indexed, instanced primitives. - /// - /// Number of indices read from the index buffer for each instance. - /// Number of instances to draw. - /// The location of the first index read by the GPU from the index buffer. - /// A value added to each index before reading a vertex from the vertex buffer. - /// A value added to each index before reading per-instance data from a vertex buffer. - public void DrawIndexedInstanced(int indexCountPerInstance, int instanceCount, int startIndexLocation = 0, int baseVertexLocation = 0, int startInstanceLocation = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - PreDraw(); -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - GL.DrawElementsInstancedBaseVertex(newPipelineState.PrimitiveType, indexCountPerInstance, indexBuffer.Type, indexBuffer.Buffer.StagingData + indexBuffer.Offset + (startIndexLocation * indexBuffer.ElementSize), instanceCount, baseVertexLocation); -#endif - - GraphicsDevice.FrameDrawCalls++; - GraphicsDevice.FrameTriangleCount += (uint)(indexCountPerInstance * instanceCount); - } - - /// - /// Draw indexed, instanced, GPU-generated primitives. - /// - /// A buffer containing the GPU generated primitives. - /// Offset in pBufferForArgs to the start of the GPU generated primitives. - public void DrawIndexedInstanced(Buffer argumentsBuffer, int alignedByteOffsetForArgs = 0) - { - - if (argumentsBuffer == null) throw new ArgumentNullException(nameof(argumentsBuffer)); - -#if DEBUG - //GraphicsDevice.EnsureContextActive(); -#endif - //PreDraw(); - - //GraphicsDevice.FrameDrawCalls++; - - Internal.Refactor.ThrowNotImplementedException(); - } - - /// - /// Draw non-indexed, instanced primitives. - /// - /// Number of vertices to draw. - /// Number of instances to draw. - /// Index of the first vertex. - /// A value added to each index before reading per-instance data from a vertex buffer. - public void DrawInstanced(int vertexCountPerInstance, int instanceCount, int startVertexLocation = 0, int startInstanceLocation = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - PreDraw(); - -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - throw new NotSupportedException("DrawArraysInstanced is not supported on OpenGL ES 2"); -#endif - GL.DrawArraysInstanced(newPipelineState.PrimitiveType, startVertexLocation, vertexCountPerInstance, instanceCount); - - GraphicsDevice.FrameDrawCalls++; - GraphicsDevice.FrameTriangleCount += (uint)(vertexCountPerInstance * instanceCount); - } - - /// - /// Draw instanced, GPU-generated primitives. - /// - /// An arguments buffer - /// Offset in pBufferForArgs to the start of the GPU generated primitives. - public void DrawInstanced(Buffer argumentsBuffer, int alignedByteOffsetForArgs = 0) - { - if (argumentsBuffer == null) - throw new ArgumentNullException(nameof(argumentsBuffer)); - -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - PreDraw(); - -#if XENKO_GRAPHICS_API_OPENGLES - GraphicsDevice.FrameDrawCalls++; - Internal.Refactor.ThrowNotImplementedException(); -#else - GL.BindBuffer(BufferTarget.DrawIndirectBuffer, argumentsBuffer.BufferId); - - GL.DrawArraysIndirect(newPipelineState.PrimitiveType, (IntPtr)alignedByteOffsetForArgs); - - GL.BindBuffer(BufferTarget.DrawIndirectBuffer, 0); - - GraphicsDevice.FrameDrawCalls++; -#endif - } - - public void BeginProfile(Color4 profileColor, string name) - { -#if !XENKO_PLATFORM_IOS - if (GraphicsDevice.ProfileEnabled) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.HasKhronosDebugKHR) - GL.Khr.PushDebugGroup(DebugSourceExternal.DebugSourceApplication, 1, -1, name); - else -#endif - GL.PushDebugGroup(DebugSourceExternal.DebugSourceApplication, 1, -1, name); - } -#endif - } - - public void EndProfile() - { -#if !XENKO_PLATFORM_IOS - if (GraphicsDevice.ProfileEnabled) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.HasKhronosDebugKHR) - GL.Khr.PopDebugGroup(); - else -#endif - GL.PopDebugGroup(); - } -#endif - } - - /// - /// Submit a timestamp query. - /// - /// The QueryPool owning the query. - /// The query index. - public void WriteTimestamp(QueryPool queryPool, int index) - { -#if XENKO_GRAPHICS_API_OPENGLES && !XENKO_PLATFORM_IOS - GL.Ext.QueryCounter(queryPool.NativeQueries[index], QueryCounterTarget.TimestampExt); -#elif !XENKO_PLATFORM_IOS - GL.QueryCounter(queryPool.NativeQueries[index], QueryCounterTarget.Timestamp); -#endif - } - - public void ResetQueryPool(QueryPool queryPool) - { - } - - public MappedResource MapSubresource(GraphicsResource resource, int subResourceIndex, MapMode mapMode, bool doNotWait = false, int offsetInBytes = 0, int lengthInBytes = 0) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - // This resource has just been recycled by the GraphicsResourceAllocator, we force a rename to avoid GPU=>GPU sync point - if (resource.DiscardNextMap && mapMode == MapMode.WriteNoOverwrite) - mapMode = MapMode.WriteDiscard; - - - var buffer = resource as Buffer; - if (buffer != null) - { - if (lengthInBytes == 0) - lengthInBytes = buffer.Description.SizeInBytes; - - if (buffer.StagingData != IntPtr.Zero) - { - // Specific case for constant buffers - return new MappedResource(resource, subResourceIndex, new DataBox { DataPointer = buffer.StagingData + offsetInBytes, SlicePitch = 0, RowPitch = 0 }, offsetInBytes, lengthInBytes); - } - -#if XENKO_GRAPHICS_API_OPENGLES - // OpenGL ES 2 needs Staging Data - if (GraphicsDevice.IsOpenGLES2) - { - Internal.Refactor.ThrowNotImplementedException(); - } -#endif - - IntPtr mapResult = IntPtr.Zero; - - //UnbindVertexArrayObject(); - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - -#if !XENKO_GRAPHICS_API_OPENGLES - //if (mapMode != MapMode.WriteDiscard && mapMode != MapMode.WriteNoOverwrite) - // mapResult = GL.MapBuffer(buffer.bufferTarget, mapMode.ToOpenGL()); - //else -#endif - { - // Orphan the buffer (let driver knows we don't need it anymore) - if (mapMode == MapMode.WriteDiscard) - { - doNotWait = true; - GL.BufferData(buffer.BufferTarget, (IntPtr)buffer.Description.SizeInBytes, IntPtr.Zero, buffer.BufferUsageHint); - } - - var unsynchronized = doNotWait && mapMode != MapMode.Read && mapMode != MapMode.ReadWrite; - - mapResult = GL.MapBufferRange(buffer.BufferTarget, (IntPtr)offsetInBytes, (IntPtr)lengthInBytes, mapMode.ToOpenGLMask() | (unsynchronized ? BufferAccessMask.MapUnsynchronizedBit : 0)); - } - - return new MappedResource(resource, subResourceIndex, new DataBox { DataPointer = mapResult, SlicePitch = 0, RowPitch = 0 }); - } - - var texture = resource as Texture; - if (texture != null) - { - if (lengthInBytes == 0) - lengthInBytes = texture.ComputeSubresourceSize(subResourceIndex); - - if (mapMode == MapMode.Read) - { - if (texture.Description.Usage != GraphicsResourceUsage.Staging) - throw new NotSupportedException("Only staging textures can be mapped."); - - var mipLevel = subResourceIndex % texture.MipLevels; - -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2 || texture.StagingData != IntPtr.Zero) - { - return new MappedResource(resource, subResourceIndex, new DataBox { DataPointer = texture.StagingData + offsetInBytes + texture.ComputeBufferOffset(subResourceIndex, 0), SlicePitch = texture.ComputeSlicePitch(mipLevel), RowPitch = texture.ComputeRowPitch(mipLevel) }, offsetInBytes, lengthInBytes); - } - else -#endif - { - if (doNotWait) - { - // Wait at least 2 frames after last operation - if (GraphicsDevice.FrameCounter < texture.PixelBufferFrame + ReadbackFrameDelay) - { - return new MappedResource(resource, subResourceIndex, new DataBox(), offsetInBytes, lengthInBytes); - } - } - - return MapTexture(texture, true, BufferTarget.PixelPackBuffer, texture.PixelBufferObjectId, subResourceIndex, mapMode, offsetInBytes, lengthInBytes); - } - } - else if (mapMode == MapMode.WriteDiscard) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - { - Internal.Refactor.ThrowNotImplementedException(); - } -#endif - if (texture.Description.Usage != GraphicsResourceUsage.Dynamic) - throw new NotSupportedException("Only dynamic texture can be mapped."); - - // Create a temporary unpack pixel buffer - // TODO: Pool/allocator? (it's an upload buffer basically) - var pixelBufferObjectId = texture.GeneratePixelBufferObject(BufferTarget.PixelUnpackBuffer, PixelStoreParameter.UnpackAlignment, BufferUsageHint.DynamicCopy, texture.ComputeSubresourceSize(subResourceIndex)); - - return MapTexture(texture, false, BufferTarget.PixelUnpackBuffer, pixelBufferObjectId, subResourceIndex, mapMode, offsetInBytes, lengthInBytes); - } - } - - throw Internal.Refactor.NewNotImplementedException("MapSubresource not implemented for type " + resource.GetType()); - } - - public void UnmapSubresource(MappedResource unmapped) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - var texture = unmapped.Resource as Texture; - if (texture != null) - { - if (texture.Description.Usage == GraphicsResourceUsage.Staging) - { -#if XENKO_GRAPHICS_API_OPENGLES - // unmapping on OpenGL ES 2 means doing nothing since the buffer is on the CPU memory - if (!GraphicsDevice.IsOpenGLES2) -#endif - { - GL.BindBuffer(BufferTarget.PixelPackBuffer, texture.PixelBufferObjectId); - GL.UnmapBuffer(BufferTarget.PixelPackBuffer); - GL.BindBuffer(BufferTarget.PixelPackBuffer, 0); - } - } -#if XENKO_GRAPHICS_API_OPENGLES - else if (!GraphicsDevice.IsOpenGLES2 && texture.Description.Usage == GraphicsResourceUsage.Dynamic) -#else - else if (texture.Description.Usage == GraphicsResourceUsage.Dynamic) -#endif - { - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, unmapped.PixelBufferObjectId); - GL.UnmapBuffer(BufferTarget.PixelUnpackBuffer); - - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - GL.BindTexture(texture.TextureTarget, texture.TextureId); - - var mipLevel = unmapped.SubResourceIndex % texture.MipLevels; - var arraySlice = unmapped.SubResourceIndex / texture.MipLevels; - - // Bind buffer to texture - switch (texture.TextureTarget) - { -#if !XENKO_GRAPHICS_API_OPENGLES - case TextureTarget.Texture1D: - GL.TexSubImage1D(TextureTarget.Texture1D, mipLevel, 0, texture.Width, texture.TextureFormat, texture.TextureType, IntPtr.Zero); - break; -#endif - case TextureTarget.Texture2D: - GL.TexSubImage2D(TextureTarget2d.Texture2D, mipLevel, 0, 0, texture.Width, texture.Height, texture.TextureFormat, texture.TextureType, IntPtr.Zero); - break; - case TextureTarget.Texture2DArray: - GL.TexSubImage3D(TextureTarget3d.Texture2DArray, mipLevel, 0, 0, arraySlice, texture.Width, texture.Height, 1, texture.TextureFormat, texture.TextureType, IntPtr.Zero); - break; - case TextureTarget.Texture3D: - GL.TexSubImage3D(TextureTarget3d.Texture3D, mipLevel, 0, 0, 0, texture.Width, texture.Height, texture.Depth, texture.TextureFormat, texture.TextureType, IntPtr.Zero); - break; - case TextureTarget.TextureCubeMap: - GL.TexSubImage2D(Texture.GetTextureTargetForDataSet2D(texture.TextureTarget, arraySlice), mipLevel, 0, 0, texture.Width, texture.Height, texture.TextureFormat, texture.TextureType, IntPtr.Zero); - break; - default: - throw new NotSupportedException("Invalid texture target: " + texture.TextureTarget); - } - GL.BindTexture(texture.TextureTarget, 0); - boundShaderResourceViews[0] = null; - GL.BindBuffer(BufferTarget.PixelUnpackBuffer, 0); - GL.DeleteBuffer(unmapped.PixelBufferObjectId); - } - else - { - throw new NotSupportedException("Not supported mapper operation for Usage: " + texture.Description.Usage); - } - } - else - { - var buffer = unmapped.Resource as Buffer; - if (buffer != null) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2 || buffer.StagingData != IntPtr.Zero) -#else - if (buffer.StagingData != IntPtr.Zero) -#endif - { - // Only buffer with StagingData (fake cbuffer) could be mapped - if (buffer.StagingData == IntPtr.Zero) - throw new InvalidOperationException(); - - // Is it a real buffer? (fake cbuffer have no real GPU counter-part in OpenGL ES 2.0 - if (buffer.BufferId != 0) - { - //UnbindVertexArrayObject(); - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - if (unmapped.OffsetInBytes == 0 && unmapped.SizeInBytes == buffer.SizeInBytes) - GL.BufferData(buffer.BufferTarget, unmapped.SizeInBytes, unmapped.DataBox.DataPointer, buffer.BufferUsageHint); - else - GL.BufferSubData(buffer.BufferTarget, (IntPtr)unmapped.OffsetInBytes, (IntPtr)unmapped.SizeInBytes, unmapped.DataBox.DataPointer); - } - } - else - { - //UnbindVertexArrayObject(); - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - GL.UnmapBuffer(buffer.BufferTarget); - } - } - else // neither texture nor buffer - { - Internal.Refactor.ThrowNotImplementedException("UnmapSubresource not implemented for type " + unmapped.Resource.GetType()); - } - } - } - - private MappedResource MapTexture(Texture texture, bool adjustOffsetForSubresource, BufferTarget bufferTarget, int pixelBufferObjectId, int subResourceIndex, MapMode mapMode, int offsetInBytes, int lengthInBytes) - { - int mipLevel = subResourceIndex % texture.MipLevels; - - GL.BindBuffer(bufferTarget, pixelBufferObjectId); - var mapResult = GL.MapBufferRange(bufferTarget, (IntPtr)offsetInBytes + (adjustOffsetForSubresource ? texture.ComputeBufferOffset(subResourceIndex, 0) : 0), (IntPtr)lengthInBytes, mapMode.ToOpenGLMask()); - GL.BindBuffer(bufferTarget, 0); - - return new MappedResource(texture, subResourceIndex, new DataBox { DataPointer = mapResult, SlicePitch = texture.ComputeSlicePitch(mipLevel), RowPitch = texture.ComputeRowPitch(mipLevel) }, offsetInBytes, lengthInBytes) - { - PixelBufferObjectId = pixelBufferObjectId, - }; - } - - internal unsafe void PreDraw() - { -#if XENKO_PLATFORM_ANDROID - // Device with no background loading context: check if some loading is pending - if (GraphicsDevice.AsyncPendingTaskWaiting) - GraphicsDevice.ExecutePendingTasks(); -#endif - // Bind program - var program = newPipelineState.EffectProgram.ProgramId; - if (program != boundProgram) - { - boundProgram = program; - GL.UseProgram(boundProgram); - } - - int vertexBufferSlot = -1; - var vertexBufferView = default(VertexBufferView); - Buffer vertexBuffer = null; - var vertexBufferBase = IntPtr.Zero; - - // TODO OPENGL compare newPipelineState.VertexAttribs directly - if (newPipelineState.VertexAttribs != currentPipelineState.VertexAttribs) - { - vboDirty = true; - } - - // Setup vertex buffers and vertex attributes - if (vboDirty) - { - foreach (var vertexAttrib in newPipelineState.VertexAttribs) - { - if (vertexAttrib.VertexBufferSlot != vertexBufferSlot) - { - vertexBufferSlot = vertexAttrib.VertexBufferSlot; - vertexBufferView = vertexBuffers[vertexBufferSlot]; - vertexBuffer = vertexBufferView.Buffer; - if (vertexBuffer != null) - { - var vertexBufferResource = vertexBufferView.Buffer.BufferId; - GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferResource); - - vertexBufferBase = vertexBufferView.Buffer.StagingData; - } - } - - var vertexAttribMask = 1U << vertexAttrib.AttributeIndex; - - // A stride of zero causes automatic stride calculation. To not use the attribute, unbind it in that case - if (vertexBuffer == null || vertexBufferView.Stride == 0) - { - // No VB bound, turn off this attribute - if ((enabledVertexAttribArrays & vertexAttribMask) != 0) - { - enabledVertexAttribArrays &= ~vertexAttribMask; - GL.DisableVertexAttribArray(vertexAttrib.AttributeIndex); - } - continue; - } - - // Enable this attribute if not previously enabled - if ((enabledVertexAttribArrays & vertexAttribMask) == 0) - { - enabledVertexAttribArrays |= vertexAttribMask; - GL.EnableVertexAttribArray(vertexAttrib.AttributeIndex); - } - -#if !XENKO_GRAPHICS_API_OPENGLES - if (vertexAttrib.IsInteger && !vertexAttrib.Normalized) - GL.VertexAttribIPointer(vertexAttrib.AttributeIndex, vertexAttrib.Size, (VertexAttribIntegerType)vertexAttrib.Type, vertexBufferView.Stride, vertexBufferBase + vertexBufferView.Offset + vertexAttrib.Offset); - else -#endif - GL.VertexAttribPointer(vertexAttrib.AttributeIndex, vertexAttrib.Size, vertexAttrib.Type, vertexAttrib.Normalized, vertexBufferView.Stride, vertexBufferBase + vertexBufferView.Offset + vertexAttrib.Offset); - } - - vboDirty = false; - } - - // Resources - newPipelineState.ResourceBinder.BindResources(this, currentDescriptorSets); - - // States - newPipelineState.Apply(this, currentPipelineState); - - foreach (var textureInfo in newPipelineState.EffectProgram.Textures) - { - var boundTexture = boundShaderResourceViews[textureInfo.TextureUnit]; - var shaderResourceView = shaderResourceViews[textureInfo.TextureUnit]; - if (shaderResourceView != null) - { - var texture = shaderResourceView as Texture; - var boundSamplerState = texture?.BoundSamplerState ?? GraphicsDevice.DefaultSamplerState; - var samplerState = samplerStates[textureInfo.TextureUnit] ?? GraphicsDevice.SamplerStates.LinearClamp; - - bool textureChanged = shaderResourceView != boundTexture; - bool samplerStateChanged = texture != null && samplerState != boundSamplerState; - - if (textureChanged || samplerStateChanged) - { - if (activeTexture != textureInfo.TextureUnit) - { - activeTexture = textureInfo.TextureUnit; - GL.ActiveTexture(TextureUnit.Texture0 + textureInfo.TextureUnit); - } - - // Lazy update for texture - if (textureChanged) - { - boundShaderResourceViews[textureInfo.TextureUnit] = shaderResourceView; - GL.BindTexture(shaderResourceView.TextureTarget, shaderResourceView.TextureId); - } - - // Lazy update for sampler state - if (samplerStateChanged && texture != null) - { - // TODO: Include hasMipmap in samplerStateChanged - bool hasMipmap = texture.Description.MipLevels > 1; - - samplerState.Apply(hasMipmap, boundSamplerState, texture.TextureTarget); - texture.BoundSamplerState = samplerState; - } - } - } - } - - // Update viewports - SetViewportImpl(); - -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - { - fixed(byte* boundUniforms = newPipelineState.EffectProgram.BoundUniforms) - { - foreach (var uniform in newPipelineState.EffectProgram.Uniforms) - { - var constantBuffer = constantBuffers[uniform.ConstantBufferSlot]; - if (constantBuffer == null) - continue; - - var constantBufferOffsetStart = newPipelineState.EffectProgram.ConstantBufferOffsets[uniform.ConstantBufferSlot]; - - var constantBufferData = constantBuffer.StagingData; - var firstUniformIndex = uniform.UniformIndex; - var lastUniformIndex = firstUniformIndex + uniform.Count; - var offset = uniform.Offset; - var boundData = (IntPtr)boundUniforms + offset + constantBufferOffsetStart; - var currentData = constantBufferData + offset; - - // Already updated? Early exit. - // TODO: Not optimal for float1/float2 arrays (rare?) - // Better to do "sparse" comparison, not sure if C# code would behave well though - if (Xenko.Core.Utilities.CompareMemory(boundData, currentData, uniform.CompareSize)) - continue; - - // Update bound cache for early exit - Xenko.Core.Utilities.CopyMemory(boundData, currentData, uniform.CompareSize); - - switch (uniform.Type) - { - case ActiveUniformType.Float: - for (int uniformIndex = firstUniformIndex; uniformIndex < lastUniformIndex; ++uniformIndex) - { - GL.Uniform1(uniformIndex, 1, (float*)currentData); - currentData += 16; // Each array element is spaced by 16 bytes - } - break; - case ActiveUniformType.FloatVec2: - for (int uniformIndex = firstUniformIndex; uniformIndex < lastUniformIndex; ++uniformIndex) - { - GL.Uniform2(uniformIndex, 1, (float*)currentData); - currentData += 16; // Each array element is spaced by 16 bytes - } - break; - case ActiveUniformType.FloatVec3: - for (int uniformIndex = firstUniformIndex; uniformIndex < lastUniformIndex; ++uniformIndex) - { - GL.Uniform3(uniformIndex, 1, (float*)currentData); - currentData += 16; // Each array element is spaced by 16 bytes - } - break; - case ActiveUniformType.FloatVec4: - GL.Uniform4(firstUniformIndex, uniform.Count, (float*)currentData); - break; - case ActiveUniformType.FloatMat4: - GL.UniformMatrix4(uniform.UniformIndex, uniform.Count, false, (float*)currentData); - break; - case ActiveUniformType.Bool: - case ActiveUniformType.Int: - for (int uniformIndex = firstUniformIndex; uniformIndex < lastUniformIndex; ++uniformIndex) - { - GL.Uniform1(uniformIndex, 1, (int*)currentData); - currentData += 16; // Each array element is spaced by 16 bytes - } - break; - case ActiveUniformType.BoolVec2: - case ActiveUniformType.IntVec2: - for (int uniformIndex = firstUniformIndex; uniformIndex < lastUniformIndex; ++uniformIndex) - { - GL.Uniform2(uniformIndex, 1, (int*)currentData); - currentData += 16; // Each array element is spaced by 16 bytes - } - break; - case ActiveUniformType.BoolVec3: - case ActiveUniformType.IntVec3: - for (int uniformIndex = firstUniformIndex; uniformIndex < lastUniformIndex; ++uniformIndex) - { - GL.Uniform3(uniformIndex, 1, (int*)currentData); - currentData += 16; // Each array element is spaced by 16 bytes - } - break; - case ActiveUniformType.BoolVec4: - case ActiveUniformType.IntVec4: - GL.Uniform4(firstUniformIndex, uniform.Count, (int*)currentData); - break; - default: - Internal.Refactor.ThrowNotImplementedException(); - break; - } - } - } - } -#endif - - currentPipelineState = newPipelineState; - } - - /// - /// Sets a constant buffer to the shader pipeline. - /// - /// The shader stage. - /// The binding slot. - /// The constant buffer to set. - internal void SetConstantBuffer(ShaderStage stage, int slot, Buffer buffer) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - if (constantBuffers[slot] != buffer) - { - // TODO OPENGL if OpenGL ES 2, might be good to have some dirty flags to explain if cbuffer changed - constantBuffers[slot] = buffer; - GL.BindBufferBase(BufferRangeTarget.UniformBuffer, slot, buffer != null ? buffer.BufferId : 0); - } - } - - private void SetRenderTargetsImpl(Texture depthStencilBuffer, int renderTargetCount, params Texture[] renderTargets) - { - if (renderTargetCount > 0) - { - // ensure size is coherent - var expectedWidth = renderTargets[0].Width; - var expectedHeight = renderTargets[0].Height; - if (depthStencilBuffer != null) - { - if (expectedWidth != depthStencilBuffer.Width || expectedHeight != depthStencilBuffer.Height) - throw new Exception("Depth buffer is not the same size as the render target"); - } - for (int i = 1; i < renderTargetCount; ++i) - { - if (renderTargets[i] != null && (expectedWidth != renderTargets[i].Width || expectedHeight != renderTargets[i].Height)) - throw new Exception("Render targets do not have the same size"); - } - } - -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - boundRenderTargetCount = renderTargetCount; - for (int i = 0; i < renderTargetCount; ++i) - boundRenderTargets[i] = renderTargets[i]; - - boundDepthStencilBuffer = depthStencilBuffer; - - needUpdateFBO = true; - - SetupTargets(); - } - - private void ResetTargetsImpl() - { - boundRenderTargetCount = 0; - } - - /// - /// Sets a sampler state to the shader pipeline. - /// - /// The shader stage. - /// The binding slot. - /// The sampler state to set. - public void SetSamplerState(ShaderStage stage, int slot, SamplerState samplerState) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - samplerStates[slot] = samplerState; - } - - unsafe partial void SetScissorRectangleImpl(ref Rectangle scissorRectangle) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - GL.Scissor(scissorRectangle.Left, scissorRectangle.Top, scissorRectangle.Width, scissorRectangle.Height); - } - - unsafe partial void SetScissorRectanglesImpl(int scissorCount, Rectangle[] scissorRectangles) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - Internal.Refactor.ThrowNotImplementedException(); -#else - for (int i = 0; i < scissorCount; ++i) - { - nativeScissorRectangles[4 * i] = scissorRectangles[i].X; - nativeScissorRectangles[4 * i + 1] = scissorRectangles[i].Y; - nativeScissorRectangles[4 * i + 2] = scissorRectangles[i].Width; - nativeScissorRectangles[4 * i + 3] = scissorRectangles[i].Height; - } - - GL.ScissorArray(0, scissorCount, nativeScissorRectangles); -#endif - } - - /// - /// Sets a shader resource view to the shader pipeline. - /// - /// The shader stage. - /// The binding slot. - /// The shader resource view. - internal void SetShaderResourceView(ShaderStage stage, int slot, GraphicsResource shaderResourceView) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - shaderResourceViews[slot] = shaderResourceView; - } - - /// - public void SetStreamTargets(params Buffer[] buffers) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - Internal.Refactor.ThrowNotImplementedException(); - } - - /// - /// Sets an unordered access view to the shader pipeline. - /// - /// The stage. - /// The slot. - /// The unordered access view. - /// The Append/Consume buffer offset. A value of -1 indicates the current offset - /// should be kept. Any other values set the hidden counter for that Appendable/Consumable - /// UAV. uavInitialCount is only relevant for UAVs which have the 'Append' or 'Counter' buffer - /// flag, otherwise the argument is ignored. - /// Invalid stage.;stage - internal void SetUnorderedAccessView(ShaderStage stage, int slot, GraphicsResource unorderedAccessView, int uavInitialOffset) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - if (stage != ShaderStage.Compute) - throw new ArgumentException("Invalid stage.", nameof(stage)); - - Internal.Refactor.ThrowNotImplementedException(); - } - - /// - /// Unsets an unordered access view from the shader pipeline. - /// - /// The unordered access view. - internal void UnsetUnorderedAccessView(GraphicsResource unorderedAccessView) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - //Internal.Refactor.ThrowNotImplementedException(); - } - - internal void SetupTargets() - { - if (needUpdateFBO) - { - boundFBO = GraphicsDevice.FindOrCreateFBO(boundDepthStencilBuffer, boundRenderTargets, boundRenderTargetCount); - } - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - } - - public void SetPipelineState(PipelineState pipelineState) - { - newPipelineState = pipelineState ?? GraphicsDevice.DefaultPipelineState; - } - - public void SetVertexBuffer(int index, Buffer buffer, int offset, int stride) - { - var newVertexBuffer = new VertexBufferView(buffer, offset, stride); - if (vertexBuffers[index] != newVertexBuffer) - { - vboDirty = true; - vertexBuffers[index] = newVertexBuffer; - } - } - - public void SetIndexBuffer(Buffer buffer, int offset, bool is32bits) - { - var newIndexBuffer = new IndexBufferView(buffer, offset, is32bits); - if (indexBuffer != newIndexBuffer) - { - // Setup index buffer - indexBuffer = newIndexBuffer; - - // Setup index buffer - GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBuffer.Buffer != null ? indexBuffer.Buffer.BufferId : 0); - } - } - - public void ResourceBarrierTransition(GraphicsResource resource, GraphicsResourceState newState) - { - // Nothing to do - } - - public void SetDescriptorSets(int index, DescriptorSet[] descriptorSets) - { - for (int i = 0; i < descriptorSets.Length; ++i) - { - currentDescriptorSets[index++] = descriptorSets[i]; - } - } - - public void SetStencilReference(int stencilReference) - { - NewStencilReference = stencilReference; - } - - public void SetBlendFactor(Color4 blendFactor) - { - NewBlendFactor = blendFactor; - } - - private void SetViewportImpl() - { - if (!viewportDirty) - return; - - viewportDirty = false; - -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - // TODO: Check all non-empty viewports are identical and match what is active in FBO! - UpdateViewport(viewports[0]); -#else - UpdateViewports(); -#endif - } - - private void UpdateViewport(Viewport viewport) - { - GL.DepthRange(viewport.MinDepth, viewport.MaxDepth); - GL.Viewport((int)viewport.X, (int)viewport.Y, (int)viewport.Width, (int)viewport.Height); - } - -#if !XENKO_GRAPHICS_API_OPENGLES - private void UpdateViewports() - { - int nbViewports = viewports.Length; - for (int i = 0; i < boundViewportCount; ++i) - { - var currViewport = viewports[i]; - nativeViewports[4 * i] = currViewport.X; - nativeViewports[4 * i + 1] = currViewport.Y; - nativeViewports[4 * i + 2] = currViewport.Width; - nativeViewports[4 * i + 3] = currViewport.Height; - } - GL.DepthRange(viewports[0].MinDepth, viewports[0].MaxDepth); - GL.ViewportArray(0, boundViewportCount, nativeViewports); - } -#endif - - public void UnsetReadWriteBuffers() - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - } - - public void UnsetRenderTargets() - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - - SetRenderTargets(null, null); - } - - internal void UpdateSubresource(GraphicsResource resource, int subResourceIndex, DataBox databox) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - var buffer = resource as Buffer; - if (buffer != null) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (buffer.StagingData != IntPtr.Zero) - { - // Specific case for constant buffers - Xenko.Core.Utilities.CopyMemory(buffer.StagingData, databox.DataPointer, buffer.Description.SizeInBytes); - return; - } -#endif - - //UnbindVertexArrayObject(); - - if (!GraphicsDevice.HasTextureBuffers && buffer.BufferId == 0) - { - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - // On platforms where it's not supported, we use a texture instead of a buffer - GL.BindTexture(buffer.TextureTarget, buffer.TextureId); - boundShaderResourceViews[0] = null; // bound active texture 0 has changed - - buffer.UpdateTextureSubresource(databox.DataPointer, 0, 0, buffer.ElementCount); - } - else - { - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - GL.BufferData(buffer.BufferTarget, buffer.Description.SizeInBytes, databox.DataPointer, buffer.BufferUsageHint); - } - } - else - { - var texture = resource as Texture; - if (texture != null) - { - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - // TODO: Handle pitchs - // TODO: handle other texture formats - GL.BindTexture(texture.TextureTarget, texture.TextureId); - boundShaderResourceViews[0] = null; // bound active texture 0 has changed - - var desc = texture.Description; - var mipLevel = subResourceIndex % texture.MipLevels; - var arraySlice = subResourceIndex / texture.MipLevels; - switch (texture.TextureTarget) - { -#if !XENKO_GRAPHICS_API_OPENGLES - case TextureTarget.Texture1D: - GL.TexSubImage1D(TextureTarget.Texture1D, mipLevel, 0, desc.Width, texture.TextureFormat, texture.TextureType, databox.DataPointer); - break; -#endif - case TextureTarget.Texture2D: - GL.TexSubImage2D(TextureTarget2d.Texture2D, mipLevel, 0, 0, desc.Width, desc.Height, texture.TextureFormat, texture.TextureType, databox.DataPointer); - break; - case TextureTarget.Texture2DArray: - GL.TexSubImage3D(TextureTarget3d.Texture2DArray, mipLevel, 0, 0, arraySlice, desc.Width, desc.Height, 1, texture.TextureFormat, texture.TextureType, databox.DataPointer); - break; - case TextureTarget.Texture3D: - GL.TexSubImage3D(TextureTarget3d.Texture3D, mipLevel, 0, 0, 0, desc.Width, desc.Height, desc.Depth, texture.TextureFormat, texture.TextureType, databox.DataPointer); - break; - case TextureTarget.TextureCubeMap: - GL.TexSubImage2D(Texture.GetTextureTargetForDataSet2D(texture.TextureTarget, arraySlice), mipLevel, 0, 0, desc.Width, desc.Height, texture.TextureFormat, texture.TextureType, databox.DataPointer); - break; - default: - Internal.Refactor.ThrowNotImplementedException("UpdateSubresource not implemented for texture target " + texture.TextureTarget); - break; - } - } - else // neither texture nor buffer - { - Internal.Refactor.ThrowNotImplementedException("UpdateSubresource not implemented for type " + resource.GetType()); - } - } - } - - internal void UpdateSubresource(GraphicsResource resource, int subResourceIndex, DataBox databox, ResourceRegion region) - { -#if DEBUG - GraphicsDevice.EnsureContextActive(); -#endif - var texture = resource as Texture; - - if (texture != null) - { - var width = region.Right - region.Left; - var height = region.Bottom - region.Top; - var depth = region.Back - region.Front; - - var expectedRowPitch = width * texture.TexturePixelSize; - - // determine the opengl read Unpack Alignment - var packAlignment = 0; - if ((databox.RowPitch & 1) != 0) - { - if (databox.RowPitch == expectedRowPitch) - packAlignment = 1; - } - else if ((databox.RowPitch & 2) != 0) - { - var diff = databox.RowPitch - expectedRowPitch; - if (diff >= 0 && diff < 2) - packAlignment = 2; - } - else if ((databox.RowPitch & 4) != 0) - { - var diff = databox.RowPitch - expectedRowPitch; - if (diff >= 0 && diff < 4) - packAlignment = 4; - } - else if ((databox.RowPitch & 8) != 0) - { - var diff = databox.RowPitch - expectedRowPitch; - if (diff >= 0 && diff < 8) - packAlignment = 8; - } - else if (databox.RowPitch == expectedRowPitch) - { - packAlignment = 4; - } - if (packAlignment == 0) - Internal.Refactor.ThrowNotImplementedException("The data box RowPitch is not compatible with the region width. This requires additional copy to be implemented."); - - // change the Unpack Alignment - int previousPackAlignment; - GL.GetInteger(GetPName.UnpackAlignment, out previousPackAlignment); - GL.PixelStore(PixelStoreParameter.UnpackAlignment, packAlignment); - - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - // Update the texture region - GL.BindTexture(texture.TextureTarget, texture.TextureId); - if (texture.Dimension == TextureDimension.Texture3D) - GL.TexSubImage3D((TextureTarget3d)texture.TextureTarget, subResourceIndex, region.Left, region.Top, region.Front, width, height, depth, texture.TextureFormat, texture.TextureType, databox.DataPointer); - else - GL.TexSubImage2D((TextureTarget2d)texture.TextureTarget, subResourceIndex, region.Left, region.Top, width, height, texture.TextureFormat, texture.TextureType, databox.DataPointer); - boundShaderResourceViews[0] = null; // bound active texture 0 has changed - - // reset the Unpack Alignment - GL.PixelStore(PixelStoreParameter.UnpackAlignment, previousPackAlignment); - } - else - { - var buffer = resource as Buffer; - if (buffer != null) - { - if (!GraphicsDevice.HasTextureBuffers && buffer.BufferId == 0) - { - if (activeTexture != 0) - { - activeTexture = 0; - GL.ActiveTexture(TextureUnit.Texture0); - } - - // On platforms where it's not supported, we use a texture instead of a buffer - GL.BindTexture(buffer.TextureTarget, buffer.TextureId); - boundShaderResourceViews[0] = null; // bound active texture 0 has changed - - buffer.UpdateTextureSubresource(databox.DataPointer, 0, region.Left, region.Right - region.Left); - } - else - { - GL.BindBuffer(buffer.BufferTarget, buffer.BufferId); - if (region.Left == 0 && region.Right == buffer.SizeInBytes) - GL.BufferData(buffer.BufferTarget, (IntPtr)region.Right, databox.DataPointer, buffer.BufferUsageHint); - else - GL.BufferSubData(buffer.BufferTarget, (IntPtr)region.Left, (IntPtr)(region.Right - region.Left), databox.DataPointer); - GL.BindBuffer(buffer.BufferTarget, 0); - } - } - } - } - - struct VertexBufferView - { - public readonly Buffer Buffer; - public readonly int Offset; - public readonly int Stride; - - public VertexBufferView(Buffer buffer, int offset, int stride) - { - Buffer = buffer; - Offset = offset; - Stride = stride; - } - - public static bool operator ==(VertexBufferView left, VertexBufferView right) - { - return Equals(left.Buffer, right.Buffer) && left.Offset == right.Offset && left.Stride == right.Stride; - } - - public static bool operator !=(VertexBufferView left, VertexBufferView right) - { - return !(left == right); - } - - public override bool Equals(object other) - { - if (other is VertexBufferView) - { - VertexBufferView p = (VertexBufferView) other; - return Equals(Buffer, p.Buffer) && Offset == p.Offset && Stride == p.Stride; - } - else - { - return false; - } - } - - public override int GetHashCode() - { - int result = Buffer.GetHashCode(); - result = (result * 397) ^ Offset; - result = (result * 397) ^ Stride; - return result; - } - } - - struct IndexBufferView - { - public readonly Buffer Buffer; - public readonly int Offset; - public readonly DrawElementsType Type; - public readonly int ElementSize; - - public IndexBufferView(Buffer buffer, int offset, bool is32Bits) - { - Buffer = buffer; - Offset = offset; - Type = is32Bits ? DrawElementsType.UnsignedInt : DrawElementsType.UnsignedShort; - ElementSize = is32Bits ? 4 : 2; - } - - public static bool operator ==(IndexBufferView left, IndexBufferView right) - { - return Equals(left.Buffer, right.Buffer) && left.Offset == right.Offset && left.Type == right.Type && left.ElementSize == right.ElementSize; - } - - public static bool operator !=(IndexBufferView left, IndexBufferView right) - { - return !(left == right); - } - - public override bool Equals(object other) - { - if (other is IndexBufferView) - { - IndexBufferView p = (IndexBufferView)other; - return Equals(Buffer, p.Buffer) && Offset == p.Offset && Type == p.Type && ElementSize == p.ElementSize; - } - else - { - return false; - } - } - - public override int GetHashCode() - { - int result = Buffer.GetHashCode(); - result = (result * 397) ^ Offset; - result = (result * 397) ^ Type.GetHashCode(); - result = (result * 397) ^ ElementSize; - return result; - } - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/DepthStencilState.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/DepthStencilState.OpenGL.cs deleted file mode 100644 index 8822df3a4f..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/DepthStencilState.OpenGL.cs +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - struct DepthStencilBoundState - { - // Depth - public bool DepthBufferEnable; - public bool DepthBufferWriteEnable; - public DepthFunction DepthFunction; - - // Stencil - public bool StencilEnable; - public byte StencilWriteMask; - public byte StencilMask; - - public StencilFaceState Faces; - } - - struct StencilFaceState - { - public StencilFunction FrontFaceStencilFunction; - public StencilOp FrontFaceDepthFailOp; - public StencilOp FrontFaceFailOp; - public StencilOp FrontFacePassOp; - - public StencilFunction BackFaceStencilFunction; - public StencilOp BackFaceDepthFailOp; - public StencilOp BackFaceFailOp; - public StencilOp BackFacePassOp; - - public bool Equals(StencilFaceState other) - { - return FrontFaceStencilFunction == other.FrontFaceStencilFunction && FrontFaceDepthFailOp == other.FrontFaceDepthFailOp && FrontFaceFailOp == other.FrontFaceFailOp && FrontFacePassOp == other.FrontFacePassOp && BackFaceStencilFunction == other.BackFaceStencilFunction && BackFaceDepthFailOp == other.BackFaceDepthFailOp && BackFaceFailOp == other.BackFaceFailOp && BackFacePassOp == other.BackFacePassOp; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is StencilFaceState && Equals((StencilFaceState)obj); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (int)FrontFaceStencilFunction; - hashCode = (hashCode * 397) ^ (int)FrontFaceDepthFailOp; - hashCode = (hashCode * 397) ^ (int)FrontFaceFailOp; - hashCode = (hashCode * 397) ^ (int)FrontFacePassOp; - hashCode = (hashCode * 397) ^ (int)BackFaceStencilFunction; - hashCode = (hashCode * 397) ^ (int)BackFaceDepthFailOp; - hashCode = (hashCode * 397) ^ (int)BackFaceFailOp; - hashCode = (hashCode * 397) ^ (int)BackFacePassOp; - return hashCode; - } - } - - public static bool operator ==(StencilFaceState left, StencilFaceState right) - { - return left.Equals(right); - } - - public static bool operator !=(StencilFaceState left, StencilFaceState right) - { - return !left.Equals(right); - } - } - - public class DepthStencilState - { - DepthStencilBoundState state; - - internal DepthStencilState(DepthStencilStateDescription depthStencilStateDescription, bool hasDepthStencilBuffer) - { - state.DepthBufferEnable = depthStencilStateDescription.DepthBufferEnable; - state.DepthBufferWriteEnable = depthStencilStateDescription.DepthBufferWriteEnable && hasDepthStencilBuffer; - - state.StencilEnable = depthStencilStateDescription.StencilEnable; - state.StencilMask = depthStencilStateDescription.StencilMask; - state.StencilWriteMask = depthStencilStateDescription.StencilWriteMask; - - state.DepthFunction = depthStencilStateDescription.DepthBufferFunction.ToOpenGLDepthFunction(); - - state.Faces.FrontFaceStencilFunction = depthStencilStateDescription.FrontFace.StencilFunction.ToOpenGLStencilFunction(); - state.Faces.FrontFaceDepthFailOp = depthStencilStateDescription.FrontFace.StencilDepthBufferFail.ToOpenGL(); - state.Faces.FrontFaceFailOp = depthStencilStateDescription.FrontFace.StencilFail.ToOpenGL(); - state.Faces.FrontFacePassOp = depthStencilStateDescription.FrontFace.StencilPass.ToOpenGL(); - - state.Faces.BackFaceStencilFunction = depthStencilStateDescription.BackFace.StencilFunction.ToOpenGLStencilFunction(); - state.Faces.BackFaceDepthFailOp = depthStencilStateDescription.BackFace.StencilDepthBufferFail.ToOpenGL(); - state.Faces.BackFaceFailOp = depthStencilStateDescription.BackFace.StencilFail.ToOpenGL(); - state.Faces.BackFacePassOp = depthStencilStateDescription.BackFace.StencilPass.ToOpenGL(); - } - - public void Apply(CommandList commandList) - { - if (commandList.DepthStencilBoundState.DepthBufferEnable != state.DepthBufferEnable) - { - commandList.DepthStencilBoundState.DepthBufferEnable = state.DepthBufferEnable; - - if (state.DepthBufferEnable) - GL.Enable(EnableCap.DepthTest); - else - GL.Disable(EnableCap.DepthTest); - } - - if (state.DepthBufferEnable && commandList.DepthStencilBoundState.DepthFunction != state.DepthFunction) - { - commandList.DepthStencilBoundState.DepthFunction = state.DepthFunction; - GL.DepthFunc(state.DepthFunction); - } - - if (commandList.DepthStencilBoundState.DepthBufferWriteEnable != state.DepthBufferWriteEnable) - { - commandList.DepthStencilBoundState.DepthBufferWriteEnable = state.DepthBufferWriteEnable; - GL.DepthMask(state.DepthBufferWriteEnable); - } - - if (commandList.DepthStencilBoundState.StencilEnable != state.StencilEnable) - { - commandList.DepthStencilBoundState.StencilEnable = state.StencilEnable; - - if (state.StencilEnable) - GL.Enable(EnableCap.StencilTest); - else - GL.Disable(EnableCap.StencilTest); - } - - if (state.StencilEnable && commandList.DepthStencilBoundState.StencilWriteMask != state.StencilWriteMask) - { - commandList.DepthStencilBoundState.StencilWriteMask = state.StencilWriteMask; - GL.StencilMask(state.StencilWriteMask); - } - - // TODO: Properly handle stencil reference - if (state.StencilEnable && (commandList.DepthStencilBoundState.Faces != state.Faces || commandList.NewStencilReference != commandList.BoundStencilReference)) - { - commandList.DepthStencilBoundState.Faces = state.Faces; - commandList.BoundStencilReference = commandList.NewStencilReference; - - GL.StencilFuncSeparate(StencilFace.Front, state.Faces.FrontFaceStencilFunction, commandList.BoundStencilReference, state.StencilWriteMask); // set both faces - GL.StencilFuncSeparate(StencilFace.Back, state.Faces.BackFaceStencilFunction, commandList.BoundStencilReference, state.StencilWriteMask); // override back face - GL.StencilOpSeparate(StencilFace.Front, state.Faces.FrontFaceDepthFailOp, state.Faces.FrontFaceFailOp, state.Faces.FrontFacePassOp); - GL.StencilOpSeparate(StencilFace.Back, state.Faces.BackFaceDepthFailOp, state.Faces.BackFaceFailOp, state.Faces.BackFacePassOp); - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/EffectProgram.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/EffectProgram.OpenGL.cs deleted file mode 100644 index 68a5e99100..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/EffectProgram.OpenGL.cs +++ /dev/null @@ -1,1043 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using OpenTK.Graphics; -using Xenko.Core; -using Xenko.Core.Collections; -using Xenko.Core.Diagnostics; -using Xenko.Core.Extensions; -using Xenko.Core.Serialization; -using Xenko.Shaders; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - - -namespace Xenko.Graphics -{ - class EffectProgram : GraphicsResourceBase - { -#if XENKO_GRAPHICS_API_OPENGLES - // The ProgramParameter.ActiveUniformBlocks enum is not defined in OpenTK for OpenGL ES - private const GetProgramParameterName XkActiveUniformBlocks = (GetProgramParameterName)0x8A36; - private const ActiveUniformType FloatMat3x2 = (ActiveUniformType)0x8B67; -#else - private const GetProgramParameterName XkActiveUniformBlocks = GetProgramParameterName.ActiveUniformBlocks; - private const ActiveUniformType FloatMat3x2 = ActiveUniformType.FloatMat3x2; -#endif - - internal int ProgramId; - - const string VertexShaderDepthClamp = @" -out float _edc_z; -void main() -{ - _edc_main(); - - // transform z to window coordinates - _edc_z = gl_Position.z / gl_Position.w; - _edc_z = (gl_DepthRange.diff * _edc_z + gl_DepthRange.near + gl_DepthRange.far) * 0.5; - - // prevent z-clipping - gl_Position.z = clamp(_edc_z, 0.0, 1.0); -} -"; - - const string FragmentShaderDepthClamp = @" -in float _edc_z; -void main() -{ - gl_FragDepth = clamp(_edc_z, 0.0, 1.0); - - _edc_main(); -} -"; - - private readonly LoggerResult reflectionResult = new LoggerResult(); - - private readonly EffectBytecode effectBytecode; - - public Dictionary Attributes { get; } = new Dictionary(); - -#if XENKO_GRAPHICS_API_OPENGLES - // Fake cbuffer emulation binding - internal struct Uniform - { - public ActiveUniformType Type; - public int UniformIndex; - public int ConstantBufferSlot; - public int Offset; - public int Count; - public int CompareSize; - } - - // Start offsets for cbuffer - private static readonly int[] EmptyConstantBufferOffsets = { 0 }; - internal int[] ConstantBufferOffsets = EmptyConstantBufferOffsets; - - internal byte[] BoundUniforms; - internal List Uniforms = new List(); -#endif - - internal struct Texture - { - public int TextureUnit; - - public Texture(int textureUnit) - { - TextureUnit = textureUnit; - } - } - - internal EffectReflection Reflection; - - internal List Textures = new List(); - - private readonly bool emulateDepthClamp; - - internal EffectProgram(GraphicsDevice device, EffectBytecode bytecode, bool emulateDepthClamp) : base(device) - { - effectBytecode = bytecode; - this.emulateDepthClamp = emulateDepthClamp; - - // TODO OPENGL currently we modify the reflection info; need to find a better way to deal with that - Reflection = effectBytecode.Reflection; - CreateShaders(); - } - - protected internal override void OnDestroyed() - { - using (GraphicsDevice.UseOpenGLCreationContext()) - { - GL.DeleteProgram(ProgramId); - } - - ProgramId = 0; - - base.OnDestroyed(); - } - - private void CreateShaders() - { - using (GraphicsDevice.UseOpenGLCreationContext()) - { - ProgramId = GL.CreateProgram(); - - // Attach shaders - foreach (var shader in effectBytecode.Stages) - { - ShaderType shaderStage; - switch (shader.Stage) - { - case ShaderStage.Vertex: - shaderStage = ShaderType.VertexShader; - break; - case ShaderStage.Pixel: - shaderStage = ShaderType.FragmentShader; - break; - default: - throw new Exception("Unsupported shader stage"); - } - -#if XENKO_GRAPHICS_API_OPENGLES - var shaderSources = BinarySerialization.Read(shader.Data); - var shaderSource = GraphicsDevice.IsOpenGLES2 ? shaderSources.DataES2 : shaderSources.DataES3; -#else - var shaderSource = shader.GetDataAsString(); -#endif - //edit the source a little to emulateDepthClamp - if (emulateDepthClamp) - { - var mainPattern = new Regex(@"void\s+main\s*\(\)"); - if (shaderStage == ShaderType.VertexShader) - { - //bypass our regular main - shaderSource = mainPattern.Replace(shaderSource, @"void _edc_main()"); - shaderSource += VertexShaderDepthClamp; - } - else if (shaderStage == ShaderType.FragmentShader) - { - //bypass our regular main - shaderSource = mainPattern.Replace(shaderSource, @"void _edc_main()"); - shaderSource += FragmentShaderDepthClamp; - } - } - - // On OpenGL ES 3.1 and before, texture buffers are likely not supported so we have a fallback using textures - shaderSource = shaderSource.Replace("#define texelFetchBufferPlaceholder", - GraphicsDevice.HasTextureBuffers - ? "#define texelFetchBuffer(sampler, P) texelFetch(sampler, P)" - : ("#define samplerBuffer sampler2D\n" - + "#define isamplerBuffer isampler2D\n" - + "#define usamplerBuffer usampler2D\n" - + "#define texelFetchBuffer(sampler, P) texelFetch(sampler, ivec2((P) & 0xFFF, (P) >> 12), 0)\n")); - - var shaderId = GL.CreateShader(shaderStage); - GL.ShaderSource(shaderId, shaderSource); - GL.CompileShader(shaderId); - - int compileStatus; - GL.GetShader(shaderId, ShaderParameter.CompileStatus, out compileStatus); - if (compileStatus != 1) - { - var glErrorMessage = GL.GetShaderInfoLog(shaderId); - throw new InvalidOperationException("Error while compiling GLSL shader. [{0}]".ToFormat(glErrorMessage)); - } - - GL.AttachShader(ProgramId, shaderId); - } - -#if !XENKO_GRAPHICS_API_OPENGLES - // Mark program as retrievable (necessary for later GL.GetProgramBinary). - GL.ProgramParameter(ProgramId, ProgramParameterName.ProgramBinaryRetrievableHint, 1); -#endif - - // Link OpenGL program - GL.LinkProgram(ProgramId); - - // Check link results - int linkStatus; - GL.GetProgram(ProgramId, GetProgramParameterName.LinkStatus, out linkStatus); - if (linkStatus != 1) - { - var infoLog = GL.GetProgramInfoLog(ProgramId); - throw new InvalidOperationException("Error while linking GLSL shaders.\n" + infoLog); - } - - if (Attributes.Count == 0) // the shader wasn't analyzed yet // TODO Is it possible? - { - // Build attributes list for shader signature - int activeAttribCount; - GL.GetProgram(ProgramId, GetProgramParameterName.ActiveAttributes, out activeAttribCount); - - for (int activeAttribIndex = 0; activeAttribIndex < activeAttribCount; ++activeAttribIndex) - { - int size; - ActiveAttribType type; - var attribName = GL.GetActiveAttrib(ProgramId, activeAttribIndex, out size, out type); - var attribIndex = GL.GetAttribLocation(ProgramId, attribName); - Attributes.Add(attribName, attribIndex); - } - } - - CreateReflection(Reflection, effectBytecode.Stages[0].Stage); // need to regenerate the Uniforms on OpenGL ES - -#if XENKO_GRAPHICS_API_OPENGLES - // Allocate a buffer that can cache all the bound parameters - BoundUniforms = new byte[ConstantBufferOffsets[ConstantBufferOffsets.Length - 1]]; -#endif - } - - // output the gathered errors - foreach (var message in reflectionResult.Messages) - Console.WriteLine(message); - if (reflectionResult.HasErrors) - throw new Exception(reflectionResult.Messages.Select(x=>x.ToString()).Aggregate((x,y)=>x+"\n"+y)); - } - - /// - protected internal override bool OnRecreate() - { - base.OnRecreate(); - CreateShaders(); - return true; - } - - /// - protected override void Destroy() - { - using (GraphicsDevice.UseOpenGLCreationContext()) - { - GL.DeleteProgram(ProgramId); - } - - ProgramId = 0; - - base.Destroy(); - } - - /// - /// Create or updates the reflection for this shader - /// - /// the reflection from the hlsl - /// the shader pipeline stage - private void CreateReflection(EffectReflection effectReflection, ShaderStage stage) - { - int currentProgram; - GL.GetInteger(GetPName.CurrentProgram, out currentProgram); - GL.UseProgram(ProgramId); - - int uniformBlockCount; - GL.GetProgram(ProgramId, XkActiveUniformBlocks, out uniformBlockCount); - - var validConstantBuffers = new bool[effectReflection.ConstantBuffers.Count]; - for (int uniformBlockIndex = 0; uniformBlockIndex < uniformBlockCount; ++uniformBlockIndex) - { - // TODO: get previous name to find te actual constant buffer in the reflexion -#if XENKO_GRAPHICS_API_OPENGLES - const int sbCapacity = 128; - int length; - var sb = new StringBuilder(sbCapacity); - GL.GetActiveUniformBlockName(ProgramId, uniformBlockIndex, sbCapacity, out length, sb); - var constantBufferName = sb.ToString(); -#else - var constantBufferName = GL.GetActiveUniformBlockName(ProgramId, uniformBlockIndex); -#endif - - var constantBufferDescriptionIndex = effectReflection.ConstantBuffers.FindIndex(x => x.Name == constantBufferName); - if (constantBufferDescriptionIndex == -1) - { - reflectionResult.Error($"Unable to find the constant buffer description [{constantBufferName}]"); - return; - } - var constantBufferIndex = effectReflection.ResourceBindings.FindIndex(x => x.RawName == constantBufferName); - if (constantBufferIndex == -1) - { - reflectionResult.Error($"Unable to find the constant buffer [{constantBufferName}]"); - return; - } - - var constantBufferDescription = effectReflection.ConstantBuffers[constantBufferDescriptionIndex]; - var constantBuffer = effectReflection.ResourceBindings[constantBufferIndex]; - - GL.GetActiveUniformBlock(ProgramId, uniformBlockIndex, ActiveUniformBlockParameter.UniformBlockDataSize, out constantBufferDescription.Size); - - int uniformCount; - GL.GetActiveUniformBlock(ProgramId, uniformBlockIndex, ActiveUniformBlockParameter.UniformBlockActiveUniforms, out uniformCount); - - // set the binding - GL.UniformBlockBinding(ProgramId, uniformBlockIndex, uniformBlockIndex); - - // Read uniforms desc - var uniformIndices = new int[uniformCount]; - var uniformOffsets = new int[uniformCount]; - var uniformTypes = new int[uniformCount]; - var uniformNames = new string[uniformCount]; - GL.GetActiveUniformBlock(ProgramId, uniformBlockIndex, ActiveUniformBlockParameter.UniformBlockActiveUniformIndices, uniformIndices); - GL.GetActiveUniforms(ProgramId, uniformIndices.Length, uniformIndices, ActiveUniformParameter.UniformOffset, uniformOffsets); - GL.GetActiveUniforms(ProgramId, uniformIndices.Length, uniformIndices, ActiveUniformParameter.UniformType, uniformTypes); - - for (int uniformIndex = 0; uniformIndex < uniformIndices.Length; ++uniformIndex) - { -#if XENKO_GRAPHICS_API_OPENGLES - int size; - ActiveUniformType aut; - GL.GetActiveUniform(ProgramId, uniformIndices[uniformIndex], sbCapacity, out length, out size, out aut, sb); - uniformNames[uniformIndex] = sb.ToString(); -#else - uniformNames[uniformIndex] = GL.GetActiveUniformName(ProgramId, uniformIndices[uniformIndex]); -#endif - } - - // Reoder by offset - var indexMapping = uniformIndices.Select((x, i) => new UniformMergeInfo { Offset = uniformOffsets[i], Type = (ActiveUniformType)uniformTypes[i], Name = uniformNames[i], NextOffset = 0 }).OrderBy(x => x.Offset).ToArray(); - indexMapping.Last().NextOffset = constantBufferDescription.Size; - - // Fill next offsets - for (int i = 1; i < indexMapping.Length; ++i) - { - indexMapping[i - 1].NextOffset = indexMapping[i].Offset; - } - - // Group arrays/structures into one variable (std140 layout is enough for offset determinism inside arrays/structures) - indexMapping = indexMapping.GroupBy(x => - { - // Use only first part of name (ignore structure/array part) - var name = x.Name; - if (name.Contains(".")) { name = name.Substring(0, name.IndexOf('.')); } - if (name.Contains("[")) { name = name.Substring(0, name.IndexOf('[')); } - return name; - }) - .Select(x => - { - var result = x.First(); - result.NextOffset = x.Last().NextOffset; - - // Check weither it's an array or a struct - int dotIndex = result.Name.IndexOf('.'); - int arrayIndex = result.Name.IndexOf('['); - - if (x.Count() > 1 && arrayIndex == -1 && dotIndex == -1) - throw new InvalidOperationException(); - - // TODO: Type processing - - result.Name = x.Key; - return result; - }).ToArray(); - - foreach (var variableIndexGroup in indexMapping) - { - var variableIndex = -1; - for (var tentativeIndex = 0; tentativeIndex < constantBufferDescription.Members.Length; ++tentativeIndex) - { - if (constantBufferDescription.Members[tentativeIndex].RawName == variableIndexGroup.Name) - { - variableIndex = tentativeIndex; - break; - } - } - - if (variableIndex == -1) - { - reflectionResult.Error($"Unable to find uniform [{variableIndexGroup.Name}] in constant buffer [{constantBufferName}]"); - continue; - } - var variable = constantBufferDescription.Members[variableIndex]; - variable.Type.Type = GetTypeFromActiveUniformType(variableIndexGroup.Type); - variable.Offset = variableIndexGroup.Offset; - variable.Size = variableIndexGroup.NextOffset - variableIndexGroup.Offset; - - constantBufferDescription.Members[variableIndex] = variable; - } - - constantBufferDescription.Type = ConstantBufferType.ConstantBuffer; - - constantBuffer.SlotCount = 1; // constant buffers are not arrays - constantBuffer.SlotStart = uniformBlockIndex; - constantBuffer.Stage = stage; - - // store the new values - validConstantBuffers[constantBufferDescriptionIndex] = true; - effectReflection.ConstantBuffers[constantBufferDescriptionIndex] = constantBufferDescription; - effectReflection.ResourceBindings[constantBufferIndex] = constantBuffer; - } -//#endif - - // Remove unecessary cbuffer and resource bindings - - // Register textures, samplers, etc... - //TODO: (?) non texture/buffer uniform outside of a block - { - // Register "NoSampler", required by HLSL=>GLSL translation to support HLSL such as texture.Load(). - var noSampler = new EffectResourceBindingDescription { KeyInfo = { KeyName = "NoSampler" }, RawName = "NoSampler", Class = EffectParameterClass.Sampler, SlotStart = -1, SlotCount = 1 }; - Reflection.ResourceBindings.Add(noSampler); - - int activeUniformCount; - GL.GetProgram(ProgramId, GetProgramParameterName.ActiveUniforms, out activeUniformCount); -#if !XENKO_GRAPHICS_API_OPENGLES - var uniformTypes = new int[activeUniformCount]; - GL.GetActiveUniforms(ProgramId, activeUniformCount, Enumerable.Range(0, activeUniformCount).ToArray(), ActiveUniformParameter.UniformType, uniformTypes); -#endif - - int textureUnitCount = 0; - - const int sbCapacity = 128; - var sb = new StringBuilder(sbCapacity); - - for (int activeUniformIndex = 0; activeUniformIndex < activeUniformCount; ++activeUniformIndex) - { -#if !XENKO_GRAPHICS_API_OPENGLES - var uniformType = (ActiveUniformType)uniformTypes[activeUniformIndex]; - var uniformName = GL.GetActiveUniformName(ProgramId, activeUniformIndex); -#else - ActiveUniformType uniformType; - int uniformCount; - int length; - GL.GetActiveUniform(ProgramId, activeUniformIndex, sbCapacity, out length, out uniformCount, out uniformType, sb); - var uniformName = sb.ToString(); - - //this is a special OpenglES case , it is declared as built in uniform, and the driver will take care of it, we just need to ignore it here - if (uniformName.StartsWith("gl_DepthRange")) - { - continue; - } -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - // Process uniforms - if (GraphicsDevice.IsOpenGLES2) - { - switch (uniformType) - { - case ActiveUniformType.Bool: - case ActiveUniformType.Int: - AddUniform(effectReflection, validConstantBuffers, sizeof(int)*1, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.BoolVec2: - case ActiveUniformType.IntVec2: - AddUniform(effectReflection, validConstantBuffers, sizeof(int)*2, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.BoolVec3: - case ActiveUniformType.IntVec3: - AddUniform(effectReflection, validConstantBuffers, sizeof(int)*3, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.BoolVec4: - case ActiveUniformType.IntVec4: - AddUniform(effectReflection, validConstantBuffers, sizeof(int)*4, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.Float: - AddUniform(effectReflection, validConstantBuffers, sizeof(float)*1, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.FloatVec2: - AddUniform(effectReflection, validConstantBuffers, sizeof(float)*2, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.FloatVec3: - AddUniform(effectReflection, validConstantBuffers, sizeof(float)*3, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.FloatVec4: - AddUniform(effectReflection, validConstantBuffers, sizeof(float)*4, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.FloatMat4: - AddUniform(effectReflection, validConstantBuffers, sizeof(float)*4*4, uniformCount, uniformName, uniformType); - break; - case ActiveUniformType.FloatMat2: - case ActiveUniformType.FloatMat3: - throw new NotImplementedException(); - } - } -#endif - - switch (uniformType) - { -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.Sampler1D: - case ActiveUniformType.Sampler1DShadow: - case ActiveUniformType.IntSampler1D: - case ActiveUniformType.UnsignedIntSampler1D: - - case ActiveUniformType.SamplerBuffer: - case ActiveUniformType.UnsignedIntSamplerBuffer: - case ActiveUniformType.IntSamplerBuffer: -#endif - case ActiveUniformType.Sampler2D: - case ActiveUniformType.Sampler2DShadow: - case ActiveUniformType.Sampler3D: // TODO: remove Texture3D that is not available in OpenGL ES 2 - case ActiveUniformType.SamplerCube: - case ActiveUniformType.IntSampler2D: - case ActiveUniformType.IntSampler3D: - case ActiveUniformType.IntSamplerCube: - case ActiveUniformType.UnsignedIntSampler2D: - case ActiveUniformType.UnsignedIntSampler3D: - case ActiveUniformType.UnsignedIntSamplerCube: - var uniformIndex = GL.GetUniformLocation(ProgramId, uniformName); - - // Temporary way to scan which texture and sampler created this texture_sampler variable (to fix with new HLSL2GLSL converter) - - var startIndex = -1; - var textureReflectionIndex = -1; - var samplerReflectionIndex = -1; - do - { - int middlePart = uniformName.IndexOf('_', startIndex + 1); - var textureName = middlePart != -1 ? uniformName.Substring(0, middlePart) : uniformName; - var samplerName = middlePart != -1 ? uniformName.Substring(middlePart + 1) : null; - - textureReflectionIndex = - effectReflection.ResourceBindings.FindIndex(x => x.RawName == textureName); - samplerReflectionIndex = - effectReflection.ResourceBindings.FindIndex(x => x.RawName == samplerName); - - if (textureReflectionIndex != -1 && samplerReflectionIndex != -1) - break; - - startIndex = middlePart; - } while (startIndex != -1); - - if (startIndex == -1 || textureReflectionIndex == -1 || samplerReflectionIndex == -1) - { - reflectionResult.Error($"Unable to find sampler and texture corresponding to [{uniformName}]"); - continue; // Error - } - - var textureReflection = effectReflection.ResourceBindings[textureReflectionIndex]; - var samplerReflection = effectReflection.ResourceBindings[samplerReflectionIndex]; - - // Contrary to Direct3D, samplers and textures are part of the same object in OpenGL - // Since we are exposing the Direct3D representation, a single sampler parameter key can be used for several textures, a single texture can be used with several samplers. - // When such a case is detected, we need to duplicate the resource binding. - textureReflectionIndex = GetReflexionIndex(textureReflection, textureReflectionIndex, effectReflection.ResourceBindings); - samplerReflectionIndex = GetReflexionIndex(samplerReflection, samplerReflectionIndex, effectReflection.ResourceBindings); - - // Update texture uniform mapping - GL.Uniform1(uniformIndex, textureUnitCount); - - textureReflection.Stage = stage; - //textureReflection.Param.RawName = uniformName; - textureReflection.Type = GetTypeFromActiveUniformType(uniformType); - textureReflection.Class = EffectParameterClass.ShaderResourceView; - textureReflection.SlotStart = textureUnitCount; - textureReflection.SlotCount = 1; // TODO: texture arrays - - samplerReflection.Stage = stage; - samplerReflection.Class = EffectParameterClass.Sampler; - samplerReflection.SlotStart = textureUnitCount; - samplerReflection.SlotCount = 1; // TODO: texture arrays - - effectReflection.ResourceBindings[textureReflectionIndex] = textureReflection; - effectReflection.ResourceBindings[samplerReflectionIndex] = samplerReflection; - - Textures.Add(new Texture(textureUnitCount)); - - textureUnitCount++; - break; - } - } - - // Remove any optimized resource binding - effectReflection.ResourceBindings.RemoveAll(x => x.SlotStart == -1); - effectReflection.ConstantBuffers = effectReflection.ConstantBuffers.Where((cb, i) => validConstantBuffers[i]).ToList(); - } - - GL.UseProgram(currentProgram); - } - -#if XENKO_GRAPHICS_API_OPENGLES - struct UniformPart - { - public int Start; - public int Count; - public int Indexer; - } - - private void AddUniform(EffectReflection effectReflection, bool[] validConstantBuffers, int uniformSize, int uniformCount, string uniformName, ActiveUniformType uniformType) - { - // OpenGL ES 2 is adding uniform for each cbuffer member, so we need to remove array and struct indexers so that we can identify it in cbuffer and find offset - var uniformParts = new List(8); - var uniformLastStart = 0; - for (var index = 0; index <= uniformName.Length; index++) - { - char c = index == uniformName.Length ? '.' : uniformName[index]; // Treat string end same as '.' - if (c == '.' || c == '[') - { - var uniformPart = new UniformPart { Start = uniformLastStart, Count = index - uniformLastStart, Indexer = -1 }; - - // Read array index (if any) - if (c == '[') - { - var indexerStart = ++index; - while (uniformName[index] != ']') - index++; - // TODO: Avoid substring - uniformPart.Indexer = int.Parse(uniformName.Substring(indexerStart, index - indexerStart)); - index++; - } - - uniformParts.Add(uniformPart); - uniformLastStart = index + 1; - } - } - - var variableName = uniformName.Substring(0, uniformParts[0].Count); - - // check that this uniform is in a constant buffer - int indexOfConstantBuffer = -1; - int indexOfMember = -1; - EffectConstantBufferDescription constantBufferDescription = null; - for (int cbIndex = 0; cbIndex < effectReflection.ConstantBuffers.Count; cbIndex++) - { - var currentConstantBuffer = effectReflection.ConstantBuffers[cbIndex]; - for (int index = 0; index < currentConstantBuffer.Members.Length; index++) - { - var member = currentConstantBuffer.Members[index]; - if (member.RawName.Equals(variableName)) - { - indexOfConstantBuffer = cbIndex; - indexOfMember = index; - constantBufferDescription = currentConstantBuffer; - break; - } - } - if (constantBufferDescription != null) - break; - } - - if (constantBufferDescription == null) - { - throw new Exception("The uniform value " + variableName + " is defined outside of a uniform block, which is not supported by the engine."); - } - - var indexOfResource = effectReflection.ResourceBindings.FindIndex(x => x.RawName == constantBufferDescription.Name); - if (indexOfResource == -1) - { - reflectionResult.Error($"Unable to find uniform [{uniformName}] in any constant buffer"); - return; - } - - //var constantBufferDescription = effectReflection.ConstantBuffers[indexOfConstantBufferDescription]; - var constantBuffer = effectReflection.ResourceBindings[indexOfResource]; - - // First time we encounter this cbuffer? - if (!validConstantBuffers[indexOfConstantBuffer]) - { - constantBuffer.SlotStart = ConstantBufferOffsets.Length - 1; - - // Find next cbuffer slot - Array.Resize(ref ConstantBufferOffsets, ConstantBufferOffsets.Length + 1); - - effectReflection.ResourceBindings[indexOfResource] = constantBuffer; - - ConstantBufferOffsets[constantBuffer.SlotStart + 1] = ConstantBufferOffsets[constantBuffer.SlotStart] + constantBufferDescription.Size; - - validConstantBuffers[indexOfConstantBuffer] = true; - } - - //var elementSize = uniformSize; - - // For array, each element is rounded to register size - //if (uniformSize%16 != 0 && uniformCount > 1) - //{ - // constantBufferDescription.Size = (constantBufferDescription.Size + 15)/16*16; - // uniformSize = (uniformSize + 15)/16*16; - //} - - // Check if it can fits in the same register, otherwise starts at the next one - //if (uniformCount == 1 && constantBufferDescription.Size/16 != (constantBufferDescription.Size + uniformSize - 1)/16) - // constantBufferDescription.Size = (constantBufferDescription.Size + 15)/16*16; - - var variable = constantBufferDescription.Members[indexOfMember]; - - // Resolve array/member - var offset = variable.Offset; - var type = variable.Type; - - for (int i = 0; i < uniformParts.Count; ++i) - { - var uniformPart = uniformParts[i]; - - // Apply member - if (i > 0) - { - if (type.Members == null) - throw new InvalidOperationException($"Tried to find member \"{uniformName.Substring(uniformPart.Start, uniformPart.Count)}\" on a non-struct type when processing \"{uniformName}\""); - - bool memberFound = false; - for (int memberIndex = 0; memberIndex < type.Members.Length; ++memberIndex) - { - var member = type.Members[memberIndex]; - if (string.Compare(member.Name, 0, uniformName, uniformPart.Start, uniformPart.Count) == 0) - { - // Adjust offset and set new type - offset += member.Offset; - type = member.Type; - - memberFound = true; - break; - } - } - - if (!memberFound) - throw new InvalidOperationException($"Couldn't find member \"{uniformName.Substring(uniformPart.Start, uniformPart.Count)}\" on struct type \"{type.Name}\" when processing \"{uniformName}\""); - } - - // Apply indexer for arrays - if (uniformPart.Indexer != -1) - { - offset += (type.ElementSize + 15) / 16 * 16 * uniformPart.Indexer; - } - } - - // Check type - if (type.Type != GetTypeFromActiveUniformType(uniformType)) - throw new InvalidOperationException($"Uniform [{uniformName}] of type [{variable.Type.Type}] doesn't match OpenGL shader expected type [{GetTypeFromActiveUniformType(uniformType)}]"); - - // No need to compare last element padding. - // TODO: In case of float1/float2 arrays (rare) it is quite non-optimal to do a CompareMemory - //variable.Size = uniformSize * (uniformCount - 1) + elementSize; - //constantBufferDescription.Members[indexOfUniform] = variable; - - Uniforms.Add(new Uniform - { - Type = uniformType, - Count = uniformCount, - CompareSize = uniformSize + (uniformSize + 15)/16*16 * (uniformCount - 1), - ConstantBufferSlot = constantBuffer.SlotStart, - Offset = offset, - UniformIndex = GL.GetUniformLocation(ProgramId, uniformName) - }); - } -#endif - - /// - /// Inserts the data in the list if this is a copy of a previously set one. - /// - /// The data. - /// The index in the list. - /// The list of bindings. - /// The new index of the data. - private static int GetReflexionIndex(EffectResourceBindingDescription data, int index, FastList bindings) - { - if (data.SlotCount != 0) - { - // slot count has been specified, this means that this resource was already configured - // We have to create a new entry for the data - var newIndex = bindings.Count; - bindings.Add(data); - return newIndex; - } - return index; - } - - private static int GetCountFromActiveUniformType(ActiveUniformType type) - { - switch (type) - { - case ActiveUniformType.Int: - case ActiveUniformType.Float: - case ActiveUniformType.Bool: - return 1; - case ActiveUniformType.IntVec2: - case ActiveUniformType.UnsignedIntVec2: - case ActiveUniformType.FloatVec2: - case ActiveUniformType.BoolVec2: - return 2; - case ActiveUniformType.IntVec3: - case ActiveUniformType.UnsignedIntVec3: - case ActiveUniformType.FloatVec3: - case ActiveUniformType.BoolVec3: - return 3; - case ActiveUniformType.IntVec4: - case ActiveUniformType.UnsignedIntVec4: - case ActiveUniformType.FloatVec4: - case ActiveUniformType.BoolVec4: - case ActiveUniformType.FloatMat2: - return 4; - case ActiveUniformType.FloatMat2x3: - case FloatMat3x2: - return 6; - case ActiveUniformType.FloatMat2x4: - case ActiveUniformType.FloatMat4x2: - return 8; - case ActiveUniformType.FloatMat3: - return 9; - case ActiveUniformType.FloatMat3x4: - case ActiveUniformType.FloatMat4x3: - return 12; - case ActiveUniformType.FloatMat4: - return 16; - - case ActiveUniformType.Sampler2D: - case ActiveUniformType.SamplerCube: - case ActiveUniformType.Sampler3D: - case ActiveUniformType.Sampler2DShadow: - case ActiveUniformType.SamplerCubeShadow: - case ActiveUniformType.IntSampler2D: - case ActiveUniformType.IntSampler3D: - case ActiveUniformType.IntSamplerCube: - case ActiveUniformType.UnsignedIntSampler2D: - case ActiveUniformType.UnsignedIntSampler3D: - case ActiveUniformType.UnsignedIntSamplerCube: - case ActiveUniformType.Sampler2DArray: - case ActiveUniformType.Sampler2DArrayShadow: - case ActiveUniformType.IntSampler2DArray: - case ActiveUniformType.UnsignedIntSampler2DArray: -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.Sampler1D: - case ActiveUniformType.Sampler1DShadow: - case ActiveUniformType.Sampler2DRect: - case ActiveUniformType.Sampler2DRectShadow: - case ActiveUniformType.IntSampler1D: - case ActiveUniformType.IntSampler2DRect: - case ActiveUniformType.UnsignedIntSampler1D: - case ActiveUniformType.UnsignedIntSampler2DRect: - case ActiveUniformType.Sampler1DArray: - case ActiveUniformType.Sampler1DArrayShadow: - case ActiveUniformType.IntSampler1DArray: - case ActiveUniformType.UnsignedIntSampler1DArray: -#endif - return 1; -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.SamplerBuffer: - case ActiveUniformType.IntSamplerBuffer: - case ActiveUniformType.UnsignedIntSamplerBuffer: - return 1; - case ActiveUniformType.Sampler2DMultisample: - case ActiveUniformType.IntSampler2DMultisample: - case ActiveUniformType.UnsignedIntSampler2DMultisample: - return 1; - case ActiveUniformType.Sampler2DMultisampleArray: - case ActiveUniformType.IntSampler2DMultisampleArray: - case ActiveUniformType.UnsignedIntSampler2DMultisampleArray: -#endif - return 1; - default: - //TODO: log error ? - return 0; - } - } - - private static EffectParameterClass GetClassFromActiveUniformType(ActiveUniformType type) - { - switch (type) - { - case ActiveUniformType.Int: - case ActiveUniformType.Float: - case ActiveUniformType.Bool: - return EffectParameterClass.Scalar; - case ActiveUniformType.FloatVec2: - case ActiveUniformType.FloatVec3: - case ActiveUniformType.FloatVec4: - case ActiveUniformType.IntVec2: - case ActiveUniformType.IntVec3: - case ActiveUniformType.IntVec4: - case ActiveUniformType.BoolVec2: - case ActiveUniformType.BoolVec3: - case ActiveUniformType.BoolVec4: - case ActiveUniformType.UnsignedIntVec2: - case ActiveUniformType.UnsignedIntVec3: - case ActiveUniformType.UnsignedIntVec4: - return EffectParameterClass.Vector; - case ActiveUniformType.FloatMat2: - case ActiveUniformType.FloatMat3: - case ActiveUniformType.FloatMat4: - case ActiveUniformType.FloatMat2x3: - case ActiveUniformType.FloatMat2x4: - case FloatMat3x2: - case ActiveUniformType.FloatMat3x4: - case ActiveUniformType.FloatMat4x2: - case ActiveUniformType.FloatMat4x3: - return EffectParameterClass.MatrixColumns; - //return EffectParameterClass.MatrixRows; - //return EffectParameterClass.Vector; - case ActiveUniformType.Sampler2D: - case ActiveUniformType.SamplerCube: - case ActiveUniformType.Sampler3D: - case ActiveUniformType.Sampler2DShadow: - case ActiveUniformType.Sampler2DArray: - case ActiveUniformType.Sampler2DArrayShadow: - case ActiveUniformType.SamplerCubeShadow: - case ActiveUniformType.IntSampler2D: - case ActiveUniformType.IntSampler3D: - case ActiveUniformType.IntSamplerCube: - case ActiveUniformType.IntSampler2DArray: - case ActiveUniformType.UnsignedIntSampler2D: - case ActiveUniformType.UnsignedIntSampler3D: - case ActiveUniformType.UnsignedIntSamplerCube: - case ActiveUniformType.UnsignedIntSampler2DArray: -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.Sampler1D: - case ActiveUniformType.Sampler1DShadow: - case ActiveUniformType.Sampler2DRect: - case ActiveUniformType.Sampler2DRectShadow: - case ActiveUniformType.Sampler1DArray: - case ActiveUniformType.SamplerBuffer: - case ActiveUniformType.Sampler1DArrayShadow: - case ActiveUniformType.IntSampler1D: - case ActiveUniformType.IntSampler2DRect: - case ActiveUniformType.IntSampler1DArray: - case ActiveUniformType.IntSamplerBuffer: - case ActiveUniformType.UnsignedIntSampler1D: - case ActiveUniformType.UnsignedIntSampler2DRect: - case ActiveUniformType.UnsignedIntSampler1DArray: - case ActiveUniformType.UnsignedIntSamplerBuffer: - case ActiveUniformType.Sampler2DMultisample: - case ActiveUniformType.IntSampler2DMultisample: - case ActiveUniformType.UnsignedIntSampler2DMultisample: - case ActiveUniformType.Sampler2DMultisampleArray: - case ActiveUniformType.IntSampler2DMultisampleArray: - case ActiveUniformType.UnsignedIntSampler2DMultisampleArray: -#endif - return EffectParameterClass.TextureBuffer; - default: - //TODO: log error ? - return EffectParameterClass.Object; - } - } - - private static EffectParameterType GetTypeFromActiveUniformType(ActiveUniformType type) - { - switch (type) - { - case ActiveUniformType.Int: - case ActiveUniformType.IntVec2: - case ActiveUniformType.IntVec3: - case ActiveUniformType.IntVec4: - return EffectParameterType.Int; - case ActiveUniformType.Float: - case ActiveUniformType.FloatVec2: - case ActiveUniformType.FloatVec3: - case ActiveUniformType.FloatVec4: - case ActiveUniformType.FloatMat2: - case ActiveUniformType.FloatMat3: - case ActiveUniformType.FloatMat4: - case ActiveUniformType.FloatMat2x3: - case ActiveUniformType.FloatMat2x4: - case FloatMat3x2: - case ActiveUniformType.FloatMat3x4: - case ActiveUniformType.FloatMat4x2: - case ActiveUniformType.FloatMat4x3: - return EffectParameterType.Float; - case ActiveUniformType.Bool: - case ActiveUniformType.BoolVec2: - case ActiveUniformType.BoolVec3: - case ActiveUniformType.BoolVec4: - return EffectParameterType.Bool; - case ActiveUniformType.UnsignedIntVec2: - case ActiveUniformType.UnsignedIntVec3: - case ActiveUniformType.UnsignedIntVec4: - return EffectParameterType.UInt; -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.Sampler1D: - case ActiveUniformType.Sampler1DShadow: - case ActiveUniformType.IntSampler1D: - case ActiveUniformType.UnsignedIntSampler1D: - return EffectParameterType.Texture1D; -#endif - case ActiveUniformType.Sampler2D: - case ActiveUniformType.Sampler2DShadow: - case ActiveUniformType.IntSampler2D: - case ActiveUniformType.UnsignedIntSampler2D: -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.Sampler2DRect: - case ActiveUniformType.Sampler2DRectShadow: - case ActiveUniformType.IntSampler2DRect: - case ActiveUniformType.UnsignedIntSampler2DRect: -#endif - return EffectParameterType.Texture2D; - case ActiveUniformType.Sampler3D: - case ActiveUniformType.IntSampler3D: - case ActiveUniformType.UnsignedIntSampler3D: - return EffectParameterType.Texture3D; - case ActiveUniformType.SamplerCube: - case ActiveUniformType.SamplerCubeShadow: - case ActiveUniformType.IntSamplerCube: - case ActiveUniformType.UnsignedIntSamplerCube: - return EffectParameterType.TextureCube; - case ActiveUniformType.Sampler2DArray: - case ActiveUniformType.Sampler2DArrayShadow: - case ActiveUniformType.IntSampler2DArray: - case ActiveUniformType.UnsignedIntSampler2DArray: - return EffectParameterType.Texture2DArray; -#if !XENKO_GRAPHICS_API_OPENGLES - case ActiveUniformType.Sampler1DArray: - case ActiveUniformType.Sampler1DArrayShadow: - case ActiveUniformType.IntSampler1DArray: - case ActiveUniformType.UnsignedIntSampler1DArray: - return EffectParameterType.Texture1DArray; - case ActiveUniformType.SamplerBuffer: - case ActiveUniformType.IntSamplerBuffer: - case ActiveUniformType.UnsignedIntSamplerBuffer: - return EffectParameterType.TextureBuffer; - case ActiveUniformType.Sampler2DMultisample: - case ActiveUniformType.IntSampler2DMultisample: - case ActiveUniformType.UnsignedIntSampler2DMultisample: - return EffectParameterType.Texture2DMultisampled; - case ActiveUniformType.Sampler2DMultisampleArray: - case ActiveUniformType.IntSampler2DMultisampleArray: - case ActiveUniformType.UnsignedIntSampler2DMultisampleArray: - return EffectParameterType.Texture2DMultisampledArray; -#endif - default: - //TODO: log error ? - return EffectParameterType.Void; - } - } - - class UniformMergeInfo - { - public ActiveUniformType Type; - public int Offset; - public int NextOffset; - public string Name; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapter.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapter.OpenGL.cs deleted file mode 100644 index 1dc0c0124e..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapter.OpenGL.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_OPENGL -using System.Linq; -using Xenko.Graphics.OpenGL; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif -namespace Xenko.Graphics -{ - /// - /// Provides methods to retrieve and manipulate graphics adapters. - /// - public partial class GraphicsAdapter - { - private GraphicsProfile supportedGraphicsProfile; - - internal GraphicsAdapter() - { - outputs = new [] { new GraphicsOutput() }; - - // set default values - int detectedVersion = 100; - - var renderer = GL.GetString(StringName.Renderer); - var vendor = GL.GetString(StringName.Vendor); - - // Stay close to D3D: Cut renderer after first / (ex: "GeForce 670/PCIe/SSE2") - var rendererSlash = renderer.IndexOf('/'); - if (rendererSlash != -1) - renderer = renderer.Substring(0, rendererSlash); - - // Stay close to D3D: Remove "Corporation" from vendor - vendor = vendor.Replace(" Corporation", string.Empty); - - // Generate adapter Description - Description = $"{vendor} {renderer}"; - - // get real values - // using glGetIntegerv(GL_MAJOR_VERSION / GL_MINOR_VERSION) only works on opengl (es) > 3.0 - var version = GL.GetString(StringName.Version); - if (version != null) - { - var splitVersion = version.Split(new char[] { '.', ' ' }); - // find first number occurrence because: - // - on OpenGL, "." - // - on OpenGL ES, "OpenGL ES ." - for (var i = 0; i < splitVersion.Length - 1; ++i) - { - int versionMajor, versionMinor; - if (int.TryParse(splitVersion[i], out versionMajor)) - { - // Note: minor version might have stuff concat, take only until not digits - var versionMinorString = splitVersion[i + 1]; - versionMinorString = new string(versionMinorString.TakeWhile(c => char.IsDigit(c)).ToArray()); - - int.TryParse(versionMinorString, out versionMinor); - - detectedVersion = versionMajor * 100 + versionMinor * 10; - break; - } - } - } - - supportedGraphicsProfile = OpenGLUtils.GetFeatureLevel(detectedVersion); - } - - public bool IsProfileSupported(GraphicsProfile graphicsProfile) - { - // TODO: Check OpenGL version? - // TODO: ES specific code? - return graphicsProfile <= supportedGraphicsProfile; - } - - /// - /// Gets the description of this adapter. - /// - /// The description. - public string Description { get; } - - /// - /// Determines if this instance of GraphicsAdapter is the default adapter. - /// - public bool IsDefaultAdapter - { - get { return true; } - } - - /// - /// Gets or sets the vendor identifier. - /// - /// - /// The vendor identifier. - /// - public int VendorId - { - get { return 0; } - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapterFactory.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapterFactory.OpenGL.cs deleted file mode 100644 index 193fd9bec5..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsAdapterFactory.OpenGL.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -namespace Xenko.Graphics -{ - public partial class GraphicsAdapterFactory - { - private static void InitializeInternal() - { - defaultAdapter = new GraphicsAdapter(); - adapters = new [] { defaultAdapter }; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsDevice.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsDevice.OpenGL.cs deleted file mode 100644 index c739551b62..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsDevice.OpenGL.cs +++ /dev/null @@ -1,1292 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using OpenTK.Graphics; -using OpenTK.Platform; -using Xenko.Core; -using Xenko.Core.Diagnostics; -using Xenko.Core.Mathematics; -using Xenko.Rendering; -using Xenko.Shaders; -using Xenko.Graphics.OpenGL; -using Color4 = Xenko.Core.Mathematics.Color4; -#if XENKO_PLATFORM_ANDROID -using System.Text; -using System.Runtime.InteropServices; -using OpenTK.Platform.Android; -#elif XENKO_PLATFORM_IOS -using OpenTK.Platform.iPhoneOS; -#endif -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using DrawBuffersEnum = OpenTK.Graphics.ES30.DrawBufferMode; -using FramebufferAttachmentObjectType = OpenTK.Graphics.ES30.All; -#else -using OpenTK.Graphics.OpenGL; -using TextureTarget2d = OpenTK.Graphics.OpenGL.TextureTarget; -using TextureTarget3d = OpenTK.Graphics.OpenGL.TextureTarget; -#endif - -#if XENKO_UI_SDL -using WindowState = Xenko.Graphics.SDL.FormWindowState; -#else -using WindowState = OpenTK.WindowState; -#endif - -namespace Xenko.Graphics -{ - /// - /// Performs primitive-based rendering, creates resources, handles system-level variables, adjusts gamma ramp levels, and creates shaders. - /// - public partial class GraphicsDevice - { - internal readonly int ConstantBufferDataPlacementAlignment = 16; - - private static readonly Logger Log = GlobalLogger.GetLogger("GraphicsDevice"); - - internal int FrameCounter; - - // Used when locking asyncCreationLockObject - private bool asyncCreationLockTaken; - - internal bool ApplicationPaused = false; - internal bool ProfileEnabled = false; - - internal IWindowInfo deviceCreationWindowInfo; - internal object asyncCreationLockObject = new object(); - internal OpenTK.Graphics.IGraphicsContext deviceCreationContext; - - internal int defaultVAO; - - internal int CopyColorSourceFBO, CopyDepthSourceFBO; - - DebugProc debugCallbackInstance; -#if XENKO_GRAPHICS_API_OPENGLES - DebugProcKhr debugCallbackInstanceKHR; -#endif - - private const GraphicsPlatform GraphicPlatform = -#if XENKO_GRAPHICS_API_OPENGLES - GraphicsPlatform.OpenGLES; -#else - GraphicsPlatform.OpenGL; -#endif - -#if XENKO_PLATFORM_ANDROID - // If context was set before Begin(), try to keep it after End() - // (otherwise devices with no backbuffer flicker) - private bool keepContextOnEnd; - - private IntPtr graphicsContextEglPtr; - internal bool AsyncPendingTaskWaiting; // Used when Workaround_Context_Tegra2_Tegra3 - - // Workarounds for specific GPUs - internal bool Workaround_Context_Tegra2_Tegra3; -#endif - - internal SamplerState DefaultSamplerState; - internal DepthStencilState defaultDepthStencilState; - internal BlendState defaultBlendState; - internal GraphicsProfile requestedGraphicsProfile; - internal int version; // queried version - internal int currentVersion; // glGetVersion - internal Texture WindowProvidedRenderTexture; - internal int WindowProvidedFrameBuffer; - - internal bool HasVAO; - - internal bool HasDXT; - - internal bool HasDepthClamp; - - internal bool HasAnisotropicFiltering; - - internal bool HasTextureBuffers; - internal bool HasKhronosDebug; - internal bool HasTimerQueries; - -#if XENKO_GRAPHICS_API_OPENGLES - internal bool HasKhronosDebugKHR; - internal bool HasDepth24; - internal bool HasPackedDepthStencilExtension; - internal bool HasExtTextureFormatBGRA8888; - internal bool HasTextureFloat; - internal bool HasTextureHalf; - internal bool HasRenderTargetFloat; - internal bool HasRenderTargetHalf; - internal bool HasTextureRG; -#endif - - private bool isFramebufferSRGB; - - private int contextBeginCounter = 0; - - // TODO: Use some LRU scheme to clean up FBOs if not used frequently anymore. - internal Dictionary existingFBOs = new Dictionary(); - - private static GraphicsDevice _currentGraphicsDevice = null; - - [ThreadStatic] private static List _graphicsDevicesInUse; - - public static GraphicsDevice Current - { - get - { - if (_graphicsDevicesInUse != null && _graphicsDevicesInUse.Count > 0) - return _graphicsDevicesInUse[_graphicsDevicesInUse.Count - 1]; - - return _currentGraphicsDevice; - } - - set - { - _currentGraphicsDevice = value; - } - } - - private OpenTK.Graphics.IGraphicsContext graphicsContext; - private OpenTK.Platform.IWindowInfo windowInfo; - -#if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX -#if XENKO_UI_SDL - private Xenko.Graphics.SDL.Window gameWindow; -#else - private OpenTK.GameWindow gameWindow; -#endif -#elif XENKO_PLATFORM_ANDROID - private AndroidGameView gameWindow; -#elif XENKO_PLATFORM_IOS - private iPhoneOSGameView gameWindow; - public ThreadLocal ThreadLocalContext { get; private set; } -#endif - -#if XENKO_PLATFORM_ANDROID - [DllImport("libEGL.dll", EntryPoint = "eglGetCurrentContext")] - internal static extern IntPtr EglGetCurrentContext(); -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - public bool IsOpenGLES2 { get; private set; } - - // Need to change sampler state depending on if texture has mipmap or not during PreDraw - private bool[] hasMipmaps = new bool[64]; -#endif - - private int copyProgram = -1; - private int copyProgramOffsetLocation = -1; - private int copyProgramScaleLocation = -1; - - private int copyProgramSRgb = -1; - private int copyProgramSRgbOffsetLocation = -1; - private int copyProgramSRgbScaleLocation = -1; - - internal float[] SquareVertices = { - 0.0f, 0.0f, - 1.0f, 0.0f, - 0.0f, 1.0f, - 1.0f, 1.0f, - }; - - internal Buffer SquareBuffer; - - /// - /// The tick frquency of timestamp queries in Hertz. - /// - public long TimestampFrequency { get; } = 1000_000_000L; - - /// - /// Gets the status of this device. - /// - public GraphicsDeviceStatus GraphicsDeviceStatus - { - get - { -#if XENKO_PLATFORM_ANDROID - if (graphicsContext != gameWindow.GraphicsContext) - { - return GraphicsDeviceStatus.Reset; - } -#endif - - // TODO implement GraphicsDeviceStatus for OpenGL - return GraphicsDeviceStatus.Normal; - } - } - - public void Use() - { - if (_graphicsDevicesInUse == null) - _graphicsDevicesInUse = new List(); - - if (!_graphicsDevicesInUse.Contains(this)) - _graphicsDevicesInUse.Add(this); - } - - public void Unuse() - { - if (_graphicsDevicesInUse == null) - return; - - _graphicsDevicesInUse.Remove(this); - - if (_graphicsDevicesInUse.Count == 0) - _graphicsDevicesInUse = null; - } - - internal UseOpenGLCreationContext UseOpenGLCreationContext() - { - return new UseOpenGLCreationContext(this); - } - - /// - /// Marks context as active on the current thread. - /// - public void Begin() - { - ++contextBeginCounter; - - if (contextBeginCounter == 1) - { - FrameCounter++; - -#if XENKO_PLATFORM_ANDROID - if (Workaround_Context_Tegra2_Tegra3) - { - Monitor.Enter(asyncCreationLockObject, ref asyncCreationLockTaken); - } - else - { - // On first set, check if context was not already set before, - // in which case we won't unset it during End(). - keepContextOnEnd = graphicsContextEglPtr == GraphicsDevice.EglGetCurrentContext(); - - if (keepContextOnEnd) - { - return; - } - } -#endif - graphicsContext.MakeCurrent(windowInfo); - } - } - - /// - /// Unmarks context as active on the current thread. - /// - public void End() - { -#if DEBUG - EnsureContextActive(); -#endif - - --contextBeginCounter; - if (contextBeginCounter == 0) - { - //UnbindVertexArrayObject(); - -#if XENKO_PLATFORM_ANDROID - if (Workaround_Context_Tegra2_Tegra3) - { - graphicsContext.MakeCurrent(null); - - // Notify that main context can be used from now on - if (asyncCreationLockTaken) - { - Monitor.Exit(asyncCreationLockObject); - asyncCreationLockTaken = false; - } - } - else if (!keepContextOnEnd) - { - GraphicsDevice.UnbindGraphicsContext(graphicsContext); - } -#else - UnbindGraphicsContext(graphicsContext); -#endif - } - else if (contextBeginCounter < 0) - { - throw new Exception("End context was called more than Begin"); - } - } - - internal Buffer GetSquareBuffer() - { - if (SquareBuffer == null) - { - SquareBuffer = Buffer.New(this, SquareVertices, BufferFlags.VertexBuffer); - } - - return SquareBuffer; - } - - internal int GetCopyProgram(bool srgb, out int offsetLocation, out int scaleLocation) - { - if (srgb) - { - if (copyProgramSRgb == -1) - { - copyProgramSRgb = CreateCopyProgram(true, out copyProgramSRgbOffsetLocation, out copyProgramSRgbScaleLocation); - } - offsetLocation = copyProgramSRgbOffsetLocation; - scaleLocation = copyProgramSRgbScaleLocation; - return copyProgramSRgb; - } - else - { - if (copyProgram == -1) - { - copyProgram = CreateCopyProgram(false, out copyProgramOffsetLocation, out copyProgramScaleLocation); - } - offsetLocation = copyProgramOffsetLocation; - scaleLocation = copyProgramScaleLocation; - return copyProgram; - } - } - - private int CreateCopyProgram(bool srgb, out int offsetLocation, out int scaleLocation) - { - string shaderVersion, inAttribute, outAttribute, varyingFragment, fragColorDeclaration, fragColorVariable, textureAPI; -#if XENKO_GRAPHICS_API_OPENGLES - // We aim at OpenGLES 3.0 or greater. - shaderVersion = "#version 300 es"; -#else - shaderVersion = "#version 410"; -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - if (currentVersion < 300) - { - // Override the version - shaderVersion = "#version 100"; - inAttribute = "attribute"; - outAttribute = "varying"; - varyingFragment = "varying"; - fragColorDeclaration = ""; - fragColorVariable = "gl_FragColor"; - textureAPI = "texture2D"; - } - else -#endif - { - inAttribute = "in"; - outAttribute = "out"; - varyingFragment = "in"; - fragColorDeclaration = "out vec4 gFragColor;\n"; - fragColorVariable = "gFragColor"; - textureAPI = "texture"; - } - - string copyVertexShaderSource = - shaderVersion + "\n" + - inAttribute + " vec2 aPosition; \n" + - outAttribute + " vec2 vTexCoord; \n" + - "uniform vec4 uScale; \n" + - "uniform vec4 uOffset; \n" + - "void main() \n" + - "{ \n" + - " vec4 transformedPosition = aPosition.xyxy * uScale + uOffset;" + - " gl_Position = vec4(transformedPosition.zw * 2.0 - 1.0, 0.0, 1.0); \n" + - " vTexCoord = transformedPosition.xy; \n" + - "} \n"; - - string copyFragmentShaderSource = - shaderVersion + "\n" + - "precision mediump float; \n" + - varyingFragment + " vec2 vTexCoord; \n" + - fragColorDeclaration + - "uniform sampler2D s_texture; \n" + - "void main() \n" + - "{ \n" + - " " + fragColorVariable + " = " + textureAPI + "(s_texture, vTexCoord); \n" + - "} \n"; - - string copyFragmentShaderSourceSRgb = - shaderVersion + "\n" + - "precision mediump float; \n" + - varyingFragment + " vec2 vTexCoord; \n" + - fragColorDeclaration + - "uniform sampler2D s_texture; \n" + - "void main() \n" + - "{ \n" + - " vec4 color = " + textureAPI + "(s_texture, vTexCoord); \n" + - " " + fragColorVariable + " = vec4(sqrt(color.rgb), color.a); \n" + // approximation of linear to SRgb - "} \n"; - - // First initialization of shader program - int vertexShader = TryCompileShader(ShaderType.VertexShader, copyVertexShaderSource); - int fragmentShader = TryCompileShader(ShaderType.FragmentShader, srgb ? copyFragmentShaderSourceSRgb : copyFragmentShaderSource); - - int program = GL.CreateProgram(); - GL.AttachShader(program, vertexShader); - GL.AttachShader(program, fragmentShader); - GL.BindAttribLocation(program, 0, "aPosition"); - GL.LinkProgram(program); - - int linkStatus; - GL.GetProgram(program, GetProgramParameterName.LinkStatus, out linkStatus); - - if (linkStatus != 1) - throw new InvalidOperationException("Error while linking GLSL shaders."); - - GL.UseProgram(program); - var textureLocation = GL.GetUniformLocation(program, "s_texture"); - offsetLocation = GL.GetUniformLocation(program, "uOffset"); - scaleLocation = GL.GetUniformLocation(program, "uScale"); - GL.Uniform1(textureLocation, 0); - - return program; - } - - public void EnableProfile(bool enabledFlag) - { - ProfileEnabled = true; - } - - internal void EnsureContextActive() - { - // TODO: Better checks (is active context the expected one?) -#if XENKO_PLATFORM_ANDROID - if (EglGetCurrentContext() == IntPtr.Zero) - throw new InvalidOperationException("No OpenGL context bound."); -#else - var context = OpenTK.Graphics.GraphicsContext.CurrentContext; //static cannot be debugged easy - if (context == null) - throw new InvalidOperationException("No OpenGL context bound."); -#endif - } - - public void ExecuteCommandList(CompiledCommandList commandList) - { -#if DEBUG - EnsureContextActive(); -#endif - - throw new NotImplementedException(); - } - - public void ExecuteCommandLists(int count, CompiledCommandList[] commandList) - { -#if DEBUG - EnsureContextActive(); -#endif - - throw new NotImplementedException(); - } - - internal int FindOrCreateFBO(GraphicsResourceBase graphicsResource, int subresource) - { - if (graphicsResource == WindowProvidedRenderTexture) - return WindowProvidedFrameBuffer; - - var texture = graphicsResource as Texture; - if (texture != null) - { - return FindOrCreateFBO(new FBOTexture(texture, subresource / texture.MipLevels, subresource % texture.MipLevels)); - } - - throw new NotSupportedException(); - } - - internal int FindOrCreateFBO(FBOTexture texture) - { - var isDepthBuffer = ((texture.Texture.Flags & TextureFlags.DepthStencil) != 0); - lock (existingFBOs) - { - foreach (var key in existingFBOs) - { - if ((isDepthBuffer && key.Key.DepthStencilBuffer == texture) - || !isDepthBuffer && key.Key.RenderTargetCount == 1 && key.Key.RenderTargets[0] == texture) - return key.Value; - } - } - - if (isDepthBuffer) - return FindOrCreateFBO(texture, null, 0); - return FindOrCreateFBO(null, new FBOTexture[] { texture }, 1); - } - - // TODO: I think having a class for FBOs would simplify some stuff. We could implement methods like "Bind()" for it. - int GenerateFBO(FBOTexture depthStencilBuffer, FBOTexture[] renderTargets, int renderTargetCount) - { - int fboID; - - GL.GenFramebuffers(1, out fboID); - GL.BindFramebuffer(FramebufferTarget.Framebuffer, fboID); - UpdateFBO(FramebufferTarget.Framebuffer, depthStencilBuffer, renderTargets, renderTargetCount); - - var framebufferStatus = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer); - if (framebufferStatus != FramebufferErrorCode.FramebufferComplete) - { - throw new InvalidOperationException(string.Format("FBO is incomplete: {0} RTs: [RT0: {1}]; Depth {2} (error: {3})", - renderTargetCount, - renderTargets != null && renderTargets.Length > 0 && renderTargets[0].Texture != null ? renderTargets[0].Texture.TextureId : 0, - depthStencilBuffer.Texture != null ? depthStencilBuffer.Texture.TextureId : 0, - framebufferStatus)); - } - - FBOTexture[] newFBOTextures = null; - if (renderTargets != null) - { - newFBOTextures = (FBOTexture[])renderTargets.Clone(); - } - - FBOKey newFBOKey = new FBOKey(depthStencilBuffer, newFBOTextures, renderTargetCount); - existingFBOs.Add(newFBOKey, fboID); - - return fboID; - } - - internal int FindOrCreateFBO(FBOTexture depthStencilBuffer, FBOTexture[] renderTargets, int renderTargetCount) // TODO: What's the point of passing an array that has reduntant elements? This could probably be reduced to only the "renderTargets" parameter. - { - // Check for existing FBO matching this configuration - lock (existingFBOs) // TODO: PERFORMANCE: Why is this lock here? Do we ever run this from multiple threads? If so, why? - { - // Check if the default-provided render target was requested: - // TODO: Need to disable some part of rendering if either is null - var isProvidedRenderTarget = (renderTargetCount == 1 && renderTargets[0] == WindowProvidedRenderTexture); - if (isProvidedRenderTarget && depthStencilBuffer.Texture != null) - { - throw new InvalidOperationException("It is impossible to bind device provided and user created buffers with OpenGL"); - } - if (depthStencilBuffer.Texture == null && (isProvidedRenderTarget || renderTargetCount == 0)) // device provided framebuffer - { - return WindowProvidedFrameBuffer; - } - - // Check if there is an already existing FBO: - var fboKey = new FBOKey(depthStencilBuffer, renderTargets, renderTargetCount); - - int fboID; - if (existingFBOs.TryGetValue(fboKey, out fboID)) - return fboID; - - // Since the desired FBO doesn't already exist, we generate it: - return GenerateFBO(depthStencilBuffer, renderTargets, renderTargetCount); - } - } - - internal FramebufferAttachment UpdateFBO(FramebufferTarget framebufferTarget, FBOTexture renderTarget) - { - var texture = renderTarget.Texture; - var isDepthBuffer = Texture.InternalIsDepthStencilFormat(texture.Format); - if (isDepthBuffer) - { - return UpdateFBODepthStencilAttachment(framebufferTarget, renderTarget); - } - else - { - UpdateFBOColorAttachment(framebufferTarget, 0, renderTarget); - return FramebufferAttachment.ColorAttachment0; - } - } - - internal void UpdateFBO(FramebufferTarget framebufferTarget, FBOTexture depthStencilBuffer, FBOTexture[] renderTargets, int renderTargetCount) // TODO: What's the point of passing an array that has reduntant elements? This could probably be reduced to only the "renderTargets" parameter. - { - for (int i = 0; i < renderTargetCount; ++i) - { - UpdateFBOColorAttachment(framebufferTarget, i, renderTargets[i]); - } - -#if XENKO_GRAPHICS_API_OPENGLES - if (!IsOpenGLES2) -#endif - { -#if !XENKO_GRAPHICS_API_OPENGLES - if (renderTargetCount <= 1) - { - GL.DrawBuffer(renderTargetCount != 0 ? DrawBufferMode.ColorAttachment0 : DrawBufferMode.None); - } - else -#endif - { - // Specify which attachments to render to (all of them in our case): - var drawBuffers = new DrawBuffersEnum[renderTargetCount]; - for (var i = 0; i < renderTargetCount; ++i) - drawBuffers[i] = DrawBuffersEnum.ColorAttachment0 + i; - GL.DrawBuffers(renderTargetCount, drawBuffers); - } - } - - if (depthStencilBuffer.Texture != null) - { - UpdateFBODepthStencilAttachment(framebufferTarget, depthStencilBuffer); - } - } - - void BindColorAttachment(FramebufferTarget framebufferTarget, int i, FBOTexture renderTarget) - { - FramebufferAttachment attachment = FramebufferAttachment.ColorAttachment0 + i; - - if (renderTarget.Texture.IsMultisample) - { - if (renderTarget.Texture.IsRenderbuffer) - { - GL.FramebufferRenderbuffer(framebufferTarget, attachment, RenderbufferTarget.Renderbuffer, renderTarget.Texture.TextureId); - } - else - { -#if XENKO_GRAPHICS_API_OPENGLES - throw new NotSupportedException("Multisample textures are not supported on OpenGL ES."); -#else - GL.FramebufferTexture2D(framebufferTarget, attachment, renderTarget.Texture.TextureTarget, renderTarget.Texture.TextureId, renderTarget.MipLevel); -#endif - } - } - else - { - TextureTarget2d textureTarget = Texture.GetTextureTargetForDataSet2D(renderTarget.Texture.TextureTarget, renderTarget.ArraySlice % 6); - GL.FramebufferTexture2D(framebufferTarget, attachment, textureTarget, renderTarget.Texture.TextureId, renderTarget.MipLevel); - } - } - - internal void UpdateFBOColorAttachment(FramebufferTarget framebufferTarget, int i, FBOTexture renderTarget) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (IsOpenGLES2 && renderTarget.MipLevel != 0) - throw new PlatformNotSupportedException("Can't read from mipmap level other than 0 on OpenGL ES 2"); -#endif - - switch (renderTarget.Texture.TextureTarget) - { -#if !XENKO_GRAPHICS_API_OPENGLES - case TextureTarget.Texture1D: - GL.FramebufferTexture1D(framebufferTarget, FramebufferAttachment.ColorAttachment0 + i, TextureTarget.Texture1D, renderTarget.Texture.TextureId, renderTarget.MipLevel); - break; -#endif - case TextureTarget.Texture2D: - case TextureTarget.TextureCubeMap: - // We don't make use of the "TextureTarget.Texture2DMultisample" enum value on purpose, because it - // allows for better code sharing between OpenGL ES and OpenGL. We simply use "TextureTarget.Texture2D" - // and check the value of "IsMultisample" instead. This is because OpenGL ES doesn't support - // multisample textures, but only multisample renderbuffers. - BindColorAttachment(framebufferTarget, i, renderTarget); - break; - case TextureTarget.Texture2DArray: - case TextureTarget.Texture3D: -#if XENKO_GRAPHICS_API_OPENGLES - if (IsOpenGLES2) - throw new PlatformNotSupportedException($"Can't bind FBO with target [{renderTarget.Texture.TextureTarget}]. Reason: 3D textures are not supported on OpenGL ES 2."); // TODO: If not supported on OpenGL ES, why is the texture even allocated? This should be catched earlier. -#endif - GL.FramebufferTextureLayer(framebufferTarget, FramebufferAttachment.ColorAttachment0 + i, renderTarget.Texture.TextureId, renderTarget.MipLevel, renderTarget.ArraySlice); - break; - default: - throw new NotImplementedException($"Can't bind FBO with target [{renderTarget.Texture.TextureTarget}]"); - } - } - - internal FramebufferAttachment UpdateFBODepthStencilAttachment(FramebufferTarget framebufferTarget, FBOTexture depthStencilBuffer) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (IsOpenGLES2 && depthStencilBuffer.MipLevel != 0) - throw new PlatformNotSupportedException("Can't read from mipmap level other than 0 on OpenGL ES 2"); -#endif - - bool useSharedAttachment = depthStencilBuffer.Texture.StencilId == depthStencilBuffer.Texture.TextureId; -#if XENKO_GRAPHICS_API_OPENGLES - if (IsOpenGLES2) // FramebufferAttachment.DepthStencilAttachment is not supported in ES 2 // TODO: Wouldn't it make more sense to check the value of "depthStencilBuffer.Texture.StencilId" instead? - useSharedAttachment = false; -#endif - var attachmentType = useSharedAttachment ? FramebufferAttachment.DepthStencilAttachment : FramebufferAttachment.DepthAttachment; - - if (depthStencilBuffer.Texture.IsRenderbuffer) - { - // Bind depth-only or packed depth-stencil buffer - GL.FramebufferRenderbuffer(framebufferTarget, attachmentType, RenderbufferTarget.Renderbuffer, depthStencilBuffer.Texture.TextureId); - - // If stencil buffer is separate, it's resource id might be stored in depthStencilBuffer.Texture.StencilId - if (depthStencilBuffer.Texture.HasStencil && !useSharedAttachment) - { - GL.FramebufferRenderbuffer(framebufferTarget, FramebufferAttachment.StencilAttachment, RenderbufferTarget.Renderbuffer, depthStencilBuffer.Texture.StencilId); - } - } - else - { - TextureTarget2d textureTarget2d = TextureTarget2d.Texture2D; - if (depthStencilBuffer.Texture.IsMultisample) - { -#if XENKO_GRAPHICS_API_OPENGLES - throw new NotSupportedException("Multisample textures are not supported on OpenGL ES."); -#else - textureTarget2d = TextureTarget2d.Texture2DMultisample; -#endif - } - - // Bind depth-only or packed depth-stencil buffer // TODO: What about separate depth and stencil? - GL.FramebufferTexture2D(framebufferTarget, attachmentType, textureTarget2d, depthStencilBuffer.Texture.TextureId, depthStencilBuffer.MipLevel); - } - - return attachmentType; - } - - internal int TryCompileShader(ShaderType shaderType, string sourceCode) - { - int shaderGL = GL.CreateShader(shaderType); - GL.ShaderSource(shaderGL, sourceCode); - GL.CompileShader(shaderGL); - - var log = GL.GetShaderInfoLog(shaderGL); - - int compileStatus; - GL.GetShader(shaderGL, ShaderParameter.CompileStatus, out compileStatus); - - if (compileStatus != 1) - throw new InvalidOperationException("Error while compiling GLSL shader: \n" + log); - - return shaderGL; - } - - internal static void UnbindGraphicsContext(IGraphicsContext graphicsContext) - { - graphicsContext.MakeCurrent(null); - } - - private void OnApplicationPaused(object sender, EventArgs e) - { - // Block async resource creation - Monitor.Enter(asyncCreationLockObject, ref asyncCreationLockTaken); - - ApplicationPaused = true; - - using (UseOpenGLCreationContext()) - { - GL.Finish(); - } - - // Unset graphics context - UnbindGraphicsContext(graphicsContext); - } - - private void OnApplicationResumed(object sender, EventArgs e) - { - windowInfo = gameWindow.WindowInfo; - - // Reenable graphics context - graphicsContext.MakeCurrent(windowInfo); - - ApplicationPaused = false; - - // Reenable async resource creation - if (asyncCreationLockTaken) - { - Monitor.Exit(asyncCreationLockObject); - asyncCreationLockTaken = false; - } - } - - private string renderer; - - private string GetRendererName() - { - return renderer; - } - - protected void InitializePlatformDevice(GraphicsProfile[] graphicsProfiles, DeviceCreationFlags deviceCreationFlags, WindowHandle windowHandle) - { - // Enable OpenGL context sharing - OpenTK.Graphics.GraphicsContext.ShareContexts = true; - - // TODO: How to control Debug flags? - var creationFlags = GraphicsContextFlags.Default; - - if (IsDebugMode) - { - creationFlags |= GraphicsContextFlags.Debug; - } - - // set default values - version = 100; - - requestedGraphicsProfile = GraphicsProfile.Level_9_1; - - // Find the first profile that is compatible with current GL version - foreach (var graphicsProfile in graphicsProfiles) - { - if (Adapter.IsProfileSupported(graphicsProfile)) - { - requestedGraphicsProfile = graphicsProfile; - break; - } - } - - // Find back OpenGL version from requested version - OpenGLUtils.GetGLVersion(requestedGraphicsProfile, out version); - - // check what is actually created - if (!OpenGLUtils.GetCurrentGLVersion(out currentVersion)) - { - currentVersion = version; - } - -#if XENKO_GRAPHICS_API_OPENGLES - IsOpenGLES2 = version < 300; - creationFlags |= GraphicsContextFlags.Embedded; -#endif - - renderer = GL.GetString(StringName.Renderer); - -#if XENKO_PLATFORM_UNIX || XENKO_PLATFORM_WINDOWS_DESKTOP -#if XENKO_UI_SDL - gameWindow = (Xenko.Graphics.SDL.Window)windowHandle.NativeWindow; -#else - gameWindow = (OpenTK.GameWindow)windowHandle.NativeWindow; -#endif -#elif XENKO_PLATFORM_ANDROID - gameWindow = (AndroidGameView)windowHandle.NativeWindow; -#elif XENKO_PLATFORM_IOS - gameWindow = (iPhoneOSGameView)windowHandle.NativeWindow; - ThreadLocalContext = new ThreadLocal(() => new OpenGLES.EAGLContext(IsOpenGLES2 ? OpenGLES.EAGLRenderingAPI.OpenGLES2 : OpenGLES.EAGLRenderingAPI.OpenGLES3, gameWindow.EAGLContext.ShareGroup)); -#endif - - windowInfo = gameWindow.WindowInfo; - - // Doesn't seems to be working on Android -#if XENKO_PLATFORM_ANDROID - graphicsContext = gameWindow.GraphicsContext; - gameWindow.Load += OnApplicationResumed; - gameWindow.Unload += OnApplicationPaused; - - Workaround_Context_Tegra2_Tegra3 = renderer == "NVIDIA Tegra 3" || renderer == "NVIDIA Tegra 2"; - - if (Workaround_Context_Tegra2_Tegra3) - { - // On Tegra2/Tegra3, we can't do any background context - // As a result, we reuse main graphics context even when loading. - // Of course, main graphics context need to be either available, or we register ourself for next ExecutePendingTasks(). - deviceCreationContext = graphicsContext; - deviceCreationWindowInfo = windowInfo; - - // We don't want context to be set or it might collide with our internal use to create async resources - // TODO: Reenabled, since the context seems to change otherwise. Do we need this in the first place, since we only want a single context? - //gameWindow.AutoSetContextOnRenderFrame = false; - } - else - { - if (deviceCreationContext != null) - { - deviceCreationContext.Dispose(); - deviceCreationWindowInfo.Dispose(); - } - - // Create PBuffer - deviceCreationWindowInfo = new AndroidWindow(null); - ((AndroidWindow)deviceCreationWindowInfo).CreateSurface(graphicsContext.GraphicsMode.Index.Value); - - deviceCreationContext = new OpenTK.Graphics.GraphicsContext(graphicsContext.GraphicsMode, deviceCreationWindowInfo, version / 100, (version % 100) / 10, creationFlags); - } - - graphicsContextEglPtr = EglGetCurrentContext(); -#elif XENKO_PLATFORM_IOS - graphicsContext = gameWindow.GraphicsContext; - gameWindow.Load += OnApplicationResumed; - gameWindow.Unload += OnApplicationPaused; - - var asyncContext = new OpenGLES.EAGLContext(IsOpenGLES2 ? OpenGLES.EAGLRenderingAPI.OpenGLES2 : OpenGLES.EAGLRenderingAPI.OpenGLES3, gameWindow.EAGLContext.ShareGroup); - OpenGLES.EAGLContext.SetCurrentContext(asyncContext); - deviceCreationContext = new OpenTK.Graphics.GraphicsContext(new OpenTK.ContextHandle(asyncContext.Handle), null, graphicsContext, version / 100, (version % 100) / 10, creationFlags); - deviceCreationWindowInfo = windowInfo; - gameWindow.MakeCurrent(); -#else -#if XENKO_UI_SDL - // Because OpenTK really wants a Sdl2GraphicsContext and not a dummy one, we will create - // a new one using the dummy one and invalidate the dummy one. - graphicsContext = new OpenTK.Graphics.GraphicsContext(gameWindow.DummyGLContext.GraphicsMode, windowInfo, version / 100, (version % 100) / 10, creationFlags); - gameWindow.DummyGLContext.Dispose(); -#else - graphicsContext = gameWindow.Context; -#endif - deviceCreationWindowInfo = windowInfo; - deviceCreationContext = new OpenTK.Graphics.GraphicsContext(graphicsContext.GraphicsMode, deviceCreationWindowInfo, version/100, (version%100)/10, creationFlags); -#endif - - // Restore main context - graphicsContext.MakeCurrent(windowInfo); - - // Create default OpenGL State objects - DefaultSamplerState = SamplerState.New(this, new SamplerStateDescription(TextureFilter.MinPointMagMipLinear, TextureAddressMode.Wrap) { MaxAnisotropy = 1 }).DisposeBy(this); - } - - private void InitializePostFeatures() - { - // Create and bind default VAO - if (HasVAO) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (!IsOpenGLES2) -#endif - { - GL.GenVertexArrays(1, out defaultVAO); - GL.BindVertexArray(defaultVAO); - } - } - - // Save current FBO aside - int boundFBO; - GL.GetInteger(GetPName.FramebufferBinding, out boundFBO); - - // Create FBO that will be used for copy operations - CopyColorSourceFBO = GL.GenFramebuffer(); - CopyDepthSourceFBO = GL.GenFramebuffer(); - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, CopyDepthSourceFBO); - GL.ReadBuffer(ReadBufferMode.None); - - // Restore FBO - GL.BindFramebuffer(FramebufferTarget.Framebuffer, boundFBO); - -#if !XENKO_PLATFORM_IOS - if (IsDebugMode && HasKhronosDebug) - { -#if XENKO_GRAPHICS_API_OPENGLES - HasKhronosDebugKHR = false; - try - { - // If properly implemented, we should use that one before ES 3.2 otherwise the other one without KHR prefix - // Unfortunately, many ES implementations don't respect this so we just try both - GL.Khr.DebugMessageCallback(debugCallbackInstanceKHR ?? (debugCallbackInstanceKHR = DebugCallback), IntPtr.Zero); - HasKhronosDebugKHR = true; - } - catch (EntryPointNotFoundException) -#endif - { - GL.DebugMessageCallback(debugCallbackInstance ?? (debugCallbackInstance = DebugCallback), IntPtr.Zero); - } - GL.Enable((EnableCap)KhrDebug.DebugOutputSynchronous); - ProfileEnabled = true; - - // Also do it on async creation context - deviceCreationContext.MakeCurrent(deviceCreationWindowInfo); -#if XENKO_GRAPHICS_API_OPENGLES - if (HasKhronosDebugKHR) - { - // If properly implemented, we should use that one before ES 3.2 otherwise the other one without KHR prefix - // Unfortunately, many ES implementations don't respect this so we just try both - GL.Khr.DebugMessageCallback(debugCallbackInstanceKHR, IntPtr.Zero); - } - else -#endif - { - GL.DebugMessageCallback(debugCallbackInstance, IntPtr.Zero); - } - GL.Enable((EnableCap)KhrDebug.DebugOutputSynchronous); - graphicsContext.MakeCurrent(windowInfo); - } -#endif - - // Create the main command list - InternalMainCommandList = CommandList.New(this); - } - - private void AdjustDefaultPipelineStateDescription(ref PipelineStateDescription pipelineStateDescription) - { - } - - private static void DebugCallback(DebugSource source, DebugType type, int id, DebugSeverity severity, int length, IntPtr message, IntPtr userparam) - { - if (severity == DebugSeverity.DebugSeverityHigh) - { - string msg = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(message); - Log.Error($"[GL] {source}; {type}; {id}; {severity}; {msg}"); - } - } - - protected void DestroyPlatformDevice() - { - // Hack: Reset the lock so that UseOpenGLCreationContext works (even if locked by previously called OnApplicationPaused, which might have been done in an unaccessible event thread) - // TODO: Does it work with Tegra3? - if (ApplicationPaused) - { - asyncCreationLockObject = new object(); - } - -#if XENKO_PLATFORM_ANDROID || XENKO_PLATFORM_IOS - gameWindow.Load -= OnApplicationResumed; - gameWindow.Unload -= OnApplicationPaused; -#endif - } - - internal void OnDestroyed() - { - // Clear existing FBOs - lock (existingFBOs) - { - existingFBOs.Clear(); - existingFBOs[new FBOKey(null, new FBOTexture[] { WindowProvidedRenderTexture }, 1)] = WindowProvidedFrameBuffer; - } - - //// Clear bound states - //for (int i = 0; i < boundTextures.Length; ++i) - //boundTextures[i] = null; - - //boundFrontFace = FrontFaceDirection.Ccw; - - //boundVertexArrayObject = null; - //enabledVertexAttribArrays = 0; - //boundDepthStencilState = null; - //boundStencilReference = 0; - //boundBlendState = null; - //boundRasterizerState = null; - //boundDepthStencilBuffer = null; - - //for (int i = 0; i < boundRenderTargets.Length; ++i) - //boundRenderTargets[i] = null; - - //boundFBO = 0; - //boundFBOHeight = 0; - //boundProgram = 0; - } - - internal void TagResource(GraphicsResourceLink resourceLink) - { - if (resourceLink.Resource is GraphicsResource resource) - resource.DiscardNextMap = true; - } - - internal void InitDefaultRenderTarget(PresentationParameters presentationParameters) - { -#if DEBUG - EnsureContextActive(); -#endif - - // TODO: Provide unified ClientSize from GameWindow -#if XENKO_PLATFORM_IOS - WindowProvidedFrameBuffer = gameWindow.Framebuffer; - - // Scale for Retina display - var width = (int)(gameWindow.Size.Width * gameWindow.ContentScaleFactor); - var height = (int)(gameWindow.Size.Height * gameWindow.ContentScaleFactor); -#else -#if XENKO_GRAPHICS_API_OPENGLCORE - var width = gameWindow.ClientSize.Width; - var height = gameWindow.ClientSize.Height; -#else - var width = gameWindow.Size.Width; - var height = gameWindow.Size.Height; -#endif - WindowProvidedFrameBuffer = 0; -#endif - - // TODO OPENGL detect if created framebuffer is sRGB or not (note: improperly reported by FramebufferParameterName.FramebufferAttachmentColorEncoding) - isFramebufferSRGB = true; - - GL.BindFramebuffer(FramebufferTarget.Framebuffer, WindowProvidedFrameBuffer); - - // TODO: iOS (and possibly other platforms): get real render buffer ID for color/depth? - WindowProvidedRenderTexture = Texture.New2D(this, width, height, 1, - // TODO: As a workaround, because OpenTK(+OpenGLES) doesn't support to create SRgb backbuffer, we fake it by creating a non-SRgb here and CopyScaler2D is responsible to transform it to non SRgb - isFramebufferSRGB ? presentationParameters.BackBufferFormat : presentationParameters.BackBufferFormat.ToNonSRgb(), TextureFlags.RenderTarget | Texture.TextureFlagsCustomResourceId); - WindowProvidedRenderTexture.Reload = graphicsResource => { }; - - // Extract FBO render target - if (WindowProvidedFrameBuffer != 0) - { - int framebufferAttachmentType; - GL.GetFramebufferAttachmentParameter(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, FramebufferParameterName.FramebufferAttachmentObjectType, out framebufferAttachmentType); - if (framebufferAttachmentType == (int)FramebufferAttachmentObjectType.Texture) - { - int renderTargetTextureId; - GL.GetFramebufferAttachmentParameter(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, FramebufferParameterName.FramebufferAttachmentObjectName, out renderTargetTextureId); - WindowProvidedRenderTexture.TextureId = renderTargetTextureId; - } - } - - existingFBOs[new FBOKey(null, new FBOTexture[] { WindowProvidedRenderTexture }, 1)] = WindowProvidedFrameBuffer; - } - - private class SwapChainBackend - { - /// - /// Default constructor to initialize fields that are not explicitly set to avoid warnings at compile time. - /// - internal SwapChainBackend() - { - PresentationParameters = null; - PresentCount = 0; - } - - public PresentationParameters PresentationParameters; - public int PresentCount; - } - - /// - /// Creates a swap chain from presentation parameters. - /// - /// The presentation parameters. - /// - private SwapChainBackend CreateSwapChainBackend(PresentationParameters presentationParameters) - { - var swapChainBackend = new SwapChainBackend(); - return swapChainBackend; - } - - /// - /// Gets the default presentation parameters associated with this graphics device. - /// - public PresentationParameters PresentationParameters - { - get { throw new InvalidOperationException(FrameworkResources.NoDefaultRenterTarget); } - } - - /// - /// Gets or sets a value indicating whether this GraphicsDevice is in fullscreen. - /// - /// - /// true if this GraphicsDevice is fullscreen; otherwise, false. - /// - public bool IsFullScreen - { - get - { -#if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX - return gameWindow.WindowState == WindowState.Fullscreen; -#else - throw new NotImplementedException(); -#endif - } - - set - { -#if XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX - if (value ^ (gameWindow.WindowState == WindowState.Fullscreen)) - gameWindow.WindowState = value ? WindowState.Fullscreen : WindowState.Normal; -#else - throw new NotImplementedException(); -#endif - } - } - -#if XENKO_PLATFORM_ANDROID - // Execute pending asynchronous object creation - // (on android devices where we can't create background context such as Tegra2/Tegra3) - internal void ExecutePendingTasks() - { - // Unbind context - graphicsContext.MakeCurrent(null); - - // Release and reacquire lock - Monitor.Wait(asyncCreationLockObject); - - // Rebind context - graphicsContext.MakeCurrent(windowInfo); - } -#endif - - internal struct FBOTexture : IEquatable - { - public readonly Texture Texture; - public readonly short ArraySlice; - public readonly short MipLevel; - - public FBOTexture(Texture texture, int arraySlice = 0, int mipLevel = 0) - { - Texture = texture; - ArraySlice = (short)arraySlice; - MipLevel = (short)mipLevel; - } - - public static implicit operator FBOTexture(Texture texture) - { - int arraySlice = 0; - int mipLevel = 0; - if (texture != null) - { - mipLevel = texture.MipLevel; - arraySlice = texture.ArraySlice; - } - - return new FBOTexture(texture, arraySlice, mipLevel); - } - - public bool Equals(FBOTexture other) - { - return Texture == other.Texture && ArraySlice == other.ArraySlice && MipLevel == other.MipLevel; - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is FBOTexture && Equals((FBOTexture)obj); - } - - public override int GetHashCode() - { - unchecked - { - var hashCode = (Texture != null ? Texture.GetHashCode() : 0); - hashCode = (hashCode * 397) ^ ArraySlice.GetHashCode(); - hashCode = (hashCode * 397) ^ MipLevel.GetHashCode(); - return hashCode; - } - } - - public static bool operator ==(FBOTexture left, FBOTexture right) - { - return left.Equals(right); - } - - public static bool operator !=(FBOTexture left, FBOTexture right) - { - return !left.Equals(right); - } - } - - internal struct FBOKey : IEquatable - { - public readonly FBOTexture DepthStencilBuffer; - public readonly FBOTexture[] RenderTargets; - public readonly int RenderTargetCount; - - public FBOKey(FBOTexture depthStencilBuffer, FBOTexture[] renderTargets, int renderTargetCount) - { - DepthStencilBuffer = depthStencilBuffer; - RenderTargetCount = renderTargetCount; - RenderTargets = RenderTargetCount != 0 ? renderTargets : null; - } - - public bool Equals(FBOKey obj2) - { - if (obj2.DepthStencilBuffer != DepthStencilBuffer) return false; - - // Should have same number of render targets - if (RenderTargetCount != obj2.RenderTargetCount) - return false; - - // Since both object have same LastRenderTarget, array is valid at least until this spot. - for (int i = 0; i < RenderTargetCount; ++i) - if (obj2.RenderTargets[i] != RenderTargets[i]) - return false; - - return true; - } - - public override bool Equals(object obj) - { - if (!(obj is FBOKey)) return false; - - var obj2 = (FBOKey)obj; - - return Equals(obj2); - } - - public override int GetHashCode() - { - var result = DepthStencilBuffer != null ? DepthStencilBuffer.GetHashCode() : 0; - if (RenderTargets != null) - { - for (int index = 0; index < RenderTargetCount; index++) - { - var renderTarget = RenderTargets[index]; - result ^= renderTarget != null ? renderTarget.GetHashCode() : 0; - } - } - return result; - } - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsDeviceFeatures.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsDeviceFeatures.OpenGL.cs deleted file mode 100644 index 67f65fec73..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsDeviceFeatures.OpenGL.cs +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using System.Collections.Generic; -using Xenko.Graphics.OpenGL; -using Xenko.Core.Diagnostics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - /// - /// Features supported by a . - /// - /// - /// This class gives also features for a particular format, using the operator this[dxgiFormat] on this structure. - /// - public partial struct GraphicsDeviceFeatures - { - private const GetPName GL_MAX_SAMPLES = (GetPName)36183; // We define this constant here because it is not contained within OpenTK... - - private static Logger logger = GlobalLogger.GetLogger(nameof(GraphicsDeviceFeatures)); - - private void EnumerateMSAASupportPerFormat(GraphicsDevice deviceRoot) - { - // Query OpenGL for the highest supported multisample count: - int globalMaxMSAASamples; - GL.GetInteger(GL_MAX_SAMPLES, out globalMaxMSAASamples); - - // Now select the highest engine-supported multisample mode: // TODO: Adjust comment. - MultisampleCount actualMultisampleCount = MultisampleCount.None; - - // Technically we could just cast "globalMaxMSAASamples" to "actualMultisampleCount", - // but AFAIK nothing prevents an implementation from exposing things like 6x MSAA or some other uncommon mode. - if (globalMaxMSAASamples >= 8) - { - // If the maximum supported MSAA mode by the OpenGL implementation is higher than the maximum supported by the engine (8xMSAA), we clamp it. - actualMultisampleCount = MultisampleCount.X8; - } - else if (globalMaxMSAASamples >= 4) - { - // If the maximum supported MSAA mode by the OpenGL implementation is between 4 and 7 samples, we fall back to the next lowest engine-supported one (4x). - actualMultisampleCount = MultisampleCount.X4; // 4-7 x MSAA => 4 x MSAA (next lowest) - } - else if (globalMaxMSAASamples == 2) - { - // If the maximum supported MSAA mode by the OpenGL implementation is between 2 and 3 samples, we fall back to the next lowest engine-supported one (2x). - actualMultisampleCount = MultisampleCount.X2; - } - - if (GraphicsDevice.Platform == GraphicsPlatform.OpenGLES -#if XENKO_GRAPHICS_API_OPENGLES - && deviceRoot.IsOpenGLES2 // No MSAA support on OpenGL ES 2. -#endif - ) - { - actualMultisampleCount = MultisampleCount.None; - logger.Error("Multisampling is not supported on OpenGL ES 2."); - } - - for (int i = 0; i < mapFeaturesPerFormat.Length; i++) - { - // TODO: This ignores the supported multisample capabilities of each render target format. But I don't know how to query this in OpenGL (assuming it's even possible at all). - mapFeaturesPerFormat[i] = new FeaturesPerFormat((PixelFormat)i, actualMultisampleCount, FormatSupport.None); - } - } - - internal GraphicsDeviceFeatures(GraphicsDevice deviceRoot) - { - mapFeaturesPerFormat = new FeaturesPerFormat[256]; - - HasSRgb = true; - - using (deviceRoot.UseOpenGLCreationContext()) - { - Vendor = GL.GetString(StringName.Vendor); - Renderer = GL.GetString(StringName.Renderer); -#if XENKO_GRAPHICS_API_OPENGLES - SupportedExtensions = GL.GetString(StringName.Extensions).Split(' '); -#else - int numExtensions; - GL.GetInteger(GetPName.NumExtensions, out numExtensions); - SupportedExtensions = new string[numExtensions]; - for (int extensionIndex = 0; extensionIndex < numExtensions; ++extensionIndex) - { - SupportedExtensions[extensionIndex] = GL.GetString(StringNameIndexed.Extensions, extensionIndex); - } -#endif - } - -#if XENKO_GRAPHICS_API_OPENGLES - var isOpenGLES3 = deviceRoot.currentVersion >= 300; - - deviceRoot.HasDepth24 = isOpenGLES3 || SupportedExtensions.Contains("GL_OES_depth24"); - deviceRoot.HasPackedDepthStencilExtension = isOpenGLES3 || SupportedExtensions.Contains("GL_OES_packed_depth_stencil"); - deviceRoot.HasExtTextureFormatBGRA8888 = SupportedExtensions.Contains("GL_EXT_texture_format_BGRA8888") - || SupportedExtensions.Contains("GL_APPLE_texture_format_BGRA8888"); - deviceRoot.HasTextureFloat = isOpenGLES3 || SupportedExtensions.Contains("GL_OES_texture_float"); - deviceRoot.HasTextureHalf = isOpenGLES3 || SupportedExtensions.Contains("GL_OES_texture_half_float"); - deviceRoot.HasRenderTargetFloat = isOpenGLES3 || SupportedExtensions.Contains("GL_EXT_color_buffer_float"); - deviceRoot.HasRenderTargetHalf = isOpenGLES3 || SupportedExtensions.Contains("GL_EXT_color_buffer_half_float"); - deviceRoot.HasVAO = isOpenGLES3 || SupportedExtensions.Contains("GL_OES_vertex_array_object"); - deviceRoot.HasTextureRG = isOpenGLES3 || SupportedExtensions.Contains("GL_EXT_texture_rg"); - deviceRoot.HasKhronosDebug = deviceRoot.currentVersion >= 320 || SupportedExtensions.Contains("GL_KHR_debug"); - deviceRoot.HasTimerQueries = SupportedExtensions.Contains("GL_EXT_disjoint_timer_query"); - - // Either 3.2+, or 3.1+ with GL_EXT_texture_buffer - // TODO: For now we don't have proper ES3 bindings on Android (and possibly iOS) - deviceRoot.HasTextureBuffers = false; - //deviceRoot.HasTextureBuffers = (deviceRoot.version >= 320) - // || (deviceRoot.version >= 310 && SupportedExtensions.Contains("GL_EXT_texture_buffer")); - - HasSRgb = isOpenGLES3 || SupportedExtensions.Contains("GL_EXT_sRGB"); - - // Compute shaders available in OpenGL ES 3.1 - HasComputeShaders = isOpenGLES3 && deviceRoot.currentVersion >= 1; - HasDoublePrecision = false; - - HasDepthAsSRV = isOpenGLES3; - HasDepthAsReadOnlyRT = isOpenGLES3; - HasMultisampleDepthAsSRV = isOpenGLES3; - - deviceRoot.HasDepthClamp = SupportedExtensions.Contains("GL_ARB_depth_clamp"); - - // TODO: from 3.1: draw indirect, separate shader object - // TODO: check tessellation & geometry shaders: GL_ANDROID_extension_pack_es31a -#else - deviceRoot.HasVAO = true; - - deviceRoot.HasDXT = SupportedExtensions.Contains("GL_EXT_texture_compression_s3tc"); - deviceRoot.HasTextureBuffers = true; - deviceRoot.HasKhronosDebug = deviceRoot.currentVersion >= 430 || SupportedExtensions.Contains("GL_KHR_debug"); - deviceRoot.HasTimerQueries = deviceRoot.version >= 320; - - // Compute shaders available in OpenGL 4.3 - HasComputeShaders = deviceRoot.version >= 430; - HasDoublePrecision = SupportedExtensions.Contains("GL_ARB_vertex_attrib_64bit"); - - HasDepthAsSRV = deviceRoot.version >= 300; - HasDepthAsReadOnlyRT = deviceRoot.version >= 300; - HasMultisampleDepthAsSRV = deviceRoot.version >= 300; - - deviceRoot.HasDepthClamp = deviceRoot.version >= 300; - - // TODO: from 4.0: tessellation, draw indirect - // TODO: from 4.1: separate shader object -#endif - - deviceRoot.HasAnisotropicFiltering = SupportedExtensions.Contains("GL_EXT_texture_filter_anisotropic"); - - HasResourceRenaming = true; - - HasDriverCommandLists = false; - HasMultiThreadingConcurrentResources = false; - - // Find shader model based on OpenGL version (might need to check extensions more carefully) - RequestedProfile = deviceRoot.requestedGraphicsProfile; - CurrentProfile = OpenGLUtils.GetFeatureLevel(deviceRoot.currentVersion); - - EnumerateMSAASupportPerFormat(deviceRoot); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsOutput.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsOutput.OpenGL.cs deleted file mode 100644 index 7e3160e68c..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsOutput.OpenGL.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL - -using System; - -namespace Xenko.Graphics -{ - public partial class GraphicsOutput - { - public DisplayMode FindClosestMatchingDisplayMode(GraphicsProfile[] targetProfiles, DisplayMode mode) - { - return mode; - } - - public IntPtr MonitorHandle - { - get { return IntPtr.Zero; } - } - - private void InitializeSupportedDisplayModes() - { - } - - private void InitializeCurrentDisplayMode() - { - currentDisplayMode = null; - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsResource.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsResource.OpenGL.cs deleted file mode 100644 index b16b56b6f6..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsResource.OpenGL.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_OPENGL - -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using PixelFormatGl = OpenTK.Graphics.ES30.PixelFormat; -using PixelInternalFormat = OpenTK.Graphics.ES30.TextureComponentCount; -#else -using OpenTK.Graphics.OpenGL; -using PixelFormatGl = OpenTK.Graphics.OpenGL.PixelFormat; -#endif - -namespace Xenko.Graphics -{ - /// - /// GraphicsResource class - /// - public partial class GraphicsResource - { - internal bool DiscardNextMap; // Used to internally force a WriteDiscard (to force a rename) with the GraphicsResourceAllocator - - // Shaader resource view (Texture or Texture Buffer) - internal int TextureId; - internal TextureTarget TextureTarget; - internal PixelInternalFormat TextureInternalFormat; - internal PixelFormatGl TextureFormat; - internal PixelType TextureType; - internal int TexturePixelSize; - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/GraphicsResourceBase.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/GraphicsResourceBase.OpenGL.cs deleted file mode 100644 index 10be554208..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/GraphicsResourceBase.OpenGL.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL - -namespace Xenko.Graphics -{ - /// - /// GraphicsResource class - /// - public partial class GraphicsResourceBase - { - private void Initialize() - { - } - - /// - /// Called when graphics device has been detected to be internally destroyed. - /// - /// - protected internal virtual void OnDestroyed() - { - } - - /// - /// Called when graphics device has been recreated. - /// - /// True if item transitioned to a state. - protected internal virtual bool OnRecreate() - { - return false; - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/MappedResource.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/MappedResource.OpenGL.cs deleted file mode 100644 index c0c94e4c5f..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/MappedResource.OpenGL.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -#if XENKO_GRAPHICS_API_OPENGL -namespace Xenko.Graphics -{ - public partial struct MappedResource - { - internal int PixelBufferObjectId; - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/OpenGLConvertExtensions.cs b/sources/engine/Xenko.Graphics/OpenGL/OpenGLConvertExtensions.cs deleted file mode 100644 index b5f7b414b9..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/OpenGLConvertExtensions.cs +++ /dev/null @@ -1,728 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using OpenTK.Graphics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using ES30 = OpenTK.Graphics.ES30; -using PixelFormatGl = OpenTK.Graphics.ES30.PixelFormat; -using PixelInternalFormat = OpenTK.Graphics.ES30.TextureComponentCount; -using PrimitiveTypeGl = OpenTK.Graphics.ES30.PrimitiveType; -#else -using OpenTK.Graphics.OpenGL; -using PixelFormatGl = OpenTK.Graphics.OpenGL.PixelFormat; -using PrimitiveTypeGl = OpenTK.Graphics.OpenGL.PrimitiveType; -#endif - -namespace Xenko.Graphics -{ - internal static class OpenGLConvertExtensions - { - public static ErrorCode GetErrorCode() - { - return GL.GetError(); - } - - public static unsafe Color4 ToOpenGL(Core.Mathematics.Color4 color) - { - return *(Color4*)&color; - } - - public static PrimitiveTypeGl ToOpenGL(this PrimitiveType primitiveType) - { - switch (primitiveType) - { - case PrimitiveType.PointList: - return PrimitiveTypeGl.Points; - case PrimitiveType.LineList: - return PrimitiveTypeGl.Lines; - case PrimitiveType.LineStrip: - return PrimitiveTypeGl.LineStrip; - case PrimitiveType.TriangleList: - return PrimitiveTypeGl.Triangles; - case PrimitiveType.TriangleStrip: - return PrimitiveTypeGl.TriangleStrip; - default: - // Undefined - return PrimitiveTypeGl.Triangles; - } - } - - public static BufferAccessMask ToOpenGLMask(this MapMode mapMode) - { - switch (mapMode) - { - case MapMode.Read: - return BufferAccessMask.MapReadBit; - case MapMode.Write: - return BufferAccessMask.MapWriteBit; - case MapMode.ReadWrite: - return BufferAccessMask.MapReadBit | BufferAccessMask.MapWriteBit; - case MapMode.WriteDiscard: - return BufferAccessMask.MapWriteBit | BufferAccessMask.MapInvalidateBufferBit; - case MapMode.WriteNoOverwrite: - return BufferAccessMask.MapWriteBit | BufferAccessMask.MapUnsynchronizedBit; - default: - throw new ArgumentOutOfRangeException("mapMode"); - } - } - -#if XENKO_GRAPHICS_API_OPENGLES - public static ES30.PrimitiveType ToOpenGLES(this PrimitiveType primitiveType) - { - switch (primitiveType) - { - case PrimitiveType.PointList: - return ES30.PrimitiveType.Points; - case PrimitiveType.LineList: - return ES30.PrimitiveType.Lines; - case PrimitiveType.LineStrip: - return ES30.PrimitiveType.LineStrip; - case PrimitiveType.TriangleList: - return ES30.PrimitiveType.Triangles; - case PrimitiveType.TriangleStrip: - return ES30.PrimitiveType.TriangleStrip; - default: - throw new NotImplementedException(); - } - } -#else - public static BufferAccess ToOpenGL(this MapMode mapMode) - { - switch (mapMode) - { - case MapMode.Read: - return BufferAccess.ReadOnly; - case MapMode.Write: - case MapMode.WriteDiscard: - case MapMode.WriteNoOverwrite: - return BufferAccess.WriteOnly; - case MapMode.ReadWrite: - return BufferAccess.ReadWrite; - default: - throw new ArgumentOutOfRangeException("mapMode"); - } - } -#endif - - public static TextureWrapMode ToOpenGL(this TextureAddressMode addressMode) - { - switch (addressMode) - { - case TextureAddressMode.Border: -#if !XENKO_GRAPHICS_API_OPENGLES - return TextureWrapMode.ClampToBorder; -#endif - case TextureAddressMode.Clamp: - return TextureWrapMode.ClampToEdge; - case TextureAddressMode.Mirror: -#if XENKO_GRAPHICS_API_OPENGLES - return (TextureWrapMode)EsVersion20.MirroredRepeat; -#else - return TextureWrapMode.MirroredRepeat; -#endif - case TextureAddressMode.Wrap: - return TextureWrapMode.Repeat; - default: - throw new NotImplementedException(); - } - } - - public static DepthFunction ToOpenGLDepthFunction(this CompareFunction function) - { - switch (function) - { - case CompareFunction.Always: - return DepthFunction.Always; - case CompareFunction.Equal: - return DepthFunction.Equal; - case CompareFunction.GreaterEqual: - return DepthFunction.Gequal; - case CompareFunction.Greater: - return DepthFunction.Greater; - case CompareFunction.LessEqual: - return DepthFunction.Lequal; - case CompareFunction.Less: - return DepthFunction.Less; - case CompareFunction.Never: - return DepthFunction.Never; - case CompareFunction.NotEqual: - return DepthFunction.Notequal; - default: - throw new NotImplementedException(); - } - } - - public static StencilFunction ToOpenGLStencilFunction(this CompareFunction function) - { - switch (function) - { - case CompareFunction.Always: - return StencilFunction.Always; - case CompareFunction.Equal: - return StencilFunction.Equal; - case CompareFunction.GreaterEqual: - return StencilFunction.Gequal; - case CompareFunction.Greater: - return StencilFunction.Greater; - case CompareFunction.LessEqual: - return StencilFunction.Lequal; - case CompareFunction.Less: - return StencilFunction.Less; - case CompareFunction.Never: - return StencilFunction.Never; - case CompareFunction.NotEqual: - return StencilFunction.Notequal; - default: - throw new NotImplementedException(); - } - } - - public static StencilOp ToOpenGL(this StencilOperation operation) - { - switch (operation) - { - case StencilOperation.Keep: - return StencilOp.Keep; - case StencilOperation.Zero: - return StencilOp.Zero; - case StencilOperation.Replace: - return StencilOp.Replace; - case StencilOperation.IncrementSaturation: - return StencilOp.Incr; - case StencilOperation.DecrementSaturation: - return StencilOp.Decr; - case StencilOperation.Invert: - return StencilOp.Invert; - case StencilOperation.Increment: - return StencilOp.IncrWrap; - case StencilOperation.Decrement: - return StencilOp.DecrWrap; - default: - throw new ArgumentOutOfRangeException("operation"); - } - } - - public static void ConvertPixelFormat(GraphicsDevice graphicsDevice, ref PixelFormat inputFormat, out PixelInternalFormat internalFormat, out PixelFormatGl format, out PixelType type, - out int pixelSize, out bool compressed) - { - compressed = false; - -#if XENKO_GRAPHICS_API_OPENGLES - // check formats more carefully if the device is initialized with OpenGL ES 2 - if (graphicsDevice.currentVersion < 300) - { - switch (inputFormat) - { - case PixelFormat.R16_Float: - case PixelFormat.R16G16_Float: - if (!graphicsDevice.HasTextureRG || !graphicsDevice.HasTextureHalf) - goto unsupported; - break; - case PixelFormat.R16G16B16A16_Float: - if (!graphicsDevice.HasTextureHalf) - goto unsupported; - break; - case PixelFormat.R16_UInt: - case PixelFormat.R16_SInt: - case PixelFormat.R16G16_UInt: - case PixelFormat.R16G16_SInt: - case PixelFormat.R16G16B16A16_UInt: - case PixelFormat.R16G16B16A16_SInt: - goto unsupported; - case PixelFormat.R32_Float: - case PixelFormat.R32G32_Float: - case PixelFormat.R32G32B32_Float: - if (!graphicsDevice.HasTextureRG || !graphicsDevice.HasTextureFloat) - goto unsupported; - break; - case PixelFormat.R32G32B32A32_Float: - if (!graphicsDevice.HasTextureFloat) - goto unsupported; - break; - case PixelFormat.R32_UInt: - case PixelFormat.R32_SInt: - case PixelFormat.R32G32_UInt: - case PixelFormat.R32G32_SInt: - case PixelFormat.R32G32B32_UInt: - case PixelFormat.R32G32B32_SInt: - case PixelFormat.R32G32B32A32_UInt: - case PixelFormat.R32G32B32A32_SInt: - goto unsupported; - case PixelFormat.D32_Float: - goto unsupported; - unsupported: - throw new NotSupportedException($"Texture format {inputFormat} not supported with OpenGL ES 2.0"); - - // NOTE: We always allow PixelFormat.D24_UNorm_S8_UInt. - // If it is not supported we will fall back to separate D24/D16 and S8 resources when creating a texture. - } - } -#endif - - // If the Device doesn't support SRGB, we remap automatically the format to non-srgb - if (!graphicsDevice.Features.HasSRgb) - { - switch (inputFormat) - { - case PixelFormat.PVRTC_2bpp_RGB_SRgb: - inputFormat = PixelFormat.PVRTC_2bpp_RGB; - break; - case PixelFormat.PVRTC_2bpp_RGBA_SRgb: - inputFormat = PixelFormat.PVRTC_2bpp_RGBA; - break; - case PixelFormat.PVRTC_4bpp_RGB_SRgb: - inputFormat = PixelFormat.PVRTC_4bpp_RGB; - break; - case PixelFormat.PVRTC_4bpp_RGBA_SRgb: - inputFormat = PixelFormat.PVRTC_4bpp_RGBA; - break; - case PixelFormat.ETC2_RGB_SRgb: - inputFormat = PixelFormat.ETC2_RGB; - break; - case PixelFormat.ETC2_RGBA_SRgb: - inputFormat = PixelFormat.ETC2_RGBA; - break; - case PixelFormat.R8G8B8A8_UNorm_SRgb: - inputFormat = PixelFormat.R8G8B8A8_UNorm; - break; - case PixelFormat.B8G8R8A8_UNorm_SRgb: - inputFormat = PixelFormat.B8G8R8A8_UNorm; - break; - } - } - - switch (inputFormat) - { - case PixelFormat.A8_UNorm: - internalFormat = PixelInternalFormat.Alpha; - format = PixelFormatGl.Alpha; - type = PixelType.UnsignedByte; - pixelSize = 1; - break; - case PixelFormat.R8_UNorm: -#if XENKO_GRAPHICS_API_OPENGLES - if (!graphicsDevice.HasTextureRG && graphicsDevice.currentVersion < 300) - { - internalFormat = PixelInternalFormat.Luminance; - format = PixelFormatGl.Luminance; - } - else -#endif - { - internalFormat = PixelInternalFormat.R8; - format = PixelFormatGl.Red; - } - type = PixelType.UnsignedByte; - pixelSize = 1; - break; - case PixelFormat.R8G8B8A8_UNorm: - internalFormat = PixelInternalFormat.Rgba; - format = PixelFormatGl.Rgba; - type = PixelType.UnsignedByte; - pixelSize = 4; - break; - case PixelFormat.B8G8R8A8_UNorm: -#if XENKO_GRAPHICS_API_OPENGLES - if (!graphicsDevice.HasExtTextureFormatBGRA8888) - throw new NotSupportedException(); - - // It seems iOS and Android expects different things -#if XENKO_PLATFORM_IOS - internalFormat = PixelInternalFormat.Rgba; -#else - internalFormat = (PixelInternalFormat)ExtTextureFormatBgra8888.BgraExt; -#endif - format = (PixelFormatGl)ExtTextureFormatBgra8888.BgraExt; -#else - internalFormat = PixelInternalFormat.Rgba; - format = PixelFormatGl.Bgra; -#endif - type = PixelType.UnsignedByte; - pixelSize = 4; - break; - case PixelFormat.R8G8B8A8_UNorm_SRgb: - internalFormat = PixelInternalFormat.Srgb8Alpha8; - format = PixelFormatGl.Rgba; - type = PixelType.UnsignedByte; - pixelSize = 4; - break; -#if XENKO_GRAPHICS_API_OPENGLCORE - case PixelFormat.B8G8R8A8_UNorm_SRgb: - // TODO: Check on iOS/Android and OpenGL 3 - internalFormat = PixelInternalFormat.Srgb8Alpha8; - format = PixelFormatGl.Bgra; - type = PixelType.UnsignedByte; - pixelSize = 4; - break; - case PixelFormat.BC1_UNorm: - if (!graphicsDevice.HasDXT) - throw new NotSupportedException(); - internalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt1Ext; - format = (PixelFormatGl)PixelInternalFormat.CompressedRgbaS3tcDxt1Ext; - pixelSize = 4; - type = PixelType.UnsignedByte; - compressed = true; - break; - case PixelFormat.BC1_UNorm_SRgb: - if (!graphicsDevice.HasDXT) - throw new NotSupportedException(); - internalFormat = PixelInternalFormat.CompressedSrgbAlphaS3tcDxt1Ext; - format = (PixelFormatGl)PixelInternalFormat.CompressedSrgbAlphaS3tcDxt1Ext; - pixelSize = 4; - type = PixelType.UnsignedByte; - compressed = true; - break; - case PixelFormat.BC2_UNorm: - if (!graphicsDevice.HasDXT) - throw new NotSupportedException(); - internalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt3Ext; - format = (PixelFormatGl)PixelInternalFormat.CompressedRgbaS3tcDxt3Ext; - pixelSize = 4; - type = PixelType.UnsignedByte; - compressed = true; - break; - case PixelFormat.BC2_UNorm_SRgb: - if (!graphicsDevice.HasDXT) - throw new NotSupportedException(); - internalFormat = PixelInternalFormat.CompressedSrgbAlphaS3tcDxt3Ext; - format = (PixelFormatGl)PixelInternalFormat.CompressedSrgbAlphaS3tcDxt3Ext; - pixelSize = 4; - type = PixelType.UnsignedByte; - compressed = true; - break; - case PixelFormat.BC3_UNorm: - if (!graphicsDevice.HasDXT) - throw new NotSupportedException(); - internalFormat = PixelInternalFormat.CompressedRgbaS3tcDxt5Ext; - format = (PixelFormatGl)PixelInternalFormat.CompressedRgbaS3tcDxt5Ext; - pixelSize = 4; - type = PixelType.UnsignedByte; - compressed = true; - break; - case PixelFormat.BC3_UNorm_SRgb: - if (!graphicsDevice.HasDXT) - throw new NotSupportedException(); - internalFormat = PixelInternalFormat.CompressedSrgbAlphaS3tcDxt5Ext; - format = (PixelFormatGl)PixelInternalFormat.CompressedSrgbAlphaS3tcDxt5Ext; - pixelSize = 4; - type = PixelType.UnsignedByte; - compressed = true; - break; -#endif - case PixelFormat.R16_SInt: - internalFormat = PixelInternalFormat.R16i; - format = PixelFormatGl.RedInteger; - type = PixelType.Short; - pixelSize = 2; - break; - case PixelFormat.R16_UInt: - internalFormat = PixelInternalFormat.R16ui; - format = PixelFormatGl.RedInteger; - type = PixelType.UnsignedShort; - pixelSize = 2; - break; - case PixelFormat.R16_Float: - internalFormat = PixelInternalFormat.R16f; - format = PixelFormatGl.Red; - type = PixelType.HalfFloat; - pixelSize = 2; - break; - case PixelFormat.R16G16_SInt: - internalFormat = PixelInternalFormat.Rg16i; - format = PixelFormatGl.RgInteger; - type = PixelType.Short; - pixelSize = 4; - break; - case PixelFormat.R16G16_UInt: - internalFormat = PixelInternalFormat.Rg16ui; - format = PixelFormatGl.RgInteger; - type = PixelType.UnsignedShort; - pixelSize = 4; - break; - case PixelFormat.R16G16_Float: - internalFormat = PixelInternalFormat.Rg16f; - format = PixelFormatGl.Rg; - type = PixelType.HalfFloat; - pixelSize = 4; - break; - case PixelFormat.R16G16B16A16_SInt: - internalFormat = PixelInternalFormat.Rgba16i; - format = PixelFormatGl.RgbaInteger; - type = PixelType.Short; - pixelSize = 8; - break; - case PixelFormat.R16G16B16A16_UInt: - internalFormat = PixelInternalFormat.Rgba16ui; - format = PixelFormatGl.RgbaInteger; - type = PixelType.UnsignedShort; - pixelSize = 8; - break; - case PixelFormat.R16G16B16A16_Float: - internalFormat = PixelInternalFormat.Rgba16f; - format = PixelFormatGl.Rgba; - type = PixelType.HalfFloat; - pixelSize = 8; - break; - case PixelFormat.R10G10B10A2_UNorm: - internalFormat = PixelInternalFormat.Rgb10A2; - format = PixelFormatGl.Rgba; - type = PixelType.UnsignedInt1010102; - pixelSize = 4; - break; - case PixelFormat.R11G11B10_Float: - internalFormat = PixelInternalFormat.R11fG11fB10f; - format = PixelFormatGl.Rgb; - type = PixelType.HalfFloat; - pixelSize = 4; - break; - case PixelFormat.R32_SInt: - internalFormat = PixelInternalFormat.R32i; - format = PixelFormatGl.RedInteger; - type = PixelType.Int; - pixelSize = 4; - break; - case PixelFormat.R32_UInt: - internalFormat = PixelInternalFormat.R32ui; - format = PixelFormatGl.RedInteger; - type = PixelType.UnsignedInt; - pixelSize = 4; - break; - case PixelFormat.R32_Float: - internalFormat = PixelInternalFormat.R32f; - format = PixelFormatGl.Red; - type = PixelType.Float; - pixelSize = 4; - break; - case PixelFormat.R32G32_SInt: - internalFormat = PixelInternalFormat.Rg32i; - format = PixelFormatGl.RgInteger; - type = PixelType.Int; - pixelSize = 8; - break; - case PixelFormat.R32G32_UInt: - internalFormat = PixelInternalFormat.Rg32ui; - format = PixelFormatGl.RgInteger; - type = PixelType.UnsignedInt; - pixelSize = 8; - break; - case PixelFormat.R32G32_Float: - internalFormat = PixelInternalFormat.Rg32f; - format = PixelFormatGl.Rg; - type = PixelType.Float; - pixelSize = 8; - break; - case PixelFormat.R32G32B32_SInt: - internalFormat = PixelInternalFormat.Rgb32i; - format = PixelFormatGl.RgbInteger; - type = PixelType.Int; - pixelSize = 12; - break; - case PixelFormat.R32G32B32_UInt: - internalFormat = PixelInternalFormat.Rgb32ui; - format = PixelFormatGl.RgbInteger; - type = PixelType.UnsignedInt; - pixelSize = 12; - break; - case PixelFormat.R32G32B32_Float: - internalFormat = PixelInternalFormat.Rgb32f; - format = PixelFormatGl.Rgb; - type = PixelType.Float; - pixelSize = 12; - break; - case PixelFormat.R32G32B32A32_SInt: - internalFormat = PixelInternalFormat.Rgba32i; - format = PixelFormatGl.RgbaInteger; - type = PixelType.Int; - pixelSize = 16; - break; - case PixelFormat.R32G32B32A32_UInt: - internalFormat = PixelInternalFormat.Rgba32ui; - format = PixelFormatGl.RgbaInteger; - type = PixelType.UnsignedInt; - pixelSize = 16; - break; - case PixelFormat.R32G32B32A32_Float: - internalFormat = PixelInternalFormat.Rgba32f; - format = PixelFormatGl.Rgba; - type = PixelType.Float; - pixelSize = 16; - break; - case PixelFormat.D16_UNorm: - internalFormat = PixelInternalFormat.DepthComponent16; - format = PixelFormatGl.DepthComponent; - type = PixelType.UnsignedShort; - pixelSize = 2; - break; - case PixelFormat.D24_UNorm_S8_UInt: - internalFormat = PixelInternalFormat.Depth24Stencil8; - format = PixelFormatGl.DepthStencil; - type = PixelType.UnsignedInt248; - pixelSize = 4; - break; - // TODO: Temporary depth format (need to decide relation between RenderTarget1D and Texture) - case PixelFormat.D32_Float: - internalFormat = PixelInternalFormat.DepthComponent32f; - format = PixelFormatGl.DepthComponent; - type = PixelType.Float; - pixelSize = 4; - break; -#if XENKO_PLATFORM_IOS - case PixelFormat.PVRTC_4bpp_RGB: - internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbPvrtc4Bppv1Img; - format = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbPvrtc4Bppv1Img; - compressed = true; - pixelSize = 4; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_2bpp_RGB: - internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbPvrtc2Bppv1Img; - format = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbPvrtc2Bppv1Img; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_4bpp_RGBA: - internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc4Bppv1Img; - format = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc4Bppv1Img; - compressed = true; - pixelSize = 4; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_2bpp_RGBA: - internalFormat = (PixelInternalFormat)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc2Bppv1Img; - format = (PixelFormatGl)ImgTextureCompressionPvrtc.CompressedRgbaPvrtc2Bppv1Img; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_4bpp_RGB_SRgb: - internalFormat = (PixelInternalFormat)ExtPvrtcSrgb.CompressedSrgbPvrtc4Bppv1Ext; - format = (PixelFormatGl)ExtPvrtcSrgb.CompressedSrgbPvrtc4Bppv1Ext; - compressed = true; - pixelSize = 4; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_2bpp_RGB_SRgb: - internalFormat = (PixelInternalFormat)ExtPvrtcSrgb.CompressedSrgbPvrtc2Bppv1Ext; - format = (PixelFormatGl)ExtPvrtcSrgb.CompressedSrgbPvrtc2Bppv1Ext; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_4bpp_RGBA_SRgb: - internalFormat = (PixelInternalFormat)ExtPvrtcSrgb.CompressedSrgbAlphaPvrtc4Bppv1Ext; - format = (PixelFormatGl)ExtPvrtcSrgb.CompressedSrgbAlphaPvrtc4Bppv1Ext; - compressed = true; - pixelSize = 4; - type = PixelType.UnsignedByte; - break; - case PixelFormat.PVRTC_2bpp_RGBA_SRgb: - internalFormat = (PixelInternalFormat)ExtPvrtcSrgb.CompressedSrgbAlphaPvrtc2Bppv1Ext; - format = (PixelFormatGl)ExtPvrtcSrgb.CompressedSrgbAlphaPvrtc2Bppv1Ext; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; -#elif XENKO_GRAPHICS_API_OPENGLES - // Desktop OpenGLES - case PixelFormat.ETC1: - // TODO: Runtime check for extension? - internalFormat = (PixelInternalFormat)OesCompressedEtc1Rgb8Texture.Etc1Rgb8Oes; - format = (PixelFormatGl)OesCompressedEtc1Rgb8Texture.Etc1Rgb8Oes; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; - case PixelFormat.ETC2_RGBA: - internalFormat = (PixelInternalFormat)CompressedInternalFormat.CompressedRgba8Etc2Eac; - format = (PixelFormatGl)CompressedInternalFormat.CompressedRgba8Etc2Eac; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; - case PixelFormat.ETC2_RGBA_SRgb: - internalFormat = (PixelInternalFormat)CompressedInternalFormat.CompressedSrgb8Alpha8Etc2Eac; - format = (PixelFormatGl)CompressedInternalFormat.CompressedSrgb8Alpha8Etc2Eac; - compressed = true; - pixelSize = 2; - type = PixelType.UnsignedByte; - break; -#endif - case PixelFormat.None: // TODO: remove this - this is only for buffers used in compute shaders - internalFormat = PixelInternalFormat.Rgba; - format = PixelFormatGl.Red; - type = PixelType.UnsignedByte; - pixelSize = 1; - break; - default: - throw new InvalidOperationException("Unsupported texture format: " + inputFormat); - } - -#if XENKO_GRAPHICS_API_OPENGLES - // override some formats for ES2.0 - if (graphicsDevice.currentVersion < 300) - { - switch (inputFormat) - { - case PixelFormat.R8G8B8A8_UNorm_SRgb: - // HasSRgb was true because we have GL_EXT_sRGB - // Note: Qualcomm Adreno 4xx fails to use GL_EXT_sRGB with FBO, - // but they will report a currentVersion >= 300 (ES 3.0) anyway - internalFormat = (PixelInternalFormat)ExtSrgb.SrgbAlphaExt; - format = (PixelFormatGl)ExtSrgb.SrgbAlphaExt; - break; - case PixelFormat.R8_UNorm: - case PixelFormat.R8_SNorm: - case PixelFormat.R8_UInt: - case PixelFormat.R8_SInt: - case PixelFormat.R16_Float: - case PixelFormat.R16_UNorm: - case PixelFormat.R16_SNorm: - case PixelFormat.R16_UInt: - case PixelFormat.R16_SInt: - case PixelFormat.R32_Float: - case PixelFormat.R32_UInt: - case PixelFormat.R32_SInt: - if (inputFormat == PixelFormat.R16_Float) - type = (PixelType)OesTextureHalfFloat.HalfFloatOes; - if (graphicsDevice.HasTextureRG) - internalFormat = (PixelInternalFormat)ExtTextureRg.RedExt; - break; - case PixelFormat.R16G16_Float: - case PixelFormat.R16G16_UNorm: - case PixelFormat.R16G16_SNorm: - case PixelFormat.R16G16_UInt: - case PixelFormat.R16G16_SInt: - case PixelFormat.R32G32_Float: - case PixelFormat.R32G32_UInt: - case PixelFormat.R32G32_SInt: - if (inputFormat == PixelFormat.R16G16_Float) - type = (PixelType)OesTextureHalfFloat.HalfFloatOes; - if (graphicsDevice.HasTextureRG) - internalFormat = (PixelInternalFormat)ExtTextureRg.RgExt; - break; - case PixelFormat.R32G32B32_Float: - case PixelFormat.R32G32B32_UInt: - case PixelFormat.R32G32B32_SInt: - internalFormat = PixelInternalFormat.Rgb; - break; - case PixelFormat.R16G16B16A16_Float: - case PixelFormat.R32G32B32A32_Float: - case PixelFormat.R16G16B16A16_UInt: - case PixelFormat.R32G32B32A32_UInt: - case PixelFormat.R16G16B16A16_SInt: - case PixelFormat.R32G32B32A32_SInt: - if (inputFormat == PixelFormat.R16G16B16A16_Float) - type = (PixelType)OesTextureHalfFloat.HalfFloatOes; - internalFormat = PixelInternalFormat.Rgba; - break; - } - } -#endif - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/OpenGLShaderBytecodeData.cs b/sources/engine/Xenko.Graphics/OpenGL/OpenGLShaderBytecodeData.cs deleted file mode 100644 index 57c0ef488e..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/OpenGLShaderBytecodeData.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; -using Xenko.Core.Serialization; - -namespace Xenko.Graphics -{ - internal struct OpenGLShaderBytecodeData - { - public bool IsBinary; - - public string Profile; - public string EntryPoint; - public string Source; - - public int BinaryFormat; - public byte[] Binary; - - public void Serialize(SerializationStream stream, ArchiveMode mode) - { - // Check version number (should be 0 for now, for future use) - if (mode == ArchiveMode.Serialize) - { - stream.Write(0); - } - else if (mode == ArchiveMode.Deserialize) - { - if (stream.ReadInt32() != 0) - throw new InvalidOperationException("Unexpected version number."); - } - - // Serialize content - stream.Serialize(ref IsBinary); - if (IsBinary) - { - stream.Serialize(ref BinaryFormat); - stream.Serialize(ref Binary, mode); - } - else - { - stream.Serialize(ref Profile); - stream.Serialize(ref EntryPoint); - stream.Serialize(ref Source); - } - } - } -} diff --git a/sources/engine/Xenko.Graphics/OpenGL/OpenGLUtils.cs b/sources/engine/Xenko.Graphics/OpenGL/OpenGLUtils.cs deleted file mode 100644 index 2c076c621d..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/OpenGLUtils.cs +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using OpenTK.Graphics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics.OpenGL -{ - /// - /// Converts between feature level and opengl versions - /// - internal static class OpenGLUtils - { -#if XENKO_GRAPHICS_API_OPENGLES - public static IEnumerable GetGLVersions(GraphicsProfile[] graphicsProfiles) - { - if (graphicsProfiles != null && graphicsProfiles.Length > 0) - { - foreach (var profile in graphicsProfiles) - { - if (profile >= GraphicsProfile.Level_10_0) - yield return 3; - else - yield return 2; - } - } - else - { - yield return 2; - } - } - - public static void GetGLVersion(GraphicsProfile graphicsProfile, out int version) - { - switch (graphicsProfile) - { - case GraphicsProfile.Level_9_1: - case GraphicsProfile.Level_9_2: - case GraphicsProfile.Level_9_3: - version = 200; - return; - case GraphicsProfile.Level_10_0: - case GraphicsProfile.Level_10_1: - version = 300; - return; - case GraphicsProfile.Level_11_0: - case GraphicsProfile.Level_11_1: - case GraphicsProfile.Level_11_2: - version = 310; - return; - default: - throw new ArgumentOutOfRangeException("graphicsProfile"); - } - } - - public static GraphicsProfile GetFeatureLevel(int version) - { - if (version >= 300) - { - if (version >= 310) - return GraphicsProfile.Level_11_0; // missing tessellation and geometry shaders - return GraphicsProfile.Level_10_0; - } - return GraphicsProfile.Level_9_3; - } -#else - public static void GetGLVersion(GraphicsProfile graphicsProfile, out int version) - { - switch (graphicsProfile) - { - case GraphicsProfile.Level_9_1: - case GraphicsProfile.Level_9_2: - case GraphicsProfile.Level_9_3: - version = 330; - return; - case GraphicsProfile.Level_10_0: - case GraphicsProfile.Level_10_1: - version = 410; - return; - case GraphicsProfile.Level_11_0: - case GraphicsProfile.Level_11_1: - case GraphicsProfile.Level_11_2: - version = 440; - return; - default: - throw new ArgumentOutOfRangeException("graphicsProfile"); - } - } - - public static GraphicsProfile GetFeatureLevel(int version) - { - if (version >= 400) - { - if (version >= 440) - return GraphicsProfile.Level_11_0; - if (version >= 410) - return GraphicsProfile.Level_10_0; - } - return GraphicsProfile.Level_9_1; - } -#endif -#if XENKO_PLATFORM_ANDROID - public static GLVersion GetGLVersion(GraphicsProfile graphicsProfile) - { - switch (graphicsProfile) - { - case GraphicsProfile.Level_9_1: - case GraphicsProfile.Level_9_2: - case GraphicsProfile.Level_9_3: - return GLVersion.ES2; - case GraphicsProfile.Level_10_0: - case GraphicsProfile.Level_10_1: - case GraphicsProfile.Level_11_0: - case GraphicsProfile.Level_11_1: - case GraphicsProfile.Level_11_2: - return GLVersion.ES3; - default: - throw new ArgumentOutOfRangeException("graphicsProfile"); - } - } -#endif - - private static readonly Regex MatchOpenGLVersion = new Regex(@"OpenGL\s+ES\s+([0-9\.]+)"); - - /// - /// Gets current GL version. - /// - /// OpenGL version encoded as major * 100 + minor * 10. - /// - public static bool GetCurrentGLVersion(out int version) - { - version = 0; - -#if XENKO_GRAPHICS_API_OPENGLES - var versionVendorText = GL.GetString(StringName.Version); - var match = MatchOpenGLVersion.Match(versionVendorText); - if (!match.Success) - return false; - - var versionText = match.Groups[1].Value; - var dotIndex = versionText.IndexOf("."); - - int versionMajor = 0; - int versionMinor = 0; - if (!int.TryParse(dotIndex != -1 ? versionText.Substring(0, dotIndex) : versionText, out versionMajor)) - { - return false; - } - - if (dotIndex == -1) - { - version = versionMajor * 100; - return true; - } - if (!int.TryParse(versionText.Substring(dotIndex + 1), out versionMinor)) - return false; - - version = versionMajor * 100 + versionMinor * 10; - return true; -#else - int versionMajor = 0; - int versionMinor = 0; - - GL.GetInteger(GetPName.MajorVersion, out versionMajor); - GL.GetInteger(GetPName.MinorVersion, out versionMinor); - - version = versionMajor * 100 + versionMinor * 10; - return true; -#endif - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/PipelineState.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/PipelineState.OpenGL.cs deleted file mode 100644 index eb00d75570..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/PipelineState.OpenGL.cs +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Collections.Generic; -using Xenko.Core; -using Xenko.Core.Storage; -using Xenko.Shaders; -using Xenko.Core.Extensions; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using PrimitiveTypeGl = OpenTK.Graphics.ES30.PrimitiveType; -#else -using OpenTK.Graphics.OpenGL; -using PrimitiveTypeGl = OpenTK.Graphics.OpenGL.PrimitiveType; -#endif - -namespace Xenko.Graphics -{ - public partial class PipelineState - { - internal BlendState BlendState; - internal DepthStencilState DepthStencilState; - - internal RasterizerState RasterizerState; - - internal EffectProgram EffectProgram; - - internal PrimitiveTypeGl PrimitiveType; - internal VertexAttrib[] VertexAttribs; - internal ResourceBinder ResourceBinder; - internal bool ready; - - public PIPELINE_STATE CurrentState() { - return ready ? PIPELINE_STATE.READY : PIPELINE_STATE.LOADING; - } - - internal PipelineState(GraphicsDevice graphicsDevice) : base(graphicsDevice) { - // just return a memory address to Prepare later - } - - internal void Prepare(PipelineStateDescription pipelineStateDescription) - { - // First time, build caches - var pipelineStateCache = GetPipelineStateCache(); - - var depthClampEmulation = !pipelineStateDescription.RasterizerState.DepthClipEnable && !GraphicsDevice.HasDepthClamp; -#if XENKO_GRAPHICS_API_OPENGLES - // Depth Clamp can't be emulated on OpenGL ES 2 (TODO: warning?) - if (GraphicsDevice.IsOpenGLES2) - depthClampEmulation = false; -#endif - - // Store states - BlendState = new BlendState(pipelineStateDescription.BlendState, pipelineStateDescription.Output.RenderTargetCount > 0); - RasterizerState = new RasterizerState(pipelineStateDescription.RasterizerState); - DepthStencilState = new DepthStencilState(pipelineStateDescription.DepthStencilState, pipelineStateDescription.Output.DepthStencilFormat != PixelFormat.None); - - PrimitiveType = pipelineStateDescription.PrimitiveType.ToOpenGL(); - - // Compile effect - var effectBytecode = pipelineStateDescription.EffectBytecode; - EffectProgram = effectBytecode != null ? pipelineStateCache.EffectProgramCache.Instantiate(Tuple.Create(effectBytecode, depthClampEmulation)) : null; - - var rootSignature = pipelineStateDescription.RootSignature; - if (rootSignature != null && effectBytecode != null) - ResourceBinder.Compile(GraphicsDevice, rootSignature.EffectDescriptorSetReflection, effectBytecode); - - // Vertex attributes - if (pipelineStateDescription.InputElements != null) - { - var vertexAttribs = new List(); - foreach (var inputElement in pipelineStateDescription.InputElements) - { - // Query attribute name from effect - var attributeName = "a_" + inputElement.SemanticName + inputElement.SemanticIndex; - int attributeIndex; - if (!EffectProgram.Attributes.TryGetValue(attributeName, out attributeIndex)) - continue; - - var vertexElementFormat = VertexAttrib.ConvertVertexElementFormat(inputElement.Format); - vertexAttribs.Add(new VertexAttrib( - inputElement.InputSlot, - attributeIndex, - vertexElementFormat.Size, - vertexElementFormat.Type, - vertexElementFormat.Normalized, - inputElement.AlignedByteOffset)); - } - - VertexAttribs = pipelineStateCache.VertexAttribsCache.Instantiate(vertexAttribs.ToArray()); - } - - ready = true; - } - - internal void Apply(CommandList commandList, PipelineState previousPipeline) - { - // Apply states - if (BlendState != previousPipeline.BlendState || commandList.NewBlendFactor != commandList.BoundBlendFactor) - BlendState.Apply(commandList, previousPipeline.BlendState); - if (RasterizerState != previousPipeline.RasterizerState) - RasterizerState.Apply(commandList); - if (DepthStencilState != previousPipeline.DepthStencilState || commandList.NewStencilReference != commandList.BoundStencilReference) - DepthStencilState.Apply(commandList); - } - - protected internal override void OnDestroyed() - { - var pipelineStateCache = GetPipelineStateCache(); - - if (EffectProgram != null) - pipelineStateCache.EffectProgramCache.Release(EffectProgram); - if (VertexAttribs != null) - pipelineStateCache.VertexAttribsCache.Release(VertexAttribs); - - base.OnDestroyed(); - } - - struct VertexAttribsKey - { - public VertexAttrib[] Attribs; - public int Hash; - - public VertexAttribsKey(VertexAttrib[] attribs) - { - Attribs = attribs; - Hash = ArrayExtensions.ComputeHash(attribs); - } - - public bool Equals(VertexAttribsKey other) - { - return Hash == other.Hash && ArrayExtensions.ArraysEqual(Attribs, other.Attribs); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is VertexAttribsKey && Equals((VertexAttribsKey)obj); - } - - public override int GetHashCode() - { - return Hash; - } - - public static bool operator ==(VertexAttribsKey left, VertexAttribsKey right) - { - return left.Equals(right); - } - - public static bool operator !=(VertexAttribsKey left, VertexAttribsKey right) - { - return !left.Equals(right); - } - } - - // Small helper to cache SharpDX graphics objects - class GraphicsCache - { - private object lockObject = new object(); - - // Store instantiated objects - private readonly Dictionary storage = new Dictionary(); - // Used for quick removal - private readonly Dictionary reverse = new Dictionary(); - - private readonly Dictionary counter = new Dictionary(); - - private readonly Func computeKey; - private readonly Func computeValue; - - public GraphicsCache(Func computeKey, Func computeValue) - { - this.computeKey = computeKey; - this.computeValue = computeValue; - } - - public TValue Instantiate(TSource source) - { - lock (lockObject) - { - TValue value; - var key = computeKey(source); - if (!storage.TryGetValue(key, out value)) - { - value = computeValue(source); - storage.Add(key, value); - reverse.Add(value, key); - counter.Add(value, 1); - } - else - { - counter[value] = counter[value] + 1; - } - - return value; - } - } - - public void Release(TValue value) - { - // Should we remove it from the cache? - lock (lockObject) - { - int refCount; - if (!counter.TryGetValue(value, out refCount)) - return; - - counter[value] = --refCount; - if (refCount == 0) - { - counter.Remove(value); - reverse.Remove(value); - TKey key; - if (reverse.TryGetValue(value, out key)) - { - storage.Remove(key); - } - - var graphicsResource = value as IReferencable; - graphicsResource?.Release(); - } - } - } - - public void Dispose() - { - lock (lockObject) - { - // Release everything - foreach (var entry in reverse) - { - var graphicsResource = entry.Key as IReferencable; - graphicsResource?.Release(); - } - - reverse.Clear(); - storage.Clear(); - counter.Clear(); - } - } - } - - private DevicePipelineStateCache GetPipelineStateCache() - { - return GraphicsDevice.GetOrCreateSharedData(GraphicsDeviceSharedDataType.PerDevice, typeof(DevicePipelineStateCache), device => new DevicePipelineStateCache(device)); - } - - // Caches - private class DevicePipelineStateCache : IDisposable - { - public readonly GraphicsCache, EffectBytecode, EffectProgram> EffectProgramCache; - public readonly GraphicsCache VertexAttribsCache; - - public DevicePipelineStateCache(GraphicsDevice graphicsDevice) - { - EffectProgramCache = new GraphicsCache, EffectBytecode, EffectProgram>(source => source.Item1, source => new EffectProgram(graphicsDevice, source.Item1, source.Item2)); - VertexAttribsCache = new GraphicsCache(source => new VertexAttribsKey(source), source => source); - } - - public void Dispose() - { - EffectProgramCache.Dispose(); - VertexAttribsCache.Dispose(); - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/QueryPool.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/QueryPool.OpenGL.cs deleted file mode 100644 index 729d921782..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/QueryPool.OpenGL.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL - -using System; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - public partial class QueryPool - { - internal int[] NativeQueries; - - public bool TryGetData(long[] dataArray) - { -#if XENKO_PLATFORM_IOS - return false; -#else - for (var index = 0; index < NativeQueries.Length; index++) - { -#if XENKO_GRAPHICS_API_OPENGLES - GL.Ext.GetQueryObject(NativeQueries[index], GetQueryObjectParam.QueryResultAvailable, out long availability); -#else - GL.GetQueryObject(NativeQueries[index], GetQueryObjectParam.QueryResultAvailable, out long availability); -#endif - if (availability == 0) - return false; - -#if XENKO_GRAPHICS_API_OPENGLES - GL.Ext.GetQueryObject(NativeQueries[index], GetQueryObjectParam.QueryResult, out dataArray[index]); -#else - GL.GetQueryObject(NativeQueries[index], GetQueryObjectParam.QueryResult, out dataArray[index]); -#endif - } - - return true; -#endif - } - - /// - protected internal override void OnDestroyed() - { -#if !XENKO_PLATFORM_IOS - GL.DeleteQueries(QueryCount, NativeQueries); - NativeQueries = null; -#endif - base.OnDestroyed(); - } - - private void Recreate() - { - switch (QueryType) - { - case QueryType.Timestamp: - break; - - default: - throw new NotImplementedException(); - } - - NativeQueries = new int[QueryCount]; -#if !XENKO_PLATFORM_IOS - GL.GenQueries(QueryCount, NativeQueries); -#endif - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/RasterizerState.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/RasterizerState.OpenGL.cs deleted file mode 100644 index 7fcd7c5412..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/RasterizerState.OpenGL.cs +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - struct RasterizerBoundState - { - public bool ScissorTestEnable; - - public bool DepthClamp; - - public bool NeedCulling; - public CullFaceMode CullMode; - public int DepthBias; - public float SlopeScaleDepthBias; - public FrontFaceDirection FrontFaceDirection; - -#if !XENKO_GRAPHICS_API_OPENGLES - public PolygonMode PolygonMode; -#endif - } - - class RasterizerState - { -#if XENKO_GRAPHICS_API_OPENGLES - private const EnableCap DepthClamp = (EnableCap)0x864F; -#else - private const EnableCap DepthClamp = (EnableCap)ArbDepthClamp.DepthClamp; -#endif - - RasterizerBoundState State; - - internal RasterizerState(RasterizerStateDescription rasterizerStateDescription) - { - State.ScissorTestEnable = rasterizerStateDescription.ScissorTestEnable; - - State.DepthClamp = !rasterizerStateDescription.DepthClipEnable; - - State.NeedCulling = rasterizerStateDescription.CullMode != CullMode.None; - State.CullMode = GetCullMode(rasterizerStateDescription.CullMode); - - State.FrontFaceDirection = - rasterizerStateDescription.FrontFaceCounterClockwise - ? FrontFaceDirection.Cw - : FrontFaceDirection.Ccw; - - State.DepthBias = rasterizerStateDescription.DepthBias; - State.SlopeScaleDepthBias = rasterizerStateDescription.SlopeScaleDepthBias; - -#if !XENKO_GRAPHICS_API_OPENGLES - State.PolygonMode = rasterizerStateDescription.FillMode == FillMode.Solid ? PolygonMode.Fill : PolygonMode.Line; -#endif - - // TODO: DepthBiasClamp and various other properties are not fully supported yet - if (rasterizerStateDescription.DepthBiasClamp != 0.0f) throw new NotSupportedException(); - } - - public void Apply(CommandList commandList) - { -#if !XENKO_GRAPHICS_API_OPENGLES - if (commandList.RasterizerBoundState.PolygonMode != State.PolygonMode) - { - commandList.RasterizerBoundState.PolygonMode = State.PolygonMode; - GL.PolygonMode(MaterialFace.FrontAndBack, State.PolygonMode); - } -#endif - - if (commandList.RasterizerBoundState.DepthBias != State.DepthBias || commandList.RasterizerBoundState.SlopeScaleDepthBias != State.SlopeScaleDepthBias) - { - commandList.RasterizerBoundState.DepthBias = State.DepthBias; - commandList.RasterizerBoundState.SlopeScaleDepthBias = State.SlopeScaleDepthBias; - GL.PolygonOffset(State.DepthBias, State.SlopeScaleDepthBias); - } - - if (commandList.RasterizerBoundState.FrontFaceDirection != State.FrontFaceDirection) - { - commandList.RasterizerBoundState.FrontFaceDirection = State.FrontFaceDirection; - GL.FrontFace(State.FrontFaceDirection); - } - - if (commandList.GraphicsDevice.HasDepthClamp) - { - if (commandList.RasterizerBoundState.DepthClamp != State.DepthClamp) - { - commandList.RasterizerBoundState.DepthClamp = State.DepthClamp; - if (State.DepthClamp) - GL.Enable(DepthClamp); - else - GL.Disable(DepthClamp); - } - } - - if (commandList.RasterizerBoundState.NeedCulling != State.NeedCulling) - { - commandList.RasterizerBoundState.NeedCulling = State.NeedCulling; - if (State.NeedCulling) - { - GL.Enable(EnableCap.CullFace); - } - else - { - GL.Disable(EnableCap.CullFace); - } - } - - if (commandList.RasterizerBoundState.CullMode != State.CullMode) - { - commandList.RasterizerBoundState.CullMode = State.CullMode; - GL.CullFace(State.CullMode); - } - - if (commandList.RasterizerBoundState.ScissorTestEnable != State.ScissorTestEnable) - { - commandList.RasterizerBoundState.ScissorTestEnable = State.ScissorTestEnable; - - if (State.ScissorTestEnable) - GL.Enable(EnableCap.ScissorTest); - else - GL.Disable(EnableCap.ScissorTest); - } - } - - private static CullFaceMode GetCullMode(CullMode cullMode) - { - switch (cullMode) - { - case CullMode.Front: - return CullFaceMode.Front; - case CullMode.Back: - return CullFaceMode.Back; - default: - return CullFaceMode.Back; // not used if CullMode.None - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/SamplerState.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/SamplerState.OpenGL.cs deleted file mode 100644 index 24dfaa820e..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/SamplerState.OpenGL.cs +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using Xenko.Core.Mathematics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using TextureCompareMode = OpenTK.Graphics.ES30.All; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - public partial class SamplerState - { - private const TextureFilter AnisotropicMask = TextureFilter.Anisotropic & ~TextureFilter.Linear; - private const TextureFilter ComparisonMask = TextureFilter.ComparisonLinear & ~TextureFilter.Linear; - - private TextureWrapMode textureWrapS; - private TextureWrapMode textureWrapT; - private TextureWrapMode textureWrapR; - - private TextureMinFilter minFilter; - private TextureMagFilter magFilter; -#if XENKO_GRAPHICS_API_OPENGLES - private TextureMinFilter minFilterNoMipmap; -#endif - - private int maxAnisotropy; - - private float[] borderColor; - - private DepthFunction compareFunc; - private TextureCompareMode compareMode; - - private SamplerState(GraphicsDevice device, SamplerStateDescription samplerStateDescription) : base(device) - { - Description = samplerStateDescription; - - textureWrapS = samplerStateDescription.AddressU.ToOpenGL(); - textureWrapT = samplerStateDescription.AddressV.ToOpenGL(); - textureWrapR = samplerStateDescription.AddressW.ToOpenGL(); - - compareMode = TextureCompareMode.None; - - // ComparisonPoint can act as a mask for Comparison filters (0x80) - if ((samplerStateDescription.Filter & ComparisonMask) != 0) - compareMode = TextureCompareMode.CompareRefToTexture; - - compareFunc = samplerStateDescription.CompareFunction.ToOpenGLDepthFunction(); - borderColor = samplerStateDescription.BorderColor.ToArray(); - // TODO: How to do MipLinear vs MipPoint? - switch (samplerStateDescription.Filter & ~(ComparisonMask | AnisotropicMask)) // Ignore comparison (128) and anisotropic (64) part - { - case TextureFilter.MinMagLinearMipPoint: - minFilter = TextureMinFilter.LinearMipmapNearest; - magFilter = TextureMagFilter.Linear; - break; - case TextureFilter.Linear: - minFilter = TextureMinFilter.LinearMipmapLinear; - magFilter = TextureMagFilter.Linear; - break; - case TextureFilter.MinPointMagMipLinear: - minFilter = TextureMinFilter.NearestMipmapLinear; - magFilter = TextureMagFilter.Linear; - break; - case TextureFilter.Point: - minFilter = TextureMinFilter.NearestMipmapNearest; - magFilter = TextureMagFilter.Nearest; - break; - case TextureFilter.MinPointMagLinearMipPoint: - minFilter = TextureMinFilter.NearestMipmapNearest; - magFilter = TextureMagFilter.Linear; - break; - case TextureFilter.MinLinearMagMipPoint: - minFilter = TextureMinFilter.LinearMipmapNearest; - magFilter = TextureMagFilter.Nearest; - break; - case TextureFilter.MinMagPointMipLinear: - minFilter = TextureMinFilter.NearestMipmapLinear; - magFilter = TextureMagFilter.Nearest; - break; - case TextureFilter.MinLinearMagPointMipLinear: - minFilter = TextureMinFilter.LinearMipmapLinear; - magFilter = TextureMagFilter.Nearest; - break; - default: - throw new NotImplementedException(); - } - - maxAnisotropy = ((samplerStateDescription.Filter & AnisotropicMask) != 0) ? Description.MaxAnisotropy : 1; - -#if XENKO_GRAPHICS_API_OPENGLES - // On OpenGL ES, we need to choose the appropriate min filter ourself if the texture doesn't contain mipmaps (done at PreDraw) - minFilterNoMipmap = minFilter; - if (minFilterNoMipmap == TextureMinFilter.LinearMipmapLinear) - minFilterNoMipmap = TextureMinFilter.Linear; - else if (minFilterNoMipmap == TextureMinFilter.NearestMipmapLinear) - minFilterNoMipmap = TextureMinFilter.Nearest; -#endif - } - - /// - protected internal override bool OnRecreate() - { - base.OnRecreate(); - return true; - } - - internal void Apply(bool hasMipmap, SamplerState oldSamplerState, TextureTarget target) - { -#if XENKO_GRAPHICS_API_OPENGLES - // TODO: support texture array, 3d and cube - if (!GraphicsDevice.IsOpenGLES2) -#endif - { - if (Description.MinMipLevel != oldSamplerState.Description.MinMipLevel) - GL.TexParameter(target, TextureParameterName.TextureMinLod, Description.MinMipLevel); - if (Description.MaxMipLevel != oldSamplerState.Description.MaxMipLevel) - GL.TexParameter(target, TextureParameterName.TextureMaxLod, Description.MaxMipLevel); - if (textureWrapR != oldSamplerState.textureWrapR) - GL.TexParameter(target, TextureParameterName.TextureWrapR, (int)textureWrapR); - if (compareMode != oldSamplerState.compareMode) - GL.TexParameter(target, TextureParameterName.TextureCompareMode, (int)compareMode); - if (compareFunc != oldSamplerState.compareFunc) - GL.TexParameter(target, TextureParameterName.TextureCompareFunc, (int)compareFunc); - } - -#if !XENKO_GRAPHICS_API_OPENGLES - if (borderColor != oldSamplerState.borderColor) - GL.TexParameter(target, TextureParameterName.TextureBorderColor, borderColor); - if (Description.MipMapLevelOfDetailBias != oldSamplerState.Description.MipMapLevelOfDetailBias) - GL.TexParameter(target, TextureParameterName.TextureLodBias, Description.MipMapLevelOfDetailBias); - if (minFilter != oldSamplerState.minFilter) - GL.TexParameter(target, TextureParameterName.TextureMinFilter, (int)minFilter); -#else - // On OpenGL ES, we need to choose the appropriate min filter ourself if the texture doesn't contain mipmaps (done at PreDraw) - if (minFilter != oldSamplerState.minFilter) - GL.TexParameter(target, TextureParameterName.TextureMinFilter, hasMipmap ? (int)minFilter : (int)minFilterNoMipmap); -#endif - -#if !XENKO_PLATFORM_IOS - if (maxAnisotropy != oldSamplerState.maxAnisotropy && GraphicsDevice.HasAnisotropicFiltering) - GL.TexParameter(target, (TextureParameterName)OpenTK.Graphics.ES20.ExtTextureFilterAnisotropic.TextureMaxAnisotropyExt, Description.MaxAnisotropy); -#endif - if (magFilter != oldSamplerState.magFilter) - GL.TexParameter(target, TextureParameterName.TextureMagFilter, (int)magFilter); - if (textureWrapS != oldSamplerState.textureWrapS) - GL.TexParameter(target, TextureParameterName.TextureWrapS, (int)textureWrapS); - if (textureWrapT != oldSamplerState.textureWrapT) - GL.TexParameter(target, TextureParameterName.TextureWrapT, (int)textureWrapT); - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.Android.cs b/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.Android.cs deleted file mode 100644 index 185e991415..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.Android.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_PLATFORM_ANDROID -using System; -using Xenko.Core.Mathematics; -using OpenTK; -using OpenTK.Platform.Android; - -namespace Xenko.Graphics -{ - public class SwapChainGraphicsPresenter : GraphicsPresenter - { - internal static Action ProcessPresentationParametersOverride; - - private AndroidGameView gameWindow; - private readonly Texture backBuffer; - private readonly GraphicsDevice graphicsDevice; - private readonly PresentationParameters startingPresentationParameters; - - public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) - { - gameWindow = (AndroidGameView)Description.DeviceWindowHandle.NativeWindow; - - graphicsDevice = device; - startingPresentationParameters = presentationParameters; - device.InitDefaultRenderTarget(Description); - - backBuffer = Texture.New2D(device, Description.BackBufferWidth, Description.BackBufferHeight, presentationParameters.BackBufferFormat, TextureFlags.RenderTarget | TextureFlags.ShaderResource); - } - - public override Texture BackBuffer => backBuffer; - - public override object NativePresenter => null; - - public override bool IsFullScreen - { - get - { - return gameWindow.WindowState == WindowState.Fullscreen; - } - set - { - gameWindow.WindowState = value ? WindowState.Fullscreen : WindowState.Normal; - } - } - - public override void EndDraw(CommandList commandList, bool present) - { - if (present) - { - GraphicsDevice.WindowProvidedRenderTexture.InternalSetSize(gameWindow.Width, gameWindow.Height); - - // If we made a fake render target to avoid OpenGL limitations on window-provided back buffer, let's copy the rendering result to it - commandList.CopyScaler2D(backBuffer, GraphicsDevice.WindowProvidedRenderTexture, - new Rectangle(0, 0, backBuffer.Width, backBuffer.Height), - new Rectangle(0, 0, GraphicsDevice.WindowProvidedRenderTexture.Width, GraphicsDevice.WindowProvidedRenderTexture.Height), true); - - gameWindow.GraphicsContext.SwapBuffers(); - } - } - - public override void Present() - { - } - - protected override void ResizeBackBuffer(int width, int height, PixelFormat format) - { - graphicsDevice.OnDestroyed(); - - startingPresentationParameters.BackBufferWidth = width; - startingPresentationParameters.BackBufferHeight = height; - - graphicsDevice.InitDefaultRenderTarget(startingPresentationParameters); - - var newTextureDescrition = backBuffer.Description; - newTextureDescrition.Width = width; - newTextureDescrition.Height = height; - - // Manually update the texture - backBuffer.OnDestroyed(); - - // Put it in our back buffer texture - backBuffer.InitializeFrom(newTextureDescrition); - } - - protected override void ResizeDepthStencilBuffer(int width, int height, PixelFormat format) - { - var newTextureDescrition = DepthStencilBuffer.Description; - newTextureDescrition.Width = width; - newTextureDescrition.Height = height; - - // Manually update the texture - DepthStencilBuffer.OnDestroyed(); - - // Put it in our back buffer texture - DepthStencilBuffer.InitializeFrom(newTextureDescrition); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.OpenTK.cs b/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.OpenTK.cs deleted file mode 100644 index 776363a0d3..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.OpenTK.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if (XENKO_PLATFORM_WINDOWS_DESKTOP || XENKO_PLATFORM_UNIX) && XENKO_GRAPHICS_API_OPENGL -using Xenko.Core.Mathematics; -using OpenTK; -using Rectangle = Xenko.Core.Mathematics.Rectangle; -#if XENKO_UI_SDL -using WindowState = Xenko.Graphics.SDL.FormWindowState; -using OpenGLWindow = Xenko.Graphics.SDL.Window; -#else -using WindowState = OpenTK.WindowState; -using OpenGLWindow = OpenTK.GameWindow; -#endif - -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - public class SwapChainGraphicsPresenter : GraphicsPresenter - { - private Texture backBuffer; - - public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) - { - device.InitDefaultRenderTarget(presentationParameters); - backBuffer = Texture.New2D(device, Description.BackBufferWidth, Description.BackBufferHeight, presentationParameters.BackBufferFormat, TextureFlags.RenderTarget | TextureFlags.ShaderResource); - } - - public override Texture BackBuffer - { - get { return backBuffer; } - } - - public override object NativePresenter - { - get { return null; } - } - - public override bool InternalFullscreen - { - get - { - return ((OpenGLWindow)Description.DeviceWindowHandle.NativeWindow).WindowState == WindowState.Fullscreen; - } - set - { - var gameWindow = (OpenGLWindow)Description.DeviceWindowHandle.NativeWindow; - if (gameWindow.Exists) - gameWindow.WindowState = value ? WindowState.Fullscreen : WindowState.Normal; - } - } - - public override void EndDraw(CommandList commandList, bool present) - { - if (present) - { - // If we made a fake render target to avoid OpenGL limitations on window-provided back buffer, let's copy the rendering result to it - commandList.CopyScaler2D(backBuffer, GraphicsDevice.WindowProvidedRenderTexture, - new Rectangle(0, 0, backBuffer.Width, backBuffer.Height), - new Rectangle(0, 0, GraphicsDevice.WindowProvidedRenderTexture.Width, GraphicsDevice.WindowProvidedRenderTexture.Height), true); - - // On macOS, `SwapBuffers` will swap whatever framebuffer is active and in our case it is not the window provided - // framebuffer, and in addition if the active framebuffer is single buffered, it won't do anything. Forcing a bind - // will ensure the window is updated. - GL.BindFramebuffer(FramebufferTarget.Framebuffer, GraphicsDevice.WindowProvidedFrameBuffer); - OpenTK.Graphics.GraphicsContext.CurrentContext.SwapBuffers(); - } - } - - public override void Present() - { - } - - protected override void ResizeBackBuffer(int width, int height, PixelFormat format) - { - } - - protected override void ResizeDepthStencilBuffer(int width, int height, PixelFormat format) - { - ReleaseCurrentDepthStencilBuffer(); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.iOS.cs b/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.iOS.cs deleted file mode 100644 index ba45612332..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/SwapChainGraphicsPresenter.iOS.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_PLATFORM_IOS -using System.Drawing; -using OpenTK; -using OpenTK.Platform.iPhoneOS; -using Rectangle = Xenko.Core.Mathematics.Rectangle; - - -namespace Xenko.Graphics -{ - public class SwapChainGraphicsPresenter : GraphicsPresenter - { - private readonly iPhoneOSGameView gameWindow; - private readonly Texture backBuffer; - private readonly GraphicsDevice graphicsDevice; - private readonly PresentationParameters startingPresentationParameters; - - public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters) : base(device, presentationParameters) - { - graphicsDevice = device; - startingPresentationParameters = presentationParameters; - gameWindow = (iPhoneOSGameView)Description.DeviceWindowHandle.NativeWindow; - device.InitDefaultRenderTarget(presentationParameters); - - backBuffer = Texture.New2D(device, Description.BackBufferWidth, Description.BackBufferHeight, presentationParameters.BackBufferFormat, TextureFlags.RenderTarget | TextureFlags.ShaderResource); - } - - public override Texture BackBuffer => backBuffer; - - public override object NativePresenter => null; - - public override bool IsFullScreen - { - get - { - return gameWindow.WindowState == WindowState.Fullscreen; - } - set - { - gameWindow.WindowState = value ? WindowState.Fullscreen : WindowState.Normal; - } - } - - public override void EndDraw(CommandList commandList, bool present) - { - if (present) - { - // If we made a fake render target to avoid OpenGL limitations on window-provided back buffer, let's copy the rendering result to it - commandList.CopyScaler2D(backBuffer, GraphicsDevice.WindowProvidedRenderTexture, - new Rectangle(0, 0, backBuffer.Width, backBuffer.Height), - new Rectangle(0, 0, GraphicsDevice.WindowProvidedRenderTexture.Width, GraphicsDevice.WindowProvidedRenderTexture.Height), true); - - gameWindow.SwapBuffers(); - } - } - - public override void Present() - { - } - - protected override void ResizeBackBuffer(int width, int height, PixelFormat format) - { - graphicsDevice.OnDestroyed(); - - startingPresentationParameters.BackBufferWidth = width; - startingPresentationParameters.BackBufferHeight = height; - - graphicsDevice.InitDefaultRenderTarget(startingPresentationParameters); - - var newTextureDescrition = backBuffer.Description; - newTextureDescrition.Width = width; - newTextureDescrition.Height = height; - - // Manually update the texture - backBuffer.OnDestroyed(); - - // Put it in our back buffer texture - backBuffer.InitializeFrom(newTextureDescrition); - } - - protected override void ResizeDepthStencilBuffer(int width, int height, PixelFormat format) - { - var newTextureDescrition = DepthStencilBuffer.Description; - newTextureDescrition.Width = width; - newTextureDescrition.Height = height; - - // Manually update the texture - DepthStencilBuffer.OnDestroyed(); - - // Put it in our back buffer texture - DepthStencilBuffer.InitializeFrom(newTextureDescrition); - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/Texture.OpenGL.cs b/sources/engine/Xenko.Graphics/OpenGL/Texture.OpenGL.cs deleted file mode 100644 index 71030546aa..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/Texture.OpenGL.cs +++ /dev/null @@ -1,743 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Runtime.InteropServices; -using Xenko.Core; -using Xenko.Core.Mathematics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -using RenderbufferStorage = OpenTK.Graphics.ES30.RenderbufferInternalFormat; -using PixelFormatGl = OpenTK.Graphics.ES30.PixelFormat; -using PixelInternalFormat = OpenTK.Graphics.ES30.TextureComponentCount; -#else -using OpenTK.Graphics.OpenGL; -using PixelFormatGl = OpenTK.Graphics.OpenGL.PixelFormat; -#endif - -// TODO: remove these when OpenTK API is consistent between OpenGL, mobile OpenGL ES and desktop OpenGL ES -#if XENKO_GRAPHICS_API_OPENGLES -using CompressedInternalFormat2D = OpenTK.Graphics.ES30.CompressedInternalFormat; -using CompressedInternalFormat3D = OpenTK.Graphics.ES30.CompressedInternalFormat; -using TextureComponentCount2D = OpenTK.Graphics.ES30.TextureComponentCount; -using TextureComponentCount3D = OpenTK.Graphics.ES30.TextureComponentCount; -#else -using CompressedInternalFormat2D = OpenTK.Graphics.OpenGL.PixelInternalFormat; -using CompressedInternalFormat3D = OpenTK.Graphics.OpenGL.PixelInternalFormat; -using TextureComponentCount2D = OpenTK.Graphics.OpenGL.PixelInternalFormat; -using TextureComponentCount3D = OpenTK.Graphics.OpenGL.PixelInternalFormat; -using TextureTarget2d = OpenTK.Graphics.OpenGL.TextureTarget; -using TextureTarget3d = OpenTK.Graphics.OpenGL.TextureTarget; -#endif - -namespace Xenko.Graphics -{ - /// - /// Abstract class for all textures - /// - public partial class Texture - { - private const int TextureRowPitchAlignment = 1; - private const int TextureSubresourceAlignment = 1; - - internal const TextureFlags TextureFlagsCustomResourceId = (TextureFlags)0x1000; - - internal SamplerState BoundSamplerState; - internal int PixelBufferFrame; - internal int TextureTotalSize; - private int pixelBufferObjectId; - private int stencilId; - - internal int DepthPitch { get; set; } - internal int RowPitch { get; set; } - internal bool IsDepthBuffer { get; private set; } // TODO: Isn't this redundant? This gets set to the same value as IsDepthStencil... - internal bool HasStencil { get; private set; } - internal bool IsRenderbuffer { get; private set; } - - internal int PixelBufferObjectId - { - get { return pixelBufferObjectId; } - } - - internal int StencilId - { - get { return stencilId; } - } - -#if XENKO_GRAPHICS_API_OPENGLES - internal IntPtr StagingData { get; set; } -#endif - - public static bool IsDepthStencilReadOnlySupported(GraphicsDevice device) - { - // always true on OpenGL - return true; - } - - internal void SwapInternal(Texture other) - { - var tmp = DepthPitch; - DepthPitch = other.DepthPitch; - other.DepthPitch = tmp; - // - tmp = RowPitch; - RowPitch = other.RowPitch; - other.RowPitch = tmp; - // - var tmp2 = IsDepthBuffer; - IsDepthBuffer = other.IsDepthBuffer; - other.IsDepthBuffer = tmp2; - // - tmp2 = HasStencil; - HasStencil = other.HasStencil; - other.HasStencil = tmp2; - // - tmp2 = IsRenderbuffer; - HasStencil = other.IsRenderbuffer; - other.IsRenderbuffer = tmp2; -#if XENKO_GRAPHICS_API_OPENGLES - var tmp3 = StagingData; - StagingData = other.StagingData; - other.StagingData = tmp3; -#endif - // - Utilities.Swap(ref BoundSamplerState, ref other.BoundSamplerState); - Utilities.Swap(ref PixelBufferFrame, ref other.PixelBufferFrame); - Utilities.Swap(ref TextureTotalSize, ref other.TextureTotalSize); - Utilities.Swap(ref pixelBufferObjectId, ref other.pixelBufferObjectId); - Utilities.Swap(ref stencilId, ref other.stencilId); - // - Utilities.Swap(ref DiscardNextMap, ref other.DiscardNextMap); - Utilities.Swap(ref TextureId, ref other.TextureId); - Utilities.Swap(ref TextureTarget, ref other.TextureTarget); - Utilities.Swap(ref TextureInternalFormat, ref other.TextureInternalFormat); - Utilities.Swap(ref TextureFormat, ref other.TextureFormat); - Utilities.Swap(ref TextureType, ref other.TextureType); - Utilities.Swap(ref TexturePixelSize, ref other.TexturePixelSize); - } - - public void Recreate(DataBox[] dataBoxes = null) - { - InitializeFromImpl(dataBoxes); - } - - private void OnRecreateImpl() - { - // Dependency: wait for underlying texture to be recreated - if (ParentTexture != null && ParentTexture.LifetimeState != GraphicsResourceLifetimeState.Active) - return; - - // Render Target / Depth Stencil are considered as "dynamic" - if ((Usage == GraphicsResourceUsage.Immutable - || Usage == GraphicsResourceUsage.Default) - && !IsRenderTarget && !IsDepthStencil) - return; - - if (ParentTexture == null && GraphicsDevice != null) - { - GraphicsDevice.RegisterTextureMemoryUsage(-SizeInBytes); - } - - InitializeFromImpl(); - } - -#if XENKO_PLATFORM_ANDROID //&& USE_GLES_EXT_OES_TEXTURE - //Prototype: experiment creating GlTextureExternalOes texture - private void InitializeForExternalOESImpl() - { - // TODO: We should probably also set the other parameters if possible, because otherwise we end up with a texture whose metadata says it's of 0x0x0 size and has no format. - - if (TextureId == 0) - { - GL.GenTextures(1, out TextureId); - - //Android.Opengl.GLES20.GlBindTexture(Android.Opengl.GLES11Ext.GlTextureExternalOes, TextureId); - - //Any "proper" way to do this? (GLES20 could directly accept it, not GLES30 anymore) - TextureTarget = (TextureTarget)Android.Opengl.GLES11Ext.GlTextureExternalOes; - GL.BindTexture(TextureTarget, TextureId); - - //GL.BindTexture(TextureTarget, 0); - } - } -#endif - - private TextureTarget GetTextureTarget(TextureDimension dimension) - { - switch (Dimension) - { - case TextureDimension.Texture1D: -#if !XENKO_GRAPHICS_API_OPENGLES - if (ArraySize > 1) - throw new PlatformNotSupportedException("Texture1DArray is not implemented under OpenGL"); - return TextureTarget.Texture1D; -#endif - case TextureDimension.Texture2D: - return ArraySize > 1 ? TextureTarget.Texture2DArray : TextureTarget.Texture2D; - case TextureDimension.Texture3D: - return TextureTarget.Texture3D; - case TextureDimension.TextureCube: - if (ArraySize > 6) - throw new PlatformNotSupportedException("TextureCubeArray is not implemented under OpenGL"); - return TextureTarget.TextureCubeMap; - } - - throw new ArgumentOutOfRangeException("TextureDimension couldn't be converted to a TextureTarget."); - } - - private void CopyParentAttributes() - { - TextureId = ParentTexture.TextureId; - - TextureInternalFormat = ParentTexture.TextureInternalFormat; - TextureFormat = ParentTexture.TextureFormat; - TextureType = ParentTexture.TextureType; - TextureTarget = ParentTexture.TextureTarget; - DepthPitch = ParentTexture.DepthPitch; - RowPitch = ParentTexture.RowPitch; - IsDepthBuffer = ParentTexture.IsDepthBuffer; - HasStencil = ParentTexture.HasStencil; - IsRenderbuffer = ParentTexture.IsRenderbuffer; - - stencilId = ParentTexture.StencilId; - pixelBufferObjectId = ParentTexture.PixelBufferObjectId; - } - - private void InitializeFromImpl(DataBox[] dataBoxes = null) - { - if (ParentTexture != null) - { - CopyParentAttributes(); - } - - if (TextureId == 0) - { - TextureTarget = GetTextureTarget(Dimension); - - bool compressed; - OpenGLConvertExtensions.ConvertPixelFormat(GraphicsDevice, ref textureDescription.Format, out TextureInternalFormat, out TextureFormat, out TextureType, out TexturePixelSize, out compressed); - - DepthPitch = Description.Width * Description.Height * TexturePixelSize; - RowPitch = Description.Width * TexturePixelSize; - - IsDepthBuffer = ((Description.Flags & TextureFlags.DepthStencil) != 0); - if (IsDepthBuffer) - { - HasStencil = InternalHasStencil(Format); - } - else - { - HasStencil = false; - } - - if ((Description.Flags & TextureFlagsCustomResourceId) != 0) - return; - - using (var openglContext = GraphicsDevice.UseOpenGLCreationContext()) - { - TextureTotalSize = ComputeBufferTotalSize(); - - if (Description.Usage == GraphicsResourceUsage.Staging) - { - InitializeStagingPixelBufferObject(dataBoxes); - return; // TODO: This return causes "GraphicsDevice.RegisterTextureMemoryUsage(SizeInBytes);" not to get entered. Is that okay? - } - - // Depth textures are renderbuffers for now // TODO: PERFORMANCE: Why? I think we should change that so we can sample them directly. - // TODO: enable switch // TODO: What does this comment even mean? - - IsRenderbuffer = !Description.IsShaderResource; - - // Force to renderbuffer if MSAA is on because we don't support MSAA textures ATM (and they don't exist on OpenGL ES). - if (Description.IsMultisample) - { - // TODO: Ideally the caller of this method should be aware of this "force to renderbuffer", - // because the caller won't be able to bind it as a texture. - IsRenderbuffer = true; - } - - if (IsRenderbuffer) - { - CreateRenderbuffer(); - return; // TODO: This return causes "GraphicsDevice.RegisterTextureMemoryUsage(SizeInBytes);" not to get entered. Is that okay? - } - - GL.GenTextures(1, out TextureId); - GL.BindTexture(TextureTarget, TextureId); - SetFilterMode(); - - if (Description.MipLevels == 0) - throw new NotImplementedException(); - - var setSize = TextureSetSize(TextureTarget); - - for (var arrayIndex = 0; arrayIndex < Description.ArraySize; ++arrayIndex) - { - int offsetArray = arrayIndex * Description.MipLevels; - - for (int mipLevel = 0; mipLevel < Description.MipLevels; ++mipLevel) - { - DataBox dataBox; - Int3 dimensions = new Int3(CalculateMipSize(Description.Width, mipLevel), - CalculateMipSize(Description.Height, mipLevel), - CalculateMipSize(Description.Depth, mipLevel)); - if (dataBoxes != null && mipLevel < dataBoxes.Length) - { - if (setSize > 1 && !compressed && dataBoxes[mipLevel].RowPitch != dimensions.X * TexturePixelSize) - throw new NotSupportedException("Can't upload texture with pitch in glTexImage2D/3D."); - // Might be possible, need to check API better. - dataBox = dataBoxes[offsetArray + mipLevel]; - } - else - { - dataBox = new DataBox(); - } - - switch (TextureTarget) - { - case TextureTarget.Texture1D: - CreateTexture1D(compressed, dimensions.X, mipLevel, dataBox); - break; - case TextureTarget.Texture2D: - case TextureTarget.TextureCubeMap: - CreateTexture2D(compressed, dimensions.X, dimensions.Y, mipLevel, arrayIndex, dataBox); - break; - case TextureTarget.Texture3D: - CreateTexture3D(compressed, dimensions.X, dimensions.Y, dimensions.Z, mipLevel, dataBox); - break; - case TextureTarget.Texture2DArray: - CreateTexture2DArray(compressed, dimensions.X, dimensions.Y, mipLevel, arrayIndex, dataBox); - break; - } - } - } - - GL.BindTexture(TextureTarget, 0); // This unbinds the texture. - if (openglContext.CommandList != null) - { - // If we messed up with some states of a command list, mark dirty states - openglContext.CommandList.boundShaderResourceViews[openglContext.CommandList.activeTexture] = null; - } - } - - GraphicsDevice.RegisterTextureMemoryUsage(SizeInBytes); - } - } - - private void CreateRenderbuffer() - { - if (Description.IsDepthStencil) // If it is a depth/stencil attachment: - { - RenderbufferStorage depthRenderbufferFormat; - RenderbufferStorage stencilRenderbufferFormat; - ConvertDepthFormat(GraphicsDevice, Description.Format, out depthRenderbufferFormat, out stencilRenderbufferFormat); - - CreateRenderbuffer(Width, Height, (int)Description.MultisampleCount, depthRenderbufferFormat, out TextureId); - - if (stencilRenderbufferFormat != 0) // If we have a separate stencil attachment: - { - CreateRenderbuffer(Width, Height, (int)Description.MultisampleCount, stencilRenderbufferFormat, out stencilId); - } - else if (HasStencil) // If depth and stencil are stored inside the same renderbuffer: - { - stencilId = TextureId; - } - } - else if (Description.IsRenderTarget) // If it is a color attachment: - { - CreateRenderbuffer(Width, Height, (int)Description.MultisampleCount, (RenderbufferStorage)TextureInternalFormat, out TextureId); - } - else - { - throw new NotSupportedException("Requested renderbuffer is neither a render target nor a depth/stencil attachment."); - } - - GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0); // Unbinds the renderbuffer. - } - - private void SetFilterMode() - { - if (Description.IsDepthStencil || Description.IsRenderTarget) // Set the filtering mode of depth, stencil and color FBO attachments: - { - // Disable filtering on FBO attachments: - GL.TexParameter(TextureTarget, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); // TODO: Do we enter this for MSAA buffers too? Is this an issue? - GL.TexParameter(TextureTarget, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); // TODO: Why would we force the filter to "nearest"? - GL.TexParameter(TextureTarget, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); - GL.TexParameter(TextureTarget, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); - BoundSamplerState = GraphicsDevice.SamplerStates.PointClamp; - - if (HasStencil) - { - // Since we store depth and stencil in a single texture, we assign the depth buffer's texture ID as the stencil texture ID. - stencilId = TextureId; - } - } -#if XENKO_GRAPHICS_API_OPENGLES - else if (Description.MipLevels <= 1) - { - GL.TexParameter(TextureTarget, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); // TODO: Why does this use the nearest filter for minification? Using Linear filtering would result in a smoother appearance for minified textures. - GL.TexParameter(TextureTarget, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); - } -#endif - -#if XENKO_GRAPHICS_API_OPENGLES - if (!GraphicsDevice.IsOpenGLES2) -#endif - { - GL.TexParameter(TextureTarget, TextureParameterName.TextureBaseLevel, 0); - GL.TexParameter(TextureTarget, TextureParameterName.TextureMaxLevel, Description.MipLevels - 1); - } - } - - private void CreateRenderbuffer(int width, int height, int multisampleCount, RenderbufferStorage internalFormat, out int textureID) - { - GL.GenRenderbuffers(1, out textureID); - GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, textureID); - - if (Description.IsMultisample) - { -#if !XENKO_PLATFORM_IOS - // MSAA is not supported on iOS currently because OpenTK doesn't expose "GL.BlitFramebuffer()" on iOS for some reason. - GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, multisampleCount, internalFormat, width, height); -#endif - } - else - { - GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, internalFormat, width, height); - } - } - - private void CreateTexture1D(bool compressed, int width, int mipLevel, DataBox dataBox) - { - // TODO: STABILITY: Since 1D textures are not supported on OpenGL ES, what should we do in this case? Throw an exception? I mean currently we just silently ignore that case on OpenGL ES. -#if !XENKO_GRAPHICS_API_OPENGLES - if (compressed) - { - GL.CompressedTexImage1D(TextureTarget, mipLevel, TextureInternalFormat, width, 0, dataBox.SlicePitch, dataBox.DataPointer); - } - else - { - GL.TexImage1D(TextureTarget, mipLevel, TextureInternalFormat, width, 0, TextureFormat, TextureType, dataBox.DataPointer); - } -#endif - } - - private void CreateTexture2D(bool compressed, int width, int height, int mipLevel, int arrayIndex, DataBox dataBox) - { - if (IsMultisample) - { - throw new InvalidOperationException("Currently if multisampling is on, a renderbuffer will be created (not a texture) in any case and this code will not be reached." + - "Therefore if this place is reached, it means something went wrong. Once multisampling has been implemented for OpenGL textures, you can remove this exception."); - - if (IsRenderbuffer) - { -#if !XENKO_PLATFORM_IOS - // MSAA is not supported on iOS currently because OpenTK doesn't expose "GL.BlitFramebuffer()" on iOS for some reason. - GL.RenderbufferStorageMultisample(RenderbufferTarget.Renderbuffer, (int)Description.MultisampleCount, (RenderbufferStorage)TextureInternalFormat, width, height); -#endif - } - else - { -#if XENKO_GRAPHICS_API_OPENGLES - throw new NotSupportedException("Multisample textures are not supported on OpenGL ES."); -#else - GL.TexImage2DMultisample(TextureTargetMultisample.Texture2DMultisample, (int)Description.MultisampleCount, (TextureComponentCount2D)TextureInternalFormat, width, height, false); -#endif - } - } - else - { - var dataSetTarget = GetTextureTargetForDataSet2D(TextureTarget, arrayIndex); - if (compressed) - { - GL.CompressedTexImage2D(dataSetTarget, mipLevel, (CompressedInternalFormat2D)TextureInternalFormat, width, height, 0, dataBox.SlicePitch, dataBox.DataPointer); - } - else - { - GL.TexImage2D(dataSetTarget, mipLevel, (TextureComponentCount2D)TextureInternalFormat, width, height, 0, TextureFormat, TextureType, dataBox.DataPointer); - } - } - } - - private void CreateTexture3D(bool compressed, int width, int height, int depth, int mipLevel, DataBox dataBox) - { - if (compressed) - { - GL.CompressedTexImage3D((TextureTarget3d)TextureTarget, mipLevel, (CompressedInternalFormat3D)TextureInternalFormat, width, height, depth, 0, dataBox.SlicePitch, dataBox.DataPointer); - } - else - { - GL.TexImage3D((TextureTarget3d)TextureTarget, mipLevel, (TextureComponentCount3D)TextureInternalFormat, width, height, depth, 0, TextureFormat, TextureType, dataBox.DataPointer); - } - } - - private void CreateTexture2DArray(bool compressed, int width, int height, int mipLevel, int arrayIndex, DataBox dataBox) - { - // We create all array slices at once, but upload them one by one - if (arrayIndex == 0) - { - if (compressed) - { - GL.CompressedTexImage3D((TextureTarget3d)TextureTarget, mipLevel, (CompressedInternalFormat3D)TextureInternalFormat, width, height, ArraySize, 0, 0, IntPtr.Zero); - } - else - { - GL.TexImage3D((TextureTarget3d)TextureTarget, mipLevel, (TextureComponentCount3D)TextureInternalFormat, width, height, ArraySize, 0, TextureFormat, TextureType, IntPtr.Zero); - } - } - - if (dataBox.DataPointer != IntPtr.Zero) - { - if (compressed) - { - GL.CompressedTexSubImage3D((TextureTarget3d)TextureTarget, mipLevel, 0, 0, arrayIndex, width, height, 1, TextureFormat, dataBox.SlicePitch, dataBox.DataPointer); - } - else - { - GL.TexSubImage3D((TextureTarget3d)TextureTarget, mipLevel, 0, 0, arrayIndex, width, height, 1, TextureFormat, TextureType, dataBox.DataPointer); - } - } - } - - /// - protected internal override void OnDestroyed() - { -#if XENKO_GRAPHICS_API_OPENGLES - if (StagingData != IntPtr.Zero) - { - Marshal.FreeHGlobal(StagingData); - StagingData = IntPtr.Zero; - } -#endif - using (GraphicsDevice.UseOpenGLCreationContext()) - { - if (TextureId != 0 && ParentTexture == null) - { - if (IsRenderbuffer) - GL.DeleteRenderbuffers(1, ref TextureId); - else - GL.DeleteTextures(1, ref TextureId); - - GraphicsDevice.RegisterTextureMemoryUsage(-SizeInBytes); - } - - if (stencilId != 0) - GL.DeleteRenderbuffers(1, ref stencilId); - - if (pixelBufferObjectId != 0) - GL.DeleteBuffers(1, ref pixelBufferObjectId); - } - - TextureTotalSize = 0; - TextureId = 0; - stencilId = 0; - pixelBufferObjectId = 0; - - base.OnDestroyed(); - } - - private static void ConvertDepthFormat(GraphicsDevice graphicsDevice, PixelFormat requestedFormat, out RenderbufferStorage depthFormat, out RenderbufferStorage stencilFormat) - { - // Default: non-separate depth/stencil - stencilFormat = 0; - - switch (requestedFormat) - { - case PixelFormat.D16_UNorm: - depthFormat = RenderbufferStorage.DepthComponent16; - break; -#if !XENKO_GRAPHICS_API_OPENGLES - case PixelFormat.D24_UNorm_S8_UInt: - depthFormat = RenderbufferStorage.Depth24Stencil8; - break; - case PixelFormat.D32_Float: - depthFormat = RenderbufferStorage.DepthComponent32; - break; - case PixelFormat.D32_Float_S8X24_UInt: - depthFormat = RenderbufferStorage.Depth32fStencil8; - break; -#else - case PixelFormat.D24_UNorm_S8_UInt: - if (graphicsDevice.HasPackedDepthStencilExtension) - { - depthFormat = RenderbufferStorage.Depth24Stencil8; - } - else - { - depthFormat = graphicsDevice.HasDepth24 ? RenderbufferStorage.DepthComponent24 : RenderbufferStorage.DepthComponent16; - stencilFormat = RenderbufferStorage.StencilIndex8; - } - break; - case PixelFormat.D32_Float: - if (graphicsDevice.IsOpenGLES2) - throw new NotSupportedException("Only 16 bits depth buffer or 24-8 bits depth-stencil buffer is supported on OpenGLES2"); - depthFormat = RenderbufferInternalFormat.DepthComponent32f; - break; - case PixelFormat.D32_Float_S8X24_UInt: - if (graphicsDevice.IsOpenGLES2) - throw new NotSupportedException("Only 16 bits depth buffer or 24-8 bits depth-stencil buffer is supported on OpenGLES2"); - // no need to check graphicsDevice.HasPackedDepthStencilExtension since supported 32F depth means OpenGL ES 3, so packing is available. - depthFormat = RenderbufferInternalFormat.Depth32fStencil8; - break; -#endif - default: - throw new NotImplementedException(); - } - } - - private static bool InternalHasStencil(PixelFormat format) - { - switch (format) - { - case PixelFormat.D32_Float_S8X24_UInt: - case PixelFormat.R32_Float_X8X24_Typeless: - case PixelFormat.X32_Typeless_G8X24_UInt: - case PixelFormat.D24_UNorm_S8_UInt: - case PixelFormat.R24_UNorm_X8_Typeless: - case PixelFormat.X24_Typeless_G8_UInt: - return true; - default: - return false; - } - } - - internal static bool InternalIsDepthStencilFormat(PixelFormat format) - { - switch (format) - { - case PixelFormat.D16_UNorm: - case PixelFormat.D32_Float: - case PixelFormat.D32_Float_S8X24_UInt: - case PixelFormat.R32_Float_X8X24_Typeless: - case PixelFormat.X32_Typeless_G8X24_UInt: - case PixelFormat.D24_UNorm_S8_UInt: - case PixelFormat.R24_UNorm_X8_Typeless: - case PixelFormat.X24_Typeless_G8_UInt: - return true; - default: - return false; - } - } - - internal static TextureTarget2d GetTextureTargetForDataSet2D(TextureTarget target, int arrayIndex) - { - // TODO: Proxy from ES 3.1? - if (target == TextureTarget.TextureCubeMap) - return TextureTarget2d.TextureCubeMapPositiveX + arrayIndex; - return (TextureTarget2d)target; - } - - internal static TextureTarget3d GetTextureTargetForDataSet3D(TextureTarget target) - { - return (TextureTarget3d)target; - } - - private static int TextureSetSize(TextureTarget target) - { - // TODO: improve that -#if !XENKO_GRAPHICS_API_OPENGLES - if (target == TextureTarget.Texture1D) - return 1; -#endif - if (target == TextureTarget.Texture3D || target == TextureTarget.Texture2DArray) - return 3; - return 2; - } - - internal void InternalSetSize(int width, int height) - { - // Set backbuffer actual size - textureDescription.Width = width; - textureDescription.Height = height; - } - - internal static PixelFormat ComputeShaderResourceFormatFromDepthFormat(PixelFormat format) - { - return format; - } - - private bool IsFlipped() - { - return GraphicsDevice.WindowProvidedRenderTexture == this; - } - - private void InitializeStagingPixelBufferObject(DataBox[] dataBoxes) - { -#if XENKO_GRAPHICS_API_OPENGLES - if (GraphicsDevice.IsOpenGLES2) - { - StagingData = Marshal.AllocHGlobal(TextureTotalSize); - } - else -#endif - { - pixelBufferObjectId = GeneratePixelBufferObject(BufferTarget.PixelPackBuffer, PixelStoreParameter.PackAlignment, BufferUsageHint.StreamRead, TextureTotalSize); - } - UploadInitialData(BufferTarget.PixelPackBuffer, dataBoxes); - } - - private void UploadInitialData(BufferTarget bufferTarget, DataBox[] dataBoxes) - { - // Upload initial data - int offset = 0; - var bufferData = IntPtr.Zero; -#if XENKO_GRAPHICS_API_OPENGLES - bufferData = StagingData; -#endif - - if (PixelBufferObjectId != 0) - { - GL.BindBuffer(bufferTarget, PixelBufferObjectId); - bufferData = GL.MapBufferRange(bufferTarget, (IntPtr)0, (IntPtr)TextureTotalSize, BufferAccessMask.MapWriteBit | BufferAccessMask.MapUnsynchronizedBit); - } - - if (bufferData != IntPtr.Zero) - { - for (var arrayIndex = 0; arrayIndex < Description.ArraySize; ++arrayIndex) - { - var offsetArray = arrayIndex * Description.MipLevels; - for (int i = 0; i < Description.MipLevels; ++i) - { - IntPtr data = IntPtr.Zero; - var width = CalculateMipSize(Description.Width, i); - var height = CalculateMipSize(Description.Height, i); - var depth = CalculateMipSize(Description.Depth, i); - if (dataBoxes != null && i < dataBoxes.Length) - { - data = dataBoxes[offsetArray + i].DataPointer; - } - - if (data != IntPtr.Zero) - { - Utilities.CopyMemory(bufferData + offset, data, width * height * depth * TexturePixelSize); - } - - offset += width*height*TexturePixelSize; - } - } - - if (PixelBufferObjectId != 0) - { - GL.UnmapBuffer(bufferTarget); - GL.BindBuffer(bufferTarget, 0); - } - } - } - - internal int GeneratePixelBufferObject(BufferTarget target, PixelStoreParameter alignment, BufferUsageHint bufferUsage, int totalSize) - { - int result; - - GL.GenBuffers(1, out result); - GL.BindBuffer(target, result); - if (RowPitch < 4) - GL.PixelStore(alignment, 1); - GL.BufferData(target, totalSize, IntPtr.Zero, bufferUsage); - GL.BindBuffer(target, 0); - - return result; - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/UseOpenGLCreationContext.cs b/sources/engine/Xenko.Graphics/OpenGL/UseOpenGLCreationContext.cs deleted file mode 100644 index 2356980c77..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/UseOpenGLCreationContext.cs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -using System.Linq; -using System.Runtime.InteropServices; -using System.Threading; -using OpenTK.Graphics; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - /// - /// Used internally to provide a context for async resource creation - /// (such as texture or buffer created on a thread where no context is active). - /// - internal struct UseOpenGLCreationContext : IDisposable - { - public readonly CommandList CommandList; - - private readonly bool useDeviceCreationContext; - private readonly bool needUnbindContext; - - private readonly bool asyncCreationLockTaken; - private readonly object asyncCreationLockObject; - - private readonly IGraphicsContext deviceCreationContext; - -#if XENKO_PLATFORM_ANDROID - private readonly bool tegraWorkaround; -#endif - -#if XENKO_PLATFORM_IOS - private OpenGLES.EAGLContext previousContext; -#endif - - public bool UseDeviceCreationContext => useDeviceCreationContext; - - public UseOpenGLCreationContext(GraphicsDevice graphicsDevice) - : this() - { - if (OpenTK.Graphics.GraphicsContext.CurrentContextHandle.Handle == IntPtr.Zero) - { - needUnbindContext = true; - useDeviceCreationContext = true; - -#if XENKO_PLATFORM_ANDROID - tegraWorkaround = graphicsDevice.Workaround_Context_Tegra2_Tegra3; - - // Notify main rendering thread there is some pending async work to do - if (tegraWorkaround) - { - useDeviceCreationContext = false; // We actually use real main context, so states will be kept - graphicsDevice.AsyncPendingTaskWaiting = true; - } -#endif - - // Lock, since there is only one deviceCreationContext. - // TODO: Support multiple deviceCreationContext (TLS creation of context was crashing, need to investigate why) - asyncCreationLockObject = graphicsDevice.asyncCreationLockObject; - Monitor.Enter(graphicsDevice.asyncCreationLockObject, ref asyncCreationLockTaken); - -#if XENKO_PLATFORM_ANDROID - if (tegraWorkaround) - graphicsDevice.AsyncPendingTaskWaiting = false; -#endif - - -#if XENKO_PLATFORM_IOS - previousContext = OpenGLES.EAGLContext.CurrentContext; - var localContext = graphicsDevice.ThreadLocalContext.Value; - OpenGLES.EAGLContext.SetCurrentContext(localContext); -#else - // Bind the context - deviceCreationContext = graphicsDevice.deviceCreationContext; - deviceCreationContext.MakeCurrent(graphicsDevice.deviceCreationWindowInfo); -#endif - } - else - { - // TODO Hardcoded to the fact it uses only one command list, this should be fixed - CommandList = graphicsDevice.InternalMainCommandList; - } - } - - public void Dispose() - { - try - { - if (needUnbindContext) - { - GL.Flush(); - -#if XENKO_PLATFORM_IOS - if (previousContext != null) - OpenGLES.EAGLContext.SetCurrentContext(previousContext); -#else - // Restore graphics context - GraphicsDevice.UnbindGraphicsContext(deviceCreationContext); -#endif - } - } - finally - { - // Unlock - if (asyncCreationLockTaken) - { -#if XENKO_PLATFORM_ANDROID - if (tegraWorkaround) - { - // Notify GraphicsDevice.ExecutePendingTasks() that we are done. - Monitor.Pulse(asyncCreationLockObject); - } -#endif - Monitor.Exit(asyncCreationLockObject); - } - } - } - } -} -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/VertexAttrib.cs b/sources/engine/Xenko.Graphics/OpenGL/VertexAttrib.cs deleted file mode 100644 index cbee690029..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/VertexAttrib.cs +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -#if XENKO_GRAPHICS_API_OPENGL -using System; -#if XENKO_GRAPHICS_API_OPENGLES -using OpenTK.Graphics.ES30; -#else -using OpenTK.Graphics.OpenGL; -#endif - -namespace Xenko.Graphics -{ - internal struct VertexAttrib : IEquatable - { - public readonly int VertexBufferSlot; - public readonly int AttributeIndex; - public readonly int Size; - public readonly bool IsInteger; - public readonly VertexAttribPointerType Type; - public readonly bool Normalized; - public readonly int Offset; - - public VertexAttrib(int vertexBufferSlot, int attributeIndex, int size, VertexAttribPointerType type, bool normalized, int offset) - { - VertexBufferSlot = vertexBufferSlot; - AttributeIndex = attributeIndex; - Size = size; - IsInteger = IsIntegerHelper(type); - Type = type; - Normalized = normalized; - Offset = offset; - } - - public bool Equals(VertexAttrib other) - { - return VertexBufferSlot == other.VertexBufferSlot && AttributeIndex == other.AttributeIndex && Size == other.Size && IsInteger.Equals(other.IsInteger) && Type == other.Type && Normalized.Equals(other.Normalized) && Offset.Equals(other.Offset); - } - - public override bool Equals(object obj) - { - if (ReferenceEquals(null, obj)) return false; - return obj is VertexAttrib && Equals((VertexAttrib) obj); - } - - public override int GetHashCode() - { - unchecked - { - int hashCode = VertexBufferSlot; - hashCode = (hashCode * 397) ^ AttributeIndex; - hashCode = (hashCode * 397) ^ Size; - hashCode = (hashCode * 397) ^ IsInteger.GetHashCode(); - hashCode = (hashCode * 397) ^ (int) Type; - hashCode = (hashCode * 397) ^ Normalized.GetHashCode(); - hashCode = (hashCode * 397) ^ Offset; - return hashCode; - } - } - - public static bool operator ==(VertexAttrib left, VertexAttrib right) - { - return left.Equals(right); - } - - public static bool operator !=(VertexAttrib left, VertexAttrib right) - { - return !left.Equals(right); - } - - private static bool IsIntegerHelper(VertexAttribPointerType type) - { - switch (type) - { - case VertexAttribPointerType.Byte: - case VertexAttribPointerType.UnsignedByte: - case VertexAttribPointerType.Short: - case VertexAttribPointerType.UnsignedShort: - case VertexAttribPointerType.Int: - case VertexAttribPointerType.UnsignedInt: - return true; - default: - return false; - } - } - - internal struct ElementFormat - { - public readonly VertexAttribPointerType Type; - public readonly byte Size; - public readonly bool Normalized; - - public ElementFormat(VertexAttribPointerType type, byte size, bool normalized = false) - { - Type = type; - Size = size; - Normalized = normalized; - } - } - - internal static ElementFormat ConvertVertexElementFormat(PixelFormat format) - { - switch (format) - { - case PixelFormat.R8_SInt: - return new ElementFormat(VertexAttribPointerType.Byte, 1); - case PixelFormat.R8_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedByte, 1); - case PixelFormat.R16_SInt: - return new ElementFormat(VertexAttribPointerType.Short, 1); - case PixelFormat.R16_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedShort, 1); - case PixelFormat.R32_SInt: - return new ElementFormat(VertexAttribPointerType.Int, 4); - case PixelFormat.R32_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedInt, 4); - case PixelFormat.R8G8_SInt: - return new ElementFormat(VertexAttribPointerType.Byte, 2); - case PixelFormat.R8G8_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedByte, 2); - case PixelFormat.R16G16_SInt: - return new ElementFormat(VertexAttribPointerType.Short, 2); - case PixelFormat.R16G16_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedShort, 2); - case PixelFormat.R8G8B8A8_SInt: - return new ElementFormat(VertexAttribPointerType.Byte, 4); - case PixelFormat.R8G8B8A8_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedByte, 4); - case PixelFormat.R16G16B16A16_SInt: - return new ElementFormat(VertexAttribPointerType.Short, 4); - case PixelFormat.R16G16B16A16_UInt: - return new ElementFormat(VertexAttribPointerType.UnsignedShort, 4); - case PixelFormat.R32_Float: - return new ElementFormat(VertexAttribPointerType.Float, 1); - case PixelFormat.R32G32_Float: - return new ElementFormat(VertexAttribPointerType.Float, 2); - case PixelFormat.R32G32B32_Float: - return new ElementFormat(VertexAttribPointerType.Float, 3); - case PixelFormat.R32G32B32A32_Float: - return new ElementFormat(VertexAttribPointerType.Float, 4); - case PixelFormat.R8_UNorm: - return new ElementFormat(VertexAttribPointerType.UnsignedByte, 1, true); - case PixelFormat.R8G8_UNorm: - return new ElementFormat(VertexAttribPointerType.UnsignedByte, 2, true); - case PixelFormat.R8G8B8A8_UNorm: - return new ElementFormat(VertexAttribPointerType.UnsignedByte, 4, true); - case PixelFormat.R8_SNorm: - return new ElementFormat(VertexAttribPointerType.Byte, 1, true); - case PixelFormat.R8G8_SNorm: - return new ElementFormat(VertexAttribPointerType.Byte, 2, true); - case PixelFormat.R8G8B8A8_SNorm: - return new ElementFormat(VertexAttribPointerType.Byte, 4, true); - case PixelFormat.R16_UNorm: - return new ElementFormat(VertexAttribPointerType.UnsignedShort, 1, true); - case PixelFormat.R16G16_UNorm: - return new ElementFormat(VertexAttribPointerType.UnsignedShort, 2, true); - case PixelFormat.R16G16B16A16_UNorm: - return new ElementFormat(VertexAttribPointerType.UnsignedShort, 4, true); - case PixelFormat.R16_SNorm: - return new ElementFormat(VertexAttribPointerType.Short, 1, true); - case PixelFormat.R16G16_SNorm: - return new ElementFormat(VertexAttribPointerType.Short, 2, true); - case PixelFormat.R16G16B16A16_SNorm: - return new ElementFormat(VertexAttribPointerType.Short, 4, true); -#if XENKO_GRAPHICS_API_OPENGLES - // HALF_FLOAT for OpenGL ES 2.x (OES extension) - case PixelFormat.R16G16B16A16_Float: - return new ElementFormat((VertexAttribPointerType)0x8D61, 4); // HALF_FLOAT_OES - case PixelFormat.R16G16_Float: - return new ElementFormat((VertexAttribPointerType)0x8D61, 2); // HALF_FLOAT_OES -#else - // HALF_FLOAT for OpenGL and OpenGL ES 3.x (also used for OpenGL ES 2.0 under 3.0 emulator) - case PixelFormat.R16G16B16A16_Float: - return new ElementFormat((VertexAttribPointerType)0x8D61, 4); // HALF_FLOAT - case PixelFormat.R16G16_Float: - return new ElementFormat((VertexAttribPointerType)0x8D61, 2); // HALF_FLOAT -#endif - default: - throw new NotSupportedException(); - } - } - } -} - -#endif diff --git a/sources/engine/Xenko.Graphics/OpenGL/apply.bat b/sources/engine/Xenko.Graphics/OpenGL/apply.bat deleted file mode 100644 index db54ae7118..0000000000 --- a/sources/engine/Xenko.Graphics/OpenGL/apply.bat +++ /dev/null @@ -1,10 +0,0 @@ -@echo off -for %%f in (*.cs) do ( - echo %%f - copy %%f temp.txt - echo #if %1 > %%f - copy %%f+temp.txt %%f - echo. >> %%f - echo #endif >> %%f - del temp.txt -) \ No newline at end of file diff --git a/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj b/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj index 9c54977465..54a7d4757a 100644 --- a/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj +++ b/sources/engine/Xenko.Graphics/Xenko.Graphics.csproj @@ -1,4 +1,4 @@ - + true true @@ -90,9 +90,7 @@ - - diff --git a/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolver.cs b/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolver.cs index cbb67afca5..3aef7ab699 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolver.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Compositing/MSAAResolver.cs @@ -162,9 +162,7 @@ protected override void DrawCore(RenderDrawContext drawContext) var svPosUnpack = new Vector4(0.5f * inputSize.Width, -0.5f * inputSize.Height, 0.5f * inputSize.Width, 0.5f * inputSize.Height); var textureSizeLess1 = new Vector2(inputSize.Width - 1.0f, inputSize.Height - 1.0f); - if (GraphicsDevice.Platform == GraphicsPlatform.OpenGL || - GraphicsDevice.Platform == GraphicsPlatform.OpenGLES || - FilterType == FilterTypes.Default) + if (FilterType == FilterTypes.Default) { // We currently only support the default hardware MSAA resolve on OpenGL and OpenGL ES. drawContext.CommandList.CopyMultisample(input, 0, output, 0); diff --git a/sources/engine/Xenko.Shaders.Compiler/EffectCompiler.cs b/sources/engine/Xenko.Shaders.Compiler/EffectCompiler.cs index c2f74aa063..b17de1977d 100644 --- a/sources/engine/Xenko.Shaders.Compiler/EffectCompiler.cs +++ b/sources/engine/Xenko.Shaders.Compiler/EffectCompiler.cs @@ -108,18 +108,6 @@ public override TaskOrResult Compile(ShaderMixinSo shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D", 1); shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D11", 1); break; - case GraphicsPlatform.Direct3D12: - shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D", 1); - shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D12", 1); - break; - case GraphicsPlatform.OpenGL: - shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGL", 1); - shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGLCORE", 1); - break; - case GraphicsPlatform.OpenGLES: - shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGL", 1); - shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGLES", 1); - break; case GraphicsPlatform.Vulkan: shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_VULKAN", 1); break; @@ -199,12 +187,9 @@ public override TaskOrResult Compile(ShaderMixinSo { #if XENKO_PLATFORM_WINDOWS case GraphicsPlatform.Direct3D11: - case GraphicsPlatform.Direct3D12: compiler = new Direct3D.ShaderCompiler(); break; #endif - case GraphicsPlatform.OpenGL: - case GraphicsPlatform.OpenGLES: case GraphicsPlatform.Vulkan: // get the number of render target outputs var rtOutputs = 0; @@ -244,11 +229,6 @@ public override TaskOrResult Compile(ShaderMixinSo #if XENKO_PLATFORM_WINDOWS_DESKTOP var stageStringBuilder = new StringBuilder(); #endif - // if the shader (non-compute) does not have a pixel shader, we should add it for OpenGL and OpenGL ES. - if ((effectParameters.Platform == GraphicsPlatform.OpenGL || effectParameters.Platform == GraphicsPlatform.OpenGLES) && !parsingResult.EntryPoints.ContainsKey(ShaderStage.Pixel) && !parsingResult.EntryPoints.ContainsKey(ShaderStage.Compute)) - { - parsingResult.EntryPoints.Add(ShaderStage.Pixel, null); - } foreach (var stageBinding in parsingResult.EntryPoints) { diff --git a/sources/engine/Xenko.Shaders.Compiler/OpenGL/ShaderCompiler.cs b/sources/engine/Xenko.Shaders.Compiler/OpenGL/ShaderCompiler.cs index 2780486200..084177d8cb 100644 --- a/sources/engine/Xenko.Shaders.Compiler/OpenGL/ShaderCompiler.cs +++ b/sources/engine/Xenko.Shaders.Compiler/OpenGL/ShaderCompiler.cs @@ -58,14 +58,6 @@ public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, Shad switch (effectParameters.Platform) { - case GraphicsPlatform.OpenGL: - shaderPlatform = GlslShaderPlatform.OpenGL; - shaderVersion = 410; - break; - case GraphicsPlatform.OpenGLES: - shaderPlatform = GlslShaderPlatform.OpenGLES; - shaderVersion = effectParameters.Profile >= GraphicsProfile.Level_10_0 ? 300 : 100; - break; case GraphicsPlatform.Vulkan: shaderPlatform = GlslShaderPlatform.Vulkan; shaderVersion = 450; @@ -79,40 +71,7 @@ public ShaderBytecodeResult Compile(string shaderSource, string entryPoint, Shad if (shader == null) return shaderBytecodeResult; - if (effectParameters.Platform == GraphicsPlatform.OpenGLES) // TODO: Add check to run on android only. The current version breaks OpenGL ES on windows. - { - //TODO: Remove this ugly hack! - if (shaderSource.Contains($"Texture2D XenkoInternal_TextureExt0") && shader.Contains("uniform sampler2D")) - { - if (shaderPlatform != GlslShaderPlatform.OpenGLES || shaderVersion != 300) - throw new Exception("Invalid GLES platform or version: require OpenGLES 300"); - - shader = shader.Replace("uniform sampler2D", "uniform samplerExternalOES"); - shader = shader.Replace("#version 300 es", "#version 300 es\n#extension GL_OES_EGL_image_external_essl3 : require"); - } - } - - if (effectParameters.Platform == GraphicsPlatform.OpenGLES) - { - // store both ES 2 and ES 3 on OpenGL ES platforms - var shaderBytecodes = new ShaderLevelBytecode(); - if (effectParameters.Profile >= GraphicsProfile.Level_10_0) - { - shaderBytecodes.DataES3 = shader; - shaderBytecodes.DataES2 = null; - } - else - { - shaderBytecodes.DataES2 = shader; - shaderBytecodes.DataES3 = Compile(shaderSource, entryPoint, stage, GlslShaderPlatform.OpenGLES, 300, shaderBytecodeResult, reflection, inputAttributeNames, resourceBindings, sourceFilename); - } - using (var stream = new MemoryStream()) - { - BinarySerialization.Write(stream, shaderBytecodes); - rawData = stream.GetBuffer(); - } - } - else if (effectParameters.Platform == GraphicsPlatform.Vulkan) + if (effectParameters.Platform == GraphicsPlatform.Vulkan) { string inputFileExtension; switch (stage) diff --git a/sources/engine/Xenko/Graphics/GraphicsPlatform.cs b/sources/engine/Xenko/Graphics/GraphicsPlatform.cs index 62c03f1d67..f060a9b50a 100644 --- a/sources/engine/Xenko/Graphics/GraphicsPlatform.cs +++ b/sources/engine/Xenko/Graphics/GraphicsPlatform.cs @@ -20,21 +20,6 @@ public enum GraphicsPlatform /// Direct3D11, - /// - /// HLSL Direct3D Shader. - /// - Direct3D12, - - /// - /// GLSL OpenGL Shader. - /// - OpenGL, - - /// - /// GLSL OpenGL ES Shader. - /// - OpenGLES, - /// /// GLSL/SPIR-V Shader. /// diff --git a/sources/engine/Xenko/runtime.json b/sources/engine/Xenko/runtime.json index 40aaa06f7b..849f359755 100644 --- a/sources/engine/Xenko/runtime.json +++ b/sources/engine/Xenko/runtime.json @@ -17,57 +17,6 @@ "win-x64" ] }, - "win-d3d12": { - "#import": [ - "win" - ] - }, - "win-d3d12-x86": { - "#import": [ - "win-d3d12", - "win-x86" - ] - }, - "win-d3d12-x64": { - "#import": [ - "win-d3d12", - "win-x64" - ] - }, - "win-opengl": { - "#import": [ - "win" - ] - }, - "win-opengl-x86": { - "#import": [ - "win-opengl", - "win-x86" - ] - }, - "win-opengl-x64": { - "#import": [ - "win-opengl", - "win-x64" - ] - }, - "win-opengles": { - "#import": [ - "win" - ] - }, - "win-opengles-x86": { - "#import": [ - "win-opengles", - "win-x86" - ] - }, - "win-opengles-x64": { - "#import": [ - "win-opengles", - "win-x64" - ] - }, "win-vulkan": { "#import": [ "win" @@ -103,60 +52,6 @@ "win7-x64" ] }, - "win7-d3d12": { - "#import": [ - "win-d3d12", - "win7" - ] - }, - "win7-d3d12-x86": { - "#import": [ - "win7-d3d12", - "win7-x86" - ] - }, - "win7-d3d12-x64": { - "#import": [ - "win7-d3d12", - "win7-x64" - ] - }, - "win7-opengl": { - "#import": [ - "win-opengl", - "win7" - ] - }, - "win7-opengl-x86": { - "#import": [ - "win7-opengl", - "win7-x86" - ] - }, - "win7-opengl-x64": { - "#import": [ - "win7-opengl", - "win7-x64" - ] - }, - "win7-opengles": { - "#import": [ - "win-opengles", - "win7" - ] - }, - "win7-opengles-x86": { - "#import": [ - "win7-opengles", - "win7-x86" - ] - }, - "win7-opengles-x64": { - "#import": [ - "win7-opengles", - "win7-x64" - ] - }, "win7-vulkan": { "#import": [ "win-vulkan", @@ -193,95 +88,7 @@ "win10-x64" ] }, - "win10-d3d12": { - "#import": [ - "win-d3d12", - "win10" - ] - }, - "win10-d3d12-x86": { - "#import": [ - "win10-d3d12", - "win10-x86" - ] - }, - "win10-d3d12-x64": { - "#import": [ - "win10-d3d12", - "win10-x64" - ] - }, - "win10-opengl": { - "#import": [ - "win-opengl", - "win10" - ] - }, - "win10-opengl-x86": { - "#import": [ - "win10-opengl", - "win10-x86" - ] - }, - "win10-opengl-x64": { - "#import": [ - "win10-opengl", - "win10-x64" - ] - }, - "win10-opengles": { - "#import": [ - "win-opengles", - "win10" - ] - }, - "win10-opengles-x86": { - "#import": [ - "win10-opengles", - "win10-x86" - ] - }, - "win10-opengles-x64": { - "#import": [ - "win10-opengles", - "win10-x64" - ] - }, - "win10-vulkan": { - "#import": [ - "win-vulkan", - "win10" - ] - }, - "win10-vulkan-x86": { - "#import": [ - "win10-vulkan", - "win10-x86" - ] - }, - "win10-vulkan-x64": { - "#import": [ - "win10-vulkan", - "win10-x64" - ] - }, - "linux-opengl": { - "#import": [ - "linux" - ] - }, - "linux-opengl-x64": { - "#import": [ - "linux-opengl", - "linux-x64" - ] - }, - "linux-vulkan": { - "#import": [ - "linux" - ] - }, - "linux-vulkan-x64": { + "linux": { "#import": [ "linux-vulkan", "linux-x64" diff --git a/sources/engine/Xenko/runtime.tt b/sources/engine/Xenko/runtime.tt index b0e7ffa26a..0a220aa078 100644 --- a/sources/engine/Xenko/runtime.tt +++ b/sources/engine/Xenko/runtime.tt @@ -8,7 +8,7 @@ "runtimes": { <# foreach (var platform in new[] { "win", "win7", "win10", "linux" }) { - foreach (var graphicsPlatform in platform.StartsWith("win") ? new[] { "d3d11", "d3d12", "opengl", "opengles", "vulkan" } : new[] { "opengl", "vulkan" }) + foreach (var graphicsPlatform in platform.StartsWith("win") ? new[] { "d3d11", "vulkan" } : new[] { "vulkan" }) { var platformForGraphicsPlatformVariant = platform.StartsWith("win") ? "win" : platform; foreach (var cpuVariant in platform.StartsWith("win") ? new[] { string.Empty, "-x86", "-x64" } : new[] { string.Empty, "-x64" }) diff --git a/sources/targets/Xenko.GlobalSettings.targets b/sources/targets/Xenko.GlobalSettings.targets index 9eee3c6fd8..27de4a1224 100644 --- a/sources/targets/Xenko.GlobalSettings.targets +++ b/sources/targets/Xenko.GlobalSettings.targets @@ -26,24 +26,20 @@ - Direct3D11;Direct3D12;OpenGL;OpenGLES;Vulkan + Direct3D11;Vulkan Direct3D11 <_XenkoGraphicsApisWindows>;$(XenkoGraphicsApisWindows); - OpenGL;Vulkan - OpenGL + Vulkan + Vulkan <_XenkoGraphicsApisLinux>;$(XenkoGraphicsApisLinux); $(RuntimeIdentifiers);win - $(RuntimeIdentifiers);win-d3d12 - $(RuntimeIdentifiers);win-opengl - $(RuntimeIdentifiers);win-opengles $(RuntimeIdentifiers);win-vulkan - $(RuntimeIdentifiers);linux - $(RuntimeIdentifiers);linux-vulkan + $(RuntimeIdentifiers);linux $(RuntimeIdentifiers);osx $([MSBuild]::Unescape($(RuntimeIdentifiers.Trim(';')))) @@ -59,18 +55,14 @@ $(RuntimeIdentifierDefault) - $(RuntimeIdentifierDefault) - $(RuntimeIdentifierDefault) + $(RuntimeIdentifierDefault) + $(RuntimeIdentifierDefault) $(RuntimeIdentifierDefault) Direct3D11 - Direct3D12 - OpenGL - OpenGLES Vulkan - OpenGL - Vulkan + Vulkan Vulkan @@ -92,22 +84,10 @@ XENKO_GRAPHICS_API_DIRECT3D;XENKO_GRAPHICS_API_DIRECT3D11 - - XENKO_GRAPHICS_API_DIRECT3D;XENKO_GRAPHICS_API_DIRECT3D12 - - XENKO_GRAPHICS_API_NULL - - XENKO_GRAPHICS_API_OPENGL;XENKO_GRAPHICS_API_OPENGLCORE - - - - XENKO_GRAPHICS_API_OPENGL;XENKO_GRAPHICS_API_OPENGLES - - XENKO_GRAPHICS_API_VULKAN @@ -159,11 +139,9 @@ SDL - $(XenkoUI);OPENTK - $(XenkoUI);WINFORMS;WPF + $(XenkoUI);WINFORMS;WPF $(DefineConstants);XENKO_UI_SDL - $(DefineConstants);XENKO_UI_OPENTK $(DefineConstants);XENKO_UI_WINFORMS $(DefineConstants);XENKO_UI_WPF From 103fd392770d5da4caf473a3ef9957f4e250f4fc Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 21 Feb 2020 19:27:53 -0500 Subject: [PATCH 0783/2038] Physics: update physics libraries --- deps/bepuphysics2/BepuPhysics.dll | 4 ++-- deps/bepuphysics2/BepuPhysics.pdb | 4 ++-- deps/bepuphysics2/BepuUtilities.dll | 2 +- deps/bepuphysics2/BepuUtilities.pdb | 2 +- deps/bepuphysics2/Debug/BepuPhysics.dll | 4 ++-- deps/bepuphysics2/Debug/BepuPhysics.pdb | 4 ++-- deps/bepuphysics2/Debug/BepuUtilities.dll | 2 +- deps/bepuphysics2/Debug/BepuUtilities.pdb | 2 +- deps/bepuphysics2/Release/BepuPhysics.dll | 4 ++-- deps/bepuphysics2/Release/BepuPhysics.pdb | 4 ++-- deps/bepuphysics2/Release/BepuUtilities.dll | 4 ++-- deps/bepuphysics2/Release/BepuUtilities.pdb | 4 ++-- 12 files changed, 20 insertions(+), 20 deletions(-) diff --git a/deps/bepuphysics2/BepuPhysics.dll b/deps/bepuphysics2/BepuPhysics.dll index 38f8f05582..d814346f7f 100644 --- a/deps/bepuphysics2/BepuPhysics.dll +++ b/deps/bepuphysics2/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:3eb5bd1d5f9eb3f9033b161503653104ad08d2a032f872489abb27778c4206b8 -size 710144 +oid sha256:fcbcdc213d8de93a08072dd3773192f13f683e5e8058710eceef07b8b8a99155 +size 711168 diff --git a/deps/bepuphysics2/BepuPhysics.pdb b/deps/bepuphysics2/BepuPhysics.pdb index 53ca81fdd9..28ea16ccd4 100644 --- a/deps/bepuphysics2/BepuPhysics.pdb +++ b/deps/bepuphysics2/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79bffd15e34bff276f85291be5824a00fde10e29314b2b9f853a58f5bb9acfe5 -size 307176 +oid sha256:bf900496db046f7f03f45510b15404eab14452d359de1089aa08fb42199ec3a0 +size 307680 diff --git a/deps/bepuphysics2/BepuUtilities.dll b/deps/bepuphysics2/BepuUtilities.dll index 7bf8aa1513..1556808a02 100644 --- a/deps/bepuphysics2/BepuUtilities.dll +++ b/deps/bepuphysics2/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:69fb2eb7a0391839b4fcc41c882c46b15dc17ff29fbde81902f782b89b6c9d94 +oid sha256:079d7f3f0462958c970af84ed30a676c0b45d7a92e6187c1df4532c08bc7f22a size 125952 diff --git a/deps/bepuphysics2/BepuUtilities.pdb b/deps/bepuphysics2/BepuUtilities.pdb index 1b09444ce0..da237fe76b 100644 --- a/deps/bepuphysics2/BepuUtilities.pdb +++ b/deps/bepuphysics2/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:bc15cf51b2337c8e83075fe829cee5e764f7ab0ffbd2db7429b9507125273d95 +oid sha256:86b8da7f9e3eaa1b46b48cac6f7fcbaa01599cc9859db1ac3cf4212975d4ff1d size 51092 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.dll b/deps/bepuphysics2/Debug/BepuPhysics.dll index b9a3a5b043..8af4d55959 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.dll +++ b/deps/bepuphysics2/Debug/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b1f6eb22b121333288a3683b555e3070238536cd76ae0d9b7f1efa429c9f60fb -size 812032 +oid sha256:9f13d8086eaf6a68094c236c6db529e989bb750cc9ebed3da50d7df0ee00d131 +size 813568 diff --git a/deps/bepuphysics2/Debug/BepuPhysics.pdb b/deps/bepuphysics2/Debug/BepuPhysics.pdb index f02fe041b0..5ad6c90fc9 100644 --- a/deps/bepuphysics2/Debug/BepuPhysics.pdb +++ b/deps/bepuphysics2/Debug/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:acecf201f1e7aa5e4eeb79ac9e9073507cae6db2edcdd5fa1d85e8f11fe4a4b5 -size 401264 +oid sha256:874d959710c2e452cbc69f5833051f9aafd30ef6e826e249028290c489ad6613 +size 401764 diff --git a/deps/bepuphysics2/Debug/BepuUtilities.dll b/deps/bepuphysics2/Debug/BepuUtilities.dll index 2e7f4d3b42..ce7df708e0 100644 --- a/deps/bepuphysics2/Debug/BepuUtilities.dll +++ b/deps/bepuphysics2/Debug/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:cde4de526cded1667c63a0338a58bb2f902a5c131105beee6f50d25ae95ea9d7 +oid sha256:c13e95a5b949df14be9a29026b99fa0ebafcc1569c64127192b4276c16ccc2d4 size 149504 diff --git a/deps/bepuphysics2/Debug/BepuUtilities.pdb b/deps/bepuphysics2/Debug/BepuUtilities.pdb index dad90b4a3c..c526b66d00 100644 --- a/deps/bepuphysics2/Debug/BepuUtilities.pdb +++ b/deps/bepuphysics2/Debug/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:a4cef340b7c15923f11cbbaa2ab9e319f95243eb3f88988d6f63d2b9394eb5d7 +oid sha256:988b91d6c9a7f4672d21a5d8a5029d8e89d648d71556766e11f7aff51c4a16cd size 67884 diff --git a/deps/bepuphysics2/Release/BepuPhysics.dll b/deps/bepuphysics2/Release/BepuPhysics.dll index 58b9319470..d814346f7f 100644 --- a/deps/bepuphysics2/Release/BepuPhysics.dll +++ b/deps/bepuphysics2/Release/BepuPhysics.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6c60bd89b4ac7f5fdf18b5f09f0dc978366a7613b38b166837cc7a499b9dde01 -size 708608 +oid sha256:fcbcdc213d8de93a08072dd3773192f13f683e5e8058710eceef07b8b8a99155 +size 711168 diff --git a/deps/bepuphysics2/Release/BepuPhysics.pdb b/deps/bepuphysics2/Release/BepuPhysics.pdb index 0c6e873277..28ea16ccd4 100644 --- a/deps/bepuphysics2/Release/BepuPhysics.pdb +++ b/deps/bepuphysics2/Release/BepuPhysics.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4b638db41da657824628fec05bcfe03cdebda786e51afccc7f35e8af1891640d -size 307480 +oid sha256:bf900496db046f7f03f45510b15404eab14452d359de1089aa08fb42199ec3a0 +size 307680 diff --git a/deps/bepuphysics2/Release/BepuUtilities.dll b/deps/bepuphysics2/Release/BepuUtilities.dll index a2032b96bb..1556808a02 100644 --- a/deps/bepuphysics2/Release/BepuUtilities.dll +++ b/deps/bepuphysics2/Release/BepuUtilities.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:5ac84baa3473b17780872f49177367a23b6e569e2b91e133f85bf210a5acc949 -size 126464 +oid sha256:079d7f3f0462958c970af84ed30a676c0b45d7a92e6187c1df4532c08bc7f22a +size 125952 diff --git a/deps/bepuphysics2/Release/BepuUtilities.pdb b/deps/bepuphysics2/Release/BepuUtilities.pdb index bdcbe8f6e4..da237fe76b 100644 --- a/deps/bepuphysics2/Release/BepuUtilities.pdb +++ b/deps/bepuphysics2/Release/BepuUtilities.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:afb1853b76f3fbd9fc9e1455afb2280b4a7d3c0f52ec2f7cdaea195658b681a5 -size 51596 +oid sha256:86b8da7f9e3eaa1b46b48cac6f7fcbaa01599cc9859db1ac3cf4212975d4ff1d +size 51092 From e68a86e28194a9c13aa597271e5f61536c4c0696 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 21 Feb 2020 21:43:49 -0500 Subject: [PATCH 0784/2038] GameSettings: better specify DefaultResolution.txt file location --- sources/engine/Xenko.Engine/Engine/Game.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/Game.cs b/sources/engine/Xenko.Engine/Engine/Game.cs index c3728c17a3..6d6246fcbb 100644 --- a/sources/engine/Xenko.Engine/Engine/Game.cs +++ b/sources/engine/Xenko.Engine/Engine/Game.cs @@ -210,9 +210,10 @@ public bool SetDefaultSettings(int width, int height, bool fullscreen) { GetDefaultSettings(out int current_width, out int current_height, out bool current_fullscreen); if (width == current_width && height == current_height && current_fullscreen == fullscreen) return false; try { - System.IO.File.WriteAllText("DefaultResolution.txt", width.ToString() + "\n" + - height.ToString() + "\n" + - (fullscreen ? "full" : "window")); + System.IO.File.WriteAllText(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/DefaultResolution.txt", + width.ToString() + "\n" + + height.ToString() + "\n" + + (fullscreen ? "fullscreen" : "window")); return true; } catch(Exception e) { return false; @@ -236,6 +237,7 @@ public void OverrideDefaultSettings(int width, int height, bool fullscreen) { /// Gets default settings that will be used on game startup, if AutoLoadDefaultSettings is true. Caps resolution to native display resolution. /// public void GetDefaultSettings(out int width, out int height, out bool fullscreen) { + string defaultFile = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/DefaultResolution.txt"; // default settings are maximum native resolution width = int.MaxValue; height = int.MaxValue; @@ -245,9 +247,9 @@ public void GetDefaultSettings(out int width, out int height, out bool fullscree width = settingsOverrideW; height = settingsOverrideH; fullscreen = settingsOverrideFS; - } else if (File.Exists("DefaultResolution.txt")) { + } else if (File.Exists(defaultFile)) { try { - string[] vals = File.ReadAllLines("DefaultResolution.txt"); + string[] vals = File.ReadAllLines(defaultFile); width = int.Parse(vals[0].Trim()); height = int.Parse(vals[1].Trim()); fullscreen = vals[2].Trim().ToLower().StartsWith("full"); From aaf4e93b823a8be0622f0765d7966c43113a69a7 Mon Sep 17 00:00:00 2001 From: Basewq Date: Wed, 19 Feb 2020 19:41:13 +1300 Subject: [PATCH 0785/2038] [Core] Fix spelling matrices in Matrix documentation --- sources/core/Xenko.Core.Mathematics/Matrix.cs | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/sources/core/Xenko.Core.Mathematics/Matrix.cs b/sources/core/Xenko.Core.Mathematics/Matrix.cs index 43f889e443..2d7ea8c70d 100644 --- a/sources/core/Xenko.Core.Mathematics/Matrix.cs +++ b/sources/core/Xenko.Core.Mathematics/Matrix.cs @@ -7,17 +7,17 @@ // ----------------------------------------------------------------------------- /* * Copyright (c) 2007-2011 SlimDX Group -* +* * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: -* +* * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. -* +* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -77,7 +77,7 @@ public struct Matrix : IEquatable, IFormattable /// Value at row 4 column 1 of the matrix. /// public float M41; - + /// /// Value at row 1 column 2 of the matrix. /// @@ -102,7 +102,7 @@ public struct Matrix : IEquatable, IFormattable /// Value at row 1 column 3 of the matrix. /// public float M13; - + /// /// Value at row 2 column 3 of the matrix. /// @@ -117,7 +117,7 @@ public struct Matrix : IEquatable, IFormattable /// Value at row 4 column 3 of the matrix. /// public float M43; - + /// /// Value at row 1 column 4 of the matrix. /// @@ -598,14 +598,14 @@ public void DecomposeLQ(out Matrix L, out Matrix Q) L = new Matrix(); L.M11 = Vector4.Dot(Q.Row1, Row1); - + L.M21 = Vector4.Dot(Q.Row1, Row2); L.M22 = Vector4.Dot(Q.Row2, Row2); - + L.M31 = Vector4.Dot(Q.Row1, Row3); L.M32 = Vector4.Dot(Q.Row2, Row3); L.M33 = Vector4.Dot(Q.Row3, Row3); - + L.M41 = Vector4.Dot(Q.Row1, Row4); L.M42 = Vector4.Dot(Q.Row2, Row4); L.M43 = Vector4.Dot(Q.Row3, Row4); @@ -622,7 +622,7 @@ public void Decompose(out float yaw, out float pitch, out float roll) { pitch = (float)Math.Asin(-M32); // Hardcoded constant - burn him, he's a witch - // double threshold = 0.001; + // double threshold = 0.001; double test = Math.Cos(pitch); if (test > MathUtil.ZeroTolerance) { @@ -1310,16 +1310,16 @@ public static Matrix Negate(Matrix value) } /// - /// Performs a linear interpolation between two matricies. + /// Performs a linear interpolation between two matrices. /// /// Start matrix. /// End matrix. /// Value between 0 and 1 indicating the weight of . - /// When the method completes, contains the linear interpolation of the two matricies. + /// When the method completes, contains the linear interpolation of the two matrices. /// /// This method performs the linear interpolation based on the following formula. /// start + (end - start) * amount - /// Passing a value of 0 will cause to be returned; a value of 1 will cause to be returned. + /// Passing a value of 0 will cause to be returned; a value of 1 will cause to be returned. /// public static void Lerp(ref Matrix start, ref Matrix end, float amount, out Matrix result) { @@ -1342,7 +1342,7 @@ public static void Lerp(ref Matrix start, ref Matrix end, float amount, out Matr } /// - /// Performs a linear interpolation between two matricies. + /// Performs a linear interpolation between two matrices. /// /// Start matrix. /// End matrix. @@ -1351,7 +1351,7 @@ public static void Lerp(ref Matrix start, ref Matrix end, float amount, out Matr /// /// This method performs the linear interpolation based on the following formula. /// start + (end - start) * amount - /// Passing a value of 0 will cause to be returned; a value of 1 will cause to be returned. + /// Passing a value of 0 will cause to be returned; a value of 1 will cause to be returned. /// public static Matrix Lerp(Matrix start, Matrix end, float amount) { @@ -1361,7 +1361,7 @@ public static Matrix Lerp(Matrix start, Matrix end, float amount) } /// - /// Performs a cubic interpolation between two matricies. + /// Performs a cubic interpolation between two matrices. /// /// Start matrix. /// End matrix. @@ -2537,13 +2537,13 @@ public static Matrix Reflection(Plane plane) /// The plane onto which to project the geometry as a shadow. This parameter is assumed to be normalized. /// When the method completes, contains the shadow matrix. public static void Shadow(ref Vector4 light, ref Plane plane, out Matrix result) - { + { float dot = (plane.Normal.X * light.X) + (plane.Normal.Y * light.Y) + (plane.Normal.Z * light.Z) + (plane.D * light.W); float x = -plane.Normal.X; float y = -plane.Normal.Y; float z = -plane.Normal.Z; float d = -plane.D; - + result.M11 = (x * light.X) + dot; result.M21 = y * light.X; result.M31 = z * light.X; @@ -2561,7 +2561,7 @@ public static void Shadow(ref Vector4 light, ref Plane plane, out Matrix result) result.M34 = z * light.W; result.M44 = (d * light.W) + dot; } - + /// /// Creates a matrix that flattens geometry into a shadow. /// @@ -3168,7 +3168,7 @@ public static void Transformation(ref Vector3 scalingCenter, ref Quaternion scal Matrix sr = RotationQuaternion(scalingRotation); result = Translation(-scalingCenter) * Transpose(sr) * Scaling(scaling) * sr * Translation(scalingCenter) * Translation(-rotationCenter) * - RotationQuaternion(rotation) * Translation(rotationCenter) * Translation(translation); + RotationQuaternion(rotation) * Translation(rotationCenter) * Translation(translation); } /// @@ -3200,7 +3200,7 @@ public static Matrix Transformation(Vector3 scalingCenter, Quaternion scalingRot /// When the method completes, contains the created transformation matrix. public static void Transformation2D(ref Vector2 scalingCenter, float scalingRotation, ref Vector2 scaling, ref Vector2 rotationCenter, float rotation, ref Vector2 translation, out Matrix result) { - result = Translation((Vector3)(-scalingCenter)) * RotationZ(-scalingRotation) * Scaling((Vector3)scaling) * RotationZ(scalingRotation) * Translation((Vector3)scalingCenter) * + result = Translation((Vector3)(-scalingCenter)) * RotationZ(-scalingRotation) * Scaling((Vector3)scaling) * RotationZ(scalingRotation) * Translation((Vector3)scalingCenter) * Translation((Vector3)(-rotationCenter)) * RotationZ(rotation) * Translation((Vector3)rotationCenter) * Translation((Vector3)translation); result.M33 = 1f; @@ -3272,11 +3272,11 @@ public unsafe void TransposeMatrixFrom(float* src, int columns, int rows) } /// - /// Adds two matricies. + /// Adds two matrices. /// /// The first matrix to add. /// The second matrix to add. - /// The sum of the two matricies. + /// The sum of the two matrices. public static Matrix operator +(Matrix left, Matrix right) { Matrix result; @@ -3295,11 +3295,11 @@ public unsafe void TransposeMatrixFrom(float* src, int columns, int rows) } /// - /// Subtracts two matricies. + /// Subtracts two matrices. /// /// The first matrix to subtract. /// The second matrix to subtract. - /// The difference between the two matricies. + /// The difference between the two matrices. public static Matrix operator -(Matrix left, Matrix right) { Matrix result; @@ -3350,7 +3350,7 @@ public unsafe void TransposeMatrixFrom(float* src, int columns, int rows) /// /// The first matrix to multiply. /// The second matrix to multiply. - /// The product of the two matricies. + /// The product of the two matrices. public static Matrix operator *(Matrix left, Matrix right) { Matrix result; @@ -3372,11 +3372,11 @@ public unsafe void TransposeMatrixFrom(float* src, int columns, int rows) } /// - /// Divides two matricies. + /// Divides two matrices. /// /// The first matrix to divide. /// The second matrix to divide. - /// The quotient of the two matricies. + /// The quotient of the two matrices. public static Matrix operator /(Matrix left, Matrix right) { Matrix result; @@ -3477,7 +3477,7 @@ public string ToString(string format, IFormatProvider formatProvider) /// Returns a hash code for this instance. /// /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// public override int GetHashCode() { From 999bad547e2363d890a4bdc196b51f03e9b36c17 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 22 Feb 2020 11:26:35 +1300 Subject: [PATCH 0786/2038] [Core] Promote Matrix.Multiply remarks to summary tags so it's visible in Intellisense --- sources/core/Xenko.Core.Mathematics/Matrix.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sources/core/Xenko.Core.Mathematics/Matrix.cs b/sources/core/Xenko.Core.Mathematics/Matrix.cs index 2d7ea8c70d..85fbfda612 100644 --- a/sources/core/Xenko.Core.Mathematics/Matrix.cs +++ b/sources/core/Xenko.Core.Mathematics/Matrix.cs @@ -1043,6 +1043,8 @@ public static Matrix Multiply(Matrix left, float right) /// /// Determines the product of two matrices. + /// Variables passed as or must not be used as the out parameter + /// , because is calculated in-place. /// /// The first matrix to multiply. /// The second matrix to multiply. @@ -1069,6 +1071,8 @@ public static void MultiplyTo(ref Matrix left, ref Matrix right, out Matrix resu /// /// Determines the product of two matrices. + /// Variables passed as or must not be used as the out parameter + /// , because is calculated in-place. /// /// The first matrix to multiply. /// The second matrix to multiply. @@ -1095,6 +1099,8 @@ public static void Multiply(ref Matrix left, ref Matrix right, out Matrix result /// /// Determines the product of two matrices. + /// Variables passed as or must not be used as the out parameter + /// , because is calculated in-place. /// /// The first matrix to multiply. /// The second matrix to multiply. From 957621d138d7cc41323d7a411834eaae3647bd88 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 22 Feb 2020 14:16:29 +1300 Subject: [PATCH 0787/2038] [Engine] Fast matrix usage by avoiding needless Matrix copies --- .../Xenko.Engine/Engine/TransformComponent.cs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/TransformComponent.cs b/sources/engine/Xenko.Engine/Engine/TransformComponent.cs index 84f36ce392..33023784e0 100644 --- a/sources/engine/Xenko.Engine/Engine/TransformComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/TransformComponent.cs @@ -303,8 +303,7 @@ public void UpdateLocalFromWorld() var scene = Entity?.Scene; if (scene != null) { - var inverseSceneTransform = scene.WorldMatrix; - inverseSceneTransform.Invert(); + Matrix.Invert(ref scene.WorldMatrix, out var inverseSceneTransform); Matrix.Multiply(ref WorldMatrix, ref inverseSceneTransform, out LocalMatrix); } else @@ -315,8 +314,7 @@ public void UpdateLocalFromWorld() else { //We are not root so we need to derive the local matrix as well - var inverseParent = Parent.WorldMatrix; - inverseParent.Invert(); + Matrix.Invert(ref Parent.WorldMatrix, out var inverseParent); Matrix.Multiply(ref WorldMatrix, ref inverseParent, out LocalMatrix); } } @@ -419,8 +417,6 @@ internal void UpdateWorldMatrixInternal(bool recursive) } else { - WorldMatrix = LocalMatrix; - var scene = Entity?.Scene; if (scene != null) { @@ -429,8 +425,11 @@ internal void UpdateWorldMatrixInternal(bool recursive) scene.UpdateWorldMatrix(); } - var curWorldMatrix = WorldMatrix; // Must make a copy to use as the ref parameter, otherwise matrix will not be calculated correctly - Matrix.Multiply(ref curWorldMatrix, ref scene.WorldMatrix, out WorldMatrix); + Matrix.Multiply(ref LocalMatrix, ref scene.WorldMatrix, out WorldMatrix); + } + else + { + WorldMatrix = LocalMatrix; } } From 59e7e78be4dba65b17b7f7567391c070f1e1dc9a Mon Sep 17 00:00:00 2001 From: Basewq Date: Sun, 23 Feb 2020 15:10:58 +1300 Subject: [PATCH 0788/2038] [GameStudio] Stop updating and rendering game scenes, prefabs and preview asset sub-windows when they are hidden in tab control --- .../GameEditor/Services/EditorGameController.cs | 10 ++++++++++ .../GameEditor/Services/IEditorGameController.cs | 10 ++++++++++ .../GameEditor/ViewModels/GameEditorViewModel.cs | 14 ++++++++++++-- .../Services/IAssetPreviewService.cs | 4 ++++ .../EditorGame/Game/EditorServiceGame.cs | 12 ++++++++++-- .../Preview/GameStudioPreviewService.cs | 12 +++++++++++- .../Xenko.GameStudio/AssetEditorsManager.cs | 15 +++++++++++++++ .../editor/Xenko.GameStudio/GameStudioWindow.xaml | 2 +- .../Xenko.GameStudio/GameStudioWindow.xaml.cs | 13 +++++++++++++ .../editor/Xenko.GameStudio/PreviewViewModel.cs | 15 ++++++++++++++- 10 files changed, 100 insertions(+), 7 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs index bb110732a9..6ecaff6f0e 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs @@ -231,6 +231,16 @@ public async Task StartGame() return true; } + public void PauseGame() + { + Game.IsSuspended = true; + } + + public void ResumeGame() + { + Game.IsSuspended = false; + } + public Vector3 GetMousePositionInScene(bool lastRightClick) { EnsureNotDestroyed(); diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs index 7b8384c907..191910106e 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs @@ -45,6 +45,16 @@ public interface IEditorGameController : IDestroyable, IDispatcherService /// True if the scene was successfully created, false otherwise. Task CreateScene(); + /// + /// Stops the game from updating and rendering. + /// + void PauseGame(); + + /// + /// Resumes the game updating and rendering. + /// + void ResumeGame(); + /// /// Finds the game-side instance corresponding to the part with the given id, if it exists. /// diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs index 19337b094a..4ff26e22f4 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs @@ -29,7 +29,7 @@ protected GameEditorViewModel([NotNull] AssetViewModel asset, [NotNull] Func @@ -77,6 +77,16 @@ public override void Destroy() base.Destroy(); } + public void PauseGame() + { + Controller.PauseGame(); + } + + public void ResumeGame() + { + Controller.ResumeGame(); + } + protected virtual async Task InitializeEditor() { Dispatcher.EnsureAccess(); @@ -112,7 +122,7 @@ private void CopyErrorToClipboard() SafeClipboard.SetText(log); } - private void Resume() + private void ResumeFromError() { Controller.GetService()?.Resume(); } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs index f6dcd20f56..ce2a2e62e3 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs @@ -13,5 +13,9 @@ public interface IAssetPreviewService : IDisposable object GetCurrentPreviewView(); event EventHandler PreviewAssetUpdated; + + void ResumeRenderPreview(); + + void SuspendRenderPreview(); } } diff --git a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs index 2606f208c3..9e8c4b0558 100644 --- a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs +++ b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs @@ -48,6 +48,14 @@ public abstract class EditorServiceGame : EmbeddedGame public IGameSettingsAccessor PackageSettings { get; set; } + /// + /// True if the game is paused. + /// + /// + /// Used when game is not visible in the editor. + /// + public bool IsSuspended { get; set; } + /// /// True if game is faulted (not running). /// @@ -114,7 +122,7 @@ protected override void Initialize() protected override void Update(GameTime gameTime) { // Keep going only if last exception has been "resolved" - if (Faulted) + if (Faulted || IsSuspended) return; try @@ -137,7 +145,7 @@ protected override void Update(GameTime gameTime) protected override void Draw(GameTime gameTime) { // Keep going only if last exception has been "resolved" - if (Faulted) + if (Faulted || IsSuspended) return; try diff --git a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs index 4dc9fa0be5..9df92bf8a6 100644 --- a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs +++ b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs @@ -195,7 +195,7 @@ public void SetAssetToPreview(AssetViewModel asset) } public AssetCompilerResult Compile(AssetItem asset) - { + { return previewCompiler.Prepare(previewCompileContext, asset); } @@ -319,5 +319,15 @@ public void RegisterAssetPreviewFactories(IReadOnlyDictionary assetPreviewFactories.Add(x.Key, x.Value)); } + + public void ResumeRenderPreview() + { + PreviewGame.IsSuspended = false; + } + + public void SuspendRenderPreview() + { + PreviewGame.IsSuspended = true; + } } } diff --git a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs index de005b51cb..356798a653 100644 --- a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs +++ b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs @@ -564,6 +564,21 @@ private static void EditorPaneIsActiveChanged(object sender, EventArgs e) { element.Loaded -= EditorPaneContentLoaded; } + var assetViewModel = element?.DataContext as AssetViewModel; + if (assetViewModel?.Editor != null) + { + if (assetViewModel.Editor is Assets.Presentation.AssetEditors.GameEditor.ViewModels.GameEditorViewModel gameEditor) + { + if (editorPane.IsActive) + { + gameEditor.ResumeGame(); + } + else + { + gameEditor.PauseGame(); + } + } + } } } diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index ad1a639c84..57fd7c34a3 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -877,7 +877,7 @@ - diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs index 700daddbc7..a59c4fb97e 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs @@ -67,6 +67,19 @@ public GameStudioWindow(EditorViewModel editor) Application.Current.Activated += (s, e) => editor.ServiceProvider.Get().ShowDelayedNotifications(); Loaded += GameStudioLoaded; + if (editor is GameStudioViewModel gsViewModel) + { + AssetPreviewPane.IsSelectedChanged += (sender, e) => + { + // This is the event when the Asset Preview tab is clicked on, or when another tab is clicked + // when in the same tab group. + // We handle the event here instead of making an OnEventCommandBehavior because WPF has some quirk where + // binding to the LayoutAnchorable's IsSelected for the CommandParameter ends up passing the previous value + // instead of the current value. + gsViewModel.Preview?.RenderPreviewCommand?.Execute(AssetPreviewPane.IsSelected); + }; + } + OpenMetricsProjectSession(editor); } diff --git a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs index 26734e384d..d9f354dec8 100644 --- a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs +++ b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs @@ -7,6 +7,7 @@ using Xenko.Core.Assets.Editor.Services; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Extensions; +using Xenko.Core.Presentation.Commands; using Xenko.Core.Presentation.ViewModel; namespace Xenko.GameStudio @@ -17,15 +18,19 @@ public class PreviewViewModel : DispatcherViewModel, IDisposable private IAssetPreviewService previewService; private object previewObject; - + public PreviewViewModel(SessionViewModel session) : base(session.SafeArgument(nameof(session)).ServiceProvider) { this.session = session; session.ActiveAssetView.SelectedAssets.CollectionChanged += SelectedAssetsCollectionChanged; session.ActiveAssetsChanged += ActiveAssetsChanged; + + RenderPreviewCommand = new AnonymousCommand(session.ServiceProvider, SetIsRendering); } + public CommandBase RenderPreviewCommand { get; } + public object PreviewObject { get { return previewObject; } private set { SetValue(ref previewObject, value); } } private IAssetPreviewService PreviewService @@ -97,5 +102,13 @@ private void SelectedAssetsCollectionChanged(object sender, NotifyCollectionChan previewService.SetAssetToPreview(null); } } + + private void SetIsRendering(bool canRender) + { + if (canRender) + PreviewService.ResumeRenderPreview(); + else + PreviewService.SuspendRenderPreview(); + } } } From e98c61dbc925d864833c58eafa77c90646f68ef2 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 22 Feb 2020 21:52:18 -0500 Subject: [PATCH 0789/2038] Audio: significantly simplify and streamline audio system GlobalSoundManager does everything you need, no need for audio processors, multiple listeners (which can cause native audio corruption if one isn't active), or audio emitters --- .../EntityFactories/AudioEntityFactory.cs | 17 - .../AssetEditors/Gizmos/AudioEmitterGizmo.cs | 15 - .../Gizmos/GizmoResources.Designer.cs | 12 +- .../View/ImageDictionary.xaml | 10 - .../Engine/TestAudioEmitterComponent.cs | 134 ----- .../Engine/TestAudioEmitterProcessor.cs | 493 ------------------ .../Xenko.Audio.Tests/TestAudioEmitter.cs | 90 ---- .../Xenko.Audio.Tests.Windows.csproj | 3 - sources/engine/Xenko.Audio/AudioEmitter.cs | 103 ---- sources/engine/Xenko.Audio/AudioEngine.cs | 2 +- .../engine/Xenko.Audio/DynamicSoundSource.cs | 1 - .../engine/Xenko.Audio/IPositionableSound.cs | 3 +- sources/engine/Xenko.Audio/SoundInstance.cs | 26 - .../Audio/AudioEmitterProcessor.cs | 284 ---------- .../Audio/AudioEmitterSoundController.cs | 294 ----------- .../Audio/AudioListenerProcessor.cs | 55 +- .../engine/Xenko.Engine/Audio/AudioSystem.cs | 35 -- .../Engine/AudioEmitterComponent.cs | 206 -------- .../Engine/AudioListenerComponent.cs | 5 +- .../Xenko.Engine/Engine/GlobalSoundManager.cs | 51 +- sources/engine/Xenko.Video/VideoComponent.cs | 6 - .../Xenko.Video/VideoInstance.Direct3D.cs | 3 +- 22 files changed, 24 insertions(+), 1824 deletions(-) delete mode 100644 sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/AudioEmitterGizmo.cs delete mode 100644 sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterComponent.cs delete mode 100644 sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterProcessor.cs delete mode 100644 sources/engine/Xenko.Audio.Tests/TestAudioEmitter.cs delete mode 100644 sources/engine/Xenko.Audio/AudioEmitter.cs delete mode 100644 sources/engine/Xenko.Engine/Audio/AudioEmitterProcessor.cs delete mode 100644 sources/engine/Xenko.Engine/Audio/AudioEmitterSoundController.cs delete mode 100644 sources/engine/Xenko.Engine/Engine/AudioEmitterComponent.cs diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/EntityFactories/AudioEntityFactory.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/EntityFactories/AudioEntityFactory.cs index f625e93d74..adbf8124d3 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/EntityFactories/AudioEntityFactory.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/EntityHierarchyEditor/EntityFactories/AudioEntityFactory.cs @@ -7,23 +7,6 @@ namespace Xenko.Assets.Presentation.AssetEditors.EntityHierarchyEditor.EntityFactories { - [Display(10, "Audio emitter", "Audio")] - public class AudioEmitterFactory : EntityFactory - { - [ModuleInitializer] - internal static void RegisterCategory() - { - EntityFactoryCategory.RegisterCategory(50, "Audio"); - } - - public override Task CreateEntity(EntityHierarchyItemViewModel parent) - { - var name = ComputeNewName(parent, "AudioEmitter"); - var component = new AudioEmitterComponent(); - return CreateEntityWithComponent(name, component); - } - } - [Display(20, "Audio listener", "Audio")] public class AudioListenerFactory : EntityFactory { diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/AudioEmitterGizmo.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/AudioEmitterGizmo.cs deleted file mode 100644 index cbdc08ec32..0000000000 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/AudioEmitterGizmo.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using Xenko.Engine; - -namespace Xenko.Assets.Presentation.AssetEditors.Gizmos -{ - [GizmoComponent(typeof(AudioEmitterComponent), true)] - public class AudioEmitterGizmo : BillboardingGizmo - { - public AudioEmitterGizmo(EntityComponent component) - : base(component, "AudioEmitter", GizmoResources.AudioEmitterGizmo) - { - } - } -} diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/GizmoResources.Designer.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/GizmoResources.Designer.cs index c6d3770100..a3c842804e 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/GizmoResources.Designer.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/Gizmos/GizmoResources.Designer.cs @@ -1,4 +1,4 @@ -//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.42000 @@ -70,16 +70,6 @@ internal static byte[] AmbientLightGizmo { } } - /// - /// Looks up a localized resource of type System.Byte[]. - /// - internal static byte[] AudioEmitterGizmo { - get { - object obj = ResourceManager.GetObject("AudioEmitterGizmo", resourceCulture); - return ((byte[])(obj)); - } - } - /// /// Looks up a localized resource of type System.Byte[]. /// diff --git a/sources/editor/Xenko.Assets.Presentation/View/ImageDictionary.xaml b/sources/editor/Xenko.Assets.Presentation/View/ImageDictionary.xaml index c2bdd5539f..7de264000f 100644 --- a/sources/editor/Xenko.Assets.Presentation/View/ImageDictionary.xaml +++ b/sources/editor/Xenko.Assets.Presentation/View/ImageDictionary.xaml @@ -888,16 +888,6 @@ - - - - - - - - - - diff --git a/sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterComponent.cs b/sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterComponent.cs deleted file mode 100644 index b43cb8da91..0000000000 --- a/sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterComponent.cs +++ /dev/null @@ -1,134 +0,0 @@ -//// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -//// This file is distributed under GPL v3. See LICENSE.md for details. -// -//using System; -// -//using Xunit; -// -//using Xenko.Core.IO; -//using Xenko.Core.Serialization.Assets; -//using Xenko.Engine; -// -//namespace Xenko.Audio.Tests.Engine -//{ -// /// -// /// Test the . Some of the test depends on internal implementation and can failed if implementation has been modified. -// /// -//// public class TestAudioEmitterComponent -// { -// /// -// /// Test Component default values and states. -// /// -// [Fact] -// public void TestInitialization() -// { -// var testInst = new AudioEmitterComponent(); -// Assert.Equal(testInst.DistanceScale, 1, "Default value of the distance scale is not correct"); -// Assert.Equal(testInst.DopplerScale, 1, "Default value of the doppler scale is not correct"); -// Assert.False(testInst.ShouldBeProcessed, "Default value of ShouldBeProcessed si not correct"); -// Assert.True(testInst.SoundEffectToController.Keys.Count ==0, "Controller list is not empty"); -// } -// -// [Fact] -// public void TestDistanceDopplerScale() -// { -// var testInst = new AudioEmitterComponent(); -// Assert.Throws(() => testInst.DistanceScale = -0.1f, "DistanceScale did not throw ArgumentOutOfRangeException"); -// Assert.Throws(() => testInst.DopplerScale = -0.1f, "DopplerScale did not throw ArgumentOutOfRangeException"); -// } -// -// /// -// /// Test the internal behaviour of the component when attaching and detaching sound to the component. -// /// -// [Fact] -// public void TestAttachDetachSounds() -// { -// var testInst = new AudioEmitterComponent(); -// using (var game = new Game()) -// { -// Game.InitializeAssetDatabase(); -// using (var audioStream1 = ContentManager.FileProvider.OpenStream("EffectToneA", VirtualFileMode.Open, VirtualFileAccess.Read)) -// using (var audioStream2 = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read)) -// using (var audioStream3 = ContentManager.FileProvider.OpenStream("EffectStereo", VirtualFileMode.Open, VirtualFileAccess.Read)) -// { -// var sound1 = SoundEffect.Load(game.Audio.AudioEngine, audioStream1); -// var sound2 = SoundEffect.Load(game.Audio.AudioEngine, audioStream2); -// var sound3 = SoundEffect.Load(game.Audio.AudioEngine, audioStream3); -// -// // Attach two soundEffect and check that their controller are correctly created. -// -// AudioEmitterSoundController soundController1 = null; -// AudioEmitterSoundController soundController2 = null; -// Assert.DoesNotThrow(() => testInst.AttachSoundEffect(sound1), "Adding a first soundEffect failed"); -// Assert.DoesNotThrow(() => soundController1 = testInst.SoundEffectToController[sound1], "There are no sound controller for sound1."); -// Assert.NotNull(soundController1, "Sound controller for sound1 is null"); -// -// Assert.DoesNotThrow(() => testInst.AttachSoundEffect(sound2), "Adding a second soundEffect failed"); -// Assert.DoesNotThrow(() => soundController2 = testInst.SoundEffectToController[sound2], "There are no sound controller for sound1."); -// Assert.NotNull(soundController2, "Sound controller for sound2 is null"); -// -// // Remove the two soundEffect and check that their controller are correctly erased. -// -// Assert.DoesNotThrow(() => testInst.DetachSoundEffect(sound2), "Removing a first soundEffect failed"); -// Assert.False(testInst.SoundEffectToController.ContainsKey(sound2), "The controller for sound2 is still present in the list."); -// -// Assert.DoesNotThrow(() => testInst.DetachSoundEffect(sound1), "Removing a second soundEffect failed"); -// Assert.False(testInst.SoundEffectToController.ContainsKey(sound1), "The controller for sound1 is still present in the list."); -// -// Assert.True(testInst.SoundEffectToController.Keys.Count == 0, "There are some controller left in the component list."); -// -// // Check the exception thrwon by attachSoundEffect. -// -// Assert.Throws(() => testInst.AttachSoundEffect(null), "AttachSoundEffect did not throw ArgumentNullException"); -// Assert.Throws(() => testInst.AttachSoundEffect(sound3), "AttachSoundEffect did not throw InvalidOperationException."); -// -// // Check the exception thrown by detachSoundEffect. -// -// Assert.Throws(() => testInst.DetachSoundEffect(null), "DetachSoundEffect did not throw ArgumentNullException."); -// Assert.Throws(() => testInst.DetachSoundEffect(sound1), "DetachSoundEffect did not throw ArgumentException "); -// } -// } -// } -// -// /// -// /// Test the function. -// /// -// [Fact] -// public void TestGetController() -// { -// var testInst = new AudioEmitterComponent(); -// using (var game = new Game()) -// { -// Game.InitializeAssetDatabase(); -// using (var audioStream1 = ContentManager.FileProvider.OpenStream("EffectToneA", VirtualFileMode.Open, VirtualFileAccess.Read)) -// using (var audioStream2 = ContentManager.FileProvider.OpenStream("EffectBip", VirtualFileMode.Open, VirtualFileAccess.Read)) -// { -// var sound1 = SoundEffect.Load(game.Audio.AudioEngine, audioStream1); -// var sound2 = SoundEffect.Load(game.Audio.AudioEngine, audioStream2); -// -// AudioEmitterSoundController soundController1 = null; -// AudioEmitterSoundController soundController2 = null; -// -// // Add two soundEffect and try to get their controller. -// -// testInst.AttachSoundEffect(sound1); -// Assert.DoesNotThrow(() => soundController1 = testInst.GetSoundEffectController(sound1), "Failed to get the controller associated to the soundEffect1."); -// -// testInst.AttachSoundEffect(sound2); -// Assert.DoesNotThrow(() => soundController2 = testInst.GetSoundEffectController(sound2), "Failed to get the controller associated to the soundEffect1."); -// -// // Suppress the two SoundEffects and check that the function throws the correct exception (ArgumentException) -// -// testInst.DetachSoundEffect(sound1); -// Assert.Throws(() => testInst.GetSoundEffectController(sound1), "GetController did not throw ArgumentException but sound1 was supposed to be detached."); -// -// testInst.DetachSoundEffect(sound2); -// Assert.Throws(() => testInst.GetSoundEffectController(sound2), "GetController did not throw ArgumentException but sound2 was supposed to be detached."); -// -// // Check the ArgumentNullException -// Assert.Throws(() => testInst.GetSoundEffectController(null), "GetController did not throw ArgumentNullException."); -// } -// } -// } -// } -//} diff --git a/sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterProcessor.cs b/sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterProcessor.cs deleted file mode 100644 index 96d216b100..0000000000 --- a/sources/engine/Xenko.Audio.Tests/Engine/TestAudioEmitterProcessor.cs +++ /dev/null @@ -1,493 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Linq; - -using Xunit; - -using Xenko.Core.Mathematics; -using Xenko.Engine; - -namespace Xenko.Audio.Tests.Engine -{ - /// - /// Test the . All the test are performed on internal members. - /// If the implementation of the is modified, those tests may not be valid anymore. - /// - public class TestAudioEmitterProcessor - { - private List listComps; - private List emitComps; - private List compEntities; - - private Entity rootEntity; - private Entity rootSubEntity1; - private Entity rootSubEntity2; - - private List sounds; - private List soundControllers; - - // build a simple entity hierarchy as follow that may be used for tests. - // o root - // / \ - // o o subEntities - // | | - // o o listCompEntities - private void BuildEntityHierarchy() - { - rootEntity = new Entity { Name = "Root entity" }; - rootSubEntity1 = new Entity { Name = "Root sub entity 1" }; - rootSubEntity2 = new Entity { Name = "Root sub entity 2" }; - compEntities = new List { new Entity { Name = "Comp entity 1" }, new Entity { Name = "Comp entity 2" } }; - - rootSubEntity1.Transform.Parent = rootEntity.Transform; - rootSubEntity2.Transform.Parent = rootEntity.Transform; - compEntities[0].Transform.Parent = rootSubEntity1.Transform; - compEntities[1].Transform.Parent = rootSubEntity2.Transform; - } - - /// - /// Load some default random , attach them to the emitter components, and query their controllers. - /// - /// - private void AddSoundEffectToEmitterComponents(Game game) - { - sounds = new List - { - game.Content.Load("EffectBip"), - game.Content.Load("EffectToneA"), - game.Content.Load("EffectToneA"), - }; - - emitComps[0].Sounds["EffectBip"] = sounds[0]; - emitComps[0].Sounds["EffectToneA"] = sounds[1]; - emitComps[1].Sounds["EffectToneA"] = sounds[2]; - - soundControllers = new List - { - emitComps[0]["EffectBip"], - emitComps[0]["EffectToneA"], - emitComps[1]["EffectToneA"], - }; - } - - /// - /// Add the root entity to the entity system - /// - /// - private void AddRootEntityToEntitySystem(Game game) - { - throw new NotImplementedException("TODO: UPDATE TO USE Scene and Graphics Composer"); // game.Entities.Add(rootEntity); - } - - /// - /// Add all the to the . - /// - /// - private void AddListenersToAudioSystem(Game game) - { - foreach (var t in listComps) - game.Audio.AddListener(t); - } - - /// - /// Create some and add them to 'compEntities'. - /// - private void CreateAndAddListenerComponentToEntities() - { - listComps = new List { new AudioListenerComponent(), new AudioListenerComponent() }; - - for (int i = 0; i < listComps.Count; i++) - compEntities[i].Add(listComps[i]); - } - - /// - /// Create some and add them to 'compEntities'. - /// - private void CreateAndAddEmitterComponentToEntities() - { - emitComps = new List { new AudioEmitterComponent(), new AudioEmitterComponent() }; - - for (int i = 0; i < compEntities.Count; i++) - compEntities[i].Add(emitComps[i]); - } - - // /// - // /// Check that each of the scene have one - // /// associated to each added to the . - // /// - // /// matching entities from the - // private void CheckSoundEffectExistance(Dictionary matchingEntities) - // { - // CheckSoundEffectExistance(new HashSet(listComps), matchingEntities); - // } - // - // /// - // /// Check that each of the scene have one - // /// associated to each of the list. - // /// - // /// the listener component that should exist - // /// matching entities from the - // private void CheckSoundEffectExistance(HashSet shouldExistListeners, Dictionary matchingEntities) - // { - // for (var i = 0; i < compEntities.Count; i++) - // { - // var data = matchingEntities[compEntities[i]]; - // foreach (var listComp in listComps) - // { - // foreach (var controller in emitComps[i].SoundToController.Values) - // { - // var currentKey = Tuple.Create(listComp, controller); - // if (shouldExistListeners.Contains(listComp)) - // Assert.True(data.ListenerControllerToSoundInstance.ContainsKey(currentKey), "Sound Effect instance should exist for registered listener"); - // else - // Assert.False(data.ListenerControllerToSoundInstance.ContainsKey(currentKey), "Sound Effect instance should not exist for not registered listener"); - // } - // } - // } - // } - - /// - /// Add and remove to the and check that - /// dedicated to each are correctly created. - /// - [Fact(Skip = "TODO: UPDATE TO USE Scene and Graphics Composer")] - public void TestAddRemoveListeners() - { - TestUtilities.CreateAndRunGame(TestAddRemoveListenersHelper, TestUtilities.ExitGame); - } - - private void TestAddRemoveListenersHelper(Game game) - { - BuildEntityHierarchy(); - CreateAndAddListenerComponentToEntities(); - CreateAndAddEmitterComponentToEntities(); - AddSoundEffectToEmitterComponents(game); - AddRootEntityToEntitySystem(game); - - throw new NotImplementedException("TODO: UPDATE TO USE Scene and Graphics Composer"); - //var matchingEntities = game.Entities.Processors.OfType().First().MatchingEntitiesForDebug; - - //// check that there are initially not SoundEffectInstance created. - //CheckSoundEffectExistance(new HashSet (), matchingEntities); - - //// add one listener - //game.Audio.AddListener(listComps[0]); - - //// check that there is now one SoundEffectInstance for each SoundController - //CheckSoundEffectExistance(new HashSet { listComps[0] }, matchingEntities); - - //// add another listener - //game.Audio.AddListener(listComps[1]); - - //// check that there is now two SoundEffectInstance for each SoundController - //CheckSoundEffectExistance(new HashSet (listComps), matchingEntities); - - //// remove one listener - //game.Audio.RemoveListener(listComps[1]); - - //// check that there is now only one SoundEffectInstance for each SoundController left - //CheckSoundEffectExistance(new HashSet { listComps[0] }, matchingEntities); - - //// remove the other listener - //game.Audio.RemoveListener(listComps[0]); - - //// check that there is no SoundEffectInstance left - //CheckSoundEffectExistance(new HashSet(), matchingEntities); - } - - - /// - /// Add entities with associated and check that for each existing in the scene - /// a have been created. Then remove the entities and check that they are removed. - /// - [Fact(Skip = "TODO: UPDATE TO USE Scene and Graphics Composer")] - public void TestAddRemoveEntityWithEmitter() - { - TestUtilities.CreateAndRunGame(TestAddRemoveEntityWithEmitterHelper, TestUtilities.ExitGame); - } - - private void TestAddRemoveEntityWithEmitterHelper(Game game) - { - BuildEntityHierarchy(); - CreateAndAddListenerComponentToEntities(); - CreateAndAddEmitterComponentToEntities(); - AddSoundEffectToEmitterComponents(game); - AddListenersToAudioSystem(game); - AddRootEntityToEntitySystem(game); - - emitComps.Add(new AudioEmitterComponent()); - emitComps[2].Sounds["EffectToneA"] = game.Content.Load("EffectToneA"); - var extraEntity = new Entity(); - extraEntity.Add(emitComps[2]); - - throw new NotImplementedException("TODO: UPDATE TO USE Scene and Graphics Composer"); - //var matchingEntities = game.Entities.Processors.OfType().First().MatchingEntitiesForDebug; - - //// check that initially there is no problems. - //CheckSoundEffectExistance(matchingEntities); - - //// and an entity and check that the soundEffectInstances have been created. - //compEntities.Add(extraEntity); - //game.Entities.Add(extraEntity); - //CheckSoundEffectExistance(matchingEntities); - - //// remove the entity and check that it is removed from the matchingComp list. - //compEntities.Remove(extraEntity); - //game.Entities.Remove(extraEntity); - //CheckSoundEffectExistance(matchingEntities); - } - - /// - /// Attach and detach to and check that the - /// and instances are created correctly. - /// - [Fact(Skip = "TODO: UPDATE TO USE Scene and Graphics Composer")] - public void TestAddRemoveSoundEffect() - { - TestUtilities.CreateAndRunGame(TestAddRemoveSoundEffectHelper, TestUtilities.ExitGame); - } - - - private void TestAddRemoveSoundEffectHelper(Game game) - { - BuildEntityHierarchy(); - CreateAndAddListenerComponentToEntities(); - CreateAndAddEmitterComponentToEntities(); - AddRootEntityToEntitySystem(game); - AddListenersToAudioSystem(game); - - throw new NotImplementedException("TODO: UPDATE TO USE Scene and Graphics Composer"); - //var matchingEntities = game.Entities.Processors.OfType().First().MatchingEntitiesForDebug; - - //CheckSoundEffectExistance(matchingEntities); - - //var sound1 = game.Content.Load("EffectToneA"); - //var sound2 = game.Content.Load("EffectFishLamp"); - //var sound3 = game.Content.Load("EffectBip"); - - //// attach new Soundeffects and check the SoundEffectInstance creation. - //emitComps[0].AttachSoundEffect(sound1); - //CheckSoundEffectExistance(matchingEntities); - - //emitComps[1].AttachSoundEffect(sound2); - //CheckSoundEffectExistance(matchingEntities); - - //emitComps[0].AttachSoundEffect(sound3); - //CheckSoundEffectExistance(matchingEntities); - - //// detach SoundEffect and check that the controllers have been deleted. - //emitComps[0].DetachSoundEffect(sound1); - //CheckSoundEffectExistance(matchingEntities); - - //emitComps[1].DetachSoundEffect(sound2); - //CheckSoundEffectExistance(matchingEntities); - - //emitComps[0].DetachSoundEffect(sound3); - //CheckSoundEffectExistance(matchingEntities); - } - - /// - /// Check that the associated to the are correctly updated - /// when at least one of the of the is playing. - /// - [Fact(Skip = "TODO: UPDATE TO USE Scene and Graphics Composer")] - public void TestEmitterUpdateValues() - { - TestUtilities.ExecuteScriptInDrawLoop(TestEmitterUpdateValuesSetup, EntityPositionAndEmitterbfrUpdate, TestEmitterUpdateValuesAtfUpdate); - } - - /// - /// Setup configuration for the test. - /// - /// - private void TestEmitterUpdateValuesSetup(Game game) - { - BuildEntityHierarchy(); - CreateAndAddListenerComponentToEntities(); - CreateAndAddEmitterComponentToEntities(); - AddRootEntityToEntitySystem(game); - AddSoundEffectToEmitterComponents(game); - AddListenersToAudioSystem(game); - } - - /// - /// Update the entities position and parameters at each loop turn. - /// - /// - /// - /// - private void EntityPositionAndEmitterbfrUpdate(Game game, int loopCount, int loopCountSum) - { - rootSubEntity1.Transform.Position += new Vector3(loopCount, 2 * loopCount, 3 * loopCount); - rootSubEntity2.Transform.Position += 2 * new Vector3(loopCount, 2 * loopCount, 3 * loopCount); - - compEntities[0].Transform.Position += new Vector3(loopCount + 1, 2 * loopCount + 1, 3 * loopCount + 1); - compEntities[1].Transform.Position -= new Vector3(loopCount, 2 * loopCount, 3 * loopCount); - - // emitComps[0].DistanceScale = loopCount; - // emitComps[0].DopplerScale = 2 * loopCount; - // emitComps[1].DistanceScale = 3 * loopCount; - // emitComps[1].DopplerScale = 4 * loopCount; - } - - // /// - // /// Check that the values of the associated to the are or are not updated as they should be. - // /// - // /// boolean indicating if emitter component 1 is supposed to be updated. - // /// boolean indicating if emitter component 2 is supposed to be updated. - // /// the matching entities of the - // /// the current loopCount of the game - // private void CheckEmittersValues(bool emitter1ShouldBeValid, bool emitter2ShouldBeValid, Dictionary matchingEntities, int loopCount) - // { - // var dataComp1 = matchingEntities[compEntities[0]]; - // var dataComp2 = matchingEntities[compEntities[1]]; - // - // // check that the boolean value of the AudioEmitterComponent indicating the processor if the AudioEmitter should be updated is valid. - // Assert.True(dataComp1.AudioEmitterComponent.ShouldBeProcessed == emitter1ShouldBeValid, "value of ShouldBeProcessed for emitter 1 is not correct at loop turn" + loopCount); - // Assert.True(dataComp2.AudioEmitterComponent.ShouldBeProcessed == emitter2ShouldBeValid, "value of ShouldBeProcessed for emitter 2 is not correct at loop turn" + loopCount); - // - // var emitter1Velocity = 2 * new Vector3(loopCount, 2 * loopCount, 3 * loopCount) + Vector3.One; - // if (emitter1ShouldBeValid) - // { - // // check the AudioEmitter 1 values are updated. - // Assert.Equal(emitter1Velocity, dataComp1.AudioEmitter.Velocity, "The velocity of emitter 1 is not valid at loop turn" + loopCount); - // Assert.Equal(loopCount, dataComp1.AudioEmitter.DistanceScale, "The distance scale of emitter 1 is not valid at loop turn" + loopCount); - // Assert.Equal(2 * loopCount, dataComp1.AudioEmitter.DopplerScale, "The Doppler scale of emitter 1 is not valid at loop turn" + loopCount); - // } - // else - // { - // // check the AudioEmitter 1 values are not updated anymore - // Assert.NotEqual(emitter1Velocity, dataComp1.AudioEmitter.Velocity, "The velocity of emitter 1 is calculated for nothing at loop turn" + loopCount); - // Assert.NotEqual(loopCount, dataComp1.AudioEmitter.DistanceScale, "The distance scale of emitter 1 is calculated for nothing at loop turn" + loopCount); - // Assert.NotEqual(2 * loopCount, dataComp1.AudioEmitter.DopplerScale, "The Doppler scale of emitter 1 is calculated for nothing loop turn" + loopCount); - // } - // - // var emitter2Velocity = new Vector3(loopCount, 2 * loopCount, 3 * loopCount); - // if (emitter2ShouldBeValid) - // { - // // check the AudioEmitter 2 values are updated. - // Assert.Equal(emitter2Velocity, dataComp2.AudioEmitter.Velocity, "The velocity of emitter 2 is not valid at loop turn" + loopCount); - // Assert.Equal(3 * loopCount, dataComp2.AudioEmitter.DistanceScale, "The distance scale of emitter 2 is not valid at loop turn" + loopCount); - // Assert.Equal(4 * loopCount, dataComp2.AudioEmitter.DopplerScale, "The Doppler scale of emitter 2 is not valid at loop turn" + loopCount); - // } - // else - // { - // // check the AudioEmitter 2 values are not updated anymore - // Assert.NotEqual(emitter2Velocity, dataComp2.AudioEmitter.Velocity, "The velocity of emitter 2 is calculated for nothing at loop turn" + loopCount); - // Assert.NotEqual(3 * loopCount, dataComp2.AudioEmitter.DistanceScale, "The distance scale of emitter 2 is calculated for nothing at loop turn" + loopCount); - // Assert.NotEqual(4 * loopCount, dataComp2.AudioEmitter.DopplerScale, "The Doppler scale of emitter 2 is calculated for nothing loop turn" + loopCount); - // } - // } - - // private bool soundController0WentToStopState; - // private bool soundController2WentToStopState; - - private void TestEmitterUpdateValuesAtfUpdate(Game game, int loopCount, int loopCountSum) - { - //throw new NotImplementedException("TODO: UPDATE TO USE Scene and Graphics Composer"); - //var matchingEntities = game.Entities.Processors.OfType().First().MatchingEntitiesForDebug; - - //var dataComp1 = matchingEntities[compEntities[0]]; - //var dataComp2 = matchingEntities[compEntities[1]]; - - //// check that AudioEmitters position is always valid. (this is required to ensure that the velocity is valid from the first update). - //Assert.Equal(2 * new Vector3(loopCountSum, 2 * loopCountSum, 3 * loopCountSum) + (loopCount + 1) * Vector3.One, dataComp1.AudioEmitter.Position, "Position of the emitter 1 is not correct"); - //Assert.Equal(new Vector3(loopCountSum, 2 * loopCountSum, 3 * loopCountSum), dataComp2.AudioEmitter.Position, "Position of the emitter 2 is not correct"); - - //if (loopCount == 0) - //{ - // soundController0WentToStopState = false; - // soundController2WentToStopState = false; - - // // check that initially AudioEmitter should not be updated. - // foreach (var data in matchingEntities.Values) - // Assert.False(data.AudioEmitterComponent.ShouldBeProcessed, "Initial value of ShouldBeProcessed is not correct at loop turn"+loopCount); - - // soundControllers[0].Play(); - //} - //else if (loopCount == 1) - //{ - // // check that emitter 1 is updated but not emitter 2 - // CheckEmittersValues(true, false, matchingEntities, loopCount); - - // soundControllers[2].Play(); - //} - //else if (soundControllers[0].PlayState == SoundPlayState.Playing) - //{ - // // check that both emitters are updated. - // CheckEmittersValues(true, true, matchingEntities, loopCount); - //} - //else if (!soundController0WentToStopState) - //{ - // // transition state of controller 1 from play to stop - // // since PlayState is updated asynchronously via callbacks, - // // PlayState may have changed between the Update and this function calls - // // that is why we wait for next loop turn to perform the new test. - // soundController0WentToStopState = true; - //} - //else if (soundControllers[2].PlayState == SoundPlayState.Playing) - //{ - // // check that emitter 2 is still updated but not emitter1 anymore. - // CheckEmittersValues(false, true, matchingEntities, loopCount); - //} - //else if (!soundController2WentToStopState) - //{ - // // transition state of controller 2 from play to stop - // // since PlayState is updated asynchronously via callbacks, - // // PlayState may have changed between the Update and this function calls - // // that is why we wait for next loop turn to perform the new test. - // soundController2WentToStopState = true; - //} - //else - //{ - // // check that both emitter are not updated anymore. - // CheckEmittersValues(false, false, matchingEntities, loopCount); - // game.Exit(); - //} - } - - /// - /// Tests the behavior of processor when several listener are present in the scene. - /// - [Fact(Skip = "TODO: UPDATE TO USE Scene and Graphics Composer")] - public void TestMultiListener() - { - TestUtilities.ExecuteScriptInDrawLoop(TestEmitterUpdateValuesSetup, TestMulteListenerUpdate); - } - - private void TestMulteListenerUpdate(Game game, int loopCount, int loopCountSum) - { - throw new NotImplementedException("TODO: UPDATE TO USE Scene and Graphics Composer"); - //var matchingEntities = game.Entities.Processors.OfType().First().MatchingEntitiesForDebug; - - //var dataComp1 = matchingEntities[compEntities[0]]; - - //if (loopCount == 0) - //{ - // soundControllers[0].Play(); - //} - //else if (loopCount < 10) - //{ - // // check that the two instances are correctly create and playing - // var tupple1 = Tuple.Create(listComps[0], soundControllers[0]); - // var tupple2 = Tuple.Create(listComps[1], soundControllers[0]); - - // Assert.True(dataComp1.ListenerControllerToSoundInstance.ContainsKey(tupple1)); - // Assert.True(dataComp1.ListenerControllerToSoundInstance.ContainsKey(tupple2)); - - // var instance1 = dataComp1.ListenerControllerToSoundInstance[tupple1]; - // var instance2 = dataComp1.ListenerControllerToSoundInstance[tupple2]; - - // Assert.Equal(SoundPlayState.Playing, instance1.PlayState); - // Assert.Equal(SoundPlayState.Playing, instance2.PlayState); - //} - //else - //{ - // game.Exit(); - //} - } - } -} diff --git a/sources/engine/Xenko.Audio.Tests/TestAudioEmitter.cs b/sources/engine/Xenko.Audio.Tests/TestAudioEmitter.cs deleted file mode 100644 index bde973eb8f..0000000000 --- a/sources/engine/Xenko.Audio.Tests/TestAudioEmitter.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; - -using Xunit; - -using Xenko.Core.Mathematics; - -namespace Xenko.Audio.Tests -{ - /// - /// Tests for . - /// - public class TestAudioEmitter - { - private readonly AudioEmitter defaultEmitter = new AudioEmitter(); - - /// - /// Test the behaviour of the Position function. - /// - [Fact] - public void TestPosition() - { - ////////////////////////////// - // 1. Check the default value - Assert.True(Vector3.Zero == defaultEmitter.Position, "The AudioEmitter defaul location is not 0"); - - /////////////////////////////////////////// - // 2. Check for no crash and correct value - defaultEmitter.Position = Vector3.One; - Assert.True(Vector3.One == defaultEmitter.Position, "AudioEmitter.Position value is not what it is supposed to be."); - } - - /// - /// Test the behaviour of the Velocity function. - /// - [Fact] - public void TestVelocity() - { - ////////////////////////////// - // 1. Check the default value - Assert.True(Vector3.Zero == defaultEmitter.Velocity, "The AudioEmitter defaul Velocity is not 0"); - - /////////////////////////////////////////// - // 2. Check for no crash and correct value - defaultEmitter.Velocity = Vector3.One; - Assert.True(Vector3.One == defaultEmitter.Velocity, "AudioEmitter.Velocity value is not what it is supposed to be."); - } - -// /// -// /// Test the behaviour of the DopplerScale function. -// /// -// [Fact] -// public void TestDopplerScale() -// { -// ////////////////////////////// -// // 1. Check the default value -// Assert.True(1f, defaultEmitter.DopplerScale, "The AudioEmitter defaul DopplerScale is not 1"); -// -// /////////////////////////////////////////// -// // 2. Check for no crash and correct value -// defaultEmitter.DopplerScale = 5f; -// Assert.Equal(5f, defaultEmitter.DopplerScale, "AudioEmitter.DopplerScale value is not what it is supposed to be."); -// -// ///////////////////////////////////////////////////////////////////////////////////// -// // 3. Check that a negative value throws the 'ArgumentOutOfRangeException' exception -// Assert.Throws(() => defaultEmitter.DopplerScale = -1f, "AudioEmitter.DopplerScale did not throw 'ArgumentOutOfRangeException' when setting a negative value."); -// } -// -// /// -// /// Test the behaviour of the DistanceScale function. -// /// -// [Fact] -// public void TestDistanceScale() -// { -// ////////////////////////////// -// // 1. Check the default value -// Assert.Equal(1f, defaultEmitter.DistanceScale, "The AudioEmitter defaul DistanceScale is not 1"); -// -// /////////////////////////////////////////// -// // 2. Check for no crash and correct value -// defaultEmitter.DistanceScale = 5f; -// Assert.Equal(5f, defaultEmitter.DistanceScale, "AudioEmitter.DistanceScale value is not what it is supposed to be."); -// -// ///////////////////////////////////////////////////////////////////////////////////// -// // 3. Check that a negative value throws the 'ArgumentOutOfRangeException' exception -// Assert.Throws(() => defaultEmitter.DistanceScale = -1f, "AudioEmitter.DistanceScale did not throw 'ArgumentOutOfRangeException' when setting a negative value."); -// } - } -} diff --git a/sources/engine/Xenko.Audio.Tests/Xenko.Audio.Tests.Windows.csproj b/sources/engine/Xenko.Audio.Tests/Xenko.Audio.Tests.Windows.csproj index 89e8daf501..875268e257 100644 --- a/sources/engine/Xenko.Audio.Tests/Xenko.Audio.Tests.Windows.csproj +++ b/sources/engine/Xenko.Audio.Tests/Xenko.Audio.Tests.Windows.csproj @@ -48,8 +48,6 @@ - - @@ -58,7 +56,6 @@ - diff --git a/sources/engine/Xenko.Audio/AudioEmitter.cs b/sources/engine/Xenko.Audio/AudioEmitter.cs deleted file mode 100644 index 4e4f809a84..0000000000 --- a/sources/engine/Xenko.Audio/AudioEmitter.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using Xenko.Core; -using Xenko.Core.Mathematics; -using Xenko.Native; - -namespace Xenko.Audio -{ - /// - /// Represents a 3D audio emitter in the audio scene. - /// This object, used in combination with an , can simulate 3D audio localization effects for a given sound implementing the interface. - /// For more details take a look at the function. - /// - /// - /// - public class AudioEmitter - { - /// - /// The position of the emitter in the 3D world. - /// - public Vector3 Position; - - /// - /// The velocity of the emitter in the 3D world. - /// - /// This is only used to calculate the doppler effect on the sound effect - public Vector3 Velocity; - - private Vector3 up; - - /// - /// Gets or sets the Up orientation vector for this emitter. This vector up of the world for the emitter. - /// - /// - /// By default, this value is (0,1,0). - /// The value provided will be normalized if it is not already. - /// The values of the Forward and Up vectors must be orthonormal (at right angles to one another). - /// Behavior is undefined if these vectors are not orthonormal. - /// Doppler and Matrix values between an and an are effected by the emitter orientation. - /// - /// The value provided to the set accessor is (0,0,0). - public Vector3 Up - { - get - { - return up; - } - set - { - if (value == Vector3.Zero) - throw new InvalidOperationException("The value of the Up vector can not be (0,0,0)"); - - up = Vector3.Normalize(value); - } - } - - private Vector3 forward; - - /// - /// Gets or sets the forward orientation vector for this emitter. This vector represents the orientation the emitter is looking at. - /// - /// - /// By default, this value is (0,0,1). - /// The value provided will be normalized if it is not already. - /// The values of the Forward and Up vectors must be orthonormal (at right angles to one another). - /// Behavior is undefined if these vectors are not orthonormal. - /// Doppler and Matrix values between an and an are effected by the emitter orientation. - /// - /// The value provided to the set accessor is (0,0,0) or . - public Vector3 Forward - { - get - { - return forward; - } - set - { - if (value == Vector3.Zero) - throw new InvalidOperationException("The value of the Forward vector can not be (0,0,0)"); - - forward = Vector3.Normalize(value); - } - } - - internal Matrix WorldTransform; - - /// - /// Initializes a new instance of the class. - /// - public AudioEmitter() - { - Forward = new Vector3(0, 0, 1); - Up = new Vector3(0, 1, 0); - } - - internal void Apply3D(AudioLayer.Source source) - { - AudioLayer.SourcePush3D(source, ref Position, ref forward, ref up, ref Velocity, ref WorldTransform); - } - } -} diff --git a/sources/engine/Xenko.Audio/AudioEngine.cs b/sources/engine/Xenko.Audio/AudioEngine.cs index fd5d9d75fa..08cccae43a 100644 --- a/sources/engine/Xenko.Audio/AudioEngine.cs +++ b/sources/engine/Xenko.Audio/AudioEngine.cs @@ -18,7 +18,7 @@ namespace Xenko.Audio /// A call to Dispose automatically stops and disposes all the , public class AudioEngine : ComponentBase { - public AudioListener DefaultListener; + public static AudioListener DefaultListener; private readonly AudioDevice audioDevice; diff --git a/sources/engine/Xenko.Audio/DynamicSoundSource.cs b/sources/engine/Xenko.Audio/DynamicSoundSource.cs index 67a18f9d38..fe1800efa4 100644 --- a/sources/engine/Xenko.Audio/DynamicSoundSource.cs +++ b/sources/engine/Xenko.Audio/DynamicSoundSource.cs @@ -413,7 +413,6 @@ private static unsafe void Worker() { // get music playing again AudioLayer.SourceStop(source.soundInstance.Source); - AudioLayer.SourceFlushBuffers(source.soundInstance.Source); source.RestartInternal(); if (source.CanFill) source.ExtractAndFillData(); AudioLayer.SourcePlay(source.soundInstance.Source); diff --git a/sources/engine/Xenko.Audio/IPositionableSound.cs b/sources/engine/Xenko.Audio/IPositionableSound.cs index 8a4ff5fedc..7919770d04 100644 --- a/sources/engine/Xenko.Audio/IPositionableSound.cs +++ b/sources/engine/Xenko.Audio/IPositionableSound.cs @@ -1,6 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using Xenko.Core.Mathematics; namespace Xenko.Audio { @@ -46,6 +47,6 @@ public interface IPositionableSound : IPlayableSound /// The final resulting channel volumes depend on the listener and emitter relative positions and the value of . /// /// - void Apply3D(AudioEmitter emitter); + void Apply3D(Vector3 Position, Vector3? velocity = null, Quaternion? direction = null, float distanceScale = 1f); } } diff --git a/sources/engine/Xenko.Audio/SoundInstance.cs b/sources/engine/Xenko.Audio/SoundInstance.cs index 3da2363a45..ac4018bfd0 100644 --- a/sources/engine/Xenko.Audio/SoundInstance.cs +++ b/sources/engine/Xenko.Audio/SoundInstance.cs @@ -187,32 +187,6 @@ public async Task ReadyToPlay() return await soundSource.ReadyToPlay.Task; } - /// - /// Applies 3D positioning to the sound. - /// More precisely adjust the channel volumes and pitch of the sound, - /// such that the sound source seems to come from the to the listener/>. - /// - /// The emitter that correspond to this sound - /// - /// can be used only on mono-sounds. - /// - /// The final resulting pitch depends on the listener and emitter relative velocity. - /// The final resulting channel volumes depend on the listener and emitter relative positions and the value of . - /// - /// - public void Apply3D(AudioEmitter emitter) - { - if (engine.State == AudioEngineState.Invalidated) - return; - - if (!spatialized) return; - - if (emitter == null) - throw new ArgumentNullException(nameof(emitter)); - - emitter.Apply3D(Source); - } - /// /// Quick and easy way to apply 3D parameters without an AudioEmitter /// diff --git a/sources/engine/Xenko.Engine/Audio/AudioEmitterProcessor.cs b/sources/engine/Xenko.Engine/Audio/AudioEmitterProcessor.cs deleted file mode 100644 index 6de4fb5b32..0000000000 --- a/sources/engine/Xenko.Engine/Audio/AudioEmitterProcessor.cs +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System.Collections.Specialized; -using System.Linq; -using Xenko.Core; -using Xenko.Core.Collections; -using Xenko.Core.Mathematics; -using Xenko.Engine; -using Xenko.Media; -using Xenko.Rendering; - -namespace Xenko.Audio -{ - /// - /// Processor in charge of updating the s. - /// - /// - /// More precisely it updates the s and - /// then applies 3D localization to each couple -. - /// When a new emitter or a new listener is added to the system, its creates the required SoundInstances and associate them with the new emitter/listener tuples. - /// - /// - public class AudioEmitterProcessor : EntityProcessor - { - /// - /// Reference to the audioSystem. - /// - private AudioSystem audioSystem; - - /// - /// Data associated to each instances of the system having an and an . - /// - public class AssociatedData - { - /// - /// The associated to the . - /// - public AudioEmitter AudioEmitter; - - /// - /// The associated to the entity - /// - public AudioEmitterComponent AudioEmitterComponent; - - /// - /// The associated to the entity - /// - public TransformComponent TransformComponent; - - /// - /// If this emitter has some instances playing - /// - public bool IsPlaying; - } - - /// - /// Create a new instance of the processor. - /// - public AudioEmitterProcessor() - : base(typeof(TransformComponent)) - { - } - - protected internal override void OnSystemAdd() - { - audioSystem = Services.GetSafeServiceAs(); - - audioSystem.Listeners.CollectionChanged += OnListenerCollectionChanged; - } - - protected override AssociatedData GenerateComponentData(Entity entity, AudioEmitterComponent component) - { - return new AssociatedData - { - AudioEmitterComponent = component, - TransformComponent = entity.Transform, - }; - } - - protected override bool IsAssociatedDataValid(Entity entity, AudioEmitterComponent component, AssociatedData associatedData) - { - return - component == associatedData.AudioEmitterComponent && - entity.Transform == associatedData.TransformComponent; - } - - protected internal override void OnSystemRemove() - { - // Destroy all the SoundInstance created by the processor before closing. - foreach (var soundInstance in ComponentDataValues.SelectMany(x => x.AudioEmitterComponent.SoundToController.Values)) - soundInstance.DestroyAllSoundInstances(); - - audioSystem.Listeners.CollectionChanged -= OnListenerCollectionChanged; - } - - protected override void OnEntityComponentAdding(Entity entity, AudioEmitterComponent component, AssociatedData data) - { - // initialize the AudioEmitter first position - data.TransformComponent.UpdateWorldMatrix(); // ensure the worldMatrix is correct - data.AudioEmitter = new AudioEmitter { Position = data.TransformComponent.WorldMatrix.TranslationVector }; // valid position is needed at first Update loop to compute velocity. - - // create a SoundInstance for each listener activated and for each sound controller of the EmitterComponent. - foreach (var listener in audioSystem.Listeners.Keys) - { - foreach (var soundController in data.AudioEmitterComponent.SoundToController.Values) - { - soundController.CreateSoundInstance(listener, false); - } - } - - data.AudioEmitterComponent.ControllerCollectionChanged += OnSoundControllerListChanged; - - component.AttachToProcessor(); - } - - public override void Draw(RenderContext context) - { - for (int a=0; a - /// This class is used to control a associated to a . - /// - /// - /// - /// Instances of this class can not be directly created by the user, but need to queried from an - /// instance using the readonly indexer. - /// - /// - /// An instance is not valid anymore if any of those situations arrives: - /// - /// The underlying is disposed. - /// The is detached from its entity. - /// The entity to which it is attached is removed from the Entity System. - /// - /// - /// - [DebuggerDisplay("Controller for {sound.Name}")] - public class AudioEmitterSoundController : IPlayableSound, IMediaPlayer - { - private readonly SoundBase sound; - private readonly AudioEmitterComponent emitter; - - public bool IsDisposed { get; set; } - - /// - /// The instances of currently created by this controller (one for each listener). - /// - [DataMemberIgnore] - internal readonly Dictionary InstanceToListener = new Dictionary(); - - /// - /// Created a new instance. - /// - /// The parent AudioEmitterComponent to which the controller is associated. - /// The underlying SoundBase to be controlled - /// A can be associated to several controllers. - internal AudioEmitterSoundController(AudioEmitterComponent parent, SoundBase sound) - { - this.sound = sound ?? throw new ArgumentNullException(nameof(sound)); - emitter = parent; - - Volume = 1; - } - - /// - /// Create an new instance of underlying sound, and register it in the controller's sound instance list. - /// - /// The new sound effect instance created - internal SoundInstance CreateSoundInstance(AudioListenerComponent listener, bool forget) - { - var newInstance = sound.CreateInstance(listener.Listener, emitter.UseHRTF, emitter.DirectionalFactor, emitter.Environment); - - if (!forget) - InstanceToListener.Add(newInstance, listener); - - return newInstance; - } - - internal void DestroySoundInstance(SoundInstance instance) - { - InstanceToListener.Remove(instance); - instance.Dispose(); - } - - internal void DestroySoundInstances(AudioListenerComponent listener) - { - var deferRemoval = new List(); - - foreach (var instance in InstanceToListener.Keys) - { - deferRemoval.Add(instance); - } - - foreach (var soundInstance in deferRemoval) - { - DestroySoundInstance(soundInstance); - } - - for (var i = 0; i < FastInstances.Count; i++) - { - var instance = FastInstances[i]; - if (instance.Listener == listener.Listener) - { - //Decrement the loop counter to iterate this index again, since later elements will get moved down during the remove operation. - FastInstances.RemoveAt(i--); - instance.Dispose(); - } - } - } - - /// - /// Dispose and removes all the controller sound instances. - /// - internal void DestroyAllSoundInstances() - { - foreach (var instance in InstanceToListener) - { - instance.Key.Dispose(); - } - InstanceToListener.Clear(); - - foreach (var soundInstance in FastInstances) - { - soundInstance.Dispose(); - } - FastInstances.Clear(); - } - - private PlayState playState; - - public PlayState PlayState - { - get - { - // force the play status to 'stopped' if there is no listeners. - if (!InstanceToListener.Any()) - return PlayState.Stopped; - - // return the controller playStatus if not started playing. - if (playState != PlayState.Playing || ShouldBePlayed) - return playState; - - // returns the playStatus of the underlying instances if controller is playing - - // A desynchronization between instances' playState can appear due to asynchronous callbacks - // setting the state of the sound to Stopped when reaching the end of the track. - // For coherency, we consider a controller as stopped only when all its instances are stopped. - // (if not the case, a play call to a stopped controller would restart only some of the underlying instances) - if (InstanceToListener.Any(x => x.Key.PlayState == PlayState.Playing)) - return PlayState.Playing; - - return playState = PlayState.Stopped; - } - } - - private bool isLooping; - - /// - /// Gets or sets whether the sound is automatically looping from beginning when it reaches the end. - /// - public bool IsLooping - { - get => isLooping; - set - { - foreach (var instance in InstanceToListener) - { - instance.Key.IsLooping = value; - } - isLooping = value; - } - } - - private float pitch = 1.0f; - - public float Pitch - { - get => pitch; - set - { - foreach (var instance in InstanceToListener) - { - instance.Key.Pitch = value; - } - pitch = value; - } - } - - /// - /// Indicate the if the controller's sound instances need to be played. - /// This variable is need because is asynchronous and actually starts playing only on next system update. - /// - internal volatile bool ShouldBePlayed; - - public void Play() - { - playState = PlayState.Playing; - - // Controller play function is asynchronous. - // underlying sound instances actually start playing only after the next system update. - // Such a asynchronous behavior is required in order to be able to update the associated AudioEmitter - // and apply localization to the sound before starting to play. - - ShouldBePlayed = true; // tells the EmitterProcessor to start playing the underlying instances. - } - - internal volatile bool FastInstancePlay; - internal List FastInstances = new List(); - - /// - /// Plays the attached sound in a new instance and let's the engine handle it's disposal. - /// This is useful for very fast overlapping sounds, gun shots, machine gun etc. Where you don't care about controlling each sound. - /// - public void PlayAndForget() - { - FastInstancePlay = true; // tells the EmitterProcessor to create and start playing a temporary instances. - } - - public void Pause() - { - if (PlayState != PlayState.Playing) - return; - - playState = PlayState.Paused; - - foreach (var instance in InstanceToListener) - { - instance.Key.Pause(); - } - - ShouldBePlayed = false; - } - - public void Stop() - { - playState = PlayState.Stopped; - - foreach (var instance in InstanceToListener) - { - instance.Key.Stop(); - } - - ShouldBePlayed = false; - } - - private float volume; - - public float Volume - { - get => volume; - set - { - volume = value; - - foreach (var instance in InstanceToListener) - { - instance.Key.Volume = volume; - } - } - } - - public float SpeedFactor - { - get => pitch; - set - { - foreach (var instance in InstanceToListener) - { - var mediaReader = instance.Key as IMediaReader; - if (mediaReader != null) - mediaReader.SpeedFactor = value; - } - Pitch = value; - } - } - - /// - /// Sets the range of the sound to play. - /// - /// a PlayRange structure that describes the starting offset and ending point of the sound to play in seconds. - /// This will not be valid if the sound is played with PlayAndForget - public void SetRange(PlayRange range) - { - foreach (var instance in InstanceToListener) - { - instance.Key.SetRange(range); - } - } - - public void Seek(TimeSpan mediaTime) - { - foreach (var instance in InstanceToListener) - { - var mediaReader = instance.Key as IMediaReader; - if (mediaReader != null) - mediaReader.Seek(mediaTime); - } - } - } -} diff --git a/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs b/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs index 80d61363ff..4f15b48cdc 100644 --- a/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs +++ b/sources/engine/Xenko.Engine/Audio/AudioListenerProcessor.cs @@ -26,6 +26,7 @@ public class AudioListenerProcessor : EntityProcessor /// Reference to the of the game instance. /// private AudioSystem audioSystem; + private TransformComponent primaryTransform; /// /// Create a new instance of AudioListenerProcessor. @@ -42,63 +43,31 @@ protected internal override void OnSystemAdd() protected internal override void OnSystemRemove() { - audioSystem.Listeners.Clear(); } protected override void OnEntityComponentAdding(Entity entity, AudioListenerComponent component, AudioListenerComponent data) { - if (AudioListenerComponent.UseSharedListener) - { - if (AudioListenerComponent.SharedListener == null) - AudioListenerComponent.SharedListener = new AudioListener(audioSystem.AudioEngine); - else - AudioLayer.ListenerEnable(AudioListenerComponent.SharedListener.Listener); - - component.Listener = AudioListenerComponent.SharedListener; - } - else - { - component.Listener = new AudioListener(audioSystem.AudioEngine); - } - - audioSystem.Listeners[component] = component.Listener; + primaryTransform = entity.Transform; } protected override void OnEntityComponentRemoved(Entity entity, AudioListenerComponent component, AudioListenerComponent data) { - audioSystem.Listeners.Remove(component); - - if (AudioListenerComponent.UseSharedListener) - { - if (AudioListenerComponent.SharedListener == null) - AudioListenerComponent.SharedListener = component.Listener; - - AudioLayer.ListenerDisable(AudioListenerComponent.SharedListener.Listener); - } - else - { - component.Listener.Dispose(); - } + primaryTransform = null; } public override void Draw(RenderContext context) { - for (int i=0; i - /// A collection containing the - associations. - /// The AudioListenerComponent keys are added/removed by the user by calls to /. - /// The AudioListener values are created/updated by the . - /// - /// When a AudioListenerComponent is added to the AudioSystem but not present in the Entity System, - /// a valid AudioListener can not be computed. Thus we set its value to 'null'. - internal readonly TrackingDictionary Listeners = new TrackingDictionary(); - public override void Initialize() { base.Initialize(); @@ -69,32 +60,6 @@ public override void Initialize() Game.Deactivated += OnDeactivated; } - /// - /// Add and activate a to the Audio System. - /// After this call sounds played via s will be heard by this listener. - /// - /// The listener to add to the audio system. - /// Adding a listener already added as no effects. - internal void AddListener(AudioListenerComponent listener) - { - if (!Listeners.ContainsKey(listener)) - Listeners[listener] = null; - } - - /// - /// Remove a from the Audio System. - /// After this call sounds played via s will not be heard by this listener anymore. - /// - /// The listener to remove from the audio system. - /// The provided listener was not present in the Audio System. - internal void RemoveListener(AudioListenerComponent listener) - { - if (!Listeners.ContainsKey(listener)) - throw new ArgumentException("The provided listener was not present in the Audio System."); - - Listeners.Remove(listener); - } - public override void Update(GameTime gameTime) { AudioEngine.Update(); diff --git a/sources/engine/Xenko.Engine/Engine/AudioEmitterComponent.cs b/sources/engine/Xenko.Engine/Engine/AudioEmitterComponent.cs deleted file mode 100644 index 36cef08d4d..0000000000 --- a/sources/engine/Xenko.Engine/Engine/AudioEmitterComponent.cs +++ /dev/null @@ -1,206 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. - -using System; -using System.Collections.Generic; -using System.Collections.Specialized; -using Xenko.Audio; -using Xenko.Core; -using Xenko.Core.Annotations; -using Xenko.Core.Collections; -using Xenko.Engine.Design; - -namespace Xenko.Engine -{ - /// - /// Component representing an audio emitter. - /// - /// - /// - /// Associate this component to an entity to simulate a 3D localized source of sound coming from the entity center. - /// - /// - /// Several sounds can be associated to a single AudioEmitterComponent. - /// Use the dictionary to associate or dissociate a to the emitter component. - /// Each SoundBase associated to the emitter component can be controlled (played, paused, stopped, ...) independently for the others. - /// Once attached to the emitter component, a SoundBase is controlled using a . - /// To get the AudioEmitterSoundController associated to a SoundBase use the readonly indexer. - /// - /// - [Display("Audio emitter", Expand = ExpandRule.Once)] - [DataContract("AudioEmitterComponent")] - [DefaultEntityComponentProcessor(typeof(AudioEmitterProcessor), ExecutionMode = ExecutionMode.Runtime)] - [ComponentOrder(7000)] - [ComponentCategory("Audio")] - public sealed class AudioEmitterComponent : ActivableEntityComponent - { - /// - /// Dictionary associating each SoundBase to a single soundController. - /// The controller a valid as long as the corresponding SoundBase is present in the dictionary. - /// - internal readonly Dictionary SoundToController = new Dictionary(); - - /// - /// Event argument class used to signal the that a new AudioEmitterSoundController has new added or removed to the component. - /// - internal class ControllerCollectionChangedEventArgs - { - /// - /// The entity associated the current component. - /// - public Entity Entity; - - /// - /// The controller that have been added or removed to the component. - /// - public AudioEmitterSoundController Controller; - - /// - /// The AudioEmitterComponent itself - /// - public AudioEmitterComponent EmitterComponent; - - /// - /// Action indication if the controller has been added or removed. - /// - public NotifyCollectionChangedAction Action; - - public ControllerCollectionChangedEventArgs(Entity entity, AudioEmitterSoundController controller, AudioEmitterComponent component, NotifyCollectionChangedAction action) - { - Entity = entity; - Controller = controller; - EmitterComponent = component; - Action = action; - } - } - - /// - /// Event triggered when an has be attached or detached to the component. - /// - internal event EventHandler ControllerCollectionChanged; - - /// - /// The sounds this audio emitter can play and use - /// - [DataMember(10)] - public TrackingDictionary Sounds = new TrackingDictionary(); - - /// - /// The sound controllers associated with the sounds this audio emitter can play and use, use this to access and play sounds. - /// - /// The name of the sound you want to access. - /// The sound controller. - [DataMemberIgnore] - public AudioEmitterSoundController this[string soundName] => SoundToController[Sounds[soundName]]; - - /// - /// If possible use a more complex HRTF algorithm to perform 3D sound simulation - /// - /// - /// If possible use a more complex HRTF algorithm to perform 3D sound simulation - /// - [DataMember(20)] - // ReSharper disable once InconsistentNaming - public bool UseHRTF { get; set; } - - /// - /// If 0 the sound will be omnidirectional, 1 fully directional - /// - /// - /// If 0 the sound will be omnidirectional, 1 fully directional - /// - [DataMember(30)] - [DataMemberRange(0.0, 1.0, 0.1, 0.2, 3)] - public float DirectionalFactor { get; set; } - - /// - /// The reverberation model that this emitter will use - /// - /// - /// The reverberation model that this emitter will use - /// - [DataMember(40)] - public HrtfEnvironment Environment { get; set; } - - /// - /// Attach a to this emitter component. - /// Once attached a can be queried using readonly indexer to control the attached SoundBase. - /// - /// The SoundBase to attach - /// The provided is null. - /// The provided can not be localized (contains more than one channel). - /// Attaching a SoundBase already attached has no effects. - public AudioEmitterSoundController AttachSound([NotNull] SoundBase sound) - { - if (sound == null) throw new ArgumentNullException(nameof(sound)); - if (sound.Channels > 1) - throw new InvalidOperationException("The provided Sound has more than one channel. It can not be localized in the 3D scene, please check the spatialized option in the Sound asset."); - - if (SoundToController.ContainsKey(sound)) - return SoundToController[sound]; - - var newController = new AudioEmitterSoundController(this, sound); - SoundToController[sound] = newController; - ControllerCollectionChanged?.Invoke(this, new ControllerCollectionChangedEventArgs(Entity, newController, this, NotifyCollectionChangedAction.Add)); - - return newController; - } - - /// - /// Detach a from this emitter component. - /// Once detach the controller previously associated to the SoundBase is invalid. - /// - /// The SoundBase to detach. - /// The provided is null. - /// The provided is not currently attached to the emitter component. - public void DetachSound([NotNull] SoundBase sound) - { - if (sound == null) throw new ArgumentNullException(nameof(sound)); - if (!SoundToController.ContainsKey(sound)) - throw new ArgumentException("The provided Sound is not currently attached to this emitter component."); - - var oldController = SoundToController[sound]; - SoundToController.Remove(sound); - ControllerCollectionChanged?.Invoke(this, new ControllerCollectionChangedEventArgs(Entity, oldController, this, NotifyCollectionChangedAction.Remove)); - } - - private void OnSoundsOnCollectionChanged(object sender, TrackingCollectionChangedEventArgs args) - { - switch (args.Action) - { - case NotifyCollectionChangedAction.Add: - AttachSound((SoundBase)args.Item); - break; - case NotifyCollectionChangedAction.Remove: - DetachSound((SoundBase)args.Item); - break; - } - } - - internal void AttachToProcessor() - { - Sounds.CollectionChanged += OnSoundsOnCollectionChanged; - - foreach (var sound in Sounds) - { - if (sound.Value != null) - { - AttachSound(sound.Value); - } - } - } - - internal void DetachFromProcessor() - { - foreach (var sound in Sounds) - { - if (sound.Value != null) - { - DetachSound(sound.Value); - } - } - - Sounds.CollectionChanged -= OnSoundsOnCollectionChanged; - } - } -} diff --git a/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs b/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs index e11b6a8dfd..4a45df8e03 100644 --- a/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs +++ b/sources/engine/Xenko.Engine/Engine/AudioListenerComponent.cs @@ -23,10 +23,7 @@ namespace Xenko.Engine [ComponentCategory("Audio")] public sealed class AudioListenerComponent : ActivableEntityComponent { - public static AudioListener SharedListener { get; internal set; } - public static bool UseSharedListener; - [DataMemberIgnore] - internal AudioListener Listener; + internal AudioListener Listener => AudioEngine.DefaultListener; } } diff --git a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs index 1fe98de8b6..fd521838e5 100644 --- a/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs +++ b/sources/engine/Xenko.Engine/Engine/GlobalSoundManager.cs @@ -38,7 +38,7 @@ public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume s.Volume = volume * MasterVolume; s.IsLooping = looped; s.Pan = pan; - if (s.IsSpatialized) s.Apply3D(Listener.Listener.Position); + if (s.IsSpatialized) s.Apply3D(AudioEngine.DefaultListener.Position); s.Play(); } return s; @@ -46,7 +46,7 @@ public SoundInstance PlayCentralSound(string url, float pitch = 1f, float volume public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch = 1f, float volume = 1f, float distanceScale = 1f, bool looped = false) { - float sqrDist = (position - Listener.Listener.Position).LengthSquared(); + float sqrDist = (position - AudioEngine.DefaultListener.Position).LengthSquared(); if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; SoundInstance s = getFreeInstance(url, true); if (s == null) return null; @@ -62,7 +62,7 @@ public SoundInstance PlayPositionSound(string url, Vector3 position, float pitch public SoundInstance PlayAttachedSound(string url, Entity parent, float pitch = 1f, float volume = 1f, float distanceScale = 1f, bool looped = false) { Vector3 pos = parent.Transform.WorldPosition(); - float sqrDist = (pos - Listener.Listener.Position).LengthSquared(); + float sqrDist = (pos - AudioEngine.DefaultListener.Position).LengthSquared(); if (MaxSoundDistance > 0f && sqrDist >= MaxSoundDistance * MaxSoundDistance) return null; SoundInstance s = getFreeInstance(url, true); if (s == null) return null; @@ -183,53 +183,14 @@ public GlobalSoundManager() { // global sound manager relies on listeners being shared, so everything can be // safely reused - AudioListenerComponent.UseSharedListener = true; internalGame = ServiceRegistry.instance?.GetService() as Game; } - [DataMemberIgnore] - private AudioListenerComponent Listener - { - get - { - if (_listener == null || _listener.Enabled == false || internalGame.Audio.Listeners.ContainsKey(_listener) == false) - { - // find a valid listener! - foreach (AudioListenerComponent alc in internalGame.Audio.Listeners.Keys) - { - if (alc.Enabled) - { - _listener = alc; - break; - } - } - - if (_listener == null) - throw new InvalidOperationException("Could not find an Audio Listener Component in scene!"); - } - - return _listener; - } - set - { - // don't set us to something null, which just breaks things - if (value == null) return; - - _listener = value; - } - } - - public void OverrideListener(AudioListenerComponent listener) - { - Listener = listener; - } - private Dictionary Sounds = new Dictionary(); private Dictionary> instances = new Dictionary>(); private List currentAttached = new List(); private System.Random rand; private Game internalGame; - private AudioListenerComponent _listener; private SoundInstance getFreeInstance(string url, bool spatialized) { @@ -249,7 +210,7 @@ private SoundInstance getFreeInstance(string url, bool spatialized) // don't have a free one to play, add a new one to the list if (Sounds.TryGetValue(url, out var snd0)) { - SoundInstance si0 = snd0.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + SoundInstance si0 = snd0.CreateInstance(AudioEngine.DefaultListener, true, false, 0f, HrtfEnvironment.Small); ins.Add(si0); return si0; } @@ -258,7 +219,7 @@ private SoundInstance getFreeInstance(string url, bool spatialized) // don't have a list for this, make one if (Sounds.TryGetValue(url, out var snd1)) { - SoundInstance si1 = snd1.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + SoundInstance si1 = snd1.CreateInstance(AudioEngine.DefaultListener, true, false, 0f, HrtfEnvironment.Small); List lsi1 = new List(); lsi1.Add(si1); instances[url] = lsi1; @@ -271,7 +232,7 @@ private SoundInstance getFreeInstance(string url, bool spatialized) if (!snd2.Spatialized && spatialized) throw new InvalidOperationException("Trying to play " + url + " positionally, yet it is a non-spatialized sound!"); - SoundInstance si = snd2.CreateInstance(Listener?.Listener, true, false, 0f, HrtfEnvironment.Small); + SoundInstance si = snd2.CreateInstance(AudioEngine.DefaultListener, true, false, 0f, HrtfEnvironment.Small); List lsi = new List(); lsi.Add(si); instances[url] = lsi; diff --git a/sources/engine/Xenko.Video/VideoComponent.cs b/sources/engine/Xenko.Video/VideoComponent.cs index 540f0fe130..ac7eca8ee5 100644 --- a/sources/engine/Xenko.Video/VideoComponent.cs +++ b/sources/engine/Xenko.Video/VideoComponent.cs @@ -75,12 +75,6 @@ public class VideoComponent : EntityComponent /// [DataMember(50)] public bool PlayAudio { get; set; } = true; - - /// - /// The list of audioEmitteur components. - /// - [DataMember(60)] - public FastCollection AudioEmitters { get; } = new FastCollection(); internal void AttachInstance([NotNull] VideoInstance instance) { diff --git a/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs b/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs index a6245245c0..ade3cd8025 100644 --- a/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs +++ b/sources/engine/Xenko.Video/VideoInstance.Direct3D.cs @@ -206,8 +206,7 @@ private void CompleteMediaInitialization() AllocateVideoTexture(videoWidth, videoHeight); - if (videoComponent.PlayAudio != true || videoComponent.AudioEmitters.Any(e => e != null)) - mediaEngine.Muted = true; + mediaEngine.Muted = true; } /// From 15bcc0b9c34b494374f33715cd331c189d60de90 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sat, 22 Feb 2020 22:12:13 -0500 Subject: [PATCH 0790/2038] Revert "[GameStudio] Stop updating and rendering game scenes, prefabs and preview asset sub-windows when they are hidden in tab control" This reverts commit 59e7e78be4dba65b17b7f7567391c070f1e1dc9a. --- .../GameEditor/Services/EditorGameController.cs | 10 ---------- .../GameEditor/Services/IEditorGameController.cs | 10 ---------- .../GameEditor/ViewModels/GameEditorViewModel.cs | 14 ++------------ .../Services/IAssetPreviewService.cs | 4 ---- .../EditorGame/Game/EditorServiceGame.cs | 12 ++---------- .../Preview/GameStudioPreviewService.cs | 12 +----------- .../Xenko.GameStudio/AssetEditorsManager.cs | 15 --------------- .../editor/Xenko.GameStudio/GameStudioWindow.xaml | 2 +- .../Xenko.GameStudio/GameStudioWindow.xaml.cs | 13 ------------- .../editor/Xenko.GameStudio/PreviewViewModel.cs | 15 +-------------- 10 files changed, 7 insertions(+), 100 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs index 6ecaff6f0e..bb110732a9 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs @@ -231,16 +231,6 @@ public async Task StartGame() return true; } - public void PauseGame() - { - Game.IsSuspended = true; - } - - public void ResumeGame() - { - Game.IsSuspended = false; - } - public Vector3 GetMousePositionInScene(bool lastRightClick) { EnsureNotDestroyed(); diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs index 191910106e..7b8384c907 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs @@ -45,16 +45,6 @@ public interface IEditorGameController : IDestroyable, IDispatcherService /// True if the scene was successfully created, false otherwise. Task CreateScene(); - /// - /// Stops the game from updating and rendering. - /// - void PauseGame(); - - /// - /// Resumes the game updating and rendering. - /// - void ResumeGame(); - /// /// Finds the game-side instance corresponding to the part with the given id, if it exists. /// diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs index 4ff26e22f4..19337b094a 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs @@ -29,7 +29,7 @@ protected GameEditorViewModel([NotNull] AssetViewModel asset, [NotNull] Func @@ -77,16 +77,6 @@ public override void Destroy() base.Destroy(); } - public void PauseGame() - { - Controller.PauseGame(); - } - - public void ResumeGame() - { - Controller.ResumeGame(); - } - protected virtual async Task InitializeEditor() { Dispatcher.EnsureAccess(); @@ -122,7 +112,7 @@ private void CopyErrorToClipboard() SafeClipboard.SetText(log); } - private void ResumeFromError() + private void Resume() { Controller.GetService()?.Resume(); } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs index ce2a2e62e3..f6dcd20f56 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs @@ -13,9 +13,5 @@ public interface IAssetPreviewService : IDisposable object GetCurrentPreviewView(); event EventHandler PreviewAssetUpdated; - - void ResumeRenderPreview(); - - void SuspendRenderPreview(); } } diff --git a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs index 9e8c4b0558..2606f208c3 100644 --- a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs +++ b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs @@ -48,14 +48,6 @@ public abstract class EditorServiceGame : EmbeddedGame public IGameSettingsAccessor PackageSettings { get; set; } - /// - /// True if the game is paused. - /// - /// - /// Used when game is not visible in the editor. - /// - public bool IsSuspended { get; set; } - /// /// True if game is faulted (not running). /// @@ -122,7 +114,7 @@ protected override void Initialize() protected override void Update(GameTime gameTime) { // Keep going only if last exception has been "resolved" - if (Faulted || IsSuspended) + if (Faulted) return; try @@ -145,7 +137,7 @@ protected override void Update(GameTime gameTime) protected override void Draw(GameTime gameTime) { // Keep going only if last exception has been "resolved" - if (Faulted || IsSuspended) + if (Faulted) return; try diff --git a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs index 9df92bf8a6..4dc9fa0be5 100644 --- a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs +++ b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs @@ -195,7 +195,7 @@ public void SetAssetToPreview(AssetViewModel asset) } public AssetCompilerResult Compile(AssetItem asset) - { + { return previewCompiler.Prepare(previewCompileContext, asset); } @@ -319,15 +319,5 @@ public void RegisterAssetPreviewFactories(IReadOnlyDictionary assetPreviewFactories.Add(x.Key, x.Value)); } - - public void ResumeRenderPreview() - { - PreviewGame.IsSuspended = false; - } - - public void SuspendRenderPreview() - { - PreviewGame.IsSuspended = true; - } } } diff --git a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs index 356798a653..de005b51cb 100644 --- a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs +++ b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs @@ -564,21 +564,6 @@ private static void EditorPaneIsActiveChanged(object sender, EventArgs e) { element.Loaded -= EditorPaneContentLoaded; } - var assetViewModel = element?.DataContext as AssetViewModel; - if (assetViewModel?.Editor != null) - { - if (assetViewModel.Editor is Assets.Presentation.AssetEditors.GameEditor.ViewModels.GameEditorViewModel gameEditor) - { - if (editorPane.IsActive) - { - gameEditor.ResumeGame(); - } - else - { - gameEditor.PauseGame(); - } - } - } } } diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index 57fd7c34a3..ad1a639c84 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -877,7 +877,7 @@ - diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs index a59c4fb97e..700daddbc7 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs @@ -67,19 +67,6 @@ public GameStudioWindow(EditorViewModel editor) Application.Current.Activated += (s, e) => editor.ServiceProvider.Get().ShowDelayedNotifications(); Loaded += GameStudioLoaded; - if (editor is GameStudioViewModel gsViewModel) - { - AssetPreviewPane.IsSelectedChanged += (sender, e) => - { - // This is the event when the Asset Preview tab is clicked on, or when another tab is clicked - // when in the same tab group. - // We handle the event here instead of making an OnEventCommandBehavior because WPF has some quirk where - // binding to the LayoutAnchorable's IsSelected for the CommandParameter ends up passing the previous value - // instead of the current value. - gsViewModel.Preview?.RenderPreviewCommand?.Execute(AssetPreviewPane.IsSelected); - }; - } - OpenMetricsProjectSession(editor); } diff --git a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs index d9f354dec8..26734e384d 100644 --- a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs +++ b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs @@ -7,7 +7,6 @@ using Xenko.Core.Assets.Editor.Services; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Extensions; -using Xenko.Core.Presentation.Commands; using Xenko.Core.Presentation.ViewModel; namespace Xenko.GameStudio @@ -18,19 +17,15 @@ public class PreviewViewModel : DispatcherViewModel, IDisposable private IAssetPreviewService previewService; private object previewObject; - + public PreviewViewModel(SessionViewModel session) : base(session.SafeArgument(nameof(session)).ServiceProvider) { this.session = session; session.ActiveAssetView.SelectedAssets.CollectionChanged += SelectedAssetsCollectionChanged; session.ActiveAssetsChanged += ActiveAssetsChanged; - - RenderPreviewCommand = new AnonymousCommand(session.ServiceProvider, SetIsRendering); } - public CommandBase RenderPreviewCommand { get; } - public object PreviewObject { get { return previewObject; } private set { SetValue(ref previewObject, value); } } private IAssetPreviewService PreviewService @@ -102,13 +97,5 @@ private void SelectedAssetsCollectionChanged(object sender, NotifyCollectionChan previewService.SetAssetToPreview(null); } } - - private void SetIsRendering(bool canRender) - { - if (canRender) - PreviewService.ResumeRenderPreview(); - else - PreviewService.SuspendRenderPreview(); - } } } From a5081222b41c9a95625be68ee39b33c8a4728337 Mon Sep 17 00:00:00 2001 From: Basewq Date: Sat, 15 Feb 2020 19:12:10 +1300 Subject: [PATCH 0791/2038] GameStudio: fix project restore functionality --- .../Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs index 2cc5c80769..cb1fb4d94b 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs @@ -345,7 +345,7 @@ public static async Task CreateNewSession(EditorViewModel edit private static void BackupProjectFiles() { - var path = Path.GetDirectoryName(EditorViewModel.Instance.projectPath); + var path = EditorViewModel.Instance.projectPath; string[] files = Directory.GetFiles(path, "*.xk*", SearchOption.AllDirectories); for (int i=0; i OpenSession(string path, IViewModelSe } // grab path for backup/restore - EditorViewModel.Instance.projectPath = path; + EditorViewModel.Instance.projectPath = Path.GetDirectoryName(path); // Register the node container to the copy/paste service. sessionViewModel.ServiceProvider.Get().PropertyGraphContainer = sessionViewModel.GraphContainer; From 0b5a2eea7ee52922308dbdd3309b729d3b36ae3a Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 24 Feb 2020 12:48:23 -0500 Subject: [PATCH 0792/2038] Bump version to 3.5.6 --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 1d39350464..a54dbb4b2e 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.5"; + public const string VersionToShowInEditor = "3.5.6"; /// /// The current assembly version as text, currently same as . From 9f56ebcd1ab090e7b9cf2d17c90ef866521de1ec Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Tue, 25 Feb 2020 15:36:05 +0900 Subject: [PATCH 0793/2038] [Editor] "Add dependencies" dialog can now list currently not yet referenced packages --- sources/assets/Xenko.Core.Assets/Package.cs | 10 +- .../PackageSession.Dependencies.cs | 76 +++++++----- .../Xenko.Core.Assets/PackageSession.cs | 16 +-- .../XenkoDefaultAssetsPlugin.cs | 11 ++ .../Services/IEditorDialogService.cs | 4 +- .../View/PackagePickerWindow.xaml.cs | 19 ++- .../ViewModel/PackageViewModel.cs | 90 ++++++++++++-- .../ViewModel/SessionViewModel.cs | 111 ++++++++++++------ 8 files changed, 231 insertions(+), 106 deletions(-) diff --git a/sources/assets/Xenko.Core.Assets/Package.cs b/sources/assets/Xenko.Core.Assets/Package.cs index 1b630199eb..2a6f7961da 100644 --- a/sources/assets/Xenko.Core.Assets/Package.cs +++ b/sources/assets/Xenko.Core.Assets/Package.cs @@ -118,7 +118,7 @@ public Package() /// /// true if this package is a system package; otherwise, false. [DataMemberIgnore] - public bool IsSystem { get; internal set; } + public bool IsSystem => !(Container is SolutionProject); /// /// Gets or sets the metadata associated with this package. @@ -629,6 +629,14 @@ public static PackageContainer LoadProject(ILogger log, string filePath) } else { + // Try to get version from NuGet folder + var path = new UFile(filePath); + var nuspecPath = UPath.Combine(path.GetFullDirectory().GetParent(), new UFile(path.GetFileNameWithoutExtension() + ".nuspec")); + if (path.GetFullDirectory().GetDirectoryName() == "xenko" && File.Exists(nuspecPath) + && PackageVersion.TryParse(path.GetFullDirectory().GetParent().GetDirectoryName(), out var packageVersion)) + { + package.Meta.Version = packageVersion; + } return new StandalonePackage(package); } } diff --git a/sources/assets/Xenko.Core.Assets/PackageSession.Dependencies.cs b/sources/assets/Xenko.Core.Assets/PackageSession.Dependencies.cs index 836e3d0b82..db30b8d50b 100644 --- a/sources/assets/Xenko.Core.Assets/PackageSession.Dependencies.cs +++ b/sources/assets/Xenko.Core.Assets/PackageSession.Dependencies.cs @@ -271,37 +271,7 @@ private async Task PreLoadPackageDependencies(ILogger log, SolutionProject proje } } - project.FlattenedDependencies.Clear(); - project.DirectDependencies.Clear(); - var projectAssetsJsonPath = Path.Combine(project.FullPath.GetFullDirectory(), @"obj", LockFileFormat.AssetsFileName); - if (File.Exists(projectAssetsJsonPath)) - { - var format = new LockFileFormat(); - var projectAssets = format.Read(projectAssetsJsonPath); - - // Update dependencies - foreach (var library in projectAssets.Libraries) - { - project.FlattenedDependencies.Add(new Dependency(library.Name, library.Version.ToPackageVersion(), library.Type == "project" ? DependencyType.Project : DependencyType.Package) { MSBuildProject = library.Type == "project" ? library.MSBuildProject : null }); - } - - foreach (var projectReference in projectAssets.PackageSpec.RestoreMetadata.TargetFrameworks.First().ProjectReferences) - { - var projectName = new UFile(projectReference.ProjectUniqueName).GetFileNameWithoutExtension(); - project.DirectDependencies.Add(new DependencyRange(projectName, null, DependencyType.Project) { MSBuildProject = projectReference.ProjectPath }); - } - - foreach (var dependency in projectAssets.PackageSpec.TargetFrameworks.First().Dependencies) - { - if (dependency.AutoReferenced) - continue; - project.DirectDependencies.Add(new DependencyRange(dependency.Name, dependency.LibraryRange.VersionRange.ToPackageVersionRange(), DependencyType.Package)); - } - - // Load dependency (if external) - - // Compute output path - } + UpdateDependencies(project, true, true); // 1. Load store package foreach (var projectDependency in project.FlattenedDependencies) @@ -324,7 +294,7 @@ private async Task PreLoadPackageDependencies(ILogger log, SolutionProject proje if (file != null && File.Exists(file)) { // Load package - var loadedProject = LoadProject(log, file, true, loadParameters); + var loadedProject = LoadProject(log, file, loadParameters); loadedProject.Package.Meta.Name = projectDependency.Name; loadedProject.Package.Meta.Version = projectDependency.Version; Projects.Add(loadedProject); @@ -365,6 +335,48 @@ private async Task PreLoadPackageDependencies(ILogger log, SolutionProject proje } } + public static void UpdateDependencies(SolutionProject project, bool directDependencies, bool flattenedDependencies) + { + if (flattenedDependencies) + project.FlattenedDependencies.Clear(); + if (directDependencies) + project.DirectDependencies.Clear(); + var projectAssetsJsonPath = Path.Combine(project.FullPath.GetFullDirectory(), @"obj", LockFileFormat.AssetsFileName); + if (File.Exists(projectAssetsJsonPath)) + { + var format = new LockFileFormat(); + var projectAssets = format.Read(projectAssetsJsonPath); + + // Update dependencies + if (flattenedDependencies) + { + foreach (var library in projectAssets.Libraries) + { + var projectDependency = new Dependency(library.Name, library.Version.ToPackageVersion(), library.Type == "project" ? DependencyType.Project : DependencyType.Package) { MSBuildProject = library.Type == "project" ? library.MSBuildProject : null }; + project.FlattenedDependencies.Add(projectDependency); + // Try to resolve package if already loaded + projectDependency.Package = project.Session.Packages.Find(projectDependency); + } + } + + if (directDependencies) + { + foreach (var projectReference in projectAssets.PackageSpec.RestoreMetadata.TargetFrameworks.First().ProjectReferences) + { + var projectName = new UFile(projectReference.ProjectUniqueName).GetFileNameWithoutExtension(); + project.DirectDependencies.Add(new DependencyRange(projectName, null, DependencyType.Project) { MSBuildProject = projectReference.ProjectPath }); + } + + foreach (var dependency in projectAssets.PackageSpec.TargetFrameworks.First().Dependencies) + { + if (dependency.AutoReferenced) + continue; + project.DirectDependencies.Add(new DependencyRange(dependency.Name, dependency.LibraryRange.VersionRange.ToPackageVersionRange(), DependencyType.Package)); + } + } + } + } + private static RemoteWalkContext CreateRemoteWalkContext(RestoreRequest request, RestoreCollectorLogger logger) { var context = new RemoteWalkContext( diff --git a/sources/assets/Xenko.Core.Assets/PackageSession.cs b/sources/assets/Xenko.Core.Assets/PackageSession.cs index 6e7ce3f05a..1f0dbd2d34 100644 --- a/sources/assets/Xenko.Core.Assets/PackageSession.cs +++ b/sources/assets/Xenko.Core.Assets/PackageSession.cs @@ -365,7 +365,9 @@ private void DirectDependencies_CollectionChanged(object sender, NotifyCollectio switch (dependency.Type) { case DependencyType.Package: - msbuildProject.AddItem("PackageReference", dependency.Name, new[] { new KeyValuePair("Version", dependency.VersionRange.ToString()) }); + msbuildProject.AddItem("PackageReference", dependency.Name, new[] { new KeyValuePair("Version", dependency.VersionRange.ToString()) }) + // Make sure Version is a XML attribute rather than a XML child. + .ForEach(packageReference => packageReference.Metadata.ForEach(metadata => metadata.Xml.ExpressedAsAttribute = true)); isProjectDirty = true; break; case DependencyType.Project: @@ -635,7 +637,7 @@ public PackageContainer AddExistingProject(UFile projectPath, ILogger logger, Pa // Enable reference analysis caching during loading AssetReferenceAnalysis.EnableCaching = true; - project = LoadProject(logger, projectPath.ToWindowsPath(), false, loadParametersArg); + project = LoadProject(logger, projectPath.ToWindowsPath(), loadParametersArg); Projects.Add(project); package = project.Package; @@ -712,7 +714,7 @@ public AssetItem FindAssetFromProxyObject(object proxyObject) return reference != null ? (FindAsset(reference.Id) ?? FindAsset(reference.Url)) : null; } - private PackageContainer LoadProject(ILogger log, string filePath, bool isSystem, PackageLoadParameters loadParameters = null) + private PackageContainer LoadProject(ILogger log, string filePath, PackageLoadParameters loadParameters = null) { var project = Package.LoadProject(log, filePath); @@ -734,7 +736,6 @@ private PackageContainer LoadProject(ILogger log, string filePath, bool isSystem } var package = project.Package; - package.IsSystem = isSystem; // If the package doesn't have a meta name, fix it here (This is supposed to be done in the above disabled analysis - but we still need to do it!) if (string.IsNullOrWhiteSpace(package.Meta.Name) && package.FullPath != null) @@ -807,7 +808,7 @@ public static void Load(string filePath, PackageSessionResult sessionResult, Pac { if (vsProject.TypeGuid == VisualStudio.KnownProjectTypeGuid.CSharp || vsProject.TypeGuid == VisualStudio.KnownProjectTypeGuid.CSharpNewSystem) { - var project = (SolutionProject)session.LoadProject(sessionResult, vsProject.FullPath, false, loadParameters); + var project = (SolutionProject)session.LoadProject(sessionResult, vsProject.FullPath, loadParameters); project.VSProject = vsProject; session.Projects.Add(project); @@ -827,7 +828,7 @@ public static void Load(string filePath, PackageSessionResult sessionResult, Pac else if (Path.GetExtension(filePath).ToLowerInvariant() == ".csproj" || Path.GetExtension(filePath).ToLowerInvariant() == Package.PackageFileExtension) { - var project = session.LoadProject(sessionResult, filePath, false, loadParameters); + var project = session.LoadProject(sessionResult, filePath, loadParameters); session.Projects.Add(project); firstProject = project as SolutionProject; } @@ -1330,7 +1331,7 @@ private void OnAssetDirtyChanged(AssetItem asset, bool oldValue, bool newValue) AssetDirtyChanged?.Invoke(asset, oldValue, newValue); } - private Package PreLoadPackage(ILogger log, string filePath, bool isSystemPackage, PackageLoadParameters loadParameters) + private Package PreLoadPackage(ILogger log, string filePath, PackageLoadParameters loadParameters) { if (log == null) throw new ArgumentNullException(nameof(log)); if (filePath == null) throw new ArgumentNullException(nameof(filePath)); @@ -1340,7 +1341,6 @@ private Package PreLoadPackage(ILogger log, string filePath, bool isSystemPackag { // Load the package without loading any assets var package = Package.LoadRaw(log, filePath); - package.IsSystem = isSystemPackage; // Convert UPath to absolute (Package only) // Removed for now because it is called again in PackageSession.LoadAssembliesAndAssets (and running it twice result in dirty package) diff --git a/sources/editor/Xenko.Assets.Presentation/XenkoDefaultAssetsPlugin.cs b/sources/editor/Xenko.Assets.Presentation/XenkoDefaultAssetsPlugin.cs index cef733815d..7e6cf2b3a6 100644 --- a/sources/editor/Xenko.Assets.Presentation/XenkoDefaultAssetsPlugin.cs +++ b/sources/editor/Xenko.Assets.Presentation/XenkoDefaultAssetsPlugin.cs @@ -25,6 +25,7 @@ using Xenko.Editor; using Xenko.Engine; using Xenko.Core.Assets.Templates; +using Xenko.Core.Packages; namespace Xenko.Assets.Presentation { @@ -210,6 +211,16 @@ public override void InitializeSession(SessionViewModel session) { effectCompilerServerSession = new EffectCompilerServerSession(session); } + + // Extra packages to display in "add reference" dialog + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.Engine.EntityComponent).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.UI.UIElement).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.Particles.Components.ParticleSystemComponent).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.Navigation.NavigationComponent).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.Physics.StaticColliderComponent).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.Video.VideoComponent).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.Voxels.Module).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); + session.SuggestedPackages.Add(new PackageName(typeof(Xenko.SpriteStudio.Runtime.SpriteStudioNodeLinkComponent).Assembly.GetName().Name, new PackageVersion(XenkoVersion.NuGetVersion))); } /// diff --git a/sources/editor/Xenko.Core.Assets.Editor/Services/IEditorDialogService.cs b/sources/editor/Xenko.Core.Assets.Editor/Services/IEditorDialogService.cs index 6dd6b0b007..7489831d27 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Services/IEditorDialogService.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/Services/IEditorDialogService.cs @@ -143,8 +143,8 @@ public interface IPackagePickerDialog : IModalDialog { bool AllowMultiSelection { get; set; } - Func Filter { get; set; } + Func Filter { get; set; } - IReadOnlyCollection SelectedPackages { get; } + IReadOnlyCollection SelectedPackages { get; } } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/PackagePickerWindow.xaml.cs b/sources/editor/Xenko.Core.Assets.Editor/View/PackagePickerWindow.xaml.cs index d424b1dd66..3e9225df80 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/PackagePickerWindow.xaml.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/PackagePickerWindow.xaml.cs @@ -20,34 +20,29 @@ public partial class PackagePickerWindow : IPackagePickerDialog { private readonly SessionViewModel session; - private readonly List selectedPackages = new List(); + private readonly List selectedPackages = new List(); public PackagePickerWindow(SessionViewModel session) { this.session = session; InitializeComponent(); - Packages = new List(); + Packages = new List(); DataContext = this; Width = Math.Min(Width, SystemParameters.WorkArea.Width); Height = Math.Min(Height, SystemParameters.WorkArea.Height); } - public List Packages { get; set; } + public List Packages { get; set; } public bool AllowMultiSelection { get; set; } - public Func Filter { get; set; } + public Func Filter { get; set; } - IReadOnlyCollection IPackagePickerDialog.SelectedPackages => selectedPackages; + IReadOnlyCollection IPackagePickerDialog.SelectedPackages => selectedPackages; public override async Task ShowModal() { - foreach (var package in session.LocalPackages) - { - if (Filter == null || Filter(package)) - Packages.Add(package); - } - foreach (var package in session.StorePackages) + foreach (var package in await session.SuggestPackagesToAdd()) { if (Filter == null || Filter(package)) Packages.Add(package); @@ -59,7 +54,7 @@ public override async Task ShowModal() if (Result == Presentation.Services.DialogResult.Ok) { - selectedPackages.AddRange(PackageListBox.SelectedItems.Cast()); + selectedPackages.AddRange(PackageListBox.SelectedItems.Cast()); } return Result; } diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/PackageViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/PackageViewModel.cs index 64759b72e0..8b5c41aa42 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/PackageViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/PackageViewModel.cs @@ -31,6 +31,8 @@ using Xenko.Core.Quantum; using Xenko.Core.Quantum.References; using Xenko.Core.Translation; +using System.IO; +using Xenko.Core.Packages; namespace Xenko.Core.Assets.Editor.ViewModel { @@ -509,24 +511,40 @@ await Task.Run(() => } } - public void AddDependency(PackageViewModel packageViewModel) + public async Task AddDependency(PickablePackageViewModel pickablePackageViewModel) { using (var transaction = UndoRedoService.CreateTransaction()) { - DependencyRange dependency; - if (packageViewModel.Package.Container is SolutionProject project) + var dependency = pickablePackageViewModel.DependencyRange; + + // Check if package isn't a dependency yet + if (Package.Container.DirectDependencies.Any(x => x.Name == dependency.Name)) + return; + + var reference = new DirectDependencyReferenceViewModel(dependency, this, Dependencies, true); + UndoRedoService.SetName(transaction, $"Add dependency to package '{reference.Name}'"); + + // Update dependencies with NuGet + if (Package.Container is SolutionProject project2) { - dependency = new DependencyRange(packageViewModel.Name, new PackageVersionRange(packageViewModel.Package.Meta.Version, true), DependencyType.Project) + var log = new LoggerResult(); + await VSProjectHelper.RestoreNugetPackages(log, project2.FullPath); + PackageSession.UpdateDependencies(project2, false, true); + + // If the package is not part of session yet, make sure it gets added at this point + foreach (var projectDependency in project2.FlattenedDependencies) { - MSBuildProject = project.FullPath, - }; - } - else - { - dependency = new DependencyRange(packageViewModel.Name, new PackageVersionRange(packageViewModel.Package.Meta.Version, true), DependencyType.Package); + if (projectDependency.Package == null && projectDependency.Type == DependencyType.Package) + { + var packageFile = PackageStore.Instance.GetPackageFileName(projectDependency.Name, new PackageVersionRange(projectDependency.Version)); + if (packageFile != null && File.Exists(packageFile)) + { + var dependencyPackageViewModel = await Session.AddExistingProject(packageFile); + projectDependency.Package = dependencyPackageViewModel.Package; + } + } + } } - var reference = new DirectDependencyReferenceViewModel(dependency, this, Dependencies, true); - UndoRedoService.SetName(transaction, $"Add dependency to package '{reference.Name}'"); } } @@ -772,4 +790,52 @@ private static int ComparePackageContent(DirtiableEditableViewModel x, Dirtiable throw new InvalidOperationException("Unable to sort the given items for the Content collection of PackageViewModel"); } } + public abstract class PickablePackageViewModel : DispatcherViewModel + { + protected PickablePackageViewModel([NotNull] IViewModelServiceProvider serviceProvider) + : base(serviceProvider) + { + } + + public abstract string Name { get; } + + public abstract DependencyRange DependencyRange { get; } + } + + public class LoadedPickablePackageViewModel : PickablePackageViewModel + { + public LoadedPickablePackageViewModel(PackageViewModel package) : base(package.ServiceProvider) + { + Package = package; + } + + public PackageViewModel Package { get; } + + public override string Name => Package.Name; + + public override DependencyRange DependencyRange => + (Package.Package.Container is SolutionProject project) + ? new DependencyRange(Package.Name, new PackageVersionRange(Package.Package.Meta.Version, true), DependencyType.Project) + { + MSBuildProject = project.FullPath, + } + : new DependencyRange(Package.Name, new PackageVersionRange(Package.Package.Meta.Version, true), DependencyType.Package); + } + + public class UnloadedPickablePackageViewModel : PickablePackageViewModel + { + private readonly SessionViewModel session; + private readonly PackageName package; + + public UnloadedPickablePackageViewModel(SessionViewModel session, PackageName package) : base(session.ServiceProvider) + { + this.session = session; + this.package = package; + } + + public override string Name => package.Id; + + public override DependencyRange DependencyRange => + new DependencyRange(package.Id, new PackageVersionRange(package.Version, true), DependencyType.Package); + } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs index cb1fb4d94b..bd328f0802 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs @@ -36,6 +36,7 @@ using Xenko.Core.Presentation.ViewModel; using Xenko.Core.Presentation.Windows; using Xenko.Core.Translation; +using Xenko.Core.Packages; namespace Xenko.Core.Assets.Editor.ViewModel { @@ -1187,55 +1188,63 @@ private async Task AddExistingProject() var projectPath = fileDialog.FilePaths.FirstOrDefault(); if (result == DialogResult.Ok && projectPath != null) { - var loggerResult = new LoggerResult(); + await AddExistingProject(projectPath); + } + } - var workProgress = new WorkProgressViewModel(ServiceProvider, loggerResult) - { - Title = Tr._p("Title", "Importing project..."), - KeepOpen = KeepOpen.OnWarningsOrErrors, - IsIndeterminate = true, - IsCancellable = false - }; - workProgress.RegisterProgressStatus(loggerResult, true); - // Note: this task is note safely cancellable - // TODO: Remove the cancellation token if possible. - var cancellationSource = new CancellationTokenSource(); - - ServiceProvider.Get().ShowProgressWindow(workProgress, 500); - - await Task.Run(() => - { - try - { - session.AddExistingProject(projectPath, loggerResult, CreatePackageLoadParameters(workProgress, cancellationSource)); - } - catch (Exception e) - { - loggerResult.Error(Tr._p("Log", "There was a problem importing the package."), e); - } + public async Task AddExistingProject(string projectPath) + { + var loggerResult = new LoggerResult(); - }, cancellationSource.Token); + var workProgress = new WorkProgressViewModel(ServiceProvider, loggerResult) + { + Title = Tr._p("Title", "Importing project..."), + KeepOpen = KeepOpen.OnWarningsOrErrors, + IsIndeterminate = true, + IsCancellable = false + }; + workProgress.RegisterProgressStatus(loggerResult, true); + // Note: this task is note safely cancellable + // TODO: Remove the cancellation token if possible. + var cancellationSource = new CancellationTokenSource(); - // Set the range of the work in progress according to the created assets - workProgress.Minimum = 0; - workProgress.ProgressValue = 0; - workProgress.Maximum = session.Projects.OfType().Where(x => !packageMap.ContainsValue(x)).Sum(x => x.Package.Assets.Count); + ServiceProvider.Get().ShowProgressWindow(workProgress, 500); - using (var transaction = UndoRedoService.CreateTransaction()) + Package package = null; + await Task.Run(() => + { + try + { + package = session.AddExistingProject(projectPath, loggerResult, CreatePackageLoadParameters(workProgress, cancellationSource)).Package; + } + catch (Exception e) { - ProcessAddedProjects(loggerResult, workProgress, false); - UndoRedoService.SetName(transaction, $"Import project '{new UFile(projectPath).GetFileNameWithoutExtension()}'"); + loggerResult.Error(Tr._p("Log", "There was a problem importing the package."), e); } - // Notify that the task is finished - await workProgress.NotifyWorkFinished(cancellationSource.IsCancellationRequested, loggerResult.HasErrors); + }, cancellationSource.Token); + + // Set the range of the work in progress according to the created assets + workProgress.Minimum = 0; + workProgress.ProgressValue = 0; + workProgress.Maximum = session.Projects.OfType().Where(x => !packageMap.ContainsValue(x)).Sum(x => x.Package.Assets.Count); + + using (var transaction = UndoRedoService.CreateTransaction()) + { + ProcessAddedProjects(loggerResult, workProgress, true); + UndoRedoService.SetName(transaction, $"Import project '{new UFile(projectPath).GetFileNameWithoutExtension()}'"); } + + // Notify that the task is finished + await workProgress.NotifyWorkFinished(cancellationSource.IsCancellationRequested, loggerResult.HasErrors); + + return AllPackages.FirstOrDefault(x => x.Package == package); } internal void ProcessAddedProjects(LoggerResult loggerResult, WorkProgressViewModel workProgress, bool packageAlreadyInSession) { var newPackages = new List(); - foreach (var package in session.Projects.OfType().Where(x => !packageMap.ContainsValue(x))) + foreach (var package in session.Projects.Where(x => !packageMap.ContainsValue(x))) { var viewModel = CreateProjectViewModel(package, packageAlreadyInSession); viewModel.LoadPackageInformation(loggerResult, workProgress); @@ -1299,11 +1308,14 @@ private async Task AddDependency() // and packages that are already referenced. packagePicker.Filter = x => { - return !(x == selectedPackage || x.DependsOn(selectedPackage) || - selectedPackage.Dependencies.Content.Select(r => r.Target).Contains(x)); + if (!(x is LoadedPickablePackageViewModel loadedPackage)) + return true; + + return !(loadedPackage.Package == selectedPackage || loadedPackage.Package.DependsOn(selectedPackage) || + selectedPackage.Dependencies.Content.Select(r => r.Target).Contains(loadedPackage.Package)); }; - if (AllPackages.All(x => !packagePicker.Filter(x))) + if (AllPackages.All(x => !packagePicker.Filter(new LoadedPickablePackageViewModel(x)))) { await Dialogs.MessageBox(Tr._p("Message", "There are no packages that can be added as dependencies to this package."), MessageBoxButton.OK, MessageBoxImage.Information); return; @@ -1775,5 +1787,26 @@ public IEnumerable FindTemplates(TemplateScope asset) { return TemplateManager.FindTemplates(asset, session); } + + public List SuggestedPackages { get; } = new List(); + + public async Task> SuggestPackagesToAdd() + { + var packages = new List(); + packages.AddRange(LocalPackages.Select(x => new LoadedPickablePackageViewModel(x))); + packages.AddRange(StorePackages.Select(x => new LoadedPickablePackageViewModel(x))); + + // Note: later, we could even go further and add a NuGet search UI rather than a hardcoded list + foreach (var packageInfo in SuggestedPackages) + { + // Make sure this package is not already in the list + if (packages.Any(x => x.Name == packageInfo.Id)) + continue; + + packages.Add(new UnloadedPickablePackageViewModel(this, packageInfo)); + } + + return packages; + } } } From 2ed47da3d2cb762dbb2bf34b2dfe2b1d3e25d90b Mon Sep 17 00:00:00 2001 From: Phr00t Date: Tue, 25 Feb 2020 15:43:45 -0500 Subject: [PATCH 0794/2038] GameStudio: default to "Shared" application and remove the "Play" button (see description) GameStudio might get root assets confused if just being added for one platform (e.g. Windows was selected by default before). This makes the shared project default, so root assets are for all platforms. You can't "run" the shared application, though, so "Play" is removed. You will run and debug through Visual Studio 2019 (as always) --- .../Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs | 2 +- sources/editor/Xenko.GameStudio/GameStudioWindow.xaml | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs index bd328f0802..043a238d5d 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs @@ -531,7 +531,7 @@ public override void Destroy() private void AutoSelectCurrentProject() { - var currentProject = LocalPackages.OfType().FirstOrDefault(x => x.Type == ProjectType.Executable && x.Platform == PlatformType.Windows) ?? LocalPackages.FirstOrDefault(); + var currentProject = LocalPackages.OfType().FirstOrDefault(x => x.Platform == PlatformType.Shared) ?? LocalPackages.FirstOrDefault(); if (currentProject != null) { SetCurrentProject(currentProject); diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index ad1a639c84..53bc222600 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -396,10 +396,6 @@ ToolTip="{xk:ToolTip {xk:Localize Build the project, Context=ToolTip}, {x:Static strings:KeyGestures.BuildProject}}" xk:ToolTipHelper.Status="{Binding Status}" ToolTipService.ShowOnDisabled="True"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs b/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs index 8e11238e97..130c2c2f0d 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/AssetViewUserControl.xaml.cs @@ -5,13 +5,12 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Input; - +using Xceed.Wpf.Toolkit.Core; using Xenko.Core.Assets.Editor.View.Controls; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Presentation.Collections; using Xenko.Core.Presentation.Extensions; -using Xceed.Wpf.DataGrid; namespace Xenko.Core.Assets.Editor.View { @@ -126,8 +125,6 @@ public AssetViewUserControl() { InitializeComponent(); - Loaded += (s, e) => AddHandler(Row.EditBeginningEvent, (CancelRoutedEventHandler)CanBeginEditEvent); - Unloaded += (s, e) => RemoveHandler(Row.EditBeginningEvent, (CancelRoutedEventHandler)CanBeginEditEvent); } /// @@ -215,7 +212,7 @@ public void BeginEdit() var listBox = AssetViewPresenter.FindVisualChildOfType(); listBox?.BeginEdit(); - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); gridView?.BeginEdit(); } @@ -231,7 +228,7 @@ private void ZoomIn() } } - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); if (gridView != null) { GridThumbnailSize += ThumbnailZoomIncrement; @@ -254,7 +251,7 @@ private void ZoomOut() } } - var gridView = AssetViewPresenter.FindVisualChildOfType(); + var gridView = AssetViewPresenter.FindVisualChildOfType(); if (gridView != null) { GridThumbnailSize -= ThumbnailZoomIncrement; diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs deleted file mode 100644 index 6d58dc1e52..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/DragDrop/XceedDataGridDragDropBehavior.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Collections.Generic; -using System.Linq; -using Xenko.Core.Extensions; -using Xceed.Wpf.DataGrid; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - public class XceedDataGridDragDropBehavior : DragDropBehavior - { - protected override IEnumerable GetItemsToDrag(DataRow container) - { - if (container != null) - { - var sourceItem = container.DataContext; - return AssociatedObject.SelectedItems.Contains(sourceItem) ? AssociatedObject.SelectedItems.Cast() : sourceItem.ToEnumerable(); - } - return Enumerable.Empty(); - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs deleted file mode 100644 index 49344c751a..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridBindableSelectedItemsBehavior.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using Xenko.Core.Presentation.Behaviors; - -using Xceed.Wpf.DataGrid; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - public class XceedDataGridBindableSelectedItemsBehavior : BindableSelectedItemsBehavior - { - protected override void OnAttached() - { - SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems; - AssociatedObject.SelectionChanged += XceedDataGridSelectionChanged; - base.OnAttached(); - } - - protected override void OnDetaching() - { - base.OnDetaching(); - AssociatedObject.SelectionChanged -= XceedDataGridSelectionChanged; - SelectedItemsInAssociatedObject = AssociatedObject.SelectedItems; - } - - protected override void ScrollIntoView(object dataItem) - { - AssociatedObject.BringItemIntoView(dataItem); - } - - private void XceedDataGridSelectionChanged(object sender, DataGridSelectionChangedEventArgs e) - { - foreach (var selectionInfo in e.SelectionInfos) - { - ControlSelectionChanged(selectionInfo.AddedItems, selectionInfo.RemovedItems); - } - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs deleted file mode 100644 index 625e8fb398..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridResizableColumnsBehavior.cs +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System; -using System.Linq; -using System.Windows; -using System.Windows.Controls; - -using Xenko.Core.Extensions; -using Xenko.Core.Presentation.Behaviors; -using Xenko.Core.Presentation.Extensions; - -using Xceed.Wpf.DataGrid; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - /// - /// This behavior allows to have resizable columns in a while being able to define default widths using star notation. - /// It also prevent the columns do be resized below the viewport width - /// - public class XceedDataGridResizableColumnsBehavior : DeferredBehaviorBase - { - private ScrollContentPresenter scrollContentPresenter; - private bool updatingColumns; - private bool itemsSourceChanged; - private bool initialized; - - protected override void OnAttachedAndLoaded() - { - base.OnAttachedAndLoaded(); - - AssociatedObject.Columns.ForEach(x => x.Width = x.ActualWidth); - - scrollContentPresenter = AssociatedObject.FindVisualChildOfType(); - - // This occurs when closing a session - it is harmless to ignore it in this case - if (scrollContentPresenter == null) - return; - - AssociatedObject.ItemsSourceChangeCompleted += ItemsSourceChanged; - AssociatedObject.LayoutUpdated += LayoutUpdated; - AssociatedObject.SizeChanged += SizeChanged; - itemsSourceChanged = true; - // Prevent the selection of the first item - AssociatedObject.SelectedItems.Clear(); - initialized = true; - } - - protected override void OnDetachingAndUnloaded() - { - if (initialized) - { - var columnManagerRow = AssociatedObject.FindVisualChildOfType(); - if (columnManagerRow != null) - { - var cells = columnManagerRow.FindVisualChildrenOfType(); - cells.ForEach(x => x.SizeChanged -= ColumnSizeChanged); - AssociatedObject.SizeChanged -= SizeChanged; - } - } - base.OnDetachingAndUnloaded(); - } - - private void ItemsSourceChanged(object sender, EventArgs e) - { - // cells update is defered to after the next layout update - itemsSourceChanged = true; - // Prevent the selection of the first item - AssociatedObject.SelectedItems.Clear(); - } - - private void LayoutUpdated(object sender, EventArgs e) - { - if (itemsSourceChanged) - { - var columnManagerRow = AssociatedObject.FindVisualChildOfType(); - if (columnManagerRow != null) - { - var cells = columnManagerRow.FindVisualChildrenOfType(); - cells.ForEach(x => x.SizeChanged += ColumnSizeChanged); - } - itemsSourceChanged = false; - } - } - - private void ColumnSizeChanged(object sender, SizeChangedEventArgs e) - { - if (updatingColumns) - return; - - updatingColumns = true; - - double total = AssociatedObject.Columns.Sum(x => x.ActualWidth); - if (total < scrollContentPresenter.ActualWidth) - { - foreach (var column in AssociatedObject.Columns) - { - column.Width = column.ActualWidth * scrollContentPresenter.ActualWidth / total; - } - } - - updatingColumns = false; - } - - private void SizeChanged(object sender, SizeChangedEventArgs e) - { - double total = AssociatedObject.Columns.Sum(x => x.ActualWidth); - var offset = e.NewSize.Width - e.PreviousSize.Width; - foreach (var column in AssociatedObject.Columns) - { - column.Width = column.ActualWidth * (total + offset) / total; - } - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs deleted file mode 100644 index 1febb52b4a..0000000000 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Behaviors/XceedDataGridThumbnailPrioritizationBehavior.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) -// Distributed under the MIT license. See the LICENSE.md file in the project root for more information. -using System.Linq; -using System.Windows.Controls; - -using Xenko.Core.Assets.Editor.ViewModel; -using Xenko.Core.Extensions; -using Xenko.Core.Presentation.Behaviors; -using Xenko.Core.Presentation.Extensions; - -using Xceed.Wpf.DataGrid; -using Xceed.Wpf.DataGrid.Views; - -namespace Xenko.Core.Assets.Editor.View.Behaviors -{ - public class XceedDataGridThumbnailPrioritizationBehavior : DeferredBehaviorBase - { - private TableViewScrollViewer scrollViewer; - - protected override void OnAttachedAndLoaded() - { - scrollViewer = AssociatedObject.FindVisualChildOfType(); - scrollViewer.ScrollChanged += ScrollChanged; - base.OnAttachedAndLoaded(); - } - - protected override void OnDetachingAndUnloaded() - { - scrollViewer.ScrollChanged -= ScrollChanged; - scrollViewer = null; - base.OnDetachingAndUnloaded(); - } - - private void ScrollChanged(object sender, ScrollChangedEventArgs e) - { - var session = AssociatedObject.ItemsSource?.Cast().FirstOrDefault()?.Session; - if (session == null) - return; - - var visibleAssets = AssociatedObject.FindVisualChildrenOfType().NotNull().Select(x => x.DataContext).OfType().Where(x => x != null); - session.Thumbnails.IncreaseThumbnailPriority(visibleAssets); - } - } -} diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml index 36141887c3..e701157a21 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml @@ -14,6 +14,19 @@ + + + + + diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs b/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs index a1e8c6a66c..bb84569c76 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/Controls/GridLogViewer.cs @@ -2,6 +2,7 @@ // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Controls; @@ -12,36 +13,20 @@ using Xenko.Core.Assets.Diagnostics; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Diagnostics; - -using Xceed.Wpf.DataGrid; +using Xenko.Core.Presentation.Collections; namespace Xenko.Core.Assets.Editor.View.Controls { /// /// This control displays a collection of in a grid. /// - [TemplatePart(Name = "PART_LogGridView", Type = typeof(DataGridControl))] - [TemplatePart(Name = "PART_PreviousResult", Type = typeof(ButtonBase))] - [TemplatePart(Name = "PART_NextResult", Type = typeof(ButtonBase))] - [TemplatePart(Name = "PART_GridLogViewerCollectionSourceContainer", Type = typeof(FrameworkElement))] + [TemplatePart(Name = "PART_LogGridView", Type = typeof(DataGridEx))] public class GridLogViewer : Control { - private int currentResult; - /// /// The used to display log messages. /// - private DataGridControl logGridView; - - /// - /// The used to navigate to the previous search result. - /// - private ButtonBase previousResultButton; - - /// - /// The used to navigate to the next search result. - /// - private ButtonBase nextResultButton; + private DataGridEx logGridView; static GridLogViewer() { @@ -51,38 +36,13 @@ static GridLogViewer() /// /// Identifies the dependency property. /// - public static readonly DependencyProperty LogMessagesProperty = DependencyProperty.Register("LogMessages", typeof(ICollection), typeof(GridLogViewer), new PropertyMetadata(null)); + public static readonly DependencyProperty LogMessagesProperty = DependencyProperty.Register("LogMessages", typeof(ObservableList), typeof(GridLogViewer), new PropertyMetadata(null)); /// /// Identifies the dependency property. /// public static readonly DependencyProperty IsToolBarVisibleProperty = DependencyProperty.Register("IsToolBarVisible", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty CanFilterLogProperty = DependencyProperty.Register("CanFilterLog", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty CanSearchLogProperty = DependencyProperty.Register("CanSearchLog", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(true)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty SearchTokenProperty = DependencyProperty.Register("SearchToken", typeof(string), typeof(GridLogViewer), new PropertyMetadata("", SearchTokenChanged)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty SearchMatchCaseProperty = DependencyProperty.Register("SearchMatchCase", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(false, SearchTokenChanged)); - - /// - /// Identifies the dependency property. - /// - public static readonly DependencyProperty SearchMatchWordProperty = DependencyProperty.Register("SearchMatchWord", typeof(bool), typeof(GridLogViewer), new PropertyMetadata(false, SearchTokenChanged)); - /// /// Identifies the dependency property. /// @@ -126,38 +86,15 @@ static GridLogViewer() /// /// Gets or sets the collection of to display. /// - public ICollection LogMessages { get { return (ICollection)GetValue(LogMessagesProperty); } set { SetValue(LogMessagesProperty, value); } } + public ObservableList LogMessages { get { return (ObservableList)GetValue(LogMessagesProperty); } set { SetValue(LogMessagesProperty, value); } } + + public ObservableList FilteredLogMessages { get; set; } = new ObservableList(); /// /// Gets or sets whether the tool bar should be visible. /// public bool IsToolBarVisible { get { return (bool)GetValue(IsToolBarVisibleProperty); } set { SetValue(IsToolBarVisibleProperty, value); } } - /// - /// Gets or sets whether it is possible to filter the log text. - /// - public bool CanFilterLog { get { return (bool)GetValue(CanFilterLogProperty); } set { SetValue(CanFilterLogProperty, value); } } - - /// - /// Gets or sets whether it is possible to search the log text. - /// - public bool CanSearchLog { get { return (bool)GetValue(CanSearchLogProperty); } set { SetValue(CanSearchLogProperty, value); } } - - /// - /// Gets or sets the current search token. - /// - public string SearchToken { get { return (string)GetValue(SearchTokenProperty); } set { SetValue(SearchTokenProperty, value); } } - - /// - /// Gets or sets whether the search result should match the case. - /// - public bool SearchMatchCase { get { return (bool)GetValue(SearchMatchCaseProperty); } set { SetValue(SearchMatchCaseProperty, value); } } - - /// - /// Gets or sets whether the search result should match whole words only. - /// - public bool SearchMatchWord { get { return (bool)GetValue(SearchMatchWordProperty); } set { SetValue(SearchMatchWordProperty, value); } } - /// /// Gets or sets whether the log viewer should display debug messages. /// @@ -203,35 +140,11 @@ public override void OnApplyTemplate() { base.OnApplyTemplate(); - logGridView = GetTemplateChild("PART_LogGridView") as DataGridControl; + logGridView = GetTemplateChild("PART_LogGridView") as DataGridEx; if (logGridView == null) throw new InvalidOperationException("A part named 'PART_LogGridView' must be present in the ControlTemplate, and must be of type 'DataGridControl'."); - previousResultButton = GetTemplateChild("PART_PreviousResult") as ButtonBase; - if (previousResultButton == null) - throw new InvalidOperationException("A part named 'PART_PreviousResult' must be present in the ControlTemplate, and must be of type 'ButtonBase'."); - - nextResultButton = GetTemplateChild("PART_NextResult") as ButtonBase; - if (nextResultButton == null) - throw new InvalidOperationException("A part named 'PART_NextResult' must be present in the ControlTemplate, and must be of type 'ButtonBase'."); - - var sourceContainer = GetTemplateChild("PART_GridLogViewerCollectionSourceContainer") as FrameworkElement; - if (sourceContainer == null) - throw new InvalidOperationException("A part named 'PART_GridLogViewerCollectionSourceContainer' must be present in the ControlTemplate, and must be of type 'FrameworkElement'."); - - var source = sourceContainer.Resources["GridLogViewerCollectionSource"]; - if (!(source is DataGridCollectionViewSourceBase)) - throw new InvalidOperationException("The 'PART_GridLogViewerCollectionSourceContainer' must be contain a 'GridLogViewerCollectionSource' resource that is the source of the collection view for the DataGridControl."); - - ((DataGridCollectionViewSourceBase)source).Filter += FilterHandler; logGridView.MouseDoubleClick += GridMouseDoubleClick; - previousResultButton.Click += PreviousResultClicked; - nextResultButton.Click += NextResultClicked; - } - - private void FilterHandler(object value, FilterEventArgs e) - { - e.Accepted = FilterMethod(e.Item); } private void GridMouseDoubleClick(object sender, MouseButtonEventArgs e) @@ -254,173 +167,27 @@ private void GridMouseDoubleClick(object sender, MouseButtonEventArgs e) if (asset != null) Session.ActiveAssetView.SelectAssetCommand.Execute(asset); } - } - private void SelectFirstOccurrence() - { - currentResult = 0; - var token = SearchToken; - if (!string.IsNullOrEmpty(token)) - { - var message = LogMessages.FirstOrDefault(Match); - logGridView.SelectedItem = message; - if (message != null) - { - logGridView.BringItemIntoView(message); - } - } } - - private void SelectPreviousOccurrence() - { - var token = SearchToken; - if (!string.IsNullOrEmpty(token)) - { - var message = FindPreviousMessage(); - logGridView.SelectedItem = message; - if (message != null) - { - logGridView.BringItemIntoView(message); - } - else - logGridView.SelectedItem = null; - } - } - - private void SelectNextOccurrence() - { - var token = SearchToken; - if (!string.IsNullOrEmpty(token)) - { - var message = FindNextMessage(); - logGridView.SelectedItem = message; - if (message != null) - { - logGridView.BringItemIntoView(message); - } - } - } - - private ILogMessage FindPreviousMessage() - { - int count = 0; - ILogMessage lastMessage = null; - --currentResult; - foreach (var message in LogMessages.Where(Match)) - { - lastMessage = message; - - if (count == currentResult) - { - return message; - } - ++count; - } - currentResult = Math.Max(0, count - 1); - return lastMessage; - } - - private ILogMessage FindNextMessage() - { - int count = 0; - ILogMessage firstMessage = null; - ++currentResult; - foreach (var message in LogMessages.Where(Match)) - { - if (firstMessage == null) - firstMessage = message; - - if (count == currentResult) - { - return message; - } - ++count; - } - currentResult = 0; - return firstMessage; - } - - private bool Match(ILogMessage message) - { - if (Match(message.Text)) - return true; - - var assetMessage = message as AssetSerializableLogMessage; - return assetMessage != null && Match(assetMessage.AssetUrl.FullPath); - } - - private bool Match(string text) - { - var token = SearchToken; - var stringComparison = SearchMatchCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; - int index = text.IndexOf(token, stringComparison); - if (index < 0) - return false; - - if (SearchMatchWord && text.Length > 1) - { - if (index > 0) - { - char c = text[index - 1]; - if (char.IsLetterOrDigit(c)) - return false; - } - if (index + token.Length < text.Length) - { - char c = text[index + token.Length]; - if (char.IsLetterOrDigit(c)) - return false; - } - } - return true; - } - private static void FilterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var logViewer = (GridLogViewer)d; logViewer.ApplyFilters(); } - /// - /// Raised when the property is changed. - /// - private static void SearchTokenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) - { - var logViewer = (GridLogViewer)d; - logViewer.SelectFirstOccurrence(); - } - - private void PreviousResultClicked(object sender, RoutedEventArgs e) - { - SelectPreviousOccurrence(); - } - - private void NextResultClicked(object sender, RoutedEventArgs e) - { - SelectNextOccurrence(); - } - + private void ApplyFilters() { if (logGridView == null || logGridView.ItemsSource == null) return; - - if (!(logGridView.ItemsSource is DataGridCollectionView)) - throw new InvalidOperationException("The item source of the part 'PART_LogGridView' must be a 'DataGridCollectionView'."); - - var view = (DataGridCollectionView)logGridView.ItemsSource; - view.Refresh(); - } - - private bool FilterMethod(object msg) - { - var message = (ILogMessage)msg; - return (ShowDebugMessages && message.Type == LogMessageType.Debug) - || (ShowVerboseMessages && message.Type == LogMessageType.Verbose) - || (ShowInfoMessages && message.Type == LogMessageType.Info) - || (ShowWarningMessages && message.Type == LogMessageType.Warning) - || (ShowErrorMessages && message.Type == LogMessageType.Error) - || (ShowFatalMessages && message.Type == LogMessageType.Fatal); + this.FilteredLogMessages.Clear(); + this.FilteredLogMessages.AddRange(this.LogMessages.Where(x => + x.IsDebug() && ShowDebugMessages || + x.IsError() && ShowErrorMessages || + x.IsFatal() && ShowFatalMessages || + x.IsInfo() && ShowInfoMessages || + x.IsVerbose() && ShowVerboseMessages || + x.IsWarning() && ShowWarningMessages)); } } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs index 7b3f26f8f2..3ba586eb5e 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/View/DataGridEx.cs @@ -11,10 +11,16 @@ using Xenko.Core.Extensions; using Xenko.Core.Presentation.Extensions; -using Xceed.Wpf.DataGrid; - namespace Xenko.Core.Assets.Editor.View { + /// + /// Xenko generic wpf data grid. Left empty for future development on a generic datagrid. + /// + public class DataGridEx : DataGrid + { + + } + /// /// This class wraps the class, making accessible all members that are required to make the feature work. /// is massively internal, making this feature impossible to implement by default on custom controls. @@ -95,14 +101,6 @@ public static string GetPrimaryTextPath(ItemsControl itemsControl) } - public static int FindMatchingPrefix(DataGridEx dataGridEx, string primaryTextPath, string prefix, string nextChar, int startItemIndex, bool lookForFallbackMatchToo, ref bool wasNewCharUsed) - { - var parameters = new object[] { dataGridEx, primaryTextPath, prefix, nextChar, startItemIndex, lookForFallbackMatchToo, wasNewCharUsed }; - var result = (int)FindMatchingPrefixMethod.Invoke(null, parameters); - wasNewCharUsed = (bool)parameters[6]; - return result; - } - public void AddCharToPrefix(string nextChar) { AddCharToPrefixMethod.Invoke(textSearch, new object[] { nextChar }); @@ -113,70 +111,4 @@ public void ResetTimeout() ResetTimeoutMethod.Invoke(textSearch, new object[] { }); } } - - /// - /// An implementation of DataGrid class that inherits from Xceed DataGridControl and add support for . - /// - public class DataGridEx : DataGridControl - { - /// - protected override void OnTextInput(TextCompositionEventArgs e) - { - base.OnTextInput(e); - if (string.IsNullOrEmpty(e.Text) || !IsTextSearchEnabled || !Equals(e.Source, this) && !Equals(ItemsControlFromItemContainer(e.Source as DependencyObject), this)) - return; - - var textSearch = TextSearchWrapper.EnsureInstance(this); - if (textSearch == null) - return; - - DoSearch(textSearch, e.Text); - e.Handled = true; - } - - /// - /// This method reimplements DoSearch from . - /// - /// - /// - private void DoSearch(TextSearchWrapper textSearch, string nextChar) - { - bool lookForFallbackMatchToo = false; - int startItemIndex = 0; - ItemCollection items = Items; - if (textSearch.IsActive) - startItemIndex = textSearch.MatchedItemIndex; - if (textSearch._charsEntered.Count > 0 && string.Compare(textSearch._charsEntered[textSearch._charsEntered.Count - 1], nextChar, true, TextSearchWrapper.GetCulture(this)) == 0) - lookForFallbackMatchToo = true; - string primaryTextPath = TextSearchWrapper.GetPrimaryTextPath(this); - bool wasNewCharUsed = false; - int matchingPrefix = TextSearchWrapper.FindMatchingPrefix(this, primaryTextPath, textSearch.Prefix, nextChar, startItemIndex, lookForFallbackMatchToo, ref wasNewCharUsed); - if (matchingPrefix != -1) - { - if (!textSearch.IsActive || matchingPrefix != startItemIndex) - { - if (SelectedItem != items[matchingPrefix]) - { - SelectedItem = items[matchingPrefix]; - BringItemIntoView(SelectedItem); - UpdateLayout(); - var container = GetContainerFromItem(SelectedItem) as DataRow; - if (container != null) - { - var cellToFocus = container.FindVisualChildrenOfType().FirstOrDefault(x => x.Focusable); - if (cellToFocus != null) - Keyboard.Focus(cellToFocus); - } - } - textSearch.MatchedItemIndex = matchingPrefix; - } - if (wasNewCharUsed) - textSearch.AddCharToPrefix(nextChar); - if (!textSearch.IsActive) - textSearch.IsActive = true; - } - if (textSearch.IsActive) - textSearch.ResetTimeout(); - } - } } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj index 0783d8d1a6..3070b75138 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj +++ b/sources/editor/Xenko.Core.Assets.Editor/Xenko.Core.Assets.Editor.csproj @@ -1,4 +1,4 @@ - + @@ -10,7 +10,7 @@ - + @@ -83,7 +83,6 @@ - diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml index 53bc222600..82fcb28b8c 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml @@ -21,7 +21,6 @@ - From b393a6bd6428c9d88786ec9c03239598c5de5c74 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Tue, 18 Feb 2020 07:39:12 +0900 Subject: [PATCH 0802/2038] Lighting: small compilation fix after merges --- .../Rendering/Shadows/LightSpotShadowMapRenderer.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/LightSpotShadowMapRenderer.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/LightSpotShadowMapRenderer.cs index 508854428c..40b08ca647 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Shadows/LightSpotShadowMapRenderer.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Shadows/LightSpotShadowMapRenderer.cs @@ -222,6 +222,9 @@ public override void ApplyDrawParameters(RenderDrawContext context, ParameterCol { for (int i = 0; i < currentLights.Count; ++i) { + var lightEntry = currentLights[i]; + var light = lightEntry.Light; + var singleLightData = (LightSpotShadowMapShaderData)lightEntry.ShadowMapTexture.ShaderData; worldToShadowCascadeUV[lightIndex] = singleLightData.WorldToShadowCascadeUV; Matrix.Invert(ref singleLightData.WorldToShadowCascadeUV, out inverseWorldToShadowCascadeUV[lightIndex]); @@ -232,7 +235,6 @@ public override void ApplyDrawParameters(RenderDrawContext context, ParameterCol if (light.BoundingBox.Intersects(ref boundingBox2)) { - var singleLightData = (LightSpotShadowMapShaderData)lightEntry.ShadowMapTexture.ShaderData; worldToShadowCascadeUV[lightIndex] = singleLightData.WorldToShadowCascadeUV; inverseWorldToShadowCascadeUV[lightIndex] = Matrix.Invert(singleLightData.WorldToShadowCascadeUV); From 30f604517c974c1af491c37bfc75c5a2c9276de6 Mon Sep 17 00:00:00 2001 From: Basewq Date: Tue, 25 Feb 2020 13:11:44 +1300 Subject: [PATCH 0803/2038] [GameStudio] Throttle game update and skip rendering game scenes, prefabs and preview asset when its sub-windows are hidden (ie. due to being in hidden in tab control) --- .../Services/EditorGameController.cs | 10 +++++ .../Services/IEditorGameController.cs | 10 +++++ .../ViewModels/GameEditorViewModel.cs | 14 +++++- .../Services/IAssetPreviewService.cs | 4 ++ .../EditorGame/Game/EditorServiceGame.cs | 45 ++++++++++++++++++- .../Preview/GameStudioPreviewService.cs | 12 ++++- .../Xenko.GameStudio/AssetEditorsManager.cs | 25 +++++++++++ .../Xenko.GameStudio/DockingLayoutManager.cs | 35 +++++++++++++++ .../Xenko.GameStudio/GameStudioWindow.xaml.cs | 28 ++++++++++++ .../Xenko.GameStudio/PreviewViewModel.cs | 15 ++++++- 10 files changed, 193 insertions(+), 5 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs index bb110732a9..e67583171b 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs @@ -231,6 +231,16 @@ public async Task StartGame() return true; } + public void OnHideGame() + { + Game.IsEditorHidden = true; + } + + public void OnShowGame() + { + Game.IsEditorHidden = false; + } + public Vector3 GetMousePositionInScene(bool lastRightClick) { EnsureNotDestroyed(); diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs index 7b8384c907..771686ea5a 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs @@ -45,6 +45,16 @@ public interface IEditorGameController : IDestroyable, IDispatcherService /// True if the scene was successfully created, false otherwise. Task CreateScene(); + /// + /// Stops the game from rendering and throttle game updates. + /// + void OnHideGame(); + + /// + /// Resumes the game rendering and updating and . + /// + void OnShowGame(); + /// /// Finds the game-side instance corresponding to the part with the given id, if it exists. /// diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs index 19337b094a..cef2992aa0 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs @@ -29,7 +29,7 @@ protected GameEditorViewModel([NotNull] AssetViewModel asset, [NotNull] Func @@ -77,6 +77,16 @@ public override void Destroy() base.Destroy(); } + public void HideGame() + { + Controller.OnHideGame(); + } + + public void ShowGame() + { + Controller.OnShowGame(); + } + protected virtual async Task InitializeEditor() { Dispatcher.EnsureAccess(); @@ -112,7 +122,7 @@ private void CopyErrorToClipboard() SafeClipboard.SetText(log); } - private void Resume() + private void ResumeFromError() { Controller.GetService()?.Resume(); } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs index f6dcd20f56..15d5936142 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs @@ -13,5 +13,9 @@ public interface IAssetPreviewService : IDisposable object GetCurrentPreviewView(); event EventHandler PreviewAssetUpdated; + + void OnShowPreview(); + + void OnHidePreview(); } } diff --git a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs index 2606f208c3..bcf1ba8d70 100644 --- a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs +++ b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs @@ -1,6 +1,7 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; +using Xenko.Core; using Xenko.Core.Annotations; using Xenko.Core.BuildEngine; using Xenko.Core.IO; @@ -8,6 +9,7 @@ using Xenko.Editor.Build; using Xenko.Editor.Engine; using Xenko.Games; +using Xenko.Games.Time; using Xenko.Graphics; using Xenko.Rendering.Compositing; @@ -44,10 +46,36 @@ public abstract class EditorServiceGame : EmbeddedGame public static readonly Color EditorBackgroundColorHdr = new Color(61, 61, 61, 255); + private static readonly TimeSpan GameHiddenNextUpdateTime = TimeSpan.FromSeconds(1); + + private readonly TimerTick gameHiddenUpdateTimer = new TimerTick(); + private TimeSpan gameHiddenUpdateTimeElapsed = TimeSpan.Zero; + private bool isEditorHidden = false; + public EditorGameServiceRegistry EditorServices { get; private set; } public IGameSettingsAccessor PackageSettings { get; set; } + /// + /// True if the game is not visible in the editor which will stop rendering and + /// throttle game updates. + /// + /// + /// Used when game is not visible in the editor (eg. hidden inside a tab control). + /// We only throttle updates instead of completely suspending the game because a game exit command is done + /// within the ScriptSystem, so we must be able to run this system. + /// + public bool IsEditorHidden + { + get { return isEditorHidden; } + set + { + gameHiddenUpdateTimer.Reset(); + gameHiddenUpdateTimeElapsed = TimeSpan.Zero; + isEditorHidden = value; + } + } + /// /// True if game is faulted (not running). /// @@ -117,6 +145,21 @@ protected override void Update(GameTime gameTime) if (Faulted) return; + if (IsEditorHidden) + { + gameHiddenUpdateTimer.Tick(); + gameHiddenUpdateTimeElapsed += gameHiddenUpdateTimer.ElapsedTime; + if (gameHiddenUpdateTimeElapsed < GameHiddenNextUpdateTime) + { + return; + } + else + { + System.Diagnostics.Debug.WriteLine($"{Name}.Update - {gameHiddenUpdateTimeElapsed.TotalMilliseconds}"); + gameHiddenUpdateTimeElapsed -= GameHiddenNextUpdateTime; + } + } + try { base.Update(gameTime); @@ -137,7 +180,7 @@ protected override void Update(GameTime gameTime) protected override void Draw(GameTime gameTime) { // Keep going only if last exception has been "resolved" - if (Faulted) + if (Faulted || IsEditorHidden) return; try diff --git a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs index 4dc9fa0be5..a28cbe453c 100644 --- a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs +++ b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs @@ -195,7 +195,7 @@ public void SetAssetToPreview(AssetViewModel asset) } public AssetCompilerResult Compile(AssetItem asset) - { + { return previewCompiler.Prepare(previewCompileContext, asset); } @@ -319,5 +319,15 @@ public void RegisterAssetPreviewFactories(IReadOnlyDictionary assetPreviewFactories.Add(x.Key, x.Value)); } + + public void OnShowPreview() + { + PreviewGame.IsEditorHidden = false; + } + + public void OnHidePreview() + { + PreviewGame.IsEditorHidden = true; + } } } diff --git a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs index de005b51cb..a95bc96aac 100644 --- a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs +++ b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs @@ -313,6 +313,7 @@ internal async Task OpenAssetEditorWindow([NotNull] AssetViewModel asset, bool s AvalonDockHelper.GetDocumentPane(dockingLayoutManager.DockingManager).Children.Add(editorPane); } editorPane.IsActiveChanged += EditorPaneIsActiveChanged; + editorPane.IsSelectedChanged += EditorPaneIsSelectedChanged; editorPane.Closing += EditorPaneClosing; editorPane.Closed += EditorPaneClosed; editorPane.Content = view; @@ -495,6 +496,7 @@ private static void CleanEditorPane([NotNull] LayoutAnchorable editorPane) private void RemoveEditorPane([NotNull] LayoutAnchorable editorPane) { editorPane.IsActiveChanged -= EditorPaneIsActiveChanged; + editorPane.IsSelectedChanged -= EditorPaneIsSelectedChanged; editorPane.Closing -= EditorPaneClosing; editorPane.Closed -= EditorPaneClosed; @@ -567,6 +569,29 @@ private static void EditorPaneIsActiveChanged(object sender, EventArgs e) } } + private static void EditorPaneIsSelectedChanged(object sender, EventArgs e) + { + var editorPane = (LayoutAnchorable)sender; + var element = editorPane.Content as FrameworkElement; + + if (element != null) + { + var assetViewModel = element?.DataContext as AssetViewModel; + if (assetViewModel?.Editor is Assets.Presentation.AssetEditors.GameEditor.ViewModels.GameEditorViewModel gameEditor) + { + // A tab/sub-window is visible via IsSelected, not IsVisible + if (editorPane.IsSelected) + { + gameEditor.ShowGame(); + } + else + { + gameEditor.HideGame(); + } + } + } + } + /// /// Makes the editor pane active and visible. /// diff --git a/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs b/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs index 4e84b3eacd..5f2e2a20dd 100644 --- a/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs +++ b/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs @@ -15,6 +15,7 @@ using Xceed.Wpf.AvalonDock; using Xceed.Wpf.AvalonDock.Layout; using Xceed.Wpf.AvalonDock.Layout.Serialization; +using Microsoft.Xaml.Behaviors; namespace Xenko.GameStudio { @@ -190,14 +191,31 @@ private void ApplyDockingLayout(string text) { // Save the binding expressions of all the current anchorables var bindings = new Dictionary>(); + var contentIdToBehaviors = new Dictionary(); foreach (var anchorable in AvalonDockHelper.GetAllAnchorables(DockingManager).Where(x => !string.IsNullOrEmpty(x.ContentId))) { var titleBindingInfo = BindingInfo.FromBindingExpression(BindingOperations.GetBindingExpression(anchorable, LayoutContent.TitleProperty)); var isVisibleBindingInfo = BindingInfo.FromBindingExpression(BindingOperations.GetBindingExpression(anchorable, AvalonDockHelper.IsVisibleProperty)); bindings.Add(anchorable.ContentId, new List { titleBindingInfo, isVisibleBindingInfo }); + + // Save behaviors, although complex bindings (eg. nested bindings) will not be restored properly... + var behaviorCollection = Interaction.GetBehaviors(anchorable); + if (behaviorCollection.Count > 0) + { + var pendingBehaviours = behaviorCollection.ToArray(); + behaviorCollection.Clear(); + contentIdToBehaviors.Add(anchorable.ContentId, pendingBehaviours); + } } // Unregister docking manager AvalonDockHelper.UnregisterDockingManager(DockingManager); + // This is a bit of a hack, but we need to do this with AssetPreview due to how bad the LayoutAnchorable is on determining + // if it's actually visible or not. + var assetPreviewAnchorable = AvalonDockHelper.GetAllAnchorables(DockingManager).FirstOrDefault(x => string.Equals(x.ContentId, "AssetPreview")); + if (assetPreviewAnchorable != null) + { + gameStudioWindow.UnregisterAssetPreview(assetPreviewAnchorable); + } // Deserialize the string using (var stream = new MemoryStream()) { @@ -219,9 +237,26 @@ private void ApplyDockingLayout(string text) BindingOperations.SetBinding(anchorable, bindingInfo.Property, bindingInfo.Binding); } } + + if (contentIdToBehaviors.TryGetValue(anchorable.ContentId, out var pendingBehaviours)) + { + // Restore behaviors + var behaviorCollection = Interaction.GetBehaviors(anchorable); + foreach (var b in pendingBehaviours) + { + b.Attach(anchorable); + behaviorCollection.Add(b); + } + } } // Re-register docking manager with new layout AvalonDockHelper.RegisterDockingManager(session.ServiceProvider, DockingManager); + // Hack: need to get AssetPreview and register handlers again + assetPreviewAnchorable = AvalonDockHelper.GetAllAnchorables(DockingManager).FirstOrDefault(x => string.Equals(x.ContentId, "AssetPreview")); + if (assetPreviewAnchorable != null) + { + gameStudioWindow.RegisterAssetPreview(assetPreviewAnchorable); + } } private string GetDockingLayout() diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs index 700daddbc7..8893764150 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs @@ -24,6 +24,7 @@ using Xenko.Core.Presentation.Interop; using Xenko.Core.Presentation.Windows; using Xenko.Core.Translation; +using Xceed.Wpf.AvalonDock.Layout; #if DEBUG using Xenko.Assets.Presentation.Test; #endif @@ -180,6 +181,33 @@ protected override void OnClosing(CancelEventArgs e) SaveAndClose().Forget(); } + internal void RegisterAssetPreview(LayoutAnchorable assetPreviewAnchorable) + { + // We listen to the events here instead of via xaml because DockingLayoutManager essentially breaks + // the entire docking control and OnEventCommandBehavior.CommandParameter binding would not + // get restored properly, due to not being able to rebind to a control. + assetPreviewAnchorable.IsSelectedChanged += OnAssetPreviewAnchorable_IsSelectedChanged; + UpdateAssetPreviewAnchorable(assetPreviewAnchorable); + } + + internal void UnregisterAssetPreview(LayoutAnchorable assetPreviewAnchorable) + { + assetPreviewAnchorable.IsSelectedChanged -= OnAssetPreviewAnchorable_IsSelectedChanged; + } + + private void OnAssetPreviewAnchorable_IsSelectedChanged(object sender, EventArgs e) + { + if (sender is LayoutAnchorable anchorable) + { + UpdateAssetPreviewAnchorable(anchorable); + } + } + + private void UpdateAssetPreviewAnchorable(LayoutAnchorable anchorable) + { + (Editor as GameStudioViewModel)?.Preview?.RenderPreviewCommand?.Execute(anchorable.IsSelected); + } + private void InitializeWindowSize() { var previousWorkAreaWidth = GameStudioInternalSettings.WorkAreaWidth.GetValue(); diff --git a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs index 26734e384d..3044b1d5a1 100644 --- a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs +++ b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs @@ -7,6 +7,7 @@ using Xenko.Core.Assets.Editor.Services; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Extensions; +using Xenko.Core.Presentation.Commands; using Xenko.Core.Presentation.ViewModel; namespace Xenko.GameStudio @@ -17,15 +18,19 @@ public class PreviewViewModel : DispatcherViewModel, IDisposable private IAssetPreviewService previewService; private object previewObject; - + public PreviewViewModel(SessionViewModel session) : base(session.SafeArgument(nameof(session)).ServiceProvider) { this.session = session; session.ActiveAssetView.SelectedAssets.CollectionChanged += SelectedAssetsCollectionChanged; session.ActiveAssetsChanged += ActiveAssetsChanged; + + RenderPreviewCommand = new AnonymousCommand(session.ServiceProvider, SetIsVisible); } + public CommandBase RenderPreviewCommand { get; } + public object PreviewObject { get { return previewObject; } private set { SetValue(ref previewObject, value); } } private IAssetPreviewService PreviewService @@ -97,5 +102,13 @@ private void SelectedAssetsCollectionChanged(object sender, NotifyCollectionChan previewService.SetAssetToPreview(null); } } + + private void SetIsVisible(bool isVisible) + { + if (isVisible) + PreviewService.OnShowPreview(); + else + PreviewService.OnHidePreview(); + } } } From d5fd4bda4be409fd6da00cbd177b07e196a51c59 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 26 Feb 2020 12:48:23 -0500 Subject: [PATCH 0804/2038] Lighting: add synchronization to point shadow mapping to remove flicker with multiple shadows --- .../LightPointShadowMapRendererCubeMap.cs | 67 ++++++++++--------- .../LightPointShadowMapRendererParaboloid.cs | 63 +++++++++-------- 2 files changed, 70 insertions(+), 60 deletions(-) diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererCubeMap.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererCubeMap.cs index d9df4e0af0..59f1e5e33b 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererCubeMap.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererCubeMap.cs @@ -243,54 +243,59 @@ public override ShaderClassSource CreateShaderSource(int lightCurrentCount) return new ShaderClassSource(ShaderName, lightCurrentCount); } + private object locker = new object(); + public override void ApplyDrawParameters(RenderDrawContext context, ParameterCollection parameters, FastListStruct currentLights, ref BoundingBoxExt boundingBox) { var boundingBox2 = (BoundingBox)boundingBox; bool shadowMapCreated = false; int lightIndex = 0; - for (int i = 0; i < currentLights.Count; ++i) + lock (locker) { - var lightEntry = currentLights[i]; - if (lightEntry.Light.BoundingBox.Intersects(ref boundingBox2)) + for (int i = 0; i < currentLights.Count; ++i) { - var shaderData = (ShaderData)lightEntry.ShadowMapTexture.ShaderData; - - // Copy per-face data - for (int j = 0; j < 6; j++) + var lightEntry = currentLights[i]; + if (lightEntry.Light.BoundingBox.Intersects(ref boundingBox2)) { - worldToShadow[lightIndex * 6 + j] = shaderData.WorldToShadow[j]; - inverseWorldToShadow[lightIndex * 6 + j] = Matrix.Invert(shaderData.WorldToShadow[j]); - } + var shaderData = (ShaderData)lightEntry.ShadowMapTexture.ShaderData; - depthBiases[lightIndex] = shaderData.DepthBias; - offsetScales[lightIndex] = shaderData.OffsetScale; - depthParameters[lightIndex] = shaderData.DepthParameters; - lightIndex++; + // Copy per-face data + for (int j = 0; j < 6; j++) + { + worldToShadow[lightIndex * 6 + j] = shaderData.WorldToShadow[j]; + inverseWorldToShadow[lightIndex * 6 + j] = Matrix.Invert(shaderData.WorldToShadow[j]); + } - // TODO: should be setup just once at creation time - if (!shadowMapCreated) - { - shadowMapTexture = shaderData.Texture; - if (shadowMapTexture != null) + depthBiases[lightIndex] = shaderData.DepthBias; + offsetScales[lightIndex] = shaderData.OffsetScale; + depthParameters[lightIndex] = shaderData.DepthParameters; + lightIndex++; + + // TODO: should be setup just once at creation time + if (!shadowMapCreated) { - shadowMapTextureSize = new Vector2(shadowMapTexture.Width, shadowMapTexture.Height); - shadowMapTextureTexelSize = 1.0f / shadowMapTextureSize; + shadowMapTexture = shaderData.Texture; + if (shadowMapTexture != null) + { + shadowMapTextureSize = new Vector2(shadowMapTexture.Width, shadowMapTexture.Height); + shadowMapTextureTexelSize = 1.0f / shadowMapTextureSize; + } + shadowMapCreated = true; } - shadowMapCreated = true; } } - } - parameters.Set(shadowMapTextureKey, shadowMapTexture); - parameters.Set(shadowMapTextureSizeKey, shadowMapTextureSize); - parameters.Set(shadowMapTextureTexelSizeKey, shadowMapTextureTexelSize); + parameters.Set(shadowMapTextureKey, shadowMapTexture); + parameters.Set(shadowMapTextureSizeKey, shadowMapTextureSize); + parameters.Set(shadowMapTextureTexelSizeKey, shadowMapTextureTexelSize); - parameters.Set(worldToShadowKey, worldToShadow); - parameters.Set(inverseWorldToShadowKey, inverseWorldToShadow); - parameters.Set(depthParametersKey, depthParameters); - parameters.Set(depthBiasesKey, depthBiases); - parameters.Set(offsetScalesKey, offsetScales); + parameters.Set(worldToShadowKey, worldToShadow); + parameters.Set(inverseWorldToShadowKey, inverseWorldToShadow); + parameters.Set(depthParametersKey, depthParameters); + parameters.Set(depthBiasesKey, depthBiases); + parameters.Set(offsetScalesKey, offsetScales); + } } } } diff --git a/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererParaboloid.cs b/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererParaboloid.cs index 9b76443b4a..edc3b511a3 100644 --- a/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererParaboloid.cs +++ b/sources/engine/Xenko.Rendering/Rendering/Shadows/LightPointShadowMapRendererParaboloid.cs @@ -277,51 +277,56 @@ public override void UpdateLightCount(int lightLastCount, int lightCurrentCount) Array.Resize(ref depthBiases, lightCurrentCount); } + private object locker = new object(); + public override void ApplyDrawParameters(RenderDrawContext context, ParameterCollection parameters, FastListStruct currentLights, ref BoundingBoxExt boundingBox) { var boundingBox2 = (BoundingBox)boundingBox; bool shadowMapCreated = false; int lightIndex = 0; - for (int i = 0; i < currentLights.Count; ++i) + lock (locker) { - var lightEntry = currentLights[i]; - if (lightEntry.Light.BoundingBox.Intersects(ref boundingBox2)) + for (int i = 0; i < currentLights.Count; ++i) { - var shaderData = (ShaderData)lightEntry.ShadowMapTexture.ShaderData; - offsets[lightIndex] = shaderData.Offset; - backfaceOffsets[lightIndex] = shaderData.BackfaceOffset; - faceSizes[lightIndex] = shaderData.FaceSize; - depthParameters[lightIndex] = shaderData.DepthParameters; - depthBiases[lightIndex] = shaderData.DepthBias; - viewMatrices[lightIndex] = shaderData.View; - lightIndex++; - - // TODO: should be setup just once at creation time - if (!shadowMapCreated) + var lightEntry = currentLights[i]; + if (lightEntry.Light.BoundingBox.Intersects(ref boundingBox2)) { - shadowMapTexture = shaderData.Texture; - if (shadowMapTexture != null) + var shaderData = (ShaderData)lightEntry.ShadowMapTexture.ShaderData; + offsets[lightIndex] = shaderData.Offset; + backfaceOffsets[lightIndex] = shaderData.BackfaceOffset; + faceSizes[lightIndex] = shaderData.FaceSize; + depthParameters[lightIndex] = shaderData.DepthParameters; + depthBiases[lightIndex] = shaderData.DepthBias; + viewMatrices[lightIndex] = shaderData.View; + lightIndex++; + + // TODO: should be setup just once at creation time + if (!shadowMapCreated) { - shadowMapTextureSize = new Vector2(shadowMapTexture.Width, shadowMapTexture.Height); - shadowMapTextureTexelSize = 1.0f / shadowMapTextureSize; + shadowMapTexture = shaderData.Texture; + if (shadowMapTexture != null) + { + shadowMapTextureSize = new Vector2(shadowMapTexture.Width, shadowMapTexture.Height); + shadowMapTextureTexelSize = 1.0f / shadowMapTextureSize; + } + shadowMapCreated = true; } - shadowMapCreated = true; } } - } - parameters.Set(shadowMapTextureKey, shadowMapTexture); - parameters.Set(shadowMapTextureSizeKey, shadowMapTextureSize); - parameters.Set(shadowMapTextureTexelSizeKey, shadowMapTextureTexelSize); + parameters.Set(shadowMapTextureKey, shadowMapTexture); + parameters.Set(shadowMapTextureSizeKey, shadowMapTextureSize); + parameters.Set(shadowMapTextureTexelSizeKey, shadowMapTextureTexelSize); - parameters.Set(viewKey, viewMatrices); - parameters.Set(offsetsKey, offsets); - parameters.Set(backfaceOffsetsKey, backfaceOffsets); - parameters.Set(faceSizesKey, faceSizes); - parameters.Set(depthParametersKey, depthParameters); + parameters.Set(viewKey, viewMatrices); + parameters.Set(offsetsKey, offsets); + parameters.Set(backfaceOffsetsKey, backfaceOffsets); + parameters.Set(faceSizesKey, faceSizes); + parameters.Set(depthParametersKey, depthParameters); - parameters.Set(depthBiasesKey, depthBiases); + parameters.Set(depthBiasesKey, depthBiases); + } } } } From f20ad99c10cc82c78e4ac9ea31f4da283c3be033 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 26 Feb 2020 12:52:59 -0500 Subject: [PATCH 0805/2038] Revert "[GameStudio] Throttle game update and skip rendering game scenes, prefabs and preview asset when its sub-windows are hidden (ie. due to being in hidden in tab control)" This reverts commit 30f604517c974c1af491c37bfc75c5a2c9276de6. --- .../Services/EditorGameController.cs | 10 ----- .../Services/IEditorGameController.cs | 10 ----- .../ViewModels/GameEditorViewModel.cs | 14 +----- .../Services/IAssetPreviewService.cs | 4 -- .../EditorGame/Game/EditorServiceGame.cs | 45 +------------------ .../Preview/GameStudioPreviewService.cs | 12 +---- .../Xenko.GameStudio/AssetEditorsManager.cs | 25 ----------- .../Xenko.GameStudio/DockingLayoutManager.cs | 35 --------------- .../Xenko.GameStudio/GameStudioWindow.xaml.cs | 28 ------------ .../Xenko.GameStudio/PreviewViewModel.cs | 15 +------ 10 files changed, 5 insertions(+), 193 deletions(-) diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs index e67583171b..bb110732a9 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/EditorGameController.cs @@ -231,16 +231,6 @@ public async Task StartGame() return true; } - public void OnHideGame() - { - Game.IsEditorHidden = true; - } - - public void OnShowGame() - { - Game.IsEditorHidden = false; - } - public Vector3 GetMousePositionInScene(bool lastRightClick) { EnsureNotDestroyed(); diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs index 771686ea5a..7b8384c907 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/Services/IEditorGameController.cs @@ -45,16 +45,6 @@ public interface IEditorGameController : IDestroyable, IDispatcherService /// True if the scene was successfully created, false otherwise. Task CreateScene(); - /// - /// Stops the game from rendering and throttle game updates. - /// - void OnHideGame(); - - /// - /// Resumes the game rendering and updating and . - /// - void OnShowGame(); - /// /// Finds the game-side instance corresponding to the part with the given id, if it exists. /// diff --git a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs index cef2992aa0..19337b094a 100644 --- a/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs +++ b/sources/editor/Xenko.Assets.Presentation/AssetEditors/GameEditor/ViewModels/GameEditorViewModel.cs @@ -29,7 +29,7 @@ protected GameEditorViewModel([NotNull] AssetViewModel asset, [NotNull] Func @@ -77,16 +77,6 @@ public override void Destroy() base.Destroy(); } - public void HideGame() - { - Controller.OnHideGame(); - } - - public void ShowGame() - { - Controller.OnShowGame(); - } - protected virtual async Task InitializeEditor() { Dispatcher.EnsureAccess(); @@ -122,7 +112,7 @@ private void CopyErrorToClipboard() SafeClipboard.SetText(log); } - private void ResumeFromError() + private void Resume() { Controller.GetService()?.Resume(); } diff --git a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs index 15d5936142..f6dcd20f56 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/Services/IAssetPreviewService.cs @@ -13,9 +13,5 @@ public interface IAssetPreviewService : IDisposable object GetCurrentPreviewView(); event EventHandler PreviewAssetUpdated; - - void OnShowPreview(); - - void OnHidePreview(); } } diff --git a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs index bcf1ba8d70..2606f208c3 100644 --- a/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs +++ b/sources/editor/Xenko.Editor/EditorGame/Game/EditorServiceGame.cs @@ -1,7 +1,6 @@ // Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; -using Xenko.Core; using Xenko.Core.Annotations; using Xenko.Core.BuildEngine; using Xenko.Core.IO; @@ -9,7 +8,6 @@ using Xenko.Editor.Build; using Xenko.Editor.Engine; using Xenko.Games; -using Xenko.Games.Time; using Xenko.Graphics; using Xenko.Rendering.Compositing; @@ -46,36 +44,10 @@ public abstract class EditorServiceGame : EmbeddedGame public static readonly Color EditorBackgroundColorHdr = new Color(61, 61, 61, 255); - private static readonly TimeSpan GameHiddenNextUpdateTime = TimeSpan.FromSeconds(1); - - private readonly TimerTick gameHiddenUpdateTimer = new TimerTick(); - private TimeSpan gameHiddenUpdateTimeElapsed = TimeSpan.Zero; - private bool isEditorHidden = false; - public EditorGameServiceRegistry EditorServices { get; private set; } public IGameSettingsAccessor PackageSettings { get; set; } - /// - /// True if the game is not visible in the editor which will stop rendering and - /// throttle game updates. - /// - /// - /// Used when game is not visible in the editor (eg. hidden inside a tab control). - /// We only throttle updates instead of completely suspending the game because a game exit command is done - /// within the ScriptSystem, so we must be able to run this system. - /// - public bool IsEditorHidden - { - get { return isEditorHidden; } - set - { - gameHiddenUpdateTimer.Reset(); - gameHiddenUpdateTimeElapsed = TimeSpan.Zero; - isEditorHidden = value; - } - } - /// /// True if game is faulted (not running). /// @@ -145,21 +117,6 @@ protected override void Update(GameTime gameTime) if (Faulted) return; - if (IsEditorHidden) - { - gameHiddenUpdateTimer.Tick(); - gameHiddenUpdateTimeElapsed += gameHiddenUpdateTimer.ElapsedTime; - if (gameHiddenUpdateTimeElapsed < GameHiddenNextUpdateTime) - { - return; - } - else - { - System.Diagnostics.Debug.WriteLine($"{Name}.Update - {gameHiddenUpdateTimeElapsed.TotalMilliseconds}"); - gameHiddenUpdateTimeElapsed -= GameHiddenNextUpdateTime; - } - } - try { base.Update(gameTime); @@ -180,7 +137,7 @@ protected override void Update(GameTime gameTime) protected override void Draw(GameTime gameTime) { // Keep going only if last exception has been "resolved" - if (Faulted || IsEditorHidden) + if (Faulted) return; try diff --git a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs index a28cbe453c..4dc9fa0be5 100644 --- a/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs +++ b/sources/editor/Xenko.Editor/Preview/GameStudioPreviewService.cs @@ -195,7 +195,7 @@ public void SetAssetToPreview(AssetViewModel asset) } public AssetCompilerResult Compile(AssetItem asset) - { + { return previewCompiler.Prepare(previewCompileContext, asset); } @@ -319,15 +319,5 @@ public void RegisterAssetPreviewFactories(IReadOnlyDictionary assetPreviewFactories.Add(x.Key, x.Value)); } - - public void OnShowPreview() - { - PreviewGame.IsEditorHidden = false; - } - - public void OnHidePreview() - { - PreviewGame.IsEditorHidden = true; - } } } diff --git a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs index a95bc96aac..de005b51cb 100644 --- a/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs +++ b/sources/editor/Xenko.GameStudio/AssetEditorsManager.cs @@ -313,7 +313,6 @@ internal async Task OpenAssetEditorWindow([NotNull] AssetViewModel asset, bool s AvalonDockHelper.GetDocumentPane(dockingLayoutManager.DockingManager).Children.Add(editorPane); } editorPane.IsActiveChanged += EditorPaneIsActiveChanged; - editorPane.IsSelectedChanged += EditorPaneIsSelectedChanged; editorPane.Closing += EditorPaneClosing; editorPane.Closed += EditorPaneClosed; editorPane.Content = view; @@ -496,7 +495,6 @@ private static void CleanEditorPane([NotNull] LayoutAnchorable editorPane) private void RemoveEditorPane([NotNull] LayoutAnchorable editorPane) { editorPane.IsActiveChanged -= EditorPaneIsActiveChanged; - editorPane.IsSelectedChanged -= EditorPaneIsSelectedChanged; editorPane.Closing -= EditorPaneClosing; editorPane.Closed -= EditorPaneClosed; @@ -569,29 +567,6 @@ private static void EditorPaneIsActiveChanged(object sender, EventArgs e) } } - private static void EditorPaneIsSelectedChanged(object sender, EventArgs e) - { - var editorPane = (LayoutAnchorable)sender; - var element = editorPane.Content as FrameworkElement; - - if (element != null) - { - var assetViewModel = element?.DataContext as AssetViewModel; - if (assetViewModel?.Editor is Assets.Presentation.AssetEditors.GameEditor.ViewModels.GameEditorViewModel gameEditor) - { - // A tab/sub-window is visible via IsSelected, not IsVisible - if (editorPane.IsSelected) - { - gameEditor.ShowGame(); - } - else - { - gameEditor.HideGame(); - } - } - } - } - /// /// Makes the editor pane active and visible. /// diff --git a/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs b/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs index 5f2e2a20dd..4e84b3eacd 100644 --- a/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs +++ b/sources/editor/Xenko.GameStudio/DockingLayoutManager.cs @@ -15,7 +15,6 @@ using Xceed.Wpf.AvalonDock; using Xceed.Wpf.AvalonDock.Layout; using Xceed.Wpf.AvalonDock.Layout.Serialization; -using Microsoft.Xaml.Behaviors; namespace Xenko.GameStudio { @@ -191,31 +190,14 @@ private void ApplyDockingLayout(string text) { // Save the binding expressions of all the current anchorables var bindings = new Dictionary>(); - var contentIdToBehaviors = new Dictionary(); foreach (var anchorable in AvalonDockHelper.GetAllAnchorables(DockingManager).Where(x => !string.IsNullOrEmpty(x.ContentId))) { var titleBindingInfo = BindingInfo.FromBindingExpression(BindingOperations.GetBindingExpression(anchorable, LayoutContent.TitleProperty)); var isVisibleBindingInfo = BindingInfo.FromBindingExpression(BindingOperations.GetBindingExpression(anchorable, AvalonDockHelper.IsVisibleProperty)); bindings.Add(anchorable.ContentId, new List { titleBindingInfo, isVisibleBindingInfo }); - - // Save behaviors, although complex bindings (eg. nested bindings) will not be restored properly... - var behaviorCollection = Interaction.GetBehaviors(anchorable); - if (behaviorCollection.Count > 0) - { - var pendingBehaviours = behaviorCollection.ToArray(); - behaviorCollection.Clear(); - contentIdToBehaviors.Add(anchorable.ContentId, pendingBehaviours); - } } // Unregister docking manager AvalonDockHelper.UnregisterDockingManager(DockingManager); - // This is a bit of a hack, but we need to do this with AssetPreview due to how bad the LayoutAnchorable is on determining - // if it's actually visible or not. - var assetPreviewAnchorable = AvalonDockHelper.GetAllAnchorables(DockingManager).FirstOrDefault(x => string.Equals(x.ContentId, "AssetPreview")); - if (assetPreviewAnchorable != null) - { - gameStudioWindow.UnregisterAssetPreview(assetPreviewAnchorable); - } // Deserialize the string using (var stream = new MemoryStream()) { @@ -237,26 +219,9 @@ private void ApplyDockingLayout(string text) BindingOperations.SetBinding(anchorable, bindingInfo.Property, bindingInfo.Binding); } } - - if (contentIdToBehaviors.TryGetValue(anchorable.ContentId, out var pendingBehaviours)) - { - // Restore behaviors - var behaviorCollection = Interaction.GetBehaviors(anchorable); - foreach (var b in pendingBehaviours) - { - b.Attach(anchorable); - behaviorCollection.Add(b); - } - } } // Re-register docking manager with new layout AvalonDockHelper.RegisterDockingManager(session.ServiceProvider, DockingManager); - // Hack: need to get AssetPreview and register handlers again - assetPreviewAnchorable = AvalonDockHelper.GetAllAnchorables(DockingManager).FirstOrDefault(x => string.Equals(x.ContentId, "AssetPreview")); - if (assetPreviewAnchorable != null) - { - gameStudioWindow.RegisterAssetPreview(assetPreviewAnchorable); - } } private string GetDockingLayout() diff --git a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs index 8893764150..700daddbc7 100644 --- a/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs +++ b/sources/editor/Xenko.GameStudio/GameStudioWindow.xaml.cs @@ -24,7 +24,6 @@ using Xenko.Core.Presentation.Interop; using Xenko.Core.Presentation.Windows; using Xenko.Core.Translation; -using Xceed.Wpf.AvalonDock.Layout; #if DEBUG using Xenko.Assets.Presentation.Test; #endif @@ -181,33 +180,6 @@ protected override void OnClosing(CancelEventArgs e) SaveAndClose().Forget(); } - internal void RegisterAssetPreview(LayoutAnchorable assetPreviewAnchorable) - { - // We listen to the events here instead of via xaml because DockingLayoutManager essentially breaks - // the entire docking control and OnEventCommandBehavior.CommandParameter binding would not - // get restored properly, due to not being able to rebind to a control. - assetPreviewAnchorable.IsSelectedChanged += OnAssetPreviewAnchorable_IsSelectedChanged; - UpdateAssetPreviewAnchorable(assetPreviewAnchorable); - } - - internal void UnregisterAssetPreview(LayoutAnchorable assetPreviewAnchorable) - { - assetPreviewAnchorable.IsSelectedChanged -= OnAssetPreviewAnchorable_IsSelectedChanged; - } - - private void OnAssetPreviewAnchorable_IsSelectedChanged(object sender, EventArgs e) - { - if (sender is LayoutAnchorable anchorable) - { - UpdateAssetPreviewAnchorable(anchorable); - } - } - - private void UpdateAssetPreviewAnchorable(LayoutAnchorable anchorable) - { - (Editor as GameStudioViewModel)?.Preview?.RenderPreviewCommand?.Execute(anchorable.IsSelected); - } - private void InitializeWindowSize() { var previousWorkAreaWidth = GameStudioInternalSettings.WorkAreaWidth.GetValue(); diff --git a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs index 3044b1d5a1..26734e384d 100644 --- a/sources/editor/Xenko.GameStudio/PreviewViewModel.cs +++ b/sources/editor/Xenko.GameStudio/PreviewViewModel.cs @@ -7,7 +7,6 @@ using Xenko.Core.Assets.Editor.Services; using Xenko.Core.Assets.Editor.ViewModel; using Xenko.Core.Extensions; -using Xenko.Core.Presentation.Commands; using Xenko.Core.Presentation.ViewModel; namespace Xenko.GameStudio @@ -18,19 +17,15 @@ public class PreviewViewModel : DispatcherViewModel, IDisposable private IAssetPreviewService previewService; private object previewObject; - + public PreviewViewModel(SessionViewModel session) : base(session.SafeArgument(nameof(session)).ServiceProvider) { this.session = session; session.ActiveAssetView.SelectedAssets.CollectionChanged += SelectedAssetsCollectionChanged; session.ActiveAssetsChanged += ActiveAssetsChanged; - - RenderPreviewCommand = new AnonymousCommand(session.ServiceProvider, SetIsVisible); } - public CommandBase RenderPreviewCommand { get; } - public object PreviewObject { get { return previewObject; } private set { SetValue(ref previewObject, value); } } private IAssetPreviewService PreviewService @@ -102,13 +97,5 @@ private void SelectedAssetsCollectionChanged(object sender, NotifyCollectionChan previewService.SetAssetToPreview(null); } } - - private void SetIsVisible(bool isVisible) - { - if (isVisible) - PreviewService.OnShowPreview(); - else - PreviewService.OnHidePreview(); - } } } From 9ec3ffeb4a36d6be3f4976c74dc101ce0a81a661 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Fri, 28 Feb 2020 13:54:42 -0500 Subject: [PATCH 0806/2038] GameStudio: fix closing bug when opening a new project --- .../Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs index 043a238d5d..434c780d58 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs +++ b/sources/editor/Xenko.Core.Assets.Editor/ViewModel/SessionViewModel.cs @@ -335,6 +335,9 @@ public static async Task CreateNewSession(EditorViewModel edit // And initialize the actions view model sessionViewModel.ActionHistory.Initialize(); + + // grab path for backup/restore + EditorViewModel.Instance.projectPath = Path.GetDirectoryName(session.SolutionPath.FullPath); } finally { @@ -347,6 +350,7 @@ public static async Task CreateNewSession(EditorViewModel edit private static void BackupProjectFiles() { var path = EditorViewModel.Instance.projectPath; + if (path == null || path.Length == 0) return; string[] files = Directory.GetFiles(path, "*.xk*", SearchOption.AllDirectories); for (int i=0; i Date: Fri, 28 Feb 2020 13:54:52 -0500 Subject: [PATCH 0807/2038] Version bump to 3.5.7 --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index a54dbb4b2e..4880fba9a7 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.6"; + public const string VersionToShowInEditor = "3.5.7"; /// /// The current assembly version as text, currently same as . From 26d38de80397cb5a4f7d1e084d973ecc76bb9361 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Sun, 1 Mar 2020 13:42:44 -0500 Subject: [PATCH 0808/2038] GameSettings: cap fullscreen resolution to specific display being used --- sources/engine/Xenko.Engine/Engine/Game.cs | 11 +++++++---- sources/engine/Xenko.Games/GameBase.cs | 2 +- sources/engine/Xenko.Games/SDL/GameWindowSDL.cs | 5 +++++ 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/sources/engine/Xenko.Engine/Engine/Game.cs b/sources/engine/Xenko.Engine/Engine/Game.cs index fb28ab0466..bf6c30c83f 100644 --- a/sources/engine/Xenko.Engine/Engine/Game.cs +++ b/sources/engine/Xenko.Engine/Engine/Game.cs @@ -18,6 +18,7 @@ using Xenko.Games; using Xenko.Graphics; using Xenko.Graphics.Font; +using Xenko.Graphics.SDL; using Xenko.Input; using Xenko.Profiling; using Xenko.Rendering; @@ -237,7 +238,7 @@ public void OverrideDefaultSettings(int width, int height, bool fullscreen) { /// /// Gets default settings that will be used on game startup, if AutoLoadDefaultSettings is true. Caps resolution to native display resolution. /// - public void GetDefaultSettings(out int width, out int height, out bool fullscreen, out float fov) { + public void GetDefaultSettings(out int width, out int height, out bool fullscreen, out float fov, Window useSDLWindow = null) { string defaultFile = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "/DefaultResolution.txt"; // default settings are maximum native resolution bool gotCustomWH = false; @@ -264,8 +265,10 @@ public void GetDefaultSettings(out int width, out int height, out bool fullscree } try { - // cap values to native resolution - Graphics.SDL.Window.GetDisplayInformation(out int native_width, out int native_height, out int refresh_rate); + // cap values to native resolution (try to use display window) + int native_width, native_height, refresh_rate, index = 0; + if (useSDLWindow is Window gwsdl) index = gwsdl.GetWindowDisplay(); + Graphics.SDL.Window.GetDisplayInformation(out native_width, out native_height, out refresh_rate, index); if (width >= native_width && height >= native_height) { @@ -398,7 +401,7 @@ protected override void PrepareContext() deviceManager.PreferredGraphicsProfile = new[] { renderingSettings.DefaultGraphicsProfile }; } - GetDefaultSettings(out renderingSettings.DefaultBackBufferWidth, out renderingSettings.DefaultBackBufferHeight, out bool fullScreen, out float fov); + GetDefaultSettings(out renderingSettings.DefaultBackBufferWidth, out renderingSettings.DefaultBackBufferHeight, out bool fullScreen, out float fov, (Context as GameContextSDL)?.Control ?? null); deviceManager.IsFullScreen = fullScreen; if (renderingSettings.DefaultBackBufferWidth > 0) deviceManager.PreferredBackBufferWidth = renderingSettings.DefaultBackBufferWidth; diff --git a/sources/engine/Xenko.Games/GameBase.cs b/sources/engine/Xenko.Games/GameBase.cs index 84d1d9ceb8..54f8c0d30e 100644 --- a/sources/engine/Xenko.Games/GameBase.cs +++ b/sources/engine/Xenko.Games/GameBase.cs @@ -467,7 +467,7 @@ public void Run(GameContext gameContext = null) } // Gets the GameWindow Context - Context = gameContext ?? GameContextFactory.NewDefaultGameContext(); + Context = gameContext ?? GameContextFactory.NewGameContext(AppContextType.Desktop); PrepareContext(); diff --git a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs index 730434fd26..3f4d605773 100644 --- a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs +++ b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs @@ -348,6 +348,11 @@ public override bool Focused } } + public int GetWindowIndex() + { + return window?.GetWindowDisplay() ?? 0; + } + protected override void Destroy() { if (window != null) From 468ed3c66edc64351d67f9d98dd0eaeeb9cac76e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Mar 2020 11:48:56 -0500 Subject: [PATCH 0809/2038] SDL: Upgrade Windows to 2.0.10 --- deps/SDL2/Windows/x64/SDL2.dll | 4 ++-- deps/SDL2/Windows/x86/SDL2.dll | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/deps/SDL2/Windows/x64/SDL2.dll b/deps/SDL2/Windows/x64/SDL2.dll index 0dcbc0089a..125b00b6d2 100644 --- a/deps/SDL2/Windows/x64/SDL2.dll +++ b/deps/SDL2/Windows/x64/SDL2.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b5b603fd71086b15a81fb294297f634d242519828ba0f20d027d8a2a4d8c4f70 -size 1331712 +oid sha256:5d66bd7c48a61ff952475ec3492fcad67a81e626d849f00824d2b6442adf8d2f +size 1401344 diff --git a/deps/SDL2/Windows/x86/SDL2.dll b/deps/SDL2/Windows/x86/SDL2.dll index 4dda4959e4..0470e42a09 100644 --- a/deps/SDL2/Windows/x86/SDL2.dll +++ b/deps/SDL2/Windows/x86/SDL2.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:6510202682a42c85928267e17746d88e972b062c99a4e01b750483954c59ddc8 -size 1088000 +oid sha256:ffbf5aa7d13fed5d12ba68ba3af930a15aa5d0ff97cfb50a5965a498a941a6dd +size 1156096 From 2248ca7d5917398ae2f429fc82bcd6bfea003ec5 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Mar 2020 11:49:21 -0500 Subject: [PATCH 0810/2038] Vulkan: get rid of code that doesn't work (and generally doesn't run) --- .../Vulkan/SwapChainGraphicsPresenter.Vulkan.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs index 16e3371a29..7e6e6fe06d 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs @@ -108,16 +108,6 @@ public override unsafe void Present() // Get next image Result r = GraphicsDevice.NativeDevice.AcquireNextImageWithResult(swapChain, ulong.MaxValue, SharpVulkan.Semaphore.Null, presentFence, out currentBufferIndex); - if (r == Result.ErrorOutOfDate) { - // re-create and do a "lite" re-present - // unfortunately this will likely crash, since recreating swapchains isn't stable - CreateSwapChain(); - while (toPresent.IsEmpty == false) toPresent.TryDequeue(out _); - toPresent.Enqueue(currentBufferIndex); - presentWaiter.Set(); - return; - } - // reset dummy fence fixed (Fence* fences = &presentFence) { From 1ba788d13e2f54426aa7bea8c99617058838d34e Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Mar 2020 12:29:22 -0500 Subject: [PATCH 0811/2038] SDL: Center window & use "desktop fullscreen" mode if requesting native fullscreen size --- .../engine/Xenko.Games/SDL/GameWindowSDL.cs | 1 + sources/engine/Xenko.Graphics/SDL/Window.cs | 38 ++++++++++++------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs index 3f4d605773..4b6af932fa 100644 --- a/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs +++ b/sources/engine/Xenko.Games/SDL/GameWindowSDL.cs @@ -44,6 +44,7 @@ public override WindowHandle NativeWindow public override void BeginScreenDeviceChange(bool willBeFullScreen) { IsFullscreen = willBeFullScreen; + if (!willBeFullScreen) window?.RecenterWindow(); } public override void EndScreenDeviceChange(int clientWidth, int clientHeight) diff --git a/sources/engine/Xenko.Graphics/SDL/Window.cs b/sources/engine/Xenko.Graphics/SDL/Window.cs index 72e7ed2af3..eec11c26d6 100644 --- a/sources/engine/Xenko.Graphics/SDL/Window.cs +++ b/sources/engine/Xenko.Graphics/SDL/Window.cs @@ -47,7 +47,7 @@ static Window() /// Get the current display information of the display (defaults to 0, the first display). /// public static void GetDisplayInformation(out int width, out int height, out int refresh_rate, int display = 0) { - SDL.SDL_GetCurrentDisplayMode(display, out SDL.SDL_DisplayMode mode); + SDL.SDL_GetDesktopDisplayMode(display, out SDL.SDL_DisplayMode mode); width = mode.w; height = mode.h; refresh_rate = mode.refresh_rate; @@ -224,6 +224,11 @@ public void Show() SDL.SDL_ShowWindow(SdlHandle); } + public static int GetNumberOfDisplays() + { + return SDL.SDL_GetNumVideoDisplays(); + } + /// /// Are we showing the window in full screen mode? /// @@ -231,28 +236,35 @@ public bool IsFullScreen { get { - return (SDL.SDL_GetWindowFlags(SdlHandle) & (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN) != 0; + uint flags = SDL.SDL_GetWindowFlags(SdlHandle); + return (flags & (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN) != 0 || + (flags & (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP) != 0; + } set { if (IsFullScreen == value) return; - SDL.SDL_SetWindowFullscreen(SdlHandle, (uint)(value ? SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN : 0)); - SDL.SDL_GetCurrentDisplayMode(SDL.SDL_GetWindowDisplayIndex(SdlHandle), out SDL.SDL_DisplayMode mode); + int displayIndex = SDL.SDL_GetWindowDisplayIndex(SdlHandle); + SDL.SDL_GetCurrentDisplayMode(displayIndex, out SDL.SDL_DisplayMode mode); if (value) { - oldSize = ClientSize; - oldLocation = Location; + SDL.SDL_GetDesktopDisplayMode(displayIndex, out SDL.SDL_DisplayMode nativemode); + SDL.SDL_SetWindowFullscreen(SdlHandle, nativemode.w <= ClientSize.Width && nativemode.h <= ClientSize.Height ? (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP : (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN); Location = Point.Zero; - if( oldSize.Value.Width != mode.w || - oldSize.Value.Height != mode.h ) ClientSize = new Size2(mode.w, mode.h); - } else { - if( oldLocation.HasValue == false || oldLocation.Value == Point.Zero ) { - Location = new Point((int)((mode.w - 1280) * 0.5f), (int)((mode.h - 720) * 0.5)); - } else Location = oldLocation.Value; - ClientSize = oldSize ?? new Size2(1280, 720); + } + else { + SDL.SDL_SetWindowFullscreen(SdlHandle, 0); + Location = new Point((int)((mode.w - ClientSize.Width) * 0.5f), (int)((mode.h - ClientSize.Height) * 0.5)); } } } + public void RecenterWindow() + { + int displayIndex = SDL.SDL_GetWindowDisplayIndex(SdlHandle); + SDL.SDL_GetDesktopDisplayMode(displayIndex, out SDL.SDL_DisplayMode nativemode); + Location = new Point((int)((nativemode.w - ClientSize.Width) * 0.5f), (int)((nativemode.h - ClientSize.Height) * 0.5)); + } + /// /// Is current window visible? /// From b0df4833cc38bab268bd6f58fe2f098c2fb039ca Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Mar 2020 16:21:33 -0500 Subject: [PATCH 0812/2038] Cross-platform support: fix context creation on Mac/Linux --- sources/engine/Xenko.Games/GameBase.cs | 2 +- sources/engine/Xenko.Games/GameContextFactory.cs | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/sources/engine/Xenko.Games/GameBase.cs b/sources/engine/Xenko.Games/GameBase.cs index 54f8c0d30e..84d1d9ceb8 100644 --- a/sources/engine/Xenko.Games/GameBase.cs +++ b/sources/engine/Xenko.Games/GameBase.cs @@ -467,7 +467,7 @@ public void Run(GameContext gameContext = null) } // Gets the GameWindow Context - Context = gameContext ?? GameContextFactory.NewGameContext(AppContextType.Desktop); + Context = gameContext ?? GameContextFactory.NewDefaultGameContext(); PrepareContext(); diff --git a/sources/engine/Xenko.Games/GameContextFactory.cs b/sources/engine/Xenko.Games/GameContextFactory.cs index bee20aa583..cf649f4cf1 100644 --- a/sources/engine/Xenko.Games/GameContextFactory.cs +++ b/sources/engine/Xenko.Games/GameContextFactory.cs @@ -10,7 +10,6 @@ namespace Xenko.Games /// public static class GameContextFactory { - [Obsolete("Use NewGameContext with the proper AppContextType.")] internal static GameContext NewDefaultGameContext() { // Default context is Desktop From 82471ac4e74a8accb475a04f5813eef2b18a44c0 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Mar 2020 19:42:36 -0500 Subject: [PATCH 0813/2038] SDL: Update SDL C# wrapper --- deps/SDL2-CS/SDL2-CS.dll | 4 ++-- deps/SDL2-CS/build.bat | 22 ------------------- deps/SDL2-CS/checkout.bat | 9 -------- .../SwapChainGraphicsPresenter.Vulkan.cs | 4 ++-- 4 files changed, 4 insertions(+), 35 deletions(-) delete mode 100644 deps/SDL2-CS/build.bat delete mode 100644 deps/SDL2-CS/checkout.bat diff --git a/deps/SDL2-CS/SDL2-CS.dll b/deps/SDL2-CS/SDL2-CS.dll index 99ff3f59d3..2458dd37bf 100644 --- a/deps/SDL2-CS/SDL2-CS.dll +++ b/deps/SDL2-CS/SDL2-CS.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:28a91a09a61a79521fc4d913e610f24dd4c31ea85189ea9798ae6095b7b389fd -size 104448 +oid sha256:f58bcc497431bfd46e9ae583d5c17dfb70675fac61092d3dc1e493eecae946d6 +size 110592 diff --git a/deps/SDL2-CS/build.bat b/deps/SDL2-CS/build.bat deleted file mode 100644 index 6c0744559c..0000000000 --- a/deps/SDL2-CS/build.bat +++ /dev/null @@ -1,22 +0,0 @@ -@echo off - -if "%1" == "" ( - echo Missing Debug or Release argument - EXIT /B 1 -) - -pushd ..\..\externals\SDL2-CS - -REM SDL2-CS -call "%PROGRAMFILES(X86)%\Microsoft Visual Studio\2017\Community\Common7\Tools\VsMSBuildCmd.bat" -msbuild /p:Configuration="%1" SDL2-CS.Core.csproj /restore -if %ERRORLEVEL% neq 0 ( - echo Error during compilation - popd - EXIT /B %ERRORLEVEL% -) - -popd - -rem Copying assemblies -copy ..\..\externals\SDL2-CS\bin\%1\netstandard2.0\*.* . diff --git a/deps/SDL2-CS/checkout.bat b/deps/SDL2-CS/checkout.bat deleted file mode 100644 index 1720ca0736..0000000000 --- a/deps/SDL2-CS/checkout.bat +++ /dev/null @@ -1,9 +0,0 @@ -@echo OFF -setlocal -set HOME=%USERPROFILE% -CALL ..\find_git.cmd -IF NOT ERRORLEVEL 0 ( - ECHO "Could not find git.exe" - EXIT /B %ERRORLEVEL% -) -%GIT_CMD% clone "https://github.com/flibitijibibo/SDL2-CS.git" ../../externals/SDL2-CS diff --git a/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs b/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs index 7e6e6fe06d..feacdb2927 100644 --- a/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs +++ b/sources/engine/Xenko.Graphics/Vulkan/SwapChainGraphicsPresenter.Vulkan.cs @@ -311,8 +311,8 @@ private unsafe void CreateSurface() // Create surface #if XENKO_UI_SDL var control = Description.DeviceWindowHandle.NativeWindow as SDL.Window; - SDL2.SDL.SDL_Vulkan_CreateSurface(control.SdlHandle, GraphicsDevice.NativeInstance.NativeHandle, out IntPtr surfacePtr); - surface = new Surface(surfacePtr); + SDL2.SDL.SDL_Vulkan_CreateSurface(control.SdlHandle, GraphicsDevice.NativeInstance.NativeHandle, out ulong surfacePtr); + surface = new Surface(new IntPtr((long)surfacePtr)); #elif XENKO_PLATFORM_WINDOWS var controlHandle = Description.DeviceWindowHandle.Handle; if (controlHandle == IntPtr.Zero) From 6bc10f8770bd6f35424e345a5d526c7179de3c4d Mon Sep 17 00:00:00 2001 From: Phr00t Date: Mon, 2 Mar 2020 21:02:57 -0500 Subject: [PATCH 0814/2038] SDL: include Linux binary library --- deps/SDL2/Linux/libSDL2.so | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 deps/SDL2/Linux/libSDL2.so diff --git a/deps/SDL2/Linux/libSDL2.so b/deps/SDL2/Linux/libSDL2.so new file mode 100644 index 0000000000..7cb4856690 --- /dev/null +++ b/deps/SDL2/Linux/libSDL2.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5d5cffbcf1ae2671b14946a08217a3261d629018d67f4263d76df677561fa87 +size 1240712 From 8ac89ed80fa21e44f53b01f67d6a29fc185a787c Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 4 Mar 2020 02:16:57 -0500 Subject: [PATCH 0815/2038] Linux: Update to 2.0.9 SDL library on Linux --- deps/SDL2/Linux/libSDL2.so | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/deps/SDL2/Linux/libSDL2.so b/deps/SDL2/Linux/libSDL2.so index 7cb4856690..966d233b76 100644 --- a/deps/SDL2/Linux/libSDL2.so +++ b/deps/SDL2/Linux/libSDL2.so @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d5d5cffbcf1ae2671b14946a08217a3261d629018d67f4263d76df677561fa87 -size 1240712 +oid sha256:f6dedd799cdbc2189976d37daaa23434d0bca79411ac31278e414e1585f4f901 +size 1317744 From 9b1ada0481e6c8c8542853bf7f5160be70a7f94e Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Tue, 3 Mar 2020 21:57:33 +0100 Subject: [PATCH 0816/2038] [Dispatcher] Pooled delegates were not working if delegate method was static. Also, if used inside a loop, only last instance was released. --- .../Xenko.Core.AssemblyProcessor.Packed2.exe | 4 ++-- .../Xenko.Core.AssemblyProcessor.Packed2.pdb | 4 ++-- .../Xenko.Core.AssemblyProcessor.exe | 4 ++-- .../Xenko.Core.AssemblyProcessor.pdb | 4 ++-- .../DispatcherProcessor.cs | 24 ++++++++++++------- 5 files changed, 24 insertions(+), 16 deletions(-) diff --git a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.exe b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.exe index 42e4a9b3e9..f15a832d79 100644 --- a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.exe +++ b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.exe @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:45d993e6a1438e3edc9c14dea4ca8764fe2687042403f21dddf8c750eed3b4b6 -size 689664 +oid sha256:ae0d82addb30df18d3236770c583bd72e69a5b2fd5355b9314586f054dbc7c68 +size 690176 diff --git a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.pdb b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.pdb index dac4c83569..a6239dfa2c 100644 --- a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.pdb +++ b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.Packed2.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:b31dbb4436dd248bceda14b1e20d873eac5b515eafc42479b97b7134cbade610 -size 300544 +oid sha256:9f8df5c9613d925197995194e6ee4eb91f7bd105950a3b2297d2b4984df1cf98 +size 302592 diff --git a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.exe b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.exe index b23e60b90c..12302ade50 100644 --- a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.exe +++ b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.exe @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0d6c55965297ebfc163cca6cbadd186213ad27749f87a957e1da1498563b70b5 -size 156160 +oid sha256:1ec781e548b880b7820a35d1865f3773a1b790c272881688d8ef639a40380d02 +size 156672 diff --git a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.pdb b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.pdb index f3e796478b..ea8f985763 100644 --- a/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.pdb +++ b/deps/AssemblyProcessor/Xenko.Core.AssemblyProcessor.pdb @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0118ad5e61dc7e26b293910a622d1245382fc7cf2ef8e65ac521b1a050849a1f -size 413184 +oid sha256:7b8ea5c3e1d0dd2e06ff8d895f5349006ce9136b5a8ee9f2b183f79250c01c3c +size 439808 diff --git a/sources/core/Xenko.Core.AssemblyProcessor/DispatcherProcessor.cs b/sources/core/Xenko.Core.AssemblyProcessor/DispatcherProcessor.cs index 3cf2acf62b..61090602fc 100644 --- a/sources/core/Xenko.Core.AssemblyProcessor/DispatcherProcessor.cs +++ b/sources/core/Xenko.Core.AssemblyProcessor/DispatcherProcessor.cs @@ -157,7 +157,7 @@ private bool ProcessDelegateAllocation(AssemblyProcessorContext context, MethodD // The previous instruction pushes the target onto the stack // If it's the this-parameter, we can create an instance field, and reuse the same delegate var loadClosureInstruction = functionPointerInstruction.Previous; - if (loadClosureInstruction.OpCode == OpCodes.Ldarg_0 && !method.IsStatic) + if ((loadClosureInstruction.OpCode == OpCodes.Ldarg_0 || loadClosureInstruction.OpCode == OpCodes.Ldnull) && !method.IsStatic) { // TODO: Handle generic methods/delegates // TODO: Handle multiple constructors propertly @@ -173,7 +173,7 @@ private bool ProcessDelegateAllocation(AssemblyProcessorContext context, MethodD // Create and store the delegate in constructor var ilProcessor5 = constructor.Body.GetILProcessor(); ilProcessor5.InsertBefore(retInstruction3, ilProcessor5.Create(OpCodes.Ldarg_0)); - ilProcessor5.InsertBefore(retInstruction3, ilProcessor5.Create(OpCodes.Ldarg_0)); + ilProcessor5.InsertBefore(retInstruction3, ilProcessor5.Create(loadClosureInstruction.OpCode)); ilProcessor5.InsertBefore(retInstruction3, ilProcessor5.Create(OpCodes.Ldftn, delegateMethod)); ilProcessor5.InsertBefore(retInstruction3, ilProcessor5.Create(OpCodes.Newobj, delegateInstanceConstructor)); ilProcessor5.InsertBefore(retInstruction3, ilProcessor5.Create(OpCodes.Stfld, sharedDelegateField)); @@ -181,6 +181,7 @@ private bool ProcessDelegateAllocation(AssemblyProcessorContext context, MethodD // Load from field instead of allocating var ilProcessor4 = method.Body.GetILProcessor(); ilProcessor4.Remove(functionPointerInstruction); + loadClosureInstruction.OpCode = OpCodes.Ldarg_0; // In case it was a ldnull ilProcessor4.Replace(delegateAllocationInstruction, ilProcessor4.Create(OpCodes.Ldfld, sharedDelegateField)); return true; @@ -241,32 +242,39 @@ private bool ProcessDelegateAllocation(AssemblyProcessorContext context, MethodD var ilProcessor = method.Body.GetILProcessor(); + Func generateClosureVariable = () => closureVarible == null ? ilProcessor.Create(loadClosureInstruction.OpCode) : ilProcessor.Create(loadClosureInstruction.OpCode, closureVarible.Resolve()); + // Retrieve from pool var closureGenericArguments = (closureInstanceType as GenericInstanceType)?.GenericArguments.ToArray() ?? new TypeReference[0]; var closureAllocation = storeClosureInstruction.Previous; if (closureAllocation.OpCode == OpCodes.Newobj) { // Retrieve closure from pool, instead of allocating + ilProcessor.Replace(storeClosureInstruction, ilProcessor.Create(OpCodes.Nop)); + var acquireClosure = ilProcessor.Create(OpCodes.Callvirt, poolAcquireMethod.MakeGeneric(closureInstanceType)); - ilProcessor.InsertAfter(closureAllocation, acquireClosure); - ilProcessor.InsertAfter(closureAllocation, ilProcessor.Create(OpCodes.Ldsfld, closure.PoolField.MakeGeneric(closureGenericArguments))); + var methodPreviousStart = ilProcessor.Body.Instructions.First(); + ilProcessor.InsertBefore(methodPreviousStart, ilProcessor.Create(OpCodes.Nop)); + ilProcessor.InsertBefore(methodPreviousStart, ilProcessor.Create(OpCodes.Ldsfld, closure.PoolField.MakeGeneric(closureGenericArguments))); + ilProcessor.InsertBefore(methodPreviousStart, acquireClosure); + ilProcessor.InsertBefore(methodPreviousStart, storeClosureInstruction); closureAllocation.OpCode = OpCodes.Nop; // Change to Nop instead of removing it, as this instruction might be reference somewhere? closureAllocation.Operand = null; // Add a reference - ilProcessor.InsertAfter(storeClosureInstruction, ilProcessor.Create(OpCodes.Callvirt, closure.AddReferenceMethod.MakeGeneric(closureGenericArguments))); - ilProcessor.InsertAfter(storeClosureInstruction, closureVarible == null ? ilProcessor.Create(loadClosureInstruction.OpCode) : ilProcessor.Create(loadClosureInstruction.OpCode, closureVarible.Resolve())); + ilProcessor.InsertBefore(methodPreviousStart, generateClosureVariable()); + ilProcessor.InsertBefore(methodPreviousStart, ilProcessor.Create(OpCodes.Callvirt, closure.AddReferenceMethod.MakeGeneric(closureGenericArguments))); // TODO: Multiple returns + try/finally // Release reference var retInstructions = method.Body.Instructions.Where(x => x.OpCode == OpCodes.Ret).ToArray(); - Instruction beforeReturn = closureVarible == null ? ilProcessor.Create(loadClosureInstruction.OpCode) : ilProcessor.Create(loadClosureInstruction.OpCode, closureVarible.Resolve()); + Instruction beforeReturn = generateClosureVariable(); Instruction newReturnInstruction = ilProcessor.Create(OpCodes.Ret); ilProcessor.Append(beforeReturn); ilProcessor.Append(ilProcessor.Create(OpCodes.Ldnull)); ilProcessor.Append(ilProcessor.Create(OpCodes.Beq, newReturnInstruction)); - ilProcessor.Append(closureVarible == null ? ilProcessor.Create(loadClosureInstruction.OpCode) : ilProcessor.Create(loadClosureInstruction.OpCode, closureVarible.Resolve())); + ilProcessor.Append(generateClosureVariable()); ilProcessor.Append(ilProcessor.Create(OpCodes.Callvirt, closure.ReleaseMethod.MakeGeneric(closureGenericArguments))); ilProcessor.Append(newReturnInstruction); From 33b8d52130ae0787a292a16df72c20059bd9c945 Mon Sep 17 00:00:00 2001 From: Phr00t Date: Wed, 4 Mar 2020 02:23:38 -0500 Subject: [PATCH 0817/2038] Version bump to 3.5.8 --- sources/shared/SharedAssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/shared/SharedAssemblyInfo.cs b/sources/shared/SharedAssemblyInfo.cs index 4880fba9a7..019ddc2922 100644 --- a/sources/shared/SharedAssemblyInfo.cs +++ b/sources/shared/SharedAssemblyInfo.cs @@ -30,7 +30,7 @@ internal class XenkoVersion /// /// This version will be shown in the editor and actually is the version. Can be changed without triggering weird NuGet behavior. /// - public const string VersionToShowInEditor = "3.5.7"; + public const string VersionToShowInEditor = "3.5.8"; /// /// The current assembly version as text, currently same as . From bf4b6e147a261dae696d1c87c2fbfb8762316710 Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Wed, 4 Mar 2020 16:05:05 +0100 Subject: [PATCH 0818/2038] [T4] Switch to latest version of Mono.TextTemplating, which fixes previous issue with space in username --- .../Xenko.Core.ProjectTemplating.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/tools/Xenko.Core.ProjectTemplating/Xenko.Core.ProjectTemplating.csproj b/sources/tools/Xenko.Core.ProjectTemplating/Xenko.Core.ProjectTemplating.csproj index 5d426e4641..0f24c6077f 100644 --- a/sources/tools/Xenko.Core.ProjectTemplating/Xenko.Core.ProjectTemplating.csproj +++ b/sources/tools/Xenko.Core.ProjectTemplating/Xenko.Core.ProjectTemplating.csproj @@ -6,7 +6,7 @@ $(TargetFrameworkTool) - + From 0c75e3db102fffe28052bb49cadb742b64158ebd Mon Sep 17 00:00:00 2001 From: Virgile Bello Date: Thu, 5 Mar 2020 08:53:24 +0100 Subject: [PATCH 0819/2038] [Build] Bumped Microsoft.SourceLink.GitHub to 1.0.0 --- sources/targets/Xenko.Core.GlobalSettings.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sources/targets/Xenko.Core.GlobalSettings.targets b/sources/targets/Xenko.Core.GlobalSettings.targets index 10fd565e7c..0e4f06a563 100644 --- a/sources/targets/Xenko.Core.GlobalSettings.targets +++ b/sources/targets/Xenko.Core.GlobalSettings.targets @@ -154,7 +154,7 @@ - + diff --git a/sources/editor/Xenko.Core.Assets.Editor/Themes/generic.xaml b/sources/editor/Xenko.Core.Assets.Editor/Themes/generic.xaml index 74b51f0108..91dfe9fd0d 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/Themes/generic.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/Themes/generic.xaml @@ -6,7 +6,7 @@ xmlns:diagnostics="clr-namespace:Xenko.Core.Assets.Diagnostics;assembly=Xenko.Core.Assets"> - + diff --git a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml index e701157a21..e9ef357765 100644 --- a/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml +++ b/sources/editor/Xenko.Core.Assets.Editor/View/CommonResources.xaml @@ -3,15 +3,16 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:xk="http://schemas.xenko.com/xaml/presentation" + xmlns:themes="clr-namespace:Xenko.Core.Presentation.Themes;assembly=Xenko.Core.Presentation" xmlns:view="clr-namespace:Xenko.Core.Assets.Editor.View" xmlns:viewModel="clr-namespace:Xenko.Core.Assets.Editor.ViewModel" xmlns:behaviors="clr-namespace:Xenko.Core.Assets.Editor.View.Behaviors" mc:Ignorable="d"> - + - +