scene

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 12 Imported by: 3 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package scene organizes a game into ordered world- and screen-space layers, hit-tests sprites and custom shapes in view coordinates, and manages scene lifecycles, stacks, and transitions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ProjectToOverlay

func ProjectToOverlay(viewProj [16]float32, worldX, worldY, worldZ, viewWidth, viewHeight float32) (x, y float32, visible bool)

ProjectToOverlay projects the 3D world point (worldX, worldY, worldZ) through the column-major view-projection matrix viewProj (using [0, 1] clip depth, as math3d.Mat4 and scene3d.Camera.ViewProj produce) into 2D overlay coordinates spanning (0..viewWidth, 0..viewHeight) with (0, 0) at the top-left corner.

visible is true when the projected point lies inside the view frustum (NDC X and Y in [-1, 1] and NDC Z in [0, 1]). Points in front of the camera but outside the frustum return their projected off-screen coordinates with visible == false; points behind the camera, degenerate matrices, non-finite inputs, or non-positive view dimensions return (0, 0, false).

func SpriteContains

func SpriteContains(s *sprite.Sprite, p core.Point) bool

SpriteContains reports whether layer-space point p lies inside s's transformed untrimmed frame bounds (position, origin, scale, rotation, and flip). Invisible sprites (Alpha <= 0) never hit.

func SpriteToLocal

func SpriteToLocal(s *sprite.Sprite, p core.Point) (core.Point, bool)

SpriteToLocal maps a layer-space point p into s's untrimmed frame coordinates (0..Width, 0..Height), inverting position, origin, scale, rotation, and flip. It returns false when s has zero scale or an empty frame.

Types

type Controller

type Controller struct {
	// Scene is an optional Scene drawn and updated when Draw or Update is nil, and targeted by Manager.DispatchPress and Manager.DispatchTouch.
	Scene *Scene
	// Transparent, when true on a pushed overlay scene, lets Manager.Draw and Manager.View also show the underlying scene(s) first.
	Transparent bool
	// View optionally builds a native NSGo view tree for this scene, such as a 3D gpu.View or Overlay3D.View, when Manager.View mounts the scene.
	//
	// Its cx is the mounted row's scope, not the child scope Enter receives: when the scene leaves the Manager, Exit runs and Enter's scope is disposed first, and the row (with everything created under View's cx) is unmounted right after, within the same Switch, Pop, or transition step, so no frame or OnFrame callback runs in between. State that View's nodes read every frame should therefore be created in View or on the Manager's parent scope rather than under Enter's cx.
	View func(cx *core.Scope) core.Node
	// Enter runs once when the scene becomes active, with a child Scope owned by the Manager.
	// Loops, signals, effects, timers, and cleanups created under cx are automatically disposed when the scene exits.
	Enter func(cx *core.Scope)
	// Exit runs once when the scene leaves the Manager (by Switch, Pop, or disposing the Manager's Scope).
	Exit func()
	// Pause runs when another scene is pushed on top of this scene.
	Pause func()
	// Resume runs when the scene on top of this scene is popped.
	Resume func()
	// Update advances the scene by one fixed step dt while it is the active top scene.
	Update func(dt time.Duration)
	// Draw records the scene's frame into d; alpha is the interpolation fraction in [0, 1).
	Draw func(d *core.Drawing, alpha float64)
}

Controller defines a managed scene's lifecycle, update, view, and draw hooks.

All fields are optional. When View is set, Manager.View mounts the returned node (such as a 3D gpu.View, an Overlay3D.View, or a native UI tree) in the scene's view scope and unmounts it when the scene exits. When View is nil, Manager.View renders the scene through a 2D core.Canvas using Draw or Scene. When Draw is nil and Scene is non-nil, Manager draws Scene automatically; when Update is nil and Scene is non-nil, Manager updates Scene automatically.

type Direction

type Direction uint8

Direction is the travel direction of a Wipe transition's dividing edge.

const (
	// DirectionLeft sweeps the dividing edge from right to left, revealing the new scene on the right.
	DirectionLeft Direction = iota
	// DirectionRight sweeps the dividing edge from left to right, revealing the new scene on the left.
	DirectionRight
	// DirectionUp sweeps the dividing edge from bottom to top, revealing the new scene on the bottom.
	DirectionUp
	// DirectionDown sweeps the dividing edge from top to bottom, revealing the new scene on the top.
	DirectionDown
)

type Drawable

type Drawable struct {
	// Draw records custom drawing operations into d, running between Save and Restore.
	Draw func(d *core.Drawing)
	// Update advances custom state by one fixed step dt when Scene.Update runs.
	Update func(dt time.Duration)
	// Hit reports whether a point in the layer's coordinate space hits this drawable.
	Hit func(p core.Point) bool
	// OnPress runs when Scene.DispatchPress hits this drawable as the topmost target.
	OnPress func(hit HitResult, ev core.PressEvent)
	// OnTouch runs when Scene.DispatchTouch hits this drawable as the topmost target.
	OnTouch func(hit HitResult, ev core.TouchEvent)
	// Z orders the drawable relative to other items in its layer: a higher Z draws over a lower one.
	Z int
	// Y is the vertical baseline coordinate used when its Layer's DepthSort is SortY (unless overridden by Layer.SortKey).
	Y float32
	// Visible controls whether the drawable is drawn and hit-tested.
	Visible bool
}

Drawable is a custom layer item with optional draw, update, hit-test, and input callbacks.

Its zero value is hidden (Visible is false); NewDrawable returns a visible Drawable.

func NewDrawable

func NewDrawable(draw func(d *core.Drawing)) *Drawable

NewDrawable returns a visible Drawable with draw as its Draw callback.

type HUD3D

type HUD3D struct {
	// Children are native NSGo views mounted directly in the safe-area HUD
	// container in slice order.
	Children []core.Node
	// Slots are anchored native NSGo HUD elements positioned inside the
	// safe-area HUD container after Children.
	Slots []HUDSlot
	// Padding adds extra inner margins around the HUD content on top of any
	// safe-area insets.
	Padding core.Edges
	// IgnoreSafeArea disables automatic core.EnvSafeArea padding when true.
	// By default (false), HUD content automatically respects platform
	// safe-area insets.
	IgnoreSafeArea bool
	// Hidden hides the HUD layer (DisplayNone and PointerEventsNone) when true,
	// forwarding all mouse and touch input to the 3D view underneath.
	Hidden bool
	// Style optionally supplies additional layout styles for the inner HUD
	// container (for example Gap, Direction, AlignItems, JustifyContent, or
	// ZIndex on the outer overlay).
	Style core.Style
	// TestID optionally sets core.View.TestID on the outer HUD overlay view.
	TestID string
	// Label optionally sets core.View.Label on the outer HUD overlay view.
	Label string
	// contains filtered or unexported fields
}

