OXT Community Stacks

The scripts of Box3D Playground

Version 1.1. These are the scripts exactly as they are in the stack that plays here. Each line has its number, and a link to a line keeps it.

the stack script

Box3D Playground.oxtstack, stack "Box3D Playground", 1322 lines

-- Box3D Playground
--
-- A tour of box3dxt, the xTalk Suite's 3D physics library (Box3D), which
-- comes with OXT-Beyond as org.openxtalk.library.boxthreed. Four scenes
-- show what it does: every kind of shape, the joints, sensors and contact
-- events, and a terrain. The library also draws the world: each frame
-- b3RenderWorld makes a picture and this stack sets it as the imageData of
-- one image. Where render3dxt (org.openxtalk.library.renderthreed) is there
-- too, the Textured look draws the same world with it instead, with
-- textures, smooth shading, two lights and fog. Click a thing in the
-- picture to kick it (a ray from the camera through the pixel finds it);
-- drag the picture to look around.
--
-- Everything is in this one script. The controls are made by pgBuildUI the
-- first time the stack opens. Licence: GPL-3.0-only.

constant kW = 640
constant kH = 400
constant kLeft = 20
constant kTop = 56
constant kLooks = "Solid,Wire,Outline,Textured"

local sWorld, sScene, sMode, sPaused, sLoop, sLast
local sYaw, sPitch, sDist, sTx, sTy, sTz, sSpin
local sDownAt, sDownYaw, sDownPitch, sDragged
local sFrames, sFpsAt, sFps, sDrawMs
local sLoose, sSensor, sInside, sPassed, sHits, sTouches, sSpawnIn
local sRotor, sPiston, sCart, sNote, sOldCompression
local sSteps, sFlash, sGreen, sHover, sPicked
local sLight, sAsleep, sBase
local s3Have, s3Scene, s3Begun, s3Fill, s3Node, s3Mat, s3Body, s3Mesh, s3Tex

-- ---------------------------------------------------------------- opening

on openStack
   -- openStack goes to the card that opens, so the stack it belongs to is
   -- the card's owner: a substack's opening is passed on, ours is not
   if the short name of the owner of the target is not the short name of me then pass openStack
   pgBuildUI
   put the paintCompression into sOldCompression
   -- "rle" makes setting an image's imageData several times quicker
   set the paintCompression to "rle"
   pgScene "shapes"
end openStack

on closeStack
   pgStop
   -- what render3dxt made lives until it is destroyed, beyond this stack
   pg3Release
   if sOldCompression is not empty then set the paintCompression to sOldCompression
   pass closeStack
end closeStack

on pgStop
   if sLoop is not empty then cancel sLoop
   put empty into sLoop
   pg3Free
   if sWorld is not empty then
      try
         b3WorldDestroy sWorld
      end try
   end if
   put empty into sWorld
   put empty into sAsleep
   put empty into sBase
end pgStop

function pgHasLibrary
   -- the pictures came with the library's second ABI: an older one that is
   -- still installed answers here and has no b3RenderWorld
   local tABI
   try
      put b3ABIVersion() into tABI
   catch tError
      return false
   end try
   return tABI is an integer and tABI >= 2
end pgHasLibrary

-- The Textured look needs render3dxt. An engine without it answers the
-- question with an error, which is caught; the answer is kept
function pgHasTextures
   local tABI
   if s3Have is not empty then return s3Have
   put false into s3Have
   try
      put r3ABIVersion() into tABI
      if tABI is an integer and tABI >= 1 then put true into s3Have
   catch tError
      put false into s3Have
   end try
   return s3Have
end pgHasTextures

-- ------------------------------------------------------------ the window

on pgBuildUI
   local tX, tName
   if there is an image "view" of card 1 of me then exit pgBuildUI
   lock screen
   set the defaultStack to the short name of me
   set the width of me to kW + 2 * kLeft
   set the height of me to 618
   set the title of me to "Box3D Playground"
   set the backgroundColor of me to "24,27,32"
   set the resizable of me to false
   pgField "title", kLeft, 12, kW, 34, "Box3D Playground", 20, "240,240,240"
   set the textStyle of field "title" of card 1 of me to "bold"
   -- a thin frame under the picture's edge, and the picture on top of it
   create graphic "frame"
   set the style of graphic "frame" of card 1 of me to "rectangle"
   set the opaque of graphic "frame" of card 1 of me to false
   set the lineSize of graphic "frame" of card 1 of me to 1
   set the foregroundColor of graphic "frame" of card 1 of me to "70,78,92"
   set the rect of graphic "frame" of card 1 of me to kLeft - 1, kTop - 1, kLeft + kW + 1, kTop + kH + 1
   create image "view"
   set the rect of image "view" of card 1 of me to kLeft, kTop, kLeft + kW, kTop + kH
   -- the scenes, then the four looks; under them what to do
   put kLeft into tX
   repeat for each item tName in "Shapes,Joints,Sensors,Terrain"
      pgButton tName, tX, kTop + kH + 10, 80
      add 84 to tX
   end repeat
   add 8 to tX
   repeat for each item tName in kLooks
      pgButton tName, tX, kTop + kH + 10, 70
      add 74 to tX
   end repeat
   set the toolTip of button "Textured" of card 1 of me to "Textures, smooth shading and fog, drawn by render3dxt"
   put kLeft into tX
   repeat for each item tName in "Drop,Boom,Pause,Spin,Reset"
      pgButton tName, tX, kTop + kH + 44, 80
      add 84 to tX
   end repeat
   -- two lines each, wrapped: neither is cut off at the window's edge
   pgField "status", kLeft, kTop + kH + 78, kW, 34, empty, 11, "150,220,160"
   pgField "help", kLeft, kTop + kH + 114, kW, 34, empty, 11, "190,196,206"
   set the dontWrap of field "status" of card 1 of me to false
   set the dontWrap of field "help" of card 1 of me to false
   -- frames a second, in the picture's corner
   pgField "fps", kLeft + kW - 70, kTop + 8, 62, 20, empty, 11, "150,220,160"
   set the opaque of field "fps" of card 1 of me to true
   set the backgroundColor of field "fps" of card 1 of me to "16,18,22"
   set the textAlign of field "fps" of card 1 of me to "center"
   set the blendLevel of field "fps" of card 1 of me to 15
   set the visible of field "fps" of card 1 of me to false
   unlock screen
end pgBuildUI

on pgField pName, pX, pY, pWidth, pHeight, pText, pSize, pColor
   create field pName
   set the rect of field pName of card 1 of me to pX, pY, pX + pWidth, pY + pHeight
   set the opaque of field pName of card 1 of me to false
   set the showBorder of field pName of card 1 of me to false
   set the lockText of field pName of card 1 of me to true
   set the traversalOn of field pName of card 1 of me to false
   set the dontWrap of field pName of card 1 of me to true
   set the textSize of field pName of card 1 of me to pSize
   set the foregroundColor of field pName of card 1 of me to pColor
   put pText into field pName of card 1 of me
end pgField

