# Projected Depth Decals & GPU-Friendly Surface Painting in Godot 4 Compatibility

> Godot 4.7 Compatibility cube-projected depth decals (handling OpenGL clip-space Z cleanly) for scorch marks and craters, plus a persistent RGBA8 Splatoon-style surface painting layer with wetness contrast.

- **Canonical page:** https://gamecrew.ai/techniques/godot/projected-decals-surface-paint
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Godot 4
- **Category:** shaders
- **Tags:** `decals`, `paint`, `splatoon`, `ink`, `splat`, `footprints`, `scorch`, `depth`, `shader`, `gdshader`, `compatibility`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-13)
- **Demo:** No demo

## When to Use & Field Best Practices

Godot 4's built-in `Decal` node is unsupported in the Compatibility renderer (WebGL 2). Two lightweight Compatibility-native patterns bring rich environmental storytelling and Splatoon-style surface painting to browser builds:

1. **Box-Projected Depth Decals (`box_projected_decal.gdshader`)**:
   - Place a unit `BoxMesh` (`1×1×1`) scaled and oriented over any wall, floor, or corner seam with `cull_front, depth_test_disabled, depth_draw_never`.
   - Sample `hint_depth_texture` (using `#if CURRENT_RENDERER == RENDERER_COMPATIBILITY` for clip-space $Z \in [-1, 1]$!), reconstruct world position, transform into the box's local space via `inverse(MODEL_MATRIX)`, and `discard` any pixel outside `[-0.5, 0.5]^3`. The decal drapes seamlessly across stairs, rocks, and angled corners!
2. **Persistent Splatoon / Turf Surface Painting (`paint_surface.gdshader` + `surface_painter.gd`)**:
   - Keep a world-mapped `256×256` `Image.FORMAT_RGBA8` paint layer (`RGB` = team/ink color, `A` = paint thickness/coverage) stamped on projectile hits or footsteps and flushed once per frame only when dirty (`ImageTexture.update`).
   - Blend painted surfaces toward glossy wet ink (`ROUGHNESS = 0.14`, subtle raised edge rim) so painted turf pops crisply against matte stone arenas.

## Mathematical & Algorithmic Core

- **Box-Space Depth Reconstruction**:
  $$\mathbf{p}_{\text{view}} = \frac{(P^{-1}\mathbf{p}_{\text{ndc}})_{xyz}}{(P^{-1}\mathbf{p}_{\text{ndc}})_w}, \qquad \mathbf{p}_{\text{local}} = M_{\text{box}}^{-1} \, V^{-1} \, \mathbf{p}_{\text{view}}$$
  Project onto UV $\mathbf{u} = \mathbf{p}_{\text{local}}.xz + 0.5$ whenever $\max(|p_x|, |p_y|, |p_z|) \le 0.5$.

## Engine Implementation

### 1. Compatibility Box-Projected Depth Decal Shader (`Assets/Game/Shaders/box_projected_decal.gdshader`)

