harvest/game/tests/test_farm_layout.gd
Forrest fc7c74fa32 Task #20: lettuce and corn fields on the south soil, map grows to 60 x 80
- farm.tscn: LettuceField moves to (-1, 0.44, 25) on the SW soil tile
  (ground_008_004) and CornField to (29, 0.31, 25) on the SE tile
  (ground_011_003), both still 10 x 10 m. Their units keep ids 31-40 /
  41-50, plots 7-10 and sprout nights 2 / 4. The sunflower children are
  replaced: lettuce rows get 8 cabbage heads each (plant_004/005), corn
  rows 10 stalks each (plant_001, scaled ~0.8). Every plant's height
  follows the soil under it (raycast), so none floats.
- South Fields (outside zone) moves to (9.5, 41), 66 x 10, between the
  new south edge (z 35) and the old south fence; its four hay points
  move there too and rest on the soil.
- FarmZones.playable: Rect2(-13, -45, 60, 80), i.e. z -45..35.
- ThiefBehavior: one rect per crop field (field_rects) instead of their
  bounding box; area_for() takes the target's position.
- LootSystem: carried/dropped crop tokens show the crop's own plant
  (CROP_TOKENS), each scene loaded once.
- Tests: test_farm_layout checks the 60 x 80 map, outside zones off the
  map, the later fields on the soil tiles with their own plants standing
  on the soil, side names for both fields, the open east side south of
  the fence, and splits the travel bound (12 s core rule, 16 s for the
  south fields). test_theft: new south edge cell, crop tokens.
  run_tests EDGE/SKY south points follow the edge. test_targets: the
  dropped animal is watched from outside the gate (the carrier now dies
  ~4 m from the west edge).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:10:08 -04:00

391 lines
20 KiB
GDScript

