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

data.gno

package golf

import (
	"chain"
	"chain/runtime"
	"crypto/sha256"
	"encoding/hex"
	"math"
	"strconv"
	"strings"
	"unicode"
	"unicode/utf8"

	"gno.land/p/nym-alexiscolin000/gnogolf/course"
)

// Holes as data: a version is a GG1 string, checked once at publish and kept
// as bytes; each call decodes it afresh and stores nothing of it. A version
// is never edited or removed: a new one takes its alias, and the old one is
// archived, still playable, its records kept.

// wearGrid is the entry's wear: a count of balls at rest per cell of the
// WearW by WearH grid, row-major.
func (e *entry) wearGrid() []int {
	out := make([]int, wearCells)
	if b := e.wear; b != nil {
		for i := range out {
			out[i] = int(uint32(b[4*i]) | uint32(b[4*i+1])<<8 | uint32(b[4*i+2])<<16 | uint32(b[4*i+3])<<24)
		}
	}
	return out
}

const wearCells = course.WearW * course.WearH

// mark counts a ball come to rest in wear cell i.
func (e *entry) mark(i int) {
	if i < 0 || i >= wearCells {
		return // course.WearIndexOn never gives one
	}
	if e.wear == nil {
		e.wear = make([]byte, 4*wearCells)
	}
	b := e.wear
	n := uint32(b[4*i]) | uint32(b[4*i+1])<<8 | uint32(b[4*i+2])<<16 | uint32(b[4*i+3])<<24
	n++
	b[4*i], b[4*i+1], b[4*i+2], b[4*i+3] = byte(n), byte(n>>8), byte(n>>16), byte(n>>24)
}

// maxData bounds a version's data: a hole at every limit of the format is
// about 21 KB.
const maxData = 32 << 10

// Publish puts a course hole's data into its slot as its next version and
// returns the new id ("garden/7/v2"). Only the owner can. hexData is the hole
// as course.Encode wrote it, in hex. slot must be the data's own world and
// order ("garden/7", order 1 to 999), so a mis-edited file cannot replace the
// wrong hole; the course holds at most 9999 slots (maxCourse). Data identical
// to the current version's is refused. The version it replaces is archived:
// its records stay, its bests leave the course standings. note (at most 140
// characters, cleaned) says why.
func Publish(cur realm, slot, hexData, note string) string {
	by := cur.Previous().Address()
	if !isOwner(by) {
		panic("golf: only the owner can publish a course hole")
	}
	h, data, sum := decodeData(hexData)
	if h.Order < 1 || h.Order != math.Trunc(h.Order) {
		panic("golf: a course hole's order is a whole number from 1 to 999")
	}
	own := h.World + "/" + strconv.Itoa(int(h.Order))
	if slot != own {
		panic("golf: this data is " + own + ", not " + slot)
	}
	key, ok := slotKeyOf(slot)
	if !ok {
		panic("golf: " + slot + " is not a course slot") // its data's own world/order: cannot happen
	}
	var old *entry
	n := 1
	if v := slots.Get(key); v != nil {
		old = find(v.(string))
		if old.sha == sum {
			panic(nothingNew(old))
		}
		n = old.version + 1
	} else if slots.Size() >= maxCourse {
		panic("golf: the course is full: 9999 slots")
	}
	e := dataEntry(slot, n, h, by, sum, note)
	e.official = true
	courseHoles.Set(e.id, e)
	holeData.Set(e.id, data)
	slots.Set(key, e.id)
	chain.Emit(EventHolePublished, "hole", e.id, "slot", slot, "sha", sum, "by", by.String(), "official", "true")
	if old != nil {
		retire(old, e.id)
	}
	return e.id
}

// PublishMine publishes a community hole of the caller's own and returns its
// id: "<caller>/<slug>/v1", then v2 and on. Anyone can while publishing is
// open (SetPublishing); only the same address adds versions. slug is 1 to 32
// of a-z, 0-9 and "-". The data is checked as Publish checks it, its world
// and order aside; its name and note carry no web address. It is playable and
// recorded, in no cup and not in the course ranking; a new version of a
// hidden hole stays hidden. The publisher pays the storage deposit (about
// half a GNOT a version), and nothing published can be deleted.
func PublishMine(cur realm, slug, hexData, note string) string {
	if !publishing {
		panic("golf: publishing community holes is not open yet")
	}
	by := cur.Previous().Address()
	if !validSlug(slug) {
		panic("golf: a slug is 1 to 32 of a-z, 0-9 and -")
	}
	alias := by.String() + "/" + slug
	h, data, sum := decodeData(hexData)
	var old *entry
	n := 1
	if v := aliases.Get(alias); v != nil {
		old = find(v.(string))
		if old.sha == sum {
			panic(nothingNew(old))
		}
		n = old.version + 1
	}
	e := dataEntry(alias, n, h, by, sum, note)
	if linkish(e.name) || linkish(e.note) {
		panic("golf: a community hole's name and note carry no web address")
	}
	community.Set(e.id, e)
	holeData.Set(e.id, data)
	aliases.Set(alias, e.id)
	if old != nil {
		old.next = e.id // archived; it never counted anywhere
	}
	if !hidden.Has(alias) { // a hidden hole has no row (Hide)
		a := by.String()
		// the newest row: the author's own moves to its height
		moveAuthor(a, newestRow(a), pad(int(e.height), 12))
		if old != nil {
			byAuthor.Remove(a + " " + recentKey(old.height, slug))
		}
		byAuthor.Set(a+" "+recentKey(e.height, slug), e.id)
	}
	chain.Emit(EventHolePublished, "hole", e.id, "slot", alias, "sha", sum, "by", by.String(), "official", "false")
	return e.id
}

// newestRow is the height of an author's newest row in byAuthor
// ("<address> <height> <slug>"), "" if they have none.
func newestRow(a string) string {
	latest := ""
	byAuthor.ReverseIterate(a+" ", a+"!", func(k string, _ any) bool {
		latest = k[len(a)+1 : len(a)+13]
		return true
	})
	return latest
}

// moveAuthor moves an author's own row in byAuthor (recentKey(height,
// address)) from the height was to now, "" for none: it stays at their
// newest row's, and goes with their last.
func moveAuthor(a, was, now string) {
	if was == now {
		return
	}
	if was != "" {
		byAuthor.Remove(was + " " + a)
	}
	if now != "" {
		byAuthor.Set(now+" "+a, nil)
	}
}

// linkish spots a web address in a community hole's name or note: "www.", a
// dot between a letter or digit and two letters ("claim.xyz", "t.me"; not
// "e.g."), or an IP address, look-alike dots (.。․﹒) read as dots, letters in
// any case. Basic (the owner can Hide what gets past) and strict on purpose
// ("St.Andrews" is refused). It reads s a byte at a time: every mark is
// ASCII, so a non-ASCII character is decoded only to tell İ and the Kelvin
// sign (which lower-case to ASCII), the look-alike dots and spaces apart.
func linkish(s string) bool {
	var c1, c2, c3 byte // the three characters before c, lower-cased
	// the word so far (as strings.Fields splits): an IP is digits, three dots
	word, ip, dots := false, true, 0
	for i := 0; i < len(s); {
		c, size, space := s[i], 1, false
		switch {
		case c >= 'A' && c <= 'Z':
			c += 'a' - 'A'
		case c >= utf8.RuneSelf:
			var r rune
			r, size = utf8.DecodeRuneInString(s[i:])
			switch r {
			case 'İ':
				c = 'i'
			case '\u212a': // the Kelvin sign
				c = 'k'
			case '.', '。', '․', '﹒':
				c = '.'
			default:
				c, space = utf8.RuneSelf, unicode.IsSpace(r) // none of the marks
			}
		case c == ' ' || c >= '\t' && c <= '\r':
			space = true
		}
		i += size
		switch {
		case c == '.' && c1 == 'w' && c2 == 'w' && c3 == 'w':
			return true
		case isLower(c) && isLower(c1) && c2 == '.' && (isLower(c3) || isDigit(c3)):
			return true
		}
		c1, c2, c3 = c, c1, c2
		if space {
			if word && ip && dots == 3 {
				return true
			}
			word, ip, dots = false, true, 0
			continue
		}
		word = true
		if c == '.' {
			dots++
		} else if !isDigit(c) {
			ip = false
		}
	}
	return word && ip && dots == 3
}

func isLower(c byte) bool { return c >= 'a' && c <= 'z' }
func isDigit(c byte) bool { return c >= '0' && c <= '9' }

// decodeData checks a version's data as it arrives: hex, GG1 within the
// format's limits, stored lengths bit-exact (DecodeChecked: every later
// Decode trusts them), and in the one form Encode gives.
func decodeData(hexData string) (*course.Simple, string, string) {
	if len(hexData) > 2*maxData {
		panic("golf: the data is too long")
	}
	b, err := hex.DecodeString(hexData)
	if err != nil {
		panic("golf: the data is not hex")
	}
	data := string(b)
	h, err := course.DecodeChecked(data)
	if err != nil {
		panic("golf: " + err.Error())
	}
	// one hole, one string: data that decodes to a hole Encode would write
	// otherwise (a skin never used, a style run split, a stored length a
	// zero-length wall never reads) is refused, so the same hole cannot come
	// back under another sha
	if course.Encode(h) != data {
		panic("golf: the data is not as course.Encode writes it")
	}
	// refused if a transaction could not replay its heaviest shot, or if in
	// its dearest weather a commit's first shot would be capped below
	// minShotWork: every commit decodes the hole and draws its forecast first
	if newWork(h, nil).bound > maxShotGas {
		panic(errShotTooHeavy)
	}
	if worstGas(h, len(data)) > workBudget {
		panic(errTooStormy)
	}
	sum := sha256.Sum256(b)
	return h, data, hex.EncodeToString(sum[:])
}

// nothingNew refuses data identical to the alias's current version: it would
// reset the hole's ranking for nothing.
func nothingNew(old *entry) string {
	return "golf: this data is already " + old.id + ": nothing to publish"
}

func dataEntry(alias string, n int, h *course.Simple, by address, sum, note string) *entry {
	e := newEntry(alias+"/v"+strconv.Itoa(n), cleanName(h.Title), h.Par(), h.World, h.Order)
	e.slot, e.version, e.by, e.height, e.sha, e.note = alias, n, by, runtime.ChainHeight(), sum, cleanText(note, maxNote)
	return e
}

// worlds is the course's worlds in play order, with their names on the page.
var worlds = []struct{ id, name string }{
	{"garden", "Garden Cup"},
	{"island", "Island Cup"},
	{"town", "Mushroom Town"},
	{"mountain", "Mountain Cup"},
	{"mines", "Crystal Mines"},
}

// worldRank is a world's place among worlds; any other comes after.
func worldRank(w string) int {
	for i, x := range worlds {
		if x.id == w {
			return i
		}
	}
	return len(worlds)
}

// slotKey is a slot's key: its world's rank, the world, and the order in
// three digits, so the slots tree is in course order.
func slotKey(world string, order int) string {
	return string(rune('0'+worldRank(world))) + world + "/" + pad(order, 3)
}

// slotKeyOf reads a slot, "world/order" (as "garden/7"), into its key.
func slotKeyOf(slot string) (string, bool) {
	i := strings.Index(slot, "/")
	if i < 0 || !course.IsWorld(slot[:i]) {
		return "", false
	}
	n, err := strconv.Atoi(slot[i+1:])
	if err != nil || n < 1 || n > course.MaxOrder || strconv.Itoa(n) != slot[i+1:] {
		return "", false
	}
	return slotKey(slot[:i], n), true
}

func validSlug(s string) bool {
	if len(s) < 1 || len(s) > 32 {
		return false
	}
	for i := 0; i < len(s); i++ {
		if c := s[i]; !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
			return false
		}
	}
	return true
}

// HoleData is a version's GG1, in hex, as it was published (an alias gives
// its current version's): what a golf/v2 or an auditor reads back.
func HoleData(hole string) string {
	e := readHole(hole)
	return hex.EncodeToString([]byte(holeData.Get(e.id).(string)))
}

// Current is the id of the version an alias ("garden/7", "<address>/<slug>")
// plays now, "" if the alias has none.
func Current(alias string) string { return current(alias) }