```glsl
shader_type spatial;
render_mode blend_mix, depth_draw_never, depth_test_disabled, cull_front, unshaded;

uniform sampler2D depth_tex : hint_depth_texture, filter_nearest;
uniform vec4 decal_color : source_color = vec4(0.12, 0.10, 0.09, 0.88);
uniform vec4 ring_color : source_color = vec4(0.95, 0.45, 0.14, 0.95);
uniform float ring_glow : hint_range(0.0, 2.0) = 0.65;
uniform float softness : hint_range(0.05, 0.5) = 0.22;

float hash21(vec2 p) {
	p = fract(p * vec2(123.34, 456.21));
	p += dot(p, p + 45.32);
	return fract(p.x * p.y);
}

void fragment() {
	float raw_depth = texture(depth_tex, SCREEN_UV).r;
	#if CURRENT_RENDERER == RENDERER_COMPATIBILITY
	vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, raw_depth * 2.0 - 1.0);
	#else
	vec3 ndc = vec3(SCREEN_UV * 2.0 - 1.0, raw_depth);
	#endif

	vec4 view_pos = INV_PROJECTION_MATRIX * vec4(ndc, 1.0);
	view_pos.xyz /= max(1e-5, view_pos.w);
	vec3 world_pos = (INV_VIEW_MATRIX * vec4(view_pos.xyz, 1.0)).xyz;
	vec3 local_pos = (inverse(MODEL_MATRIX) * vec4(world_pos, 1.0)).xyz;

	if (abs(local_pos.x) > 0.5 || abs(local_pos.y) > 0.5 || abs(local_pos.z) > 0.5) {
		discard;
	}

	vec2 uv = local_pos.xz + 0.5;
	vec2 centered = (uv - 0.5) * 2.0;
	float angle = atan(centered.y, centered.x);
	float splat_r = length(centered) + 0.14 * sin(angle * 7.0) * hash21(floor(uv * 12.0));
	float mask = 1.0 - smoothstep(1.0 - softness, 1.0, splat_r);
	float y_fade = 1.0 - smoothstep(0.32, 0.5, abs(local_pos.y));
	float alpha = mask * y_fade * decal_color.a;
	if (alpha < 0.02) {
		discard;
	}

	float hot_ring = smoothstep(0.45, 0.72, splat_r) * (1.0 - smoothstep(0.75, 0.96, splat_r)) * ring_glow;
	ALBEDO = mix(decal_color.rgb, ring_color.rgb, clamp(hot_ring, 0.0, 1.0));
	ALPHA = alpha;
}
```

### 2. Persistent Splatoon / Ink Surface Shader (`Assets/Game/Shaders/paint_surface.gdshader`)

```glsl
shader_type spatial;
render_mode blend_mix, depth_draw_opaque, cull_back, specular_schlick_ggx;

uniform sampler2D paint_tex : source_color, filter_linear, repeat_disable;
uniform vec4 base_color : source_color = vec4(0.74, 0.76, 0.79, 1.0);
uniform vec2 area_min = vec2(-24.0, -24.0);
uniform vec2 area_size = vec2(48.0, 48.0);
uniform float paint_roughness : hint_range(0.05, 0.5) = 0.14;

varying vec3 v_world_pos;

void vertex() {
	v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
}

void fragment() {
	vec2 uv = (v_world_pos.xz - area_min) / max(vec2(0.01), area_size);
	vec4 paint = vec4(0.0);
	if (uv.x >= 0.0 && uv.x <= 1.0 && uv.y >= 0.0 && uv.y <= 1.0) {
		paint = texture(paint_tex, uv);
	}
	float coverage = smoothstep(0.28, 0.55, paint.a);
	float edge = smoothstep(0.24, 0.42, paint.a) * (1.0 - smoothstep(0.42, 0.62, paint.a));

	ALBEDO = mix(base_color.rgb, paint.rgb * (1.0 + edge * 0.18), coverage);
	ROUGHNESS = mix(0.84, paint_roughness, coverage);
	SPECULAR = mix(0.35, 0.85, coverage);
}
```

### 3. Typed GDScript Surface Paint Stamper & Decal Helper (`Assets/Game/Scripts/gameplay/surface_painter.gd`)

