lights2d

package
v0.4.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 7 Imported by: 1 module, 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 lights2d is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package lights2d implements 2D lighting for NSGo games: a darkness overlay (the default) or an opt-in multiplied offscreen light buffer, point, spot, textured, and directional lights with add/subtract/mix blend modes, per-layer light and shadow masks, exact and soft visibility-polygon shadows with shadow tinting, and GPU/CPU tangent-space normal-mapped sprite shading.

Index

Examples

Constants

View Source
const (
	// MaxGPUNormalLights is the maximum number of point/spot lights evaluated
	// per draw in the GPU normal-map Kage shader.
	MaxGPUNormalLights = 32
	// MaxGPUDirectionalLights is the maximum number of directional lights
	// evaluated per draw in the GPU normal-map Kage shader.
	MaxGPUDirectionalLights = 4
)
View Source
const DefaultLightMask uint32 = 1

DefaultLightMask is the default 32-bit light mask bit (bit 0) assigned to layers, objects, and occluders when no explicit mask is configured.

Variables

This section is empty.

Functions

func LineOfSight

func LineOfSight(occluders *[]Occluder) func(from, to core.Point) bool

LineOfSight returns a function that reports Visible against *occluders, reading the slice on every call so a game that rebuilds its occluders keeps one function. It has the shape of ai.LineOfSight, so the occluders that cast shadows also block an agent's sight.

Example

LineOfSight turns the occluders into a line-of-sight check, such as ai.PerceptionSystem.LineOfSight, that follows the slice as the level changes.

package main

