Render3D. Render3DPlugin

Render3D Plugin - The 3D renderer, camera, lights, shadows and fog

  • There is one of these, in the global render3D
  • It draws the 3D scene before gameRender, so 2D drawing lands on top
  • Set renderAfter2D to draw the 3D scene over the 2D scene instead
  • Settings like lighting and specular are read as each thing draws
  • Every object sets them from its own flags, so you rarely touch them

Constructor

new Render3DPlugin()

Create the global 3D renderer, call in gameInit

Example
new Render3DPlugin;
render3D.camera.pos = vec3(0, 5, 10);
render3D.camera.lookAt(vec3());
new EngineObject3D(vec3(), buildBox());

Members

additive

Properties
TypeDescription
boolean

Additive blending instead of alpha, in the transparent stage

ambientColor

Properties
TypeDescription
Color

Ambient light color

anisotropy

Properties
TypeDescription
number

Anisotropic filtering for textures seen at an angle, 1 to 16, 1 is off; needs mipmaps

boxMesh

Properties
TypeDescription
Mesh

A box of size 1 that drawBox uses, for any object that is a box; set the object's scale3D and color instead of editing the mesh, which would change every box that uses it

camera

Properties
TypeDescription
Camera3D

The camera

cameraForward

Properties
TypeDescription
Vector3

Camera forward axis this frame

cameraRight

Properties
TypeDescription
Vector3

Camera right axis this frame

cameraUp

Properties
TypeDescription
Vector3

Camera up axis this frame

cullBackFaces

Properties
TypeDescription
boolean

Skip faces that point away from the camera, set per object with its cullBackFaces flag

depthTest

Properties
TypeDescription
boolean

Test against the depth buffer, reset to true before each object and callback

depthWrite

Properties
TypeDescription
boolean

Write to the depth buffer, owned by the stages: on for opaque, off for transparent

emissive

Properties
TypeDescription
number

How much a surface lights itself, set per object by its emissive

fogColor :Color|undefined

Type:
  • Color | undefined
Properties
TypeDescription
Color | undefined

Fog color, uses canvasClearColor when undefined

fogEnd

Properties
TypeDescription
number

Distance from the camera where fog is total, 0 disables fog

fogStart

Properties
TypeDescription
number

Distance from the camera where fog starts

frustumCulling

Properties
TypeDescription
boolean

Skip meshes whose bounding sphere is outside the view

gravity

Properties
TypeDescription
Vector3

Added to the velocity3D of every object with a mass each frame, scaled by its gravityScale; sync2D objects use the 2D gravity

instancing

Properties
TypeDescription
boolean

Draw every use of a mesh in the opaque stage as one instanced call, mesh.instanced overrides it per mesh

isRendering

Properties
TypeDescription
boolean

True while the 3D pass is running, 3D draws are only valid then

lightColor

Properties
TypeDescription
Color

Directional light color

lightDirection

Properties
TypeDescription
Vector3

Direction the directional light travels, read at each draw; any length will do, both the shading and the shadows normalize it themselves

lighting

Properties
TypeDescription
boolean

Apply lighting, when false draws plain vertex color times texture and casts no shadow; off for billboards, lines, ribbons and soft discs, an object sets emissive instead

mipmaps

Properties
TypeDescription
boolean

Sample textures through mipmaps so they do not shimmer in the distance, false uses each texture's own filtering like 2D

onRenderOpaque :function|undefined

Type:
  • function | undefined
Properties
TypeDescription
function | undefined

Draw solid world here, it runs again for shadows so only draw in it

onRenderTransparent :function|undefined

Type:
  • function | undefined
Properties
TypeDescription
function | undefined

Draw see through things here, like glows, billboards and soft shadows

pixelated

Properties
TypeDescription
boolean

Draw state: keep texture pixels hard edged, no mipmaps and no blending between them, set per object by pixelated

projectionMatrix

Properties
TypeDescription
Matrix4

This frame's projection matrix

receiveShadow

Properties
TypeDescription
boolean

Darken by the shadow map when shadows are on, turn it off for things that should stay lit inside a shadow

renderAfter2D

Properties
TypeDescription
boolean

Draw the 3D scene on top of the 2D scene instead of under it

shadowBias

Properties
TypeDescription
number

Stops surfaces shadowing themselves, raise for speckles, lower if shadows drift off

shadowCenter :Vector3|undefined

Type:
  • Vector3 | undefined
Properties
TypeDescription
Vector3 | undefined

Center of the shadowed area, read each frame, undefined follows the camera

shadowMapSize

Properties
TypeDescription
number

Size of the shadow map in pixels, bigger is sharper and slower

