Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

adapter.gno

package physics

import "gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/penalty/v0"

// ParamsOf converts a game's constants from the realm's integer units (mm,
// mm/s, ms, per-mille, milli-radii) to the engine's. The defaults convert to
// DefaultParams exactly: each division is correctly rounded, so 2424/1000 is
// the same double as the browser's literal 2.424.
func ParamsOf(c penalty.Config) Params {
	return Params{
		GoalHalfWidth: float64(c.GoalWidth) / 2000,
		GoalHeight:    float64(c.GoalHeight) / 1000,
		KeeperScale:   float64(c.KeeperScale) / 1000,
		ReactionMin:   float64(c.ReactionMin) / 1000,
		ReactionMax:   float64(c.ReactionMax) / 1000,
		StarShare:     float64(c.StarShare) / 1000,
		ReadShare:     float64(c.ReadShare) / 1000,
		DiveMin:       float64(c.DiveMin) / 1000,
		DiveMax:       float64(c.DiveMax) / 1000,
		JumpMin:       float64(c.JumpMin) / 1000,
		JumpMax:       float64(c.JumpMax) / 1000,
		BallMinSpeed:  float64(c.BallMinSpeed) / 1000,
		BallMaxSpeed:  float64(c.BallMaxSpeed) / 1000,
		FuzzBase:      float64(c.FuzzBase) / 1000,
		FuzzPower:     float64(c.FuzzPower) / 1000,
		MaxContact:    float64(c.MaxContact) / 1000,
	}
}

// ShotOf converts the taker's ten-input half (integer units plus the mishit
// seed) to the engine's units, as the web game does: each value / 1000.
func ShotOf(s penalty.ShotParams) Shot {
	return Shot{
		AimX:      float64(s.AimX) / 1000,
		AimY:      float64(s.AimY) / 1000,
		ContactX:  float64(s.ContactX) / 1000,
		ContactY:  float64(s.ContactY) / 1000,
		Power:     float64(s.Power) / 1000,
		Mishit:    s.Mishit,
		HasMishit: true,
	}
}

// SimulateShot is the realm's outcome function on this engine: the taker's
// six inputs and the keeper's four, under a game's constants.
func SimulateShot(shot penalty.ShotParams, plan penalty.KeeperPlan, cfg penalty.Config) penalty.Result {
	prm := ParamsOf(cfg)
	pl := DecodePlan([4]uint16{plan.Direction, plan.Speed, plan.Jump, plan.Reaction}, prm)
	r := Simulate(ShotOf(shot), pl, prm, Options{})
	return ResultOf(r, pl)
}

// ResultOf summarises a decided kick in the realm's integer units.
func ResultOf(r Result, pl Plan) penalty.Result {
	out := penalty.Result{
		BallSpeed: int64(jsRound(r.Launch.Speed * 1000)),
		MishitX:   int64(jsRound(r.Launch.FuzzX * 1000)),
		MishitY:   int64(jsRound(r.Launch.FuzzY * 1000)),
	}
	switch r.Outcome {
	case Goal:
		out.Outcome = penalty.OutcomeGoal
	case Save:
		out.Outcome = penalty.OutcomeSave
	case Miss:
		out.Outcome = penalty.OutcomeMiss
	case Post:
		out.Outcome = penalty.OutcomePost
	}
	switch pl.Mode {
	case ModeStar:
		out.Keeper = penalty.ModeStar
	case ModeRead:
		out.Keeper = penalty.ModeRead
	default:
		out.Keeper = penalty.ModeDive
	}
	// Where the ball reached the goal line, or failing that where it was
	// when the kick was decided (kept out before the line).
	if r.LineCross {
		out.X = int64(jsRound(r.LineX * 1000))
		out.Y = int64(jsRound(r.LineY * 1000))
		out.ArrivalMS = int64(jsRound(r.LineT * 1000))
	} else {
		out.X = int64(jsRound(r.EndX * 1000))
		out.Y = int64(jsRound(r.EndY * 1000))
		out.ArrivalMS = int64(jsRound(r.DecidedAt * 1000))
	}
	return out
}

engine.gno

// Package physics is the Spot Kick penalty engine: a port of the browser
// game's gno-shots/src/physics.js that produces bit-identical results.
//
// The JavaScript engine uses only + - * /, square roots, comparisons and
// 32-bit integer mixing inside its simulation, all of which IEEE-754 rounds
// exactly; gno does float64 arithmetic in software with the same rounding,
// and its math.Sqrt is correctly rounded. So the same inputs give the same
// bits here as in any browser, provided every operation happens in the same
// order. That is the rule this file follows, line by line:
//
//   - every float constant is a variable, never a Go constant: constant
//     expressions are folded at arbitrary precision, JavaScript rounds after
//     each operation;
//   - expressions keep the JavaScript order and grouping;
//   - JavaScript's Math.min, Math.max and Math.round are reproduced exactly
//     (jsMin, jsMax, jsRound), down to the sign of zero.
//
// Unlike the browser, which keeps simulating for the replay, Simulate stops
// as soon as the kick is decided; nothing after that can change the verdict.
package physics

import "math"

// ---------------------------------------------------------------- constants

var (
	negInf  = math.Inf(-1)
	negZero = math.Copysign(0, -1)

	simDT   = 0.001
	simMaxT = 2.5
	simG    = 9.81

	ballR         = 0.11
	ballM         = 0.43
	ballEGround   = 0.55
	ballGroundKep = 0.85
	ballMinBounce = 1.0
	ballRollDecel = 1.2
	ballSpinDecay = 0.05
	ballI         float64

	airRho  = 1.2
	airCD   = 0.25
	airCL   = 1.0
	area    float64
	dragK   float64
	magnusK float64

	goalZ       = -11.0
	postR       = 0.06
	goalDepth   = 2.0
	ePost       = 0.7
	netKs       = 2500.0
	netCs       = 40.0
	netRecoil   = 0.1
	netFriction = 3.0
	boardsZ     = -16.0
	boardsH     = 1.0
	boardsHW    = 30.0
	netBackZ    float64

	kickNormalMix = 0.18
	kickSideSpin  = 0.6
	kickBackSpin  = 0.25
	kickMaxSpin   = 110.0
	kickMaxStrike = 0.8
	kickAimX      = 6.0
	kickAimY      = 4.0

	kLineOffset    = 0.25
	kHipFactor     = 0.93
	kPushTime      = 0.12
	kLeanRate      = 8.0
	kArmRate       = 10.0
	kLeanBias      = -0.3
	kLeanMin       = 0.15
	kSlideDecel    = 8.0
	kStarSpeed     = 1.2
	kEGlove        = 0.25
	kEBody         = 0.45
	kFriction      = 0.3
	kShoulderX     = 0.24
	kShoulderY     = 0.5
	kArmLen        = 0.62
	kGloveReach    = 0.73
	kGloveR        = 0.125
	kReachPivot    = 1.8
	kReachSpan     = 2.6
	kPerceive      = 0.16
	kArmTrackRate  = 12.0
	kReadEvery     = 20
	kReadBase      = 0.16
	kReadReach     = 0.75
	kReadHeightGn  = 2.2
	kReadShuffleT  = 0.45
	kMisreadX      = [2]float64{0.05, 1.2}
	kMisreadY      = [2]float64{0.04, 0.5}
	kMisreadT      = [2]float64{0.18, 0.28}
	kMisjudgeVX    = [2]float64{0.12, 0.6}
	kMisjudgeJump  = [2]float64{0.12, 0.6}
	kPlantExtra    = 0.08
	kPlantStretch  = 1.15
	kRecoverDelay  = 0.08
	kHoldDownT     = 0.3
	kRecoverLeanRt = 9.0
	kRecoverSpeed  = 2.6
	kRecoverAccel  = 9.0
	kRediveWindow  = 0.38
	kRediveMinDX   = 0.45
	kMaxCommits    = 2
	kCatchMin      = 9.0
	kCatchMax      = 25.0
	kHandsGap      = 0.14
	kHandsSpan     = 0.32
	kBodyNear      = 0.25
	kBodyFar       = 0.8
	kHandsWeight   = 0.65
	kHoldPull      = 25.0
	kTouchGap      = 0.08
	kMarginGlove   = 0.03
	kMarginArm     = 0.02
	kMarginTorso   = 0.02
	kMarginLeg     = 0.02
	kMarginHead    = 0.01
	kReactSpeed    = 12.0
	kReactReach    = 0.12
	kGatherSpeed   = 7.5
	kOneHandMax    = 13.0
	kLowDropSpeed  = 1.8
	kGiveHands     = 36.0
	kGiveGlove     = 31.0
	kGiveArm       = 14.0
	kGiveTorso     = 30.0
	kGiveHead      = 30.0
	kGiveLeg       = 32.0
	kGiveLegInAir  = 26.0
	kReflexBody    = 0.25
	kFingertipGive = 0.75
	kParryControl  = 16.0
	kParryOut      = 3.0
	kParryWide     = 2.0
	kHandLateMax   = 0.07
	kHandLateRate  = 0.25
	kPounceSpeed   = 3.0
	kPounceReach   = 1.8
	kPounceHeight  = 2.2
	kPounceDelay   = 0.2
	kPounceNear    = 0.9
	kPounceMove    = 3.0

	planForwardMax  = 22.0
	planCentreShare = 0.06
	planStarMaxSpd  = 1.15

	halfPi = 1.5707963267948966
	pi     = 3.141592653589793
	twoPi  = 6.283185307179586
	sqrt2  = 1.4142135623730951

	armsReady, armsStar, armsHold armPair
	zeroVec                       vec
	upVec                         vec
)

func init() {
	two, three := 2.0, 3.0
	ballI = (two / three) * ballM * ballR * ballR
	area = pi * ballR * ballR
	dragK = (0.5 * airRho * airCD * area) / ballM
	magnusK = (0.5 * airRho * airCL * area * ballR) / ballM
	netBackZ = goalZ - goalDepth
	upVec = vec{0, 1, 0}
	armsReady = armPair{norm(vec{-0.55, -0.45, 0.7}), norm(vec{0.55, -0.45, 0.7})}
	armsStar = armPair{norm(vec{-0.9, 0.6, 0.15}), norm(vec{0.9, 0.6, 0.15})}
	armsHold = armPair{norm(vec{0.18, 0.12, 0.95}), norm(vec{-0.18, 0.12, 0.95})}
}

// Params are the constants a game may change (penalty.Config, in SI units).
// DefaultParams are the browser engine's.
type Params struct {
	GoalHalfWidth float64 // m
	GoalHeight    float64 // m
	KeeperScale   float64
	ReactionMin   float64 // s
	ReactionMax   float64
	StarShare     float64 // of the speed range
	ReadShare     float64
	DiveMin       float64 // m/s
	DiveMax       float64
	JumpMin       float64 // m/s
	JumpMax       float64
	BallMinSpeed  float64 // m/s
	BallMaxSpeed  float64
	FuzzBase      float64 // ball radii
	FuzzPower     float64
	MaxContact    float64 // ball radii
}

// DefaultParams returns the constants of the browser engine.
func DefaultParams() Params {
	return Params{
		GoalHalfWidth: 3.2775, GoalHeight: 2.424, KeeperScale: 1.176,
		ReactionMin: 0.02, ReactionMax: 0.12, StarShare: 0.06, ReadShare: 0.24,
		DiveMin: 2.6, DiveMax: 5.2, JumpMin: -1.4, JumpMax: 4.0,
		BallMinSpeed: 10, BallMaxSpeed: 34, FuzzBase: 0.03, FuzzPower: 0.1, MaxContact: 0.5,
	}
}

// ------------------------------------------------------------- vector maths

type vec struct{ x, y, z float64 }

type armPair struct{ l, r vec }