// Versions is every version of an alias, oldest first (the newest pageMax if
// there are more): its id, number, the height it was published at, by whom,
// its data's sha256, its note, and the version that took its place. slot is
// the alias, "" (and no versions) for one that has none.
func Versions(alias string) string {
	now := find(current(alias))
	slot := ""
	if now != nil {
		slot = now.slot // never the caller's own bytes
	}
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"slot":` + jstr(slot) + `,"versions":[`)
	if now != nil {
		from := firstVersion(now)
		for n := from; n <= now.version; n++ {
			e := find(now.slot + "/v" + strconv.Itoa(n))
			sb.WriteString(sep(n-from) + `{"id":` + jstr(e.id) + `,"v":` + strconv.Itoa(e.version) +
				`,"height":` + strconv.FormatInt(e.height, 10) + `,"by":` + jstr(e.by.String()) +
				`,"sha":` + jstr(e.sha) + `,"note":` + jstr(e.note) + `,"next":` + jstr(e.next) + "}")
		}
	}
	sb.WriteString("]}")
	return sb.String()
}

// firstVersion is the oldest of now's versions a list shows: the newest
// pageMax are (now is its alias's current version).
func firstVersion(now *entry) int {
	if now.version > pageMax {
		return now.version - pageMax + 1
	}
	return 1
}

// BestOf is a player's best finished round on a hole in a mode, 0 if none.
func BestOf(hole, mode string, player address) int {
	e, m := readHole(hole), modeOf(mode)
	return bestStrokes(e.bests(m).Get(player.String()))
}

gnomod.toml

module = "gno.land/r/nym-alexiscolin000/gnogolf/golf"
gno = "0.9"

[addpkg]
  creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq"
  height = 65086
  max_deposit = "30000000ugnot"

golf.gno

// Package golf is the game realm: it keeps the holes, the players' rounds,
// the records and the rankings. Every hole is data (a GG1 string, p/…/course),
// never code: golf decodes it and plays it with p/…/physics. The owner
// publishes the course's holes into slots of a cup ("garden/7"), each publish
// a new version ("garden/7/v2"); once the owner opens publishing, anyone can
// publish a community hole ("<address>/<slug>/v1", PublishMine), playable and
// recorded but outside the course and its ranking.
//
// Reads take a version's id or its alias ("garden/7", "<address>/<slug>"),
// its current version. Writes take the exact id only, as HoleState or Holes gave
// it: a round cannot be replayed on a version it was not played on.
//
// Who can change what (in full on the hub page): the owner holds one power,
// the course itself: its holes (Publish), what the lists show (Hide), and
// whether anyone can publish (SetPublishing).
package golf

import (
	"chain"
	"chain/runtime"
	"math"
	"strconv"
	"strings"
	"unicode"

	"gno.land/p/nym-alexiscolin000/gnogolf/course"
	"gno.land/p/nym-alexiscolin000/gnogolf/physics"
	"gno.land/p/nt/avl/v0"
	bptree "gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/ufmt/v0"
	"gno.land/r/sys/users"
)

const (
	maxPower = 10.0
	// maxShots bounds a commit; its work (workBudget) may bound it lower.
	maxShots = 12
)

// The refusals said in more than one place.
const (
	errShot         = "golf: a shot is an angle and a power between 0 and 10"
	errStrokeLimit  = "golf: this round is over its stroke limit, Reset to play again"
	errShotTooHeavy = "golf: one shot on this hole could cost more than a transaction can replay"
	errTooStormy    = "golf: in its dearest weather, a commit on this hole would leave too little room for a shot"
	errUnknownHole  = "golf: unknown hole: "
)

type entry struct {
	id    string // "<alias>/v<n>"
	name  string // the hole's name, cleaned; frozen when it was published
	par   int    // frozen like the name
	world string // "garden", "island", "town": frozen too
	order float64
	// official: a version the owner published into a slot; only these rank
	official bool
	// its provenance, set at publish (the hole itself is never stored: hole())
	slot    string  // the alias it answers to: "garden/7", "<address>/<slug>"
	version int     // its number under that alias, from 1
	by      address // who published it
	height  int64
	sha     string // sha256 of its data, hex
	note    string
	wear    []byte // WearW*WearH little-endian u32 counters, made at its first play
	// Its rounds, bests and board are rows of the shared indexes (views), not
	// trees of its own, whose first leaf (a few KB) its first player would pay.
	plays int
	// the records per mode (rec), flat: a nested object costs a few hundred
	// bytes more
	best, proBest     int
	bestBy, proBestBy address
	next              string // the version that took this one's place, "" while it is current
	// its drain once archived (drain); nil if never archived
	out *draining
}

// record is the hole's record in one mode: who holds it, in how many
// strokes, 0 if never completed.
type record struct {
	by   address
	best int
}

// rec is the entry's record in mode m.
func (e *entry) rec(m int) record {
	if m == pro {
		return record{e.proBestBy, e.proBest}
	}
	return record{e.bestBy, e.best}
}

// roundTree is the version's rounds under way: player address -> *round. A
// round is stored from its first commit that does not finish it, and removed
// as it is holed (stroke) or Reset: a finish is kept as a best, not a round.
func (e *entry) roundTree() view { return view{rounds, e.id + " "} }

// bests is the version's results in mode m: player address -> their best
// finished round there, kept across replays, as bestOf writes it.
func (e *entry) bests(m int) view { return view{bests, e.id + " " + modeNames[m] + " "} }

// bestOf is how a best is kept: "<strokes> <height> <period> <shots>". The
// height ranks it before a later tie (boardKey); the period and shots let
// Ghost replay it in its own weather. The mode is in the key.
func bestOf(r *round) string {
	return strconv.Itoa(r.strokes) + " " + strconv.FormatInt(runtime.ChainHeight(), 10) + " " +
		strconv.FormatInt(r.period, 10) + " " + r.shots
}

// errBest is a best not as bestOf writes it: never written, refused if read.
const errBest = "golf: a best not as bestOf writes it: "

// bestStrokes is a kept best's strokes, 0 for none (a tree's nil).
func bestStrokes(v any) int {
	if v == nil {
		return 0
	}
	s := v.(string)
	i := strings.Index(s, " ")
	if i < 0 {
		panic(errBest + s)
	}
	n, err := strconv.Atoi(s[:i])
	if err != nil {
		panic(errBest + s)
	}
	return n
}

// bestFields is a kept best's height, period and shots.
func bestFields(v any) (int64, int64, string) {
	s := v.(string)
	f := strings.SplitN(s, " ", 4)
	if len(f) < 4 {
		panic(errBest + s)
	}
	at, err := strconv.ParseInt(f[1], 10, 64)
	period, err2 := strconv.ParseInt(f[2], 10, 64)
	if err != nil || err2 != nil {
		panic(errBest + s)
	}
	return at, period, f[3]
}

// board is the version's board in mode m: boardKey(best, player) ->
// player, the named players' bests, fewest strokes first.
func (e *entry) board(m int) view { return view{boards, e.id + " " + modeNames[m] + " "} }

// view is the rows of a shared index under prefix p, read and written
// without it. p ends with a space, which no id holds, so its rows are exactly
// the keys from p to p with the space made a "!".
type view struct {
	t *bptree.BPTree
	p string
}

func (v view) end() string                 { return v.p[:len(v.p)-1] + "!" }
func (v view) Get(k string) any            { return v.t.Get(v.p + k) }
func (v view) Has(k string) bool           { return v.t.Has(v.p + k) }
func (v view) Set(k string, x any) bool    { return v.t.Set(v.p+k, x) }
func (v view) Remove(k string) (any, bool) { return v.t.Remove(v.p + k) }
func (v view) Size() int                   { return before(v.t, v.end()) - before(v.t, v.p) }
func (v view) index(k string) int          { return before(v.t, v.p+k) - before(v.t, v.p) }
func (v view) strip(cb func(string, any) bool) func(string, any) bool {
	return func(k string, x any) bool { return cb(k[len(v.p):], x) }
}

// Iterate is the rows in [start, end) ascending, end "" for no bound.
func (v view) Iterate(start, end string, cb func(key string, x any) bool) bool {
	hi := v.end()
	if end != "" {
		hi = v.p + end
	}
	return v.t.Iterate(v.p+start, hi, v.strip(cb))
}

// IterateByOffset is count rows from the offset-th, fewer at the end.
func (v view) IterateByOffset(offset, count int, cb func(key string, x any) bool) bool {
	end := v.end()
	return v.t.IterateByOffset(before(v.t, v.p)+offset, count, func(k string, x any) bool {
		return k >= end || v.strip(cb)(k, x)
	})
}

// before is how many keys of t sort before k: a binary search by index.
func before(t *bptree.BPTree, k string) int {
	lo, hi := 0, t.Size()
	for lo < hi {
		mid := (lo + hi) / 2
		if key, _ := t.GetByIndex(mid); key < k {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo
}

// seeded is a shared index whose first leaf the deployer pays at init, not
// its first player. Its key "" sorts before every view's rows: no view sees it.
func seeded() *bptree.BPTree {
	t := bptree.NewBPTree32()
	t.Set("", nil)
	return t
}

func newEntry(id, name string, par int, world string, order float64) *entry {
	return &entry{id: id, name: name, par: par, world: world, order: order}
}

// hole is the entry's hole, decoded from its data for this call only: a
// public call decodes it once and passes it down, and it is never stored.
func (e *entry) hole() *course.Simple {
	s, err := course.Decode(holeData.Get(e.id).(string))
	if err != nil {
		panic("golf: the data of " + e.id + " does not decode: " + err.Error()) // checked at publish: cannot happen
	}
	return s
}

// draining is an archived hole's drain, per mode: the next player to take
// out, whether all are out, and the players whose first finish came after it
// was archived: never counted, so never taken out.
type draining struct {
	from  [modes]string
	done  [modes]bool
	fresh [modes]*avl.Tree // player -> true
}

type round struct {
	bx, by  float64 // the ball, exactly: flat, not a nested Vec2 object
	fx, fy  float64 // where the last stroke started: its path is replayed from there
	strokes int
	period  int64  // the weather it is played in: set by its first stroke
	shots   string // the decisions so far, "angle,power,tick;…": the round, replayable
	mode    int    // assisted or pro: set by its first stroke, like the weather
}

func (r *round) ball() physics.Vec2 { return physics.Vec2{X: r.bx, Y: r.by} }

// A round is played in one of two modes, each with its own records and
// rankings: assisted (the full aim preview) or pro (the preview cut short).
// The chain cannot see a screen: the mode is the player's word.
const (
	assisted = iota
	pro
	modes
)

// modeOf reads a mode's name: "assisted" (or "") or "pro"; anything else
// panics rather than answer for another mode.
func modeOf(name string) int {
	switch name {
	case "", "assisted":
		return assisted
	case "pro":
		return pro
	}
	panic(`golf: a mode is "assisted" or "pro", got: ` + name)
}

var modeNames = [modes]string{"assisted", "pro"}

// modeTitles is how the pages head a mode's board.
var modeTitles = [modes]string{"Assisted", "Pro"}

// The indexes are B+ trees (32 entries a leaf: far cheaper an entry than an
// AVL node). What players add goes to five of them, shared by every version
// and mode and seeded at init (views): a first player pays for their own rows
// only.
//
// A B+ tree must not change while it is iterated: no callback below writes
// to the tree it walks (drain walks a hole's bests and writes the standings).
var (
	// the course's versions, current and archived: id -> *entry
	courseHoles = bptree.NewBPTree32()
	// everyone else's published data: id -> *entry
	community = bptree.NewBPTree32()
	// id -> a version's GG1 string, apart from its entry so that listing
	// holes never loads it
	holeData = bptree.NewBPTree32()
	// slotKey(world, order) -> id of the current version there, in course order
	slots = bptree.NewBPTree32()
	// "<address>/<slug>" -> id of the current version of a community hole
	aliases = bptree.NewBPTree32()
	// the listed community holes, two kinds of row in one tree (one first
	// leaf to pay, not two):
	//   - "<address> " + recentKey(publish height, slug) -> id: an author's
	//     holes not hidden, newest last;
	//   - recentKey(their newest row's height, address) -> nil: one per
	//     author (moveAuthor), the latest to publish last.
	// A height is digits and an address "g1…": the two never mix.
	byAuthor = bptree.NewBPTree32()
	// "<address>/<slug>" -> true: community holes hidden (Hide), every
	// version, out of byAuthor; still playable
	hidden = avl.NewTree()
	// recentKey(archive height, id) -> id of an archived course version
	archived = bptree.NewBPTree32()
	// every version's rounds, bests and boards, under its id (views)
	rounds, bests, boards = seeded(), seeded(), seeded()
	// per mode: player -> *row, their standing over the official holes
	allTotals = seeded()
	totals    = [modes]view{{allTotals, "assisted "}, {allTotals, "pro "}}
	// per mode: rankKey(row) -> player, the named players with a hole, best
	// first
	allRanks = seeded()
	ranks    = [modes]view{{allRanks, "assisted "}, {allRanks, "pro "}}
	// per mode: rankKey(row) -> player, standings with no hole left (setRow)
	idle = [modes]view{{allRanks, "idle assisted "}, {allRanks, "idle pro "}}
	// archived holes still in the standings, oldest first (drain)
	archiving []string
)

// row is one player's standing across the course: their best on each hole
// counted, summed, and those holes' pars, summed. Its score against par,
// strokes - par, is what ranks it after its holes.
type row struct {
	player              string
	holes, strokes, par int
	height              int64 // of the finish that last improved it: the first there ranks first
}

const topSize = 10

// named reports whether a player has a gno.land name (r/sys/users). Only
// named players rank: a name takes a registration, so a script cannot fill
// the boards with free addresses. Every finish is still kept.
func named(player string) bool {
	return !users.ResolveAddress(address(player)).IsDeleted()
}

// nameOf is a named player's name, "" for anyone else.
func nameOf(player string) string {
	if u := users.ResolveAddress(address(player)); !u.IsDeleted() && nameish(u.Name()) {
		return u.Name()
	}
	return ""
}

// nameish is a name as r/sys/users registers it (a-z, then a-z, 0-9, "_" and
// "-", at most 64), checked again because the pages print names in links.
func nameish(n string) bool {
	if n == "" || len(n) > 64 || n[0] < 'a' || n[0] > 'z' {
		return false
	}
	for i := 0; i < len(n); i++ {
		if c := n[i]; !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '_' || c == '-') {
			return false
		}
	}
	return true
}

// find is the hole with this exact id, nil if none.
func find(id string) *entry {
	if v := courseHoles.Get(id); v != nil {
		return v.(*entry)
	}
	if v := community.Get(id); v != nil {
		return v.(*entry)
	}
	return nil
}

// current is the id an alias points at now: a course slot's or a community
// hole's current version; "" if it is neither.
func current(alias string) string {
	if k, ok := slotKeyOf(alias); ok {
		if v := slots.Get(k); v != nil {
			return v.(string)
		}
		return ""
	}
	if v := aliases.Get(alias); v != nil {
		return v.(string)
	}
	return ""
}

// mustHole is the hole a write names: its exact id. An alias is refused: a
// new version may have taken its place since the round's shots were chosen.
func mustHole(id string) *entry {
	if e := find(id); e != nil {
		return e
	}
	if now := current(id); now != "" {
		panic("golf: " + id + " is an alias: play its version by id, " + now)
	}
	panic(errUnknownHole + id)
}

// readHole is the hole a read names: an exact id, or an alias for its
// current version.
func readHole(id string) *entry {
	if e := find(id); e != nil {
		return e
	}
	if now := current(id); now != "" {
		return find(now)
	}
	panic(errUnknownHole + id)
}

// recentKey orders by height, then by what is at that height.
func recentKey(height int64, what string) string { return pad(int(height), 12) + " " + what }

// pad writes n in width digits, zeros first: keys that sort as numbers.
func pad(n, width int) string {
	s := strconv.Itoa(n)
	for len(s) < width {
		s = "0" + s
	}
	return s
}

// rankKey orders the course ranking: most holes first, then the best score
// against par (a hole at par counts the same whatever its par), then the
// first there, then the address. The score is signed: vsParBias puts it in
// seven digits. The holes take five: a standing can count more than the
// course's slots while a republished hole drains (its old best still counts,
// its new one adds a hole), so they get room well past maxCourse.
func rankKey(r *row) string {
	return pad(99999-r.holes, 5) + "/" + pad(vsParBias+r.strokes-r.par, 7) + "/" + pad(int(r.height), 12) + "/" + r.player
}

// maxCourse bounds the course's slots (Publish); a standing's holes are at
// most those plus the archived versions drain has not taken it out of yet.
// vsParBias is more than a standing can be under or over par: a hole is -18
// to +59 (1 to 60 strokes, par 1 to 19), so a full course at most 9999 * 59 =
// 589,941 over, 179,982 under, and the seven digits hold 55,555 holes.
const (
	maxCourse = 9999
	vsParBias = 1000000
)

// boardKey orders a hole's board by each player's best v: fewest strokes,
// then the first to make them (a best's shots are public: whoever replays
// them ties it and ranks after), then the address.
func boardKey(v any, player string) string {
	at, _, _ := bestFields(v)
	return pad(bestStrokes(v), 3) + "/" + pad(int(at), 12) + "/" + player
}

// boardStrokes is the strokes of a board's key: always its three digits.
func boardStrokes(k string) int {
	n, err := strconv.Atoi(k[:3])
	if err != nil {
		panic("golf: bad board key: " + k) // pad writes three digits: cannot happen
	}
	return n
}

// setRow moves a player's standing, as of height at, and keeps the ranking
// in step. A standing with no hole left is not freed, nor its key, which
// moves to idle: its deposit is the player's, and freeing it would refund
// whoever drained it. It moves back at the player's next hole.
func setRow(m int, r *row, holes, strokes, par int, at int64) {
	k := rankKey(r)
	_, had := ranks[m].Remove(k)
	if _, ok := idle[m].Remove(k); ok {
		had = true
	}
	r.holes, r.strokes, r.par, r.height = holes, strokes, par, at
	switch {
	case r.holes > 0 && named(r.player):
		ranks[m].Set(rankKey(r), r.player)
	case had:
		idle[m].Set(rankKey(r), r.player)
	}
}

// improve moves a player's standing by a new best on an official hole of par
// par (was: their old best there, 0 if none): only those count, or anyone's
// own hole would be a way to the top. The standing is kept, not recomputed,
// so a finish costs the same however many play.
func improve(m int, player string, par, was, best int) {
	r := &row{player: player}
	if v := totals[m].Get(player); v != nil {
		r = v.(*row)
	} else {
		totals[m].Set(player, r)
	}
	if was == 0 {
		setRow(m, r, r.holes+1, r.strokes+best, r.par+par, runtime.ChainHeight())
	} else {
		setRow(m, r, r.holes, r.strokes+best-was, r.par, runtime.ChainHeight())
	}
}

// retire archives an official hole replaced by next. Its bests stay there as
// its records but leave the course standings, in batches (drain): the Publish
// takes retireBatch, each course finish finishBatch, a Drain up to drainMax.
func retire(old *entry, next string) {
	old.next, old.out = next, &draining{}
	archived.Set(recentKey(runtime.ChainHeight(), old.id), old.id)
	archiving = append(archiving, old.id)
	chain.Emit(EventHoleRetired, "hole", old.id, "next", next)
	drain(retireBatch)
}

// How many archived players a Publish, a course finish and a Drain take out
// of the standings: sized so none costs more however many played.
const (
	retireBatch = 150
	finishBatch = 4
	drainMax    = 400
)

// drain takes up to n archived players out of the standings, oldest
// archived hole first.
func drain(n int) {
	for n > 0 && len(archiving) > 0 {
		e := find(archiving[0])
		d := e.out
		for m := 0; m < modes && n > 0; m++ {
			if d.done[m] {
				continue
			}
			stopped := e.bests(m).Iterate(d.from[m], "", func(p string, v any) bool {
				if n == 0 {
					d.from[m] = p
					return true
				}
				if d.fresh[m] == nil || !d.fresh[m].Has(p) {
					if t := totals[m].Get(p); t != nil {
						r := t.(*row)
						setRow(m, r, r.holes-1, r.strokes-bestStrokes(v), r.par-e.par, r.height)
					}
				}
				n--
				return false
			})
			if !stopped {
				d.done[m] = true
			}
		}
		if d.done[assisted] && d.done[pro] {
			if len(archiving) == 1 {
				archiving = nil // the backing array goes with it
			} else {
				archiving = archiving[1:]
			}
		}
	}
}

// Drain takes up to n players (1 to 400) of archived holes out of the course
// standings, sooner than the finishes would, and returns how many archived
// holes still have players in them. Anyone can call it. A standing it
// empties is kept at 0 holes (setRow): nothing is refunded to the caller.
func Drain(cur realm, n int) int {
	if n < 1 {
		n = 1
	}
	if n > drainMax {
		n = drainMax
	}
	drain(n)
	return len(archiving)
}

// counts reports whether a best on e by player (was: their previous best, 0
// if none) moves their standing: e is a current official hole, or an archived
// one whose drain has not reached them yet and where they already counted. A
// first finish on an archived hole never counts.
func counts(e *entry, m int, player string, was int) bool {
	if !e.official {
		return false
	}
	if e.next == "" {
		return true
	}
	if was == 0 || e.out.done[m] || player < e.out.from[m] {
		return false
	}
	return e.out.fresh[m] == nil || !e.out.fresh[m].Has(player)
}

// Launch plays one shot of the caller's round on hole (an exact id): angle in
// degrees (0 = right, 90 = down), power in (0, 10]. It is how gnoweb plays,
// with no aim preview, so its rounds are pro rounds. It answers with where
// the ball stopped, or the score if holed; PlayRoundAt commits many shots.
func Launch(cur realm, hole string, angle, power float64) string {
	e := mustHole(hole)
	h := e.hole()
	player := cur.Previous().Address()
	r := roundOf(e, h, player)
	fresh := r.strokes == 0
	if fresh {
		r.period = Period() // a round starts in the weather of the moment, and keeps it
		r.mode = pro
	} else if r.mode != pro {
		panic(otherMode(r))
	}

	fc := weatherOf(e, h, r.period)
	w := newWork(h, fc.Zones)
	w.fixed = fixedGas(e, fc)
	w.next(h)
	shot, holed := stroke(e, h, r, player, angle, power, 0, fc.Zones)
	w.add(shot)
	if holed {
		return ufmt.Sprintf("Holed in %d on %s! Your best there: %s:%s/%s", r.strokes, e.id, hub, e.id, player.String())
	}
	if fresh {
		e.roundTree().Set(player.String(), r)
	}
	// what a gnoweb player needs for the next shot
	a, d := aim(r.ball(), h.Cup())
	return ufmt.Sprintf("Stroke %d on %s: the ball stopped %.1f from the cup, which is at %.0f° from it. Your round: %s:%s/%s",
		r.strokes, e.id, d, a, hub, e.id, player.String())
}

// aim is the angle, in the shot's degrees, and the straight-line distance
// from a ball to the cup: walls and slopes are the player's to allow for.
func aim(from, cup physics.Vec2) (float64, float64) {
	d := cup.Sub(from)
	a := math.Atan2(d.Y, d.X) * 180 / math.Pi
	if a < 0 {
		a += 360
	}
	return a, d.Len()
}

// PlayRound is PlayRoundAt in the current period, for a caller with none to
// give (a form, a script); a round under way keeps its own. Prefer
// PlayRoundAt: a commit included after the weather turned is then played in
// the weather its shots were chosen in.
func PlayRound(cur realm, hole string, shots string) string {
	e, p := mustHole(hole), cur.Previous().Address()
	period := Period()
	if v := e.roundTree().Get(p.String()); v != nil { // (a round is kept from its first stroke on)
		period = v.(*round).period // stroke() still refuses a stale one
	}
	return playRound(e, p, shots, period, assisted)
}

// PlayRoundAt replays shots into the caller's assisted round on hole (an
// exact id), continuing it, in the weather of period: the current one or the
// one before, and a round under way keeps its own. The client sends
// decisions, never outcomes: the chain replays them.
//
// shots is "angle,power[,tick];…" (MsgCall carries no slice), at most 12,
// fewer on a heavy hole: a commit past the work budget is refused with the
// number of shots that fit, and the rest goes in the next commit.
func PlayRoundAt(cur realm, hole string, shots string, period int64) string {
	return playRound(mustHole(hole), cur.Previous().Address(), shots, period, assisted)
}

// PlayRoundPro is PlayRoundAt for a round played in pro mode: the aim
// preview cut short. It counts on the pro records and rankings only.
func PlayRoundPro(cur realm, hole string, shots string, period int64) string {
	return playRound(mustHole(hole), cur.Previous().Address(), shots, period, pro)
}

func playRound(e *entry, player address, shots string, period int64, mode int) string {
	h := e.hole()
	r := roundOf(e, h, player)
	fresh := r.strokes == 0
	if fresh {
		playablePeriod(period)
		r.period, r.mode = period, mode
	} else if r.period != period {
		panic(ufmt.Sprintf("golf: this round is being played in the weather of period %d", r.period))
	} else if r.mode != mode {
		panic(otherMode(r))
	}

	list := shotList(shots)
	fc := weatherOf(e, h, r.period) // once for the whole commit
	weather := fc.Zones
	w := newWork(h, weather)
	w.fixed = fixedGas(e, fc)
	for _, s := range list {
		w.next(h)
		angle, power, tick := parseShot(s)
		shot, holed := stroke(e, h, r, player, angle, power, tick, weather)
		w.add(shot)
		if holed {
			return ufmt.Sprintf("holed in %d strokes", r.strokes)
		}
	}
	if fresh { // under way: stored from its first commit
		e.roundTree().Set(player.String(), r)
	}
	return ufmt.Sprintf("%d shots replayed, ball at %.1f,%.1f after %d strokes",
		w.played, r.bx, r.by, r.strokes)
}

// otherMode refuses to go on with a round in a mode it was not started in.
func otherMode(r *round) string {
	return "golf: this round is being played in " + modeNames[r.mode] + " mode"
}

// shotList is a commit's shots: the non-empty entries of "a,p;a,p;…", at
// least one and at most maxShots.
func shotList(shots string) []string {
	var list []string
	for _, s := range strings.Split(shots, ";") {
		if s = strings.TrimSpace(s); s == "" {
			continue
		}
		if len(list) == maxShots {
			panic("golf: too many shots in one commit")
		}
		list = append(list, s)
	}
	if len(list) == 0 {
		panic("golf: no shots")
	}
	return list
}

// work is a commit's estimated gas so far. A shot counts the larger of its
// path's estimate and its Shot.Work's, plus its pulses' set-up, on top of
// what the commit spent before its shots (fixed: decoding, forecast). A shot
// that could pass workBudget is refused before anything is kept, and each is
// played under a work cap (physics.Field.Cap), so no commit can pass it; the
// client mirrors the model. An estimate, not a gas meter: see docs/golf.md,
// "The work budget".
type work struct {
	walls, pieces int64 // on the board this commit: walls, and every piece and polygon edge
	setup         int64 // what each shot spends outside its Shot.Work: a pulse's pieces, set up afresh
	bound         int64 // shotBound, and the set-up
	fixed         int64 // spent before the shots: decoding, forecast
	spent, most   int64
	played        int
	cap           int // the work cap of the shot being played
}

// The budget: of the 2e9 gas a wallet lets a transaction simulate, 1.4e9 for
// a commit, decoding and forecast included; the rest for package loads and
// bookkeeping.
const (
	workBudget   = 1400000000
	workPerShot  = 10000000
	workPerWall  = 150000
	workPerPoint = 1200000
	workPerPiece = 15000
	workPerUnit  = 1000
	// a pulse's walls and posts, set up afresh for each shot outside its
	// Shot.Work
	workPerPulseWall = 700000
	workPerPulsePost = 200000
)

// Decoding a hole's data costs at most decodeBase and decodePerByte a byte.
const (
	decodeBase    = 6000000
	decodePerByte = 4000
)

// fixedGas is what a commit on e spends before its shots, in the forecast
// fc: decoding the hole, and drawing the forecast.
func fixedGas(e *entry, fc course.Forecast) int64 {
	return decodeGas(len(holeData.Get(e.id).(string))) + int64(fc.Work)*workPerUnit
}

// decodeGas bounds decoding size bytes of a hole's data.
func decodeGas(size int) int64 { return decodeBase + decodePerByte*int64(size) }

// maxShotGas bounds a hole's heaviest shot (shotBound and its pulses'
// set-up): a hole past it is refused at publish.
const maxShotGas = 1300000000

// minShotWork is the work, in the physics' units, a commit's first shot may
// always do whatever the weather: four fifths of MaxWork. A shot is capped at
// what is left of the budget (work.next), so a hole whose dearest weather
// would leave less is refused at publish (worstGas): on a published hole,
// every shot of less than minShotWork plays out in any weather (as a commit's
// first, if need be), and an author whose board is too heavy is told at
// publish, not by a hole that misbehaves in the rain. A shot past it may be
// cut short; none is known: the course's heaviest real shot does 441,737
// over the full grid of tee shots (mountain/16, full power, in a storm), and
// the heaviest found in an adversarial search 0.74 of MaxWork (docs/golf.md);
// the course's tightest room in its dearest weather is 839,278 (mountain/7),
// 39,278 over the floor.
const minShotWork = 4 * physics.MaxWork / 5

// worstGas is what a commit on h (size bytes of data) spends up to a first
// shot of minShotWork in its dearest weather: decoding, the forecast at its
// most (course.WorstForecastWork), and the shot, its walls and its pulses'
// set-up, as work.next caps it.
func worstGas(h *course.Simple, size int) int64 {
	w := newWork(h, nil)
	return decodeGas(size) + int64(course.WorstForecastWork(h))*workPerUnit +
		workPerShot + w.walls*workPerWall + w.setup + (physics.MaxWorkStep+minShotWork)*workPerUnit
}

// newWork is a commit's work on a hole, before any shot: its walls and
// pieces, a pulse's as if always there, and the weather's.
func newWork(h *course.Simple, weather []physics.Zone) *work {
	w := &work{}
	if f := h.Field(); f != nil {
		w.walls = int64(len(f.Walls))
		w.pieces = pieces(f.Walls, f.Posts, f.Zones)
	}
	for _, p := range h.Pulses {
		w.walls += int64(len(p.Walls))
		w.pieces += pieces(p.Walls, p.Posts, p.Zones)
		w.setup += int64(len(p.Walls))*workPerPulseWall + int64(len(p.Posts))*workPerPulsePost
	}
	w.pieces += pieces(nil, nil, weather)
	w.bound = shotBound(w.walls) + w.setup
	return w
}

// shotBound is the most one shot on a board of walls walls can cost: the
// physics ends a stroke at MaxWork, passing it by MaxWorkStep at most.
func shotBound(walls int64) int64 {
	return workPerShot + walls*workPerWall + (physics.MaxWork+physics.MaxWorkStep)*workPerUnit
}

// pieces counts what a ball is tested against: each wall, post and zone, and
// each edge of a zone's polygon.
func pieces(ws []physics.Wall, ps []physics.Post, zs []physics.Zone) int64 {
	n := len(ws) + len(ps) + len(zs)
	for i := range zs {
		n += len(zs[i].Poly)
	}
	return int64(n)
}

// next refuses the next shot if it could overrun the budget, and caps its
// work at what is left of it.
func (w *work) next(h *course.Simple) {
	if w.played == 0 && w.bound > workBudget {
		w.refuse()
	}
	if w.played > 0 && w.spent+w.most > workBudget {
		w.refuse()
	}
	c := (workBudget-w.fixed-w.spent-workPerShot-w.walls*workPerWall)/workPerUnit - physics.MaxWorkStep
	c -= w.setup / workPerUnit
	if c < 1 {
		w.refuse()
	}
	if c > physics.MaxWork {
		c = physics.MaxWork
	}
	w.cap = int(c)
	if f := h.Field(); f != nil {
		f.Cap = w.cap // the decoded hole of this call only: never stored
	}
}

// refuse refuses the shot being played: it does not fit the budget.
func (w *work) refuse() {
	if w.played == 0 {
		panic(errShotTooHeavy)
	}
	panic(ufmt.Sprintf("golf: more shots than one transaction can replay on this hole: commit the first %d, then the rest", w.played))
}

func (w *work) add(s physics.Shot) {
	if w.cap < physics.MaxWork && s.Work > w.cap {
		w.refuse() // it reached its cap: it would have gone further
	}
	c := workPerShot + w.walls*workPerWall + int64(len(s.Path))*(workPerPoint+w.pieces*workPerPiece)
	if u := workPerShot + w.walls*workPerWall + int64(s.Work)*workPerUnit; u > c {
		c = u // a shot that did more than its path shows
	}
	c += w.setup
	w.spent += c
	if c > w.most {
		w.most = c
	}
	w.played++
}

// Reset abandons the caller's round under way on hole (an exact id), freeing
// its storage: the next stroke starts a new one from the tee. A finished round
// is not kept (its best is), so a new one needs no Reset. With no round under
// way it does nothing, and says nothing.
func Reset(cur realm, hole string) {
	e := mustHole(hole)
	player := cur.Previous().Address().String()
	if _, ok := e.roundTree().Remove(player); ok {
		chain.Emit(EventRoundReset, "hole", e.id, "player", player)
	}
}

// validShot refuses what would poison a round and returns the shot as
// recorded. NaN and infinities pass every comparison, so they are refused by
// name. The power is quantized before it is checked (0.00001 would round to
// 0). The angle is brought into (-360, 360), so a huge one cannot overflow to
// NaN in the physics, and again after rounding (-359.99996 is -0, not -360).
func validShot(angle, power float64) (float64, float64) {
	power = q4(power)
	if math.IsNaN(angle) || math.IsInf(angle, 0) || !(power > 0 && power <= maxPower) {
		panic(errShot)
	}
	angle = q4(math.Mod(angle, 360))
	if angle <= -360 || angle >= 360 {
		angle = math.Mod(angle, 360)
	}
	return angle, power
}

// resolve checks what the physics returned for a stroke: a path a read may
// print, and a ball that is a number. A hole is anyone's data.
func resolve(shot physics.Shot, holed bool) (physics.Shot, bool) {
	if len(shot.Path) > maxPath {
		panic("golf: the hole returned an oversized path")
	}
	rest := shot.Rest()
	if math.IsNaN(rest.X) || math.IsNaN(rest.Y) || math.IsInf(rest.X, 0) || math.IsInf(rest.Y, 0) {
		panic("golf: the hole returned a ball off the board")
	}
	return shot, holed
}

// back brings a ball that came to rest off the board (a leak in a hole's
// walls) back to from, where the shot started; the stroke counts, with no
// penalty. Every stroke golf plays or replays goes through it.
func back(h *course.Simple, from physics.Vec2, shot physics.Shot, holed bool) physics.Shot {
	rest := shot.Rest()
	w, hh := h.W, h.H
	if holed || len(shot.Path) == 0 || (rest.X >= 0 && rest.X <= float64(w) && rest.Y >= 0 && rest.Y <= float64(hh)) {
		return shot
	}
	// copies: the hole's own slices are the hole's
	shot.Path = append(append(make([]physics.Vec2, 0, len(shot.Path)+1), shot.Path...), from)
	shot.Air = append(append(make([]bool, 0, len(shot.Air)+1), shot.Air...), false)
	shot.Cause = append(append(make([]byte, 0, len(shot.Cause)+1), shot.Cause...), '-')
	return shot
}

// stroke resolves one shot into the round and reports whether it was holed.
func stroke(e *entry, h *course.Simple, r *round, player address, angle, power float64, tick int, weather []physics.Zone) (physics.Shot, bool) {
	if r.strokes >= maxRoundStrokes {
		panic(errStrokeLimit)
	}
	notOver(r.period) // every stroke, not only the first
	// played exactly as it is recorded, so the record replays
	angle, power = validShot(angle, power)

	from := r.ball()
	shot, holed := resolve(h.PreviewWith(from, angle*math.Pi/180, power, r.strokes, tick, weather))
	shot = back(h, from, shot, holed)
	w, hh := h.W, h.H
	e.mark(course.WearIndexOn(shot.Rest(), w, hh)) // where the round's ball is: back's, for a leak
	// the decisions, as played: what anyone needs to replay the round
	if r.shots != "" {
		r.shots += ";"
	}
	played := ufmt.Sprintf("%.4f,%.4f,%d", angle, power, tick)
	r.shots += played
	rest := shot.Rest()
	r.fx, r.fy, r.bx, r.by = from.X, from.Y, rest.X, rest.Y
	r.strokes++
	e.plays++

	if !holed {
		chain.Emit(EventShot, "hole", e.id, "player", player.String(),
			"strokes", strconv.Itoa(r.strokes), "mode", modeNames[r.mode], "shot", played)
		return shot, false
	}
	m, p := r.mode, player.String()
	// a player's best stays theirs: replaying the hole never erases it, and a
	// tie keeps the older round, shots and all
	best := e.bests(m).Get(p)
	if was := bestStrokes(best); was == 0 || r.strokes < was {
		if was > 0 {
			e.board(m).Remove(boardKey(best, p))
		}
		best = bestOf(r)
		e.bests(m).Set(p, best)
		if counts(e, m, p, was) {
			improve(m, p, e.par, was, r.strokes)
		} else if was == 0 && e.official && e.next != "" && !e.out.done[m] && p >= e.out.from[m] {
			// the drain has yet to reach this first finish: it was never
			// counted, so it must not be taken out
			if e.out.fresh[m] == nil {
				e.out.fresh[m] = avl.NewTree()
			}
			e.out.fresh[m].Set(p, true)
		}
	}
	if named(p) {
		seat(e, m, p, best)
	}
	if e.official {
		drain(finishBatch) // only the course's finishes pay for the course's drain
	}
	chain.Emit(EventHoled, "hole", e.id, "player", p,
		"strokes", strconv.Itoa(r.strokes), "mode", modeNames[m], "shots", r.shots)
	// the round is its best now, or no better than it: not kept (a round of
	// this commit's alone was never stored)
	e.roundTree().Remove(p)
	return shot, true
}

// seat puts a named player where their best puts them: on the hole's board,
// in its record if it tops it, and in the course ranking if they stand in it.
// Every finish does it, improved or not, so a player named since ranks.
func seat(e *entry, m int, p string, best any) {
	k := boardKey(best, p)
	if !e.board(m).Has(k) {
		e.board(m).Set(k, p)
	}
	// the record is a named player's (a throwaway address could hold it for
	// good) and the board's top, so a tie goes to the first to make it
	if n, rec := bestStrokes(best), e.rec(m); rec.best == 0 || n < rec.best ||
		n == rec.best && address(p) != rec.by && k < boardKey(e.bests(m).Get(rec.by.String()), rec.by.String()) {
		if m == pro {
			e.proBest, e.proBestBy = n, address(p)
		} else {
			e.best, e.bestBy = n, address(p)
		}
	}
	if v := totals[m].Get(p); v != nil && v.(*row).holes > 0 {
		if rk := rankKey(v.(*row)); !ranks[m].Has(rk) {
			idle[m].Remove(rk) // a standing parked while unnamed leaves idle as it ranks
			ranks[m].Set(rk, p)
		}
	}
}

// Claim ranks the caller's bests kept while they had no name: on the boards
// of the course's current holes, in both modes, and in the course ranking.
// It returns how many bests it seated, and refuses a caller with no gno.land
// name. It reads the course's holes only, so it costs the same for everyone.
func Claim(cur realm) int {
	p := cur.Previous().Address().String()
	if !named(p) {
		panic("golf: take a gno.land name first: only named players are ranked")
	}
	n := 0
	slots.Iterate("", "", func(_ string, v any) bool {
		e := find(v.(string))
		for m := 0; m < modes; m++ {
			if best := e.bests(m).Get(p); best != nil {
				seat(e, m, p, best)
				n++
			}
		}
		return false
	})
	return n
}

// maxRoundStrokes bounds a round's history (Round shows it); maxPath the path
// a hole may return for a stroke (an honest one: a few hundred points).
const (
	maxRoundStrokes = 60
	maxPath         = 512
)

// q4 rounds to the precision a shot is recorded at.
func q4(x float64) float64 { return math.Round(x*1e4) / 1e4 }

// maxTick bounds the third field of a shot: any timed piece turns in fewer.
const maxTick = 1023

// parseShot reads "angle,power" or "angle,power,tick". The tick is where the
// timed pieces were when the player let go (0 if absent), clamped to
// 0..maxTick.
func parseShot(s string) (float64, float64, int) {
	parts := strings.Split(s, ",")
	if len(parts) != 2 && len(parts) != 3 {
		panic(`golf: a shot is "angle,power" or "angle,power,tick", got: ` + s)
	}
	angle, err := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
	if err != nil {
		panic("golf: bad angle: " + s)
	}
	power, err := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
	if err != nil {
		panic("golf: bad power: " + s)
	}
	tick := 0
	if len(parts) == 3 {
		tick = clampTick(strings.TrimSpace(parts[2]), s)
	}
	return angle, power, tick
}

// clampTick reads a tick: an optional sign and digits, clamped to
// 0..maxTick, even past what an int holds.
func clampTick(t, shot string) int {
	digits := strings.TrimPrefix(strings.TrimPrefix(t, "-"), "+")
	if digits == "" {
		panic("golf: bad tick: " + shot)
	}
	for i := 0; i < len(digits); i++ {
		if digits[i] < '0' || digits[i] > '9' {
			panic("golf: bad tick: " + shot)
		}
	}
	if strings.HasPrefix(t, "-") {
		return 0
	}
	if digits = strings.TrimLeft(digits, "0"); len(digits) > 4 {
		return maxTick
	}
	n, err := strconv.Atoi("0" + digits)
	if err != nil {
		panic("golf: bad tick: " + shot) // digits only, at most 4: cannot happen
	}
	if n > maxTick {
		return maxTick
	}
	return n
}

// roundOf is the player's round under way on e, or a new one from the tee,
// not stored: its commit stores it if it does not finish it.
func roundOf(e *entry, h *course.Simple, player address) *round {
	if v := e.roundTree().Get(player.String()); v != nil {
		return v.(*round)
	}
	s := h.Start()
	return &round{bx: s.X, by: s.Y}
}

// maxName and maxNote bound a hole's name and a version's note.
const (
	maxName = 40
	maxNote = 140
)

// cleanName keeps a hole's name to one short line of plain text
// (cleanText), with at least a letter or a digit in it.
func cleanName(n string) string {
	s := cleanText(n, maxName)
	for _, c := range s {
		if unicode.IsLetter(c) || unicode.IsDigit(c) {
			return s
		}
	}
	return "Untitled hole"
}

// cleanText keeps an author's text to one line of plain text, at most max
// characters: no control, format (Cf: bidi, zero-width, tags) or nonspacing
// (Mn: stacked accents, variation selectors) characters, no blank-looking
// ones, nothing that ends a markdown table cell or opens a link, a tag, an
// HTML entity, a strikethrough, a mention or an email link.
func cleanText(n string, max int) string {
	b := make([]rune, 0, max)
	for _, c := range n {
		if len(b) >= max {
			break
		}
		switch {
		case c < 0x20 || c >= 0x7f && c < 0xa0:
			continue
		case c == 0xad, c == 0x34f, c == 0x61c, c == 0x115f, c == 0x1160, c == 0x17b4, c == 0x17b5, c == 0x180e,
			c >= 0x200b && c <= 0x200f, c >= 0x2028 && c <= 0x202e, c >= 0x2060 && c <= 0x206f,
			c == 0x2800, c == 0x3164, c >= 0xfe00 && c <= 0xfe0f, c == 0xfeff, c == 0xffa0,
			c >= 0xe0000 && c <= 0xe0fff:
			continue
		case unicode.In(c, unicode.Mn, unicode.Cf):
			// é typed as one (NFC) stays; combining marks (Devanagari, Thai) go
			continue
		case !unicode.IsPrint(c) && c != ' ':
			// what Go would print escaped (\U…), which JSON readers refuse
			continue
		case strings.ContainsRune("|[]<>`*_#\\&~@", c):
			continue
		}
		b = append(b, c)
	}
	// no bare link a page might make clickable (": /" keeps the length)
	return strings.TrimSpace(strings.ReplaceAll(string(b), "://", ": /"))
}