HUD3D composes native NSGo views (such as ui.Button, ui.Card, ui.Badge, ui.Progress, ui.Switch, and core.Text) over a 3D gpu.View.

The overlay layer uses core.PointerEventsBoxNone so interactive HUD controls receive mouse and touch input directly while open regions pass mouse and touch events straight through to the 3D view underneath. Safe-area insets (core.EnvSafeArea) are applied automatically by default so HUD controls stay clear of notches, status bars, and home indicators, and visibility can be toggled reactively without remounting HUD subtrees.

func NewHUD3D

func NewHUD3D(cx *core.Scope) *HUD3D

NewHUD3D returns a visible HUD3D bound to cx with safe-area insets enabled. A nil cx defers reactive scope binding until Layer, View, or Wrap mounts the HUD in a scope.

func (*HUD3D) Add

func (h *HUD3D) Add(nodes ...core.Node)

Add appends one or more native NSGo view nodes to h.Children. Nil nodes are ignored.

func (*HUD3D) AddAt

func (h *HUD3D) AddAt(anchor HUDAnchor, node core.Node)

AddAt appends node anchored at anchor inside the safe-area HUD frame.

func (*HUD3D) AddPassThrough

func (h *HUD3D) AddPassThrough(anchor HUDAnchor, node core.Node)

AddPassThrough appends a non-interactive decorative node anchored at anchor with core.PointerEventsNone so all mouse and touch input passes straight through it to the 3D view underneath.

func (*HUD3D) AddSlot

func (h *HUD3D) AddSlot(slot HUDSlot)

AddSlot appends slot to h.Slots when slot.Node is non-nil.

func (*HUD3D) Layer

func (h *HUD3D) Layer(cx *core.Scope) core.Node

Layer returns the absolutely positioned, pass-through native HUD overlay node covering its parent bounds. Mount it directly in gpu.ViewProps.Children, above a 2D Overlay3D canvas, or compose it automatically via HUD3D.View or HUD3D.Wrap.

func (*HUD3D) SafeAreaEnabled

func (h *HUD3D) SafeAreaEnabled() bool

SafeAreaEnabled reports whether automatic safe-area inset padding is enabled. When called inside a reactive binding, it subscribes to safe-area toggle changes.

func (*HUD3D) SetHidden

func (h *HUD3D) SetHidden(hidden bool)

SetHidden hides or shows the HUD overlay reactively. While hidden, the HUD layer uses core.DisplayNone and core.PointerEventsNone so all mouse and touch events reach the 3D view underneath.

func (*HUD3D) SetSafeArea

func (h *HUD3D) SetSafeArea(enabled bool)

SetSafeArea enables or disables automatic core.EnvSafeArea inset padding on the HUD overlay reactively.

func (*HUD3D) SetVisible

func (h *HUD3D) SetVisible(visible bool)

SetVisible shows or hides the HUD overlay reactively. It is the inverse of SetHidden.

func (*HUD3D) Toggle

func (h *HUD3D) Toggle() bool

Toggle flips HUD visibility and returns the new Visible state.

func (*HUD3D) View

func (h *HUD3D) View(cx *core.Scope, props gpu.ViewProps) core.Node

View returns a gpu.View configured by props with h's native HUD layer mounted on top of the 3D GPU surface (and above any existing props.Children such as a 2D overlay canvas).

func (*HUD3D) Visible

func (h *HUD3D) Visible() bool

Visible reports whether the HUD overlay is currently visible. When called inside a reactive binding or StyleFunc, it subscribes to visibility changes.

func (*HUD3D) Wrap

func (h *HUD3D) Wrap(cx *core.Scope, view3D core.Node) core.Node

Wrap composes view3D and h's native HUD layer as siblings in a Z-stack core.View, placing the HUD above view3D.

Use Wrap when view3D is already constructed (for example a gpu.View wrapped in an interactive core.View that handles OnMouseDown, OnMouseMove, and OnTouch for 3D camera orbit or picking) so touches and hovers on HUD controls never bubble into view3D while open HUD regions pass all mouse and touch events through to view3D.

type HUDAnchor

type HUDAnchor uint8

HUDAnchor names a region inside a HUD3D safe-area frame where a HUDSlot is placed.

const (
	// HUDFull stretches across the full HUD area inside safe-area insets and
	// padding while passing open regions through to the 3D view underneath.
	HUDFull HUDAnchor = iota
	// HUDTopLeft anchors content to the top-left corner.
	HUDTopLeft
	// HUDTopCenter anchors content horizontally centered along the top edge.
	HUDTopCenter
	// HUDTopRight anchors content to the top-right corner.
	HUDTopRight
	// HUDCenterLeft anchors content vertically centered along the left edge.
	HUDCenterLeft
	// HUDCenter anchors content centered both horizontally and vertically.
	HUDCenter
	// HUDCenterRight anchors content vertically centered along the right edge.
	HUDCenterRight
	// HUDBottomLeft anchors content to the bottom-left corner.
	HUDBottomLeft
	// HUDBottomCenter anchors content horizontally centered along the bottom edge.
	HUDBottomCenter
	// HUDBottomRight anchors content to the bottom-right corner.
	HUDBottomRight
)

func (HUDAnchor) String

func (a HUDAnchor) String() string

String returns the anchor's name.

type HUDSlot

type HUDSlot struct {
	// Anchor chooses where the slot sits inside the safe-area HUD frame.
	// Its zero value is HUDFull.
	Anchor HUDAnchor
	// Node is the native NSGo view rendered in this slot.
	Node core.Node
	// PassThrough sets core.PointerEventsNone on the slot so mouse clicks,
	// drags, and touches pass straight through decorative HUD elements (such
	// as crosshairs or status readouts) to the 3D view underneath.
	PassThrough bool
	// Padding optionally insets the slot's content from its anchor edges.
	Padding core.Edges
	// TestID optionally sets core.View.TestID on the slot's anchor wrapper.
	TestID string
}

HUDSlot places one native NSGo view subtree (such as ui.Button, ui.Card, ui.Badge, ui.Progress, or core.View) inside a HUD3D overlay.

type HitFunc

type HitFunc func(p core.Point) bool

