metal/minimal_sdl2 macOS

Code

objc_metal_with_sdl.odin ¶
99 linesSource

1package objc_test
2
3import NS  "core:sys/darwin/Foundation"
4import MTL "vendor:darwin/Metal"
5import CA  "vendor:darwin/QuartzCore"
6	
7import SDL "vendor:sdl2"
8
9import "core:fmt"
10
11main :: proc() {
12	SDL.SetHint(SDL.HINT_RENDER_DRIVER, "metal")
13	SDL.setenv("METAL_DEVICE_WRAPPER_TYPE", "1", 0)
14	SDL.Init({.VIDEO})
15	defer SDL.Quit()
16
17	window := SDL.CreateWindow("SDL Metal", 
18		SDL.WINDOWPOS_CENTERED, SDL.WINDOWPOS_CENTERED, 
19		854, 480, 
20		SDL.WINDOW_ALLOW_HIGHDPI|SDL.WINDOW_HIDDEN,
21	)
22	defer SDL.DestroyWindow(window)
23
24	window_system_info: SDL.SysWMinfo
25	SDL.GetVersion(&window_system_info.version)
26	SDL.GetWindowWMInfo(window, &window_system_info)
27	assert(window_system_info.subsystem == .COCOA)
28	fmt.println(window_system_info)
29
30	swapchain: ^CA.MetalLayer
31	device: ^MTL.Device
32	when true {
33		native_window := (^NS.Window)(window_system_info.info.cocoa.window)
34
35		device = MTL.CreateSystemDefaultDevice()
36
37		name := device->name()->odinString()
38		fmt.println(name)
39
40		swapchain = CA.MetalLayer.layer()
41		swapchain->setDevice(device)
42		swapchain->setPixelFormat(.BGRA8Unorm_sRGB)
43		swapchain->setFramebufferOnly(true)
44		swapchain->setFrame(native_window->frame())
45
46		// native_window->addSublayer(swapchain)
47		native_window->contentView()->setLayer(swapchain)
48		native_window->setOpaque(true)
49		native_window->setBackgroundColor(nil)
50	} else {
51		renderer := SDL.CreateRenderer(window, -1, SDL.RENDERER_PRESENTVSYNC)
52		defer SDL.DestroyRenderer(renderer)
53
54		swapchain = (^CA.MetalLayer)(SDL.RenderGetMetalLayer(renderer))
55		device = swapchain->device()
56	}
57
58	command_queue := device->newCommandQueue()
59
60	SDL.ShowWindow(window)
61
62	color := MTL.ClearColor{0.5, 0.7, 1.0, 1.0}
63
64	quit := false
65
66	for !quit {
67		for e: SDL.Event; SDL.PollEvent(&e); {
68			#partial switch e.type {
69			case .QUIT: quit = true
70			case .KEYDOWN:
71				if e.key.keysym.sym == .ESCAPE {
72					quit = true
73				}
74			}
75		}
76
77		NS.scoped_autoreleasepool()
78
79		drawable := swapchain->nextDrawable()
80		assert(drawable != nil)
81
82		pass := MTL.RenderPassDescriptor.renderPassDescriptor()
83		color_attachment := pass->colorAttachments()->object(0)
84		assert(color_attachment != nil)
85		color_attachment->setClearColor(color)
86		color_attachment->setLoadAction(.Clear)
87		color_attachment->setStoreAction(.Store)
88		color_attachment->setTexture(drawable->texture())
89
90		
91		command_buffer := command_queue->commandBuffer()
92		encoder := command_buffer->renderCommandEncoderWithDescriptor(pass)
93		// ...
94		encoder->endEncoding()
95
96		command_buffer->presentDrawable(drawable)
97		command_buffer->commit()
98	}
99}

Declarations Used 28