last_light/engine/engine_layers.go

120 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-05-06 20:43:35 +03:00
package engine
import (
"slices"
"github.com/gdamore/tcell/v2/views"
"github.com/google/uuid"
)
2024-04-19 23:11:21 +03:00
type layer struct {
zIndex uint8
contents []Drawable
}
func makeLayer(zIndex uint8) *layer {
l := new(layer)
l.zIndex = zIndex
l.contents = make([]Drawable, 0, 1)
return l
}
func (l *layer) push(drawable Drawable) {
l.contents = append(l.contents, drawable)
}
func (l *layer) remove(uuid uuid.UUID) {
l.contents = slices.DeleteFunc(l.contents, func(d Drawable) bool {
return d.UniqueId() == uuid
})
}
func (l *layer) draw(s views.View) {
2024-04-19 23:11:21 +03:00
for _, d := range l.contents {
d.Draw(s)
}
}
2024-04-24 17:11:33 +03:00
type UnorderedDrawContainer struct {
2024-04-21 03:48:58 +03:00
id uuid.UUID
contents []Drawable
}
2024-04-24 17:11:33 +03:00
func CreateUnorderedDrawContainer(contents []Drawable) UnorderedDrawContainer {
return UnorderedDrawContainer{
2024-04-21 03:48:58 +03:00
id: uuid.New(),
contents: contents,
}
}
type layeredDrawContainer struct {
id uuid.UUID
2024-04-19 23:11:21 +03:00
layers []*layer
}
func CreateLayeredDrawContainer() *layeredDrawContainer {
container := new(layeredDrawContainer)
2024-04-19 23:11:21 +03:00
container.layers = make([]*layer, 0, 32)
return container
}
func (ldc *layeredDrawContainer) Insert(zLevel uint8, drawable Drawable) {
2024-04-19 23:11:21 +03:00
// if no layers exist, just insert a new one
if len(ldc.layers) == 0 {
l := makeLayer(zLevel)
l.push(drawable)
ldc.layers = append(ldc.layers, l)
2024-04-19 23:11:21 +03:00
return
}
2024-04-19 23:11:21 +03:00
// find a layer with this z-index
i := slices.IndexFunc(ldc.layers, func(l *layer) bool {
return l.zIndex == zLevel
})
2024-04-19 23:11:21 +03:00
// z index already exists
if i > 0 {
l := ldc.layers[i]
l.push(drawable)
2024-04-19 23:11:21 +03:00
return
}
2024-04-19 23:11:21 +03:00
// no such layer exists, create it
2024-04-19 23:11:21 +03:00
l := makeLayer(zLevel)
l.push(drawable)
ldc.layers = append(ldc.layers, l)
// order layers ascending
slices.SortFunc(ldc.layers, func(l1 *layer, l2 *layer) int {
return int(l1.zIndex) - int(l2.zIndex)
})
}
2024-04-19 23:11:21 +03:00
func (ldc *layeredDrawContainer) Remove(id uuid.UUID) {
for _, l := range ldc.layers {
l.remove(id)
}
}
func (ldc *layeredDrawContainer) Clear() {
2024-04-19 23:11:21 +03:00
ldc.layers = make([]*layer, 0, 32)
}
func (ldc *layeredDrawContainer) UniqueId() uuid.UUID {
return ldc.id
}
func (ldc *layeredDrawContainer) Draw(s views.View) {
2024-04-19 23:11:21 +03:00
for _, d := range ldc.layers {
d.draw(s)
}
}