HitFunc reports whether p (in the layer's coordinate space: world space for SpaceWorld, view space for SpaceScreen) hits a target.

func CircleHit

func CircleHit(center core.Point, radius float32) HitFunc

CircleHit returns a HitFunc that hits points within radius of center (inclusive).

func PolygonHit

func PolygonHit(vertices ...core.Point) HitFunc

PolygonHit returns a HitFunc that tests whether a point lies inside or on the boundary of the polygon formed by vertices.

func RectHit

func RectHit(bounds core.Bounds) HitFunc

RectHit returns a HitFunc that hits points inside bounds (inclusive of edges).

func SpriteLocalHit

func SpriteLocalHit(s *sprite.Sprite, local HitFunc) HitFunc

SpriteLocalHit returns a HitFunc that transforms each tested point into s's untrimmed local frame space before evaluating local.

type HitOptions

type HitOptions struct {
	// Hit overrides the sprite's default transformed untrimmed bounds when non-nil.
	Hit HitFunc
	// OnPress runs when Scene.DispatchPress hits this sprite as the topmost target.
	OnPress func(hit HitResult, ev core.PressEvent)
	// OnTouch runs when Scene.DispatchTouch hits this sprite as the topmost target.
	OnTouch func(hit HitResult, ev core.TouchEvent)
	// Ignore excludes the sprite from hit testing when true.
	Ignore bool
}

HitOptions configures custom hit testing and press/touch callbacks for a sprite in a Scene.

type HitResult

type HitResult struct {
	// Layer is the layer containing the hit target.
	Layer *Layer
	// Space is the layer's coordinate space (SpaceWorld or SpaceScreen).
	Space Space
	// Point is the tested point in the layer's coordinate space: world coordinates for SpaceWorld, view coordinates for SpaceScreen.
	Point core.Point
	// ViewPoint is the original tested point in view coordinates.
	ViewPoint core.Point
	// Sprite is non-nil when the hit target is a sprite inside a Batch.
	Sprite *sprite.Sprite
	// Batch is the sprite's batch when Sprite is non-nil.
	Batch *sprite.Batch
	// Drawable is non-nil when the hit target is a custom Drawable.
	Drawable *Drawable
}

HitResult describes one target hit by a view-space point.

type HostOptions

type HostOptions struct {
	// Class sets Tailwind CSS classes on the outer host container view.
	Class string
	// Style sets layout and appearance on the outer host container view. When Width or Height are unset, the missing dimension defaults to 100%. When Position is unset, it defaults to core.Relative.
	Style core.Style
	// StyleFunc optionally supplies reactive styles for the outer host container view.
	StyleFunc func() core.Style
	// Ref optionally attaches a core.Ref to the persistent interactive stage view (where Manager.Actions is attached). Call Ref.Focus once the host is mounted so focused key input reaches Manager.Actions; the stage persists across 2D and 3D scene switches, so focus and pointer lock survive them.
	Ref *core.Ref
	// TestID optionally sets core.View.TestID on the outer host container view.
	TestID string
	// StageTestID optionally sets core.View.TestID on the inner stage view that receives attached input events and hosts mounted scenes.
	StageTestID string
	// TransitionTestID optionally sets core.View.TestID on the top transition overlay canvas.
	TransitionTestID string
	// Label optionally sets core.View.Label on the outer host container view.
	Label string
	// OnLayout optionally receives layout bounds changes of the outer host view.
	OnLayout func(core.Bounds)
	// Alpha optionally returns the interpolation fraction in [0, 1) for 2D scene redraws. Reading a reactive signal inside Alpha (such as a loop tick or interpolation signal) redraws mounted 2D canvases on every loop frame without causing mounted 3D gpu.View scenes to rebuild or commit.
	Alpha func() float64
	// Viewport optionally scales and clips 2D scenes rendered by the host through screen.Viewport. Transparent pushed 2D overlays treat a zero BarColor as core.Transparent so underlying 3D views remain visible in margin areas.
	Viewport *screen.Viewport
	// Children are optional persistent native views (such as a global HUD, audio controls, or debug overlay) mounted above all scenes and transitions.
	Children []core.Node
}

HostOptions configures the reactive view host returned by Manager.View.

type Item

type Item struct {
	Batch     *sprite.Batch
	Tilemap   *tilemap.Tilemap
	TileLayer *tilemap.TileLayer
	Drawable  *Drawable
	Z         int
}

Item is one entry in a Layer: a sprite batch, a tilemap (or single tile layer), or a custom Drawable.

Z orders items within their layer (lowest first, ties keeping slice order). For a Drawable, a zero Item.Z falls back to Drawable.Z so changing Drawable.Z takes effect immediately. When Tilemap and TileLayer are both set, only TileLayer is drawn instead of the entire Tilemap.

type Layer

type Layer struct {
	// Name identifies the layer for Scene.Layer lookups.
	Name string
	// Space selects whether the layer draws under Scene.Camera (SpaceWorld) or directly in view space (SpaceScreen).
	Space Space
	// Visible controls whether the layer is drawn and hit-tested.
	Visible bool
	// Order sorts layers in a Scene: a higher Order draws over a lower one, ties keeping the Scene.Layers slice order.
	Order int
	// Items are the batches, tilemaps, and custom drawables in the layer.
	Items []Item

	// ParallaxX and ParallaxY scale how fast a SpaceWorld layer scrolls relative to Scene.Camera.
	// On a struct literal without SetParallax/NewLayer/NewParallaxLayer, zero values default to 1.0.
	ParallaxX, ParallaxY float32
	// OffsetX and OffsetY shift the layer's content in layer coordinates.
	OffsetX, OffsetY float32
	// RepeatX and RepeatY tile a SpaceWorld layer seamlessly across the camera's visible region using RepeatWidth and RepeatHeight as periods.
	RepeatX, RepeatY bool
	// RepeatWidth and RepeatHeight are the horizontal and vertical repeat periods in layer points when RepeatX / RepeatY are enabled.
	RepeatWidth, RepeatHeight float32

	// DepthSort controls how items and sprites within the layer are depth-sorted during Draw and HitTest.
	DepthSort SortMode
	// SortKey optionally supplies a custom depth key for items in SortY (or SortCustom when SortFunc is nil).
	SortKey func(Item) float32
	// SpriteSortKey optionally supplies a custom depth key for sprites in SortY (after Sprite.Z) or SortCustom.
	SpriteSortKey func(*sprite.Sprite) float32
	// SortFunc supplies a custom item comparator when DepthSort is SortCustom.
	SortFunc func(a, b Item) int
	// contains filtered or unexported fields
}

Layer holds an ordered list of items drawn in either world or screen space.

Its zero value is hidden (Visible is false); NewLayer returns a visible Layer.

func NewLayer

func NewLayer(name string, space Space, order int) *Layer

NewLayer returns a visible Layer with the given name, coordinate space, and draw order.

func NewParallaxLayer

func NewParallaxLayer(name string, order int, parallaxX, parallaxY float32) *Layer

NewParallaxLayer returns a visible SpaceWorld Layer with the given draw order and parallax scroll factors.

Factors of 0 keep the layer fixed against camera translation, 0.5 scrolls at half the camera's speed, 1.0 matches the world camera, and values greater than 1.0 scroll faster for foreground layers.

Example

A parallax layer scrolls slower than the camera, which makes a background look far away.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/scene"
)