func add(a, b vec) vec           { return vec{a.x + b.x, a.y + b.y, a.z + b.z} }
func sub(a, b vec) vec           { return vec{a.x - b.x, a.y - b.y, a.z - b.z} }
func scale(a vec, s float64) vec { return vec{a.x * s, a.y * s, a.z * s} }
func dot(a, b vec) float64       { return a.x*b.x + a.y*b.y + a.z*b.z }
func crossVec(a, b vec) vec {
	return vec{a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x}
}
func length(a vec) float64 { return fsqrt(dot(a, a)) }
func norm(a vec) vec {
	l := length(a)
	if l > 0 {
		return scale(a, 1/l)
	}
	return vec{0, 0, 0}
}

func clamp(x, lo, hi float64) float64 {
	if x < lo {
		return lo
	}
	if x > hi {
		return hi
	}
	return x
}

// jsMin and jsMax are Math.min and Math.max for two non-NaN numbers: of two
// zeros, min prefers -0 and max prefers +0.
func jsMin(a, b float64) float64 {
	if a < b {
		return a
	}
	if b < a {
		return b
	}
	if math.Signbit(b) {
		return b
	}
	return a
}

func jsMax(a, b float64) float64 {
	if a > b {
		return a
	}
	if b > a {
		return b
	}
	if !math.Signbit(b) {
		return b
	}
	return a
}

// jsRound is Math.round: the nearest integer, halves rounded up, and -0
// for -0.5 <= x <= -0.
func jsRound(x float64) float64 {
	f := floor(x)
	if x-f >= 0.5 {
		f++
	}
	if f == 0 {
		if x < 0 {
			return negZero
		}
		if math.Float64bits(x)>>63 != 0 {
			return negZero
		}
	}
	return f
}

// floor is math.Floor (gno's is interpreted and dear): below 2^52 in
// magnitude by truncation, keeping -0; beyond that, and for infinities and
// NaN, x itself.
func floor(x float64) float64 {
	if x < 4503599627370496 {
		if x > -4503599627370496 {
			f := float64(int64(x))
			if f > x {
				return f - 1
			}
			if f == 0 {
				return x * 0
			}
			return f
		}
	}
	return x
}

// detSin is the JavaScript engine's sine: range reduction and a Taylor series.
func detSin(x float64) float64 {
	x -= twoPi * jsRound(x/twoPi)
	if x > halfPi {
		x = pi - x
	} else if x < -halfPi {
		x = -pi - x
	}
	x2 := x * x
	term := x
	sum := x
	for n := 1; n <= 9; n++ {
		term *= -x2 / (float64(2*n) * float64(2*n+1))
		sum += term
	}
	return sum
}

func detCos(x float64) float64 { return detSin(x + halfPi) }

// ------------------------------------------------------------ seeded random

type mulberry struct{ a uint32 }

func (m *mulberry) next() float64 {
	m.a += 0x6d2b79f5
	t := m.a
	t = (t ^ (t >> 15)) * (t | 1)
	t ^= t + (t^(t>>7))*(t|61)
	return float64(t^(t>>14)) / 4294967296
}

func fnvBytes(h uint32, b []byte) uint32 {
	for _, c := range b {
		h ^= uint32(c)
		h *= 0x01000193
	}
	return h
}

func u16(b []byte, i int) uint16 { return uint16(b[i])<<8 | uint16(b[i+1]) }

// ------------------------------------------------------------------- plans

// Plan modes.
const (
	ModeStar = 1
	ModeRead = 2
	ModeDive = 3
)

// Plan is a keeper plan decoded from its four uint16.
type Plan struct {
	Raw       [4]uint16
	Mode      int
	Direction float64 // degrees: 0 = along the line to the taker's right, 180 = left
	Speed     float64 // m/s
	Jump      float64 // m/s
	Reaction  float64 // s
}

// DecodePlan maps four uint16 onto a plan exactly as the browser does.
func DecodePlan(raw [4]uint16, p Params) Plan {
	d := float64(raw[0]) / 65535
	sp := float64(raw[1]) / 65535
	j := float64(raw[2]) / 65535
	r := float64(raw[3]) / 65535
	pl := Plan{Raw: raw}
	switch {
	case sp < p.StarShare:
		pl.Mode = ModeStar
	case sp < p.StarShare+p.ReadShare:
		pl.Mode = ModeRead
	default:
		pl.Mode = ModeDive
	}
	pl.Direction = planDirection(d)
	pl.Speed = planSpeed(sp, p)
	pl.Jump = lin(j, p.JumpMin, p.JumpMax)
	pl.Reaction = lin(r, p.ReactionMin, p.ReactionMax)
	return pl
}

func lin(vv, lo, hi float64) float64 { return lo + (hi-lo)*vv }

func planDirection(vv float64) float64 {
	s := 2*vv - 1
	c := planCentreShare
	F := planForwardMax
	if s <= -c {
		return (F * (1 + s)) / (1 - c)
	}
	if s >= c {
		return 180 - (F*(1-s))/(1-c)
	}
	return 90 + ((90-F)*s)/c
}

func planSpeed(vv float64, p Params) float64 {
	k := p.StarShare
	r := k + p.ReadShare
	if vv < k {
		return (planStarMaxSpd * vv) / k
	}
	if vv < r {
		return 0
	}
	return lin((vv-r)/(1-r), p.DiveMin, p.DiveMax)
}

func (pl *Plan) commitTime() float64 {
	if pl.Mode == ModeRead {
		return kReadBase + pl.Reaction
	}
	return pl.Reaction
}

func launchVelocity(pl *Plan) vec {
	a := pl.Direction * (pi / 180)
	return vec{pl.Speed * detCos(a), pl.Jump, pl.Speed * detSin(a)}
}

gnomod.toml

module = "gno.land/p/g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm/penalty/physics/v0"
gno = "0.9"

[addpkg]
  creator = "g1lnkytfqcjwllws63gvf0mv9yt04aswy4y9amhm"
  height = 163388
  max_deposit = "100000000ugnot"

keeper.gno

package physics

// Keeper phases.
const (
	phaseReady = iota
	phasePush
	phaseAir
	phaseGround
	phaseRecover
)

// Body parts, in the order the browser builds them. Both torso capsules are
// one part ("body"), as in the browser, where parts are keyed by name.
const (
	partLeftLeg = iota
	partBody
	partLeftArm
	partLeftGlove
	partRightLeg
	partRightArm
	partRightGlove
	partHead
	nParts
)

// PartNames are the browser's names for the parts.
var PartNames = [nParts]string{"left leg", "body", "left arm", "left glove", "right leg", "right arm", "right glove", "head"}

const (
	kindLeg = iota
	kindTorso
	kindArm
	kindGlove
	kindHead
)

const nCaps = 9

type capsule struct {
	a, b vec
	r    float64
	hit  float64
	kind int
	part int
}

type caps [nCaps]capsule

type plant struct {
	on      bool
	side    float64
	x, y, z float64
}

type lean2 struct{ s, c float64 }

// Commit is one move the keeper made: when, how fast sideways, how high.
type Commit struct {
	Step int
	T0   float64
	VX   float64
	Jump float64
	Star bool
	Read bool
}

type misread struct {
	on             bool
	x, y, vx, jump float64
}

type keeper struct {
	mis        misread
	phase      int
	pushT      float64
	groundT    float64
	pos, vel   vec
	lean       lean2
	arms       armPair
	launchVel  vec
	leanTarget lean2
	armsTarget armPair
	plant      plant
	plantUntil float64
	commits    []Commit
	holding    bool
	read       pred    // its latest read of where the ball will cross
	nextRead   int     // the step of its next read
	seen       ball    // the ball at a read not worked out yet (see keeperStep)
	seenZ      float64 // and the keeper's z, and the time, at that read
	seenT      float64
	pending    bool
	clr        float64
	clrS, clrC float64 // the lean clr was computed for
	clrOK      bool
}

type pred struct {
	ok   bool
	x, y float64
	tau  float64
}

func (e *engine) keeperInit(m misread) keeper {
	return keeper{
		mis:        m,
		phase:      phaseReady,
		pos:        vec{0, e.standHipY, goalZ + kLineOffset},
		lean:       lean2{0, 1},
		arms:       armsReady,
		leanTarget: lean2{0, 1},
		armsTarget: armsReady,
		nextRead:   1,
	}
}

func margin(kind int) float64 {
	switch kind {
	case kindGlove:
		return kMarginGlove
	case kindArm:
		return kMarginArm
	case kindTorso:
		return kMarginTorso
	case kindLeg:
		return kMarginLeg
	}
	return kMarginHead
}

// Fixed offsets of the body points, already scaled: what the browser's w()
// computes as x *= S, y *= S for each constant point, per side.
type sideK struct {
	side                        float64
	sx                          float64 // shoulder x, unscaled
	legX, legY, footX, footY    float64
	torX, torAY, torBY          float64
	armAX, armAY                float64
	legR, torR, armR, gloveR    float64
	legH, torH, armH, gloveH    float64
	legPart, armPart, glovePart int
}

func (e *engine) initBody() {
	S := e.scale
	zero := 0.0
	for i, side := range [2]float64{-1, 1} {
		k := sideK{side: side, sx: kShoulderX * side}
		k.legX, k.legY = 0.11*side*S, zero*S
		k.footX, k.footY = 0.15*side*S, -0.85*S
		k.torX, k.torAY, k.torBY = 0.09*side*S, 0.05*S, 0.46*S
		k.armAX, k.armAY = k.sx*S, kShoulderY*S
		k.legR, k.torR, k.armR, k.gloveR = 0.08*S, 0.14*S, 0.055*S, kGloveR
		k.legH, k.torH, k.armH, k.gloveH = k.legR+kMarginLeg, k.torR+kMarginTorso, k.armR+kMarginArm, k.gloveR+kMarginGlove
		if side < 0 {
			k.legPart, k.armPart, k.glovePart = partLeftLeg, partLeftArm, partLeftGlove
		} else {
			k.legPart, k.armPart, k.glovePart = partRightLeg, partRightArm, partRightGlove
		}
		e.body[i] = k
	}
	e.headX, e.headY = zero*S, 0.72*S
	e.headR = 0.12 * S
	e.headH = e.headR + kMarginHead
	e.zeroZ = zero * S
}

// wpt is the browser's w() for a point already scaled: X = x*S, Y = y*S,
// Z = z*S.
func wpt(pos vec, ln lean2, X, Y, Z float64) vec {
	return vec{pos.x + X*ln.c + Y*ln.s, pos.y - X*ln.s + Y*ln.c, pos.z + Z}
}

// initCaps sets what never changes in the keeper's collision shapes: radii,
// kinds and parts, in the browser's order (left leg, body, left arm, left
// glove, the same on the right, head).
func (e *engine) initCaps(cs *caps) {
	for i := 0; i < 2; i++ {
		k := &e.body[i]
		j := 4 * i
		cs[j] = capsule{r: k.legR, hit: k.legH, kind: kindLeg, part: k.legPart}
		cs[j+1] = capsule{r: k.torR, hit: k.torH, kind: kindTorso, part: partBody}
		cs[j+2] = capsule{r: k.armR, hit: k.armH, kind: kindArm, part: k.armPart}
		cs[j+3] = capsule{r: k.gloveR, hit: k.gloveH, kind: kindGlove, part: k.glovePart}
	}
	cs[8] = capsule{r: e.headR, hit: e.headH, kind: kindHead, part: partHead}
}