-- The buttons are drawn by the stack, not by the system, so they look the
-- same under every theme and in the browser: pgPaint gives each its colours
on pgButton pName, pX, pY, pWidth
   create button pName
   set the rect of button pName of card 1 of me to pX, pY, pX + pWidth, pY + 28
   set the style of button pName of card 1 of me to "rectangle"
   set the opaque of button pName of card 1 of me to true
   set the threeD of button pName of card 1 of me to false
   set the showBorder of button pName of card 1 of me to true
   set the borderWidth of button pName of card 1 of me to 1
   set the autoHilite of button pName of card 1 of me to false
   set the showFocusBorder of button pName of card 1 of me to false
   set the textSize of button pName of card 1 of me to 12
   set the traversalOn of button pName of card 1 of me to false
   pgPaint pName, false
end pgButton

-- One button's colours: filled with the accent when what it names is on,
-- lighter under the mouse, and faint when the engine cannot do it
on pgPaint pName, pOn
   local tBack, tText, tEdge
   if pOn is true then
      put "58,124,224" into tBack
      if pName is sHover then put "82,146,242" into tBack
      put "255,255,255" into tText
      put "120,176,255" into tEdge
   else if pOn is "off" then
      put "34,38,45" into tBack
      put "104,110,122" into tText
      put "56,62,74" into tEdge
   else
      put "44,49,58" into tBack
      if pName is sHover then put "66,74,90" into tBack
      put "226,230,238" into tText
      put "74,82,98" into tEdge
   end if
   set the backgroundColor of button pName of card 1 of me to tBack
   set the foregroundColor of button pName of card 1 of me to tText
   set the borderColor of button pName of card 1 of me to tEdge
end pgPaint

on mouseEnter
   if word 1 of the name of the target is not "button" then pass mouseEnter
   put the short name of the target into sHover
   pgMarks
end mouseEnter

on mouseLeave
   if word 1 of the name of the target is not "button" then pass mouseLeave
   put empty into sHover
   pgMarks
end mouseLeave

-- The buttons say what is on: the scene, the look, a pause and the turning
-- camera are filled with the accent colour
on pgMarks
   local tName
   if there is not a button "Pause" of card 1 of me then exit pgMarks
   lock screen
   repeat for each item tName in "Shapes,Joints,Sensors,Terrain"
      pgPaint tName, toLower(tName) is sScene
   end repeat
   repeat for each item tName in kLooks
      pgPaint tName, itemOffset(tName, kLooks) - 1 is sMode
   end repeat
   if not pgHasTextures() then pgPaint "Textured", "off"
   pgPaint "Pause", sPaused is true
   pgPaint "Spin", sSpin is true
   pgPaint "Drop", false
   pgPaint "Boom", false
   pgPaint "Reset", false
   if sPaused is true then
      set the label of button "Pause" of card 1 of me to "Resume"
   else
      set the label of button "Pause" of card 1 of me to "Pause"
   end if
   unlock screen
end pgMarks

on pgSay pText
   if there is a field "status" of card 1 of me then put pText into field "status" of card 1 of me
end pgSay

on pgHelp pText
   put pText into sNote
   if there is a field "help" of card 1 of me then put pText into field "help" of card 1 of me
end pgHelp

-- ------------------------------------------------------------ the scenes

on pgScene pName
   pgStop
   if not pgHasLibrary() then
      pgSay "This stack needs the box3dxt extension (org.openxtalk.library.boxthreed)."
      pgHelp "It comes with OXT-Beyond 0.2.8-dp.2.1 and later, and with the web Stack Player made from it."
      exit pgScene
   end if
   -- each scene opens in the look that suits it until a button has chosen
   -- one: Textured where render3dxt is, otherwise the hills solid and the
   -- rest outlined
   if sPicked is not true and (sMode is empty or pName is not sScene) then
      if pgHasTextures() then
         put 3 into sMode
      else if pName is "terrain" then
         put 0 into sMode
      else
         put 2 into sMode
      end if
   end if
   put pName into sScene
   -- a slowly turning camera, until a button says otherwise
   if sSpin is empty then put true into sSpin
   put empty into sLoose
   put empty into sInside
   put 0 into sSensor
   put 0 into sPassed
   put 0 into sHits
   put 0 into sTouches
   put 0 into sRotor
   put 0 into sPiston
   put empty into sCart
   put 0 into sSpawnIn
   put 0 into sSteps
   put empty into sFlash
   put empty into sGreen
   put false into sPaused
   put 0.6 into sYaw
   put 0.42 into sPitch
   put 16 into sDist
   put 0 into sTx
   put 0.8 into sTy
   put 0 into sTz
   b3ShapeOptionsReset
   put b3WorldCreate(0, -10, 0, 1) into sWorld
   -- a sky that is not the window's colour, so the picture has an edge:
   -- dark above and lighter at the horizon where the library can paint
   -- two colours (its ABI 3), and one colour where it cannot
   try
      b3RenderSetSky 22, 30, 52, 86, 108, 142
   catch tError
      b3RenderSetBackground 40, 54, 80
   end try
   pgLight -0.4, -1, -0.5
   switch pName
      case "shapes"
         pgSceneShapes
         break
      case "joints"
         pgSceneJoints
         break
      case "sensors"
         pgSceneSensors
         break
      case "terrain"
         pgSceneTerrain
         break
   end switch
   if sMode is 3 then
      pg3Build
      -- render3dxt refused to make a scene: the scene's own look instead
      if s3Scene is empty then
         if pName is "terrain" then
            put 0 into sMode
         else
            put 2 into sMode
         end if
      end if
   end if
   put the milliseconds into sLast
   put the milliseconds into sFpsAt
   put 0 into sFrames
   put empty into sFps
   put 0 into sDrawMs
   pgBadge
   pgMarks
   -- the counts of this scene at once, not the last scene's for a second
   pgStatus
   pgTick
end pgScene

-- The light the scene is lit by, the direction it travels: both renderers
-- take it from here
on pgLight pX, pY, pZ
   put pX & comma & pY & comma & pZ into sLight
   b3RenderSetLight pX, pY, pZ
end pgLight

function pgFloor pHalf
   local tBody, tShape
   put b3BodyCreate(sWorld, 0, 0, -0.5, 0) into tBody
   put b3ShapeAddBox(tBody, pHalf, 0.5, pHalf, 0, 0.7, 0.1) into tShape
   b3ShapeSetColor tShape, 96, 104, 116
   return tBody
end pgFloor

