diff --git a/src/Immersion/PictureInPictureFollow.cs b/src/Immersion/PictureInPictureFollow.cs index dea011f..21b1f5c 100644 --- a/src/Immersion/PictureInPictureFollow.cs +++ b/src/Immersion/PictureInPictureFollow.cs @@ -11,7 +11,7 @@ public class PictureInPictureFollow { public Game Game { get; } = null!; - public Universe.Entity PIPCamera { get; private set; } + public Universe.Entity PipCamera { get; private set; } public void OnLoad() { @@ -21,8 +21,8 @@ public void OnLoad() // var (_, mesh) = Game.GetAll().First(); // Game.Set(Game.MainCamera, mesh); - PIPCamera = Game.Entities.New() - .Set(Camera.Create3D( + PipCamera = Game.Entities.New() + .Set(Camera.Create3d( fieldOfView: 90.0F, clearColor: Color.Black, viewport: new(8, 8, 320, 180) @@ -31,8 +31,8 @@ public void OnLoad() public void OnUnload() { - PIPCamera.Delete(); - PIPCamera = default; + PipCamera.Delete(); + PipCamera = default; } public void OnUpdate(double delta) @@ -40,7 +40,7 @@ public void OnUpdate(double delta) var cameraPos = Game.MainCamera.Get().Translation; var lookAt = Matrix4x4.CreateLookAt(new(8, 28, 8), cameraPos, Vector3.UnitY); Matrix4x4.Invert(lookAt, out lookAt); - PIPCamera.Set((Transform)lookAt); + PipCamera.Set((Transform)lookAt); } } } diff --git a/src/Immersion/Program.cs b/src/Immersion/Program.cs index 53d9b65..ba81f73 100644 --- a/src/Immersion/Program.cs +++ b/src/Immersion/Program.cs @@ -18,7 +18,7 @@ public class Program : Game static void Main() => new Program().Run(); - public Random RND { get; } = new(); + public Random Rnd { get; } = new(); public Program() { @@ -45,10 +45,10 @@ protected override void OnLoad() for (var x = -12; x <= 12; x++) for (var z = -12; z <= 12; z++) { var position = Matrix4x4.CreateTranslation(x * 2, 25, z * 2); - var rotation = Matrix4x4.CreateRotationY(RND.NextFloat(MathF.PI * 2)); + var rotation = Matrix4x4.CreateRotationY(Rnd.NextFloat(MathF.PI * 2)); Entities.New() .Set((Transform)(rotation * position)) - .Set(RND.Pick(heartMesh, swordMesh)); + .Set(Rnd.Pick(heartMesh, swordMesh)); } MainCamera.Set((Transform)Matrix4x4.CreateTranslation(0, 26, 0)); @@ -68,7 +68,7 @@ void CreateChunk(ChunkPos pos) for (var y = 0; y < 16; y++) for (var z = 0; z < 16; z++) { var yy = (pos.Y << 4) | y; - if (RND.NextBool(0.5 - yy / 48.0)) + if (Rnd.NextBool(0.5 - yy / 48.0)) storage[x, y, z] = new((yy > 16) ? grass : (yy > -16) ? dirt : stone); diff --git a/src/gaemstone.Bloxel/BlockFacing.cs b/src/gaemstone.Bloxel/BlockFacing.cs index a92aa96..e603773 100644 --- a/src/gaemstone.Bloxel/BlockFacing.cs +++ b/src/gaemstone.Bloxel/BlockFacing.cs @@ -16,15 +16,15 @@ public enum BlockFacing public static class BlockFacings { - public static readonly ImmutableHashSet HORIZONTALS + public static readonly ImmutableHashSet Horizontals = ImmutableHashSet.Create(BlockFacing.East , BlockFacing.West , BlockFacing.South, BlockFacing.North); - public static readonly ImmutableHashSet VERTICALS + public static readonly ImmutableHashSet Verticals = ImmutableHashSet.Create(BlockFacing.Up, BlockFacing.Down); - public static readonly ImmutableHashSet ALL - = HORIZONTALS.Union(VERTICALS); + public static readonly ImmutableHashSet All + = Horizontals.Union(Verticals); } public static class BlockFacingExtensions diff --git a/src/gaemstone.Bloxel/BlockPos.cs b/src/gaemstone.Bloxel/BlockPos.cs index 51091ca..a10e5f7 100644 --- a/src/gaemstone.Bloxel/BlockPos.cs +++ b/src/gaemstone.Bloxel/BlockPos.cs @@ -6,7 +6,7 @@ namespace gaemstone.Bloxel public readonly struct BlockPos : IEquatable { - public static readonly BlockPos ORIGIN = new(0, 0, 0); + public static readonly BlockPos Origin = new(0, 0, 0); public int X { get; } public int Y { get; } diff --git a/src/gaemstone.Bloxel/Chunks/ChunkPaletteStorage.cs b/src/gaemstone.Bloxel/Chunks/ChunkPaletteStorage.cs index 4ff4c18..d55ceef 100644 --- a/src/gaemstone.Bloxel/Chunks/ChunkPaletteStorage.cs +++ b/src/gaemstone.Bloxel/Chunks/ChunkPaletteStorage.cs @@ -9,7 +9,7 @@ namespace gaemstone.Bloxel.Chunks // https://www.reddit.com/r/VoxelGameDev/comments/9yu8qy/palettebased_compression_for_chunked_discrete/ public class ChunkPaletteStorage { - const int SIZE = 16 * 16 * 16; + const int Size = 16 * 16 * 16; static readonly EqualityComparer COMPARER = EqualityComparer.Default; @@ -90,19 +90,19 @@ int NewPaletteEntry() void GrowPalette() { if (_palette == null) { - _data = new(SIZE); + _data = new(Size); _palette = new PaletteEntry[2]; _usedPalettes = 1; _indicesLength = 1; - _palette[0] = new PaletteEntry { Value = Default, RefCount = SIZE }; + _palette[0] = new PaletteEntry { Value = Default, RefCount = Size }; return; } _indicesLength <<= 1; var oldIndicesLength = _indicesLength >> 1; - var newData = new BitArray(SIZE * _indicesLength); - for (var i = 0; i < SIZE; i++) + var newData = new BitArray(Size * _indicesLength); + for (var i = 0; i < Size; i++) for (var j = 0; j < oldIndicesLength; j++) newData.Set(i * _indicesLength + j, _data!.Get(i * oldIndicesLength + j)); _data = newData; diff --git a/src/gaemstone.Bloxel/Client/ChunkMeshGenerator.cs b/src/gaemstone.Bloxel/Client/ChunkMeshGenerator.cs index 54427c3..929030e 100644 --- a/src/gaemstone.Bloxel/Client/ChunkMeshGenerator.cs +++ b/src/gaemstone.Bloxel/Client/ChunkMeshGenerator.cs @@ -11,9 +11,9 @@ namespace gaemstone.Bloxel.Client public class ChunkMeshGenerator : IProcessor { - const int STARTING_CAPACITY = 1024; + const int StartingCapacity = 1024; - static readonly Vector3[][] OFFSET_PER_FACING = { + static readonly Vector3[][] OffsetPerFacing = { new Vector3[]{ new(1,1,1), new(1,0,1), new(1,0,0), new(1,1,0) }, // East (+X) new Vector3[]{ new(0,1,0), new(0,0,0), new(0,0,1), new(0,1,1) }, // West (-X) new Vector3[]{ new(1,1,0), new(0,1,0), new(0,1,1), new(1,1,1) }, // Up (+Y) @@ -22,7 +22,7 @@ public class ChunkMeshGenerator new Vector3[]{ new(1,1,0), new(1,0,0), new(0,0,0), new(0,1,0) } // North (-Z) }; - static readonly int[] TRIANGLE_INDICES + static readonly int[] TriangleIndices = { 0, 1, 3, 1, 2, 3 }; @@ -31,10 +31,10 @@ static readonly int[] TRIANGLE_INDICES // TODO: Automatically populate other processors. MeshManager _meshManager = null!; - ushort[] _indices = new ushort[STARTING_CAPACITY]; - Vector3[] _vertices = new Vector3[STARTING_CAPACITY]; - Vector3[] _normals = new Vector3[STARTING_CAPACITY]; - Vector2[] _uvs = new Vector2[STARTING_CAPACITY]; + ushort[] _indices = new ushort[StartingCapacity]; + Vector3[] _vertices = new Vector3[StartingCapacity]; + Vector3[] _normals = new Vector3[StartingCapacity]; + Vector2[] _uvs = new Vector2[StartingCapacity]; public void OnLoad() @@ -80,7 +80,7 @@ public void OnUpdate(double delta) var blockVertex = new Vector3(x, y, z); var textureCell = Game.Get(block); - foreach (var facing in BlockFacings.ALL) { + foreach (var facing in BlockFacings.All) { if (!IsNeighborEmpty(storages, x, y, z, facing)) continue; if (_indices.Length <= indexCount + 6) @@ -91,12 +91,12 @@ public void OnUpdate(double delta) Array.Resize(ref _uvs , _vertices.Length << 1); } - for (var i = 0; i < TRIANGLE_INDICES.Length; i++) - _indices[indexCount++] = (ushort)(vertexCount + TRIANGLE_INDICES[i]); + for (var i = 0; i < TriangleIndices.Length; i++) + _indices[indexCount++] = (ushort)(vertexCount + TriangleIndices[i]); var normal = facing.ToVector3(); for (var i = 0; i < 4; i++) { - var offset = OFFSET_PER_FACING[(int)facing][i]; + var offset = OffsetPerFacing[(int)facing][i]; _vertices[vertexCount] = blockVertex + offset; _normals[vertexCount] = normal; _uvs[vertexCount] = i switch { diff --git a/src/gaemstone.Bloxel/Neighbor.cs b/src/gaemstone.Bloxel/Neighbor.cs index d910a80..8212df9 100644 --- a/src/gaemstone.Bloxel/Neighbor.cs +++ b/src/gaemstone.Bloxel/Neighbor.cs @@ -49,23 +49,23 @@ public enum Neighbor : byte public static class Neighbors { - public static readonly ImmutableHashSet HORIZONTALS + public static readonly ImmutableHashSet Horizontals = ImmutableHashSet.Create(Neighbor.East , Neighbor.West , Neighbor.South, Neighbor.North); - public static readonly ImmutableHashSet VERTICALS + public static readonly ImmutableHashSet Verticals = ImmutableHashSet.Create(Neighbor.Up, Neighbor.Down); - public static readonly ImmutableHashSet FACINGS - = HORIZONTALS.Union(VERTICALS); + public static readonly ImmutableHashSet Facings + = Horizontals.Union(Verticals); - public static readonly ImmutableHashSet CARDINALS - = HORIZONTALS.Union(new []{ + public static readonly ImmutableHashSet Cardinals + = Horizontals.Union(new []{ Neighbor.SouthEast, Neighbor.SouthWest, Neighbor.NorthEast, Neighbor.NorthWest }); - public static readonly ImmutableHashSet ALL_AXIS_PLANES - = FACINGS.Union(new []{ + public static readonly ImmutableHashSet AllAxisPlanes + = Facings.Union(new []{ Neighbor.SouthEast, Neighbor.SouthWest, Neighbor.NorthEast, Neighbor.NorthWest, Neighbor.UpEast , Neighbor.UpWest , @@ -73,8 +73,8 @@ public static readonly ImmutableHashSet ALL_AXIS_PLANES Neighbor.DownEast , Neighbor.DownWest , Neighbor.DownSouth, Neighbor.DownNorth }); - public static readonly ImmutableHashSet ALL - = ALL_AXIS_PLANES.Union(new []{ + public static readonly ImmutableHashSet All + = AllAxisPlanes.Union(new []{ Neighbor.UpSouthEast, Neighbor.UpSouthWest, Neighbor.UpNorthEast, Neighbor.UpNorthWest, Neighbor.DownSouthEast, Neighbor.DownSouthWest, @@ -83,14 +83,14 @@ public static readonly ImmutableHashSet ALL public static class NeighborExtensions { - const int X_SET_BIT = 0b000010, X_VALUE_BIT = 0b000001; - const int Y_SET_BIT = 0b001000, Y_VALUE_BIT = 0b000100; - const int Z_SET_BIT = 0b100000, Z_VALUE_BIT = 0b010000; + const int SetBitX = 0b000010, ValueBitX = 0b000001; + const int SetBitY = 0b001000, ValueBitY = 0b000100; + const int SetBitZ = 0b100000, ValueBitZ = 0b010000; public static void Deconstruct(this Neighbor self, out int x, out int y, out int z) { - x = (((int)self & X_SET_BIT) != 0) ? ((((int)self & X_VALUE_BIT) != 0) ? 1 : -1) : 0; - y = (((int)self & Y_SET_BIT) != 0) ? ((((int)self & Y_VALUE_BIT) != 0) ? 1 : -1) : 0; - z = (((int)self & Z_SET_BIT) != 0) ? ((((int)self & Z_VALUE_BIT) != 0) ? 1 : -1) : 0; + x = (((int)self & SetBitX) != 0) ? ((((int)self & ValueBitX) != 0) ? 1 : -1) : 0; + y = (((int)self & SetBitY) != 0) ? ((((int)self & ValueBitY) != 0) ? 1 : -1) : 0; + z = (((int)self & SetBitZ) != 0) ? ((((int)self & ValueBitZ) != 0) ? 1 : -1) : 0; } @@ -182,15 +182,15 @@ public static bool IsNone(this Neighbor self) => (self == Neighbor.None); public static bool IsHorizontal(this Neighbor self) - => Neighbors.HORIZONTALS.Contains(self); + => Neighbors.Horizontals.Contains(self); public static bool IsVertical(this Neighbor self) - => Neighbors.VERTICALS.Contains(self); + => Neighbors.Verticals.Contains(self); public static bool IsCardinal(this Neighbor self) - => Neighbors.CARDINALS.Contains(self); + => Neighbors.Cardinals.Contains(self); public static bool IsFacing(this Neighbor self) - => Neighbors.FACINGS.Contains(self); + => Neighbors.Facings.Contains(self); public static bool IsValid(this Neighbor self) - => Neighbors.ALL.Contains(self); + => Neighbors.All.Contains(self); public static string ToShortString(this Neighbor self) diff --git a/src/gaemstone.Client/Components/Camera.cs b/src/gaemstone.Client/Components/Camera.cs index 6b1696c..e4492d8 100644 --- a/src/gaemstone.Client/Components/Camera.cs +++ b/src/gaemstone.Client/Components/Camera.cs @@ -3,10 +3,10 @@ namespace gaemstone.Client { public class Camera { - public static readonly Camera Default2D = Create2D(); - public static readonly Camera Default3D = Create3D(80.0F); + public static readonly Camera Default2d = Create2d(); + public static readonly Camera Default3d = Create3d(80.0F); - public static Camera Create2D( + public static Camera Create2d( float nearPlane = -100.0F, float farPlane = 100.0F, Color? clearColor = null, Rectangle? viewport = null ) => new(){ @@ -14,7 +14,7 @@ public static Camera Create2D( ClearColor = clearColor, Viewport = viewport, }; - public static Camera Create3D( + public static Camera Create3d( float fieldOfView, float nearPlane = 0.1F, float farPlane = 200.0F, Color? clearColor = null, Rectangle? viewport = null ) => new(){ @@ -31,7 +31,7 @@ public static Camera Create3D( public bool IsOrthographic { get => (FieldOfView == 0.0F); - set => FieldOfView = (value ? 0.0F : Default3D.FieldOfView); + set => FieldOfView = (value ? 0.0F : Default3d.FieldOfView); } public override string ToString() diff --git a/src/gaemstone.Client/Game.cs b/src/gaemstone.Client/Game.cs index 00aa916..65e090a 100644 --- a/src/gaemstone.Client/Game.cs +++ b/src/gaemstone.Client/Game.cs @@ -60,8 +60,8 @@ protected virtual void OnLoad() { _input = Window.CreateInput(); - GFX.Initialize(Window); - GFX.OnDebugOutput += (source, type, id, severity, message) => + Gfx.Initialize(Window); + Gfx.OnDebugOutput += (source, type, id, severity, message) => Console.WriteLine($"[GLDebug] [{severity}] {type}/{id}: {message}"); // TODO: Automatically create components that have a specific attribute? @@ -78,7 +78,7 @@ protected virtual void OnLoad() MainCamera = Entities.New() .Set((Transform)Matrix4x4.Identity) - .Set(Camera.Default3D); + .Set(Camera.Default3d); } protected virtual void OnClosing() diff --git a/src/gaemstone.Client/Graphics/Components/Mesh.cs b/src/gaemstone.Client/Graphics/Components/Mesh.cs index 46779bd..794a41e 100644 --- a/src/gaemstone.Client/Graphics/Components/Mesh.cs +++ b/src/gaemstone.Client/Graphics/Components/Mesh.cs @@ -4,22 +4,22 @@ namespace gaemstone.Client.Graphics { public readonly struct Mesh { - public VertexArray VAO { get; } + public VertexArray Vao { get; } public int Triangles { get; } public bool IsIndexed { get; } internal Mesh(VertexArray vao, int triangles, bool isIndexed = true) - => (VAO, Triangles, IsIndexed) = (vao, triangles, isIndexed); + => (Vao, Triangles, IsIndexed) = (vao, triangles, isIndexed); public void Draw() => Draw(0, Triangles * 3); public void Draw(int start, int count) { unsafe { - VAO.Bind(); - if (IsIndexed) GFX.GL.DrawElements( + Vao.Bind(); + if (IsIndexed) Gfx.Gl.DrawElements( PrimitiveType.Triangles, (uint)count, DrawElementsType.UnsignedShort, (void*)start); - else GFX.GL.DrawArrays( + else Gfx.Gl.DrawArrays( PrimitiveType.Triangles, start, (uint)count); } } diff --git a/src/gaemstone.Client/Graphics/Components/Texture.cs b/src/gaemstone.Client/Graphics/Components/Texture.cs index 542971d..b1450a0 100644 --- a/src/gaemstone.Client/Graphics/Components/Texture.cs +++ b/src/gaemstone.Client/Graphics/Components/Texture.cs @@ -6,7 +6,7 @@ namespace gaemstone.Client.Graphics public readonly struct Texture { public static Texture Gen(TextureTarget target) - => new(target, GFX.GL.GenTexture()); + => new(target, Gfx.Gl.GenTexture()); public TextureTarget Target { get; } @@ -18,37 +18,37 @@ public Texture(TextureTarget target, uint handle) public UnbindOnDispose Bind() { - GFX.GL.BindTexture(Target, Handle); + Gfx.Gl.BindTexture(Target, Handle); return new(Target); } public void Unbind() - => GFX.GL.BindTexture(Target, 0); + => Gfx.Gl.BindTexture(Target, 0); public static void Unbind(TextureTarget target) - => GFX.GL.BindTexture(target, 0); + => Gfx.Gl.BindTexture(target, 0); public readonly struct UnbindOnDispose : IDisposable { public TextureTarget Target { get; } public UnbindOnDispose(TextureTarget target) => Target = target; - public void Dispose() => GFX.GL.BindTexture(Target, 0); + public void Dispose() => Gfx.Gl.BindTexture(Target, 0); } public TextureMagFilter MagFilter { get { - GFX.GL.GetTexParameterI(Target, GetTextureParameter.TextureMagFilter, out int value); + Gfx.Gl.GetTexParameterI(Target, GetTextureParameter.TextureMagFilter, out int value); return (TextureMagFilter)value; } - set => GFX.GL.TexParameterI(Target, TextureParameterName.TextureMagFilter, (int)value); + set => Gfx.Gl.TexParameterI(Target, TextureParameterName.TextureMagFilter, (int)value); } public TextureMinFilter MinFilter { get { - GFX.GL.GetTexParameterI(Target, GetTextureParameter.TextureMinFilter, out int value); + Gfx.Gl.GetTexParameterI(Target, GetTextureParameter.TextureMinFilter, out int value); return (TextureMinFilter)value; } - set => GFX.GL.TexParameterI(Target, TextureParameterName.TextureMinFilter, (int)value); + set => Gfx.Gl.TexParameterI(Target, TextureParameterName.TextureMinFilter, (int)value); } } } diff --git a/src/gaemstone.Client/Graphics/GFX.cs b/src/gaemstone.Client/Graphics/Gfx.cs similarity index 57% rename from src/gaemstone.Client/Graphics/GFX.cs rename to src/gaemstone.Client/Graphics/Gfx.cs index 9846a37..f3b1519 100644 --- a/src/gaemstone.Client/Graphics/GFX.cs +++ b/src/gaemstone.Client/Graphics/Gfx.cs @@ -8,10 +8,10 @@ namespace gaemstone.Client.Graphics { - public static class GFX + public static class Gfx { static GL? _gl; - public static GL GL => _gl + public static GL Gl => _gl ?? throw new InvalidOperationException("OpenGL has not been initialized"); public static bool IsInitialized => (_gl != null); @@ -23,8 +23,8 @@ public static void Initialize(IGLContextSource glContextSource) // FIXME: Debugger currently doesn't like us specifying a callback. if (!Debugger.IsAttached) { - GL.Enable(GLEnum.DebugOutput); - GL.DebugMessageCallback( + Gl.Enable(GLEnum.DebugOutput); + Gl.DebugMessageCallback( (source, type, id, severity, length, message, userParam) => OnDebugOutput?.Invoke( (DebugSource)source, (DebugType)type, id, @@ -32,47 +32,47 @@ public static void Initialize(IGLContextSource glContextSource) false); } - GL.Enable(EnableCap.CullFace); - GL.CullFace(CullFaceMode.Back); + Gl.Enable(EnableCap.CullFace); + Gl.CullFace(CullFaceMode.Back); - GL.Enable(EnableCap.DepthTest); - GL.DepthFunc(DepthFunction.Less); + Gl.Enable(EnableCap.DepthTest); + Gl.DepthFunc(DepthFunction.Less); - GL.Enable(EnableCap.Blend); - GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); + Gl.Enable(EnableCap.Blend); + Gl.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); } public static void Clear(Color color) { - GL.ClearColor(color); - GL.Clear((uint)(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit)); + Gl.ClearColor(color); + Gl.Clear((uint)(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit)); } public static void Clear(Vector4 color) { - GL.ClearColor(color.X, color.Y, color.Z, color.W); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); + Gl.ClearColor(color.X, color.Y, color.Z, color.W); + Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); } public static void Clear(Color color, Rectangle area) { - GL.Enable(EnableCap.ScissorTest); - GL.Scissor(area.X, area.Y, (uint)area.Width, (uint)area.Height); - GL.ClearColor(color); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - GL.Disable(EnableCap.ScissorTest); + Gl.Enable(EnableCap.ScissorTest); + Gl.Scissor(area.X, area.Y, (uint)area.Width, (uint)area.Height); + Gl.ClearColor(color); + Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); + Gl.Disable(EnableCap.ScissorTest); } public static void Clear(Vector4 color, Rectangle area) { - GL.Enable(EnableCap.ScissorTest); - GL.Scissor(area.X, area.Y, (uint)area.Width, (uint)area.Height); - GL.ClearColor(color.X, color.Y, color.Z, color.W); - GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); - GL.Disable(EnableCap.ScissorTest); + Gl.Enable(EnableCap.ScissorTest); + Gl.Scissor(area.X, area.Y, (uint)area.Width, (uint)area.Height); + Gl.ClearColor(color.X, color.Y, color.Z, color.W); + Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); + Gl.Disable(EnableCap.ScissorTest); } public static void Viewport(Size size) - => GL.Viewport(size); + => Gl.Viewport(size); public static void Viewport(Rectangle rectangle) - => GL.Viewport(rectangle); + => Gl.Viewport(rectangle); static int MAX_LABEL_LENGTH; static string? LABEL_BUFFER; @@ -80,13 +80,13 @@ public static string GetObjectLabel(ObjectIdentifier identifier, uint handle) { if (MAX_LABEL_LENGTH == 0) { // One-time initialization. - MAX_LABEL_LENGTH = GL.GetInteger(GLEnum.MaxLabelLength); + MAX_LABEL_LENGTH = Gl.GetInteger(GLEnum.MaxLabelLength); LABEL_BUFFER = new(' ', MAX_LABEL_LENGTH); } - GL.GetObjectLabel(identifier, handle, (uint)MAX_LABEL_LENGTH, out var length, out LABEL_BUFFER); + Gl.GetObjectLabel(identifier, handle, (uint)MAX_LABEL_LENGTH, out var length, out LABEL_BUFFER); return LABEL_BUFFER[..(int)length]; } public static void SetObjectLabel(ObjectIdentifier identifier, uint handle, string label) - => GL.ObjectLabel(identifier, handle, (uint)label.Length, label); + => Gl.ObjectLabel(identifier, handle, (uint)label.Length, label); } } diff --git a/src/gaemstone.Client/Graphics/OpenGL/Buffer.cs b/src/gaemstone.Client/Graphics/OpenGL/Buffer.cs index ad7cc46..7becffb 100644 --- a/src/gaemstone.Client/Graphics/OpenGL/Buffer.cs +++ b/src/gaemstone.Client/Graphics/OpenGL/Buffer.cs @@ -7,7 +7,7 @@ namespace gaemstone.Client.Graphics public readonly struct Buffer { public static Buffer Gen(BufferTargetARB target) - => new(GFX.GL.GenBuffer(), target); + => new(Gfx.Gl.GenBuffer(), target); // These overloads are available because without them, the implicit casting // (say from T[] to ReadOnlySpan) causes the generic type resolving to break. @@ -45,7 +45,7 @@ public static Buffer CreateFromData(ReadOnlySpan data, => (Handle, Target) = (handle, target); public void Bind() - => GFX.GL.BindBuffer(Target, Handle); + => Gfx.Gl.BindBuffer(Target, Handle); public void Data(T[] data, BufferUsageARB usage) where T : unmanaged @@ -58,6 +58,6 @@ public void Data(Span data, BufferUsageARB usage) => Data((ReadOnlySpan)data, usage); public void Data(ReadOnlySpan data, BufferUsageARB usage) where T : unmanaged - => GFX.GL.BufferData(Target, (UIntPtr)(data.Length * Unsafe.SizeOf()), data, usage); + => Gfx.Gl.BufferData(Target, (UIntPtr)(data.Length * Unsafe.SizeOf()), data, usage); } } diff --git a/src/gaemstone.Client/Graphics/OpenGL/Program.cs b/src/gaemstone.Client/Graphics/OpenGL/Program.cs index 8fa2fed..785afb3 100644 --- a/src/gaemstone.Client/Graphics/OpenGL/Program.cs +++ b/src/gaemstone.Client/Graphics/OpenGL/Program.cs @@ -8,7 +8,7 @@ namespace gaemstone.Client.Graphics public readonly struct Program { public static Program Create() - => new(GFX.GL.CreateProgram()); + => new(Gfx.Gl.CreateProgram()); public static Program LinkFromShaders(string label, params Shader[] shaders) { @@ -26,31 +26,31 @@ public static Program LinkFromShaders(string label, params Shader[] shaders) Program(uint handle) => Handle = handle; public string Label { - get => GFX.GetObjectLabel(ObjectIdentifier.Program, Handle); - set => GFX.SetObjectLabel(ObjectIdentifier.Program, Handle, value); + get => Gfx.GetObjectLabel(ObjectIdentifier.Program, Handle); + set => Gfx.SetObjectLabel(ObjectIdentifier.Program, Handle, value); } public void Attach(Shader shader) - => GFX.GL.AttachShader(Handle, shader.Handle); + => Gfx.Gl.AttachShader(Handle, shader.Handle); public void Link() { - GFX.GL.LinkProgram(Handle); - GFX.GL.GetProgram(Handle, ProgramPropertyARB.LinkStatus, out var result); + Gfx.Gl.LinkProgram(Handle); + Gfx.Gl.GetProgram(Handle, ProgramPropertyARB.LinkStatus, out var result); if (result != (int)GLEnum.True) throw new Exception( - $"Failed linking Program \"{Label}\" ({Handle}):\n{GFX.GL.GetProgramInfoLog(Handle)}"); + $"Failed linking Program \"{Label}\" ({Handle}):\n{Gfx.Gl.GetProgramInfoLog(Handle)}"); } public void Detach(Shader shader) - => GFX.GL.DetachShader(Handle, shader.Handle); + => Gfx.Gl.DetachShader(Handle, shader.Handle); public ICollection GetAttachedShaders() { - GFX.GL.GetProgram(Handle, ProgramPropertyARB.AttachedShaders, out var count); + Gfx.Gl.GetProgram(Handle, ProgramPropertyARB.AttachedShaders, out var count); var shaders = new uint[count]; - GFX.GL.GetAttachedShaders(Handle, (uint)count, out var _, out shaders[0]); + Gfx.Gl.GetAttachedShaders(Handle, (uint)count, out var _, out shaders[0]); return shaders.Select(handle => new Shader(handle)).ToArray(); } @@ -65,7 +65,7 @@ public void DetachAndDeleteShaders() public Uniforms GetActiveUniforms() => new(this); public VertexAttributes GetActiveAttributes() => new(this); - public void Use() => GFX.GL.UseProgram(Handle); - public void Delete() => GFX.GL.DeleteProgram(Handle); + public void Use() => Gfx.Gl.UseProgram(Handle); + public void Delete() => Gfx.Gl.DeleteProgram(Handle); } } diff --git a/src/gaemstone.Client/Graphics/OpenGL/Shader.cs b/src/gaemstone.Client/Graphics/OpenGL/Shader.cs index caee5db..0dc75db 100644 --- a/src/gaemstone.Client/Graphics/OpenGL/Shader.cs +++ b/src/gaemstone.Client/Graphics/OpenGL/Shader.cs @@ -6,7 +6,7 @@ namespace gaemstone.Client.Graphics public readonly struct Shader { public static Shader Create(ShaderType type) - => new(GFX.GL.CreateShader(type)); + => new(Gfx.Gl.CreateShader(type)); public static Shader CompileFromSource(string label, ShaderType type, string source) { @@ -23,34 +23,34 @@ public static Shader CompileFromSource(string label, ShaderType type, string sou internal Shader(uint handle) => Handle = handle; public ShaderType Type { get { - GFX.GL.GetShader(Handle, GLEnum.ShaderType, out var shaderType); + Gfx.Gl.GetShader(Handle, GLEnum.ShaderType, out var shaderType); return (ShaderType)shaderType; } } public string Label { - get => GFX.GetObjectLabel(ObjectIdentifier.Shader, Handle); - set => GFX.SetObjectLabel(ObjectIdentifier.Shader, Handle, value); + get => Gfx.GetObjectLabel(ObjectIdentifier.Shader, Handle); + set => Gfx.SetObjectLabel(ObjectIdentifier.Shader, Handle, value); } public string Source { get { - GFX.GL.GetShader(Handle, GLEnum.ShaderSourceLength, out var sourceLength); + Gfx.Gl.GetShader(Handle, GLEnum.ShaderSourceLength, out var sourceLength); var source = new string(' ', sourceLength); - GFX.GL.GetShaderSource(Handle, (uint)source.Length, out _, out source); + Gfx.Gl.GetShaderSource(Handle, (uint)source.Length, out _, out source); return source; } - set => GFX.GL.ShaderSource(Handle, value); + set => Gfx.Gl.ShaderSource(Handle, value); } public void Compile() { - GFX.GL.CompileShader(Handle); - GFX.GL.GetShader(Handle, ShaderParameterName.CompileStatus, out var result); + Gfx.Gl.CompileShader(Handle); + Gfx.Gl.GetShader(Handle, ShaderParameterName.CompileStatus, out var result); if (result != (int)GLEnum.True) throw new Exception( - $"Failed compiling shader \"{Label}\" ({Handle}):\n{GFX.GL.GetShaderInfoLog(Handle)}"); + $"Failed compiling shader \"{Label}\" ({Handle}):\n{Gfx.Gl.GetShaderInfoLog(Handle)}"); } public void Delete() - => GFX.GL.DeleteShader(Handle); + => Gfx.Gl.DeleteShader(Handle); } } diff --git a/src/gaemstone.Client/Graphics/OpenGL/Uniforms.cs b/src/gaemstone.Client/Graphics/OpenGL/Uniforms.cs index 8dc6035..3570e6d 100644 --- a/src/gaemstone.Client/Graphics/OpenGL/Uniforms.cs +++ b/src/gaemstone.Client/Graphics/OpenGL/Uniforms.cs @@ -19,15 +19,15 @@ public class Uniforms internal Uniforms(Program program) { - GFX.GL.GetProgram(program.Handle, ProgramPropertyARB.ActiveUniformMaxLength, out var uniformMaxLength); + Gfx.Gl.GetProgram(program.Handle, ProgramPropertyARB.ActiveUniformMaxLength, out var uniformMaxLength); var nameBuffer = new string(' ', uniformMaxLength); - GFX.GL.GetProgram(program.Handle, ProgramPropertyARB.ActiveUniforms, out var uniformCount); + Gfx.Gl.GetProgram(program.Handle, ProgramPropertyARB.ActiveUniforms, out var uniformCount); _activeUniforms = new UniformInfo[uniformCount]; for (uint uniformIndex = 0; uniformIndex < uniformCount; uniformIndex++) { - GFX.GL.GetActiveUniform(program.Handle, uniformIndex, (uint)uniformMaxLength, + Gfx.Gl.GetActiveUniform(program.Handle, uniformIndex, (uint)uniformMaxLength, out var length, out var size, out UniformType type, out nameBuffer); var name = nameBuffer[..(int)length]; - var location = GFX.GL.GetUniformLocation(program.Handle, name); + var location = Gfx.Gl.GetUniformLocation(program.Handle, name); var uniform = new UniformInfo(uniformIndex, location, size, type, name); _activeUniforms[uniformIndex] = uniform; _uniformsByName[nameBuffer] = uniform; @@ -71,36 +71,36 @@ public readonly struct UniformBool { public int Location { get; } internal UniformBool(int location) => Location = location; - public void Set(bool value) => GFX.GL.Uniform1(Location, value ? 1 : 0); + public void Set(bool value) => Gfx.Gl.Uniform1(Location, value ? 1 : 0); } public readonly struct UniformInt { public int Location { get; } internal UniformInt(int location) => Location = location; - public void Set(int value) => GFX.GL.Uniform1(Location, value); + public void Set(int value) => Gfx.Gl.Uniform1(Location, value); } public readonly struct UniformFloat { public int Location { get; } internal UniformFloat(int location) => Location = location; - public void Set(float value) => GFX.GL.Uniform1(Location, value); + public void Set(float value) => Gfx.Gl.Uniform1(Location, value); } public readonly struct UniformVector3 { public int Location { get; } internal UniformVector3(int location) => Location = location; - public void Set(in Vector3 value) => GFX.GL.Uniform3(Location, 1, in value.X); + public void Set(in Vector3 value) => Gfx.Gl.Uniform3(Location, 1, in value.X); } public readonly struct UniformVector4 { public int Location { get; } internal UniformVector4(int location) => Location = location; - public void Set(in Vector4 value) => GFX.GL.Uniform4(Location, 1, in value.X); + public void Set(in Vector4 value) => Gfx.Gl.Uniform4(Location, 1, in value.X); } public readonly struct UniformMatrix4x4 { public int Location { get; } internal UniformMatrix4x4(int location) => Location = location; - public void Set(in Matrix4x4 value) => GFX.GL.UniformMatrix4(Location, 1, false, in value.M11); + public void Set(in Matrix4x4 value) => Gfx.Gl.UniformMatrix4(Location, 1, false, in value.M11); } } diff --git a/src/gaemstone.Client/Graphics/OpenGL/VertexArray.cs b/src/gaemstone.Client/Graphics/OpenGL/VertexArray.cs index 5cc4e5c..06e6b7d 100644 --- a/src/gaemstone.Client/Graphics/OpenGL/VertexArray.cs +++ b/src/gaemstone.Client/Graphics/OpenGL/VertexArray.cs @@ -5,7 +5,7 @@ namespace gaemstone.Client.Graphics public readonly struct VertexArray { public static VertexArray Gen() - => new(GFX.GL.GenVertexArray()); + => new(Gfx.Gl.GenVertexArray()); public uint Handle { get; } @@ -14,12 +14,12 @@ public static VertexArray Gen() public UnbindOnDispose Bind() { - GFX.GL.BindVertexArray(Handle); + Gfx.Gl.BindVertexArray(Handle); return new(); } public static void Unbind() - => GFX.GL.BindVertexArray(0); + => Gfx.Gl.BindVertexArray(0); public readonly struct UnbindOnDispose : IDisposable diff --git a/src/gaemstone.Client/Graphics/OpenGL/VertexAttributes.cs b/src/gaemstone.Client/Graphics/OpenGL/VertexAttributes.cs index 4b7d3ba..635a337 100644 --- a/src/gaemstone.Client/Graphics/OpenGL/VertexAttributes.cs +++ b/src/gaemstone.Client/Graphics/OpenGL/VertexAttributes.cs @@ -17,15 +17,15 @@ public class VertexAttributes internal VertexAttributes(Program program) { - GFX.GL.GetProgram(program.Handle, ProgramPropertyARB.ActiveAttributeMaxLength, out var attribMaxLength); + Gfx.Gl.GetProgram(program.Handle, ProgramPropertyARB.ActiveAttributeMaxLength, out var attribMaxLength); var nameBuffer = new string(' ', attribMaxLength); - GFX.GL.GetProgram(program.Handle, ProgramPropertyARB.ActiveAttributes, out var attribCount); + Gfx.Gl.GetProgram(program.Handle, ProgramPropertyARB.ActiveAttributes, out var attribCount); _activeAttribs = new VertexAttributeInfo[attribCount]; for (uint attribIndex = 0; attribIndex < attribCount; attribIndex++) { - GFX.GL.GetActiveAttrib(program.Handle, attribIndex, (uint)attribMaxLength, + Gfx.Gl.GetActiveAttrib(program.Handle, attribIndex, (uint)attribMaxLength, out var length, out var size, out AttributeType type, out nameBuffer); var name = nameBuffer[..(int)length]; - var location = GFX.GL.GetAttribLocation(program.Handle, name); + var location = Gfx.Gl.GetAttribLocation(program.Handle, name); var attrib = new VertexAttributeInfo(attribIndex, location, size, type, name); _activeAttribs[attribIndex] = attrib; _attribsByName[nameBuffer] = attrib; @@ -53,8 +53,8 @@ internal VertexAttributeInfo(uint index, int location, int size, AttributeType t public void Pointer(int size, VertexAttribPointerType type, bool normalized = false, uint stride = 0, int offset = 0) { - GFX.GL.EnableVertexAttribArray((uint)Location); - unsafe { GFX.GL.VertexAttribPointer((uint)Location, size, type, normalized, stride, (void*)offset); } + Gfx.Gl.EnableVertexAttribArray((uint)Location); + unsafe { Gfx.Gl.VertexAttribPointer((uint)Location, size, type, normalized, stride, (void*)offset); } } public override string ToString() diff --git a/src/gaemstone.Client/Graphics/Processors/MeshManager.cs b/src/gaemstone.Client/Graphics/Processors/MeshManager.cs index f2a2fe2..8fdbeaf 100644 --- a/src/gaemstone.Client/Graphics/Processors/MeshManager.cs +++ b/src/gaemstone.Client/Graphics/Processors/MeshManager.cs @@ -9,9 +9,9 @@ namespace gaemstone.Client.Graphics public class MeshManager : IProcessor { - const uint POSITION_ATTRIB_INDEX = 0; - const uint NORMAL_ATTRIB_INDEX = 1; - const uint UV_ATTRIB_INDEX = 2; + const uint PositionAttribIndex = 0; + const uint NormalAttribIndex = 1; + const uint UvAttribIndex = 2; public Mesh Load(Game game, string name) @@ -31,14 +31,14 @@ public Mesh Load(Game game, string name) BufferTargetARB.ElementArrayBuffer); Buffer.CreateFromData(vertices.SourceBufferView.Content); - GFX.GL.EnableVertexAttribArray(POSITION_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(POSITION_ATTRIB_INDEX, 3, + Gfx.Gl.EnableVertexAttribArray(PositionAttribIndex); + Gfx.Gl.VertexAttribPointer(PositionAttribIndex, 3, (VertexAttribPointerType)vertices.Encoding, vertices.Normalized, (uint)vertices.SourceBufferView.ByteStride, (void*)vertices.ByteOffset); Buffer.CreateFromData(normals.SourceBufferView.Content); - GFX.GL.EnableVertexAttribArray(NORMAL_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(NORMAL_ATTRIB_INDEX, 3, + Gfx.Gl.EnableVertexAttribArray(NormalAttribIndex); + Gfx.Gl.VertexAttribPointer(NormalAttribIndex, 3, (VertexAttribPointerType)vertices.Encoding, vertices.Normalized, (uint)vertices.SourceBufferView.ByteStride, (void*)vertices.ByteOffset); } @@ -55,19 +55,19 @@ public Mesh Create( using (vertexArray.Bind()) { Buffer.CreateFromData(indices, BufferTargetARB.ElementArrayBuffer); Buffer.CreateFromData(vertices); - GFX.GL.EnableVertexAttribArray(POSITION_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(POSITION_ATTRIB_INDEX, 3, + Gfx.Gl.EnableVertexAttribArray(PositionAttribIndex); + Gfx.Gl.VertexAttribPointer(PositionAttribIndex, 3, VertexAttribPointerType.Float, false, 0, (void*)0); if (!normals.IsEmpty) { Buffer.CreateFromData(normals); - GFX.GL.EnableVertexAttribArray(NORMAL_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(NORMAL_ATTRIB_INDEX, 3, + Gfx.Gl.EnableVertexAttribArray(NormalAttribIndex); + Gfx.Gl.VertexAttribPointer(NormalAttribIndex, 3, VertexAttribPointerType.Float, false, 0, (void*)0); } if (!uvs.IsEmpty) { Buffer.CreateFromData(uvs); - GFX.GL.EnableVertexAttribArray(UV_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(UV_ATTRIB_INDEX, 2, + Gfx.Gl.EnableVertexAttribArray(UvAttribIndex); + Gfx.Gl.VertexAttribPointer(UvAttribIndex, 2, VertexAttribPointerType.Float, false, 0, (void*)0); } } @@ -80,19 +80,19 @@ public Mesh Create(ReadOnlySpan vertices, var vertexArray = VertexArray.Gen(); using (vertexArray.Bind()) { Buffer.CreateFromData(vertices); - GFX.GL.EnableVertexAttribArray(POSITION_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(POSITION_ATTRIB_INDEX, 3, + Gfx.Gl.EnableVertexAttribArray(PositionAttribIndex); + Gfx.Gl.VertexAttribPointer(PositionAttribIndex, 3, VertexAttribPointerType.Float, false, 0, (void*)0); if (!normals.IsEmpty) { Buffer.CreateFromData(normals); - GFX.GL.EnableVertexAttribArray(NORMAL_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(NORMAL_ATTRIB_INDEX, 3, + Gfx.Gl.EnableVertexAttribArray(NormalAttribIndex); + Gfx.Gl.VertexAttribPointer(NormalAttribIndex, 3, VertexAttribPointerType.Float, false, 0, (void*)0); } if (!uvs.IsEmpty) { Buffer.CreateFromData(uvs); - GFX.GL.EnableVertexAttribArray(UV_ATTRIB_INDEX); - GFX.GL.VertexAttribPointer(UV_ATTRIB_INDEX, 2, + Gfx.Gl.EnableVertexAttribArray(UvAttribIndex); + Gfx.Gl.VertexAttribPointer(UvAttribIndex, 2, VertexAttribPointerType.Float, false, 0, (void*)0); } } diff --git a/src/gaemstone.Client/Graphics/Processors/Renderer.cs b/src/gaemstone.Client/Graphics/Processors/Renderer.cs index 5c1b7fc..a8d149f 100644 --- a/src/gaemstone.Client/Graphics/Processors/Renderer.cs +++ b/src/gaemstone.Client/Graphics/Processors/Renderer.cs @@ -41,14 +41,14 @@ public void OnUpdate(double delta) { } public void OnWindowRender(double delta) { - GFX.Clear(Color.Indigo); + Gfx.Clear(Color.Indigo); _program.Use(); Game.Queries.Run((Camera camera, in Transform transform) => { var clearColor = camera.ClearColor ?? Color.Indigo; var viewport = camera.Viewport ?? new(0, 0, Game.Window.Size.X, Game.Window.Size.Y); - GFX.Viewport(viewport); - GFX.Clear(clearColor, viewport); + Gfx.Viewport(viewport); + Gfx.Clear(clearColor, viewport); // Get the camera's transform matrix and invert it. Matrix4x4.Invert(transform, out var cameraTransform); diff --git a/src/gaemstone.Client/Graphics/Processors/TextureManager.cs b/src/gaemstone.Client/Graphics/Processors/TextureManager.cs index 6e42ba0..9a49539 100644 --- a/src/gaemstone.Client/Graphics/Processors/TextureManager.cs +++ b/src/gaemstone.Client/Graphics/Processors/TextureManager.cs @@ -30,7 +30,7 @@ public Texture CreateFromStream(Stream stream, string? sourceFile = null) if (!image.Frames[0].TryGetSinglePixelSpan(out var pixels)) throw new InvalidOperationException( "TryGetSinglePixelSpan failed" + ((sourceFile != null) ? "\nSource File: " + sourceFile : "")); - GFX.GL.TexImage2D(texture.Target, 0, (int)PixelFormat.Rgba, + Gfx.Gl.TexImage2D(texture.Target, 0, (int)PixelFormat.Rgba, (uint)image.Width, (uint)image.Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, pixels[0]); texture.MagFilter = TextureMagFilter.Nearest; @@ -61,7 +61,7 @@ public void OnLoad() texture.Bind(); Span pixel = stackalloc byte[4]; pixel.Fill(255); - GFX.GL.TexImage2D(TextureTarget.Texture2D, 0, (int)PixelFormat.Rgba, + Gfx.Gl.TexImage2D(TextureTarget.Texture2D, 0, (int)PixelFormat.Rgba, 1, 1, 0, PixelFormat.Rgba, PixelType.UnsignedByte, pixel[0]); texture.MagFilter = TextureMagFilter.Nearest; texture.MinFilter = TextureMinFilter.Nearest; diff --git a/src/gaemstone.Common/ECS/EcsId+Entity.cs b/src/gaemstone.Common/ECS/EcsId+Entity.cs index 2e2bc1b..93a1762 100644 --- a/src/gaemstone.Common/ECS/EcsId+Entity.cs +++ b/src/gaemstone.Common/ECS/EcsId+Entity.cs @@ -27,7 +27,7 @@ public readonly struct Entity /// The unique 32-bit integer identifier for this entity. /// Only one (alive) entity may have this identifier at a time. /// - [FieldOffset(0)] public readonly uint ID; + [FieldOffset(0)] public readonly uint Id; /// /// The generation of this entitiy. @@ -36,22 +36,22 @@ public readonly struct Entity [FieldOffset(4)] public readonly ushort Generation; - public bool IsNone => ID == 0; + public bool IsNone => Id == 0; public Entity(ulong value) : this() { - const ulong UNUSED_MASK = 0x00FF_0000_0000_0000; - const ulong ROLE_MASK = 0xFF00_0000_0000_0000; - if ((value & UNUSED_MASK) != 0L) throw new ArgumentException("Value has unused bits set", nameof(value)); - if ((value & ROLE_MASK) != 0L) throw new ArgumentException("Value has role bits set", nameof(value)); + const ulong UnusedMask = 0x00FF_0000_0000_0000; + const ulong RoleMask = 0xFF00_0000_0000_0000; + if ((value & UnusedMask) != 0L) throw new ArgumentException("Value has unused bits set", nameof(value)); + if ((value & RoleMask) != 0L) throw new ArgumentException("Value has role bits set", nameof(value)); Value = value; } public Entity(uint id, ushort generation) : this() { - if (id == 0) throw new ArgumentException("ID must be greater than 0", nameof(id)); - ID = id; Generation = generation; + if (id == 0) throw new ArgumentException("Id must be greater than 0", nameof(id)); + Id = id; Generation = generation; } @@ -64,7 +64,7 @@ public Entity(uint id, ushort generation) : this() public int CompareTo(Entity other) => Value.CompareTo(other.Value); - public override string ToString() => $"Entity(Id=0x{ID:X},Generation=0x{Generation:X})"; + public override string ToString() => $"Entity(Id=0x{Id:X},Generation=0x{Generation:X})"; } } } diff --git a/src/gaemstone.Common/ECS/EntityManager.cs b/src/gaemstone.Common/ECS/EntityManager.cs index 112ac00..6209f23 100644 --- a/src/gaemstone.Common/ECS/EntityManager.cs +++ b/src/gaemstone.Common/ECS/EntityManager.cs @@ -16,20 +16,20 @@ internal struct Record public class EntityManager { - const int INITIAL_CAPACITY = 1024; + const int InitialCapacity = 1024; readonly Universe _universe; - readonly Queue _unusedEntityIDs = new(); - Record[] _entities = new Record[INITIAL_CAPACITY]; + readonly Queue _unusedEntityIds = new(); + Record[] _entities = new Record[InitialCapacity]; // TODO: Attempt to keep Generation low by prioritizing smallest Generation? - uint _nextUnusedID = 1; + uint _nextUnusedId = 1; public int Count { get; private set; } public int Capacity => _entities.Length; internal EntityManager(Universe universe) - => _universe = universe; + => _universe = universe; void Resize(int newCapacity) { @@ -54,54 +54,54 @@ void EnsureCapacity(uint minCapacity) /// Creates a new entity with the specified type and returns it. public Universe.Entity New(EntityType type) { - ref var record = ref NewRecord(type, out var entityID); - return new(_universe, new(entityID, record.Generation)); + ref var record = ref NewRecord(type, out var entityId); + return new(_universe, new(entityId, record.Generation)); } - /// Creates a new entity with the specified ID and an empty type and returns it. - /// Thrown if the specified ID is already in use. - public Universe.Entity NewWithID(uint entityID) => NewWithID(entityID, _universe.EmptyType); - /// Creates a new entity with the specified ID and type and returns it. - /// Thrown if the specified ID is already in use. - public Universe.Entity NewWithID(uint entityID, params object[] ids) => NewWithID(entityID, _universe.Type(ids)); - /// Creates a new entity with the specified ID and type and returns it. - /// Thrown if the specified ID is already in use. - public Universe.Entity NewWithID(uint entityID, params EcsId[] ids) => NewWithID(entityID, _universe.Type(ids)); - /// Creates a new entity with the specified ID and type and returns it. - /// Thrown if the specified ID is already in use. - public Universe.Entity NewWithID(uint entityID, EntityType type) + /// Creates a new entity with the specifiedid and an empty type and returns it. + /// Thrown if the specified id is already in use. + public Universe.Entity NewWithId(uint entityId) => NewWithId(entityId, _universe.EmptyType); + /// Creates a new entity with the specified id and type and returns it. + /// Thrown if the specified id is already in use. + public Universe.Entity NewWithId(uint entityId, params object[] ids) => NewWithId(entityId, _universe.Type(ids)); + /// Creates a new entity with the specified id and type and returns it. + /// Thrown if the specified id is already in use. + public Universe.Entity NewWithId(uint entityId, params EcsId[] ids) => NewWithId(entityId, _universe.Type(ids)); + /// Creates a new entity with the specified id and type and returns it. + /// Thrown if the specified id is already in use. + public Universe.Entity NewWithId(uint entityId, EntityType type) { - ref var record = ref NewRecordWithID(type, entityID); - return new(_universe, new(entityID, record.Generation)); + ref var record = ref NewRecordWithId(type, entityId); + return new(_universe, new(entityId, record.Generation)); } /// Creates a new entity with and returns a reference to the record. - internal ref Record NewRecord(EntityType type, out uint entityID) + internal ref Record NewRecord(EntityType type, out uint entityId) { - // Try to reuse a previously used entity ID. - if (!_unusedEntityIDs.TryDequeue(out entityID)) { - // If none are available, get the next fresh entity ID. + // Try to reuse a previously used entity id. + if (!_unusedEntityIds.TryDequeue(out entityId)) { + // If none are available, get the next fresh entity id. // And resize the entities array if necessary. do { - EnsureCapacity(_nextUnusedID + 1); - entityID = _nextUnusedID++; - } while (GetRecord(entityID).Occupied); + EnsureCapacity(_nextUnusedId + 1); + entityId = _nextUnusedId++; + } while (GetRecord(entityId).Occupied); } - return ref NewRecordWithID(type, entityID); + return ref NewRecordWithId(type, entityId); } - /// Creates a new entity with the specified ID and returns a reference to the record. - /// Thrown if the specified ID is already in use. - internal ref Record NewRecordWithID(EntityType type, uint entityID) + /// Creates a new entity with the specified id and returns a reference to the record. + /// Thrown if the specified id is already in use. + internal ref Record NewRecordWithId(EntityType type, uint entityId) { - EnsureCapacity(entityID + 1); + EnsureCapacity(entityId + 1); - ref var record = ref GetRecord(entityID); - if (record.Occupied) throw new EntityExistsException(entityID, - $"Entity already exists as {new EcsId.Entity(entityID, record.Generation)}"); + ref var record = ref GetRecord(entityId); + if (record.Occupied) throw new EntityExistsException(entityId, + $"Entity already exists as {new EcsId.Entity(entityId, record.Generation)}"); record.Table = _universe.Tables.GetOrCreate(type); - record.Row = record.Table.Add(new(entityID, record.Generation)); + record.Row = record.Table.Add(new(entityId, record.Generation)); Count++; return ref record; @@ -112,7 +112,7 @@ public void Delete(EcsId.Entity entity) { ref var record = ref GetRecord(entity); - _unusedEntityIDs.Enqueue(entity.ID); + _unusedEntityIds.Enqueue(entity.Id); record.Table.Remove(record.Row); record.Generation++; @@ -122,45 +122,45 @@ public void Delete(EcsId.Entity entity) } - /// Returns the record for the specified ID. - /// Thrown if the specified ID is out of range. - internal ref Record GetRecord(uint entityID) + /// Returns the record for the specified id. + /// Thrown if the specified id is out of range. + internal ref Record GetRecord(uint entityId) { - if ((entityID == 0) || (entityID >= _entities.Length)) throw new EntityNotFoundException( - entityID, $"Specified entity ID is outside of valid range (1 to {_entities.Length - 1})"); - return ref _entities[entityID]; + if ((entityId == 0) || (entityId >= _entities.Length)) throw new EntityNotFoundException( + entityId, $"Specified entity id is outside of valid range (1 to {_entities.Length - 1})"); + return ref _entities[entityId]; } /// Returns the record for the specified entity, which must be alive. - /// Thrown if the specified entity's ID is out of range, or the entity is not alive. + /// Thrown if the specified entity's id is out of range, or the entity is not alive. internal ref Record GetRecord(EcsId.Entity entity) { - ref var record = ref GetRecord(entity.ID); + ref var record = ref GetRecord(entity.Id); if (!record.Occupied || (record.Generation != entity.Generation)) throw new EntityNotFoundException(entity); return ref record; } - public Universe.Entity Lookup(uint entityID) - => TryLookup(entityID, out var entity) ? entity - : throw new EntityNotFoundException(entityID); - public bool TryLookup(uint entityID, out Universe.Entity entity) + public Universe.Entity Lookup(uint entityId) + => TryLookup(entityId, out var entity) ? entity + : throw new EntityNotFoundException(entityId); + public bool TryLookup(uint entityId, out Universe.Entity entity) { entity = default; - if ((entityID == 0) || (entityID >= _nextUnusedID)) return false; - ref var entry = ref _entities[entityID]; + if ((entityId == 0) || (entityId >= _nextUnusedId)) return false; + ref var entry = ref _entities[entityId]; if (!entry.Occupied) return false; - entity = new(_universe, new(entityID, entry.Generation)); + entity = new(_universe, new(entityId, entry.Generation)); return true; } public bool IsAlive(EcsId.Entity entity) { - if (entity.ID >= _nextUnusedID) return false; - ref var entry = ref _entities[entity.ID]; + if (entity.Id >= _nextUnusedId) return false; + ref var entry = ref _entities[entity.Id]; return (entry.Occupied && (entry.Generation == entity.Generation)); } } diff --git a/src/gaemstone.Common/ECS/EntityType.cs b/src/gaemstone.Common/ECS/EntityType.cs index 92aa957..59ed647 100644 --- a/src/gaemstone.Common/ECS/EntityType.cs +++ b/src/gaemstone.Common/ECS/EntityType.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; -using System.Text; namespace gaemstone.ECS { @@ -48,7 +47,7 @@ public bool Overlaps(EntityType other) public EntityType Union(params object[] ids) - => Union(ids.Select(o => (EcsId)Universe.Lookup(o).ID)); + => Union(ids.Select(o => (EcsId)Universe.Lookup(o).Id)); public EntityType Union(params EcsId[] ids) => Union((IEnumerable)ids); public EntityType Union(IEnumerable ids) @@ -59,7 +58,7 @@ public EntityType Union(IEnumerable ids) } public EntityType Except(params object[] ids) - => Except(ids.Select(o => Universe.Lookup(o).ID)); + => Except(ids.Select(o => Universe.Lookup(o).Id)); public EntityType Except(params EcsId[] ids) => Except((IEnumerable)ids); public EntityType Except(IEnumerable ids) diff --git a/src/gaemstone.Common/ECS/QueryManager.cs b/src/gaemstone.Common/ECS/QueryManager.cs index e689803..06c6e07 100644 --- a/src/gaemstone.Common/ECS/QueryManager.cs +++ b/src/gaemstone.Common/ECS/QueryManager.cs @@ -50,11 +50,11 @@ public QueryImpl(Universe universe, Delegate action, public void Run() { // TODO: Support using Universe.Entity as parameter type. - // TODO: This could be optimized by picking the least common ID first. + // TODO: This could be optimized by picking the least common id first. var with = _universe.Type(_generator.Parameters .Where(p => (p.Kind != QueryActionGenerator.ParamKind.Entity) && p.IsRequired) - .Select(p => (EcsId)_universe.Lookup(p.UnderlyingType).ID) + .Select(p => (EcsId)_universe.Lookup(p.UnderlyingType).Id) .Concat(_filterWith)); var tablesAndColumns = _universe.Tables.GetAll(with.First()) diff --git a/src/gaemstone.Common/ECS/Table.cs b/src/gaemstone.Common/ECS/Table.cs index 3e14ef5..cad1c30 100644 --- a/src/gaemstone.Common/ECS/Table.cs +++ b/src/gaemstone.Common/ECS/Table.cs @@ -8,7 +8,7 @@ namespace gaemstone.ECS { public class Table { - const int STARTING_CAPACITY = 16; + const int InitialCapacity = 16; public Universe Universe { get; } @@ -55,7 +55,7 @@ public void EnsureCapacity(int minCapacity) { if (minCapacity <= 0) throw new ArgumentOutOfRangeException(nameof(minCapacity), "minCapacity must be positive"); if (minCapacity <= Capacity) return; // Already have the necessary capacity. - if (minCapacity < STARTING_CAPACITY) minCapacity = STARTING_CAPACITY; + if (minCapacity < InitialCapacity) minCapacity = InitialCapacity; Resize((int)BitOperations.RoundUpToPowerOf2((uint)minCapacity)); } @@ -78,7 +78,7 @@ internal void Remove(int row) foreach (var column in Columns) Array.Copy(column, Count, column, row, 1); // Update the moved element's Record to point to its new row. - ref var record = ref Universe.Entities.GetRecord(Entities[row].ID); + ref var record = ref Universe.Entities.GetRecord(Entities[row].Id); record.Table = this; record.Row = row; } diff --git a/src/gaemstone.Common/ECS/TableManager.cs b/src/gaemstone.Common/ECS/TableManager.cs index 8d5f62d..0e06f02 100644 --- a/src/gaemstone.Common/ECS/TableManager.cs +++ b/src/gaemstone.Common/ECS/TableManager.cs @@ -25,24 +25,24 @@ internal TableManager(Universe universe) internal void Bootstrap() { var componentTable = BootstrapTable( - type: _universe.Type(Universe.TypeID, Universe.IdentifierID, Universe.ComponentID), - storageType: _universe.Type(Universe.TypeID, Universe.IdentifierID), + type: _universe.Type(Universe.TypeId, Universe.IdentifierId, Universe.ComponentId), + storageType: _universe.Type(Universe.TypeId, Universe.IdentifierId), columnTypes: new[]{ typeof(Type), typeof(Identifier) }, - (Universe.TypeID , typeof(Type)), - (Universe.IdentifierID , typeof(Identifier))); + (Universe.TypeId , typeof(Type)), + (Universe.IdentifierId , typeof(Identifier))); var tagTable = BootstrapTable( - type: _universe.Type(Universe.TypeID, Universe.IdentifierID, Universe.TagID), - storageType: _universe.Type(Universe.TypeID, Universe.IdentifierID), + type: _universe.Type(Universe.TypeId, Universe.IdentifierId, Universe.TagId), + storageType: _universe.Type(Universe.TypeId, Universe.IdentifierId), columnTypes: new[]{ typeof(Type), typeof(Identifier) }, - (Universe.ComponentID , typeof(Component)), - (Universe.TagID , typeof(Tag))); + (Universe.ComponentId , typeof(Component)), + (Universe.TagId , typeof(Tag))); TableAdded?.Invoke(componentTable); TableAdded?.Invoke(tagTable); } Table BootstrapTable(EntityType type, EntityType storageType, Type[] columnTypes, - params (EcsId.Entity ID, Type Type)[] entities) + params (EcsId.Entity Id, Type Type)[] entities) { var table = new Table(_universe, type, storageType, columnTypes); _tables.Add(type, table); @@ -66,8 +66,8 @@ void AddTableToIndex(Table table) { foreach (var id in table.Type) { if (id.AsPair() is EcsId.Pair pair) { - _index.GetOrAddNew(new EcsId.Pair(Universe.Wildcard.ID, pair.Target)).Add(table); - _index.GetOrAddNew(new EcsId.Pair(pair.Relation, Universe.Wildcard.ID)).Add(table); + _index.GetOrAddNew(new EcsId.Pair(Universe.Wildcard.Id, pair.Target)).Add(table); + _index.GetOrAddNew(new EcsId.Pair(pair.Relation, Universe.Wildcard.Id)).Add(table); } _index.GetOrAddNew(id).Add(table); } diff --git a/src/gaemstone.Common/ECS/Universe+Entity.cs b/src/gaemstone.Common/ECS/Universe+Entity.cs index 9de1d30..9b4043f 100644 --- a/src/gaemstone.Common/ECS/Universe+Entity.cs +++ b/src/gaemstone.Common/ECS/Universe+Entity.cs @@ -9,7 +9,7 @@ public readonly struct Entity : IEntity, IEquatable { public Universe Universe { get; } - public EcsId.Entity ID { get; } + public EcsId.Entity Id { get; } public bool IsAlive => Universe.Entities.IsAlive(this); public EntityType Type { @@ -18,7 +18,7 @@ public EntityType Type { } public Entity(Universe universe, EcsId.Entity id) - { Universe = universe; ID = id; } + { Universe = universe; Id = id; } public void Delete() => Universe.Entities.Delete(this); @@ -33,15 +33,15 @@ public Entity(Universe universe, EcsId.Entity id) IEntity IEntity.Set(T value) => Set(value); public override bool Equals(object? obj) => (obj is Entity entity) && Equals(entity); - public bool Equals(Entity other) => (Universe == other.Universe) && (ID == other.ID); - public override int GetHashCode() => HashCode.Combine(Universe, ID); + public bool Equals(Entity other) => (Universe == other.Universe) && (Id == other.Id); + public override int GetHashCode() => HashCode.Combine(Universe, Id); // TODO: Do the ToString stuff. - // public override string? ToString() => ID.ToString(Universe); - // public void AppendString(StringBuilder builder) => ID.AppendString(builder); + // public override string? ToString() => Id.ToString(Universe); + // public void AppendString(StringBuilder builder) => Id.AppendString(builder); - public static implicit operator EcsId (Entity entity) => entity.ID; - public static implicit operator EcsId.Entity(Entity entity) => entity.ID; + public static implicit operator EcsId (Entity entity) => entity.Id; + public static implicit operator EcsId.Entity(Entity entity) => entity.Id; } } } diff --git a/src/gaemstone.Common/ECS/Universe+Lookup.cs b/src/gaemstone.Common/ECS/Universe+Lookup.cs index adadefb..50e787e 100644 --- a/src/gaemstone.Common/ECS/Universe+Lookup.cs +++ b/src/gaemstone.Common/ECS/Universe+Lookup.cs @@ -32,8 +32,8 @@ public Entity Lookup(Type type) => TryLookup(type, out var id) ? id public bool TryLookup(out Entity entity) => TryLookup(typeof(T), out entity); public bool TryLookup(Type type, out Entity entity) { - foreach (var table in Tables.GetAll(TypeID)) { - var column = table.GetStorageColumn(TypeID); + foreach (var table in Tables.GetAll(TypeId)) { + var column = table.GetStorageColumn(TypeId); for (var i = 0; i < table.Count; i++) if (column[i] == type) { entity = new(this, table.Entities[i]); return true; } } @@ -47,8 +47,8 @@ public Entity Lookup(string name) => TryLookup(name, out var id) ? id public bool TryLookup(string name, out Entity entity) { - foreach (var table in Tables.GetAll(IdentifierID)) { - var column = table.GetStorageColumn(IdentifierID); + foreach (var table in Tables.GetAll(IdentifierId)) { + var column = table.GetStorageColumn(IdentifierId); for (var i = 0; i < table.Count; i++) if (column[i] == name) { entity = new(this, table.Entities[i]); return true; } } diff --git a/src/gaemstone.Common/ECS/Universe.cs b/src/gaemstone.Common/ECS/Universe.cs index 2aeeed5..af796c8 100644 --- a/src/gaemstone.Common/ECS/Universe.cs +++ b/src/gaemstone.Common/ECS/Universe.cs @@ -5,13 +5,13 @@ namespace gaemstone.ECS public partial class Universe { // Built-in Components - static internal readonly EcsId.Entity TypeID = new(0x01); - static internal readonly EcsId.Entity IdentifierID = new(0x02); + static internal readonly EcsId.Entity TypeId = new(0x01); + static internal readonly EcsId.Entity IdentifierId = new(0x02); // Built-in Tags - static internal readonly EcsId.Entity ComponentID = new(0x10); - static internal readonly EcsId.Entity TagID = new(0x11); - static internal readonly EcsId.Entity RelationID = new(0x12); + static internal readonly EcsId.Entity ComponentId = new(0x10); + static internal readonly EcsId.Entity TagId = new(0x11); + static internal readonly EcsId.Entity RelationId = new(0x12); // TODO: Built-in Relationships static internal readonly EcsId.Entity ChildOf = new(0x20); @@ -41,24 +41,24 @@ public Universe() // Built-in Components required to bootstrap - Entities.NewWithID(TypeID.ID); - Entities.NewWithID(IdentifierID.ID); + Entities.NewWithId(TypeId.Id); + Entities.NewWithId(IdentifierId.Id); // Built-in Tags required to bootstrap. - Entities.NewWithID(ComponentID.ID); - Entities.NewWithID(TagID.ID); + Entities.NewWithId(ComponentId.Id); + Entities.NewWithId(TagId.Id); // Bootstrap table structures so other methods can work. Tables.Bootstrap(); // Build-in Tags - Entities.NewWithID(RelationID.ID).Add(typeof(Tag)).Set(typeof(Relation)); + Entities.NewWithId(RelationId.Id).Add(typeof(Tag)).Set(typeof(Relation)); // Build-in Relations - Entities.NewWithID(ChildOf.ID).Add(typeof(Tag), typeof(Relation)).Set(typeof(ChildOf)); - Entities.NewWithID(IsA.ID ).Add(typeof(Tag), typeof(Relation)).Set(typeof(IsA)); + Entities.NewWithId(ChildOf.Id).Add(typeof(Tag), typeof(Relation)).Set(typeof(ChildOf)); + Entities.NewWithId(IsA.Id ).Add(typeof(Tag), typeof(Relation)).Set(typeof(IsA)); // Special "Wildcard" (*), used when looking up relationships - Entities.NewWithID(Wildcard.ID).Set((Identifier)"*"); + Entities.NewWithId(Wildcard.Id).Set((Identifier)"*"); NewComponent(); diff --git a/src/gaemstone.Common/ECS/Utility/Exceptions.cs b/src/gaemstone.Common/ECS/Utility/Exceptions.cs index 95dbf66..37a0015 100644 --- a/src/gaemstone.Common/ECS/Utility/Exceptions.cs +++ b/src/gaemstone.Common/ECS/Utility/Exceptions.cs @@ -25,7 +25,7 @@ public EntityNotFoundException(object entity, string? message, Exception? innerE => Entity = entity; } - /// Thrown when an entity with a certain ID already exists. + /// Thrown when an entity with a certain id already exists. public class EntityExistsException : Exception { public object Entity { get; } diff --git a/src/gaemstone.Common/Utility/RandomExtensions.cs b/src/gaemstone.Common/Utility/RandomExtensions.cs index fb53cfa..ff83dce 100644 --- a/src/gaemstone.Common/Utility/RandomExtensions.cs +++ b/src/gaemstone.Common/Utility/RandomExtensions.cs @@ -27,7 +27,7 @@ public static T Pick(this Random rnd, IReadOnlyList elements) public static T Pick(this Random rnd, Span elements) => elements[rnd.Next(elements.Length)]; -#pragma warning disable CS8509 +#pragma warning disable CS8509 // Switch expression is not exhaustive. public static T Pick(this Random rnd, T elem1, T elem2) => rnd.Next(2) switch { 0 => elem1, 1 => elem2 }; public static T Pick(this Random rnd, T elem1, T elem2, T elem3) diff --git a/src/gaemstone.Common/Utility/RefDictionary.cs b/src/gaemstone.Common/Utility/RefDictionary.cs index 3bb4235..09e7b1a 100644 --- a/src/gaemstone.Common/Utility/RefDictionary.cs +++ b/src/gaemstone.Common/Utility/RefDictionary.cs @@ -347,9 +347,8 @@ public void CopyTo(TValue[] array, int arrayIndex) // https://github.com/dotnet/coreclr/blob/master/src/System.Private.CoreLib/shared/System/Collections/HashHelpers.cs static class PrimeHelper { - public const int MAX_PRIME_ARRAY_LENGTH = 0x7FEFFFFD; - - public const int HASH_PRIME = 101; + public const int MaxPrimeArrayLength = 0x7FEFFFFD; + public const int HashPrime = 101; static readonly int[] _primes = { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, @@ -380,7 +379,7 @@ public static int GetPrime(int min) return prime; } for (int i = (min | 1); i < int.MaxValue; i += 2) - if (IsPrime(i) && ((i - 1) % HASH_PRIME != 0)) + if (IsPrime(i) && ((i - 1) % HashPrime != 0)) return i; return min; } @@ -388,9 +387,9 @@ public static int GetPrime(int min) public static int ExpandPrime(int oldSize) { int newSize = 2 * oldSize; - if (((uint)newSize > MAX_PRIME_ARRAY_LENGTH) && (MAX_PRIME_ARRAY_LENGTH > oldSize)) { - Debug.Assert(MAX_PRIME_ARRAY_LENGTH == GetPrime(MAX_PRIME_ARRAY_LENGTH), "Invalid MaxPrimeArrayLength"); - return MAX_PRIME_ARRAY_LENGTH; + if (((uint)newSize > MaxPrimeArrayLength) && (MaxPrimeArrayLength > oldSize)) { + Debug.Assert(MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength"); + return MaxPrimeArrayLength; } return GetPrime(newSize); }