// maxSkin bounds a skin's length.
const maxSkin = 24

// cleanSkin keeps a skin to what it is meant to be: a short lower-case id.
func cleanSkin(s string) string {
	b := make([]byte, 0, maxSkin)
	for i := 0; i < len(s) && len(b) < maxSkin; i++ {
		c := s[i]
		if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == ' ' || c == '-' || c == '_' {
			b = append(b, c)
		}
	}
	return string(b)
}

owner.gno

package golf

import (
	"chain"
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"strings"
)

// The course's owner, the deployer, set at init: golf's only role. Every
// check is on the immediate caller (cur.Previous().Address()), never the
// signer, so a realm the owner calls cannot act in their name. The role
// passes by Transfer then Accept; Renounce freezes the course for good.
var (
	owner   address // "" once renounced
	pending address // the address a Transfer offered the role to, "" if none
)

// self is golf's own pkgpath, hub its gnoweb path: every link follows from
// them, so the same code serves under any namespace.
var (
	self           = unsafe.CurrentRealm().PkgPath()
	hub            = strings.TrimPrefix(self, "gno.land")
	officialPrefix = self[:strings.LastIndex(self, "/")+1] // the namespace's realms, as "…/"
)

// playURL is the 3D client every page links to (SetPlayURL moves it).
var playURL = "https://gnogolf.xyz/"

