-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
366 lines (310 loc) · 8.39 KB
/
main.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
package main
import (
"fmt"
"log"
"math"
"runtime"
"strings"
"sync"
"time"
"github.com/go-gl/mathgl/mgl32"
"github.com/go-gl/gl/v4.1-core/gl"
"github.com/go-gl/glfw/v3.2/glfw"
)
func init() {
// This is needed to arrange that main() runs on main thread.
// See documentation for functions that are only allowed to be called from the main thread.
runtime.LockOSThread()
}
type forceFunc func(x, v mgl32.Vec2) mgl32.Vec2
func main() {
err := glfw.Init()
if err != nil {
panic(err)
}
defer glfw.Terminate()
// configure window options
glfw.WindowHint(glfw.Samples, 4)
glfw.WindowHint(glfw.ContextVersionMinor, 2)
glfw.WindowHint(glfw.ContextVersionMajor, 3)
glfw.WindowHint(glfw.OpenGLForwardCompatible, gl.TRUE)
glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)
// create window
window, err := glfw.CreateWindow(1280, 720, "Testing", nil, nil)
if err != nil {
panic(err)
}
// make window context available for gl operations
window.MakeContextCurrent()
// configure window key input mode
window.SetInputMode(glfw.StickyKeysMode, glfw.True)
// init opengl
err = gl.Init()
if err != nil {
log.Fatal(err)
}
window.SetSizeCallback(func(w *glfw.Window, width int, height int) {
width, height = w.GetFramebufferSize()
size := width
if height < width {
size = height
}
gl.Viewport(int32(width-size)/2, int32(height-size)/2, int32(size), int32(size))
})
// compile shaders
program, err := newProgram(vertexshader, fragmentshader)
if err != nil {
log.Fatal(err)
}
// create vertex buffer
var vertexArrayID uint32
gl.GenVertexArrays(1, &vertexArrayID)
gl.BindVertexArray(vertexArrayID)
// init data for physics
points := make([]mgl32.Vec2, 200000)
for i := range points {
phi := 2 * math.Pi / float64(len(points)) * float64(i)
points[i][0] = float32(math.Cos(phi)) * .5
points[i][1] = float32(math.Sin(phi)) * .5
}
velocities := make([]mgl32.Vec2, len(points))
forceFuncs := make(chan forceFunc, 1)
// init slice for vertex data
gVertexBufferData := make([]float32, len(points)*24)
var gVertexBufferDataMutex sync.Mutex
// start physics
doPhysics := true
asyncPhysics(points, velocities, forceFuncs, gVertexBufferData, &gVertexBufferDataMutex, &doPhysics)
// init vertex buffer in gpu
var vertexbuffer uint32
gl.GenBuffers(1, &vertexbuffer)
gl.BindBuffer(gl.ARRAY_BUFFER, vertexbuffer)
lastupdate := time.Now()
for !window.ShouldClose() {
// record timing
diff := float32(time.Since(lastupdate)) / float32(time.Second)
lastupdate = time.Now()
window.SetTitle(fmt.Sprintf("Testing (%f FPS)", 1/diff))
// handle physics
x, y := window.GetCursorPos()
w, h := window.GetSize()
size := w
if h < size {
size = h
}
glX, glY := mgl32.ScreenToGLCoords(int(x)-(w-size)/2, int(y)-(h-size)/2, size, size)
glPos := mgl32.Vec2{glX, glY}
force := float32(0)
if window.GetMouseButton(glfw.MouseButtonLeft) == glfw.Press {
force = 1
} else if window.GetMouseButton(glfw.MouseButtonRight) == glfw.Press {
force = -1
} else if window.GetMouseButton(glfw.MouseButtonMiddle) == glfw.Press {
force = 3
}
select {
case forceFuncs <- func(x, v mgl32.Vec2) mgl32.Vec2 {
r := glPos.Sub(x).Len()
return glPos.Sub(x).Normalize().Mul(0.005 * force / ((r) + .01)).Add(v.Mul(-v.Len() * 300))
}:
default:
}
// reupdate buffer
gVertexBufferDataMutex.Lock()
gl.BufferData(gl.ARRAY_BUFFER, len(gVertexBufferData)*4, gl.Ptr(gVertexBufferData), gl.STATIC_DRAW)
gVertexBufferDataMutex.Unlock()
// clear canvas
gl.ClearColor(0.1, 0, .1, 0)
gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
// compile shader
gl.UseProgram(program)
// draw data from buffer
gl.EnableVertexAttribArray(0)
gl.BindBuffer(gl.ARRAY_BUFFER, vertexbuffer)
gl.VertexAttribPointer(0, 4, gl.FLOAT, false, 0, nil)
gl.DrawArrays(gl.TRIANGLES, 0, int32(len(gVertexBufferData)))
gl.DisableVertexAttribArray(0)
// show new image
window.SwapBuffers()
// handle window events
glfw.PollEvents()
if window.GetKey(glfw.KeyEscape) == glfw.Press {
window.SetShouldClose(true)
}
if window.GetKey(glfw.KeySpace) == glfw.Press {
doPhysics = false
} else {
doPhysics = true
}
}
}
var vertexshader = `
#version 330 core
/*#extension GL_ARB_enhanced_layouts : enable*/
layout(location=0) in vec4 pos;
/*layout(location=0,component=3) in float color;*/
out float c;
void main() {
gl_Position.xyz = pos.xyz;
gl_Position.w = 1.0;
c = pos.w;
}
` + "\x00"
var fragmentshader = `
#version 330 core
out vec3 color;
in float c;
void main() {
color = vec3(1-c,c,0);
}
` + "\x00"
func asyncPhysics(x, v []mgl32.Vec2, force chan forceFunc, data []float32, dataMutex *sync.Mutex, run *bool) {
t := time.Now()
go func() {
f := <-force
for {
dt := float32(time.Since(t)) / float32(time.Second)
fmt.Println("Physics!", (1 / dt))
t = time.Now()
if !*run {
time.Sleep(50 * time.Millisecond)
continue
}
physics(dt, x, v, f)
dataMutex.Lock()
createVertexBuffer(x, v, data)
dataMutex.Unlock()
select {
case f = <-force:
default:
}
}
}()
}
func physics(t float32, x, v []mgl32.Vec2, force forceFunc) {
if len(x) > len(v) {
panic("not enough velocities")
}
//var c int64 = -1
var wg sync.WaitGroup
chunk := len(x)/(runtime.NumCPU()*2) + 1
for s := 0; s < len(x); s += chunk {
start := s
end := start + chunk
if end > len(x) {
end = len(x)
}
wg.Add(1)
go func() {
defer wg.Done()
for i := start; i < end; i++ {
//i := atomic.AddInt64(&c, 1)
//if int(i) >= len(x) {
// return
//}
vOld := v[i]
v[i] = v[i].Add(force(x[i], v[i]).Mul(t))
x[i] = x[i].Add(vOld.Add(v[i]))
if x[i][0] < -1 {
x[i][0] = -2 - x[i][0]
v[i][0] = -v[i][0]
}
if x[i][0] > 1 {
x[i][0] = 2 - x[i][0]
v[i][0] = -v[i][0]
}
if x[i][1] < -1 {
x[i][1] = -2 - x[i][1]
v[i][1] = -v[i][1]
}
if x[i][1] > 1 {
x[i][1] = 2 - x[i][1]
v[i][1] = -v[i][1]
}
}
}()
}
wg.Wait()
}
func createVertexBuffer(in []mgl32.Vec2, v []mgl32.Vec2, out []float32) {
if len(out) < 24*len(in) {
panic("out to short")
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < len(in); i++ {
c := mgl32.Clamp(v[i].Len()*100, 0, 1)
for j := 0; j < 6; j++ {
out[24*i+4*j+2] = 0 // z-coordinate
out[24*i+4*j+3] = c // color
}
}
}()
wg.Add(1)
go func() {
defer wg.Done()
d := float32(.001)
for i := range in {
// 1st triangle
out[24*i+0] = -d + in[i][0] // x of 1st point
out[24*i+1] = d + in[i][1] // y of 1nd point
out[24*i+4*1+0] = -d + in[i][0] // 2nd point
out[24*i+4*1+1] = -d + in[i][1]
out[24*i+4*2+0] = d + in[i][0] // 3rd point
out[24*i+4*2+1] = -d + in[i][1]
// 2nd triangle -> counterpart to form a square
out[24*i+4*3+0] = d + in[i][0]
out[24*i+4*3+1] = -d + in[i][1]
out[24*i+4*4+0] = d + in[i][0]
out[24*i+4*4+1] = d + in[i][1]
out[24*i+4*5+0] = -d + in[i][0]
out[24*i+4*5+1] = d + in[i][1]
}
}()
wg.Wait()
}
func newProgram(vertexShaderSource, fragmentShaderSource string) (uint32, error) {
vertexShader, err := compileShader(vertexShaderSource, gl.VERTEX_SHADER)
if err != nil {
return 0, err
}
fragmentShader, err := compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER)
if err != nil {
return 0, err
}
program := gl.CreateProgram()
gl.AttachShader(program, vertexShader)
gl.AttachShader(program, fragmentShader)
gl.LinkProgram(program)
var status int32
gl.GetProgramiv(program, gl.LINK_STATUS, &status)
if status == gl.FALSE {
var logLength int32
gl.GetProgramiv(program, gl.INFO_LOG_LENGTH, &logLength)
log := strings.Repeat("\x00", int(logLength+1))
gl.GetProgramInfoLog(program, logLength, nil, gl.Str(log))
return 0, fmt.Errorf("failed to link program: %v", log)
}
gl.DeleteShader(vertexShader)
gl.DeleteShader(fragmentShader)
return program, nil
}
func compileShader(source string, shaderType uint32) (uint32, error) {
shader := gl.CreateShader(shaderType)
csources, free := gl.Strs(source)
gl.ShaderSource(shader, 1, csources, nil)
free()
gl.CompileShader(shader)
var status int32
gl.GetShaderiv(shader, gl.COMPILE_STATUS, &status)
if status == gl.FALSE {
var logLength int32
gl.GetShaderiv(shader, gl.INFO_LOG_LENGTH, &logLength)
log := strings.Repeat("\x00", int(logLength+1))
gl.GetShaderInfoLog(shader, logLength, nil, gl.Str(log))
return 0, fmt.Errorf("failed to compile %v: %v", source, log)
}
return shader, nil
}