```gdscript
class_name SurfacePainter
extends RefCounted

var img: Image
var tex: ImageTexture
var area_min: Vector2
var area_size: Vector2
var resolution: int
var _dirty: bool = false

func _init(p_area_min: Vector2 = Vector2(-24.0, -24.0), p_area_size: Vector2 = Vector2(48.0, 48.0), p_res: int = 256) -> void:
	area_min = p_area_min
	area_size = p_area_size
	resolution = clampi(p_res, 64, 512)
	img = Image.create(resolution, resolution, false, Image.FORMAT_RGBA8)
	img.fill(Color(0.0, 0.0, 0.0, 0.0))
	tex = ImageTexture.create_from_image(img)

func bind_material(mat: ShaderMaterial) -> void:
	mat.set_shader_parameter("paint_tex", tex)
	mat.set_shader_parameter("area_min", area_min)
	mat.set_shader_parameter("area_size", area_size)

func splat(world_pos: Vector3, color: Color, radius_m: float = 1.4, seed_val: int = 0) -> void:
	var uv := Vector2(
		(world_pos.x - area_min.x) / maxf(0.01, area_size.x),
		(world_pos.z - area_min.y) / maxf(0.01, area_size.y)
	)
	if uv.x < 0.0 or uv.x > 1.0 or uv.y < 0.0 or uv.y > 1.0:
		return
	var cx := uv.x * float(resolution)
	var cy := uv.y * float(resolution)
	var rx := maxf(2.0, (radius_m / maxf(0.01, area_size.x)) * float(resolution))
	var ry := maxf(2.0, (radius_m / maxf(0.01, area_size.y)) * float(resolution))
	var x0 := maxi(0, int(floorf(cx - rx * 1.25)))
	var x1 := mini(resolution - 1, int(ceilf(cx + rx * 1.25)))
	var y0 := maxi(0, int(floorf(cy - ry * 1.25)))
	var y1 := mini(resolution - 1, int(ceilf(cy + ry * 1.25)))
	var phase := float(seed_val % 97) * 0.37

	for py: int in range(y0, y1 + 1):
		var dy := (float(py) - cy) / ry
		for px: int in range(x0, x1 + 1):
			var dx := (float(px) - cx) / rx
			var angle := atan2(dy, dx)
			var lobe := 1.0 + 0.18 * sin(angle * 5.0 + phase) + 0.10 * cos(angle * 9.0 - phase)
			var dist := sqrt(dx * dx + dy * dy) / maxf(0.3, lobe)
			if dist < 1.0:
				var a := clampf((1.0 - dist) * 2.2, 0.0, 1.0)
				if a > 0.25:
					img.set_pixel(px, py, Color(color.r, color.g, color.b, maxf(a, img.get_pixel(px, py).a)))
					_dirty = true

func flush() -> void:
	if _dirty:
		tex.update(img)
		_dirty = false

static func spawn_decal_box(parent: Node3D, decal_shader: Shader, pos: Vector3, size: Vector3, yaw: float = 0.0) -> MeshInstance3D:
	var box := BoxMesh.new()
	box.size = Vector3.ONE
	var mat := ShaderMaterial.new()
	mat.shader = decal_shader
	var inst := MeshInstance3D.new()
	inst.name = "ProjectedDecal"
	inst.mesh = box
	inst.material_override = mat
	inst.position = pos
	inst.rotation.y = yaw
	inst.scale = size
	inst.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
	parent.add_child(inst)
	return inst
```

## Browser, Mobile & Software-Renderer Budgets

- **Pool Projected Decals**: Cap active `box_projected_decal` meshes to `24–40` in a ring buffer so transparent depth-read overdraw stays minimal on phones.
- **Compatibility Clip-Space Z**: Always preserve `#if CURRENT_RENDERER == RENDERER_COMPATIBILITY` when reconstructing world position from `hint_depth_texture` so decals never vanish in WebGL 2 exports.
- **Dirty Flush Only**: Call `painter.flush()` once per frame; when no splat landed that frame, GPU upload cost is `0`.

## Verification Checklist

1. Run `compile` to verify both `.gdshader` shaders and `surface_painter.gd` pass Godot 4.7 lint with zero warnings.
2. Place a `spawn_decal_box` straddling a stair step or wall-floor corner and confirm it wraps cleanly onto both faces in `Captures/*.png`.
3. Call `painter.splat(pos, Color(0.95, 0.25, 0.45)); painter.flush()` and confirm glossy organic paint blobs appear immediately on the arena floor.

## Official references

- maantho — gpu-texture-painter (MIT)
- sakkaku-dev — splatoon-demo (MIT)
- Miziziziz — GodotProjectedDecals (MIT)
- Godot 4 Spatial Shader hint_depth_texture Reference

## Open-source sources

- Takes an idea from GodotProjectedDecals by Miziziziz (MIT License), https://github.com/Miziziziz/GodotProjectedDecals (box-projected depth decal reconstruction in Compatibility renderer)
- Takes an idea from gpu-texture-painter by maantho (MIT License), https://github.com/maantho/gpu-texture-painter (persistent RGBA8 surface paint workflow)
- Takes an idea from splatoon-demo by sakkaku-dev (MIT License), https://github.com/sakkaku-dev/splatoon-demo (surface paint wetness and splat blending technique)

Games built with this guide carry these credits, and the licence notices they ask for, in their third-party notices.