import (
	"fmt"

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

func main() {
	occluders := []lights2d.Occluder{}
	canSee := lights2d.LineOfSight(&occluders)
	guard, intruder := core.Point{X: 0, Y: 50}, core.Point{X: 100, Y: 50}
	fmt.Println(canSee(guard, intruder))
	occluders = append(occluders, lights2d.SegmentOccluder(lights2d.Segment{A: core.Point{X: 50, Y: 0}, B: core.Point{X: 50, Y: 100}}))
	fmt.Println(canSee(guard, intruder))
}
Output:
true
false

func NormalMapShader

func NormalMapShader() (*core.ShaderProgram, error)

NormalMapShader returns the compiled Kage ShaderProgram that shades normal-mapped 2D sprites against up to MaxGPUNormalLights point/spot lights and MaxGPUDirectionalLights directional lights on the GPU.

The program is compiled once on first use. On builds where shaders are unavailable (such as nsgo_noshader), NormalMapShader returns (nil, err) matching errors.ErrUnsupported, and callers fall back to CPU ShadeNormalMap.

func PointInPolygon

func PointInPolygon(p core.Point, poly []core.Point) bool

PointInPolygon reports whether p lies inside the closed polygon poly using the even-odd ray-casting rule.

func ShadeNormalMap

func ShadeNormalMap(diffuse, normalMap *image.NRGBA, spriteX, spriteY float32, ambient core.Color, lights []*Light, lightZ float32) *image.NRGBA

ShadeNormalMap computes tangent-space normal-mapped lighting for diffuse using normalMap, placing the sprite's top-left corner at (spriteX, spriteY).

Normal vectors are decoded from normalMap RGB channels as (nx, ny, nz) = (2*R - 1, 2*G - 1, 2*B - 1) and normalized. Each pixel's diffuse RGB is modulated by ambient combined with every light's color, intensity, blend mode, attenuation, and max(0, N·L), where L points from the pixel toward (light.X, light.Y, effectiveHeight). Alpha is preserved from diffuse.

If diffuse is nil, ShadeNormalMap returns nil. If normalMap is nil, a flat forward-facing normal (0, 0, 1) is used.

func ShadeNormalMapWithOccluders

func ShadeNormalMapWithOccluders(diffuse, normalMap *image.NRGBA, spriteX, spriteY float32, ambient core.Color, lights []*Light, lightZ float32, occluders []Occluder) *image.NRGBA

ShadeNormalMapWithOccluders behaves like ShadeNormalMap and also tests line-of-sight shadow occlusion against occluders for lights with CastShadows enabled.

func VisibilityPolygon

func VisibilityPolygon(origin core.Point, radius float32, occluders []Occluder) []core.Point

VisibilityPolygon computes the exact 2D visibility polygon from origin within the bounding square [origin.X-radius, origin.X+radius] x [origin.Y-radius, origin.Y+radius] against occluders using radial ray casting.

It returns nil when radius <= 0 or any input is non-finite.

Example

VisibilityPolygon returns the area a light or viewer sees around the occluders, which PointInPolygon then tests points against.

package main

import (
	"fmt"

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

func main() {
	box := lights2d.RectOccluder(core.Bounds{Origin: core.Point{X: 20, Y: -5}, Size: core.Size{Width: 10, Height: 10}})
	area := lights2d.VisibilityPolygon(core.Point{}, 50, []lights2d.Occluder{box})
	fmt.Println(len(area) > 0)
	fmt.Println(lights2d.PointInPolygon(core.Point{X: 10, Y: 0}, area), lights2d.PointInPolygon(core.Point{X: 40, Y: 0}, area))
}
Output:
true
true false

func Visible

func Visible(origin, target core.Point, occluders []Occluder) bool

Visible reports whether the line of sight from origin to target is unobstructed by occluders.

Example

Visible tests line of sight between two points past the occluders, as an enemy's view check does.

package main

import (
	"fmt"

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

func main() {
	wall := lights2d.SegmentOccluder(lights2d.Segment{A: core.Point{X: 50, Y: 0}, B: core.Point{X: 50, Y: 100}})
	guard := core.Point{X: 0, Y: 50}
	fmt.Println(lights2d.Visible(guard, core.Point{X: 100, Y: 50}, []lights2d.Occluder{wall}))
	fmt.Println(lights2d.Visible(guard, core.Point{X: 40, Y: 90}, []lights2d.Occluder{wall}))
}
Output:
false
true

Types

type BlendMode

type BlendMode uint8

BlendMode selects how a Light or DirectionalLight combines with the light buffer (or directly with the canvas in Overlay mode).

const (
	// BlendAdd adds the light's RGB contribution (default).
	BlendAdd BlendMode = iota
	// BlendSubtract subtracts the light's RGB contribution, darkening lit areas.
	BlendSubtract
	// BlendMix alpha-blends the light's color over the buffer using source-over.
	BlendMix
)

func (BlendMode) String

func (b BlendMode) String() string

String returns "add", "subtract", or "mix".

type DirectionalLight

type DirectionalLight struct {
	// Angle is the direction light travels in radians (0 = +X, pi/2 = +Y).
	Angle float32
	// Color is the light's color (its alpha further scales brightness).
	Color core.Color
	// Energy scales the light's brightness. Non-positive values emit nothing.
	Energy float32
	// MaxDistance limits how far shadows extend behind occluders in world points.
	// Values <= 0 extend across the full view diagonal.
	MaxDistance float32
	// Blend selects how the light combines with the light buffer: BlendAdd
	// (default), BlendSubtract, or BlendMix.
	Blend BlendMode
	// CastShadows projects parallel shadows behind occluders matching ShadowMask.
	CastShadows bool
	// ShadowColor tints regions occluded from this directional light.
	// A color with alpha 0 (including the zero value) leaves occluded regions
	// unlit by this light.
	ShadowColor core.Color
	// ShadowSoftness sets the angular penumbra spread in radians used to soften
	// directional shadows by sampling offset directions. Values <= 0 cast hard
	// shadows.
	ShadowSoftness float32
	// Height is the virtual elevation component (Z) for normal-map shading.
	// Values <= 0 default to 0.5.
	Height float32
	// ItemMask is a 32-bit bitmask of layers/objects this light illuminates.
	// Zero illuminates every lit layer and object.
	ItemMask uint32
	// ShadowMask is a 32-bit bitmask of occluders that cast shadows from this
	// light. Zero tests against every occluder.
	ShadowMask uint32
	// Disabled turns the directional light off when true.
	Disabled bool
}

DirectionalLight is a parallel infinite-distance 2D light (such as sun or moonlight) traveling in direction Angle (radians: 0 = +X, pi/2 = +Y).

Its zero-value Disabled field is false so struct literals such as DirectionalLight{Angle: a, Color: c, Energy: 0.8, MaxDistance: 400} are active immediately.

func NewDirectionalLight

func NewDirectionalLight(angle float32, color core.Color, energy float32) *DirectionalLight

NewDirectionalLight returns an active DirectionalLight with CastShadows enabled.

type Light

type Light struct {
	// X and Y are the light's position in world coordinates.
	X, Y float32
	// Radius is the maximum reach of the light. Non-positive values emit nothing
	// unless Texture is set with explicit dimensions.
	Radius float32
	// Color is the light's color (its alpha further scales brightness).
	Color core.Color
	// Intensity scales the light's brightness. Non-positive values emit nothing.
	Intensity float32
	// Falloff is the distance attenuation exponent in (1 - d/Radius)^Falloff.
	// Values <= 0 default to 2 (smooth quadratic falloff).
	Falloff float32
	// ConeAngle is the spotlight direction (or Texture rotation) in radians
	// (0 = +X, pi/2 = +Y).
	ConeAngle float32
	// ConeSpread is the total angular width of the spotlight cone in radians.
	// When ConeSpread <= 0 or >= 2*pi, the light is omnidirectional.
	ConeSpread float32
	// CastShadows clips the light against occluders matching ShadowMask.
	CastShadows bool
	// Enabled turns the light on or off.
	Enabled bool

	// Texture optionally shapes the light using an image cookie centered at
	// (X, Y), rotated by ConeAngle, and scaled by TextureScale.
	Texture core.ImageSource
	// TextureScale uniformly scales Texture around the light center.
	// Values <= 0 default to 1.
	TextureScale float32
	// Blend selects how the light combines with the light buffer: BlendAdd
	// (default), BlendSubtract, or BlendMix.
	Blend BlendMode
	// ShadowColor tints regions occluded from this light inside its reach.
	// A color with alpha 0 (including the zero value) leaves occluded regions
	// untouched (ambient only).
	ShadowColor core.Color
	// ShadowSoftness sets the virtual emitter radius in world points used to
	// soften shadow edges (penumbra) by sampling visibility polygons from offset
	// origins. Values <= 0 cast crisp hard shadows.
	ShadowSoftness float32
	// Height is the light's virtual elevation above the 2D plane for normal-map
	// shading. Values <= 0 fall back to the caller's default lightZ.
	Height float32
	// ItemMask is a 32-bit bitmask of layers/objects this light illuminates.
	// Zero illuminates every lit layer and object.
	ItemMask uint32
	// ShadowMask is a 32-bit bitmask of occluders that cast shadows from this
	// light. Zero tests against every occluder.
	ShadowMask uint32
}

Light is a 2D point light, directional spotlight, or textured (cookie) light.

func NewLight

func NewLight(x, y, radius float32, color core.Color) *Light

NewLight returns an enabled omnidirectional light with Intensity 1 and quadratic Falloff (2).

func (*Light) AttenuationAt

func (l *Light) AttenuationAt(x, y float32) float32

AttenuationAt returns the combined distance and spotlight-cone attenuation factor in [0, 1] at world point (x, y). It returns 0 when the light is disabled, has non-positive Radius or Intensity, or any coordinate is non-finite, or (x, y) lies outside the light's radius or spotlight cone.

Example

A Light fades from full strength at its center to nothing at its radius.

package main

import (
	"fmt"

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

func main() {
	l := lights2d.NewLight(0, 0, 100, core.RGB(0xffcc88))
	for _, d := range []float32{0, 50, 100} {
		fmt.Printf("%.2f\n", l.AttenuationAt(d, 0))
	}
}
Output:
1.00
0.25
0.00

type Mode

type Mode uint8

Mode selects how Scene.Draw composites lighting onto a drawing.

const (
	// Overlay draws ambient darkness with source-over followed by each light directly onto the canvas (defaulting to core.CompositeLighter), without an offscreen light buffer. This is the zero value and default mode, so scenes keep the darkness-overlay look they had before Multiply existed.
	Overlay Mode = iota
	// Multiply renders ambient illumination and every active light into an offscreen light buffer and composites it over the lit layers using core.CompositeMultiply. Opt in by setting Scene.Mode; Ambient then means the baseline light color (RGB scaled by alpha), so a zero Ambient leaves everything outside the lights black.
	Multiply
)

func (Mode) String

func (m Mode) String() string

String returns "overlay" or "multiply".

type NormalSprite

type NormalSprite struct {
	// Diffuse is the unlit straight-alpha sprite image.
	Diffuse *image.NRGBA
	// NormalMap is the tangent-space normal map matching Diffuse.
	NormalMap *image.NRGBA
	// X and Y are the sprite's top-left position in world coordinates.
	X, Y float32
	// LightZ is the default elevation of 2D lights above the sprite plane when a
	// light's Height is <= 0. NewNormalSprite initializes it to 32.
	LightZ float32
	// LightMask is a 32-bit bitmask matched against Light.ItemMask and
	// DirectionalLight.ItemMask. Zero matches every light.
	LightMask uint32
	// PreferCPU forces Draw to use the cached CPU ShadeNormalMap path even when
	// GPU Kage shaders are available.
	PreferCPU bool
	// contains filtered or unexported fields
}

NormalSprite shades a diffuse/normal-map sprite pair against a lighting Scene.

Draw uses the GPU Kage normal-map shader (NormalMapShader) against up to MaxGPUNormalLights point/spot lights and MaxGPUDirectionalLights directional lights when shaders are available and PreferCPU is false, uploading Diffuse and NormalMap pixels only when they change. Where shaders are unavailable or PreferCPU is true (or when calling ImageSource directly), it falls back to cached CPU ShadeNormalMap shading.

func NewNormalSprite

func NewNormalSprite(diffuse, normalMap *image.NRGBA) *NormalSprite

NewNormalSprite returns a NormalSprite with a default LightZ of 32.

func (*NormalSprite) Draw

func (ns *NormalSprite) Draw(d *core.Drawing, scene *Scene)

Draw shades and draws the sprite into d at (ns.X, ns.Y). When GPU shaders are available, PreferCPU is false, and no shadow-casting light could be blocked by the scene's occluders, Draw runs the Kage normal-map shader on the GPU via Drawing.SetShader; otherwise it uses the CPU ImageSource path, which raycasts per-pixel shadows against Occluders (the shader does not test occluders).

func (*NormalSprite) ImageSource

func (ns *NormalSprite) ImageSource(scene *Scene) core.ImageSource

ImageSource returns a core.ImageSource backed by premultiplied Pixels shaded on the CPU by scene. Repeated calls with unchanged inputs return the cached ImageSource with the same Version and perform no re-shading.

func (*NormalSprite) Invalidate

func (ns *NormalSprite) Invalidate()

Invalidate marks both the cached CPU shaded image and uploaded GPU source textures stale so the next ImageSource or Draw call recomputes/re-uploads them. Call this after mutating Diffuse or NormalMap pixels in place.

func (*NormalSprite) Shaded

func (ns *NormalSprite) Shaded() *image.NRGBA

Shaded returns the most recently computed straight-alpha CPU shaded image, or nil if ImageSource has not been called yet.

type Occluder

type Occluder struct {
	Vertices  []core.Point
	Segments  []Segment
	LightMask uint32
}

Occluder blocks light along its edges.

Vertices form a closed polygon (each consecutive pair of vertices, plus the edge from the last vertex back to the first when there are at least three vertices). Segments are additional explicit line segments. An Occluder may populate Vertices, Segments, or both.

LightMask is a 32-bit bitmask matched against Light.ShadowMask and DirectionalLight.ShadowMask. A zero LightMask defaults to DefaultLightMask (bit 0).

func PolygonOccluder

func PolygonOccluder(vertices ...core.Point) Occluder

PolygonOccluder returns a closed polygon Occluder from vertices.

func RectOccluder

func RectOccluder(b core.Bounds) Occluder

RectOccluder returns a closed rectangular Occluder for b.

func SegmentOccluder

func SegmentOccluder(segments ...Segment) Occluder

SegmentOccluder returns an Occluder built from explicit line segments.

func (Occluder) EffectiveLightMask

func (o Occluder) EffectiveLightMask() uint32

EffectiveLightMask returns the occluder's effective 32-bit shadow mask, defaulting a zero LightMask to DefaultLightMask.

type Scene

type Scene struct {
	// Ambient is the baseline ambient light color in Multiply mode (with RGB
	// scaled by alpha), the darkness overlay tint in Overlay mode, and the
	// baseline illumination in EvaluateAt and normal-map shading.
	Ambient core.Color
	// Lights are the point, spot, and textured lights in the scene.
	Lights []*Light
	// DirectionalLights are parallel infinite-distance lights (such as sun or
	// moonlight) shining across the entire view.
	DirectionalLights []*DirectionalLight
	// Occluders block light from lights with CastShadows enabled.
	Occluders []Occluder
	// Mode selects how Draw composites lighting: Overlay (default, draws ambient darkness and lights directly onto the canvas) or Multiply (renders into an offscreen light buffer and composites with core.CompositeMultiply).
	Mode Mode
	// BufferScale optionally sets the backing pixel scale of the offscreen light
	// buffer in Multiply mode (for example 0.5 for half-resolution lighting on
	// mobile). Values <= 0 default to 1.
	BufferScale float32
	// LightComposite sets how additive light glows composite onto the drawing in
	// Overlay mode. Zero defaults to core.CompositeLighter (additive) unless set
	// explicitly with SetLightComposite. Assign core.CompositeScreen for softer
	// screen-blended lights, or call SetLightComposite(core.CompositeSourceOver)
	// for alpha-over glows.
	LightComposite core.CompositeOp
	// DisableShadows skips occlusion for every light, as though none had CastShadows,
	// without changing the lights; a low quality preset sets it (quality.Preset.Shadows false).
	DisableShadows bool
	// contains filtered or unexported fields
}

Scene holds the ambient illumination, point/spot/textured lights, directional lights, and shadow-casting occluders for a 2D lighting pass.

Example

A Scene darkens the level with an ambient color and adds lights; EvaluateAt reads the light reaching a point, which game logic can use for stealth.

package main

import (
	"fmt"

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

func main() {
	torch := lights2d.NewLight(100, 100, 80, core.RGB(0xffffff))
	torch.CastShadows = true
	scene := &lights2d.Scene{
		Ambient:   core.RGBA(0x000000, 0.75),
		Lights:    []*lights2d.Light{torch},
		Occluders: []lights2d.Occluder{lights2d.RectOccluder(core.Bounds{Origin: core.Point{X: 140, Y: 80}, Size: core.Size{Width: 10, Height: 40}})},
	}
	for _, x := range []float32{100, 130, 170} {
		r, _, _ := scene.EvaluateAt(x, 100)
		fmt.Printf("x=%v: %.2f\n", x, r)
	}
}
Output:
x=100: 1.00
x=130: 0.39
x=170: 0.00

func (*Scene) Draw

func (s *Scene) Draw(d *core.Drawing, bounds core.Bounds)

Draw renders lighting into d clipped to bounds for all active lights and directional lights.

In Overlay mode (default), Draw draws ambient darkness and light glows directly onto d without an offscreen buffer. In Multiply mode, Draw renders ambient illumination and every active light into an offscreen light buffer and composites that buffer over d using core.CompositeMultiply.

Draw leaves d's graphics state as it found it.

func (*Scene) DrawMask

func (s *Scene) DrawMask(d *core.Drawing, bounds core.Bounds, itemMask uint32)

DrawMask renders lighting into d clipped to bounds using only lights and directional lights whose ItemMask matches itemMask. When itemMask is 0 (an unlit layer), DrawMask does nothing.

DrawMask leaves d's graphics state as it found it.

func (*Scene) EffectiveLightComposite

func (s *Scene) EffectiveLightComposite() core.CompositeOp

EffectiveLightComposite returns the composite operation Overlay mode uses for additive light glows: s.LightComposite when non-zero or set with SetLightComposite, and core.CompositeLighter otherwise.

func (*Scene) EvaluateAt

func (s *Scene) EvaluateAt(x, y float32) (r, g, b float32)

EvaluateAt computes the lit RGB intensity at world point (x, y), combining ambient illumination with every active light's and directional light's color, intensity/energy, distance falloff, spotlight cone, blend mode, soft shadow occlusion, and shadow tint.

func (*Scene) EvaluateAtMask

func (s *Scene) EvaluateAtMask(x, y float32, itemMask uint32) (r, g, b float32)

EvaluateAtMask computes the lit RGB intensity at world point (x, y) for a layer or object with light mask itemMask. An unlit itemMask of 0 returns (1, 1, 1) (full unlit brightness).

func (*Scene) NormalMapPaint

func (s *Scene) NormalMapPaint(normalMap core.ImageSource, spriteX, spriteY, spriteW, spriteH, lightZ float32, itemMask uint32) (core.ShaderPaint, bool)

NormalMapPaint returns a core.ShaderPaint ready for Drawing.SetShader that shades a sprite covering [spriteX, spriteX+spriteW] x [spriteY, spriteY+spriteH] using normalMap (empty uses a flat forward normal) against active lights and directional lights matching itemMask.

Pass itemMask == 0 to match all lights, or a specific 32-bit layer/object light mask. It returns (core.ShaderPaint{}, false) when GPU shaders are unavailable.

func (*Scene) SetLightComposite

func (s *Scene) SetLightComposite(op core.CompositeOp)

SetLightComposite sets how additive light glows composite onto the drawing in Overlay mode, including core.CompositeSourceOver (whose zero value is otherwise treated as unset and defaults to core.CompositeLighter).

func (*Scene) ShadeNormalMap

func (s *Scene) ShadeNormalMap(diffuse, normalMap *image.NRGBA, spriteX, spriteY, lightZ float32) *image.NRGBA

ShadeNormalMap shades diffuse using normalMap with the scene's Ambient, Lights, DirectionalLights, and Occluders, leaving occluders out when DisableShadows is set.

func (*Scene) ShadeNormalMapMask

func (s *Scene) ShadeNormalMapMask(diffuse, normalMap *image.NRGBA, spriteX, spriteY, lightZ float32, itemMask uint32) *image.NRGBA

ShadeNormalMapMask shades diffuse using normalMap against lights and directional lights matching itemMask. An itemMask of 0 returns an unlit copy of diffuse.

type Segment

type Segment struct {
	A, B core.Point
}

Segment is a 2D line segment from A to B that blocks light.

Jump to

Keyboard shortcuts

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