Documentation
¶
Index ¶
- Constants
- Variables
- func AvatarOf[T Entity](s *Server, sessionID int64) (T, bool)
- func MustCollisionBackend(backend CollisionBackend)
- func MustCollisionBackend3D(backend CollisionBackend3D)
- func NewCollisionLayers() *collision.Layers
- func NewCollisionLayers3D() *collision3d.Layers
- func NewCollisionSimple3DBackend() *collision3d.SimpleBackend
- func OverlapOfType[T Entity](s *Server, entityIDs []int64) []T
- func WrapEntityUpdate(data []byte) []byte
- func WrapServerEvent(data []byte) []byte
- func WrapWorldUpdate(data []byte) []byte
- type AvatarOptions
- type CertificateHash
- type ColliderProvider
- type ColliderProvider3D
- type CollisionAABB
- type CollisionAABB3D
- type CollisionBackend
- type CollisionBackend3D
- type CollisionCastQuery
- type CollisionCastQuery3D
- type CollisionCircle
- type CollisionContact
- type CollisionContact3D
- type CollisionEnter
- type CollisionExit
- type CollisionLayers
- type CollisionLayers3D
- type CollisionRaycastHit
- type CollisionRaycastHit3D
- type CollisionShape
- type CollisionShape3D
- type CollisionSimple3DBackend
- type CollisionSpatialQuery
- type CollisionSpatialQuery3D
- type CollisionSphere
- type CollisionStay
- type CollisionVec2
- type CollisionVec3
- type Contact3DFunc
- type ContactFunc
- type Entity
- type EntityIDSetter
- type InterestDiff
- type InterestFOI
- type InterestManager
- type NavAgent
- func (a *NavAgent) Bind(e navMover)
- func (a *NavAgent) HasPath() bool
- func (a *NavAgent) NextWaypoint() (NavPoint, bool)
- func (a *NavAgent) RemainingDistance(x, y float64) float64
- func (a *NavAgent) ResetPath()
- func (a *NavAgent) SetDestination(s *Server, toX, toY float64) bool
- func (a *NavAgent) Step(dt, x, y float64) (float64, float64)
- func (a *NavAgent) Tick(dt float64)
- func (a *NavAgent) Velocity() (float64, float64)
- type NavBackend
- type NavDynamicBackend
- type NavPoint
- type OwnerScopedEntity
- type Position3DWriter
- type PositionWriter
- type RealtimeConfigOptions
- type RemovalSerializer
- type Remover
- type ReplicationStats
- type Server
- func (s *Server) All() []Entity
- func (s *Server) AssignFOI(sessionID, entityID int64, radius, margin float64)
- func (s *Server) Avatar(sessionID int64) (Entity, bool)
- func (s *Server) BoxCast(ox, oy, hw, hh, dx, dy float64, layerMask uint32) (CollisionRaycastHit, bool)
- func (s *Server) BoxCastAll(ox, oy, hw, hh, dx, dy float64, layerMask uint32) []CollisionRaycastHit
- func (s *Server) Broadcast(data [][]byte) error
- func (s *Server) BroadcastEvent(data []byte) error
- func (s *Server) BroadcastReliableOrdered(data []byte) error
- func (s *Server) BroadcastReliableUnordered(data []byte) error
- func (s *Server) BroadcastUnreliable(data []byte) error
- func (s *Server) CircleCast(ox, oy, radius, dx, dy float64, layerMask uint32) (CollisionRaycastHit, bool)
- func (s *Server) CircleCastAll(ox, oy, radius, dx, dy float64, layerMask uint32) []CollisionRaycastHit
- func (s *Server) CreateEntity(e Entity, owner ...int64) error
- func (s *Server) DeleteEntity(id int64)
- func (s *Server) EnableContactEvents()
- func (s *Server) FindPath(x0, y0, x1, y1 float64) ([]NavPoint, bool)
- func (s *Server) Get(id int64) (Entity, bool)
- func (s *Server) Handler() http.HandlerFunc
- func (s *Server) JoinVisibilityGroup(sessionID int64, group string)
- func (s *Server) LeaveVisibilityGroup(sessionID int64, group string)
- func (s *Server) Len() int
- func (s *Server) LoadSnapshot(path, fingerprint string, restore func(snapshot.Record) (Entity, error)) error
- func (s *Server) MapFileHandler(dir string) http.Handler
- func (s *Server) OnConnect(fn func(*Session))
- func (s *Server) OnContact(fn ContactFunc)
- func (s *Server) OnContact3D(fn Contact3DFunc)
- func (s *Server) OnDatagram(fn func(*Session, []byte))
- func (s *Server) OnDisconnect(fn func(*Session))
- func (s *Server) OnMessage(fn func(*Session, []byte))
- func (s *Server) OnReliableOrdered(fn func(*Session, []byte))
- func (s *Server) OnReliableUnordered(fn func(*Session, []byte))
- func (s *Server) OnTick(fn TickFunc)
- func (s *Server) OnTickEnd(fn func(tick uint64, wall time.Duration))
- func (s *Server) OnTickStart(fn func(tick uint64))
- func (s *Server) OnUpdates(fn UpdateFunc)
- func (s *Server) OnUpgrade(fn func(*http.Request) (any, error))
- func (s *Server) OverlapBox(cx, cy, hw, hh float64, layerMask uint32) []int64
- func (s *Server) OverlapBox3D(cx, cy, cz, hw, hh, hd float64, layerMask uint32) []int64
- func (s *Server) OverlapCircle(cx, cy, radius float64, layerMask uint32) []int64
- func (s *Server) OverlapSphere(cx, cy, cz, radius float64, layerMask uint32) []int64
- func (s *Server) Owner(entityID int64) (sessionID int64, owned bool)
- func (s *Server) Post(fn func(*Server)) error
- func (s *Server) PushWorldData(name string) error
- func (s *Server) Raycast(x1, y1, x2, y2 float64, layerMask uint32) (CollisionRaycastHit, bool)
- func (s *Server) Raycast3D(from, to CollisionVec3, layerMask uint32) (CollisionRaycastHit3D, bool)
- func (s *Server) RaycastAll(x1, y1, x2, y2 float64, layerMask uint32) []CollisionRaycastHit
- func (s *Server) RaycastAll3D(from, to CollisionVec3, layerMask uint32) []CollisionRaycastHit3D
- func (s *Server) RealtimeConfigHandler(opts RealtimeConfigOptions) http.Handler
- func (s *Server) RemoveFOI(sessionID int64)
- func (s *Server) ReplicationStats() ReplicationStats
- func (s *Server) ReserveEntityID() int64
- func (s *Server) Run(ctx context.Context) error
- func (s *Server) SaveSnapshot(fingerprint, path string) <-chan error
- func (s *Server) Send(sessionID int64, data []byte) error
- func (s *Server) SendReliableOrdered(sessionID int64, data []byte) error
- func (s *Server) SendReliableUnordered(sessionID int64, data []byte) error
- func (s *Server) SendStoredWorldData(sessionID int64, name string) error
- func (s *Server) SendUnreliable(sessionID int64, data []byte) error
- func (s *Server) SendWorldData(sessionID int64, data WorldData) error
- func (s *Server) SessionCount() int
- func (s *Server) SessionsKnowing(entityID int64) []int64
- func (s *Server) SetCollision3DBackend(b collision3d.Backend)
- func (s *Server) SetCollisionBackend(b collision.Backend)
- func (s *Server) SetCollisionLayers(l *collision.Layers)
- func (s *Server) SetCollisionLayers3D(l *collision3d.Layers)
- func (s *Server) SetEntityIDCounter(n int64)
- func (s *Server) SetEntityVisibilityGroup(entityID int64, group string)
- func (s *Server) SetNavBackend(b nav.Backend)
- func (s *Server) SetNavWalkable(x, y float64, walkable bool)
- func (s *Server) SetOwner(entityID, sessionID int64) bool
- func (s *Server) SetRemovalSerializer(fn RemovalSerializer)
- func (s *Server) SetWebTransportCheckOrigin(fn func(*http.Request) bool)
- func (s *Server) SnapshotAll() ([][]byte, error)
- func (s *Server) SpawnAvatar(sess *Session, e Entity, opts AvatarOptions) error
- func (s *Server) SubmitTask(ctx context.Context, work func(context.Context) error, ...) error
- func (s *Server) TaskStats() TaskStats
- func (s *Server) Tick() uint64
- func (s *Server) WaitReady(ctx context.Context) error
- func (s *Server) WebSocketHandler() http.HandlerFunc
- func (s *Server) WebTransportCertificateHashes() []golemnet.CertificateHash
- func (s *Server) WebTransportServer(h3 *http3.Server) *webtransport.Server
- type ServerBinder
- type ServerConfig
- type Session
- type SnapshotRecord
- type Spatial3DEntity
- type Spawner
- type StateUpdateLane
- type TaskStats
- type TickFunc
- type Ticker
- type Transport
- type TriggerEnter
- type TriggerExit
- type TriggerStay
- type UpdateFunc
- type WorldData
- type WorldStore
Constants ¶
const ( TransportWebSocket = golemnet.TransportWebSocket TransportWebTransport = golemnet.TransportWebTransport )
Variables ¶
var ( // ErrServerNotRunning is returned by Post and SubmitTask when the server // has not entered Run, has begun shutdown, or has already returned from Run. ErrServerNotRunning = errors.New("golem: server is not running") // ErrServerAlreadyRun is returned when Run is called concurrently with or // after another Run on the same Server. Run is single-use. ErrServerAlreadyRun = errors.New("golem: server has already been run") // ErrPostQueueFull is returned when Post cannot enqueue because the // bounded post queue is at capacity. ErrPostQueueFull = errors.New("golem: post queue is full") // ErrTaskQueueFull is returned when SubmitTask cannot accept work because // the bounded worker-pool queue is at capacity. ErrTaskQueueFull = errors.New("golem: task queue is full") // ErrTaskPanicked is wrapped into the completion error when work panics. // The completion callback still runs on the tick goroutine while the // server remains running. ErrTaskPanicked = errors.New("golem: task panicked") )
Lifecycle, Post, and SubmitTask sentinel errors.
var ErrReliableDatagramsNotSupported = golemnet.ErrReliableDatagramsNotSupported
ErrReliableDatagramsNotSupported reports that the active transport has no reliable datagram lanes.
var ErrSessionNotFound = golemnet.ErrSessionNotFound
ErrSessionNotFound reports that a targeted session disconnected before a send operation could deliver the frame.
var ErrUnreliableNotSupported = golemnet.ErrUnreliableNotSupported
ErrUnreliableNotSupported reports that the active transport has no datagram lane.
Functions ¶
func AvatarOf ¶ added in v0.3.0
AvatarOf returns the avatar for sessionID asserted to type T. Returns false when there is no avatar or the live entity is not of type T.
func MustCollisionBackend ¶ added in v0.3.0
func MustCollisionBackend(backend CollisionBackend)
MustCollisionBackend panics when backend is nil. Generated EnableCollision calls this before configuring Layers so a nil backend cannot install a half-configured helper on the Server. The panic preserves the convenient no-error EnableCollision API.
func MustCollisionBackend3D ¶ added in v0.3.0
func MustCollisionBackend3D(backend CollisionBackend3D)
MustCollisionBackend3D panics when backend is nil. Generated EnableCollision3D calls this before configuring Layers3D so a nil backend cannot install a half-configured helper on the Server.
func NewCollisionLayers ¶
NewCollisionLayers creates an empty CollisionLayers registry. Call Bind to attach a backend, then Define to register named layers, then SetCollides to record which layer pairs interact. After that, use Add, Set, and Remove instead of calling the backend directly — layer bits and masks are derived automatically from the collision matrix.
Layer, Mask, and MaskFor remain available for spatial queries such as OverlapBox and Raycast.
func NewCollisionLayers3D ¶ added in v0.3.0
func NewCollisionLayers3D() *collision3d.Layers
NewCollisionLayers3D creates an empty CollisionLayers3D registry for 3D backends. Call Bind, Define, and SetCollides as with NewCollisionLayers, then use Add/Set/Remove with CollisionShape3D values.
func NewCollisionSimple3DBackend ¶
func NewCollisionSimple3DBackend() *collision3d.SimpleBackend
NewCollisionSimple3DBackend creates a pure-Go detection-only 3D collision backend.
func OverlapOfType ¶ added in v0.3.0
OverlapOfType resolves entityIDs through Server.Get and returns those that satisfy T, preserving input/backend order. Missing IDs and type mismatches are skipped. Returns nil when entityIDs is empty or no entry matches T. A nil Server always panics with "golem: OverlapOfType: Server must be non-nil", including when entityIDs is empty.
Compose with overlap ID queries rather than geometry-specific generics:
mobs := golem.OverlapOfType[*Mob](s, s.OverlapCircle(x, y, r, mask))
func WrapEntityUpdate ¶
WrapEntityUpdate wraps serialized EntityUpdate bytes in a ServerMessage envelope (proto field 1, length-delimited). The Listener applies this transparently to all outgoing entity frames when integrated networking is active.
func WrapServerEvent ¶
WrapServerEvent wraps serialized ServerEvent bytes in a ServerMessage envelope (proto field 3, length-delimited). Used by EventBroadcaster methods — event frames bypass the entity messageWrapper.
func WrapWorldUpdate ¶
WrapWorldUpdate wraps serialized WorldUpdate bytes in a ServerMessage envelope (proto field 2, length-delimited). Used by PushWorldData, SendWorldData / SendStoredWorldData, and the world snapshot closure — world frames bypass the entity messageWrapper.
Types ¶
type AvatarOptions ¶ added in v0.3.0
type AvatarOptions struct {
// FOIRadius is the interest radius centred on the avatar entity.
// When > 0, SpawnAvatar assigns FOI (requires CellSize > 0). When 0, no FOI
// is assigned. Negative values are rejected.
FOIRadius float64
// FOIMargin is the hysteresis margin passed to AssignFOI when FOIRadius > 0.
FOIMargin float64
}
AvatarOptions configures optional FOI assignment when spawning a session avatar.
type CertificateHash ¶
type CertificateHash = golemnet.CertificateHash
type ColliderProvider ¶ added in v0.3.0
type ColliderProvider interface {
Collider() (shape CollisionShape, layer string, trigger bool)
}
ColliderProvider is implemented by entities that expose a 2D schema-declared (or hand-written) collider. CreateEntity registers the shape on the server's CollisionLayers when SetCollisionLayers has been called (typically via generated Runtime.EnableCollision).
Wrapper types that embed a generated Synced* inherit Collider(); overriding it intentionally replaces the schema shape for that wrapper.
type ColliderProvider3D ¶ added in v0.3.0
type ColliderProvider3D interface {
Collider3D() (shape CollisionShape3D, layer string, trigger bool)
}
ColliderProvider3D is implemented by entities that expose a 3D schema-declared (or hand-written) collider. CreateEntity registers the shape on the server's CollisionLayers3D when SetCollisionLayers3D has been called (typically via generated Runtime.EnableCollision3D).
Wrapper types that embed a generated Synced* inherit Collider3D(); overriding it intentionally replaces the schema shape for that wrapper.
type CollisionAABB ¶
CollisionAABB is an axis-aligned bounding-box collision shape.
type CollisionAABB3D ¶
type CollisionAABB3D = collision3d.AABB
CollisionAABB3D is an axis-aligned 3D box collision shape.
type CollisionBackend ¶
CollisionBackend is the interface implemented by collision backends (resolv, cp, …). Pass one to Server.SetCollisionBackend.
type CollisionBackend3D ¶
type CollisionBackend3D = collision3d.Backend
CollisionBackend3D is the interface implemented by 3D collision backends.
type CollisionCastQuery ¶
CollisionCastQuery is an optional interface backends may implement to support Raycast, BoxCast, and CircleCast queries.
type CollisionCastQuery3D ¶
type CollisionCastQuery3D = collision3d.CastQuery
CollisionCastQuery3D is an optional interface backends may implement to support Raycast3D queries.
type CollisionCircle ¶
CollisionCircle is a circular collision shape.
type CollisionContact ¶
CollisionContact describes a single detected collision between two entities.
type CollisionContact3D ¶
type CollisionContact3D = collision3d.Contact
CollisionContact3D describes a detected 3D collision between two entities.
type CollisionEnter ¶
type CollisionEnter interface {
OnCollisionEnter(other Entity, normal CollisionVec2, depth float64)
}
CollisionEnter is optionally implemented by entities that want to be notified when a solid collision with another entity begins. normal is a unit vector pointing away from other (the push direction for the receiver). Contact.Normal from the backend points away from the other entity toward the receiver, and is negated for the B side so both entities always receive "away from the other". other may be nil if the other entity was removed in the same tick.
type CollisionExit ¶
type CollisionExit interface {
OnCollisionExit(other Entity)
}
CollisionExit is optionally implemented by entities that want to be notified when a solid collision with another entity ends. other may be nil if the other entity was removed and is no longer in the registry.
type CollisionLayers ¶
CollisionLayers maps named layers to bit indices and maintains a symmetric collision matrix. Use NewCollisionLayers to create one; call Define then SetCollides to configure it; then pass Layer/Mask/MaskFor results to backend.Add, backend.Set, and spatial query methods.
type CollisionLayers3D ¶ added in v0.3.0
type CollisionLayers3D = collision3d.Layers
CollisionLayers3D is the 3D equivalent of CollisionLayers for collision3d.Backend. Use NewCollisionLayers3D to create one.
type CollisionRaycastHit ¶
type CollisionRaycastHit = collision.RaycastHit
CollisionRaycastHit is the result of a cast query: entity ID, world-space contact point and normal, and normalised fraction along the cast segment.
type CollisionRaycastHit3D ¶
type CollisionRaycastHit3D = collision3d.RaycastHit
CollisionRaycastHit3D is the result of a 3D cast query.
type CollisionShape ¶
CollisionShape is the sealed interface for collision shape descriptors (CollisionCircle, CollisionAABB).
type CollisionShape3D ¶
type CollisionShape3D = collision3d.Shape
CollisionShape3D is the sealed interface for 3D collision shapes.
type CollisionSimple3DBackend ¶
type CollisionSimple3DBackend = collision3d.SimpleBackend
CollisionSimple3DBackend is the pure-Go detection-only 3D collision backend.
type CollisionSpatialQuery ¶
type CollisionSpatialQuery = collision.SpatialQuery
CollisionSpatialQuery is an optional interface backends may implement to support one-shot OverlapBox / OverlapCircle queries.
type CollisionSpatialQuery3D ¶
type CollisionSpatialQuery3D = collision3d.SpatialQuery
CollisionSpatialQuery3D is an optional interface backends may implement to support OverlapBox3D / OverlapSphere queries.
type CollisionSphere ¶
type CollisionSphere = collision3d.Sphere
CollisionSphere is a spherical 3D collision shape.
type CollisionStay ¶
type CollisionStay interface {
OnCollisionStay(other Entity, normal CollisionVec2, depth float64)
}
CollisionStay is optionally implemented by entities that want to be notified every tick while a solid collision with another entity persists. normal and depth carry the current frame's contact data. other may be nil if the other entity was removed in the same tick.
type CollisionVec2 ¶
CollisionVec2 is a 2D vector used in collision contacts.
type CollisionVec3 ¶
type CollisionVec3 = collision3d.Vec3
CollisionVec3 is a 3D vector used in collision contacts and queries.
type Contact3DFunc ¶
type Contact3DFunc func(contacts []collision3d.Contact)
Contact3DFunc is called after each 3D collision step with contacts detected in that tick. It is only invoked when at least one contact was found.
type ContactFunc ¶
ContactFunc is called after each collision step with all contacts detected in that tick. It is only invoked when at least one contact was found.
type EntityIDSetter ¶
type EntityIDSetter = registry.EntityIDSetter
EntityIDSetter is satisfied by any entity with SetEntityID(int64). All generated Synced* types implement it. Used by CreateEntity to assign an auto-incremented ID when the entity is constructed without one.
type InterestDiff ¶
type InterestFOI ¶
type InterestManager ¶
type NavAgent ¶
type NavAgent struct {
Speed float64
// waypoint) the agent must be before it advances to the next waypoint.
// Use a value around half a grid cell for smooth movement (e.g. 8.0 for
// 16-pixel tiles). Zero relies entirely on overshoot protection to
// snap the agent onto each waypoint position exactly.
StoppingDistance float64
// contains filtered or unexported fields
}
NavAgent manages path-following movement for an NPC entity. Embed it in your NPC struct, call Bind once in OnSpawn, then call SetDestination whenever the goal changes — movement happens automatically each tick via the Ticker interface.
type NPC struct { Agent golem.NavAgent }
func (n *NPC) OnSpawn() { n.Agent.Bind(n) }
func (n *NPC) Tick(dt float64) { n.Agent.Tick(dt) }
// Anywhere (command handler, OnTick, OnSpawn):
npc.Agent.SetDestination(s, targetX, targetY)
func (*NavAgent) Bind ¶
func (a *NavAgent) Bind(e navMover)
Bind attaches a position-aware entity to the agent. Call this from OnSpawn so that SetDestination and Tick can read and write the entity's position without extra arguments. Any generated Synced* type satisfies the required interface automatically.
func (*NavAgent) NextWaypoint ¶
NextWaypoint returns the next world-space position the agent is heading toward, and true. Returns the zero value and false when no path is set.
func (*NavAgent) RemainingDistance ¶
RemainingDistance returns the total length of the path from (x, y) to the goal, summing straight-line distances to each remaining waypoint. Returns 0 when the agent has no path.
func (*NavAgent) ResetPath ¶
func (a *NavAgent) ResetPath()
ResetPath clears the current path, stopping all movement immediately.
func (*NavAgent) SetDestination ¶
SetDestination finds a path to (toX, toY) from the bound entity's current position and stores it as the agent's route. Returns false if the agent is not bound, no nav backend is configured, or no path exists. Any existing path is replaced.
func (*NavAgent) Step ¶
Step advances the agent one tick along its current path. x and y are the entity's current world-space position; returns the new position after applying one tick of movement at the configured Speed.
When the agent reaches the goal or has no path, (x, y) is returned unchanged and velocity is zeroed. Overshoot is prevented: the agent snaps to a waypoint rather than moving past it in a single tick.
Use Step when you need manual control without binding, or when position management lives outside the entity (e.g. a shared physics body):
npc.X, npc.Y = npc.Agent.Step(dt, npc.X, npc.Y) npc.SetPosition(npc.X, npc.Y)
func (*NavAgent) Tick ¶
Tick advances the agent one tick along its current path, reading position from the bound entity and writing the updated position back via SetPosition. No-op if the agent is not bound or has no path. Call this from the entity's Tick method to drive automatic movement.
type NavBackend ¶
NavBackend is the interface implemented by nav backends. Build one from your map data at startup and pass it to Server.SetNavBackend.
type NavDynamicBackend ¶
type NavDynamicBackend = nav.DynamicBackend
NavDynamicBackend is an optional nav.Backend extension for backends that support runtime walkability updates. Check for it with a type assertion or use Server.SetNavWalkable, which does so internally.
type OwnerScopedEntity ¶ added in v0.3.0
type OwnerScopedEntity = registry.OwnerScopedEntity
OwnerScopedEntity is satisfied by generated entities with visibility: owner vars. PublicFullUpdate / PublicReplicationMask redact those fields for non-owner recipients; FullUpdate remains authoritative.
type Position3DWriter ¶
type Position3DWriter = registry.Position3DWriter
Position3DWriter is satisfied by generated 3D entities with SetPosition3D.
type PositionWriter ¶
type PositionWriter = registry.PositionWriter
PositionWriter is satisfied by any entity with SetPosition(x, y float32). All generated Synced* types implement it. Used by collision backends to write physics-corrected positions back to entities each tick.
type RealtimeConfigOptions ¶
type RealtimeConfigOptions struct {
PublicURL string
// WebSocketFallbackURL advertises an optional WebSocket endpoint backed by
// the same Server. It is valid only when WebTransport is the primary
// transport.
WebSocketFallbackURL string
EventualAckIntervalMs *int
// IncludeServerCertificateHashes overrides whether WebTransport certificate
// hashes are returned. When nil, hashes are included only for generated
// development self-signed certificates.
IncludeServerCertificateHashes *bool
}
RealtimeConfigOptions configures the browser bootstrap JSON served by Server.RealtimeConfigHandler.
type RemovalSerializer ¶
RemovalSerializer converts a removed entity ID and revision into a serialized EntityUpdate message. Provided by generated code (e.g. synced.MarshalEntityRemoved).
type ReplicationStats ¶ added in v0.3.0
type ReplicationStats struct {
LastTick uint64
DeltasFlushed int
StreamBatchedFrames int
StreamWireMsgs int
DatagramBatchedFrames int
DatagramWirePayloads int
}
ReplicationStats is a snapshot of the most recently completed replication pass. Wire message totals include every session (broadcast multiplies by client count; interest sums per-send chunks).
type Server ¶
Server runs the core game loop and, when Addr is configured, an integrated transport server for client connections.
func NewServer ¶
func NewServer(cfg ServerConfig) *Server
NewServer creates a game server with the given configuration. The internal Listener is always created so Handler() works regardless of whether Addr is set. When Addr is set, Run also starts the built-in transport server; otherwise only the tick loop runs and the game is expected to mount Handler() on its own router. When CellSize > 0, interest management is enabled and entity snapshots on connect are deferred to the interest system. Session lifecycle hooks (OnConnect, OnMessage, OnDisconnect) are queued from connection goroutines and dispatched on the tick goroutine.
func (*Server) AssignFOI ¶
AssignFOI associates a session with a circular field of interest centred on the given entity. Panics if interest management is not enabled (CellSize <= 0). Concurrency-safe with other Server FOI APIs via interestMu.
func (*Server) Avatar ¶ added in v0.3.0
Avatar returns the avatar entity bound to sessionID, if any and still registered.
func (*Server) BoxCast ¶
func (s *Server) BoxCast(ox, oy, hw, hh, dx, dy float64, layerMask uint32) (CollisionRaycastHit, bool)
BoxCast sweeps an AABB with half-extents (hw, hh) from (ox, oy) by the displacement (dx, dy) and returns the first entity hit. Returns a zero RaycastHit and false if no backend is set, the backend does not implement CollisionCastQuery, or no entity was hit.
func (*Server) BoxCastAll ¶
func (s *Server) BoxCastAll(ox, oy, hw, hh, dx, dy float64, layerMask uint32) []CollisionRaycastHit
BoxCastAll sweeps an AABB with half-extents (hw, hh) from (ox, oy) by the displacement (dx, dy) and returns all entities hit, sorted by Fraction. Returns nil if no backend is set, the backend does not implement CollisionCastQuery, or no entity was hit.
func (*Server) Broadcast ¶
Broadcast sends a set of binary messages to every connected session. No-op when no clients are connected.
func (*Server) BroadcastEvent ¶
BroadcastEvent sends a pre-wrapped server event frame to every connected session without applying the entity messageWrapper.
func (*Server) BroadcastReliableOrdered ¶
BroadcastReliableOrdered sends one reliable ordered datagram to every datagram-capable session. A pure WebSocket server returns ErrReliableDatagramsNotSupported.
func (*Server) BroadcastReliableUnordered ¶
BroadcastReliableUnordered sends one reliable unordered datagram to every datagram-capable session. A pure WebSocket server returns ErrReliableDatagramsNotSupported.
func (*Server) BroadcastUnreliable ¶
BroadcastUnreliable sends one lossy datagram to every datagram-capable session. A pure WebSocket server returns ErrUnreliableNotSupported.
func (*Server) CircleCast ¶
func (s *Server) CircleCast(ox, oy, radius, dx, dy float64, layerMask uint32) (CollisionRaycastHit, bool)
CircleCast sweeps a circle with the given radius from (ox, oy) by the displacement (dx, dy) and returns the first entity hit. Returns a zero RaycastHit and false if no backend is set, the backend does not implement CollisionCastQuery, or no entity was hit.
func (*Server) CircleCastAll ¶
func (s *Server) CircleCastAll(ox, oy, radius, dx, dy float64, layerMask uint32) []CollisionRaycastHit
CircleCastAll sweeps a circle with the given radius from (ox, oy) by the displacement (dx, dy) and returns all entities hit, sorted by Fraction. Returns nil if no backend is set, the backend does not implement CollisionCastQuery, or no entity was hit.
func (*Server) CreateEntity ¶
CreateEntity registers e for simulation and replication. If the entity was constructed without an ID (EntityID() == 0), the next counter value is assigned automatically via EntityIDSetter. If e implements ServerBinder, BindServer is invoked after validation/ID assignment and before registry insertion so OnSpawn can call Server().
When e implements ColliderProvider or ColliderProvider3D, its shape is registered on the configured named-layer helper after successful registry insertion and before OnSpawn. Registration is skipped without panicking when no layer helper is set — call SetCollisionLayers / SetCollisionLayers3D (or generated EnableCollision / EnableCollision3D) before spawning or snapshot-loading collidable entities. Failed duplicate insertion does not register a collider.
With no extra owner arguments the entity is unowned (e.g. world NPC); with one argument that value is the owning session ID for command authority. More than one owner argument is invalid.
func (*Server) DeleteEntity ¶
DeleteEntity unregisters an entity by ID and queues a removal for clients. If the entity is a session avatar, both avatar indexes are cleared in O(1) before registry deletion. When the entity implements ColliderProvider or ColliderProvider3D and a matching layer helper is configured, its shape is removed after avatar index cleanup and before registry deletion (and thus before OnRemove). Safe to call repeatedly; does not hold the avatar mutex while invoking registry hooks (OnRemove) or interest operations.
func (*Server) EnableContactEvents ¶
func (s *Server) EnableContactEvents()
EnableContactEvents activates per-entity collision event dispatch for this server. When enabled, the tick loop tracks which entity pairs are overlapping each tick and calls OnTriggerEnter/Stay/Exit and OnCollisionEnter/Stay/Exit on entities that implement those interfaces. This requires a collision backend (SetCollisionBackend) to have any effect — without a backend, no contacts are produced and no events fire. Safe to call after Run has started; the tracking maps begin empty, so all currently-overlapping pairs fire as Enter on the next tick.
func (*Server) FindPath ¶
FindPath returns world-space waypoints from (x0,y0) to (x1,y1). The first element is the start position; subsequent elements are the world-space centres of each grid cell along the route, ending at the goal. Returns nil, false when no nav backend is set, no path exists, or either coordinate is outside the grid.
func (*Server) Handler ¶
func (s *Server) Handler() http.HandlerFunc
Handler returns the configured transport endpoint handler for external mounting on a custom router. When using WebTransport, pair it with WebTransportServer on a caller-owned HTTP/3 server.
func (*Server) JoinVisibilityGroup ¶ added in v0.3.0
JoinVisibilityGroup adds sessionID to the named visibility group. Grouped entities assigned to that group replicate only to members. Concurrency-safe under interestMu and never waits on network I/O. Policy is point-in-time: a join after a replication/snapshot decision takes effect on the next pass (via known-set enter/stay), and does not revoke frames already selected or queued.
func (*Server) LeaveVisibilityGroup ¶ added in v0.3.0
LeaveVisibilityGroup removes sessionID from the named visibility group. Concurrency-safe under interestMu and never waits on network I/O. A leave after a replication/snapshot decision takes effect on the next pass (known recipients get EntityRemoved when no longer allowed).
func (*Server) LoadSnapshot ¶
func (s *Server) LoadSnapshot(path, fingerprint string, restore func(snapshot.Record) (Entity, error)) error
LoadSnapshot reads a snapshot file, restores all entities via the provided restore function, registers them with their original IDs, and advances the entity ID counter past the highest restored ID.
restore should be the generated synced.RestoreEntity function. Records whose type is unknown to restore (it returns a non-nil error) are silently skipped— this is the expected behavior when an entity type has been removed from the schema.
Returns snapshot.ErrFingerprintMismatch when the file was saved with a different schema binary layout — the caller should delete the snapshot and rebuild state from scratch.
func (*Server) MapFileHandler ¶
MapFileHandler returns an http.Handler that serves map files from dir. Mount it on a custom router when using an external HTTP server:
mux.Handle("/maps/", http.StripPrefix("/maps/", server.MapFileHandler("maps/")))
When using the integrated server, set ServerConfig.MapDir instead.
func (*Server) OnConnect ¶
OnConnect registers a hook called when a client connects and receives the world-state snapshot. The hook fires on the tick goroutine, so it is safe to call CreateEntity and other Server methods directly.
func (*Server) OnContact ¶
func (s *Server) OnContact(fn ContactFunc)
OnContact registers a callback invoked after each collision step when at least one contact was detected. Contacts include both solid overlaps and trigger overlaps (Depth == 0 for triggers).
func (*Server) OnContact3D ¶
func (s *Server) OnContact3D(fn Contact3DFunc)
OnContact3D registers a callback invoked after each 3D collision step when at least one contact was detected.
func (*Server) OnDatagram ¶
OnDatagram registers a hook called when a client sends an unreliable datagram. The hook fires on the tick goroutine, so it is safe to call Server methods directly.
func (*Server) OnDisconnect ¶
OnDisconnect registers a hook called when a client disconnects. The hook fires on the tick goroutine before automatic avatar cleanup, so Avatar / AvatarOf still resolve during the callback. After the hook returns, the server RemoveFOI (when interest is enabled), deletes any avatar still bound to the session (including a replacement spawned inside the callback), and clears avatar indexes — replacements are reaped so they cannot leak past disconnect. It is safe to call DeleteEntity and other Server methods from the hook. Disconnect events from the listener always carry a non-nil *Session.
func (*Server) OnMessage ¶
OnMessage registers a hook called when a client sends a binary message. The hook fires on the tick goroutine, so it is safe to call CreateEntity, DeleteEntity, and other Server methods directly.
func (*Server) OnReliableOrdered ¶
OnReliableOrdered registers a hook called when a client sends a reliable ordered datagram. The hook fires on the tick goroutine, so it is safe to call Server methods directly.
func (*Server) OnReliableUnordered ¶
OnReliableUnordered registers a hook called when a client sends a reliable unordered datagram. The hook fires on the tick goroutine, so it is safe to call Server methods directly.
func (*Server) OnTickEnd ¶
OnTickEnd appends a callback called at the end of each tick, after all entity updates and the broadcast flush. wall is the total tick wall time. Use it to record per-tick latency histograms or close trace regions opened in OnTickStart.
func (*Server) OnTickStart ¶
OnTickStart appends a callback called at the very start of each tick, before entity updates and game logic. tick is the 1-based tick counter. Runs on the tick goroutine, so runtime/trace regions and pprof.Do labels nest cleanly with work done in OnTick and OnTickEnd.
func (*Server) OnUpdates ¶
func (s *Server) OnUpdates(fn UpdateFunc)
OnUpdates registers a callback that receives all serialized entity updates (spawns, deltas, and removals) after each tick. When integrated networking is active the server broadcasts automatically; use OnUpdates for extra logic like logging or filtering. Interest mode invokes the callback with the unique flush payloads before per-session FOI sends (does not replace sends).
func (*Server) OnUpgrade ¶
OnUpgrade registers a hook called before transport session acceptance. The hook receives the HTTP request for auth inspection; returning a non-nil error rejects the request with HTTP 401. The returned value is stored in Session.Data before OnConnect fires.
func (*Server) OverlapBox ¶
OverlapBox returns the IDs of all registered entities whose collision shapes overlap the axis-aligned box centred at (cx, cy) with half-extents (hw, hh). Only entities whose layer has at least one bit in layerMask are returned. Returns nil if no collision backend is set or the backend does not implement CollisionSpatialQuery.
func (*Server) OverlapBox3D ¶
OverlapBox3D returns IDs whose 3D collision shapes overlap the axis-aligned box centered at (cx, cy, cz) with half-extents (hw, hh, hd). Returns nil if no 3D collision backend is set or the backend does not implement CollisionSpatialQuery3D.
func (*Server) OverlapCircle ¶
OverlapCircle returns the IDs of all registered entities whose collision shapes overlap the circle centred at (cx, cy) with the given radius. Only entities whose layer has at least one bit in layerMask are returned. Returns nil if no collision backend is set or the backend does not implement CollisionSpatialQuery.
func (*Server) OverlapSphere ¶
OverlapSphere returns IDs whose 3D collision shapes overlap the sphere centered at (cx, cy, cz) with the given radius. Returns nil if no 3D collision backend is set or the backend does not implement CollisionSpatialQuery3D.
func (*Server) Post ¶ added in v0.3.0
Post enqueues fn to run on the tick goroutine after OnTickStart and before session-message drain. It never invokes fn inline, including when called from a tick callback; such posts run on a later tick drain.
Post returns ErrServerNotRunning before Run, once shutdown is linearized, and after Run returns. A full queue returns ErrPostQueueFull immediately without blocking. A nil fn returns a non-nil validation error and is not enqueued.
Accepted posts may be discarded without running when the server shuts down before they are drained. Posts and task completions share the per-tick AsyncCallbacksPerTick budget (round-robin, completion-first on the first drain, preference persisted across ticks).
Pipeline counters are exposed by TaskStats / Server.TaskStats (PostsAccepted, PostsExecuted, PostsRejectedFull, QueuedPosts).
func (*Server) PushWorldData ¶
PushWorldData broadcasts the current value of a single world data type to all connected sessions. Returns nil if the name is not in the store or the broadcast succeeds. Returns a non-nil error if serialization fails. Reliable frames are capped at 256 KiB; oversized embedded maps should use map_url instead of tile_data.
func (*Server) Raycast ¶
func (s *Server) Raycast(x1, y1, x2, y2 float64, layerMask uint32) (CollisionRaycastHit, bool)
Raycast casts a segment from (x1, y1) to (x2, y2) and returns the first entity hit, along with a boolean indicating whether anything was hit. Only entities whose layer has at least one bit in layerMask are considered. Returns a zero RaycastHit and false if no backend is set, the backend does not implement CollisionCastQuery, or no entity was hit.
func (*Server) Raycast3D ¶
func (s *Server) Raycast3D(from, to CollisionVec3, layerMask uint32) (CollisionRaycastHit3D, bool)
Raycast3D casts a segment from from to to and returns the first 3D hit.
func (*Server) RaycastAll ¶
func (s *Server) RaycastAll(x1, y1, x2, y2 float64, layerMask uint32) []CollisionRaycastHit
RaycastAll casts a segment from (x1, y1) to (x2, y2) and returns all entities hit, sorted by Fraction (closest first). Returns nil if no backend is set, the backend does not implement CollisionCastQuery, or no entity was hit.
func (*Server) RaycastAll3D ¶
func (s *Server) RaycastAll3D(from, to CollisionVec3, layerMask uint32) []CollisionRaycastHit3D
RaycastAll3D casts a segment from from to to and returns all 3D hits sorted by Fraction.
func (*Server) RealtimeConfigHandler ¶
func (s *Server) RealtimeConfigHandler(opts RealtimeConfigOptions) http.Handler
RealtimeConfigHandler returns an HTTP handler that serves client connection settings for the server's integrated transport.
func (*Server) RemoveFOI ¶
RemoveFOI removes a session's field of interest and clears its known set. Panics if interest management is not enabled. Concurrency-safe with other Server FOI APIs via interestMu.
func (*Server) ReplicationStats ¶ added in v0.3.0
func (s *Server) ReplicationStats() ReplicationStats
ReplicationStats returns counts from the most recently completed replication pass.
func (*Server) ReserveEntityID ¶
ReserveEntityID increments the counter and returns the reserved ID. Pass the returned value as the optional trailing argument to the generated NewSynced* constructor when you need to know the ID before the entity is registered (e.g. to wire up relationships between entities up-front).
func (*Server) Run ¶
Run starts the game loop at the configured tick rate. When Addr is set it also starts the built-in transport server. Entity updates are auto-broadcast to all connected clients after each tick regardless of whether the built-in server or an external router is used.
Each tick runs in order: OnTickStart, drain async completions/posts (combined AsyncCallbacksPerTick budget, round-robin starting with completions on the first drain and persisting preference across ticks), drain session-event queue (OnConnect / OnMessage / OnDisconnect), entity ticks, OnTick game logic, collision step, flush and broadcast, OnTickEnd.
Run is single-use: a concurrent or later call returns ErrServerAlreadyRun. It always derives an internal run context for the listener, tick loop, and SubmitTask worker pool (independent of the caller context so Pond can be cancelled then StopAndWait). Cancellation linearizes shutdown in this order: stop accepting Post/SubmitTask (ErrServerNotRunning), cancel the run/worker context, wait for the Pond pool (queued-not-started tasks are not executed; running tasks receive cancellation), discard queued completions/posts, and mark stopped. No Post or SubmitTask completion callback runs after Run returns. Work that ignores context cancellation can delay return indefinitely.
If the caller context is already cancelled, Run linearizes stopping under lifeMu before the tick loop or Post/SubmitTask acceptance, then shuts down the independent run context and pool without entering the loop. Live caller cancellation is still linked through AfterFunc after acceptance opens.
TaskStats / Server.TaskStats expose accept/reject, finish vs callback-executed, cancellation, panic, and approximate queue/worker gauges for this pipeline.
Blocks until the internal context is cancelled or the loop fails. Returns ctx.Err() on clean shutdown.
func (*Server) SaveSnapshot ¶
SaveSnapshot collects the full state of all persistent entities and writes an atomic snapshot file to path. The write runs in a background goroutine so the game loop is never blocked. The returned channel receives exactly one value: nil on success or a non-nil error on failure.
fingerprint should be the generated SchemaFingerprint constant from the consumer's generated code (e.g. synced.SchemaFingerprint). It is embedded in the file header and validated on Load to detect schema changes between saves.
func (*Server) Send ¶
Send delivers a single binary message to a specific session without altering bytes. When integrated networking uses the ServerMessage envelope, entity payloads must already be wrapped (e.g. WrapEntityUpdate); world payloads must use WrapWorldUpdate.
func (*Server) SendReliableOrdered ¶
SendReliableOrdered sends one reliable ordered datagram to a specific session when supported.
func (*Server) SendReliableUnordered ¶
SendReliableUnordered sends one reliable unordered datagram to a specific session when supported.
func (*Server) SendStoredWorldData ¶ added in v0.3.0
SendStoredWorldData sends the currently stored world value for name to one session. Returns nil when the name is missing (same no-op as PushWorldData). Marshal failures, oversize reliable frames, and disconnected sessions propagate. Prefer SendWorldData when delivering a per-session value that must not replace Server.World.
func (*Server) SendUnreliable ¶
SendUnreliable sends one lossy datagram to a specific session when supported.
func (*Server) SendWorldData ¶ added in v0.3.0
SendWorldData serializes data directly, wraps it with WrapWorldUpdate, and sends it on the reliable stream to one session. It does not read or mutate Server.World, so two sessions can receive different generated values that share the same WorldName. Nil and typed-nil data return an error. Marshal failures, oversize reliable frames (256 KiB cap), and disconnected sessions propagate. Prefer map_url when payloads may exceed the frame cap. Names listed in WorldSnapshotExclude are omitted from connect snapshots; callers own delivering those values (for example via this method).
func (*Server) SessionCount ¶ added in v0.3.0
SessionCount returns the number of currently connected realtime sessions.
func (*Server) SessionsKnowing ¶
SessionsKnowing returns the IDs of all sessions that currently have entityID in their actual replication known set. In interest mode this is the FOI known set; in broadcast mode it is the broadcast known set seeded by successful connect snapshots and updated by replication decisions. It never consults raw visibility-group membership — a session that just joined a group is not returned until the next replication pass queues full state. Safe to call concurrently with AssignFOI / RemoveFOI / visibility APIs / SpawnAvatar; guarded by interestMu.
func (*Server) SetCollision3DBackend ¶
func (s *Server) SetCollision3DBackend(b collision3d.Backend)
SetCollision3DBackend attaches a 3D collision backend to the server. When set, each tick syncs 3D entity positions into the backend, steps it, reads corrections back via Position3DWriter, and fires OnContact3D handlers.
func (*Server) SetCollisionBackend ¶
SetCollisionBackend attaches a collision backend to the server. When set, each tick syncs entity positions into the backend, steps it, reads physics corrections back via PositionWriter, and fires OnContact handlers. Shape registration (Add/Remove) remains in game code.
func (*Server) SetCollisionLayers ¶ added in v0.3.0
SetCollisionLayers stores the 2D named-layer helper used for automatic ColliderProvider registration in CreateEntity / removal in DeleteEntity. A nil helper disables automatic registration without panicking.
Call before spawning or restoring collidable entities (for example before Runtime.LoadSnapshot). EnableCollision generated helpers set this after binding the backend.
func (*Server) SetCollisionLayers3D ¶ added in v0.3.0
func (s *Server) SetCollisionLayers3D(l *collision3d.Layers)
SetCollisionLayers3D stores the 3D named-layer helper used for automatic ColliderProvider3D registration. A nil helper disables automatic registration without panicking. Call before spawning or restoring collidable 3D entities.
func (*Server) SetEntityIDCounter ¶
SetEntityIDCounter seeds the ID counter to n. The next auto-assigned or reserved ID will be n+1. Call this during server initialisation when loading persisted state so that new entities never collide with existing ones.
func (*Server) SetEntityVisibilityGroup ¶ added in v0.3.0
SetEntityVisibilityGroup assigns entityID to group. An empty group clears the assignment and makes the entity public (replicated to all otherwise-eligible sessions). Concurrency-safe under interestMu and never waits on network I/O. Public→grouped (and other) mutations after a blind/filtered decision or connect-snapshot ID selection apply on the next replication pass via known-set removal/full transitions; already selected/queued frames are not retroactively revoked.
func (*Server) SetNavBackend ¶
SetNavBackend registers a nav backend for use by Server.FindPath and Server.SetNavWalkable. Call this at startup after building your grid from map data. Passing nil disables the nav backend.
func (*Server) SetNavWalkable ¶
SetNavWalkable marks the cell at world-space (x, y) as passable (true) or impassable (false). No-op if no nav backend is set or the backend does not implement NavDynamicBackend.
func (*Server) SetOwner ¶
SetOwner updates the owning session of an existing entity for command authority immediately (e.g. reconnect with a new session ID). sessionID 0 clears ownership. Ownership transfer does not transfer avatar identity: session↔avatar indexes from SpawnAvatar are unchanged. Re-bind avatars explicitly with SpawnAvatar after disconnect cleanup (or after DeleteEntity) rather than via SetOwner.
Concurrent SetOwner calls are serialized under interestMu (lock order: interestMu before the registry mutex). Owner lookup, registry mutation, and ownership-refresh coalescing are atomic relative to other Server.SetOwner calls so a stale pre-change owner cannot be recorded. Locks are not held across network sends or registry hooks.
For entities with visibility: owner vars, SetOwner also queues a replication confidentiality refresh processed on the next replication pass: the original old owner that still knows the entity receives public full state (clearing retained private fields), and the final new owner that knows it receives authoritative full state. Same-tick A→…→A coalesces to a no-op. Visibility: owner is replication redaction only — command authorization remains the separate Owner check used by generated routers.
func (*Server) SetRemovalSerializer ¶
func (s *Server) SetRemovalSerializer(fn RemovalSerializer)
SetRemovalSerializer registers the function used to serialize EntityRemoved messages. Pass the generated synced.MarshalEntityRemoved.
func (*Server) SetWebTransportCheckOrigin ¶
SetWebTransportCheckOrigin overrides the WebTransport origin policy. Passing nil restores the policy built from ServerConfig.
func (*Server) SnapshotAll ¶
SnapshotAll returns a full-state serialized update for every live entity.
func (*Server) SpawnAvatar ¶ added in v0.3.0
func (s *Server) SpawnAvatar(sess *Session, e Entity, opts AvatarOptions) error
SpawnAvatar registers e as sess's avatar: CreateEntity(e, sess.ID), optional FOI when opts.FOIRadius > 0, and session↔entity avatar indexes.
Duplicate calls for a session that already has a live avatar return an error; a prior avatar is not replaced. Partial failures roll back the entity, FOI, and any reserved index slot where possible. FOI updates go through AssignFOI / RemoveFOI (interestMu); avatar indexes use avatarMu. Lock order when both are needed: interestMu before avatarMu.
func (*Server) SubmitTask ¶ added in v0.3.0
func (s *Server) SubmitTask(ctx context.Context, work func(context.Context) error, complete func(*Server, error)) error
SubmitTask schedules work on the bounded background worker pool. work runs off the tick goroutine; complete runs later on the tick goroutine (after OnTickStart, before session-message drain), sharing the AsyncCallbacksPerTick budget with Post.
Ownership: work must treat inputs as immutable/caller-owned and must not touch Server entities, registry, visibility, sessions, or other tick-owned state. Only complete (or Post) may mutate game/server state. Values captured by work and read in complete are safely visible: the worker's completion enqueue happens-before the tick drain receives and invokes complete.
The effective work context is derived from ctx (so an already-cancelled or queue-cancelled caller context is visible synchronously when work starts) and cancelled when the server run context ends. A non-nil error returned by work is delivered unchanged. If work returns nil after the effective context has ended, complete receives that context error. A panic in work is recovered, logged with a stack, and delivered as an error wrapping ErrTaskPanicked; while the server remains running, complete still runs exactly once for that task.
SubmitTask returns ErrServerNotRunning before Run, once shutdown is linearized, and after Run returns. A saturated pool queue returns ErrTaskQueueFull immediately without blocking. Nil ctx, work, or complete return a non-nil validation error and are not accepted.
When the independent completion queue is full, a finished worker applies bounded backpressure (select on the run context) so completions are not dropped while the server remains running and workers never block past shutdown. On shutdown, queued-not-started tasks are not executed, in-flight work receives cancellation, queued completions/posts are discarded, and no complete/Post callback runs after the tick loop exits. Work that ignores context cancellation can delay Run's return indefinitely.
Pipeline counters are exposed by TaskStats / Server.TaskStats. TasksAccepted is incremented under lifeMu before the per-submission start gate opens, so worker finish/cancel/panic counters cannot observe an accepted task before TasksAccepted reflects it. TasksFinished increments when work returns or panics; TaskCompletionsExecuted increments only when complete actually runs on the tick goroutine (so shutdown discard is observable as finished without executed). Rejected submissions never open the gate and are not counted as accepted.
func (*Server) TaskStats ¶ added in v0.3.0
TaskStats returns independently sampled pipeline counters and live gauges. Values are read separately (atomics and gauges are not frozen together), so the returned struct is not a cross-field consistent point-in-time cut under concurrency. See TaskStats field docs for counter semantics.
func (*Server) Tick ¶
Tick returns the current tick counter. The counter is 1-based and is incremented at the start of each tick before OnTickStart fires. Safe to read from OnTick, OnTickStart, and OnTickEnd.
func (*Server) WaitReady ¶
WaitReady blocks until the integrated listener has prepared its transport endpoint. When WebTransport is active, the TLS certificate has been resolved after this returns nil.
func (*Server) WebSocketHandler ¶ added in v0.3.0
func (s *Server) WebSocketHandler() http.HandlerFunc
WebSocketHandler returns a WebSocket endpoint handler backed by the same sessions, hooks, snapshots, and game loop as the configured primary transport. Mount it on a caller-owned HTTP server to provide a fallback for a WebTransport primary endpoint.
func (*Server) WebTransportCertificateHashes ¶
func (s *Server) WebTransportCertificateHashes() []golemnet.CertificateHash
WebTransportCertificateHashes returns the WebTransport certificate digests known by the integrated listener.
func (*Server) WebTransportServer ¶
func (s *Server) WebTransportServer(h3 *http3.Server) *webtransport.Server
WebTransportServer returns the configured WebTransport server for callers that mount Server.Handler on a caller-owned HTTP/3 server. Callers still own TLS configuration and server startup.
type ServerBinder ¶ added in v0.3.0
type ServerBinder interface {
BindServer(*Server)
}
ServerBinder is implemented by entities that store a back-reference to the owning Server. CreateEntity calls BindServer after ID assignment and before registry Add/AddOwned so OnSpawn can use the bound server.
type ServerConfig ¶
type ServerConfig struct {
TickRate int // ticks per second (default: 20)
Addr string // listen address (e.g. ":8080" or ":4433"); enables integrated networking when set
Path string // transport endpoint path (default: "/ws" or "/wt")
Transport golemnet.Transport // integrated transport kind (default: golem.TransportWebTransport)
TLSCertFile string // PEM certificate file used by WebTransport / HTTP3
TLSKeyFile string // PEM private key file used by WebTransport / HTTP3
DevSelfSignedCert bool // generate a short-lived self-signed certificate for WebTransport when no files are configured
// WebTransportAllowedOrigins lists exact browser origins allowed to connect
// to WebTransport, e.g. "https://game.example.com:8080".
WebTransportAllowedOrigins []string
// WebTransportAllowSameHostOrigin allows HTTPS origins whose hostname
// matches the WebTransport request host, regardless of port.
WebTransportAllowSameHostOrigin bool
StaticDir string // directory of static files served over HTTP (optional)
MapDir string // directory of map files served at /maps/ over HTTP (optional)
CellSize float64 // spatial hash cell size; >0 enables interest management
StateUpdateLane StateUpdateLane // incremental entity update transport lane (default: datagram)
// LogReplicationStats emits a log line about once per second with batched
// state-update counts, wire message counts, and registry delta flush size
// for the most recently completed tick (reliable stream vs datagrams).
// The environment variable GOLEM_LOG_REPLICATION_STATS=1 (or "true", case
// insensitive) also turns this on for quick debugging without recompiling.
LogReplicationStats bool
// WorldSnapshotExclude lists world data names omitted from the connect
// snapshot. Entries remain in Server.World; callers own on-demand delivery
// (typically via SendWorldData / SendStoredWorldData). NewServer copies and
// normalizes the slice (drops empties/duplicates) so later caller mutation
// cannot race with snapshot reads. Large embedded maps can exceed the
// 256 KiB reliable frame cap — prefer map_url for oversized payloads.
WorldSnapshotExclude []string
// PostQueueCapacity is the bounded capacity of the tick-safe Post queue
// (default 1024). Zero selects the default; negative values panic in
// NewServer. A full queue causes Post to return ErrPostQueueFull without
// blocking. Depth is visible as TaskStats.QueuedPosts (approximate).
PostQueueCapacity int
// AsyncCallbacksPerTick caps how many task-completion and Post callbacks
// run each tick combined (default 256). Drain is round-robin that starts
// with a completion on the first drain and persists preference across
// ticks. Excess remain queued for later ticks. Zero selects the default;
// negative values panic in NewServer.
AsyncCallbacksPerTick int
// TaskWorkers is the maximum Pond worker concurrency for SubmitTask
// (default 4). Zero selects the default; negative values panic in NewServer.
// Live concurrency is visible as TaskStats.RunningTasks (approximate).
TaskWorkers int
// TaskQueueCapacity is the bounded Pond task-queue capacity for SubmitTask
// (default 256). Zero selects the default; negative values panic in
// NewServer. A full queue causes SubmitTask to return ErrTaskQueueFull
// without blocking. Depth is visible as TaskStats.QueuedTasks (approximate).
TaskQueueCapacity int
// TaskCompletionQueueCapacity is the bounded capacity of the independent
// worker→tick completion queue (default 256). Zero selects the default;
// negative values panic in NewServer. When full, finished workers apply
// backpressure until capacity frees or the run context ends. Depth is
// visible as TaskStats.QueuedCompletions (approximate).
TaskCompletionQueueCapacity int
}
ServerConfig holds configuration for the game server.
type SnapshotRecord ¶
SnapshotRecord is the decoded state of one entity from a snapshot file. Pass records from snapshot.Load to the generated RestoreEntity helper.
type Spatial3DEntity ¶
type Spatial3DEntity = registry.Spatial3DEntity
Spatial3DEntity is satisfied by generated 3D entities with Position3D.
type StateUpdateLane ¶
type StateUpdateLane string
StateUpdateLane selects the transport lane used for incremental entity updates during integrated networking.
const ( // StateUpdateLaneStream keeps incremental entity updates on the reliable // stream path. StateUpdateLaneStream StateUpdateLane = "stream" // StateUpdateLaneDatagram sends incremental entity updates over // state-aware WebTransport datagrams that rebase lost fields to current values. StateUpdateLaneDatagram StateUpdateLane = "datagram" )
type TaskStats ¶ added in v0.3.0
type TaskStats struct {
// QueuedTasks is the number of accepted tasks waiting in the worker-pool
// queue (not yet executing). Approximate under concurrency.
QueuedTasks uint64
// RunningTasks is the number of active worker goroutines currently
// executing accepted task wrappers. Approximate under concurrency.
RunningTasks uint64
// QueuedCompletions is the instantaneous length of the independent
// worker→tick completion queue. Approximate under concurrency.
QueuedCompletions uint64
// QueuedPosts is the instantaneous length of the Post queue.
// Approximate under concurrency.
QueuedPosts uint64
// TasksAccepted counts SubmitTask calls that successfully entered the
// worker pool (not validation failures, not ErrServerNotRunning, not
// ErrTaskQueueFull).
TasksAccepted uint64
// TasksFinished counts accepted tasks whose work function returned or
// panicked. Distinct from TaskCompletionsExecuted: finished work may
// still be awaiting tick drain, or its completion may be discarded on
// shutdown without running the callback.
TasksFinished uint64
// TaskCompletionsExecuted counts completion callbacks that actually ran
// on the tick goroutine. Shutdown discard of queued completions does not
// increment this counter.
TaskCompletionsExecuted uint64
// TasksRejectedFull counts SubmitTask calls that returned ErrTaskQueueFull.
TasksRejectedFull uint64
// TasksCancelled counts each accepted task at most once when either
// (1) queued-not-started work is discarded on shutdown without executing
// user work, or (2) accepted work runs and its effective context has
// already ended by the time work returns (caller or server cancellation).
TasksCancelled uint64
// TaskPanics counts accepted tasks whose work function panicked
// (recovered into an ErrTaskPanicked completion error while running).
TaskPanics uint64
// PostsAccepted counts Post calls that successfully enqueued a callback.
PostsAccepted uint64
// PostsExecuted counts Post callbacks that actually ran on the tick
// goroutine. Shutdown discard of queued posts does not increment this.
PostsExecuted uint64
// PostsRejectedFull counts Post calls that returned ErrPostQueueFull.
PostsRejectedFull uint64
}
TaskStats holds independently sampled counters and live gauges for the background-task and Post pipelines. Fields are not a single cross-field consistent cut: atomics and gauges are read separately and may disagree slightly under concurrency. Cumulative counters are Golem-owned and monotonic for the Server's lifetime. Live gauges are approximate: QueuedTasks/RunningTasks come from the internal Pond pool when present; QueuedCompletions/QueuedPosts are instantaneous channel lengths and may race with producers and the tick drain.
type TickFunc ¶
TickFunc is the signature for the user's per-tick game logic callback. dt is the fixed time step in seconds; s is the server (entities, world, networking).
type TriggerEnter ¶
type TriggerEnter interface {
OnTriggerEnter(other Entity)
}
TriggerEnter is optionally implemented by entities that want to be notified when another entity's trigger shape begins overlapping their shape. other is the entity that entered; it may be nil if that entity was removed in the same tick.
type TriggerExit ¶
type TriggerExit interface {
OnTriggerExit(other Entity)
}
TriggerExit is optionally implemented by entities that want to be notified when another entity's trigger shape stops overlapping their shape. other may be nil if the other entity was removed and is no longer in the registry.
type TriggerStay ¶
type TriggerStay interface {
OnTriggerStay(other Entity)
}
TriggerStay is optionally implemented by entities that want to be notified every tick while another entity's trigger shape continues to overlap theirs. other may be nil if the other entity was removed in the same tick.
type UpdateFunc ¶
type UpdateFunc func(updates [][]byte)
UpdateFunc is called after each tick with all serialized entity updates (spawns, deltas, and removals combined) before auto-broadcast.
type WorldStore ¶
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth standardizes token-in-query-parameter authorization for realtime transport upgrades (golem.Server.OnUpgrade / golem/net.Listener.OnUpgrade).
|
Package auth standardizes token-in-query-parameter authorization for realtime transport upgrades (golem.Server.OnUpgrade / golem/net.Listener.OnUpgrade). |
|
collision
module
|
|
|
cp
module
|
|
|
resolv
module
|
|
|
Package collision3d defines pure-Go 3D collision interfaces and primitive shapes.
|
Package collision3d defines pure-Go 3D collision interfaces and primitive shapes. |
|
Package footprint loads versioned collision footprint YAML and places shapes into a collision.Backend or collision3d.Backend.
|
Package footprint loads versioned collision footprint YAML and places shapes into a collision.Backend or collision3d.Backend. |
|
Package ldtk provides types and a loader for LDtk project files (.ldtk JSON format).
|
Package ldtk provides types and a loader for LDtk project files (.ldtk JSON format). |
|
nav
module
|
|
|
kelindar
module
|
|
|
pathing
module
|
|
|
Package tiled provides types and a loader for Tiled map files (.tmj JSON format).
|
Package tiled provides types and a loader for Tiled map files (.tmj JSON format). |
|
Package visibility provides a lower-level, non-thread-safe policy manager for named visibility groups that gate entity replication.
|
Package visibility provides a lower-level, non-thread-safe policy manager for named visibility groups that gate entity replication. |