shadowMatrix

Properties
TypeDescription
Matrix4

This frame's light view projection for the shadow map

shadowPass

Properties
TypeDescription
boolean

True while the shadow map is being drawn, draws go to the depth only shader

shadowRange

Properties
TypeDescription
number

World size the shadow map covers around shadowCenter, smaller is sharper; it is a square facing the light, so it turns as the light does, and about 1.5 times an area's width covers it from any angle

shadowSoftness

Properties
TypeDescription
number

How much to blur the shadow edges

shadows

Properties
TypeDescription
boolean

Cast real shadows from the directional light, off by default and free when off

sky :Mesh|undefined

Type:
  • Mesh | undefined
Properties
TypeDescription
Mesh | undefined

Sky dome from buildSky or setSky, drawn around the camera behind everything

smoothShading

Properties
TypeDescription
boolean

Default for every builder's smooth argument: true for smooth vertex normals, false for flat faces

softShadowHeight :number|HeightMap|function

Type:
  • number | HeightMap | function
Properties
TypeDescription
number | HeightMap | function

Floor for objects with a softShadow: a height, a HeightMap, or (x, z) => y

sortTransparent

Properties
TypeDescription
boolean

Draw see through things far to near so they blend correctly

specular

Properties
TypeDescription
number

Strength of the highlight where the directional light reflects, 0 is none and 1 adds the light's full color at its brightest; its size is fixed

sphereMesh

Properties
TypeDescription
Mesh

A smooth sphere of diameter 1 that drawSphere uses, shared the same way as boxMesh

viewMatrix

Properties
TypeDescription
Matrix4

This frame's view matrix

viewProjection

Properties
TypeDescription
Matrix4

This frame's combined view projection

Methods

bake(drawFunction) → {Mesh}

Build a mesh once out of draw calls, instead of redrawing the shapes every frame

  • Call the same drawStrip, drawQuad and drawBox calls inside, and get a mesh back
  • Strips inside a bake ignore their tileInfo, the finished mesh picks the texture when it draws
  • drawMesh, drawBox and drawSphere copy their mesh in, moved and tinted, their tileInfo dropped too
Parameters:
NameTypeDescription
drawFunctionfunction
Returns:
Type: 
Mesh

drawBillboard(pos, sizeopt, tileInfoopt, coloropt, angleopt, uprightopt)

Draw a flat square that always faces the camera, unlit so it keeps its own colors

  • Draw it from onRenderTransparent or a transparent object so it can fade
Parameters:
NameTypeAttributesDefaultDescription
posVector3

Center

sizeVector2<optional>

World units

tileInfoTileInfo | TextureInfo<optional>
colorColor<optional>
anglenumber<optional>
0

Rotation in the camera plane, counter clockwise

uprightboolean<optional>
false

Stand on world up and only turn to face the camera, for sprites on the ground

drawBox(pos, sizeopt, coloropt, rotationopt)

Draw a box, untextured, for blocking out a scene without meshes or objects

Parameters:
NameTypeAttributesDefaultDescription
posVector3

Center

sizeVector3 | number<optional>
1

Full size, a number for a cube

colorColor<optional>
rotationVector3<optional>

vec3(pitch, yaw, roll)

drawLine(posA, posB, widthopt, coloropt)

Draw a line as a camera facing ribbon, unlit

Parameters:
NameTypeAttributesDefaultDescription
posAVector3
posBVector3
widthnumber<optional>
0.1
colorColor<optional>

drawMesh(mesh, matrixopt, tileInfoopt, coloropt)

Draw a mesh with the current draw state, batched with its other uses in the opaque stage when instancing is on

Parameters:
NameTypeAttributesDescription
meshMesh
matrixMatrix4 | Vector3<optional>

Object transform, or just a position to draw it at

tileInfoTileInfo | TextureInfo<optional>

Texture, mesh uvs map across the tile or the whole texture

colorColor<optional>

Tint

drawQuad(a, b, c, d, tileInfoopt, coloropt)

Draw a quad from four corners in loop order, counter clockwise seen from the front, a is the top left of the texture

Parameters:
NameTypeAttributesDescription
aVector3
bVector3
cVector3
dVector3
tileInfoTileInfo | TextureInfo<optional>
colorColor | Array.<Color><optional>

One for all or one per corner

drawRibbon(points, widthopt, coloropt, tileInfoopt, sideopt)

Draw a ribbon along a path, unlit and visible from both sides; width and color can change along it

  • The texture runs along the length, u from the first point to the last
  • A path that ends where it starts is a loop, and joins with no seam
