package main

import "math"

// A piece's hitbox is the outline it is drawn with, at the size it is drawn and
// turned by the angle it is drawn at, so a click or a round lands on the glyphs
// that are lit and on nothing else. A radius test would be a blob nobody can see,
// and sharing that radius with anything else would silently tie two decisions
// together: the size of a hull's click target is not a tunable of its own.
//
// The numbers are the client's, from view/shapes.ts, because the outline is a fact
// about the drawing and not a second opinion about it.
var outline = map[string][][2]float64{
	"triangle": poly(3, pieceR, 0, 0),
	"square":   poly(4, pieceR*0.8, 0, math.Pi/4),
	"circle":   poly(18, pieceR*0.75, 0, 0),
	"star":     poly(10, pieceR, pieceR*0.45, -math.Pi/2),
}

// The polygon the client builds: n points on a circle of radius r, every other one
// pulled in to inner when inner is set, the whole thing tilted by tilt.
func poly(n int, r, inner, tilt float64) [][2]float64 {
	vs := make([][2]float64, n)
	for i := range vs {
		a := tilt + float64(i)/float64(n)*2*math.Pi
		if inner > 0 && i%2 == 1 {
			vs[i] = [2]float64{math.Cos(a) * inner, math.Sin(a) * inner}
			continue
		}
		vs[i] = [2]float64{math.Cos(a) * r, math.Sin(a) * r}
	}
	return vs
}

// A world offset in the frame of something centred at (x, y) and turned by h: the
// inverse of hullToWorld, and what every outline test starts with.
func inward(x, y, h, px, py float64) (float64, float64) {
	c, s := math.Cos(h), math.Sin(h)
	dx, dy := px-x, py-y
	return dx*c + dy*s, -dx*s + dy*c
}

// Is the point inside the piece centred at (x, y) and turned by h?
func pieceAt(kind string, x, y, h, px, py float64) bool {
	vs := outline[kind]
	lx, ly := inward(x, y, h, px, py)
	hit := false
	for i, a := range vs {
		b := vs[(i+1)%len(vs)]
		if (a[1] > ly) != (b[1] > ly) && lx < (b[0]-a[0])*(ly-a[1])/(b[1]-a[1])+a[0] {
			hit = !hit
		}
	}
	return hit
}

// Does the segment swept from (x0, y0) to (x1, y1) this tick cross the piece? A
// round is checked as the line it flew, so a fast one cannot tunnel through a
// piece between two ticks, and the outline decides what it hit.
func pieceCross(kind string, x, y, h, x0, y0, x1, y1 float64) bool {
	if pieceAt(kind, x, y, h, x0, y0) || pieceAt(kind, x, y, h, x1, y1) {
		return true
	}
	vs := outline[kind]
	ax, ay := inward(x, y, h, x0, y0)
	bx, by := inward(x, y, h, x1, y1)
	for i, a := range vs {
		if b := vs[(i+1)%len(vs)]; crosses(ax, ay, bx, by, a[0], a[1], b[0], b[1]) {
			return true
		}
	}
	return false
}

// Do two segments cross? Touching counts: a round that only grazes an edge of a
// piece has hit the piece.
func crosses(ax, ay, bx, by, cx, cy, dx, dy float64) bool {
	return ((bx-ax)*(cy-ay)-(by-ay)*(cx-ax))*((bx-ax)*(dy-ay)-(by-ay)*(dx-ax)) <= 0 &&
		((dx-cx)*(ay-cy)-(dy-cy)*(ax-cx))*((dx-cx)*(by-cy)-(dy-cy)*(bx-cx)) <= 0
}
