lights2d

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 4 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 implements 2D lighting for NSGo games: point and spot lights composited over ambient darkness, exact 2D visibility-polygon shadows from occluders, and tangent-space normal-mapped sprite shading.

Index

Examples

Constants

This section is empty.

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 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 + Σ(lightColor * intensity * atten * max(0, N·L)), where L points from the pixel toward (light.X, light.Y, lightZ). 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.

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 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.
	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 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 the scene's occluders.
	CastShadows bool
	// Enabled turns the light on or off.
	Enabled bool
}

Light is a 2D point light or directional spotlight.

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 (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 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 elevation of 2D lights above the sprite plane.
	// Values <= 0 are passed through directly; NewNormalSprite initializes it to 32.
	LightZ float32
	// contains filtered or unexported fields
}

NormalSprite caches normal-mapped shading of a diffuse/normal-map sprite pair and exposes a premultiplied core.ImageSource ready for Drawing.DrawImage.

It only recomputes shading and increments ImageSource.Version when the sprite's position, LightZ, source images, or the scene's lighting/occluders change, or after Invalidate is called.

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 (if dirty) and draws the sprite into d at (ns.X, ns.Y).

func (*NormalSprite) ImageSource

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

ImageSource returns a core.ImageSource backed by premultiplied Pixels shaded 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 the cached shaded image stale so the next ImageSource or Draw call recomputes it. 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 shaded image, or nil if ImageSource has not been called yet.

type Occluder

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

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.

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.

type Scene

type Scene struct {
	// Ambient is the ambient darkness tint and alpha drawn over the scene bounds,
	// and the baseline ambient illumination in EvaluateAt and normal-map shading.
	Ambient core.Color
	// Lights are the point and spot lights in the scene.
	Lights []*Light
	// Occluders block light from lights with CastShadows enabled.
	Occluders []Occluder
	// LightComposite sets how light glows composite onto the drawing.
	// 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 darkness, 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 the ambient darkness overlay followed by all active light glows into d, clipped to bounds. Lights with CastShadows enabled are clipped to their exact 2D visibility polygon against s.Occluders.

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

func (*Scene) EffectiveLightComposite

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

EffectiveLightComposite returns the composite operation Draw uses for 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 color, intensity, distance falloff, spotlight cone, and shadow occlusion.

func (*Scene) SetLightComposite

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

SetLightComposite sets how light glows composite onto the drawing, 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, and Occluders, leaving the occluders out when DisableShadows is set.

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