// capsulesInto sets the end points of the shapes in cs (see initCaps) for a
// pose: the browser's keeperCapsules, each point wpt written out.
func (e *engine) capsulesInto(cs *caps, ps *pose) {
	S := e.scale
	px, py, pz := ps.pos.x, ps.pos.y, ps.pos.z
	s, c := ps.lean.s, ps.lean.c
	z0 := pz + e.zeroZ
	pl := &ps.plant
	for i := 0; i < 2; i++ {
		k := &e.body[i]
		arm := &ps.arms.r
		if k.side < 0 {
			arm = &ps.arms.l
		}
		ax, ay, az := arm.x, arm.y, arm.z
		j := 4 * i
		cp := &cs[j]
		X, Y := k.legX, k.legY
		cp.a = vec{px + X*c + Y*s, py - X*s + Y*c, z0}
		if pl.on && pl.side == k.side {
			cp.b = vec{pl.x, pl.y, pl.z}
		} else {
			X, Y = k.footX, k.footY
			cp.b = vec{px + X*c + Y*s, py - X*s + Y*c, z0}
		}
		cp = &cs[j+1]
		X, Y = k.torX, k.torAY
		cp.a = vec{px + X*c + Y*s, py - X*s + Y*c, z0}
		Y = k.torBY
		cp.b = vec{px + X*c + Y*s, py - X*s + Y*c, z0}
		cp = &cs[j+2]
		X, Y = k.armAX, k.armAY
		cp.a = vec{px + X*c + Y*s, py - X*s + Y*c, z0}
		X, Y = (k.sx+ax*kArmLen)*S, (kShoulderY+ay*kArmLen)*S
		cp.b = vec{px + X*c + Y*s, py - X*s + Y*c, pz + az*kArmLen*S}
		cp = &cs[j+3]
		X, Y = (k.sx+ax*kGloveReach)*S, (kShoulderY+ay*kGloveReach)*S
		g := vec{px + X*c + Y*s, py - X*s + Y*c, pz + az*kGloveReach*S}
		cp.a, cp.b = g, g
	}
	X, Y := e.headX, e.headY
	h := vec{px + X*c + Y*s, py - X*s + Y*c, z0}
	cs[8].a, cs[8].b = h, h
}

func (e *engine) keeperCaps(k *keeper) caps {
	var cs caps
	e.initCaps(&cs)
	ps := poseOf(k)
	e.capsulesInto(&cs, &ps)
	return cs
}

// clearance is keeperClearance: the hip height at which the lowest of the
// legs, torso and head touches the ground (the browser builds every shape at
// the origin; only these heights matter).
func (e *engine) clearance(k *keeper) float64 {
	s, c := k.lean.s, k.lean.c
	// The browser's Math.min over these heights, in its order, signed zeros
	// included: jsMin only when two are equal.
	l := &e.body[0]
	r := &e.body[1]
	m := 0 - l.legX*s + l.legY*c - l.legR
	if v := 0 - l.footX*s + l.footY*c - l.legR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - l.torX*s + l.torAY*c - l.torR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - l.torX*s + l.torBY*c - l.torR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - r.legX*s + r.legY*c - r.legR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - r.footX*s + r.footY*c - r.legR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - r.torX*s + r.torAY*c - r.torR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - r.torX*s + r.torBY*c - r.torR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	if v := 0 - e.headX*s + e.headY*c - e.headR; v < m {
		m = v
	} else if v == m {
		m = jsMin(m, v)
	}
	return -m
}

func (e *engine) armsAboveGround(k *keeper) {
	s, c := k.lean.s, k.lean.c
	sy := e.shY
	reach := e.gloveReachS
	py := k.pos.y
	syc := sy * c
	// Left arm, then right, as the browser's loop over the sides.
	shoulderY := py - e.shXL*s + syc
	minDy := (kGloveR - shoulderY) / reach
	if minDy < 1 {
		arm := &k.arms.l
		if -arm.x*s+arm.y*c < minDy {
			liftArm(arm, minDy, s, c)
		}
	}
	shoulderY = py - e.shXR*s + syc
	minDy = (kGloveR - shoulderY) / reach
	if minDy < 1 {
		arm := &k.arms.r
		if -arm.x*s+arm.y*c < minDy {
			liftArm(arm, minDy, s, c)
		}
	}
}

// liftArm raises an arm (body frame) whose hand would be below the ground
// to world height minDy, keeping its direction across.
func liftArm(arm *vec, minDy, s, c float64) {
	wx := arm.x*c + arm.y*s
	h0 := fsqrt(wx*wx + arm.z*arm.z)
	h := fsqrt(1 - minDy*minDy)
	nx, nz := h, 0.0
	if h0 > 0 {
		nx = (wx * h) / h0
		nz = (arm.z * h) / h0
	}
	*arm = vec{nx*c - minDy*s, nx*s + minDy*c, nz}
}

// pose is what the keeper's shapes are built from.
type pose struct {
	pos   vec
	lean  lean2
	arms  armPair
	plant plant
}

func poseOf(k *keeper) pose { return pose{k.pos, k.lean, k.arms, k.plant} }

// blocks is the keeper's movement at 50 Hz: blocks of keeperBlock steps,
// each one keeper step of that length taken at the block's start, from pose
// A (the block's start) to pose B (its end). A block in which its plan
// commits is a single millisecond instead, so the reaction time keeps 1 ms
// precision. Within a block the shapes the ball meets are interpolated
// between A's and B's, one per millisecond, at the block's constant velocity.
type blocks struct {
	s0, n     int
	ia        int // pose[ia] is pose A (the block's start), pose[1-ia] pose B
	pose      [2]pose
	cbuf      [2]caps // the shapes of each pose
	ok        [2]bool // whether cbuf holds them
	vel       [nCaps][2]vec
	velOK     [nCaps]bool
	box       [nCaps][6]float64 // lo/hi x, y, z of each part's end points over the block
	boxOK     [nCaps]bool
	lastBox   [nCaps][6]float64 // the same for pose B alone (the block's last step)
	lastBoxOK [nCaps]bool
	body      [6]float64 // every part over the block, widened by maxReach
	bodyOK    bool
	cand      [nCaps]bool // parts that can reach a ball within candR of candP this block
	candP     vec
	candOK    bool
}

func blockLen(k *keeper, pl *Plan, step int) int {
	if k.phase != phaseReady {
		return keeperBlock
	}
	if k.holding {
		return keeperBlock
	}
	if pl.commitTime() <= float64(step+keeperBlock-1)*simDT {
		return 1
	}
	return keeperBlock
}

func (e *engine) keeperBlock(k *keeper, pl *Plan, step int, b *ball, kb *blocks) {
	kb.s0 = step
	kb.n = blockLen(k, pl, step)
	kb.ia = 1 - kb.ia // B becomes A, with its shapes
	kb.velOK = [nCaps]bool{}
	kb.boxOK = [nCaps]bool{}
	kb.lastBoxOK = [nCaps]bool{}
	kb.bodyOK = false
	kb.candOK = false
	end := step + kb.n - 1
	e.keeperStep(k, pl, end, float64(end)*simDT, float64(kb.n)*simDT, b)
	kb.pose[1-kb.ia] = poseOf(k)
	kb.ok[1-kb.ia] = false
}

func (e *engine) blockCapsA(kb *blocks) *caps {
	i := kb.ia
	if !kb.ok[i] {
		e.capsulesInto(&kb.cbuf[i], &kb.pose[i])
		kb.ok[i] = true
	}
	return &kb.cbuf[i]
}

func (e *engine) blockCapsB(kb *blocks) *caps {
	i := 1 - kb.ia
	if !kb.ok[i] {
		e.capsulesInto(&kb.cbuf[i], &kb.pose[i])
		kb.ok[i] = true
	}
	return &kb.cbuf[i]
}

// blockCap is shape i num steps into the block (num = n is pose B).
func (e *engine) blockCap(kb *blocks, i, num int) capsule {
	b := e.blockCapsB(kb)[i]
	if num == kb.n {
		return b
	}
	a := &e.blockCapsA(kb)[i]
	f := float64(num) / float64(kb.n)
	b.a = lerpV(a.a, b.a, f)
	b.b = lerpV(a.b, b.b, f)
	return b
}

func (e *engine) blockCaps(kb *blocks, num int) caps {
	if num == kb.n {
		return *e.blockCapsB(kb)
	}
	var cs caps
	for i := range cs {
		cs[i] = e.blockCap(kb, i, num)
	}
	return cs
}

// blockVel is the velocity of shape i's end points during the block.
func (e *engine) blockVel(kb *blocks, i int) (vec, vec) {
	if !kb.velOK[i] {
		a := &e.blockCapsA(kb)[i]
		b := &e.blockCapsB(kb)[i]
		inv := 1 / (float64(kb.n) * simDT)
		kb.vel[i] = [2]vec{scale(sub(b.a, a.a), inv), scale(sub(b.b, a.b), inv)}
		kb.velOK[i] = true
	}
	return kb.vel[i][0], kb.vel[i][1]
}

// blockBox bounds part i over the rest of the block: its end points at the
// block's start and end (every interpolated position lies between them), or
// at the end alone on the block's last step, as the browser's outsideBox4.
func (e *engine) blockBox(kb *blocks, i, num int) *[6]float64 {
	if num == kb.n {
		if !kb.lastBoxOK[i] {
			c := &e.blockCapsB(kb)[i]
			boxInto(&kb.lastBox[i], c, c)
			kb.lastBoxOK[i] = true
		}
		return &kb.lastBox[i]
	}
	if !kb.boxOK[i] {
		boxInto(&kb.box[i], &e.blockCapsA(kb)[i], &e.blockCapsB(kb)[i])
		kb.boxOK[i] = true
	}
	return &kb.box[i]
}

// candSlack is how far the ball may move before the candidate parts are
// worked out again.
var candSlack = 0.1

// blockCands lists the parts whose swept box over the block, widened by the
// most that part can reach (collision radius, slow-ball reaction, late
// hands, the ball, a centimetre), comes within candSlack of the ball: no
// other part can pass the per-part test while the ball stays within
// candSlack of where the list was made, so the list is reused until then.
func (e *engine) blockCands(kb *blocks, p vec) *[nCaps]bool {
	if kb.candOK {
		q := kb.candP
		if p.x-q.x >= candSlack {
		} else if q.x-p.x >= candSlack {
		} else if p.y-q.y >= candSlack {
		} else if q.y-p.y >= candSlack {
		} else if p.z-q.z >= candSlack {
		} else if q.z-p.z >= candSlack {
		} else {
			return &kb.cand
		}
	}
	cb := e.blockCapsB(kb)
	px, py, pz := p.x, p.y, p.z
	for i := 0; i < nCaps; i++ {
		bx := e.blockBox(kb, i, 0) // start and end poses: covers the last step's box too
		c := &cb[i]
		m := ballR + c.hit + kReactReach + 0.01 + candSlack
		if c.kind == kindGlove {
			m += kHandLateMax
		}
		in := false
		if px < bx[0]-m {
		} else if px > bx[1]+m {
		} else if py < bx[2]-m {
		} else if py > bx[3]+m {
		} else if pz < bx[4]-m {
		} else if pz > bx[5]+m {
		} else {
			in = true
		}
		kb.cand[i] = in
	}
	kb.candP = p
	kb.candOK = true
	return &kb.cand
}

// blockBody bounds every part over the block (start and end poses), widened
// by the most any part reaches (e.maxReach).
func (e *engine) blockBody(kb *blocks) *[6]float64 {
	if !kb.bodyOK {
		bx := *e.blockBox(kb, 0, 0)
		for i := 1; i < nCaps; i++ {
			o := e.blockBox(kb, i, 0)
			if o[0] < bx[0] {
				bx[0] = o[0]
			}
			if o[1] > bx[1] {
				bx[1] = o[1]
			}
			if o[2] < bx[2] {
				bx[2] = o[2]
			}
			if o[3] > bx[3] {
				bx[3] = o[3]
			}
			if o[4] < bx[4] {
				bx[4] = o[4]
			}
			if o[5] > bx[5] {
				bx[5] = o[5]
			}
		}
		m := e.maxReach
		kb.body = [6]float64{bx[0] - m, bx[1] + m, bx[2] - m, bx[3] + m, bx[4] - m, bx[5] + m}
		kb.bodyOK = true
	}
	return &kb.body
}