func main() {
	hills := scene.NewParallaxLayer("hills", -1, 0.5, 0)
	fmt.Println(hills.Name, hills.Space == scene.SpaceWorld, hills.ParallaxX, hills.ParallaxY)
}
Output:
hills true 0.5 0

func (*Layer) AddBatch

func (l *Layer) AddBatch(b *sprite.Batch)

AddBatch appends a sprite batch to the layer.

func (*Layer) AddDrawable

func (l *Layer) AddDrawable(d *Drawable)

AddDrawable appends a custom Drawable to the layer.

func (*Layer) AddItem

func (l *Layer) AddItem(item Item)

AddItem appends an explicit Item to the layer.

func (*Layer) AddTileLayer

func (l *Layer) AddTileLayer(m *tilemap.Tilemap, layer *tilemap.TileLayer)

AddTileLayer appends a single TileLayer of m to the layer. When layer.YSort is true and the scene Layer uses SortY, its visible tiles join the layer's Y-sorted draw list.

func (*Layer) AddTilemap

func (l *Layer) AddTilemap(m *tilemap.Tilemap)

AddTilemap appends a tilemap to the layer.

func (*Layer) Parallax

func (l *Layer) Parallax() (x, y float32)

Parallax returns the layer's effective horizontal and vertical parallax scroll factors. Unset zero factors on a struct literal report 1, while factors set with NewLayer, NewParallaxLayer or SetParallax are returned verbatim.

func (*Layer) SetParallax

func (l *Layer) SetParallax(x, y float32) *Layer

SetParallax sets the layer's horizontal and vertical parallax scroll factors and returns l.

Calling SetParallax marks parallax factors as explicitly configured so zero factors lock an axis instead of defaulting to 1.

type Manager

type Manager struct {
	// Actions is an optional input action map shared across all 2D and 3D scenes managed by this Manager.
	//
	// When non-nil, Manager.View attaches Actions to its persistent stage view so touch, mouse, pointer-lock, and focused key input survive scene switches without re-binding. Set Actions before calling Manager.View: the stage is wired once when View builds it, so assigning Actions afterwards attaches nothing. Key events reach the stage only while it holds focus (focus it through HostOptions.Ref); to read keys regardless of focus, also call Actions.WatchKeys on the Manager's scope. Switch, Push, and Pop call Actions.Reset() by default (unless KeepInputOnSwitch is true) so transient press edges and held keys do not leak into the newly active scene while bindings, axes, and pointer lock remain intact.
	Actions *input.Actions
	// KeepInputOnSwitch, when true, skips calling Actions.Reset() on Switch, Push, and Pop so held keys and buttons stay continuously active across scene changes.
	KeepInputOnSwitch bool
	// contains filtered or unexported fields
}

Manager owns a stack of scenes under a core.Scope, driving their lifecycle hooks, child-scope disposal, view mounting for 2D and 3D scenes, shared input, and animated transitions.

Audio needs no Manager support to outlive a switch: a sound.Mixer created on the Manager's parent scope (the cx passed to NewManager, or an ancestor of it) is not disposed when scenes exit, so its music keeps playing and its SFX groups stay live while scenes reach it through their own closures. A Mixer created under a scene's Enter scope is disposed with that scene.

Example

A Manager keeps a stack of scenes: Push pauses the scene below, such as gameplay under a pause menu, and Pop resumes it. Switch replaces the stack, animating the transition over display frames; here a manual clock stands in for the display.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/scene"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	clock := core.NewManualClock(time.Unix(0, 0))
	frameWanted := false
	root := core.NewRoot(core.RootOptions{Clock: clock, RequestFrame: func() { frameWanted = true }})
	defer root.Dispose() // disposing the root exits the scene still on the stack
	frame := func(d time.Duration) {
		clock.Advance(d)
		if frameWanted {
			frameWanted = false
			root.RunFrame()
		}
	}

	m := scene.NewManager(root)
	logged := func(name string) *scene.Controller {
		return &scene.Controller{
			Enter:  func(*core.Scope) { fmt.Println("enter", name) },
			Exit:   func() { fmt.Println("exit", name) },
			Pause:  func() { fmt.Println("pause", name) },
			Resume: func() { fmt.Println("resume", name) },
		}
	}
	m.Push(logged("level"))
	m.Push(logged("pause menu"))
	fmt.Println("depth", m.Depth())
	m.Pop()
	m.Switch(logged("title"), scene.Fade(500*time.Millisecond, core.RGB(0x000000)))
	frame(0)
	frame(250 * time.Millisecond)
	fmt.Println(m.Transitioning(), m.TransitionProgress())
	frame(250 * time.Millisecond)
	fmt.Println(m.Transitioning())
}
Output:
enter level
pause level
enter pause menu
depth 2
exit pause menu
resume level
enter title
true 0.5
exit level
false
exit title
Example (Switch2D3D)

ExampleManager_switch2D3D switches between a 2D canvas scene and a 3D gpu.View scene through one Manager and one shared input.Actions, fading through black each way. Mounting the scenes with Manager.View needs a running app, so this example shows the scene lifecycle the host follows; TestManagerSwitch2DTo3DAndBackWithSharedInputAndSound mounts the same pair and checks the 3D view mounts once and unmounts on exit.

package main

import (
	"fmt"
	"time"

	"github.com/nsgo-dev/game/pkg/input"
	"github.com/nsgo-dev/game/pkg/scene"
	"github.com/nsgo-dev/nsgo/core"
	"github.com/nsgo-dev/nsgo/gpu"
)