// successor is the realm that took this course over, "" until the owner
// names it, once (SetSuccessor).
var successor string

func init() { setUp(unsafe.OriginCaller(), runtime.ChainID()) }

// setUp is init: the deployer owns the course, and community publishing
// starts closed. Only `gno test` (chain "dev") runs it with no signer: the
// owner stays "", which holds no power, and publishing starts open, since
// nobody there could open it.
func setUp(deployer address, chainID string) {
	if deployer == "" && chainID != "dev" {
		panic("golf: no owner: golf must be deployed by an account")
	}
	owner, publishing = deployer, deployer == ""
}

// Owner is the course's owner, "" once renounced.
func Owner() address { return owner }

// Pending is the address a Transfer offered the role to, "" if none.
func Pending() address { return pending }

// Successor is the realm that took this course over, "" if none.
func Successor() string { return successor }

// isOwner is the one owner check: a live role, held by the caller.
func isOwner(caller address) bool { return owner != "" && caller == owner }

// Transfer offers the role to another address, which takes it with Accept.
// Offering it to the owner themselves cancels an offer.
func Transfer(cur realm, to address) {
	if !isOwner(cur.Previous().Address()) {
		panic("golf: only the owner can transfer the course")
	}
	if !to.IsValid() {
		panic("golf: not an address: " + to.String())
	}
	if to == owner {
		pending = ""
		chain.Emit(EventOwnershipOfferCancelled, "owner", owner.String())
		return
	}
	pending = to
	chain.Emit(EventOwnershipOffered, "owner", owner.String(), "to", to.String())
}

// Accept takes the role a Transfer offered the caller.
func Accept(cur realm) {
	caller := cur.Previous().Address()
	if owner == "" || pending == "" || caller != pending {
		panic("golf: no transfer of the course is offered to you")
	}
	from := owner
	owner, pending = caller, ""
	chain.Emit(EventOwnershipTransfer, "from", from.String(), "to", owner.String())
}

// Renounce gives the role up for good: no owner, no offer, and none possible.
func Renounce(cur realm) {
	if !isOwner(cur.Previous().Address()) {
		panic("golf: only the owner can renounce the course")
	}
	from := owner
	owner, pending = "", ""
	chain.Emit(EventOwnershipRenounced, "from", from.String())
}

// maxURL bounds the play link, maxPkgPath a successor's pkgpath.
const (
	maxURL     = 100
	maxPkgPath = 100
)

// SetPlayURL moves the link every page gives to the 3D client. Only the
// owner can. url is https://, at most 100 of letters, digits and "-._~/:%",
// with no query or fragment: a hole's link adds "?cup=…&hole=…" to it.
func SetPlayURL(cur realm, url string) {
	if !isOwner(cur.Previous().Address()) {
		panic("golf: only the owner can move the play link")
	}
	if !validURL(url) {
		panic("golf: a play link is https:// and up to 100 of a-z, A-Z, 0-9 and -._~/:%")
	}
	playURL = url
	chain.Emit(EventPlayURLSet, "url", url)
}

func validURL(u string) bool {
	if len(u) > maxURL || !strings.HasPrefix(u, "https://") || len(u) == len("https://") {
		return false
	}
	for i := 0; i < len(u); i++ {
		c := u[i]
		if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.IndexByte("-._~/:%", c) >= 0) {
			return false
		}
	}
	return true
}

// SetSuccessor names the realm that takes this course over, once and for
// good: a pkgpath under gno.land/r/, not golf itself, with no "", "." or ".."
// segment. Only the owner can. It moves and blocks nothing: the pages and
// Holes say where the course went, and play goes on here. golf does not check
// the realm exists: check the path before sending.
func SetSuccessor(cur realm, pkgpath string) {
	if !isOwner(cur.Previous().Address()) {
		panic("golf: only the owner can name a successor")
	}
	if successor != "" {
		panic("golf: the successor is already " + successor)
	}
	if !validPkgPath(pkgpath) || pkgpath == self {
		panic("golf: a successor is a realm's pkgpath, gno.land/r/ and up to 100 of a-z, 0-9 and _-/.")
	}
	successor = pkgpath
	chain.Emit(EventSuccessorSet, "successor", pkgpath)
}

// Hide takes a community hole ("<address>/<slug>", every version) off the
// lists (the hub, Holes, the 3D game), for a scam or abuse in its name or
// note; hide=false puts it back. Only the owner can. Its data, rounds and
// page stay, Community still has it, and a new version stays hidden. A hole
// already as asked is left alone, with no event.
func Hide(cur realm, slot string, hide bool) {
	if !isOwner(cur.Previous().Address()) {
		panic("golf: only the owner can hide a hole")
	}
	v := aliases.Get(slot)
	if v == nil {
		if e := find(slot); e != nil && !e.official {
			panic("golf: " + slot + " is a version: hide its hole, " + e.slot)
		}
		panic("golf: " + slot + " is not a community hole")
	}
	if hidden.Has(slot) == hide {
		return
	}
	// out of byAuthor, all the lists walk: they never read a hidden hole
	e := find(v.(string))
	a := e.by.String()
	row := a + " " + recentKey(e.height, slot[len(a)+1:])
	was := newestRow(a)
	if hide {
		hidden.Set(slot, true)
		byAuthor.Remove(row)
	} else {
		hidden.Remove(slot)
		byAuthor.Set(row, e.id)
	}
	moveAuthor(a, was, newestRow(a))
	chain.Emit(EventHoleHidden, "slot", slot, "hidden", strconv.FormatBool(hide))
}

// publishing is whether anyone can publish a community hole (PublishMine):
// closed at deploy (setUp), opened later without a redeploy.
var publishing bool

// Publishing is whether PublishMine is open.
func Publishing() bool { return publishing }

// SetPublishing opens community publishing (PublishMine) or closes it again.
// Only the owner can. Closing stops new holes and versions only: every hole
// published stays playable and listed. Setting it as it is does nothing.
func SetPublishing(cur realm, open bool) {
	if !isOwner(cur.Previous().Address()) {
		panic("golf: only the owner can open or close publishing")
	}
	if publishing == open {
		return
	}
	publishing = open
	chain.Emit(EventPublishingSet, "open", strconv.FormatBool(open))
}

func validPkgPath(p string) bool {
	if len(p) > maxPkgPath || !strings.HasPrefix(p, "gno.land/r/") {
		return false
	}
	for _, seg := range strings.Split(p[len("gno.land/r/"):], "/") {
		if seg == "" || seg == "." || seg == ".." {
			return false
		}
	}
	for i := 0; i < len(p); i++ {
		c := p[i]
		if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.IndexByte("_-/.", c) >= 0) {
			return false
		}
	}
	return true
}

// The events golf emits, and their attributes. A hole is always "hole", a
// player "player".
const (
	EventHolePublished           = "HolePublished"           // hole, slot, sha, by, official ("true"/"false")
	EventHoleRetired             = "HoleRetired"             // hole, next
	EventShot                    = "Shot"                    // hole, player, strokes, mode, shot ("angle,power,tick" as recorded)
	EventHoled                   = "Holed"                   // hole, player, strokes, mode, shots (the round's)
	EventRoundReset              = "RoundReset"              // hole, player
	EventOwnershipOffered        = "OwnershipOffered"        // owner, to
	EventOwnershipOfferCancelled = "OwnershipOfferCancelled" // owner
	EventOwnershipTransfer       = "OwnershipTransfer"       // from, to
	EventOwnershipRenounced      = "OwnershipRenounced"      // from
	EventPlayURLSet              = "PlayURLSet"              // url
	EventSuccessorSet            = "SuccessorSet"            // successor
	EventHoleHidden              = "HoleHidden"              // slot, hidden ("true"/"false")
	EventPublishingSet           = "PublishingSet"           // open ("true"/"false")
)

render.gno

package golf

import (
	"encoding/hex"
	"math"
	"strconv"
	"strings"
	"time"

	"gno.land/p/nym-alexiscolin000/gnogolf/course"
	"gno.land/p/nym-alexiscolin000/gnogolf/physics"
	"gno.land/p/nt/ufmt/v0"
)

// wearRunes draw a cell's wear: none, then up to wearLight, wearWorn and
// wearGroove balls come to rest there, and past.
const (
	wearRunes  = " :;x%" // pristine grass blank: a shot's dots stand out on it
	wearLight  = 2
	wearWorn   = 6
	wearGroove = 14
)

// maxTunnels is how many tunnels the board numbers, 1 to 9.
const maxTunnels = 9

const (
	markWall = '#'
	markPost = '0'
	markCup  = 'U' // not O: in gnoweb's font O and the post's 0 look alike
	markTee  = '*'
)

// Render is the game as text: gnoweb draws the board and submits the shot.
//
// Paths: "" the hub; "<world>" a cup's holes; "<address>" the holes an
// address published; "<hole>" a hole's page, "<hole>/<address>" the same
// with that player's ball, "<hole>/data" a version's provenance and data.
// <hole> is a version's id or an alias. A query string ("?…") is ignored.
func Render(path string) string {
	if i := strings.IndexByte(path, '?'); i >= 0 {
		path = path[:i]
	}
	if path == "" {
		return renderHub()
	}
	if e := lookup(path); e != nil {
		return renderHole(e, e.hole(), "")
	}
	// the segments of a hole's path, which gnoweb links one by one
	if course.IsWorld(path) {
		return renderCup(path)
	}
	if address(path).IsValid() {
		return renderAuthor(address(path))
	}
	// the id has slashes of its own, so what trails it is looked at last
	if i := strings.LastIndex(path, "/"); i >= 0 {
		head, tail := path[:i], path[i+1:]
		if e := lookup(head); e != nil {
			if address(tail).IsValid() {
				return renderHole(e, e.hole(), address(tail))
			}
			if tail == "data" {
				return renderData(e)
			}
		}
	}
	return noSuch(path)
}

// noSuch is the page for a path that is no hole, cup or address.
func noSuch(path string) string {
	what := "That page"
	if c := cleanText(path, maxName); c != "" {
		what = "`" + c + "`"
	}
	return "# No such hole\n\n> [!WARNING]\n> " + what + " is not a hole here. " + md("See every hole", hub) + ".\n"
}

// lookup is readHole that answers nil for no hole.
func lookup(id string) *entry {
	if e := find(id); e != nil {
		return e
	}
	return find(current(id))
}

// playLink is the 3D client's link to this hole: a current course hole by cup
// and order, any other by its id, which no newer version can take.
func playLink(e *entry) string {
	if !e.official || e.next != "" {
		return playURL + "?hole=" + e.id
	}
	return playURL + "?cup=" + e.world + "&hole=" + strconv.Itoa(int(e.order))
}

// cupName is how a world is called on the page.
func cupName(w string) string {
	if r := worldRank(w); r < len(worlds) {
		return worlds[r].name
	}
	if w == "" {
		return "Holes"
	}
	return strings.ToUpper(w[:1]) + w[1:]
}

// who is a player as a link to their gno.land profile.
func who(addr string) string { return md(short(addr), "/u/"+addr) }

