1 //------------------------------------------------------------------------------
2 //  triangle.d
3 //
4 //  Vertex buffer, shader, pipeline state object.
5 //------------------------------------------------------------------------------
6 module examples.triangle;
7 
8 private:
9 
10 import sg = sokol.gfx;
11 import sapp = sokol.app;
12 import log = sokol.log;
13 import sglue = sokol.glue;
14 import shd = examples.shaders.triangle;
15 
16 extern (C):
17 @safe:
18 
19 struct State
20 {
21     sg.Bindings bind;
22     sg.Pipeline pip;
23 }
24 
25 static State state;
26 
27 static void init()
28 {
29     sg.Desc sg_desc = {
30         environment: sglue.environment(),
31         logger: {func: &log.slog_func},
32     };
33     sg.setup(sg_desc);
34 
35     // create vertex buffer with triangle vertices
36     float[21] vertices = [
37         // positions      colors
38         0.0, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0,
39         0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 1.0,
40         -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0,
41     ];
42     sg.BufferDesc buf_desc = {data: {ptr: vertices.ptr,
43     size: vertices.sizeof,}};
44     state.bind.vertex_buffers[0] = sg.makeBuffer(buf_desc);
45 
46     // create a shader and pipeline object
47     sg.PipelineDesc pip_desc = {
48         shader: sg.makeShader(shd.triangleShaderDesc(sg.queryBackend())),
49         layout: {
50             attrs: [
51                 shd.ATTR_TRIANGLE_POSITION: {format: sg.VertexFormat.Float3},
52                 shd.ATTR_TRIANGLE_COLOR0: {format: sg.VertexFormat.Float4},
53             ],
54         }
55     };
56     state.pip = sg.makePipeline(pip_desc);
57 }
58 
59 static void frame()
60 {
61     // default pass-action clears to grey
62     sg.Pass pass = {swapchain: sglue.swapchain()};
63     sg.beginPass(pass);
64     sg.applyPipeline(state.pip);
65     sg.applyBindings(state.bind);
66     sg.draw(0, 3, 1);
67     sg.endPass();
68     sg.commit();
69 }
70 
71 static void cleanup()
72 {
73     sg.shutdown();
74 }
75 
76 void main()
77 {
78     sapp.Desc runner = {
79         window_title: "triangle.d",
80         init_cb: &init,
81         frame_cb: &frame,
82         cleanup_cb: &cleanup,
83         width: 800,
84         height: 600,
85         icon: {sokol_default: true},
86         logger: {func: &log.func}
87     };
88     sapp.run(runner);
89 }