// boxInto sets bx to the box of c0's and c1's end points: per axis the
// least and greatest of the four, found in pairs. (The browser keeps a
// running min and max; the two differ at most in the sign of a zero, which
// no comparison against the box can see.)
func boxInto(bx *[6]float64, c0, c1 *capsule) {
	a, b, c, d := c0.a, c0.b, c1.a, c1.b
	lo, hi := a.x, b.x
	if hi < lo {
		lo, hi = hi, lo
	}
	l2, h2 := c.x, d.x
	if h2 < l2 {
		l2, h2 = h2, l2
	}
	if l2 < lo {
		lo = l2
	}
	if h2 > hi {
		hi = h2
	}
	bx[0], bx[1] = lo, hi
	lo, hi = a.y, b.y
	if hi < lo {
		lo, hi = hi, lo
	}
	l2, h2 = c.y, d.y
	if h2 < l2 {
		l2, h2 = h2, l2
	}
	if l2 < lo {
		lo = l2
	}
	if h2 > hi {
		hi = h2
	}
	bx[2], bx[3] = lo, hi
	lo, hi = a.z, b.z
	if hi < lo {
		lo, hi = hi, lo
	}
	l2, h2 = c.z, d.z
	if h2 < l2 {
		l2, h2 = h2, l2
	}
	if l2 < lo {
		lo = l2
	}
	if h2 > hi {
		hi = h2
	}
	bx[4], bx[5] = lo, hi
}

func lerpV(p, q vec, f float64) vec {
	return vec{p.x + (q.x-p.x)*f, p.y + (q.y-p.y)*f, p.z + (q.z-p.z)*f}
}

// predictCrossing: where the keeper expects the ball to cross z = zk.
// (ballSpeed written out.)
func predictCrossing(b *ball, zk float64) pred {
	ux, uz := b.v.x, b.v.z
	if uz >= -0.5 {
		return pred{}
	}
	dz := zk - b.p.z
	if dz >= 0 {
		return pred{}
	}
	uy := b.v.y
	sh := fsqrt(ux*ux + uz*uz)
	s2 := ux*ux + uy*uy + uz*uz
	sp := b.sp
	if q := sp; !(q > 0) {
		sp = fsqrt(s2)
	} else if d, lim := s2-q*q, 0.01*s2; d > lim {
		sp = fsqrt(s2)
	} else if d < -lim {
		sp = fsqrt(s2)
	} else {
		sp = 0.5 * (q + s2/q)
	}
	dist := (dz / uz) * sh
	grounded := b.grounded
	roll := 0.0
	if grounded {
		roll = ballRollDecel
	}
	decel := dragK*sp*sh + roll
	tau := dist / sh
	if decel > 1e-9 {
		disc := sh*sh - 2*decel*dist
		if disc <= 0 {
			return pred{}
		}
		tau = (sh - fsqrt(disc)) / decel
	}
	y := ballR
	if !grounded {
		if y = b.p.y + uy*tau - 0.5*simG*tau*tau; y < ballR {
			y = ballR
		}
	}
	return pred{ok: true, x: b.p.x + (ux/sh)*dist, y: y, tau: tau}
}

func (e *engine) readLaunch(k *keeper, pr pred) vec {
	S := e.scale
	dx := pr.x - k.pos.x
	sgn := 1.0
	ax := dx
	if dx < 0 {
		sgn = -1
		ax = -dx
	}
	T := jsMax(0.15, pr.tau-kPushTime*0.5)
	need := jsMax(0, ax-kReadReach*S)
	vx := jsMin(e.p.DiveMax, need/T)
	if pr.y < 0.6*S && ax > 0.2 {
		vx = jsMax(vx, kLowDropSpeed)
	}
	jump := clamp((pr.y-0.9*S)*kReadHeightGn, e.p.JumpMin, e.p.JumpMax)
	return vec{sgn * vx, jump, 0.12 * vx}
}

func diveArms(side float64, jump float64, ln lean2) armPair {
	toBody := func(wx, wy float64) vec {
		return norm(vec{wx*ln.c - wy*ln.s, wx*ln.s + wy*ln.c, 0.1})
	}
	reach := (jump - kReachPivot) / kReachSpan
	lead := toBody(side, reach)
	trail := toBody(side, reach+0.45)
	if side > 0 {
		return armPair{trail, lead}
	}
	return armPair{lead, trail}
}

func (e *engine) commitLaunch(k *keeper, step int, t float64, lv vec, read bool) {
	k.phase = phasePush
	k.pushT = 0
	k.groundT = 0
	k.launchVel = lv
	lx := lv.x
	ly := jsMax(kLeanMin, lv.y+kLeanBias)
	l := fsqrt(lx*lx + ly*ly)
	k.leanTarget = lean2{lx / l, ly / l}
	ax := lx
	if lx < 0 {
		ax = -lx
	}
	star := ax < kStarSpeed && lv.y > 0.5
	if star {
		k.armsTarget = armsStar
	} else {
		side := -1.0
		if lx > 0 {
			side = 1
		}
		k.armsTarget = diveArms(side, lv.y, k.leanTarget)
	}
	k.commits = append(k.commits, Commit{Step: int(jsRound(t / simDT)), T0: t, VX: lx, Jump: lv.y, Star: star, Read: read})
	if ax >= kStarSpeed {
		side := 1.0
		bk := &e.body[1]
		if lx > 0 {
			side = -1
			bk = &e.body[0]
		}
		// That side's foot, as the browser takes it from keeperCapsules.
		foot := wpt(k.pos, k.lean, bk.footX, bk.footY, e.zeroZ)
		k.plant = plant{on: true, side: side, x: foot.x, y: foot.y, z: foot.z}
		k.plantUntil = t + kPushTime + kPlantExtra
	}
}

// trackArms steers both hands at the predicted crossing (body frame). The
// arithmetic is the browser's aim() and norm(), written out.
func (e *engine) trackArms(k *keeper, pr pred) {
	s, c := k.lean.s, k.lean.c
	sy := e.shY
	dz, dz2 := e.aimDZ, e.aimDZ2
	px, py := k.pos.x, k.pos.y
	sys, syc := sy*s, sy*c
	// Left hand, then right.
	sx := e.shXL
	wx := pr.x - (px + sx*c + sys)
	wy := pr.y - (py - sx*s + syc)
	var dx, dy, dd float64
	if l := fsqrt(wx*wx + wy*wy + dz2); l > 0 {
		inv := 1 / l
		dx, dy, dd = wx*inv, wy*inv, dz*inv
	}
	k.armsTarget.l = vec{dx*c - dy*s, dx*s + dy*c, dd}
	sx = e.shXR
	wx = pr.x - (px + sx*c + sys)
	wy = pr.y - (py - sx*s + syc)
	dx, dy, dd = 0, 0, 0
	if l := fsqrt(wx*wx + wy*wy + dz2); l > 0 {
		inv := 1 / l
		dx, dy, dd = wx*inv, wy*inv, dz*inv
	}
	k.armsTarget.r = vec{dx*c - dy*s, dx*s + dy*c, dd}
}

func lerpRange(r [2]float64, f float64) float64 { return r[0] + (r[1]-r[0])*f }

func (e *engine) diveEarliness(reaction float64) float64 {
	return clamp((e.p.ReactionMax-reaction)/(e.p.ReactionMax-e.p.ReactionMin), 0, 1)
}

func (e *engine) misjudge(k *keeper, lv vec, reaction float64) vec {
	if !k.mis.on {
		return lv
	}
	f := e.diveEarliness(reaction)
	vx := clamp(lv.x+k.mis.vx*lerpRange(kMisjudgeVX, f), -e.p.DiveMax, e.p.DiveMax)
	jump := clamp(lv.y+k.mis.jump*lerpRange(kMisjudgeJump, f), e.p.JumpMin, e.p.JumpMax)
	return vec{vx, jump, lv.z}
}

// readIdle reports whether nothing in a keeper step at t can act on the
// keeper's read: before kPerceive the hands do not track it, a keeper
// waiting to dive or diving does not use it, and one waiting to read uses it
// only from kReadBase + its reaction.
func readIdle(k *keeper, pl *Plan, t float64) bool {
	if t >= kPerceive {
		return false
	}
	switch k.phase {
	case phaseReady:
		return pl.Mode != ModeRead || t < kReadBase+pl.Reaction
	case phasePush, phaseAir:
		return true
	}
	return false
}

// perceive is the keeper's read of a predicted crossing at t: off by its
// misread, more the earlier it reads.
func (e *engine) perceive(k *keeper, pr pred, t float64) pred {
	if !pr.ok || !k.mis.on {
		return pr
	}
	f := clamp((e.misT1-t)/e.misTd, 0, 1)
	y := pr.y + k.mis.y*(e.misY0+e.misYd*f)
	if y < ballR {
		y = ballR
	}
	return pred{ok: true, x: pr.x + k.mis.x*(e.misX0+e.misXd*f), y: y, tau: pr.tau}
}

