Help us shape the future of Go! Take the 2026 Go Developer Survey

world

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: MIT Imports: 7 Imported by: 0

README

World authoring semantics

worldsource defines typed room, prefab, port, content and material authoring semantics. It has no YAML implementation dependency: YAML tags describe field names, and Validate checks typed values. Public compilers own text parsing, presence and unknown-field checks, diagnostics, prefab expansion and convex decomposition. They must enforce compiled-world bounds again after expansion. Runtime format types have no JSON tags or custom JSON methods; source YAML vocabulary and TOML asset controls remain explicit and independently checked.

The Karty CLI generates local YAML editor schemas with karty schema. Run it from a game project to include that level's material, texture and prefab choices, or from this repository root to generate the shared base referenced by the standalone source fixture. The generated .karty/schemas directory is ignored; format validation and builds do not require the CLI or a YAML parser here.

Source version Added semantics
1 Rooms, prefabs and ordinary connections
2 Typed actors and instance tags
3 Directed and transformed connections
4 Root authored lighting
5 Material UV mapping
6 Static solids, root/prefab contents and room-free prefabs
7 Top/bottom wall bands and secondary colour textures
8 Reusable actor and material animations
9 Environment presets, sky ceilings and horizon boundaries
10 GPU sprite particle presets and transformed emitters
11 Renderable solid-only prefabs and actor solid renderers

Versions 1–11 remain supported. Optional fields must respect their version gates; omitting new fields preserves older encodings. See the compiled world contract for output validation and lighting bounds. Root lighting remains in global coordinates and is never transformed by a prefab.

The unreleased SDK 0.0.11 candidate separates the 4,096 authored-source bound (worldsource.MaxLights) from the 50 live direct-light budget (world.MaxRuntimeLights). Offline build policy may automatically select every fixed light without a nonzero linked emission pulse; motion and pulsing sources remain runtime lights. Authoring and compiled validation accept the complete source set, while producers check the remaining live budget when packaging a world. An unbaked preview still uses the runtime limit.

Environment and outdoor geometry, source version 9

Source v9 adds an optional root environment and room/edge sky markers:

version: 9
environment:
  preset: fantasy
  palette: violet # optional; omitted means the preset's default sky
  sun: # optional; omission uses the preset direction
    azimuth: 135
    elevation: 40
rooms:
  - id: courtyard
    sky: true
    # Ordinary finite geometry and material fields remain required.

preset is daylight, space, cartoon or fantasy. palette is omitted, default, violet or twilight; it changes sky colors without changing light colors or intensity. A supplied sun requires both finite angles in degrees: azimuth [0,360) measured from +X toward +Y, and elevation [0,90] above the XY plane. Environment belongs to the root, with no prefab transform. A preset alone supplies bounded sky, sun and outdoor fill defaults.

Optional time_of_day supplies finite hours [0,24) (midnight 0, sunrise 6, noon 12, sunset 18); optional cloud_amount supplies finite coverage [0,1]. Omitted time preserves fixed sun defaults or explicit angles; providing both time and sun is rejected. Omitted clouds resolve to 0.35; explicit zero is clear. Compilers preserve pointer presence for these optional controls. The engine live setter can subsequently override the clock/clouds for every camera in a mounted world while retaining authored preset/palette choices.

Room sky: true turns its ceiling into an environment opening. The room retains its finite ceiling for spatial bounds and portal confinement. Edge sky: true turns an opaque boundary into a horizon opening, while preserving confinement; it requires a sky room and cannot be a connection or exported port endpoint, including through nested prefab ports. Ordinary walls, floors, roofs and static solids keep their physical behavior. Sky rooms in prefabs require the root environment. Outdoor rooms remain ordinary connected playable geometry.

Source v1–8 reject all environment/sky fields, including explicitly supplied environment: null and sky: false. Text parsers reject null, unknown fields, missing sun angles and bad scalar types; typed SDK validation checks the values and complete graph. Compilers preserve sky markers through expansion and convex decomposition, add the compiled version-1 environment payload and declare world/environment@1 with world/sectors@1. See the compiled decision.

Material mapping, version 1

SDK 0.0.8 provides world/material-mapping@1. Authoring source v5 supports optional root uv, room floor_uv, ceiling_uv, wall_uv, and edge uv. Source v1–4 reject those fields; omission preserves their previous encodings and compiler behavior. Source v5 defaults to triplanar mapping with world anchoring, one world unit per repeat, zero offset and zero rotation. Controls inherit field by field from root to room to edge; nil numeric pointers and empty mode/anchor strings inherit. Explicit rotation_degrees: 0 overrides an inherited rotation.

