Files
mortal-maze-the-game/tools/capture_art.gd

227 lines
9.2 KiB
GDScript

extends Node
## Capturas del viewport real, con un perfil de progreso aislado.
## Abrir capture_art.tscn y pulsar F6; no funciona con el renderer --headless.
## Opcional: -- --capture-plan=/ruta/plan.json o res://.godot/art_capture_plan.json.
## Cada captura acepta scene, name, character, player_position, camera_position,
## camera_zoom, animation, frame, mobile, pause y menu (home/levels/characters/inventory).
## gate_open anima KillGate; boss_hud admite phase/health/animation/frame.
const PROFILE_FIXTURE = preload("res://tests/runtime_test_profile.gd")
const DEFAULT_PLAN: Dictionary = {
"output_dir": "user://art_captures",
"captures": [
{"name": "menu", "scene": "res://ui/menu/main_menu.tscn"},
{"name": "characters", "scene": "res://ui/menu/main_menu.tscn", "menu": "characters"},
{"name": "level_00", "scene": "res://levels/level_00.tscn"},
{"name": "level_01", "scene": "res://levels/level_01.tscn"},
{"name": "level_02", "scene": "res://levels/level_02.tscn"},
]
}
var _output_dir: String
var _results: Array[Dictionary] = []
var _failures: int = 0
func _ready() -> void:
process_mode = Node.PROCESS_MODE_ALWAYS
call_deferred("_run")
func _run() -> void:
if DisplayServer.get_name() == "headless":
push_error("CAPTURE: se necesita un renderer grafico; --headless no dibuja el viewport.")
get_tree().quit(2)
return
PROFILE_FIXTURE.prepare(get_tree())
var plan: Dictionary = _load_plan()
_output_dir = ProjectSettings.globalize_path(String(plan.get("output_dir", "user://art_captures")))
if DirAccess.make_dir_recursive_absolute(_output_dir) != OK:
push_error("CAPTURE: no se pudo crear " + _output_dir)
get_tree().quit(2)
return
get_tree().root.size = Vector2i(1280, 720)
for raw_capture: Variant in plan.get("captures", []):
if not raw_capture is Dictionary:
_failures += 1
continue
await _capture(raw_capture as Dictionary)
var report: Dictionary = {
"engine": Engine.get_version_info(),
"display": DisplayServer.get_name(),
"rendering_method": RenderingServer.get_current_rendering_method(),
"adapter": RenderingServer.get_video_adapter_name(),
"profile_isolated": true,
"failures": _failures,
"captures": _results,
}
var file: FileAccess = FileAccess.open(_output_dir.path_join("capture_report.json"), FileAccess.WRITE)
if file != null:
file.store_string(JSON.stringify(report, "\t"))
else:
_failures += 1
push_error("CAPTURE: no se pudo escribir el informe.")
print("CAPTURE COMPLETE: %d capturas, %d fallos, %s" % [_results.size(), _failures, _output_dir])
get_tree().quit(0 if _failures == 0 else 1)
func _load_plan() -> Dictionary:
var path: String = "res://.godot/art_capture_plan.json"
for argument: String in OS.get_cmdline_user_args():
if argument.begins_with("--capture-plan="):
path = argument.trim_prefix("--capture-plan=")
if not FileAccess.file_exists(path):
return DEFAULT_PLAN.duplicate(true)
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
if parsed is Dictionary and (parsed as Dictionary).get("captures") is Array:
return parsed as Dictionary
push_error("CAPTURE: plan JSON invalido: " + path)
_failures += 1
return {"captures": []}
func _capture(spec: Dictionary) -> void:
var scene_path: String = String(spec.get("scene", ""))
var capture_name: String = String(spec.get("name", scene_path.get_file().get_basename())).validate_filename()
var packed: PackedScene = load(scene_path) as PackedScene
if packed == null:
_failures += 1
push_error("CAPTURE: escena no encontrada: " + scene_path)
return
seed(1731)
var scene: Node = packed.instantiate()
var player: Node2D = scene.get_node_or_null("Player") as Node2D
var character_path: String = String(spec.get("character", ""))
var session: RunSessionState = get_node_or_null("/root/RunSession") as RunSessionState
if session != null:
session.clear()
if player != null and not character_path.is_empty():
player.set("character_data", load(character_path))
get_tree().root.add_child(scene)
get_tree().current_scene = scene
await get_tree().process_frame
if player != null:
# Los actores nacen unos pixeles sobre su plataforma. Deja que la fisica
# los asiente antes de inmovilizar la escena para la captura.
for index: int in range(int(spec.get("settle_frames", 30))):
await get_tree().physics_frame
_setup_player(scene, player, spec)
_setup_effects(scene, player, spec)
if bool(spec.get("gate_open", false)):
var gate: Node = scene.get_node_or_null("Gate")
if gate != null:
while int(gate.get("remaining")) > 0:
gate.call("_on_enemy_died")
gate.get_node("Visual").call("_process", 2.0)
if spec.has("boss_hud"):
var boss: Node = scene.get_node_or_null("Boss")
if boss != null:
var boss_spec: Dictionary = spec["boss_hud"] as Dictionary
boss.set("phase", int(boss_spec.get("phase", 0)))
boss.set("current_health", int(boss_spec.get("health", 40)))
boss.call("_update_hud")
(boss.get_node("BossHUD") as CanvasLayer).show()
var boss_body: AnimatedSprite2D = boss.get_node("Body") as AnimatedSprite2D
boss_body.play(StringName(String(boss_spec.get("animation", "idle"))))
boss_body.set_frame_and_progress(int(boss_spec.get("frame", 0)), 0.0)
boss_body.pause()
if bool(spec.get("mobile", false)):
var controls: Control = scene.get_node_or_null("MobileControls/Controls") as Control
if controls != null:
controls.show()
if bool(spec.get("pause", false)):
scene.get_node("LevelNavigation").call("pause_game")
else:
_setup_menu(scene, spec)
# Deja resolver contenedores, textura importada, parallax y Camera2D.
for index: int in range(12):
await get_tree().process_frame
await RenderingServer.frame_post_draw
var viewport_image: Image = get_viewport().get_texture().get_image()
var destination: String = _output_dir.path_join(capture_name + ".png")
var success: bool = viewport_image != null and not viewport_image.is_empty()
if success:
success = viewport_image.save_png(destination) == OK
if not success:
_failures += 1
push_error("CAPTURE: no se pudo guardar " + destination)
var entry: Dictionary = {"name": capture_name, "scene": scene_path, "path": destination, "ok": success}
if viewport_image != null:
entry["size"] = [viewport_image.get_width(), viewport_image.get_height()]
if player != null:
entry["player_position"] = [player.global_position.x, player.global_position.y]
entry["character"] = String((player.get("character_data") as CharacterData).id)
var sprite: AnimatedSprite2D = player.get_node("AnimatedSprite2D") as AnimatedSprite2D
entry["animation"] = String(sprite.animation)
entry["frame"] = sprite.frame
_results.append(entry)
print("CAPTURE: ", JSON.stringify(entry))
get_tree().paused = false
get_tree().current_scene = self
scene.queue_free()
await get_tree().process_frame
func _setup_player(scene: Node, player: Node2D, spec: Dictionary) -> void:
# Detiene IA y fisica solo en esta instancia de QA; no cambia recursos ni escenas.
for actor: Node in get_tree().get_nodes_in_group("enemy"):
actor.set_physics_process(false)
actor.set_process(false)
player.set_physics_process(false)
player.set_process_unhandled_input(false)
player.set_process_input(false)
if scene is LevelRoot:
(scene as LevelRoot).reset_after_fall = false
if spec.has("player_position"):
player.global_position = _vector(spec["player_position"])
var camera: Camera2D = player.get_node("Camera2D") as Camera2D
camera.set_process(false)
camera.position_smoothing_enabled = false
camera.offset = Vector2.ZERO
if spec.has("camera_zoom"):
camera.zoom = Vector2.ONE * float(spec["camera_zoom"])
if spec.has("camera_position"):
camera.global_position = _vector(spec["camera_position"])
camera.reset_smoothing()
camera.force_update_scroll()
var sprite: AnimatedSprite2D = player.get_node("AnimatedSprite2D") as AnimatedSprite2D
var animation: StringName = StringName(String(spec.get("animation", "idle")))
if not sprite.sprite_frames.has_animation(animation):
_failures += 1
push_error("CAPTURE: animacion no encontrada: " + animation)
else:
sprite.play(animation)
sprite.set_frame_and_progress(int(spec.get("frame", 0)), 0.0)
sprite.pause()
func _setup_menu(scene: Node, spec: Dictionary) -> void:
match String(spec.get("menu", "home")):
"levels":
scene.call("_show_levels")
"characters":
scene.call("_show_characters", String(spec.get("level", "res://levels/level_00.tscn")))
"inventory":
scene.call("_show_inventory")
func _setup_effects(scene: Node, player: Node2D, spec: Dictionary) -> void:
for raw_effect: Variant in spec.get("effects", []):
var settings: Dictionary = raw_effect as Dictionary
var effect: Node2D = load("res://effects/combat_fx.gd").new() as Node2D
effect.set("kind", StringName(String(settings.get("kind", "hit"))))
effect.set("radius", float(settings.get("radius", 54.0)))
effect.set("direction", float(settings.get("direction", 1.0)))
scene.add_child(effect)
effect.global_position = player.global_position + _vector(settings.get("offset", [0, 0]))
effect.set_process(false)
effect.set("_age", float(effect.get("_lifetime")) * float(settings.get("progress", 0.18)))
effect.queue_redraw()
func _vector(value: Variant) -> Vector2:
if value is Array and (value as Array).size() == 2:
return Vector2(float(value[0]), float(value[1]))
return Vector2.ZERO