extends RefCounted
## The playable farm: every zone exists once inside the 60 x 80 m map without overlapping (the
## outside zones stay off it), lookups by position, the crop units, the later crop fields on the
## plowed soil south of the original map with their own plants, the farm's edge (where enemies
## arrive) and the gaps in what's left of the perimeter fence (the north and east sides, without
## holes except their gaps; the south, the west, and the east side south of the fence are open),
## ground navigation from anywhere on the edge to every zone, scarecrow-only bounds, zone-to-zone
## travel times (printed as the table kept in game/LAYOUT.md), and the zone banner.
const RUN_SPEED := 5.0 # PlayerCharacter.run_speed
## The layout rule: no key area more than 12 s from another. It holds for the farm's original
## zones.
const MAX_TRAVEL := 12.0
## #20: the lettuce/cabbage and corn fields sprout later, on the plowed soil at the map's south
## end (user-decided placement), so trips to them run longer: the farthest, the lettuce field to
## the Haystacks clear across the map, is 15.5 s. They get their own bound with a little room.
const MAX_TRAVEL_SOUTH_FIELDS := 16.0
## #20: the later fields' plants: cabbage heads and corn stalks, never the original field's
## sunflowers.
const PLANTS := "res://assets/farm/ithappy/farm/prefabs/assets/plant/plant_%s.tscn"
const FIELD_PLANTS := {"lettuce": ["004", "005"], "corn": ["001"]}
const SUNFLOWER_PLANTS := ["007", "008"]
## How deep a later field's plant may sit in the soil (its base below the surface).
const SUNK := 0.2
const ENEMY_RADIUS := 0.35
const SCARECROW_RADIUS := 0.4
const CELL := 0.5
func run(r: GameTestRunner) -> void:
var farm := (load("res://game/scenes/farm.tscn") as PackedScene).instantiate() as Node3D
r.root.add_child(farm)
await r.process_frame
await r.physics_frame
var zones := farm.get_node("Zones") as FarmZones
r.check(zones != null, "farm.tscn has a FarmZones node")
if zones == null:
return
var map := zones.playable
r.check(map.position.is_equal_approx(Vector2(-13.0, -45.0)) and map.size.is_equal_approx(Vector2(60.0, 80.0)),
"the playable map is 60 x 80 m, x -13..47 and z -45..35 (%s)" % map)
_zones(r, zones)
_crops(r, zones)
_south_fields(r, farm, zones)
_markers(r, zones)
var nav := FarmNavigation.new()
nav.build(farm, map.grow(5.0), CELL, ENEMY_RADIUS)
r.info("enemy nav: %d cells, %d shapes rasterized, built in %.1f ms" % [nav.cell_count(), nav.shapes_rasterized, nav.build_usec / 1000.0])
_fence(r, zones, nav)
_enemy_routes(r, zones, nav)
_scarecrow(r, farm, zones)
_travel_times(r, farm, zones)
await _banner(r, farm, zones)
farm.queue_free()
await r.process_frame
func _zones(r: GameTestRunner, zones: FarmZones) -> void:
var all := zones.zones()
# #13: two more CROP_FIELD zones (lettuce/cabbage, corn), so it's no longer one zone per kind.
r.check(all.size() == FarmZone.Kind.size() + 2, "every kind has a zone, plus 2 more crop fields (%d zones)" % all.size())
for kind: FarmZone.Kind in FarmZone.Kind.values():
var z := zones.zone(kind)
r.check(z != null and z.display_name != "", "zone %s exists and has a name" % FarmZone.Kind.keys()[kind])
r.check(zones.zones_of(FarmZone.Kind.CROP_FIELD).size() == 3, "3 crop fields: the original, lettuce/cabbage, and corn")
for i in all.size():
var a := all[i]
r.check(zones.playable.encloses(a.rect()), "%s lies inside the playable map" % a.display_name)
r.check(zones.zone_at(a.global_position) == a, "zone_at(center of %s) finds it" % a.display_name)
for j in range(i + 1, all.size()):
r.check(not a.rect().intersects(all[j].rect()), "%s and %s don't overlap" % [a.display_name, all[j].display_name])
r.check(zones.zone_at(Vector3(8.0, 0.0, -10.0)) == null, "open ground between zones belongs to no zone")
# The gathering areas beyond the fence stay off the map (#20: the South Fields moved south of
# the map's new south edge) and clear of every other zone.
var outside := zones.outside_zones()
for i in outside.size():
var o := outside[i]
r.check(not zones.playable.intersects(o.rect()), "%s lies outside the playable map" % o.display_name)
r.check(zones.zone_at(o.global_position) == o, "zone_at(center of %s) finds it" % o.display_name)
for z in all + outside.slice(i + 1):
r.check(not o.rect().intersects(z.rect()), "%s and %s don't overlap" % [o.display_name, z.display_name])
## #13: 20 more crop units in two later-sprouting fields (lettuce/cabbage, corn), 10 each, ids
## 31..40 and 41..50, continuing the original field's plot numbering (7..10). GameConfig.start_crops
## (30) only counts the original, always-grown field; the later fields grow FarmState.crops_total
## when they sprout (LootSystem), so it's not part of this static count.
func _crops(r: GameTestRunner, zones: FarmZones) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var units := zones.crop_units()
var fields := zones.zones_of(FarmZone.Kind.CROP_FIELD)
r.check(units.size() == cfg.start_crops + 20, "%d crop units: %d in the original field, 20 in the two later ones" % [units.size(), cfg.start_crops])
var ids := {}
var per_plot := {}
var fewest := 1 << 30
var by_crop := {} # crop name -> {sprout_night, count}
for u in units:
ids[u.unit_id] = true
per_plot[u.plot] = int(per_plot.get(u.plot, 0)) + 1
fewest = mini(fewest, u.get_child_count())
r.check(fields.any(func(z: FarmZone) -> bool: return z.contains(u.global_position)), "crop unit %d lies in a crop field" % u.unit_id)
var g: Dictionary = by_crop.get(u.crop, {"sprout_night": u.sprout_night, "count": 0})
r.check(g["sprout_night"] == u.sprout_night, "every %s unit shares one sprout_night" % u.crop)
g["count"] = int(g["count"]) + 1
by_crop[u.crop] = g
r.check(ids.size() == units.size() and ids.has(1) and ids.has(units.size()), "crop unit ids are unique, 1..%d" % units.size())
r.check(per_plot.size() == 10 and per_plot.values().all(func(n: int) -> bool: return n == 5), "10 plots of 5 units (%s)" % [per_plot])
r.check(fewest >= 8, "every unit is a visible cluster (fewest plants: %d)" % fewest)
r.check(by_crop.get("sunflower", {}).get("count", 0) == cfg.start_crops and by_crop["sunflower"]["sprout_night"] == 0,
"the original field's %d units are sunflowers, already grown" % cfg.start_crops)
r.check(by_crop.get("lettuce", {}).get("count", 0) == 10 and by_crop["lettuce"]["sprout_night"] == 2,
"10 lettuce/cabbage units sprout after night 2")
r.check(by_crop.get("corn", {}).get("count", 0) == 10 and by_crop["corn"]["sprout_night"] == 4,
"10 corn units sprout after night 4")
## #20: the lettuce/cabbage and corn fields grow on the bare plowed soil south of the original map
## (the ithappy ground_008 / ground_011 tiles under Level/): each lies on one tile's footprint, with
## a meter to spare for its sloped rim, and is inside the playable map. Their plants are cabbage
## heads and corn stalks, not the original field's sunflowers, and stand on the soil: none floats
## above it, none is sunk deeper than SUNK.
func _south_fields(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
var soil: Array[Rect2] = []
var soil_bodies: Array[RID] = []
for tile in farm.get_node("Level").get_children():
var tile_name := String(tile.name)
if not (tile_name.begins_with("ground_008") or tile_name.begins_with("ground_011")):
continue
var a := _footprint(tile as Node3D)
soil.append(Rect2(a.position.x, a.position.z, a.size.x, a.size.z))
for body in tile.find_children("*", "StaticBody3D", true, false):
soil_bodies.append((body as StaticBody3D).get_rid())
var space := farm.get_world_3d().direct_space_state
for crop: String in FIELD_PLANTS:
var field := _field_of(zones, crop)
r.check(field != null, "there is a %s field" % crop)
if field == null:
continue
var rect := field.rect()
r.check(soil.any(func(s: Rect2) -> bool: return s.grow(-1.0).encloses(rect)) and zones.playable.encloses(rect),
"the %s (%s) lies on the plowed soil, inside the playable map" % [field.display_name, rect])
var want: Array = FIELD_PLANTS[crop].map(func(n: String) -> String: return PLANTS % n)
var wrong: Array[String] = []
var sunflowers := 0
var plants := 0
var lowest := INF
var highest := -INF
for u in _units_of(field):
for plant in u.get_children():
plants += 1
var path := (plant as Node).scene_file_path
if path not in want:
wrong.append("%s/%s" % [u.unit_id, plant.name])
if SUNFLOWER_PLANTS.any(func(n: String) -> bool: return path == PLANTS % n):
sunflowers += 1
var at := (plant as Node3D).global_position
var ground := _soil_height(space, soil_bodies, at)
lowest = minf(lowest, at.y - ground)
highest = maxf(highest, at.y - ground)
r.check(plants > 0 and wrong.is_empty() and sunflowers == 0, "the %s's %d plants are %s, none a sunflower (%s)"
% [field.display_name, plants, " / ".join(want.map(func(p: String) -> String: return p.get_file().get_basename())), wrong.slice(0, 4)])
r.check(lowest >= -SUNK and highest <= 0.01, "the %s's plants stand on the soil (base %.2f..%.2f m from it)" % [field.display_name, lowest, highest])
## The soil's height under a point (a ray down that skips everything but the soil tiles), or INF.
func _soil_height(space: PhysicsDirectSpaceState3D, soil_bodies: Array[RID], at: Vector3) -> float:
var skip: Array[RID] = []
for attempt in 8:
var q := PhysicsRayQueryParameters3D.create(Vector3(at.x, 6.0, at.z), Vector3(at.x, -3.0, at.z))
q.exclude = skip
var hit := space.intersect_ray(q)
if hit.is_empty():
break
if hit["rid"] in soil_bodies:
return (hit["position"] as Vector3).y
skip.append(hit["rid"])
return INF
## The world-space box around every mesh under a node.
static func _footprint(node: Node3D) -> AABB:
var box := AABB()
var first := true
for mi in node.find_children("*", "MeshInstance3D", true, false):
var m := mi as MeshInstance3D
if m.mesh == null:
continue
var a := m.global_transform * m.mesh.get_aabb()
box = a if first else box.merge(a)
first = false
return box
## The crop growing in a crop field ("sunflower", "lettuce", "corn"), or "" for other zones.
static func _crop_of(zone: FarmZone) -> String:
if zone.kind != FarmZone.Kind.CROP_FIELD:
return ""
var units := _units_of(zone)
return units[0].crop if units.size() > 0 else ""
static func _units_of(zone: FarmZone) -> Array[CropUnit]:
var out: Array[CropUnit] = []
for node in zone.find_children("*", "Node3D", true, false):
if node is CropUnit:
out.append(node)
return out
static func _field_of(zones: FarmZones, crop: String) -> FarmZone:
for z in zones.zones_of(FarmZone.Kind.CROP_FIELD):
if _crop_of(z) == crop:
return z
return null
func _markers(r: GameTestRunner, zones: FarmZones) -> void:
var map := zones.playable
var gaps := zones.gaps()
r.check(gaps.size() == 3, "3 gaps in what's left of the perimeter fence (got %d)" % gaps.size())
for m in gaps:
var p := Vector2(m.global_position.x, m.global_position.z)
r.check(not map.has_point(p) and map.grow(4.0).has_point(p), "%s sits just outside the perimeter" % m.name)
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var edge := zones.edge(cfg.spawn_margin)
var on_edge := true
for k in 40:
var p := zones.edge_point(k / 40.0 + 0.01, cfg.spawn_margin)
on_edge = on_edge and FarmZones.nearest_on_outline(edge, p).distance_to(p) < 1e-3
r.check(on_edge and zones.edge_point(0.0, cfg.spawn_margin).is_equal_approx(edge.position)
and zones.edge_point(0.5, cfg.spawn_margin).is_equal_approx(edge.end), "edge_point walks the farm's edge, %.0f m out" % cfg.spawn_margin)
var lettuce := _field_of(zones, "lettuce").global_position
var corn := _field_of(zones, "corn").global_position
var names := [zones.side_of(Vector2(17.0, -48.0)), zones.side_of(Vector2(50.0, -40.0)), zones.side_of(Vector2(-16.0, -15.0)),
zones.side_of(Vector2(corn.x, corn.z)), zones.side_of(Vector2(lettuce.x, lettuce.z)), zones.side_of(map.get_center())]
r.check(names == ["north", "north-east", "west", "south-east", "south-west", ""],
"the farm's sides are named by thirds (the corn field south-east, the lettuce field south-west): %s" % [names])
## What's left of the perimeter fence (the north side, and the east side down to the original map's
## south-east corner) has no holes except its gaps, and every gap is open; the south and west
## sides are open ground, and so is the east side south of the fence (#20: the map reaches 20 m
## further south there, with no fence).
func _fence(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
var map := zones.playable
var gaps := zones.gaps()
var fence_end := _footprint(zones.get_node("Perimeter/Fence") as Node3D).end.z
var corners := [map.position, Vector2(map.end.x, map.position.y), map.end, Vector2(map.position.x, map.end.y)]
var holes: Array[Vector2] = []
var free_share: Array[float] = []
var east_open := Vector2i.ZERO # free, all: the east side south of the fence
for side in 4: # north, east, south, west
var a: Vector2 = corners[side]
var b: Vector2 = corners[(side + 1) % 4]
var steps := ceili(a.distance_to(b) / (CELL * 0.5))
var free := 0
for k in steps + 1:
var p := a.lerp(b, k / float(steps))
var past_fence := side == 1 and p.y > fence_end + CELL
east_open.y += 1 if past_fence else 0
if not nav.is_free(nav.cell_of(p.x, p.y)):
continue
free += 1
if past_fence:
east_open.x += 1
elif side < 2 and not gaps.any(func(m: FarmMarker) -> bool:
return Vector2(m.global_position.x, m.global_position.z).distance_to(p) < 4.5):
holes.append(p)
free_share.append(free / float(steps + 1))
r.check(holes.is_empty(), "the north and east fence has no holes outside its gaps %s" % [holes.slice(0, 5)])
var east_share := east_open.x / float(maxi(east_open.y, 1))
r.check(free_share[2] > 0.9 and free_share[3] > 0.5 and east_open.y > 0 and east_share > 0.9,
"the south and west sides are open (%.0f%% and %.0f%% free), and the east side south of the fence (z %.0f..%.0f, %.0f%% free)"
% [free_share[2] * 100.0, free_share[3] * 100.0, fence_end, map.end.y, east_share * 100.0])
for m in gaps:
var g := Vector2(m.global_position.x, m.global_position.z)
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
r.check(nav.is_free(nav.cell_of(edge.x, edge.y)), "%s is open for ground enemies" % m.name)
## Ground enemies arrive anywhere on the edge with a route in (as FarmSim picks them: a route to
## the pen) and can walk from there to every zone; the lengths printed are from the middle of each
## side (the table in game/LAYOUT.md).
func _enemy_routes(r: GameTestRunner, zones: FarmZones, nav: FarmNavigation) -> void:
var cfg := load("res://game/resources/game_config.tres") as GameConfig
var edge := zones.edge(cfg.spawn_margin)
var ring := nav.free_cells_on_outline(edge, CELL * 0.75)
var pen := nav.distance_field(nav.free_cells_in(zones.zone(FarmZone.Kind.ANIMAL_PEN).rect().grow(-1.0)))
var spawns := PackedInt32Array()
for c in ring:
if pen[c] < FarmNavigation.UNREACHABLE:
spawns.append(c)
r.check(spawns.size() > ring.size() * 0.9, "enemies can arrive on nearly all of the farm's edge (%d of %d free cells)" % [spawns.size(), ring.size()])
var mid := edge.get_center()
var middles := {"north": Vector2(mid.x, edge.position.y), "east": Vector2(edge.end.x, mid.y), "south": Vector2(mid.x, edge.end.y), "west": Vector2(edge.position.x, mid.y)}
for zone in zones.zones():
var goal := nav.free_cells_in(zone.rect())
r.check(goal.size() > 0, "%s has walkable ground (%d cells)" % [zone.display_name, goal.size()])
var field := nav.distance_field(goal)
var cut_off := 0
for s in spawns:
if field[s] >= FarmNavigation.UNREACHABLE:
cut_off += 1
r.check(cut_off == 0, "ground enemies can walk from anywhere on the edge to the %s and back (%d cells can't)" % [zone.display_name, cut_off])
var lengths: Array[String] = []
for side: String in middles:
var at: Vector2 = middles[side]
var m := nav.nearest_free(nav.cell_of(at.x, at.y))
lengths.append("%s %.0f" % [side, nav.meters(field[m])] if m >= 0 and field[m] < FarmNavigation.UNREACHABLE else "%s -" % side)
r.info("%-12s from the edge (m): %s" % [zone.display_name, ", ".join(lengths)])
func _scarecrow(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
var player := farm.get_node("Player") as CharacterBody3D
var bounds := farm.get_node("Zones/Perimeter/PlayerBounds") as StaticBody3D
r.check(zones.playable.has_point(Vector2(player.global_position.x, player.global_position.z)), "the scarecrow starts inside the map")
r.check(bounds.collision_layer == 4 and (player.collision_mask & 4) != 0 and (player.collision_mask & 1) != 0,
"PlayerBounds is on the player_bounds layer, which only the scarecrow collides with")
# Stand in each gap and walk out: nothing stops the scarecrow (the gathering areas outside).
var start := player.global_transform
for m in zones.gaps():
var g := Vector2(m.global_position.x, m.global_position.z)
var map := zones.playable
var edge := Vector2(clampf(g.x, map.position.x, map.end.x), clampf(g.y, map.position.y, map.end.y))
var out := (g - edge).normalized()
player.global_position = Vector3(edge.x - out.x * 1.0, 0.6, edge.y - out.y * 1.0) # above the driveway's road
var hit := player.move_and_collide(Vector3(out.x, 0.0, out.y) * 3.0, true)
r.check(hit == null, "the scarecrow can walk out through %s" % m.name)
# ...but not past the old farm's outer fences: the invisible walls are there now.
var roam := zones.roam
var sides := {"north": [Vector2(-20.0, roam.position.y + 1.0), Vector2(0, -1)], "south": [Vector2(5.0, roam.end.y - 1.0), Vector2(0, 1)],
"west": [Vector2(roam.position.x + 1.0, 0.0), Vector2(-1, 0)], "east": [Vector2(roam.end.x - 1.0, -30.0), Vector2(1, 0)]}
for side: String in sides:
var at: Vector2 = sides[side][0]
var dir: Vector2 = sides[side][1]
player.global_position = Vector3(at.x, 0.3, at.y)
var hit := player.move_and_collide(Vector3(dir.x, 0.0, dir.y) * 3.0, true)
r.check(hit != null, "the scarecrow can't go past the %s edge of the roaming area" % side)
player.global_transform = start
func _travel_times(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
var nav := FarmNavigation.new()
nav.build(farm, zones.playable, CELL, SCARECROW_RADIUS, 1 | 4)
var all := zones.zones()
var anchors := PackedInt32Array()
for z in all:
anchors.append(nav.nearest_free(nav.cell_of(z.global_position.x, z.global_position.z)))
var header := "| From \\ to |"
var rule := "|---|"
for z in all:
header += " %s |" % z.display_name
rule += "---|"
r.info(header)
r.info(rule)
var later := all.map(func(z: FarmZone) -> bool: return _crop_of(z) in FIELD_PLANTS)
var worst := [0.0, 0.0] # among the original zones; pairs with a later field
var worst_pair := ["", ""]
for i in all.size():
var field := nav.distance_field(PackedInt32Array([anchors[i]]))
var row := "| **%s** |" % all[i].display_name
for j in all.size():
var cost := field[anchors[j]]
r.check(cost < FarmNavigation.UNREACHABLE, "the scarecrow can walk from %s to %s" % [all[i].display_name, all[j].display_name])
var seconds := nav.meters(cost) / RUN_SPEED
row += " — |" if i == j else " %.1f s |" % seconds
var k := 1 if later[i] or later[j] else 0
if seconds > worst[k]:
worst[k] = seconds
worst_pair[k] = "%s -> %s" % [all[i].display_name, all[j].display_name]
r.info(row)
r.check(worst[0] <= MAX_TRAVEL, "no key area is more than %.0f s from another (worst %.1f s: %s)" % [MAX_TRAVEL, worst[0], worst_pair[0]])
r.check(worst[1] <= MAX_TRAVEL_SOUTH_FIELDS, "the later crop fields, at the map's south end, are at most %.0f s from any key area (worst %.1f s: %s)"
% [MAX_TRAVEL_SOUTH_FIELDS, worst[1], worst_pair[1]])
func _banner(r: GameTestRunner, farm: Node3D, zones: FarmZones) -> void:
var banner := farm.get_node("ZoneBanner") as ZoneBanner
var player := farm.get_node("Player") as Node3D
var start := player.global_transform
for zone in zones.zones():
player.global_position = zone.global_position + Vector3(0.0, 0.5, 0.0)
await r.process_frame # emitted before _process, so wait for the next one too
await r.process_frame
r.check(banner.current == zone, "walking into the %s shows its name" % zone.display_name)
player.global_position = Vector3(8.0, 0.5, -10.0)
await r.process_frame
await r.process_frame
r.check(banner.current == null, "walking out of every zone clears the banner")
player.global_transform = start