func renderHub() string {
	var sb strings.Builder
	sb.WriteString("# Gnogolf — mini-golf on-chain\n\n" + moved() +
		"The course is data its owner published, anyone can add holes of their own, and the chain computes every shot: nobody can fake a score.\n\n" +
		"> [!TIP] How to play\n" +
		"> **In 3D:** " + md("open the game", playURL) + ". Aim with a free preview, then record your round in a transaction (a long one in a few).\n>\n" +
		"> **Here, one shot at a time:** open a hole, fill its Launch form (an angle and a power) and sign it with your gno.land wallet (" + md("Adena", "https://adena.app") + "), then add `/<your address>` to the hole's URL to see your ball.\n>\n" +
		"> Only players with a gno.land name are ranked.\n\n")
	var archived, others []*entry
	type cup struct {
		world      string
		holes, par int
		top        *entry
	}
	var cups []*cup
	for _, e := range listed() {
		switch {
		case e.official && e.next == "":
			// one column per cup: nothing here calls a hole
			if len(cups) == 0 || cups[len(cups)-1].world != e.world {
				cups = append(cups, &cup{world: e.world})
			}
			c := cups[len(cups)-1]
			c.holes++
			c.par += e.par
			if e.plays > 0 && (c.top == nil || e.plays > c.top.plays) {
				c.top = e
			}
		case e.official:
			archived = append(archived, e)
		default:
			others = append(others, e)
		}
	}
	if len(cups) == 0 {
		sb.WriteString("_No course hole yet._\n\n")
	} else {
		// a column a cup, so they all fit one row (gnoweb's columns wrap past four)
		head, rule, sizes, tops := "| ", "|---", "| holes · par", "| most played"
		for _, c := range cups {
			top := "—"
			if c.top != nil {
				top = c.top.name
			}
			head += " | " + md(cupName(c.world), hub+":"+c.world)
			rule += "|---"
			sizes += " | " + strconv.Itoa(c.holes) + " · " + strconv.Itoa(c.par)
			tops += " | " + top
		}
		sb.WriteString(head + " |\n" + rule + "|\n" + sizes + " |\n" + tops + " |\n\n")
	}

	sb.WriteString("## Leaderboard\n\nEach named player's best finish on each current hole of the course, added up: most holes first, then the best score against par (each hole's strokes less its par, added up: a hole at par counts the same whatever its par). " +
		"Assisted rounds (played with the 3D game's aim line) and pro rounds (without it, on the player's word; every round played on this page is pro) are ranked apart.\n\n")
	for m := 0; m < modes; m++ {
		sb.WriteString("### " + modeTitles[m] + "\n\n")
		rows, i := "", 0
		eachRanked(m, func(r *row, name string) {
			i++
			rows += "| " + strconv.Itoa(i) + " | " + md("@"+name, "/u/"+name) + " | " + strconv.Itoa(r.holes) + " | " + vsPar(r.strokes-r.par) + " |\n"
		})
		if rows == "" {
			sb.WriteString("_Nobody has finished a hole of the course yet._\n\n")
			continue
		}
		sb.WriteString("| rank | player | holes | vs par |\n|---|---|---|---|\n" + rows + "\n")
	}

	sb.WriteString("## Community holes\n\nAnyone can publish a hole of their own with PublishMine while the owner keeps publishing open. These are not part of the course: they have no cup and do not count in its ranking.\n\n")
	switch {
	case len(others) > 0:
	case publishing:
		sb.WriteString("_None yet. Publish yours with " + md("PublishMine", hub+"$help&func=PublishMine") + "._\n")
	default:
		sb.WriteString("_None yet: publishing opens with the game's hole builder._\n")
	}
	names := map[string]string{} // the record holders' names, read once each (bestCell)
	if len(others) > 0 {
		sb.WriteString("| hole | by | par | best | shots played |\n|---|---|---|---|---|\n")
		for _, e := range others {
			sb.WriteString("| " + md(e.name, hub+":"+e.slot) + " | " + md(short(e.by.String()), hub+":"+e.by.String()) + " | " + strconv.Itoa(e.par) + " | " + bestCell(e, names) + " | " +
				strconv.Itoa(e.plays) + " |\n")
		}
	}
	if len(archived) > 0 {
		sb.WriteString("\n## Archived course holes\n\nA newer version took each one's place in its cup. They can still be played, and keep their records, but no longer count in the course-wide ranking. Every version of a slot is on its data page.\n\n" +
			"| hole | version | par | best | shots played | now |\n|---|---|---|---|---|---|\n")
		for _, e := range archived {
			sb.WriteString("| " + md(e.name, hub+":"+e.id) + " | " + e.id + " | " + strconv.Itoa(e.par) + " | " + bestCell(e, names) + " | " +
				strconv.Itoa(e.plays) + " | " + md(e.next, hub+":"+e.next) + " |\n")
		}
	}
	sb.WriteString(noAdmin())
	return sb.String()
}

// moved is the banner a course taken over shows on every page.
func moved() string {
	if successor == "" {
		return ""
	}
	return "> [!NOTE] This course has moved\n> Its successor is " + md(successor, strings.TrimPrefix(successor, "gno.land")) +
		". Everything here still plays and keeps its records.\n\n"
}

// renderCup is a cup's page: its current holes, in order.
func renderCup(world string) string {
	var sb strings.Builder
	sb.WriteString("# " + cupName(world) + "\n\n" + moved())
	k := slotKey(world, 0)
	k = k[:len(k)-3] // the world's slots are the keys "<rank><world>/…"
	n, names := 0, map[string]string{}
	slots.Iterate(k, k[:len(k)-1]+"0", func(_ string, v any) bool {
		e := find(v.(string))
		if n == 0 {
			sb.WriteString("| # | hole | par | best | shots played |\n|---|---|---|---|---|\n")
		}
		n++
		sb.WriteString("| " + strconv.Itoa(int(e.order)) + " | " + md(e.name, hub+":"+e.slot) + " | " + strconv.Itoa(e.par) + " | " +
			bestCell(e, names) + " | " + strconv.Itoa(e.plays) + " |\n")
		return n >= maxListed
	})
	if n == 0 {
		return noSuch(world)
	}
	return sb.String() + "\n" + md("Every cup", hub) + "\n"
}

// renderAuthor is the holes an address published, as their current versions.
func renderAuthor(a address) string {
	var sb strings.Builder
	sb.WriteString("# Community holes by " + who(a.String()) + "\n\n" + moved())
	n, names := 0, map[string]string{}
	aliases.Iterate(a.String()+"/", a.String()+"0", func(k string, v any) bool {
		if hidden.Has(k) {
			return false // off the lists, as Hide says: this page is one
		}
		e := find(v.(string))
		if n == 0 {
			sb.WriteString("| hole | versions | par | best | shots played | data |\n|---|---|---|---|---|---|\n")
		}
		n++
		sb.WriteString("| " + md(e.name, hub+":"+e.slot) + " | " + strconv.Itoa(e.version) + " | " + strconv.Itoa(e.par) + " | " +
			bestCell(e, names) + " | " + strconv.Itoa(e.plays) + " | " + source(e) + " |\n")
		return n >= pageMax
	})
	if n == 0 {
		sb.WriteString("_This address has published no community hole._\n")
	}
	return sb.String() + "\n" + md("Every hole", hub) + "\n"
}

// bestCell is a hole's records, assisted then pro, for a table cell. names
// caches holders: r/sys/users is read once a player, not once a record.
func bestCell(e *entry, names map[string]string) string {
	best := ""
	for m := 0; m < modes; m++ {
		if r := e.rec(m); r.best > 0 {
			if best != "" {
				best += " · "
			}
			by := r.by.String()
			name, ok := names[by]
			if !ok {
				name = byName(by)
				names[by] = name
			}
			best += ufmt.Sprintf("%s %d, %s", modeNames[m], r.best, name)
		}
	}
	if best == "" {
		return "—"
	}
	return best
}

// weatherNote is the hole's weather now (f, the forecast of this period) and
// how long it lasts, on a hole's own page.
func weatherNote(f course.Forecast) string {
	left := PeriodSeconds - time.Now().Unix()%PeriodSeconds
	what := "Clear"
	switch f.Kind {
	case course.Wind:
		a, _ := aim(physics.Vec2{}, f.Wind)
		what = ufmt.Sprintf("Wind toward **%.0f°**: it pushes every roll that way", a)
	case course.Rain:
		what = "Rain: the green runs fast, and puddles slow the ball"
	case course.Fog:
		what = "Fog: it hides nothing here, and does not touch the ball"
	case course.Storm:
		what = "Storm: rain, puddles and wind"
	case course.Snow:
		what = "Snow: the green runs slow"
	}
	// ufmt has no width: the seconds padded by hand
	return ufmt.Sprintf("> [!NOTE] Weather now\n> %s — for %d min %s s more. A round keeps the weather it started in, and can be played on until the next weather is over: after that it must be Reset.\n\n",
		what, left/60, pad(int(left%60), 2))
}

// noAdmin states who can change what, the owner's own powers included.
func noAdmin() string {
	holder := who(owner.String())
	if owner == "" {
		holder = "nobody: the role was given up, and the course is frozen for good"
	}
	return "\n> [!INFO]- Who can change what\n" +
		"> Anyone can play (Launch, PlayRound, PlayRoundAt, PlayRoundPro), Reset their own round, " +
		"publish holes of their own (PublishMine) while publishing is open, and settle the ranking sooner (Drain). Nobody can edit or delete a round, a record, a best, a standing or a published version, " +
		"and nobody can pause or upgrade this realm. Every hole is data, played by golf's own physics: no hole runs code of its own. Check it yourself: " + md("the source", hub+"$source") + ".\n>\n" +
		"> One party holds a real power: the course's owner, now " + holder + ". The owner publishes the course holes and their new versions (Publish). " +
		"A new version takes its slot: the old one is archived, still playable, its records kept, but its bests leave the course-wide ranking, which the new version starts afresh. " +
		"So the owner shapes the course, and through it the ranking, and a stolen owner key could archive every slot, for good. " +
		"A version identical to the current one is refused, but a replacement can still be unplayable: a hole can be replaced, never taken down. " +
		"When a version is published picks its id, and its id seeds its weather. " +
		"The owner also sets where the pages link the 3D game (SetPlayURL), and can name, once and for good, a successor this course has moved to (SetSuccessor): a banner, which blocks nothing. " +
		"Whoever holds `" + strings.TrimPrefix(officialPrefix, "gno.land/") + "` can deploy lookalike realms under it. " +
		"The owner can take a community hole off the lists (Hide: a scam or abuse in its name or note), and put it back; it stays playable, its page and data kept. " +
		"The owner opens community publishing and can close it again (SetPublishing): closed, nobody adds a hole or a version, and every hole published plays on. " +
		"The owner cannot edit or remove a version, change a community hole, the weather, the physics or this code, " +
		"and can only hand the role on (Transfer, then Accept) or give it up for good (Renounce).\n"
}

// source links a hole's data page: read it before trusting it with a round.
func source(e *entry) string { return md("data", hub+":"+e.id+"/data") }

func md(label, href string) string { return "[" + label + "](" + href + ")" }

// vsPar is a score against par: "even", "+3", "-2" (ufmt has no %+d).
func vsPar(d int) string {
	switch {
	case d > 0:
		return "+" + strconv.Itoa(d)
	case d < 0:
		return strconv.Itoa(d)
	}
	return "even"
}

// flatRolls is how far a shot rolls on flat grass (a tee shot's Kick, the
// usual friction).
const flatRolls = "On flat grass a power of 10 rolls about 40, a 5 about 15."

func renderHole(e *entry, h *course.Simple, focus address) string {
	f := h.Field()
	var mine *round // the focused player's round, looked up once
	if v := e.roundTree().Get(focus.String()); v != nil {
		mine = v.(*round)
	}
	stroke := 0
	if mine != nil {
		stroke = mine.strokes
	}
	// a timed hole is drawn as it stands for the focused player's next stroke
	ws, ps := h.Extras(stroke)
	f = course.WithZones(course.WithExtras(f, ws, ps), h.ExtraZones(stroke))
	// a community hole's world is its author's word: only the course has cups
	where := md(cupName(e.world), hub+":"+e.world)
	if !e.official {
		where = "Community hole by " + md(short(e.by.String()), hub+":"+e.by.String())
	}
	s := ufmt.Sprintf("# %s\n\n**Par %d** · %s · %s\n\n", e.name, e.par, where, md("Play in 3D", playLink(e))) + moved()
	if e.next != "" {
		next := e.next
		if n := find(e.next); n != nil {
			next = n.name
		}
		s += "> [!NOTE]\n> Archived: " + md(next, hub+":"+e.next) + " (" + e.next + ") took its place. It can still be played, and your best here still shows on this page"
		if e.official {
			s += ", but it no longer counts in the course-wide ranking"
		}
		s += ".\n\n"
	}
	if focus != "" {
		s += roundSummary(e, focus, mine)
	}
	// the page's forecast, drawn once: its note, and the last shot of a round
	// played in it
	now := weatherOf(e, h, Period())
	s += weatherNote(now)
	if h.Varies() {
		if focus == "" {
			s += "_This hole changes with every stroke. It is drawn for a first shot; add `/<your address>` to the URL to see it for your next one._\n\n"
		} else {
			s += ufmt.Sprintf("_This hole changes with every stroke. Drawn for %s's stroke %d._\n\n", short(focus.String()), stroke+1)
		}
	}
	if boardWork(f, h) > maxBoardWork {
		s += "_This hole is too detailed to draw here: " + md("play it in 3D", playLink(e)) + "._\n\n"
	} else {
		b := board(e, h, f, mine, now)
		leg, walls := legend(f)
		s += "```\n" + b + "```\n\n"
		s += key(b, walls) + leg + "\n\n"
	}

	s += "## Play\n\n"
	// the one number a text player cannot read off the board: where the cup is
	from, who := h.Start(), "the tee"
	if mine != nil {
		from, who = mine.ball(), "the ball"
	}
	a, d := aim(from, h.Cup())
	s += ufmt.Sprintf("From %s the cup is **%.0f°** away, **%.1f** units in a straight line (0° = right, 90° = down). %s\n\n", who, a, d, flatRolls)
	s += "_Rounds played here have no aim preview, so they go on the **Pro** board. A shot needs a gno.land wallet (Adena); the 3D game previews shots for free._\n\n"
	s += "<gno-form exec=\"Launch\">\n"
	s += ufmt.Sprintf("<gno-input name=\"hole\" value=\"%s\" readonly=\"true\" description=\"this hole\" required=\"true\" />\n", e.id)
	s += "<gno-input name=\"angle\" description=\"angle in degrees: 0 = right, 90 = down\" placeholder=\"e.g. 12.5\" required=\"true\" />\n"
	s += "<gno-input name=\"power\" description=\"power: above 0, up to 10\" placeholder=\"e.g. 6\" required=\"true\" />\n"
	s += "</gno-form>\n\n"
	s += ufmt.Sprintf("_After your shot, see your ball at `%s:%s/<your address>`._\n\n", hub, e.id)
	s += "A round under way you would rather start afresh? Put your ball back on the tee (a holed round needs nothing: the next shot starts a new one):\n\n"
	s += "<gno-form exec=\"Reset\">\n"
	s += ufmt.Sprintf("<gno-input name=\"hole\" value=\"%s\" readonly=\"true\" description=\"this hole\" required=\"true\" />\n", e.id)
	s += "</gno-form>\n\n"
	if e.official && e.next == "" {
		s += "Took a gno.land name after saving rounds? " + md("Claim", hub+"$help&func=Claim") + " puts them on the boards now.\n\n"
	}

	s += ufmt.Sprintf("## Best rounds\n\n%d rounds under way here; finished: %d assisted, %d pro.", e.roundTree().Size(), e.bests(assisted).Size(), e.bests(pro).Size())
	if e.board(assisted).Size()+e.board(pro).Size() == 0 {
		s += " No named player has finished it yet.\n\n"
	} else {
		s += " The named players' bests: each keeps its round, which the 3D game replays as a ghost to race.\n\n"
	}
	for m := 0; m < modes; m++ {
		rows := ""
		n, walked := 0, 0
		e.board(m).Iterate("", "", func(k string, v any) bool {
			walked++
			p := v.(string)
			if name := nameOf(p); name != "" { // a name deleted since is skipped
				n++
				rows += ufmt.Sprintf("| %d | [@%s](%s:%s/%s) | %d | %s |\n", n, name, hub, e.id, p, boardStrokes(k), race(e, p, "race"))
			}
			return n >= topSize || walked >= maxWalked
		})
		if rows != "" {
			s += "### " + modeTitles[m] + "\n\n| # | player | score | ghost |\n|---|---|---|---|\n" + rows + "\n"
		}
	}
	return s + "\n_This hole is " + source(e) + " — read it before you trust it with a round._\n"
}

// roundSummary is how a player stands on the hole: their round under way, if
// any, and their best in each mode, with where it puts them on the hole's
// board, or why nowhere. A holed round is not kept: its best is.
func roundSummary(e *entry, p address, r *round) string {
	who := short(p.String())
	name := nameOf(p.String())
	if name != "" {
		who = "@" + name
	}
	s := ""
	if r != nil {
		over := ""
		if r.period < Period()-1 {
			over = " Its weather is over: Reset (below) before the next shot."
		}
		s = ufmt.Sprintf("> %s's round: %s so far, not holed yet.%s\n>\n> %s\n>\n", who, count(r.strokes, "stroke"), over, shotsOf(r.shots))
	}
	for m := 0; m < modes; m++ {
		v := e.bests(m).Get(p.String())
		if v == nil {
			continue
		}
		best := bestStrokes(v)
		s += ufmt.Sprintf("> **%s's best here: %d** (par %d, %s), %s. ", who, best, e.par, vsPar(best-e.par), modeNames[m])
		b := e.board(m)
		switch k := boardKey(v, p.String()); {
		case b.Has(k):
			s += ufmt.Sprintf("**#%d of %d** on the %s board. %s.\n>\n", b.index(k)+1, b.Size(), modeNames[m], race(e, p.String(), "Race this ghost in 3D"))
		case name == "":
			s += "Not on the board: only players with a gno.land name are ranked.\n>\n"
		case e.official && e.next == "":
			s += "Not on the board yet: the name came after this round. Claim (below, or the game's \"Rank them\") ranks it now.\n>\n"
		default: // Claim seats the course's current holes only
			s += "Not on the board yet: the name came after this round. Finish it again: a named player's every finish puts their best on the board.\n>\n"
		}
		_, _, shots := bestFields(v)
		s += "> " + shotsOf(shots) + "\n>\n"
	}
	if s == "" {
		return "> [!NOTE]\n> " + who + " has no round on this hole yet.\n\n"
	}
	return "> [!NOTE]\n" + strings.TrimSuffix(s, ">\n") + "\n"
}

// shotsOf is a round's shots for a page: golf's own "%.4f,%.4f,%d", digits
// and punctuation only.
func shotsOf(shots string) string {
	return "Shots: `" + strings.ReplaceAll(shots, ";", "; ") + "`"
}