mode accepts triplanar, planar, wrap; anchor accepts world, top, bottom. scale: {x: ..., y: ...} gives positive world units per repeat in [0.001, 1,000,000]. offset is in repeats, with finite components bounded to ±1,000,000. rotation_degrees is finite and bounded to ±1,000,000. Wrap and vertical top/bottom anchors apply to walls: top uses ceiling(x,y)-z, bottom uses z-floor(x,y). Explicit floor/ceiling wrap or top/bottom anchors are invalid. Inherited root wrap falls back to planar on floors/ceilings; inherited wall anchors do not move horizontal surfaces. The compiler resolves inheritance, projection axes, scale, offset, rotation, anchoring and prefab transforms.

See compiled mapping for the resolved affine projections and capability requirements.

Solids and loose contents, version 1

Source v6 adds optional solids and contents to root documents and prefabs. Detail-only, sprite-only and nested room-free prefabs expand into existing rooms without creating sectors. Older source versions reject these fields. Omission preserves existing encoded bytes. The source solid count is at most 1,024 across root solids and prefab definitions; compilers enforce it again after expansion.

Source material names resolve through packaged textures. Nested prefab scale, yaw, translation and material overrides apply to solids and loose sprites. The compiler assigns loose contents to the first containing compiled sector in stable order, including shared boundaries and elevation. Source caps inherit horizontal root mapping defaults; source side_uv is restricted to shared planar/world X/Z mapping. Per-edge wrap and varying side triplanar weights are not expressible by a single SideUV and are rejected. Mapped solids require the existing world/material-mapping@1 marker/capability; hosts also require world/static-solids@1. No new guest command or level envelope version is added.

See compiled solids for exact geometry, material and collision bounds.

Wall bands and secondary colour, source version 7

Source v7 adds wall_bands to rooms and bands to directed authored edges. Each contains optional enabled, top and bottom. Each horizontal band accepts texture, enabled, height, repeat_width and offset: {x, y}. Textures resolve through the ordinary level texture catalog; the same texture can be reused by both bands. Enabled resolved bands require a texture and height. Repeat width defaults to 1 world unit and offset to zero. Alpha is band coverage; transparent pixels reveal the underlying opaque wall.

Rooms also supply floor_secondary, ceiling_secondary, wall_secondary, and edges may override secondary. A secondary references one opaque texture, optional enabled, strength in [0,1], and existing uv settings. Its colour modulates the main in linear space; neutral sRGB (188,188,188) preserves the main colour. It does not replace normal, height or AO channels.

All optional fields inherit field by field after prefab expansion; explicit enabled: false disables an inherited setting. Builders apply material substitution independently to top, bottom and secondary references. MergeBandSettings returns independent nested band records, preserving input values. Dimensions and repeats use world units and must be finite in [0.001,1000000]; offsets retain ±1000000 bounds. Source versions 1–6 reject these fields; omission preserves their existing serialized shape. Typed SDK validation checks versions and partial controls; public text parsers must additionally reject explicit null and unknown fields and validate the complete resolved settings and resource references.

Horizontal bands follow visible solid-span floor and ceiling profiles with fixed vertical thickness. Opposing envelopes on a short span crop at a proportional boundary, retaining requested texture density. The builder compiles the complete nonoverlapping wall partition, mappings, material IDs and coverage classes. There are no vertical-band or frame-sheet authoring fields. The source-v7 simplification revises the unreleased SDK 0.0.10 candidate; released source versions and compiled world/material-layer formats are unchanged. See the compiled contract.

Source v8 reusable animations

Source v8 adds optional top-level animations: {version: 1, presets: [...], materials: [...]} and actor.animation: {preset: name, phase_seconds: 0}. Presets are level-wide and referenced by name, including inside prefabs. Material bindings use declared texture names; flipbook frames are lists of declared texture names. The compiler resolves every frame to a nonzero level texture ID. Material bindings apply wherever the material occurs; an explicit actor binding supplies its own preset and phase. Preset coordinates stay actor-local through prefab expansion, so placement scale and orientation carry motion along with the actor.

The initial catalogue is flipbook, liquid, spin, and oscillate. See the compiled contract for parameters, bounds and timing. Source v1–v7 reject animations and retain existing wire behavior. Frames are separate complete textures, which the world material atlas packs into ordinary slots; they are not arbitrary authored atlas rectangles. Flipbook frames must have equal processed dimensions. Presets cannot be nested or reference other presets, and frame materials cannot select another material animation.