-- One loose thing of the kind asked for, at a place. Each kind of shape
-- Box3D has for a moving body: sphere, capsule, box, cylinder, cone, hull.
function pgDropKind pKind, pX, pY, pZ
   local tBody, tShape, tQ
   put b3QuatFromEuler(random(600) / 100, random(600) / 100, random(600) / 100) into tQ
   put b3BodyCreateRotated(sWorld, 2, pX, pY, pZ, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tBody
   -- a little rolling resistance, so that round things come to rest on the
   -- floor instead of rolling off its edge
   b3ShapeOptionsSetRollingResistance 0.08
   switch pKind
      case "sphere"
         put b3ShapeAddSphere(tBody, 0, 0, 0, 0.45, 1, 0.5, 0.35) into tShape
         b3ShapeSetColor tShape, 235, 96, 80
         break
      case "capsule"
         -- along the body's y axis, as render3dxt makes a capsule
         put b3ShapeAddCapsule(tBody, 0, -0.45, 0, 0, 0.45, 0, 0.3, 1, 0.5, 0.2) into tShape
         b3ShapeSetColor tShape, 250, 176, 70
         break
      case "box"
         put b3ShapeAddBox(tBody, 0.45, 0.35, 0.4, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 96, 170, 240
         break
      case "cylinder"
         put b3ShapeAddCylinder(tBody, 0.8, 0.4, 16, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 120, 210, 150
         break
      case "cone"
         put b3ShapeAddCone(tBody, 0.9, 0.5, 0.12, 16, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 190, 130, 240
         break
      case "hull"
         -- an eight-faced gem: the convex hull of six points
         get b3GeometryBegin()
         get b3GeometryAddPoint(0.55, 0, 0)
         get b3GeometryAddPoint(-0.55, 0, 0)
         get b3GeometryAddPoint(0, 0.7, 0)
         get b3GeometryAddPoint(0, -0.7, 0)
         get b3GeometryAddPoint(0, 0, 0.55)
         get b3GeometryAddPoint(0, 0, -0.55)
         put b3ShapeAddHull(tBody, 1, 0.6, 0.1) into tShape
         b3ShapeSetColor tShape, 240, 230, 110
         break
   end switch
   b3ShapeOptionsReset
   if tShape is 0 then
      b3BodyDestroy tBody
      return 0
   end if
   put tBody & comma after sLoose
   pg3Add tBody
   return tBody
end pgDropKind

function pgAnyKind
   return item random(6) of "sphere,capsule,box,cylinder,cone,hull"
end pgAnyKind

on pgSceneShapes
   local tRamp, tShape, tKind, tX
   get pgFloor(9)
   -- a triangle mesh: a ramp of two triangles, named counter-clockwise as
   -- seen from above, the side things land on
   put b3BodyCreate(sWorld, 0, -5, 0, 0) into tRamp
   get b3GeometryBegin()
   get b3GeometryAddPoint(-3, 3, -2.5)
   get b3GeometryAddPoint(3, 0, -2.5)
   get b3GeometryAddPoint(3, 0, 2.5)
   get b3GeometryAddPoint(-3, 3, 2.5)
   get b3GeometryAddTriangle(1, 4, 3)
   get b3GeometryAddTriangle(1, 3, 2)
   put b3ShapeAddMesh(tRamp, 0.4, 0.1) into tShape
   b3ShapeSetColor tShape, 150, 140, 128
   put -6 into tX
   repeat for each item tKind in "sphere,capsule,box,cylinder,cone,hull"
      get pgDropKind(tKind, tX, 5 + random(3), -1 + random(20) / 10)
      add 1.6 to tX
   end repeat
   repeat 6 times
      get pgDropKind(pgAnyKind(), 1 + random(40) / 10, 6 + random(5), -2 + random(40) / 10)
   end repeat
   pgHelp "Every kind of shape, and a mesh ramp. Click a thing to kick it. Drag to look around. Drop adds more; Boom pushes them away."
end pgSceneShapes

on pgSceneJoints
   local tAnchor, tPrev, tLink, tShape, tX, tJoint, tPost, tBase, tA, tB, tWheel, i, tZ, tQ
   get pgFloor(9)
   -- 1. a rope of ball-and-socket (spherical) joints with a heavy ball.
   -- Each link is turned a quarter round z, so that its capsule, made
   -- along the link's own y axis, lies along the rope
   put b3BodyCreate(sWorld, 0, -7, 7, 0) into tAnchor
   put b3ShapeAddBox(tAnchor, 0.2, 0.2, 0.2, 0, 0.6, 0) into tShape
   put tAnchor into tPrev
   put b3QuatFromAxisAngle(0, 0, 1, -pi / 2) into tQ
   put -7 into tX
   repeat with i = 1 to 6
      put b3BodyCreateRotated(sWorld, 2, tX + 0.5, 7, 0, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tLink
      if i < 6 then
         put b3ShapeAddCapsule(tLink, 0, -0.38, 0, 0, 0.38, 0, 0.1, 2, 0.5, 0.1) into tShape
         b3ShapeSetColor tShape, 250, 176, 70
      else
         put b3ShapeAddSphere(tLink, 0, 0, 0, 0.6, 3, 0.5, 0.2) into tShape
         b3ShapeSetColor tShape, 235, 96, 80
      end if
      put b3JointSpherical(sWorld, tPrev, tLink, tX, 7, 0, 1, 0, 0, false) into tJoint
      put tLink into tPrev
      put tLink & comma after sLoose
      add 1 to tX
   end repeat
   -- 2. a windmill on a hinge (revolute) joint, turned by its motor
   put b3BodyCreate(sWorld, 0, 0, 1.5, -1) into tPost
   put b3ShapeAddBox(tPost, 0.2, 1.5, 0.2, 0, 0.6, 0) into tShape
   put b3BodyCreate(sWorld, 2, 0, 3.2, -0.6) into tA
   put b3ShapeAddBox(tA, 2.2, 0.18, 0.1, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 96, 170, 240
   put b3ShapeAddBox(tA, 0.18, 2.2, 0.1, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 96, 170, 240
   put b3JointRevolute(sWorld, tPost, tA, 0, 3.2, -0.6, 0, 0, 1, false) into sRotor
   b3RevoluteSetMaxMotorTorque sRotor, 400
   b3RevoluteSetMotorSpeed sRotor, 1.5
   b3RevoluteEnableMotor sRotor, true
   -- 3. a platform on a slider (prismatic) joint with a spring
   put b3BodyCreate(sWorld, 0, 5, 0.1, 3) into tBase
   put b3ShapeAddBox(tBase, 0.3, 0.1, 0.3, 0, 0.6, 0) into tShape
   put b3BodyCreate(sWorld, 2, 5, 1.6, 3) into tA
   put b3ShapeAddBox(tA, 1.4, 0.15, 1.4, 1, 0.7, 0) into tShape
   b3ShapeSetColor tShape, 120, 210, 150
   put b3JointPrismatic(sWorld, tBase, tA, 5, 1.6, 3, 0, 1, 0, false) into sPiston
   b3PrismaticSetSpringHertz sPiston, 1.5
   b3PrismaticSetSpringDampingRatio sPiston, 0.15
   b3PrismaticEnableSpring sPiston, true
   b3PrismaticSetLimits sPiston, -1.2, 1.5
   b3PrismaticEnableLimit sPiston, true
   get pgDropKind("box", 5, 5, 3)
   -- 4. two balls a fixed distance apart (distance joint)
   put b3BodyCreate(sWorld, 2, -4, 5, 4) into tA
   put b3ShapeAddSphere(tA, 0, 0, 0, 0.4, 1, 0.5, 0.4) into tShape
   b3ShapeSetColor tShape, 190, 130, 240
   put b3BodyCreate(sWorld, 2, -2.4, 5.6, 4) into tB
   put b3ShapeAddSphere(tB, 0, 0, 0, 0.4, 1, 0.5, 0.4) into tShape
   b3ShapeSetColor tShape, 190, 130, 240
   put b3JointDistance(sWorld, tA, tB, -4, 5, 4, -2.4, 5.6, 4, true) into tJoint
   put tA & comma & tB & comma after sLoose
   -- 5. two boxes glued into an L (weld joint)
   put b3BodyCreate(sWorld, 2, -5, 3, -4) into tA
   put b3ShapeAddBox(tA, 0.9, 0.2, 0.3, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 240, 230, 110
   put b3BodyCreate(sWorld, 2, -4.3, 3.8, -4) into tB
   put b3ShapeAddBox(tB, 0.2, 0.6, 0.3, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 240, 230, 110
   put b3JointWeld(sWorld, tA, tB, -4.3, 3.2, -4, false) into tJoint
   put tA & comma & tB & comma after sLoose
   -- 6. a cart on four wheel joints: suspension, and motors that drive it
   put b3BodyCreate(sWorld, 2, -3, 0.9, 6.4) into tA
   put b3ShapeAddBox(tA, 1.1, 0.2, 0.6, 1, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 235, 96, 80
   put tA & comma after sLoose
   repeat for each item tX in "-3.8,-2.2"
      repeat for each item tZ in "5.6,7.2"
         put b3BodyCreate(sWorld, 2, tX, 0.5, tZ) into tWheel
         put b3ShapeAddSphere(tWheel, 0, 0, 0, 0.4, 1, 1.2, 0) into tShape
         b3ShapeSetColor tShape, 60, 60, 66
         put b3JointWheel(sWorld, tA, tWheel, tX, 0.5, tZ, 0, 1, 0, 0, 0, 1, false) into tJoint
         b3WheelSetSuspensionHertz tJoint, 4
         b3WheelSetSuspensionDampingRatio tJoint, 0.7
         b3WheelEnableSuspension tJoint, true
         b3WheelSetMaxSpinTorque tJoint, 12
         b3WheelSetSpinMotorSpeed tJoint, -5
         b3WheelEnableSpinMotor tJoint, true
         put tJoint & comma after sCart
      end repeat
   end repeat
   put 17 into sDist
   put 1.6 into sTy
   put -0.5 into sTx
   pgHelp "Joints: a rope of ball-and-sockets, a motor on a hinge, a sprung slider, a rod, a weld and a cart on wheel joints. Click to kick."
end pgSceneJoints

on pgSceneSensors
   local tBody, tShape, tQ, tGate
   get pgFloor(9)
   -- a chute: a tilted slab with two walls
   put b3QuatFromAxisAngle(0, 0, 1, -0.32) into tQ
   put b3BodyCreateRotated(sWorld, 0, -3, 3, 0, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tBody
   put b3ShapeAddBox(tBody, 5, 0.15, 1.6, 0, 0.2, 0.1) into tShape
   b3ShapeSetColor tShape, 150, 140, 128
   put b3ShapeAddBoxAt(tBody, 5, 0.5, 0.1, 0, 0.5, 1.6, 0, 0, 0, 1, 0, 0.2, 0.1) into tShape
   b3ShapeSetColor tShape, 120, 112, 104
   put b3ShapeAddBoxAt(tBody, 5, 0.5, 0.1, 0, 0.5, -1.6, 0, 0, 0, 1, 0, 0.2, 0.1) into tShape
   b3ShapeSetColor tShape, 120, 112, 104
   -- the sensor: a thin gate across the chute. It collides with nothing
   -- and reports what passes through it.
   put b3BodyCreateRotated(sWorld, 0, -2.4, 3.6, 0, item 1 of tQ, item 2 of tQ, item 3 of tQ, item 4 of tQ) into tGate
   b3ShapeOptionsSetSensor true
   b3ShapeOptionsSetEvents false, false, true
   put b3ShapeAddBox(tGate, 0.04, 0.75, 1.5, 0, 0, 0) into sSensor
   b3ShapeSetColor sSensor, 90, 235, 255
   b3ShapeOptionsReset
   -- a bin at the bottom
   put b3BodyCreate(sWorld, 0, 6, 0, 0) into tBody
   put b3ShapeAddBoxAt(tBody, 0.1, 0.8, 2.2, 2.2, 0.8, 0, 0, 0, 0, 1, 0, 0.5, 0.1) into tShape
   put b3ShapeAddBoxAt(tBody, 2.2, 0.8, 0.1, 0, 0.8, 2.2, 0, 0, 0, 1, 0, 0.5, 0.1) into tShape
   put b3ShapeAddBoxAt(tBody, 2.2, 0.8, 0.1, 0, 0.8, -2.2, 0, 0, 0, 1, 0, 0.5, 0.1) into tShape
   put 0 into sTx
   put 1 into sTy
   put 17 into sDist
   pgHelp "Balls turn green as they pass the bright gate (a sensor) and flash white on a hard hit (a hit event). Click one to kick it."
end pgSceneSensors

-- A ball for the sensor scene: it is noticed by sensors and reports its
-- touches and hard hits
on pgSpawnBall
   local tBody, tShape
   put b3BodyCreate(sWorld, 2, -7.2 + random(10) / 20, 6.6, -0.9 + random(18) / 10) into tBody
   b3ShapeOptionsSetEvents true, true, true
   put b3ShapeAddSphere(tBody, 0, 0, 0, 0.32, 1, 0.3, 0.45) into tShape
   b3ShapeOptionsReset
   b3ShapeSetColor tShape, 250, 176, 70
   put tBody & comma after sLoose
   pg3Add tBody
   -- keep the scene small: the oldest ball goes when there are too many
   if the number of items in sLoose > 36 then
      pgForget item 1 of sLoose
      b3BodyDestroy item 1 of sLoose
      delete item 1 of sLoose
   end if
end pgSpawnBall

on pgSceneTerrain
   local tBody, tShape, tI, tJ, tN, tKind
   -- a height field: rows of heights, here rolling hills with a rim
   put 25 into tN
   -- the field starts at its body and runs along +x and +z, so the body
   -- goes at one corner to put the middle of the hills at the origin
   put b3BodyCreate(sWorld, 0, -9.6, 0, -9.6) into tBody
   get b3GeometryBegin()
   repeat with tJ = 0 to tN - 1
      repeat with tI = 0 to tN - 1
         get b3GeometryAddHeight(pgHill(tI, tJ, tN))
      end repeat
   end repeat
   put b3ShapeAddHeightField(tBody, tN, tN, 0.8, 1, 0.8, 0.6, 0.1) into tShape
   b3ShapeSetColor tShape, 110, 150, 96
   repeat 14 times
      put item random(3) of "sphere,sphere,box" into tKind
      get pgDropKind(tKind, -6 + random(120) / 10, 4 + random(4), -6 + random(120) / 10)
   end repeat
   -- a low light from the side, so the slopes show
   pgLight -0.8, -0.55, -0.3
   put 19 into sDist
   put 0.62 into sPitch
   put 1.2 into sTy
   pgHelp "A height field: 625 heights make the hills. Balls and boxes roll into the valleys and fall asleep (dimmer). Drop adds more."
end pgSceneTerrain

function pgHill pCol, pRow, pCount
   local tEdge
   put min(pCol, pRow, pCount - 1 - pCol, pCount - 1 - pRow) into tEdge
   if tEdge < 2 then return 2.6 - tEdge
   return 1.1 + 0.9 * sin(pCol * 0.55) * cos(pRow * 0.5) + 0.4 * sin((pCol + pRow) * 0.3)
end pgHill

-- -------------------------------------------------------------- the loop

on pgTick
   local tNow, tSteps, tStart
   put empty into sLoop
   if sWorld is empty then exit pgTick
   put the milliseconds into tNow
   -- as many sixtieths of a second as have passed, at most three
   put max(1, min(3, round((tNow - sLast) / 16.667))) into tSteps
   put tNow into sLast
   -- in the Textured look the picture begun last tick was drawn while the
   -- engine waited for this one: it is shown before the world changes
   if s3Begun is true then
      put false into s3Begun
      pgShow r3SceneFrame(s3Scene)
   end if
   if not sPaused then
      repeat tSteps times
         pgStep
      end repeat
   end if
   if sSpin and sDownAt is empty then add 0.0035 * tSteps to sYaw
   -- the numbers once a second, before the next picture is begun: a call
   -- that names a scene waits for a picture being drawn
   add 1 to sFrames
   if tNow - sFpsAt >= 1000 then
      put round(sFrames * 1000 / (tNow - sFpsAt)) into sFps
      pgBadge
      put 0 into sFrames
      put tNow into sFpsAt
      pgStatus
   end if
   put the milliseconds into tStart
   if sMode is 3 and s3Scene is not empty then
      -- the next picture is begun, and drawn by render3dxt's own threads
      pgCamera
      put r3SceneRenderBegin(s3Scene, kW, kH) > 0 into s3Begun
   else
      pgDraw
   end if
   put the milliseconds - tStart into sDrawMs
   send "pgTick" to me in 10 milliseconds
   put the result into sLoop
end pgTick

on pgStep
   local i, tBody, tMoves, tLine
   if sScene is "sensors" then
      subtract 1 from sSpawnIn
      if sSpawnIn <= 0 then
         pgSpawnBall
         put 22 into sSpawnIn
      end if
   end if
   b3WorldStep sWorld, 1 / 60, 4
   add 1 to sSteps
   -- the bodies that moved: in the Textured look their nodes follow them,
   -- and in every look what fell asleep is dimmed until it moves again
   get b3WorldUpdateMoves(sWorld)
   put b3MovesText() into tMoves
   if tMoves is not empty then
      if s3Scene is not empty then get r3SceneApplyMoves(s3Scene, tMoves)
      repeat for each line tLine in tMoves
         if item 9 of tLine is 1 then
            pgSleep item 1 of tLine, true
         else if sAsleep[item 1 of tLine] is true then
            pgSleep item 1 of tLine, false
         end if
      end repeat
   end if
   if sScene is "sensors" then pgEvents
   -- the cart turns back before it reaches the floor's edge: a short first
   -- leg, then to and fro about where it began
   if sCart is not empty and (sSteps + 70) mod 140 is 0 then
      repeat for each item tBody in sCart
         b3WheelSetSpinMotorSpeed tBody, - b3WheelSpinMotorSpeed(tBody)
      end repeat
   end if
   -- what falls off the edge is taken out of the world
   if sLoose is not empty and sSteps mod 30 is 0 then
      repeat with i = the number of items in sLoose down to 1
         put item i of sLoose into tBody
         if b3BodyY(tBody) < -20 then
            pgForget tBody
            b3BodyDestroy tBody
            delete item i of sLoose
         end if
      end repeat
   end if
end pgStep

-- Events are read by asking after each step: nothing calls the script
on pgEvents
   local i, tShape
   b3WorldUpdateSensorEvents sWorld
   repeat with i = 1 to b3SensorBeginCount()
      put b3SensorBeginVisitor(i) into tShape
      pgColor tShape, 110, 230, 120
      put true into sGreen[tShape]
      add 1 to sPassed
   end repeat
   b3WorldUpdateContactEvents sWorld
   add b3ContactBeginCount() to sTouches
   repeat with i = 1 to b3ContactHitCount()
      add 1 to sHits
      if b3ContactHitSpeed(i) > 6 then
         pgFlash b3ContactHitShapeA(i)
         pgFlash b3ContactHitShapeB(i)
      end if
   end repeat
   -- a flash lasts a tenth of a second, then the ball has its colour back
   repeat for each key tShape in sFlash
      subtract 1 from sFlash[tShape]
      if sFlash[tShape] <= 0 then
         delete variable sFlash[tShape]
         if b3ShapeBody(tShape) is 0 then
            delete variable sGreen[tShape]
         else if sGreen[tShape] then
            pgColor tShape, 110, 230, 120
         else
            pgColor tShape, 250, 176, 70
         end if
      end if
   end repeat
end pgEvents

on pgFlash pShape
   if pShape is 0 or pShape is sSensor then exit pgFlash
   if b3BodyType(b3ShapeBody(pShape)) is not 2 then exit pgFlash
   pgColor pShape, 255, 255, 255
   put 6 into sFlash[pShape]
end pgFlash

-- A shape's own colour, as a scene sets it. While its body sleeps the
-- colour is kept and shown dimmed.
on pgColor pShape, pR, pG, pB
   if sAsleep[b3ShapeBody(pShape)] is true then
      put pR & comma & pG & comma & pB into sBase[pShape]
      pgShowColor pShape, pgDim(sBase[pShape])
   else
      pgShowColor pShape, pR & comma & pG & comma & pB
   end if
end pgColor

-- The colour a shape is drawn in, in both renderers
on pgShowColor pShape, pColor
   b3ShapeSetColor pShape, item 1 of pColor, item 2 of pColor, item 3 of pColor
   if s3Mat[pShape] is not empty then r3MaterialSetColor s3Mat[pShape], item 1 of pColor, item 2 of pColor, item 3 of pColor
end pgShowColor

-- Asleep, a body is drawn in its colours dimmed, the way box3dxt's renderer
-- dims a body that has no colour of its own; awake, in its colours again
on pgSleep pBody, pAsleep
   local tShape, tColor
   if pAsleep is (sAsleep[pBody] is true) then exit pgSleep
   if pAsleep then
      put true into sAsleep[pBody]
      repeat for each item tShape in pgShapesOf(pBody)
         put b3ShapeColor(tShape) into tColor
         if tColor is empty then next repeat
         put tColor into sBase[tShape]
         pgShowColor tShape, pgDim(tColor)
      end repeat
   else
      delete variable sAsleep[pBody]
      repeat for each item tShape in pgShapesOf(pBody)
         if sBase[tShape] is empty then next repeat
         pgShowColor tShape, sBase[tShape]
         delete variable sBase[tShape]
      end repeat
   end if
end pgSleep

function pgDim pColor
   return ((item 1 of pColor + 110) div 2 * 3 div 4) & comma & ((item 2 of pColor + 110) div 2 * 3 div 4) \
         & comma & ((item 3 of pColor + 110) div 2 * 3 div 4)
end pgDim

function pgShapesOf pBody
   local tCount, i, tShapes
   put b3BodyListShapes(pBody) into tCount
   repeat with i = 1 to tCount
      put b3ListItem(i) & comma after tShapes
   end repeat
   return tShapes
end pgShapesOf

-- A body is about to be taken out of the world: what drew it goes too
on pgForget pBody
   local tShape
   if sAsleep[pBody] is true then
      repeat for each item tShape in pgShapesOf(pBody)
         delete variable sBase[tShape]
      end repeat
      delete variable sAsleep[pBody]
   end if
   if s3Scene is empty or s3Body[pBody] is empty then exit pgForget
   repeat for each item tShape in s3Body[pBody]
      r3NodeDestroy s3Node[tShape]
      r3MaterialDestroy s3Mat[tShape]
      delete variable s3Node[tShape]
      delete variable s3Mat[tShape]
   end repeat
   delete variable s3Body[pBody]
end pgForget

on pgCamera
   local tEx, tEy, tEz
   put sTx + sDist * cos(sPitch) * sin(sYaw) into tEx
   put sTy + sDist * sin(sPitch) into tEy
   put sTz + sDist * cos(sPitch) * cos(sYaw) into tEz
   b3RenderSetCamera tEx, tEy, tEz, sTx, sTy, sTz, 50
   if s3Scene is empty then exit pgCamera
   r3SceneSetCamera s3Scene, tEx, tEy, tEz, sTx, sTy, sTz, 50
   r3LightSetDirection s3Fill, 0 - cos(sPitch + 0.4) * sin(sYaw + 0.5), 0 - sin(sPitch + 0.4), 0 - cos(sPitch + 0.4) * cos(sYaw + 0.5)
end pgCamera

-- One picture, drawn now
on pgDraw
   pgCamera
   if sMode is 3 and s3Scene is not empty then
      -- a picture still being drawn is taken first; this one replaces it
      if s3Begun is true then get r3SceneFrame(s3Scene)
      put false into s3Begun
      pgShow r3SceneRender(s3Scene, kW, kH)
   else if b3RenderWorld(sWorld, kW, kH, sMode) then
      pgShow b3RenderPixels()
   end if
end pgDraw

on pgShow pPicture
   if pPicture is empty then exit pgShow
   if there is an image "view" of card 1 of me then set the imageData of image "view" of card 1 of me to pPicture
end pgShow

on pgStatus
   local tText, tPicture
   if sWorld is empty then exit pgStatus
   if sMode is 3 and s3Scene is not empty then
      put "a picture" && format("%.1f", item 3 of r3SceneStats(s3Scene)) && "ms, drawn by render3dxt" into tPicture
   else
      put "a picture" && sDrawMs && "ms" into tPicture
   end if
   put b3WorldBodyCount(sWorld) && "bodies," && b3WorldAwakeBodyCount(sWorld) && "awake," && b3WorldJointCount(sWorld) && "joints," \
         && b3WorldContactCount(sWorld) && "contacts. A step of physics takes" && format("%.2f", b3WorldStepMs(sWorld)) && "ms," \
         && tPicture & "." into tText
   if sScene is "sensors" then
      put return & "Through the gate:" && sPassed & ", touches:" && sTouches & ", hard hits:" && sHits after tText
   end if
   if sScene is "joints" and sRotor is not 0 then
      put return & "Windmill angle" && format("%.1f", b3RevoluteAngle(sRotor)) & ", slider at" && format("%.2f", b3PrismaticTranslation(sPiston)) after tText
   end if
   pgSay tText
end pgStatus

on pgBadge
   if there is not a field "fps" of card 1 of me then exit pgBadge
   put sFps && "fps" into field "fps" of card 1 of me
   set the visible of field "fps" of card 1 of me to sFps is not empty
end pgBadge

-- ---------------------------------------------------- the Textured look
--
-- render3dxt draws the same world: one node a shape, tagged with its body,
-- so that one call a step (r3SceneApplyMoves, in pgStep) moves every node
-- whose body moved. A node has a material of its own, so that it can take
-- its shape's colour when that changes. The meshes and textures are made
-- once and kept until the stack closes; a scene and its materials last as
-- long as the scene.

on pg3Build
   local tLight
   pg3Free
   if sWorld is empty or not pgHasTextures() then exit pg3Build
   put r3SceneCreate() into s3Scene
   if s3Scene is 0 then
      put empty into s3Scene
      exit pg3Build
   end if
   put false into s3Begun
   -- the sky's colour at the horizon, and fog of it, so that the far edge
   -- of the floor melts into the sky
   r3SceneSetBackground s3Scene, 86, 108, 142
   r3SceneSetFog s3Scene, 86, 108, 142, 24, 64
   r3SceneSetAmbient s3Scene, 80, 86, 102
   -- the sun from the scene's direction, and a cool light from above and to
   -- the right of the camera, which pgCamera turns with the view: the faces
   -- seen are never only the sun's dark sides, and a face turned straight
   -- at the camera does not mirror the light back at it
   put r3SceneLight(s3Scene, 1) into tLight
   r3LightSetDirection tLight, item 1 of sLight, item 2 of sLight, item 3 of sLight
   r3LightSetColor tLight, 255, 244, 228, 0.9
   put r3LightCreateDirectional(s3Scene, 0, -0.4, -1, 150, 162, 196, 0.4) into s3Fill
   -- smooth edges where the library has threads to draw them with
   if r3ThreadCount() > 1 then r3SceneSetSupersample s3Scene, 2
   pg3AddAll
end pg3Build

-- Every shape in the world: a box round the whole world lists them all
on pg3AddAll
   local tBounds, tCount, i, tShapes, tShape
   put b3WorldBounds(sWorld) into tBounds
   if tBounds is empty then exit pg3AddAll
   put b3OverlapAABB(sWorld, item 1 of tBounds - 1, item 2 of tBounds - 1, item 3 of tBounds - 1, \
         item 4 of tBounds + 1, item 5 of tBounds + 1, item 6 of tBounds + 1) into tCount
   repeat with i = 1 to tCount
      put b3ListItem(i) & comma after tShapes
   end repeat
   repeat for each item tShape in tShapes
      pg3Shape tShape
   end repeat
end pg3AddAll

-- The shapes of a body that has just been made
on pg3Add pBody
   local tShape
   if s3Scene is empty then exit pg3Add
   repeat for each item tShape in pgShapesOf(pBody)
      pg3Shape tShape
   end repeat
end pg3Add

on pg3Shape pShape
   local tBody, tMoving, tPick, tMesh, tColor, tMat, tNode
   if s3Node[pShape] is not empty then exit pg3Shape
   put b3ShapeBody(pShape) into tBody
   if tBody is 0 then exit pg3Shape
   put b3BodyType(tBody) is not 0 into tMoving
   put pg3Mesh(pShape, tMoving) into tPick
   put item 1 of tPick into tMesh
   if tMesh is empty or tMesh is 0 then exit pg3Shape
   -- the colour it is drawn in now, dimmed if its body sleeps
   put b3ShapeColor(pShape) into tColor
   if tColor is empty then
      if tMoving then
         put "200,200,206" into tColor
      else
         put "140,154,140" into tColor
      end if
   end if
   put r3MaterialCreate(item 1 of tColor, item 2 of tColor, item 3 of tColor) into tMat
   pg3Look tMat, item 2 of tPick, b3ShapeIsSensor(pShape)
   put r3NodeCreate(s3Scene, tMesh) into tNode
   r3NodeSetMaterial tNode, tMat
   r3NodeSetTransformText tNode, b3BodyTransform(tBody)
   r3NodeSetTag tNode, tBody
   put tNode into s3Node[pShape]
   put tMat into s3Mat[pShape]
   put pShape & comma after s3Body[tBody]
end pg3Shape

-- The mesh that draws a shape, and its look, made once for each size.
-- Round things and the boxes that move get render3dxt's own smooth meshes,
-- which carry a texture well; the rest is drawn from the triangles Box3D
-- collides with, so that what is drawn is what is simulated.
function pg3Mesh pShape, pMoving
   local tText, tKey, tFlat, tBounds, tType, tX, tY, tZ, tMesh, tLook, tCount
   put b3ShapeTrianglesText(pShape) into tText
   if tText is empty then return empty
   put pMoving & ":" & tText into tKey
   if s3Mesh[tKey] is not empty then return s3Mesh[tKey]
   put r3MeshFromTrianglesText(tText) into tFlat
   if tFlat is 0 then return empty
   put r3MeshBounds(tFlat) into tBounds
   -- half its size each way
   put (item 4 of tBounds - item 1 of tBounds) / 2 into tX
   put (item 5 of tBounds - item 2 of tBounds) / 2 into tY
   put (item 6 of tBounds - item 3 of tBounds) / 2 into tZ
   put b3ShapeType(pShape) into tType
   put the number of lines of tText into tCount
   put 0 into tMesh
   if pMoving and pg3Centred(tBounds) then
      if tType is 5 then
         put r3MeshSphere(tX, 32, 16) into tMesh
         put "ball" into tLook
      else if tType is 0 and abs(tX - tZ) < 0.001 and tY > tX then
         -- standing along y, as the capsules here are made
         put r3MeshCapsule(tX, tY - tX, 32, 8) into tMesh
         put "ball" into tLook
      else if tType is 3 and pg3IsBox(tText, tX, tY, tZ) and max(tX, tY, tZ) <= 2.5 * min(tX, tY, tZ) then
         put r3MeshBox(tX, tY, tZ) into tMesh
         put "crate" into tLook
      else if tType is 3 and abs(tX - tZ) < 0.001 and tCount >= 28 and tCount mod 4 is 0 then
         -- Box3D's cylinder is a hull with sides of a ring of points
         put r3MeshCylinder(tX, tY, 32) into tMesh
         put "ball" into tLook
      end if
   end if
   if tMesh is 0 or tMesh is empty then
      if tType is 2 then
         -- the hills: drawn smooth, from the same triangles
         put pg3Terrain(tText) into tMesh
         put "grass" into tLook
      end if
   end if
   if tMesh is 0 or tMesh is empty then
      put tFlat into tMesh
      if pMoving and tType is 3 and tCount <= 8 then
         -- the eight-faced gem
         put "gem" into tLook
      else if pMoving then
         put "paint" into tLook
      else if tX >= 4 and tZ >= 4 and tY <= 1 then
         put "floor" into tLook
      else
         put "planks" into tLook
      end if
   else
      r3MeshDestroy tFlat
   end if
   put tMesh & comma & tLook into s3Mesh[tKey]
   return s3Mesh[tKey]
end pg3Mesh

function pg3Centred pBounds
   return abs(item 1 of pBounds + item 4 of pBounds) < 0.002 and abs(item 2 of pBounds + item 5 of pBounds) < 0.002 \
         and abs(item 3 of pBounds + item 6 of pBounds) < 0.002
end pg3Centred

-- Twelve triangles whose every corner is a corner of the box round them
function pg3IsBox pText, pX, pY, pZ
   local tLine, i, tHalf
   if the number of lines of pText is not 12 then return false
   put pX & comma & pY & comma & pZ into tHalf
   repeat for each line tLine in pText
      repeat with i = 1 to 9
         if abs(abs(item i of tLine) - item ((i - 1) mod 3 + 1) of tHalf) > 0.001 then return false
      end repeat
   end repeat
   return true
end pg3IsBox

-- The hills' triangles with their corners shared, so that render3dxt
-- lights them smoothly; the grass is laid on from above, once in 2 m
function pg3Terrain pText
   local tMesh, tLine, tKey, tAt, tCorners, i
   put r3MeshCreate() into tMesh
   if tMesh is 0 then return 0
   repeat for each line tLine in pText
      put empty into tCorners
      repeat with i = 0 to 2
         put item (i * 3 + 1) to (i * 3 + 3) of tLine into tKey
         if tAt[tKey] is empty then
            put r3MeshAddVertex(tMesh, item 1 of tKey, item 2 of tKey, item 3 of tKey, 0, 1, 0, \
                  item 1 of tKey / 2, item 3 of tKey / 2) into tAt[tKey]
         end if
         put tAt[tKey] & comma after tCorners
      end repeat
      get r3MeshAddTriangle(tMesh, item 1 of tCorners, item 2 of tCorners, item 3 of tCorners, 1)
   end repeat
   r3MeshComputeNormals tMesh
   return tMesh
end pg3Terrain

on pg3Look pMat, pLook, pSensor
   -- the gate glows: it is drawn at its own colour whatever the light
   if pSensor is true then
      r3MaterialSetUnlit pMat, true
      exit pg3Look
   end if
   switch pLook
      case "ball"
         r3MaterialSetTexture pMat, pg3Texture("ball")
         r3MaterialSetSpecular pMat, 0.35, 24
         break
      case "crate"
         r3MaterialSetTexture pMat, pg3Texture("crate")
         r3MaterialSetSpecular pMat, 0.12, 10
         break
      case "gem"
         r3MaterialSetFlat pMat, true
         r3MaterialSetSpecular pMat, 0.6, 48
         break
      case "paint"
         r3MaterialSetSpecular pMat, 0.3, 18
         break
      case "floor"
      case "planks"
      case "grass"
         r3MaterialSetTexture pMat, pg3Texture(pLook)
         break
   end switch
end pg3Look

-- The textures, made once: two checkerboards, and three painted here a
-- pixel at a time. Each is in greys, and the material's colour tints it.
function pg3Texture pName
   if s3Tex[pName] is not empty then return s3Tex[pName]
   switch pName
      case "ball"
         put r3TextureChecker(64, 4, 255, 255, 255, 168, 168, 168) into s3Tex[pName]
         break
      case "floor"
         put r3TextureChecker(64, 2, 255, 255, 255, 206, 212, 222) into s3Tex[pName]
         break
      default
         put r3TextureFromImageData(pg3Paint(pName), 64, 64) into s3Tex[pName]
   end switch
   return s3Tex[pName]
end pg3Texture

-- 64 by 64 pixels of imageData: a crate (a frame, boards and a brace),
-- planks (boards with grain and joints) or grass (speckles)
function pg3Paint pName
   local tData, tX, tY, tV, tBoard
   repeat with tY = 0 to 63
      repeat with tX = 0 to 63
         switch pName
            case "crate"
               if tX < 6 or tX > 57 or tY < 6 or tY > 57 then
                  put 150 + random(14) into tV
               else if abs(tX - (63 - tY)) < 5 then
                  put 168 + random(14) into tV
               else if (tY - 6) mod 13 is 0 then
                  put 186 into tV
               else
                  put 222 + random(20) into tV
               end if
               break
            case "planks"
               put tY div 16 into tBoard
               if tY mod 16 is 0 or (tX + tBoard * 23) mod 64 is 0 then
                  put 132 into tV
               else
                  put 206 + (tBoard mod 2) * 18 + round(10 * sin(tY * 1.7 + tBoard)) + random(10) into tV
               end if
               break
            default
               put 196 + random(59) into tV
         end switch
         put numToByte(0) & numToByte(tV) & numToByte(tV) & numToByte(tV) after tData
      end repeat
   end repeat
   return tData
end pg3Paint

-- The scene ends: it takes its nodes and lights with it, and its materials
-- go with it
on pg3Free
   local tShape
   if s3Scene is empty then exit pg3Free
   r3SceneDestroy s3Scene
   repeat for each key tShape in s3Mat
      r3MaterialDestroy s3Mat[tShape]
   end repeat
   put empty into s3Scene
   put false into s3Begun
   put 0 into s3Fill
   put empty into s3Node
   put empty into s3Mat
   put empty into s3Body
end pg3Free

-- The stack closes: the meshes and textures go too
on pg3Release
   local tKey
   pg3Free
   repeat for each key tKey in s3Mesh
      r3MeshDestroy item 1 of s3Mesh[tKey]
   end repeat
   repeat for each key tKey in s3Tex
      r3TextureDestroy s3Tex[tKey]
   end repeat
   put empty into s3Mesh
   put empty into s3Tex
end pg3Release

-- ------------------------------------------------------------- the mouse

on mouseUp
   local tName
   put the short name of the target into tName
   if (word 1 of the name of the target is "image" and tName is "view") or tName is "fps" then
      if not sDragged then pgKick the mouseH - kLeft, the mouseV - kTop
      put empty into sDownAt
      exit mouseUp
   end if
   if word 1 of the name of the target is not "button" then pass mouseUp
   switch tName
      case "Shapes"
      case "Joints"
      case "Sensors"
      case "Terrain"
         pgScene toLower(tName)
         break
      case "Solid"
      case "Wire"
      case "Outline"
         put itemOffset(tName, kLooks) - 1 into sMode
         put true into sPicked
         pg3Free
         break
      case "Textured"
         pgTextured
         break
      case "Pause"
         put not sPaused into sPaused
         break
      case "Spin"
         put not sSpin into sSpin
         break
      case "Reset"
         if sScene is not empty then pgScene sScene
         break
      case "Drop"
         pgDropMore
         break
      case "Boom"
         if sWorld is not empty then b3WorldExplode sWorld, sTx, 0.3, sTz, 4, 4, 6
         break
      default
         pass mouseUp
   end switch
   pgMarks
end mouseUp

on pgTextured
   if not pgHasTextures() then
      pgHelp "The Textured look needs the render3dxt extension (org.openxtalk.library.renderthreed), which this engine does not have."
      exit pgTextured
   end if
   put true into sPicked
   if sWorld is empty then exit pgTextured
   if s3Scene is empty then pg3Build
   if s3Scene is empty then
      pgSay "render3dxt could not make a scene:" && r3LastError()
      exit pgTextured
   end if
   put 3 into sMode
end pgTextured

on mouseRelease
   put empty into sDownAt
   pass mouseRelease
end mouseRelease

on mouseDown
   if word 1 of the name of the target is "image" and the short name of the target is "view" then
      put the mouseH & comma & the mouseV into sDownAt
      put sYaw into sDownYaw
      put sPitch into sDownPitch
      put false into sDragged
   else
      pass mouseDown
   end if
end mouseDown

on mouseMove pX, pY
   if sDownAt is empty then pass mouseMove
   if abs(pX - item 1 of sDownAt) + abs(pY - item 2 of sDownAt) > 5 then put true into sDragged
   if sDragged then
      put sDownYaw - (pX - item 1 of sDownAt) * 0.008 into sYaw
      put max(0.08, min(1.45, sDownPitch + (pY - item 2 of sDownAt) * 0.006)) into sPitch
   end if
end mouseMove

-- A click: the ray from the camera through the picture point, cast into
-- the world; what it meets first is pushed along the ray. The renderer that
-- drew the picture says where the ray goes.
on pgKick pX, pY
   local tRay, tBody, tPush, tPoint
   if sWorld is empty then exit pgKick
   if sMode is 3 and s3Scene is not empty then
      put r3SceneRay(s3Scene, kW, kH, pX + 0.5, pY + 0.5) into tRay
   else
      put b3RenderRay(pX + 0.5, pY + 0.5) into tRay
   end if
   if tRay is empty then exit pgKick
   if b3CastRayClosest(sWorld, item 1 of tRay, item 2 of tRay, item 3 of tRay, \
         100 * item 4 of tRay, 100 * item 5 of tRay, 100 * item 6 of tRay) is 0 then exit pgKick
   put b3HitBody(1) into tBody
   if b3BodyType(tBody) is not 2 then exit pgKick
   put 7 * b3BodyMass(tBody) into tPush
   put b3HitPoint(1) into tPoint
   b3BodyApplyImpulse tBody, tPush * item 4 of tRay, tPush * item 5 of tRay + 0.4 * tPush, tPush * item 6 of tRay, \
         item 1 of tPoint, item 2 of tPoint, item 3 of tPoint, true
end pgKick

on pgDropMore
   local tBody
   if sWorld is empty then exit pgDropMore
   switch sScene
      case "sensors"
         repeat 4 times
            pgSpawnBall
         end repeat
         break
      case "joints"
         get pgDropKind(pgAnyKind(), 5 + random(10) / 10 - 0.5, 7, 3)
         get pgDropKind(pgAnyKind(), -1 + random(20) / 10, 8, -0.6)
         break
      case "terrain"
         repeat 5 times
            get pgDropKind(pgAnyKind(), -5 + random(100) / 10, 5 + random(4), -5 + random(100) / 10)
         end repeat
         break
      default
         repeat 4 times
            get pgDropKind(pgAnyKind(), -5 + random(100) / 10, 7 + random(4), -3 + random(60) / 10)
         end repeat
   end switch
end pgDropMore