func (e *engine) keeperStep(k *keeper, pl *Plan, step int, t, dt float64, b *ball) {
	// It reads the ball every kReadEvery steps and acts on its latest read
	// in between; once it holds the ball it stops reading.
	fresh := false
	if !k.holding && step >= k.nextRead {
		k.nextRead = step + kReadEvery
		fresh = true
		if readIdle(k, pl, t) {
			// Nothing acts on this read before the next one (see readIdle):
			// keep what the keeper saw, worked out only if something does.
			k.seen, k.seenZ, k.seenT, k.pending = *b, k.pos.z, t, true
		} else {
			k.read = e.perceive(k, predictCrossing(b, k.pos.z), t)
			k.pending = false
		}
	}
	var pr pred
	if !k.holding {
		if k.pending && !readIdle(k, pl, t) {
			k.read = e.perceive(k, predictCrossing(&k.seen, k.seenZ), k.seenT)
			k.pending = false
		}
		pr = k.read
	} else {
		k.armsTarget = armsHold
	}

	if k.phase == phaseReady && !k.holding {
		if pl.Mode == ModeRead {
			if t >= kReadBase+pl.Reaction {
				if pr.ok && pr.tau <= kReadShuffleT {
					e.commitLaunch(k, step, t, e.readLaunch(k, pr), true)
				} else {
					k.phase = phaseRecover
				}
			}
		} else if t >= pl.Reaction {
			e.commitLaunch(k, step, t, e.misjudge(k, launchVelocity(pl), pl.Reaction), false)
		}
	}
	if fresh && t >= kPerceive && pr.ok {
		e.trackArms(k, pr)
	}

	leanRate := kLeanRate
	switch k.phase {
	case phasePush:
		k.pushT += dt
		f := jsMin(1, k.pushT/kPushTime)
		lv := k.launchVel
		k.vel = vec{lv.x * f, lv.y*f - simG*k.pushT, lv.z * f}
		if f >= 1 {
			k.phase = phaseAir
		}
	case phaseAir:
		k.vel.y -= simG * dt
	case phaseGround:
		sp := fsqrt(k.vel.x*k.vel.x + k.vel.z*k.vel.z)
		sc := 0.0
		if sp > 0 {
			sc = jsMax(0, sp-kSlideDecel*dt) / sp
		}
		k.vel = vec{k.vel.x * sc, 0, k.vel.z * sc}
		k.groundT += dt
		if k.groundT >= kRecoverDelay && !(pr.ok && pr.tau < kHoldDownT) {
			k.phase = phaseRecover
			k.leanTarget = lean2{0, 1}
		}
	case phaseRecover:
		leanRate = kRecoverLeanRt
		vx := k.vel.x
		vz := 0.0
		if k.lean.c > 0.35 {
			tx := k.pos.x
			if pr.ok {
				tx = clamp(pr.x, -e.p.GoalHalfWidth, e.p.GoalHalfWidth)
			}
			top := kRecoverSpeed * k.lean.c
			want := clamp((tx-k.pos.x)*5, -top, top)
			vx += clamp(want-vx, -kRecoverAccel*dt, kRecoverAccel*dt)
			vz = clamp((goalZ+kLineOffset-k.pos.z)*3, -1.5, 1.5)
		} else {
			vx = 0
		}
		k.vel = vec{vx, 0, vz}
		if len(k.commits) < kMaxCommits && k.lean.c > 0.55 && pr.ok && pr.tau < kRediveWindow {
			dx := pr.x - k.pos.x
			if dx > kRediveMinDX || dx < -kRediveMinDX || pr.y < 0.45 || pr.y > 1.9 {
				e.commitLaunch(k, step, t, e.readLaunch(k, pr), true)
			}
		}
	}
	kp, kv := &k.pos, &k.vel
	kp.x += kv.x * dt
	kp.y += kv.y * dt
	kp.z += kv.z * dt
	fl := leanRate * dt
	if fl >= 1 {
		fl = 1 // jsMin(1, fl) for a positive rate
	}
	ln, lt := &k.lean, &k.leanTarget
	ls, lc := ln.s+(lt.s-ln.s)*fl, ln.c+(lt.c-ln.c)*fl
	// nlerp2: three Newton steps towards unit length, as the browser.
	g := 1.5 - 0.5*(ls*ls+lc*lc)
	ls, lc = ls*g, lc*g
	g = 1.5 - 0.5*(ls*ls+lc*lc)
	ls, lc = ls*g, lc*g
	g = 1.5 - 0.5*(ls*ls+lc*lc)
	ln.s, ln.c = ls*g, lc*g
	rate := kArmRate
	if t >= kPerceive {
		rate = kArmTrackRate
	}
	fa := rate * dt
	if fa >= 1 {
		fa = 1
	}
	// blendUnit for each arm, written out. Each arm is replaced whole, not
	// updated field by field: the arms start as copies of armsReady, and a
	// gno struct copy shares its nested structs, so writing a.x in place
	// would write to this package's armsReady (which a realm may not do).
	a, b2 := &k.arms.l, &k.armsTarget.l
	x, y, z := a.x+(b2.x-a.x)*fa, a.y+(b2.y-a.y)*fa, a.z+(b2.z-a.z)*fa
	g = 1.5 - 0.5*(x*x+y*y+z*z)
	x, y, z = x*g, y*g, z*g
	g = 1.5 - 0.5*(x*x+y*y+z*z)
	x, y, z = x*g, y*g, z*g
	g = 1.5 - 0.5*(x*x+y*y+z*z)
	*a = vec{x * g, y * g, z * g}
	a, b2 = &k.arms.r, &k.armsTarget.r
	x, y, z = a.x+(b2.x-a.x)*fa, a.y+(b2.y-a.y)*fa, a.z+(b2.z-a.z)*fa
	g = 1.5 - 0.5*(x*x+y*y+z*z)
	x, y, z = x*g, y*g, z*g
	g = 1.5 - 0.5*(x*x+y*y+z*z)
	x, y, z = x*g, y*g, z*g
	g = 1.5 - 0.5*(x*x+y*y+z*z)
	*a = vec{x * g, y * g, z * g}

	// The clearance depends on the lean alone (cached), and no lean puts it
	// above the keeper's scale: with the hips higher than that it cannot
	// matter.
	grounded := false
	if k.phase == phaseGround {
		grounded = true
	} else if k.phase == phaseRecover {
		grounded = true
	}
	clr := negInf
	if grounded || k.pos.y <= e.scale {
		stale := true
		if !k.clrOK {
		} else if k.clrS != k.lean.s {
		} else if k.clrC != k.lean.c {
		} else {
			stale = false
		}
		if stale {
			k.clr = e.clearance(k)
			k.clrS, k.clrC, k.clrOK = k.lean.s, k.lean.c, true
		}
		clr = k.clr
	}
	if grounded || k.pos.y < clr {
		k.pos = vec{k.pos.x, clr, k.pos.z}
		if k.phase == phaseAir {
			if k.vel.y <= 0 {
				k.phase = phaseGround
				k.groundT = 0
			}
		}
		if grounded {
			k.vel = vec{k.vel.x, 0, k.vel.z}
		} else if k.vel.y < 0 {
			k.vel = vec{k.vel.x, 0, k.vel.z}
		}
	}
	e.armsAboveGround(k)

	if k.plant.on {
		S := e.scale
		hx := k.pos.x + 0.11*k.plant.side*S*k.lean.c
		hy := k.pos.y - 0.11*k.plant.side*S*k.lean.s
		dx := k.plant.x - hx
		dy := k.plant.y - hy
		maxL := 0.85 * S * kPlantStretch
		if t > k.plantUntil || dx*dx+dy*dy > maxL*maxL {
			k.plant = plant{}
		}
	}
}

simulate.gno

package physics

import "math"

// Outcomes.
const (
	Goal = 1
	Save = 2
	Miss = 3
	Post = 4
)

// Woodwork parts.
const (
	LeftPost  = 1
	RightPost = 2
	Crossbar  = 3
)

// Shot is the taker's input in the browser engine's units.
type Shot struct {
	AimX, AimY         float64 // m, point on the goal plane the swing heads for
	ContactX, ContactY float64 // ball radii
	Power              float64 // 0..1
	Mishit             [24]byte
	HasMishit          bool
}

// Launch is the ball as it leaves the boot.
type Launch struct {
	Vel, Spin          [3]float64
	Speed              float64
	FuzzX, FuzzY       float64 // contact error the mishit seed added, ball radii
	ContactX, ContactY float64 // where the boot actually met the ball
}

// Contact is one keeper touch, decided at its first contact.
type Contact struct {
	Step    int
	Part    int // index into PartNames
	Catch   bool
	GaveWay bool
}

// Result is a decided kick.
type Result struct {
	Outcome     int
	DecidedStep int     // the 1 kHz step it was decided in
	DecidedAt   float64 // s after contact
	Launch      Launch
	Touch       int // first part to touch the ball, -1 for none
	TouchStep   int
	Woodwork    int // first frame part it hit, 0 for none
	Caught      bool
	Pounced     bool // decided by the keeper pouncing on a loose ball
	Contacts    []Contact
	Commits     []Commit
	Misread     [4]float64 // the keeper's four normal draws (x, y, vx, jump)
	// Where the ball's centre first reached the goal line (rounded to the
	// millimetre, as the browser reports it), if it did.
	LineCross           bool
	LineT, LineX, LineY float64
	// Where it was when the whole ball was over the whole line, if it was.
	Crossing               bool
	CrossT, CrossX, CrossY float64
	EndX, EndY             float64 // the ball when the kick was decided, m
	Steps                  int
	Trace                  uint32 // see Options.Trace
}

// Options are for tests and analysis.
type Options struct {
	NoKeeper  bool // an empty goal
	NoMisread bool // a keeper that reads perfectly
	// Trace folds the state into Result.Trace every TraceEvery steps and at
	// the deciding step, for comparing with the browser engine bit for bit.
	Trace      bool
	TraceEvery int
}

type ball struct {
	p, v, w  vec
	grounded bool
	inGoal   bool
	held     bool
	sp       float64 // speed at the last drag evaluation (see ballSpeed)
}

// engine holds the constants derived from a game's Params.
type engine struct {
	p         Params
	body      [2]sideK
	headX     float64
	headY     float64
	headR     float64
	headH     float64
	zeroZ     float64
	scale     float64
	maxReach  float64
	standHipY float64
	netSideX  float64
	netRoofY  float64
	frame     [3]capsule

	// Per-game products the keeper's steps use, worked out once with the
	// browser's operations.
	shXL, shXR    float64 // kShoulderX * side * S, left and right
	shY           float64 // kShoulderY * S
	aimDZ, aimDZ2 float64 // 0.25 * S and its square: trackArms' forward offset
	gloveReachS   float64 // kGloveReach * S
	misT1, misTd  float64 // kMisreadT[1] and kMisreadT[1] - kMisreadT[0]
	misX0, misXd  float64 // lerpRange(kMisreadX, f) = misX0 + misXd*f
	misY0, misYd  float64
}

func newEngine(p Params) *engine {
	e := &engine{p: p, scale: p.KeeperScale}
	e.standHipY = kHipFactor * p.KeeperScale
	e.initBody()
	e.netSideX = p.GoalHalfWidth + postR
	e.netRoofY = p.GoalHeight + postR
	S := p.KeeperScale
	e.shXL, e.shXR = kShoulderX*-1.0*S, kShoulderX*1.0*S
	e.shY = kShoulderY * S
	e.aimDZ = 0.25 * S
	e.aimDZ2 = e.aimDZ * e.aimDZ
	e.gloveReachS = kGloveReach * S
	e.misT1, e.misTd = kMisreadT[1], kMisreadT[1]-kMisreadT[0]
	e.misX0, e.misXd = kMisreadX[0], kMisreadX[1]-kMisreadX[0]
	e.misY0, e.misYd = kMisreadY[0], kMisreadY[1]-kMisreadY[0]
	// The most any part reaches, plus the ball and a centimetre: the
	// thickest part's collision radius, slow-ball reaction and late hands.
	e.maxReach = ballR + jsMax(jsMax(0.14*p.KeeperScale+kMarginTorso, 0.08*p.KeeperScale+kMarginLeg),
		jsMax(kGloveR+kMarginGlove, 0.12*p.KeeperScale+kMarginHead)) + kReactReach + kHandLateMax + 0.01
	px := p.GoalHalfWidth + postR
	top := p.GoalHeight + postR
	e.frame = [3]capsule{
		{a: vec{-px, 0, goalZ}, b: vec{-px, top, goalZ}, r: postR, part: LeftPost},
		{a: vec{px, 0, goalZ}, b: vec{px, top, goalZ}, r: postR, part: RightPost},
		{a: vec{-px, top, goalZ}, b: vec{px, top, goalZ}, r: postR, part: Crossbar},
	}
	return e
}

// ---------------------------------------------------------------- the kick

type disc struct{ x, y float64 }

func clampDisc(x, y, max float64) disc {
	r2 := x*x + y*y
	if r2 <= max*max {
		return disc{x, y}
	}
	s := max / fsqrt(r2)
	return disc{x * s, y * s}
}

func mishitNormal(seed *[24]byte, offset int) float64 {
	sum := 0.0
	for i := 0; i < 6; i++ {
		sum += float64(u16(seed[:], offset+2*i)) / 65535
	}
	return (sum - 3) * sqrt2
}

const misreadSalt = 0x6b656570 // "keep"

func keeperMisread(seed *[24]byte) misread {
	m := mulberry{a: fnvBytes(0x811c9dc5^misreadSalt, seed[:])}
	normal := func() float64 {
		sum := 0.0
		for i := 0; i < 6; i++ {
			sum += m.next()
		}
		return (sum - 3) * sqrt2
	}
	x := normal()
	y := normal()
	vx := normal()
	jump := normal()
	return misread{on: true, x: x, y: y, vx: vx, jump: jump}
}

type launch struct {
	pos, vel, spin vec
	speed          float64
	fuzz           disc
	contact        disc
}