Liquid presets may also specify surface_amplitude (0–0.25 world metres), opacity (0–1, omitted means 1), and pixel_size (integer 0–32). These fields are liquid-only; explicit nulls are rejected by the source YAML adapter. Compilation owns an independent copy of an explicit opacity value.

GPU sprite particles, source version 10

Candidate SDK 0.0.11 adds root particles: {version: 1, presets: [...], emitters: [...]} and room/prefab particle_emitters arrays. Presets name level textures; emitter positions, yaw and uniform scale follow prefab transforms. Source v1–9 rejects particle fields, including explicit null. Optional fields should be omitted; text decoders also reject null inside the particle block and require explicitly authored zero-valued fields such as seed, position, curve age and burst time.

Compilers resolve all frames, require square matching frame dimensions, reserve complete birth schedule groups for overlapping lifetimes, compute conservative GPU motion bounds, and confine every emitter to one compiled convex sector. Room-local emitters remain in sectors owned by their expanded room. An emitter-only prefab is valid without unrelated geometry or marker contents. Optional scale omission or zero defaults to one; omitted vector components remain zero. They stage the separate @world/particles resource and declare world/particles@1 alongside world/sectors@1. See the version-1 particle contract for exact fields, units, lifecycle rules and resource bounds.

Solid renderers, source version 11

Prefab.Renderable packages a rigid solid-only prefab for runtime creation. Actor.SolidRenderer references one such prefab and also implicitly packages it. Renderer prefabs may nest solid-only instances; rooms, connections, ports, contents, emitters and collision-enabled solids are rejected. Actor sprites and actor animation bindings cannot coexist with a solid renderer. Public compilers retain one local definition per referenced/exported prefab, resolve level materials, and emit actor attachments in world.SolidRenderers. They must reject explicit renderer fields before v11 and null/empty renderer identifiers.

Solid renderer extension

world/solid-renderers@1 retains existing solid extrusions as immutable local prefab definitions and binds ordinary content actors to them. It permits 64 prefabs, 1,024 total solid definitions and 4,096 unique actor attachments. Definitions contribute level material IDs but no static receivers, collision volumes or shadow casters. Renderer actors cannot also contain sprites or actor animations. Deforming or blended material presets are rejected.

The explicit KWR2 envelope serializes the unchanged KWR1 document fields, then the bounded generated SolidRenderers extension. Absent extensions retain exact KWR1 bytes. Complete scan preflight, semantic validation and trailing-byte rejection apply to both envelopes; JSON remains unsupported.

Documentation

Overview

Code generated by internal/codegen/binary; DO NOT EDIT.

Package world defines the bounded compiled sector format shared by level compilers and Karty hosts. It contains data contracts and validation only.

Index

Constants