Parameters:
NameTypeAttributesDefaultDescription
pointsArray.<Vector3>

Center line in order, at least two

widthnumber | Array.<number><optional>
0.1

Full width, one for all or one per point

colorColor | Array.<Color><optional>

One for all or one per point

tileInfoTileInfo | TextureInfo<optional>
sideVector3 | Array.<Vector3><optional>

Direction across the ribbon, one for all or one per point, default faces the camera

drawSky()

Draw render3D.sky around the camera, unlit, unfogged and behind everything, called automatically by the pass

drawSoftDisc(pos, sizeopt, coloropt, normalopt, sidesopt)

Draw a disc that fades to transparent at the rim, unlit, for glows, puffs and sky dots

Parameters:
NameTypeAttributesDefaultDescription
posVector3

Center

sizenumber<optional>
1

Diameter

colorColor<optional>
normalVector3<optional>

Facing direction, faces the camera by default

sidesnumber<optional>
16

drawSoftShadow(pos, sizeopt, floorHeightopt, coloropt, liftopt)

Draw a soft round shadow on the ground under something, much cheaper than a real shadow

  • Draw it from onRenderTransparent or from a transparent object
Parameters:
NameTypeAttributesDefaultDescription
posVector3

Position of the thing casting the shadow

sizenumber<optional>
1

Diameter

floorHeightnumber | HeightMap | function<optional>
0

Height of the ground, a HeightMap, or (x, z) => y to follow terrain

colorColor<optional>
liftnumber<optional>
0.02

How far above the ground to draw, raise it if the shadow cuts into rough ground

drawSphere(pos, sizeopt, coloropt)

Draw a sphere, untextured and smooth shaded

Parameters:
NameTypeAttributesDefaultDescription
posVector3

Center

sizenumber<optional>
1

Diameter

colorColor<optional>

drawStrip(points, normalsopt, uvsopt, colorsopt, tileInfoopt)

Draw a triangle strip, batched into the stream with the current draw state

  • Strip order: the first three points make a triangle, then each point makes another with the two before it
  • List the first three points counter clockwise as seen from the front, or the face points away and may vanish when back faces are culled
  • inside a bake the strip goes into the mesh instead, in the transparent stage it is queued for sorting
Parameters:
NameTypeAttributesDescription
pointsArray.<Vector3>

In strip order

normalsVector3 | Array.<Vector3><optional>

One for all or one per point, default up

uvsVector2 | Array.<Vector2><optional>

One for all or one per point, 0-1 across the tile

colorsColor | Array.<Color><optional>

One for all or one per point, vertex colors come before the texture

tileInfoTileInfo | TextureInfo<optional>

Texture for this strip

drawStripUnlit(points, normalsopt, uvsopt, colorsopt, tileInfoopt)

Draw a strip with lighting off, for camera facing shapes where the light direction means nothing

Parameters:
NameTypeAttributesDescription
pointsArray.<Vector3>

Strip order

normalsVector3 | Array.<Vector3><optional>
uvsVector2 | Array.<Vector2><optional>
colorsColor | Array.<Color><optional>
tileInfoTileInfo | TextureInfo<optional>

drawTriangle(a, b, c, coloropt)

Draw a triangle, counter clockwise from outside is the front

Parameters:
NameTypeAttributesDescription
aVector3
bVector3
cVector3
colorColor<optional>

flush()

Draw the pending stream vertices as one strip with the state they were drawn under, called automatically when needed

flushTransparentQueue()

Draw the queued transparent draws far to near with the state each was drawn under, called automatically at the end of the transparent stage

isSphereVisible(center, radius) → {boolean}

Is any part of a sphere on screen this frame, the test that skips meshes the camera cannot see

  • While the shadow map is drawing it tests the shadow area instead
Parameters:
NameTypeDescription
centerVector3
radiusnumber
Returns:
Type: 
boolean

pick(from, objectsopt) → {Object|undefined}

Find the nearest object under a screen position or along a ray, for clicking on things

  • Each object is tested as a sphere around its mesh, or around a sprite's size3D, not triangle by triangle
  • engineObjectsRaycast3D is the other half of this, every object along a ray instead of the nearest
Parameters:
NameTypeAttributesDescription
fromVector2 | Ray3D

A screen position like mousePosScreen, or a ray to look along

objectsArray.<EngineObject><optional>

Defaults to every object; only those with a mesh or a sprite count

Returns:
Type: 
Object | undefined

playSound(sound, pos3D, volumeopt, pitchopt, randomnessScaleopt, loopopt) → {SoundInstance|undefined}

Play a sound at a 3D position, quieter with distance from the camera and panned by its side, like Sound.play with a 2D position

