package main

import (
	"fmt"
	"log"
	"math"
	"net/http"
)

const (
	width, height = 600, 320            // 画布大小
	cells         = 100                 // 单元格大小
	xyrange       = 30.0                // 坐标轴范围 (-xyrange..+xyrange)
	xyscale       = width / 2 / xyrange // x或y轴上每个单位长度的像素
	zscale        = height * 0.4        // z轴上每个单位长度的像素
	angle         = math.Pi / 6         // x、y轴的角度(=30°)
)

var sin30, cos30 = math.Sin(angle), math.Cos(angle) // sin(30°), cos(30°)

var ConcerError error

func main() {

	http.HandleFunc("/", surface)
	log.Fatal(http.ListenAndServe("localhost:8080", nil))
}

func surface(w http.ResponseWriter, r *http.Request) {
	vars := r.URL.Query()
	stroke := vars.Get("stroke")
	if stroke == "" {
		stroke = "red"
	}
	fill := vars.Get("fill")
	if fill == "" {
		fill = "blue"
	}
	w.Header().Set("Content-Type", "image/svg+xml")
	fmt.Fprintf(w, `<svg xmlns='http://www.w3.org/2000/svg' 
				style='stroke: %s; fill: %s; stroke-width: 0.7' width='%d' height='%d'>`,
		stroke, fill, width, height)
	fmt.Fprint(w, "\n")
	for i := 0; i < cells; i++ {
		for j := 0; j < cells; j++ {
			ax, ay := corner(i+1, j)
			bx, by := corner(i, j)
			cx, cy := corner(i, j+1)
			dx, dy := corner(i+1, j+1)
			fmt.Fprintf(w, "<polygon style='stroke: %s;' points='%g,%g %g,%g %g,%g %g,%g'/>\n",
				stroke, ax, ay, bx, by, cx, cy, dx, dy)
		}
	}
	fmt.Fprint(w, "</svg>")
}
func corner(i, j int) (float64, float64) {
	// 求出网格单元(i,j)的顶点坐标(x,y)
	x := xyrange * (float64(i)/cells - 0.5)
	y := xyrange * (float64(j)/cells - 0.5)

	// 计算曲面高度 z.
	z := f(x, y)

	// 将(x, y, z)等角投射到二维SVG绘图平面上,坐标是(sx, sy)
	sx := width/2 + (x-y)*cos30*xyscale
	sy := height/2 + (x+y)*sin30*xyscale - z*zscale
	if math.IsNaN(sx) || math.IsNaN(sy) {
		ConcerError = fmt.Errorf("corner() 产生非数值")
	}
	return sx, sy
}

func f(x, y float64) float64 {
	r := math.Hypot(x, y) // 到 (0,0) 的距离
	return math.Sin(r) / r
}