View Source
const (
	AnimationVersion      = uint32(1)
	FeatureAnimations     = cartridge.FeatureWorldAnimationsV1
	MaxAnimationPresets   = 64
	MaxMaterialAnimations = 196
	MaxAnimationFrames    = 64
	MaxAnimationSeconds   = 86400.0
)
View Source
const (
	FeatureEmission      = cartridge.FeatureWorldEmissionV1
	EmissionVersion      = uint32(1)
	MaxEmissionMaterials = 196
	MaxEmissionIntensity = 8.0
)
View Source
const (
	DefaultEnvironmentTimeOfDay   = 15.0
	DefaultEnvironmentCloudAmount = .35
)
View Source
const (
	MaterialMappingVersion = uint32(1)
	FeatureMaterialMapping = cartridge.FeatureWorldMaterialMappingV1
	MaxUVProjectionValue   = 1e12
	UVWeightTolerance      = 1e-9
)
View Source
const (
	MaterialLayersVersion = uint32(1)
	FeatureMaterialLayers = cartridge.FeatureWorldMaterialLayersV1
	FrameCoverageMain     = "main"
	FrameCoverageOpaque   = "opaque"
	FrameCoverageMasked   = "masked"
	// Each wall has <=7 profile intervals, <=2 solid spans, <=2 band-overlap
	// branches, <=3 vertical columns and <=3 horizontal rows. Every cell is a quad.
	MaxFrameRegionsPerWall = 7 * 2 * 2 * 3 * 3
	MaxFrameRegionVertices = 4
	MaxFrameRegions        = 32768
)
View Source
const (
	SolidRenderersVersion     = uint32(1)
	FeatureSolidRenderers     = "world/solid-renderers@1"
	MaxSolidPrefabs           = 64
	MaxSolidRendererTriangles = 65536
)
View Source
const (
	StaticSolidsVersion = uint32(1)
	FeatureStaticSolids = cartridge.FeatureWorldStaticSolidsV1
	MaxStaticSolids     = 1024
	MaxSolidVertices    = 64
)
View Source
const (
	LegacyVersion      = uint16(1)
	ActorVersion       = uint16(2)
	Version            = uint16(3)
	LightingVersion    = uint32(1)
	EntryName          = "@world/main"
	Feature            = cartridge.FeatureWorldSectorsV1
	FeatureLighting    = cartridge.FeatureWorldLightingV1
	EnvironmentVersion = uint32(1)
	FeatureEnvironment = cartridge.FeatureWorldEnvironmentV1
	MaxEncodedSize     = 8 * 1024 * 1024
	MaxSectors         = 256
	MaxWalls           = 8192
	MaxWallsPerSector  = 256
	MaxContents        = 4096
	// MaxLights bounds authored sources, including lights compiled into an
	// offline lightmap. It does not enlarge the runtime direct-light budget.
	MaxLights          = 4096
	MaxRuntimeLights   = 50
	MinLightRadius     = 0.001
	MaxIdentifierBytes = 128
	MaxKindBytes       = 128
	MaxTags            = 8
	MaxTagBytes        = 64
	MaxCoordinate      = 1_000_000.0
	MinEdgeLength      = 1e-6
	MinClearance       = 1e-6
)
View Source
const BinaryMagic = "KWR1"
View Source
const SolidBinaryMagic = "KWR2"

Variables

View Source
var (
	ErrSize            = errors.New("world payload size is invalid")
	ErrSyntax          = errors.New("world payload syntax is invalid")
	ErrVersion         = errors.New("world payload version is unsupported")
	ErrBounds          = errors.New("world payload exceeds a declared bound")
	ErrIdentity        = errors.New("world identity is invalid")
	ErrGeometry        = errors.New("world geometry is invalid")
	ErrPortal          = errors.New("world portal is invalid")
	ErrContent         = errors.New("world content is invalid")
	ErrMaterialMapping = errors.New("world material mapping is invalid")
	ErrLighting        = errors.New("world lighting is invalid")
	ErrEnvironment     = errors.New("world environment is invalid")
	ErrStaticSolids    = errors.New("world static solids are invalid")
	ErrCanonical       = errors.New("world payload is not canonical")
)

Functions

func Encode

func Encode(document Document) ([]byte, error)

Encode validates and encodes one compiled world as canonical typed binary.

func EncodeEmissionIntensity added in v0.0.11

func EncodeEmissionIntensity(value float64) (uint8, error)

func MaterialIDs added in v0.0.10

func MaterialIDs(d *Document) []uint32

MaterialIDs returns canonical deduplicated atlas order. All legacy primary references retain their original order, followed by secondary references, then non-main frame regions, in sector/floor/ceiling/wall order.

func SolidRendererTriangles added in v0.0.13

func SolidRendererTriangles(renderers *SolidRenderers) int

SolidRendererTriangles counts immutable triangles in validated extrusions: two triangles per side and n-2 triangles on each cap.

func Validate

func Validate(document *Document) error

Validate checks a complete compiled document before a host prepares private indexes or publishes a mounted resource.

func ValidateAnimationPreset added in v0.0.11

func ValidateAnimationPreset(p *AnimationPreset) error

ValidateAnimationPreset checks kind-specific bounds and rejects fields from other kinds. Flipbook holds frame zero outside its optional repeat burst.

func ValidateAnimations added in v0.0.11

func ValidateAnimations(document *Document) error

ValidateAnimations validates presets and bindings together, including complete actor references and nonrecursive frame targets. Texture existence is checked by the level compiler and host against packaged assets.

func ValidateEmission added in v0.0.11

func ValidateEmission(document *Document) error

func ValidateEnvironment added in v0.0.12

func ValidateEnvironment(environment *Environment) error

func ValidateEnvironmentSettings added in v0.0.12

func ValidateEnvironmentSettings(settings EnvironmentSettings) error

func ValidateLighting added in v0.0.8

func ValidateLighting(lighting *Lighting) error