func (e *engine) computeLaunch(in *Shot) launch {
	pos := vec{0, ballR, 0}
	target := vec{clamp(in.AimX, -kickAimX, kickAimX), clamp(in.AimY, 0, kickAimY), goalZ}
	f := norm(sub(target, pos))
	right := norm(crossVec(f, upVec))
	up := crossVec(right, f)

	power := clamp(in.Power, 0, 1)
	intended := clampDisc(in.ContactX, in.ContactY, e.p.MaxContact)
	var fuzz disc
	if in.HasMishit {
		sigma := e.p.FuzzBase + e.p.FuzzPower*power
		fuzz.x = mishitNormal(&in.Mishit, 0) * sigma
		fuzz.y = mishitNormal(&in.Mishit, 12) * sigma
	}
	c := clampDisc(intended.x+fuzz.x, intended.y+fuzz.y, kickMaxStrike)
	cx, cy := c.x, c.y
	cz := fsqrt(1 - cx*cx - cy*cy)
	n := add(add(scale(right, cx), scale(up, cy)), scale(f, -cz))

	dir := norm(add(scale(f, 1-kickNormalMix), scale(n, -kickNormalMix)))
	quality := cz
	efficiency := 0.55 + 0.45*quality
	speed := (e.p.BallMinSpeed + (e.p.BallMaxSpeed-e.p.BallMinSpeed)*power) * efficiency
	vel := scale(dir, speed)

	rc := scale(n, ballR)
	dL := scale(crossVec(rc, scale(vel, ballM)), 1/ballI)
	side := dot(dL, up)
	backAxis := sub(dL, scale(up, side))
	spin := add(scale(up, side*kickSideSpin), scale(backAxis, kickBackSpin))
	sm := length(spin)
	if sm > kickMaxSpin {
		spin = scale(spin, kickMaxSpin/sm)
	}
	return launch{pos: pos, vel: vel, spin: spin, speed: speed, fuzz: fuzz, contact: c}
}

// ---------------------------------------------------------------- the ball

func rollingSpin(u vec) vec { return vec{u.z / ballR, 0, -u.x / ballR} }

func (e *engine) netAccel(b *ball) vec {
	p, u := b.p, b.v
	R := ballR
	K := netKs / ballM
	C := netCs / ballM
	ax, ay, az := 0.0, 0.0, 0.0
	touching := false
	panel := func(pen, vn float64) float64 {
		if pen <= 0 {
			return 0
		}
		touching = true
		k := K * netRecoil
		if vn < 0 {
			k = K
		}
		f := k*pen - C*vn
		if f > 0 {
			return f
		}
		return 0
	}
	az += panel(netBackZ-(p.z-R), u.z)
	ay -= panel(p.y+R-e.netRoofY, -u.y)
	sx := 1.0
	if p.x > 0 {
		sx = -1
	}
	ax += sx * panel(math.Abs(p.x)+R-e.netSideX, sx*u.x)
	if touching {
		ax -= netFriction * u.x
		ay -= netFriction * u.y
		az -= netFriction * u.z
	}
	return vec{ax, ay, az}
}

// ballSpeed is the ball's speed for drag: one Newton step from the speed of
// the previous evaluation while the speed has changed by under half a per
// cent, otherwise (the first step, after an impact) a square root.
func ballSpeed(b *ball, u vec) float64 {
	s2 := u.x*u.x + u.y*u.y + u.z*u.z
	s := b.sp
	d := s2 - s*s
	if s > 0 && d <= 0.01*s2 && d >= -0.01*s2 {
		return 0.5 * (s + s2/s)
	}
	return fsqrt(s2)
}

// heunBall is a free-flight step of dt (second-order Runge-Kutta), as the
// browser's: ballSpeed and airAccel written out.
func heunBall(b *ball, dt float64) {
	ux, uy, uz := b.v.x, b.v.y, b.v.z
	wx, wy, wz := b.w.x, b.w.y, b.w.z
	s2 := ux*ux + uy*uy + uz*uz
	sp := b.sp
	if q := sp; !(q > 0) {
		sp = fsqrt(s2)
	} else if d, lim := s2-q*q, 0.01*s2; d > lim {
		sp = fsqrt(s2)
	} else if d < -lim {
		sp = fsqrt(s2)
	} else {
		sp = 0.5 * (q + s2/q)
	}
	nk := -dragK * sp
	a1x := nk*ux + (wy*uz-wz*uy)*magnusK
	a1y := nk*uy - simG + (wz*ux-wx*uz)*magnusK
	a1z := nk*uz + (wx*uy-wy*ux)*magnusK
	vx, vy, vz := ux+a1x*dt, uy+a1y*dt, uz+a1z*dt
	f := 1 - ballSpinDecay*dt
	wx, wy, wz = wx*f, wy*f, wz*f
	s2 = vx*vx + vy*vy + vz*vz
	if q := sp; !(q > 0) {
		sp = fsqrt(s2)
	} else if d, lim := s2-q*q, 0.01*s2; d > lim {
		sp = fsqrt(s2)
	} else if d < -lim {
		sp = fsqrt(s2)
	} else {
		sp = 0.5 * (q + s2/q)
	}
	b.sp = sp
	nk = -dragK * sp
	a2x := nk*vx + (wy*vz-wz*vy)*magnusK
	a2y := nk*vy - simG + (wz*vx-wx*vz)*magnusK
	a2z := nk*vz + (wx*vy-wy*vx)*magnusK
	h := 0.5 * dt
	p := &b.p
	p.x += (ux + vx) * h
	p.y += (uy + vy) * h
	p.z += (uz + vz) * h
	b.v = vec{ux + (a1x+a2x)*h, uy + (a1y+a2y)*h, uz + (a1z+a2z)*h}
	b.w = vec{wx, wy, wz}
}

// integrateBall is the browser's semi-implicit Euler step, written out.
// (x += e rounds exactly as x = x + e, and is cheaper in gno.)
func (e *engine) integrateBall(b *ball, dt float64) {
	v := &b.v
	ux, uy, uz := v.x, v.y, v.z
	s2 := ux*ux + uy*uy + uz*uz
	sp := b.sp
	if q := sp; !(q > 0) {
		sp = fsqrt(s2)
	} else if d, lim := s2-q*q, 0.01*s2; d > lim {
		sp = fsqrt(s2)
	} else if d < -lim {
		sp = fsqrt(s2)
	} else {
		sp = 0.5 * (q + s2/q)
	}
	b.sp = sp
	nk := -dragK * sp
	ax, ay, az := nk*ux, nk*uy-simG, nk*uz
	grounded := b.grounded
	w := &b.w
	if !grounded {
		wx, wy, wz := w.x, w.y, w.z
		ax += (wy*uz - wz*uy) * magnusK
		ay += (wz*ux - wx*uz) * magnusK
		az += (wx*uy - wy*ux) * magnusK
	}
	if b.inGoal {
		n := e.netAccel(b)
		ax, ay, az = ax+n.x, ay+n.y, az+n.z
	}
	if grounded {
		if ay < 0 {
			ay = 0
		}
		if h := fsqrt(ux*ux + uz*uz); h > 0 {
			d := ballRollDecel // jsMin(ballRollDecel, h/dt), both positive
			if q := h / dt; q < d {
				d = q
			}
			ax -= (d * ux) / h
			az -= (d * uz) / h
		}
	}
	vx, vy, vz := ux+ax*dt, uy+ay*dt, uz+az*dt
	v.x, v.y, v.z = vx, vy, vz
	p := &b.p
	p.x += vx * dt
	p.y += vy * dt
	p.z += vz * dt
	if grounded {
		w.x, w.y, w.z = vz/ballR, w.y*(1-2*dt), -vx/ballR
	} else {
		f := 1 - ballSpinDecay*dt
		w.x *= f
		w.y *= f
		w.z *= f
	}
}

func groundContact(b *ball) float64 {
	if b.p.y >= ballR {
		return 0
	}
	b.p = vec{b.p.x, ballR, b.p.z}
	if b.v.y >= 0 {
		return 0
	}
	vy := -b.v.y
	if !b.grounded && vy > ballMinBounce {
		k := ballGroundKep
		b.v = vec{b.v.x * k, vy * ballEGround, b.v.z * k}
		b.w = add(scale(b.w, 0.5), scale(rollingSpin(b.v), 0.5))
		return vy
	}
	b.v = vec{b.v.x, 0, b.v.z}
	b.grounded = true
	return 0
}

type probe struct {
	ok       bool
	relSpeed float64
	dist     float64
}

func probeCapsule(b *ball, a, bb vec, r float64, va, vb vec) probe {
	ab := sub(bb, a)
	abab := dot(ab, ab)
	s := 0.0
	if abab > 0 {
		s = clamp(dot(sub(b.p, a), ab)/abab, 0, 1)
	}
	d := sub(b.p, add(a, scale(ab, s)))
	minD := ballR + r
	d2 := dot(d, d)
	if d2 >= minD*minD {
		return probe{}
	}
	dist := fsqrt(d2)
	n := vec{0, 0, 1}
	if dist > 1e-9 {
		n = scale(d, 1/dist)
	}
	sv := add(va, scale(sub(vb, va), s))
	rel := sub(b.v, sv)
	vn := dot(rel, n)
	if vn >= 0 {
		return probe{}
	}
	return probe{ok: true, relSpeed: length(rel), dist: dist}
}

type hit struct {
	ok          bool
	impactSpeed float64
	gaveWay     bool
}

// collideCapsule resolves the ball against a capsule moving with end
// velocities va, vb (nil in the browser for the goal frame: still). give < 0
// means the part never gives way (Infinity in the browser).
func collideCapsule(b *ball, a, bb vec, r float64, moving bool, va, vb vec, e, mu, spinKeep, give float64) hit {
	ab := sub(bb, a)
	abab := dot(ab, ab)
	s := 0.0
	if abab > 0 {
		s = clamp(dot(sub(b.p, a), ab)/abab, 0, 1)
	}
	q := add(a, scale(ab, s))
	d := sub(b.p, q)
	d2 := dot(d, d)
	minD := ballR + r
	if d2 >= minD*minD {
		return hit{}
	}
	dist := fsqrt(d2)
	n := vec{0, 0, 1}
	if dist > 1e-9 {
		n = scale(d, 1/dist)
	}
	sv := vec{0, 0, 0}
	if moving {
		sv = add(va, scale(sub(vb, va), s))
	}
	rel := sub(b.v, sv)
	vn := dot(rel, n)
	if vn >= 0 {
		b.p = add(q, scale(n, minD))
		return hit{}
	}
	relN := scale(n, vn)
	relT := sub(rel, relN)
	needed := -(1 + e) * vn
	if give >= 0 && needed > give {
		b.v = add(sv, add(scale(relT, 1-mu), scale(n, vn+give)))
		b.w = scale(b.w, spinKeep)
		return hit{ok: true, impactSpeed: -vn, gaveWay: true}
	}
	b.p = add(q, scale(n, minD))
	b.v = add(sv, sub(scale(relT, 1-mu), scale(relN, e)))
	b.w = scale(b.w, spinKeep)
	return hit{ok: true, impactSpeed: -vn}
}

// slowerThan is length(v) < s, taking the root only when it could be true.
func slowerThan(v vec, s float64) bool {
	d := v.x*v.x + v.y*v.y + v.z*v.z
	if d > s*s*1.01 {
		return false
	}
	return fsqrt(d) < s
}

