Author SHA1 Message Date
Simon Lübeß aa70d99e31 Fin 2022-02-14 20:36:48 +01:00
Simon Lübeß c8cc2f442a Added ColorHSV 2022-02-14 20:36:07 +01:00
Simon Lübeß 574f54e32b Added Window.SetIcon 2022-02-14 20:35:35 +01:00
Simon Lübeß 58cf92fb57 Renderer2D limit instances per batch 2022-02-14 20:19:19 +01:00
Simon Lübeß f49acf34a1 Added particle system 2022-02-13 23:56:58 +01:00
Simon Lübeß 7f11b982ee Added text and restart 2022-02-13 22:51:55 +01:00
Simon Lübeß d9e34b27a3 Rocket Game 2022-02-13 15:22:45 +01:00
Simon Lübeß e61c53400f Added DeltaTime 2022-02-13 15:22:18 +01:00
118 changed files with 1774 additions and 6332 deletions
+7 -10
View File
@@ -1,9 +1,15 @@
[submodule "GlitchyEngine/vendor/directx"]
path = GlitchyEngine/vendor/directx
url = https://github.com/aharabada/directx-beef.git
[submodule "GlitchyEngine/vendor/DirectXTK"]
path = GlitchyEngine/vendor/DirectXTK
url = https://github.com/aharabada/DirectXTK-beef.git
[submodule "vendor/lodepng-beef"]
path = vendor/lodepng-beef
url = https://github.com/aharabada/lodepng-beef.git
[submodule "GlitchyEngine\\vendor\\freetype"]
path = GlitchyEngine\\vendor\\freetype
url = https://github.com/aharabada/FreeType-beef.git
[submodule "GlitchyEngine/vendor/freetype"]
path = GlitchyEngine/vendor/freetype
url = https://github.com/aharabada/FreeType-beef.git
@@ -15,13 +21,4 @@
url = https://github.com/aharabada/msdfgen-beef.git
[submodule "GlitchyEngine/vendor/imgui"]
path = GlitchyEngine/vendor/imgui
url = https://github.com/aharabada/ImGui_GlitchyEngine.git
[submodule "GlitchyEngineHelper/vendor/xxHash"]
path = GlitchyEngineHelper/vendor/xxHash
url = https://github.com/Cyan4973/xxHash.git
[submodule "GlitchyEngine/vendor/bon"]
path = GlitchyEngine/vendor/bon
url = https://github.com/EinScott/bon.git
[submodule "GlitchyEngineHelper/vendor/DirectXTK"]
path = GlitchyEngineHelper/vendor/DirectXTK
url = https://github.com/microsoft/DirectXTK.git
url = https://github.com/aharabada/ImGui_GlitchyEngine.git
+2 -3
View File
@@ -1,6 +1,5 @@
FileVersion = 1
Projects = {Sandbox = {Path = "Sandbox"}, GlitchyEngine = {Path = "GlitchyEngine"}, GlitchLog = {Path = "GlitchLog"}, DirectX = {Path = "GlitchyEngine/vendor/directx/DirectX"}, LodePng = {Path = "vendor/lodepng-beef/lodepng-beef"}, FreeType = {Path = "GlitchyEngine/vendor/freetype"}, cgltf-beef = {Path = "GlitchyEngine/vendor/gltf/cgltf-beef"}, GlitchyEditor = {Path = "GlitchyEditor"}, msdfgen-beef = {Path = "GlitchyEngine/vendor/msdfgen/msdfgen-beef"}, ImGui = {Path = "GlitchyEngine/vendor/imgui/ImGui"}, ImGuiImplDX11 = {Path = "GlitchyEngine/vendor/imgui/ImGuiImplDX11"}, ImGuiImplWin32 = {Path = "GlitchyEngine/vendor/imgui/ImGuiImplWin32"}, ImGuizmo = {Path = "GlitchyEngine/vendor/imgui/ImGuizmo"}, GlitchyEngineHelper = {Path = "GlitchyEngineHelper"}, bon = {Path = "GlitchyEngine/vendor/bon"}}
WorkspaceFolders = {GlitchyEngine = ["GlitchyEngine", "GlitchLog", "GlitchyEngineHelper"], "GlitchyEngine/Dependencies" = ["cgltf-beef", "DirectX", "FreeType", "ImGui", "ImGuiImplDX11", "ImGuiImplWin32", "ImGuizmo", "LodePng", "msdfgen-beef", "bon"]}
Projects = {Sandbox = {Path = "Sandbox"}, GlitchyEngine = {Path = "GlitchyEngine"}, GlitchLog = {Path = "GlitchLog"}, DirectX = {Path = "GlitchyEngine/vendor/directx/DirectX"}, DirectXTK = {Path = "GlitchyEngine/vendor/DirectXTK/DirectXTK-beef"}, LodePng = {Path = "vendor/lodepng-beef/lodepng-beef"}, FreeType = {Path = "GlitchyEngine/vendor/freetype"}, cgltf-beef = {Path = "GlitchyEngine/vendor/gltf/cgltf-beef"}, GlitchyEditor = {Path = "GlitchyEditor"}, msdfgen-beef = {Path = "GlitchyEngine/vendor/msdfgen/msdfgen-beef"}, ImGui = {Path = "GlitchyEngine/vendor/imgui/ImGui"}, ImGuiImplDX11 = {Path = "GlitchyEngine/vendor/imgui/ImGuiImplDX11"}, ImGuiImplWin32 = {Path = "GlitchyEngine/vendor/imgui/ImGuiImplWin32"}, ImGuizmo = {Path = "GlitchyEngine/vendor/imgui/ImGuizmo"}}
[Workspace]
StartupProject = "GlitchyEditor"
StartupProject = "Sandbox"
Binary file not shown.
@@ -1,62 +0,0 @@
Texture2D Texture : register(t0);
SamplerState Sampler : register(s0);
cbuffer Constants : register(b0)
{
float4x4 ViewProjection;
};
struct VS_Input
{
float2 Position : POSITION;
float2 Texcoord : TEXCOORD0;
float4x4 Transform : TRANSFORM;
float4 Color : COLOR;
float4 UVTransform : TEXCOORD1;
float InnerRadius : TEXCOORD2;
};
struct PS_Input
{
float4 Position : SV_Position;
float2 RawPos : TEXCOORD0;
float2 Texcoord : TEXCOORD1;
float4 Color : COLOR;
float InnerRadius : TEXCOORD2;
};
PS_Input VS(VS_Input input)
{
PS_Input output;
output.Position = mul(ViewProjection, mul(input.Transform, float4(input.Position, 0.0f, 1.0f)));
output.Texcoord = input.UVTransform.xy + input.UVTransform.zw * input.Texcoord;
output.RawPos = input.Position;
output.Color = input.Color;
output.InnerRadius = input.InnerRadius;
return output;
}
float4 PS(PS_Input input) : SV_Target0
{
float2 uv = input.RawPos * 2;
float distance = 1.0f - length(uv);
// Smoothing edges based on derivative (not sure if RawPos is the best value for this)
float f = fwidth(input.RawPos.x) + fwidth(input.RawPos.y);
float amount = smoothstep(0.0f, f, distance);
amount *= smoothstep(input.InnerRadius + f, input.InnerRadius, distance);
// Discard invisible pixels
clip(amount - 0.5f);
float4 color = Texture.Sample(Sampler, input.Texcoord) * input.Color;
color.a *= amount;
return color;
}
#effect[VS=VS, PS=PS]
@@ -1,93 +0,0 @@
Texture2D<float3> Texture : register(t0);
SamplerState Sampler : register(s0);
cbuffer Constants
{
float4x4 ViewProjection;
float2 UnitRange;
float screenPixelRange = 2;
}
struct VS_Input
{
float2 Position : POSITION;
float2 Texcoord : TEXCOORD0;
float4x4 Tranform : TRANSFORM;
float4 Color : COLOR;
float4 UVTransform : TEXCOORD1;
};
struct PS_Input
{
float4 Position : SV_Position;
float2 TexCoord : TEXCOORD0;
float4 Color : COLOR;
};
PS_Input VS(VS_Input input)
{
PS_Input output;
output.Position = mul(ViewProjection, mul(input.Tranform, float4(input.Position, 0.0f, 1.0f)));
output.TexCoord = input.UVTransform.xy + input.UVTransform.zw * input.Texcoord;
output.Color = input.Color;
return output;
}
/*
in vec2 texCoord;
out vec4 color;
uniform sampler2D msdf;
uniform vec4 bgColor;
uniform vec4 fgColor;
float median(float r, float g, float b) {
return max(min(r, g), min(max(r, g), b));
}
void main() {
vec3 msd = texture(msdf, texCoord).rgb;
float sd = median(msd.r, msd.g, msd.b);
float screenPxDistance = screenPxRange()*(sd - 0.5);
float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
color = mix(bgColor, fgColor, opacity);
}
*/
float median(float r, float g, float b)
{
return max(min(r, g), min(max(r, g), b));
}
float ScreenPxRange(float2 texcoord)
{
float2 screenTexSize = 1.0f / fwidth(texcoord);
return max(0.5f * dot(UnitRange, screenTexSize), 1.0f);
}
float4 PS(PS_Input input) : SV_Target0
{
float3 msd = Texture.Sample(Sampler, input.TexCoord);
float sd = median(msd.r, msd.g, msd.b);
float screenPxDistance = ScreenPxRange(input.TexCoord) * (sd - 0.5);
float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
return float4(input.Color.rgb, opacity * input.Color.a);
}
/*
// 2D
float4 PS(PS_Input input) : SV_Target0
{
float3 msd = Texture.Sample(Sampler, input.TexCoord).rgb;
float sd = median(msd.r, msd.g, msd.b);
float screenPxDistance = screenPixelRange*(sd - 0.5);
float opacity = clamp(screenPxDistance + 0.5, 0.0, 1.0);
return float4(input.Color.rgb, opacity * input.Color.a);
}
*/
#effect[VS=VS, PS=PS]
@@ -0,0 +1,37 @@
Texture2D Texture : register(t0);
SamplerState Sampler : register(s0);
struct VS_Input
{
float2 Position : POSITION;
float4x4 Tranform : TRANSFORM;
float4 Color : COLOR;
float4 UVTransform : TEXCOORD;
};
struct PS_Input
{
float4 Position : SV_Position;
float2 TexCoord : TEXCOORD0;
float4 Color : COLOR;
};
PS_Input VS(VS_Input input)
{
PS_Input output;
output.Position = mul(float4(input.Position, 0.0f, 1.0f), input.Tranform);
output.TexCoord = input.UVTransform.xy + input.UVTransform.zw * input.Position;
output.Color = input.Color;
return output;
}
float4 PS(PS_Input input) : SV_Target0
{
float4 color = input.Color * Texture.Sample(Sampler, input.TexCoord);
return color;
}
#effect[VS=VS, PS=PS]
@@ -1,41 +0,0 @@
Texture2D Texture : register(t0);
SamplerState Sampler : register(s0);
cbuffer Constants : register(b0)
{
float4x4 ViewProjection;
};
struct VS_Input
{
float2 Position : POSITION;
float2 Texcoord : TEXCOORD0;
float4x4 Transform : TRANSFORM;
float4 Color : COLOR;
float4 UVTransform : TEXCOORD1;
};
struct PS_Input
{
float4 Position : SV_Position;
float2 Texcoord : TEXCOORD;
float4 Color : COLOR;
};
PS_Input VS(VS_Input input)
{
PS_Input output;
output.Position = mul(ViewProjection, mul(input.Transform, float4(input.Position, 0.0f, 1.0f)));
output.Texcoord = input.UVTransform.xy + input.UVTransform.zw * input.Texcoord;
output.Color = input.Color;
return output;
}
float4 PS(PS_Input input) : SV_Target0
{
return Texture.Sample(Sampler, input.Texcoord) * input.Color;
}
#effect[VS=VS, PS=PS]
@@ -0,0 +1,84 @@
cbuffer SceneConstants
{
float4x4 ViewProjection = float4x4(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
cbuffer ObjectConstants
{
float4x4 Transform;
}
cbuffer Constants
{
float4 BaseColor;
float3 LightDir;
}
cbuffer SkinningMatrices
{
matrix SkinningMatrices[255];
float3x3 InvTransSkinningMatrices[255];
}
struct VS_IN
{
float3 Position : POSITION;
float3 Normal : NORMAL;
uint4 JointIndices : JOINTS_0;
float4 JointWeights : WEIGHTS_0;
};
struct PS_IN
{
float4 Position : SV_POSITION;
float3 Normal : NORMAL;
};
PS_IN VS(VS_IN input)
{
PS_IN output;
// Unanimated position in modelspace
float4 positionRaw = float4(input.Position, 1);
// Calculate animated position in modelspace
float4 position =
mul(SkinningMatrices[input.JointIndices.x], positionRaw) * input.JointWeights.x +
mul(SkinningMatrices[input.JointIndices.y], positionRaw) * input.JointWeights.y +
mul(SkinningMatrices[input.JointIndices.z], positionRaw) * input.JointWeights.z +
mul(SkinningMatrices[input.JointIndices.w], positionRaw) * input.JointWeights.w;
float3 normal =
mul(InvTransSkinningMatrices[input.JointIndices.x], input.Normal) * input.JointWeights.x +
mul(InvTransSkinningMatrices[input.JointIndices.y], input.Normal) * input.JointWeights.y +
mul(InvTransSkinningMatrices[input.JointIndices.z], input.Normal) * input.JointWeights.z +
mul(InvTransSkinningMatrices[input.JointIndices.w], input.Normal) * input.JointWeights.w;
//position = saturate(position - 1000) + positionRaw;
//float4 position = mul(SkinningMatrices[input.JointIndices.x], positionRaw);
float4 worldPosition = mul(Transform, position);
output.Position = mul(ViewProjection, worldPosition);
output.Normal = mul((float3x3)Transform, normal);
return output;
}
float4 PS(PS_IN input) : SV_TARGET
{
input.Normal = normalize(input.Normal);
float shading = dot(LightDir, input.Normal);
//float shading = dot(LightDir, LightDir) + 1;
shading = clamp(shading, 0.0f, 1.0f);
return BaseColor * shading;
}
#effect[VS=VS,PS=PS]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 258 B

@@ -2,118 +2,65 @@ using ImGui;
using GlitchyEngine.World;
using System;
using GlitchyEngine.Math;
using System.Collections;
namespace GlitchyEditor.EditWindows
{
using internal GlitchyEngine.World.TransformComponent;
class ComponentEditWindow : EditorWindow
class ComponentEditWindow
{
public const String s_WindowTitle = "Components";
private EntityHierarchyWindow _entityHierarchyWindow;
private Editor _editor;
private bool _open = true;
private List<(Type, ComponentAttribute attribute)> _componentTypes = new .() ~ delete _;
public this(EntityHierarchyWindow entityHierarchyWindow)
public Editor Editor => _editor;
public bool Open
{
_entityHierarchyWindow = entityHierarchyWindow;
for (let type in Type.Types)
{
if (let componentAttribute = type.GetCustomAttribute<ComponentAttribute>())
{
_componentTypes.Add((type, componentAttribute));
}
}
get => _open;
set => _open = value;
}
protected override void InternalShow()
public this(Editor editor)
{
ImGui.PushStyleVar(.WindowMinSize, ImGui.Vec2(1000, 100));
_editor = editor;
}
public void Show()
{
if(!_open)
return;
if(!ImGui.Begin(s_WindowTitle, &_open, .None))
{
ImGui.PopStyleVar();
ImGui.End();
return;
}
if(_entityHierarchyWindow.SelectedEntities.Count == 1)
if(_editor.SelectedEntities.Count == 1)
{
Entity entity = _entityHierarchyWindow.SelectedEntities.Front;
Entity entity = _editor.SelectedEntities.Front;
ShowComponents(entity);
}
ImGui.PopStyleVar();
ImGui.End();
}
private void ShowComponents(Entity entity)
{
ShowNameComponentEditor(entity);
ShowComponentEditor<TransformComponent>("Transform", entity, => ShowTransformComponentEditor);
ShowComponentEditor<CameraComponent>("Camera", entity, => ShowCameraComponentEditor, => ShowComponentContextMenu<CameraComponent>);
ShowComponentEditor<SpriterRendererComponent>("Sprite Renderer", entity, => ShowSpriteRendererComponentEditor, => ShowComponentContextMenu<SpriterRendererComponent>);
ShowAddComponentButton(entity);
NameComponentEditor.Show(_editor.World, entity);
TransformComponentEditor.Show(_editor.World, entity);
}
}
private static void ShowComponentContextMenu<TComponent>(Entity entity, TComponent* component) where TComponent: struct, new
static class NameComponentEditor
{
public static void Show(EcsWorld world, Entity entity)
{
if (ImGui.Selectable("Remove Component"))
entity.RemoveComponent<TComponent>();
}
char8[128] nameBuffer = default;
private static void ShowComponentEditor<TComponent>(String header, Entity entity, function void(Entity, TComponent*) showComponentEditor, function void(Entity, TComponent*) showComponentContextMenu = null) where TComponent: struct, new
{
if (!entity.HasComponent<TComponent>())
return;
TComponent* component = entity.GetComponent<TComponent>();
ImGui.PushID(header);
bool nodeOpen = ImGui.TreeNodeEx(header.CStr(), .DefaultOpen | .AllowItemOverlap | .Framed | .SpanFullWidth);
if (showComponentContextMenu != null)
{
ImGui.SameLine(ImGui.GetWindowContentRegionMax().x - ImGui.CalcTextSize("...").x - 2 * ImGui.GetStyle().FramePadding.x);
if (ImGui.SmallButton("..."))
{
ImGui.OpenPopup("component_popup");
}
if (ImGui.BeginPopup("component_popup"))
{
showComponentContextMenu(entity, component);
ImGui.EndPopup();
}
}
if (nodeOpen)
{
showComponentEditor(entity, component);
ImGui.TreePop();
}
ImGui.PopID();
}
private static void ShowNameComponentEditor(Entity entity)
{
if (!entity.HasComponent<DebugNameComponent>())
return;
char8[256] nameBuffer = default;
DebugNameComponent* component = entity.GetComponent<DebugNameComponent>();
DebugNameComponent* component = world.GetComponent<DebugNameComponent>(entity);
String name = null;
@@ -123,7 +70,7 @@ namespace GlitchyEditor.EditWindows
}
else
{
name = scope:: $"Entity {entity.Handle.[Friend]Index}";
name = scope:: $"Entity {entity.[Friend]Index}";
}
// Copy name to buffer
@@ -133,166 +80,78 @@ namespace GlitchyEditor.EditWindows
{
if(component == null)
{
component = entity.AddComponent<DebugNameComponent>();
component = world.AssignComponent<DebugNameComponent>(entity);
}
component.DebugName.Clear();
component.DebugName.Append(&nameBuffer);
}
}
}
private static void ShowTransformComponentEditor(Entity entity, TransformComponent* transform)
static class TransformComponentEditor
{
public static void Show(EcsWorld world, Entity entity)
{
float textWidth = ImGui.CalcTextSize("Position".CStr()).x;
textWidth = Math.Max(textWidth, ImGui.CalcTextSize("Rotation".CStr()).x);
textWidth = Math.Max(textWidth, ImGui.CalcTextSize("Scale".CStr()).x);
TransformComponent* component = world.GetComponent<TransformComponent>(entity);
textWidth += ImGui.GetStyle().FramePadding.x * 3.0f;
if(component == null)
return;
Vector3 position = transform.Position;
if (ImGui.EditVector3("Position", ref position, .Zero, 0.1f, textWidth))
transform.Position = position;
Vector3 rotationEuler = MathHelper.ToDegrees(transform.EditorRotationEuler);
if (ImGui.EditVector3("Rotation", ref rotationEuler, .Zero, 0.1f, textWidth))
transform.EditorRotationEuler = MathHelper.ToRadians(rotationEuler);
Vector3 scale = transform.Scale;
if (ImGui.EditVector3("Scale", ref scale, .One, 0.1f, textWidth))
transform.Scale = scale;
}
static String[] strings = new String[]("Orthographic", "Perspective", "Perspective (Infinite)") ~ delete _;
private static void ShowCameraComponentEditor(Entity entity, CameraComponent* cameraComponent)
{
ImGui.Checkbox("Primary", &cameraComponent.Primary);
var camera = ref cameraComponent.Camera;
String typeName = strings[camera.ProjectionType.Underlying];
if (ImGui.BeginCombo("Projection", typeName.CStr()))
if(ImGui.TreeNodeEx("Transform", .DefaultOpen))
{
for (int i = 0; i < 3; i++)
Vector3 position = component.Position;
bool positionChanged = false;
Vector3 rotationEuler = MathHelper.ToDegrees(component.RotationEuler);
bool rotationChanged = false;
Vector3 scale = component.Scale;
bool scaleChanged = false;
void ShowValue(String text, ref float value, ref bool valueChanged, String id)
{
bool isSelected = (typeName == strings[i]);
if (ImGui.Selectable(strings[i], isSelected))
{
camera.ProjectionType = (.)i;
}
if (isSelected)
ImGui.SetItemDefaultFocus();
ImGui.Text(text);
ImGui.SameLine();
ImGui.PushID(id);
valueChanged |= ImGui.DragFloat(String.Empty, &value, 0.1f);
ImGui.PopID();
}
ImGui.EndCombo();
}
if (camera.ProjectionType == .Perspective)
{
float fovY = MathHelper.ToDegrees(camera.PerspectiveFovY);
if (ImGui.DragFloat("Fov Y", &fovY, 0.1f))
camera.PerspectiveFovY = MathHelper.ToRadians(fovY);
float near = camera.PerspectiveNearPlane;
if (ImGui.DragFloat("Near", &near, 0.1f))
camera.PerspectiveNearPlane = near;
float far = camera.PerspectiveFarPlane;
if (ImGui.DragFloat("Far", &far, 0.1f))
camera.PerspectiveFarPlane = far;
}
else if (camera.ProjectionType == .InfinitePerspective)
{
float fovY = MathHelper.ToDegrees(camera.PerspectiveFovY);
if (ImGui.DragFloat("Vertical FOV", &fovY, 0.1f))
camera.PerspectiveFovY = MathHelper.ToRadians(fovY);
float near = camera.PerspectiveNearPlane;
if (ImGui.DragFloat("Near", &near, 0.1f))
camera.PerspectiveNearPlane = near;
}
else if (camera.ProjectionType == .Orthographic)
{
float size = camera.OrthographicHeight;
if (ImGui.DragFloat("Size", &size, 0.1f))
camera.OrthographicHeight = size;
float near = camera.OrthographicNearPlane;
if (ImGui.DragFloat("Near", &near, 0.1f))
camera.OrthographicNearPlane = near;
float far = camera.OrthographicFarPlane;
if (ImGui.DragFloat("Far", &far, 0.1f))
camera.OrthographicFarPlane = far;
}
bool fixedAspectRatio = camera.FixedAspectRatio;
if (ImGui.Checkbox("Fixed Aspect Ratio", &fixedAspectRatio))
camera.FixedAspectRatio = fixedAspectRatio;
if (fixedAspectRatio)
{
float aspect = camera.AspectRatio;
if (ImGui.DragFloat("Aspect Ratio", &aspect, 0.1f))
camera.AspectRatio = aspect;
}
}
private static void ShowSpriteRendererComponentEditor(Entity entity, SpriterRendererComponent* spriteRendererComponent)
{
ImGui.ColorEdit4("Color", ref spriteRendererComponent.Color);
}
private static void ShowAddComponentButton(Entity entity)
{
static char8[128] searchBuffer = .();
static StringView searchFilter = .();
static float buttonWidth = 100;
ImGui.NewLine();
ImGui.Separator();
ImGui.NewLine();
void ShowComponentButton<TComponent>(String name) where TComponent : struct, new
{
float textWidth = ImGui.CalcTextSize(name.CStr()).x;
buttonWidth = Math.Max(buttonWidth, textWidth + ImGui.GetStyle().FramePadding.x * 2);
if (name.Contains(searchFilter, true) && ImGui.Selectable(name))
void ShowTableRow(String name, ref Vector3 value, ref bool valueChanged)
{
if (!entity.HasComponent<TComponent>())
entity.AddComponent<TComponent>();
ImGui.TableNextColumn();
ImGui.Text(name);
ImGui.TableNextColumn();
ShowValue("X: ", ref value.X, ref valueChanged, scope $"{name}X");
ImGui.TableNextColumn();
ShowValue("Y: ", ref value.Y, ref valueChanged, scope $"{name}Y");
ImGui.TableNextColumn();
ShowValue("Z: ", ref value.Z, ref valueChanged, scope $"{name}Z");
ImGui.TableNextRow();
}
ImGui.BeginTable("posRotScaleTable", 4);
ShowTableRow("Position", ref position, ref positionChanged);
ShowTableRow("Rotation", ref rotationEuler, ref rotationChanged);
ShowTableRow("Scale", ref scale, ref scaleChanged);
ImGui.EndTable();
if(positionChanged)
component.Position = position;
if(rotationChanged)
component.RotationEuler = MathHelper.ToRadians(rotationEuler);
if(scaleChanged)
component.Scale = scale;
ImGui.TreePop();
}
float textWidth = ImGui.CalcTextSize("Add Component...").x;
buttonWidth = Math.Max(buttonWidth, textWidth + ImGui.GetStyle().FramePadding.x * 2);
ImGui.PushItemWidth(buttonWidth);
ImGui.NewLine();
ImGui.SameLine(ImGui.GetContentRegionMax().x / 2 - buttonWidth / 2);
if (ImGui.BeginCombo("##add_component_combo", "Add Component...", .NoArrowButton))
{
if (ImGui.InputText("##search_component_name", &searchBuffer, (.)searchBuffer.Count))
{
searchFilter = .(&searchBuffer);
}
ImGui.Separator();
ShowComponentButton<CameraComponent>("Camera");
ShowComponentButton<SpriterRendererComponent>("Sprite Renderer");
ImGui.EndCombo();
}
ImGui.PopItemWidth();
}
}
}
@@ -1,31 +0,0 @@
namespace GlitchyEditor.EditWindows
{
abstract class EditorWindow
{
protected Editor _editor;
protected bool _open = true;
protected bool _hasFocus;
public bool Open
{
get => _open;
set => _open = value;
}
public bool HasFocus
{
get => _hasFocus;
}
public void Show()
{
if(!_open)
return;
InternalShow();
}
protected abstract void InternalShow();
}
}
@@ -10,31 +10,35 @@ namespace GlitchyEditor.EditWindows
using internal GlitchyEditor;
/// A window for viewing and editing the scene hierarchy
class EntityHierarchyWindow : EditorWindow
class EntityHierarchyWindow
{
public const String s_WindowTitle = "Entity Hierarchy";
private Editor _editor;
/// Buffer for the entity search string.
private char8[64] _entitySearchChars;
private Scene _scene;
private bool _open = true;
private List<Entity> _selectedEntities = new .() ~ delete _;
public List<Entity> SelectedEntities => _selectedEntities;
public this(Scene scene)
public Editor Editor => _editor;
public bool Open
{
SetContext(scene);
get => _open;
set => _open = value;
}
public void SetContext(Scene scene)
public this(Editor editor)
{
_scene = scene;
_editor = editor;
}
protected override void InternalShow()
public void Show()
{
if(!_open)
return;
if(!ImGui.Begin(s_WindowTitle, &_open, .MenuBar))
{
ImGui.End();
@@ -43,79 +47,70 @@ namespace GlitchyEditor.EditWindows
ShowEntityHierarchyMenuBar();
if (ImGui.BeginPopupContextWindow(s_WindowTitle))
{
Show_ContextMenu_Create(true, false, false);
ImGui.EndPopup();
}
ShowEntityHierarchy();
if ((ImGui.IsMouseDown(.Left) || ImGui.IsMouseDown(.Right)) && !ImGui.IsAnyItemHovered() && !ImGui.GetIO().KeyCtrl && ImGui.IsWindowHovered(.AllowWhenBlockedByPopup))
_selectedEntities.Clear();
ImGui.End();
}
/// Returns whether or not all selected entities have the same parent.
internal bool AllSelectionsOnSameLevel()
{
EcsEntity? parent = .InvalidEntity;
for(var selectedEntity in _selectedEntities)
{
var transformComponent = selectedEntity.GetComponent<TransformComponent>();
if(parent == .InvalidEntity)
{
parent = transformComponent.Parent;
}
else if(transformComponent.Parent != parent)
{
return false;
}
}
return true;
}
/// Finds all children of the given entity and stores their IDs in the given list.
internal void FindChildren(EcsEntity entity, List<EcsEntity> entities)
{
for(var (child, childTransform) in _scene.[Friend]_ecsWorld.Enumerate<TransformComponent>())
{
if(childTransform.Parent == entity)
{
if(!entities.Contains(child))
entities.Add(child);
FindChildren(child, entities);
}
}
}
/// Deletes all selected entities and their children.
internal void DeleteSelectedEntities()
{
for (var entity in _selectedEntities)
{
_scene.DestroyEntity(entity, true);
}
}
private void ShowEntityHierarchyMenuBar()
{
if(ImGui.BeginMenuBar())
{
Show_ContextMenu_Create(true, true, true);
Show_ContextMenu_Delete();
if(ImGui.MenuItem("Delete", null, false, !_selectedEntities.IsEmpty) ||
(Input.IsKeyPressed(.Delete) && ImGui.IsWindowHovered()))
if(ImGui.BeginMenu("Create"))
{
DeleteSelectedEntities();
if(ImGui.MenuItem("Empty Entity"))
{
_editor.CreateEntityWithTransform();
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity with a transform component.");
if(ImGui.MenuItem("Empty Child", null, false, !_editor.SelectedEntities.IsEmpty))
{
var newEntity = _editor.CreateEntityWithTransform();
var parent = _editor.World.AssignComponent<ParentComponent>(newEntity);
// Last entity in list is the entity that has been selected last.
parent.Entity = _editor.SelectedEntities.Back;
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity that is a child of the currently selected entity.");
if(ImGui.MenuItem("Empty Parent", null, false, !_editor.SelectedEntities.IsEmpty && _editor.AllSelectionsOnSameLevel()))
{
var commonParent = _editor.World.GetComponent<ParentComponent>(_editor.SelectedEntities.Front);
var newEntity = _editor.CreateEntityWithTransform();
if(commonParent != null)
{
// parent of selected entities is parent of the new entity.
// (which is why this doesn't work if the entities don't have the same parent)
var newEntityParent = _editor.World.AssignComponent<ParentComponent>(newEntity);
newEntityParent.Entity = commonParent.Entity;
}
// new entity is parent of all selected entities.
for(var selectedEntity in _editor.SelectedEntities)
{
var selectedEntityParent = _editor.World.AssignComponent<ParentComponent>(selectedEntity);
selectedEntityParent.Entity = newEntity;
}
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity that is the parent of the currently selected entities.");
ImGui.EndMenu();
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity.");
if(ImGui.MenuItem("Delete", null, false, !_editor.SelectedEntities.IsEmpty) || Input.IsKeyPressed(.Delete))
{
_editor.DeleteSelectedEntities();
}
if(ImGui.IsItemHovered())
@@ -129,119 +124,11 @@ namespace GlitchyEditor.EditWindows
}
}
/// Creates a new entity that is a child of the given entity.
private void CreateChild(Entity? entity)
{
var newEntity = _scene.CreateEntity();
var transformCmp = newEntity.GetComponent<TransformComponent>();
// Last entity in list is the entity that has been selected last.
transformCmp.Parent = entity?.Handle ?? .InvalidEntity;
}
/// Creates a new entity that is a parent of the selected entities.
private void CreateParent()
{
if (_selectedEntities.IsEmpty || !AllSelectionsOnSameLevel())
{
Log.EngineLogger.Error("Cannot create parent entity.");
return;
}
var commonParent = _selectedEntities.Front.GetComponent<TransformComponent>();
var newEntity = _scene.CreateEntity();
if(commonParent != null)
{
// parent of selected entities is parent of the new entity.
// (which is why this doesn't work if the entities don't have the same parent)
var newEntityTransform = newEntity.GetComponent<TransformComponent>();
newEntityTransform.Parent = commonParent.Parent;
}
// new entity is parent of all selected entities.
for(var selectedEntity in _selectedEntities)
{
var selectedTransform = selectedEntity.GetComponent<TransformComponent>();
selectedTransform.Parent = newEntity.Handle;
}
}
private void Show_ContextMenu_Create(bool allowEmpty = true, bool allowChild = true, bool allowParent = true)
{
if (ImGui.BeginMenu("Create"))
{
if (allowEmpty)
{
if(ImGui.MenuItem("Empty Entity"))
{
if (_selectedEntities.IsEmpty)
_scene.CreateEntity();
else
{
Entity? parent = _selectedEntities.Back.Parent;
CreateChild(parent);
}
}
if(ImGui.IsItemHovered())
{
ImGui.SetTooltip("Create a new Entity.");
}
}
if (allowChild)
{
if(ImGui.MenuItem("Empty Child", null, false, !_selectedEntities.IsEmpty))
{
CreateChild(_selectedEntities.Back);
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity that is a child of the selected entity.");
}
if (allowParent)
{
if(ImGui.MenuItem("Parent", null, false, !_selectedEntities.IsEmpty && AllSelectionsOnSameLevel()))
{
CreateParent();
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity that is the parent of the selected entities.");
}
ImGui.EndMenu();
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Create a new Entity.");
}
private bool Show_ContextMenu_Delete()
{
bool deleted = false;
if(ImGui.MenuItem("Delete", null, false, !_selectedEntities.IsEmpty))
{
DeleteSelectedEntities();
deleted = true;
}
if(ImGui.IsItemHovered())
ImGui.SetTooltip("Deletes the selected Entities and their children.");
return deleted;
}
private void ImGuiPrintEntityTree(TreeNode<Entity> tree)
{
String name = null;
var nameComponent = tree.Value.GetComponent<DebugNameComponent>();
var nameComponent = _editor.World.GetComponent<DebugNameComponent>(tree.Value);
if(nameComponent != null)
{
@@ -249,37 +136,20 @@ namespace GlitchyEditor.EditWindows
}
else
{
name = scope:: $"Entity {(tree.Value.Handle.[Friend]Index)}";
name = scope:: $"Entity {(tree.Value.[Friend]Index)}";
}
ImGui.TreeNodeFlags flags = .OpenOnArrow | .DefaultOpen | .SpanAvailWidth;
ImGui.TreeNodeFlags flags = .OpenOnArrow;
if(tree.Children.Count == 0)
flags |= .Leaf;
bool inSelectedList = _selectedEntities.Contains(tree.Value);
bool inSelectedList = _editor.SelectedEntities.Contains(tree.Value);
if(inSelectedList)
flags |= .Selected;
bool isOpen = ImGui.TreeNodeEx((void*)(uint)tree.Value.Handle.[Friend]Index, flags, $"{name}");
ImGui.PushID((void*)(uint)tree.Value.Handle.[Friend]Index);
bool deleted = false;
if (ImGui.BeginPopupContextItem("treeNodePopup"))
{
Show_ContextMenu_Create(true, true, true);
deleted = Show_ContextMenu_Delete();
ImGui.EndPopup();
}
ImGui.PopID();
if (deleted)
return;
bool isOpen = ImGui.TreeNodeEx(name, flags);
if(ImGui.BeginDragDropSource())
{
@@ -307,34 +177,33 @@ namespace GlitchyEditor.EditWindows
// make sure the dropped entity is not a parent of the entity we dropped it on.
while(true)
{
var parentTransform = walker.GetComponent<TransformComponent>();
if(parentTransform.Parent == .InvalidEntity)
var walkerParent = _editor.World.GetComponent<ParentComponent>(walker);
if(walkerParent == null)
{
dropLegal = true;
break;
}
else if(parentTransform.Parent == movedEntity.Handle)
else if(walkerParent.Entity == movedEntity)
{
dropLegal = false;
break;
}
walker = .(parentTransform.Parent, _scene);
walker = walkerParent.Entity;
}
if(dropLegal)
{
var movedEntityTransform = movedEntity.GetComponent<TransformComponent>();
movedEntityTransform.Parent = tree.Value.Handle;
var movedEntityParent = _editor.World.AssignComponent<ParentComponent>(movedEntity);
movedEntityParent.Entity = tree.Value;
}
}
ImGui.EndDragDropTarget();
}
bool clicked = ImGui.IsItemClicked(.Left);
bool clickedRight = ImGui.IsItemClicked(.Right);
bool clicked = ImGui.IsItemClicked();
if(isOpen)
{
@@ -346,23 +215,23 @@ namespace GlitchyEditor.EditWindows
ImGui.TreePop();
}
if (clicked || clickedRight)
if(clicked)
{
if (inSelectedList && !clickedRight)
if(inSelectedList)
{
_selectedEntities.Remove(tree.Value);
inSelectedList = false;
_editor.SelectedEntities.Remove(tree.Value);
}
else
{
if (!ImGui.GetIO().KeyCtrl && !clickedRight)
if(!ImGui.GetIO().KeyCtrl)
{
_selectedEntities.Clear();
_editor.SelectedEntities.Clear();
}
_selectedEntities.Add(tree.Value);
inSelectedList = true;
_editor.SelectedEntities.Add(tree.Value);
}
inSelectedList = !inSelectedList;
}
}
@@ -370,39 +239,34 @@ namespace GlitchyEditor.EditWindows
{
StringView searchString = StringView(&_entitySearchChars);
if(searchString.IsWhiteSpace)
if(searchString.Length == 0)
{
// Show entity hierarchy as tree
TreeNode<Entity> root = scope .(Entity(.InvalidEntity, _scene));
TreeNode<Entity> root = scope .(.InvalidEntity);
TreeNode<Entity> InsertIntoTree(Entity entity)
TreeNode<Entity> AddEntity(Entity entity)
{
var transform = entity.GetComponent<TransformComponent>();
var parent = _editor.World.GetComponent<ParentComponent>(entity);
if(transform == null)
if(parent == null)
{
return root.AddChild(entity);
}
else
{
var parentEntity = Entity(transform.Parent, _scene);
var parentNode = root.FindNode(parentEntity);
var parentNode = root.FindNode(parent.Entity);
if(parentNode == null)
parentNode = InsertIntoTree(parentEntity);
parentNode = AddEntity(parent.Entity);
return parentNode.AddChild(entity);
}
}
for(var entityId in _scene.[Friend]_ecsWorld.Enumerate())
for(var entity in _editor.World.Enumerate())
{
Entity entity = .(entityId, _scene);
//if (!entity.HasComponent<EditorComponent>())
InsertIntoTree(entity);
AddEntity(entity);
}
if(ImGui.TreeNodeEx("Scene", .DefaultOpen))
@@ -417,10 +281,11 @@ namespace GlitchyEditor.EditWindows
Entity movedEntity = *(Entity*)payload.Data;
_editor.World.RemoveComponent<ParentComponent>(movedEntity);
// Also mark transform as dirty
var transformComponent = movedEntity.GetComponent<TransformComponent>();
transformComponent.Parent = .InvalidEntity;
//transformComponent?.IsDirty = true;
var transformComponent = _editor.World.GetComponent<TransformComponent>(movedEntity);
transformComponent?.IsDirty = true;
}
ImGui.EndDragDropTarget();
@@ -442,13 +307,11 @@ namespace GlitchyEditor.EditWindows
List<StringView> searchTokens = new:ScopedAlloc! .(searchString.Split(' ', .RemoveEmptyEntries));
worldEnumeration:
for(var entityId in _scene.[Friend]_ecsWorld.Enumerate())
for(var entity in _editor.World.Enumerate())
{
Entity entity = .(entityId, _scene);
String name = null;
var nameComponent = entity.GetComponent<DebugNameComponent>();
var nameComponent = _editor.World.GetComponent<DebugNameComponent>(entity);
if(nameComponent != null)
{
@@ -456,7 +319,7 @@ namespace GlitchyEditor.EditWindows
}
else
{
name = scope:worldEnumeration $"Entity {entityId.[Friend]Index}";
name = scope:worldEnumeration $"Entity {entity.[Friend]Index}";
}
StringView nameView = StringView(name);
@@ -8,16 +8,32 @@ using ImGuizmo;
namespace GlitchyEditor.EditWindows
{
class SceneViewportWindow : EditorWindow
class SceneViewportWindow
{
//public OldCamera _camera;
private Editor _editor;
public Camera _camera;
public const String s_WindowTitle = "Scene";
private bool _open = true;
private RenderTarget2D _renderTarget ~ _?.ReleaseRef();
private bool _hasFocus;
public Event<EventHandler<Vector2>> ViewportSizeChangedEvent ~ _.Dispose();
public bool Open
{
get => _open;
set => _open = value;
}
public bool HasFocus
{
get => _hasFocus;
}
public RenderTarget2D RenderTarget
{
get => _renderTarget;
@@ -38,10 +54,11 @@ namespace GlitchyEditor.EditWindows
private ImGui.Vec2 oldViewportSize;
private bool viewPortChanged;
public Entity CameraEntity { get; set; }
protected override void InternalShow()
public void Show()
{
if(!_open)
return;
ImGui.PushStyleVar(.WindowPadding, ImGui.Vec2(1, 1));
defer ImGui.PopStyleVar();
@@ -66,51 +83,47 @@ namespace GlitchyEditor.EditWindows
ImGui.Image(_renderTarget, viewportSize);
}
DrawImGuizmo(viewportSize);
ImGui.End();
if(oldViewportSize != viewportSize)
{
ViewportSizeChangedEvent.Invoke(this, (Vector2)viewportSize);
viewPortChanged = true;
oldViewportSize = viewportSize;
}
}
private void DrawImGuizmo(ImGui.Vec2 viewportSize)
{
ImGuizmo.SetDrawlist();
var topLeft = ImGui.GetWindowPos();
var cntMin = ImGui.GetWindowContentRegionMin();
topLeft.x += cntMin.x;
topLeft.y += cntMin.y;
ImGuizmo.SetRect(topLeft.x, topLeft.y, viewportSize.x, viewportSize.y);
var cameraTransformCmp = CameraEntity.GetComponent<TransformComponent>();
var view = cameraTransformCmp.WorldTransform.Invert();
var cameraCmp = CameraEntity.GetComponent<CameraComponent>();
var projection = cameraCmp.Camera.Projection;
Matrix mat = .Identity;
ImGuizmo.DrawGrid((.)&view, (.)&projection, (.)&mat, 10);
if(_editor.SelectedEntities.Count > 0)
{
var entity = _editor.SelectedEntities.Front;
ImGuizmo.SetDrawlist();
var entity = _editor.SelectedEntities.Back;
var transformCmp = _editor.World.GetComponent<TransformComponent>(entity);
var transform = transformCmp.LocalTransform;
ImGuizmo.SetRect(topLeft.x, topLeft.y, viewportSize.x, viewportSize.y);
var view = _camera.View;
var projection = _camera.Projection;
var v = ImGui.GetWindowPos();
var cntMin = ImGui.GetWindowContentRegionMin();
v.x += cntMin.x;
v.y += cntMin.y;
ImGuizmo.SetRect(v.x, v.y, viewportSize.x, viewportSize.y);
Color c = .(0,0,0,255);
//ImGuizmo.DrawCubes((.)&view, (.)&projection, (.)&transform, 1);
ImGuizmo.Manipulate((.)&view, (.)&projection, .TRANSLATE, .LOCAL, (.)&transform);
Matrix mat = .Identity;
ImGuizmo.DrawGrid((.)&view, (.)&projection, (.)&mat, 10);
transformCmp.LocalTransform = transform;
//ImGuizmo.ViewManipulate((.)&view, , .TRANSLATE, .LOCAL, (.)&transform);
}
ImGui.End();
if(oldViewportSize != viewportSize)
{
ViewportSizeChangedEvent.Invoke(this, *(Vector2*)&oldViewportSize);
viewPortChanged = true;
oldViewportSize = viewportSize;
}
}
}
+19 -41
View File
@@ -4,54 +4,31 @@ using System;
using System.Collections;
using GlitchyEngine.Collections;
using GlitchyEditor.EditWindows;
using GlitchyEngineHelper;
using System.IO;
using GlitchyEngineHelper.DotNet;
namespace GlitchyEditor
{
class Editor
{
private EcsWorld _ecsWorld;
private Scene _scene;
private EcsWorld _world;
private EntityHierarchyWindow _entityHierarchyWindow ~ delete _;
private ComponentEditWindow _componentEditWindow ~ delete _;
private EntityHierarchyWindow _entityHierarchyWindow = new .(this) ~ delete _;
private ComponentEditWindow _componentEditWindow = new .(this) ~ delete _;
private SceneViewportWindow _sceneViewportWindow = new .(this) ~ delete _;
private List<EcsEntity> _selectedEntities = new .() ~ delete _;
private List<Entity> _selectedEntities = new .() ~ delete _;
public EcsWorld World => _ecsWorld;
public EcsWorld World => _world;
public List<EcsEntity> SelectedEntities => _selectedEntities;
public List<Entity> SelectedEntities => _selectedEntities;
public EntityHierarchyWindow EntityHierarchyWindow => _entityHierarchyWindow;
public ComponentEditWindow ComponentEditWindow => _componentEditWindow;
public SceneViewportWindow SceneViewportWindow => _sceneViewportWindow;
/// Creates a new editor for the given world
public this(Scene scene)
public this(EcsWorld world)
{
String exePath = Environment.GetExecutableFilePath(.. scope String());
String exeDir = Path.GetDirectoryPath(exePath, .. scope String());
String assemblyPath = scope String(exeDir, "/DotNetScriptingHelper.dll");
DotNetContext dotty = new DotNetContext(assemblyPath);
defer delete dotty;
dotty.Init();
dotty.GetFunctionPointerUnmanagedCallersOnly("DotNetScriptingHelper.ScriptableEntity, DotNetScriptingHelper", "CreateInstance", out DotNetScriptComponent.CreateInstanceFn);
dotty.GetFunctionPointerUnmanagedCallersOnly("DotNetScriptingHelper.ScriptableEntity, DotNetScriptingHelper", "UpdateEntity", out DotNetScriptComponent.UpdateInstanceFn);
dotty.GetFunctionPointerUnmanagedCallersOnly("DotNetScriptingHelper.ScriptableEntity, DotNetScriptingHelper", "DestroyEntity", out DotNetScriptComponent.DestroyInstanceFn);
_scene = scene;
_ecsWorld = _scene.[Friend]_ecsWorld;
_entityHierarchyWindow = new EntityHierarchyWindow(_scene);
_componentEditWindow = new ComponentEditWindow(_entityHierarchyWindow);
_world = world;
}
public void Update()
@@ -62,14 +39,14 @@ namespace GlitchyEditor
}
/// Creates a new entity with a transform component.
internal EcsEntity CreateEntityWithTransform()
internal Entity CreateEntityWithTransform()
{
var entity = _ecsWorld.NewEntity();
var entity = _world.NewEntity();
var transformComponent = ref *_ecsWorld.AssignComponent<TransformComponent>(entity);
var transformComponent = ref *_world.AssignComponent<TransformComponent>(entity);
transformComponent = TransformComponent();
var nameComponent = ref *_ecsWorld.AssignComponent<DebugNameComponent>(entity);
var nameComponent = ref *_world.AssignComponent<DebugNameComponent>(entity);
nameComponent.SetName("Entity");
return entity;
@@ -79,11 +56,11 @@ namespace GlitchyEditor
/// Returns whether or not all selected entities have the same parent.
internal bool AllSelectionsOnSameLevel()
{
EcsEntity? parent = .InvalidEntity;
Entity? parent = .InvalidEntity;
for(var selectedEntity in _selectedEntities)
{
var parentComponent = _ecsWorld.GetComponent<ParentComponent>(selectedEntity);
var parentComponent = _world.GetComponent<ParentComponent>(selectedEntity);
if(parent == .InvalidEntity)
{
@@ -99,9 +76,9 @@ namespace GlitchyEditor
}
/// Finds all children of the given entity and stores their IDs in the given list.
internal void FindChildren(EcsEntity entity, List<EcsEntity> entities)
internal void FindChildren(Entity entity, List<Entity> entities)
{
for(var (child, childParent) in _ecsWorld.Enumerate<ParentComponent>())
for(var (child, childParent) in _world.Enumerate<ParentComponent>())
{
if(childParent.Entity == entity)
{
@@ -116,7 +93,7 @@ namespace GlitchyEditor
/// Deletes all selected entities and their children.
internal void DeleteSelectedEntities()
{
List<EcsEntity> entities = scope .();
List<Entity> entities = scope .();
for(var entity in _selectedEntities)
{
@@ -127,10 +104,11 @@ namespace GlitchyEditor
for(var entity in entities)
{
_ecsWorld.RemoveEntity(entity);
_world.RemoveEntity(entity);
}
_selectedEntities.Clear();
}
}
}
@@ -1,63 +0,0 @@
using GlitchyEngine;
using GlitchyEngine.Math;
using GlitchyEngine.World;
namespace GlitchyEditor
{
class EditorCameraController : ScriptableEntity
{
private float _cameraTranslationSpeed = 2.0f;
private float _cameraRotationSpeedX = 0.001f;
private float _cameraRotationSpeedY = 0.001f;
public bool IsEnabled = false;
protected override void OnUpdate(GameTime gt)
{
if (!IsEnabled)
return;
Debug.Profiler.ProfileFunction!();
Vector3 movement = .();
if(Input.IsKeyPressed(Key.W))
movement.Z += 1;
if(Input.IsKeyPressed(Key.S))
movement.Z -= 1;
if(Input.IsKeyPressed(Key.A))
movement.X -= 1;
if(Input.IsKeyPressed(Key.D))
movement.X += 1;
if(Input.IsKeyPressed(Key.Space))
movement.Y += 1;
if(Input.IsKeyPressed(Key.Control))
movement.Y -= 1;
var transformComponent = transform;
if(movement != .Zero)
{
movement.Normalize();
movement *= (float)(gt.FrameTime.TotalSeconds) * _cameraTranslationSpeed;
Matrix view = transformComponent.WorldTransform.Invert();
Vector4 delta = Vector4(movement, 1.0f) * view;
transformComponent.Position = transformComponent.Position + delta.XYZ;
}
// Camera rotation
var mouseDelta = Input.GetMouseMovement();
float rotY = mouseDelta.X * _cameraRotationSpeedX;
float rotX = mouseDelta.Y * _cameraRotationSpeedY;
transformComponent.RotationEuler = transformComponent.RotationEuler + .(rotX, rotY, 0);
}
}
}
+64 -126
View File
@@ -15,94 +15,26 @@ namespace GlitchyEditor
RasterizerState _rasterizerState ~ _?.ReleaseRef();
RasterizerState _rasterizerStateClockWise ~ _?.ReleaseRef();
GraphicsContext _context ~ _.ReleaseRef();
GraphicsContext _context ~ _?.ReleaseRef();
DepthStencilTarget _swapchainDepthBuffer ~ _?.ReleaseRef();
BlendState _alphaBlendState ~ _.ReleaseRef();
BlendState _opaqueBlendState ~ _.ReleaseRef();
DepthStencilState _depthStencilState ~ _.ReleaseRef();
BlendState _alphaBlendState ~ _?.ReleaseRef();
BlendState _opaqueBlendState ~ _?.ReleaseRef();
Scene _scene = new Scene() ~ delete _;
EcsWorld _world = new EcsWorld() ~ delete _;
Editor _editor ~ delete _;
RenderTarget2D _viewportTarget ~ _?.ReleaseRef();
SettingsWindow _settingsWindow = new .() ~ delete _;
Entity _cameraEntity;
Entity _otherCameraEntity;
class CameraController : ScriptableEntity
{
protected override void OnCreate()
{
Log.EngineLogger.Trace("Cam controller created!");
}
protected override void OnUpdate(GameTime gameTime)
{
var transformCmp = GetComponent<TransformComponent>();
Vector3 position = transformCmp.Position;
if (Input.IsKeyPressed(Key.A))
{
position.X -= gameTime.DeltaTime;
}
if (Input.IsKeyPressed(Key.D))
{
position.X += gameTime.DeltaTime;
}
if (Input.IsKeyPressed(Key.W))
{
position.Y += gameTime.DeltaTime;
}
if (Input.IsKeyPressed(Key.S))
{
position.Y -= gameTime.DeltaTime;
}
transformCmp.Position = position;
}
protected override void OnDestroy()
{
Log.EngineLogger.Trace("Cam controller destroyed!");
}
}
PerspectiveCameraController _cameraController ~ delete _;
RenderTarget2D _renderTarget2D ~ _?.ReleaseRef();
public this() : base("Example")
{
Application.Get().Window.IsVSync = false;
InitGraphics();
{
_cameraEntity = _scene.CreateEntity("Camera Entity");
let camera = _cameraEntity.AddComponent<CameraComponent>();
camera.Camera.SetPerspective(MathHelper.ToRadians(75), 0.1f, 10000.0f);
camera.Primary = true;
camera.FixedAspectRatio = false;
let transform = _cameraEntity.GetComponent<TransformComponent>();
transform.Position = .(0, 0, -5);
_cameraEntity.AddComponent<NativeScriptComponent>().Bind<EditorCameraController>();
_cameraEntity.AddComponent<EditorComponent>();
}
{
_otherCameraEntity = _scene.CreateEntity("Other Camera Entity");
let camera = _otherCameraEntity.AddComponent<CameraComponent>();
camera.Camera.SetPerspective(MathHelper.ToRadians(45), 0.1f, 1000.0f);
camera.Primary = false;
camera.FixedAspectRatio = false;
let transform = _otherCameraEntity.GetComponent<TransformComponent>();
transform.Position = .(0, 0, -5);
_otherCameraEntity.AddComponent<NativeScriptComponent>().Bind<EditorCameraController>();
_otherCameraEntity.AddComponent<EditorComponent>();
}
InitEcs();
InitEditor();
}
@@ -110,6 +42,8 @@ namespace GlitchyEditor
{
_context = Application.Get().Window.Context..AddRef();
_swapchainDepthBuffer = new DepthStencilTarget(_context.SwapChain.Width, _context.SwapChain.Height);
RasterizerStateDescription rsDesc = .(.Solid, .Back, true);
_rasterizerState = new RasterizerState(rsDesc);
@@ -121,62 +55,80 @@ namespace GlitchyEditor
_alphaBlendState = new BlendState(blendDesc);
_opaqueBlendState = new BlendState(.Default);
DepthStencilStateDescription dsDesc = .();
_depthStencilState = new DepthStencilState(dsDesc);
_renderTarget2D = new RenderTarget2D(RenderTarget2DDescription(.R8G8B8A8_UNorm, 100, 100) {DepthStencilFormat = .D32_Float});
_viewportTarget = new RenderTarget2D(RenderTarget2DDescription(.R8G8B8A8_UNorm, 100, 100) {DepthStencilFormat = .D32_Float});
_viewportTarget.SamplerState = SamplerStateManager.LinearClamp;
SamplerStateDescription desc = .();
SamplerState sampler = new SamplerState(desc);
_renderTarget2D.SamplerState = sampler;
sampler.ReleaseRef();
}
private void InitEcs()
{
_world.Register<DebugNameComponent>();
_world.Register<TransformComponent>();
_world.Register<ParentComponent>();
_world.Register<MeshComponent>();
_world.Register<MeshRendererComponent>();
_world.Register<SkinnedMeshRendererComponent>();
_world.Register<CameraComponent>();
_world.Register<AnimationComponent>();
}
private void InitEditor()
{
_editor = new Editor(_scene);
_editor = new Editor(_world);
_editor.SceneViewportWindow.ViewportSizeChangedEvent.Add(new (s, e) => ViewportSizeChanged(s, e));
//_editor.[Friend]CreateEntityWithTransform();
_cameraController = new .(Application.Get().Window.Context.SwapChain.BackbufferViewport.Width /
Application.Get().Window.Context.SwapChain.BackbufferViewport.Height);
_cameraController.CameraPosition = .(0, 0, -5);
_cameraController.TranslationSpeed = 10;
_editor.SceneViewportWindow.CameraEntity = _cameraEntity;
_editor.[Friend]CreateEntityWithTransform();
_editor.SceneViewportWindow._camera = _cameraController.Camera;
}
public override void Update(GameTime gameTime)
{
var scriptComponent = _cameraEntity.GetComponent<NativeScriptComponent>();
if(_editor.SceneViewportWindow.HasFocus && Input.IsMouseButtonPressed(.RightButton))
_cameraController.Update(gameTime);
if (var camController = scriptComponent.Instance as EditorCameraController)
{
camController.IsEnabled = (_editor.SceneViewportWindow.HasFocus && Input.IsMouseButtonPressed(.RightButton));
}
TransformSystem.Update(_world);
//TransformSystem.Update(_world);
RenderCommand.Clear(_renderTarget2D, .Color | .Depth, .(0.2f, 0.2f, 0.2f), 1.0f, 0);
RenderCommand.Clear(_viewportTarget, .Color | .Depth, .(0.2f, 0.2f, 0.2f), 1.0f, 0);
_context.SetRenderTarget(_renderTarget2D);
_context.BindRenderTargets();
RenderCommand.SetRenderTarget(_viewportTarget, 0, true);
RenderCommand.BindRenderTargets();
RenderCommand.SetViewport(Viewport(0, 0, _renderTarget2D.Width, _renderTarget2D.Height));
RenderCommand.SetViewport(Viewport(0, 0, _viewportTarget.Width, _viewportTarget.Height));
RenderCommand.SetBlendState(_opaqueBlendState);
RenderCommand.SetBlendState(_alphaBlendState);
RenderCommand.SetDepthStencilState(_depthStencilState);
Renderer.BeginScene(_cameraController.Camera);
//Renderer.BeginScene(_cameraController.Camera);
//DebugRenderer.Render(_scene.[Friend]_ecsWorld);
DebugRenderer.Render(_world);
//Renderer.EndScene();
Renderer.EndScene();
_scene.Update(gameTime);
RenderCommand.Clear(null, .(0.2f, 0.2f, 0.2f));
RenderCommand.Clear(_swapchainDepthBuffer, .Depth, 1.0f, 0);
RenderCommand.Clear(null, .Color | .Depth, .(0.2f, 0.2f, 0.2f), 1.0f, 0);
RenderCommand.SetRenderTarget(null, 0, true);
RenderCommand.BindRenderTargets();
_context.SetRenderTarget(null);
_context.SetDepthStencilTarget(_swapchainDepthBuffer);
_context.BindRenderTargets();
RenderCommand.SetViewport(_context.SwapChain.BackbufferViewport);
}
public override void OnEvent(Event event)
{
_cameraController.OnEvent(event);
EventDispatcher dispatcher = EventDispatcher(event);
dispatcher.Dispatch<ImGuiRenderEvent>(scope (e) => OnImGuiRender(e));
@@ -187,29 +139,15 @@ namespace GlitchyEditor
private bool OnImGuiRender(ImGuiRenderEvent event)
{
ImGui.Begin("Test");
static bool cameraA = true;
if (ImGui.Checkbox("Camera A", &cameraA))
{
_cameraEntity.GetComponent<CameraComponent>().Primary = cameraA;
_otherCameraEntity.GetComponent<CameraComponent>().Primary = !cameraA;
}
ImGui.End();
ImGui.Viewport* viewport = ImGui.GetMainViewport();
ImGui.DockSpaceOverViewport(viewport);
DrawMainMenuBar();
_editor.SceneViewportWindow.RenderTarget = _viewportTarget;
_editor.SceneViewportWindow.RenderTarget = _renderTarget2D;
_editor.Update();
_settingsWindow.Show();
return false;
}
@@ -217,11 +155,8 @@ namespace GlitchyEditor
{
ImGui.BeginMainMenuBar();
if(ImGui.BeginMenu("File", true))
if(ImGui.BeginMenu("File", false))
{
if (ImGui.MenuItem("Settings"))
_settingsWindow.Open = true;
ImGui.EndMenu();
}
@@ -251,6 +186,9 @@ namespace GlitchyEditor
private bool OnWindowResize(WindowResizeEvent e)
{
_swapchainDepthBuffer.ReleaseRef();
_swapchainDepthBuffer = new DepthStencilTarget(_context.SwapChain.Width, _context.SwapChain.Height);
return false;
}
@@ -262,9 +200,9 @@ namespace GlitchyEditor
if(sizeX == 0 || sizeY == 0)
return;
_viewportTarget.Resize(sizeX, sizeY);
_renderTarget2D.Resize(sizeX, sizeY);
_scene.OnViewportResize(sizeX, sizeY);
_cameraController.AspectRatio = (float)sizeX / (float)sizeY;
}
}
}
-253
View File
@@ -1,253 +0,0 @@
using GlitchyEditor.EditWindows;
using ImGui;
using GlitchyEngine;
using System;
using System.Collections;
using System.Reflection;
namespace GlitchyEditor
{
class SettingsWindow : EditorWindow
{
class Binding
{
public Object SettingsObject;
public String Name ~ delete _;
public String FieldName ~ delete _;
public this(StringView name, StringView fieldName, Object settingsObject)
{
Name = new String(name);
FieldName = new String(fieldName);
SettingsObject = settingsObject;
}
}
class Category
{
public List<Binding> _bindings = new .() ~ DeleteContainerAndItems!(_);
public String Header ~ delete _;
public Object SettingsObject;
public this(String header)
{
Header = new String(header);
}
public void AddSetting(StringView name, StringView fieldName, Object settingsObject = null)
{
Binding binding = new .(name, fieldName, settingsObject ?? SettingsObject);
_bindings.Add(binding);
}
}
Settings _settings;
bool _settingsChanged = false;
private Dictionary<String, Category> _categories = new .() ~ DeleteDictionaryAndValues!(_);
public this()
{
_open = false;
_settings = Application.Get().Settings;
Create();
}
void Create()
{
ScanForSettings(_settings);
/*for (ISettings settings in _settings.[Friend]_userSettings)
{
ScanForSettings(settings);
}*/
}
Category AddCategory(String header)
{
if (_categories.TryGetValue(header, let category))
return category;
Category newCat = new Category(header);
_categories.Add(newCat.Header, newCat);
return newCat;
}
void ScanForSettings(Object container)
{
Type type = container.GetType();
for (var field in type.GetFields())
{
Result<SettingAttribute> settingResult = field.GetCustomAttribute<SettingAttribute>();
if (settingResult case .Ok(let settingInfo))
{
AddSetting(settingInfo.Category, settingInfo.Name, field.Name, container);
}
Result<SettingContainerAttribute> containerResult = field.GetCustomAttribute<SettingContainerAttribute>();
if (containerResult case .Ok(let containerInfo))
{
var res = field.GetValue<Object>(container, let childContainer);
if (res case .Err(let error))
{
Log.EngineLogger.Error($"Failed to get settings container. Error: {error}");
continue;
}
ScanForSettings(childContainer);
}
}
}
void AddSetting(String categoryName, String name, StringView fieldName, Object container)
{
Category category = AddCategory(categoryName);
category.AddSetting(name, fieldName, container);
}
protected override void InternalShow()
{
ImGui.Begin("Settings", &_open, .NoDocking);
defer ImGui.End();
// Leave room for 1 line below us
ImGui.BeginChild("item view", ImGui.Vec2(0, -ImGui.GetFrameHeightWithSpacing()));
ImGui.BeginTabBar("##Tabs");
for (Category category in _categories.Values)
{
if (ImGui.BeginTabItem(category.Header))
{
ImGui.Columns(2);
defer ImGui.Columns(1);
ImGui.SetColumnWidth(0, 100);
for (Binding setting in category._bindings)
{
ImGui.TextUnformatted(setting.Name);
ImGui.NextColumn();
Type settingsObjectType = setting.SettingsObject.GetType();
Result<FieldInfo> result = settingsObjectType.GetField(setting.FieldName);
if (result case .Err)
{
ImGui.PushStyleColor(.Text, ImGui.Vec4(1f, 0f, 0f, 1f));
ImGui.Text($"Field {setting.FieldName} not found.");
ImGui.PopStyleColor();
continue;
}
FieldInfo fieldInfo = result.Get();
Type fieldType = fieldInfo.FieldType;
mixin GetSettingValue<T>()
{
var error = fieldInfo.GetValue<T>(setting.SettingsObject, var value);
if (error case .Err(let err))
{
Log.EngineLogger.Error($"Could not get value of setting {setting.FieldName}. Error: {err}");
ImGui.PushStyleColor(.Text, ImGui.Vec4(1f, 0f, 0f, 1f));
ImGui.Text($"Could not get value of setting {setting.FieldName}. Error: {err}");
ImGui.PopStyleColor();
break;
}
value
}
mixin SetSettingValue<T>(T value)
{
var error = fieldInfo.SetValue(setting.SettingsObject, value);
if (error case .Err(let err))
{
Log.EngineLogger.Error($"Could not set value of setting {setting.FieldName}. Error: {err}");
}
}
switch (fieldType)
{
case typeof(int32):
int32 value = GetSettingValue!<int32>();
if (!ImGui.InputInt(scope $"##{setting.Name}", &value))
break;
SetSettingValue!(value);
_settingsChanged = true;
case typeof(String):
String value = GetSettingValue!<String>();
char8[256] buffer = .();
value.CopyTo(buffer);
if (ImGui.InputText(scope $"##{setting.Name}", &buffer, buffer.Count))
{
value..Clear().Append(&buffer);
_settingsChanged = true;
}
}
ImGui.NextColumn();
}
ImGui.EndTabItem();
}
}
ImGui.EndTabBar();
ImGui.EndChild();
ImGui.BeginDisabled(!_settingsChanged);
if (ImGui.Button("Save"))
{
_settings.Save();
_settings.Apply();
_open = false;
}
ImGui.SameLine();
if (ImGui.Button("Apply"))
{
_settings.Apply();
}
ImGui.EndDisabled();
ImGui.SameLine();
if (ImGui.Button("Cancel"))
{
Settings.Load();
_open = false;
}
}
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
FileVersion = 1
Dependencies = {GlitchLog = "*", corlib = "*", DirectX = "*", FreeType = "*", cgltf-beef = "*", msdfgen-beef = "*", ImGui = "*", ImGuiImplDX11 = "*", ImGuiImplWin32 = "*", ImGuizmo = "*", Beefy2D = "*", LodePng = "*", GlitchyEngineHelper = "*", bon = "*"}
Dependencies = {GlitchLog = "*", corlib = "*", DirectX = "*", DirectXTK = "*", FreeType = "*", cgltf-beef = "*", msdfgen-beef = "*", ImGui = "*", ImGuiImplDX11 = "*", ImGuiImplWin32 = "*", ImGuizmo = "*", Beefy2D = "*", LodePng = "*"}
[Project]
Name = "GlitchyEngine"
@@ -15,7 +15,7 @@ PreprocessorMacros = ["DEBUG", "PARANOID", "GE_WINDOWS"]
PreprocessorMacros = ["RELEASE", "GE_WINDOWS"]
[Configs.Release.Win64]
PreprocessorMacros = ["IMGUI", "RELEASE", "GE_PROFILE"]
PreprocessorMacros = ["RELEASE", "GE_PROFILE"]
[Configs.Test.Win32]
PreprocessorMacros = ["TEST", "GE_WINDOWS"]
@@ -24,4 +24,4 @@ PreprocessorMacros = ["TEST", "GE_WINDOWS"]
PreprocessorMacros = ["TEST", "GE_WINDOWS"]
[Configs.Debug.Win64]
PreprocessorMacros = ["DEBUG", "GE_PROFILE", "GE_PROFILE_RENDERER", "GE_PROFILE_RESOURCES", "IMGUI"]
PreprocessorMacros = ["DEBUG", "GE_PROFILE", "GE_PROFILE_RENDERER", "GE_PROFILE_RESOURCES"]
+6 -35
View File
@@ -3,7 +3,6 @@ using GlitchyEngine.Events;
using GlitchyEngine.ImGui;
using GlitchyEngine.Renderer;
using GlitchyEngine.Debug;
using GlitchyEngine.Content;
namespace GlitchyEngine
{
@@ -11,37 +10,29 @@ namespace GlitchyEngine
{
static Application s_Instance = null;
private Window _window;
private RendererAPI _rendererApi;
private EffectLibrary _effectLibrary;
private Window _window ~ delete _;
private RendererAPI _rendererApi ~ delete _;
private EffectLibrary _effectLibrary ~ delete _;
private bool _running = true;
private bool _isMinimized = false;
private LayerStack _layerStack;
private LayerStack _layerStack = new LayerStack();
#if IMGUI
private ImGuiLayer _imGuiLayer;
#endif
private GameTime _gameTime;
private IContentManager _contentManager;
private GameTime _gameTime = new GameTime(true);
public bool IsRunning => _running;
public Window Window => _window;
public EffectLibrary EffectLibrary => _effectLibrary;
public IContentManager ContentManager => _contentManager;
public bool IsMinimized => _isMinimized;
[Inline]
public static Application Get() => s_Instance;
public Settings Settings {get; private set;} = new .() ~ delete _;
public this()
{
Profiler.ProfileFunction!();
@@ -49,17 +40,12 @@ namespace GlitchyEngine
Log.EngineLogger.Assert(s_Instance == null, "Tried to create a second application.");
s_Instance = this;
_layerStack = new LayerStack();
_gameTime = new GameTime(true);
_window = new Window(.Default);
_window.EventCallback = new => OnEvent;
_rendererApi = new RendererAPI();
_rendererApi.Context = _window.Context;
_contentManager = new ContentManager("./content");
SamplerStateManager.Init();
RenderCommand.RendererAPI = _rendererApi;
@@ -68,31 +54,18 @@ namespace GlitchyEngine
Renderer.Init(_window.Context, _effectLibrary);
#if IMGUI
_imGuiLayer = new ImGuiLayer();
PushOverlay(_imGuiLayer);
#endif
GlitchyEngine.Settings.Load();
Settings.Apply();
}
public ~this()
{
Profiler.ProfileFunction!();
delete _layerStack;
SamplerStateManager.Uninit();
Renderer.Deinit();
delete _effectLibrary;
delete _contentManager;
delete _rendererApi;
delete _window;
delete _gameTime;
delete _layerStack;
}
public void OnEvent(Event e)
@@ -158,9 +131,7 @@ namespace GlitchyEngine
if(allowFrame)
{
#if IMGUI
_imGuiLayer.ImGuiRender();
#endif
_window.Context.SwapChain.Present();
}
@@ -1,68 +0,0 @@
using System;
using System.IO;
using xxHash;
namespace GlitchyEngine.Content
{
class ContentId
{
private readonly String _string;
private readonly XXH64_hash _hash;
public String String => _string;
public XXH64_hash Hash => _hash;
[AllowAppend]
public this(StringView id)
{
String str = append String(id);
_string = str;
_hash = xxHash.ComputeHash(id);
}
}
interface IContentManager
{
void GetFilePath(String outFilename, String filename);
Stream GetFile(String filename);
}
class ContentManager : IContentManager
{
private String _contentRoot;
[AllowAppend]
public this(String contentRoot)
{
String cntRoot = append String(contentRoot);
_contentRoot = cntRoot;
Runtime.Assert(Directory.Exists(contentRoot), "Content root directory doesn't exist.");
}
public void GetFilePath(String outFilename, String filename)
{
Path.InternalCombine(outFilename, _contentRoot, filename);
}
public Stream GetFile(String filename)
{
String fullpath = scope .(_contentRoot.Length + 1 + filename.Length);
GetFilePath(fullpath, filename);
FileStream stream = new FileStream();
var result = stream.Open(fullpath, .Read, .Read);
if (result case .Err(let error))
{
Log.EngineLogger.Error($"Failed to open file \"{fullpath}\". Error: {error}");
return null;
}
return stream;
}
}
}
+3 -3
View File
@@ -33,9 +33,9 @@ namespace GlitchyEngine.Content
CGLTF.Free(data);
}
private static void NodesToEntities(CGLTF.Data* data, CGLTF.Node* node, EcsEntity? parentEntity, EcsWorld world, Effect validationEffect, Material material, List<AnimationClip> clips)
private static void NodesToEntities(CGLTF.Data* data, CGLTF.Node* node, Entity? parentEntity, EcsWorld world, Effect validationEffect, Material material, List<AnimationClip> clips)
{
EcsEntity entity = world.NewEntity();
Entity entity = world.NewEntity();
#if DEBUG
var nameComponent = world.AssignComponent<DebugNameComponent>(entity);
@@ -122,7 +122,7 @@ namespace GlitchyEngine.Content
{
for(var primitive in node.Mesh.Primitives)
{
EcsEntity meshEntity = world.NewEntity();
Entity meshEntity = world.NewEntity();
var meshParent = world.AssignComponent<ParentComponent>(meshEntity);
meshParent.Entity = entity;
@@ -1,13 +0,0 @@
namespace System
{
extension Runtime
{
[NoReturn, Warn("The method is not implemented.")]
#unwarn
public static void NotImplemented(String filePath = Compiler.CallerFilePath, int line = Compiler.CallerLineNum)
{
String failStr = scope .()..AppendF("Not Implemented at line {} in {}", line, filePath);
Internal.FatalError(failStr, 1);
}
}
}
@@ -1,21 +0,0 @@
namespace System
{
extension String
{
[Inline]
public void CopyTo(Span<char8> target)
{
CopyTo(target.Ptr, target.Length);
}
[Inline]
public void CopyTo(char8* target, int targetLength)
{
int copiedChars = Math.Min(targetLength - 1, Length);
Internal.MemCpy(target, Ptr, copiedChars);
target[copiedChars] = '\0';
}
}
}
+1 -100
View File
@@ -1,24 +1,12 @@
using GlitchyEngine.Math;
using GlitchyEngine.Renderer;
using System;
namespace ImGui
{
extension ImGui
{
extension Vec2
{
public static explicit operator Vector2(Vec2 v) => .(v.x, v.y);
public static explicit operator Vec2(Vector2 v) => .(v.X, v.Y);
}
extension Vec4
{
public static explicit operator Vector4(Vec4 v) => .(v.x, v.y, v.z, v.w);
public static explicit operator Vec4(Vector4 v) => .(v.X, v.Y, v.Z, v.W);
}
// TODO: Color-functions
public static bool ColorEdit3(char* label, ref ColorRGB col, ColorEditFlags flags = (ColorEditFlags) 0) => ColorEdit3Impl(label, *(float[3]*)&col, flags);
public static bool ColorEdit3(char* label, ref ColorRGBA col, ColorEditFlags flags = (ColorEditFlags) 0) => ColorEdit3Impl(label, *(float[3]*)&col, flags);
@@ -33,94 +21,7 @@ namespace ImGui
// Wouldn't be necesseary if RenderTarget2D was Texture2D
public static extern void Image(RenderTarget2D texture, Vec2 size, Vec2 uv0 = Vec2.Zero, Vec2 uv1 = Vec2.Ones, Vec4 tint_col = Vec4.Ones, Vec4 border_col = Vec4.Zero);
public static void TextUnformatted(StringView text) => TextUnformattedImpl(text.Ptr, text.Ptr + text.Length);
public static void PushID(StringView id) => PushID(id.Ptr, id.Ptr + id.Length);
/// Releases references that accumulated calls like ImGui::Image
protected internal static extern void CleanupFrame();
/// Control to edit a vector 3 with drag functionality and reset buttons
public static bool EditVector3(StringView label, ref Vector3 value, Vector3 resetValues = .Zero, float dragSpeed = 0.1f, float columnWidth = 100f)
{
bool changed = false;
PushID(label);
defer PopID();
Columns(2);
defer Columns(1);
SetColumnWidth(0, columnWidth);
TextUnformatted(label);
NextColumn();
PushMultiItemsWidths(3, CalcItemWidth());
PushStyleVar(.ItemSpacing, Vec2.Zero);
defer PopStyleVar();
float lineHeight = GetFont().FontSize + GetStyle().FramePadding.y * 2.0f;
ImGui.Vec2 buttonSize = .(lineHeight + 3.0f, lineHeight);
PushStyleColor(.Button, Color(230, 25, 45).Value);
PushStyleColor(.ButtonHovered, Color(150, 25, 45).Value);
PushStyleColor(.ButtonActive, Color(230, 120, 130).Value);
if (Button("X", buttonSize))
{
value.X = resetValues.X;
changed = true;
}
SameLine();
if (DragFloat("##X", &value.X, dragSpeed))
changed = true;
PopItemWidth();
SameLine();
PopStyleColor(3);
PushStyleColor(.Button, Color(50, 190, 15).Value);
PushStyleColor(.ButtonHovered, Color(50, 120, 15).Value);
PushStyleColor(.ButtonActive, Color(116, 190, 99).Value);
if (Button("Y", buttonSize))
{
value.Y = resetValues.Y;
changed = true;
}
SameLine();
if (DragFloat("##Y", &value.Y, dragSpeed))
changed = true;
PopItemWidth();
SameLine();
PopStyleColor(3);
PushStyleColor(.Button, Color(55, 55, 230).Value);
PushStyleColor(.ButtonHovered, Color(55, 55, 150).Value);
PushStyleColor(.ButtonActive, Color(90, 90, 230).Value);
if (Button("Z", buttonSize))
{
value.Z = resetValues.Z;
changed = true;
}
SameLine();
if (DragFloat("##Z", &value.Z, dragSpeed))
changed = true;
PopItemWidth();
PopStyleColor(3);
return changed;
}
}
}
+143 -52
View File
@@ -2,8 +2,6 @@ using System;
using ImGui;
using GlitchyEngine.Events;
using ImGuizmo;
using GlitchyEngine.Renderer;
using System.IO;
using internal ImGui;
@@ -18,10 +16,6 @@ namespace GlitchyEngine.ImGui
{
public class ImGuiLayer : Layer
{
ImGui.IO* _io;
public bool SettingsInvalid;
public this() : base("ImGuiLayer") { }
public override void OnAttach()
@@ -35,10 +29,10 @@ namespace GlitchyEngine.ImGui
ImGui.CreateContext();
ImGui.StyleColorsDark();
_io = ImGui.GetIO();
_io.ConfigFlags |= .NavEnableKeyboard;
_io.ConfigFlags |= .DockingEnable;
_io.ConfigFlags |= .ViewportsEnable;
ImGui.IO* io = ImGui.GetIO();
io.ConfigFlags |= .NavEnableKeyboard;
io.ConfigFlags |= .DockingEnable;
io.ConfigFlags |= .ViewportsEnable;
// Todo: currently broken in ImGui
//io.ConfigFlags |= .DpiEnableScaleFonts;
@@ -46,14 +40,15 @@ namespace GlitchyEngine.ImGui
// When viewports are enabled we tweak WindowRounding/WindowBg so platform windows can look identical to regular ones.
ImGui.Style* style = ImGui.GetStyle();
if(_io.ConfigFlags.HasFlag(.ViewportsEnable))
if(io.ConfigFlags.HasFlag(.ViewportsEnable))
{
style.WindowRounding = 0.0f;
style.Colors[(int)ImGui.Col.WindowBg].w = 1.0f;
}
#if BF_PLATFORM_WINDOWS
ImGuiImplWin32.Init(Application.Get().Window.NativeWindow);
// Todo: temporary, needs to be platform independent
ImGuiImplWin32.Init((void*)(uint)(Windows.HWnd)(int)Application.Get().Window.NativeWindow);
#endif
#if GE_GRAPHICS_DX11
@@ -64,56 +59,153 @@ namespace GlitchyEngine.ImGui
public override void OnDetach()
{
Debug.Profiler.ProfileFunction!();
#if GE_GRAPHICS_DX11
ImGuiImplDX11.Shutdown();
#endif
#if BF_PLATFORM_WINDOWS
ImGuiImplWin32.Shutdown();
#endif
ImGui.DestroyContext();
}
public override void OnEvent(Event event)
{
/*
EventDispatcher dispatcher = scope EventDispatcher(event);
dispatcher.Dispatch<WindowResizeEvent>(scope (e) =>
{
//ref ImGui.IO io = ref ImGui.GetIO();
//io.DisplaySize = .(e.Width, e.Height);
//io.DisplayFramebufferScale = .(1.0f, 1.0f);
return false;
});
dispatcher.Dispatch<MouseMovedEvent>(scope (e) =>
{
ref ImGui.IO io = ref ImGui.GetIO();
io.MousePos = ImGui.Vec2(e.PositionX, e.PositionY);
return false;
});
dispatcher.Dispatch<MouseButtonPressedEvent>(scope (e) =>
{
int button = 0;
switch(e.MouseButton)
{
case .LeftButton:
button = (uint)ImGui.MouseButton.Left;
case .RightButton:
button = (uint)ImGui.MouseButton.Right;
case .MiddleButton:
button = (uint)ImGui.MouseButton.Middle;
case .XButton1:
button = (uint)3;
case .XButton2:
button = (uint)4;
default:
}
ref ImGui.IO io = ref ImGui.GetIO();
io.MouseDown[button] = true;
return false;
});
dispatcher.Dispatch<MouseButtonReleasedEvent>(scope (e) =>
{
int button = 0;
switch(e.MouseButton)
{
case .LeftButton:
button = (uint)ImGui.MouseButton.Left;
case .RightButton:
button = (uint)ImGui.MouseButton.Right;
case .MiddleButton:
button = (uint)ImGui.MouseButton.Middle;
case .XButton1:
button = (uint)3;
case .XButton2:
button = (uint)4;
default:
}
ref ImGui.IO io = ref ImGui.GetIO();
io.MouseDown[button] = false;
return false;
});
dispatcher.Dispatch<MouseScrolledEvent>(scope (e) =>
{
ref ImGui.IO io = ref ImGui.GetIO();
io.MouseWheel += e.YOffset;
io.MouseWheelH += e.XOffset; // Todo: horizontal mousewheel inverted?!
return false;
});
dispatcher.Dispatch<KeyPressedEvent>(scope (e) =>
{
if(e.KeyCode >= (.)256)
return false;
ref ImGui.IO io = ref ImGui.GetIO();
io.KeysDown[(int32)e.KeyCode] = true;
io.KeyCtrl = io.KeysDown[(int32)Key.Control];
io.KeyShift = io.KeysDown[(int32)Key.Shift];
io.KeyAlt = io.KeysDown[(int32)Key.Alt];
io.KeySuper = io.KeysDown[(int32)Key.LeftSuper] || io.KeysDown[(int32)Key.RightSuper];
return false;
});
dispatcher.Dispatch<KeyReleasedEvent>(scope (e) =>
{
if(e.KeyCode >= (.)256)
return false;
ref ImGui.IO io = ref ImGui.GetIO();
io.KeysDown[(int32)e.KeyCode] = false;
io.KeyCtrl = io.KeysDown[(int32)Key.Control];
io.KeyShift = io.KeysDown[(int32)Key.Shift];
io.KeyAlt = io.KeysDown[(int32)Key.Alt];
io.KeySuper = io.KeysDown[(int32)Key.LeftSuper] || io.KeysDown[(int32)Key.RightSuper];
return false;
});
dispatcher.Dispatch<KeyTypedEvent>(scope (e) =>
{
ref ImGui.IO io = ref ImGui.GetIO();
io.AddInputCharacterUTF16((uint16)e.Char);
return false;
});
*/
}
public void Begin()
{
Debug.Profiler.ProfileFunction!();
// Todo:
//var v = DirectX.ImmediateContext;
//v.OutputMerger.SetRenderTargets(1, &DirectX.BackBufferTarget, null);
Application.Get().Window.Context.SetRenderTarget(null);
ImGuiImplDX11.NewFrame();
ImGuiImplWin32.NewFrame();
ImGui.NewFrame();
ImGuizmo.BeginFrame();
}
bool showDemo = true;
public void ImGuiRender()
{
Debug.Profiler.ProfileFunction!();
if (SettingsInvalid)
{
var settings = Application.Get().Settings.ImGuiSettings;
ImGui.GetIO().Fonts.Clear();
String fullpath = scope String();
Application.Get().ContentManager.GetFilePath(fullpath, settings.FontName);
if (File.Exists(fullpath))
{
ImGui.GetIO().Fonts.AddFontFromFileTTF(fullpath, settings.FontSize);
}
else
{
ImGui.GetIO().Fonts.AddFontDefault();
}
#if GE_GRAPHICS_DX11
ImGuiImplDX11.CreateDeviceObjects();
#endif
SettingsInvalid = false;
}
Begin();
{
@@ -122,6 +214,7 @@ namespace GlitchyEngine.ImGui
var event = scope ImGuiRenderEvent();
Application.Get().OnEvent(event);
}
//ImGui.ShowDemoWindow(&showDemo);
End();
}
@@ -130,19 +223,17 @@ namespace GlitchyEngine.ImGui
{
Debug.Profiler.ProfileFunction!();
ImGui.Render();
RenderCommand.SetDepthStencilTarget(null);
RenderCommand.SetRenderTarget(null);
RenderCommand.BindRenderTargets();
ImGui.IO* io = ImGui.GetIO();
#if GE_GRAPHICS_DX11
let window = Application.Get().Window;
io.DisplaySize = .(window.Width, window.Height);
ImGui.Render();
ImGuiImplDX11.RenderDrawData(ImGui.GetDrawData());
#endif
ImGui.CleanupFrame();
if(_io.ConfigFlags.HasFlag(.ViewportsEnable))
if(io.ConfigFlags.HasFlag(.ViewportsEnable))
{
ImGui.UpdatePlatformWindows();
ImGui.RenderPlatformWindowsDefault();
-5
View File
@@ -18,11 +18,6 @@ namespace GlitchyEngine.Math
public this(int initialCapacity = sizeof(uint))
{
var initialCapacity;
if (initialCapacity < sizeof(uint))
initialCapacity = sizeof(uint);
EnsureCapacity(initialCapacity);
}
+2 -2
View File
@@ -18,10 +18,10 @@ namespace GlitchyEngine.Math
public const float PiOverFour = 0.785398163f;
/// Converts radians to degrees
public const float RadToDeg = 180.0f / Pi;
const float RadToDeg = 180.0f / Pi;
/// Converts radians to degrees
public const float DegToRad = Pi / 180.0f;
const float DegToRad = Pi / 180.0f;
// Converts the given radians to degrees
public static float ToDegrees(float radians)
+13 -43
View File
@@ -314,65 +314,35 @@ namespace GlitchyEngine.Math
return result;
}
public static Vector3 ToEulerAngles(Quaternion q)
public static Vector3 ToEulerAngles(Quaternion q1)
{
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/
Vector3 result;
float sqw = q.W*q.W;
float sqx = q.X*q.X;
float sqy = q.Y*q.Y;
float sqz = q.Z*q.Z;
float sqw = q1.W*q1.W;
float sqx = q1.X*q1.X;
float sqy = q1.Y*q1.Y;
float sqz = q1.Z*q1.Z;
float unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
float test = q.X*q.Y + q.Z*q.W;
if (test > 0.4999f*unit) { // singularity at north pole
result.Y = 2.0f * Math.Atan2(q.X,q.W);
float test = q1.X*q1.Y + q1.Z*q1.W;
if (test > 0.499f*unit) { // singularity at north pole
result.Y = 2.0f * Math.Atan2(q1.X,q1.W);
result.Z = Math.PI_f / 2.0f;
result.X = 0.0f;
return result;
}
if (test < -0.4999f*unit) { // singularity at south pole
result.Y = -2.0f * Math.Atan2(q.X,q.W);
if (test < -0.499f*unit) { // singularity at south pole
result.Y = -2.0f * Math.Atan2(q1.X,q1.W);
result.Z = -Math.PI_f / 2.0f;
result.X = 0.0f;
return result;
}
result.Y = Math.Atan2(2*q.Y*q.W-2*q.X*q.Z , sqx - sqy - sqz + sqw);
result.Y = Math.Atan2(2*q1.Y*q1.W-2*q1.X*q1.Z , sqx - sqy - sqz + sqw);
result.Z = Math.Asin(2*test/unit);
result.X = Math.Atan2(2*q.X*q.W-2*q.Y*q.Z , -sqx + sqy - sqz + sqw);
result.X = Math.Atan2(2*q1.X*q1.W-2*q1.Y*q1.Z , -sqx + sqy - sqz + sqw);
return result;
//return .(q.Pitch(), q.Yaw(), q.Roll());
}
/*
public float Pitch()
{
float y = 2.0f * (Y * Z + W * X);
float x = W * W - X * X - Y * Y + Z * Z;
if (Vector2(x, y).Equals(.Zero)) //avoid atan2(0,0) - handle singularity - Matiis
return 2.0f * Math.Atan2(X, W);
return Math.Atan2(y, x);
}
public float Yaw()
{
return Math.Asin(Math.Clamp(-2.0f * (X * Z - W * Y), -1.0f, 1.0f));
}
public float Roll()
{
float y = 2.0f * (X * Y + W * Z);
float x = W * W + X * X - Y * Y - Z * Z;
if (Vector2(x, y).Equals(.Zero)) //avoid atan2(0,0) - handle singularity - Matiis
return 0;
return Math.Atan2(y, x);
}
*/
}
}
@@ -21,9 +21,9 @@ namespace GlitchyEngine.Math
}
/**
* Returns true if the swizzle operator is invalid (same component assigned twice).
* Determines whether or not a swizzle operator can have a valid setter (e.g. no component assigned twice)
*/
static bool IsSetterValid(int[4] cmp, int vecSize)
static bool invalidSetter(int[4] cmp, int vecSize)
{
return cmp[0] == cmp[1] || (vecSize >= 3 && cmp[0] == cmp[2]) || (vecSize == 4 && cmp[0] == cmp[3]) ||
(vecSize >= 3 && cmp[1] == cmp[2]) || (vecSize == 4 && cmp[1] == cmp[3]) ||
@@ -33,7 +33,8 @@ namespace GlitchyEngine.Math
[Comptime]
public void ApplyToType(Type type)
{
String[4] componentNames = .("X", "Y", "Z", "W");
// TODO: report bug... sized array not working
String[] componentNames = scope String[]("X", "Y", "Z", "W");
for(int swizzleCount = 2; swizzleCount <= 4; swizzleCount++)
{
@@ -51,16 +52,7 @@ namespace GlitchyEngine.Math
String swizzleConstructor = scope String(swizzleCount * 3);
String setter = scope String(128);
bool setterInvalid = IsSetterValid(cmp, swizzleCount);
if (!setterInvalid)
{
setter.Append(
"""
set mut
{
""");
}
bool setterInvalid = invalidSetter(cmp, swizzleCount);
for(int c = 0; c < swizzleCount; c++)
{
@@ -72,26 +64,21 @@ namespace GlitchyEngine.Math
}
swizzleConstructor.Append(componentNames[cmp[c]]);
if(!setterInvalid && c < _vectorSize)
if(!setterInvalid && c < _vectorSize) //
{
setter.AppendF($"\n\t\t{componentNames[cmp[c]]} = value.{componentNames[c]};");
}
}
if (!setterInvalid)
{
setter.Append(
"""
}
""");
}
//{(setterInvalid ? "[Error(\"Cannot assign multiple values to same component.\")]" : String.Empty)}
String swizzleString = scope $"""
public {_vectorTypeName}{swizzleCount} {swizzleName}
{{
get => .({swizzleConstructor});
{setter}
set mut
{{{setter}
}}
}}
""";
-5
View File
@@ -284,10 +284,5 @@ namespace GlitchyEngine.Math
[Inline]
public static explicit operator Self(float value) => Self(value);
public bool Equals(Vector2 v, float epsilon = Math.[Friend]sMachineEpsilonFloat)
{
return (Math.Abs(v.X - X) < epsilon) && (Math.Abs(v.Y - Y) < epsilon);
}
}
}
@@ -1,13 +1,12 @@
#if GE_GRAPHICS_DX11
#if !BF_PLATFORM_WINDOWS
#error DirectX 11 (GE_GRAPHICS_DX11) can only be used on Windows.
#error DirectX 11 (GE_GRAPHICS_DX11) can on be used on Windows.
#endif
using DirectX.Common;
using DirectX.D3D11;
using DirectX.D3D11.SDKLayers;
using System.Diagnostics;
namespace GlitchyEngine.Platform.DX11
{
@@ -18,9 +17,7 @@ namespace GlitchyEngine.Platform.DX11
protected internal static ID3D11Device* NativeDevice;
protected internal static ID3D11DeviceContext* NativeContext;
#if DEBUG
protected internal static ID3D11Debug* DebugDevice;
#endif
internal static void Dx11Init()
{
@@ -31,9 +28,9 @@ namespace GlitchyEngine.Platform.DX11
Log.EngineLogger.Trace("Creating D3D11 Device and Context...");
DeviceCreationFlags deviceFlags = .None;
#if DEBUG
#if DEBUG
deviceFlags |= .Debug;
#endif
#endif
FeatureLevel[] levels = scope .(.Level_11_0);
@@ -47,7 +44,7 @@ namespace GlitchyEngine.Platform.DX11
Log.EngineLogger.Assert(deviceResult.Succeeded, scope $"Failed to create D3D11 Device. Message({(int32)deviceResult}): {deviceResult}");
#if DEBUG
#if DEBUG
{
Debug.Profiler.ProfileScope!("Query for ID3D11Debug");
if(NativeDevice.QueryInterface<ID3D11Debug>(out DebugDevice).Succeeded)
@@ -62,7 +59,7 @@ namespace GlitchyEngine.Platform.DX11
}
}
}
#endif
#endif
Log.EngineLogger.Trace($"D3D11 Device and Context created (Feature level: {deviceLevel})");
}
@@ -71,9 +68,7 @@ namespace GlitchyEngine.Platform.DX11
// We created a second GraphicsContext (for some reason?) just increment references.
NativeDevice.AddRef();
NativeContext.AddRef();
#if DEBUG
DebugDevice.AddRef();
#endif
}
}
@@ -83,24 +78,8 @@ namespace GlitchyEngine.Platform.DX11
NativeDevice.Release();
NativeContext.Release();
#if DEBUG
Debug.WriteLine("""
-------------------------
Live DX Objects Report:
""");
DebugDevice.ReportLiveDeviceObjects(.Detail | .IgnoreInternal);
Debug.WriteLine("""
-------------------------
""");
DebugDevice.ReportLiveDeviceObjects(.Detail);
DebugDevice.Release();
#endif
}
}
}
@@ -46,7 +46,7 @@ namespace GlitchyEngine.Renderer
var result = D3DCompiler.D3DCompile(code.CStr(), (.)code.Length, null, nativeMacros, null, entryPoint, target, compileFlags, .None, &shaderBlob, &errorBlob);
if(result.Failed)
{
StringView str = StringView((char8*)errorBlob.GetBufferPointer(), (int)errorBlob.GetBufferSize());
StringView str = StringView((char8*)errorBlob.GetBufferPointer(), errorBlob.GetBufferSize());
Log.EngineLogger.Error($"Failed to compile Shader: Error Code({(int)result}): {result} | Error Message: {str}");
}
}
@@ -1,52 +1,50 @@
#if GE_GRAPHICS_DX11
using System;
using System.IO;
using DirectX.D3D11;
using DirectX.Common;
using DirectXTK;
using GlitchyEngine.Math;
using GlitchyEngine.Platform.DX11;
using System.Collections;
using internal GlitchyEngine.Renderer;
typealias NativeTex2DDesc = DirectX.D3D11.Texture2DDescription;
using GlitchyEngine.Platform.DX11;
using internal GlitchyEngine.Platform.DX11;
namespace GlitchyEngine.Renderer
{
internal typealias NativeTex2DDesc = DirectX.D3D11.Texture2DDescription;
extension Texture
{
protected internal ID3D11ShaderResourceView* nativeResourceView ~ _?.Release();
protected override void ImplBind(uint32 slot)
{
// TODO: textures don't bind themselves!
NativeContext.VertexShader.SetShaderResources(slot, 1, &nativeResourceView);
NativeContext.PixelShader.SetShaderResources(slot, 1, &nativeResourceView);
}
/** \brief Loads the texture from the specified path.
* @param path The path of the texture to load.
* @param texture The reference to the pointer that will hold the texture.
* @returns true if the texture was loaded successfully; false otherwise.
*/
protected bool LoadDdsResourcePlatform<T>(Stream stream, ref T* texture) where T : ID3D11Resource
protected bool LoadResourcePlatform<T>(StringView path, ref T* texture) where T : ID3D11Resource
{
Debug.Profiler.ProfileResourceFunction!();
uint8[] ddsData = new:ScopedAlloc! uint8[stream.Length];
var result = stream.TryRead(ddsData);
if (result case .Err(let err))
{
Log.EngineLogger.Error($"Failed to read texture data from stream. Error: {err}");
}
((ID3D11Resource*)texture)?.Release();
nativeResourceView?.Release();
HResult loadResult = DDSTextureLoader.CreateDDSTextureFromMemory(NativeDevice,
ddsData.Ptr, (uint)ddsData.Count, (.)&texture, &nativeResourceView);
HResult loadResult = DDSTextureLoader.CreateDDSTextureFromFile(NativeDevice, path.ToScopedNativeWChar!(),
(.)&texture, &nativeResourceView);
if(loadResult.Failed)
{
Log.EngineLogger.Error($"Failed to load texture. Error({(int)loadResult}): {loadResult}");
Log.EngineLogger.Error($"Failed to load texture \"{path}\". Error({(int)loadResult}): {loadResult}");
ReleaseAndNullify!(texture);
ReleaseAndNullify!(nativeResourceView);
@@ -94,11 +92,11 @@ namespace GlitchyEngine.Renderer
public override uint32 ArraySize => nativeDesc.ArraySize;
public override uint32 MipLevels => nativeDesc.MipLevels;
protected override void LoadDdsPlatform(Stream stream)
protected override void LoadTexturePlatform()
{
Debug.Profiler.ProfileResourceFunction!();
LoadDdsResourcePlatform(stream, ref nativeTexture);
LoadResourcePlatform(_path, ref nativeTexture);
let resType = nativeTexture.GetResourceType();
Log.EngineLogger.Assert(resType == .Texture2D, scope $"The texture \"{_path}\" is not a 2D texture (it is {resType}).");
@@ -268,11 +266,11 @@ namespace GlitchyEngine.Renderer
public override uint32 ArraySize => nativeDesc.ArraySize / 6;
public override uint32 MipLevels => nativeDesc.MipLevels;
protected override void LoadTexturePlatform(Stream stream)
protected override void LoadTexturePlatform()
{
Debug.Profiler.ProfileResourceFunction!();
LoadDdsResourcePlatform(stream, ref nativeTexture);
LoadResourcePlatform(_path, ref nativeTexture);
let resType = nativeTexture.GetResourceType();
Log.EngineLogger.Assert(resType == .Texture2D, scope $"The texture \"{_path}\" is not a texture cube (it is {resType}).");
-1
View File
@@ -42,7 +42,6 @@ namespace GlitchyEngine
Log.EngineLogger.Info("Application uninitialized.");
}
Debug.Profiler.EndProfiling();
return 0;
+1 -19
View File
@@ -3,25 +3,7 @@ using GlitchyEngine.Math;
namespace GlitchyEngine.Renderer
{
struct Camera
{
protected Matrix _projection;
public Matrix Projection => _projection;
protected this()
{
_projection = .Identity;
}
public this(Matrix projection)
{
_projection = projection;
}
}
public abstract class OldCamera
public abstract class Camera
{
protected Matrix _view;
protected Matrix _transform;
@@ -2,7 +2,7 @@ using GlitchyEngine.Math;
namespace GlitchyEngine.Renderer
{
public struct OldCameraComponent
public struct CameraComponent
{
public enum Projection
{
@@ -29,11 +29,10 @@ namespace GlitchyEngine.Renderer
*/
Orthographic
}
float _nearPlane;
float _farPlane;
Projection _projectionType;
float _fovY;
float _aspect;
@@ -2,7 +2,7 @@ using GlitchyEngine.Math;
namespace GlitchyEngine.Renderer
{
public class OrthographicCamera : OldCamera
public class OrthographicCamera : Camera
{
protected float _bottom, _left, _right, _top;
@@ -6,7 +6,7 @@ namespace GlitchyEngine.Renderer
/**
* If FarPlane is float.PositiveInfinity the projection matrix will be an infinite projection (that means no far plane)
*/
public class PerspectiveCamera : OldCamera
public class PerspectiveCamera : Camera
{
public enum ProjectionType
{
@@ -7,5 +7,7 @@ namespace GlitchyEngine.Renderer
[AllowAppend]
public this(String source, String entryPoint, ShaderDefine[] macros = null)
: base(source, entryPoint, macros) { }
public override extern void CompileFromSource(String code, String entryPoint, ShaderDefine[] macros = null);
}
}
+3 -4
View File
@@ -79,8 +79,7 @@ namespace GlitchyEngine.Renderer
LineGeometry.SetVertexLayout(layout..ReleaseRefNoDelete());
}
// TODO
/*public static void BeginScene(EcsWorld world, EcsEntity cameraEntity)
public static void BeginScene(EcsWorld world, Entity cameraEntity)
{
Debug.Profiler.ProfileRendererFunction!();
@@ -92,9 +91,9 @@ namespace GlitchyEngine.Renderer
var proj = camera.Projection;
_sceneConstants.ViewProjection = proj * view;
}*/
}
public static void BeginScene(OldCamera camera)
public static void BeginScene(Camera camera)
{
Debug.Profiler.ProfileRendererFunction!();
+91 -262
View File
@@ -3,7 +3,6 @@ using System.Collections;
using System;
using System.Diagnostics;
using GlitchyEngine.Renderer.Text;
using GlitchyEngine.World;
namespace GlitchyEngine.Renderer
{
@@ -116,18 +115,16 @@ namespace GlitchyEngine.Renderer
private static Texture2D s_whiteTexture;
private static GeometryBinding s_quadBatchBinding;
private static GeometryBinding s_batchBinding;
private static GeometryBinding s_circleBatchBinding;
private static VertexBuffer s_quadInstanceBuffer;
private static VertexBuffer s_instanceBuffer;
private static VertexBuffer s_circleInstanceBuffer;
private static uint32 s_maxInstancesPerBatch = 8192;
private static BatchVertex[] s_rawQuadInstances;
private static BatchVertex[] s_rawInstances;
private static CircleBatchVertex[] s_rawCircleInstances;
private static uint32 s_setInstances = 0;
private static uint32 s_setInstances;
private static List<QueueQuad> s_QuadinstanceQueue;
private static List<QueueQuad> s_instanceQueue;
private static List<QueueCircle> s_circleInstanceQueue;
private static DrawOrder s_drawOrder;
@@ -136,20 +133,9 @@ namespace GlitchyEngine.Renderer
private static Effect s_currentEffect;
private static Effect s_currentCircleEffect;
public static uint32 MaxInstancesPerBatch
{
get => s_maxInstancesPerBatch;
set
{
if (s_maxInstancesPerBatch == value)
return;
private static int s_InstancesPerDrawCall = 1024;
private static int s_MaxInstancesPerDrawCall = 8192;
s_maxInstancesPerBatch = value;
ApplyInstanceCount();
}
}
private static void InitEffect()
{
Debug.Profiler.ProfileFunction!();
@@ -194,8 +180,10 @@ namespace GlitchyEngine.Renderer
{
Debug.Profiler.ProfileFunction!();
// Quad
{
s_instanceBuffer = new VertexBuffer(typeof(BatchVertex), 1024, .Dynamic, .Write);
s_instanceBuffer.SetData(0);
VertexElement[] vertexElements = new .(
VertexElement(.R32G32_Float, "POSITION", false, 0, 0, 0, .PerVertexData, 0),
VertexElement(.R32G32_Float, "TEXCOORD", false, 0, 0, (.)-1, .PerVertexData, 0),
@@ -208,20 +196,27 @@ namespace GlitchyEngine.Renderer
VertexElement(.R32G32B32A32_Float, "TEXCOORD", false, 1, 1, (.)-1, .PerInstanceData, 1)
);
s_quadBatchBinding = new GeometryBinding();
s_quadBatchBinding.SetPrimitiveTopology(.TriangleList);
using (var quadBatchLayout = new VertexLayout(vertexElements, true, s_batchEffect.VertexShader))
{
s_quadBatchBinding.SetVertexLayout(quadBatchLayout);
}
VertexLayout batchLayout = new VertexLayout(vertexElements, true, s_batchEffect.VertexShader);
s_quadBatchBinding.SetVertexBufferSlot(s_quadGeometry.GetVertexBuffer(0), 0);
s_quadBatchBinding.SetIndexBuffer(s_quadGeometry.GetIndexBuffer(), 0);
s_batchBinding = new GeometryBinding();
s_batchBinding.SetVertexLayout(batchLayout..ReleaseRefNoDelete());
s_batchBinding.SetPrimitiveTopology(.TriangleList);
s_batchBinding.SetVertexBufferSlot(s_quadGeometry.GetVertexBuffer(0), 0);
s_batchBinding.SetIndexBuffer(s_quadGeometry.GetIndexBuffer(), 0);
s_batchBinding.SetVertexBufferSlot(s_instanceBuffer, 1);
s_rawInstances = new BatchVertex[s_InstancesPerDrawCall];
s_setInstances = 0;
s_instanceQueue = new List<QueueQuad>(s_InstancesPerDrawCall);
}
// Circle
{
s_circleInstanceBuffer = new VertexBuffer(typeof(CircleBatchVertex), 1024, .Dynamic, .Write);
s_circleInstanceBuffer.SetData(0);
VertexElement[] vertexElements = new .(
VertexElement(.R32G32_Float, "POSITION", false, 0, 0, 0, .PerVertexData, 0),
VertexElement(.R32G32_Float, "TEXCOORD", false, 0, 0, (.)-1, .PerVertexData, 0),
@@ -236,54 +231,21 @@ namespace GlitchyEngine.Renderer
);
s_circleBatchBinding = new GeometryBinding();
s_circleBatchBinding.SetPrimitiveTopology(.TriangleList);
s_circleBatchBinding.SetPrimitiveTopology(.TriangleList);
using (var circleBatchLayout = new VertexLayout(vertexElements, true, s_circleBatchEffect.VertexShader))
using(var circleBatchLayout = new VertexLayout(vertexElements, true, s_circleBatchEffect.VertexShader))
{
s_circleBatchBinding.SetVertexLayout(circleBatchLayout);
}
s_circleBatchBinding.SetVertexBufferSlot(s_quadGeometry.GetVertexBuffer(0), 0);
s_circleBatchBinding.SetIndexBuffer(s_quadGeometry.GetIndexBuffer(), 0);
}
ApplyInstanceCount();
}
/// Updates the instance buffers so that they can fit s_maxInstancesPerBatch many instances
private static void ApplyInstanceCount()
{
Debug.Profiler.ProfileFunction!();
// Quads
{
VertexBuffer quadInstanceBuffer = new VertexBuffer(typeof(BatchVertex), s_maxInstancesPerBatch, .Dynamic, .Write);
quadInstanceBuffer.SetData(0);
s_quadInstanceBuffer?.ReleaseRef();
s_quadInstanceBuffer = quadInstanceBuffer;
s_quadBatchBinding.SetVertexBufferSlot(s_quadInstanceBuffer, 1);
delete s_rawQuadInstances;
delete s_QuadinstanceQueue;
s_rawQuadInstances = new BatchVertex[s_maxInstancesPerBatch];
s_QuadinstanceQueue = new List<QueueQuad>(s_maxInstancesPerBatch);
}
// Circles
{
VertexBuffer circleInstanceBuffer = new VertexBuffer(typeof(CircleBatchVertex), s_maxInstancesPerBatch, .Dynamic, .Write);
circleInstanceBuffer.SetData(0);
s_circleInstanceBuffer?.ReleaseRef();
s_circleInstanceBuffer = circleInstanceBuffer;
s_circleBatchBinding.SetVertexBufferSlot(s_circleInstanceBuffer, 1);
delete s_rawCircleInstances;
delete s_circleInstanceQueue;
s_rawCircleInstances = new CircleBatchVertex[s_maxInstancesPerBatch];
s_circleInstanceQueue = new List<QueueCircle>(s_maxInstancesPerBatch);
s_rawCircleInstances = new CircleBatchVertex[s_InstancesPerDrawCall];
s_circleInstanceQueue = new List<QueueCircle>(s_InstancesPerDrawCall);
}
}
@@ -345,14 +307,14 @@ namespace GlitchyEngine.Renderer
s_whiteTexture.ReleaseRef();
s_quadBatchBinding.ReleaseRef();
s_batchBinding.ReleaseRef();
s_circleBatchBinding.ReleaseRef();
s_quadInstanceBuffer.ReleaseRef();
s_instanceBuffer.ReleaseRef();
s_circleInstanceBuffer.ReleaseRef();
delete s_rawQuadInstances;
delete s_rawInstances;
delete s_rawCircleInstances;
delete s_QuadinstanceQueue;
delete s_instanceQueue;
delete s_circleInstanceQueue;
s_currentEffect?.ReleaseRef();
@@ -363,8 +325,7 @@ namespace GlitchyEngine.Renderer
#endif
}
// TODO: remove?
public static void BeginScene(OldCamera camera, DrawOrder drawOrder = .SortByTexture, Effect effect = null, Effect circleEffect = null)
public static void BeginScene(Camera camera, DrawOrder drawOrder = .SortByTexture, Effect effect = null, Effect circleEffect = null)
{
Debug.Profiler.ProfileRendererFunction!();
#if DEBUG
@@ -399,48 +360,6 @@ namespace GlitchyEngine.Renderer
s_drawOrder = drawOrder;
#if DEBUG
s_sceneRunning = true;
#endif
}
public static void BeginScene(Camera camera, Matrix transform, DrawOrder drawOrder = .SortByTexture, Effect effect = null, Effect circleEffect = null)
{
Debug.Profiler.ProfileRendererFunction!();
#if DEBUG
Log.EngineLogger.AssertDebug(s_initialized, "Renderer2D was not initialized.");
Log.EngineLogger.AssertDebug(!s_sceneRunning, "You have to call EndScene before you can make another call to BeginScene.");
#endif
//s_textureColorEffect.Bind(Renderer._context);
s_currentEffect?.ReleaseRef();
if(effect != null)
{
s_currentEffect = effect..AddRef();
}
else
{
s_currentEffect = s_batchEffect..AddRef();
}
s_currentCircleEffect?.ReleaseRef();
if(circleEffect != null)
{
s_currentCircleEffect = effect..AddRef();
}
else
{
s_currentCircleEffect = s_circleBatchEffect..AddRef();
}
Matrix viewProjection = camera.Projection * Matrix.Invert(transform);
s_currentEffect.Variables["ViewProjection"].SetData(viewProjection);
s_currentCircleEffect.Variables["ViewProjection"].SetData(viewProjection);
s_drawOrder = drawOrder;
#if DEBUG
s_sceneRunning = true;
#endif
@@ -474,8 +393,12 @@ namespace GlitchyEngine.Renderer
[Inline]
private static void QueueQuadInstance(Matrix transform, ColorRGBA color, Texture2D texture, float depth, Vector4 uvTransform)
{
s_QuadinstanceQueue.Add(QueueQuad(transform, color, texture ?? s_whiteTexture, depth, uvTransform));
s_statistics.QuadCount++;
s_instanceQueue.Add(QueueQuad(transform, color, texture ?? s_whiteTexture, depth, uvTransform));
if (s_instanceQueue.Count >= s_MaxInstancesPerDrawCall)
{
Flush();
}
}
/// Adds a circle instance to the instance queue.
@@ -483,7 +406,11 @@ namespace GlitchyEngine.Renderer
private static void QueueCircleInstance(Matrix transform, ColorRGBA color, Texture2D texture, float depth, Vector4 uvTransform, float innerRadius)
{
s_circleInstanceQueue.Add(QueueCircle(transform, color, texture ?? s_whiteTexture, depth, uvTransform, innerRadius));
s_statistics.CircleCount++;
if (s_circleInstanceQueue.Count >= s_MaxInstancesPerDrawCall)
{
Flush();
}
}
private static void FlushInstances()
@@ -493,16 +420,14 @@ namespace GlitchyEngine.Renderer
if(s_setInstances == 0)
return;
s_quadInstanceBuffer.SetData<BatchVertex>(s_rawQuadInstances.Ptr, s_setInstances, 0, .WriteDiscard);
s_instanceBuffer.SetData<BatchVertex>(s_rawInstances.Ptr, s_setInstances, 0, .WriteDiscard);
s_currentEffect.Bind(Renderer._context);
s_quadBatchBinding.InstanceCount = s_setInstances;
s_quadBatchBinding.Bind();
RenderCommand.DrawIndexedInstanced(s_quadBatchBinding);
s_batchBinding.InstanceCount = s_setInstances;
s_batchBinding.Bind();
RenderCommand.DrawIndexedInstanced(s_batchBinding);
s_setInstances = 0;
s_statistics.QuadDrawCalls++;
}
private static void FlushCircleInstances()
@@ -520,8 +445,6 @@ namespace GlitchyEngine.Renderer
RenderCommand.DrawIndexedInstanced(s_circleBatchBinding);
s_setInstances = 0;
s_statistics.CircleDrawCalls++;
}
// Quad comparison
@@ -559,13 +482,13 @@ namespace GlitchyEngine.Renderer
switch(s_drawOrder)
{
case .SortByTexture:
s_QuadinstanceQueue.Sort(scope => TextureComparison);
s_instanceQueue.Sort(scope => TextureComparison);
s_circleInstanceQueue.Sort(scope => TextureComparison);
case .BackToFront:
s_QuadinstanceQueue.Sort(scope => BackToFrontComparison);
s_instanceQueue.Sort(scope => BackToFrontComparison);
s_circleInstanceQueue.Sort(scope => BackToFrontComparison);
case .FrontToBack:
s_QuadinstanceQueue.Sort(scope => FrontToBackComparison);
s_instanceQueue.Sort(scope => FrontToBackComparison);
s_circleInstanceQueue.Sort(scope => FrontToBackComparison);
case .Immediate:
default:
@@ -577,7 +500,7 @@ namespace GlitchyEngine.Renderer
{
Debug.Profiler.ProfileRendererFunction!();
if(s_QuadinstanceQueue.IsEmpty && s_circleInstanceQueue.IsEmpty)
if(s_instanceQueue.IsEmpty && s_circleInstanceQueue.IsEmpty)
return;
SortInstances();
@@ -590,17 +513,17 @@ namespace GlitchyEngine.Renderer
{
Debug.Profiler.ProfileRendererFunction!();
if(s_QuadinstanceQueue.IsEmpty)
if(s_instanceQueue.IsEmpty)
return;
Texture2D texture = s_QuadinstanceQueue[0].Texture;
Texture2D texture = s_instanceQueue[0].Texture;
s_currentEffect.SetTexture("Texture", texture);
s_setInstances = 0;
for(int i < s_QuadinstanceQueue.Count)
for(int i < s_instanceQueue.Count)
{
var quad = ref s_QuadinstanceQueue[i];
var quad = ref s_instanceQueue[i];
// flush every time the texture changes
if(quad.Texture != texture)
@@ -611,9 +534,9 @@ namespace GlitchyEngine.Renderer
s_currentEffect.SetTexture("Texture", texture);
}
s_rawQuadInstances[s_setInstances++] = .(quad.Transform, quad.Color, quad.uvTransform);
s_rawInstances[s_setInstances++] = .(quad.Transform, quad.Color, quad.uvTransform);
if(s_setInstances == s_rawQuadInstances.Count)
if(s_setInstances == s_rawInstances.Count)
{
FlushInstances();
}
@@ -621,7 +544,7 @@ namespace GlitchyEngine.Renderer
FlushInstances();
s_QuadinstanceQueue.Clear();
s_instanceQueue.Clear();
}
private static void DrawDeferredCircles()
@@ -662,27 +585,9 @@ namespace GlitchyEngine.Renderer
s_circleInstanceQueue.Clear();
}
/// A specialized function that calculates the 2D transform matrix
private static Matrix Calculate2DTransform(Vector3 translation, Vector2 scale, float rotation)
{
float sin = 0.0f;
float cos = 1.0f;
if (rotation != 0.0f)
{
sin = Math.Sin(rotation);
cos = Math.Cos(rotation);
}
return .(cos * scale.X, -sin * scale.Y, 0, translation.X,
sin * scale.X, cos * scale.Y, 0, translation.Y,
0 , 0 , 1, translation.Z,
0 , 0 , 0, 1);
}
// Primitives
// Colored Quad
// Quad
public static void DrawQuad(Vector2 position, Vector2 size, float rotation, ColorRGBA color)
{
@@ -710,70 +615,32 @@ namespace GlitchyEngine.Renderer
DrawQuad(transform, s_whiteTexture, color);
}
// Quad Subtexture
[Inline]
private static Vector4 CalculateSubTexcoords(Vector4 texCoords, Vector4 innerTexcoords)
{
Vector4 uv = texCoords;
uv.XY += innerTexcoords.XY * uv.ZW;
uv.ZW *= innerTexcoords.ZW;
return uv;
}
// Subtex only
public static void DrawQuad(Vector2 position, Vector2 size, float rotation, SubTexture2D texture, ColorRGBA color = .White)
{
DrawQuad(Vector3(position, 0.0f), size, rotation, texture.Texture, .White, texture.TexCoords);
}
public static void DrawQuad(Vector3 position, Vector2 size, float rotation, SubTexture2D texture, ColorRGBA color = .White)
{
DrawQuad(position, size, rotation, texture.Texture, .White, texture.TexCoords);
}
public static void DrawQuad(Matrix transform, SubTexture2D texture, ColorRGBA color = .White)
{
DrawQuad(transform, texture.Texture, .White, texture.TexCoords);
}
// Subtex + Texcoords
public static void DrawQuad(Vector2 position, Vector2 size, float rotation, SubTexture2D subtexture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
Vector4 uv = CalculateSubTexcoords(subtexture.TexCoords, uvTransform);
DrawQuad(Vector3(position, 0.0f), size, rotation, subtexture.Texture, .White, uv);
}
public static void DrawQuad(Vector3 position, Vector2 size, float rotation, SubTexture2D subtexture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
Vector4 uv = CalculateSubTexcoords(subtexture.TexCoords, uvTransform);
DrawQuad(position, size, rotation, subtexture.Texture, .White, uv);
}
public static void DrawQuad(Matrix transform, SubTexture2D subtexture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
Vector4 uv = CalculateSubTexcoords(subtexture.TexCoords, uvTransform);
DrawQuad(transform, subtexture.Texture, .White, uv);
}
// Textured Quad
public static void DrawQuad(Vector2 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
DrawQuad(Vector3(position, 0.0f), size, rotation, texture, color, uvTransform);
}
public static void DrawQuadPivotCorner(Vector2 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
DrawQuadPivotCorner(Vector3(position, 0.0f), size, rotation, texture, color, uvTransform);
}
public static void DrawQuad(Vector3 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
Matrix transform = Calculate2DTransform(position, size, rotation);
Debug.Profiler.ProfileRendererFunction!();
DrawQuad(transform, texture, color, uvTransform);
#if DEBUG
Log.EngineLogger.AssertDebug(s_sceneRunning, "Missing call of BeginScene.");
#endif
Matrix transform = Matrix.Translation(position) * Matrix.RotationZ(rotation) * Matrix.Scaling(size.X, size.Y, 1.0f);
QueueQuadInstance(transform, color, texture, position.Z, uvTransform);
if(s_drawOrder == .Immediate)
{
DrawDeferred();
}
}
public static void DrawQuad(Matrix transform, Texture2D texture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
@@ -792,13 +659,6 @@ namespace GlitchyEngine.Renderer
}
}
// Textured quad pivot
public static void DrawQuadPivotCorner(Vector2 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
DrawQuadPivotCorner(Vector3(position, 0.0f), size, rotation, texture, color, uvTransform);
}
public static void DrawQuadPivotCorner(Vector3 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, Vector4 uvTransform = .(0, 0, 1, 1))
{
DrawQuad(position + Vector3(size.X / 2, size.Y / -2, 0), size, rotation, texture, color, uvTransform);
@@ -808,66 +668,35 @@ namespace GlitchyEngine.Renderer
public static void DrawCircle(Vector2 position, Vector2 size, ColorRGBA color, float innerRadius = 1.0f)
{
DrawCircle(Vector3(position, 0.0f), size, 0, s_whiteTexture, color, innerRadius);
DrawCircle(Vector3(position, 0.0f), size, s_whiteTexture, color, innerRadius);
}
public static void DrawCircle(Vector3 position, Vector2 size, ColorRGBA color, float innerRadius = 1.0f)
{
DrawCircle(position, size, 0, s_whiteTexture, color, innerRadius);
DrawCircle(position, size, s_whiteTexture, color, innerRadius);
}
public static void DrawCircle(Vector2 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, float innerRadius = 1.0f, Vector4 uvTransform = .(0, 0, 1, 1))
{
DrawCircle(Vector3(position, 0.0f), size, rotation, texture, color, innerRadius, uvTransform);
DrawCircle(Vector3(position, 0.0f), size, texture, color, innerRadius, uvTransform);
}
public static void DrawCircle(Vector3 position, Vector2 size, float rotation, Texture2D texture, ColorRGBA color = .White, float innerRadius = 1.0f, Vector4 uvTransform = .(0, 0, 1, 1))
{
Matrix transform = Calculate2DTransform(position, size, rotation);
DrawCircle(transform, texture, color, innerRadius, uvTransform);
}
public static void DrawCircle(Matrix transform, Texture2D texture, ColorRGBA color = .White, float innerRadius = 1.0f, Vector4 uvTransform = .(0, 0, 1, 1))
public static void DrawCircle(Vector3 position, Vector2 size, Texture2D texture, ColorRGBA color = .White, float innerRadius = 1.0f, Vector4 uvTransform = .(0, 0, 1, 1))
{
Debug.Profiler.ProfileRendererFunction!();
#if DEBUG
Log.EngineLogger.AssertDebug(s_sceneRunning, "Missing call of BeginScene.");
#endif
QueueCircleInstance(transform, color, texture, transform.Translation.Z, uvTransform, innerRadius);
Matrix transform = Matrix.Translation(position) * Matrix.Scaling(size.X, size.Y, 1.0f);
QueueCircleInstance(transform, color, texture, position.Z, uvTransform, innerRadius);
if(s_drawOrder == .Immediate)
{
DrawDeferred();
}
}
public struct Statistics
{
public uint32 QuadDrawCalls = 0;
public uint32 CircleDrawCalls = 0;
public uint32 QuadCount = 0;
public uint32 CircleCount = 0;
public uint32 TotalDrawCalls => QuadDrawCalls + CircleDrawCalls;
public uint32 TotalInstanceCount => QuadCount + CircleCount;
public uint32 TotalVertexCount => TotalInstanceCount * 4;
public uint32 TotalTriangleCount => TotalInstanceCount * 2;
public uint32 TotalIndexCount => TotalInstanceCount * 6;
public void Reset() mut
{
QuadDrawCalls = 0;
CircleDrawCalls = 0;
QuadCount = 0;
CircleCount = 0;
}
}
private static Statistics s_statistics;
public static ref Statistics Stats => ref s_statistics;
}
}
-41
View File
@@ -1,41 +0,0 @@
using GlitchyEngine.Core;
using GlitchyEngine.Math;
namespace GlitchyEngine.Renderer
{
class SubTexture2D : RefCounter
{
protected Texture2D _texture ~ _.ReleaseRef();
protected Vector4 _texCoords;
public Texture2D Texture => _texture;
public Vector4 TexCoords => _texCoords;
public this(Texture2D texture) : this(_texture, .(0, 0, 1, 1)) { }
public this(Texture2D texture, Int2 topLeft, Int2 size) :
this(texture,
{
Vector2 texSize = Vector2(texture.Width, texture.Height);
Vector4 texCoords = Vector4((Vector2)topLeft, (Vector2)size) / texSize.XYXY;
texCoords
}) { }
public this(Texture2D texture, Vector2 topLeft, Vector2 size) : this(texture, Vector4(topLeft, size)) { }
public this(Texture2D texture, Vector4 texCoords)
{
_texture = texture..AddRef();
_texCoords = texCoords;
}
public static SubTexture2D CreateFromGrid(Texture2D texture, Vector2 coords, Vector2 gridSize, Vector2 spriteSize = .One)
{
Vector2 textureSize = .(texture.Width, texture.Height);
Vector4 uv = .(coords * gridSize, gridSize * spriteSize) / textureSize.XYXY;
return new SubTexture2D(texture, uv);
}
}
}
+13 -13
View File
@@ -141,14 +141,6 @@ namespace GlitchyEngine.Renderer.Text
Log.EngineLogger.Assert(res.Success, scope $"Set_Pixel_Sizes failed({(int)res}): {res}");
}
// HarfBuzz
{
Debug.Profiler.ProfileResourceScope!("hb_ft_font_create_referenced");
_harfBuzzFont = hb_ft_font_create_referenced(_face);
hb_font_set_scale(_harfBuzzFont, (.)fontSize * 64, (.)fontSize * 64);
}
double unitsPerEm = F26Dot6ToDouble(_face.units_per_EM);
_geometryScaler = _fontSize / unitsPerEm;
@@ -163,6 +155,14 @@ namespace GlitchyEngine.Renderer.Text
LoadGlyphs(firstChar, charCount);
// HarfBuzz
{
Debug.Profiler.ProfileResourceScope!("hb_ft_font_create_referenced");
_harfBuzzFont = hb_ft_font_create_referenced(_face);
hb_font_set_scale(_harfBuzzFont, (.)fontSize * 64, (.)fontSize * 64);
}
//TestMSDF();
}
@@ -185,17 +185,17 @@ namespace GlitchyEngine.Renderer.Text
}
/// Returns the font that can draw the char
internal Font GetDrawingFont(char32 char)
static internal Font GetDrawingFont(char32 char, Font font)
{
uint32 glyphId = FreeType.Get_Char_Index(_face, char);
uint32 glyphId = FreeType.Get_Char_Index(font._face, char);
if (glyphId != 0)
{
return this;
return font;
}
else if (Fallback != null)
else if (font.Fallback != null)
{
return Fallback.GetDrawingFont(char);
return GetDrawingFont(char, font.Fallback);
}
else
{
@@ -193,7 +193,7 @@ namespace GlitchyEngine.Renderer.Text
hb_buffer_set_script(buf, .HB_SCRIPT_LATIN);
hb_buffer_set_language(buf, hb_language_from_string("en".CStr(), -1));
hb_shape(currentFont._harfBuzzFont, buf, null, 0);
hb_shape(font._harfBuzzFont, buf, null, 0);
// 5. Get the glyph and position information.
@@ -209,7 +209,7 @@ namespace GlitchyEngine.Renderer.Text
hb_position_t x_advance = glyph_pos[i].x_advance;
hb_position_t y_advance = glyph_pos[i].y_advance;
PreparedGlyph glyph = .(currentFont, glyphid, .(penPosition, baseline), fontScale);//, x_advance / 64, y_advance / 64);
PreparedGlyph glyph = .(font, glyphid, .(penPosition, baseline), fontScale);//, x_advance / 64, y_advance / 64);
preparedText.Glyphs.Add(glyph);
@@ -277,9 +277,9 @@ namespace GlitchyEngine.Renderer.Text
}
// Get the font that can draw the char. Use the given font if no fallback is found (will draw the "missing glyph").
Font charFont = currentFont.GetDrawingFont(char) ?? font;
Font charFont = Font.GetDrawingFont(char, font) ?? font;
if (charFont != currentFont)
if (charFont != font)
{
FlushShapeBuffer();
+29 -43
View File
@@ -29,6 +29,16 @@ namespace GlitchyEngine.Renderer
public abstract uint32 Depth {get;}
public abstract uint32 ArraySize {get;}
public abstract uint32 MipLevels {get;}
public void Bind(uint32 slot = 0)
{
ImplBind(slot);
if(_samplerState != null)
_samplerState.Bind(slot);
}
protected extern void ImplBind(uint32 slot);
}
public struct Texture2DDesc
@@ -59,11 +69,11 @@ namespace GlitchyEngine.Renderer
{
protected String _path ~ delete _;
//public override extern uint32 Width {get;}
//public override extern uint32 Height {get;}
public override extern uint32 Width {get;}
public override extern uint32 Height {get;}
public override uint32 Depth => 1;
//public override extern uint32 ArraySize {get;}
//public override extern uint32 MipLevels {get;}
public override extern uint32 ArraySize {get;}
public override extern uint32 MipLevels {get;}
public this(StringView path)
{
@@ -78,12 +88,12 @@ namespace GlitchyEngine.Renderer
{
Debug.Profiler.ProfileResourceFunction!();
Stream data = Application.Get().ContentManager.GetFile(_path);
defer delete data;
FileStream fs = new FileStream();
var readResult = data.Read<char8[8]>();
fs.Open(_path, .Read);
var readResult = fs.Read<char8[8]>();
data.Position = 0;
delete fs;
char8[8] magicWord;
@@ -93,11 +103,11 @@ namespace GlitchyEngine.Renderer
if (strView.StartsWith(PngMagicWord))
{
LoadPng(data);
LoadPng();
}
else if (strView.StartsWith(DdsMagicWord))
{
LoadDds(data);
LoadTexturePlatform();
}
else
{
@@ -106,23 +116,14 @@ namespace GlitchyEngine.Renderer
}
}
protected void LoadPng(Stream stream)
protected void LoadPng()
{
Debug.Profiler.ProfileResourceFunction!();
uint8[] pngData = new:ScopedAlloc! uint8[stream.Length];
var result = stream.TryRead(pngData);
if (result case .Err(let err))
{
Log.EngineLogger.Error($"Failed to read data from stream. Texture: \"{_path}\", Error: {err}");
}
uint8* rawData = ?;
uint32 width = 0, height = 0;
uint32 errorCode = LodePng.LodePng.Decode32(&rawData, &width, &height, pngData.Ptr, (.)pngData.Count);
uint32 errorCode = LodePng.LodePng.Decode32File(&rawData, &width, &height, _path.CStr());
Debug.Assert(errorCode == 0, "Failed to load png File");
@@ -137,11 +138,6 @@ namespace GlitchyEngine.Renderer
LodePng.LodePng.Free(rawData);
}
protected void LoadDds(Stream stream)
{
LoadDdsPlatform(stream);
}
public this(Texture2DDesc desc)
{
PrepareTexturePlatform(desc, false);
@@ -162,7 +158,7 @@ namespace GlitchyEngine.Renderer
uint32 mipLevels = 1, uint32 arraySize = 1, Usage usage = .Default, CPUAccessFlags cpuAccess = .None
*/
protected extern void LoadDdsPlatform(Stream stream);
protected extern void LoadTexturePlatform();
protected extern void CreateTexturePlatform(Texture2DDesc desc, bool isRenderTarget, void* data, uint32 linePitch);
@@ -191,28 +187,18 @@ namespace GlitchyEngine.Renderer
{
protected String _path ~ delete _;
// public override extern uint32 Width {get;}
// public override extern uint32 Height {get;}
public override extern uint32 Width {get;}
public override extern uint32 Height {get;}
public override uint32 Depth => 1;
// public override extern uint32 ArraySize {get;}
// public override extern uint32 MipLevels {get;}
public override extern uint32 ArraySize {get;}
public override extern uint32 MipLevels {get;}
public this(String path)
{
this._path = new String(path);
LoadTexture();
}
private void LoadTexture()
{
Debug.Profiler.ProfileResourceFunction!();
Stream data = Application.Get().ContentManager.GetFile(_path);
defer delete data;
LoadTexturePlatform(data);
LoadTexturePlatform();
}
protected extern void LoadTexturePlatform(Stream stream);
protected extern void LoadTexturePlatform();
}
}
@@ -7,5 +7,7 @@ namespace GlitchyEngine.Renderer
[AllowAppend]
public this(String source, String entryPoint, ShaderDefine[] macros = null)
: base(source, entryPoint, macros) { }
public override extern void CompileFromSource(String code, String entryPoint, ShaderDefine[] macros = null);
}
}
-121
View File
@@ -1,121 +0,0 @@
using System;
using ImGui;
using System.Collections;
using System.IO;
using Bon;
namespace GlitchyEngine
{
interface ISettings
{
void Apply();
}
/// Fields with this Attribute will be scanned for Settings.
[AttributeUsage(.Field, .ReflectAttribute)]
struct SettingContainerAttribute : Attribute
{
}
/// Fields with this Attribute will be exposed as settings.
[AttributeUsage(.Field, .ReflectAttribute)]
struct SettingAttribute : Attribute
{
public String Category;
public String Name;
public this(String category, String name)
{
Category = category;
Name = name;
}
}
[Reflect, BonTarget]
class Settings
{
#if IMGUI
[SettingContainer, BonInclude]
public readonly ImGuiSettings ImGuiSettings = new .() ~ delete _;
#endif
/*
[BonInclude]
private List<ISettings> _userSettings ~ ClearAndDeleteItems!(_);
*/
[AllowAppend]
public this()
{
/*List<ISettings> userSettings = append .();
_userSettings = userSettings;*/
}
public void Apply()
{
#if IMGUI
ImGuiSettings.Apply();
#endif
/*for (let settings in _userSettings)
{
settings.Apply();
}*/
}
public static void Load()
{
Settings settings = Application.Get().Settings;
var result = Bon.DeserializeFromFile(ref settings, "./settings.bon");
if (result case .Err)
Log.EngineLogger.Error("Failed to deserialze settings.");
Application.Get().Settings.Apply();
}
public void Save()
{
gBonEnv.serializeFlags |= .Verbose;
Bon.SerializeIntoFile(this, "./settings.bon");
}
/*
/// Registers a instance of a settings interface. Note: Takes ownership of the instance.
public void RegisterUserSettings(ISettings settings)
{
_userSettings.Add(settings);
}
public T GetUserSettings<T>() where T : ISettings, class
{
for (let v in _userSettings)
{
if (v is T)
{
return (T)v;
}
}
return null;
}*/
}
#if IMGUI
[Reflect]
class ImGuiSettings
{
[Setting("UI", "Font Size"), BonInclude]
public int32 FontSize = 14;
[Setting("UI", "Font name"), BonInclude]
public readonly String FontName = new .("Fonts/CascadiaCode.ttf") ~ delete _;
public void Apply()
{
Application.Get().[Friend]_imGuiLayer.SettingsInvalid = true;
}
}
#endif
}
-355
View File
@@ -1,355 +0,0 @@
using GlitchyEngine.Math;
using GlitchyEngine.Renderer;
using System;
namespace GlitchyEngine.World
{
[AttributeUsage(.Struct, .ReflectAttribute, ReflectUser=.Methods | .NonStaticFields)]
struct ComponentAttribute : Attribute
{
public String Name;
public this(String name)
{
Name = name;
}
}
/// If an entity has the EditorComponent it won't be displayed in the scene hierarchy.
struct EditorComponent
{
bool b = false;
public this()
{
}
}
[Component("Sprite Renderer")]
struct SpriterRendererComponent : IDisposableComponent
{
public Texture2D Sprite = null;
public ColorRGBA Color = .White;
public this()
{
}
public this(ColorRGBA color)
{
Color = color;
}
public void Dispose()
{
Sprite?.ReleaseRef();
}
}
struct SceneCamera : Camera
{
public enum ProjectionType
{
case Orthographic = 0;//(float Height, float NearPlane, float FarPlane);
case Perspective = 1;//(float FovY, float NearPlane, float FarPlane);
case InfinitePerspective = 2;//(float FovY, float NearPlane);
}
private float _perspectiveFovY = MathHelper.ToRadians(75f);
private float _perspectiveNearPlane = 0.1f;
private float _perspectiveFarPlane = 10000.0f;
private float _orthographicHeight = 10.0f;
private float _orthographicNearPlane = 0.0f;
private float _orthographicFarPlane = 10.0f;
private float _aspectRatio = 16.0f / 9.0f;
private bool _fixedAspectRatio = false;
private ProjectionType _projectionType = .InfinitePerspective;//(MathHelper.ToRadians(75f), 0.1f);
public ProjectionType ProjectionType
{
get => _projectionType;
set mut
{
_projectionType = value;
CalculateProjection();
}
}
public float PerspectiveFovY
{
get => _perspectiveFovY;
set mut
{
if (_perspectiveFovY == value)
return;
_perspectiveFovY = value;
CalculateProjection();
}
}
public float PerspectiveNearPlane
{
get => _perspectiveNearPlane;
set mut
{
if (_perspectiveNearPlane == value)
return;
_perspectiveNearPlane = value;
CalculateProjection();
}
}
public float PerspectiveFarPlane
{
get => _perspectiveFarPlane;
set mut
{
if (_perspectiveFarPlane == value)
return;
_perspectiveFarPlane = value;
CalculateProjection();
}
}
public float OrthographicHeight
{
get => _orthographicHeight;
set mut
{
if (_orthographicHeight == value)
return;
_orthographicHeight = value;
CalculateProjection();
}
}
public float OrthographicNearPlane
{
get => _orthographicNearPlane;
set mut
{
if (_orthographicNearPlane == value)
return;
_orthographicNearPlane = value;
CalculateProjection();
}
}
public float OrthographicFarPlane
{
get => _orthographicFarPlane;
set mut
{
if (_orthographicFarPlane == value)
return;
_orthographicFarPlane = value;
CalculateProjection();
}
}
public float AspectRatio
{
get => _aspectRatio;
set mut
{
if (_aspectRatio == value)
return;
_aspectRatio = value;
CalculateProjection();
}
}
public bool FixedAspectRatio
{
get => _fixedAspectRatio;
set mut
{
if (_fixedAspectRatio == value)
return;
_fixedAspectRatio = value;
CalculateProjection();
}
}
private const Matrix mat = Matrix.InfinitePerspectiveProjection(MathHelper.ToRadians(75f), 1.0f, 0.1f);
public this()
{
CalculateProjection();
}
public void SetOrthographic(float height, float nearPlane, float farPlane) mut
{
_projectionType = .Orthographic;//(height, nearPlane, farPlane);
_orthographicHeight = height;
_orthographicNearPlane = nearPlane;
_orthographicFarPlane = farPlane;
CalculateProjection();
}
public void SetPerspective(float fovY, float nearPlane, float farPlane) mut
{
_projectionType = .Perspective;//(fovY, nearPlane, farPlane);
_perspectiveFovY = fovY;
_perspectiveNearPlane = nearPlane;
_perspectiveFarPlane = farPlane;
CalculateProjection();
}
public void SetInfinitePerspective(float fovY, float nearPlane) mut
{
_projectionType = .InfinitePerspective;//(fovY, nearPlane);
_perspectiveFovY = fovY;
_perspectiveNearPlane = nearPlane;
//_perspectiveFarPlane = farPlane;
CalculateProjection();
}
public void SetViewportSize(uint32 width, uint32 height) mut
{
_aspectRatio = (float)width / (float)height;
CalculateProjection();
}
private void CalculateProjection() mut
{
if (_projectionType case .Orthographic)
{
float halfHeight = _orthographicHeight / 2.0f;
float halfWidth = halfHeight * _aspectRatio;
_projection = Matrix.OrthographicProjectionOffCenter(-halfWidth, halfWidth, halfHeight, -halfHeight,
_orthographicNearPlane, _orthographicFarPlane);
}
else if (_projectionType case .Perspective)
{
_projection = Matrix.PerspectiveProjection(_perspectiveFovY, _aspectRatio, _perspectiveNearPlane, _perspectiveFarPlane);
}
else if (_projectionType case .InfinitePerspective)
{
_projection = Matrix.InfinitePerspectiveProjection(_perspectiveFovY, _aspectRatio, _perspectiveNearPlane);
}
}
}
struct CameraComponent
{
public SceneCamera Camera;
public bool Primary = true; // Todo: probably move into scene
public bool FixedAspectRatio = false;
public this()
{
Camera = .();
}
}
struct NativeScriptComponent : IDisposableComponent
{
public ScriptableEntity Instance = null;
public function void (mut NativeScriptComponent this) Func;
public function ScriptableEntity () InstantiateFunction;
public function void (NativeScriptComponent* self) DestroyInstanceFunction;
public void Bind<T>() mut where T : ScriptableEntity
{
InstantiateFunction = () =>
{
return new T();
};
DestroyInstanceFunction = (self) =>
{
delete self.Instance;
};
}
public void Dispose() mut
{
DestroyInstanceFunction(&this);
}
}
struct DotNetScriptComponent : IDisposableComponent
{
public struct Instance : int {}
public Instance InstanceHandlePtr = 0;
private String TypeName = null;
typealias CreateInstanceDelegate = function Instance(void* typeNamePtr, int32 typeNameLength, EcsEntity entity, void* scene);
typealias UpdateInstanceDelegate = function void(Instance instance, uint64 frameCount, TimeSpan totalTime, TimeSpan frameTime);
typealias DestroyInstanceDelegate = function void(Instance instance);
public static CreateInstanceDelegate CreateInstanceFn;
public static UpdateInstanceDelegate UpdateInstanceFn;
public static DestroyInstanceDelegate DestroyInstanceFn;
public const Self ss = Self();
public void Bind(StringView dotNetAssemblyQualifiedTypeName) mut
{
TypeName = new String(dotNetAssemblyQualifiedTypeName);
}
internal void CreateInstance(EcsEntity entity, Scene scene) mut
{
void* scenePtr = Internal.UnsafeCastToPtr(scene);
InstanceHandlePtr = CreateInstanceFn(TypeName.Ptr, (int32)TypeName.Length, entity, scenePtr);
}
internal void UpdateInstance(GameTime gameTime)
{
UpdateInstanceFn(InstanceHandlePtr, gameTime.FrameCount, gameTime.TotalTime, gameTime.FrameTime);
}
internal void DestroyInstance()
{
DestroyInstanceFn(InstanceHandlePtr);
}
public void Dispose() mut
{
delete TypeName;
}
[Export(), LinkName("GE_DoStuff")]
public static int32 DoStuff()
{
return 69;
}
[Export, LinkName("GE_DotNetScript_GetComponent")]
private static void* GetComponent(EcsEntity entity, void* scenePtr)
{
Scene scene = (Scene)Internal.UnsafeCastToObject(scenePtr);
Entity e = .(entity, scene);
TransformComponent* ptr = e.GetComponent<TransformComponent>();
return ptr;
}
}
}
-30
View File
@@ -1,30 +0,0 @@
using System;
using internal GlitchyEngine.World;
namespace GlitchyEngine.World
{
public struct EcsEntity : uint64
{
// Binary Format:
// Bits: [0 - 31] [32 - 64]
// Data: Version Index
[Inline]
internal uint32 Version => (uint32)this;
[Inline]
internal uint32 Index => (uint32)(this >> 32);
[Inline]
static internal EcsEntity CreateEntityID(uint32 index, uint32 version)
{
return ((uint64)index << 32) | version;
}
[Inline]
internal bool IsValid => Index != InvalidEntity.Index;
public const EcsEntity InvalidEntity = CreateEntityID(uint32.MaxValue, 0);
}
}
+22 -40
View File
@@ -10,7 +10,7 @@ namespace GlitchyEngine.World
{
const int MaxEntities = 1024;
internal typealias BitmaskEntry = (EcsEntity ID, BitArray ComponentMask);
internal typealias BitmaskEntry = (Entity ID, BitArray ComponentMask);
internal List<BitmaskEntry> _entities = new .();
List<uint32> _freeIndices = new List<uint32>() ~ delete _;
@@ -40,11 +40,11 @@ namespace GlitchyEngine.World
delete _componentPools;
}
/**
* Registers a new Component.
*/
public void Register<T>() where T: struct, new
public void Register<T>() where T: struct
{
uint32 id = (uint32)_componentPools.Count;
ComponentPool<T> componentPool = new ComponentPool<T>(MaxEntities);
@@ -55,7 +55,7 @@ namespace GlitchyEngine.World
/**
* Registers a new Component.
*/
public void Register<T>() where T: struct, new, IDisposableComponent
public void Register<T>() where T: struct, IDisposableComponent
{
uint32 id = (uint32)_componentPools.Count;
ComponentPool<T> componentPool = new ComponentPool<T>(MaxEntities);
@@ -88,23 +88,23 @@ namespace GlitchyEngine.World
/**
* Creates a new Entity and returns its ID.
*/
public EcsEntity NewEntity()
public Entity NewEntity()
{
EcsEntity entity;
Entity entity;
// Reuse freed entity slot
if(_freeIndices.Count > 0)
{
uint32 index = _freeIndices.PopBack();
entity = EcsEntity.CreateEntityID(index, _entities[index].ID.Version);
entity = Entity.CreateEntityID(index, _entities[index].ID.Version);
_entities[index].ID = entity;
}
// Create new entity slot
else
{
entity = EcsEntity.CreateEntityID((.)_entities.Count, 0);
entity = Entity.CreateEntityID((.)_entities.Count, 0);
_entities.Add((entity, new BitArray(_componentPools.Count)));
}
@@ -114,7 +114,7 @@ namespace GlitchyEngine.World
/**
* Removes the specified Entity from the World.
*/
public void RemoveEntity(EcsEntity entity)
public void RemoveEntity(Entity entity)
{
var listEntity = ref _entities[entity.Index];
if(entity != listEntity.ID)
@@ -123,7 +123,7 @@ namespace GlitchyEngine.World
DisposeComponents(listEntity);
// Invalidate entry and increment version
listEntity.ID = EcsEntity.CreateEntityID(EcsEntity.InvalidEntity.Index, entity.Version + 1);
listEntity.ID = Entity.CreateEntityID(Entity.InvalidEntity.Index, entity.Version + 1);
_entities[entity.Index].ComponentMask.Clear();
_freeIndices.Add(entity.Index);
@@ -152,7 +152,7 @@ namespace GlitchyEngine.World
/**
* Assigns a component of type T to the specified entity and returns it.
*/
public T* AssignComponent<T>(EcsEntity entity, T value = T()) where T : struct, new
public T* AssignComponent<T>(Entity entity) where T : struct, new
{
if(entity.Index > _entities.Count)
return null;
@@ -165,12 +165,8 @@ namespace GlitchyEngine.World
ComponentPoolEntry entry;
if(!_componentPools.TryGetValue(typeof(T), out entry))
{
Register<T>();
entry = _componentPools[typeof(T)];
//Log.EngineLogger.AssertDebug(false, scope $"Tried to assign unregistered component type {typeof(T)}");
//return null;
Log.EngineLogger.AssertDebug(false, scope $"Tried to assign unregistered component type {typeof(T)}");
return null;
}
// TODO: is it a problem to assign a component again?
@@ -181,7 +177,7 @@ namespace GlitchyEngine.World
T* component = (T*)entry.Pool.Get(entity.Index);
*component = value;
*component = T();
return component;
}
@@ -189,7 +185,7 @@ namespace GlitchyEngine.World
/**
* Removes a component of type T from the specified entity.
*/
public void RemoveComponent<T>(EcsEntity entity) where T : struct, new
public void RemoveComponent<T>(Entity entity) where T : struct
{
if(entity.Index > _entities.Count)
return;
@@ -209,7 +205,7 @@ namespace GlitchyEngine.World
listEntity.ComponentMask[entry.Id] = false;
}
public void RemoveComponent<T>(EcsEntity entity) where T : struct, new, IDisposableComponent
public void RemoveComponent<T>(Entity entity) where T : struct, IDisposableComponent
{
if(entity.Index > _entities.Count)
return;
@@ -232,21 +228,7 @@ namespace GlitchyEngine.World
DisposeComponent<T>(entry.Pool.Get(entity.Index));
}
/// Returns whether or not the given entity has the specified component.
public bool HasComponent<T>(EcsEntity entity) where T : struct, new
{
var listEntity = ref _entities[entity.Index];
if(entity != listEntity.ID)
return false;
ComponentPoolEntry entry;
if(!_componentPools.TryGetValue(typeof(T), out entry))
return false;
return listEntity.ComponentMask[entry.Id];
}
public T* GetComponent<T>(EcsEntity entity) where T : struct, new
public T* GetComponent<T>(Entity entity) where T : struct
{
var listEntity = ref _entities[entity.Index];
if(entity != listEntity.ID)
@@ -262,7 +244,7 @@ namespace GlitchyEngine.World
return (.)entry.Pool.Get(entity.Index);
}
public WorldEnumerator Enumerate(params Type[] componentTypes)
{
return WorldEnumerator(this, componentTypes);
@@ -297,7 +279,7 @@ namespace GlitchyEngine.World
world.Register<TransformComponent>();
EcsEntity entity = world.NewEntity();
Entity entity = world.NewEntity();
TransformComponent* myComp = world.AssignComponent<TransformComponent>(entity);
myComp.LocalTransform = Matrix.Identity;
@@ -307,7 +289,7 @@ namespace GlitchyEngine.World
world.RemoveComponent<TransformComponent>(entity);
EcsEntity entity2 = world.NewEntity();
Entity entity2 = world.NewEntity();
world.AssignComponent<TransformComponent>(entity2);
world.RemoveEntity(entity);
@@ -348,7 +330,7 @@ namespace GlitchyEngine.World
// Test dispose on component removal
{
// Create entity with disposable component.
EcsEntity entity = world.NewEntity();
Entity entity = world.NewEntity();
var component = world.AssignComponent<TestDisposingComponent>(entity);
component.IsDisposed = false;
@@ -360,7 +342,7 @@ namespace GlitchyEngine.World
// Test dispose on entity removal
{
// Create entity with disposable component.
EcsEntity entity = world.NewEntity();
Entity entity = world.NewEntity();
var component = world.AssignComponent<TestDisposingComponent>(entity);
component.IsDisposed = false;
+16 -118
View File
@@ -1,132 +1,30 @@
using System;
using System.Collections;
using internal GlitchyEngine.World;
namespace GlitchyEngine.World
{
public struct Entity
{
private EcsEntity _entity = .InvalidEntity;
public struct Entity : uint64
{
// Binary Format:
// Bits: [0 - 31] [32 - 64]
// Data: Version Index
private Scene _scene = null;
[Inline]
internal uint32 Version => (uint32)this;
public EcsEntity Handle => _entity;
public Scene Scene => _scene;
public this()
[Inline]
internal uint32 Index => (uint32)(this >> 32);
[Inline]
static internal Entity CreateEntityID(uint32 index, uint32 version)
{
}
public this(EcsEntity entity, Scene scene)
{
_entity = entity;
_scene = scene;
}
public ChildEnumerator EnumerateChildren => .(this);
public bool IsValid => _entity.IsValid;
public Entity? Parent
{
get
{
var cmp = GetComponent<TransformComponent>();
if (cmp.Parent == .InvalidEntity)
return null;
return .(cmp.Parent, _scene);
}
set
{
if (value == null)
{
var cmp = GetComponent<TransformComponent>();
cmp.Parent = .InvalidEntity;
}
else
{
Entity parent = value.Value;
if (parent.Scene != _scene)
{
Log.EngineLogger.AssertDebug(false);
return;
}
var cmp = GetComponent<TransformComponent>();
cmp.Parent = parent._entity;
}
}
}
public T* AddComponent<T>(T value = T()) where T: struct, new
{
Log.EngineLogger.AssertDebug(!HasComponent<T>(), scope $"Entity already has component.");
T* component = _scene._ecsWorld.AssignComponent<T>(_entity, value);
_scene.[Friend]OnComponentAdded(this, typeof(T), component);
return component;
}
public T* GetComponent<T>() where T: struct, new
{
Log.EngineLogger.AssertDebug(HasComponent<T>(), "Entity doesn't have component!");
return _scene._ecsWorld.GetComponent<T>(_entity);
return ((uint64)index << 32) | version;
}
public bool HasComponent<T>() where T: struct, new
{
return _scene._ecsWorld.HasComponent<T>(_entity);
}
public void RemoveComponent<T>() where T: struct, new
{
Log.EngineLogger.AssertDebug(HasComponent<T>(), "Entity doesn't have component!");
[Inline]
internal bool IsValid => Index != InvalidEntity.Index;
_scene._ecsWorld.RemoveComponent<T>(_entity);
}
public struct ChildEnumerator : IEnumerator<Entity>, IDisposable
{
private WorldEnumerator<TransformComponent> _transformEnum;
private EcsEntity _entity;
private Entity _currentChild;
public this(Entity entity)
{
_entity = entity.Handle;
_transformEnum = entity.Scene._ecsWorld.Enumerate<TransformComponent>();
_currentChild = .(.InvalidEntity, entity.Scene);
}
public Entity Current => _currentChild;
public Result<Entity> GetNext() mut
{
while (true)
{
(EcsEntity entity, TransformComponent* transform) = Try!(_transformEnum.GetNext());
if (transform.Parent == _entity)
{
_currentChild.[Friend]_entity = entity;
return .Ok(_currentChild);
}
}
}
public void Dispose()
{
_transformEnum.Dispose();
}
}
public const Entity InvalidEntity = ((uint64)uint32.MaxValue << 32) | 0;//TODO: Report bug: CreateEntityID(uint32.MaxValue, 0);
}
}
+1 -1
View File
@@ -5,6 +5,6 @@ namespace GlitchyEngine.World
*/
public struct ParentComponent
{
public EcsEntity Entity;
public Entity Entity;
}
}
-148
View File
@@ -1,148 +0,0 @@
using GlitchyEngine.Math;
using GlitchyEngine.Renderer;
using System;
using System.Collections;
namespace GlitchyEngine.World
{
using internal ScriptableEntity;
class Scene
{
internal EcsWorld _ecsWorld = new .() ~ delete _;
private Dictionary<Type, function void(Entity entity, Type componentType, void* component)> _onComponentAddedHandlers = new .() ~ delete _;
public this()
{
Entity entity = CreateEntity("Green Quad");
entity.AddComponent<SpriterRendererComponent>(.(ColorRGBA(0.2f, 0.9f, 0.15f)));
Entity entity2 = CreateEntity("Red Square");
var v = entity2.AddComponent<SpriterRendererComponent>(.(ColorRGBA(0.95f, 0.1f, 0.3f)));
v.Sprite = new Texture2D("Textures/rocket.dds");
v.Sprite.SamplerState = SamplerStateManager.PointClamp;
_onComponentAddedHandlers.Add(typeof(CameraComponent), (e, t, c) => {
CameraComponent* cameraComponent = (.)c;
cameraComponent.Camera.SetViewportSize(e.Scene.ViewportWidth, e.Scene.ViewportHeight);
});
Entity dotNetEntity = CreateEntity("DotNet rocks!");
dotNetEntity.AddComponent<SpriterRendererComponent>(.(Color(81, 43, 212)));
var vv = dotNetEntity.AddComponent<DotNetScriptComponent>();
vv.Bind("DotNetScriptingHelper.TestEntityScript, DotNetScriptingHelper");
}
public ~this()
{
}
public void Update(GameTime gameTime)
{
TransformSystem.Update(_ecsWorld);
for (var (entity, script) in _ecsWorld.Enumerate<NativeScriptComponent>())
{
if (script.Instance == null)
{
script.Instance = script.InstantiateFunction();
script.Instance._entity = Entity(entity, this);
script.Instance.[Friend]OnCreate();
}
script.Instance.[Friend]OnUpdate(gameTime);
}
for (var (entity, script) in _ecsWorld.Enumerate<DotNetScriptComponent>())
{
if (script.InstanceHandlePtr == 0)
{
script.[Friend]CreateInstance(entity, this);
}
script.[Friend]UpdateInstance(gameTime);
}
Camera* primaryCamera = null;
Matrix primaryCameraTransform = default;
for (var (entity, transform, camera) in _ecsWorld.Enumerate<TransformComponent, CameraComponent>())
{
if (camera.Primary)
{
primaryCamera = &camera.Camera;
primaryCameraTransform = transform.WorldTransform;
}
}
// Sprite renderer
if (primaryCamera != null)
{
Renderer2D.BeginScene(*primaryCamera, primaryCameraTransform);
for (var (entity, transform, sprite) in _ecsWorld.Enumerate<TransformComponent, SpriterRendererComponent>())
{
Renderer2D.DrawQuad(transform.WorldTransform, sprite.Sprite, sprite.Color);
}
Renderer2D.EndScene();
}
}
/// Creates a new Entity with the given name.
public Entity CreateEntity(String name = "")
{
Entity entity = Entity(_ecsWorld.NewEntity(), this);
entity.AddComponent<TransformComponent>();
let nameComponent = entity.AddComponent<DebugNameComponent>();
nameComponent.SetName(name.IsEmpty ? "Entity" : name);
return entity;
}
/** Deletes the given entity.
* @param entity The entity to delete.
* @param destroyChildren If set to true all children of entity will be destroyed.
*/
public void DestroyEntity(Entity entity, bool destroyChildren = false)
{
if (destroyChildren)
{
for (Entity child in entity.EnumerateChildren)
{
DestroyEntity(child, true);
}
}
_ecsWorld.RemoveEntity(entity.Handle);
}
private uint32 ViewportWidth, ViewportHeight;
/// Sets the size of the viewport into which the scene will be rendered.
public void OnViewportResize(uint32 width, uint32 height)
{
ViewportWidth = width;
ViewportHeight = height;
for (var (entity, cameraComponent) in _ecsWorld.Enumerate<CameraComponent>())
{
if (!cameraComponent.FixedAspectRatio)
{
cameraComponent.Camera.SetViewportSize(width, height);
}
}
}
private void OnComponentAdded(Entity entity, Type componentType, void* component)
{
if (_onComponentAddedHandlers.TryGetValue(componentType, let handler))
{
handler(entity, componentType, component);
}
}
}
}
@@ -1,33 +0,0 @@
namespace GlitchyEngine.World
{
class ScriptableEntity
{
internal Entity _entity;
protected TransformComponent* transform => GetComponent<TransformComponent>();
public T* AddComponent<T>(T value = T()) where T: struct, new
{
return _entity.AddComponent<T>(value);
}
public T* GetComponent<T>() where T: struct, new
{
return _entity.GetComponent<T>();
}
public bool HasComponent<T>() where T: struct, new
{
return _entity.HasComponent<T>();
}
public void RemoveComponent<T>() where T: struct, new
{
_entity.RemoveComponent<T>();
}
protected virtual void OnCreate() {}
protected virtual void OnDestroy() {}
protected virtual void OnUpdate(GameTime gt) {}
}
}
+13 -41
View File
@@ -1,18 +1,12 @@
using System;
using GlitchyEngine.Math;
namespace GlitchyEngine.World
{
[Ordered]
public struct TransformComponent
{
EcsEntity _parent = .InvalidEntity;
Vector3 _position = .(0, 0, 0);
Quaternion _rotation = .(0, 0, 0, 1);
Vector3 _scale = .(1, 1, 1);
Vector3 _editorRotationEuler = .Zero;
Vector3 _position = .Zero;
Quaternion _rotation = .Identity;
Vector3 _scale = .One;
Matrix _localTransform = .Identity;
public bool IsDirty = false;
@@ -22,19 +16,6 @@ namespace GlitchyEngine.World
/// The frame when the transform was recalculated
public uint Frame;
public EcsEntity Parent
{
get => _parent;
set mut
{
if (_parent == value)
return;
_parent = value;
IsDirty = true;
}
}
public Matrix LocalTransform
{
get => _localTransform;
@@ -74,24 +55,6 @@ namespace GlitchyEngine.World
_rotation = value;
IsDirty = true;
_editorRotationEuler = Quaternion.ToEulerAngles(_rotation);
}
}
/// Allows the user to edit the euler angles in the editor without rotations getting funky because of singularities or ambiguity of angles.
internal Vector3 EditorRotationEuler
{
get => _editorRotationEuler;
set mut
{
if (_editorRotationEuler == value)
return;
_editorRotationEuler = value;
_rotation = Quaternion.FromEulerAngles(_editorRotationEuler.Y, _editorRotationEuler.X, _editorRotationEuler.Z);
IsDirty = true;
}
}
@@ -102,7 +65,16 @@ namespace GlitchyEngine.World
public Vector3 RotationEuler
{
get => Quaternion.ToEulerAngles(_rotation);
set mut => Rotation = Quaternion.FromEulerAngles(value.Y, value.X, value.Z);
set mut
{
Quaternion quat = Quaternion.FromEulerAngles(value.Y, value.X, value.Z);
if(_rotation == quat)
return;
_rotation = quat;
IsDirty = true;
}
}
/**
+8 -6
View File
@@ -16,7 +16,7 @@ namespace GlitchyEngine.World
}
}
private static void UpdateEntity(EcsEntity entity, TransformComponent* transform, EcsWorld world)
private static void UpdateEntity(Entity entity, TransformComponent* transform, EcsWorld world)
{
// Todo: test scaling with deep hierarchies!
@@ -26,7 +26,7 @@ namespace GlitchyEngine.World
transform.Frame = _frame;
//var parent = world.GetComponent<ParentComponent>(entity);
var parent = world.GetComponent<ParentComponent>(entity);
if(transform.IsDirty)
{
@@ -35,16 +35,18 @@ namespace GlitchyEngine.World
transform.IsDirty = false;
if(transform.Parent == EcsEntity.InvalidEntity)
if(parent == null)
{
transform.WorldTransform = transform.LocalTransform;
}
}
if(transform.Parent != EcsEntity.InvalidEntity)
if(parent != null)
{
var parentTransform = world.GetComponent<TransformComponent>(transform.Parent);
UpdateEntity(transform.Parent, parentTransform, world);
var parentEntity = parent.Entity;
var parentTransform = world.GetComponent<TransformComponent>(parentEntity);
UpdateEntity(parentEntity, parentTransform, world);
// TODO: I think we unnecessarily recalculate world transform every frame
// Parent transform is newer than our transform or was updated this frame
+16 -16
View File
@@ -6,7 +6,7 @@ using internal GlitchyEngine.World;
namespace GlitchyEngine.World
{
public struct WorldEnumerator : IEnumerator<EcsEntity>, IDisposable
public struct WorldEnumerator : IEnumerator<Entity>, IDisposable
{
internal EcsWorld _world;
internal BitArray _bitMask;
@@ -32,19 +32,19 @@ namespace GlitchyEngine.World
}
else
{
//Log.EngineLogger.AssertDebug(false, "Queried component is not registered for this world. This is invalid because the query would never return any results.");
Log.EngineLogger.AssertDebug(false, "Queried component is not registered for this world. This is invalid because the query would never return any results.");
}
}
}
public Result<EcsEntity> GetNext() mut
public Result<Entity> GetNext() mut
{
while(_currentEntry < _endEntry)
{
EcsWorld.BitmaskEntry* entry = _currentEntry++;
// Skip deleted entities
if(entry.ID.Index == EcsEntity.InvalidEntity.Index)
if(entry.ID.Index == Entity.InvalidEntity.Index)
continue;
// Check whether or not mask matches
@@ -61,7 +61,7 @@ namespace GlitchyEngine.World
}
}
public struct WorldEnumerator<TComponent> : WorldEnumerator, IEnumerator<(EcsEntity Entity, TComponent* Component)> where TComponent : struct
public struct WorldEnumerator<TComponent> : WorldEnumerator, IEnumerator<(Entity Entity, TComponent* Component)> where TComponent : struct
{
internal EcsWorld.ComponentPoolEntry* _componentPool;
@@ -70,9 +70,9 @@ namespace GlitchyEngine.World
_componentPool = &world.GetComponentPool<TComponent>();
}
public new Result<(EcsEntity Entity, TComponent* Component)> GetNext() mut
public new Result<(Entity Entity, TComponent* Component)> GetNext() mut
{
Result<EcsEntity> entity = base.GetNext();
Result<Entity> entity = base.GetNext();
if(entity case .Err)
return .Err;
@@ -84,7 +84,7 @@ namespace GlitchyEngine.World
}
public struct WorldEnumerator<TComponent0, TComponent1> : WorldEnumerator,
IEnumerator<(EcsEntity Entity, TComponent0* Component0, TComponent1* Component1)>
IEnumerator<(Entity Entity, TComponent0* Component0, TComponent1* Component1)>
where TComponent0 : struct where TComponent1 : struct
{
internal EcsWorld.ComponentPoolEntry* _componentPool0;
@@ -96,9 +96,9 @@ namespace GlitchyEngine.World
_componentPool1 = &world.GetComponentPool<TComponent1>();
}
public new Result<(EcsEntity Entity, TComponent0* Component0, TComponent1* Component1)> GetNext() mut
public new Result<(Entity Entity, TComponent0* Component0, TComponent1* Component1)> GetNext() mut
{
Result<EcsEntity> entity = base.GetNext();
Result<Entity> entity = base.GetNext();
if(entity case .Err)
return .Err;
@@ -111,7 +111,7 @@ namespace GlitchyEngine.World
}
public struct WorldEnumerator<TComponent0, TComponent1, TComponent2> : WorldEnumerator,
IEnumerator<(EcsEntity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2)>
IEnumerator<(Entity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2)>
where TComponent0 : struct where TComponent1 : struct where TComponent2 : struct
{
internal EcsWorld.ComponentPoolEntry* _componentPool0;
@@ -125,9 +125,9 @@ namespace GlitchyEngine.World
_componentPool2 = &world.GetComponentPool<TComponent2>();
}
public new Result<(EcsEntity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2)> GetNext() mut
public new Result<(Entity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2)> GetNext() mut
{
Result<EcsEntity> entity = base.GetNext();
Result<Entity> entity = base.GetNext();
if(entity case .Err)
return .Err;
@@ -141,7 +141,7 @@ namespace GlitchyEngine.World
}
public struct WorldEnumerator<TComponent0, TComponent1, TComponent2, TComponent3> : WorldEnumerator,
IEnumerator<(EcsEntity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2, TComponent3* Component3)>
IEnumerator<(Entity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2, TComponent3* Component3)>
where TComponent0 : struct where TComponent1 : struct where TComponent2 : struct where TComponent3 : struct
{
internal EcsWorld.ComponentPoolEntry* _componentPool0;
@@ -157,9 +157,9 @@ namespace GlitchyEngine.World
_componentPool3 = &world.GetComponentPool<TComponent3>();
}
public new Result<(EcsEntity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2, TComponent3* Component3)> GetNext() mut
public new Result<(Entity Entity, TComponent0* Component0, TComponent1* Component1, TComponent2* Component2, TComponent3* Component3)> GetNext() mut
{
Result<EcsEntity> entity = base.GetNext();
Result<Entity> entity = base.GetNext();
if(entity case .Err)
return .Err;
-398
View File
@@ -1,398 +0,0 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
-13
View File
@@ -1,13 +0,0 @@
FileVersion = 1
Dependencies = {corlib = "*", corlib = "*", DirectX = "*"}
[Project]
Name = "GlitchyEngineHelper"
TargetType = "BeefLib"
StartupObject = "GlitchyEngineHelper.Program"
[Configs.Debug.Win64]
BuildCommandsOnCompile = "IfFilesChanged"
BuildCommandsOnRun = "IfFilesChanged"
LibPaths = ["$(ProjectDir)/out/build/x64-debug/GlitchyEngineHelper.lib"]
PreBuildCmds = ["$(ProjectDir)\\..\\bin\\vscmake.bat x64 $(ProjectDir) x64-debug", "CopyToDependents(\"$(ProjectDir)/out/build/x64-debug/*.dll\")", "dotnet build $(ProjectDir)/DotNetScriptingHelper/DotNetScriptingHelper.csproj -c Debug", "CopyToDependents(\"$(ProjectDir)/DotNetScriptingHelper/bin/Debug/*\")"]
-56
View File
@@ -1,56 +0,0 @@
# CMakeList.txt : CMake project for GlitchyEngineHelper, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.15)
project ("GlitchyEngineHelper")
# DotNet Apphost:
# Base directory of dotnet app host
SET(DOTNET_APP_HOST_BASE "${CMAKE_SOURCE_DIR}/vendor/dotnetapphost")
# Construct platform specific directory
IF (WIN32)
IF (${TARGET_ARCH} STREQUAL "amd64")
SET(DOTNET_APP_HOST ${DOTNET_APP_HOST_BASE}/win-x64/)
ELSE ()
SET(DOTNET_APP_HOST ${DOTNET_APP_HOST_BASE}/win-x86/)
ENDIF ()
SET(NET_HOST_LIB ${DOTNET_APP_HOST}/nethost.lib)
SET(NET_HOST_DLL_NAME "nethost.dll")
ELSE ()
# LINUX/MAC/...
ENDIF ()
# Less sketchy way of adding a library. If the other method breaks (because it's sketchy) use this one and include nethost.lib manually in Beef-IDE
# target_link_libraries(GlitchyEngineHelper "vendor/dotnethost/nethost.lib")
# Sketchy way to compile a static library into a static target. Notice that we add the objects of this libary in add_library(GlitchyEngineHelper ...
add_library(NetHost OBJECT IMPORTED)
set_property(TARGET NetHost PROPERTY IMPORTED_OBJECTS ${NET_HOST_LIB})
# Copy nethost.dll to output directory
configure_file("${DOTNET_APP_HOST}/${NET_HOST_DLL_NAME}" "${CMAKE_CURRENT_BINARY_DIR}/${NET_HOST_DLL_NAME}" COPYONLY)
# GlitchyEngineHelper:
# Add source to this project's executable.
add_library (GlitchyEngineHelper STATIC
"GlitchyEngineHelper.cpp" "GlitchyEngineHelper.h" "vendor/xxHash/xxhash.c" "vendor/xxHash/xxhash.h" "vendor/DirectXTK/Src/DDSTextureLoader.cpp"
# Link object files from nethost into library (kinda dirty I think, but avoids linking to nethost.lib when compiling in beef)
$<TARGET_OBJECTS:NetHost>
)
target_include_directories(GlitchyEngineHelper PRIVATE
"vendor/DirectXTK/Inc"
${DOTNET_APP_HOST}
)
IF (WIN32)
add_compile_definitions(WINDOWS)
ENDIF()
# Use statically linked multithreaded MSVC runtime
set_property(TARGET GlitchyEngineHelper PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
-65
View File
@@ -1,65 +0,0 @@
{
"version": 3,
"configurePresets": [
{
"name": "windows-base",
"hidden": true,
"generator": "Ninja",
"binaryDir": "${sourceDir}/out/build/${presetName}",
"installDir": "${sourceDir}/out/install/${presetName}",
"cacheVariables": {
"CMAKE_C_COMPILER": "cl.exe",
"CMAKE_CXX_COMPILER": "cl.exe"
},
"condition": {
"type": "equals",
"lhs": "${hostSystemName}",
"rhs": "Windows"
}
},
{
"name": "x64-debug",
"displayName": "x64 Debug",
"inherits": "windows-base",
"architecture": {
"value": "x64",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"TARGET_ARCH": "amd64"
}
},
{
"name": "x64-release",
"displayName": "x64 Release",
"inherits": "x64-debug",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"TARGET_ARCH": "amd64"
}
},
{
"name": "x86-debug",
"displayName": "x86 Debug",
"inherits": "windows-base",
"architecture": {
"value": "x86",
"strategy": "external"
},
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"TARGET_ARCH": "x86"
}
},
{
"name": "x86-release",
"displayName": "x86 Release",
"inherits": "x86-debug",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"TARGET_ARCH": "x86"
}
}
]
}
@@ -1,229 +0,0 @@
using System.Numerics;
using System.Runtime.InteropServices;
namespace DotNetScriptingHelper.Components;
[GameComponent, StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct LameTransformComponent
{
private EcsEntity _parent;
private Vector3 _position;
private Quaternion _rotation;
private Vector3 _scale;
private Vector3 _editorRotationEuler;
private Matrix4x4 _localTransform;
private bool _isDirty;
private Matrix4x4 _worldTransform;
private UIntPtr _frame;
public EcsEntity Parent
{
get => _parent;
set
{
if (_parent == value)
return;
_parent = value;
_isDirty = true;
}
}
public Matrix4x4 LocalTransform
{
get => _localTransform;
set
{
if (_localTransform == value)
return;
_localTransform = value;
Matrix4x4.Decompose(_localTransform, out _position, out _rotation, out _scale);
_isDirty = true;
}
}
// Todo: WorldTransform?
public Vector3 Position
{
get => _position;
set
{
if (_position == value)
return;
_position = value;
_isDirty = true;
}
}
public Quaternion Rotation
{
get => _rotation;
set
{
if (_rotation == value)
return;
_rotation = value;
_isDirty = true;
}
}
public (Vector3 Axis, float Angle) RotationAxisAngle
{
get => _rotation.ToAxisAngle();
set
{
Quaternion quat = Quaternion.CreateFromAxisAngle(value.Axis, value.Angle);
if (_rotation == quat)
return;
_rotation = quat;
_isDirty = true;
}
}
public Vector3 RotationEuler
{
get => _rotation.ToEulerAngles();
set => Rotation = Quaternion.CreateFromYawPitchRoll(value.Y, value.X, value.Z);
}
public Vector3 Scale
{
get => _scale;
set
{
if (_scale == value)
return;
_scale = value;
_isDirty = true;
}
}
}
public unsafe struct TransformComponent
{
[GameComponent, StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TransformComponentData
{
internal EcsEntity _parent;
internal Vector3 _position;
internal Quaternion _rotation;
internal Vector3 _scale;
internal Vector3 _editorRotationEuler;
internal Matrix4x4 _localTransform;
internal bool _isDirty;
internal Matrix4x4 _worldTransform;
internal UIntPtr _frame;
}
private TransformComponentData* _component;
internal TransformComponent(IntPtr component)
{
_component = (TransformComponentData*)component;
}
public EcsEntity Parent
{
get => _component->_parent;
set
{
if (_component->_parent == value)
return;
_component->_parent = value;
_component->_isDirty = true;
}
}
public Matrix4x4 LocalTransform
{
get => _component->_localTransform;
set
{
if (_component->_localTransform == value)
return;
_component->_localTransform = value;
Matrix4x4.Decompose(_component->_localTransform,
out _component->_position, out _component->_rotation, out _component->_scale);
_component->_isDirty = true;
}
}
// Todo: WorldTransform?
public Vector3 Position
{
get => _component->_position;
set
{
if (_component->_position == value)
return;
_component->_position = value;
_component->_isDirty = true;
}
}
public Quaternion Rotation
{
get => _component->_rotation;
set
{
if (_component->_rotation == value)
return;
_component->_rotation = value;
_component->_isDirty = true;
}
}
public (Vector3 Axis, float Angle) RotationAxisAngle
{
get => _component->_rotation.ToAxisAngle();
set
{
Quaternion quat = Quaternion.CreateFromAxisAngle(value.Axis, value.Angle);
if (_component->_rotation == quat)
return;
_component->_rotation = quat;
_component->_isDirty = true;
}
}
public Vector3 RotationEuler
{
get => _component->_rotation.ToEulerAngles();
set => Rotation = Quaternion.CreateFromYawPitchRoll(value.Y, value.X, value.Z);
}
public Vector3 Scale
{
get => _component->_scale;
set
{
if (_component->_scale == value)
return;
_component->_scale = value;
_component->_isDirty = true;
}
}
}
@@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<EnableDynamicLoading>true</EnableDynamicLoading>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<BaseOutputPath></BaseOutputPath>
<DebugType>embedded</DebugType>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
</Project>
@@ -1,25 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32328.378
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DotNetScriptingHelper", "DotNetScriptingHelper.csproj", "{4B439162-2FA7-494E-A459-8F6D34FED80C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B439162-2FA7-494E-A459-8F6D34FED80C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B439162-2FA7-494E-A459-8F6D34FED80C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B439162-2FA7-494E-A459-8F6D34FED80C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B439162-2FA7-494E-A459-8F6D34FED80C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {968CFBCF-61D9-404C-83CC-0F616E89DA10}
EndGlobalSection
EndGlobal
@@ -1,33 +0,0 @@
namespace DotNetScriptingHelper;
public readonly struct EcsEntity
{
// Binary Format:
// Bits: [0 - 31] [32 - 64]
// Data: Version Index
private readonly ulong _id;
internal uint Version => (uint)_id;
internal uint Index => (uint)(_id >> 32);
public EcsEntity(uint index, uint version)
{
_id = ((ulong)index << 32) | version;
}
public bool IsValid => Index != InvalidEntity.Index;
public static readonly EcsEntity InvalidEntity = new(uint.MaxValue, 0);
public static bool operator ==(EcsEntity left, EcsEntity right)
{
return left._id == right._id;
}
public static bool operator !=(EcsEntity left, EcsEntity right)
{
return left._id != right._id;
}
}
@@ -1,17 +0,0 @@
namespace DotNetScriptingHelper;
public struct Entity
{
public EcsEntity Handle { get; }
public IntPtr Scene { get; }
public bool IsValid => Handle.IsValid;
public Entity(EcsEntity handle, IntPtr scene)
{
Handle = handle;
Scene = scene;
}
// TODO: Get Parent, Children
}
@@ -1,23 +0,0 @@
namespace DotNetScriptingHelper;
public class GameTime
{
private ulong _frameCount;
private TimeSpan _totalTime;
private TimeSpan _frameTime;
public ulong FrameCount => _frameCount;
public TimeSpan TotalTime => _totalTime;
public TimeSpan FrameTime => _frameTime;
public float DeltaTime => (float)_frameTime.TotalSeconds;
public float TotalSeconds => (float)_totalTime.TotalSeconds;
internal GameTime(ulong frameCount, TimeSpan totalTime, TimeSpan frameTime)
{
_frameCount = frameCount;
_totalTime = totalTime;
_frameTime = frameTime;
}
}
@@ -1,14 +0,0 @@
namespace DotNetScriptingHelper;
public interface IGameComponent
{
static int I { get; }
}
public class GameComponentAttribute : Attribute
{
public GameComponentAttribute()
{
}
}
@@ -1,91 +0,0 @@
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
namespace DotNetScriptingHelper;
public class InteropHelper
{
struct CreateArgs
{
public IntPtr Ptr;
public int Length;
public string ManagedCopy => Marshal.PtrToStringUTF8(Ptr, Length);
}
//[UnmanagedCallersOnly]
public static int SomeMethod(IntPtr args, int argLength)
{
Debug.WriteLine(typeof(InteropHelper).AssemblyQualifiedName);
return 5;
}
[UnmanagedCallersOnly]
public static IntPtr CreateInstance(IntPtr args, int argLength)
{
try
{
Debug.Assert(Marshal.SizeOf<CreateArgs>() == argLength, "Provided argument has wrong size.");
CreateArgs createArgs = Marshal.PtrToStructure<CreateArgs>(args);
string str = createArgs.ManagedCopy;
Console.WriteLine($"Trying to get type \"{str}\"");
Type? type = Type.GetType(createArgs.ManagedCopy, true);
if (type == null)
{
Console.WriteLine("Type was null.");
return IntPtr.Zero;
}
object? instance = Activator.CreateInstance(type);
if (instance == null)
return IntPtr.Zero;
GCHandle handle = GCHandle.Alloc(instance);
return GCHandle.ToIntPtr(handle);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[UnmanagedCallersOnly]
public static void CallMethod(IntPtr instance, IntPtr methodName, int methodNameLength)
{
GCHandle handle = GCHandle.FromIntPtr(instance);
if (handle.Target == null)
throw new Exception("Handle has no target?");
Type type = handle.Target.GetType();
string name = Marshal.PtrToStringUTF8(methodName, methodNameLength);
MethodInfo? mi = type.GetMethod(name);
if (mi == null)
throw new Exception("MethodInfo is null.");
mi.Invoke(handle.Target, null);
}
public delegate void FreeInstanceEntryPoint(IntPtr instance);
[UnmanagedCallersOnly]
public static void FreeInstance(IntPtr instance)
{
GCHandle handle = GCHandle.FromIntPtr(instance);
handle.Free();
}
}
@@ -1,68 +0,0 @@
using System.Numerics;
namespace DotNetScriptingHelper;
public static class QuaternionExtensions
{
public static (Vector3 Axis, float Angle) ToAxisAngle(this Quaternion quat)
{
// scalar part = cos(θ/2)
// So, we can extract the angle directly.
float angle = 2.0f * MathF.Acos(quat.W);
// vector part = axis * sin(θ/2)
// In other words, the vector part is the axis, but with length of sin(θ/2).
// We assume quaternion is unit length, so subtracting w^2 gives us length of just vector part (aka sin(θ/2)).
float length = MathF.Sqrt(1.0f - (quat.W * quat.W));
Vector3 axis;
// Normalize vector part to get the axis!
if (length == 0)
{
axis = Vector3.Zero;
}
else
{
length = 1.0f / length;
axis.X = quat.X * length;
axis.Y = quat.Y * length;
axis.Z = quat.Z * length;
}
return (axis, angle);
}
public static Vector3 ToEulerAngles(this Quaternion q)
{
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/
Vector3 result;
float sqw = q.W * q.W;
float sqx = q.X * q.X;
float sqy = q.Y * q.Y;
float sqz = q.Z * q.Z;
float unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
float test = q.X * q.Y + q.Z * q.W;
if (test > 0.4999f * unit)
{ // singularity at north pole
result.Y = 2.0f * MathF.Atan2(q.X, q.W);
result.Z = MathF.PI / 2.0f;
result.X = 0.0f;
return result;
}
if (test < -0.4999f * unit)
{ // singularity at south pole
result.Y = -2.0f * MathF.Atan2(q.X, q.W);
result.Z = -MathF.PI / 2.0f;
result.X = 0.0f;
return result;
}
result.Y = MathF.Atan2(2 * q.Y * q.W - 2 * q.X * q.Z, sqx - sqy - sqz + sqw);
result.Z = MathF.Asin(2 * test / unit);
result.X = MathF.Atan2(2 * q.X * q.W - 2 * q.Y * q.Z, -sqx + sqy - sqz + sqw);
return result;
}
}
@@ -1,98 +0,0 @@
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using DotNetScriptingHelper.Components;
namespace DotNetScriptingHelper;
public abstract class ScriptableEntity
{
internal Entity Entity;
public virtual void OnCreate() { }
protected virtual void OnDestroy() { }
protected virtual void OnUpdate(GameTime gameTime) { }
[UnmanagedCallersOnly]
public static IntPtr CreateInstance(IntPtr typeNamePtr, int typeNameLength, EcsEntity entity, IntPtr scene)
{
try
{
string typeName = Marshal.PtrToStringUTF8(typeNamePtr, typeNameLength);
Type? type = Type.GetType(typeName, true);
Debug.Assert(type != null, "Type not found.");
object? instance = Activator.CreateInstance(type);
Debug.Assert(instance != null, "Instance could not be created");
Debug.Assert(instance is ScriptableEntity, "Activated instance doesn't inherit from ScriptableEntity");
if (instance is not ScriptableEntity scriptableEntity)
return IntPtr.Zero;
scriptableEntity.Entity = new Entity(entity, scene);
scriptableEntity.OnCreate();
GCHandle handle = GCHandle.Alloc(instance);
return GCHandle.ToIntPtr(handle);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
[UnmanagedCallersOnly]
public static void DestroyEntity(IntPtr entityPtr)
{
GCHandle entityHandle = GCHandle.FromIntPtr(entityPtr);
if (entityHandle.Target is ScriptableEntity entity)
{
entity.OnDestroy();
}
entityHandle.Free();
}
[UnmanagedCallersOnly]
public static void UpdateEntity(IntPtr entityPtr, ulong frameCount, TimeSpan totalTime, TimeSpan frameTime)
{
GCHandle entityHandle = GCHandle.FromIntPtr(entityPtr);
if (entityHandle.Target is ScriptableEntity entity)
{
GameTime gameTime = new GameTime(frameCount, totalTime, frameTime);
entity.OnUpdate(gameTime);
}
}
[DllImport("GlitchyEditor.exe", EntryPoint = "GE_DoStuff")]
static extern int DoStuff();
[DllImport("GlitchyEditor.exe", EntryPoint = "GE_DotNetScript_GetComponent")]
private static extern IntPtr GetComponent(EcsEntity entity, IntPtr scenePtr);
protected TransformComponent GetTransform()// where T : struct
{
IntPtr component = GetComponent(Entity.Handle, Entity.Scene);
return new TransformComponent(component);
//unsafe
//{
// TransformComponent* transform = (TransformComponent*)component;
// return ref *transform;
//}
//GameComponentAttribute? attribute = typeof(T).GetCustomAttribute<GameComponentAttribute>();
//Debug.Assert(attribute != null, $"Requested type {typeof(T)} is not a component.");
}
}
@@ -1,39 +0,0 @@
using System.Numerics;
using DotNetScriptingHelper.Components;
namespace DotNetScriptingHelper;
public class TestEntityScript : ScriptableEntity
{
private TransformComponent _transform;
public override void OnCreate()
{
_transform = GetTransform();
}
protected override void OnUpdate(GameTime gameTime)
{
float f = (float)Math.Sin(gameTime.TotalSeconds);
Vector3 pos = _transform.Position;
pos.Y = f;
_transform.Position = pos;
float fx = MathF.Sin(gameTime.TotalSeconds * 2) / 2 + 1;
float fy = MathF.Cos(gameTime.TotalSeconds * 2) / 2 + 1;
Vector3 scl = _transform.Scale;
scl.X = fx;
scl.Y = fy;
_transform.Scale = scl;
float fr = MathF.Cos(gameTime.TotalSeconds / 4) * MathF.PI * 10;
_transform.Rotation = Quaternion.CreateFromYawPitchRoll(0, 0, fr);
}
}
-158
View File
@@ -1,158 +0,0 @@
// GlitchyEngineHelper.cpp : Defines the entry point for the application.
//
#include "GlitchyEngineHelper.h"
#include "vendor/xxHash/xxhash.h"
#include "vendor/DirectXTK/Inc/DDSTextureLoader.h"
using namespace std;
GE_EXPORT int GE_CALLTYPE test(int x, int y)
{
return x + y;
}
GE_EXPORT XXH64_hash_t bla(void* buffer, size_t size, XXH64_hash_t seed)
{
return XXH64(buffer, size, seed);
}
// Standard version
GE_EXPORT HRESULT GE_CALLTYPE DirectXTK_CreateDDSTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromMemory(d3dDevice, ddsData, ddsDataSize, texture, textureView, maxsize, alphaMode);
}
GE_EXPORT HRESULT GE_CALLTYPE DirectXTK_CreateDDSTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromFile(d3dDevice, szFileName, texture, textureView, maxsize, alphaMode);
}
// Standard version with optional auto-gen mipmap support
GE_EXPORT HRESULT GE_CALLTYPE DirectXTK_CreateDDSTextureFromMemoryMip(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromMemory(d3dDevice, d3dContext, ddsData, ddsDataSize, texture, textureView, maxsize, alphaMode);
}
GE_EXPORT HRESULT GE_CALLTYPE DirectXTK_CreateDDSTextureFromFileMip(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromFile(d3dDevice, d3dContext, szFileName, texture, textureView, maxsize, alphaMode);
}
// Extended version
HRESULT __cdecl DirectXTK_CreateDDSTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromMemoryEx(d3dDevice, ddsData, ddsDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView, alphaMode);
}
HRESULT __cdecl DirectXTK_CreateDDSTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromFileEx(d3dDevice, szFileName, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView, alphaMode);
}
// Extended version with optional auto-gen mipmap support
HRESULT __cdecl DirectXTK_CreateDDSTextureFromMemoryExMip(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_reads_bytes_(ddsDataSize) const uint8_t* ddsData,
_In_ size_t ddsDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromMemoryEx(d3dDevice, d3dContext, ddsData, ddsDataSize, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView, alphaMode);
}
HRESULT __cdecl DirectXTK_CreateDDSTextureFromFileExMip(
#if defined(_XBOX_ONE) && defined(_TITLE)
_In_ ID3D11DeviceX* d3dDevice,
_In_opt_ ID3D11DeviceContextX* d3dContext,
#else
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
#endif
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ bool forceSRGB,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_Out_opt_ DirectX::DDS_ALPHA_MODE* alphaMode) noexcept
{
return DirectX::CreateDDSTextureFromFileEx(d3dDevice, d3dContext, szFileName, maxsize, usage, bindFlags, cpuAccessFlags, miscFlags, forceSRGB, texture, textureView, alphaMode);
}
@@ -1,7 +0,0 @@
// GlitchyEngineHelper.h : Include file for standard system include files,
// or project specific include files.
#pragma once
#define GE_EXPORT extern "C" __declspec(dllexport)
#define GE_CALLTYPE __cdecl
@@ -1,123 +0,0 @@
using DirectX.Common;
using DirectX.D3D11;
using System;
using System.Interop;
namespace DirectXTK
{
enum DdsAlphaMode : uint32
{
Unknown = 0,
Straight = 1,
Premultiplied = 2,
Opaque = 3,
Custom = 4,
}
public static class DDSTextureLoader
{
// Standard version
[LinkName("DirectXTK_CreateDDSTextureFromMemory"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromMemory(
ID3D11Device* d3dDevice,
uint8* ddsData,
c_size ddsDataSize,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
c_size maxsize = 0,
DdsAlphaMode* alphaMode = null);
[LinkName("DirectXTK_CreateDDSTextureFromFile"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromFile(
ID3D11Device* d3dDevice,
c_wchar* szFileName,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
c_size maxsize = 0,
DdsAlphaMode* alphaMode = null);
// Standard version with optional auto-gen mipmap support
[LinkName("DirectXTK_CreateDDSTextureFromMemoryMip"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromMemory(
ID3D11Device* d3dDevice,
ID3D11DeviceContext* d3dContext,
uint8* ddsData,
c_size ddsDataSize,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
c_size maxsize = 0,
DdsAlphaMode* alphaMode = null);
[LinkName("DirectXTK_CreateDDSTextureFromFileMip"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromFile(
ID3D11Device* d3dDevice,
ID3D11DeviceContext* d3dContext,
c_wchar* szFileName,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
c_size maxsize = 0,
DdsAlphaMode* alphaMode = null);
// Extended version
[LinkName("DirectXTK_CreateDDSTextureFromMemoryEx"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromMemoryEx(
ID3D11Device* d3dDevice,
uint8* ddsData,
c_size ddsDataSize,
c_size maxsize,
Usage usage,
BindFlags bindFlags,
CpuAccessFlags cpuAccessFlags,
ResourceMiscFlags miscFlags,
bool forceSRGB,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
DdsAlphaMode* alphaMode = null);
[LinkName("DirectXTK_CreateDDSTextureFromFileEx"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromFileEx(
ID3D11Device* d3dDevice,
c_wchar* szFileName,
c_size maxsize,
Usage usage,
BindFlags bindFlags,
CpuAccessFlags cpuAccessFlags,
ResourceMiscFlags miscFlags,
bool forceSRGB,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
DdsAlphaMode* alphaMode = null);
// Extended version with optional auto-gen mipmap support
[LinkName("DirectXTK_CreateDDSTextureFromMemoryExMip"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromMemoryEx(
ID3D11Device* d3dDevice,
ID3D11DeviceContext* d3dContext,
uint8* ddsData,
c_size ddsDataSize,
c_size maxsize,
Usage usage,
BindFlags bindFlags,
CpuAccessFlags cpuAccessFlags,
ResourceMiscFlags miscFlags,
bool forceSRGB,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
DdsAlphaMode* alphaMode = null);
[LinkName("DirectXTK_CreateDDSTextureFromFileExMip"), CallingConvention(.Cdecl)]
public static extern HResult CreateDDSTextureFromFileEx(
ID3D11Device* d3dDevice,
ID3D11DeviceContext* d3dContext,
c_wchar* szFileName,
c_size maxsize,
Usage usage,
BindFlags bindFlags,
CpuAccessFlags cpuAccessFlags,
ResourceMiscFlags miscFlags,
bool forceSRGB,
ID3D11Resource** texture,
ID3D11ShaderResourceView** textureView,
DdsAlphaMode* alphaMode = null);
}
}
-38
View File
@@ -1,38 +0,0 @@
using System;
using System.Interop;
using internal GlitchyEngineHelper.DotNet;
namespace GlitchyEngineHelper.DotNet
{
static
{
#if BF_PLATFORM_WINDOWS
internal typealias char = char16;
#else
internal typealias char = char8;
#endif
}
static class CoreClr
{
public const char* UNMANAGEDCALLERSONLY_METHOD = (char*)(void*)-1;
public typealias LoadAssemblyAndGetFunctionPointerFn = function [CallingConvention(.Stdcall)] c_int(
char* assemblyPath,
char* typeName,
char* methodName,
char* delegateTypeName,
void* reserved,
out void* outDelegate);
public typealias GetFunctionPointerFn = function [CallingConvention(.Stdcall)] c_int(
char* typeName,
char* MethodName,
char* delegateTypeName,
void* loadContext,
void* reserved,
out void* outDelegate
);
}
}
@@ -1,176 +0,0 @@
using System;
using System.IO;
using System.Interop;
using System.Diagnostics;
using GlitchyEngineHelper.DotNet;
namespace GlitchyEngineHelper.DotNet
{
class DotNetContext
{
#if BF_PLATFORM_WINDOWS
internal typealias char = char16;
#else
internal typealias char = char8;
#endif
HostFxr.InitializeForDotnetCommandLineFn InitFn;
HostFxr.GetRuntimeDelegateFn GetDelegate;
HostFxr.CloseFn Close;
HostFxr.SetRuntimePropertyValueFn SetRuntimePropertyValueFn;
CoreClr.LoadAssemblyAndGetFunctionPointerFn LoadAssemblyAndGetFunctionPointerFn;
CoreClr.GetFunctionPointerFn GetFunctionPointerFn;
private String _configPath ~ delete _;
public this(String configPath)
{
_configPath = new String(configPath);
}
private mixin RawPointer(StringView str)
{
#if BF_PLATFORM_WINDOWS
str.ToScopedNativeWChar!:mixin()
#else
str.CStr()
#endif
}
public void Init()
{
LoadHostFxr();
InitAndStartRuntime();
}
private void LoadHostFxr()
{
char[256] buffer = ?;
c_size bufferSize = buffer.Count;
int rc = NetHost.get_hostfxr_path(&buffer, &bufferSize, null);
Debug.Assert(rc == 0);
// Load hostfxr and get desired exports
void* lib = LoadLibrary(&buffer);
InitFn = GetExport<HostFxr.InitializeForDotnetCommandLineFn>(lib, "hostfxr_initialize_for_dotnet_command_line");
GetDelegate = GetExport<HostFxr.GetRuntimeDelegateFn>(lib, "hostfxr_get_runtime_delegate");
SetRuntimePropertyValueFn = GetExport<HostFxr.SetRuntimePropertyValueFn>(lib, "hostfxr_set_runtime_property_value");
Close = GetExport<HostFxr.CloseFn>(lib, "hostfxr_close");
Debug.Assert(InitFn != null && GetDelegate != null && Close != null);
}
private void InitAndStartRuntime()
{
char* ptr = RawPointer!(_configPath);
char*[2] args = char*[](
ptr,
null
);
HostFxr.Handle cxt = null;
int rc = InitFn(1, &args, null, &cxt);
if (rc != 0 || cxt == null)
{
Debug.WriteLine($"Init failed: {rc}");
Close(cxt);
Debug.Assert(rc == 0);
return;
}
Debug.Assert(rc == 0);
rc = GetDelegate(cxt, .LoadAssemblyAndGetFunctionPointer, (void**)&LoadAssemblyAndGetFunctionPointerFn);
Debug.Assert(rc == 0, scope $"Get delegate failed: {rc}");
rc = GetDelegate(cxt, .GetFunctionPointer, (void**)&GetFunctionPointerFn);
Debug.Assert(rc == 0, scope $"Get delegate failed: {rc}");
Close(cxt);
}
/*public int SetRuntimePropertyValue(StringView property, StringView value)
{
return SetRuntimePropertyValueFn(cxt, RawPointer!(property), RawPointer!(value));
}*/
public int LoadAssemblyAndGetFunctionPointer<T>(StringView libraryPath, StringView typeName, StringView methodName, StringView delegateName, out T outDelegate) where T: operator explicit void*
{
void* funPtr = null;
int rc = LoadAssemblyAndGetFunctionPointerFn(RawPointer!(libraryPath), RawPointer!(typeName), RawPointer!(methodName), RawPointer!(delegateName), null, out funPtr);
outDelegate = (T)funPtr;
return rc;
}
public int LoadAssemblyAndGetFunctionPointerUnmanagedCallersOnly<T>(String libraryPath, String typeName, String methodName, out T outDelegate) where T: operator explicit void*
{
void* funPtr = null;
int rc = LoadAssemblyAndGetFunctionPointerFn(RawPointer!(libraryPath), RawPointer!(typeName), RawPointer!(methodName), CoreClr.UNMANAGEDCALLERSONLY_METHOD, null, out funPtr);
outDelegate = (T)funPtr;
return rc;
}
public int GetFunctionPointer<T>(String typeName, String methodName, String delegateName, out T outDelegate) where T: operator explicit void*
{
void* funPtr = null;
int rc = GetFunctionPointerFn(RawPointer!(typeName), RawPointer!(methodName), RawPointer!(delegateName), null, null, out funPtr);
outDelegate = (T)funPtr;
return rc;
}
public int GetFunctionPointerUnmanagedCallersOnly<T>(String typeName, String methodName, out T outDelegate) where T: operator explicit void*
{
void* funPtr = null;
int rc = GetFunctionPointerFn(RawPointer!(typeName), RawPointer!(methodName), CoreClr.UNMANAGEDCALLERSONLY_METHOD, null, null, out funPtr);
outDelegate = (T)funPtr;
return rc;
}
#if BF_PLATFORM_WINDOWS
private void* LoadLibrary(char* path)
{
Windows.HInstance handle = Windows.LoadLibraryW(path);
Debug.Assert(handle != 0);
return (void*)(int)handle;
}
private T GetExport<T>(void* handle, char8* name) where T : operator explicit void*
{
void* f = Windows.GetProcAddress((Windows.HModule)(int)handle, name);
Debug.Assert(f != null);
return (T)f;
}
#else
private void* LoadLibrary(char* path)
{
// TODO!
}
#endif
}
}
-37
View File
@@ -1,37 +0,0 @@
using System;
using System.Interop;
using internal GlitchyEngineHelper.DotNet;
namespace GlitchyEngineHelper.DotNet
{
static class HostFxr
{
public enum DelegateType : c_int
{
ComActivation,
LoadInMemoryAssembly,
WinrtActivation,
ComRegister,
ComUnregister,
LoadAssemblyAndGetFunctionPointer,
GetFunctionPointer,
}
public typealias Handle = void*;
[CRepr]
public struct InitializeParameters
{
public c_size Size = sizeof(InitializeParameters);
public char* HostPath;
public char* DotnetRoot;
};
public typealias InitializeForRuntimeConfigFn = function [CallingConvention(.Cdecl)] int32(char* runtimeConfigPath, InitializeParameters* parameters, Handle* hostContextHandle);
public typealias InitializeForDotnetCommandLineFn = function [CallingConvention(.Cdecl)] int32(c_int argc, char** argv, InitializeParameters* parameters, Handle* hostContextHandle);
public typealias GetRuntimeDelegateFn = function [CallingConvention(.Cdecl)] int32(Handle host_context_handle, DelegateType type, void** outDelegate);
public typealias SetRuntimePropertyValueFn = function [CallingConvention(.Cdecl)] int32(Handle host_context_handle, char* name, char* value);
public typealias CloseFn = function [CallingConvention(.Cdecl)] int32(Handle host_context_handle);
}
}
-23
View File
@@ -1,23 +0,0 @@
using System;
using System.Interop;
using internal GlitchyEngineHelper.DotNet;
namespace GlitchyEngineHelper.DotNet
{
static class NetHost
{
public struct get_hostfxr_parameters
{
public c_size size;
public char* assembly_path;
public char* dotnet_root;
};
[CallingConvention(.Stdcall), LinkName("get_hostfxr_path")]
public static extern int get_hostfxr_path(
char* buffer,
c_size* buffer_size,
get_hostfxr_parameters *parameters);
}
}
-22
View File
@@ -1,22 +0,0 @@
using System;
using System.Interop;
namespace xxHash
{
struct XXH64_hash : uint64{}
static
{
[LinkName(.C)]
public static extern XXH64_hash XXH64(void* buffer, c_size size, XXH64_hash seed = 0);
}
static class xxHash
{
[Inline]
public static XXH64_hash ComputeHash(StringView string, XXH64_hash seed = 0)
{
return XXH64(string.Ptr, (.)string.Length, seed);
}
}
}
@@ -1,23 +0,0 @@
The MIT License (MIT)
Copyright (c) .NET Foundation and Contributors
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.
@@ -1,6 +0,0 @@
[InternetShortcut]
URL=https://www.nuget.org/packages/Microsoft.NETCore.App.Host.win-x64/6.0.4
IDList=
HotKey=0
IconFile=C:\Users\Simon\AppData\Local\Mozilla\Firefox\Profiles\4fg8w6bv.default-release\shortcutCache\ZRtEa8YtjlqBgeyz_pfmfw==.ico
IconIndex=0
@@ -1,939 +0,0 @@
.NET Runtime uses third-party libraries or other resources that may be
distributed under licenses different than the .NET Runtime software.
In the event that we accidentally failed to list a required notice, please
bring it to our attention. Post an issue or email us:
dotnet@microsoft.com
The attached notices are provided for information only.
License notice for ASP.NET
-------------------------------
Copyright (c) .NET Foundation. All rights reserved.
Licensed under the Apache License, Version 2.0.
Available at
https://github.com/dotnet/aspnetcore/blob/main/LICENSE.txt
License notice for Slicing-by-8
-------------------------------
http://sourceforge.net/projects/slicing-by-8/
Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved
This software program is licensed subject to the BSD License, available at
http://www.opensource.org/licenses/bsd-license.html.
License notice for Unicode data
-------------------------------
https://www.unicode.org/license.html
Copyright © 1991-2020 Unicode, Inc. All rights reserved.
Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Unicode data files and any associated documentation
(the "Data Files") or Unicode software and any associated documentation
(the "Software") to deal in the Data Files or Software
without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that either
(a) this copyright and permission notice appear with all copies
of the Data Files or Software, or
(b) this copyright and permission notice appear in associated
Documentation.
THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in these Data Files or Software without prior
written authorization of the copyright holder.
License notice for Zlib
-----------------------
https://github.com/madler/zlib
http://zlib.net/zlib_license.html
/* zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.11, January 15th, 2017
Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
*/
License notice for Mono
-------------------------------
http://www.mono-project.com/docs/about-mono/
Copyright (c) .NET Foundation Contributors
MIT License
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.
License notice for International Organization for Standardization
-----------------------------------------------------------------
Portions (C) International Organization for Standardization 1986:
Permission to copy in any form is granted for use with
conforming SGML systems and applications as defined in
ISO 8879, provided this notice is included in all copies.
License notice for Intel
------------------------
"Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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 HOLDER 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.
License notice for Xamarin and Novell
-------------------------------------
Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com)
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.
Copyright (c) 2011 Novell, Inc (http://www.novell.com)
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 party notice for W3C
--------------------------
"W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE
Status: This license takes effect 13 May, 2015.
This work is being provided by the copyright holders under the following license.
License
By obtaining and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions.
Permission to copy, modify, and distribute this work, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the work or portions thereof, including modifications:
The full text of this NOTICE in a location viewable to users of the redistributed or derivative work.
Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software and Document Short Notice should be included.
Notice of any changes or modifications, through a copyright statement on the new code or document such as "This software or document includes material copied from or derived from [title and URI of the W3C document]. Copyright © [YEAR] W3C® (MIT, ERCIM, Keio, Beihang)."
Disclaimers
THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT.
The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the work without specific, written prior permission. Title to copyright in this work will at all times remain with copyright holders."
License notice for Bit Twiddling Hacks
--------------------------------------
Bit Twiddling Hacks
By Sean Eron Anderson
seander@cs.stanford.edu
Individually, the code snippets here are in the public domain (unless otherwise
noted) — feel free to use them however you please. The aggregate collection and
descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are
distributed in the hope that they will be useful, but WITHOUT ANY WARRANTY and
without even the implied warranty of merchantability or fitness for a particular
purpose.
License notice for Brotli
--------------------------------------
Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.
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.
compress_fragment.c:
Copyright (c) 2011, Google Inc.
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 Google Inc. 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.
decode_fuzzer.c:
Copyright (c) 2015 The Chromium Authors. 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 Google Inc. 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."
License notice for Json.NET
-------------------------------
https://github.com/JamesNK/Newtonsoft.Json/blob/master/LICENSE.md
The MIT License (MIT)
Copyright (c) 2007 James Newton-King
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.
License notice for vectorized base64 encoding / decoding
--------------------------------------------------------
Copyright (c) 2005-2007, Nick Galbreath
Copyright (c) 2013-2017, Alfred Klomp
Copyright (c) 2015-2017, Wojciech Mula
Copyright (c) 2016-2017, Matthieu Darbois
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.
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
HOLDER 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.
License notice for RFC 3492
---------------------------
The punycode implementation is based on the sample code in RFC 3492
Copyright (C) The Internet Society (2003). All Rights Reserved.
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it
or assist in its implementation may be prepared, copied, published
and distributed, in whole or in part, without restriction of any
kind, provided that the above copyright notice and this paragraph are
included on all such copies and derivative works. However, this
document itself may not be modified in any way, such as by removing
the copyright notice or references to the Internet Society or other
Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for
copyrights defined in the Internet Standards process must be
followed, or as required to translate it into languages other than
English.
The limited permissions granted above are perpetual and will not be
revoked by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an
"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
License notice for Algorithm from Internet Draft document "UUIDs and GUIDs"
---------------------------------------------------------------------------
Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
Digital Equipment Corporation, Maynard, Mass.
To anyone who acknowledges that this file is provided "AS IS"
without any express or implied warranty: permission to use, copy,
modify, and distribute this file for any purpose is hereby
granted without fee, provided that the above copyright notices and
this notice appears in all source code copies, and that none of
the names of Open Software Foundation, Inc., Hewlett-Packard
Company, or Digital Equipment Corporation be used in advertising
or publicity pertaining to distribution of the software without
specific, written prior permission. Neither Open Software
Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital Equipment
Corporation makes any representations about the suitability of
this software for any purpose.
Copyright(C) The Internet Society 1997. All Rights Reserved.
This document and translations of it may be copied and furnished to others,
and derivative works that comment on or otherwise explain it or assist in
its implementation may be prepared, copied, published and distributed, in
whole or in part, without restriction of any kind, provided that the above
copyright notice and this paragraph are included on all such copies and
derivative works.However, this document itself may not be modified in any
way, such as by removing the copyright notice or references to the Internet
Society or other Internet organizations, except as needed for the purpose of
developing Internet standards in which case the procedures for copyrights
defined in the Internet Standards process must be followed, or as required
to translate it into languages other than English.
The limited permissions granted above are perpetual and will not be revoked
by the Internet Society or its successors or assigns.
This document and the information contained herein is provided on an "AS IS"
basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE
DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE.
License notice for Algorithm from RFC 4122 -
A Universally Unique IDentifier (UUID) URN Namespace
----------------------------------------------------
Copyright (c) 1990- 1993, 1996 Open Software Foundation, Inc.
Copyright (c) 1989 by Hewlett-Packard Company, Palo Alto, Ca. &
Digital Equipment Corporation, Maynard, Mass.
Copyright (c) 1998 Microsoft.
To anyone who acknowledges that this file is provided "AS IS"
without any express or implied warranty: permission to use, copy,
modify, and distribute this file for any purpose is hereby
granted without fee, provided that the above copyright notices and
this notice appears in all source code copies, and that none of
the names of Open Software Foundation, Inc., Hewlett-Packard
Company, Microsoft, or Digital Equipment Corporation be used in
advertising or publicity pertaining to distribution of the software
without specific, written prior permission. Neither Open Software
Foundation, Inc., Hewlett-Packard Company, Microsoft, nor Digital
Equipment Corporation makes any representations about the
suitability of this software for any purpose."
License notice for The LLVM Compiler Infrastructure
---------------------------------------------------
Developed by:
LLVM Team
University of Illinois at Urbana-Champaign
http://llvm.org
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal with
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:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the
documentation and/or other materials provided with the distribution.
* Neither the names of the LLVM Team, University of Illinois at
Urbana-Champaign, nor the names of its contributors may be used to
endorse or promote products derived from this Software without specific
prior written permission.
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
CONTRIBUTORS 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 WITH THE
SOFTWARE.
License notice for Bob Jenkins
------------------------------
By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this
code any way you wish, private, educational, or commercial. It's free.
License notice for Greg Parker
------------------------------
Greg Parker gparker@cs.stanford.edu December 2000
This code is in the public domain and may be copied or modified without
permission.
License notice for libunwind based code
----------------------------------------
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.
License notice for Printing Floating-Point Numbers (Dragon4)
------------------------------------------------------------
/******************************************************************************
Copyright (c) 2014 Ryan Juckett
http://www.ryanjuckett.com/
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
******************************************************************************/
License notice for Printing Floating-point Numbers (Grisu3)
-----------------------------------------------------------
Copyright 2012 the V8 project authors. 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 Google Inc. 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.
License notice for xxHash
-------------------------
xxHash Library
Copyright (c) 2012-2014, Yann Collet
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.
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 HOLDER 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.
License notice for Berkeley SoftFloat Release 3e
------------------------------------------------
https://github.com/ucb-bar/berkeley-softfloat-3
https://github.com/ucb-bar/berkeley-softfloat-3/blob/master/COPYING.txt
License for Berkeley SoftFloat Release 3e
John R. Hauser
2018 January 20
The following applies to the whole of SoftFloat Release 3e as well as to
each source file individually.
Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 The Regents of the
University of California. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions, and the following disclaimer.
2. 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.
3. Neither the name of the University 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 REGENTS 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 REGENTS 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.
License notice for xoshiro RNGs
--------------------------------
Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>.
License for fastmod (https://github.com/lemire/fastmod) and ibm-fpgen (https://github.com/nigeltao/parse-number-fxx-test-data)
--------------------------------------
Copyright 2018 Daniel Lemire
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
License notice for The C++ REST SDK
-----------------------------------
C++ REST SDK
The MIT License (MIT)
Copyright (c) Microsoft Corporation
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.
License notice for MessagePack-CSharp
-------------------------------------
MessagePack for C#
MIT License
Copyright (c) 2017 Yoshifumi Kawai
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.
License notice for lz4net
-------------------------------------
lz4net
Copyright (c) 2013-2017, Milosz Krajewski
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.
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 HOLDER 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.
License notice for Nerdbank.Streams
-----------------------------------
The MIT License (MIT)
Copyright (c) Andrew Arnott
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.
License notice for RapidJSON
----------------------------
Tencent is pleased to support the open source community by making RapidJSON available.
Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except
in compliance with the License. You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
License notice for DirectX Math Library
---------------------------------------
https://github.com/microsoft/DirectXMath/blob/master/LICENSE
The MIT License (MIT)
Copyright (c) 2011-2020 Microsoft Corp
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.
License notice for ldap4net
---------------------------
The MIT License (MIT)
Copyright (c) 2018 Alexander Chermyanin
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.
License notice for vectorized sorting code
------------------------------------------
MIT License
Copyright (c) 2020 Dan Shechter
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.
License notice for musl
-----------------------
musl as a whole is licensed under the following standard MIT license:
Copyright © 2005-2020 Rich Felker, et al.
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.
License notice for "Faster Unsigned Division by Constants"
------------------------------
Reference implementations of computing and using the "magic number" approach to dividing
by constants, including codegen instructions. The unsigned division incorporates the
"round down" optimization per ridiculous_fish.
This is free and unencumbered software. Any copyright is dedicated to the Public Domain.
License notice for mimalloc
-----------------------------------
MIT License
Copyright (c) 2019 Microsoft Corporation, Daan Leijen
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.
Binary file not shown.
Binary file not shown.
@@ -1,47 +0,0 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef __CORECLR_DELEGATES_H__
#define __CORECLR_DELEGATES_H__
#include <stdint.h>
#if defined(_WIN32)
#define CORECLR_DELEGATE_CALLTYPE __stdcall
#ifdef _WCHAR_T_DEFINED
typedef wchar_t char_t;
#else
typedef unsigned short char_t;
#endif
#else
#define CORECLR_DELEGATE_CALLTYPE
typedef char char_t;
#endif
#define UNMANAGEDCALLERSONLY_METHOD ((const char_t*)-1)
// Signature of delegate returned by coreclr_delegate_type::load_assembly_and_get_function_pointer
typedef int (CORECLR_DELEGATE_CALLTYPE *load_assembly_and_get_function_pointer_fn)(
const char_t *assembly_path /* Fully qualified path to assembly */,
const char_t *type_name /* Assembly qualified type name */,
const char_t *method_name /* Public static method name compatible with delegateType */,
const char_t *delegate_type_name /* Assembly qualified delegate type name or null
or UNMANAGEDCALLERSONLY_METHOD if the method is marked with
the UnmanagedCallersOnlyAttribute. */,
void *reserved /* Extensibility parameter (currently unused and must be 0) */,
/*out*/ void **delegate /* Pointer where to store the function pointer result */);
// Signature of delegate returned by load_assembly_and_get_function_pointer_fn when delegate_type_name == null (default)
typedef int (CORECLR_DELEGATE_CALLTYPE *component_entry_point_fn)(void *arg, int32_t arg_size_in_bytes);
typedef int (CORECLR_DELEGATE_CALLTYPE *get_function_pointer_fn)(
const char_t *type_name /* Assembly qualified type name */,
const char_t *method_name /* Public static method name compatible with delegateType */,
const char_t *delegate_type_name /* Assembly qualified delegate type name or null,
or UNMANAGEDCALLERSONLY_METHOD if the method is marked with
the UnmanagedCallersOnlyAttribute. */,
void *load_context /* Extensibility parameter (currently unused and must be 0) */,
void *reserved /* Extensibility parameter (currently unused and must be 0) */,
/*out*/ void **delegate /* Pointer where to store the function pointer result */);
#endif // __CORECLR_DELEGATES_H__
@@ -1,323 +0,0 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef __HOSTFXR_H__
#define __HOSTFXR_H__
#include <stddef.h>
#include <stdint.h>
#if defined(_WIN32)
#define HOSTFXR_CALLTYPE __cdecl
#ifdef _WCHAR_T_DEFINED
typedef wchar_t char_t;
#else
typedef unsigned short char_t;
#endif
#else
#define HOSTFXR_CALLTYPE
typedef char char_t;
#endif
enum hostfxr_delegate_type
{
hdt_com_activation,
hdt_load_in_memory_assembly,
hdt_winrt_activation,
hdt_com_register,
hdt_com_unregister,
hdt_load_assembly_and_get_function_pointer,
hdt_get_function_pointer,
};
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_main_fn)(const int argc, const char_t **argv);
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_main_startupinfo_fn)(
const int argc,
const char_t **argv,
const char_t *host_path,
const char_t *dotnet_root,
const char_t *app_path);
typedef int32_t(HOSTFXR_CALLTYPE* hostfxr_main_bundle_startupinfo_fn)(
const int argc,
const char_t** argv,
const char_t* host_path,
const char_t* dotnet_root,
const char_t* app_path,
int64_t bundle_header_offset);
typedef void(HOSTFXR_CALLTYPE *hostfxr_error_writer_fn)(const char_t *message);
//
// Sets a callback which is to be used to write errors to.
//
// Parameters:
// error_writer
// A callback function which will be invoked every time an error is to be reported.
// Or nullptr to unregister previously registered callback and return to the default behavior.
// Return value:
// The previously registered callback (which is now unregistered), or nullptr if no previous callback
// was registered
//
// The error writer is registered per-thread, so the registration is thread-local. On each thread
// only one callback can be registered. Subsequent registrations overwrite the previous ones.
//
// By default no callback is registered in which case the errors are written to stderr.
//
// Each call to the error writer is sort of like writing a single line (the EOL character is omitted).
// Multiple calls to the error writer may occure for one failure.
//
// If the hostfxr invokes functions in hostpolicy as part of its operation, the error writer
// will be propagated to hostpolicy for the duration of the call. This means that errors from
// both hostfxr and hostpolicy will be reporter through the same error writer.
//
typedef hostfxr_error_writer_fn(HOSTFXR_CALLTYPE *hostfxr_set_error_writer_fn)(hostfxr_error_writer_fn error_writer);
typedef void* hostfxr_handle;
struct hostfxr_initialize_parameters
{
size_t size;
const char_t *host_path;
const char_t *dotnet_root;
};
//
// Initializes the hosting components for a dotnet command line running an application
//
// Parameters:
// argc
// Number of argv arguments
// argv
// Command-line arguments for running an application (as if through the dotnet executable).
// Only command-line arguments which are accepted by runtime installation are supported, SDK/CLI commands are not supported.
// For example 'app.dll app_argument_1 app_argument_2`.
// parameters
// Optional. Additional parameters for initialization
// host_context_handle
// On success, this will be populated with an opaque value representing the initialized host context
//
// Return value:
// Success - Hosting components were successfully initialized
// HostInvalidState - Hosting components are already initialized
//
// This function parses the specified command-line arguments to determine the application to run. It will
// then find the corresponding .runtimeconfig.json and .deps.json with which to resolve frameworks and
// dependencies and prepare everything needed to load the runtime.
//
// This function only supports arguments for running an application. It does not support SDK commands.
//
// This function does not load the runtime.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_initialize_for_dotnet_command_line_fn)(
int argc,
const char_t **argv,
const struct hostfxr_initialize_parameters *parameters,
/*out*/ hostfxr_handle *host_context_handle);
//
// Initializes the hosting components using a .runtimeconfig.json file
//
// Parameters:
// runtime_config_path
// Path to the .runtimeconfig.json file
// parameters
// Optional. Additional parameters for initialization
// host_context_handle
// On success, this will be populated with an opaque value representing the initialized host context
//
// Return value:
// Success - Hosting components were successfully initialized
// Success_HostAlreadyInitialized - Config is compatible with already initialized hosting components
// Success_DifferentRuntimeProperties - Config has runtime properties that differ from already initialized hosting components
// CoreHostIncompatibleConfig - Config is incompatible with already initialized hosting components
//
// This function will process the .runtimeconfig.json to resolve frameworks and prepare everything needed
// to load the runtime. It will only process the .deps.json from frameworks (not any app/component that
// may be next to the .runtimeconfig.json).
//
// This function does not load the runtime.
//
// If called when the runtime has already been loaded, this function will check if the specified runtime
// config is compatible with the existing runtime.
//
// Both Success_HostAlreadyInitialized and Success_DifferentRuntimeProperties codes are considered successful
// initializations. In the case of Success_DifferentRuntimeProperties, it is left to the consumer to verify that
// the difference in properties is acceptable.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_initialize_for_runtime_config_fn)(
const char_t *runtime_config_path,
const struct hostfxr_initialize_parameters *parameters,
/*out*/ hostfxr_handle *host_context_handle);
//
// Gets the runtime property value for an initialized host context
//
// Parameters:
// host_context_handle
// Handle to the initialized host context
// name
// Runtime property name
// value
// Out parameter. Pointer to a buffer with the property value.
//
// Return value:
// The error code result.
//
// The buffer pointed to by value is owned by the host context. The lifetime of the buffer is only
// guaranteed until any of the below occur:
// - a 'run' method is called for the host context
// - properties are changed via hostfxr_set_runtime_property_value
// - the host context is closed via 'hostfxr_close'
//
// If host_context_handle is nullptr and an active host context exists, this function will get the
// property value for the active host context.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_get_runtime_property_value_fn)(
const hostfxr_handle host_context_handle,
const char_t *name,
/*out*/ const char_t **value);
//
// Sets the value of a runtime property for an initialized host context
//
// Parameters:
// host_context_handle
// Handle to the initialized host context
// name
// Runtime property name
// value
// Value to set
//
// Return value:
// The error code result.
//
// Setting properties is only supported for the first host context, before the runtime has been loaded.
//
// If the property already exists in the host context, it will be overwritten. If value is nullptr, the
// property will be removed.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_set_runtime_property_value_fn)(
const hostfxr_handle host_context_handle,
const char_t *name,
const char_t *value);
//
// Gets all the runtime properties for an initialized host context
//
// Parameters:
// host_context_handle
// Handle to the initialized host context
// count
// [in] Size of the keys and values buffers
// [out] Number of properties returned (size of keys/values buffers used). If the input value is too
// small or keys/values is nullptr, this is populated with the number of available properties
// keys
// Array of pointers to buffers with runtime property keys
// values
// Array of pointers to buffers with runtime property values
//
// Return value:
// The error code result.
//
// The buffers pointed to by keys and values are owned by the host context. The lifetime of the buffers is only
// guaranteed until any of the below occur:
// - a 'run' method is called for the host context
// - properties are changed via hostfxr_set_runtime_property_value
// - the host context is closed via 'hostfxr_close'
//
// If host_context_handle is nullptr and an active host context exists, this function will get the
// properties for the active host context.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_get_runtime_properties_fn)(
const hostfxr_handle host_context_handle,
/*inout*/ size_t * count,
/*out*/ const char_t **keys,
/*out*/ const char_t **values);
//
// Load CoreCLR and run the application for an initialized host context
//
// Parameters:
// host_context_handle
// Handle to the initialized host context
//
// Return value:
// If the app was successfully run, the exit code of the application. Otherwise, the error code result.
//
// The host_context_handle must have been initialized using hostfxr_initialize_for_dotnet_command_line.
//
// This function will not return until the managed application exits.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_run_app_fn)(const hostfxr_handle host_context_handle);
//
// Gets a typed delegate from the currently loaded CoreCLR or from a newly created one.
//
// Parameters:
// host_context_handle
// Handle to the initialized host context
// type
// Type of runtime delegate requested
// delegate
// An out parameter that will be assigned the delegate.
//
// Return value:
// The error code result.
//
// If the host_context_handle was initialized using hostfxr_initialize_for_runtime_config,
// then all delegate types are supported.
// If the host_context_handle was initialized using hostfxr_initialize_for_dotnet_command_line,
// then only the following delegate types are currently supported:
// hdt_load_assembly_and_get_function_pointer
// hdt_get_function_pointer
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_get_runtime_delegate_fn)(
const hostfxr_handle host_context_handle,
enum hostfxr_delegate_type type,
/*out*/ void **delegate);
//
// Closes an initialized host context
//
// Parameters:
// host_context_handle
// Handle to the initialized host context
//
// Return value:
// The error code result.
//
typedef int32_t(HOSTFXR_CALLTYPE *hostfxr_close_fn)(const hostfxr_handle host_context_handle);
struct hostfxr_dotnet_environment_sdk_info
{
size_t size;
const char_t* version;
const char_t* path;
};
typedef void(HOSTFXR_CALLTYPE* hostfxr_get_dotnet_environment_info_result_fn)(
const struct hostfxr_dotnet_environment_info* info,
void* result_context);
struct hostfxr_dotnet_environment_framework_info
{
size_t size;
const char_t* name;
const char_t* version;
const char_t* path;
};
struct hostfxr_dotnet_environment_info
{
size_t size;
const char_t* hostfxr_version;
const char_t* hostfxr_commit_hash;
size_t sdk_count;
const hostfxr_dotnet_environment_sdk_info* sdks;
size_t framework_count;
const hostfxr_dotnet_environment_framework_info* frameworks;
};
#endif //__HOSTFXR_H__
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,99 +0,0 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#ifndef __NETHOST_H__
#define __NETHOST_H__
#include <stddef.h>
#ifdef _WIN32
#ifdef NETHOST_EXPORT
#define NETHOST_API __declspec(dllexport)
#else
// Consuming the nethost as a static library
// Shouldn't export attempt to dllimport.
#ifdef NETHOST_USE_AS_STATIC
#define NETHOST_API
#else
#define NETHOST_API __declspec(dllimport)
#endif
#endif
#define NETHOST_CALLTYPE __stdcall
#ifdef _WCHAR_T_DEFINED
typedef wchar_t char_t;
#else
typedef unsigned short char_t;
#endif
#else
#ifdef NETHOST_EXPORT
#define NETHOST_API __attribute__((__visibility__("default")))
#else
#define NETHOST_API
#endif
#define NETHOST_CALLTYPE
typedef char char_t;
#endif
#ifdef __cplusplus
extern "C" {
#endif
// Parameters for get_hostfxr_path
//
// Fields:
// size
// Size of the struct. This is used for versioning.
//
// assembly_path
// Path to the compenent's assembly.
// If specified, hostfxr is located as if the assembly_path is the apphost
//
// dotnet_root
// Path to directory containing the dotnet executable.
// If specified, hostfxr is located as if an application is started using
// 'dotnet app.dll', which means it will be searched for under the dotnet_root
// path and the assembly_path is ignored.
//
struct get_hostfxr_parameters {
size_t size;
const char_t *assembly_path;
const char_t *dotnet_root;
};
//
// Get the path to the hostfxr library
//
// Parameters:
// buffer
// Buffer that will be populated with the hostfxr path, including a null terminator.
//
// buffer_size
// [in] Size of buffer in char_t units.
// [out] Size of buffer used in char_t units. If the input value is too small
// or buffer is nullptr, this is populated with the minimum required size
// in char_t units for a buffer to hold the hostfxr path
//
// get_hostfxr_parameters
// Optional. Parameters that modify the behaviour for locating the hostfxr library.
// If nullptr, hostfxr is located using the enviroment variable or global registration
//
// Return value:
// 0 on success, otherwise failure
// 0x80008098 - buffer is too small (HostApiBufferTooSmall)
//
// Remarks:
// The full search for the hostfxr library is done on every call. To minimize the need
// to call this function multiple times, pass a large buffer (e.g. PATH_MAX).
//
NETHOST_API int NETHOST_CALLTYPE get_hostfxr_path(
char_t * buffer,
size_t * buffer_size,
const struct get_hostfxr_parameters *parameters);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // __NETHOST_H__
Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More