ValidateLighting checks the complete lighting payload without requiring sector geometry. Optional absence is represented by Document.Lighting == nil; passing nil here is invalid. Capability/world consistency is the consumer's responsibility because the payload does not contain a cartridge manifest.

func ValidateSolidRenderers added in v0.0.13

func ValidateSolidRenderers(document *Document) error

func ValidateStaticSolids added in v0.0.8

func ValidateStaticSolids(solids *StaticSolids) (err error)

ValidateStaticSolids validates every item, including the last, before mounting. Solids may overlap each other and sectors; sector validation is unchanged.

func ValidateSurfaceSecondary added in v0.0.10

func ValidateSurfaceSecondary(s *SurfaceSecondary) error

func ValidateSurfaceUV added in v0.0.8

func ValidateSurfaceUV(mapping *SurfaceUV) error

ValidateSurfaceUV validates complete bounded projection and weight lists.

Types

type Actor added in v0.0.6

type Actor struct {
	Yaw       float64
	Pitch     float64
	Roll      float64
	Scale     Vec3
	Sprite    *Sprite
	Tags      []string
	Animation *AnimationBinding
}

Actor is the optional typed ECS payload introduced by compiled-world v2. Position remains on Content so actor and non-rendered gameplay contents share the same stable identity and sector assignment.

type AmbientCube added in v0.0.8

type AmbientCube struct {
	PositiveX Vec3
	NegativeX Vec3
	PositiveY Vec3
	NegativeY Vec3
	PositiveZ Vec3
	NegativeZ Vec3
}

AmbientCube supplies six world-space directional ambient colors. It replaces Ambient when present; squared unit-normal components weight each selected face. Colors are finite linear RGB intensities in [0,1].

type AnimationBinding added in v0.0.11

type AnimationBinding struct {
	Preset       string
	PhaseSeconds float64
}

AnimationBinding selects a named preset and a nonnegative clock offset.

type AnimationPreset added in v0.0.11

type AnimationPreset struct {
	Name             string
	Kind             string
	Frames           []uint32
	FPS              float64
	IntervalSeconds  float64
	Flow             Vec2
	Amplitude        float64
	SurfaceAmplitude float64
	Opacity          *float64
	PixelSize        uint32
	Frequency        float64
	Speed            float64
	Axis             Vec3
	Pivot            Vec3
	Offset           Vec3
	PeriodSeconds    float64
}

AnimationPreset contains exactly the fields relevant to Kind. Speeds are radians/second for spin and liquid; liquid flow and amplitude use UV units. SurfaceAmplitude is visual displacement in world metres on horizontal up-facing surfaces. Opacity defaults to 1; PixelSize defaults to 0 (continuous sampling). Axis, Pivot and Offset are actor-local, before actor scale and orientation.

type Animations added in v0.0.11

type Animations struct {
	Version   uint32
	Presets   []AnimationPreset
	Materials []MaterialAnimation
}

Animations is the optional world/animations@1 payload in compiled world v3.

type Content

type Content struct {
	ID       string
	SourceID string
	Instance string
	Kind     string
	Sector   uint32
	Position Vec3
	Actor    *Actor
}

Content retains both its compiled identity and authored/prefab provenance. The component payload is deliberately deferred to its own versioned format.

type Document

type Document struct {
	Version  uint16
	Sectors  []Sector
	Contents []Content
	// Lighting is opt-in in compiled v3 and requires FeatureLighting in addition
	// to Feature. Nil preserves the legacy wire encoding and runtime behavior.
	Lighting        *Lighting
	MaterialMapping *MaterialMapping
	StaticSolids    *StaticSolids
	MaterialLayers  *MaterialLayers
	Animations      *Animations
	Emission        *Emission
	Environment     *Environment
	SolidRenderers  *SolidRenderers
}

Document is one completely compiled world. Sector order is stable because portal references use sector indexes.

func Decode

func Decode(encoded []byte) (Document, error)

Decode rejects JSON, unsupported binary versions, trailing bytes and malformed records. A complete allocation-free scan bounds all typed allocations first.

type Emission added in v0.0.11

type Emission struct {
	Version   uint32
	Materials []MaterialEmission
}

Emission is an optional world/emission@1 payload. Intensity is an eight-bit linear-albedo multiplier, decoded as code*8/255. Pulse is independent of the material's optional flipbook/liquid animation; these are two bounded effects.

type EmissionPulse added in v0.0.11

type EmissionPulse struct {
	Depth         float64
	PeriodSeconds float64
	PhaseSeconds  float64
}

