Gerador de vídeos narrativos (Godot + FFmpeg), painel Next.js, serviço de voz, Clipador de lives e Publicador para YouTube, TikTok e Instagram. Inclui a leitura das visualizações dos posts para o Dashboard e o botão "Publicar no <rede>" nos cartões das publicações. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
297 lines
11 KiB
GDScript
297 lines
11 KiB
GDScript
extends Node3D
|
|
## Inicialização e orquestração da cena.
|
|
##
|
|
## Argumentos da aplicação (depois de `--` na linha de comando da Godot):
|
|
## --config <arquivo.json> cena a montar (padrão: config/demo-street.json)
|
|
## --validate-only só valida a configuração e sai (0 = ok, 2 = inválida)
|
|
## --manifest <arquivo.json> no render, grava o resumo dos quadros produzidos
|
|
## --debug-frame-index desenha índice do quadro e tempo de cena
|
|
## --warmup-frames <n> no render, quadros descartáveis em t=0 antes da
|
|
## cena (padrão 3). Na Godot 4.7.2 o 1º quadro sai
|
|
## com sombras e luz do céu incompletas; o lançador
|
|
## passa a codificar a partir do índice n.
|
|
## Caminhos relativos são resolvidos a partir da RAIZ DO REPOSITÓRIO (a pasta
|
|
## que contém godot/), nunca do diretório de execução.
|
|
##
|
|
## Modos:
|
|
## render (Movie Maker ativo): t = quadro / fps. O delta do motor é ignorado
|
|
## porque não é exatamente 1/fps nem com --fixed-fps.
|
|
## preview (janela normal): o tempo de cena avança com o delta; Espaço pausa,
|
|
## R reinicia, ←/→ andam um quadro pausado, L liga/desliga repetição.
|
|
|
|
const SceneConfig := preload("res://scripts/core/scene_config.gd")
|
|
const StreetBuilder := preload("res://scripts/builders/street_builder.gd")
|
|
const RiderBuilder := preload("res://scripts/builders/rider_builder.gd")
|
|
const Timeline := preload("res://scripts/core/timeline_controller.gd")
|
|
const CameraController := preload("res://scripts/view/camera_controller.gd")
|
|
const OverlayController := preload("res://scripts/view/overlay_controller.gd")
|
|
|
|
const DEFAULT_CONFIG := "config/demo-street.json"
|
|
const EXIT_INVALID_CONFIG := 2
|
|
const EXIT_ENVIRONMENT := 3
|
|
const EXIT_MANIFEST := 4
|
|
const DEFAULT_WARMUP_FRAMES := 3
|
|
const MAX_WARMUP_FRAMES := 30
|
|
|
|
var _cfg: Dictionary
|
|
var _timeline: Timeline
|
|
var _rider: Dictionary
|
|
var _camera: Camera3D
|
|
var _overlay: OverlayController
|
|
var _render_mode := false
|
|
var _frame := 0
|
|
var _warmup_frames := DEFAULT_WARMUP_FRAMES
|
|
var _warmup_done := 0
|
|
var _total_frames := 0
|
|
var _fps := 30
|
|
var _preview_time := 0.0
|
|
var _paused := false
|
|
var _loop := false
|
|
var _show_debug := false
|
|
var _manifest_path := ""
|
|
var _config_path := ""
|
|
var _scene_stats := {}
|
|
var _state_lines := PackedStringArray()
|
|
var _started_msec := 0
|
|
var _halted := false
|
|
|
|
|
|
func _ready() -> void:
|
|
_started_msec = Time.get_ticks_msec()
|
|
var args := _parse_user_args(OS.get_cmdline_user_args())
|
|
_config_path = _resolve_path(args.get("config", DEFAULT_CONFIG))
|
|
_render_mode = Engine.get_write_movie_path() != ""
|
|
_show_debug = args.has("debug-frame-index")
|
|
_manifest_path = _resolve_path(args.manifest) if args.has("manifest") else ""
|
|
if args.has("warmup-frames"):
|
|
var value := str(args["warmup-frames"])
|
|
if not value.is_valid_int() or int(value) < 0 or int(value) > MAX_WARMUP_FRAMES:
|
|
printerr("ARGS_INVALID --warmup-frames precisa ser inteiro entre 0 e %d" % MAX_WARMUP_FRAMES)
|
|
_halt(EXIT_INVALID_CONFIG)
|
|
return
|
|
_warmup_frames = int(value)
|
|
|
|
var result := SceneConfig.load_file(_config_path)
|
|
if not result.ok:
|
|
printerr("CONFIG_INVALID %s" % _config_path)
|
|
for e in result.errors:
|
|
printerr(" - " + e)
|
|
_halt(EXIT_INVALID_CONFIG)
|
|
return
|
|
_cfg = result.config
|
|
if args.has("validate-only"):
|
|
print("CONFIG_OK %s (%s, %d quadros)" % [_cfg.id, _config_path, _cfg.video.total_frames])
|
|
_halt(0)
|
|
return
|
|
|
|
_fps = _cfg.video.fps
|
|
_total_frames = _cfg.video.total_frames
|
|
var viewport_size := get_viewport().get_visible_rect().size
|
|
if _render_mode:
|
|
# Caminho relativo em --write-movie é resolvido a partir de godot/, e
|
|
# a Godot 4.7.2 sai com código 0 mesmo sem conseguir gravar os PNGs.
|
|
var movie_dir := Engine.get_write_movie_path().get_base_dir()
|
|
if movie_dir.is_relative_path():
|
|
movie_dir = ProjectSettings.globalize_path("res://").path_join(movie_dir)
|
|
if not DirAccess.dir_exists_absolute(movie_dir):
|
|
printerr("RENDER_ENVIRONMENT pasta de saída do Movie Maker não existe: %s (use caminho absoluto e crie a pasta antes)" % movie_dir)
|
|
_halt(EXIT_ENVIRONMENT)
|
|
return
|
|
var expected := Vector2(_cfg.video.width, _cfg.video.height)
|
|
if viewport_size != expected:
|
|
printerr("RENDER_ENVIRONMENT viewport %s difere da configuração %s. O Movie Maker fixa o tamanho na inicialização: use o lançador (gera override.cfg) ou ajuste display/window/size no projeto." % [viewport_size, expected])
|
|
_halt(EXIT_ENVIRONMENT)
|
|
return
|
|
|
|
_build_scene(viewport_size)
|
|
_apply(0.0)
|
|
print("SCENE_READY id=%s mode=%s frames=%d fps=%d viewport=%dx%d renderer=%s" % [
|
|
_cfg.id, "render" if _render_mode else "preview", _total_frames, _fps,
|
|
int(viewport_size.x), int(viewport_size.y), RenderingServer.get_current_rendering_method()])
|
|
|
|
|
|
func _build_scene(viewport_size: Vector2) -> void:
|
|
var world := Node3D.new()
|
|
world.name = "World"
|
|
add_child(world)
|
|
_scene_stats = StreetBuilder.build(world, _cfg, ProjectSettings.globalize_path("res://assets/backgrounds"))
|
|
|
|
_rider = RiderBuilder.build(_cfg)
|
|
add_child(_rider.root)
|
|
|
|
_camera = Camera3D.new()
|
|
_camera.name = "Camera"
|
|
_camera.near = 0.05
|
|
_camera.far = 600.0
|
|
_camera.keep_aspect = Camera3D.KEEP_HEIGHT
|
|
add_child(_camera)
|
|
_camera.current = true
|
|
|
|
_overlay = OverlayController.new()
|
|
_overlay.name = "Overlay"
|
|
add_child(_overlay)
|
|
_overlay.setup(_cfg, viewport_size, _show_debug or not _render_mode)
|
|
|
|
_timeline = Timeline.new(_cfg, _rider.wheel_radius)
|
|
|
|
|
|
func _process(delta: float) -> void:
|
|
if _cfg.is_empty() or _halted:
|
|
return
|
|
if _render_mode:
|
|
_process_render()
|
|
else:
|
|
_process_preview(delta)
|
|
|
|
|
|
## Um quadro por iteração. Primeiro vêm os quadros de aquecimento (estado de
|
|
## t=0, descartados na conversão); depois o quadro N da cena mostra o estado em
|
|
## t = N / fps. A iteração em que chamamos quit() ainda é desenhada e gravada,
|
|
## então o total de PNGs é exatamente warmup + total_frames (confirmado com a
|
|
## Godot 4.7.2).
|
|
func _process_render() -> void:
|
|
if _warmup_done < _warmup_frames:
|
|
_apply(0.0)
|
|
_warmup_done += 1
|
|
return
|
|
var t := float(_frame) / float(_fps)
|
|
var state := _apply(t)
|
|
_state_lines.append(_state_line(state))
|
|
_frame += 1
|
|
if _frame >= _total_frames:
|
|
_finish_render(state)
|
|
|
|
|
|
func _process_preview(delta: float) -> void:
|
|
if not _paused:
|
|
_preview_time += delta
|
|
var duration: float = _cfg.video.duration
|
|
if _preview_time > duration:
|
|
_preview_time = 0.0 if _loop else duration
|
|
_apply(_preview_time)
|
|
|
|
|
|
func _apply(t: float) -> Dictionary:
|
|
var state := _timeline.evaluate_at_time(t)
|
|
var root: Node3D = _rider.root
|
|
root.position = state.rider_position
|
|
var body: Node3D = _rider.body
|
|
body.position = Vector3(0, state.body_bob, 0)
|
|
body.rotation = Vector3(state.body_pitch, 0, 0)
|
|
_rider.front_wheel.rotation = Vector3(state.wheel_angle, 0, 0)
|
|
_rider.rear_wheel.rotation = Vector3(state.wheel_angle, 0, 0)
|
|
CameraController.apply(_camera, state.camera)
|
|
var debug_text := ""
|
|
if _show_debug or not _render_mode:
|
|
debug_text = "q=%03d t=%.3fs d=%.2fm v=%.2fm/s" % [int(round(t * _fps)), t, state.distance, state.speed]
|
|
if not _render_mode:
|
|
debug_text += "\n[Espaço] pausa [R] reinicia [←/→] quadro [L] repetir=%s" % ("sim" if _loop else "não")
|
|
_overlay.apply(state.overlay, debug_text)
|
|
return state
|
|
|
|
|
|
func _unhandled_input(event: InputEvent) -> void:
|
|
if _render_mode or _cfg.is_empty() or not (event is InputEventKey) or not event.pressed:
|
|
return
|
|
var step := 1.0 / float(_fps)
|
|
match event.keycode:
|
|
KEY_SPACE:
|
|
_paused = not _paused
|
|
KEY_R:
|
|
_preview_time = 0.0
|
|
KEY_L:
|
|
_loop = not _loop
|
|
KEY_RIGHT:
|
|
_paused = true
|
|
_preview_time = minf(_preview_time + step, _cfg.video.duration)
|
|
KEY_LEFT:
|
|
_paused = true
|
|
_preview_time = maxf(_preview_time - step, 0.0)
|
|
KEY_ESCAPE:
|
|
get_tree().quit(0)
|
|
|
|
|
|
func _state_line(state: Dictionary) -> String:
|
|
var p: Vector3 = state.rider_position
|
|
var c: Vector3 = state.camera.position
|
|
return "%.4f|%.5f,%.5f,%.5f|%.5f|%.5f,%.5f,%.5f|%.3f" % [state.t, p.x, p.y, p.z, state.wheel_angle, c.x, c.y, c.z, state.overlay.title]
|
|
|
|
|
|
func _finish_render(last_state: Dictionary) -> void:
|
|
var final_position: Vector3 = last_state.rider_position
|
|
var manifest := {
|
|
"configId": _cfg.id,
|
|
"configPath": _config_path,
|
|
"fps": _fps,
|
|
"durationSeconds": _cfg.video.duration,
|
|
"framesRendered": _frame,
|
|
"expectedFrames": _total_frames,
|
|
"warmupFrames": _warmup_frames,
|
|
"firstSceneFrameIndex": _warmup_frames,
|
|
"pngFramesWritten": _warmup_frames + _frame,
|
|
"firstFrameTime": 0.0,
|
|
"lastFrameTime": float(_frame - 1) / float(_fps),
|
|
"viewport": [int(get_viewport().get_visible_rect().size.x), int(get_viewport().get_visible_rect().size.y)],
|
|
"renderer": {
|
|
"method": RenderingServer.get_current_rendering_method(),
|
|
"driver": RenderingServer.get_current_rendering_driver_name(),
|
|
"adapter": RenderingServer.get_video_adapter_name(),
|
|
"vendor": RenderingServer.get_video_adapter_vendor(),
|
|
},
|
|
"godotVersion": Engine.get_version_info().string,
|
|
"finalDistanceMeters": last_state.distance,
|
|
"travelMeters": _cfg.rider.travel,
|
|
"finalPosition": [final_position.x, final_position.y, final_position.z],
|
|
"cruiseSpeedMetersPerSecond": _timeline.cruise_speed(),
|
|
"scene": _scene_stats,
|
|
# Resumo do estado de todos os quadros: duas execuções da mesma
|
|
# configuração precisam gerar o mesmo valor.
|
|
"stateDigest": "\n".join(_state_lines).md5_text(),
|
|
"wallClockSeconds": (Time.get_ticks_msec() - _started_msec) / 1000.0,
|
|
}
|
|
if _manifest_path != "":
|
|
DirAccess.make_dir_recursive_absolute(_manifest_path.get_base_dir())
|
|
var file := FileAccess.open(_manifest_path, FileAccess.WRITE)
|
|
if file == null:
|
|
printerr("MANIFEST_WRITE_FAILED %s (erro %d)" % [_manifest_path, FileAccess.get_open_error()])
|
|
get_tree().quit(EXIT_MANIFEST)
|
|
return
|
|
file.store_string(JSON.stringify(manifest, " "))
|
|
file.close()
|
|
print("RENDER_DONE frames=%d warmup=%d fps=%d digest=%s" % [_frame, _warmup_frames, _fps, manifest.stateDigest])
|
|
get_tree().quit(0)
|
|
|
|
|
|
func _halt(code: int) -> void:
|
|
_halted = true
|
|
get_tree().quit(code)
|
|
|
|
|
|
func _parse_user_args(raw: PackedStringArray) -> Dictionary:
|
|
var out := {}
|
|
var i := 0
|
|
while i < raw.size():
|
|
var arg := raw[i]
|
|
if arg.begins_with("--"):
|
|
var key := arg.substr(2)
|
|
if key.contains("="):
|
|
out[key.get_slice("=", 0)] = key.substr(key.find("=") + 1)
|
|
elif i + 1 < raw.size() and not raw[i + 1].begins_with("--"):
|
|
out[key] = raw[i + 1]
|
|
i += 1
|
|
else:
|
|
out[key] = true
|
|
i += 1
|
|
return out
|
|
|
|
|
|
static func repo_root() -> String:
|
|
return ProjectSettings.globalize_path("res://").trim_suffix("/").get_base_dir()
|
|
|
|
|
|
static func _resolve_path(path: String) -> String:
|
|
var p := path.replace("\\", "/")
|
|
if p.is_absolute_path():
|
|
return p.simplify_path()
|
|
return repo_root().path_join(p).simplify_path()
|