// pounces reports whether the keeper gets to a loose ball before it is
// wholly over the line: slower than kPounceSpeed, within kPounceReach of the
// hips and below kPounceHeight, the keeper not mid-dive, and the ball needing
// longer to cross than the keeper needs to go down on it.
func pounces(k *keeper, b *ball) bool {
	if k.holding || k.phase == phasePush || k.phase == phaseAir || b.p.y > kPounceHeight {
		return false
	}
	dx, dy, dz := b.p.x-k.pos.x, b.p.y-k.pos.y, b.p.z-k.pos.z
	d2 := dx*dx + dy*dy + dz*dz
	if d2 >= kPounceReach*kPounceReach {
		return false
	}
	u := b.v
	if u.x*u.x+u.y*u.y+u.z*u.z >= kPounceSpeed*kPounceSpeed {
		return false
	}
	if u.z >= 0 {
		return true
	}
	// The keeper needs kPounceDelay plus the distance beyond kPounceNear at
	// kPounceMove: compared squared, as the browser does.
	over := goalZ - postR - ballR
	spare := (b.p.z-over)/-u.z - kPounceDelay
	if spare <= 0 {
		return false
	}
	reach := kPounceNear + spare*kPounceMove
	return d2 < reach*reach
}

// ------------------------------------------------------------ catch or parry

func segDist(p, a, b vec) float64 {
	ab := sub(b, a)
	abab := dot(ab, ab)
	s := 0.0
	if abab > 0 {
		s = clamp(dot(sub(p, a), ab)/abab, 0, 1)
	}
	return length(sub(p, add(a, scale(ab, s))))
}

func clamp01(x float64) float64 {
	if x < 0 {
		return 0
	}
	if x > 1 {
		return 1
	}
	return x
}

type decision struct {
	held   bool
	hands  float64
	toBody float64
}

func (e *engine) catchDecision(cs *caps, part *capsule, relSpeed float64, ballP vec) decision {
	S := e.scale
	gl := cs[3].a
	gr := cs[7].a
	mid := scale(add(gl, gr), 0.5)
	hx := ballP.x - mid.x
	hy := ballP.y - mid.y
	hands := 1 - clamp01((fsqrt(hx*hx+hy*hy)-kHandsGap*S)/((kHandsSpan-kHandsGap)*S))
	toBody := math.Inf(1)
	for i := range cs {
		if cs[i].kind == kindTorso {
			toBody = jsMin(toBody, segDist(ballP, cs[i].a, cs[i].b)-cs[i].r)
		}
	}
	body := 1 - clamp01((toBody-kBodyNear*S)/((kBodyFar-kBodyNear)*S))
	quality := kHandsWeight*hands + (1-kHandsWeight)*body
	limit := kCatchMin + (kCatchMax-kCatchMin)*quality
	if part.kind == kindGlove && hands < 0.5 {
		limit = jsMin(limit, kOneHandMax)
	}
	catchable := part.kind == kindGlove || part.kind == kindTorso
	if part.kind == kindLeg || part.kind == kindArm {
		catchable = true
		limit = kGatherSpeed
	} else if catchable && relSpeed <= kGatherSpeed && ballP.y < 0.6 {
		limit = jsMax(limit, kGatherSpeed)
	}
	return decision{held: catchable && relSpeed <= limit, hands: hands, toBody: toBody}
}

func (e *engine) holdPoint(cs *caps) vec {
	gl := cs[3].a
	gr := cs[7].a
	p := add(scale(add(gl, gr), 0.5), vec{0, 0, 0.06 * e.scale})
	return vec{p.x, jsMax(ballR, p.y), p.z}
}

// r3 is the browser's millimetre rounding: Math.round(x * 1000) / 1000.
func r3(x float64) float64 {
	return jsRound(x*1000) / 1000
}

// ---------------------------------------------------------------- simulate

// Work done only near the keeper or the goal frame (the browser engine has
// the same ZONES). A keeper part at full reach can touch the ball only
// within 1.97 m of the hip: the farthest part is a glove, 1.29 x scale from
// it, plus 0.35 m of collision margin, reaction reach and late hand reach,
// plus the ball's radius; the hip used is the keeper block's end pose, at
// most 14 cm from the interpolated one. Contacts are checked from probeZone
// out, posts and bar only within a centimetre of reach (nearFrame). Skipping checks that would find
// nothing leaves every result unchanged.
var (
	probeZone   = 2.2
	keeperBlock = 20 // steps per keeper step: it moves at 50 Hz
	ballBlock   = 5  // steps per ball step in free flight
)

// Simulate plays a kick to its verdict. plan is ignored with opt.NoKeeper.
func Simulate(in Shot, pl Plan, prm Params, opt Options) Result {
	e := newEngine(prm)
	withKeeper := !opt.NoKeeper
	ln := e.computeLaunch(&in)
	b := ball{p: ln.pos, v: ln.vel, w: ln.spin}
	res := Result{
		Touch: -1,
		Launch: Launch{
			Vel:   [3]float64{ln.vel.x, ln.vel.y, ln.vel.z},
			Spin:  [3]float64{ln.spin.x, ln.spin.y, ln.spin.z},
			Speed: ln.speed, FuzzX: ln.fuzz.x, FuzzY: ln.fuzz.y,
			ContactX: ln.contact.x, ContactY: ln.contact.y,
		},
	}
	var k keeper
	var kb blocks
	if withKeeper {
		var m misread
		if in.HasMishit && !opt.NoMisread {
			m = keeperMisread(&in.Mishit)
			res.Misread = [4]float64{m.x, m.y, m.vx, m.jump}
		}
		k = e.keeperInit(m)
		e.initCaps(&kb.cbuf[0])
		e.initCaps(&kb.cbuf[1])
		kb.pose[1] = poseOf(&k)
	}
	every := opt.TraceEvery
	if every <= 0 {
		every = 25
	}
	trace := uint32(0x811c9dc5)

	step := 0
	t := 0.0
	verdict := 0
	lastContact := -1.0
	var gaveWay [nParts]float64
	for i := range gaveWay {
		gaveWay[i] = negInf
	}
	woodworkSet := false
	touched := false // res.Touch >= 0 || woodworkSet
	tracing := opt.Trace

	// The bounds the loop tests against, worked out once with the same
	// operations as the browser's checks.
	near2 := probeZone * probeZone
	far := probeZone + 0.3
	far2 := far * far
	lowY := ballR + 0.15
	fr25 := ballR + postR + 0.25 // nearFrame(p, 0.25)
	nfr25 := -fr25
	fr01 := ballR + postR + 0.01 // nearFrame(p, 0.01)
	nfr01 := -fr01
	sideX, roofY := e.netSideX, e.netRoofY
	side25 := sideX + fr25
	side01 := sideX + fr01
	boardsIn := boardsZ - 0.3
	netZ := goalZ - postR
	netZ2 := goalZ - postR - 0.5
	crossZ := goalZ - postR - ballR
	awayZ := goalZ + 0.8
	wideX := sideX + ballR
	liftY := ballR + 0.005

	for verdict == 0 {
		if tracing && step%every == 0 {
			trace = foldState(trace, &b, withKeeper, &k)
		}
		px, py, pz := b.p.x, b.p.y, b.p.z
		// In free flight the ball moves in steps of ballBlock; this pass then
		// covers steps first..step. The browser's freeFlight, written out:
		// nothing the ball can touch within reach during the step, and the
		// step inside one keeper block.
		adv := 1
		if !b.held && !b.inGoal {
			// Comparisons are kept in if conditions: as operands of && and ||
			// gno converts each to bool at a cost.
			ff := true
			if withKeeper {
				dx, dy, dz := px-k.pos.x, py-k.pos.y, pz-k.pos.z
				if dx*dx+dy*dy+dz*dz < far2 {
					ff = false
				}
			}
			if !ff {
			} else if b.grounded {
			} else if py < lowY {
				ff = false
			}
			if !ff {
			} else if dz := pz - goalZ; dz > fr25 {
			} else if dz < nfr25 {
			} else {
				ax := px
				if px < 0 {
					ax = -px
				}
				if dx := ax - sideX; dx < fr25 {
					if dx > nfr25 {
						ff = false
					}
				}
				if !ff {
				} else if dy := py - roofY; dy < fr25 {
					if dy > nfr25 {
						if ax < side25 {
							ff = false
						}
					}
				}
			}
			if !ff {
			} else if withKeeper {
				first := step + 1
				end := kb.s0 + kb.n - 1
				if first >= kb.s0+kb.n {
					end = first + blockLen(&k, &pl, first) - 1
				}
				ff = first+ballBlock-1 <= end
			}
			if ff {
				adv = ballBlock
			}
		}
		first := step + 1
		step += adv
		t = float64(step) * simDT

		// The keeper moves in 50 Hz blocks; its shapes are only needed once
		// the ball is within reach (probeZone).
		near := false
		num := 0 // steps into the keeper's current block
		if withKeeper {
			if first >= kb.s0+kb.n {
				e.keeperBlock(&k, &pl, first, &b, &kb)
			}
			num = step - kb.s0 + 1
			dx, dy, dz := px-k.pos.x, py-k.pos.y, pz-k.pos.z
			if dx*dx+dy*dy+dz*dz < near2 {
				near = true
			}
		}

		if b.held {
			all := e.blockCaps(&kb, num)
			target := e.holdPoint(&all)
			f := jsMin(1, kHoldPull*simDT)
			np := add(b.p, scale(sub(target, b.p), f))
			b.v = scale(sub(np, b.p), 1/simDT)
			b.p = vec{np.x, jsMax(ballR, np.y), np.z}
			b.w = scale(b.w, jsMax(0, 1-20*simDT))
			continue
		}

		if adv == 1 {
			e.integrateBall(&b, simDT)
		} else if b.grounded {
			e.integrateBall(&b, float64(adv)*simDT)
		} else {
			heunBall(&b, float64(adv)*simDT)
		}
		if b.p.y < ballR {
			groundContact(&b)
		}
		px, py, pz = b.p.x, b.p.y, b.p.z

		// Posts and bar: only near them (nearFrame(p, 0.01), written out).
		frameNear := false
		if dz := pz - goalZ; dz > fr01 {
		} else if dz < nfr01 {
		} else {
			ax := px
			if px < 0 {
				ax = -px
			}
			if dx := ax - sideX; dx < fr01 {
				if dx > nfr01 {
					frameNear = true
				}
			}
			if frameNear {
			} else if dy := py - roofY; dy < fr01 {
				if dy > nfr01 {
					if ax < side01 {
						frameNear = true
					}
				}
			}
		}
		if frameNear {
			for i := range e.frame {
				c := &e.frame[i]
				h := collideCapsule(&b, c.a, c.b, c.r, false, vec{}, vec{}, ePost, 0.1, 0.7, -1)
				if h.ok && h.impactSpeed > 0.5 && !woodworkSet {
					woodworkSet = true
					touched = true
					res.Woodwork = c.part
				}
			}
			px, py, pz = b.p.x, b.p.y, b.p.z
		}

		near0 := near // within probeZone of the hips; pouncing needs kPounceReach, less
		// Clear of the whole body over the block, at any part's full reach:
		// every per-part check below would find nothing.
		if near {
			bd := e.blockBody(&kb)
			if px < bd[0] {
				near = false
			} else if px > bd[1] {
				near = false
			} else if py < bd[2] {
				near = false
			} else if py > bd[3] {
				near = false
			} else if pz < bd[4] {
				near = false
			} else if pz > bd[5] {
				near = false
			}
		}
		if near {
			sp := ballSpeed(&b, b.v)
			react := 0.0
			if t >= kPerceive && sp < kReactSpeed {
				react = kReactReach * (kReactSpeed - sp) / kReactSpeed
			}
			late := jsMin(kHandLateMax, kHandLateRate*jsMax(0, t-kPerceive-0.1))
			inAir := k.phase == phaseAir
			capsB := e.blockCapsB(&kb)
			cand := e.blockCands(&kb, b.p)
			for i := 0; i < nCaps; i++ {
				if !cand[i] {
					continue
				}
				cb := &capsB[i]
				if gaveWay[cb.part] > t {
					continue
				}
				// The browser adds 0 for the parts without the extra reach,
				// which leaves the (positive) radius as it is.
				reach := cb.hit
				if cb.kind != kindHead {
					reach += react
				}
				if cb.kind == kindGlove {
					reach += late
				}
				// Outside the box of the part's positions over the block by
				// more than the contact distance (plus a centimetre against
				// rounding) on any axis: the probe could only find nothing.
				bx := e.blockBox(&kb, i, num)
				m := ballR + reach + 0.01
				if px < bx[0]-m {
					continue
				} else if px > bx[1]+m {
					continue
				} else if py < bx[2]-m {
					continue
				} else if py > bx[3]+m {
					continue
				} else if pz < bx[4]-m {
					continue
				} else if pz > bx[5]+m {
					continue
				}
				cc := e.blockCap(&kb, i, num)
				c := &cc
				va, vb := e.blockVel(&kb, i)
				pr := probeCapsule(&b, c.a, c.b, reach, va, vb)
				if !pr.ok {
					continue
				}
				if res.Touch < 0 {
					res.Touch = c.part
					res.TouchStep = step
					touched = true
				}
				newTouch := t-lastContact > kTouchGap
				lastContact = t
				all := e.blockCaps(&kb, num)
				d := e.catchDecision(&all, c, pr.relSpeed, b.p)
				if newTouch && d.held && verdict == 0 && pz >= crossZ {
					res.Contacts = append(res.Contacts, Contact{Step: step, Part: c.part, Catch: true})
					res.Caught = true
					b.held = true
					b.grounded = false
					k.holding = true
					verdict, res.DecidedStep, res.DecidedAt = Save, step, t
					break
				}
				var give float64
				switch c.kind {
				case kindGlove:
					give = kGiveGlove
					if d.hands >= 0.5 {
						give = kGiveHands
					}
				case kindLeg:
					give = kGiveLeg
					if inAir {
						give = kGiveLegInAir
					}
				case kindArm:
					give = kGiveArm
				case kindTorso:
					give = kGiveTorso
				default:
					give = kGiveHead
				}
				if pr.dist > ballR+c.r {
					give *= kFingertipGive
				}
				if c.kind == kindGlove && d.toBody < kReflexBody*e.scale {
					give = jsMax(give, kGiveTorso)
				}
				el := kEBody
				if c.kind == kindGlove {
					el = kEGlove
				}
				h := collideCapsule(&b, c.a, c.b, reach, true, va, vb, el, kFriction, 0.4, give)
				px, py, pz = b.p.x, b.p.y, b.p.z
				if !h.ok {
					continue
				}
				if h.gaveWay {
					gaveWay[c.part] = t + kTouchGap
				}
				if !h.gaveWay && c.kind == kindGlove && pr.relSpeed < kParryControl && b.v.z < kParryOut {
					wide := -1.0
					if px >= k.pos.x {
						wide = 1
					}
					b.v = vec{b.v.x + wide*kParryWide, b.v.y, kParryOut}
				}
				if newTouch {
					res.Contacts = append(res.Contacts, Contact{Step: step, Part: c.part, GaveWay: h.gaveWay})
				}
			}
			if b.held {
				continue
			}
		}

		// The boards, the line and the net all lie at or behind the goal line.
		x, y, z := px, py, pz
		ax := x
		if x < 0 {
			ax = -x
		}
		if z <= goalZ {
			if z-ballR < boardsZ && z > boardsIn && b.v.z < 0 && y-ballR < boardsH && ax < boardsHW {
				b.p = vec{x, y, boardsZ + ballR}
				b.v = vec{b.v.x * 0.7, b.v.y * 0.7, -0.3 * b.v.z}
				z = b.p.z
			}
		}

		if b.grounded {
			if b.v.y > 0.3 {
				b.grounded = false
			} else if y > liftY {
				b.grounded = false
			}
		}

		if z <= goalZ {
			if !res.LineCross {
				res.LineCross = true
				res.LineT, res.LineX, res.LineY = r3(t), r3(x), r3(y)
			}
			if !b.inGoal && z < netZ && z > netZ2 && ax < sideX && y < roofY {
				b.inGoal = true
			}
			if !res.Crossing && z < crossZ {
				res.Crossing = true
				res.CrossT, res.CrossX, res.CrossY = r3(t), r3(x), r3(y)
				if b.inGoal {
					verdict = Goal
				} else if res.Touch >= 0 {
					verdict = Save
				} else if woodworkSet {
					verdict = Post
				} else {
					verdict = Miss
				}
				res.DecidedStep, res.DecidedAt = step, t
			}
		}

		if verdict == 0 {
			kept := false // decided without crossing the line
			if touched {
				if b.v.z > 0 {
					if z > awayZ {
						kept = true // parried away
					}
				}
			}
			if kept {
			} else if b.grounded && slowerThan(b.v, 0.15) {
				kept = true
			} else if ax > wideX {
				if x*b.v.x >= 0 {
					kept = true // outside a post and moving away from it
				}
			}
			if kept {
			} else if touched && withKeeper && near0 && pounces(&k, &b) {
				// The keeper pounces on the loose ball.
				verdict, res.DecidedStep, res.DecidedAt = Save, step, t
				b.v = vec{0, 0, 0}
				b.w = vec{0, 0, 0}
				res.Pounced = true
			} else if t >= simMaxT {
				kept = true
			}
			if kept {
				if res.Touch >= 0 {
					verdict = Save
				} else if woodworkSet {
					verdict = Post
				} else {
					verdict = Miss
				}
				res.DecidedStep, res.DecidedAt = step, t
			}
		}
	}
	if opt.Trace {
		trace = foldState(trace, &b, withKeeper, &k)
	}
	res.Outcome = verdict
	res.EndX, res.EndY = b.p.x, b.p.y
	res.Steps = step
	res.Trace = trace
	if withKeeper {
		res.Commits = k.commits
	}
	return res
}