func main() {
	clock := core.NewManualClock(time.Unix(0, 0))
	frameWanted := false
	root := core.NewRoot(core.RootOptions{Clock: clock, RequestFrame: func() { frameWanted = true }})
	defer root.Dispose()
	frame := func(d time.Duration) {
		clock.Advance(d)
		if frameWanted {
			frameWanted = false
			root.RunFrame()
		}
	}

	mgr := scene.NewManager(root)
	mgr.Actions = input.NewActions()
	mgr.Actions.Bind("toggle", input.Key("tab"))

	var scene2D, scene3D *scene.Controller
	scene2D = &scene.Controller{
		Scene: scene.NewScene(nil),
		Enter: func(*core.Scope) { fmt.Println("enter 2D") },
		Exit:  func() { fmt.Println("exit 2D") },
		Update: func(time.Duration) {
			if mgr.Actions.JustPressed("toggle") {
				mgr.Switch(scene3D, scene.Fade(200*time.Millisecond, core.RGB(0x000000)))
			}
		},
	}
	scene3D = &scene.Controller{
		Enter: func(*core.Scope) { fmt.Println("enter 3D") },
		Exit:  func() { fmt.Println("exit 3D") },
		View: func(cx *core.Scope) core.Node {
			return gpu.View(cx, gpu.ViewProps{
				Style:       core.Style{Width: core.Pct(100), Height: core.Pct(100)},
				DepthFormat: gpu.FormatDepth24Plus,
			})
		},
		Update: func(time.Duration) {
			if mgr.Actions.JustPressed("toggle") {
				mgr.Switch(scene2D, scene.Fade(200*time.Millisecond, core.RGB(0x000000)))
			}
		},
	}

	mgr.Switch(scene2D, nil)
	mgr.Actions.Trigger("toggle")
	mgr.Actions.Step()
	mgr.Update(16 * time.Millisecond) // switches 2D -> 3D with fade
	frame(0)
	frame(100 * time.Millisecond)
	fmt.Println("mid-fade transitioning:", mgr.Transitioning())
	frame(100 * time.Millisecond)
	fmt.Println("after fade, in 3D:", mgr.Current() == scene3D)

	mgr.Actions.Trigger("toggle")
	mgr.Actions.Step()
	mgr.Update(16 * time.Millisecond) // switches 3D -> 2D with fade
	frame(0)
	frame(200 * time.Millisecond)
	fmt.Println("back in 2D:", mgr.Current() == scene2D)
}
Output:
enter 2D
enter 3D
mid-fade transitioning: true
exit 2D
after fade, in 3D: true
enter 2D
exit 3D
back in 2D: true
exit 2D

func NewManager

func NewManager(cx *core.Scope) *Manager

NewManager returns a Manager whose scenes run inside child scopes of cx. Disposing cx exits any active scenes and cancels any running transition.

func (*Manager) Current

func (m *Manager) Current() *Controller

Current returns the active scene at the top of the stack, or nil when empty.

func (*Manager) Depth

func (m *Manager) Depth() int

Depth returns the number of scenes currently on the stack.

func (*Manager) DispatchPress

func (m *Manager) DispatchPress(ev core.PressEvent) bool

DispatchPress forwards ev to the active scene's Scene.DispatchPress when present.

func (*Manager) DispatchTouch

func (m *Manager) DispatchTouch(ev core.TouchEvent) bool

DispatchTouch forwards ev to the active scene's Scene.DispatchTouch when present.

func (*Manager) Draw

func (m *Manager) Draw(d *core.Drawing, size core.Size, alpha float64)

Draw draws the active scene (or active transition) into d for a canvas of size.

Reading from Draw inside a core.Canvas subscribes the canvas to scene changes and transition frames automatically.

func (*Manager) Invalidate

func (m *Manager) Invalidate()

Invalidate marks the manager's 2D canvases dirty so they redraw on the next frame without rebuilding or unmounting mounted 3D views.

func (*Manager) Pop

func (m *Manager) Pop() *Controller

Pop exits and disposes the top scene, resumes the underlying scene (if any), and returns the popped Controller (or nil if the stack was empty).

func (*Manager) Push

func (m *Manager) Push(next *Controller)

Push pauses the current top scene (if any) and enters next on top of the stack in its own child Scope.

func (*Manager) Stack

func (m *Manager) Stack() []*Controller

Stack returns the active scene controllers from bottom to top of the stack, or nil when the stack is empty.

func (*Manager) Switch

func (m *Manager) Switch(next *Controller, transition *Transition)

Switch replaces the current scene stack with next.

When transition is nil or has a non-positive Duration, the old scenes exit and dispose their child scopes immediately before next enters. When transition has a positive Duration, next enters immediately while the old scenes remain alive to render until the transition completes on the frame clock, at which point the old scenes exit and dispose their child scopes.

func (*Manager) TransitionProgress

func (m *Manager) TransitionProgress() float64

TransitionProgress returns the active transition's eased progress in [0, 1], or 1 when no transition is running.

func (*Manager) Transitioning

func (m *Manager) Transitioning() bool

Transitioning reports whether a Switch transition is currently running.

func (*Manager) Update

func (m *Manager) Update(dt time.Duration)

Update advances the top active scene by dt.

func (*Manager) View

func (m *Manager) View(opts HostOptions) core.Node

View returns a reactive NSGo view host that mounts and switches between 2D canvas scenes (Controller.Draw / Controller.Scene) and 3D or native view scenes (Controller.View, such as gpu.View or Overlay3D.View).

Each entered scene is keyed by a unique instance ID via core.Each so mounted views (including 3D gpu.View surfaces and GPU pipelines) stay alive across transition frames and across Push/Pop of 2D overlays, and unmount cleanly when the scene exits. The host owns no state of its own: everything it renders lives on the Manager, so it needs no scope beyond the one it is mounted in.

When Manager.Actions is non-nil at the time View is called, View attaches it to the persistent stage view so touch, mouse, pointer-lock, and focused key input stay wired across 2D <-> 3D scene switches. Key events reach the stage only while it holds focus; focus it through HostOptions.Ref, or call Actions.WatchKeys to read keys regardless of focus.

Across a boundary involving a Controller.View scene:

  • Fade(d, color) (non-transparent) fades the outgoing scene under a colored overlay canvas over the first half, reveals the incoming scene at the midpoint, and fades the overlay out over the second half.
  • Crossfade(d) (or Fade(d, 0)) crossfades the outgoing and incoming scene wrappers' Opacity from 1->0 and 0->1.
  • Wipe(d, dir) uses exact path clipping between 2D scenes and falls back to smooth crossfade opacity when a Controller.View scene is involved.
  • CustomTransition, or a constructor's Transition whose Draw the caller replaced, runs Transition.Draw directly between 2D scenes, or switches visibility at the midpoint while drawing custom overlay effects on top when a Controller.View scene is involved.
  • A Transition with a nil Draw shows the incoming scene for its whole Duration, as Manager.Draw does.

type Overlay3D

