Debian Codegraph @

shiny/example/fluid/main.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build example
6 // +build example
7
8 //
9 // This build tag means that "go install golang.org/x/exp/shiny/..." doesn't
10 // install this example program. Use "go run main.go" to run it or "go install
11 // -tags=example" to install it.
12
13 // Fluid is a fluid dynamics simulator. It is based on Jos Stam, "Real-Time
14 // Fluid Dynamics for Games", Proceedings of the Game Developer Conference,
15 // March 2003. See
16 // http://www.dgp.toronto.edu/people/stam/reality/Research/pub.html
17 package main
18
19 import (
20 "image"
21 "image/color"
22 "image/draw"
23 "log"
24 "sync"
25 "time"
26
27 "golang.org/x/exp/shiny/driver"
28 "golang.org/x/exp/shiny/screen"
29 "golang.org/x/mobile/event/lifecycle"
30 "golang.org/x/mobile/event/mouse"
31 "golang.org/x/mobile/event/paint"
32 "golang.org/x/mobile/event/size"
33 )
34
35 const (
36 N = 128 // The grid of cells has size NxN.
37
38 tickDuration = time.Second / 60
39
40 // These remaining numbers have magic values, determined by trial and error
41 // to look good, rather than being derived from first principles.
42 iterations = 20
43 dt = 0.1
44 diff = 0
45 visc = 0
46 force = 5
47 source = 20
48 fade = 0.89
49 )
50
51 func main() {
52 driver.Main(func(s screen.Screen) {
53 w, err := s.NewWindow(&screen.NewWindowOptions{
54 Title: "Fluid Shiny Example",
55 })
56 if err != nil {
57 log.Fatal(err)
58 }
59 buf, tex := screen.Buffer(nil), screen.Texture(nil)
60 defer func() {
61 if buf != nil {
62 tex.Release()
63 buf.Release()
64 }
65 w.Release()
66 }()
67
68 go simulate(w)
69
70 var (
71 buttonDown bool
72 sz size.Event
73 )
74 for {
75 publish := false
76
77 switch e := w.NextEvent().(type) {
78 case lifecycle.Event:
79 if e.To == lifecycle.StageDead {
80 return
81 }
82
83 switch e.Crosses(lifecycle.StageVisible) {
84 case lifecycle.CrossOn:
85 pauseChan <- play
86 var err error
87 buf, err = s.NewBuffer(image.Point{N, N})
88 if err != nil {
89 log.Fatal(err)
90 }
91 tex, err = s.NewTexture(image.Point{N, N})
92 if err != nil {
93 log.Fatal(err)
94 }
95 tex.Fill(tex.Bounds(), color.White, draw.Src)
96
97 case lifecycle.CrossOff:
98 pauseChan <- pause
99 tex.Release()
100 tex = nil
101 buf.Release()
102 buf = nil
103 }
104
105 case mouse.Event:
106 if e.Button == mouse.ButtonLeft {
107 buttonDown = e.Direction == mouse.DirPress
108 }
109 if !buttonDown {
110 break
111 }
112 z := sz.Size()
113 x := int(e.X) * N / z.X
114 y := int(e.Y) * N / z.Y
115 if x < 0 || N <= x || y < 0 || N <= y {
116 break
117 }
118
119 shared.mu.Lock()
120 shared.mouseEvents = append(shared.mouseEvents, image.Point{x, y})
121 shared.mu.Unlock()
122
123 case paint.Event:
124 publish = buf != nil
125
126 case size.Event:
127 sz = e
128
129 case uploadEvent:
130 shared.mu.Lock()
131 if buf != nil {
132 copy(buf.RGBA().Pix, shared.pix)
133 publish = true
134 }
135 shared.uploadEventSent = false
136 shared.mu.Unlock()
137
138 if publish {
139 tex.Upload(image.Point{}, buf, buf.Bounds())
140 }
141
142 case error:
143 log.Print(e)
144 }
145
146 if publish {
147 w.Scale(sz.Bounds(), tex, tex.Bounds(), draw.Src, nil)
148 w.Publish()
149 }
150 }
151 })
152 }
153
154 const (
155 pause = false
156 play = true
157 )
158
159 // pauseChan lets the UI event goroutine pause and play the CPU-intensive
160 // simulation goroutine depending on whether the window is visible (e.g.
161 // minimized). 64 should be large enough, in typical use, so that the former
162 // doesn't ever block on the latter.
163 var pauseChan = make(chan bool, 64)
164
165 // uploadEvent signals that the shared pix slice should be uploaded to the
166 // screen.Texture via the screen.Buffer.
167 type uploadEvent struct{}
168
169 var shared = struct {
170 mu sync.Mutex
171 uploadEventSent bool
172 mouseEvents []image.Point
173 pix []byte
174 }{
175 pix: make([]byte, 4*N*N),
176 }
177
178 func simulate(q screen.EventDeque) {
179 var (
180 dens, densPrev array
181 u, uPrev array
182 v, vPrev array
183 xPrev, yPrev int
184 havePrevLoc bool
185 )
186
187 ticker := time.NewTicker(tickDuration)
188 var tickerC <-chan time.Time
189 for {
190 select {
191 case p := <-pauseChan:
192 if p == pause {
193 tickerC = nil
194 } else {
195 tickerC = ticker.C
196 }
197 continue
198 case <-tickerC:
199 }
200
201 shared.mu.Lock()
202 for _, p := range shared.mouseEvents {
203 dens[p.X+1][p.Y] = source
204 if havePrevLoc {
205 u[p.X+1][p.Y+1] = force * float32(p.X-xPrev)
206 v[p.X+1][p.Y+1] = force * float32(p.Y-yPrev)
207 }
208 xPrev, yPrev, havePrevLoc = p.X, p.Y, true
209 }
210 shared.mouseEvents = shared.mouseEvents[:0]
211 shared.mu.Unlock()
212
213 velStep(&u, &v, &uPrev, &vPrev)
214 densStep(&dens, &densPrev, &u, &v)
215
216 // This fade isn't part of Stam's GDC03 paper, but it looks nice.
217 for i := range dens {
218 for j := range dens[i] {
219 dens[i][j] *= fade
220 }
221 }
222
223 shared.mu.Lock()
224 for y := 0; y < N; y++ {
225 for x := 0; x < N; x++ {
226 d := int32(dens[x+1][y+1] * 0xff)
227 if d < 0 {
228 d = 0
229 } else if d > 0xff {
230 d = 0xff
231 }
232 v := 255 - uint8(d)
233 p := (N*y + x) * 4
234 shared.pix[p+0] = v
235 shared.pix[p+1] = v
236 shared.pix[p+2] = v
237 shared.pix[p+3] = 0xff
238 }
239 }
240 uploadEventSent := shared.uploadEventSent
241 shared.uploadEventSent = true
242 shared.mu.Unlock()
243
244 if !uploadEventSent {
245 q.Send(uploadEvent{})
246 }
247 }
248 }
249
250 // All of the remaining code more or less comes from Stam's GDC03 paper.
251
252 type array [N + 2][N + 2]float32
253
254 func addSource(x, s *array) {
255 for i := range x {
256 for j := range x[i] {
257 x[i][j] += dt * s[i][j]
258 }
259 }
260 }
261
262 func setBnd(b int, x *array) {
263 switch b {
264 case 0:
265 for i := 1; i <= N; i++ {
266 x[0+0][i] = +x[1][i]
267 x[N+1][i] = +x[N][i]
268 x[i][0+0] = +x[i][1]
269 x[i][N+1] = +x[i][N]
270 }
271 case 1:
272 for i := 1; i <= N; i++ {
273 x[0+0][i] = -x[1][i]
274 x[N+1][i] = -x[N][i]
275 x[i][0+0] = +x[i][1]
276 x[i][N+1] = +x[i][N]
277 }
278 case 2:
279 for i := 1; i <= N; i++ {
280 x[0+0][i] = +x[1][i]
281 x[N+1][i] = +x[N][i]
282 x[i][0+0] = -x[i][1]
283 x[i][N+1] = -x[i][N]
284 }
285 }
286 x[0+0][0+0] = 0.5 * (x[1][0+0] + x[0+0][1])
287 x[0+0][N+1] = 0.5 * (x[1][N+1] + x[0+0][N])
288 x[N+1][0+0] = 0.5 * (x[N][0+0] + x[N+1][1])
289 x[N+1][N+1] = 0.5 * (x[N][N+1] + x[N+1][N])
290 }
291
292 func linSolve(b int, x, x0 *array, a, c float32) {
293 // This if block isn't part of Stam's GDC03 paper, but it's a nice
294 // optimization when the diff diffusion parameter is zero.
295 if a == 0 && c == 1 {
296 for i := 1; i <= N; i++ {
297 for j := 1; j <= N; j++ {
298 x[i][j] = x0[i][j]
299 }
300 }
301 setBnd(b, x)
302 return
303 }
304
305 invC := 1 / c
306 for k := 0; k < iterations; k++ {
307 for i := 1; i <= N; i++ {
308 for j := 1; j <= N; j++ {
309 x[i][j] = (x0[i][j] + a*(x[i-1][j]+x[i+1][j]+x[i][j-1]+x[i][j+1])) * invC
310 }
311 }
312 setBnd(b, x)
313 }
314 }
315
316 func diffuse(b int, x, x0 *array, diff float32) {
317 a := dt * diff * N * N
318 linSolve(b, x, x0, a, 1+4*a)
319 }
320
321 func advect(b int, d, d0, u, v *array) {
322 const dt0 = dt * N
323 for i := 1; i <= N; i++ {
324 for j := 1; j <= N; j++ {
325 x := float32(i) - dt0*u[i][j]
326 if x < 0.5 {
327 x = 0.5
328 }
329 if x > N+0.5 {
330 x = N + 0.5
331 }
332 i0 := int(x)
333 i1 := i0 + 1
334
335 y := float32(j) - dt0*v[i][j]
336 if y < 0.5 {
337 y = 0.5
338 }
339 if y > N+0.5 {
340 y = N + 0.5
341 }
342 j0 := int(y)
343 j1 := j0 + 1
344
345 s1 := x - float32(i0)
346 s0 := 1 - s1
347 t1 := y - float32(j0)
348 t0 := 1 - t1
349 d[i][j] = s0*(t0*d0[i0][j0]+t1*d0[i0][j1]) + s1*(t0*d0[i1][j0]+t1*d0[i1][j1])
350 }
351 }
352 setBnd(b, d)
353 }
354
355 func project(u, v, p, div *array) {
356 for i := 1; i <= N; i++ {
357 for j := 1; j <= N; j++ {
358 div[i][j] = (u[i+1][j] - u[i-1][j] + v[i][j+1] - v[i][j-1]) / (-2 * N)
359 p[i][j] = 0
360 }
361 }
362 setBnd(0, div)
363 setBnd(0, p)
364 linSolve(0, p, div, 1, 4)
365 for i := 1; i <= N; i++ {
366 for j := 1; j <= N; j++ {
367 u[i][j] -= (N / 2) * (p[i+1][j+0] - p[i-1][j+0])
368 v[i][j] -= (N / 2) * (p[i+0][j+1] - p[i+0][j-1])
369 }
370 }
371 setBnd(1, u)
372 setBnd(2, v)
373 }
374
375 func velStep(u, v, u0, v0 *array) {
376 addSource(u, u0)
377 addSource(v, v0)
378 u0, u = u, u0
379 diffuse(1, u, u0, visc)
380 v0, v = v, v0
381 diffuse(2, v, v0, visc)
382 project(u, v, u0, v0)
383 u0, u = u, u0
384 v0, v = v, v0
385 advect(1, u, u0, u0, v0)
386 advect(2, v, v0, u0, v0)
387 project(u, v, u0, v0)
388 }
389
390 func densStep(x, x0, u, v *array) {
391 addSource(x, x0)
392 x0, x = x, x0
393 diffuse(0, x, x0, diff)
394 x0, x = x, x0
395 advect(0, x, x0, u, v)
396 }