Hello Window
Time to get something on screen. Our first program opens a window, connects Direct3D to it, and fills it with one colour, over and over, until we close it. That sounds like very little, and in pixels it is, but every later program starts with exactly this code, so it is worth understanding each line. The whole program is hello_window.rasm, under two hundred lines with its comments. This lesson and the next write all of it out; from Shaders on, the same code lives in learn/window.rasm, and a lesson starts with one call to
It begins by importing what it needs: the Windows and Direct3D declarations, the call macros, and the print routine for error messages.
import "../../../includes/d3d11.rin"
import "../../../includes/calls.rasm"
import "../../../includes/print.rasm"
; settings
#define SCR_WIDTH 1280
#define SCR_HEIGHT 720
The two settings are the size of the area we draw into, in pixels. A #define is a compile-time constant, exactly as in C: wherever it is used it is a number, an immediate in an instruction or a value in an initialiser, and it takes no memory. Then
- register a window class and create a window,
- create the Direct3D device, its immediate context and a swap chain for the window,
- create a render target view of the swap chain's back buffer,
- loop: handle the window's messages and input, clear, present.
The window
On Windows, a window doesn't call us to report what happens to it; it sends
; The parameters stay in their registers: rcx hwnd, edx msg, r8 wparam, r9
; lparam. Anything not handled goes to DefWindowProcA with all four still in
; place, so that call is a jump.
window_proc: proc(hwnd: HWND, umsg: UINT, wparam: WPARAM, lparam: LPARAM) -> LRESULT = {
cmp edx, WM_DESTROY
jne pass_on
sub rsp, 40 ; shadow space, and rsp back on 16: it was 8 off at entry
invoke(PostQuitMessage, 0)
add rsp, 40
xor eax, eax
ret
pass_on:
jmp DefWindowProcA
}
Every message gets the window it is for, a number saying which message it is, and two parameters whose meaning depends on the message. We react to exactly one, WM_DESTROY, which arrives when the window is being destroyed: we ask for the program to end, which we come back to in the render loop, and return 0 in rax (xor eax, eax clears all of rax, since writing a 32-bit register zeroes the top half). Everything else goes to
proc is documentation, and the prototype C sees; the names are not operands. Win64 passes the four arguments in rcx, rdx, r8 and r9, and the code uses the registers: the message number is 32 bits, so it is compared in edx. Two things follow from the registers being left alone. The call to jmp, a rax. And the one path that makes a call of its own sets up a sub rsp, 40: 32 bytes of shadow space for the callee, plus 8 to put rsp back on a multiple of 16, which the call that brought us here left 8 off. Hello Triangle goes through frames in full. x64 Windows has a single calling convention, so a procedure that Windows calls back needs nothing special.
Before a window can be made, Windows wants a
; win32 state. What is known now is written now; the rest is stored by main.
wc: WNDCLASSEXA = {
.cbSize = sizeof(WNDCLASSEXA),
.lpfnWndProc = window_proc&,
.lpszClassName = "LearnD3D11",
}
and
call SetProcessDPIAware
invoke(GetModuleHandleA, 0)
mov wc.hInstance, rax
invoke(LoadCursorA, 0, IDC_ARROW)
mov wc.hCursor, rax
invoke(RegisterClassExA, wc&)
The class records the window procedure, the module it lives in (our executable, from EX version of the structure starts with its own size, cbSize, which Windows checks. Before any of that,
sizeof(WNDCLASSEXA), the address of our procedure, window_proc& (the & after a name is its address), and a string, which becomes the address of its text. An operand that names a field, mov wc.hInstance, rax, gets its offset and size from the type, and the build checks the offset against the C header. And invoke(RegisterClassExA, wc&) passes the structure's address, where C would write &wc; includes/calls.rasm, moves its arguments into rcx, rdx, r8, r9 (and the stack beyond four) and makes the call, and nothing else. A call with no arguments is a plain call. IDC_ARROW is spelled MAKEINTRESOURCE(32512) in windows.h, a macro that looks like a call and that rasm does not evaluate, so the lesson defines it as the number: #define IDC_ARROW 32512.
Now the window itself:
#define WINDOW_STYLE (WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME | WS_MAXIMIZEBOX))
; ...
rect: RECT = { .right = SCR_WIDTH, .bottom = SCR_HEIGHT }
window: HWND = {}
; ...
invoke(AdjustWindowRect, rect&, WINDOW_STYLE, 0)
mov ebx, rect.right
sub ebx, rect.left
mov esi, rect.bottom
sub esi, rect.top
invoke(CreateWindowExA, 0, wc.lpszClassName, "LearnD3D11", WINDOW_STYLE | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rbx, rsi, 0, 0,
wc.hInstance, 0)
test rax, rax
jnz window_created
invoke(print, "Failed to create the window\n")
invoke(ExitProcess, 1)
window_created:
mov window, rax
WS_OVERLAPPEDWINDOW is the usual top-level window, with a title bar, a border and the minimise, maximise and close buttons. We remove two parts of it: the thick frame that lets the user resize the window, and the maximise button. Our window has a fixed size, for a reason we will see shortly.
The size we pass to
A few things are assembly's own. The style is a constant expression, worked out before the program runs: &, ~ and | are C's operators, and WINDOW_STYLE | WS_VISIBLE in the argument list is a single number. The rectangle starts out as 1280 by 720, from its initialiser. The width and height are computed into ebx and esi before the call, because rbx and rsi are registers a procedure must give back as it found them, so
main: proc() -> i32 = {
push rbx
push rsi
sub rsp, 104 ; 12-argument calls: 32 shadow + 8 * 8, plus 8 to land on 16
This is rsp ends on 16. A failed
The device and the swap chain
LearnOpenGL at this point creates an OpenGL context, makes it current, and asks GLAD to load the OpenGL functions. Our counterpart is a single call that creates all three objects from the Direct3D 11 chapter: the device, the immediate context and the swap chain. The swap chain needs a description first, and it too is all known in advance, except for the window:
swap_desc: DXGI_SWAP_CHAIN_DESC = {
.BufferDesc = {
.Width = SCR_WIDTH,
.Height = SCR_HEIGHT,
.Format = DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM,
},
.SampleDesc = { .Count = 1 },
.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT,
.BufferCount = 2,
.Windowed = 1,
.SwapEffect = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_DISCARD,
}
; ...
mov window, rax
mov swap_desc.OutputWindow, rax
A field that is itself a structure gets an initialiser of its own, in braces, and in code is reached with a second dot, as in swap_desc.BufferDesc.Height. The fields have their real names, the ones in Microsoft's documentation. An enum member is written with its enum in front, DXGI_FORMAT.DXGI_FORMAT_R8G8B8A8_UNORM; a plain #define of the headers, such as DXGI_USAGE_RENDER_TARGET_OUTPUT, is written as it is.
A swap chain is a small set of images, its
- The same size as the client area, with four 8-bit channels per pixel: red, green, blue and alpha. UNORM means each channel's integer 0..255 is read as a number from 0.0 to 1.0.
- One sample per pixel, so no multisampling. Multisampled rendering is done differently in Direct3D 11 and gets its own chapter, Anti Aliasing.
- Used as render target output, which means we will draw into them.
- Two buffers, shown in our window, in a window rather than full screen.
- The
flip model of presentation, DXGI_SWAP_EFFECT_FLIP_DISCARD. Windows' compositor shows our finished buffer directly instead of copying it, and "discard" means we make no assumptions about what a buffer contains after it has been shown. We clear it every frame anyway.
With that, we create everything:
feature_level: D3D_FEATURE_LEVEL = D3D_FEATURE_LEVEL.D3D_FEATURE_LEVEL_11_0
swap_chain: *IDXGISwapChain = {}
device: *ID3D11Device = {}
context: *ID3D11DeviceContext = {}
; ...
invoke(D3D11CreateDeviceAndSwapChain, 0, D3D_DRIVER_TYPE.D3D_DRIVER_TYPE_HARDWARE, 0, 0, feature_level&, 1, D3D11_SDK_VERSION,
swap_desc&, swap_chain&, device&, 0, context&)
test eax, eax
jns device_created
invoke(print, "Failed to create the D3D11 device\n")
invoke(ExitProcess, 1)
device_created:
Taking the arguments in order: 0 for the adapter means the system's default GPU; D3D_DRIVER_TYPE_HARDWARE asks for a real GPU rather than a software rasterizer; the next 0 is the software module, which only applies to software drivers; the one after it means no creation flags. Then comes the list of feature levels we accept, which is just 11_0, and its length, and D3D11_SDK_VERSION, which lets the runtime check that it matches the headers we compiled against. The rest are our swap chain description and the addresses where the swap chain, the device, the feature level obtained (we pass 0, since we accept only one) and the immediate context are written. The swap chain, device and context are three pointer globals, typed with their interfaces, each holding the object once the call returns. A call's arguments may continue on the next line.
Like most Direct3D functions, it returns an HRESULT in eax, negative on failure, and this is one call where failure is worth checking: on a machine without a feature level 11_0 GPU it is the first thing to go wrong. test eax, eax sets the sign flag from the top bit, and jns jumps past the error when it is clear.
The render target view
We have a swap chain, but we cannot draw into it yet. The pipeline draws into resources only through views (see the Direct3D 11 chapter), so we fetch the swap chain's back buffer as a texture and create a
vcall(swap_chain, IDXGISwapChainVtbl.GetBuffer, 0, IID_ID3D11Texture2D&, backbuffer&)
vcall(device, ID3D11DeviceVtbl.CreateRenderTargetView, backbuffer, 0, backbuffer_rtv&)
These are our first COM calls, made with IDXGISwapChainVtbl.GetBuffer, then the arguments that follow the hidden this. dxguid.lib, and it writes the pointer into backbuffer. C needs a cast on each call, to an untyped pointer and to the base interface ID3D11Resource; an argument register holds 64 bits whatever they mean, and there is nothing to cast. The 0 is an optional view description; without one, the view covers the whole texture in the texture's own format.
One view is enough for the life of the program, even though there are two buffers taking turns. In Direct3D 11, buffer 0 of a flip-model swap chain always refers to whichever buffer is currently the back buffer, and the runtime moves the view along with it after each present.
Viewport
OpenGL has to be told the size of the area it renders into, with hello_window.rasm doesn't set one yet. The next program declares one like this, and from Shaders on learn/window.rasm has the same global for every lesson:
viewport: D3D11_VIEWPORT = {
.Width = cast(SCR_WIDTH, f32), ; folded here, as C folds it; no conversion runs
.Height = cast(SCR_HEIGHT, f32),
.MaxDepth = 1.0,
}
The viewport's fields are floats. Since the size is a constant, the conversion from integer to float is done when the program is built, by the C compiler, which folds cast(SCR_WIDTH, f32) to 1280.0, and the global starts out holding the finished values; no instruction runs for it. MinDepth, TopLeftX and TopLeftY are left at zero. It is bound every frame with vcall(context, ID3D11DeviceContextVtbl.RSSetViewports, 1, viewport&).
The viewport is the rectangle of the render target that the final, normalized coordinates are mapped onto: here, the whole window, starting at its top-left corner, with depth values from 0 to 1. A point that comes out of the pipeline at \((x, y)\), with both running from -1 to 1, lands on pixel
\[ x_{\text{pixel}} = \frac{x + 1}{2} \cdot \text{Width}, \qquad y_{\text{pixel}} = \frac{1 - y}{2} \cdot \text{Height} \]The \(1 - y\) is the one difference from OpenGL here. Direct3D counts pixel rows from the top of the window, OpenGL from the bottom, so in Direct3D a larger \(y\) means a smaller row number. Up is still up on screen: the point \((-0.5, 0.5)\) is in the upper left quarter in both APIs, and in our 1280 by 720 window it is the pixel \((320, 180)\), counted from the top-left corner.
LearnOpenGL also registers a callback to update the viewport whenever the window is resized. We have none, because our window cannot be resized. Resizing in Direct3D means more than a new viewport: the swap chain's buffers have to be resized, and every view of them, and every render target the size of the window (later chapters have several), has to be recreated. A fixed size keeps all of that out of the lessons.
The render loop
We don't want to draw one picture and quit. The program runs a loop, the
running: b32 = 1
; ...
render_loop:
pump:
invoke(PeekMessageA, msg&, 0, 0, 0, PM_REMOVE)
test eax, eax
jz pumped
cmp msg.message, WM_QUIT
jne not_quit
mov running, 0
not_quit:
invoke(TranslateMessage, msg&)
invoke(DispatchMessageA, msg&)
jmp pump
pumped:
cmp running, 0
je render_loop_done
; input
; -----
call process_input
; render
; ------
vcall(context, ID3D11DeviceContextVtbl.ClearRenderTargetView, backbuffer_rtv, clear_color&)
; dxgi: show the image just drawn, waiting for the next vertical blank
; --------------------------------------------------------------------
vcall(swap_chain, IDXGISwapChainVtbl.Present, 1, 0)
jmp render_loop
render_loop_done:
; ExitProcess does not return, so there is no epilogue: rbx and rsi are
; never restored, and the 104 bytes are never given back.
invoke(ExitProcess, 0)
Assembly has no while: a loop is a label, a test, and a jump back. The outer loop runs from render_loop to the jmp render_loop at the bottom, and the inner one, from pump to jmp pump, runs until jz pumped leaves it. Labels are local to the procedure they are in, so every lesson can have its own render_loop, and every procedure its own done. cmp msg.message, WM_QUIT needs no size: the field's type says it is 32 bits, as the type of running, a 32-bit boolean, says it is.
It has three parts. First the
Then input and rendering, which the next sections fill in. And last,
Double buffering
If we drew straight into the image the monitor was showing, it would show our work in progress: half-cleared frames, objects drawn but not yet covered by the ones in front, and flicker. The swap chain avoids this with two buffers. The
The first argument to glfwSwapInterval(1). The second argument holds flags, none here.
One last thing
The loop runs while running is set, and it is cleared by one message: WM_QUIT. Here is how that message comes about. Clicking the close button sends the window WM_CLOSE; our procedure passes it to invoke(ExitProcess, 0). As the comment above it says, rbx and rsi or gives back the 104 bytes, because nothing after it would notice.
LearnOpenGL ends with
Build it (python build.py hello_window, as in the previous chapter) and run build\hello_window.exe, and you should see this:
A plain teal rectangle: if that's what you got, everything is working. The colour comes from the clear we skipped over, which is the last part of this chapter, just after input.
Input
The Escape key should close the window. LearnOpenGL asks GLFW with test ax, ax sets the sign flag from that bit, and jns skips ahead when it is clear.
; process all input: ask Windows whether relevant keys are down this frame and react accordingly
; ----------------------------------------------------------------------------------------------
; The top bit of GetAsyncKeyState is set while a key is held, which makes the
; SHORT negative.
process_input: proc() = {
sub rsp, 40 ; 32 shadow, and rsp back on 16
invoke(GetAsyncKeyState, VK_ESCAPE)
test ax, ax
jns done
invoke(DestroyWindow, window)
done:
add rsp, 40
ret
}
When Escape is down, we call
There is one catch. learn/window.rasm, which first checks that our window is the one in front, which is what
; ecx: virtual key -> eax: 1 while it is held. The top bit of
; GetAsyncKeyState is set while a key is down, which makes the SHORT negative.
key_down: proc(vkey: u32) -> b32 = {
push rbx
sub rsp, 32 ; 32 shadow; entry 8 + push 8 + 32 lands on 16
mov ebx, ecx
call GetForegroundWindow
cmp rax, window
jne up
invoke(GetAsyncKeyState, rbx)
test ax, ax
jns up
mov eax, 1
jmp done
up:
xor eax, eax
done:
add rsp, 32
pop rbx
ret
}
The key arrives in ecx, which the first call may overwrite, so it is kept in rbx, which survives calls; and since rbx is ours only on loan, it is pushed first and popped last. With that push, 32 bytes are already enough to bring rsp back on 16.
Polling like this suits keys held down, like movement keys later on. Keys that should do something once per press, like switching modes with Tab, come in as WM_KEYDOWN messages to the window procedure instead; we will see that in the next lesson.
Rendering
Each frame we want to start from a clean picture; otherwise we would see whatever was in the buffer before (with the flip model's discard, that could be anything). So the render part of the loop clears the back buffer to a colour of our choice:
clear_color: [4]const f32 = { 0.2, 0.3, 0.3, 1.0 }
; ...
vcall(context, ID3D11DeviceContextVtbl.ClearRenderTargetView, backbuffer_rtv, clear_color&)
The colour is four floats, red, green and blue (0.2, 0.3, 0.3 is a dark blue-green) and alpha, which is 1, fully opaque. The method wants their address, so they are data: [4]const f32 is an array of four 32-bit floats that nothing writes, placed in the read-only data section, and clear_color& is its address. Compare this with OpenGL, which sets the clear colour as a piece of state with
Everything we draw in later chapters goes between this clear and the
Additional resources
- Your first Windows program: Microsoft's introduction to window classes, window procedures and the message loop.
- DXGI flip model: how flip-model swap chains present, and why they are preferred.
- D3D11CreateDeviceAndSwapChain: the reference for every parameter used above.
- High DPI desktop application development: what
SetProcessDPIAware opts into. - LearnOpenGL's Hello Window: the same program with GLFW.
Exercises
- Make the clear colour change over time.
learn/window.rasmhas aget_time procedure built onQueryPerformanceFrequency andQueryPerformanceCounter , which the shaders lesson uses; write its like intohello_window.rasm, importmath.rasmforsinf (angle inxmm0, result inxmm0), and drive one of the colour channels with it. clear_color isconst, so the colour needs a writable home instead,[4]f32without theconst, into which amovsscan store a channel. - Change the sync interval passed to
Present from 1 to 0. Count frames, and once a second show the count in the title bar withSetWindowTextA , after formatting it into a buffer withwsprintfA . Compare it with the count at interval 1. - Make the space bar close the window too. Then make it do something that should happen once per press, such as toggling between two clear colours, and see why polling
GetAsyncKeyState every frame is the wrong tool for that.