type Overlay3D struct {
	// Scene is an optional Scene whose visible SpaceScreen layers draw over the
	// 3D view. SpaceWorld layers in Scene are skipped.
	Scene *Scene
	// Layers are additional 2D layers drawn over the 3D view alongside Scene's
	// SpaceScreen layers, ordered together by stable ascending Layer.Order.
	Layers []*Layer
	// Batches are standalone sprite batches drawn over the layers in slice order.
	Batches []*sprite.Batch
	// Viewport optionally scales and clips the 2D overlay to a virtual
	// resolution using screen.Viewport. A zero BarColor defaults to transparent
	// so the 3D scene shows through letterbox and pillarbox margins.
	Viewport *screen.Viewport
	// OnDraw optionally records additional 2D drawing operations after all
	// layers and batches, inside the active Viewport transform when set.
	OnDraw func(d *core.Drawing, size core.Size)
	// Hidden suppresses drawing and hit testing of the entire 2D overlay when true.
	Hidden bool
	// Interactive, when true (or when OnPress is non-nil), enables pointer
	// events (core.PointerEventsAuto) on the overlay canvas. When false and
	// OnPress is nil, the canvas uses core.PointerEventsNone so pointer input
	// passes through to the 3D gpu.View beneath it.
	Interactive bool
	// OnPress handles presses on the overlay canvas when Interactive is true or
	// OnPress is non-nil. When Interactive is true and OnPress is nil, presses
	// are routed to DispatchPress automatically.
	OnPress func(ev core.PressEvent)
	// TestID optionally sets core.Canvas.TestID on the overlay canvas.
	TestID string
	// Label optionally sets core.Canvas.Label on the overlay canvas.
	Label string
	// contains filtered or unexported fields
}

Overlay3D draws 2D screen-space layers, sprite batches, and custom draw callbacks in a transparent core.Canvas stacked over a 3D gpu.View.

Items draw in deterministic order on every redraw:

  1. Visible SpaceScreen layers from Scene (SpaceWorld layers in Scene are skipped because the 3D view supplies the world) merged with visible Layers, sorted in stable ascending Layer.Order.
  2. Batches in slice order.
  3. OnDraw (when non-nil), receiving d and the active canvas or virtual size.

When Viewport is non-nil, drawing scales and clips through screen.Viewport. A zero Viewport.BarColor is treated as core.Transparent so letterbox and pillarbox margins reveal the 3D scene underneath; set Viewport.BarColor explicitly (for example core.RGB(0x000000)) when opaque bars are desired.

By default the overlay canvas sets core.PointerEventsNone so pointer events pass through unobstructed to the 3D gpu.View underneath. Set Interactive to true (or provide OnPress) to receive pointer events directly on the overlay canvas instead.

func NewOverlay3D

func NewOverlay3D(cx *core.Scope) *Overlay3D

NewOverlay3D returns a visible Overlay3D bound to cx so Invalidate triggers redraws of its overlay canvas. A nil cx defers binding until Canvas or View mounts the overlay in a scope.

func (*Overlay3D) AddBatch

func (o *Overlay3D) AddBatch(b *sprite.Batch)

AddBatch appends b to o.Batches.

func (*Overlay3D) AddLayer

func (o *Overlay3D) AddLayer(l *Layer) *Layer

AddLayer appends l to o.Layers and returns l.

func (*Overlay3D) Canvas

func (o *Overlay3D) Canvas(cx *core.Scope) core.Canvas

Canvas returns a transparent, absolutely positioned core.Canvas sized to fill its parent view (such as a gpu.View). Mount it directly in gpu.ViewProps.Children or compose it automatically with Overlay3D.View.

func (*Overlay3D) DispatchPress

func (o *Overlay3D) DispatchPress(window core.Size, ev core.PressEvent) bool

DispatchPress hit-tests ev.Position in o for a view of size window and invokes the topmost hit target's OnPress callback when set, returning whether a callback ran.

func (*Overlay3D) DispatchTouch

func (o *Overlay3D) DispatchTouch(window core.Size, ev core.TouchEvent) bool

DispatchTouch hit-tests each changed finger of ev (or all fingers when none are marked Changed) against o for a view of size window, invoking OnTouch or falling back to OnPress on TouchStart when OnTouch is nil.

func (*Overlay3D) Draw

func (o *Overlay3D) Draw(d *core.Drawing, size core.Size)

Draw records the 2D overlay into d for a canvas of size, leaving d's transform and paint state as it found it.

Calling Draw inside a core.Canvas subscribes the canvas to Invalidate calls automatically.

func (*Overlay3D) HitTest

func (o *Overlay3D) HitTest(window core.Size, p core.Point) (*HitResult, bool)

HitTest returns the topmost visible 2D overlay target hit by view-space point p inside a view of size window, testing standalone Batches first (in reverse slice and Z order) and then merged screen layers (in reverse Layer.Order).

func (*Overlay3D) HitTestAll

func (o *Overlay3D) HitTestAll(window core.Size, p core.Point) []HitResult

HitTestAll returns every visible 2D overlay target hit by view-space point p inside a view of size window, ordered from topmost to bottommost.

func (*Overlay3D) Invalidate

func (o *Overlay3D) Invalidate()

Invalidate marks the 2D overlay dirty so any mounted overlay canvas redraws on the next frame.

func (*Overlay3D) Project

func (o *Overlay3D) Project(viewProj [16]float32, worldX, worldY, worldZ float32, window core.Size) (x, y float32, visible bool)

Project maps the 3D world point (worldX, worldY, worldZ) through the column-major view-projection matrix viewProj (as scene3d.Camera.ViewProj returns) into o's active 2D drawing coordinates for a 3D view of size window. When o.Viewport is set, projected view coordinates are converted into virtual coordinates via Viewport.ViewToGame, returning visible == false if the projected point falls outside the frustum or inside clipped letterbox/pillarbox margins.

func (*Overlay3D) SetHidden

func (o *Overlay3D) SetHidden(hidden bool)

SetHidden updates o.Hidden and invalidates the overlay when the state changes.

func (*Overlay3D) Update

func (o *Overlay3D) Update(dt time.Duration)

Update advances tilemaps and custom drawables in Scene's SpaceScreen layers and o.Layers by dt in ascending Layer.Order.

func (*Overlay3D) View

func (o *Overlay3D) View(cx *core.Scope, props gpu.ViewProps) core.Node

View returns a gpu.View configured by props with o's transparent 2D overlay canvas mounted directly above the 3D GPU surface and beneath any native views listed in props.Children.

type Scene

type Scene struct {
	// Camera transforms SpaceWorld layers during Draw and HitTest; nil leaves world coordinates untransformed.
	Camera *tilemap.Camera
	// Layers are the scene's layers, drawn in stable ascending Layer.Order.
	Layers []*Layer
	// contains filtered or unexported fields
}

Scene composes ordered world- and screen-space Layers sharing a 2D Camera.

func NewScene

func NewScene(cam *tilemap.Camera) *Scene

NewScene returns an empty Scene using cam for its world-space layers.

func (*Scene) AddLayer

func (s *Scene) AddLayer(l *Layer) *Layer

AddLayer appends l to the scene and returns l.

func (*Scene) ClearSpriteHit