EmissionPulse has depth is the fraction of intensity removed at the dimmest point. A cosine pulse begins at full brightness and reaches its minimum after half a period.

func (EmissionPulse) Validate added in v0.0.11

func (p EmissionPulse) Validate() error

type Environment added in v0.0.12

type Environment struct {
	Version     uint32
	Preset      EnvironmentPreset
	Palette     EnvironmentPalette
	Sun         *EnvironmentSun
	TimeOfDay   *float64
	CloudAmount *float64
}

Environment is the optional world/environment@1 payload, available in compiled-world v3. Preset defaults are fixed by this payload version. Palette affects sky appearance only, independently of surface illumination.

type EnvironmentPalette added in v0.0.12

type EnvironmentPalette string
const (
	EnvironmentPaletteDefault  EnvironmentPalette = "default"
	EnvironmentPaletteViolet   EnvironmentPalette = "violet"
	EnvironmentPaletteTwilight EnvironmentPalette = "twilight"
)

type EnvironmentPreset added in v0.0.12

type EnvironmentPreset string
const (
	EnvironmentDaylight EnvironmentPreset = "daylight"
	EnvironmentSpace    EnvironmentPreset = "space"
	EnvironmentCartoon  EnvironmentPreset = "cartoon"
	EnvironmentFantasy  EnvironmentPreset = "fantasy"
)

type EnvironmentSettings added in v0.0.12

type EnvironmentSettings struct {
	TimeOfDay   float64
	CloudAmount float64
}

EnvironmentSettings is a complete live override of the clock and cloud coverage. TimeOfDay is hours in [0,24); CloudAmount is in [0,1]. A live clock overrides the authored fixed sun. Preset and palette remain authored.

type EnvironmentSun added in v0.0.12

type EnvironmentSun struct {
	Azimuth   float64 `yaml:"azimuth"`
	Elevation float64 `yaml:"elevation"`
}

EnvironmentSun supplies a fixed global sun direction in degrees. Azimuth is [0,360), measured from +X toward +Y. Elevation is [0,90] above the XY plane. If present both angles are explicit; omission selects the preset defaults.

type FrameHorizontal added in v0.0.10

type FrameHorizontal struct {
	Height, Repeat float64
	Offset         Vec2
	Piece          FramePiece
}

type FramePiece added in v0.0.10

type FramePiece struct {
	Material uint32
	Coverage string
}

FramePiece is an already resolved sheet region and its tile coverage class.

type FrameVertical added in v0.0.10

type FrameVertical struct {
	Width, Repeat, Phase float64
	Offset               Vec2
	Piece                FramePiece
}

type LightMotion added in v0.0.8

type LightMotion struct {
	Version       uint32
	Offset        Vec3
	PeriodSeconds float64
}

LightMotion version 1 moves a light smoothly from Position to Position+Offset and back once per PeriodSeconds. It is runtime direct lighting, never baked. The complete segment must stay within the ordinary light coordinate bounds.

type Lighting added in v0.0.8

type Lighting struct {
	Version     uint32
	Ambient     Vec3
	Lights      []PointLight
	AmbientCube *AmbientCube
	Actors      bool
}

Lighting is the independently versioned world/lighting@1 payload. Ambient and point colors are linear RGB intensities in [0,1]. Lights retain authored order and global world coordinates, without sector assignment, prefab transforms, shadows, portal transport or PBR parameters.

type MaterialAnimation added in v0.0.11

type MaterialAnimation struct {
	Material     uint32
	Preset       string
	PhaseSeconds float64
}

type MaterialEmission added in v0.0.11

type MaterialEmission struct {
	Material  uint32
	Intensity uint8
	Pulse     *EmissionPulse
	Lights    []string
}

type MaterialLayers added in v0.0.10

type MaterialLayers struct {
	Version uint32
}

type MaterialMapping added in v0.0.8

type MaterialMapping struct {
	Version uint32
}

MaterialMapping opts a compiled v3 world into world/material-mapping@1. Every floor, ceiling and wall must then supply complete baked projections. Projection setup, authoring modes and anchors belong to the compiler.

type Plane

type Plane struct {
	A float64
	B float64
	C float64
}

Plane describes elevation z=A*x+B*y+C.

type PointLight added in v0.0.8

type PointLight struct {
	ID       string
	Position Vec3
	Color    Vec3
	Radius   float64
	Motion   *LightMotion
}

PointLight is one bounded global light. ID is unique within Lighting; Radius is an influence radius in world units in [MinLightRadius, MaxCoordinate].