// renderData is a data version's page: where it came from, its versions,
// and its data, which is all the hole there is.
func renderData(e *entry) string {
	pkgs := strings.Replace(officialPrefix, "gno.land/r/", "/p/", 1) // the course's packages, as "/p/<ns>/"
	s := "# " + e.name + ": its data\n\n**" + e.id + "**, version " + strconv.Itoa(e.version) + " of " + md(e.slot, hub+":"+e.slot) +
		", published at height " + strconv.FormatInt(e.height, 10) + " by " + who(e.by.String()) + ". " + md("Play it", hub+":"+e.id) + ".\n\n"
	if e.note != "" {
		s += "> " + e.note + "\n\n"
	}
	if e.next != "" {
		s += "_Archived: " + md(e.next, hub+":"+e.next) + " took its place._\n\n"
	}
	s += "## Versions\n\n| version | height | by | sha256 | note |\n|---|---|---|---|---|\n"
	now := find(current(e.slot))
	for n := firstVersion(now); n <= now.version; n++ {
		v := find(e.slot + "/v" + strconv.Itoa(n))
		s += "| " + md(v.id, hub+":"+v.id+"/data") + " | " + strconv.FormatInt(v.height, 10) + " | " + who(v.by.String()) + " | `" + v.sha[:16] + "…` | " + v.note + " |\n"
	}
	data := holeData.Get(e.id).(string)
	s += "\n## The data\n\n" + strconv.Itoa(len(data)) + " bytes of GG1, sha256 `" + e.sha + "`. " +
		"Every call decodes it with " + md("course", pkgs+"course$source") + " and plays it with " + md("physics", pkgs+"physics$source") +
		"; " + md("golf", hub+"$source") + " checked it once, when it was published. HoleData gives it back as hex:\n\n"
	return s + "```\n" + hex.EncodeToString([]byte(data)) + "\n```\n"
}

// board rasterises the hole: wear, then zones, posts, walls, cup, and mine,
// the focused player's round (nil for none); now is this period's forecast.
func board(e *entry, h *course.Simple, f *physics.Field, mine *round, now course.Forecast) string {
	bw, bh := h.W, h.H
	g := make([][]rune, bh)
	wear := e.wearGrid()
	for y := 0; y < bh; y++ {
		row := make([]rune, bw)
		for x := 0; x < bw; x++ {
			row[x] = wearRune(wear, x*course.WearW/bw, y*course.WearH/bh)
		}
		g[y] = row
	}
	// the walls, traced once: drawn, and what the flood fill stops at
	wall := make([][]rune, bh)
	for y := range wall {
		wall[y] = make([]rune, bw)
	}
	for _, w := range f.Walls {
		trace(wall, w.Seg, mark(w.Mark, markWall))
	}

	// the last flight first, so the pieces drawn over it stay visible
	if mine != nil {
		fc := now
		if mine.period != now.Period { // a round begun in the period before
			fc = weatherOf(e, h, mine.period)
		}
		for _, p := range lastShot(h, mine, fc).Path {
			put(g, p, '·')
		}
	}

	tunnel := 0
	for i := range f.Zones {
		z := &f.Zones[i]
		m := mark(z.Mark, '?')
		if z.Kind == physics.Tunnel && tunnel < maxTunnels {
			// a tunnel's mouth and exit share a digit
			tunnel++
			m = rune('0' + tunnel)
		}
		drawZone(g, z, m)
	}
	for y := range wall {
		for x, c := range wall[y] {
			if c != 0 {
				g[y][x] = c
			}
		}
	}
	for _, p := range f.Posts {
		fill(g, p.Circle, mark(p.Mark, markPost))
		put(g, p.C, mark(p.Mark, markPost)) // a small post still shows
	}
	tunnel = 0
	for _, z := range f.Zones {
		if z.Kind == physics.Tunnel && tunnel < maxTunnels {
			tunnel++
			put(g, z.Vec, rune('0'+tunnel))
		}
	}
	put(g, h.Start(), markTee)
	put(g, h.Cup(), markCup)

	// ground no ball can reach is not green: blank it, as the 3D client does
	blankUnreachable(g, wall, f, h.Start(), h.Cup())

	// only your own ball: everyone's at once would bury the board
	if mine != nil {
		put(g, mine.ball(), '@')
	}

	var sb strings.Builder
	for _, row := range g {
		sb.WriteString(string(row) + "\n")
	}
	return sb.String()
}

// drawZone marks the cells whose centre the zone holds, as the physics sees it
// (physics.Zone.Contains): a polygon's row from where the centre line crosses
// its edges, an ellipse's as the run the physics' test finds from its middle.
func drawZone(g [][]rune, z *physics.Zone, m rune) {
	bh := len(g)
	if bh == 0 {
		return
	}
	bw := len(g[0])
	x0, x1 := boxCells(z.Min.X, z.Max.X, bw)
	y0, y1 := boxCells(z.Min.Y, z.Max.Y, bh)
	if x0 >= x1 {
		return
	}
	poly := len(z.Poly) >= 3
	var flip []bool
	if poly {
		flip = make([]bool, x1+1)
	}
	for y := y0; y < y1; y++ {
		row, py := g[y], float64(y)+0.5
		switch {
		case poly:
			// even-odd, as inPoly: a sweep from the right flips at each
			// crossing's cell. No sort: a row costs its edges and cells.
			for x := x0; x <= x1; x++ {
				flip[x] = false
			}
			a := z.Poly[len(z.Poly)-1]
			for _, b := range z.Poly { // the edge from a to b
				if (a.Y > py) != (b.Y > py) {
					c := cellAt(a.X+(py-a.Y)*(b.X-a.X)/(b.Y-a.Y), x0, x1)
					flip[c] = !flip[c]
				}
				a = b
			}
			in := false
			for x := x1 - 1; x >= x0; x-- {
				if flip[x+1] {
					in = !in
				}
				if in != z.Outside {
					row[x] = m
				}
			}
		case z.Round:
			hx, hy := (z.Max.X-z.Min.X)/2, (z.Max.Y-z.Min.Y)/2
			dy := (py - z.Min.Y - hy) / hy
			in := func(x int) bool {
				dx := (float64(x) + 0.5 - z.Min.X - hx) / hx
				return dx*dx+dy*dy < 1
			}
			// the cells nearest the middle: if neither is in, none is
			mid := int(math.Floor(z.Min.X + hx - 0.5))
			c := -1
			for _, x := range [2]int{mid, mid + 1} {
				if x < x0 {
					x = x0
				}
				if x >= x1 {
					x = x1 - 1
				}
				if c < 0 && in(x) {
					c = x
				}
			}
			if c >= 0 {
				from := firstCell(x0, c, in)
				to := firstCell(c, x1, func(x int) bool { return !in(x) })
				fillRow(row, from, to, m)
			}
		default:
			fillRow(row, x0, x1, m)
		}
	}
}

// boxCells is the cells from int(lo) to int(hi), within 0..n, whose centre
// lies in [lo, hi): the cells the physics' box test takes.
func boxCells(lo, hi float64, n int) (int, int) {
	a, b := span(lo, hi, n)
	if a >= b {
		return a, a
	}
	a = firstCell(a, b, func(x int) bool { return float64(x)+0.5 >= lo })
	return a, firstCell(a, b, func(x int) bool { return !(float64(x)+0.5 < hi) })
}

// cellAt is the first cell in [lo, hi), lo >= 0, whose centre is at or past c
// (!(x+0.5 < c), as the physics compares), hi if none: ceil(c-0.5).
func cellAt(c float64, lo, hi int) int {
	if !(float64(lo)+0.5 < c) { // NaN too, as a search would find
		return lo
	}
	if c >= float64(hi) {
		return hi
	}
	x := int(c) // c > 0.5: its floor
	if float64(x)+0.5 < c {
		x++
	}
	if x > hi {
		x = hi
	}
	return x
}

// firstCell is the first x in [lo, hi) where ok turns true, hi if it never
// does: ok is false up to some x, and true from there.
func firstCell(lo, hi int, ok func(x int) bool) int {
	for lo < hi {
		mid := (lo + hi) / 2
		if ok(mid) {
			hi = mid
		} else {
			lo = mid + 1
		}
	}
	return lo
}

func fillRow(row []rune, from, to int, m rune) {
	for x := from; x < to; x++ {
		row[x] = m
	}
}

// span is the cells from int(lo) to int(hi), within 0..n.
func span(lo, hi float64, n int) (int, int) {
	a, b := int(lo), int(hi)
	if a < 0 {
		a = 0
	}
	if b > n {
		b = n
	}
	return a, b
}

// maxBoardWork bounds a board's drawing, in thousands of gas (boardWork):
// past it the page does not draw, far under the 3e9 a query may use.
const maxBoardWork = 600000

// boardWork estimates board's cost in thousands of gas, with measured weights:
// a board cell; a cell and a polygon edge per row of a zone's box (every edge
// counted as crossing, as a zigzag's do); a step along a wall; a cell of a
// post's box.
func boardWork(f *physics.Field, h *course.Simple) int {
	bw, bh := h.W, h.H
	n := 32 * bw * bh
	for i := range f.Zones {
		z := &f.Zones[i]
		x0, x1 := span(z.Min.X, z.Max.X, bw)
		y0, y1 := span(z.Min.Y, z.Max.Y, bh)
		if x1 > x0 && y1 > y0 {
			n += (y1 - y0) * (5*(x1-x0) + 16*len(z.Poly))
		}
	}
	for i := range f.Walls {
		n += 10 * (int(f.Walls[i].Seg.B.Sub(f.Walls[i].Seg.A).Len()*2) + 2)
	}
	for i := range f.Posts {
		d := int(2*f.Posts[i].R) + 2
		n += 20 * d * d
	}
	return n
}

// key names the board's fixed marks it shows (tee and cup always), with the
// skins of the walls drawn `#`.
func key(b, walls string) string {
	// what the board shows, read once: a big board is thousands of runes
	var on [128]bool
	shot := false // '·', the one mark past ASCII
	for _, c := range b {
		if c < 128 {
			on[c] = true
		} else if c == '·' {
			shot = true
		}
	}
	s := "`*` tee · `U` cup"
	for _, k := range []struct{ marks, what string }{
		{"@", "the ball"}, {"·", "its last shot"}, {"#", "wall"},
		{":;x%", "wear (worn by past shots)"},
	} {
		shown := k.marks == "·" && shot
		for i := 0; i < len(k.marks) && k.marks[i] < 128; i++ {
			shown = shown || on[k.marks[i]]
		}
		if shown {
			s += " · `" + k.marks + "` " + k.what
			if k.marks == "#" && walls != "" {
				s += " (" + walls + ")"
			}
		}
	}
	// tunnels are numbered from 1: name the digits the board has
	digits := ""
	for c := '1'; c <= '9'; c++ {
		if on[c] {
			digits += string(c)
		}
	}
	switch len(digits) {
	case 0:
	case 1:
		s += " · `" + digits + "` a tunnel and its exit"
	default:
		s += " · `" + digits + "` tunnels, each with its exit"
	}
	return s
}

// legend names the pieces the hole gave a skin (a slope with the way it
// falls), and the skins of its `#` walls.
func legend(f *physics.Field) (string, string) {
	s, walls := "", ""
	add := func(m rune, def rune, skin string) {
		if skin == "" {
			return
		}
		r := mark(m, def)
		if r == markWall {
			// the key's own wall: name its skins there, once each
			if !strings.Contains(", "+walls+", ", ", "+skin+", ") {
				if walls != "" {
					walls += ", "
				}
				walls += skin
			}
			return
		}
		// once each: a mark with two meanings (two slopes' ways) says both
		item := ufmt.Sprintf(" · `%s` %s", string(r), skin)
		if strings.Contains(s+" · ", item+" · ") {
			return
		}
		s += item
	}
	for _, z := range f.Zones {
		if z.Kind == physics.Tunnel {
			continue // numbered on the board
		}
		name := cleanSkin(z.Skin)
		if name == "" || name == z.Kind.String() {
			name = z.Kind.String()
		} else {
			name += " (" + z.Kind.String() + ")"
		}
		// a slope says which way it takes the ball, in the shot's degrees (the wind's, the cup's)
		if z.Kind == physics.Slope && (z.Vec.X != 0 || z.Vec.Y != 0) {
			a, _ := aim(physics.Vec2{}, z.Vec)
			if z.Air {
				name += ufmt.Sprintf(", pushes toward %.0f°", a)
			} else {
				name += ufmt.Sprintf(", falls toward %.0f°", a)
			}
		}
		add(z.Mark, '?', name)
	}
	for _, p := range f.Posts {
		add(p.Mark, markPost, cleanSkin(p.Skin))
	}
	for _, w := range f.Walls {
		add(w.Mark, markWall, cleanSkin(w.Skin))
	}
	return s, walls
}

// mark is what a piece shows on the text board. Marks come from the hole's
// author, and the board sits in a code block: only a printable ASCII
// character that cannot close the block or start markdown is kept.
func mark(m, def rune) rune {
	if m <= ' ' || m > '~' || strings.ContainsRune("`[]()<>*_#|\\!@oU0123456789", m) {
		return def
	}
	return m
}

// wearRune takes wear-cell coordinates.
func wearRune(wear []int, x, y int) rune {
	i := y*course.WearW + x
	if i < 0 || i >= len(wear) {
		return rune(wearRunes[0])
	}
	switch v := wear[i]; {
	case v == 0:
		return rune(wearRunes[0])
	case v <= wearLight:
		return rune(wearRunes[1])
	case v <= wearWorn:
		return rune(wearRunes[2])
	case v <= wearGroove:
		return rune(wearRunes[3])
	default:
		return rune(wearRunes[4])
	}
}

// trace draws a wall as points every half unit, put inlined: a board has
// thousands.
func trace(g [][]rune, s physics.Segment, c rune) {
	bh := len(g)
	if bh == 0 {
		return
	}
	bw := len(g[0])
	d := s.B.Sub(s.A)
	steps := int(d.Len()*2) + 1
	for i := 0; i <= steps; i++ {
		k := float64(i) / float64(steps)
		x, y := int(s.A.X+d.X*k), int(s.A.Y+d.Y*k)
		if x == bw {
			x = bw - 1
		}
		if y == bh {
			y = bh - 1
		}
		if x >= 0 && x < bw && y >= 0 && y < bh {
			g[y][x] = c
		}
	}
}

// fill draws a post: the cells whose centre is within its radius. LenCmp
// skips Len's software square root.
func fill(g [][]rune, c physics.Circle, r rune) {
	bh := len(g)
	if bh == 0 {
		return
	}
	bw := len(g[0])
	for y := int(c.C.Y - c.R); y <= int(c.C.Y+c.R); y++ {
		gy := y
		if gy == bh {
			gy = bh - 1
		}
		if gy < 0 || gy >= bh {
			continue
		}
		for x := int(c.C.X - c.R); x <= int(c.C.X+c.R); x++ {
			gx := x
			if gx == bw {
				gx = bw - 1
			}
			if gx >= 0 && gx < bw && (physics.Vec2{X: float64(x) + 0.5, Y: float64(y) + 0.5}).Sub(c.C).LenCmp(c.R) <= 0 {
				g[gy][gx] = r
			}
		}
	}
}

func put(g [][]rune, p physics.Vec2, c rune) {
	x, y := int(p.X), int(p.Y)
	bh := len(g)
	if bh == 0 {
		return
	}
	bw := len(g[0])
	// the far edge belongs to the last cell, not off the board
	if x == bw {
		x = bw - 1
	}
	if y == bh {
		y = bh - 1
	}
	if x < 0 || x >= bw || y < 0 || y >= bh {
		return
	}
	g[y][x] = c
}

func short(addr string) string {
	if len(addr) <= 12 {
		return addr
	}
	return addr[:8] + "…" + addr[len(addr)-4:]
}

// blankUnreachable clears the cells no ball can reach: a flood fill from the
// tee, the cup and where tunnels and hazards put the ball, stopped by walls.
func blankUnreachable(g, wall [][]rune, f *physics.Field, seeds ...physics.Vec2) {
	bh := len(g)
	if bh == 0 {
		return
	}
	bw := len(g[0])
	for _, z := range f.Zones {
		if z.Kind == physics.Tunnel || z.Kind == physics.Hazard {
			seeds = append(seeds, z.Vec)
		}
	}
	// a row's run at a time, no closure: a board has thousands of cells
	seen := make([][]bool, bh)
	for y := range seen {
		seen[y] = make([]bool, bw)
	}
	var stack []int // y*bw + x: a cell whose run is yet to fill
	for _, p := range seeds {
		if x, y := int(p.X), int(p.Y); x >= 0 && y >= 0 && x < bw && y < bh {
			stack = append(stack, y*bw+x)
		}
	}
	for len(stack) > 0 {
		c := stack[len(stack)-1]
		stack = stack[:len(stack)-1]
		x, y := c%bw, c/bw
		s, w := seen[y], wall[y]
		if s[x] || w[x] != 0 {
			continue
		}
		l, r := x, x+1
		for l > 0 && !s[l-1] && w[l-1] == 0 {
			l--
		}
		for r < bw && !s[r] && w[r] == 0 {
			r++
		}
		for i := l; i < r; i++ {
			s[i] = true
		}
		// the rows above and below: a cell for each open run under this one
		for ny := y - 1; ny <= y+1; ny += 2 {
			if ny < 0 || ny >= bh {
				continue
			}
			ns, nw := seen[ny], wall[ny]
			open := false
			for i := l; i < r; i++ {
				o := !ns[i] && nw[i] == 0
				if o && !open {
					stack = append(stack, ny*bw+i)
				}
				open = o
			}
		}
	}
	for y := 0; y < bh; y++ {
		for x := 0; x < bw; x++ {
			if !seen[y][x] && wall[y][x] == 0 {
				g[y][x] = ' '
			}
		}
	}
}