func (s *Scene) ClearSpriteHit(sp *sprite.Sprite)

ClearSpriteHit removes any custom hit-testing options previously bound to sp.

func (*Scene) DispatchPress

func (s *Scene) DispatchPress(ev core.PressEvent) bool

DispatchPress hit-tests ev.Position and invokes the topmost hit target's OnPress callback when set, returning whether a callback ran.

func (*Scene) DispatchTouch

func (s *Scene) DispatchTouch(ev core.TouchEvent) bool

DispatchTouch hit-tests each changed finger of ev (or all fingers when none are marked Changed) and routes it to the topmost hit target's OnTouch callback, or to OnPress on TouchStart when OnTouch is nil. It returns whether any callback ran.

func (*Scene) Draw

func (s *Scene) Draw(d *core.Drawing)

Draw draws every visible layer in stable ascending Order into d, leaving d's transform and paint state as it found it.

func (*Scene) DrawScreenLayers

func (s *Scene) DrawScreenLayers(d *core.Drawing)

DrawScreenLayers draws only the visible SpaceScreen layers of s in stable ascending Order into d, skipping SpaceWorld layers and leaving d's transform and paint state as it found it.

func (*Scene) HitTest

func (s *Scene) HitTest(p core.Point) (*HitResult, bool)

HitTest returns the topmost visible target hit by view-space point p, or (nil, false) if nothing was hit.

Layers are tested in reverse draw order (highest Order first), and items and sprites within each layer are tested in reverse Z/slice order. SpaceWorld layers convert p via Camera.ViewToWorld; SpaceScreen layers test p directly in view coordinates.

Example

A Scene draws its layers through a camera, and HitTest finds the topmost sprite under a point on the screen.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/scene"
	"github.com/nsgo-dev/game/pkg/sprite"
	"github.com/nsgo-dev/game/pkg/tilemap"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	cam := &tilemap.Camera{X: 100, Y: 0, Zoom: 1, Width: 320, Height: 180}
	s := scene.NewScene(cam)
	world := s.AddLayer(scene.NewLayer("world", scene.SpaceWorld, 0))
	chest := sprite.NewSprite(sprite.Frame{W: 16, H: 16, Width: 16, Height: 16})
	chest.X, chest.Y = 200, 50
	world.AddBatch(&sprite.Batch{Sprites: []*sprite.Sprite{&chest}})

	viewPoint := cam.WorldToView(core.Point{X: 208, Y: 58})
	hit, ok := s.HitTest(viewPoint)
	fmt.Println(ok, hit.Layer.Name, hit.Sprite == &chest, hit.Point)
	_, ok = s.HitTest(core.Point{X: 0, Y: 0})
	fmt.Println(ok)
}
Output:
true world true {208 58}
false

func (*Scene) HitTestAll

func (s *Scene) HitTestAll(p core.Point) []HitResult

HitTestAll returns every visible target hit by view-space point p, ordered from topmost to bottommost.

func (*Scene) Layer

func (s *Scene) Layer(name string) *Layer

Layer returns the first layer named name, or nil if none matches.

func (*Scene) SetSpriteHit

func (s *Scene) SetSpriteHit(sp *sprite.Sprite, opts HitOptions)

SetSpriteHit binds custom hit-testing options and input callbacks to sp in s.

func (*Scene) Update

func (s *Scene) Update(dt time.Duration)

Update advances the scene's Camera, tilemaps, and custom drawables by dt in layer order.

type ScreenNotifier

type ScreenNotifier struct {
	// Rect is the watched rectangle in world coordinates. An empty rectangle (zero or negative size) never enters any view.
	Rect core.Bounds
	// Margin is the extra points around a view's bounds an on-screen notifier may reach before OnExit fires; 0 exits exactly at the view's edge. A negative margin behaves as 0.
	Margin float32
	// OnEnter runs when Rect starts overlapping a view (or the first Step sees it inside one). Nil fires nothing.
	OnEnter func()
	// OnExit runs when Rect stops overlapping every view, margin included. Nil fires nothing.
	OnExit func()
	// contains filtered or unexported fields
}

ScreenNotifier watches a world rectangle against camera views and fires OnEnter and OnExit when it starts and stops being visible. It is the code counterpart of the scene format's built-in "on_screen" component, for games that do not use scene files.

Rect is the watched rectangle in world coordinates; move it as the object moves. Margin is a band of extra points around a view's bounds: a visible notifier fires OnExit only after leaving the view by more than the margin, while an off-screen notifier fires OnEnter as soon as it touches the view itself, so a view hovering near an edge does not flap between the two states.

A notifier starts off-screen, so the first Step that finds Rect inside a view fires OnEnter, as Godot's VisibleOnScreenNotifier2D does for a node that begins on-screen. Step with no views treats the notifier as on-screen. It is not safe for concurrent use: step it from the goroutine that runs the game's update.

func (*ScreenNotifier) OnScreen

func (n *ScreenNotifier) OnScreen() bool

OnScreen reports whether the notifier is currently inside a view, as of the last Step.

func (*ScreenNotifier) Step

func (n *ScreenNotifier) Step(views ...*tilemap.Camera) bool

Step tests Rect against every view's visible bounds and fires OnEnter or OnExit when the result changes, then returns whether the notifier is on screen. An object is on screen when any view sees it, so pass every camera that draws the world, such as every SplitScreen viewport's camera. Nil cameras are skipped, and Step with no views reports the notifier on screen. Visible bounds are the axis-aligned rectangle covering a view's rotated corners, as tilemap.Camera.VisibleBounds computes them.

type SortMode

type SortMode uint8

SortMode controls how items and sprites are depth-sorted within a Layer during Draw and HitTest.

const (
	// SortNone preserves Z and slice insertion order (default).
	SortNone SortMode = iota
	// SortY sorts drawables and sprites in painter's order: primary Z, then ascending Y (or SortKey / SpriteSortKey), then insertion order.
	SortY
	// SortCustom sorts items with Layer.SortFunc (or Layer.SortKey / Z) and sprites with Layer.SpriteSortKey (or Z).
	SortCustom
)

type Space

type Space uint8

Space names the coordinate system a Layer draws and hit-tests in.

const (
	// SpaceWorld draws under the Scene's Camera and converts view points to world space for hit testing.
	SpaceWorld Space = iota
	// SpaceScreen draws directly in view coordinates, unaffected by the Scene's Camera.
	SpaceScreen
)

type SplitScreen

type SplitScreen struct {
	// Viewports are the active screen regions drawn in slice order.
	Viewports []SplitViewport
	// DividerWidth is the thickness in points of divider lines drawn along shared edges between viewports when positive.
	DividerWidth float32
	// DividerColor is the fill color of divider lines when DividerWidth > 0; a zero color defaults to opaque black.
	DividerColor core.Color
}

