Applied ringbuff to resolv_tailored for reducing memory usage.

This commit is contained in:
genxium
2023-02-15 12:02:07 +08:00
parent 2d179d0cdf
commit 5b7f35b874
19 changed files with 7279 additions and 407 deletions

View File

@@ -2,8 +2,8 @@ package resolv
// Cell is used to contain and organize Object information.
type Cell struct {
X, Y int // The X and Y position of the cell in the Space - note that this is in Grid position, not World position.
Objects []*Object // The Objects that a Cell contains.
X, Y int // The X and Y position of the cell in the Space - note that this is in Grid position, not World position.
Objects *RingBuffer // The Objects that a Cell contains.
}
// newCell creates a new cell at the specified X and Y position. Should not be used directly.
@@ -11,25 +11,27 @@ func newCell(x, y int) *Cell {
return &Cell{
X: x,
Y: y,
Objects: []*Object{},
Objects: NewRingBuffer(16), // A single cell is so small thus wouldn't have many touching objects simultaneously
}
}
// register registers an object with a Cell. Should not be used directly.
func (cell *Cell) register(obj *Object) {
if !cell.Contains(obj) {
cell.Objects = append(cell.Objects, obj)
cell.Objects.Put(obj)
}
}
// unregister unregisters an object from a Cell. Should not be used directly.
func (cell *Cell) unregister(obj *Object) {
for i, o := range cell.Objects {
rb := cell.Objects
for i := rb.StFrameId; i < rb.EdFrameId; i++ {
o := rb.GetByFrameId(i).(*Object)
if o == obj {
cell.Objects[i] = cell.Objects[len(cell.Objects)-1]
cell.Objects = cell.Objects[:len(cell.Objects)-1]
// swap with the st element
rb.SetByFrameId(rb.GetByFrameId(rb.StFrameId), i)
// pop the current st element
rb.Pop()
break
}
@@ -39,7 +41,9 @@ func (cell *Cell) unregister(obj *Object) {
// Contains returns whether a Cell contains the specified Object at its position.
func (cell *Cell) Contains(obj *Object) bool {
for _, o := range cell.Objects {
rb := cell.Objects
for i := rb.StFrameId; i < rb.EdFrameId; i++ {
o := rb.GetByFrameId(i).(*Object)
if o == obj {
return true
}
@@ -49,7 +53,9 @@ func (cell *Cell) Contains(obj *Object) bool {
// ContainsTags returns whether a Cell contains an Object that has the specified tag at its position.
func (cell *Cell) ContainsTags(tags ...string) bool {
for _, o := range cell.Objects {
rb := cell.Objects
for i := rb.StFrameId; i < rb.EdFrameId; i++ {
o := rb.GetByFrameId(i).(*Object)
if o.HasTags(tags...) {
return true
}
@@ -59,5 +65,5 @@ func (cell *Cell) ContainsTags(tags ...string) bool {
// Occupied returns whether a Cell contains any Objects at all.
func (cell *Cell) Occupied() bool {
return len(cell.Objects) > 0
return 0 < cell.Objects.Cnt
}