Files
CenaForge/godot/scripts/core/scene_config.gd
T
MateuusandClaude Opus 5.5 84f30bbc2d CenaForge: primeira versão pública
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>
2026-11-17 16:35:09 -03:00

335 lines
15 KiB
GDScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
extends RefCounted
## Leitura e validação do contrato de cena (schemaVersion 1).
##
## O JSON só descreve dados: números, textos curtos, cores e valores de listas
## fechadas. Nenhum campo é interpretado como código ou comando. Campos
## desconhecidos são rejeitados para o contrato não crescer por acidente.
##
## Saída: { "ok": bool, "errors": PackedStringArray, "config": Dictionary }
## O dicionário "config" usa nomes internos em snake_case com tipos Godot
## (Vector3, Color). Os nomes em camelCase pertencem ao contrato do JSON.
const SUPPORTED_SCHEMA_VERSION := 1
const LIGHTING_PRESETS := ["warm_day", "golden_hour"]
const BACKGROUND_MODES := ["cards", "none"]
const CAMERA_PRESETS := ["third_person_follow"]
const RIDER_ASSETS := ["placeholder-rider"]
## Velocidade de cruzeiro máxima aceita (m/s). Acima disso o plano deixa de ser
## uma rua de bairro e a câmera não acompanha de forma legível.
const MAX_CRUISE_SPEED := 20.0
## A moto precisa parar a esta distância do fim da rua, para o fim do cenário
## não aparecer em primeiro plano.
const STREET_END_MARGIN := 15.0
const MIN_CAMERA_HEIGHT := 0.5
const DEFAULT_BOX_COLOR := "#1F8A70"
static func load_file(path: String) -> Dictionary:
if not FileAccess.file_exists(path):
return _failure(["arquivo de configuração não encontrado: %s" % path])
var text := FileAccess.get_file_as_string(path)
if text.is_empty():
var open_error := FileAccess.get_open_error()
if open_error != OK:
return _failure(["não foi possível ler %s (erro %d)" % [path, open_error]])
return _failure(["arquivo de configuração vazio: %s" % path])
return parse_text(text)
static func parse_text(text: String) -> Dictionary:
var json := JSON.new()
var parse_error := json.parse(text)
if parse_error != OK:
return _failure(["JSON inválido na linha %d: %s" % [json.get_error_line(), json.get_error_message()]])
if typeof(json.data) != TYPE_DICTIONARY:
return _failure(["a raiz do JSON precisa ser um objeto"])
return validate(json.data)
static func validate(raw: Dictionary) -> Dictionary:
var v := Validator.new()
v.check_keys(raw, ["schemaVersion", "id", "seed", "video", "world", "rider", "motion", "camera", "overlay", "audio"], "")
var version = raw.get("schemaVersion")
if not _is_number(version) or float(version) != SUPPORTED_SCHEMA_VERSION:
# Sem versão conhecida não há como interpretar o resto com segurança.
return _failure(["schemaVersion %s não suportada (esperado %d)" % [str(version), SUPPORTED_SCHEMA_VERSION]])
var cfg := {"schema_version": SUPPORTED_SCHEMA_VERSION}
cfg.id = v.text(raw, "id", "id", 1, 64)
if cfg.id != "" and not RegEx.create_from_string("^[a-z0-9][a-z0-9_-]*$").search(cfg.id):
v.fail("id", "use apenas letras minúsculas, números, '-' e '_' (ex.: demo-street)")
cfg.seed = v.integer(raw, "seed", "seed", 0, 2147483647)
# --- video ---
var video := v.object(raw, "video", "video", ["width", "height", "fps", "durationSeconds"])
cfg.video = {
"width": v.integer(video, "width", "video.width", 128, 4096),
"height": v.integer(video, "height", "video.height", 128, 4096),
"fps": v.integer(video, "fps", "video.fps", 1, 120),
"duration": v.number(video, "durationSeconds", "video.durationSeconds", 0.5, 120.0),
}
for key in ["width", "height"]:
if cfg.video[key] % 2 != 0:
v.fail("video." + key, "precisa ser par (H.264 com yuv420p exige dimensões pares)")
var frames_exact: float = cfg.video.fps * cfg.video.duration
cfg.video.total_frames = int(round(frames_exact))
if v.ok() and absf(frames_exact - cfg.video.total_frames) > 1e-6:
v.fail("video.durationSeconds", "fps × duração precisa dar um número inteiro de quadros (deu %.4f)" % frames_exact)
# --- world ---
var world := v.object(raw, "world", "world", ["streetLengthMeters", "roadWidthMeters", "nearHousesPerSide", "backgroundMode", "lightingPreset"])
cfg.world = {
"street_length": v.number(world, "streetLengthMeters", "world.streetLengthMeters", 40.0, 1000.0),
"road_width": v.number(world, "roadWidthMeters", "world.roadWidthMeters", 4.0, 20.0),
"near_houses_per_side": v.integer(world, "nearHousesPerSide", "world.nearHousesPerSide", 0, 40),
"background_mode": v.choice(world, "backgroundMode", "world.backgroundMode", BACKGROUND_MODES),
"lighting_preset": v.choice(world, "lightingPreset", "world.lightingPreset", LIGHTING_PRESETS),
}
# --- rider ---
var rider := v.object(raw, "rider", "rider", ["assetId", "bikeColor", "boxColor", "startPosition", "travelMeters"])
cfg.rider = {
"asset_id": v.choice(rider, "assetId", "rider.assetId", RIDER_ASSETS),
"bike_color": v.color(rider, "bikeColor", "rider.bikeColor"),
"box_color": v.color(rider, "boxColor", "rider.boxColor", DEFAULT_BOX_COLOR),
"start_position": v.vec3(rider, "startPosition", "rider.startPosition", 1000.0),
"travel": v.number(rider, "travelMeters", "rider.travelMeters", 1.0, 900.0),
}
# --- motion ---
var motion := v.object(raw, "motion", "motion", ["startSeconds", "accelSeconds", "brakeStartSeconds", "stopSeconds"])
cfg.motion = {
"start": v.number(motion, "startSeconds", "motion.startSeconds", 0.0, 120.0),
"brake_start": v.number(motion, "brakeStartSeconds", "motion.brakeStartSeconds", 0.0, 120.0),
"stop": v.number(motion, "stopSeconds", "motion.stopSeconds", 0.0, 120.0),
"accel_seconds": v.number(motion, "accelSeconds", "motion.accelSeconds", 0.05, 60.0, -1.0),
}
# --- camera ---
var camera := v.object(raw, "camera", "camera", ["preset", "offset", "lookAtOffset", "fovDegrees", "endOffset", "endLookAtOffset", "transitionStartSeconds", "transitionEndSeconds"])
cfg.camera = {
"preset": v.choice(camera, "preset", "camera.preset", CAMERA_PRESETS),
"offset": v.vec3(camera, "offset", "camera.offset", 60.0),
"look_at_offset": v.vec3(camera, "lookAtOffset", "camera.lookAtOffset", 60.0),
"fov": v.number(camera, "fovDegrees", "camera.fovDegrees", 20.0, 100.0),
}
cfg.camera.end_offset = v.vec3(camera, "endOffset", "camera.endOffset", 60.0, cfg.camera.offset)
cfg.camera.end_look_at_offset = v.vec3(camera, "endLookAtOffset", "camera.endLookAtOffset", 60.0, cfg.camera.look_at_offset)
cfg.camera.transition_start = v.number(camera, "transitionStartSeconds", "camera.transitionStartSeconds", 0.0, 120.0, -1.0)
cfg.camera.transition_end = v.number(camera, "transitionEndSeconds", "camera.transitionEndSeconds", 0.0, 120.0, -1.0)
# --- overlay ---
var overlay := v.object(raw, "overlay", "overlay", ["startSeconds", "fadeSeconds", "title", "choiceA", "choiceB"])
cfg.overlay = {
"start": v.number(overlay, "startSeconds", "overlay.startSeconds", 0.0, 120.0),
"fade_seconds": v.number(overlay, "fadeSeconds", "overlay.fadeSeconds", 0.0, 2.0, 0.4),
"title": v.text(overlay, "title", "overlay.title", 1, 80),
"choice_a": v.text(overlay, "choiceA", "overlay.choiceA", 1, 48),
"choice_b": v.text(overlay, "choiceB", "overlay.choiceB", 1, 48),
}
# --- audio ---
var audio := v.object(raw, "audio", "audio", ["enabled", "file", "offsetSeconds"])
cfg.audio = {
"enabled": v.boolean(audio, "enabled", "audio.enabled"),
"file": v.optional_text(audio, "file", "audio.file", 260),
"offset": v.number(audio, "offsetSeconds", "audio.offsetSeconds", 0.0, 120.0, 0.0),
}
if v.ok():
_check_relations(cfg, v)
return {"ok": v.ok(), "errors": v.errors, "config": cfg if v.ok() else {}}
## Regras que envolvem mais de um campo. Só roda se os campos isolados passaram.
static func _check_relations(cfg: Dictionary, v: Validator) -> void:
var duration: float = cfg.video.duration
var m: Dictionary = cfg.motion
if not (m.start < m.brake_start and m.brake_start < m.stop and m.stop <= duration):
v.fail("motion", "exige startSeconds < brakeStartSeconds < stopSeconds <= durationSeconds (recebido %s < %s < %s <= %s)" % [m.start, m.brake_start, m.stop, duration])
return
var free_run: float = m.brake_start - m.start
if m.accel_seconds < 0.0:
m.accel_seconds = minf(1.5, free_run * 0.5)
elif m.accel_seconds > free_run:
v.fail("motion.accelSeconds", "precisa caber entre startSeconds e brakeStartSeconds (máx. %.2f s)" % free_run)
return
var w: Dictionary = cfg.world
var r: Dictionary = cfg.rider
if absf(r.start_position.x) > w.road_width * 0.5 - 0.5:
v.fail("rider.startPosition", "x precisa ficar dentro da pista (|x| <= %.1f)" % (w.road_width * 0.5 - 0.5))
if r.start_position.y < -0.5 or r.start_position.y > 5.0:
v.fail("rider.startPosition", "y precisa estar entre -0.5 e 5")
if r.start_position.z > 20.0:
v.fail("rider.startPosition", "z precisa ser <= 20 (a rua começa logo atrás da câmera)")
var end_z: float = r.start_position.z - r.travel
if end_z < -w.street_length + STREET_END_MARGIN:
v.fail("rider.travelMeters", "a moto pararia a menos de %d m do fim da rua (fim em z=%.1f, parada em z=%.1f); aumente streetLengthMeters ou reduza o percurso" % [int(STREET_END_MARGIN), -w.street_length, end_z])
var speed := cruise_speed(m, r.travel)
if speed > MAX_CRUISE_SPEED:
v.fail("rider.travelMeters", "percurso exige %.1f m/s de cruzeiro (máx. %.0f m/s); aumente o tempo de movimento ou reduza a distância" % [speed, MAX_CRUISE_SPEED])
var c: Dictionary = cfg.camera
for key in ["offset", "end_offset"]:
var off: Vector3 = c[key]
if r.start_position.y + off.y < MIN_CAMERA_HEIGHT:
v.fail("camera." + ("offset" if key == "offset" else "endOffset"), "câmera ficaria abaixo de %.1f m de altura" % MIN_CAMERA_HEIGHT)
if off.length() < 1.5:
v.fail("camera." + ("offset" if key == "offset" else "endOffset"), "câmera colada no personagem (distância < 1,5 m)")
if c.transition_start < 0.0:
c.transition_start = m.brake_start
if c.transition_end < 0.0:
c.transition_end = minf(duration, cfg.overlay.start + 0.6)
if not (c.transition_start < c.transition_end and c.transition_end <= duration):
v.fail("camera", "exige transitionStartSeconds < transitionEndSeconds <= durationSeconds")
if cfg.overlay.start >= duration:
v.fail("overlay.startSeconds", "precisa ser menor que durationSeconds")
var a: Dictionary = cfg.audio
if a.enabled and typeof(a.file) == TYPE_NIL:
v.fail("audio.file", "obrigatório quando audio.enabled = true")
if a.offset >= duration:
v.fail("audio.offsetSeconds", "precisa ser menor que durationSeconds")
## Velocidade de cruzeiro que faz o perfil (rampa suave, cruzeiro, frenagem
## suave) cobrir exatamente `travel` metros. Cada rampa suave anda metade do que
## andaria em velocidade plena no mesmo tempo.
static func cruise_speed(motion: Dictionary, travel: float) -> float:
var accel: float = motion.accel_seconds
var cruise: float = motion.brake_start - motion.start - accel
var brake: float = motion.stop - motion.brake_start
return travel / (accel * 0.5 + cruise + brake * 0.5)
static func _failure(errors: Array) -> Dictionary:
return {"ok": false, "errors": PackedStringArray(errors), "config": {}}
static func _is_number(value) -> bool:
return (typeof(value) == TYPE_FLOAT or typeof(value) == TYPE_INT) and is_finite(float(value))
## Acumula erros com o caminho do campo, para a mensagem final apontar o lugar exato.
class Validator:
var errors := PackedStringArray()
func ok() -> bool:
return errors.is_empty()
func fail(path: String, message: String) -> void:
errors.append("%s: %s" % [path, message] if path != "" else message)
func check_keys(obj: Dictionary, allowed: Array, path: String) -> void:
for key in obj.keys():
if not allowed.has(key):
fail(path + ("." if path != "" else "") + str(key), "campo desconhecido (permitidos: %s)" % ", ".join(PackedStringArray(allowed)))
func object(parent: Dictionary, key: String, path: String, allowed: Array) -> Dictionary:
var value = parent.get(key)
if typeof(value) != TYPE_DICTIONARY:
fail(path, "obrigatório e precisa ser um objeto")
return {}
check_keys(value, allowed, path)
return value
## `fallback` diferente de null torna o campo opcional.
func number(obj: Dictionary, key: String, path: String, min_value: float, max_value: float, fallback = null) -> float:
if not obj.has(key) or (typeof(obj[key]) == TYPE_NIL and typeof(fallback) != TYPE_NIL):
if typeof(fallback) == TYPE_NIL:
fail(path, "obrigatório")
return 0.0
return fallback
var value = obj[key]
if not _is_number(value):
fail(path, "precisa ser um número finito (recebido %s)" % _describe(value))
return 0.0
var f := float(value)
if f < min_value or f > max_value:
fail(path, "fora do intervalo [%s, %s] (recebido %s)" % [min_value, max_value, f])
return f
func integer(obj: Dictionary, key: String, path: String, min_value: int, max_value: int) -> int:
var f := number(obj, key, path, min_value, max_value)
if obj.has(key) and _is_number(obj[key]) and f != floorf(f):
fail(path, "precisa ser inteiro (recebido %s)" % f)
return int(f)
func boolean(obj: Dictionary, key: String, path: String) -> bool:
if typeof(obj.get(key)) != TYPE_BOOL:
fail(path, "obrigatório e precisa ser true ou false")
return false
return obj[key]
func text(obj: Dictionary, key: String, path: String, min_len: int, max_len: int) -> String:
var value = obj.get(key)
if typeof(value) != TYPE_STRING:
fail(path, "obrigatório e precisa ser texto")
return ""
return _check_text(value, path, min_len, max_len)
func optional_text(obj: Dictionary, key: String, path: String, max_len: int):
var value = obj.get(key)
if typeof(value) == TYPE_NIL:
return null
if typeof(value) != TYPE_STRING:
fail(path, "precisa ser texto ou null")
return null
if value.strip_edges() == "":
return null
return _check_text(value, path, 1, max_len)
func choice(obj: Dictionary, key: String, path: String, options: Array) -> String:
var value = obj.get(key)
if typeof(value) != TYPE_STRING or not options.has(value):
fail(path, "precisa ser um de: %s (recebido %s)" % [", ".join(PackedStringArray(options)), _describe(value)])
return options[0]
return value
func color(obj: Dictionary, key: String, path: String, fallback = null) -> Color:
var value = obj.get(key, fallback)
if typeof(value) == TYPE_NIL:
value = fallback
if typeof(value) != TYPE_STRING or not RegEx.create_from_string("^#[0-9A-Fa-f]{6}$").search(value):
fail(path, "precisa ser uma cor no formato #RRGGBB (recebido %s)" % _describe(value))
return Color.MAGENTA
return Color.html(value)
func vec3(obj: Dictionary, key: String, path: String, max_abs: float, fallback = null) -> Vector3:
if not obj.has(key) and typeof(fallback) != TYPE_NIL:
return fallback
var value = obj.get(key)
if typeof(value) != TYPE_ARRAY or value.size() != 3:
fail(path, "precisa ser uma lista [x, y, z] (recebido %s)" % _describe(value))
return Vector3.ZERO
for item in value:
if not _is_number(item) or absf(float(item)) > max_abs:
fail(path, "cada componente precisa ser número finito com |valor| <= %s" % max_abs)
return Vector3.ZERO
return Vector3(float(value[0]), float(value[1]), float(value[2]))
func _check_text(value: String, path: String, min_len: int, max_len: int) -> String:
var trimmed := value.strip_edges()
if trimmed.length() < min_len or trimmed.length() > max_len:
fail(path, "precisa ter entre %d e %d caracteres (tem %d)" % [min_len, max_len, trimmed.length()])
for i in trimmed.length():
if trimmed.unicode_at(i) < 32 or trimmed.unicode_at(i) == 127:
fail(path, "contém caractere de controle")
break
return trimmed
static func _is_number(value) -> bool:
return (typeof(value) == TYPE_FLOAT or typeof(value) == TYPE_INT) and is_finite(float(value))
func _describe(value) -> String:
if typeof(value) == TYPE_NIL:
return "nada"
var s := JSON.stringify(value)
return s if s.length() <= 40 else s.substr(0, 37) + "..."