SplitScreen renders and hit-tests a Scene across multiple clipped viewports with independent cameras.

Example

A SplitScreen draws one scene in several viewports, each through its own camera sized to its viewport, and routes a point on the screen to the viewport under it and that viewport's camera.

package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/scene"
	"github.com/nsgo-dev/game/pkg/sprite"
	"github.com/nsgo-dev/game/pkg/tilemap"
	"github.com/nsgo-dev/nsgo/core"
)

func main() {
	// A camera's X and Y are the world point at the centre of its view.
	left := &tilemap.Camera{X: 160, Y: 90, Zoom: 1}
	right := &tilemap.Camera{X: 352, Y: 132, Zoom: 1}
	s := scene.NewScene(left)
	world := s.AddLayer(scene.NewLayer("world", scene.SpaceWorld, 0))
	chest := sprite.NewSprite(sprite.Frame{W: 16, H: 16, Width: 16, Height: 16})
	chest.X, chest.Y = 200, 50
	world.AddBatch(&sprite.Batch{Sprites: []*sprite.Sprite{&chest}})

	split := scene.VerticalSplit(core.Size{Width: 640, Height: 180}, left, right)
	// The chest's centre, (208, 58) in the world, is at (208, 58) in the left half and at (336, 16) in the right half.
	for _, p := range []core.Point{{X: 208, Y: 58}, {X: 336, Y: 16}, {X: 336, Y: 100}} {
		i, hit, ok := split.HitTest(s, p)
		fmt.Println(i, ok, ok && hit.Sprite == &chest)
	}
	fmt.Println(split.ViewportAt(core.Point{X: 700, Y: 0}), s.Camera == left)
}
Output:
0 true true
1 true true
1 false false
-1 true

func HorizontalSplit

func HorizontalSplit(size core.Size, topCam, bottomCam *tilemap.Camera) *SplitScreen

HorizontalSplit returns a two-viewport top/bottom SplitScreen covering size.

func NewSplitScreen

func NewSplitScreen(views ...SplitViewport) *SplitScreen

NewSplitScreen returns a SplitScreen configured with the given viewports.

func QuadSplit

func QuadSplit(size core.Size, cams [4]*tilemap.Camera) *SplitScreen

QuadSplit returns a four-viewport 2x2 SplitScreen covering size in row-major order: top-left (0), top-right (1), bottom-left (2), bottom-right (3).

func VerticalSplit

func VerticalSplit(size core.Size, leftCam, rightCam *tilemap.Camera) *SplitScreen

VerticalSplit returns a two-viewport left/right SplitScreen covering size.

func (*SplitScreen) DispatchPress

func (ss *SplitScreen) DispatchPress(s *Scene, ev core.PressEvent) (viewportIndex int, handled bool)

DispatchPress hit-tests ev.Position in the matching viewport and invokes the topmost target's OnPress callback when set.

func (*SplitScreen) DispatchTouch

func (ss *SplitScreen) DispatchTouch(s *Scene, ev core.TouchEvent) bool

DispatchTouch hit-tests each changed finger of ev (or all fingers when none are marked Changed) against its containing viewport and routes it to OnTouch (or OnPress on TouchStart when OnTouch is nil).

func (*SplitScreen) Draw

func (ss *SplitScreen) Draw(d *core.Drawing, s *Scene)

Draw renders s into each viewport clipped strictly to its Region under its Camera, draws any per-viewport HUD, draws divider lines when DividerWidth > 0, and restores both d and s.Camera cleanly.

func (*SplitScreen) HitTest

func (ss *SplitScreen) HitTest(s *Scene, p core.Point) (viewportIndex int, hit *HitResult, ok bool)

HitTest routes parent view-space point p to the viewport containing p, hit-tests s under that viewport's Camera, and restores s.Camera afterwards.

When p lies outside all viewports, it returns (-1, nil, false). When p falls inside viewport i but hits nothing, it returns (i, nil, false).

func (*SplitScreen) HitTestAll

func (ss *SplitScreen) HitTestAll(s *Scene, p core.Point) (viewportIndex int, hits []HitResult)

HitTestAll routes parent view-space point p to the viewport containing p and returns all hits in topmost-to-bottommost order.

func (*SplitScreen) ViewportAt

func (ss *SplitScreen) ViewportAt(p core.Point) int

ViewportAt returns the index of the topmost viewport containing parent view point p, or -1 if p lies outside all viewports.

type SplitViewport

type SplitViewport struct {
	// Camera is the world camera used to draw and hit-test the scene in this viewport.
	Camera *tilemap.Camera
	// Region is the viewport rectangle in parent view coordinates.
	Region core.Bounds
	// DrawHUD optionally draws per-viewport HUD elements in viewport-local coordinates
	// (0..Region.Size.Width, 0..Region.Size.Height) after the scene draws.
	DrawHUD func(d *core.Drawing, size core.Size)
}

SplitViewport defines one clipped viewport region within a SplitScreen layout.

type Transition

type Transition struct {
	// Duration is how long the transition runs; a non-positive Duration switches immediately.
	Duration time.Duration
	// Curve eases the linear progress in [0, 1]; its zero value is core.Linear.
	Curve core.Curve
	// Draw draws one transition frame at eased progress in [0, 1] into d for a canvas of size, calling drawOld and drawNew as needed to render the outgoing and incoming scenes. When Draw is nil, Manager.Draw and Manager.View show the incoming scene for the whole Duration.
	Draw func(d *core.Drawing, size core.Size, progress float64, drawOld, drawNew func(*core.Drawing))
	// contains filtered or unexported fields
}

Transition animates the visual handoff between an outgoing scene and an incoming scene over Duration.

func Crossfade

func Crossfade(duration time.Duration) *Transition

Crossfade returns a Transition that crossfades directly from the old scene to the new scene over duration.

func CustomTransition

func CustomTransition(duration time.Duration, draw func(d *core.Drawing, size core.Size, progress float64, drawOld, drawNew func(*core.Drawing))) *Transition

CustomTransition returns a Transition driven over duration with a caller-supplied draw function.

func Fade

func Fade(duration time.Duration, color core.Color) *Transition

Fade returns a Transition lasting duration.

When color is 0 or core.Transparent, it crossfades directly from the old scene (alpha 1 to 0) to the new scene (alpha 0 to 1). When color is non-transparent, it fades the old scene to color over the first half of duration and reveals the new scene from color over the second half.

func Wipe

func Wipe(duration time.Duration, dir Direction) *Transition

Wipe returns a Transition that clips the old and new scenes along an axis-aligned dividing edge moving in dir over duration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL