World Plugin
The Clay World plugin provides comprehensive game world management for both 2D and 3D games. It integrates canvas rendering, physics simulation, and SVG-based level loading into cohesive world components. The plugin offers separate implementations for 2D and 3D worlds while sharing common functionality like scene loading and entity management.
Getting Started
To use the Clay World plugin in your QML files:
import Clayground.World
Core Components
- ClayWorld2d - Complete 2D game world with Box2D physics, ClayCanvas rendering, and camera following
- ClayWorld3d - Complete 3D game world with Qt Quick 3D physics and WASD/orbit camera controls (desktop only:
QtQuick3D.Physicsis not in the Web Runtime) - ClayWorldBase - Shared base functionality for scene loading and entity management
- SceneLoader2d - Loads entities from SVG files into 2D worlds
- SceneLoader3d - Loads entities from SVG files into 3D worlds
- Minimap2d - Miniature map view of a 2D world
- Box3DBody - 3D physics-enabled box shape (desktop only, like ClayWorld3d)
Usage Examples
Basic 2D World
import QtQuick
import Clayground.World
import Clayground.Physics
ClayWorld2d {
id: gameWorld
anchors.fill: parent
// World setup
xWuMin: 0
xWuMax: 100
yWuMin: 0
yWuMax: 50
// Physics
gravity: Qt.point(0, 10)
// Camera follows player
observedItem: player
RectBoxBody {
id: player
xWu: 10
yWu: 10
widthWu: 2
heightWu: 2
color: "blue"
bodyType: Body.Dynamic
}
}
Level Loading from SVG
ClayWorld2d {
id: world
scene: "levels/level1.svg"
loadMapAsync: true
// Register components for SVG loading
components: new Map([
["Wall", wallComponent],
["Enemy", enemyComponent],
["Collectible", coinComponent]
])
Component {
id: wallComponent
RectBoxBody {
color: "#333333"
bodyType: Body.Static
}
}
Component {
id: enemyComponent
RectBoxBody {
color: "red"
bodyType: Body.Dynamic
}
}
onMapLoaded: {
console.log("Level loaded!")
}
}
3D World Setup
ClayWorld3d {
id: world3d
anchors.fill: parent
// World size
xWuMax: 200
zWuMax: 200
// Camera setup
observedObject: player3d
Box3DBody {
id: player3d
position: Qt.vector3d(50, 10, 50)
width: 20
height: 20
depth: 20
color: "orange"
}
// Load 3D scene
scene: "levels/3d_level.svg"
components: new Map([
["Platform", platform3dComponent]
])
}
Areas in a 3D World
A polygon in the map - a lake, a plaza, a building footprint - becomes a 3D
entity the same way a rectangle does: its description names a registered
component, and the loader hands over the ring in world coordinates plus the
SVG fill as color. A Poly3D needs nothing else.
ClayWorld3d {
id: world
scene: "levels/town.svg"
components: new Map([["Area", areaComponent]])
Component {
id: areaComponent
Poly3D { useToonShading: true }
}
}
Height is not a mechanism of its own: it rides the properties section every
loaded entity has, so a footprint that should stand up says so in its SVG
description.
{"component":"Area","properties":{"extrude":12}}
The scene coordinates a loader works in are Y-up with the origin at the map’s
bottom left, while a 3D world spans x: [0, xWuMax] and z: [0, zWuMax]. So
the map’s Y becomes zWuMax - y - the conversion SceneLoader3d::toWorldRing()
does, and the same one the rectangle handler applies to a rectangle’s center.
Seen from above, the world is the SVG as it was drawn.
A polygon whose description names no registered component is not dropped: it
reaches polygonLoaded with its scene points untouched, so a sandbox can build
something the loader would not have guessed - an area with holes, for instance,
which an SVG polygon cannot express on its own.
ClayWorld3d {
id: world
onPolygonLoaded: (id, groupId, points, fillColor, strokeColor, description) => {
let ring = points.map(p => Qt.vector2d(p.x, world.zWuMax - p.y));
pondComponent.createObject(world.root, {vertices: ring, color: fillColor});
}
}
See demo/Sandbox3dScene.qml and demo/areas.svg for both routes side by side.
Minimap Implementation
ClayWorld2d {
id: mainWorld
// ... world setup
}
Minimap2d {
world: mainWorld
width: 200
height: 150
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 20
// Map entity types to minimap representations
typeMapping: new Map([
["Player", playerDotComponent],
["Enemy", enemyDotComponent],
["Wall", wallRectComponent]
])
Component {
id: playerDotComponent
Rectangle {
color: "green"
radius: width * 0.5
}
}
Component {
id: enemyDotComponent
Rectangle { color: "red" }
}
}
Dynamic Entity Creation
ClayWorld2d {
id: world
function spawnEnemy(x, y) {
let enemy = enemyComponent.createObject(room, {
xWu: x,
yWu: y
})
return enemy
}
Component {
id: enemyComponent
RectBoxBody {
widthWu: 2
heightWu: 2
color: "red"
bodyType: Body.Dynamic
}
}
Timer {
interval: 5000
repeat: true
running: true
onTriggered: {
world.spawnEnemy(
Math.random() * world.xWuMax,
Math.random() * world.yWuMax
)
}
}
}
Custom Scene Loading
ClayWorld2d {
id: world
onPolylineLoaded: (id, groupId, points, fillColor, strokeColor, description) => {
// Handle patrol paths
if (description.includes("patrol_path")) {
createPatrolPath(id, points)
}
}
onGroupAboutToBeLoaded: (id, description) => {
console.log("Loading group:", id)
}
onMapEntityCreated: (obj, groupId, compName) => {
// Post-process loaded entities
if (compName === "Enemy") {
obj.target = player
}
}
}
Physics Configuration
ClayWorld2d {
// Platformer physics
gravity: Qt.point(0, 20)
timeStep: 1/60
// Top-down physics
// gravity: Qt.point(0, 0)
// Debug rendering
debugPhysics: true
debugRendering: true
// Pause physics
MouseArea {
anchors.fill: parent
onClicked: parent.physicsEnabled = !parent.physicsEnabled
}
}
Best Practices
-
Scene Organization: Use SVG groups to organize level elements logically.
-
Component Registration: Register all components before loading scenes.
-
Async Loading: Use
loadMapAsync: truefor large levels to prevent UI freezing. -
World Units: Always work in world units for consistency across different screen sizes.
-
Entity Management: Use the
roomcontainer for proper entity lifecycle management. -
Performance: Limit physics bodies and use static bodies where possible.
Technical Implementation
The Clay World plugin provides:
- Unified World Management: Common base for 2D and 3D worlds
- SVG Scene Loading: Parse SVG files with JSON metadata for game entities
- Physics Integration: Seamless Box2D (2D) and Qt Quick 3D Physics integration
- Camera Systems: Automatic following for 2D, orbit/WASD controls for 3D
- Async Loading: Non-blocking entity creation for smooth gameplay
- Component Factory: Map SVG descriptions to QML components
The plugin handles coordinate transformations, physics body creation, and proper parent-child relationships automatically, making it easy to create complex game worlds from simple SVG layouts.
API Reference
AnchoredMask Shader-based radial darkness mask that tracks a target Item
Properties
| Name | Type | Description |
|---|---|---|
_ppu readonly | real | When false the shader is fully skipped (no GPU cost) |
color | color | Warm tint applied in the falloff region between inner and outer |
darkness | color | Color applied outside outerRadius |
enabled readonly | bool | When false the shader is fully skipped (no GPU cost) |
flicker | real | Flicker amplitude in 0..1. Set to 0 to disable flicker |
innerRadius | real | Fully visible radius around the target, in world units |
outerRadius | real | Fully dark radius around the target, in world units |
target | var | Item the mask centers on. Must expose xWu and yWu (e.g. a PhysicsItem) |
world | var | ClayWorld2d reference used for pixelPerUnit and viewport offsets |
Box3DBody 3D physics-enabled box with visual representation
ClayWorld2d Complete 2D game world with physics, rendering, and scene loading
ClayWorld3d Complete 3D game world with physics, camera, and scene loading
ClayWorldBase Common base functionality for 2D and 3D game worlds
Light2d A coloured point light in world units, rendered by LightLayer2d
Properties
| Name | Type | Description |
|---|---|---|
castsShadows | bool | Whether the layer's occluders block this light |
color | color | Light colour. Saturated colours tint what they light |
flicker | real | Flicker amount in 0..1; 0 is a steady light |
intensity | real | Brightness multiplier; 1 lights the centre to full scene brightness, above 1 overexposes into the light colour |
lightLayer | LightLayer2d | Restricts the light to one layer; null (default) means every layer shows it. (Not layer: that is Item's own.) |
offsetXWu | real | X offset from the followed item, in world units |
offsetYWu | real | Y offset from the followed item, in world units |
phase | real | Flicker phase offset; randomised per light on creation |
radius | real | Distance in world units at which the light has faded to zero |
target | var | Optional item to follow; it must expose xWu and yWu |
xWu | real | X position in world units, used when nothing is followed |
yWu | real | Y position in world units, used when nothing is followed |
Methods
| Method | Returns | Description |
|---|---|---|
positionWu() | point |
LightLayer2d Lights a ClayWorld2d with coloured Light2d lights and wall shadows
Properties
| Name | Type | Description |
|---|---|---|
active | bool | When false the layer is not drawn at all |
ambient | color | Light level where no light reaches |
bands | int | Quantises the light level into this many steps, for a retro look; 0 (default) is a smooth falloff |
dither | real | Ordered (Bayer 4x4) dither amount in 0..1 |
emissive readonly | Item | Parent for things that give off light themselves |
falloff | real | How fast light fades with distance: the light at a fraction x of the radius is (1 - x)^falloff. 2 (default) pools light around its source, 1 fills the circle more evenly |
glow | real | How strongly the colour of a light is added on top of the brightened scene (0 = lights only brighten) |
lightCount readonly | int | How many lights were drawn in the last frame |
maxLights readonly | int | How many lights the shader takes at once |
resolutionScale | real | Renders the lighting at this fraction of the viewport's resolution (0.25..1) and scales it up linearly |
shadowHardness | real | How much wall a ray must cross to be fully blocked, as 1 / cells. The default 2.5 blocks behind 0.4 cells of wall; lower values let light seep through thin walls |
world | var | ClayWorld2d to light |
Methods
| Method | Returns | Description |
|---|---|---|
clayInspect() | object | |
clearOccluders() | void | |
isOccluded(real xWu, real yWu) | bool | |
setOccluderCell(int cx, int cy, bool solid) | void | |
setOccluderGrid(int cols, int rows, real cellSizeWu, var isSolid, real originXWu, real originYWu) | void | |
setOccluderRects(list rects, real cellSizeWu) | void | |
visibleLights() | list |
Minimap2d Miniature map view of a 2D world
SceneLoader2d Scene loader specialized for 2D worlds
SceneLoaderBase Base scene loader for parsing SVG files into game entities
ScreenFx2d Screen effects for a ClayWorld2d: vignette, colour grade, flash, chromatic aberration, low-health warning, grain and posterise
Properties
| Name | Type | Description |
|---|---|---|
aberration | real | Standing chromatic aberration in 0..1; 0 is off |
brightness | real | Added to every channel; 0 is neutral |
colorLevels | int | Posterises the brightness to this many levels, for a retro look; 0 is off. The hue is kept, so dark scenes do not shift colour |
contrast | real | Contrast around mid grey; 1 is neutral |
dither | real | Ordered dither applied with colorLevels, in 0..1 |
gradeActive readonly | bool | True while the world is rendered through the grade pass |
grain | real | Film grain in 0..1; 0 is off |
lowHealth | real | Low-health warning in 0..1: desaturates the world and beats a red edge. Bind it to the player's health |
maxAberrationPx | real | Channel offset at the screen corners, in pixels, for an aberration of 1 |
overlayActive readonly | bool | True while the overlay pass is drawn |
saturation | real | Saturation; 1 is neutral, 0 is greyscale |
sourceItem | Item | Item the grade reads and hides; defaults to the world's picture - its canvas, or the held frame of a view-only hit stop. The effect covers the ScreenFx2d's own geometry, which fills its parent |
temperature | real | Colour temperature in -1 (cold, blue) .. 1 (warm, orange); 0 is neutral |
tint | color | Multiplies the world colour; white is neutral |
vignette | real | Vignette strength in 0..1; 0 is off |
vignetteColor | color | Colour the edges fade to |
vignetteRadius | real | Where the vignette starts, as a fraction of the centre-to-corner distance |
vignetteSoftness | real | Width of the vignette falloff, same unit as vignetteRadius |
world | var | ClayWorld2d whose canvas is processed |
Methods
| Method | Returns | Description |
|---|---|---|
clayInspect() | object | |
flash(color color, int ms, real strength) | void | |
pulse(real amount, int ms) | void |