-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathrender.go
432 lines (400 loc) · 11.5 KB
/
render.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Copyright (c) 2019, The Emergent 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 netview
import (
"cmp"
"fmt"
"math"
"slices"
"cogentcore.org/core/base/errors"
"cogentcore.org/core/colors"
"cogentcore.org/core/math32"
"cogentcore.org/core/styles"
"cogentcore.org/core/tree"
"cogentcore.org/core/types"
"cogentcore.org/core/xyz"
"github.com/emer/emergent/v2/emer"
)
// UpdateLayers updates the layer display with any structural or
// current data changes. Very fast if no structural changes.
func (nv *NetView) UpdateLayers() {
sw := nv.SceneWidget()
se := sw.SceneXYZ()
if nv.Net == nil || nv.Net.NumLayers() == 0 {
se.DeleteChildren()
se.Meshes.Reset()
return
}
nb := nv.Net.AsEmer()
if nv.NeedsRebuild() {
se.Background = colors.Scheme.Background
}
nlay := nv.Net.NumLayers()
laysGp := se.ChildByName("Layers", 0).(*xyz.Group)
layConfig := tree.TypePlan{}
for li := range nlay {
ly := nv.Net.EmerLayer(li)
layConfig.Add(types.For[xyz.Group](), ly.Label())
}
if !tree.Update(laysGp, layConfig) && nv.layerNameSizeShown == nv.Options.LayerNameSize {
for li := range laysGp.Children {
ly := nv.Net.EmerLayer(li)
lmesh := errors.Log1(se.MeshByName(ly.Label()))
se.SetMesh(lmesh) // does update
}
if nv.hasPaths != nv.Options.Paths || nv.pathTypeShown != nv.Options.PathType ||
nv.pathWidthShown != nv.Options.PathWidth {
nv.UpdatePaths()
}
return
}
nv.layerNameSizeShown = nv.Options.LayerNameSize
gpConfig := tree.TypePlan{}
gpConfig.Add(types.For[LayObj](), "layer")
gpConfig.Add(types.For[LayName](), "name")
nmin, nmax := nb.MinPos, nb.MaxPos
nsz := nmax.Sub(nmin).Sub(math32.Vec3(1, 1, 0)).Max(math32.Vec3(1, 1, 1))
nsc := math32.Vec3(1.0/nsz.X, 1.0/nsz.Y, 1.0/nsz.Z)
szc := math32.Max(nsc.X, nsc.Y)
poff := math32.Vector3Scalar(0.5)
poff.Y = -0.5
for li, lgi := range laysGp.Children {
ly := nv.Net.EmerLayer(li)
lb := ly.AsEmer()
lmesh, _ := se.MeshByName(ly.Label())
if lmesh == nil {
NewLayMesh(se, nv, ly)
} else {
lmesh.(*LayMesh).Lay = ly // make sure
}
lg := lgi.(*xyz.Group)
gpConfig[1].Name = ly.Label() // text2d textures use obj name, so must be unique
tree.Update(lg, gpConfig)
lp := lb.Pos.Pos
lp.Y = -lp.Y // reverse direction
lp = lp.Sub(nmin).Mul(nsc).Sub(poff)
lg.Pose.Pos.Set(lp.X, lp.Z, lp.Y)
lg.Pose.Scale.Set(nsc.X*lb.Pos.Scale, szc, nsc.Y*lb.Pos.Scale)
lo := lg.Child(0).(*LayObj)
lo.Defaults()
lo.LayName = ly.Label()
lo.NetView = nv
lo.SetMeshName(ly.Label())
lo.Material.Color = colors.FromRGB(255, 100, 255)
lo.Material.Reflective = 8
lo.Material.Bright = 8
lo.Material.Shiny = 30
// note: would actually be better to NOT cull back so you can view underneath
// but then the front and back fight against each other, causing flickering
txt := lg.Child(1).(*LayName)
txt.Defaults()
txt.NetView = nv
txt.SetText(ly.Label())
txt.Pose.Scale = math32.Vector3Scalar(nv.Options.LayerNameSize).Div(lg.Pose.Scale)
txt.Styles.Background = colors.Uniform(colors.Transparent)
txt.Styles.Text.Align = styles.Start
txt.Styles.Text.AlignV = styles.Start
}
nv.UpdatePaths()
sw.XYZ.SetNeedsUpdate()
sw.NeedsRender()
}
// UpdatePaths updates the path display.
// Only called when layers have structural changes.
func (nv *NetView) UpdatePaths() {
sw := nv.SceneWidget()
se := sw.SceneXYZ()
nb := nv.Net.AsEmer()
nlay := nv.Net.NumLayers()
pathsGp := se.ChildByName("Paths", 0).(*xyz.Group)
pathsGp.DeleteChildren()
if !nv.Options.Paths {
nv.hasPaths = false
return
}
nv.hasPaths = true
nmin, nmax := nb.MinPos, nb.MaxPos
nsz := nmax.Sub(nmin).Sub(math32.Vec3(1, 1, 0)).Max(math32.Vec3(1, 1, 1))
nsc := math32.Vec3(1.0/nsz.X, 1.0/nsz.Y, 1.0/nsz.Z)
poff := math32.Vector3Scalar(0.5)
poff.Y = -0.5
lineWidth := nv.Options.PathWidth
// weight factors applied to distance for the different sides,
// to encourage / discourage choice of sides.
// In general the sides are preferred, and back is discouraged.
sideWeights := [4]float32{1.1, 1, 1, 1.1}
type pathData struct {
path emer.Path
sSide, rSide, cat int
sIdx, sN, rIdx, rN int // indexes and numbers for each side
sPos, rPos math32.Vector3
}
pdIdx := func(side, cat int) int {
return side*3 + cat
}
type layerData struct {
paths [12][]*pathData // by side * category
selfPaths []*pathData
}
layPaths := make([]layerData, nlay)
// 0 = forward, "left" side; 1 = lateral, "middle"; 2 = back, "right"
sideCat := func(rLayY, sLayY float32) int {
if rLayY < sLayY {
return 2
} else if rLayY == sLayY {
return 1
}
return 0
}
// returns layer position and size in normalized display coordinates (NDC)
// using the correct rendering coordinate system: X = X, Y <-> Z
layPosSize := func(lb *emer.LayerBase) (math32.Vector3, math32.Vector3) {
lp := lb.Pos.Pos
lp.Y = -lp.Y
lp = lp.Sub(nmin).Mul(nsc).Sub(poff)
lp.Y, lp.Z = lp.Z, lp.Y
dsz := lb.DisplaySize()
lsz := math32.Vector3{dsz.X * nsc.X, 0, dsz.Y * nsc.Y}
return lp, lsz
}
// F, L, R, B -- center of each side, z is negative; order favors front in a tie
sideMids := []math32.Vector3{{0.5, 0, 0}, {0, 0, -0.5}, {1, 0, -0.5}, {0.5, 0, -1}}
sideDims := []math32.Dims{math32.X, math32.Z, math32.Z, math32.X}
// returns the matrix
sideMtx := func(side int, prop float32) math32.Vector3 {
dim := sideDims[side]
smat := sideMids[side]
smat.SetDim(dim, prop)
if dim == math32.Z {
smat.Z *= -1
}
return smat
}
laySidePos := func(lb *emer.LayerBase, side, cat, idx, n int, off float32) math32.Vector3 {
prop := (float32(cat) / 3) + (float32(idx)+off)/float32(3*n)
pos, sz := layPosSize(lb)
mat := sideMtx(side, prop)
return pos.Add(sz.Mul(mat))
}
// returns the sending, recv positions of the path,
// for point at given index along side, cat
setPathPos := func(pd *pathData) {
pt := pd.path
sb := pt.SendLayer().AsEmer()
rb := pt.RecvLayer().AsEmer()
off := float32(0.4)
if rb.Index < sb.Index {
off = 0.6
}
pd.sPos = laySidePos(sb, pd.sSide, pd.cat, pd.sIdx, pd.sN, off)
pd.rPos = laySidePos(rb, pd.rSide, pd.cat, pd.rIdx, pd.rN, off)
return
}
// first pass: find the side to make connections on, based on shortest weighted length
for si := range nlay {
sl := nv.Net.EmerLayer(si)
sb := sl.AsEmer()
slayData := &layPaths[sb.Index]
sLayPos, _ := layPosSize(sb)
npt := sl.NumSendPaths()
for pi := range npt {
pt := sl.SendPath(pi)
if !nv.pathTypeNameMatch(pt) {
continue
}
rb := pt.RecvLayer().AsEmer()
if sb.Index == rb.Index { // self
slayData.selfPaths = append(slayData.selfPaths, &pathData{path: pt, cat: 1})
continue
}
minDist := float32(math.MaxFloat32)
var minData *pathData
for sSide := range 4 {
swt := sideWeights[sSide]
for rSide := range 4 {
rwt := sideWeights[rSide]
rLayPos, _ := layPosSize(rb)
cat := sideCat(rLayPos.Y, sLayPos.Y)
pd := &pathData{path: pt, sSide: sSide, rSide: rSide, cat: cat, sN: 1, rN: 1}
setPathPos(pd)
dist := pd.rPos.Sub(pd.sPos).Length() * swt * rwt
if dist < minDist {
minDist = dist
minData = pd
}
}
}
i := pdIdx(minData.sSide, minData.cat)
slayData.paths[i] = append(slayData.paths[i], minData)
rlayData := &layPaths[rb.Index]
i = pdIdx(minData.rSide, minData.cat)
rlayData.paths[i] = append(rlayData.paths[i], minData)
}
}
for li := range nlay {
ly := nv.Net.EmerLayer(li)
lb := ly.AsEmer()
layData := &layPaths[lb.Index]
for side := range 4 {
for cat := range 3 {
pidx := pdIdx(side, cat)
pths := layData.paths[pidx]
npt := len(pths)
if npt == 0 {
continue
}
for pi, pd := range pths {
if pd.path.RecvLayer() == ly {
pd.rIdx = pi
pd.rN = npt
} else {
pd.sIdx = pi
pd.sN = npt
}
}
}
}
}
// now we have the full set of data, sort positions
for range 10 { // 10 seems to get as much as 100 on complex networks
for li := range nlay {
ly := nv.Net.EmerLayer(li)
lb := ly.AsEmer()
layData := &layPaths[lb.Index]
for side := range 4 {
for cat := range 3 {
pidx := pdIdx(side, cat)
pths := layData.paths[pidx]
npt := len(pths)
if npt == 0 {
continue
}
for _, pd := range pths {
if pd.path.RecvLayer() == ly {
setPathPos(pd)
}
}
}
}
}
orderChanged := false
for li := range nlay {
ly := nv.Net.EmerLayer(li)
lb := ly.AsEmer()
layData := &layPaths[lb.Index]
for side := range 4 {
for cat := range 3 {
pidx := pdIdx(side, cat)
pths := layData.paths[pidx]
npt := len(pths)
if npt == 0 {
continue
}
slices.SortStableFunc(pths, func(a, b *pathData) int {
if a.path.RecvLayer() == ly {
return -cmp.Compare(a.sPos.Dim(sideDims[a.rSide]), b.sPos.Dim(sideDims[b.rSide]))
} else {
return -cmp.Compare(a.rPos.Dim(sideDims[a.sSide]), b.rPos.Dim(sideDims[b.sSide]))
}
})
for pi, pd := range pths {
if pd.path.RecvLayer() == ly {
if pi != pd.rIdx {
orderChanged = true
pd.rIdx = pi
}
} else {
if pi != pd.sIdx {
orderChanged = true
pd.sIdx = pi
}
}
}
}
}
}
if !orderChanged {
break
}
}
// final render
for li := range nlay {
ly := nv.Net.EmerLayer(li)
lb := ly.AsEmer()
layData := &layPaths[lb.Index]
for side := range 4 {
for cat := range 3 {
pidx := pdIdx(side, cat)
pths := layData.paths[pidx]
for _, pd := range pths {
if pd.path.RecvLayer() != ly {
continue
}
pt := pd.path
pb := pt.AsEmer()
clr := colors.Spaced(pt.TypeNumber())
xyz.NewArrow(se, pathsGp, pb.Name, pd.sPos, pd.rPos, lineWidth, clr, xyz.NoStartArrow, xyz.EndArrow, 4, .5, 4)
}
}
}
npt := len(layData.selfPaths)
if npt == 0 {
continue
}
// determine which side to put the self connections on.
// they will show up in the front by default.
var totLeft, totRight int
for side := 1; side <= 2; side++ { // left, right
for cat := range 3 {
pidx := pdIdx(side, cat)
if side == 1 {
totLeft += len(layData.paths[pidx])
} else {
totRight += len(layData.paths[pidx])
}
}
}
selfSide := 1 // left
if totRight < totLeft {
selfSide = 2 // right
}
for pi, pd := range layData.selfPaths {
pt := pd.path
pb := pt.AsEmer()
pd.sSide, pd.rSide = selfSide, selfSide
clr := colors.Spaced(pt.TypeNumber())
spm := nv.selfPrjn(se, pd.sSide)
sfgp := xyz.NewGroup(pathsGp)
sfgp.SetName(pb.Name)
sfp := xyz.NewSolid(sfgp).SetMesh(spm).SetColor(clr)
sfp.SetName(pb.Name)
sfp.Pose.Pos = laySidePos(lb, selfSide, 1, pi, npt, 0)
}
}
nv.pathTypeShown = nv.Options.PathType
nv.pathWidthShown = nv.Options.PathWidth
}
func (nv *NetView) pathTypeNameMatch(pt emer.Path) bool {
if len(nv.Options.PathType) == 0 {
return true
}
return pt.AsEmer().IsTypeOrClass(nv.Options.PathType)
}
// returns the self projection mesh, either left = 1 or right = 2
func (nv *NetView) selfPrjn(se *xyz.Scene, side int) xyz.Mesh {
selfnm := fmt.Sprintf("selfPathSide%d", side)
sm, err := se.MeshByName(selfnm)
if err == nil && nv.pathWidthShown == nv.Options.PathWidth {
return sm
}
szm := max(nv.Options.PathWidth/0.002, 1)
lineWidth := 1.5 * nv.Options.PathWidth
size := float32(0.015) * szm
sideFact := float32(1.5)
if side == 1 {
sideFact = -1.5
}
sm = xyz.NewLines(se, selfnm, []math32.Vector3{{0, 0, -size}, {sideFact * size, 0, -size}, {sideFact * size, 0, size}, {0, 0, size}}, math32.Vec2(lineWidth, lineWidth), xyz.OpenLines)
return sm
}