// foldState hashes the ball and keeper state (FNV-1a over the float64 bits,
// big-endian), as the browser-side test harness does.
func foldState(h uint32, b *ball, withKeeper bool, k *keeper) uint32 {
	h = foldVec(h, b.p)
	h = foldVec(h, b.v)
	h = foldVec(h, b.w)
	if withKeeper {
		h = foldVec(h, k.pos)
		h = foldVec(h, k.vel)
		h = foldFloat(h, k.lean.s)
		h = foldFloat(h, k.lean.c)
		h = foldVec(h, k.arms.l)
		h = foldVec(h, k.arms.r)
	}
	return h
}

func foldVec(h uint32, v vec) uint32 {
	h = foldFloat(h, v.x)
	h = foldFloat(h, v.y)
	return foldFloat(h, v.z)
}

func foldFloat(h uint32, f float64) uint32 {
	u := math.Float64bits(f)
	for i := 0; i < 8; i++ {
		h ^= uint32(byte(u >> (56 - 8*uint(i))))
		h *= 0x01000193
	}
	return h
}

sqrt.gno

package physics

import "math"

// fsqrt is math.Sqrt, bit for bit, at a fraction of its gas.
//
// gno's math.Sqrt computes the root one bit at a time in interpreted code
// (~170k gas); the engine takes several roots every millisecond step. Here a
// float Newton iteration gets within a unit in the last place, and an exact
// integer test settles the last bit: for x = M * 2^e (e even) the correctly
// rounded root is R * 2^q, q = e/2 - 26, where R is the integer nearest
// sqrt(N), N = M * 2^52, and R is that integer exactly when
// R*R - R < N <= R*R + R (no square root of an integer lies halfway between
// two integers). N - R*R is small, so it is computed exactly mod 2^64. A
// Newton result one ulp off is moved by that ulp; anything else (rare) goes
// to sqrtSlow. Zero, subnormals, infinities and NaN go to math.Sqrt.
func fsqrt(x float64) float64 {
	b := math.Float64bits(x)
	if b-1<<52 >= 0x7fe0000000000000 { // negative, zero, subnormal, infinite or NaN
		return math.Sqrt(x)
	}
	y := math.Float64frombits((b >> 1) + 0x1ff8000000000000)
	y = 0.5 * (y + x/y)
	y = 0.5 * (y + x/y)
	y = 0.5 * (y + x/y)
	y = 0.5 * (y + x/y)
	yb := math.Float64bits(y)
	// x = m * 2^(ex), y = R * 2^q: y is the root when R*R - R < N <= R*R + R
	// for N = m * 2^(ex-2q), which is m << 52 or m << 53 when y is in the
	// root's binade.
	s := b>>52 - yb>>52<<1 + 1075
	if s-52 > 1 {
		return sqrtSlow(x)
	}
	R := yb&(1<<52-1) | 1<<52
	N := (b&(1<<52-1) | 1<<52) << s
	d := int64(N - R*R)
	if d > int64(R) {
		// One ulp low: R+1 is the root when N - (R+1)^2 = d - 2R - 1 is in range.
		if d2 := d - int64(R<<1) - 1; d2 <= int64(R+1) && d2 > -int64(R+1) && R+1 < 1<<53 {
			return math.Float64frombits(yb + 1)
		}
		return sqrtSlow(x)
	}
	if d <= -int64(R) {
		if d2 := d + int64(R<<1) - 1; d2 <= int64(R-1) && d2 > -int64(R-1) && R > 1<<52 {
			return math.Float64frombits(yb - 1)
		}
		return sqrtSlow(x)
	}
	return y
}

// sqrtSlow settles the roots the fast path cannot: the general case.
func sqrtSlow(x float64) float64 {
	b := math.Float64bits(x)
	exp := int(b>>52) & 0x7ff
	if b>>63 != 0 || exp == 0 || exp == 0x7ff {
		return math.Sqrt(x)
	}
	// Halve the exponent, then four Newton steps: within an ulp.
	y := math.Float64frombits((b >> 1) + 0x1ff8000000000000)
	y = 0.5 * (y + x/y)
	y = 0.5 * (y + x/y)
	y = 0.5 * (y + x/y)
	y = 0.5 * (y + x/y)

	m := b&(1<<52-1) | 1<<52
	e := exp - 1075 // x = m * 2^e
	if e&1 != 0 {
		m <<= 1
		e--
	}
	N := m << 52
	yb := math.Float64bits(y)
	if int(yb>>52) != e/2+1049 { // y is not in the root's binade: settle it the long way
		return rootOf(N, e/2-26, y)
	}
	R := yb&(1<<52-1) | 1<<52 // y = R * 2^q
	d := int64(N - R*R)
	if d > int64(R) {
		if d2 := int64(N - (R+1)*(R+1)); d2 > int64(R+1) || d2 <= -int64(R+1) {
			return rootOf(N, e/2-26, y)
		}
		return math.Float64frombits(yb + 1)
	}
	if d <= -int64(R) {
		if R == 1<<52 {
			return rootOf(N, e/2-26, y)
		}
		if d2 := int64(N - (R-1)*(R-1)); d2 > int64(R-1) || d2 <= -int64(R-1) {
			return rootOf(N, e/2-26, y)
		}
		return math.Float64frombits(yb - 1)
	}
	return y
}

// rootOf is the general case: R from the estimate y, an integer Newton step,
// then whole units until R is the nearest integer to sqrt(N).
func rootOf(N uint64, q int, y float64) float64 {
	R := uint64(y * math.Float64frombits(uint64(1023-q)<<52))
	d := int64(N - R*R)
	R = uint64(int64(R) + d/int64(2*R))
	for {
		d = int64(N - R*R)
		if d > int64(R) {
			R++
		} else if d <= -int64(R) {
			R--
		} else {
			break
		}
	}
	return float64(R) * math.Float64frombits(uint64(q+1023)<<52)
}