// race is the 3D game's dare link (by=): this hole against p's best's ghost.
func race(e *entry, p, label string) string { return md(label, playLink(e)+"&by="+p) }

// byName is a player by their gno.land name when they have one.
func byName(addr string) string {
	if n := nameOf(addr); n != "" {
		return md("@"+n, "/u/"+n)
	}
	return who(addr)
}

// count is n things, said right for one.
func count(n int, what string) string {
	if n == 1 {
		return "1 " + what
	}
	return strconv.Itoa(n) + " " + what + "s"
}

state.gno

package golf

import (
	"math"
	"strconv"
	"strings"

	"gno.land/p/nym-alexiscolin000/gnogolf/course"
	"gno.land/p/nym-alexiscolin000/gnogolf/physics"
	bptree "gno.land/p/nt/bptree/v0"
	"gno.land/p/nt/ufmt/v0"
)

// HoleState is the hole as JSON for a client: geometry, skins (names the
// client looks up), weather and wear, all it needs to draw the hole and aim.
// hole is a version's id or an alias; "hole" in the answer is always the
// version's id, the one to write with, with its "slot" and "v", and an
// archived one's "next".
//
// A shot's path (Round, Simulate*) is the flight the chain computed: replay
// it, never re-simulate. Points far apart are a tunnel: do not interpolate.
func HoleState(hole string) string {
	e := readHole(hole)
	h := e.hole()
	f := h.Field()
	var sb strings.Builder
	sb.WriteString("{" + versionJSON +
		`,"hole":` + jstr(e.id) +
		`,"name":` + jstr(e.name) +
		`,"official":` + strconv.FormatBool(e.official))
	if e.slot != "" {
		sb.WriteString(`,"slot":` + jstr(e.slot) + `,"v":` + strconv.Itoa(e.version))
	}
	if e.next != "" {
		sb.WriteString(`,"next":` + jstr(e.next))
	}
	p := Period()
	sb.WriteString(boardJSON(h) +
		`,"par":` + strconv.Itoa(e.par) +
		`,"world":` + jstr(e.world) + `,"order":` + jnum(e.order) +
		`,"timed":` + strconv.FormatBool(h.Varies()) +
		`,"period":` + strconv.FormatInt(p, 10) +
		`,"weather":` + forecastJSON("", weatherOf(e, h, p)) +
		`,"start":` + jvec(h.Start()) +
		`,"cup":` + jvec(h.Cup()) +
		`,"cupR":` + jnum(h.CupRadius) + `,"ballR":` + jnum(f.Radius))
	// the hole's work before the weather (newWork): the client splits a save
	// and sets its gas by it
	w := newWork(h, nil)
	sb.WriteString(ufmt.Sprintf(`,"work":{"walls":%d,"pieces":%d,"setup":%d}`, w.walls, w.pieces, w.setup))
	sb.WriteString(`,"walls":` + wallsJSON(f.Walls) + `,"posts":` + postsJSON(f.Posts))
	sb.WriteString(`,"zones":` + zonesJSON(f.Zones, true))
	sb.WriteString(`,"wear":{"w":` + strconv.Itoa(course.WearW) + `,"h":` + strconv.Itoa(course.WearH) + `,"cells":[`)
	for i, c := range e.wearGrid() {
		sb.WriteString(sep(i))
		sb.WriteString(strconv.Itoa(c))
	}
	sb.WriteString("]}}")
	return sb.String()
}

// roundJSON is one player's round: ball rounded, rest exact (for SimulateFrom)
// and the last stroke replayed: rounds store shots, not paths.
func roundJSON(e *entry, h *course.Simple, player string, r *round) string {
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"player":` + jstr(player) +
		`,"ball":` + jvec(r.ball()) + `,"rest":` + jexact(r.ball()) +
		ufmt.Sprintf(`,"strokes":%d,"period":%d`, r.strokes, r.period) +
		`,"mode":` + jstr(modeNames[r.mode]) +
		`,"shots":` + jstr(r.shots))
	shot := lastShot(h, r, weatherOf(e, h, r.period))
	sb.WriteString(`,"path":[` + pathJSON(shot.Path) + `],"air":` + jstr(airOf(shot)) + `,"cause":` + jstr(string(shot.Cause)))
	sb.WriteString("}")
	return sb.String()
}

// lastShot replays a round's last stroke, read-only, with its stroke number,
// tick and weather (fc, its period's forecast): the same flight, less the
// wear. Empty before a first one.
func lastShot(h *course.Simple, r *round, fc course.Forecast) physics.Shot {
	if r.strokes == 0 || r.shots == "" {
		return physics.Shot{}
	}
	s := r.shots
	if i := strings.LastIndex(s, ";"); i >= 0 {
		s = s[i+1:]
	}
	angle, power, tick := parseShot(s)
	from := physics.Vec2{X: r.fx, Y: r.fy}
	shot, holed := h.PreviewWith(from, angle*math.Pi/180, power, r.strokes-1, tick, fc.Zones)
	return back(h, from, shot, holed)
}

// pathJSON is a shot's path points, comma separated.
func pathJSON(ps []physics.Vec2) string {
	var sb strings.Builder
	for i, p := range ps {
		sb.WriteString(sep(i))
		sb.WriteString(jvec(p))
	}
	return sb.String()
}

// airOf is a shot's air flags, one character per path point: "0001100…".
func airOf(s physics.Shot) string {
	b := make([]byte, len(s.Path))
	for i := range b {
		b[i] = '0'
		if i < len(s.Air) && s.Air[i] {
			b[i] = '1'
		}
	}
	return string(b)
}

// Round is one player's round under way on a hole with its last stroke's
// path, or null if they have none: never started, holed (its best is kept:
// Ghost) or Reset. It costs one stroke of gas.
func Round(hole string, player address) string {
	e := readHole(hole)
	v := e.roundTree().Get(player.String())
	if v == nil {
		return "null"
	}
	return roundJSON(e, e.hole(), player.String(), v.(*round))
}

func sep(i int) string {
	if i == 0 {
		return ""
	}
	return ","
}

// jnum is a number with 3 decimals, the bytes of ufmt's "%.3f" at a fraction
// of its gas. NaN and Inf, not JSON, print 0. Below 1e12, v*1000 is within
// 1.2e-4 of the exact decimal, so its integer part decides the rounding
// unless the fraction is within 1e-3 of a half: those, and huge numbers, go
// to strconv, which is exact.
func jnum(v float64) string {
	if math.IsNaN(v) || math.IsInf(v, 0) {
		return "0"
	}
	a := v * 1000
	if a < 0 {
		a = -a
	}
	if a >= 1e12 {
		return strconv.FormatFloat(v, 'f', 3, 64)
	}
	k := int64(a)
	switch f := a - float64(k); {
	case f > 0.499 && f < 0.501:
		return strconv.FormatFloat(v, 'f', 3, 64)
	case f > 0.5:
		k++
	}
	frac := k % 1000
	s := strconv.FormatInt(k/1000, 10) + "."
	if frac < 100 {
		s += "0"
	}
	if frac < 10 {
		s += "0"
	}
	s += strconv.FormatInt(frac, 10)
	if math.Signbit(v) { // "%.3f" keeps the sign of a negative that rounds to 0
		s = "-" + s
	}
	return s
}

// jexact is a point exactly, as the shortest decimals that read back as the
// same float64: what a client hands back to SimulateFrom.
func jexact(v physics.Vec2) string {
	return "[" + strconv.FormatFloat(v.X, 'g', -1, 64) + "," + strconv.FormatFloat(v.Y, 'g', -1, 64) + "]"
}

// versionJSON opens every object a read returns.
const versionJSON = `"version":1`

func jvec(v physics.Vec2) string { return "[" + jnum(v.X) + "," + jnum(v.Y) + "]" }

// jstr quotes an author's string so it cannot break out of its JSON. Every
// byte below 0x20 is escaped: one in one hole's name would make Holes()
// invalid JSON for every client.
func jstr(s string) string {
	const hex = "0123456789abcdef"
	b := make([]byte, 0, len(s)+2)
	b = append(b, '"')
	for i := 0; i < len(s); i++ {
		c := s[i]
		switch {
		case c == '"' || c == '\\':
			b = append(b, '\\', c)
		case c < 0x20:
			b = append(b, '\\', 'u', '0', '0', hex[c>>4], hex[c&15])
		default:
			b = append(b, c)
		}
	}
	return string(append(b, '"'))
}

// Holes lists at most maxListed holes for a client's menu, as listed orders
// them: the course's current holes, its latest archived versions, then
// community holes, newest first, perAuthor an address, none hidden (the rest
// are in Community). official marks the course's holes, the only ones in a
// cup and the course ranking; next is the version that replaced a hole, slot
// its alias, play the 3D client's link, successor the realm that took the
// course over ("" if none). It decodes nothing.
func Holes() string {
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"play":` + jstr(playURL) + `,"successor":` + jstr(successor) + `,"holes":[`)
	for i, e := range listed() {
		sb.WriteString(sep(i) + holeRow(e))
	}
	sb.WriteString("]}")
	return sb.String()
}

// holeRow is one hole as Holes and Community list it.
func holeRow(e *entry) string {
	s := `{"id":` + jstr(e.id) +
		`,"name":` + jstr(e.name) +
		`,"official":` + strconv.FormatBool(e.official) +
		`,"plays":` + strconv.Itoa(e.plays) +
		`,"best":` + strconv.Itoa(e.rec(assisted).best) +
		`,"proBest":` + strconv.Itoa(e.rec(pro).best) +
		`,"par":` + strconv.Itoa(e.par) +
		`,"world":` + jstr(e.world) + `,"order":` + jnum(e.order) + `,"next":` + jstr(e.next)
	if e.slot != "" {
		s += `,"slot":` + jstr(e.slot)
	}
	return s + "}"
}

// Community is a page of every community hole, every version of each, by id:
// all that Holes leaves out. It is paged like Records.
func Community(after string, limit int) string {
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"rows":[`)
	next := page(bpWalk(community), after, limit, func(i int, _ string, v any) {
		sb.WriteString(sep(i) + holeRow(v.(*entry)))
	})
	sb.WriteString(`],"next":` + jstr(next) + "}")
	return sb.String()
}

// perAuthor is the most published holes of one address Holes and the hub
// list: one address publishing a hundred cannot push everyone else's out.
const perAuthor = 3

// listed is the holes in list order, at most maxListed: every current course
// hole in course order; then, if minCommunity places stay free, up to
// maxArchived archived course versions, latest archived first; then, in the
// room left, the newest shown community holes (current, not hidden) among
// each author's perAuthor newest, by block height then alias, last first. An
// author fills perAuthor rows at most, however many holes they publish.
//
// It reads about what it lists: authors latest first, perAuthor keys each,
// until an author's latest is older than every row kept (room+1 authors at
// most). Hidden holes have no byAuthor row: nothing hidden is walked.
func listed() []*entry {
	list := make([]*entry, 0, maxListed)
	full := func() bool { return len(list) >= maxListed }
	slots.Iterate("", "", func(_ string, v any) bool {
		list = append(list, find(v.(string)))
		return full()
	})
	if room := maxListed - minCommunity - len(list); room > 0 {
		if room > maxArchived {
			room = maxArchived
		}
		archived.ReverseIterate("", "", func(_ string, v any) bool {
			list = append(list, find(v.(string)))
			room--
			return room == 0
		})
	}
	room := maxListed - len(list)
	if room <= 0 {
		return list
	}
	// the newest room of the rows seen, newest first, by recentKey(height,
	// alias): an author walked later has only older holes than the one
	// before's latest, so a row past room never comes back
	type seen struct{ key, id string }
	top := make([]seen, 0, room)
	byAuthor.ReverseIterate("", authorRows, func(ak string, _ any) bool {
		if len(top) == room && ak < top[room-1].key {
			return true // their latest, and so all theirs, are older than all kept
		}
		a := ak[13:] + " "
		n := 0
		byAuthor.ReverseIterate(a, a[:len(a)-1]+"!", func(k string, v any) bool {
			// "<address> <height> <slug>" -> "<height> <address>/<slug>"
			key := k[len(a):len(a)+12] + " " + a[:len(a)-1] + "/" + k[len(a)+13:]
			i := len(top)
			for i > 0 && top[i-1].key < key {
				i--
			}
			if i < room {
				if len(top) < room {
					top = append(top, seen{})
				}
				copy(top[i+1:], top[i:len(top)-1])
				top[i] = seen{key, v.(string)}
			}
			n++
			return n == perAuthor
		})
		return false
	})
	for _, s := range top {
		list = append(list, find(s.id))
	}
	return list
}

// authorRows is past the last of byAuthor's author rows ("<height> <address>")
// and before its first hole ("g1…"): no key is ":".
const authorRows = ":"

// maxArchived bounds the archived course versions Holes and the hub list,
// and minCommunity is the room they leave for community holes.
const (
	maxArchived  = 20
	minCommunity = 20
)

// SimulateFrom previews one shot, read-only: from an exact ball (a "rest"
// answered before), shot "angle,power,tick", its stroke number (0 is the
// first; timed and pulse holes change with it) and any period not ahead.
// It is what PlayRoundAt would play, for one shot's gas. As a vm/qeval query
// it needs no transaction or wallet: a client animates a shot the instant it
// is released.
func SimulateFrom(hole string, ballX, ballY float64, shot string, stroke int, period int64) string {
	notAhead(period)
	validStroke(stroke)
	angle, power, tick := parseShot(shot)
	e := readHole(hole)
	h := e.hole()
	ball := onBoard(h, ballX, ballY)
	angle, power = validShot(angle, power)
	sh, holed := resolve(h.PreviewWith(ball, angle*math.Pi/180, power, stroke, tick, weatherOf(e, h, period).Zones))
	sh = back(h, ball, sh, holed)
	return "{" + versionJSON + `,"holed":` + strconv.FormatBool(holed) + `,"bounces":` + strconv.Itoa(sh.Bounces) + shotJSON(sh) + "}"
}

func validStroke(stroke int) {
	if stroke < 0 || stroke >= maxRoundStrokes {
		panic("golf: a stroke is between 0 and 59")
	}
}

// onBoard refuses a ball off the board (or NaN): no round leaves one there.
func onBoard(h *course.Simple, x, y float64) physics.Vec2 {
	w, hh := h.W, h.H
	if !(x >= 0 && x <= float64(w) && y >= 0 && y <= float64(hh)) {
		panic("golf: the ball must be on the board")
	}
	return physics.Vec2{X: x, Y: y}
}

// shotJSON is a shot's path, air, cause, work (Shot.Work, which a client adds
// up as a commit does) and exact resting point.
func shotJSON(shot physics.Shot) string {
	return `,"path":[` + pathJSON(shot.Path) + `],"air":` + jstr(airOf(shot)) + `,"cause":` + jstr(string(shot.Cause)) +
		`,"work":` + strconv.Itoa(shot.Work) + `,"rest":` + jexact(shot.Rest())
}

// SimulateRound replays a shot list from the tee, read-only, and returns its
// last shot and stroke count: what PlayRound would record, refusals included.
// Continue from an exact "rest" (SimulateFrom): rounded points are for drawing.
func SimulateRound(hole string, shots string) string {
	return simulateRound(hole, nil, 0, shots, Period())
}

// SimulateRoundAt is SimulateRound in a period's weather, the current one or
// the one before, as a round's first stroke: it agrees with PlayRoundAt.
func SimulateRoundAt(hole string, shots string, period int64) string {
	playablePeriod(period)
	return simulateRound(hole, nil, 0, shots, period)
}

// SimulateRoundIn is SimulateRound in any period gone by, to check a recorded
// round as the chain played it. Weather still to come is refused.
func SimulateRoundIn(hole string, shots string, period int64) string {
	notAhead(period)
	return simulateRound(hole, nil, 0, shots, period)
}

// SimulateCommit previews the next PlayRoundAt (or PlayRoundPro) commit,
// read-only: shots from the exact ball ("rest") at stroke number stroke (0 is
// the first) in period's weather. It refuses what that commit would (too much
// work, too many strokes, a weather over), so a client checks every commit
// before it signs any. JSON as SimulateRound; strokes counts after the commit.
func SimulateCommit(hole string, ballX, ballY float64, stroke int, shots string, period int64) string {
	if stroke == 0 {
		playablePeriod(period)
	} else {
		notAhead(period)
		notOver(period)
	}
	validStroke(stroke)
	return simulateRound(hole, &physics.Vec2{X: ballX, Y: ballY}, stroke, shots, period)
}

// simulateRound is the SimulateRound* and SimulateCommit replay: from nil is
// the tee, and the first shot is stroke number strokes.
func simulateRound(hole string, from *physics.Vec2, strokes int, shots string, period int64) string {
	e := readHole(hole)
	h := e.hole()
	ball := h.Start()
	if from != nil {
		ball = onBoard(h, from.X, from.Y)
	}
	fc := weatherOf(e, h, period)
	weather := fc.Zones
	list := shotList(shots)
	w := newWork(h, weather)
	w.fixed = fixedGas(e, fc)
	holed := false
	var last physics.Shot
	for _, s := range list {
		if strokes >= maxRoundStrokes {
			panic(errStrokeLimit)
		}
		w.next(h)
		angle, power, tick := parseShot(s)
		angle, power = validShot(angle, power)
		last, holed = resolve(h.PreviewWith(ball, angle*math.Pi/180, power, strokes, tick, weather))
		last = back(h, ball, last, holed)
		w.add(last)
		ball = last.Rest()
		strokes++
		if holed {
			break
		}
	}
	return "{" + versionJSON + `,"holed":` + strconv.FormatBool(holed) + `,"strokes":` + strconv.Itoa(strokes) +
		`,"bounces":` + strconv.Itoa(last.Bounces) + `,"period":` + strconv.FormatInt(period, 10) +
		shotJSON(last) + "}"
}

func boardJSON(h *course.Simple) string {
	w, hh := h.W, h.H
	return `,"board":{"w":` + strconv.Itoa(w) + `,"h":` + strconv.Itoa(hh) + "}"
}

func wallsJSON(ws []physics.Wall) string {
	var sb strings.Builder
	sb.WriteString("[")
	for i := range ws {
		w := &ws[i]
		sb.WriteString(sep(i) + "{" + `"a":` + jvec(w.Seg.A) + `,"b":` + jvec(w.Seg.B) +
			`,"skin":` + jstr(cleanSkin(w.Skin)) + timingJSON(w.Every, w.On, w.Phase) + "}")
	}
	sb.WriteString("]")
	return sb.String()
}

func postsJSON(ps []physics.Post) string {
	var sb strings.Builder
	sb.WriteString("[")
	for i := range ps {
		p := &ps[i]
		sb.WriteString(sep(i) + "{" + `"c":` + jvec(p.C) + `,"r":` + jnum(p.R) +
			`,"skin":` + jstr(cleanSkin(p.Skin)) + "}")
	}
	sb.WriteString("]")
	return sb.String()
}

// zonesJSON is a hole's zones, or the weather's (forecastJSON: no flags).
// With flags, "air" and "capped" are printed only when true.
func zonesJSON(zs []physics.Zone, flags bool) string {
	var sb strings.Builder
	sb.WriteString("[")
	for i := range zs {
		z := &zs[i]
		sb.WriteString(sep(i) + "{" + `"kind":` + jstr(z.Kind.String()) +
			`,"min":` + jvec(z.Min) + `,"max":` + jvec(z.Max) +
			`,"vec":` + jvec(z.Vec) + `,"scale":` + jnum(z.Scale) +
			`,"round":` + strconv.FormatBool(z.Round) + polyJSON(z) + timingJSON(z.Every, z.On, z.Phase))
		if flags && z.Air {
			sb.WriteString(`,"air":true`)
		}
		if flags && z.Capped {
			sb.WriteString(`,"capped":true`)
		}
		sb.WriteString(`,"skin":` + jstr(cleanSkin(z.Skin)) + "}")
	}
	sb.WriteString("]")
	return sb.String()
}

// timingJSON is a timed piece's clock (a tram, a storm's gusts); nothing for
// an untimed one.
func timingJSON(every, on, phase int) string {
	if every <= 0 {
		return ""
	}
	return `,"every":` + strconv.Itoa(every) + `,"on":` + strconv.Itoa(on) + `,"phase":` + strconv.Itoa(phase)
}

// polyJSON is a polygon zone's outline, and whether it is the outside of it;
// nothing for the usual rectangle or ellipse.
func polyJSON(z *physics.Zone) string {
	if len(z.Poly) < 3 {
		return ""
	}
	return `,"poly":[` + pathJSON(z.Poly) + `],"outside":` + strconv.FormatBool(z.Outside)
}

// Extras is what a timed hole adds at one stroke of a round (0 is the first),
// to draw over HoleState's field. Empty for other holes.
func Extras(hole string, stroke int) string {
	h := readHole(hole).hole()
	if stroke < 0 {
		return "{" + versionJSON + `,"walls":[],"posts":[],"zones":[]}`
	}
	ws, ps := h.Extras(stroke)
	return "{" + versionJSON + `,"walls":` + wallsJSON(ws) + `,"posts":` + postsJSON(ps) + `,"zones":` + zonesJSON(h.ExtraZones(stroke), true) + "}"
}

// Leaderboard is a mode's course-wide top ten ("assisted" or "pro"): named
// players' bests on the current course holes, summed; most holes, then the
// best score against par (strokes - par), then the first there. Its cost does
// not grow with players.
func Leaderboard(mode string) string {
	m := modeOf(mode)
	var sb strings.Builder
	// holes: the course's current ones, the only ones that count
	sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"holes":` + strconv.Itoa(slots.Size()) + `,"rows":[`)
	n := 0
	eachRanked(m, func(r *row, name string) {
		sb.WriteString(sep(n) + standingRow(r.player, name, r))
		n++
	})
	sb.WriteString("]}")
	return sb.String()
}

