# HG changeset patch # User sam # Date 1722246650 -25200 # Node ID 0369fa1ffbd9c539342405a9d4030f224e4a12fc # Parent 3308b88e53a68f2a1854faad9ccb6b43e60856f3 did: undo part of stupid API renaming a few weeks back ;( diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/core.nim --- a/semicongine/core.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/core.nim Mon Jul 29 16:50:50 2024 +0700 @@ -1,4 +1,4 @@ -const RESOURCEROOT = "resources" +const RESOURCEROOT {.hint[XDeclaredButNotUsed]: off.} = "resources" include ./core/utils include ./core/buildconfig diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/gltf.nim --- a/semicongine/gltf.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/gltf.nim Mon Jul 29 16:50:50 2024 +0700 @@ -154,7 +154,7 @@ let bufferView = root["bufferViews"][root["images"][imageIndex][ "bufferView"].getInt()] - result = LoadImageData[BGRA](getBufferViewData(bufferView, mainBuffer)) + result = loadImageData[BGRA](getBufferViewData(bufferView, mainBuffer)) if textureNode.hasKey("sampler"): let sampler = root["samplers"][textureNode["sampler"].getInt()] @@ -339,7 +339,7 @@ nodes.add nodeId.getInt() result.scenes.add nodes -proc LoadMeshes*[TMesh, TMaterial]( +proc loadMeshes*[TMesh, TMaterial]( path: string, meshAttributesMapping: static MeshAttributeNames, materialAttributesMapping: static MaterialAttributeNames, diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/image.nim --- a/semicongine/image.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/image.nim Mon Jul 29 16:50:50 2024 +0700 @@ -28,7 +28,7 @@ isRenderTarget*: bool = false samples*: VkSampleCountFlagBits = VK_SAMPLE_COUNT_1_BIT -proc LoadImageData*[T: PixelType](pngData: string|seq[uint8]): Image[T] = +proc loadImageData*[T: PixelType](pngData: string|seq[uint8]): Image[T] = when T is Gray: let nChannels = 1.cint elif T is BGRA: @@ -57,14 +57,14 @@ for i in 0 ..< result.data.len: swap(result.data[i][0], result.data[i][2]) -proc LoadImage*[T: PixelType](path: string, package = DEFAULT_PACKAGE): Image[T] = +proc loadImage*[T: PixelType](path: string, package = DEFAULT_PACKAGE): Image[T] = assert path.splitFile().ext.toLowerAscii == ".png", "Unsupported image type: " & path.splitFile().ext.toLowerAscii when T is Gray: let pngType = 0.cint elif T is BGRA: let pngType = 6.cint - result = LoadImageData[T](loadResource_intern(path, package = package).readAll()) + result = loadImageData[T](loadResource_intern(path, package = package).readAll()) # stb_image.h has no encoding support, maybe check stb_image_write or similar # diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/input.nim --- a/semicongine/input.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/input.nim Mon Jul 29 16:50:50 2024 +0700 @@ -17,7 +17,7 @@ # warning, shit is not thread safe var input = Input() -proc UpdateInputs*(): bool = +proc updateInputs*(): bool = # reset input states input.keyWasPressed = {} input.keyWasReleased = {} @@ -28,10 +28,10 @@ input.windowWasResized = false if input.lockMouse and input.hasFocus: - SetMousePosition(vulkan.window, x=int(vulkan.swapchain.width div 2), y=int(vulkan.swapchain.height div 2)) + setMousePosition(vulkan.window, x=int(vulkan.swapchain.width div 2), y=int(vulkan.swapchain.height div 2)) var killed = false - for event in vulkan.window.PendingEvents(): + for event in vulkan.window.pendingEvents(): case event.eventType: of Quit: killed = true @@ -66,27 +66,27 @@ return not killed -proc KeyIsDown*(key: Key): bool = key in input.keyIsDown -proc KeyWasPressed*(key: Key): bool = key in input.keyWasPressed -proc KeyWasPressed*(): bool = input.keyWasPressed.len > 0 -proc KeyWasReleased*(key: Key): bool = key in input.keyWasReleased -proc MouseIsDown*(button: MouseButton): bool = button in input.mouseIsDown -proc MouseWasPressed*(): bool = input.mouseWasPressed.len > 0 -proc MouseWasPressed*(button: MouseButton): bool = button in input.mouseWasPressed -proc MousePressedButtons*(): set[MouseButton] = input.mouseWasPressed -proc MouseWasReleased*(): bool = input.mouseWasReleased.len > 0 -proc MouseWasReleased*(button: MouseButton): bool = button in input.mouseWasReleased -proc MouseReleasedButtons*(): set[MouseButton] = input.mouseWasReleased -proc MousePosition*(): Vec2f = input.mousePosition -proc MousePositionNormalized*(size: (int, int)): Vec2f = +proc keyIsDown*(key: Key): bool = key in input.keyIsDown +proc keyWasPressed*(key: Key): bool = key in input.keyWasPressed +proc keyWasPressed*(): bool = input.keyWasPressed.len > 0 +proc keyWasReleased*(key: Key): bool = key in input.keyWasReleased +proc mouseIsDown*(button: MouseButton): bool = button in input.mouseIsDown +proc mouseWasPressed*(): bool = input.mouseWasPressed.len > 0 +proc mouseWasPressed*(button: MouseButton): bool = button in input.mouseWasPressed +proc mousePressedButtons*(): set[MouseButton] = input.mouseWasPressed +proc mouseWasReleased*(): bool = input.mouseWasReleased.len > 0 +proc mouseWasReleased*(button: MouseButton): bool = button in input.mouseWasReleased +proc mouseReleasedButtons*(): set[MouseButton] = input.mouseWasReleased +proc mousePosition*(): Vec2f = input.mousePosition +proc mousePositionNormalized*(size: (int, int)): Vec2f = result.x = (input.mousePosition.x / float32(size[0])) * 2.0 - 1.0 result.y = (input.mousePosition.y / float32(size[1])) * 2.0 - 1.0 -proc MouseMove*(): Vec2f = input.mouseMove -proc MouseWheel*(): float32 = input.mouseWheel -proc WindowWasResized*(): auto = input.windowWasResized -proc WindowIsMinimized*(): auto = input.windowIsMinimized -proc LockMouse*(value: bool) = input.lockMouse = value -proc HasFocus*(): bool = input.hasFocus +proc mouseMove*(): Vec2f = input.mouseMove +proc mouseWheel*(): float32 = input.mouseWheel +proc windowWasResized*(): auto = input.windowWasResized +proc windowIsMinimized*(): auto = input.windowIsMinimized +proc lockMouse*(value: bool) = input.lockMouse = value +proc hasFocus*(): bool = input.hasFocus # actions as a slight abstraction over raw input @@ -99,49 +99,49 @@ # warning, shit is not thread safe var actionMap: ActionMap -proc MapAction*[T: enum](action: T, key: Key) = +proc mapAction*[T: enum](action: T, key: Key) = if not actionMap.keyActions.contains($action): actionMap.keyActions[$action] = {} actionMap.keyActions[$action].incl key -proc MapAction*[T: enum](action: T, button: MouseButton) = +proc mapAction*[T: enum](action: T, button: MouseButton) = if not actionMap.mouseActions.contains($action): actionMap.mouseActions[$action] = {} actionMap.mouseActions[$action].incl button -proc MapAction*[T: enum](action: T, keys: openArray[Key|MouseButton]) = +proc mapAction*[T: enum](action: T, keys: openArray[Key|MouseButton]) = for key in keys: - MapAction(action, key) + mapAction(action, key) -proc UnmapAction*[T: enum](action: T, key: Key) = +proc unmapAction*[T: enum](action: T, key: Key) = if actionMap.keyActions.contains($action): actionMap.keyActions[$action].excl(key) -proc UnmapAction*[T: enum](action: T, button: MouseButton) = +proc unmapAction*[T: enum](action: T, button: MouseButton) = if actionMap.mouseActions.contains($action): actionMap.mouseActions[$action].excl(button) -proc UnmapAction*[T: enum](action: T) = +proc unmapAction*[T: enum](action: T) = if actionMap.keyActions.contains($action): actionMap.keyActions[$action] = {} if actionMap.mouseActions.contains($action): actionMap.mouseActions[$action] = {} -proc SaveCurrentActionMapping*() = +proc saveCurrentActionMapping*() = for name, keys in actionMap.keyActions.pairs: - SystemStorage.Store(name, keys, table = "input_mapping_key") + SystemStorage.store(name, keys, table = "input_mapping_key") for name, buttons in actionMap.mouseActions.pairs: - SystemStorage.Store(name, buttons, table = "input_mapping_mouse") + SystemStorage.store(name, buttons, table = "input_mapping_mouse") -proc LoadActionMapping*[T]() = +proc loadActionMapping*[T]() = reset(actionMap) for name in SystemStorage.List(table = "input_mapping_key"): let action = parseEnum[T](name) let keys = SystemStorage.Load(name, set[Key](), table = "input_mapping_key") for key in keys: - MapAction(action, key) + mapAction(action, key) -proc ActionDown*[T](action: T): bool = +proc actionDown*[T](action: T): bool = if actionMap.keyActions.contains($action): for key in actionMap.keyActions[$action]: if key in input.keyIsDown: @@ -153,7 +153,7 @@ return true return false -proc ActionPressed*[T](action: T): bool = +proc actionPressed*[T](action: T): bool = if actionMap.keyActions.contains($action): for key in actionMap.keyActions[$action]: if key in input.keyWasPressed: @@ -163,7 +163,7 @@ if button in input.mouseWasPressed: return true -proc ActionReleased*[T](action: T): bool = +proc actionReleased*[T](action: T): bool = if actionMap.keyActions.contains($action): for key in actionMap.keyActions[$action]: if key in input.keyWasReleased: @@ -173,7 +173,7 @@ if button in input.mouseWasReleased: return true -proc ActionValue*[T](action: T): float32 = +proc actionValue*[T](action: T): float32 = if actionMap.keyActions.contains($action): for key in actionMap.keyActions[$action]: if key in input.keyIsDown: diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering.nim --- a/semicongine/rendering.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering.nim Mon Jul 29 16:50:50 2024 +0700 @@ -44,7 +44,7 @@ graphicsQueueFamily*: uint32 graphicsQueue*: VkQueue debugMessenger: VkDebugUtilsMessengerEXT - # populated through the InitSwapchain proc + # populated through the initSwapchain proc swapchain*: Swapchain # unclear as of yet anisotropy*: float32 = 0 # needs to be enable during device creation @@ -53,10 +53,10 @@ samples*: VkSampleCountFlagBits depthBuffer*: bool Swapchain* = ref object - # parameters to InitSwapchain, required for swapchain recreation + # parameters to initSwapchain, required for swapchain recreation renderPass*: RenderPass vSync: bool - # populated through InitSwapchain proc + # populated through initSwapchain proc vk: VkSwapchainKHR width*: uint32 height*: uint32 @@ -82,7 +82,7 @@ oldSwapchainCounter: int # swaps until old swapchain will be destroyed var vulkan*: VulkanGlobals -var fullscreen: bool +var fullscreen_internal: bool type # type aliases @@ -137,40 +137,40 @@ imageViews: seq[VkImageView] samplers: seq[VkSampler] -template ForDescriptorFields(shader: typed, fieldname, valuename, typename, countname, bindingNumber, body: untyped): untyped = +template forDescriptorFields(shader: typed, fieldname, valuename, typename, countname, bindingNumber, body: untyped): untyped = var `bindingNumber` {.inject.} = 0'u32 for theFieldname, value in fieldPairs(shader): when typeof(value) is Image: block: - const `fieldname` {.inject.} = theFieldname + const `fieldname` {.inject, hint[XDeclaredButNotUsed]: off.} = theFieldname const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER const `countname` {.inject.} = 1'u32 - let `valuename` {.inject.} = value + let `valuename` {.inject, hint[XDeclaredButNotUsed]: off.} = value body `bindingNumber`.inc elif typeof(value) is GPUValue: block: - const `fieldname` {.inject.} = theFieldname + const `fieldname` {.inject, hint[XDeclaredButNotUsed]: off.} = theFieldname const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER const `countname` {.inject.} = 1'u32 - let `valuename` {.inject.} = value + let `valuename` {.inject, hint[XDeclaredButNotUsed]: off.} = value body `bindingNumber`.inc elif typeof(value) is array: when elementType(value) is Image: block: - const `fieldname` {.inject.} = theFieldname + const `fieldname` {.inject, hint[XDeclaredButNotUsed]: off.} = theFieldname const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER const `countname` {.inject.} = uint32(typeof(value).len) - let `valuename` {.inject.} = value + let `valuename` {.inject, hint[XDeclaredButNotUsed]: off.} = value body `bindingNumber`.inc elif elementType(value) is GPUValue: block: - const `fieldname` {.inject.} = theFieldname + const `fieldname` {.inject, hint[XDeclaredButNotUsed]: off.} = theFieldname const `typename` {.inject.} = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER const `countname` {.inject.} = len(value).uint32 - let `valuename` {.inject.} = value + let `valuename` {.inject hint[XDeclaredButNotUsed]: off.} = value body `bindingNumber`.inc else: @@ -206,7 +206,7 @@ raise newException(Exception, errorMsg) return false -proc InitVulkan*(appName: string = "semicongine app") = +proc initVulkan*(appName: string = "semicongine app") = # instance creation @@ -248,8 +248,8 @@ # for extension in requiredExtensions: loadExtension(vulkan.instance, $extension) - vulkan.window = CreateWindow(appName) - vulkan.surface = CreateNativeSurface(vulkan.instance, vulkan.window) + vulkan.window = createWindow(appName) + vulkan.surface = createNativeSurface(vulkan.instance, vulkan.window) # logical device creation @@ -278,8 +278,8 @@ ) # get physical device and graphics queue family - vulkan.physicalDevice = GetBestPhysicalDevice(vulkan.instance) - vulkan.graphicsQueueFamily = GetQueueFamily(vulkan.physicalDevice, VK_QUEUE_GRAPHICS_BIT) + vulkan.physicalDevice = getBestPhysicalDevice(vulkan.instance) + vulkan.graphicsQueueFamily = getQueueFamily(vulkan.physicalDevice, VK_QUEUE_GRAPHICS_BIT) let priority = cfloat(1) @@ -315,31 +315,31 @@ ) vulkan.graphicsQueue = svkGetDeviceQueue(vulkan.device, vulkan.graphicsQueueFamily, VK_QUEUE_GRAPHICS_BIT) -proc ClearSwapchain*() = +proc clearSwapchain*() = assert vulkan.swapchain != nil, "Swapchain has not been initialized yet" - DestroySwapchain(vulkan.swapchain) + destroySwapchain(vulkan.swapchain) vulkan.swapchain = nil -proc SetupSwapchain*(renderPass: RenderPass, vSync: bool = false) = +proc setupSwapchain*(renderPass: RenderPass, vSync: bool = false) = assert vulkan.swapchain == nil, "Swapchain has already been initialized yet" - vulkan.swapchain = InitSwapchain(renderPass, vSync = vSync) + vulkan.swapchain = initSwapchain(renderPass, vSync = vSync) -proc DestroyVulkan*() = +proc destroyVulkan*() = if vulkan.swapchain != nil: - DestroySwapchain(vulkan.swapchain) + destroySwapchain(vulkan.swapchain) vkDestroyDevice(vulkan.device, nil) vkDestroySurfaceKHR(vulkan.instance, vulkan.surface, nil) vkDestroyDebugUtilsMessengerEXT(vulkan.instance, vulkan.debugMessenger, nil) vkDestroyInstance(vulkan.instance, nil) -proc ShowSystemCursor*(value: bool) = vulkan.window.ShowSystemCursor(value) -proc Fullscreen*(): bool = fullscreen -proc SetFullscreen*(enable: bool) = - if enable != fullscreen: - fullscreen = enable - vulkan.window.SetFullscreen(fullscreen) +proc showSystemCursor*(value: bool) = vulkan.window.showSystemCursor(value) +proc fullscreen*(): bool = fullscreen_internal +proc setFullscreen*(enable: bool) = + if enable != fullscreen_internal: + fullscreen_internal = enable + vulkan.window.setFullscreen(fullscreen_internal) -proc GetAspectRatio*(): float32 = +proc getAspectRatio*(): float32 = assert vulkan.swapchain != nil, "Swapchain has not been initialized yet" vulkan.swapchain.width.float32 / vulkan.swapchain.height.float32 @@ -347,7 +347,7 @@ assert vulkan.swapchain != nil, "Swapchain has not been initialized yet" vulkan.swapchain.currentFiF -proc MaxFramebufferSampleCount*(maxSamples = VK_SAMPLE_COUNT_8_BIT): VkSampleCountFlagBits = +proc maxFramebufferSampleCount*(maxSamples = VK_SAMPLE_COUNT_8_BIT): VkSampleCountFlagBits = let limits = svkGetPhysicalDeviceProperties().limits let available = VkSampleCountFlags( limits.framebufferColorSampleCounts.uint32 and limits.framebufferDepthSampleCounts.uint32 diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/platform/linux.nim --- a/semicongine/rendering/platform/linux.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/platform/linux.nim Mon Jul 29 16:50:50 2024 +0700 @@ -51,7 +51,7 @@ proc XErrorLogger(display: PDisplay, event: PXErrorEvent): cint {.cdecl.} = logging.error &"Xlib: {event[]}" -proc CreateWindow*(title: string): NativeWindow = +proc createWindow*(title: string): NativeWindow = checkXlibResult XInitThreads() let display = XOpenDisplay(nil) if display == nil: @@ -94,10 +94,10 @@ checkXlibResult display.XFreePixmap(pixmap) return NativeWindow(display: display, window: window, emptyCursor: empty_cursor) -proc SetTitle*(window: NativeWindow, title: string) = +proc setTitle*(window: NativeWindow, title: string) = checkXlibResult XSetStandardProperties(window.display, window.window, title, "window", 0, nil, 0, nil) -proc SetFullscreen*(window: var NativeWindow, enable: bool) = +proc setFullscreen*(window: var NativeWindow, enable: bool) = var wm_state = window.display.XInternAtom("_NET_WM_STATE", 0) wm_fullscreen = window.display.XInternAtom("_NET_WM_STATE_FULLSCREEN", 0) @@ -127,7 +127,7 @@ ) checkXlibResult window.display.XFlush() -proc ShowSystemCursor*(window: NativeWindow, value: bool) = +proc showSystemCursor*(window: NativeWindow, value: bool) = if value == true: checkXlibResult XUndefineCursor(window.display, window.window) checkXlibResult window.display.XFlush() @@ -135,17 +135,17 @@ checkXlibResult XDefineCursor(window.display, window.window, window.emptyCursor) checkXlibResult window.display.XFlush() -proc Destroy*(window: NativeWindow) = +proc destroy*(window: NativeWindow) = checkXlibResult window.display.XFreeCursor(window.emptyCursor) checkXlibResult window.display.XDestroyWindow(window.window) discard window.display.XCloseDisplay() # always returns 0 -proc Size*(window: NativeWindow): (int, int) = +proc size*(window: NativeWindow): (int, int) = var attribs: XWindowAttributes checkXlibResult XGetWindowAttributes(window.display, window.window, addr(attribs)) return (int(attribs.width), int(attribs.height)) -proc PendingEvents*(window: NativeWindow): seq[Event] = +proc pendingEvents*(window: NativeWindow): seq[Event] = var event: XEvent while window.display.XPending() > 0: discard window.display.XNextEvent(addr(event)) @@ -185,7 +185,7 @@ discard -proc GetMousePosition*(window: NativeWindow): Option[Vec2f] = +proc getMousePosition*(window: NativeWindow): Option[Vec2f] = var root: x11.Window win: x11.Window @@ -208,7 +208,7 @@ if onscreen != 0: result = some(Vec2f([float32(winX), float32(winY)])) -proc SetMousePosition*(window: NativeWindow, x, y: int) = +proc setMousePosition*(window: NativeWindow, x, y: int) = checkXlibResult XWarpPointer( window.display, default(x11.Window), @@ -219,7 +219,7 @@ ) checkXlibResult XSync(window.display, false.XBool) -proc CreateNativeSurface(instance: VkInstance, window: NativeWindow): VkSurfaceKHR = +proc createNativeSurface(instance: VkInstance, window: NativeWindow): VkSurfaceKHR = var surfaceCreateInfo = VkXlibSurfaceCreateInfoKHR( sType: VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR, dpy: cast[ptr Display](window.display), diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/platform/windows.nim --- a/semicongine/rendering/platform/windows.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/platform/windows.nim Mon Jul 29 16:50:50 2024 +0700 @@ -40,7 +40,7 @@ # sorry, have to use module-global variable to capture windows events var currentEvents: seq[Event] -template CheckWin32Result*(call: untyped) = +template checkWin32Result*(call: untyped) = let value = call if value == 0: raise newException(Exception, "Win32 error: " & astToStr(call) & " returned " & $value) @@ -52,7 +52,7 @@ defaultCursor = LoadCursor(0, IDC_ARROW) var currentCursor = defaultCursor -proc MapLeftRightKeys(key: INT, lparam: LPARAM): INT = +proc mapLeftRightKeys(key: INT, lparam: LPARAM): INT = case key of VK_SHIFT: MapVirtualKey(UINT((lParam and 0x00ff0000) shr 16), MAPVK_VSC_TO_VK_EX) @@ -63,7 +63,7 @@ else: key -proc WindowHandler(hwnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM): LRESULT {.stdcall.} = +proc windowHandler(hwnd: HWND, uMsg: UINT, wParam: WPARAM, lParam: LPARAM): LRESULT {.stdcall.} = case uMsg of WM_DESTROY: currentEvents.add(Event(eventType: EventType.Quit)) @@ -110,7 +110,7 @@ return DefWindowProc(hwnd, uMsg, wParam, lParam) -proc CreateWindow*(title: string): NativeWindow = +proc createWindow*(title: string): NativeWindow = when DEBUG: AllocConsole() discard stdin.reopen("conIN$", fmRead) @@ -147,12 +147,12 @@ result.g_wpPrev.length = UINT(sizeof(WINDOWPLACEMENT)) discard result.hwnd.ShowWindow(SW_SHOW) -proc SetTitle*(window: NativeWindow, title: string) = +proc setTitle*(window: NativeWindow, title: string) = window.hwnd.SetWindowText(T(title)) # inspired by the one and only, Raymond Chen # https://devblogs.microsoft.com/oldnewthing/20100412-00/?p=14353 -proc SetFullscreen*(window: var NativeWindow, enable: bool) = +proc setFullscreen*(window: var NativeWindow, enable: bool) = let dwStyle: DWORD = GetWindowLong(window.hwnd, GWL_STYLE) if enable: var mi = MONITORINFO(cbSize: DWORD(sizeof(MONITORINFO))) @@ -164,7 +164,7 @@ SetWindowPlacement(window.hwnd, addr window.g_wpPrev) SetWindowPos(window.hwnd, HWND(0), 0, 0, 0, 0, SWP_NOMOVE or SWP_NOSIZE or SWP_NOZORDER or SWP_NOOWNERZORDER or SWP_FRAMECHANGED) -proc ShowSystemCursor*(window: NativeWindow, value: bool) = +proc showSystemCursor*(window: NativeWindow, value: bool) = if value == true: currentCursor = defaultCursor SetCursor(currentCursor) @@ -172,15 +172,15 @@ currentCursor = invisibleCursor SetCursor(currentCursor) -proc Destroy*(window: NativeWindow) = +proc destroy*(window: NativeWindow) = discard -proc Size*(window: NativeWindow): (int, int) = +proc size*(window: NativeWindow): (int, int) = var rect: RECT - CheckWin32Result GetWindowRect(window.hwnd, addr(rect)) + checkWin32Result GetWindowRect(window.hwnd, addr(rect)) (int(rect.right - rect.left), int(rect.bottom - rect.top)) -proc PendingEvents*(window: NativeWindow): seq[Event] = +proc pendingEvents*(window: NativeWindow): seq[Event] = # empty queue currentEvents = newSeq[Event]() var msg: MSG @@ -190,17 +190,17 @@ DispatchMessage(addr(msg)) return currentEvents -proc GetMousePosition*(window: NativeWindow): Option[Vec2f] = +proc getMousePosition*(window: NativeWindow): Option[Vec2f] = var p: POINT let res = GetCursorPos(addr(p)) if res: return some(Vec2f([float32(p.x), float32(p.y)])) return none(Vec2f) -proc SetMousePosition*(window: NativeWindow, x, y: int) = - CheckWin32Result SetCursorPos(x, y) +proc setMousePosition*(window: NativeWindow, x, y: int) = + checkWin32Result SetCursorPos(x, y) -proc CreateNativeSurface*(instance: VkInstance, window: NativeWindow): VkSurfaceKHR = +proc createNativeSurface*(instance: VkInstance, window: NativeWindow): VkSurfaceKHR = assert instance.Valid var surfaceCreateInfo = VkWin32SurfaceCreateInfoKHR( sType: VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/renderer.nim --- a/semicongine/rendering/renderer.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/renderer.nim Mon Jul 29 16:50:50 2024 +0700 @@ -10,7 +10,7 @@ of UniformBuffer: @[VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT] of UniformBufferMapped: @[VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT] -proc GetVkFormat(grayscale: bool, usage: openArray[VkImageUsageFlagBits]): VkFormat = +proc getVkFormat(grayscale: bool, usage: openArray[VkImageUsageFlagBits]): VkFormat = let formats = if grayscale: [VK_FORMAT_R8_SRGB, VK_FORMAT_R8_UNORM] else: [VK_FORMAT_B8G8R8A8_SRGB, VK_FORMAT_B8G8R8A8_UNORM] @@ -50,10 +50,10 @@ template bufferType(gpuData: GPUData): untyped = typeof(gpuData).TBuffer -func NeedsMapping(bType: BufferType): bool = +func needsMapping(bType: BufferType): bool = bType in [VertexBufferMapped, IndexBufferMapped, UniformBufferMapped] -template NeedsMapping(gpuData: GPUData): untyped = - gpuData.bufferType.NeedsMapping +template needsMapping(gpuData: GPUData): untyped = + gpuData.bufferType.needsMapping template size(gpuArray: GPUArray): uint64 = (gpuArray.data.len * sizeof(elementType(gpuArray.data))).uint64 @@ -67,13 +67,13 @@ template rawPointer(gpuValue: GPUValue): pointer = addr(gpuValue.data) -proc IsMappable(memoryTypeIndex: uint32): bool = +proc isMappable(memoryTypeIndex: uint32): bool = var physicalProperties: VkPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties(vulkan.physicalDevice, addr(physicalProperties)) let flags = toEnums(physicalProperties.memoryTypes[memoryTypeIndex].propertyFlags) return VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT in flags -proc InitDescriptorSet*( +proc initDescriptorSet*( renderData: RenderData, layout: VkDescriptorSetLayout, descriptorSet: var DescriptorSet, @@ -117,7 +117,7 @@ var imageWrites = newSeqOfCap[VkDescriptorImageInfo](1024) var bufferWrites = newSeqOfCap[VkDescriptorBufferInfo](1024) - ForDescriptorFields(descriptorSet.data, fieldName, fieldValue, descriptorType, descriptorCount, descriptorBindingNumber): + forDescriptorFields(descriptorSet.data, fieldName, fieldValue, descriptorType, descriptorCount, descriptorBindingNumber): for i in 0 ..< descriptorSet.vk.len: when typeof(fieldValue) is GPUValue: bufferWrites.add VkDescriptorBufferInfo( @@ -199,14 +199,14 @@ pDescriptorCopies = nil, ) -proc AllocateNewMemoryBlock(size: uint64, mType: uint32): MemoryBlock = +proc allocateNewMemoryBlock(size: uint64, mType: uint32): MemoryBlock = result = MemoryBlock( vk: svkAllocateMemory(size, mType), size: size, rawPointer: nil, offsetNextFree: 0, ) - if mType.IsMappable(): + if mType.isMappable(): checkVkResult vkMapMemory( device = vulkan.device, memory = result.vk, @@ -216,7 +216,7 @@ ppData = addr(result.rawPointer) ) -proc FlushBuffer*(buffer: Buffer) = +proc flushBuffer*(buffer: Buffer) = var flushRegion = VkMappedMemoryRange( sType: VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, memory: buffer.memory, @@ -225,7 +225,7 @@ ) checkVkResult vkFlushMappedMemoryRanges(vulkan.device, 1, addr(flushRegion)) -proc FlushAllMemory*(renderData: RenderData) = +proc flushAllMemory*(renderData: RenderData) = var flushRegions = newSeq[VkMappedMemoryRange]() for memoryBlocks in renderData.memory: for memoryBlock in memoryBlocks: @@ -238,7 +238,7 @@ if flushRegions.len > 0: checkVkResult vkFlushMappedMemoryRanges(vulkan.device, flushRegions.len.uint32, flushRegions.ToCPointer()) -proc AllocateNewBuffer(renderData: var RenderData, size: uint64, bufferType: BufferType): Buffer = +proc allocateNewBuffer(renderData: var RenderData, size: uint64, bufferType: BufferType): Buffer = result = Buffer( vk: svkCreateBuffer(size, bufferType.usage), size: size, @@ -246,7 +246,7 @@ offsetNextFree: 0, ) let memoryRequirements = svkGetBufferMemoryRequirements(result.vk) - let memoryType = BestMemory(mappable = bufferType.NeedsMapping, filter = memoryRequirements.memoryTypes) + let memoryType = bestMemory(mappable = bufferType.needsMapping, filter = memoryRequirements.memoryTypes) # check if there is an existing allocated memory block that is large enough to be used var selectedBlockI = -1 @@ -258,7 +258,7 @@ # otherwise, allocate a new block of memory and use that if selectedBlockI < 0: selectedBlockI = renderData.memory[memoryType].len - renderData.memory[memoryType].add AllocateNewMemoryBlock( + renderData.memory[memoryType].add allocateNewMemoryBlock( size = max(memoryRequirements.size, MEMORY_BLOCK_ALLOCATION_SIZE), mType = memoryType ) @@ -279,28 +279,28 @@ result.rawPointer = selectedBlock.rawPointer.pointerAddOffset(selectedBlock.offsetNextFree) renderData.memory[memoryType][selectedBlockI].offsetNextFree += memoryRequirements.size -proc UpdateGPUBuffer*(gpuData: GPUData, flush = false, allFrames = false) = +proc updateGPUBuffer*(gpuData: GPUData, flush = false, allFrames = false) = if gpuData.size == 0: return - when NeedsMapping(gpuData): + when needsMapping(gpuData): copyMem(pointerAddOffset(gpuData.buffer.rawPointer, gpuData.offset), gpuData.rawPointer, gpuData.size) if flush: - FlushBuffer(gpuData.buffer) + flushBuffer(gpuData.buffer) else: - WithStagingBuffer((gpuData.buffer.vk, gpuData.offset), gpuData.size, stagingPtr): + withStagingBuffer((gpuData.buffer.vk, gpuData.offset), gpuData.size, stagingPtr): copyMem(stagingPtr, gpuData.rawPointer, gpuData.size) -proc UpdateAllGPUBuffers*[T](value: T, flush = false, allFrames = false) = +proc updateAllGPUBuffers*[T](value: T, flush = false, allFrames = false) = for name, fieldvalue in value.fieldPairs(): when typeof(fieldvalue) is GPUData: - UpdateGPUBuffer(fieldvalue, flush = flush, allFrames = allFrames) + updateGPUBuffer(fieldvalue, flush = flush, allFrames = allFrames) when typeof(fieldvalue) is array: when elementType(fieldvalue) is GPUData: for entry in fieldvalue: - UpdateGPUBuffer(entry, flush = flush, allFrames = allFrames) + updateGPUBuffer(entry, flush = flush, allFrames = allFrames) -proc AllocateGPUData( +proc allocateGPUData( renderdata: var RenderData, bufferType: BufferType, size: uint64, @@ -317,7 +317,7 @@ # otherwise create new buffer if selectedBufferI < 0: selectedBufferI = renderdata.buffers[bufferType].len - renderdata.buffers[bufferType].add renderdata.AllocateNewBuffer( + renderdata.buffers[bufferType].add renderdata.allocateNewBuffer( size = max(size, BUFFER_ALLOCATION_SIZE), bufferType = bufferType, ) @@ -333,27 +333,27 @@ result[1] = renderdata.buffers[bufferType][selectedBufferI].offsetNextFree renderdata.buffers[bufferType][selectedBufferI].offsetNextFree += size -proc AssignBuffers*[T](renderdata: var RenderData, data: var T, uploadData = true) = +proc assignBuffers*[T](renderdata: var RenderData, data: var T, uploadData = true) = for name, value in fieldPairs(data): when typeof(value) is GPUData: - (value.buffer, value.offset) = AllocateGPUData(renderdata, value.bufferType, value.size) + (value.buffer, value.offset) = allocateGPUData(renderdata, value.bufferType, value.size) elif typeof(value) is DescriptorSet: - AssignBuffers(renderdata, value.data, uploadData = uploadData) + assignBuffers(renderdata, value.data, uploadData = uploadData) elif typeof(value) is array: when elementType(value) is GPUValue: for v in value.mitems: - (v.buffer, v.offset) = AllocateGPUData(renderdata, v.bufferType, v.size) + (v.buffer, v.offset) = allocateGPUData(renderdata, v.bufferType, v.size) if uploadData: - UpdateAllGPUBuffers(data, flush = true, allFrames = true) + updateAllGPUBuffers(data, flush = true, allFrames = true) -proc AssignBuffers*(renderdata: var RenderData, descriptorSet: var DescriptorSet, uploadData = true) = - AssignBuffers(renderdata, descriptorSet.data, uploadData = uploadData) +proc assignBuffers*(renderdata: var RenderData, descriptorSet: var DescriptorSet, uploadData = true) = + assignBuffers(renderdata, descriptorSet.data, uploadData = uploadData) -proc InitRenderData*(descriptorPoolLimit = 1024'u32): RenderData = +proc initRenderData*(descriptorPoolLimit = 1024'u32): RenderData = # allocate descriptor pools var poolSizes = [ VkDescriptorPoolSize(thetype: VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, descriptorCount: descriptorPoolLimit), @@ -367,7 +367,7 @@ ) checkVkResult vkCreateDescriptorPool(vulkan.device, addr(poolInfo), nil, addr(result.descriptorPool)) -proc DestroyRenderData*(renderData: RenderData) = +proc destroyRenderData*(renderData: RenderData) = vkDestroyDescriptorPool(vulkan.device, renderData.descriptorPool, nil) for buffers in renderData.buffers: @@ -387,7 +387,7 @@ for memory in memoryBlocks: vkFreeMemory(vulkan.device, memory.vk, nil) -proc TransitionImageLayout(image: VkImage, oldLayout, newLayout: VkImageLayout) = +proc transitionImageLayout(image: VkImage, oldLayout, newLayout: VkImageLayout) = var barrier = VkImageMemoryBarrier( sType: VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, @@ -420,7 +420,7 @@ else: raise newException(Exception, "Unsupported layout transition!") - WithSingleUseCommandBuffer(commandBuffer): + withSingleUseCommandBuffer(commandBuffer): vkCmdPipelineBarrier( commandBuffer, srcStageMask = [srcStage].toBits, @@ -466,7 +466,7 @@ var usage = @[VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_USAGE_SAMPLED_BIT] if image.isRenderTarget: usage.add VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT - let format = GetVkFormat(grayscale = elementType(image.data) is Gray, usage = usage) + let format = getVkFormat(grayscale = elementType(image.data) is Gray, usage = usage) image.vk = svkCreate2DImage(image.width, image.height, format, usage, image.samples) renderData.images.add image.vk @@ -479,7 +479,7 @@ renderData.samplers.add image.sampler let memoryRequirements = image.vk.svkGetImageMemoryRequirements() - let memoryType = BestMemory(mappable = false, filter = memoryRequirements.memoryTypes) + let memoryType = bestMemory(mappable = false, filter = memoryRequirements.memoryTypes) # check if there is an existing allocated memory block that is large enough to be used var selectedBlockI = -1 for i in 0 ..< renderData.memory[memoryType].len: @@ -490,7 +490,7 @@ # otherwise, allocate a new block of memory and use that if selectedBlockI < 0: selectedBlockI = renderData.memory[memoryType].len - renderData.memory[memoryType].add AllocateNewMemoryBlock( + renderData.memory[memoryType].add allocateNewMemoryBlock( size = max(memoryRequirements.size, MEMORY_BLOCK_ALLOCATION_SIZE), mType = memoryType ) @@ -513,18 +513,18 @@ renderData.imageViews.add image.imageview # data transfer and layout transition - TransitionImageLayout(image.vk, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) + transitionImageLayout(image.vk, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) if image.data.len > 0: - WithStagingBuffer( + withStagingBuffer( (image.vk, image.width, image.height), memoryRequirements.size, stagingPtr ): copyMem(stagingPtr, image.data.ToCPointer, image.size) - TransitionImageLayout(image.vk, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) + transitionImageLayout(image.vk, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) -proc UploadImages*(renderdata: var RenderData, descriptorSet: var DescriptorSet) = +proc uploadImages*(renderdata: var RenderData, descriptorSet: var DescriptorSet) = for name, value in fieldPairs(descriptorSet.data): when typeof(value) is Image: renderdata.createVulkanImage(value) @@ -548,58 +548,58 @@ var hasBoundDescriptorSets {.compileTime.} = false # okay, I am not sure if this is clean, unproblematic or sane. Just trying to get some comptime-validation var hasDescriptorSets {.compileTime} = false -template WithBind*[A, B, C, D, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], DescriptorSet[B], DescriptorSet[C], DescriptorSet[D]), pipeline: Pipeline[TShader], body: untyped): untyped = +template withBind*[A, B, C, D, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], DescriptorSet[B], DescriptorSet[C], DescriptorSet[D]), pipeline: Pipeline[TShader], body: untyped): untyped = static: assertAllDescriptorsBound(A, B, C, D, TShader) block: var descriptorSets: seq[VkDescriptorSet] for dSet in sets.fields: - assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call InitDescriptorSet" + assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call initDescriptorSet" descriptorSets.add dSet.vk[currentFiF()] svkCmdBindDescriptorSets(commandBuffer, descriptorSets, pipeline.layout) static: - assert not hasBoundDescriptorSets, "Cannot call WithBind nested" + assert not hasBoundDescriptorSets, "Cannot call withBind nested" hasBoundDescriptorSets = true body static: hasBoundDescriptorSets = false -template WithBind*[A, B, C, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], DescriptorSet[B], DescriptorSet[C]), pipeline: Pipeline[TShader], body: untyped): untyped = +template withBind*[A, B, C, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], DescriptorSet[B], DescriptorSet[C]), pipeline: Pipeline[TShader], body: untyped): untyped = static: assertAllDescriptorsBound(A, B, C, EMPTY, TShader) block: var descriptorSets: seq[VkDescriptorSet] for dSet in sets.fields: - assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call InitDescriptorSet" + assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call initDescriptorSet" descriptorSets.add dSet.vk[currentFiF()] svkCmdBindDescriptorSets(commandBuffer, descriptorSets, pipeline.layout) static: - assert not hasBoundDescriptorSets, "Cannot call WithBind nested" + assert not hasBoundDescriptorSets, "Cannot call withBind nested" hasBoundDescriptorSets = true body static: hasBoundDescriptorSets = false -template WithBind*[A, B, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], DescriptorSet[B]), pipeline: Pipeline[TShader], body: untyped): untyped = +template withBind*[A, B, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], DescriptorSet[B]), pipeline: Pipeline[TShader], body: untyped): untyped = static: assertAllDescriptorsBound(A, B, EMPTY, EMPTY, TShader) block: var descriptorSets: seq[VkDescriptorSet] for dSet in sets.fields: - assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call InitDescriptorSet" + assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call initDescriptorSet" descriptorSets.add dSet.vk[currentFiF()] svkCmdBindDescriptorSets(commandBuffer, descriptorSets, pipeline.layout) static: - assert not hasBoundDescriptorSets, "Cannot call WithBind nested" + assert not hasBoundDescriptorSets, "Cannot call withBind nested" hasBoundDescriptorSets = true body static: hasBoundDescriptorSets = false -template WithBind*[A, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], ), pipeline: Pipeline[TShader], body: untyped): untyped = +template withBind*[A, TShader](commandBuffer: VkCommandBuffer, sets: (DescriptorSet[A], ), pipeline: Pipeline[TShader], body: untyped): untyped = static: assertAllDescriptorsBound(A, EMPTY, EMPTY, EMPTY, TShader) block: var descriptorSets: seq[VkDescriptorSet] for dSet in sets.fields: - assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call InitDescriptorSet" + assert dSet.vk[currentFiF()].Valid, "DescriptorSet not initialized, maybe forgot to call initDescriptorSet" descriptorSets.add dSet.vk[currentFiF()] svkCmdBindDescriptorSets(commandBuffer, descriptorSets, pipeline.layout) static: - assert not hasBoundDescriptorSets, "Cannot call WithBind nested" + assert not hasBoundDescriptorSets, "Cannot call withBind nested" hasBoundDescriptorSets = true body static: @@ -625,7 +625,7 @@ foundAttr = true assert foundAttr, "Attribute '" & attrName & "' is not provided in instance type '" & name(TInstance) & "'" -proc Render*[TShader, TMesh, TInstance]( +proc render*[TShader, TMesh, TInstance]( commandBuffer: VkCommandBuffer, pipeline: Pipeline[TShader], mesh: TMesh, @@ -716,12 +716,12 @@ firstInstance = 0 ) -proc Render*[TShader, TMesh]( +proc render*[TShader, TMesh]( commandBuffer: VkCommandBuffer, pipeline: Pipeline[TShader], mesh: TMesh, ) = - Render(commandBuffer, pipeline, mesh, EMPTY()) + render(commandBuffer, pipeline, mesh, EMPTY()) proc assertValidPushConstantType(TShader, TPushConstant: typedesc) = assert sizeof(TPushConstant) <= PUSH_CONSTANT_SIZE, "Push constant values must be <= 128 bytes" @@ -733,7 +733,7 @@ foundPushConstant = true assert foundPushConstant == true, "No push constant found in shader" -proc RenderWithPushConstant*[TShader, TMesh, TInstance, TPushConstant]( +proc renderWithPushConstant*[TShader, TMesh, TInstance, TPushConstant]( commandBuffer: VkCommandBuffer, pipeline: Pipeline[TShader], mesh: TMesh, @@ -749,8 +749,8 @@ size = PUSH_CONSTANT_SIZE, pValues = addr(pushConstant) ); - Render(commandBuffer, pipeline, mesh, instances) -proc RenderWithPushConstant*[TShader, TMesh, TPushConstant]( + render(commandBuffer, pipeline, mesh, instances) +proc renderWithPushConstant*[TShader, TMesh, TPushConstant]( commandBuffer: VkCommandBuffer, pipeline: Pipeline[TShader], mesh: TMesh, @@ -765,7 +765,7 @@ size = PUSH_CONSTANT_SIZE, pValues = addr(pushConstant) ); - Render(commandBuffer, pipeline, mesh, EMPTY()) + render(commandBuffer, pipeline, mesh, EMPTY()) proc asGPUArray*[T](data: openArray[T], bufferType: static BufferType): auto = GPUArray[T, bufferType](data: @data) diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/renderpasses.nim --- a/semicongine/rendering/renderpasses.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/renderpasses.nim Mon Jul 29 16:50:50 2024 +0700 @@ -1,4 +1,4 @@ -proc CreateDirectPresentationRenderPass*(depthBuffer: bool, samples = VK_SAMPLE_COUNT_1_BIT): RenderPass = +proc createDirectPresentationRenderPass*(depthBuffer: bool, samples = VK_SAMPLE_COUNT_1_BIT): RenderPass = assert vulkan.instance.Valid, "Vulkan not initialized" result = RenderPass(depthBuffer: depthBuffer, samples: samples) @@ -66,7 +66,7 @@ dependencies = dependencies, ) -proc CreateIndirectPresentationRenderPass*(depthBuffer: bool, samples = VK_SAMPLE_COUNT_1_BIT): (RenderPass, RenderPass) = +proc createIndirectPresentationRenderPass*(depthBuffer: bool, samples = VK_SAMPLE_COUNT_1_BIT): (RenderPass, RenderPass) = assert vulkan.instance.Valid, "Vulkan not initialized" result[0] = RenderPass(depthBuffer: depthBuffer, samples: samples) @@ -188,7 +188,7 @@ dependencies = presentDependencies ) -template WithRenderPass*( +template withRenderPass*( theRenderPass: RenderPass, theFramebuffer: VkFramebuffer, commandbuffer: VkCommandBuffer, diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/shaders.nim --- a/semicongine/rendering/shaders.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/shaders.nim Mon Jul 29 16:50:50 2024 +0700 @@ -1,4 +1,4 @@ -func GlslType[T: SupportedGPUType|Image](value: T): string = +func glslType[T: SupportedGPUType|Image](value: T): string = when T is float32: "float" elif T is float64: "double" elif T is int8 or T is int16 or T is int32 or T is int64: "int" @@ -40,7 +40,7 @@ const n = typetraits.name(T) {.error: "Unsupported data type on GPU: " & n.} -func VkType[T: SupportedGPUType](value: T): VkFormat = +func vkType[T: SupportedGPUType](value: T): VkFormat = when T is float32: VK_FORMAT_R32_SFLOAT elif T is float64: VK_FORMAT_R64_SFLOAT elif T is int8: VK_FORMAT_R8_SINT @@ -86,7 +86,7 @@ else: {.error: "Unsupported data type on GPU".} -func NumberOfVertexInputAttributeDescriptors[T: SupportedGPUType|Image](value: T): uint32 = +func numberOfVertexInputAttributeDescriptors[T: SupportedGPUType|Image](value: T): uint32 = when T is TMat2[float32] or T is TMat2[float64] or T is TMat23[float32] or T is TMat23[float64]: 2 elif T is TMat32[float32] or T is TMat32[float64] or T is TMat3[float32] or T is TMat3[float64] or T is TMat34[float32] or T is TMat34[float64]: @@ -96,7 +96,7 @@ else: 1 -func NLocationSlots[T: SupportedGPUType|Image](value: T): uint32 = +func nLocationSlots[T: SupportedGPUType|Image](value: T): uint32 = #[ single location: - any scalar @@ -142,20 +142,20 @@ # vertex shader inputs when hasCustomPragma(value, VertexAttribute) or hasCustomPragma(value, InstanceAttribute): assert typeof(value) is SupportedGPUType - vsInput.add "layout(location = " & $vsInputLocation & ") in " & GlslType(value) & " " & fieldname & ";" - for j in 0 ..< NumberOfVertexInputAttributeDescriptors(value): - vsInputLocation += NLocationSlots(value) + vsInput.add "layout(location = " & $vsInputLocation & ") in " & glslType(value) & " " & fieldname & ";" + for j in 0 ..< numberOfVertexInputAttributeDescriptors(value): + vsInputLocation += nLocationSlots(value) # intermediate values, passed between shaders elif hasCustomPragma(value, Pass) or hasCustomPragma(value, PassFlat): let flat = if hasCustomPragma(value, PassFlat): "flat " else: "" - vsOutput.add "layout(location = " & $passLocation & ") " & flat & "out " & GlslType(value) & " " & fieldname & ";" - fsInput.add "layout(location = " & $passLocation & ") " & flat & "in " & GlslType(value) & " " & fieldname & ";" + vsOutput.add "layout(location = " & $passLocation & ") " & flat & "out " & glslType(value) & " " & fieldname & ";" + fsInput.add "layout(location = " & $passLocation & ") " & flat & "in " & glslType(value) & " " & fieldname & ";" passLocation.inc # fragment shader output elif hasCustomPragma(value, ShaderOutput): - fsOutput.add &"layout(location = " & $fsOutputLocation & ") out " & GlslType(value) & " " & fieldname & ";" + fsOutput.add &"layout(location = " & $fsOutputLocation & ") out " & glslType(value) & " " & fieldname & ";" fsOutputLocation.inc # descriptor sets @@ -173,7 +173,7 @@ for descriptorName, descriptorValue in fieldPairs(descriptor): when typeof(descriptorValue) is Image: - samplers.add "layout(set=" & $descriptorSetIndex & ", binding = " & $descriptorBinding & ") uniform " & GlslType(descriptorValue) & " " & descriptorName & ";" + samplers.add "layout(set=" & $descriptorSetIndex & ", binding = " & $descriptorBinding & ") uniform " & glslType(descriptorValue) & " " & descriptorName & ";" descriptorBinding.inc elif typeof(descriptorValue) is GPUValue: @@ -183,7 +183,7 @@ for blockFieldName, blockFieldValue in descriptorValue.data.fieldPairs(): assert typeof(blockFieldValue) is SupportedGPUType, "uniform block field '" & blockFieldName & "' is not a SupportedGPUType" - uniforms.add " " & GlslType(blockFieldValue) & " " & blockFieldName & ";" + uniforms.add " " & glslType(blockFieldValue) & " " & blockFieldName & ";" uniforms.add "} " & descriptorName & ";" else: @@ -195,7 +195,7 @@ when elementType(descriptorValue) is Image: let arrayDecl = "[" & $typeof(descriptorValue).len & "]" - samplers.add "layout(set=" & $descriptorSetIndex & ", binding = " & $descriptorBinding & ") uniform " & GlslType(default(elementType(descriptorValue))) & " " & descriptorName & "" & arrayDecl & ";" + samplers.add "layout(set=" & $descriptorSetIndex & ", binding = " & $descriptorBinding & ") uniform " & glslType(default(elementType(descriptorValue))) & " " & descriptorName & "" & arrayDecl & ";" descriptorBinding.inc elif elementType(descriptorValue) is GPUValue: @@ -204,7 +204,7 @@ for blockFieldName, blockFieldValue in default(elementType(descriptorValue)).data.fieldPairs(): assert typeof(blockFieldValue) is SupportedGPUType, "uniform block field '" & blockFieldName & "' is not a SupportedGPUType" - uniforms.add " " & GlslType(blockFieldValue) & " " & blockFieldName & ";" + uniforms.add " " & glslType(blockFieldValue) & " " & blockFieldName & ";" uniforms.add "} " & descriptorName & "[" & $descriptorValue.len & "];" descriptorBinding.inc @@ -221,7 +221,7 @@ pushConstants.add "{" for constFieldName, constFieldValue in value.fieldPairs(): assert typeof(constFieldValue) is SupportedGPUType, "push constant field '" & constFieldName & "' is not a SupportedGPUType" - pushConstants.add " " & GlslType(constFieldValue) & " " & constFieldName & ";" + pushConstants.add " " & glslType(constFieldValue) & " " & constFieldName & ";" pushConstants.add "} " & fieldname & ";" else: {.error: "Unsupported shader field '" & typetraits.name(TShader) & "." & fieldname & "' of type " & typetraits.name(typeof(value)).} @@ -293,7 +293,7 @@ i += 4 -proc CompileShader[TShader](shader: static TShader): (VkShaderModule, VkShaderModule) = +proc compileShader[TShader](shader: static TShader): (VkShaderModule, VkShaderModule) = const (vertexShaderSource, fragmentShaderSource) = generateShaderSource(shader) let vertexBinary = compileGlslToSPIRV(VK_SHADER_STAGE_VERTEX_BIT, vertexShaderSource) @@ -325,18 +325,18 @@ const `isinstancename` {.inject.} = hasCustomPragma(value, InstanceAttribute) body -proc GetDescriptorSetCount[TShader](): uint32 = +proc getDescriptorSetCount[TShader](): uint32 = for _, value in fieldPairs(default(TShader)): when hasCustomPragma(value, DescriptorSets): return tupleLen(typeof(value)).uint32 -proc CreateDescriptorSetLayouts[TShader](): array[MAX_DESCRIPTORSETS, VkDescriptorSetLayout] = +proc createDescriptorSetLayouts[TShader](): array[MAX_DESCRIPTORSETS, VkDescriptorSetLayout] = var setNumber: int for _, value in fieldPairs(default(TShader)): when hasCustomPragma(value, DescriptorSets): for descriptorSet in value.fields: var layoutbindings: seq[VkDescriptorSetLayoutBinding] - ForDescriptorFields(descriptorSet, fieldName, fieldValue, descriptorType, descriptorCount, descriptorBindingNumber): + forDescriptorFields(descriptorSet, fieldName, fieldValue, descriptorType, descriptorCount, descriptorBindingNumber): layoutbindings.add VkDescriptorSetLayoutBinding( binding: descriptorBindingNumber, descriptorType: descriptorType, @@ -357,7 +357,7 @@ ) inc setNumber -proc CreatePipeline*[TShader]( +proc createPipeline*[TShader]( renderPass: RenderPass, topology: VkPrimitiveTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, polygonMode: VkPolygonMode = VK_POLYGON_MODE_FILL, @@ -369,10 +369,10 @@ # create pipeline const shader = default(TShader) - (result.vertexShaderModule, result.fragmentShaderModule) = CompileShader(shader) + (result.vertexShaderModule, result.fragmentShaderModule) = compileShader(shader) - var nSets = GetDescriptorSetCount[TShader]() - result.descriptorSetLayouts = CreateDescriptorSetLayouts[TShader]() + var nSets = getDescriptorSetCount[TShader]() + result.descriptorSetLayouts = createDescriptorSetLayouts[TShader]() let pushConstant = VkPushConstantRange( stageFlags: VkShaderStageFlags(VK_SHADER_STAGE_ALL_GRAPHICS), @@ -415,15 +415,15 @@ inputRate: if isInstanceAttr: VK_VERTEX_INPUT_RATE_INSTANCE else: VK_VERTEX_INPUT_RATE_VERTEX, ) # allows to submit larger data structures like Mat44, for most other types will be 1 - let perDescriptorSize = sizeof(value).uint32 div NumberOfVertexInputAttributeDescriptors(value) - for i in 0'u32 ..< NumberOfVertexInputAttributeDescriptors(value): + let perDescriptorSize = sizeof(value).uint32 div numberOfVertexInputAttributeDescriptors(value) + for i in 0'u32 ..< numberOfVertexInputAttributeDescriptors(value): attributes.add VkVertexInputAttributeDescription( binding: inputBindingNumber, location: location, - format: VkType(value), + format: vkType(value), offset: i * perDescriptorSize, ) - location += NLocationSlots(value) + location += nLocationSlots(value) inc inputBindingNumber let @@ -528,12 +528,12 @@ addr(result.vk) ) -template WithPipeline*(commandbuffer: VkCommandBuffer, pipeline: Pipeline, body: untyped): untyped = +template withPipeline*(commandbuffer: VkCommandBuffer, pipeline: Pipeline, body: untyped): untyped = block: vkCmdBindPipeline(commandbuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline.vk) body -proc DestroyPipeline*(pipeline: Pipeline) = +proc destroyPipeline*(pipeline: Pipeline) = for descriptorSetLayout in pipeline.descriptorSetLayouts: vkDestroyDescriptorSetLayout(vulkan.device, descriptorSetLayout, nil) diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/swapchain.nim --- a/semicongine/rendering/swapchain.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/swapchain.nim Mon Jul 29 16:50:50 2024 +0700 @@ -1,6 +1,6 @@ const N_FRAMEBUFFERS = 3'u32 -proc InitSwapchain( +proc initSwapchain( renderPass: RenderPass, vSync: bool = false, oldSwapchain: Swapchain = nil, @@ -66,7 +66,7 @@ let requirements = svkGetImageMemoryRequirements(swapchain.depthImage) swapchain.depthMemory = svkAllocateMemory( requirements.size, - BestMemory(mappable = false, filter = requirements.memoryTypes) + bestMemory(mappable = false, filter = requirements.memoryTypes) ) checkVkResult vkBindImageMemory( vulkan.device, @@ -92,7 +92,7 @@ let requirements = svkGetImageMemoryRequirements(swapchain.msaaImage) swapchain.msaaMemory = svkAllocateMemory( requirements.size, - BestMemory(mappable = false, filter = requirements.memoryTypes) + bestMemory(mappable = false, filter = requirements.memoryTypes) ) checkVkResult vkBindImageMemory( vulkan.device, @@ -152,9 +152,9 @@ return swapchain -proc DestroySwapchain*(swapchain: Swapchain) = +proc destroySwapchain*(swapchain: Swapchain) = if swapchain.oldSwapchain != nil: - DestroySwapchain(swapchain.oldSwapchain) + destroySwapchain(swapchain.oldSwapchain) if swapchain.msaaImage.Valid: vkDestroyImageView(vulkan.device, swapchain.msaaImageView, nil) @@ -185,8 +185,8 @@ vkDestroySwapchainKHR(vulkan.device, swapchain.vk, nil) -proc TryAcquireNextImage(swapchain: Swapchain): Option[VkFramebuffer] = - if not swapchain.queueFinishedFence[swapchain.currentFiF].Await(100_000_000): +proc tryAcquireNextImage(swapchain: Swapchain): Option[VkFramebuffer] = + if not swapchain.queueFinishedFence[swapchain.currentFiF].await(100_000_000): return none(VkFramebuffer) let nextImageResult = vkAcquireNextImageKHR( @@ -204,7 +204,7 @@ return none(VkFramebuffer) return some(swapchain.framebuffers[swapchain.currentFramebufferIndex]) -proc Swap(swapchain: Swapchain, commandBuffer: VkCommandBuffer): bool = +proc swap(swapchain: Swapchain, commandBuffer: VkCommandBuffer): bool = var waitStage = VkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) submitInfo = VkSubmitInfo( @@ -238,7 +238,7 @@ if swapchain.oldSwapchain != nil: dec swapchain.oldSwapchainCounter if swapchain.oldSwapchainCounter <= 0: - DestroySwapchain(swapchain.oldSwapchain) + destroySwapchain(swapchain.oldSwapchain) swapchain.oldSwapchain = nil if presentResult != VK_SUCCESS: @@ -247,16 +247,16 @@ swapchain.currentFiF = (uint32(swapchain.currentFiF) + 1) mod INFLIGHTFRAMES return true -proc Recreate(swapchain: Swapchain): Swapchain = - InitSwapchain( +proc recreate(swapchain: Swapchain): Swapchain = + initSwapchain( renderPass = swapchain.renderPass, vSync = swapchain.vSync, oldSwapchain = swapchain, ) -template WithNextFrame*(framebufferName, commandBufferName, body: untyped): untyped = +template withNextFrame*(framebufferName, commandBufferName, body: untyped): untyped = assert vulkan.swapchain != nil, "Swapchain has not been initialized yet" - var maybeFramebuffer = TryAcquireNextImage(vulkan.swapchain) + var maybeFramebuffer = tryAcquireNextImage(vulkan.swapchain) if maybeFramebuffer.isSome: block: let `framebufferName` {.inject.} = maybeFramebuffer.get @@ -271,8 +271,8 @@ body checkVkResult vkEndCommandBuffer(`commandBufferName`) - discard Swap(swapchain = vulkan.swapchain, commandBuffer = `commandBufferName`) + discard swap(swapchain = vulkan.swapchain, commandBuffer = `commandBufferName`) else: - let newSwapchain = Recreate(vulkan.swapchain) + let newSwapchain = recreate(vulkan.swapchain) if newSwapchain != nil: vulkan.swapchain = newSwapchain diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/rendering/vulkan_wrappers.nim --- a/semicongine/rendering/vulkan_wrappers.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/rendering/vulkan_wrappers.nim Mon Jul 29 16:50:50 2024 +0700 @@ -1,4 +1,4 @@ -proc GetBestPhysicalDevice(instance: VkInstance): VkPhysicalDevice = +proc getBestPhysicalDevice(instance: VkInstance): VkPhysicalDevice = var nDevices: uint32 checkVkResult vkEnumeratePhysicalDevices(instance, addr(nDevices), nil) var devices = newSeq[VkPhysicalDevice](nDevices) @@ -29,7 +29,7 @@ checkVkResult vkGetPhysicalDeviceSurfaceSupportKHR(vulkan.physicalDevice, queueFamily, vulkan.surface, addr(presentation)) return bool(presentation) -proc GetQueueFamily(pDevice: VkPhysicalDevice, qType: VkQueueFlagBits): uint32 = +proc getQueueFamily(pDevice: VkPhysicalDevice, qType: VkQueueFlagBits): uint32 = var nQueuefamilies: uint32 vkGetPhysicalDeviceQueueFamilyProperties(pDevice, addr nQueuefamilies, nil) var queuFamilies = newSeq[VkQueueFamilyProperties](nQueuefamilies) @@ -199,7 +199,7 @@ var semaphoreInfo = VkSemaphoreCreateInfo(sType: VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO) checkVkResult vkCreateSemaphore(vulkan.device, addr(semaphoreInfo), nil, addr(result)) -proc Await*(fence: VkFence, timeout = high(uint64)): bool = +proc await*(fence: VkFence, timeout = high(uint64)): bool = let waitResult = vkWaitForFences(vulkan.device, 1, addr(fence), false, timeout) if waitResult == VK_TIMEOUT: return false @@ -253,7 +253,7 @@ ) checkVkResult vkCreateRenderPass(vulkan.device, addr(createInfo), nil, addr(result)) -proc BestMemory*(mappable: bool, filter: seq[uint32] = @[]): uint32 = +proc bestMemory*(mappable: bool, filter: seq[uint32] = @[]): uint32 = var physicalProperties: VkPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties(vulkan.physicalDevice, addr(physicalProperties)) @@ -273,7 +273,7 @@ assert maxScore > 0, &"Unable to find memory type (mappable: {mappable}, filter: {filter})" return maxIndex -template WithSingleUseCommandBuffer*(cmd, body: untyped): untyped = +template withSingleUseCommandBuffer*(cmd, body: untyped): untyped = block: var commandBufferPool: VkCommandPool @@ -309,11 +309,11 @@ var fence = svkCreateFence() checkVkResult vkQueueSubmit(vulkan.graphicsQueue, 1, addr(submitInfo), fence) - discard fence.Await() + discard fence.await() vkDestroyFence(vulkan.device, fence, nil) vkDestroyCommandPool(vulkan.device, commandBufferPool, nil) -template WithStagingBuffer*[T: (VkBuffer, uint64)|(VkImage, uint32, uint32)]( +template withStagingBuffer*[T: (VkBuffer, uint64)|(VkImage, uint32, uint32)]( target: T, bufferSize: uint64, dataPointer, @@ -322,7 +322,7 @@ var `dataPointer` {.inject.}: pointer let stagingBuffer = svkCreateBuffer(bufferSize, [VK_BUFFER_USAGE_TRANSFER_SRC_BIT]) let memoryRequirements = svkGetBufferMemoryRequirements(stagingBuffer) - let memoryType = BestMemory(mappable = true, filter = memoryRequirements.memoryTypes) + let memoryType = bestMemory(mappable = true, filter = memoryRequirements.memoryTypes) let stagingMemory = svkAllocateMemory(memoryRequirements.size, memoryType) checkVkResult vkMapMemory( device = vulkan.device, @@ -345,7 +345,7 @@ ) checkVkResult vkFlushMappedMemoryRanges(vulkan.device, 1, addr(stagingRange)) - WithSingleUseCommandBuffer(commandBuffer): + withSingleUseCommandBuffer(commandBuffer): when T is (VkBuffer, uint64): # first make sure memory has been made available with a memory barrier # we are just waiting for the vertex input stage, but I think that is fine for most buffer copies (for now at least) diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/resources.nim --- a/semicongine/resources.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/resources.nim Mon Jul 29 16:50:50 2024 +0700 @@ -138,25 +138,25 @@ yield (kind: pcDir, path: components[0]) yielded.incl components[0] -proc LoadResource*(path: string, package = DEFAULT_PACKAGE): Stream = +proc loadResource*(path: string, package = DEFAULT_PACKAGE): Stream = loadResource_intern(path, package = package) -proc LoadJson*(path: string, package = DEFAULT_PACKAGE): JsonNode = +proc loadJson*(path: string, package = DEFAULT_PACKAGE): JsonNode = path.loadResource_intern(package = package).readAll().parseJson() -proc LoadConfig*(path: string, package = DEFAULT_PACKAGE): Config = +proc loadConfig*(path: string, package = DEFAULT_PACKAGE): Config = path.loadResource_intern(package = package).loadConfig(filename = path) -proc Packages*(): seq[string] = +proc packages*(): seq[string] = modList_intern() -proc WalkResources*(dir = "", package = DEFAULT_PACKAGE): seq[string] = +proc walkResources*(dir = "", package = DEFAULT_PACKAGE): seq[string] = for i in walkResources_intern(dir, package = package): if i.startsWith(dir): result.add i result.sort() -proc List*(dir: string, package = DEFAULT_PACKAGE): seq[tuple[kind: PathComponent, path: string]] = +proc list*(dir: string, package = DEFAULT_PACKAGE): seq[tuple[kind: PathComponent, path: string]] = for i in ls_intern(dir = dir, package = package): result.add i result.sort() diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/storage.nim --- a/semicongine/storage.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/storage.nim Mon Jul 29 16:50:50 2024 +0700 @@ -31,23 +31,23 @@ value TEXT NOT NULL )""")) -proc Store*[T](storageType: StorageType, key: string, value: T, table = DEFAULT_KEY_VALUE_TABLE_NAME) = +proc store*[T](storageType: StorageType, key: string, value: T, table = DEFAULT_KEY_VALUE_TABLE_NAME) = storageType.ensureExists(table) db[storageType].exec(sql(&"""INSERT INTO {table} VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value """), key, $$value) -proc Load*[T](storageType: StorageType, key: string, default: T, table = DEFAULT_KEY_VALUE_TABLE_NAME): T = +proc load*[T](storageType: StorageType, key: string, default: T, table = DEFAULT_KEY_VALUE_TABLE_NAME): T = storageType.ensureExists(table) let dbResult = db[storageType].getValue(sql(&"""SELECT value FROM {table} WHERE key = ? """), key) if dbResult == "": return default return to[T](dbResult) -proc List*[T](storageType: StorageType, table = DEFAULT_KEY_VALUE_TABLE_NAME): seq[string] = +proc list*[T](storageType: StorageType, table = DEFAULT_KEY_VALUE_TABLE_NAME): seq[string] = storageType.ensureExists(table) for row in db[storageType].fastRows(sql(&"""SELECT key FROM {table}""")): result.add row[0] -proc Purge*(storageType: StorageType) = +proc purge*(storageType: StorageType) = storageType.path().string.removeFile() diff -r 3308b88e53a6 -r 0369fa1ffbd9 semicongine/text/textbox.nim --- a/semicongine/text/textbox.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/semicongine/text/textbox.nim Mon Jul 29 16:50:50 2024 +0700 @@ -14,18 +14,18 @@ lastRenderedText: seq[Rune] # stores the last rendered text, to prevent unnecessary updates # rendering data - position*: GPUArray[Vec3f, VertexBuffer] - uv*: GPUArray[Vec2f, VertexBuffer] - indices*: GPUArray[uint16, IndexBuffer] - shaderdata*: DescriptorSet[TextboxDescriptorSet] + position: GPUArray[Vec3f, VertexBuffer] + uv: GPUArray[Vec2f, VertexBuffer] + indices: GPUArray[uint16, IndexBuffer] + shaderdata: DescriptorSet[TextboxDescriptorSet] func `$`*(textbox: Textbox): string = "\"" & $textbox.text[0 ..< min(textbox.text.len, 16)] & "\"" -proc RefreshShaderdata(textbox: Textbox) = - textbox.shaderdata.data.textbox.UpdateGPUBuffer(flush = true) +proc refreshShaderdata(textbox: Textbox) = + textbox.shaderdata.data.textbox.updateGPUBuffer(flush = true) -proc RefreshGeometry(textbox: var Textbox) = +proc refreshGeometry(textbox: var Textbox) = # pre-calculate text-width var width = 0'f32 var lineWidths: seq[float32] @@ -98,8 +98,8 @@ textbox.position.data[vertexOffset + 1] = vec3(0, 0, 0) textbox.position.data[vertexOffset + 2] = vec3(0, 0, 0) textbox.position.data[vertexOffset + 3] = vec3(0, 0, 0) - UpdateGPUBuffer(textbox.position) - UpdateGPUBuffer(textbox.uv) + updateGPUBuffer(textbox.position) + updateGPUBuffer(textbox.uv) textbox.lastRenderedText = textbox.processedText func text*(textbox: Textbox): seq[Rune] = @@ -122,26 +122,26 @@ proc `text=`*(textbox: var Textbox, newText: string) = `text=`(textbox, newText.toRunes) -proc Color*(textbox: Textbox): Vec4f = +proc color*(textbox: Textbox): Vec4f = textbox.shaderdata.data.textbox.data.color -proc `Color=`*(textbox: var Textbox, value: Vec4f) = +proc `color=`*(textbox: var Textbox, value: Vec4f) = if textbox.shaderdata.data.textbox.data.color != value: textbox.dirtyShaderdata = true textbox.shaderdata.data.textbox.data.color = value -proc Scale*(textbox: Textbox): float32 = +proc scale*(textbox: Textbox): float32 = textbox.shaderdata.data.textbox.data.scale -proc `Scale=`*(textbox: var Textbox, value: float32) = +proc `scale=`*(textbox: var Textbox, value: float32) = if textbox.shaderdata.data.textbox.data.scale != value: textbox.dirtyShaderdata = true textbox.shaderdata.data.textbox.data.scale = value -proc Position*(textbox: Textbox): Vec3f = +proc position*(textbox: Textbox): Vec3f = textbox.shaderdata.data.textbox.data.position -proc `Position=`*(textbox: var Textbox, value: Vec3f) = +proc `position=`*(textbox: var Textbox, value: Vec3f) = if textbox.shaderdata.data.textbox.data.position != value: textbox.dirtyShaderdata = true textbox.shaderdata.data.textbox.data.position = value @@ -160,24 +160,24 @@ textbox.verticalAlignment = value textbox.dirtyGeometry = true -proc Refresh*(textbox: var Textbox) = - if textbox.shaderdata.data.textbox.data.aspectratio != GetAspectRatio(): +proc refresh*(textbox: var Textbox) = + if textbox.shaderdata.data.textbox.data.aspectratio != getAspectRatio(): textbox.dirtyShaderdata = true - textbox.shaderdata.data.textbox.data.aspectratio = GetAspectRatio() + textbox.shaderdata.data.textbox.data.aspectratio = getAspectRatio() if textbox.dirtyShaderdata: - textbox.RefreshShaderdata() + textbox.refreshShaderdata() textbox.dirtyShaderdata = false if textbox.dirtyGeometry or textbox.processedText != textbox.lastRenderedText: - textbox.RefreshGeometry() + textbox.refreshGeometry() textbox.dirtyGeometry = false -proc Render*(textbox: Textbox, commandbuffer: VkCommandBuffer, pipeline: Pipeline) = - WithBind(commandbuffer, (textbox.shaderdata, ), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = textbox) +proc render*(textbox: Textbox, commandbuffer: VkCommandBuffer, pipeline: Pipeline) = + withBind(commandbuffer, (textbox.shaderdata, ), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = textbox) -proc InitTextbox*[T: string | seq[Rune]]( +proc initTextbox*[T: string | seq[Rune]]( renderdata: var RenderData, descriptorSetLayout: VkDescriptorSetLayout, font: Font, @@ -229,10 +229,10 @@ else: `text=`(result, text) - AssignBuffers(renderdata, result, uploadData = false) - UploadImages(renderdata, result.shaderdata) - InitDescriptorSet(renderdata, descriptorSetLayout, result.shaderdata) + assignBuffers(renderdata, result, uploadData = false) + uploadImages(renderdata, result.shaderdata) + initDescriptorSet(renderdata, descriptorSetLayout, result.shaderdata) - result.Refresh() - UpdateAllGPUBuffers(result, flush = true, allFrames = true) - UpdateAllGPUBuffers(result.shaderdata.data, flush = true) + result.refresh() + updateAllGPUBuffers(result, flush = true, allFrames = true) + updateAllGPUBuffers(result.shaderdata.data, flush = true) diff -r 3308b88e53a6 -r 0369fa1ffbd9 tests/test_gltf.nim --- a/tests/test_gltf.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/tests/test_gltf.nim Mon Jul 29 16:50:50 2024 +0700 @@ -8,7 +8,7 @@ import ../semicongine proc test_gltf(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type ObjectData = object @@ -90,7 +90,7 @@ indices: GPUArray[uint32, IndexBuffer] material: int32 - var gltfData = LoadMeshes[Mesh, Material]( + var gltfData = loadMeshes[Mesh, Material]( "town.glb", # "forest.glb", MeshAttributeNames( @@ -126,19 +126,19 @@ for mesh in mitems(gltfData.meshes): for primitive in mitems(mesh): primitive[0].color = asGPUArray(newSeqWith(primitive[0].position.data.len, vec4(1, 1, 1, 1)), VertexBuffer) - renderdata.AssignBuffers(primitive[0]) - renderdata.AssignBuffers(descriptors) + renderdata.assignBuffers(primitive[0]) + renderdata.assignBuffers(descriptors) - var pipeline = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass, cullMode=[]) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], descriptors) + var pipeline = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass, cullMode=[]) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], descriptors) - renderdata.FlushAllMemory() + renderdata.flushAllMemory() proc drawNode(commandbuffer: VkCommandBuffer, pipeline: Pipeline, nodeId: int, transform: Mat4) = let nodeTransform = gltfData.nodes[nodeId].transform * transform if gltfData.nodes[nodeId].mesh >= 0: for primitive in gltfData.meshes[gltfData.nodes[nodeId].mesh]: - RenderWithPushConstant( + renderWithPushConstant( commandbuffer = commandbuffer, pipeline = pipeline, mesh = primitive[0], @@ -151,23 +151,23 @@ var camYaw: float32 var camPitch: float32 - discard UpdateInputs() # clear inputs, otherwise MouseMove will have stuff + discard updateInputs() # clear inputs, otherwise MouseMove will have stuff var start = getMonoTime() var lastT = getMonoTime() - while ((getMonoTime() - start).inMilliseconds().int / 1000) < time and UpdateInputs(): + while ((getMonoTime() - start).inMilliseconds().int / 1000) < time and updateInputs(): let dt = ((getMonoTime() - lastT).inNanoseconds().int / 1_000_000_000).float32 lastT = getMonoTime() - camYaw -= MouseMove().x / 1000 - camPitch -= MouseMove().y / 1000 + camYaw -= mouseMove().x / 1000 + camPitch -= mouseMove().y / 1000 var forward = 0'f32 sideward = 0'f32 - if KeyIsDown(W): forward += 2 - if KeyIsDown(S): forward -= 2 - if KeyIsDown(A): sideward -= 2 - if KeyIsDown(D): sideward += 2 + if keyIsDown(W): forward += 2 + if keyIsDown(S): forward -= 2 + if keyIsDown(A): sideward -= 2 + if keyIsDown(D): sideward += 2 let camDir = (rotate(camYaw, Y) * rotate(camPitch, X)) * Z let camDirSide = camDir.cross(-Y).normalized @@ -177,16 +177,16 @@ let view = rotate(-camPitch, X) * rotate(-camYaw, Y) * translate(-camPos) descriptors.data.camera.data.view = view descriptors.data.camera.data.normal = view - descriptors.data.camera.data.projection = projection(PI / 2, aspect = GetAspectRatio(), zNear = 0.01, zFar = 20) + descriptors.data.camera.data.projection = projection(PI / 2, aspect = getAspectRatio(), zNear = 0.01, zFar = 20) - UpdateGPUBuffer(descriptors.data.camera) + updateGPUBuffer(descriptors.data.camera) - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): - WithBind(commandbuffer, (descriptors, ), pipeline): + withPipeline(commandbuffer, pipeline): + withBind(commandbuffer, (descriptors, ), pipeline): for nodeId in gltfData.scenes[0]: drawNode( commandbuffer = commandbuffer, @@ -197,23 +197,23 @@ # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) when isMainModule: var time = 1000'f32 - InitVulkan() + initVulkan() - var renderpass = CreateDirectPresentationRenderPass(depthBuffer = true, samples = VK_SAMPLE_COUNT_4_BIT) - SetupSwapchain(renderpass = renderpass) - LockMouse(true) - ShowSystemCursor(false) + var renderpass = createDirectPresentationRenderPass(depthBuffer = true, samples = VK_SAMPLE_COUNT_4_BIT) + setupSwapchain(renderpass = renderpass) + lockMouse(true) + showSystemCursor(false) # tests a simple triangle with minimalistic shader and vertex format test_gltf(time) checkVkResult vkDeviceWaitIdle(vulkan.device) vkDestroyRenderPass(vulkan.device, renderpass.vk, nil) - ClearSwapchain() + clearSwapchain() - DestroyVulkan() + destroyVulkan() diff -r 3308b88e53a6 -r 0369fa1ffbd9 tests/test_rendering.nim --- a/tests/test_rendering.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/tests/test_rendering.nim Mon Jul 29 16:50:50 2024 +0700 @@ -8,7 +8,7 @@ import ../semicongine proc test_01_triangle(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type PushConstant = object @@ -32,30 +32,30 @@ position: asGPUArray([vec3(-0.5, -0.5, 0), vec3(0, 0.5, 0), vec3(0.5, -0.5, 0)], VertexBuffer), color: asGPUArray([vec3(0, 0, 1), vec3(0, 1, 0), vec3(1, 0, 0)], VertexBuffer), ) - AssignBuffers(renderdata, mesh) - renderdata.FlushAllMemory() + assignBuffers(renderdata, mesh) + renderdata.flushAllMemory() - var pipeline = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withPipeline(commandbuffer, pipeline): - RenderWithPushConstant(commandbuffer = commandbuffer, pipeline = pipeline, mesh = mesh, pushConstant = PushConstant(scale: 0.3 + ((getMonoTime() - start).inMilliseconds().int / 1000))) + renderWithPushConstant(commandbuffer = commandbuffer, pipeline = pipeline, mesh = mesh, pushConstant = PushConstant(scale: 0.3 + ((getMonoTime() - start).inMilliseconds().int / 1000))) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_02_triangle_quad_instanced(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type SomeShader = object @@ -100,35 +100,35 @@ instancesB.pos.data.add vec3(rand(-0.8'f32 .. 0.8'f32), rand(0'f32 .. 0.8'f32), 0) instancesB.scale.data.add rand(0.1'f32 .. 0.2'f32) - AssignBuffers(renderdata, tri) - AssignBuffers(renderdata, quad) - AssignBuffers(renderdata, instancesA) - AssignBuffers(renderdata, instancesB) - renderdata.FlushAllMemory() + assignBuffers(renderdata, tri) + assignBuffers(renderdata, quad) + assignBuffers(renderdata, instancesA) + assignBuffers(renderdata, instancesB) + renderdata.flushAllMemory() - var pipeline = CreatePipeline[SomeShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[SomeShader](renderPass = vulkan.swapchain.renderPass) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withPipeline(commandbuffer, pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad, instances = instancesA) - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad, instances = instancesB) - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = tri, instances = instancesA) - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = tri, instances = instancesB) + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad, instances = instancesA) + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad, instances = instancesB) + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = tri, instances = instancesA) + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = tri, instances = instancesB) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_03_simple_descriptorset(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type Material = object @@ -179,40 +179,40 @@ ) ) - AssignBuffers(renderdata, quad) - AssignBuffers(renderdata, uniforms1) - AssignBuffers(renderdata, uniforms2) - UploadImages(renderdata, uniforms1) - UploadImages(renderdata, uniforms2) - renderdata.FlushAllMemory() + assignBuffers(renderdata, quad) + assignBuffers(renderdata, uniforms1) + assignBuffers(renderdata, uniforms2) + uploadImages(renderdata, uniforms1) + uploadImages(renderdata, uniforms2) + renderdata.flushAllMemory() - var pipeline = CreatePipeline[QuadShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[QuadShader](renderPass = vulkan.swapchain.renderPass) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms1) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms2) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms1) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms2) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withPipeline(commandbuffer, pipeline): - WithBind(commandbuffer, (uniforms1, ), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) + withBind(commandbuffer, (uniforms1, ), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) - WithBind(commandbuffer, (uniforms2, ), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) + withBind(commandbuffer, (uniforms2, ), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_04_multiple_descriptorsets(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type RenderSettings = object @@ -290,46 +290,46 @@ ) ) - AssignBuffers(renderdata, quad) - AssignBuffers(renderdata, constset) - AssignBuffers(renderdata, mainset) - AssignBuffers(renderdata, otherset1) - AssignBuffers(renderdata, otherset2) - UploadImages(renderdata, mainset) - renderdata.FlushAllMemory() + assignBuffers(renderdata, quad) + assignBuffers(renderdata, constset) + assignBuffers(renderdata, mainset) + assignBuffers(renderdata, otherset1) + assignBuffers(renderdata, otherset2) + uploadImages(renderdata, mainset) + renderdata.flushAllMemory() - var pipeline = CreatePipeline[QuadShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[QuadShader](renderPass = vulkan.swapchain.renderPass) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], constset) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[1], mainset) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[2], otherset1) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[2], otherset2) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], constset) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[1], mainset) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[2], otherset1) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[2], otherset2) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withPipeline(commandbuffer, pipeline): - WithBind(commandbuffer, (constset, mainset, otherset1), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) + withBind(commandbuffer, (constset, mainset, otherset1), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) - WithBind(commandbuffer, (constset, mainset, otherset2), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) + withBind(commandbuffer, (constset, mainset, otherset2), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = quad) mainset.data.renderSettings.data.brigthness = ((getMonoTime() - start).inMilliseconds().int / 1000) / time otherset1.data.objectSettings.data.scale = 0.5 + ((getMonoTime() - start).inMilliseconds().int / 1000) / time - UpdateGPUBuffer(mainset.data.renderSettings) - UpdateGPUBuffer(otherset1.data.objectSettings) - renderdata.FlushAllMemory() + updateGPUBuffer(mainset.data.renderSettings) + updateGPUBuffer(otherset1.data.objectSettings) + renderdata.flushAllMemory() # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_05_cube(time: float32) = type @@ -400,33 +400,33 @@ colors.add newSeqWith(6, vec4(1, 1, 0, 1)) normals.add newSeqWith(6, vec3(0, 1, 0)) - var renderdata = InitRenderData() + var renderdata = initRenderData() var mesh = Mesh( position: asGPUArray(vertices, VertexBuffer), color: asGPUArray(colors, VertexBuffer), normals: asGPUArray(normals, VertexBuffer), ) - AssignBuffers(renderdata, mesh) + assignBuffers(renderdata, mesh) var floor = Mesh( position: asGPUArray(quad.transf(scale(10, 10, 10) * rotate(-PI / 2, X) * translate(0, 0, 0.05)), VertexBuffer), color: asGPUArray(newSeqWith(6, vec4(0.1, 0.1, 0.1, 1)), VertexBuffer), normals: asGPUArray(newSeqWith(6, Y), VertexBuffer), ) - AssignBuffers(renderdata, floor) + assignBuffers(renderdata, floor) var uniforms1 = asDescriptorSet( Uniforms( data: asGPUValue(UniformData(mvp: Unit4), UniformBufferMapped) ) ) - AssignBuffers(renderdata, uniforms1) + assignBuffers(renderdata, uniforms1) - renderdata.FlushAllMemory() + renderdata.flushAllMemory() - var pipeline = CreatePipeline[CubeShader](renderPass = vulkan.swapchain.renderPass) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms1) + var pipeline = createPipeline[CubeShader](renderPass = vulkan.swapchain.renderPass) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms1) var tStart = getMonoTime() var t = tStart @@ -436,21 +436,21 @@ let tStartLoop = getMonoTime() - tStart uniforms1.data.data.data.mvp = ( - projection(-PI / 2, GetAspectRatio(), 0.01, 100) * + projection(-PI / 2, getAspectRatio(), 0.01, 100) * translate(0, 0, 2) * rotate(PI / 4, X) * rotate(PI * 0.1 * (tStartLoop.inMicroseconds() / 1_000_000), Y) ) - UpdateGPUBuffer(uniforms1.data.data, flush = true) + updateGPUBuffer(uniforms1.data.data, flush = true) - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, pipeline): - WithBind(commandbuffer, (uniforms1, ), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = mesh) - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = floor) + withBind(commandbuffer, (uniforms1, ), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = mesh) + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = floor) let tEndLoop = getMonoTime() - tStart let looptime = tEndLoop - tStartLoop @@ -460,11 +460,11 @@ # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_06_different_draw_modes(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type Shader = object @@ -490,38 +490,38 @@ position: asGPUArray([vec3(-0.9, 0, 0), vec3(-0.05, -0.9, 0), vec3(0.05, -0.9, 0), vec3(0.9, 0, 0)], VertexBuffer), color: asGPUArray([vec3(1, 1, 0), vec3(1, 1, 0), vec3(0, 1, 0), vec3(0, 1, 0)], VertexBuffer), ) - AssignBuffers(renderdata, triangle) - AssignBuffers(renderdata, lines) - renderdata.FlushAllMemory() + assignBuffers(renderdata, triangle) + assignBuffers(renderdata, lines) + renderdata.flushAllMemory() - var pipeline1 = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass, polygonMode = VK_POLYGON_MODE_LINE, lineWidth = 20'f32) - var pipeline2 = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass, polygonMode = VK_POLYGON_MODE_POINT) - var pipeline3 = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass, topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST, lineWidth = 5) - var pipeline4 = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass, topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST) + var pipeline1 = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass, polygonMode = VK_POLYGON_MODE_LINE, lineWidth = 20'f32) + var pipeline2 = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass, polygonMode = VK_POLYGON_MODE_POINT) + var pipeline3 = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass, topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST, lineWidth = 5) + var pipeline4 = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass, topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline1): - Render(commandbuffer = commandbuffer, pipeline = pipeline1, mesh = triangle) - WithPipeline(commandbuffer, pipeline2): - Render(commandbuffer = commandbuffer, pipeline = pipeline2, mesh = triangle) - WithPipeline(commandbuffer, pipeline3): - Render(commandbuffer = commandbuffer, pipeline = pipeline3, mesh = lines) - WithPipeline(commandbuffer, pipeline4): - Render(commandbuffer = commandbuffer, pipeline = pipeline4, mesh = lines) + withNextFrame(framebuffer, commandbuffer): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, pipeline1): + render(commandbuffer = commandbuffer, pipeline = pipeline1, mesh = triangle) + withPipeline(commandbuffer, pipeline2): + render(commandbuffer = commandbuffer, pipeline = pipeline2, mesh = triangle) + withPipeline(commandbuffer, pipeline3): + render(commandbuffer = commandbuffer, pipeline = pipeline3, mesh = lines) + withPipeline(commandbuffer, pipeline4): + render(commandbuffer = commandbuffer, pipeline = pipeline4, mesh = lines) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline1) - DestroyPipeline(pipeline2) - DestroyPipeline(pipeline3) - DestroyPipeline(pipeline4) - DestroyRenderData(renderdata) + destroyPipeline(pipeline1) + destroyPipeline(pipeline2) + destroyPipeline(pipeline3) + destroyPipeline(pipeline4) + destroyRenderData(renderdata) proc test_07_png_texture(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() type Uniforms = object @@ -555,41 +555,41 @@ vec2(1, 0), vec2(1, 1), vec2(0, 1), ], VertexBuffer), ) - AssignBuffers(renderdata, mesh) - renderdata.FlushAllMemory() + assignBuffers(renderdata, mesh) + renderdata.flushAllMemory() - var pipeline = CreatePipeline[Shader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[Shader](renderPass = vulkan.swapchain.renderPass) var uniforms1 = asDescriptorSet( Uniforms( - texture1: LoadImage[BGRA]("art.png"), + texture1: loadImage[BGRA]("art.png"), ) ) - UploadImages(renderdata, uniforms1) - InitDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms1) + uploadImages(renderdata, uniforms1) + initDescriptorSet(renderdata, pipeline.descriptorSetLayouts[0], uniforms1) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withPipeline(commandbuffer, pipeline): - WithBind(commandbuffer, (uniforms1, ), pipeline): - Render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = mesh) + withBind(commandbuffer, (uniforms1, ), pipeline): + render(commandbuffer = commandbuffer, pipeline = pipeline, mesh = mesh) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_08_triangle_2pass(time: float32, depthBuffer: bool, samples: VkSampleCountFlagBits) = - var (offscreenRP, presentRP) = CreateIndirectPresentationRenderPass(depthBuffer = depthBuffer, samples = samples) + var (offscreenRP, presentRP) = createIndirectPresentationRenderPass(depthBuffer = depthBuffer, samples = samples) - SetupSwapchain(renderpass = presentRP) + setupSwapchain(renderpass = presentRP) - var renderdata = InitRenderData() + var renderdata = initRenderData() type Uniforms = object @@ -645,16 +645,16 @@ frameTexture: Image[BGRA](width: vulkan.swapchain.width, height: vulkan.swapchain.height, isRenderTarget: true), ) ) - AssignBuffers(renderdata, mesh) - AssignBuffers(renderdata, quad) - UploadImages(renderdata, uniforms1) - renderdata.FlushAllMemory() + assignBuffers(renderdata, mesh) + assignBuffers(renderdata, quad) + uploadImages(renderdata, uniforms1) + renderdata.flushAllMemory() var - drawPipeline = CreatePipeline[TriangleShader](renderPass = offscreenRP) - presentPipeline = CreatePipeline[PresentShader](renderPass = presentRP) + drawPipeline = createPipeline[TriangleShader](renderPass = offscreenRP) + presentPipeline = createPipeline[PresentShader](renderPass = presentRP) - InitDescriptorSet(renderdata, presentPipeline.descriptorSetLayouts[0], uniforms1) + initDescriptorSet(renderdata, presentPipeline.descriptorSetLayouts[0], uniforms1) # create depth buffer images (will not use the one in the swapchain var @@ -672,7 +672,7 @@ let requirements = svkGetImageMemoryRequirements(depthImage) depthMemory = svkAllocateMemory( requirements.size, - BestMemory(mappable = false, filter = requirements.memoryTypes) + bestMemory(mappable = false, filter = requirements.memoryTypes) ) checkVkResult vkBindImageMemory( vulkan.device, @@ -702,7 +702,7 @@ let requirements = svkGetImageMemoryRequirements(msaaImage) msaaMemory = svkAllocateMemory( requirements.size, - BestMemory(mappable = false, filter = requirements.memoryTypes) + bestMemory(mappable = false, filter = requirements.memoryTypes) ) checkVkResult vkBindImageMemory( vulkan.device, @@ -733,24 +733,24 @@ var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - WithNextFrame(framebuffer, commandbuffer): + withNextFrame(framebuffer, commandbuffer): - WithRenderPass(offscreenRP, offscreenFB, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, drawPipeline): - Render(commandbuffer = commandbuffer, pipeline = drawPipeline, mesh = mesh) + withRenderPass(offscreenRP, offscreenFB, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, drawPipeline): + render(commandbuffer = commandbuffer, pipeline = drawPipeline, mesh = mesh) - WithRenderPass(presentRP, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withRenderPass(presentRP, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, presentPipeline): + withPipeline(commandbuffer, presentPipeline): - WithBind(commandbuffer, (uniforms1, ), presentPipeline): - Render(commandbuffer = commandbuffer, pipeline = presentPipeline, mesh = quad) + withBind(commandbuffer, (uniforms1, ), presentPipeline): + render(commandbuffer = commandbuffer, pipeline = presentPipeline, mesh = quad) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(presentPipeline) - DestroyPipeline(drawPipeline) - DestroyRenderData(renderdata) + destroyPipeline(presentPipeline) + destroyPipeline(drawPipeline) + destroyRenderData(renderdata) if depthImage.Valid: vkDestroyImageView(vulkan.device, depthImageView, nil) vkDestroyImage(vulkan.device, depthImage, nil) @@ -762,11 +762,11 @@ vkDestroyRenderPass(vulkan.device, offscreenRP.vk, nil) vkDestroyRenderPass(vulkan.device, presentRP.vk, nil) vkDestroyFramebuffer(vulkan.device, offscreenFB, nil) - ClearSwapchain() + clearSwapchain() when isMainModule: var time = 1'f32 - InitVulkan() + initVulkan() var mainRenderpass: RenderPass var renderPasses = [ @@ -779,8 +779,8 @@ # test normal for i, (depthBuffer, samples) in renderPasses: - var renderpass = CreateDirectPresentationRenderPass(depthBuffer = depthBuffer, samples = samples) - SetupSwapchain(renderpass = renderpass) + var renderpass = createDirectPresentationRenderPass(depthBuffer = depthBuffer, samples = samples) + setupSwapchain(renderpass = renderpass) # tests a simple triangle with minimalistic shader and vertex format test_01_triangle(time) @@ -805,10 +805,10 @@ checkVkResult vkDeviceWaitIdle(vulkan.device) vkDestroyRenderPass(vulkan.device, renderpass.vk, nil) - ClearSwapchain() + clearSwapchain() # test multiple render passes for i, (depthBuffer, samples) in renderPasses: test_08_triangle_2pass(time, depthBuffer, samples) - DestroyVulkan() + destroyVulkan() diff -r 3308b88e53a6 -r 0369fa1ffbd9 tests/test_text.nim --- a/tests/test_text.nim Mon Jul 29 16:05:09 2024 +0700 +++ b/tests/test_text.nim Mon Jul 29 16:50:50 2024 +0700 @@ -10,12 +10,12 @@ import ../semicongine proc test_01_static_label(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() - var pipeline = CreatePipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) var font = loadFont("Overhaul.ttf", lineHeightPixels = 160) - var label1 = InitTextbox( + var label1 = initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font, @@ -26,27 +26,27 @@ var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: - label1.Refresh() - WithNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): - Render(label1, commandbuffer, pipeline) + label1.refresh() + withNextFrame(framebuffer, commandbuffer): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, pipeline): + render(label1, commandbuffer, pipeline) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_02_multiple_animated(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() - var pipeline = CreatePipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) var font1 = loadFont("Overhaul.ttf", lineHeightPixels = 40) var font2 = loadFont("Overhaul.ttf", lineHeightPixels = 160) var font3 = loadFont("DejaVuSans.ttf", lineHeightPixels = 160) var labels = [ - InitTextbox( + initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font1, @@ -55,7 +55,7 @@ scale = 0.004, position = vec3(-0.3, 0.5) ), - InitTextbox( + initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font2, @@ -64,7 +64,7 @@ scale = 0.001, position = vec3(0, 0) ), - InitTextbox( + initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font3, @@ -80,35 +80,35 @@ while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: let progress = ((getMonoTime() - start).inMilliseconds().int / 1000) / time for i in 0 ..< labels.len: - var c = labels[i].Color + var c = labels[i].color c[i] = progress - labels[i].Color = c - labels[i].Scale = labels[i].Scale * (1.0 + (i + 1).float * 0.001) - labels[i].Position = labels[i].Position + vec3(0.001 * (i.float - 1'f)) + labels[i].color = c + labels[i].scale = labels[i].scale * (1.0 + (i + 1).float * 0.001) + labels[i].position = labels[i].position + vec3(0.001 * (i.float - 1'f)) labels[i].text = $(p + i) - labels[i].Refresh() + labels[i].refresh() inc p - WithNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withNextFrame(framebuffer, commandbuffer): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, pipeline): for label in labels: - Render(label, commandbuffer, pipeline) + render(label, commandbuffer, pipeline) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_03_layouting(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() - var pipeline = CreatePipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) var font = loadFont("DejaVuSans.ttf", lineHeightPixels = 40) var labels: seq[Textbox] for horizontal in HorizontalAlignment: - labels.add InitTextbox( + labels.add initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font, @@ -119,7 +119,7 @@ horizontalAlignment = horizontal, ) for vertical in VerticalAlignment: - labels.add InitTextbox( + labels.add initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font, @@ -129,7 +129,7 @@ position = vec3(-0.35 + (vertical.float * 0.35), 0.3), verticalAlignment = vertical, ) - labels.add InitTextbox( + labels.add initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font, @@ -149,26 +149,26 @@ var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: let progress = ((getMonoTime() - start).inMilliseconds().int / 1000) / time - WithNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + withNextFrame(framebuffer, commandbuffer): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, pipeline): for label in labels: - Render(label, commandbuffer, pipeline) + render(label, commandbuffer, pipeline) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) proc test_04_lots_of_texts(time: float32) = - var renderdata = InitRenderData() + var renderdata = initRenderData() - var pipeline = CreatePipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) + var pipeline = createPipeline[DefaultFontShader](renderPass = vulkan.swapchain.renderPass) var font = loadFont("DejaVuSans.ttf", lineHeightPixels = 160) var labels: seq[Textbox] for i in 0 ..< 100: - labels.add InitTextbox( + labels.add initTextbox( renderdata, pipeline.descriptorSetLayouts[0], font, @@ -177,30 +177,30 @@ scale = rand(0.0002 .. 0.002), position = vec3(rand(-0.5 .. 0.5), rand(-0.5 .. 0.5), rand(-0.1 .. 0.1)) ) - labels = labels.sortedByIt(-it.Position.z) + labels = labels.sortedByIt(-it.position.z) var start = getMonoTime() while ((getMonoTime() - start).inMilliseconds().int / 1000) < time: for l in labels.mitems: - l.Refresh() - WithNextFrame(framebuffer, commandbuffer): - WithRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): - WithPipeline(commandbuffer, pipeline): + l.refresh() + withNextFrame(framebuffer, commandbuffer): + withRenderPass(vulkan.swapchain.renderPass, framebuffer, commandbuffer, vulkan.swapchain.width, vulkan.swapchain.height, vec4(0, 0, 0, 0)): + withPipeline(commandbuffer, pipeline): for l in labels: - Render(l, commandbuffer, pipeline) + render(l, commandbuffer, pipeline) # cleanup checkVkResult vkDeviceWaitIdle(vulkan.device) - DestroyPipeline(pipeline) - DestroyRenderData(renderdata) + destroyPipeline(pipeline) + destroyRenderData(renderdata) when isMainModule: var time = 1'f32 - InitVulkan() + initVulkan() for depthBuffer in [true, false]: - var renderpass = CreateDirectPresentationRenderPass(depthBuffer = depthBuffer) - SetupSwapchain(renderpass = renderpass) + var renderpass = createDirectPresentationRenderPass(depthBuffer = depthBuffer) + setupSwapchain(renderpass = renderpass) # tests a simple triangle with minimalistic shader and vertex format test_01_static_label(time) @@ -210,6 +210,6 @@ checkVkResult vkDeviceWaitIdle(vulkan.device) vkDestroyRenderPass(vulkan.device, renderpass.vk, nil) - ClearSwapchain() + clearSwapchain() - DestroyVulkan() + destroyVulkan()