-
Notifications
You must be signed in to change notification settings - Fork 0
/
scene.go
410 lines (339 loc) · 12.2 KB
/
scene.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package main
import (
"fmt"
"log"
"reflect"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/mathgl/mgl32"
"github.com/nicholasblaskey/stbi"
"github.com/qmuntal/gltf"
"github.com/qmuntal/gltf/modeler"
//"bufio"
//"os"
)
type Scene struct {
drawables []DrawableInstance
lights []Light
}
// These will be on the GPU, but first preload to CPU
type MeshGeometry struct {
vertArray [][3]float32
uvArray [][2]float32
normArray [][3]float32
indArray []uint32
}
type MeshGPUBufferIDs struct {
vaoID uint32
vertexBufferID uint32
normalBufferID uint32
uvBufferID uint32
indexBufferID uint32
lenIndices int32
}
type DrawableInstance struct {
mesh *MeshGPUBufferIDs
model *mgl32.Mat4
baseColorTextureID uint32
metallicRoughnessTextureID uint32
}
type Light struct {
dir mgl32.Vec3
color mgl32.Vec3
intensity float32
projView mgl32.Mat4
shMapWidth int32
shMapHeight int32
txrID uint32
txrUnit uint32
FBOID uint32
rerender bool
}
func initScene() Scene {
//folderPath := "/home/tokyo/blenderProj/cube77_03/"
//gltfFileToLoad := folderPath + "mycube077_embedded.gltf"
//folderPath := "/home/tokyo/sponzaGLTF/Sponza/glTF/"
//gltfFileToLoad := folderPath + "Sponza.gltf"
//folderPath := "/home/tokyo/boomboxGLTF/BoomBox/glTF/"
//gltfFileToLoad := folderPath + "BoomBox.gltf"
folderPath := "/home/tokyo/Sponza_GLTF2/"
gltfFileToLoad := folderPath + "Sponza.gltf"
//folderPath := "/home/tokyo/Cube/glTF/"
//gltfFileToLoad := folderPath + "Cube.gltf"
//folderPath := "/home/tokyo/Sponza_GLTF2_png/"
//gltfFileToLoad := folderPath + "Sponza.gltf"
//folderPath := "/home/tokyo/SciFiHelmet/glTF/"
//gltfFileToLoad := folderPath + "SciFiHelmet.gltf"
//folderPath := "/home/tokyo/Cube/glTF/"
//gltfFileToLoad := folderPath + "Cube.gltf"
doc, err := gltf.Open(gltfFileToLoad)
if err != nil {
log.Fatal(err)
}
/*
fmt.Println("Asset info:")
fmt.Print(doc.Asset)
fmt.Println("\nDone.")
*/
//Exercise: Get the bbox over all the assets to know the global scale
var loadedMeshPtrs []*MeshGPUBufferIDs
var loadedTextureBaseColorIDs []uint32
var loadedTextureMetallicRoughnessIDs []uint32
for it, primitive := range doc.Meshes[0].Primitives {
fmt.Printf("Primitive No.%d: ", it)
//One needs to pass three gates to enter Valhalla:
meshGeom, err := loadMeshFromGLTF(doc, primitive)
if err != nil {
continue
}
meshGPU := uploadMeshToGPU(meshGeom)
//fmt.Printf("meshGPU.lenIndices[%d] = %d.\n", it, meshGPU.lenIndices)
textureBaseColorID, err := loadTextureGLTFBaseColor(doc, primitive, folderPath)
if err != nil {
fmt.Println("Texture file not loaded, err =", err)
continue
}
//fmt.Println("Still OK here?")
textureMetallicRoughnessID, err := loadTextureGLTFMetallicRoughness(doc, primitive, folderPath)
if err != nil {
fmt.Println("Not loaded, err =", err)
continue
}
//We have all the loading data, now store it:
loadedMeshPtrs = append(loadedMeshPtrs, &meshGPU)
loadedTextureBaseColorIDs = append(loadedTextureBaseColorIDs, textureBaseColorID)
loadedTextureMetallicRoughnessIDs = append(loadedTextureMetallicRoughnessIDs, textureMetallicRoughnessID)
fmt.Printf("Loaded.\n")
//fmt.Print("Press 'Enter' to continue...")
//bufio.NewReader(os.Stdin).ReadBytes('\n')
}
//fmt.Printf("Loaded %d instances out of %d Sponza assets.\n", len(loadedMeshPtrs), len(doc.Meshes[0].Primitives))
mWorldCommon := mgl32.Ident4()
var instances []DrawableInstance
for i := 0; i < len(loadedMeshPtrs); i++ {
inst := DrawableInstance{
mesh: loadedMeshPtrs[i],
model: &mWorldCommon,
baseColorTextureID: loadedTextureBaseColorIDs[i],
metallicRoughnessTextureID: loadedTextureMetallicRoughnessIDs[i]}
instances = append(instances, inst)
}
var lights []Light
light0 := Light{
dir: mgl32.Vec3{0.1, -0.6, -1.0},
color: mgl32.Vec3{1.0 * 2.0, 0.8 * 2.0, 0.6 * 2.0},
intensity: 900.0,
shMapWidth: 4096,
shMapHeight: 4096,
rerender: true}
/*
light1 := Light{
dir: mgl32.Vec3{1, -0.25, -0.25},
color: mgl32.Vec3{1.0 * 2.0, 0.8 * 2.0, 0.6 * 2.0},
intensity: 900.0,
shMapWidth: 4096,
shMapHeight: 4096,
rerender: true}
*/
light0.initShadowMap()
//light1.initShadowMap()
//lights = append(lights, light0, light1)
lights = append(lights, light0)
return Scene{drawables: instances, lights: lights}
}
func loadMeshFromGLTF(doc *gltf.Document, primitive *gltf.Primitive) (MeshGeometry, error) {
positionIndex := primitive.Attributes["POSITION"]
positionAccessor := doc.Accessors[positionIndex]
positions, err := modeler.ReadPosition(doc, positionAccessor, nil)
if err != nil {
log.Fatal(err)
}
/*
fmt.Println("Positions:")
fmt.Printf("%#v", positions)
fmt.Println("\nDone.")
*/
normalIndex := primitive.Attributes["NORMAL"]
normalAccessor := doc.Accessors[normalIndex]
normals, err := modeler.ReadNormal(doc, normalAccessor, nil)
if err != nil {
log.Fatal(err)
}
/*
fmt.Println("Normals:")
fmt.Printf("%#v", normals)
fmt.Println("\nDone.")
*/
uvIndex := primitive.Attributes["TEXCOORD_0"]
uvAccessor := doc.Accessors[uvIndex]
uvs, err := modeler.ReadTextureCoord(doc, uvAccessor, nil)
if err != nil {
log.Fatal(err)
}
/*
fmt.Println("uvs:")
fmt.Printf("%#v", uvs)
fmt.Println("\nDone.")
*/
indexIndex := *(primitive.Indices)
indexAccessor := doc.Accessors[indexIndex]
indices, err := modeler.ReadIndices(doc, indexAccessor, nil)
if err != nil {
log.Fatal(err)
}
/*
fmt.Println("Indices:")
fmt.Printf("%#v", indices)
fmt.Println("\nDone.")
*/
return MeshGeometry{positions, uvs, normals, indices}, nil
}
func uploadMeshToGPU(mshIN MeshGeometry) MeshGPUBufferIDs {
var mshOUT MeshGPUBufferIDs
mshOUT.lenIndices = int32(len(mshIN.indArray))
gl.GenVertexArrays(1, &mshOUT.vaoID)
gl.BindVertexArray(mshOUT.vaoID)
// Buffer for vertices
fmt.Printf("len(mshIN.vertArray): %v\n", len(mshIN.vertArray))
gl.GenBuffers(1, &mshOUT.vertexBufferID)
gl.BindBuffer(gl.ARRAY_BUFFER, mshOUT.vertexBufferID)
gl.BufferData(gl.ARRAY_BUFFER, len(mshIN.vertArray)*int(reflect.TypeOf(mshIN.vertArray).Elem().Size()),
gl.Ptr(mshIN.vertArray), gl.STATIC_DRAW)
// Buffer for uvs
fmt.Printf("len(mshIN.uvArray): %v\n", len(mshIN.uvArray))
if len(mshIN.uvArray) > 0 {
gl.GenBuffers(1, &mshOUT.uvBufferID)
gl.BindBuffer(gl.ARRAY_BUFFER, mshOUT.uvBufferID)
gl.BufferData(gl.ARRAY_BUFFER, len(mshIN.uvArray)*int(reflect.TypeOf(mshIN.uvArray).Elem().Size()),
gl.Ptr(mshIN.uvArray), gl.STATIC_DRAW)
}
// Buffer for normals
fmt.Printf("len(mshIN.normArray): %v\n", len(mshIN.normArray))
if len(mshIN.normArray) > 0 {
gl.GenBuffers(1, &mshOUT.normalBufferID)
gl.BindBuffer(gl.ARRAY_BUFFER, mshOUT.normalBufferID)
gl.BufferData(gl.ARRAY_BUFFER, len(mshIN.normArray)*int(reflect.TypeOf(mshIN.normArray).Elem().Size()),
gl.Ptr(mshIN.normArray), gl.STATIC_DRAW)
}
fmt.Printf("len(mshIN.indArray): %v\n", len(mshIN.indArray))
// Buffer for vertex indecies
gl.GenBuffers(1, &mshOUT.indexBufferID)
gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, mshOUT.indexBufferID)
gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(mshIN.indArray)*int(reflect.TypeOf(mshIN.indArray).Elem().Size()),
gl.Ptr(mshIN.indArray), gl.STATIC_DRAW)
/*
Two things to note here:
Danger-1
There was a bug here which I located only with the renderdoc by inspecting a cube.
indArray initially was of type uint which takes 8 bytes, not 4.
However, the function gl.BufferData works correctly only with 4-byte sized ints (uint32).
It's very hard to see this as underneath it's just void* and bytenumber so you can pass any types.
Set indArray as uint and all you would get is a a black screen without any compiler or glcheck errors.
//indArray := []uint{0 1 2 1 3 2} would get uploaded as {0 0 1 0 2 0} wrongly bypassing any checks.
Danger-2
len and Elem is needed here as the direct .Size() on a slice does not produce the correct size in bytes.
*/
return mshOUT
}
func loadTextureGLTFBaseColor(doc *gltf.Document, primitive *gltf.Primitive, folderPath string) (uint32, error) {
materialIndex := *(primitive.Material)
material := doc.Materials[materialIndex]
intermediateStruct := *(material.PBRMetallicRoughness)
textureInfo := *(intermediateStruct.BaseColorTexture)
textureIndex := textureInfo.Index
texture := doc.Textures[textureIndex]
imageIndex := *(texture.Source)
image := doc.Images[imageIndex]
textureFileToLoad := folderPath + image.URI
/*
fmt.Println("Texture file:")
fmt.Printf("%#v", textureFileToLoad)
fmt.Println("\nDone.")
*/
flipVertical := false
desiredChannels := 0 // leave 0 for it to decide
data, width, height, nChannels, cleanup, err := stbi.Load(textureFileToLoad, flipVertical, desiredChannels)
fmt.Println("width=", width, "height=", height, "nchannels=", nChannels)
check(err)
defer cleanup()
var textureID uint32
gl.GenTextures(1, &textureID)
gl.BindTexture(gl.TEXTURE_2D, textureID)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
if nChannels == 3 {
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.SRGB, int32(width), int32(height), 0,
gl.RGB, gl.UNSIGNED_BYTE, data)
}
if nChannels == 4 {
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.SRGB_ALPHA, int32(width), int32(height), 0,
gl.RGBA, gl.UNSIGNED_BYTE, data)
}
if nChannels != 3 && nChannels != 4 {
return 0, fmt.Errorf("3 or 4 nChannels required, received %v", nChannels)
}
gl.BindTexture(gl.TEXTURE_2D, 0)
return textureID, nil
}
func loadTextureGLTFMetallicRoughness(doc *gltf.Document, primitive *gltf.Primitive, folderPath string) (uint32, error) {
materialIndex := *(primitive.Material)
material := doc.Materials[materialIndex]
intermediateStruct := *(material.PBRMetallicRoughness)
//This works as the struct field under the check is a pointer, otherwise one would need some reflection?!
if intermediateStruct.MetallicRoughnessTexture == nil {
return 0, fmt.Errorf("Check %s, its MetallicRoughnessTexture field does not exist in .gltf.", material.Name)
}
textureInfo := *(intermediateStruct.MetallicRoughnessTexture)
textureIndex := textureInfo.Index
texture := doc.Textures[textureIndex]
imageIndex := *(texture.Source)
image := doc.Images[imageIndex]
textureFileToLoad := folderPath + image.URI
/*
fmt.Println("Texture file:")
fmt.Printf("%#v", textureFileToLoad)
fmt.Println("\nDone.")
*/
flipVertical := false
desiredChannels := 0 // leave 0 for it to decide
data, width, height, nChannels, cleanup, err := stbi.Load(textureFileToLoad, flipVertical, desiredChannels)
//fmt.Println("width=", width, "height=", height, "nchannels=", nChannels)
check(err)
defer cleanup()
var textureID uint32
gl.GenTextures(1, &textureID)
gl.BindTexture(gl.TEXTURE_2D, textureID)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
if nChannels == 3 {
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.SRGB, int32(width), int32(height), 0,
gl.RGB, gl.UNSIGNED_BYTE, data)
}
if nChannels == 4 {
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.SRGB_ALPHA, int32(width), int32(height), 0,
gl.RGBA, gl.UNSIGNED_BYTE, data)
}
if nChannels != 3 && nChannels != 4 {
return 0, fmt.Errorf("3 or 4 nChannels required, received %v", nChannels)
}
gl.BindTexture(gl.TEXTURE_2D, 0)
return textureID, nil
}
// Fill in texture and framebuffer IDs
func (lht *Light) initShadowMap() {
gl.GenTextures(1, &(lht.txrID))
// Init shadow map textures
gl.BindTexture(gl.TEXTURE_2D, lht.txrID)
gl.TexImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, lht.shMapWidth, lht.shMapHeight,
0, gl.DEPTH_COMPONENT, gl.FLOAT, nil)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT)
gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT)
// Init FBO
gl.GenFramebuffers(1, &(lht.FBOID))
gl.BindFramebuffer(gl.FRAMEBUFFER, lht.FBOID)
gl.FramebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, lht.txrID, 0)
gl.ReadBuffer(gl.NONE) //No color texture will be used
gl.DrawBuffer(gl.NONE) //No color texture will be used
gl.BindFramebuffer(gl.FRAMEBUFFER, 0)
}