diff --git a/assets/hunter.png b/assets/hunter.png new file mode 100644 index 0000000..02e60e5 Binary files /dev/null and b/assets/hunter.png differ diff --git a/assets/npc_00.png b/assets/npc_00.png new file mode 100644 index 0000000..2ec78e1 Binary files /dev/null and b/assets/npc_00.png differ diff --git a/assets/oath_corner_inner.png b/assets/oath_corner_inner.png new file mode 100644 index 0000000..3ee040d Binary files /dev/null and b/assets/oath_corner_inner.png differ diff --git a/assets/path_corner.png b/assets/path_corner.png new file mode 100644 index 0000000..679e87a Binary files /dev/null and b/assets/path_corner.png differ diff --git a/assets/path_middle.png b/assets/path_middle.png new file mode 100644 index 0000000..53d815c Binary files /dev/null and b/assets/path_middle.png differ diff --git a/assets/path_middle_edge.png b/assets/path_middle_edge.png new file mode 100644 index 0000000..dff3b8c Binary files /dev/null and b/assets/path_middle_edge.png differ diff --git a/assets/saloon_ext.png b/assets/saloon_ext.png new file mode 100644 index 0000000..3705ef2 Binary files /dev/null and b/assets/saloon_ext.png differ diff --git a/assets/tile_detail_0.png b/assets/tile_detail_0.png new file mode 100644 index 0000000..9d2d4e2 Binary files /dev/null and b/assets/tile_detail_0.png differ diff --git a/assets/tile_detail_1.png b/assets/tile_detail_1.png new file mode 100644 index 0000000..5b8c8e3 Binary files /dev/null and b/assets/tile_detail_1.png differ diff --git a/assets/tile_detail_2.png b/assets/tile_detail_2.png new file mode 100644 index 0000000..d2dadd1 Binary files /dev/null and b/assets/tile_detail_2.png differ diff --git a/assets/tile_detail_3.png b/assets/tile_detail_3.png new file mode 100644 index 0000000..892b79f Binary files /dev/null and b/assets/tile_detail_3.png differ diff --git a/assets/tile_detail_4.png b/assets/tile_detail_4.png new file mode 100644 index 0000000..96dc324 Binary files /dev/null and b/assets/tile_detail_4.png differ diff --git a/assets/tile_detail_5.png b/assets/tile_detail_5.png new file mode 100644 index 0000000..12ca6b8 Binary files /dev/null and b/assets/tile_detail_5.png differ diff --git a/assets/tile_detail_6.png b/assets/tile_detail_6.png new file mode 100644 index 0000000..0ea1098 Binary files /dev/null and b/assets/tile_detail_6.png differ diff --git a/assets/tile_dirt_0.png b/assets/tile_dirt_0.png new file mode 100644 index 0000000..cc5209a Binary files /dev/null and b/assets/tile_dirt_0.png differ diff --git a/assets/tile_dirt_1.png b/assets/tile_dirt_1.png new file mode 100644 index 0000000..51431e6 Binary files /dev/null and b/assets/tile_dirt_1.png differ diff --git a/code/core/arena.h b/code/core/arena.h index ba65059..34a4fc0 100644 --- a/code/core/arena.h +++ b/code/core/arena.h @@ -1,7 +1,7 @@ #if !defined(LD_CORE_ARENA_H_) #define LD_CORE_ARENA_H_ -#define AlignUp(x, a) (((x) + ~((a) - 1)) & ~((a) - 1)) +#define AlignUp(x, a) (((x) + ((a) - 1)) & ~((a) - 1)) #define AlignDown(x, a) (((x)) & ~((a) - 1)) #define KB(x) ((U64) (x) << 10) @@ -64,8 +64,8 @@ function void *_M_ArenaPush(M_Arena *arena, U64 esize, M_ArenaPushOpts *opts) function void *_M_ArenaPushCopy(M_Arena *arena, void *src, U64 esize, M_ArenaPushOpts *opts); #define M_ArenaAlloc(limit, ...) _M_ArenaAlloc(limit, &(M_ArenaOpts) { .initial = MB(1), .increment = KB(64), ##__VA_ARGS__ }) -#define M_ArenaPush(arena, T, ...) (T *) _M_ArenaPush(arena, sizeof(T), &(M_ArenaOpts) { .count = 1, .align = Alignof(T), ##__VA_ARGS__ }) -#define M_ArenaPushCopy(arena, T, src, ...) (T *) _M_ArenaPush(arena, src, sizeof(T), &(M_ArenaOpts) { .count = 1, .align = Alignof(T), ##__VA_ARGS__ }) +#define M_ArenaPush(arena, T, ...) (T *) _M_ArenaPush(arena, sizeof(T), &(M_ArenaPushOpts) { .count = 1, .align = Alignof(T), ##__VA_ARGS__ }) +#define M_ArenaPushCopy(arena, T, src, ...) (T *) _M_ArenaPush(arena, src, sizeof(T), &(M_ArenaPushOpts) { .count = 1, .align = Alignof(T), ##__VA_ARGS__ }) function void M_ArenaReset(M_Arena *arena); function void M_ArenaRelease(M_Arena *arena); diff --git a/code/core/core.c b/code/core/core.c index d45a634..cc2a7c0 100644 --- a/code/core/core.c +++ b/code/core/core.c @@ -1 +1,2 @@ #include "impl/arena.c" +#include "impl/string.c" diff --git a/code/core/core.h b/code/core/core.h index 216a612..80b81fb 100644 --- a/code/core/core.h +++ b/code/core/core.h @@ -5,5 +5,6 @@ #include "platform.h" #include "macros.h" #include "arena.h" +#include "string.h" #endif // LD_CORE_CORE_H_ diff --git a/code/core/impl/string.c b/code/core/impl/string.c new file mode 100644 index 0000000..8c9a042 --- /dev/null +++ b/code/core/impl/string.c @@ -0,0 +1,150 @@ +Str8 Str8_Wrap(S64 count, U8 *data) { + Str8 result; + result.data = data; + result.count = count; + + return result; +} + +Str8 Str8_WrapRange(U8 *start, U8 *end) { + Str8 result; + result.data = start; + result.count = cast(S64) (end - start); + + return result; +} + +internal S64 Str8_CountZ(U8 *data) { + S64 result = 0; + while (data[result] != 0) { result += 1; } + + return result; +} + +Str8 Str8_WrapZ(U8 *data) { + Str8 result; + result.data = data; + result.count = Str8_CountZ(data); + + return result; +} + +Str8 Str8_Copy(M_Arena *arena, Str8 s) { + Str8 result; + result.count = s.count; + result.data = M_ArenaPush(arena, U8, .count = s.count + 1); + + M_CopySize(result.data, s.data, s.count); + return result; +} + +Str8 Str8_Format(M_Arena *arena, const char *format, ...) { + va_list args; + va_start(args, format); + + Str8 result = Str8_FormatArgs(arena, format, args); + va_end(args); + + return result; +} + +internal S64 Str8_ProcessFormat(Str8 out, const char *format, va_list args) { + S64 result = vsnprintf((char *) out.data, (int) out.count, format, args); + return result; +} + +Str8 Str8_FormatArgs(M_Arena *arena, const char *format, va_list args) { + Str8 result; + + va_list copy; + va_copy(copy, args); + + U64 offset = M_ArenaOffset(arena); + + result.count = KB(1); + result.data = M_ArenaPush(arena, U8, .count = result.count); + + S64 needed = Str8_ProcessFormat(result, format, args); + if (needed >= result.count) { + M_ArenaPop(arena, offset); + + result.count = needed; + result.data = M_ArenaPush(arena, U8, .count = result.count + 1); + + Str8_ProcessFormat(result, format, copy); + } + else { + U64 size = result.count - needed - 1; + M_ArenaPopSize(arena, size); + + result.count = needed; + } + + return result; +} + +B32 Str8_Equal(Str8 a, Str8 b, Str8_EqualFlags flags) { + B32 result = (a.count == b.count); + + if (result) { + B32 ignore_case = (flags & STR8_EQUAL_IGNORE_CASE) != 0; + + for (S64 it = 0; it < a.count; ++it) { + U8 ac = ignore_case ? Chr_ToLowercase(a.data[it]) : a.data[it]; + U8 bc = ignore_case ? Chr_ToLowercase(b.data[it]) : b.data[it]; + + if (ac != bc) { + result = false; + break; + } + } + } + + return result; +} + +Str8 Str8_Prefix(Str8 s, S64 count) { + Str8 result; + result.data = s.data; + result.count = Min(s.count, count); + + return result; +} + +Str8 Str8_Suffix(Str8 s, S64 count) { + Str8 result; + result.count = Min(s.count, count); + result.data = s.data + (s.count - result.count); + + return result; +} + +Str8 Str8_RemoveAfterLast(Str8 s, U8 c) { + Str8 result; + result.data = s.data; + result.count = s.count; + + for (S64 it = s.count - 1; it >= 0; --it) { + if (result.data[it] == c) { + result.count = it; + break; + } + } + + return result; +} + +B32 Str8_EndsWith(Str8 s, Str8 suffix) { + B32 result = Str8_Equal(Str8_Suffix(s, suffix.count), suffix, 0); + return result; +} + +U8 Chr_ToUppercase(U8 c) { + U8 result = (c >= 'a' && c <= 'z') ? (c - ('a' - 'A')) : c; + return result; +} + +U8 Chr_ToLowercase(U8 c) { + U8 result = (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c; + return result; +} diff --git a/code/core/macros.h b/code/core/macros.h index fed60b8..cae2d9d 100644 --- a/code/core/macros.h +++ b/code/core/macros.h @@ -34,6 +34,8 @@ #define SLL_PushN(h, n, next) ((n)->next = (h), (h) = (n)) #define SLL_PopN(h, next) (((h) != 0) ? (h) = (h)->next : 0) +#define SLL_Enqueue(h, t, n) SLL_EnqueueN(h, t, n, next) + #define function static #define internal static #define global_var static @@ -45,14 +47,4 @@ #define thread_var __thread #endif -#define S(x) Str8_Wrap(sizeof(x) - sizeof(*(x)), (U8 *) (x)) -Str8 Str8_Wrap(S64 count, U8 *data) { - Str8 result; - result.data = data; - result.count = count; - - return result; -} -#define Sv(x) (int) (x).count, (x).data - #endif // LD_CORE_MACROS_H_ diff --git a/code/core/platform.h b/code/core/platform.h index 5047a9f..63b6827 100644 --- a/code/core/platform.h +++ b/code/core/platform.h @@ -68,11 +68,17 @@ #if OS_WINDOWS #define WIN32_LEAN_AND_MEAN 1 #include + #include #pragma warning(disable : 4201) #elif OS_LINUX + #include #include #include #include + #include + #include + #include + #include #endif #endif // LD_CORE_PLATFORM_H_ diff --git a/code/core/string.h b/code/core/string.h new file mode 100644 index 0000000..4adb71e --- /dev/null +++ b/code/core/string.h @@ -0,0 +1,36 @@ +#if !defined(LD_CORE_STRING_H_) +#define LD_CORE_STRING_H_ + +#define S(x) Str8_Wrap(sizeof(x) - sizeof(*(x)), (U8 *) (x)) +#define Sz(x) Str8_WrapZ((U8 *) (x)) + +#define Sv(x) (int) (x).count, (x).data +#define Sf(arena, fmt, ...) Str8_Format(arena, fmt, ##__VA_ARGS__) + +function Str8 Str8_Wrap(S64 count, U8 *data); +function Str8 Str8_WrapRange(U8 *start, U8 *end); +function Str8 Str8_WrapZ(U8 *data); + +function Str8 Str8_Copy(M_Arena *arena, Str8 s); + +function Str8 Str8_Format(M_Arena *arena, const char *format, ...); +function Str8 Str8_FormatArgs(M_Arena *arena, const char *format, va_list args); + +typedef U32 Str8_EqualFlags; +enum { + STR8_EQUAL_IGNORE_CASE = (1 << 0) +}; + +function B32 Str8_Equal(Str8 a, Str8 b, Str8_EqualFlags flags); + +function Str8 Str8_Prefix(Str8 s, S64 count); +function Str8 Str8_Suffix(Str8 s, S64 count); + +function Str8 Str8_RemoveAfterLast(Str8 s, U8 c); + +function B32 Str8_EndsWith(Str8 s, Str8 suffix); + +function U8 Chr_ToUppercase(U8 c); +function U8 Chr_ToLowercase(U8 c); + +#endif // LD_CORE_STRING_H_ diff --git a/code/core/types.h b/code/core/types.h index a5bc66d..cf33cd6 100644 --- a/code/core/types.h +++ b/code/core/types.h @@ -41,4 +41,9 @@ struct V2i { U32 y; }; +#define U8_MAX ((U8) -1) +#define U16_MAX ((U16) -1) +#define U32_MAX ((U32) -1) +#define U64_MAX ((U64) -1) + #endif // LD_CORE_TYPES_H_ diff --git a/code/first.c b/code/first.c index ed12e21..952cda9 100644 --- a/code/first.c +++ b/code/first.c @@ -2,22 +2,24 @@ #include #include +#define STB_IMAGE_IMPLEMENTATION 1 +#include + #include "core/core.h" #include "core/types.h" #include "game/npc.h" #include "os/core.h" #include "vulkan/core.h" +#include "game/core.h" -#include "game/impl/player.c" #include "game/world.h" #include "game/impl/npc.c" #include "game/testnavmesh.h" -int main(int argc, char **argv) -{ - (void)argc; - (void)argv; +int main(int argc, char **argv) { + (void) argc; + (void) argv; if (!SDL_Init(SDL_INIT_VIDEO)) { @@ -34,6 +36,44 @@ int main(int argc, char **argv) Vk_Setup(window); + G_State *game = 0; + G_Image *img = 0; + { + M_Arena *arena = M_ArenaAlloc(GB(64), .initial = MB(4)); + game = M_ArenaPush(arena, G_State); + + game->arena = arena; + + G_ImagesLoad(game); + G_PipelinesLoad(game); + + for (U32 it = 0; it < game->n_images; ++it) { + if (Str8_Equal(game->images[it].name, S("saloon_ext"), 0)) { + img = &game->images[it]; + break; + } + } + + if (!img) { img = &game->images[0]; } + + Vk_Buffer *vbo = &game->vbo; + vbo->size = KB(4096); + vbo->usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; + vbo->host_visible = true; + + Vk_BufferCreate(vbo); + + G_Vertex *vertices = cast(G_Vertex *) vbo->data; + + vertices[0] = (G_Vertex) { -0.25f, -0.25f, 1.0f, 1.0f, 0.0f, 0.0f, 0xFFFFFFFF, 0}; + vertices[1] = (G_Vertex) { 0.25f, -0.25f, 1.0f, 1.0f, 1.0f, 0.0f, 0xFFFFFFFF, 0}; + vertices[2] = (G_Vertex) { -0.25f, 0.25f, 1.0f, 1.0f, 0.0f, 1.0f, 0xFFFFFFFF, 0}; + + vertices[3] = (G_Vertex) { 0.25f, -0.25f, 1.0f, 1.0f, 1.0f, 0.0f, 0xFFFFFFFF, 0}; + vertices[4] = (G_Vertex) { 0.25f, 0.25f, 1.0f, 1.0f, 1.0f, 1.0f, 0xFFFFFFFF, 0}; + vertices[5] = (G_Vertex) { -0.25f, 0.25f, 1.0f, 1.0f, 0.0f, 1.0f, 0xFFFFFFFF, 0}; + } + bool running = true; Player player; player.pos.x = 0; @@ -78,26 +118,6 @@ int main(int argc, char **argv) Vk_Frame *frame = Vk_FrameBegin(window); VkCommandBuffer cmd = frame->cmd; - VkImageMemoryBarrier2 colour_optimal = {0}; - colour_optimal.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2; - colour_optimal.srcStageMask = VK_PIPELINE_STAGE_2_NONE; - colour_optimal.srcAccessMask = VK_ACCESS_2_NONE; - colour_optimal.dstStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; - colour_optimal.dstAccessMask = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT; - colour_optimal.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; - colour_optimal.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - colour_optimal.image = vk.swapchain.images[frame->image]; - - colour_optimal.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - colour_optimal.subresourceRange.layerCount = 1; - colour_optimal.subresourceRange.levelCount = 1; - - VkDependencyInfo colour_barrier = {0}; - colour_barrier.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO; - colour_barrier.imageMemoryBarrierCount = 1; - colour_barrier.pImageMemoryBarriers = &colour_optimal; - - vk.CmdPipelineBarrier2(cmd, &colour_barrier); VkClearValue clear_colour; clear_colour.color.float32[0] = 1.0f; @@ -122,28 +142,61 @@ int main(int argc, char **argv) vk.CmdBeginRendering(cmd, &rendering_info); + Vk_Pipeline *basic = &game->pipelines[0]; + + VkDescriptorSet set; + VkDescriptorSetAllocateInfo alloc_info = { 0 }; + alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; + alloc_info.descriptorPool = frame->descriptors; + alloc_info.descriptorSetCount = 1; + alloc_info.pSetLayouts = &basic->layout.set; + + vk.AllocateDescriptorSets(vk.device, &alloc_info, &set); + + // 'update' the descriptor sets for binding + { + VkWriteDescriptorSet writes[2] = { 0 }; + + VkDescriptorBufferInfo vbo_info = { 0 }; + vbo_info.buffer = game->vbo.handle; + vbo_info.offset = 0; + vbo_info.range = 256; + + VkDescriptorImageInfo image_info = { 0 }; + image_info.imageView = img->image.view; + image_info.sampler = vk.sampler; + image_info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + + writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].dstSet = set; + writes[0].dstBinding = 0; + writes[0].descriptorCount = 1; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + writes[0].pBufferInfo = &vbo_info; + + writes[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[1].dstSet = set; + writes[1].dstBinding = 1; + writes[1].descriptorCount = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + writes[1].pImageInfo = &image_info; + + vk.UpdateDescriptorSets(vk.device, ArraySize(writes), writes, 0, 0); + } + + vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, basic->handle); + vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, basic->layout.pipeline, 0, 1, &set, 0, 0); + + VkViewport viewport = { 0, 0, (F32) w, (F32) h, 0.0f, 1.0f }; + VkRect2D scissor = { 0, 0, w, h }; + + vk.CmdSetViewport(cmd, 0, 1, &viewport); + vk.CmdSetScissor(cmd, 0, 1, &scissor); + + vk.CmdDraw(cmd, 6, 1, 0, 0); + vk.CmdEndRendering(cmd); - VkImageMemoryBarrier2 present_src = {0}; - present_src.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2; - present_src.srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; - present_src.srcAccessMask = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT; - present_src.dstStageMask = VK_PIPELINE_STAGE_2_NONE; - present_src.dstAccessMask = VK_ACCESS_2_NONE; - present_src.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - present_src.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; - present_src.image = vk.swapchain.images[frame->image]; - - present_src.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; - present_src.subresourceRange.layerCount = 1; - present_src.subresourceRange.levelCount = 1; - - VkDependencyInfo to_present = {0}; - to_present.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO; - to_present.imageMemoryBarrierCount = 1; - to_present.pImageMemoryBarriers = &present_src; - - vk.CmdPipelineBarrier2(cmd, &to_present); Vk_FrameEnd(); } @@ -157,3 +210,4 @@ int main(int argc, char **argv) #include "core/core.c" #include "os/core.c" #include "vulkan/core.c" +#include "game/core.c" diff --git a/code/game/aabb.h b/code/game/aabb.h index 5254925..e61ba60 100644 --- a/code/game/aabb.h +++ b/code/game/aabb.h @@ -11,7 +11,7 @@ struct AABB { }; -function bool AABB_Collide(AABB a, AABB b); -function bool AABB_Point(AABB a, V2f v); +function bool AABB_Collide(AABB a, AABB b); +function bool AABB_Point(AABB a, V2f v); #endif // LD_GAME_AABB_H_ diff --git a/code/game/core.c b/code/game/core.c new file mode 100644 index 0000000..194b74f --- /dev/null +++ b/code/game/core.c @@ -0,0 +1,198 @@ +void G_ImagesLoad(G_State *game) { + M_TempScope(0, 0) { + Str8 exe_path = FS_SystemPath(temp.arena, FS_SYSTEM_PATH_EXE); + Str8 path = Sf(temp.arena, "%.*s/assets", Sv(exe_path)); + + FS_List assets = FS_PathList(temp.arena, path); + + Vk_Buffer staging = { 0 }; + staging.size = MB(256); + staging.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; + staging.host_visible = true; + + Vk_BufferCreate(&staging); + + U8 *base = staging.data; + U64 offset = 0; + + Vk_CommandBuffer *cmds = Vk_CommandBufferPush(); + + for (FS_Entry *it = assets.first; it != 0; it = it->next) { + if (Str8_EndsWith(it->basename, S("png"))) { + game->n_images += 1; + } + } + + VkBufferImageCopy copy = { 0 }; + game->images = M_ArenaPush(game->arena, G_Image, .count = game->n_images); + game->n_images = 0; + + // Image upload is sbi_load -> copy to staging -> upload to gpu texture + + for (FS_Entry *it = assets.first; it != 0; it = it->next) { + if (Str8_EndsWith(it->basename, S("png"))) { + S32 w, h, c; + stbi_uc *data = stbi_load((const char *) it->path.data, &w, &h, &c, 4); + + if (data) { + G_Image *image = &game->images[game->n_images]; + + U64 image_sz = 4 * w * h; + + M_CopySize(base, data, image_sz); + + copy.bufferOffset = offset; + copy.bufferRowLength = 0; + copy.bufferImageHeight = 0; + + copy.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + copy.imageSubresource.mipLevel = 0; + copy.imageSubresource.baseArrayLayer = 0; + copy.imageSubresource.layerCount = 1; + + copy.imageExtent.width = w; + copy.imageExtent.height = h; + copy.imageExtent.depth = 1; + + base += image_sz; + offset += image_sz; + + Assert(offset <= staging.size); + + game->n_images += 1; + + image->name = Str8_Copy(game->arena, Str8_RemoveAfterLast(it->basename, '.')); + + printf("[Info] :: Loaded %.*s from %.*s\n", Sv(image->name), Sv(it->basename)); + + image->image.width = w; + image->image.height = h; + + image->image.format = VK_FORMAT_R8G8B8A8_SRGB; + image->image.usage = VK_IMAGE_USAGE_SAMPLED_BIT; + + Vk_ImageCreate(&image->image); + + VkImageMemoryBarrier2 transfer = { 0 }; + VkImageMemoryBarrier2 shader_read = { 0 }; + + transfer.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2; + transfer.srcStageMask = VK_PIPELINE_STAGE_2_NONE; + transfer.srcAccessMask = VK_ACCESS_2_NONE; + transfer.dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT; + transfer.dstAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT; + transfer.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + transfer.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + transfer.image = image->image.handle; + + transfer.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + transfer.subresourceRange.layerCount = 1; + transfer.subresourceRange.levelCount = 1; + + shader_read.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2; + shader_read.srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT; + shader_read.srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT; + shader_read.dstStageMask = VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT; + shader_read.dstAccessMask = VK_ACCESS_2_SHADER_SAMPLED_READ_BIT; + shader_read.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; + shader_read.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + shader_read.image = image->image.handle; + + shader_read.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + shader_read.subresourceRange.layerCount = 1; + shader_read.subresourceRange.levelCount = 1; + + VkDependencyInfo dep = { 0 }; + dep.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO; + + dep.imageMemoryBarrierCount = 1; + dep.pImageMemoryBarriers = &transfer; + + vk.CmdPipelineBarrier2(cmds->handle, &dep); + + vk.CmdCopyBufferToImage(cmds->handle, staging.handle, image->image.handle, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ©); + + dep.pImageMemoryBarriers = &shader_read; + + vk.CmdPipelineBarrier2(cmds->handle, &dep); + + stbi_image_free(data); + } + } + } + + Vk_CommandBufferSubmit(cmds, true /* wait */); + } +} + +void G_PipelinesLoad(G_State *game) { + game->pipelines = M_ArenaPush(game->arena, Vk_Pipeline, .count = 1); + + Vk_Pipeline *basic = &game->pipelines[0]; + + VkShaderModule vshader = 0, fshader = 0; + M_TempScope(0, 0) { + Str8 exe_path = FS_SystemPath(temp.arena, FS_SYSTEM_PATH_EXE); + Str8 vshader_code = FS_ReadEntireFile(temp.arena, Sf(temp.arena, "%.*s/assets/shaders/basic.vert.spv", Sv(exe_path))); + Str8 fshader_code = FS_ReadEntireFile(temp.arena, Sf(temp.arena, "%.*s/assets/shaders/basic.frag.spv", Sv(exe_path))); + + VkShaderModuleCreateInfo create_info = { 0 }; + create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; + create_info.pCode = (U32 *) vshader_code.data; + create_info.codeSize = vshader_code.count; + + vk.CreateShaderModule(vk.device, &create_info, 0, &vshader); + + create_info.pCode = (U32 *) fshader_code.data; + create_info.codeSize = fshader_code.count; + + vk.CreateShaderModule(vk.device, &create_info, 0, &fshader); + } + + // Create pipeline layout, its insane what you have to do for this because the ALREADY KNOW + // all of this information + { + VkDescriptorSetLayoutBinding bindings[2] = { 0 }; + + bindings[0].binding = 0; + bindings[0].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + bindings[0].descriptorCount = 1; + bindings[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT; + + bindings[1].binding = 1; + bindings[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + bindings[1].descriptorCount = 1; + bindings[1].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; + + VkDescriptorSetLayoutCreateInfo set_info = { 0 }; + set_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; + set_info.bindingCount = 2; + set_info.pBindings = bindings; + + vk.CreateDescriptorSetLayout(vk.device, &set_info, 0, &basic->layout.set); + + VkPipelineLayoutCreateInfo layout_create = { 0 }; + layout_create.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; + layout_create.setLayoutCount = 1; + layout_create.pSetLayouts = &basic->layout.set; + + vk.CreatePipelineLayout(vk.device, &layout_create, 0, &basic->layout.pipeline); + } + + basic->targets.items[0] = vk.swapchain.format.format; + basic->targets.count = 1; + + basic->shaders.count = 2; + + basic->shaders.items[0].stage = VK_SHADER_STAGE_VERTEX_BIT; + basic->shaders.items[0].handle = vshader; + + basic->shaders.items[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; + basic->shaders.items[1].handle = fshader; + + Vk_PipelineCreate(basic); +} + +#include "impl/aabb.c" +#include "impl/nav.c" +#include "impl/player.c" diff --git a/code/game/core.h b/code/game/core.h new file mode 100644 index 0000000..70f4fa6 --- /dev/null +++ b/code/game/core.h @@ -0,0 +1,40 @@ +#if !defined(LD_GAME_CORE_H_) +#define LD_GAME_CORE_H_ + +typedef struct G_Vertex G_Vertex; +struct G_Vertex { + F32 x, y, z, w; + F32 u, v; + U32 c; + U32 pad; +}; + +typedef struct G_Image G_Image; +struct G_Image { + Str8 name; + Vk_Image image; +}; + +typedef struct G_State G_State; +struct G_State { + M_Arena *arena; + + U32 n_images; + G_Image *images; + + U32 n_pipelines; + Vk_Pipeline *pipelines; + + Vk_Buffer vbo; +}; + +function void G_ImagesLoad(G_State *game); +function void G_PipelinesLoad(G_State *game); + +#include "aabb.h" +#include "player.h" +#include "nav.h" +#include "npc.h" +#include "world.h" + +#endif // LD_GAME_CORE_H_ diff --git a/code/game/impl/aabb.c b/code/game/impl/aabb.c index 3637513..c1d1fba 100644 --- a/code/game/impl/aabb.c +++ b/code/game/impl/aabb.c @@ -1,5 +1,5 @@ -#include "../aabb.h" -#include "../types.h" +#include "game/aabb.h" +#include "core/types.h" bool AABB_Collide(AABB a, AABB b) { bool collision_x = a.pos.x + a.size.x >= b.pos.x && b.pos.x + b.size.x >= a.pos.x; diff --git a/code/game/impl/nav.c b/code/game/impl/nav.c index 090eb09..96f78ae 100644 --- a/code/game/impl/nav.c +++ b/code/game/impl/nav.c @@ -1,5 +1,6 @@ -#include "../nav.h" -#include "../../core/types.h" +#include "game/nav.h" +#include "core/types.h" + #include #define MAX_UNFINISHED 128 @@ -14,16 +15,16 @@ struct navSearchNodeState{ typedef struct navSearchState navSearchState; struct navSearchState{ - navSearchNodeState nodeStates[NAV_MAX_NODES]; + navSearchNodeState nodeStates[NAV_MAX_NODES]; }; navSearchState initState(U32 start, U32 meshSize) { navSearchState state = {}; - for(int i = 0; i < meshSize; i++) { + for(U32 i = 0; i < meshSize; i++) { state.nodeStates[i].visited = false; state.nodeStates[i].addedToUnvisited = false; - // underflow to the max :) - state.nodeStates[i].distance = -1; + // underflow to the max :) + state.nodeStates[i].distance = U64_MAX; state.nodeStates[i].shortest = 0; } state.nodeStates[start].distance = 0; @@ -31,10 +32,10 @@ navSearchState initState(U32 start, U32 meshSize) { } U32 getLowestState(U32 unfinishedIndexes[128], U32 unfinishedCount, navSearchState state, U32 *offset) { - U32 lowest = -1; - U32 lowestI = -1; + U32 lowest = U32_MAX; + U32 lowestI = U32_MAX; bool startFound = false; - for(int i = *offset; i < unfinishedCount; i++) { + for(U32 i = *offset; i < unfinishedCount; i++) { navSearchNodeState checkNode = state.nodeStates[unfinishedIndexes[i]]; if(checkNode.visited) { if(!startFound) { @@ -44,7 +45,7 @@ U32 getLowestState(U32 unfinishedIndexes[128], U32 unfinishedCount, navSearchSta } startFound = true; if (lowest > checkNode.distance) { - lowest = checkNode.distance; + lowest = cast(U32) checkNode.distance; lowestI = unfinishedIndexes[i]; } } @@ -60,7 +61,7 @@ NavPath Nav_Path(NavMesh mesh, U32 start, U32 end) { // the unfinished nodes, so when checking for a lowest // if I find the first N items have been checked, I'll mark // an offset to skip the first N items. - U32 unfinishedOffset = 0; + U32 unfinishedOffset = 0; U32 lowestNodeIndex = start; bool found = false; while(!found) { @@ -68,11 +69,11 @@ NavPath Nav_Path(NavMesh mesh, U32 start, U32 end) { NavConnection connection = mesh.nodes[lowestNodeIndex].connections[connectionI]; navSearchNodeState *testNode = &state.nodeStates[connection.NodeIndex]; if(testNode->visited) {continue;} - U32 distance = state.nodeStates[lowestNodeIndex].distance + connection.Cost; - distance += mesh.nodes[end].pos.x - mesh.nodes[connection.NodeIndex].pos.x; - distance += mesh.nodes[end].pos.y - mesh.nodes[connection.NodeIndex].pos.y; + U32 distance = cast(U32) (state.nodeStates[lowestNodeIndex].distance + connection.Cost); + distance += cast(U32) (mesh.nodes[end].pos.x - mesh.nodes[connection.NodeIndex].pos.x); + distance += cast(U32) (mesh.nodes[end].pos.y - mesh.nodes[connection.NodeIndex].pos.y); if(testNode->distance > distance) { - testNode->distance = distance; + testNode->distance = distance; testNode->shortest = lowestNodeIndex; } if(!testNode->addedToUnvisited) { diff --git a/code/game/impl/npc.c b/code/game/impl/npc.c index 4cc3551..dc806b3 100644 --- a/code/game/impl/npc.c +++ b/code/game/impl/npc.c @@ -1,7 +1,6 @@ #include "../npc.h" #include "../world.h" #include "../../core/types.h" -#include "nav.c" #include void updateNPC(F32 delta, NPC *npc, World *world) { diff --git a/code/game/nav.h b/code/game/nav.h index 5820cb6..b407c26 100644 --- a/code/game/nav.h +++ b/code/game/nav.h @@ -1,8 +1,8 @@ #if !defined(LD_GAME_NAV_H_) #define LD_GAME_NAV_H_ -#include "../core/types.h" -#include "../core/macros.h" +#include "core/types.h" +#include "core/macros.h" #define NAV_MAX_PATH 1024 #define NAV_MAX_CONNECTIONS 8 diff --git a/code/game/player.h b/code/game/player.h index f24a863..8067026 100644 --- a/code/game/player.h +++ b/code/game/player.h @@ -1,7 +1,11 @@ +#if !defined(LD_GAME_PLAYER_H_) +#define LD_GAME_PLAYER_H_ + #include "../core/types.h" -#include #include "../core/macros.h" +#include + typedef struct Player Player; struct Player { @@ -9,3 +13,5 @@ struct Player }; function void PlayerUpdate(SDL_Event *event, Player *player); + +#endif // LD_GAME_PLAYER_H_ diff --git a/code/os/core.c b/code/os/core.c index 0ebb8a9..dd739ff 100644 --- a/code/os/core.c +++ b/code/os/core.c @@ -3,3 +3,19 @@ #elif OS_LINUX #include "impl/linux/core.c" #endif + + +Str8 FS_ReadEntireFile(M_Arena *arena, Str8 path) { + Str8 result = { 0 }; + + OS_Handle file = FS_FileOpen(path, FS_ACCESS_READ); + if (file.v[0]) { + result.count = FS_FileSize(file); + result.data = M_ArenaPush(arena, U8, .count = result.count); + + FS_FileRead(file, result.data, result.count, 0); + FS_FileClose(file); + } + + return result; +} diff --git a/code/os/core.h b/code/os/core.h index 55ac3b8..efca174 100644 --- a/code/os/core.h +++ b/code/os/core.h @@ -1,6 +1,11 @@ #if !defined(LD_OS_CORE_H_) #define LD_OS_CORE_H_ +typedef struct OS_Handle OS_Handle; +struct OS_Handle { + U64 v[1]; +}; + // Virtual memory function U64 VM_PageSize(); @@ -11,4 +16,6 @@ function B32 VM_Commit(void *base, U64 size); function void VM_Decommit(void *base, U64 size); function void VM_Release(void *base, U64 size); +#include "filesystem.h" + #endif // LD_OS_CORE_H_ diff --git a/code/os/filesystem.h b/code/os/filesystem.h new file mode 100644 index 0000000..ef4f7d9 --- /dev/null +++ b/code/os/filesystem.h @@ -0,0 +1,59 @@ +#if !defined(LD_OS_FILESYSTEM_H_) +#define LD_OS_FILESYSTEM_H_ + +typedef U32 FS_AccessFlags; +enum { + FS_ACCESS_READ = (1 << 0), + FS_ACCESS_WRITE = (1 << 1) +}; + +function OS_Handle FS_FileOpen(Str8 path, FS_AccessFlags access); +function void FS_FileClose(OS_Handle file); + +function void FS_FileRead(OS_Handle file, void *ptr, U64 size, U64 offset); +function void FS_FileWrite(OS_Handle file, void *ptr, U64 size, U64 offset); + +function U64 FS_FileSize(OS_Handle file); + +typedef U32 FS_EntryType; +enum { + FS_ENTRY_TYPE_FILE = 0, + FS_ENTRY_TYPE_DIR +}; + +typedef struct FS_Entry FS_Entry; +struct FS_Entry { + FS_Entry *next; + + FS_EntryType type; + + Str8 path; + Str8 basename; + + U64 time; + U64 size; +}; + +typedef struct FS_List FS_List; +struct FS_List { + FS_Entry *first; + FS_Entry *last; + + U32 count; +}; + +function FS_List FS_PathList(M_Arena *arena, Str8 path); + +function Str8 FS_ReadEntireFile(M_Arena *arena, Str8 path); + +typedef U32 FS_SystemPathType; +enum { + FS_SYSTEM_PATH_EXE = 0, + FS_SYSTEM_PATH_WORKING, + FS_SYSTEM_PATH_USER, + FS_SYSTEM_PATH_TEMP +}; + +function Str8 FS_SystemPath(M_Arena *arena, FS_SystemPathType path); + +#endif // LD_OS_FILESYSTEM_H_ diff --git a/code/os/impl/linux/core.c b/code/os/impl/linux/core.c index 1dd1cd9..79c0af9 100644 --- a/code/os/impl/linux/core.c +++ b/code/os/impl/linux/core.c @@ -28,4 +28,4 @@ void VM_Release(void *base, U64 size) { munmap(base, size); } - +#include "filesystem.c" diff --git a/code/os/impl/linux/filesystem.c b/code/os/impl/linux/filesystem.c new file mode 100644 index 0000000..ef3a9a4 --- /dev/null +++ b/code/os/impl/linux/filesystem.c @@ -0,0 +1,215 @@ +OS_Handle FS_FileOpen(Str8 path, FS_AccessFlags access) { + OS_Handle result = { 0 }; + + M_TempScope(0, 0) { + Str8 zpath = Str8_Copy(temp.arena, path); + + int mode = 0644; + int flags = 0; + if (access & FS_ACCESS_READ) { + if (access & FS_ACCESS_WRITE) { + flags = O_RDWR | O_CREAT; + } + else { + flags = O_RDONLY; + } + } + else if (access & FS_ACCESS_WRITE) { + flags = O_WRONLY | O_CREAT; + } + + + int fd = open((const char *) zpath.data, flags, mode); + result.v[0] = (fd > 0) ? (U64) fd : 0; + } + + return result; +} +void FS_FileClose(OS_Handle file) { + int fd = cast(int) file.v[0]; + if (fd > 0) { + close(fd); + } +} + +void FS_FileRead(OS_Handle file, void *ptr, U64 size, U64 offset) { + int fd = cast(int) file.v[0]; + if (fd > 0) { + U8 *buffer = ptr; + U64 current = offset; + U64 remainder = size; + + while (remainder != 0) { + S64 nread = pread(fd, buffer, remainder, current); + if (nread <= 0) { + break; + } + + buffer += nread; + current += nread; + remainder -= nread; + } + } +} + +void FS_FileWrite(OS_Handle file, void *ptr, U64 size, U64 offset) { + int fd = cast(int) file.v[0]; + if (fd > 0) { + U8 *buffer = ptr; + U64 current = offset; + U64 remainder = size; + + while (remainder != 0) { + S64 nwritten = pwrite(fd, buffer, remainder, current); + if (nwritten <= 0) { + break; + } + + buffer += nwritten; + current += nwritten; + remainder -= nwritten; + } + } +} + +U64 FS_FileSize(OS_Handle file) { + U64 result = 0; + + int fd = cast(int) file.v[0]; + if (fd > 0) { + struct stat sb; + fstat(fd, &sb); + + result = sb.st_size; + } + + return result; +} + +FS_List FS_PathList(M_Arena *arena, Str8 path) { + FS_List result = { 0 }; + + M_TempScope(1, &arena) { + Str8 zpath = Str8_Copy(temp.arena, path); + + DIR *dir = opendir((const char *) zpath.data); + + struct dirent *ent = readdir(dir); + while (ent != 0) { + if (ent->d_name[0] != '.') { + FS_Entry *entry = M_ArenaPush(arena, FS_Entry); + + entry->basename = Str8_Copy(arena, Sz(ent->d_name)); + entry->path = Sf(arena, "%.*s/%.*s", Sv(path), Sv(entry->basename)); + + struct stat sb; + stat((const char *) entry->path.data, &sb); + + entry->type = ((sb.st_mode & S_IFMT) == S_IFDIR) ? FS_ENTRY_TYPE_DIR : FS_ENTRY_TYPE_FILE; + entry->time = (sb.st_mtim.tv_sec * 1e9) + sb.st_mtim.tv_nsec; + entry->size = sb.st_size; + + SLL_Enqueue(result.first, result.last, entry); + result.count += 1; + } + + ent = readdir(dir); + } + } + + return result; +} + +Str8 FS_SystemPath(M_Arena *arena, FS_SystemPathType path) { + Str8 result = { 0 }; + + switch (path) { + case FS_SYSTEM_PATH_EXE: { + U64 offset = M_ArenaOffset(arena); + + Str8 buffer; + buffer.count = KB(1); + buffer.data = M_ArenaPush(arena, U8, .count = buffer.count); + + ssize_t nwritten = 0; + for (;;) { + nwritten = readlink("/proc/self/exe", cast(char *) buffer.data, buffer.count); + if (nwritten < buffer.count) { + break; + } + + M_ArenaPop(arena, offset); + + buffer.count *= 2; + buffer.data = M_ArenaPush(arena, U8, .count = buffer.count); + } + + if (nwritten > 0) { + // Walk back until the prevous slash, then null-terminate there + while (buffer.data[nwritten] != '/') { nwritten -= 1; } + buffer.data[nwritten] = 0; + + M_ArenaPopSize(arena, buffer.count - nwritten - 1); + + result.count = nwritten; + result.data = buffer.data; + } + else { + M_ArenaPop(arena, offset); + } + } + break; + + case FS_SYSTEM_PATH_WORKING: { + U64 offset = M_ArenaOffset(arena); + + Str8 buffer; + buffer.count = KB(1); + buffer.data = M_ArenaPush(arena, U8, .count = buffer.count); + + char *wd; + + for (;;) { + wd = getcwd((char *) buffer.data, buffer.count); + if (wd != 0) { + break; + } + else if (errno != ERANGE) { + break; + } + + M_ArenaPop(arena, offset); + + buffer.count *= 2; + buffer.data = M_ArenaPush(arena, U8, .count = buffer.count); + } + + if (wd) { + result = Sz(wd); + M_ArenaPopSize(arena, buffer.count - result.count - 1); + } + } + break; + + case FS_SYSTEM_PATH_USER: { + char *home = getenv("HOME"); + if (home) { + result = Sf(arena, "%s/.local/share", home); + } + } + break; + + case FS_SYSTEM_PATH_TEMP: { + char *temp = getenv("TEMP"); + if (temp) { + result = Str8_Copy(arena, Sz(temp)); + } + else { + result = Str8_Copy(arena, S("/tmp")); + } + } + break; + } + + return result; +} diff --git a/code/os/impl/windows/core.c b/code/os/impl/windows/core.c index 7c95e39..1586489 100644 --- a/code/os/impl/windows/core.c +++ b/code/os/impl/windows/core.c @@ -1,3 +1,32 @@ +// Windows utilities + +internal Str8 Win32_WideStr(M_Arena *arena, Str8 v) { + Str8 result = { 0 }; + + S32 nchars = MultiByteToWideChar(CP_UTF8, 0, (LPCCH) v.data, (int) v.count, 0, 0) + 1; + U64 nbytes = nchars << 1; + + result.count = nbytes - 2; // -2 because we don't include the null-terminator in the count + result.data = M_ArenaPush(arena, U8, .count = nbytes); + + MultiByteToWideChar(CP_UTF8, 0, (LPCCH) v.data, (int) v.count, (LPWSTR) result.data, nchars); + + return result; +} + +internal Str8 Win32_MultiByteStr(M_Arena *arena, LPWSTR wstr) { + Str8 result = { 0 }; + + S32 nbytes = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, 0, 0, 0, 0); + + result.count = nbytes - 1; + result.data = M_ArenaPush(arena, U8, .count = nbytes); + + WideCharToMultiByte(CP_UTF8, 0, wstr, -1, (LPSTR) result.data, nbytes, 0, 0); + + return result; +} + // Virtual memory U64 VM_PageSize() { @@ -36,3 +65,4 @@ void VM_Release(void *base, U64 size) { VirtualFree(base, 0, MEM_RELEASE); } +#include "filesystem.c" diff --git a/code/os/impl/windows/filesystem.c b/code/os/impl/windows/filesystem.c new file mode 100644 index 0000000..4819811 --- /dev/null +++ b/code/os/impl/windows/filesystem.c @@ -0,0 +1,209 @@ +OS_Handle FS_FileOpen(Str8 path, FS_AccessFlags access) { + OS_Handle result = { 0 }; + + M_TempScope(0, 0) { + Str8 wpath = Win32_WideStr(temp.arena, path); + + DWORD dwAccess = 0; + DWORD dwShare = FILE_SHARE_READ; + DWORD dwCreate = OPEN_EXISTING; + + if (access & FS_ACCESS_WRITE) { + dwCreate = CREATE_ALWAYS; + dwAccess = GENERIC_WRITE; + } + + if (access & FS_ACCESS_READ) { + dwAccess |= GENERIC_READ; + } + + HANDLE hFile = CreateFileW((LPCWSTR) wpath.data, dwAccess, dwShare, 0, dwCreate, 0, 0); + + result.v[0] = (hFile == INVALID_HANDLE_VALUE) ? 0 : ((U64) hFile); + } + return result; +} + +void FS_FileClose(OS_Handle file) { + HANDLE hFile = cast(HANDLE) file.v[0]; + if (hFile) { + CloseHandle(hFile); + } +} + +void FS_FileRead(OS_Handle file, void *ptr, U64 size, U64 offset) { + HANDLE hFile = cast(HANDLE) file.v[0]; + if (hFile) { + U8 *buffer = ptr; + U64 current = offset; + U64 remainder = size; + + while (remainder != 0) { + OVERLAPPED overlapped = { 0 }; + overlapped.Offset = cast(DWORD) (current & 0xFFFFFFFF); + overlapped.OffsetHigh = cast(DWORD) ((current >> 32) & 0xFFFFFFFF); + + DWORD toread = (remainder > U32_MAX) ? U32_MAX : (DWORD) remainder; + DWORD nread = 0; + + if (!ReadFile(hFile, buffer, toread, &nread, &overlapped)) { + break; + } + + buffer += nread; + current += nread; + remainder -= nread; + } + } +} + +void FS_FileWrite(OS_Handle file, void *ptr, U64 size, U64 offset) { + HANDLE hFile = cast(HANDLE) file.v[0]; + if (hFile) { + U8 *buffer = ptr; + U64 current = offset; + U64 remainder = size; + + while (remainder != 0) { + OVERLAPPED overlapped = { 0 }; + overlapped.Offset = cast(DWORD) (current & 0xFFFFFFFF); + overlapped.OffsetHigh = cast(DWORD) ((current >> 32) & 0xFFFFFFFF); + + DWORD towrite = (remainder > U32_MAX) ? U32_MAX : (DWORD) remainder; + DWORD nwritten = 0; + + if (!WriteFile(hFile, buffer, towrite, &nwritten, &overlapped)) { + break; + } + + buffer += nwritten; + current += nwritten; + remainder -= nwritten; + } + } +} + +U64 FS_FileSize(OS_Handle file) { + U64 result = 0; + HANDLE hFile = cast(HANDLE) file.v[0]; + if (hFile) { + DWORD dwLow, dwHigh; + dwLow = GetFileSize(hFile, &dwHigh); + + result = ((U64) dwHigh << 32) | ((U64) dwLow); + } + + return result; +} + +FS_List FS_PathList(M_Arena *arena, Str8 path) { + FS_List result = { 0 }; + + M_TempScope(1, &arena) { + Str8 wpath = Win32_WideStr(temp.arena, Sf(temp.arena, "%.*s\\*", Sv(path))); + + WIN32_FIND_DATAW find = { 0 }; + HANDLE hFind = FindFirstFileW((LPCWSTR) wpath.data, &find); + + while (hFind != INVALID_HANDLE_VALUE) { + if (find.cFileName[0] != L'.') { + FS_Entry *entry = M_ArenaPush(arena, FS_Entry); + + entry->type = (find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? FS_ENTRY_TYPE_DIR : FS_ENTRY_TYPE_FILE; + + entry->basename = Win32_MultiByteStr(arena, find.cFileName); + entry->path = Sf(arena, "%.*s/%.*s", Sv(path), Sv(entry->basename)); + + FILETIME *wt = &find.ftLastWriteTime; + + entry->time = ((U64) wt->dwHighDateTime << 32) | ((U64) wt->dwLowDateTime); + entry->size = ((U64) find.nFileSizeHigh << 32) | ((U64) find.nFileSizeLow); + + SLL_Enqueue(result.first, result.last, entry); + + result.count += 1; + } + + if (!FindNextFileW(hFind, &find)) { + break; + } + } + } + + return result; +} + +Str8 FS_SystemPath(M_Arena *arena, FS_SystemPathType path) { + Str8 result = { 0 }; + + M_TempScope(1, &arena) { + switch (path) { + case FS_SYSTEM_PATH_EXE: { + U64 offset = M_ArenaOffset(temp.arena); + + DWORD err, nchars; + + DWORD nSize = 1024; + LPWSTR lpFilename = M_ArenaPush(temp.arena, WCHAR, .count = nSize, .flags = M_ARENA_NO_ZERO); + + for (;;) { + nchars = GetModuleFileNameW(0, lpFilename, nSize); + + err = GetLastError(); + if (err != ERROR_INSUFFICIENT_BUFFER) { + break; + } + + M_ArenaPop(temp.arena, offset); + + nSize *= 2; + lpFilename = M_ArenaPush(temp.arena, WCHAR, .count = nSize, .flags = M_ARENA_NO_ZERO); + } + + if (err == ERROR_SUCCESS) { + while (lpFilename[nchars] != '\\') { nchars -= 1; } + lpFilename[nchars] = 0; + + result = Win32_MultiByteStr(arena, lpFilename); + } + } + break; + + case FS_SYSTEM_PATH_WORKING: { + DWORD nSize = GetCurrentDirectoryW(0, 0); + + if (nSize != 0) { + LPWSTR lpBuffer = M_ArenaPush(temp.arena, WCHAR, .count = nSize, .flags = M_ARENA_NO_ZERO); + GetCurrentDirectoryW(nSize, lpBuffer); + + result = Win32_MultiByteStr(arena, lpBuffer); + } + } + break; + + case FS_SYSTEM_PATH_USER: { + LPWSTR wpath; + HRESULT hResult = SHGetKnownFolderPath(&FOLDERID_RoamingAppData, 0, 0, &wpath); + if (hResult == S_OK) { + result = Win32_MultiByteStr(arena, wpath); + CoTaskMemFree(wpath); + } + } + break; + + case FS_SYSTEM_PATH_TEMP: { + DWORD nSize = MAX_PATH + 1; + LPWSTR lpBuffer = M_ArenaPush(temp.arena, WCHAR, .count = nSize); + + DWORD nchars = GetTempPathW(nSize, lpBuffer); + if (nchars != 0) { + lpBuffer[nchars - 1] = 0; // Strip trailing backslash + result = Win32_MultiByteStr(arena, lpBuffer); + } + } + break; + } + } + + return result; +} diff --git a/code/vulkan/core.c b/code/vulkan/core.c index 8b7f8c1..01201e2 100644 --- a/code/vulkan/core.c +++ b/code/vulkan/core.c @@ -330,6 +330,7 @@ bool Vk_Setup(SDL_Window *window) { VkResult err = vk.CreateCommandPool(vk.device, &pool, 0, &frame->pool); + // Base command buffer VkCommandBufferAllocateInfo alloc = { 0 }; alloc.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; alloc.commandBufferCount = 1; @@ -338,21 +339,58 @@ bool Vk_Setup(SDL_Window *window) { vk.AllocateCommandBuffers(vk.device, &alloc, &frame->cmd); - VkSemaphoreCreateInfo semaphore = { 0 }; - semaphore.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + // Scratch command buffers + VkCommandBuffer scratch[VK_NUM_SCRATCH]; + alloc.commandBufferCount = VK_NUM_SCRATCH; - err = Min(vk.CreateSemaphore(vk.device, &semaphore, 0, &frame->acquire), err); - err = Min(vk.CreateSemaphore(vk.device, &semaphore, 0, &frame->complete), err); + vk.AllocateCommandBuffers(vk.device, &alloc, scratch); VkFenceCreateInfo fence = { 0 }; fence.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fence.flags = VK_FENCE_CREATE_SIGNALED_BIT; + for (U32 s = 0; s < VK_NUM_SCRATCH; ++s) { + frame->scratch[s].handle = scratch[s]; + err = Min(vk.CreateFence(vk.device, &fence, 0, &frame->scratch[s].fence), err); + } + + // Descriptor pool + VkDescriptorPoolSize pool_sizes[2] = { 0 }; + + pool_sizes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + pool_sizes[0].descriptorCount = 2048; + + pool_sizes[1].type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; + pool_sizes[1].descriptorCount = 2048; + + VkDescriptorPoolCreateInfo descriptor_pool = { 0 }; + descriptor_pool.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; + descriptor_pool.maxSets = 1024; + descriptor_pool.poolSizeCount = 2; + descriptor_pool.pPoolSizes = pool_sizes; + + vk.CreateDescriptorPool(vk.device, &descriptor_pool, 0, &frame->descriptors); + + VkSemaphoreCreateInfo semaphore = { 0 }; + semaphore.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; + + err = Min(vk.CreateSemaphore(vk.device, &semaphore, 0, &frame->acquire), err); + err = Min(vk.CreateSemaphore(vk.device, &semaphore, 0, &frame->complete), err); err = Min(vk.CreateFence(vk.device, &fence, 0, &frame->fence), err); vk.err = err; } + { + VkSamplerCreateInfo create_info = { 0 }; + create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; + create_info.magFilter = VK_FILTER_NEAREST; + create_info.minFilter = VK_FILTER_NEAREST; + create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; + + vk.CreateSampler(vk.device, &create_info, 0, &vk.sampler); + } + result = (vk.err == VK_SUCCESS); return result; } @@ -365,6 +403,7 @@ Vk_Frame *Vk_FrameBegin(SDL_Window *window) { vk.ResetFences(vk.device, 1, &frame->fence); vk.ResetCommandPool(vk.device, frame->pool, 0); + vk.ResetDescriptorPool(vk.device, frame->descriptors, 0); VkResult res = vk.AcquireNextImageKHR(vk.device, vk.swapchain.handle, UINT64_MAX, frame->acquire, 0, &frame->image); (void) res; // @Todo: check res to see if swapchain is out of date and rebuild @@ -374,12 +413,54 @@ Vk_Frame *Vk_FrameBegin(SDL_Window *window) { vk.BeginCommandBuffer(frame->cmd, &begin_info); + VkImageMemoryBarrier2 colour_optimal = { 0 }; + colour_optimal.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2; + colour_optimal.srcStageMask = VK_PIPELINE_STAGE_2_NONE; + colour_optimal.srcAccessMask = VK_ACCESS_2_NONE; + colour_optimal.dstStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; + colour_optimal.dstAccessMask = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT; + colour_optimal.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; + colour_optimal.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + colour_optimal.image = vk.swapchain.images[frame->image]; + + colour_optimal.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + colour_optimal.subresourceRange.layerCount = 1; + colour_optimal.subresourceRange.levelCount = 1; + + VkDependencyInfo colour_barrier = { 0 }; + colour_barrier.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO; + colour_barrier.imageMemoryBarrierCount = 1; + colour_barrier.pImageMemoryBarriers = &colour_optimal; + + vk.CmdPipelineBarrier2(frame->cmd, &colour_barrier); + return frame; } void Vk_FrameEnd() { Vk_Frame *frame = &vk.frames[vk.n_frames % vk.in_flight]; + VkImageMemoryBarrier2 present_src = { 0 }; + present_src.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2; + present_src.srcStageMask = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT; + present_src.srcAccessMask = VK_ACCESS_2_COLOR_ATTACHMENT_WRITE_BIT; + present_src.dstStageMask = VK_PIPELINE_STAGE_2_NONE; + present_src.dstAccessMask = VK_ACCESS_2_NONE; + present_src.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + present_src.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + present_src.image = vk.swapchain.images[frame->image]; + + present_src.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + present_src.subresourceRange.layerCount = 1; + present_src.subresourceRange.levelCount = 1; + + VkDependencyInfo to_present = { 0 }; + to_present.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO; + to_present.imageMemoryBarrierCount = 1; + to_present.pImageMemoryBarriers = &present_src; + + vk.CmdPipelineBarrier2(frame->cmd, &to_present); + vk.EndCommandBuffer(frame->cmd); VkPipelineStageFlags stage = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT; @@ -408,3 +489,223 @@ void Vk_FrameEnd() { vk.n_frames += 1; } + +Vk_CommandBuffer *Vk_CommandBufferPush() { + Vk_Frame *frame = &vk.frames[vk.n_frames % vk.in_flight]; + + // If this scratch buffer is still in use wait for it to finish, this is _bad_ but we + // shouldn't hit this + U32 idx = frame->next_scratch & (VK_NUM_SCRATCH - 1); + + Vk_CommandBuffer *result = &frame->scratch[idx]; + + vk.WaitForFences(vk.device, 1, &result->fence, VK_TRUE, U64_MAX); + vk.ResetFences(vk.device, 1, &result->fence); + + VkCommandBufferBeginInfo begin_info = { 0 }; + begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; + + vk.BeginCommandBuffer(result->handle, &begin_info); + + return result; +} + +void Vk_CommandBufferSubmit(Vk_CommandBuffer *cmds, B32 wait) { + vk.EndCommandBuffer(cmds->handle); + + VkSubmitInfo submit_info = { 0 }; + submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; + submit_info.commandBufferCount = 1; + submit_info.pCommandBuffers = &cmds->handle; + + vk.QueueSubmit(vk.queue.handle, 1, &submit_info, cmds->fence); + + if (wait) { vk.DeviceWaitIdle(vk.device); } +} + +#define VK_HOST_VISIBLE_FLAGS (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) + +internal VkDeviceMemory Vk_Allocate(VkMemoryRequirements *mreq, VkMemoryPropertyFlags usage) { + VkDeviceMemory result = VK_NULL_HANDLE; + + VkPhysicalDeviceMemoryProperties2 _props = { 0 }; + _props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2; + + vk.GetPhysicalDeviceMemoryProperties2(vk.gpu, &_props); + + // ????? + VkPhysicalDeviceMemoryProperties *props = &_props.memoryProperties; + + U32 type_index = U32_MAX; + + for (U32 it = 0; it < props->memoryTypeCount; ++it) { + VkMemoryType *type = &props->memoryTypes[it]; + if ((type->propertyFlags & usage) == usage) { + type_index = it; + break; + } + } + + if (type_index != -1) { + VkMemoryAllocateInfo alloc_info = { 0 }; + alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; + alloc_info.allocationSize = mreq->size; + alloc_info.memoryTypeIndex = type_index; + + vk.AllocateMemory(vk.device, &alloc_info, 0, &result); + } + + return result; +} + +void Vk_BufferCreate(Vk_Buffer *buffer) { + VkBufferCreateInfo create_info = { 0 }; + create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; + create_info.usage = buffer->usage; + create_info.size = buffer->size; + + vk.CreateBuffer(vk.device, &create_info, 0, &buffer->handle); + + VkMemoryRequirements req; + vk.GetBufferMemoryRequirements(vk.device, buffer->handle, &req); + + VkMemoryPropertyFlags usage = buffer->host_visible ? VK_HOST_VISIBLE_FLAGS : VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; + + buffer->size = req.size; + buffer->memory = Vk_Allocate(&req, usage); + + vk.BindBufferMemory(vk.device, buffer->handle, buffer->memory, 0); + + if (buffer->host_visible) { + vk.MapMemory(vk.device, buffer->memory, 0, buffer->size, 0, &buffer->data); + } +} + +void Vk_ImageCreate(Vk_Image *image) { + VkImageCreateInfo create_info = { 0 }; + create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; + create_info.imageType = VK_IMAGE_TYPE_2D; + create_info.format = image->format; + create_info.extent.width = image->width; + create_info.extent.height = image->height; + create_info.extent.depth = 1; + create_info.mipLevels = 1; + create_info.arrayLayers = 1; + create_info.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | image->usage; + create_info.samples = VK_SAMPLE_COUNT_1_BIT; + create_info.tiling = VK_IMAGE_TILING_OPTIMAL; + + vk.CreateImage(vk.device, &create_info, 0, &image->handle); + + VkMemoryRequirements req; + vk.GetImageMemoryRequirements(vk.device, image->handle, &req); + + image->size = req.size; + image->memory = Vk_Allocate(&req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + + vk.BindImageMemory(vk.device, image->handle, image->memory, 0); + + VkImageViewCreateInfo view_info = { 0 }; + view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; + view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; + view_info.format = image->format; + view_info.image = image->handle; + + view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + view_info.subresourceRange.levelCount = 1; + view_info.subresourceRange.layerCount = 1; + + vk.CreateImageView(vk.device, &view_info, 0, &image->view); +} + +void Vk_PipelineCreate(Vk_Pipeline *pipeline) { + VkPipelineInputAssemblyStateCreateInfo ia = { 0 }; + ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + + VkPipelineShaderStageCreateInfo shaders[8] = { 0 }; + for (U32 it = 0; it < pipeline->shaders.count; ++it) { + shaders[it].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; + shaders[it].stage = pipeline->shaders.items[it].stage; + shaders[it].module = pipeline->shaders.items[it].handle; + shaders[it].pName = "main"; + } + + VkPipelineVertexInputStateCreateInfo vi = { 0 }; + vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; + + // This will be updated later using dynamic commands but we still need to supply one here for + // some reason + VkViewport viewport = { 0, 0, 10, 10, 0, 1 }; + VkRect2D scissor = { 0, 0, 10, 10 }; + + VkPipelineViewportStateCreateInfo vp = { 0 }; + vp.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; + vp.viewportCount = 1; + vp.pViewports = &viewport; + vp.scissorCount = 1; + vp.pScissors = &scissor; + + VkPipelineRasterizationStateCreateInfo rs = { 0 }; + rs.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; + rs.lineWidth = 1.0f; + + VkPipelineMultisampleStateCreateInfo ms = { 0 }; + ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + + VkPipelineDepthStencilStateCreateInfo ds = { 0 }; + ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; + + VkPipelineColorBlendAttachmentState blend = { 0 }; + blend.blendEnable = VK_TRUE; + blend.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA; + blend.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA; + blend.colorBlendOp = VK_BLEND_OP_ADD; + blend.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; + blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; + blend.alphaBlendOp = VK_BLEND_OP_ADD; + blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; + + VkPipelineColorBlendStateCreateInfo om = { 0 }; + om.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; + om.attachmentCount = 1; + om.pAttachments = &blend; + + VkDynamicState dynamic_state[] = { + VK_DYNAMIC_STATE_VIEWPORT, + VK_DYNAMIC_STATE_SCISSOR + }; + + VkPipelineDynamicStateCreateInfo dyn = { 0 }; + dyn.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO; + dyn.dynamicStateCount = ArraySize(dynamic_state); + dyn.pDynamicStates = dynamic_state; + + VkFormat formats[8]; + for (U32 it = 0; it < pipeline->targets.count; ++it) { + formats[it] = pipeline->targets.items[it]; + } + + VkPipelineRenderingCreateInfo rendering_info = { 0 }; + rendering_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RENDERING_CREATE_INFO; + rendering_info.colorAttachmentCount = pipeline->targets.count; + rendering_info.pColorAttachmentFormats = formats; + + VkGraphicsPipelineCreateInfo create_info = { 0 }; + create_info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; + create_info.pNext = &rendering_info; + create_info.stageCount = pipeline->shaders.count; + create_info.pStages = shaders; + create_info.pVertexInputState = &vi; + create_info.pInputAssemblyState = &ia; + create_info.pViewportState = &vp; + create_info.pRasterizationState = &rs; + create_info.pMultisampleState = &ms; + create_info.pDepthStencilState = &ds; + create_info.pColorBlendState = &om; + create_info.pDynamicState = &dyn; + create_info.layout = pipeline->layout.pipeline; + + vk.CreateGraphicsPipelines(vk.device, 0, 1, &create_info, 0, &pipeline->handle); +} diff --git a/code/vulkan/core.h b/code/vulkan/core.h index 88825ea..b6849bf 100644 --- a/code/vulkan/core.h +++ b/code/vulkan/core.h @@ -23,15 +23,79 @@ #define function static #define VK_MAX_FRAMES_IN_FLIGHT 8 +#define VK_NUM_SCRATCH 8 + +typedef struct Vk_Image Vk_Image; +struct Vk_Image { + VkDeviceMemory memory; + VkDeviceSize size; + + VkImage handle; + VkImageView view; + + VkFormat format; + VkImageUsageFlags usage; + U32 width, height; +}; + +typedef struct Vk_Buffer Vk_Buffer; +struct Vk_Buffer { + VkBuffer handle; + + VkDeviceMemory memory; + VkDeviceSize size; + + VkBufferUsageFlags usage; + + B32 host_visible; + void *data; // if mapped host visible memory +}; + +typedef struct Vk_Shader Vk_Shader; +struct Vk_Shader { + VkShaderModule handle; + VkShaderStageFlags stage; +}; + +typedef struct Vk_Pipeline Vk_Pipeline; +struct Vk_Pipeline { + VkPipeline handle; + + struct { + VkPipelineLayout pipeline; + VkDescriptorSetLayout set; + } layout; + + struct { + VkFormat items[8]; + U32 count; + } targets; + + struct { + Vk_Shader items[8]; + U32 count; + } shaders; +}; + +typedef struct Vk_CommandBuffer Vk_CommandBuffer; +struct Vk_CommandBuffer { + VkCommandBuffer handle; + VkFence fence; +}; typedef struct Vk_Frame Vk_Frame; struct Vk_Frame { VkCommandPool pool; VkCommandBuffer cmd; + VkDescriptorPool descriptors; + VkSemaphore acquire, complete; VkFence fence; + U32 next_scratch; + Vk_CommandBuffer scratch[VK_NUM_SCRATCH]; + U32 image; // swapchain image index }; @@ -77,6 +141,8 @@ struct Vk_Context { U32 width; U32 height; } swapchain; + + VkSampler sampler; }; extern Vk_Context vk; @@ -86,4 +152,10 @@ function bool Vk_Setup(SDL_Window *window); function Vk_Frame *Vk_FrameBegin(SDL_Window *window); function void Vk_FrameEnd(); +function Vk_CommandBuffer *Vk_CommandBufferPush(); +function void Vk_CommandBufferSubmit(Vk_CommandBuffer *cmds, B32 wait); + +function void Vk_BufferCreate(Vk_Buffer *buffer); +function void Vk_ImageCreate(Vk_Image *image); + #endif // LD_VULKAN_CORE_H_ diff --git a/code/vulkan/functions.h b/code/vulkan/functions.h index 426bb55..afd5e41 100644 --- a/code/vulkan/functions.h +++ b/code/vulkan/functions.h @@ -6,6 +6,7 @@ VK_FUNC(GetDeviceProcAddr); VK_FUNC(GetPhysicalDeviceSurfaceCapabilitiesKHR); VK_FUNC(GetPhysicalDeviceSurfaceFormatsKHR); + VK_FUNC(GetPhysicalDeviceMemoryProperties2); #if defined(VK_USE_PLATFORM_WIN32_KHR) VK_FUNC(CreateWin32SurfaceKHR); @@ -39,7 +40,30 @@ VK_FUNC(BeginCommandBuffer); VK_FUNC(EndCommandBuffer); VK_FUNC(DeviceWaitIdle); + VK_FUNC(AllocateMemory); + VK_FUNC(CreateBuffer); + VK_FUNC(GetBufferMemoryRequirements); + VK_FUNC(BindBufferMemory); + VK_FUNC(CreateImage); + VK_FUNC(GetImageMemoryRequirements); + VK_FUNC(BindImageMemory); + VK_FUNC(MapMemory); + VK_FUNC(CreateGraphicsPipelines); + VK_FUNC(CreateShaderModule); + VK_FUNC(CreateDescriptorSetLayout); + VK_FUNC(CreatePipelineLayout); + VK_FUNC(CmdBindPipeline); + VK_FUNC(CreateDescriptorPool); + VK_FUNC(ResetDescriptorPool); + VK_FUNC(AllocateDescriptorSets); + VK_FUNC(CmdBindDescriptorSets); + VK_FUNC(UpdateDescriptorSets); + VK_FUNC(CreateSampler); + VK_FUNC(CmdDraw); + VK_FUNC(CmdSetViewport); + VK_FUNC(CmdSetScissor); + VK_FUNC(CmdCopyBufferToImage); VK_FUNC(CmdPipelineBarrier2); VK_FUNC(CmdBeginRendering); VK_FUNC(CmdEndRendering); diff --git a/code/vulkan/shaders/basic.frag b/code/vulkan/shaders/basic.frag new file mode 100644 index 0000000..8886c82 --- /dev/null +++ b/code/vulkan/shaders/basic.frag @@ -0,0 +1,12 @@ +#version 460 core + +layout(location = 0) in vec2 frag_uv; +layout(location = 1) in vec4 frag_c; + +layout(location = 0) out vec4 framebuffer; + +layout(binding = 1) uniform sampler2D u_image; + +void main() { + framebuffer = frag_c * texture(u_image, frag_uv); +} diff --git a/code/vulkan/shaders/basic.vert b/code/vulkan/shaders/basic.vert new file mode 100644 index 0000000..f0b8dfe --- /dev/null +++ b/code/vulkan/shaders/basic.vert @@ -0,0 +1,28 @@ +#version 460 core + +#extension GL_EXT_scalar_block_layout : enable + +struct Vertex { + vec4 p; + vec2 uv; + uint c; + uint pad; +}; + +layout(binding = 0, scalar) +readonly buffer Vertices { + Vertex vtx[]; +}; + +layout(location = 0) out vec2 frag_uv; +layout(location = 1) out vec4 frag_c; + +void main() { + Vertex v = vtx[gl_VertexIndex]; + + gl_Position = v.p; + + frag_uv = v.uv; + frag_c = vec4((v.c >> 24) & 0xFF, (v.c >> 16) & 0xFF, (v.c >> 8) & 0xFF, (v.c >> 0) & 0xFF) / 255.0f; + frag_c = frag_c.abgr; +} diff --git a/linux b/linux index 2930c89..e259fee 100755 --- a/linux +++ b/linux @@ -12,6 +12,7 @@ pushd "build" > /dev/null release=0 deps=0 +assets=0 for a in $* do @@ -23,6 +24,11 @@ then deps=1 fi +if [[ ! -d "assets" ]] +then + assets=1 +fi + if [[ $deps == 1 ]] then # We don't build SDL3 like on windows, this assumes you have it installed instead. We can't @@ -35,10 +41,24 @@ then cp ../thirdparty/stb/*.h deps/stb fi +if [[ $assets == 1 ]] +then + echo "[Copying assets]" + + cp -r "../assets" . +fi + +echo "[Building shaders]" + +[[ ! -d "assets/shaders" ]] && mkdir "assets/shaders" + +glslangValidator -o "assets/shaders/basic.vert.spv" --target-env "vulkan1.3" "../code/vulkan/shaders/basic.vert" +glslangValidator -o "assets/shaders/basic.frag.spv" --target-env "vulkan1.3" "../code/vulkan/shaders/basic.frag" + echo "[Building source]" -COMPILER_OPTS="-Wall -Wno-missing-braces -Wno-unused-function -I'deps/stb'" -LINKER_OPTS="-lSDL3" +COMPILER_OPTS="-Wall -Wno-missing-braces -Wno-unused-function -Ideps/stb -I../code" +LINKER_OPTS="-lSDL3 -lm" if [[ $release == 1 ]] then diff --git a/windows.bat b/windows.bat index 3539c84..d3daa61 100644 --- a/windows.bat +++ b/windows.bat @@ -9,6 +9,7 @@ PUSHD "build" SET deps=0 SET release=0 +SET assets=0 FOR %%A in (%*) DO ( SET %%A=1 @@ -51,10 +52,23 @@ IF %deps% equ 1 ( COPY "..\thirdparty\stb\*.h" "deps\stb" > NUL ) +IF %assets% equ 1 ( + ECHO [Copying assets] + + xcopy /Y /Q "..\assets" "assets" +) + +ECHO [Building shaders] + +IF NOT EXIST "assets\shaders" ( MKDIR "assets\shaders" ) + +glslangValidator -o "assets\shaders\basic.vert.spv" --target-env vulkan1.3 "..\code\vulkan\shaders\basic.vert" +glslangValidator -o "assets\shaders\basic.frag.spv" --target-env vulkan1.3 "..\code\vulkan\shaders\basic.frag" + ECHO [Building source] -SET COMPILER_OPTS=-nologo -W4 -I"deps\SDL3\include" -I"deps\stb" -I"%VULKAN_SDK%\Include" -SET LINKER_OPTS=-LIBPATH:"deps\SDL3\lib" SDL3.lib +SET COMPILER_OPTS=-nologo -W4 -I"deps\SDL3\include" -I"deps\stb" -I"%VULKAN_SDK%\Include" -I"..\code" +SET LINKER_OPTS=-LIBPATH:"deps\SDL3\lib" SDL3.lib Ole32.lib Shell32.lib IF %release% equ 1 ( ECHO [Release build]