Line data Source code
1 : package overworld
2 :
3 : import (
4 : "cmp"
5 : "slices"
6 :
7 : "github.com/kijimaD/ruins/internal/consts"
8 : )
9 :
10 : // scatterTiles はチャンク w×h の外周1タイルを除いた内側から、accept を満たすタイルを count 枚選ぶ。
11 : // 並びは seed とタイル座標で決まるので、同じ入力なら同じタイルを返す。外周を除くので、チャンクの継ぎ目には置かない
12 : func scatterTiles(w, h consts.Tile, accept func(consts.Coord[consts.Tile]) bool, seed uint64, count int) []consts.Coord[consts.Tile] {
13 1 : if count <= 0 {
14 1 : return nil
15 1 : }
16 1 : type scored struct {
17 1 : pos consts.Coord[consts.Tile]
18 1 : score uint64
19 1 : }
20 1 : var cands []scored
21 1 : for y := consts.Tile(1); y < h-1; y++ {
22 1 : for x := consts.Tile(1); x < w-1; x++ {
23 1 : t := consts.Coord[consts.Tile]{X: x, Y: y}
24 1 : if accept(t) {
25 1 : cands = append(cands, scored{pos: t, score: tileJitter(seed, t) >> 11})
26 1 : }
27 : }
28 : }
29 1 : slices.SortStableFunc(cands, func(a, b scored) int {
30 1 : if a.score != b.score {
31 1 : return cmp.Compare(b.score, a.score)
32 1 : }
33 0 : if a.pos.Y != b.pos.Y {
34 0 : return cmp.Compare(a.pos.Y, b.pos.Y)
35 0 : }
36 0 : return cmp.Compare(a.pos.X, b.pos.X)
37 : })
38 1 : out := make([]consts.Coord[consts.Tile], min(count, len(cands)))
39 1 : for i := range out {
40 1 : out[i] = cands[i].pos
41 1 : }
42 1 : return out
43 : }
44 :
45 : // tileJitter は seed とタイル座標を splitmix64 の finalizer で撹拌する
46 : func tileJitter(seed uint64, t consts.Coord[consts.Tile]) uint64 {
47 1 : x := seed
48 1 : x ^= uint64(uint32(t.X)) * 0x9E3779B97F4A7C15
49 1 : x ^= uint64(uint32(t.Y)) * 0xC2B2AE3D27D4EB4F
50 1 : x ^= x >> 30
51 1 : x *= 0xBF58476D1CE4E5B9
52 1 : x ^= x >> 27
53 1 : x *= 0x94D049BB133111EB
54 1 : x ^= x >> 31
55 1 : return x
56 1 : }
|