type ResolvedEnvironment added in v0.0.12

type ResolvedEnvironment struct {
	Preset       EnvironmentPreset
	SkyZenith    Vec3
	SkyHorizon   Vec3
	SkyNadir     Vec3
	CloudColor   Vec3
	SunDiskColor Vec3
	SunDirection Vec3
	SunColor     Vec3
	SunIntensity float64
	Ambient      Vec3
	AmbientCube  AmbientCube
	TimeOfDay    float64
	CloudAmount  float64
}

ResolvedEnvironment supplies bounded linear RGB defaults to consumers without runtime allocation. SunDirection points toward the light; incoming rays travel in the opposite direction. AmbientCube is outdoor fill, not global indoor illumination. Consumers must restrict fill and sun visibility using sky openings and geometry. Decorative sky elements add no additional lights.

func ResolveEnvironment added in v0.0.12

func ResolveEnvironment(environment *Environment) (ResolvedEnvironment, error)

ResolveEnvironment validates and resolves the versioned preset. Palette overrides never modify the sun or ambient light defaults. Calling this at world preparation keeps preset work outside the render loop.

func ResolveEnvironmentSettings added in v0.0.12

func ResolveEnvironmentSettings(environment *Environment, settings EnvironmentSettings) (ResolvedEnvironment, error)

ResolveEnvironmentSettings applies a validated live clock to the authored style. It allocates no memory and never changes the authored payload.

type Sector

type Sector struct {
	ID               string
	SourceRoom       string
	Instance         string
	Walls            []Wall
	Floor            Plane
	Ceiling          Plane
	FloorMaterial    uint32
	CeilingMaterial  uint32
	FloorUV          *SurfaceUV
	CeilingUV        *SurfaceUV
	FloorSecondary   *SurfaceSecondary
	CeilingSecondary *SurfaceSecondary
	// Sky opens the ceiling visually and to environment lighting. The finite
	// ceiling plane still bounds navigation, portals and spatial queries.
	Sky bool
}

Sector is a strictly convex CCW cell. SourceRoom and Instance retain the authoring identity after prefab expansion and decomposition.

type Solid added in v0.0.8

type Solid struct {
	ID             string
	Footprint      []Vec2
	Bottom         Plane
	Top            Plane
	SideMaterial   uint32
	TopMaterial    uint32
	BottomMaterial uint32
	SideUV         *SurfaceUV
	TopUV          *SurfaceUV
	BottomUV       *SurfaceUV
	Collision      bool
}

Solid is a strictly convex CCW extrusion between two elevation planes. Collision blocks movement but never makes Top a walkable floor. Optional mappings are shared by the indicated surface group; SideUV is not per-edge.

type SolidAttachment added in v0.0.13

type SolidAttachment struct {
	Actor  string
	Prefab string
}

type SolidPrefab added in v0.0.13

type SolidPrefab struct {
	ID     string
	Solids []Solid
}

type SolidRenderers added in v0.0.13

type SolidRenderers struct {
	Version uint32
	Prefabs []SolidPrefab
	Actors  []SolidAttachment
}

SolidRenderers retains reusable local solid geometry separately from static world geometry. Actors bind existing content identities to prefab identities.

type Sprite added in v0.0.6

type Sprite struct {
	AssetID uint32
	Facing  SpriteFacing
	Alpha   SpriteAlpha
	Width   float64
	Height  float64
	OriginX float64
	OriginY float64
}

type SpriteAlpha added in v0.0.6

type SpriteAlpha string
const (
	SpriteCutout SpriteAlpha = "cutout"
	SpriteBlend  SpriteAlpha = "blend"
)

type SpriteFacing added in v0.0.6

type SpriteFacing string
const (
	SpriteCameraFacing SpriteFacing = "camera-facing"
	SpriteUpright      SpriteFacing = "upright"
	SpriteCross        SpriteFacing = "cross"
	SpriteFixed        SpriteFacing = "fixed"
)

type StaticSolids added in v0.0.8

type StaticSolids struct {
	Version uint32
	Items   []Solid
}

StaticSolids contains independently placed opaque volumes. They never alter the sector/portal graph. Hosts must advertise FeatureStaticSolids.

type SurfaceSecondary added in v0.0.10

type SurfaceSecondary struct {
	Material uint32
	Strength float64
	UV       *SurfaceUV
}

type SurfaceUV added in v0.0.8

