comparison examples/E01_hello_triangle.nim @ 594:512d33d314c4

add: correct swapchain destruction, update 1st example to be working
author Sam <sam@basx.dev>
date Thu, 20 Apr 2023 21:59:52 +0700
parents 21c276c0a968
children fdae5f50fa00
comparison
equal deleted inserted replaced
593:dfd554f8487a 594:512d33d314c4
1 import std/times
2 import std/strutils 1 import std/strutils
3 import std/enumerate 2 import std/enumerate
4 3
5 import semicongine 4 import semicongine
6 5
7 type
8 # define type of vertex
9 VertexDataA = object
10 position: PositionAttribute[Vec2]
11 color: ColorAttribute[Vec3]
12 6
13 var pipeline: RenderPipeline[VertexDataA, void] 7 const
8 vertexInput = @[
9 attr[Vec3f]("position", memoryLocation=VRAM),
10 attr[Vec3f]("color", memoryLocation=VRAM),
11 ]
12 vertexOutput = @[attr[Vec3f]("outcolor")]
13 fragOutput = @[attr[Vec4f]("color")]
14 vertexCode = compileGlslShader(
15 stage=VK_SHADER_STAGE_VERTEX_BIT,
16 inputs=vertexInput,
17 outputs=vertexOutput,
18 main="""gl_Position = vec4(position, 1.0); outcolor = color;"""
19 )
20 fragmentCode = compileGlslShader(
21 stage=VK_SHADER_STAGE_FRAGMENT_BIT,
22 inputs=vertexOutput,
23 outputs=fragOutput,
24 main="color = vec4(outcolor, 1);"
25 )
14 26
15 proc globalUpdate(engine: var Engine, t, dt: float32) = 27 var
16 discard 28 triangle = newEntity(
29 "triangle",
30 newMesh(
31 [newVec3f(-0.5, 0.5), newVec3f(0, -0.5), newVec3f(0.5, 0.5)],
32 [X, Y, Z],
33 )
34 )
35 myengine = initEngine("Hello triangle")
36 renderPass = myengine.gpuDevice.simpleForwardRenderPass(vertexCode, fragmentCode)
17 37
18 # vertex data (types must match the above VertexAttributes) 38 myengine.setRenderer(renderPass)
19 const 39 myengine.addScene(triangle, vertexInput)
20 triangle_pos = @[
21 Vec2([0.0'f32, -0.5'f32]),
22 Vec2([0.5'f32, 0.5'f32]),
23 Vec2([-0.5'f32, 0.5'f32]),
24 ]
25 triangle_color = @[
26 Vec3([1.0'f32, 0.0'f32, 0.0'f32]),
27 Vec3([0.0'f32, 1.0'f32, 0.0'f32]),
28 Vec3([0.0'f32, 0.0'f32, 1.0'f32]),
29 ]
30 40
31 when isMainModule: 41 while myengine.running and not myengine.keyWasPressed(Escape):
32 var myengine = igniteEngine("Hello triangle") 42 myengine.updateInputs()
43 myengine.renderScene(triangle)
33 44
34 # build a mesh 45 myengine.destroy()
35 var trianglemesh = new Mesh[VertexDataA, uint16]
36 trianglemesh.vertexData = VertexDataA(
37 position: PositionAttribute[Vec2](data: triangle_pos),
38 color: ColorAttribute[Vec3](data: triangle_color),
39 )
40 # build a single-object scene graph
41 var triangle = newThing("triangle", trianglemesh)
42
43 # upload data, prepare shaders, etc
44 const vertexShader = generateVertexShaderCode[VertexDataA, void]()
45 const fragmentShader = generateFragmentShaderCode[VertexDataA]()
46 pipeline = setupPipeline[VertexDataA, void, uint16](
47 myengine,
48 triangle,
49 vertexShader,
50 fragmentShader
51 )
52 # show something
53 myengine.run(pipeline, globalUpdate)
54 pipeline.trash()
55 myengine.trash()