extends RefCounted
## CLIENT RENDER PERFORMANCE (lead 2026-10-24, docs/SMOOTHNESS_REPORT.md §R): a crowded meadow cost ~15 draw calls +
## ~15 shadow draws per monster on screen (QA200: 108 monsters + 31 players = 2,500-3,000 draws). Most of them are tiny
## parts - eyes, pupils, mouths, little horns / dress bits - drawn as their own meshes, each also cast into every
## shadow cascade (High = 4). This pass, run once per monster / NPC view after it is built:
##   - parts smaller than SMALL m: no shadow (a 4 cm pupil's shadow is not visible) and not drawn beyond FAR m
##     (at that distance they are 1-2 px; the body, its outline and the name stay)
##   - billboard labels / sprites (name tags, role badges) never cast shadows
##   - per-monster particles (element aura) are not drawn beyond FAR + 8 m
##   - the body meshes go on their own render layer (settings.gd L_MON_BODY / L_NPC_BODY): Low / Medium shadows
##     leave them out of the sun's shadow (the blob shadow under them stays), High keeps real shadows
## Look up close is unchanged. Off with --viewlod=off (A/B).

const SMALL := 0.26
const FAR := 24.0

static var enabled: bool = not ("--viewlod=off" in OS.get_cmdline_user_args())


## Returns how many pieces were changed.
static func apply(view: Node3D, body_layer: int = 0) -> int:
	if not enabled or view == null or not is_instance_valid(view) or not view.is_inside_tree():
		return 0
	var n := 0
	for g in view.find_children("*", "GeometryInstance3D", true, false):
		var gi := g as GeometryInstance3D
		if gi is Label3D or gi is Sprite3D:
			if gi.cast_shadow != GeometryInstance3D.SHADOW_CASTING_SETTING_OFF:
				gi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
				n += 1
		elif gi is CPUParticles3D or gi is GPUParticles3D:
			if gi.visibility_range_end <= 0.0:
				gi.visibility_range_end = FAR + 8.0
				n += 1
		elif gi is MeshInstance3D and (gi as MeshInstance3D).mesh != null and str(gi.name) != "BlobShadow":
			var mi := gi as MeshInstance3D
			if body_layer > 0 and mi.layers == 1:
				mi.layers = 1 << (body_layer - 1)
			var sz := mi.get_aabb().size * mi.global_transform.basis.get_scale().abs()
			if maxf(sz.x, maxf(sz.y, sz.z)) < SMALL and mi.visibility_range_end <= 0.0:
				mi.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
				mi.visibility_range_end = FAR
				mi.visibility_range_end_margin = 1.5
				n += 1
	return n