// eachRanked walks a mode's top ten: the first named players of its ranking,
// with their names. A name deleted since is skipped, not shown.
func eachRanked(m int, fn func(r *row, name string)) {
	n, walked := 0, 0
	ranks[m].Iterate("", "", func(_ string, v any) bool {
		walked++ // skipped names count: the walk stays bounded
		p := v.(string)
		if name := nameOf(p); name != "" {
			fn(totals[m].Get(p).(*row), name)
			n++
		}
		return n >= topSize || walked >= maxWalked
	})
}

// maxWalked is the most rows a top ten walks, skipped names included.
const maxWalked = 4 * topSize

// strokesRow and standingRow are a player's best or standing row; name is ""
// on the reads that resolve no names. A standing's par is its holes' pars
// summed: strokes - par is its score against par.
func strokesRow(p, name string, strokes int) string {
	return `{"player":` + jstr(p) + nameField(name) + `,"strokes":` + strconv.Itoa(strokes) + "}"
}

func standingRow(p, name string, r *row) string {
	return `{"player":` + jstr(p) + nameField(name) + standingFields(r) + "}"
}

// standingFields is a standing's numbers: holes, strokes and par.
func standingFields(r *row) string {
	return `,"holes":` + strconv.Itoa(r.holes) + `,"strokes":` + strconv.Itoa(r.strokes) + `,"par":` + strconv.Itoa(r.par)
}

func nameField(name string) string {
	if name == "" {
		return ""
	}
	return `,"name":` + jstr(name)
}

// Rank is a player's place in a mode's course ranking, with their standing:
// "rank" 1 is the top, out of "of"; 0 if unnamed or no current course hole
// finished. A name deleted since keeps its place until its next change, so a
// rank may be that many too low.
func Rank(mode string, player address) string {
	m := modeOf(mode)
	p := player.String()
	rank, r := 0, &row{}
	if v := totals[m].Get(p); v != nil {
		r = v.(*row)
		if key := rankKey(r); ranks[m].Has(key) {
			rank = ranks[m].index(key) + 1
		}
	}
	return "{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"player":` + jstr(p) +
		`,"rank":` + strconv.Itoa(rank) + `,"of":` + strconv.Itoa(ranks[m].Size()) + standingFields(r) + "}"
}

// CourseLeaderboard is a page of a mode's course ranking, paged like
// HoleLeaderboard. holes is the course's current holes, players how many the
// ranking holds.
func CourseLeaderboard(mode string, offset, limit int) string {
	m := modeOf(mode)
	limit = clampLimit(limit)
	size := ranks[m].Size()
	if offset < 0 {
		offset = 0
	}
	if offset > size {
		offset = size // and offset+limit cannot overflow
	}
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"holes":` + strconv.Itoa(slots.Size()) +
		`,"players":` + strconv.Itoa(size) + `,"offset":` + strconv.Itoa(offset) + `,"rows":[`)
	n := 0
	ranks[m].IterateByOffset(offset, limit, func(_ string, v any) bool {
		p := v.(string)
		name := nameOf(p)
		if name == "" {
			return false // a name deleted since
		}
		sb.WriteString(sep(n) + standingRow(p, name, totals[m].Get(p).(*row)))
		n++
		return false
	})
	next := 0
	if offset+limit < size {
		next = offset + limit
	}
	sb.WriteString(`],"next":` + strconv.Itoa(next) + "}")
	return sb.String()
}

// Ghost is a player's best round on a hole in a mode, named or not, with its
// height (the first to a score ranks first), period and shots, or null: what a
// duel races. It replays in its own weather (SimulateRoundIn for the first
// stroke, then SimulateFrom from each rest).
func Ghost(hole, mode string, player address) string {
	e, m := readHole(hole), modeOf(mode)
	v := e.bests(m).Get(player.String())
	if v == nil {
		return "null"
	}
	strokes := bestStrokes(v)
	at, period, shots := bestFields(v)
	return "{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"player":` + jstr(player.String()) +
		`,"height":` + strconv.FormatInt(at, 10) + `,"strokes":` + strconv.Itoa(strokes) + `,"period":` + strconv.FormatInt(period, 10) + `,"shots":` + jstr(shots) + "}"
}

// HoleRank is a player's place on a hole's board in a mode, with their best,
// as Rank: 0 if unnamed or no finish there.
func HoleRank(hole, mode string, player address) string {
	e, m := readHole(hole), modeOf(mode)
	p := player.String()
	v := e.bests(m).Get(p)
	rank, strokes := 0, bestStrokes(v)
	if strokes > 0 {
		if k := boardKey(v, p); e.board(m).Has(k) {
			rank = e.board(m).index(k) + 1
		}
	}
	return "{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"player":` + jstr(p) +
		`,"rank":` + strconv.Itoa(rank) + `,"of":` + strconv.Itoa(e.board(m).Size()) + `,"strokes":` + strconv.Itoa(strokes) + "}"
}

// maxListed bounds Holes() and the hub: anyone can add a hole.
const maxListed = 120

// HoleLeaderboard is a page of a hole's board in a mode: named players' bests,
// fewest strokes then first there, from rank offset+1 (clamped to
// 0..players), at most limit rows (1..100). players is the named players,
// finished anyone who finished; next is the next offset, 0 at the end. A name
// deleted since is skipped, so a page may hold fewer rows. A page reads its
// own rows only.
func HoleLeaderboard(hole, mode string, offset, limit int) string {
	e, m := readHole(hole), modeOf(mode)
	limit = clampLimit(limit)
	board := e.board(m)
	size := board.Size()
	if offset < 0 {
		offset = 0
	}
	if offset > size {
		offset = size // and offset+limit cannot overflow
	}
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) +
		`,"par":` + strconv.Itoa(e.par) + `,"players":` + strconv.Itoa(size) + `,"finished":` + strconv.Itoa(e.bests(m).Size()) +
		`,"offset":` + strconv.Itoa(offset) + `,"rows":[`)
	n := 0
	board.IterateByOffset(offset, limit, func(k string, v any) bool {
		p := v.(string)
		name := nameOf(p)
		if name == "" {
			return false // a name deleted since
		}
		sb.WriteString(sep(n) + strokesRow(p, name, boardStrokes(k)))
		n++
		return false
	})
	next := 0
	if offset+limit < size {
		next = offset + limit
	}
	sb.WriteString(`],"next":` + strconv.Itoa(next) + "}")
	return sb.String()
}

// pageMax is the most rows one page of a read returns.
const pageMax = 100

// clampLimit keeps a page's size to 1..pageMax.
func clampLimit(n int) int {
	if n < 1 {
		return 1
	}
	if n > pageMax {
		return pageMax
	}
	return n
}

// maxFriends bounds the addresses one Bests or Standings read takes.
const maxFriends = 50

// friends splits a comma-separated list of addresses: each valid one once,
// at most maxFriends. Junk and repeats are skipped and use up nothing.
func friends(list string) []string {
	var out []string
	seen := map[string]bool{}
	for _, p := range strings.Split(list, ",") {
		if len(out) == maxFriends {
			break
		}
		if p = strings.TrimSpace(p); p != "" && !seen[p] && address(p).IsValid() {
			seen[p] = true
			out = append(out, p)
		}
	}
	return out
}

// Bests is the best finished round on one hole, in a mode, of each of the
// given players (comma-separated addresses, named or not): a board of
// friends, where no stranger and no bot can push anyone off.
func Bests(hole, mode, players string) string {
	e, m := readHole(hole), modeOf(mode)
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"par":` + strconv.Itoa(e.par) + `,"rows":[`)
	n := 0
	for _, p := range friends(players) {
		if v := e.bests(m).Get(p); v != nil {
			sb.WriteString(sep(n) + strokesRow(p, "", bestStrokes(v)))
			n++
		}
	}
	sb.WriteString("]}")
	return sb.String()
}

// Standings is each given player's course-wide standing in a mode: how many
// of the course's current holes they finished, in how many strokes, and
// those holes' pars summed.
func Standings(mode, players string) string {
	m := modeOf(mode)
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"holes":` + strconv.Itoa(slots.Size()) + `,"rows":[`)
	n := 0
	for _, p := range friends(players) {
		if v := totals[m].Get(p); v != nil {
			sb.WriteString(sep(n) + standingRow(p, "", v.(*row)))
			n++
		}
	}
	sb.WriteString("]}")
	return sb.String()
}

// Records is a page of every player's best on a hole in a mode, named or not,
// with the height that ranks it before a later tie: all a successor needs to
// carry the boards over in their order.
// The paged reads (Records, Players, Community) walk everything by
// key: after is the last key of the page before ("" for the first), limit is
// clamped to 1..100, next is the after of the next page ("" at the end).
func Records(hole, mode, after string, limit int) string {
	e, m := readHole(hole), modeOf(mode)
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"hole":` + jstr(e.id) + `,"mode":` + jstr(modeNames[m]) + `,"rows":[`)
	next := page(e.bests(m).Iterate, after, limit, func(i int, p string, v any) {
		at, _, _ := bestFields(v)
		sb.WriteString(sep(i) + `{"player":` + jstr(p) + `,"strokes":` + strconv.Itoa(bestStrokes(v)) + `,"height":` + strconv.FormatInt(at, 10) + "}")
	})
	sb.WriteString(`],"next":` + jstr(next) + "}")
	return sb.String()
}

// Players is a page of every course standing in a mode, named or not: its
// holes, strokes and par (all the ranking's key reads) and the height of the
// finish that last improved it (the tie-break), paged like Records.
func Players(mode, after string, limit int) string {
	m := modeOf(mode)
	var sb strings.Builder
	sb.WriteString("{" + versionJSON + `,"mode":` + jstr(modeNames[m]) + `,"rows":[`)
	next := page(totals[m].Iterate, after, limit, func(i int, p string, v any) {
		r := v.(*row)
		sb.WriteString(sep(i) + `{"player":` + jstr(p) + standingFields(r) + `,"height":` + strconv.FormatInt(r.height, 10) + "}")
	})
	sb.WriteString(`],"next":` + jstr(next) + "}")
	return sb.String()
}

// walk is a tree's Iterate: what page reads.
type walk func(start, end string, cb func(key string, v any) bool) bool

func bpWalk(t *bptree.BPTree) walk {
	return func(start, end string, cb func(string, any) bool) bool { return t.Iterate(start, end, cb) }
}

// page walks up to limit entries of t after the key after, and returns the
// key to continue from, "" at the end.
func page(t walk, after string, limit int, fn func(i int, key string, v any)) string {
	limit = clampLimit(limit)
	start := ""
	if after != "" {
		start = after + "\x00" // the first key past after
	}
	n, next, last := 0, "", ""
	t(start, "", func(k string, v any) bool {
		if n == limit {
			next = last
			return true
		}
		fn(n, k, v)
		last = k
		n++
		return false
	})
	return next
}

weather.gno

package golf

import (
	"strconv"
	"time"

	"gno.land/p/nym-alexiscolin000/gnogolf/course"
	"gno.land/p/nt/ufmt/v0"
)

// The weather changes every five minutes of chain time, differs from hole to
// hole and is the same for everyone (course.ForecastFor hashes hole and
// period). A round is played in the weather of the period it started in, and
// records it, so anyone can replay it.

// PeriodSeconds is how long one weather lasts.
const PeriodSeconds = 5 * 60

// Period is the weather period of the chain's current block time.
func Period() int64 { return time.Now().Unix() / PeriodSeconds }

// weatherOf is the hole's weather in a period: seeded by its id, so each
// version of a slot has weather of its own.
func weatherOf(e *entry, h *course.Simple, period int64) course.Forecast {
	return course.ForecastFor(e.id, e.world, h, period)
}

// forecastJSON is a forecast as an object, head its first fields if any
// (as `"version":1,`). Zones' air and capped are not printed: only the wind
// has them, always.
func forecastJSON(head string, f course.Forecast) string {
	return "{" + head + `"period":` + strconv.FormatInt(f.Period, 10) + `,"kind":` + jstr(f.Kind) +
		`,"wind":` + jvec(f.Wind) + `,"zones":` + zonesJSON(f.Zones, false) + "}"
}

// Weather is a hole's weather in a period, as JSON: the zones a client draws
// and the chain plays under. Its "gas" is what a commit there spends before
// its first shot (decoding and forecast), counted against the commit's
// budget: a client adds it to its shots' estimate. A future period panics.
func Weather(hole string, period int64) string {
	notAhead(period)
	e := readHole(hole)
	fc := weatherOf(e, e.hole(), period)
	return forecastJSON(versionJSON+`,"gas":`+strconv.FormatInt(fixedGas(e, fc), 10)+",", fc)
}

// notAhead refuses a period still to come. It is no secret (ForecastFor is
// pure): this only keeps reads to the weather a round can be played in.
func notAhead(period int64) {
	if period > Period() {
		panic("golf: that weather has not come yet")
	}
}

// notOver refuses a round's weather two periods or more behind: a round left
// for later cannot be finished days on in the weather it picked.
func notOver(period int64) {
	if period < Period()-1 {
		panic(ufmt.Sprintf("golf: this round's weather (period %d) is over: Reset to play again", period))
	}
}

// playablePeriod checks the period a round starts under: the current one, or
// the one just gone, for a round that ran over the turn of the period.
func playablePeriod(period int64) {
	now := Period()
	if period != now && period != now-1 {
		panic(ufmt.Sprintf("golf: period %d is not the current weather (%d) or the one before", period, now))
	}
}