...

Source file src/code.rocketnine.space/tslocum/gohan/entity.go

Documentation: code.rocketnine.space/tslocum/gohan

     1  package gohan
     2  
     3  import (
     4  	"time"
     5  )
     6  
     7  // Entity is an entity identifier.
     8  type Entity int
     9  
    10  // NewEntity returns a new (or previously removed and cleared) Entity. Because
    11  // Gohan reuses removed Entity IDs, a previously removed ID may be returned.
    12  func NewEntity() Entity {
    13  	w.entityMutex.Lock()
    14  	defer w.entityMutex.Unlock()
    15  
    16  	if len(w.availableEntities) > 0 {
    17  		id := w.availableEntities[0]
    18  		w.availableEntities = w.availableEntities[1:]
    19  		w.allEntities = append(w.allEntities, id)
    20  		return id
    21  	}
    22  
    23  	w.maxEntityID++
    24  	w.allEntities = append(w.allEntities, w.maxEntityID)
    25  	w.components = append(w.components, make([]interface{}, w.maxComponentID+1))
    26  
    27  	return w.maxEntityID
    28  }
    29  
    30  // Remove removes the provided Entity's components, causing it to no
    31  // longer be handled by any system.  Because Gohan reuses removed EntityIDs,
    32  // applications must also remove any internal references to the removed Entity.
    33  func (e Entity) Remove() bool {
    34  	w.entityMutex.Lock()
    35  	defer w.entityMutex.Unlock()
    36  
    37  	for i, ent := range w.allEntities {
    38  		if ent == e {
    39  			w.allEntities = _removeAt(w.allEntities, i)
    40  
    41  			// Remove components.
    42  			for i := range w.components[e] {
    43  				w.components[e][i] = nil
    44  			}
    45  
    46  			w.removedEntities = append(w.removedEntities, e)
    47  			return true
    48  		}
    49  	}
    50  	return false
    51  }
    52  
    53  // AllEntities returns a slice of all active entities. To retrieve only the
    54  // number of currently active entities, use CurrentEntities.
    55  func AllEntities() []Entity {
    56  	w.entityMutex.Lock()
    57  	defer w.entityMutex.Unlock()
    58  	allEntities := make([]Entity, len(w.allEntities))
    59  	copy(allEntities, w.allEntities)
    60  	return allEntities
    61  }
    62  
    63  var numEntities int
    64  var numEntitiesT time.Time
    65  
    66  // CurrentEntities returns the number of currently active entities.
    67  func CurrentEntities() int {
    68  	if time.Since(numEntitiesT) >= w.cacheTime {
    69  		numEntities = len(w.allEntities)
    70  		numEntitiesT = time.Now()
    71  	}
    72  	return numEntities
    73  }
    74  
    75  func _removeAt(v []Entity, i int) []Entity {
    76  	v[i] = v[len(v)-1]
    77  	return v[:len(v)-1]
    78  }
    79  

View as plain text