forked from google/gxui
/
vertex_stream.go
91 lines (76 loc) · 1.94 KB
/
vertex_stream.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
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gl
import (
"fmt"
"math"
"reflect"
"github.com/goxjs/gl"
)
type vertexStream struct {
refCounted
name string
data []byte
ty shaderDataType
count int
}
type vertexStreamContext struct {
buffer gl.Buffer
}
func newVertexStream(name string, ty shaderDataType, data32 []float32) *vertexStream {
dataVal := reflect.ValueOf(data32)
dataLen := dataVal.Len()
if dataLen%ty.vectorElementCount() != 0 {
panic(fmt.Errorf("Incorrect multiple of elements. Got: %d, Requires multiple of %d",
dataLen, ty.vectorElementCount()))
}
if !ty.vectorElementType().isArrayOfType(data32) {
panic("Data is not of the specified type")
}
// HACK.
data := float32Bytes(data32...)
vs := &vertexStream{
name: name,
data: data,
ty: ty,
count: dataLen / ty.vectorElementCount(),
}
vs.init()
globalStats.vertexStreamCount.inc()
return vs
}
func (s *vertexStream) release() bool {
if !s.refCounted.release() {
return false
}
globalStats.vertexStreamCount.dec()
return true
}
func (s *vertexStream) newContext() *vertexStreamContext {
buffer := gl.CreateBuffer()
gl.BindBuffer(gl.ARRAY_BUFFER, buffer)
gl.BufferData(gl.ARRAY_BUFFER, s.data, gl.STATIC_DRAW)
gl.BindBuffer(gl.ARRAY_BUFFER, gl.Buffer{})
checkError()
return &vertexStreamContext{buffer}
}
func (c vertexStreamContext) bind() {
gl.BindBuffer(gl.ARRAY_BUFFER, c.buffer)
}
func (c *vertexStreamContext) destroy() {
gl.DeleteBuffer(c.buffer)
c.buffer = gl.Buffer{}
}
// float32Bytes returns the byte representation of float32 values in little endian byte order.
func float32Bytes(values ...float32) []byte {
b := make([]byte, 4*len(values))
for i, v := range values {
u := math.Float32bits(v)
b[4*i+0] = byte(u >> 0)
b[4*i+1] = byte(u >> 8)
b[4*i+2] = byte(u >> 16)
b[4*i+3] = byte(u >> 24)
}
return b
}