type SurfaceUV struct {
	Projections []UVProjection
	Weights     []float64
}

SurfaceUV contains one planar/wrapped projection or three blended projections. Weights are constant per surface, finite, nonnegative and normalized to one within UVWeightTolerance. They apply to all material channels, not just color.

type UVPlane added in v0.0.8

type UVPlane struct {
	X      float64
	Y      float64
	Z      float64
	Offset float64
}

UVPlane evaluates X*position.X+Y*position.Y+Z*position.Z+Offset. All coefficients and Offset are finite with absolute value at most 1e12.

type UVProjection added in v0.0.8

type UVProjection struct {
	U UVPlane
	V UVPlane
}

UVProjection is an authored-position affine mapping to texture repeats. Hosts evaluate these planes before clipping; no projection setup is inferred.

type Vec2

type Vec2 struct {
	X float64
	Y float64
}

type Vec3

type Vec3 struct {
	X float64
	Y float64
	Z float64
}

type Wall

type Wall struct {
	Start        Vec2
	End          Vec2
	Portal       int32
	PortalWall   uint16
	Material     uint32
	SourceEdge   string
	UV           *SurfaceUV
	Secondary    *SurfaceSecondary
	FrameRegions []WallFrameRegion
	// FrameCompiled preserves static-frame participation when a portal has no
	// exposed solid spans and thus no region records.
	FrameCompiled bool
	// Sky is an opaque boundary rendered as the environment. It is valid only
	// in a sky sector and cannot participate in a portal. Confinement remains.
	Sky bool
}

Wall is one directed sector boundary. Portal is the adjacent sector index, or -1 for an opaque wall. PortalWall is one plus the reciprocal wall index in compiled-world v3; zero is reserved for v1/v2 coincident portals and opaque walls. The paired directed edges define a rigid destination-to-source portal transform. SourceEdge is empty only for compiler-generated internal decomposition edges.

type WallFrameConfig added in v0.0.10

type WallFrameConfig struct {
	Top, Bottom     FrameHorizontal
	Start, End      FrameVertical
	Patches         [4]FramePiece
	PerimeterOffset float64
}

WallFrameConfig is a build-time recipe; it is never serialized to the host. Patches are top/start, top/end, bottom/start, bottom/end in that order.

type WallFrameRegion added in v0.0.10

type WallFrameRegion struct {
	Vertices []Vec2
	Material uint32
	UV       *SurfaceUV
	Coverage string
	RepeatU  bool
	RepeatV  bool
}

WallFrameRegion is one complete, nonoverlapping wall partition, already selected by the builder. Vertices use X=edge fraction and Y=world elevation, ordered counterclockwise in this two-dimensional coordinate system. Main regions retain the wall's mapping and have no region UV. Opaque regions sample their sole material; masked regions blend over the wall's main material.

func CompileWallFrame added in v0.0.10

func CompileWallFrame(w Wall, p WallProfile, f WallFrameConfig) ([]WallFrameRegion, error)

CompileWallFrame partitions visible solid spans into at most 252 convex regions. Bands follow affine floor/ceiling profiles; opposing envelopes crop proportionally when a face is shorter than their combined requested sizes. Original authored corners and texture IDs have already been resolved by the builder. The output contains every main and frame region with no overlap.

type WallProfile added in v0.0.8

type WallProfile struct {
	Heights [4][2]float64
	Cuts    [8]float64
	Count   int
}

WallProfile divides a wall where any of its four linear elevation functions cross. Heights 0/1 are source floor/ceiling; 2/3 are destination elevations already transformed into the source coordinate frame. It contains no mesh or renderer state and can be used by public builders and private hosts alike.

func NewWallProfile added in v0.0.8

func NewWallProfile(heights [4][2]float64, tolerance float64) (WallProfile, error)

NewWallProfile requires finite endpoint heights and a finite positive tolerance. The four pairs have at most six interior crossings.

func ProfileForWall added in v0.0.10

func ProfileForWall(d *Document, sector, index int) (WallProfile, error)

ProfileForWall resolves destination endpoints and elevation translation using the compiled portal pair. Callers validate the world before invoking it.

func (WallProfile) Controls added in v0.0.8

func (p WallProfile) Controls(t float64) (int, int)

Controls returns the maximum floor and minimum ceiling at an edge fraction.

func (WallProfile) Height added in v0.0.8

func (p WallProfile) Height(kind int, t float64) float64

Height evaluates one linear elevation at an edge fraction.

Jump to

Keyboard shortcuts

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