stymee / SilkVulkanTutorial

C# port of Vulkan Game Engine Tutorial
MIT License
56 stars 5 forks source link

Small aligment suggestion #6

Open Arugin opened 1 year ago

Arugin commented 1 year ago

https://github.com/stymee/SilkVulkanTutorial/blob/7d089b0f4f947bfcd152b657b8db9a27ca7fceba/Source/Chapter09PushConstants/FirstApp.cs#L30C17-L30C17

Here you can do something like this

[StructLayout(LayoutKind.Explicit)]
public struct SimplePushConstantData {
    [FieldOffset(0)] public Vector2 Offset;
    [FieldOffset(16)] public Vector3 Color;

    public static uint SizeOf() => (uint)Unsafe.SizeOf<SimplePushConstantData>();
}

Pack property of LayoutKind.Sequential is for type aligment itself, but each field must align with fields of its own size (1, 2, 4, 8, etc., bytes) or the alignment of the type, whichever is smaller (source https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.structlayoutattribute.pack?view=net-7.0)

clibequilibrium commented 1 year ago

@Arugin you can also do

[StructLayout(LayoutKind.Sequential, Pack = 1)]
unsafe struct SimplePushConstantData 
{
    fixed byte padding[16];
    public Vector4 Color;
}