Parameters:
NameTypeAttributesDefaultDescription
soundSound
pos3DVector3
volumenumber<optional>
1
pitchnumber<optional>
1
randomnessScalenumber<optional>
1

How much to scale pitch randomness

loopboolean<optional>
false
Returns:
  • undefined when out of range or sound is off
Type: 
SoundInstance | undefined

playSoundLoop(sound, pos3D, volumeopt, pitchopt, randomnessScaleopt) → {SoundInstance|undefined}

Play a sound on a loop at a 3D position, the same as playSound with loop on

  • Its volume and pan are set when it starts, change or stop it through the SoundInstance returned
Parameters:
NameTypeAttributesDefaultDescription
soundSound
pos3DVector3
volumenumber<optional>
1
pitchnumber<optional>
1
randomnessScalenumber<optional>
1

How much to scale pitch randomness

Returns:
  • undefined when out of range or sound is off
Type: 
SoundInstance | undefined

queueTransparent(pos, draw)

Queue a draw for the transparent stage, replayed far to near with the current draw state, or draw it now when sorting is off

Parameters:
NameTypeDescription
posVector3

Where the draw is, for sorting

drawfunction

renderStages(objects, isDefaultopt)

Draw a layer's objects, solid ones first and see through ones after, called automatically

  • The main layer also draws the sky, the render callbacks and the debug shapes
Parameters:
NameTypeAttributesDefaultDescription
objectsArray.<EngineObject3D>
isDefaultboolean<optional>
true

screenToGround(screenPos, groundHeightopt, canvasSizeopt) → {Vector3|undefined}

Where a screen position lands on a flat ground plane, for top down games; use HeightMap.raycast for terrain

Parameters:
NameTypeAttributesDefaultDescription
screenPosVector2

Same space as mousePosScreen

groundHeightnumber<optional>
0

World height of the ground plane

canvasSizeVector2<optional>

Defaults to the main canvas size, as in screenToRay

Returns:
  • undefined when the ray misses the plane
Type: 
Vector3 | undefined

screenToRay(screenPos, canvasSizeopt) → {Ray3D}

Get the world ray under a screen position, for clicking on things in 3D

  • Uses the camera where it is right now, so it is fine to call from gameUpdate
  • It brings the view matrices up to date for that canvas, so worldToScreen stays its exact opposite
Parameters:
NameTypeAttributesDescription
screenPosVector2

Same space as mousePosScreen

canvasSizeVector2<optional>

Defaults to the main canvas size

Returns:
  • Starts at the camera with a unit direction, or on the camera plane when orthographic
Type: 
Ray3D

setFog(fogStart, fogEnd, fogColoropt)

Set where fog starts and ends, and its color

Parameters:
NameTypeAttributesDescription
fogStartnumber

Distance from the camera where fog starts

fogEndnumber

Distance where fog is total, 0 disables fog

fogColorColor<optional>

Leaves the color alone when not passed, setSky sets it to the horizon

setSky(topColoropt, horizonColoropt, bottomColoropt) → {Mesh}

Build a sky dome, set it as the sky and set the fog color to the horizon color

Parameters:
NameTypeAttributesDescription
topColorColor<optional>

Straight up

horizonColorColor<optional>

Level with the camera

bottomColorColor<optional>

Straight down, defaults to the horizon color

Returns:
  • The dome, also in render3D.sky
Type: 
Mesh

updateMatrices(aspectopt)

Rebuild the view and projection matrices from the camera, called automatically each frame

Parameters:
NameTypeAttributesDescription
aspectnumber<optional>

Width over height, defaults to the main canvas

updateShadowMatrix()

Rebuild the light's view projection around the shadow center, called automatically each frame shadows are on

worldToClip(pos) → {Vector3|undefined}

Where a world point lands on screen as -1 to 1 across and up, with z as depth

  • Uses this frame's camera, call updateMatrices first if the camera just moved
Parameters:
NameTypeDescription
posVector3
Returns:
  • undefined when behind the camera or closer than the near plane
Type: 
Vector3 | undefined

worldToScreen(pos, canvasSizeopt) → {Vector2|undefined}

Project a world point to screen space pixels, same space as mousePosScreen

  • The opposite of screenToRay, and it takes the same canvas so the pair agree
Parameters:
NameTypeAttributesDescription
posVector3
canvasSizeVector2<optional>

Defaults to the main canvas size, as in screenToRay; the projection is whatever updateMatrices last built, which screenToRay does for its canvas

Returns:
  • undefined when behind the camera or closer than the near plane
Type: 
Vector2 | undefined