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>
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://bx1qgayxuhe44"
|
||||
path="res://.godot/imported/facade_00.png-b6e50b47d80c25746138e1b9f8c2ac83.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_00.png"
|
||||
dest_files=["res://.godot/imported/facade_00.png-b6e50b47d80c25746138e1b9f8c2ac83.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 50 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://cc4te1cx5il6d"
|
||||
path="res://.godot/imported/facade_01.png-9453391b69f713985b7ae4903094587d.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_01.png"
|
||||
dest_files=["res://.godot/imported/facade_01.png-9453391b69f713985b7ae4903094587d.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://crlh8t1p8osmr"
|
||||
path="res://.godot/imported/facade_02.png-8e75bfa1062aff4324df25842a12617c.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_02.png"
|
||||
dest_files=["res://.godot/imported/facade_02.png-8e75bfa1062aff4324df25842a12617c.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://c43lcl13u2vnr"
|
||||
path="res://.godot/imported/facade_03.png-79f5be0c1b526dbdee352f4b37cb5eae.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_03.png"
|
||||
dest_files=["res://.godot/imported/facade_03.png-79f5be0c1b526dbdee352f4b37cb5eae.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://rhhumceas2gt"
|
||||
path="res://.godot/imported/facade_04.png-fe6c0b9fc603273d1f631c28dab357aa.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_04.png"
|
||||
dest_files=["res://.godot/imported/facade_04.png-fe6c0b9fc603273d1f631c28dab357aa.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://c5u11pybth6xg"
|
||||
path="res://.godot/imported/facade_05.png-9cb33af8bc9def1296625cb8bafe7ace.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_05.png"
|
||||
dest_files=["res://.godot/imported/facade_05.png-9cb33af8bc9def1296625cb8bafe7ace.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://emu4yxef27fk"
|
||||
path="res://.godot/imported/facade_06.png-6d9085aa18aeadc632f17b226f5d60eb.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_06.png"
|
||||
dest_files=["res://.godot/imported/facade_06.png-6d9085aa18aeadc632f17b226f5d60eb.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
|
After Width: | Height: | Size: 35 KiB |
@@ -0,0 +1,40 @@
|
||||
[remap]
|
||||
|
||||
importer="texture"
|
||||
type="CompressedTexture2D"
|
||||
uid="uid://2c1u08v6tq0l"
|
||||
path="res://.godot/imported/facade_07.png-1bc84ab6118fabfa34d700d380d34d5a.ctex"
|
||||
metadata={
|
||||
"vram_texture": false
|
||||
}
|
||||
|
||||
[deps]
|
||||
|
||||
source_file="res://assets/backgrounds/facade_07.png"
|
||||
dest_files=["res://.godot/imported/facade_07.png-1bc84ab6118fabfa34d700d380d34d5a.ctex"]
|
||||
|
||||
[params]
|
||||
|
||||
compress/mode=0
|
||||
compress/high_quality=false
|
||||
compress/lossy_quality=0.7
|
||||
compress/uastc_level=0
|
||||
compress/rdo_quality_loss=0.0
|
||||
compress/hdr_compression=1
|
||||
compress/normal_map=0
|
||||
compress/channel_pack=0
|
||||
mipmaps/generate=false
|
||||
mipmaps/limit=-1
|
||||
roughness/mode=0
|
||||
roughness/src_normal=""
|
||||
process/channel_remap/red=0
|
||||
process/channel_remap/green=1
|
||||
process/channel_remap/blue=2
|
||||
process/channel_remap/alpha=3
|
||||
process/fix_alpha_border=true
|
||||
process/premult_alpha=false
|
||||
process/normal_map_invert_y=false
|
||||
process/hdr_as_srgb=false
|
||||
process/hdr_clamp_exposure=false
|
||||
process/size_limit=0
|
||||
detect_3d/compress_to=1
|
||||
@@ -0,0 +1,164 @@
|
||||
extends Node3D
|
||||
## Peça reaproveitável: lancha de pesca (~8 m) low-poly, com balanço e afundamento.
|
||||
##
|
||||
## const Boat := preload("res://kits/boat.gd")
|
||||
## var b := Boat.new()
|
||||
## b.build({"hull": "#f2f0ea", "stripe": "#1f5fa8", "cabin": "#e9e6df", "lights": true})
|
||||
## add_child(b)
|
||||
## # em apply(t):
|
||||
## b.float_on(t, 1.0) # balanço no mar (intensidade 0 = calmo, 1 = normal, 2 = agitado)
|
||||
## b.sink(0.6) # 0 = flutuando; 1 = quase submerso (popa afunda primeiro, adernado)
|
||||
##
|
||||
## Origem no centro do casco na linha d'água (y = 0 é o nível do mar), proa em -Z.
|
||||
|
||||
const LENGTH := 8.0
|
||||
const BEAM := 2.6
|
||||
|
||||
var _body: Node3D
|
||||
var _sink := 0.0
|
||||
var _materials := {}
|
||||
var _lights: Array[MeshInstance3D] = []
|
||||
|
||||
|
||||
func build(opts: Dictionary = {}) -> void:
|
||||
var hull := Color(str(opts.get("hull", "#f2f0ea")))
|
||||
var stripe := Color(str(opts.get("stripe", "#1f5fa8")))
|
||||
var cabin := Color(str(opts.get("cabin", "#e9e6df")))
|
||||
_body = Node3D.new()
|
||||
_body.name = "Body"
|
||||
add_child(_body)
|
||||
_build_hull(hull, stripe)
|
||||
# Convés.
|
||||
var deck := BoxMesh.new()
|
||||
deck.size = Vector3(BEAM * 0.86, 0.08, LENGTH * 0.78)
|
||||
_add(_body, deck, Color("#9a7b55"), Vector3(0, 0.62, 0.35))
|
||||
# Cabine com janelas.
|
||||
var box := BoxMesh.new()
|
||||
box.size = Vector3(BEAM * 0.62, 1.3, 2.2)
|
||||
_add(_body, box, cabin, Vector3(0, 1.3, -0.4))
|
||||
var roof := BoxMesh.new()
|
||||
roof.size = Vector3(BEAM * 0.7, 0.1, 2.5)
|
||||
_add(_body, roof, stripe, Vector3(0, 1.99, -0.4))
|
||||
for i in 3:
|
||||
var win := BoxMesh.new()
|
||||
win.size = Vector3(BEAM * 0.63, 0.34, 0.5)
|
||||
_add(_body, win, Color("#1d2c3a"), Vector3(0, 1.5, -1.15 + i * 0.68))
|
||||
var front := BoxMesh.new()
|
||||
front.size = Vector3(BEAM * 0.55, 0.4, 0.05)
|
||||
_add(_body, front, Color("#1d2c3a"), Vector3(0, 1.5, -1.52))
|
||||
# Antena e mastro.
|
||||
var mast := CylinderMesh.new()
|
||||
mast.top_radius = 0.03
|
||||
mast.bottom_radius = 0.04
|
||||
mast.height = 2.0
|
||||
_add(_body, mast, Color("#d8d8d8"), Vector3(0, 3.0, -0.2))
|
||||
# Grade (amurada) dos dois lados.
|
||||
for sx in [-1.0, 1.0]:
|
||||
var rail := BoxMesh.new()
|
||||
rail.size = Vector3(0.04, 0.04, LENGTH * 0.6)
|
||||
_add(_body, rail, Color("#cfcfcf"), Vector3(sx * BEAM * 0.42, 1.0, 0.9))
|
||||
# Luzes de navegação (bombordo vermelha, boreste verde, branca no mastro).
|
||||
if bool(opts.get("lights", true)):
|
||||
_lights.append(_light(Vector3(-BEAM * 0.36, 2.05, -1.2), Color("#ff3b30")))
|
||||
_lights.append(_light(Vector3(BEAM * 0.36, 2.05, -1.2), Color("#34c759")))
|
||||
_lights.append(_light(Vector3(0, 4.02, -0.2), Color("#fff6d8")))
|
||||
|
||||
|
||||
## Altura do convés no corpo do barco (pés de quem está a bordo).
|
||||
const DECK_Y := 0.66
|
||||
|
||||
|
||||
## Corpo do barco (balança e afunda): pessoas e objetos a bordo entram como filhos dele,
|
||||
## com o pé em y = DECK_Y; popa em +Z (z de 0,8 a 3,4 livre atrás da cabine).
|
||||
func deck() -> Node3D:
|
||||
return _body
|
||||
|
||||
|
||||
## Balanço determinístico no mar (sobe/desce, arfagem e jogo).
|
||||
func float_on(t: float, intensity := 1.0) -> void:
|
||||
var k := intensity
|
||||
_body.position = Vector3(0, sin(t * 1.3) * 0.18 * k - _sink * 1.9, 0)
|
||||
_body.rotation = Vector3(
|
||||
sin(t * 0.9 + 0.7) * 0.05 * k + _sink * 0.42, # popa afunda primeiro
|
||||
sin(t * 0.35) * 0.03 * k,
|
||||
sin(t * 1.1) * 0.07 * k + _sink * 0.35) # adernando
|
||||
|
||||
|
||||
## 0 = flutuando; 1 = quase submerso. Chame antes de float_on no mesmo quadro.
|
||||
func sink(amount: float) -> void:
|
||||
_sink = clampf(amount, 0.0, 1.0)
|
||||
for l in _lights:
|
||||
l.visible = _sink < 0.75
|
||||
|
||||
|
||||
func _build_hull(hull: Color, stripe: Color) -> void:
|
||||
# Casco: seções em "V" ao longo do comprimento, fechando na proa.
|
||||
var st := SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
var sections := 14
|
||||
var rows: Array = []
|
||||
for i in sections + 1:
|
||||
var u := float(i) / sections # 0 = popa, 1 = proa
|
||||
var z := LENGTH * 0.5 - u * LENGTH
|
||||
var width := BEAM * 0.5 * (1.0 - pow(maxf(u - 0.55, 0.0) / 0.45, 1.6))
|
||||
width = maxf(width, 0.02)
|
||||
var keel := -0.75 + u * 0.15
|
||||
var top := 0.65 + pow(u, 3.0) * 0.45 # proa mais alta
|
||||
rows.append([Vector3(-width, top, z), Vector3(-width * 0.8, 0.0, z), Vector3(0, keel, z), Vector3(width * 0.8, 0.0, z), Vector3(width, top, z)])
|
||||
for i in sections:
|
||||
for k in 4:
|
||||
var a: Vector3 = rows[i][k]
|
||||
var b: Vector3 = rows[i][k + 1]
|
||||
var c: Vector3 = rows[i + 1][k]
|
||||
var d: Vector3 = rows[i + 1][k + 1]
|
||||
var col := stripe if (k == 0 or k == 3) and i < sections - 1 else hull
|
||||
for v in [a, c, b, b, c, d]:
|
||||
st.set_color(col)
|
||||
st.add_vertex(v)
|
||||
# Popa fechada.
|
||||
var r0: Array = rows[0]
|
||||
for k in [[0, 1, 2], [0, 2, 4], [2, 3, 4]]:
|
||||
for idx in k:
|
||||
st.set_color(hull)
|
||||
st.add_vertex(r0[idx])
|
||||
st.generate_normals()
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.vertex_color_use_as_albedo = true
|
||||
mat.roughness = 0.55
|
||||
mat.cull_mode = BaseMaterial3D.CULL_DISABLED
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = st.commit()
|
||||
mi.material_override = mat
|
||||
_body.add_child(mi)
|
||||
|
||||
|
||||
func _light(pos: Vector3, color: Color) -> MeshInstance3D:
|
||||
var mesh := SphereMesh.new()
|
||||
mesh.radius = 0.07
|
||||
mesh.height = 0.14
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.albedo_color = color
|
||||
mat.emission_enabled = true
|
||||
mat.emission = color
|
||||
mat.emission_energy_multiplier = 4.0
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
mi.material_override = mat
|
||||
mi.position = pos
|
||||
_body.add_child(mi)
|
||||
return mi
|
||||
|
||||
|
||||
func _add(parent: Node3D, mesh: Mesh, color: Color, pos: Vector3) -> MeshInstance3D:
|
||||
var key := color.to_html()
|
||||
if not _materials.has(key):
|
||||
var m := StandardMaterial3D.new()
|
||||
m.albedo_color = color
|
||||
m.roughness = 0.7
|
||||
_materials[key] = m
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
mi.material_override = _materials[key]
|
||||
mi.position = pos
|
||||
parent.add_child(mi)
|
||||
return mi
|
||||
@@ -0,0 +1,254 @@
|
||||
extends Node3D
|
||||
## Peça reaproveitável: pessoa estilizada (low-poly) com juntas e animações por tempo.
|
||||
##
|
||||
## const Person := preload("res://kits/person.gd")
|
||||
## var p := Person.new()
|
||||
## p.build({"shirt": "#2f6fb3", "pants": "#3a3a3a", "skin": "#c68e6a", "hair": "#2b1d14", "height": 1.75})
|
||||
## # opções: "sleeveless": true (regata, braço de fora), "shorts": true (bermuda), "vest", "shoes"
|
||||
## add_child(p)
|
||||
## # em apply(t):
|
||||
## p.pose("walk", t) # parado | andar | correr | nadar | sentar | acenar | ajoelhar | deitar
|
||||
## p.blend("walk", "run", t, 0.3) # mistura duas poses (0 = a primeira, 1 = a segunda)
|
||||
##
|
||||
## Origem nos pés (y = 0 é o chão), frente em -Z. Tudo depende só de t: determinístico.
|
||||
## Poses: "idle", "walk", "run", "swim", "sit", "wave", "kneel", "lie", "exhausted".
|
||||
|
||||
var joints := {} # nome → Node3D (hips, spine, chest, neck, head, shoulder_l/r, elbow_l/r, hip_l/r, knee_l/r)
|
||||
var height := 1.75
|
||||
var _s := 1.0 # escala (altura / 1,75)
|
||||
var _materials := {}
|
||||
|
||||
|
||||
func build(opts: Dictionary = {}) -> void:
|
||||
height = float(opts.get("height", 1.75))
|
||||
_s = height / 1.75
|
||||
var shirt := Color(str(opts.get("shirt", "#2f6fb3")))
|
||||
var pants := Color(str(opts.get("pants", "#34363a")))
|
||||
var skin := Color(str(opts.get("skin", "#c68e6a")))
|
||||
var hair := Color(str(opts.get("hair", "#2b1d14")))
|
||||
var shoes := Color(str(opts.get("shoes", "#1c1c1c")))
|
||||
var vest = opts.get("vest") # colete salva-vidas, ex.: "#ff6a00" (opcional)
|
||||
var arm := skin if bool(opts.get("sleeveless", false)) else shirt # regata: braço de fora
|
||||
var shin := skin if bool(opts.get("shorts", false)) else pants # bermuda: canela de fora
|
||||
|
||||
var hips := _joint("hips", self, Vector3(0, 0.95, 0))
|
||||
var spine := _joint("spine", hips, Vector3(0, 0.08, 0))
|
||||
var chest := _joint("chest", spine, Vector3(0, 0.28, 0))
|
||||
var neck := _joint("neck", chest, Vector3(0, 0.22, 0))
|
||||
var head := _joint("head", neck, Vector3(0, 0.1, 0))
|
||||
# Tronco e quadril.
|
||||
_capsule(hips, 0.17, 0.32, pants, Vector3(0, -0.02, 0), Vector3(0, 0, PI / 2))
|
||||
_capsule(spine, 0.16, 0.42, shirt, Vector3(0, 0.16, 0))
|
||||
_capsule(chest, 0.19, 0.36, shirt, Vector3(0, 0.06, 0), Vector3(0, 0, PI / 2))
|
||||
if vest != null:
|
||||
_box(chest, Vector3(0.44, 0.36, 0.26), Color(str(vest)), Vector3(0, -0.02, 0))
|
||||
_capsule(neck, 0.05, 0.12, skin, Vector3(0, 0.02, 0))
|
||||
_sphere(head, 0.12, skin, Vector3(0, 0.1, 0))
|
||||
_sphere(head, 0.125, hair, Vector3(0, 0.15, 0.02), Vector3(1.0, 0.62, 1.0)) # cabelo
|
||||
_sphere(head, 0.02, Color("#1a1a1a"), Vector3(-0.045, 0.11, -0.11)) # olhos
|
||||
_sphere(head, 0.02, Color("#1a1a1a"), Vector3(0.045, 0.11, -0.11))
|
||||
# Braços: ombro → cotovelo → mão.
|
||||
for side in ["l", "r"]:
|
||||
var sx := -1.0 if side == "l" else 1.0
|
||||
var shoulder := _joint("shoulder_" + side, chest, Vector3(0.22 * sx, 0.14, 0))
|
||||
_capsule(shoulder, 0.055, 0.3, arm, Vector3(0, -0.14, 0))
|
||||
var elbow := _joint("elbow_" + side, shoulder, Vector3(0, -0.29, 0))
|
||||
_capsule(elbow, 0.047, 0.27, skin, Vector3(0, -0.13, 0))
|
||||
_sphere(elbow, 0.05, skin, Vector3(0, -0.28, 0))
|
||||
# Pernas: quadril → joelho → pé.
|
||||
var hip := _joint("hip_" + side, hips, Vector3(0.1 * sx, -0.05, 0))
|
||||
_capsule(hip, 0.08, 0.44, pants, Vector3(0, -0.21, 0))
|
||||
var knee := _joint("knee_" + side, hip, Vector3(0, -0.43, 0))
|
||||
_capsule(knee, 0.065, 0.42, shin, Vector3(0, -0.2, 0))
|
||||
_box(knee, Vector3(0.1, 0.07, 0.24), shoes, Vector3(0, -0.43, -0.05))
|
||||
scale = Vector3.ONE * _s
|
||||
pose("idle", 0.0)
|
||||
|
||||
|
||||
## Aplica uma pose no instante t (segundos). Ver lista no topo.
|
||||
func pose(action: String, t: float, amount := 1.0) -> void:
|
||||
var r := _pose_values(action, t)
|
||||
for k in r.keys():
|
||||
if k == "root_y" or k == "root_rx" or k == "root_rz":
|
||||
continue
|
||||
var j: Node3D = joints[k]
|
||||
j.rotation = r[k] * amount
|
||||
joints.hips.position = Vector3(0, 0.95 + float(r.get("root_y", 0.0)) * amount, 0)
|
||||
joints.hips.rotation.x = float(r.get("root_rx", 0.0)) * amount
|
||||
joints.hips.rotation.z = float(r.get("root_rz", 0.0)) * amount
|
||||
|
||||
|
||||
## Mistura duas poses (k de 0 a 1), por exemplo "walk" → "kneel" quando o personagem chega.
|
||||
func blend(a: String, b: String, t: float, k: float) -> void:
|
||||
var ra := _pose_values(a, t)
|
||||
var rb := _pose_values(b, t)
|
||||
var keys := {}
|
||||
for key in ra.keys():
|
||||
keys[key] = true
|
||||
for key in rb.keys():
|
||||
keys[key] = true
|
||||
for key in keys.keys():
|
||||
var va = ra.get(key, Vector3.ZERO if not key.begins_with("root") else 0.0)
|
||||
var vb = rb.get(key, Vector3.ZERO if not key.begins_with("root") else 0.0)
|
||||
var v = lerp(va, vb, clampf(k, 0.0, 1.0))
|
||||
if key == "root_y":
|
||||
joints.hips.position = Vector3(0, 0.95 + float(v), 0)
|
||||
elif key == "root_rx":
|
||||
joints.hips.rotation.x = float(v)
|
||||
elif key == "root_rz":
|
||||
joints.hips.rotation.z = float(v)
|
||||
else:
|
||||
(joints[key] as Node3D).rotation = v
|
||||
|
||||
|
||||
func _pose_values(action: String, t: float) -> Dictionary:
|
||||
var v := {}
|
||||
for k in joints.keys():
|
||||
v[k] = Vector3.ZERO
|
||||
match action:
|
||||
"walk", "run":
|
||||
var run := action == "run"
|
||||
var w := t * (8.5 if run else 5.6)
|
||||
var amp := 0.85 if run else 0.5
|
||||
v.hip_l = Vector3(sin(w) * amp, 0, 0)
|
||||
v.hip_r = Vector3(-sin(w) * amp, 0, 0)
|
||||
v.knee_l = Vector3(maxf(0.0, -sin(w + 0.9)) * (1.4 if run else 0.9), 0, 0)
|
||||
v.knee_r = Vector3(maxf(0.0, sin(w + 0.9)) * (1.4 if run else 0.9), 0, 0)
|
||||
v.shoulder_l = Vector3(-sin(w) * amp * 0.9, 0, 0.08)
|
||||
v.shoulder_r = Vector3(sin(w) * amp * 0.9, 0, -0.08)
|
||||
v.elbow_l = Vector3(-(1.3 if run else 0.35), 0, 0)
|
||||
v.elbow_r = Vector3(-(1.3 if run else 0.35), 0, 0)
|
||||
v.spine = Vector3(-(0.22 if run else 0.05), 0, 0)
|
||||
v.root_y = absf(sin(w)) * (0.06 if run else 0.025) - (0.04 if run else 0.0)
|
||||
"swim":
|
||||
# Crawl: corpo deitado na água, braços em círculo alternado, pernas batendo.
|
||||
var w := t * 3.2
|
||||
v.root_rx = -PI / 2.0 + 0.1
|
||||
v.root_y = -0.85
|
||||
v.shoulder_l = Vector3(w, 0, 0.15)
|
||||
v.shoulder_r = Vector3(w + PI, 0, -0.15)
|
||||
v.elbow_l = Vector3(-0.3, 0, 0)
|
||||
v.elbow_r = Vector3(-0.3, 0, 0)
|
||||
v.hip_l = Vector3(sin(w * 3.0) * 0.3, 0, 0)
|
||||
v.hip_r = Vector3(-sin(w * 3.0) * 0.3, 0, 0)
|
||||
v.neck = Vector3(0.5, sin(w) * 0.5, 0)
|
||||
v.root_rz = sin(w) * 0.25
|
||||
"sit":
|
||||
v.root_y = -0.5
|
||||
v.hip_l = Vector3(-PI / 2.0 + 0.1, 0, 0.08)
|
||||
v.hip_r = Vector3(-PI / 2.0 + 0.1, 0, -0.08)
|
||||
v.knee_l = Vector3(PI / 2.0 - 0.2, 0, 0)
|
||||
v.knee_r = Vector3(PI / 2.0 - 0.2, 0, 0)
|
||||
v.shoulder_l = Vector3(-0.4, 0, 0.1)
|
||||
v.shoulder_r = Vector3(-0.4, 0, -0.1)
|
||||
v.elbow_l = Vector3(-0.8, 0, 0)
|
||||
v.elbow_r = Vector3(-0.8, 0, 0)
|
||||
v.spine = Vector3(-0.25 + sin(t * 1.6) * 0.03, 0, 0)
|
||||
v.neck = Vector3(0.25, 0, 0)
|
||||
"wave":
|
||||
v.shoulder_r = Vector3(-PI + 0.3, 0, -0.3)
|
||||
v.elbow_r = Vector3(-0.5 + sin(t * 9.0) * 0.45, 0, 0)
|
||||
v.shoulder_l = Vector3(0.05, 0, 0.08)
|
||||
v.spine = Vector3(0.04, 0, 0)
|
||||
v.root_y = absf(sin(t * 4.5)) * 0.02
|
||||
"kneel":
|
||||
v.root_y = -0.42
|
||||
v.hip_l = Vector3(-PI / 2.0 + 0.2, 0, 0.05)
|
||||
v.knee_l = Vector3(PI / 2.0 - 0.1, 0, 0)
|
||||
v.hip_r = Vector3(0.2, 0, -0.05)
|
||||
v.knee_r = Vector3(PI / 2.0 + 0.3, 0, 0)
|
||||
v.spine = Vector3(-0.35, 0, 0)
|
||||
v.shoulder_l = Vector3(-0.6, 0, 0.1)
|
||||
v.shoulder_r = Vector3(-0.6, 0, -0.1)
|
||||
v.elbow_l = Vector3(-0.6, 0, 0)
|
||||
v.elbow_r = Vector3(-0.6, 0, 0)
|
||||
"exhausted":
|
||||
# Curvado, mãos nos joelhos, respirando fundo.
|
||||
var b := sin(t * 2.4) * 0.04
|
||||
v.spine = Vector3(-0.75 + b, 0, 0)
|
||||
v.chest = Vector3(-0.15, 0, 0)
|
||||
v.hip_l = Vector3(-0.35, 0, 0.06)
|
||||
v.hip_r = Vector3(-0.35, 0, -0.06)
|
||||
v.knee_l = Vector3(0.55, 0, 0)
|
||||
v.knee_r = Vector3(0.55, 0, 0)
|
||||
v.shoulder_l = Vector3(-0.55, 0, 0.12)
|
||||
v.shoulder_r = Vector3(-0.55, 0, -0.12)
|
||||
v.elbow_l = Vector3(-0.25, 0, 0)
|
||||
v.elbow_r = Vector3(-0.25, 0, 0)
|
||||
v.neck = Vector3(0.45, 0, 0)
|
||||
v.root_y = -0.14
|
||||
"lie":
|
||||
# Deitado de costas, exausto (respiração visível).
|
||||
v.root_rx = PI / 2.0
|
||||
v.root_y = -0.82
|
||||
v.chest = Vector3(sin(t * 2.0) * 0.04, 0, 0)
|
||||
v.shoulder_l = Vector3(0.2, 0, 0.6)
|
||||
v.shoulder_r = Vector3(0.2, 0, -0.6)
|
||||
v.hip_r = Vector3(-0.3, 0, 0)
|
||||
v.knee_r = Vector3(0.6, 0, 0)
|
||||
_:
|
||||
# idle: respiração e peso mudando de perna.
|
||||
v.chest = Vector3(sin(t * 1.8) * 0.025, 0, 0)
|
||||
v.spine = Vector3(0, sin(t * 0.6) * 0.04, 0)
|
||||
v.shoulder_l = Vector3(0.05, 0, 0.08)
|
||||
v.shoulder_r = Vector3(0.05, 0, -0.08)
|
||||
v.elbow_l = Vector3(-0.15, 0, 0)
|
||||
v.elbow_r = Vector3(-0.15, 0, 0)
|
||||
return v
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ montagem
|
||||
|
||||
func _joint(joint_name: String, parent: Node3D, offset: Vector3) -> Node3D:
|
||||
var j := Node3D.new()
|
||||
j.name = joint_name
|
||||
j.position = offset
|
||||
parent.add_child(j)
|
||||
joints[joint_name] = j
|
||||
return j
|
||||
|
||||
|
||||
func _material(color: Color) -> StandardMaterial3D:
|
||||
var key := color.to_html()
|
||||
if not _materials.has(key):
|
||||
var m := StandardMaterial3D.new()
|
||||
m.albedo_color = color
|
||||
m.roughness = 0.8
|
||||
_materials[key] = m
|
||||
return _materials[key]
|
||||
|
||||
|
||||
func _capsule(parent: Node3D, radius: float, length: float, color: Color, pos: Vector3, rot := Vector3.ZERO) -> MeshInstance3D:
|
||||
var mesh := CapsuleMesh.new()
|
||||
mesh.radius = radius
|
||||
mesh.height = maxf(length, radius * 2.0)
|
||||
mesh.radial_segments = 10
|
||||
mesh.rings = 4
|
||||
return _add(parent, mesh, color, pos, rot)
|
||||
|
||||
|
||||
func _sphere(parent: Node3D, radius: float, color: Color, pos: Vector3, scl := Vector3.ONE) -> MeshInstance3D:
|
||||
var mesh := SphereMesh.new()
|
||||
mesh.radius = radius
|
||||
mesh.height = radius * 2.0
|
||||
mesh.radial_segments = 12
|
||||
mesh.rings = 6
|
||||
var mi := _add(parent, mesh, color, pos)
|
||||
mi.scale = scl
|
||||
return mi
|
||||
|
||||
|
||||
func _box(parent: Node3D, size: Vector3, color: Color, pos: Vector3) -> MeshInstance3D:
|
||||
var mesh := BoxMesh.new()
|
||||
mesh.size = size
|
||||
return _add(parent, mesh, color, pos)
|
||||
|
||||
|
||||
func _add(parent: Node3D, mesh: Mesh, color: Color, pos: Vector3, rot := Vector3.ZERO) -> MeshInstance3D:
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
mi.material_override = _material(color)
|
||||
mi.position = pos
|
||||
mi.rotation = rot
|
||||
parent.add_child(mi)
|
||||
return mi
|
||||
@@ -0,0 +1,12 @@
|
||||
extends "res://kits/person.gd"
|
||||
## Mantém o kit e suas roupas; flexão das poses voltada para a frente local (-Z).
|
||||
|
||||
|
||||
func _pose_values(action: String, t: float) -> Dictionary:
|
||||
var values: Dictionary = super._pose_values(action, t)
|
||||
if action in ["sit", "kneel", "exhausted"]:
|
||||
for key in ["hip_l", "hip_r", "knee_l", "knee_r", "spine", "chest", "shoulder_l", "shoulder_r", "elbow_l", "elbow_r"]:
|
||||
var angle: Vector3 = values[key]
|
||||
angle.x *= -1.0
|
||||
values[key] = angle
|
||||
return values
|
||||
@@ -0,0 +1,28 @@
|
||||
extends RefCounted
|
||||
## Elenco e barcos da reconstituição dos náufragos (opções de res://kits/person.gd e boat.gd).
|
||||
## Elenilson: regata cinza e bermuda escura (convenção visual do roteiro, igual em todo o vídeo).
|
||||
## Os companheiros usam cores discretas e diferentes entre si, nenhuma cinza.
|
||||
|
||||
const LOOKS := {
|
||||
"elenilson": {"shirt": "#8f9297", "pants": "#24272c", "skin": "#b27a54", "hair": "#17110d",
|
||||
"shoes": "#3b2a1f", "height": 1.74, "sleeveless": true, "shorts": true},
|
||||
"ivan": {"shirt": "#3c5272", "pants": "#4b4236", "skin": "#8a5838", "hair": "#120d0a",
|
||||
"shoes": "#2a2420", "height": 1.70},
|
||||
"manoel": {"shirt": "#7b3d34", "pants": "#3c4047", "skin": "#c69772", "hair": "#55534f",
|
||||
"shoes": "#2a2420", "height": 1.67},
|
||||
"iranildo": {"shirt": "#5c6a48", "pants": "#6d685b", "skin": "#a26a47", "hair": "#1e1611",
|
||||
"shoes": "#2a2420", "height": 1.78, "shorts": true},
|
||||
# Os outros dois homens do pesqueiro (aparecem só no naufrágio).
|
||||
"crew_a": {"shirt": "#9c5a30", "pants": "#2c2c2c", "skin": "#b98560", "hair": "#1a1410", "height": 1.72},
|
||||
"crew_b": {"shirt": "#2f3b31", "pants": "#3a352f", "skin": "#94603f", "hair": "#120d0a", "height": 1.69},
|
||||
# Equipe de mergulho da lancha (roupa de neoprene).
|
||||
"diver_a": {"shirt": "#17191d", "pants": "#17191d", "skin": "#c08a64", "hair": "#2a1d14",
|
||||
"shoes": "#101114", "height": 1.76},
|
||||
"diver_b": {"shirt": "#1d2a3a", "pants": "#17191d", "skin": "#9c6b48", "hair": "#120d0a",
|
||||
"shoes": "#101114", "height": 1.73},
|
||||
}
|
||||
|
||||
## Pesqueiro de madeira pintado (azul e vermelho, cabine creme), sem nome no casco.
|
||||
const FISHING_BOAT := {"hull": "#2d5b86", "stripe": "#b5382b", "cabin": "#e6dfcc", "lights": true}
|
||||
## Lancha de mergulho civil: branca com faixa laranja.
|
||||
const DIVE_BOAT := {"hull": "#f3f2ee", "stripe": "#e2701c", "cabin": "#f7f6f2", "lights": false}
|
||||
@@ -0,0 +1,153 @@
|
||||
{
|
||||
"id": "castaways",
|
||||
"kind": "doc3d",
|
||||
"label": "Náufragos no costão",
|
||||
"description": "Reconstituição estilizada: quatro pescadores, pesqueiro e lancha civil na ilha. Chegada, naufrágio, nado, espera, resgate, embarque e partida. Elenilson mantém regata cinza e bermuda escura; roupas e gestos são ilustrativos.",
|
||||
"keywords": [
|
||||
"náufrago",
|
||||
"pescador",
|
||||
"pesqueiro",
|
||||
"costão",
|
||||
"lancha",
|
||||
"resgate",
|
||||
"nadando",
|
||||
"Elenilson",
|
||||
"apoia a mão",
|
||||
"ergue o corpo",
|
||||
"joelhos",
|
||||
"recuperando o fôlego",
|
||||
"companheiros",
|
||||
"convés",
|
||||
"casco",
|
||||
"silhuetas próximas",
|
||||
"sentado observa",
|
||||
"se levanta",
|
||||
"acena",
|
||||
"mergulhador",
|
||||
"subida assistida",
|
||||
"acomodados",
|
||||
"sentado em silêncio",
|
||||
"repousa",
|
||||
"costão à noite",
|
||||
"passagem de noite",
|
||||
"indica a espera",
|
||||
"ainda a bordo",
|
||||
"costão que se distancia"
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "moment",
|
||||
"label": "Momento",
|
||||
"type": "select",
|
||||
"default": "arrival",
|
||||
"options": [
|
||||
{
|
||||
"value": "arrival",
|
||||
"label": "Chegada às rochas",
|
||||
"keywords": [
|
||||
"apoia a mão",
|
||||
"ergue o corpo",
|
||||
"joelhos",
|
||||
"recuperando o fôlego",
|
||||
"perfil estilizado"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "sinking",
|
||||
"label": "Pesqueiro naufragando",
|
||||
"keywords": [
|
||||
"acidente",
|
||||
"pesqueiro",
|
||||
"convés",
|
||||
"inclinação",
|
||||
"cobrindo o casco",
|
||||
"anoitecendo"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "swimming",
|
||||
"label": "Travessia a nado",
|
||||
"keywords": [
|
||||
"mar escuro",
|
||||
"nadando",
|
||||
"silhuetas próximas",
|
||||
"travessia condensada",
|
||||
"mãos buscando"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "waiting",
|
||||
"label": "Espera no costão",
|
||||
"keywords": [
|
||||
"costão à noite",
|
||||
"sentado observa",
|
||||
"repousa",
|
||||
"passagem de noite",
|
||||
"indica a espera"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "rescue",
|
||||
"label": "Acenos e aproximação",
|
||||
"keywords": [
|
||||
"se levanta",
|
||||
"acena",
|
||||
"mergulhadores aproximando",
|
||||
"homens ainda pequenos",
|
||||
"costão de dia"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "boarding",
|
||||
"label": "Nado e subida à lancha",
|
||||
"keywords": [
|
||||
"entra na água",
|
||||
"nada até a equipe",
|
||||
"subida assistida",
|
||||
"acomodados a bordo",
|
||||
"ombro de um mergulhador"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "departure",
|
||||
"label": "Partida com os sobreviventes",
|
||||
"keywords": [
|
||||
"afastando-se",
|
||||
"sentado em silêncio",
|
||||
"ainda a bordo",
|
||||
"se distancia",
|
||||
"costão que se distancia"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "camera",
|
||||
"label": "Distância da câmera",
|
||||
"type": "select",
|
||||
"default": "medium",
|
||||
"options": [
|
||||
{
|
||||
"value": "medium",
|
||||
"label": "Média"
|
||||
},
|
||||
{
|
||||
"value": "close",
|
||||
"label": "Próxima"
|
||||
},
|
||||
{
|
||||
"value": "wide",
|
||||
"label": "Aberta"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "variant",
|
||||
"label": "Variação de ângulo",
|
||||
"type": "number",
|
||||
"default": 0
|
||||
}
|
||||
],
|
||||
"createdBy": "Codex (continuação da cena CenaForge)",
|
||||
"createdAt": "2026-11-17"
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
extends "res://library/island/template.gd"
|
||||
## Ilha reutilizada com uma pequena laje de costão para encenação, sem precisão topográfica.
|
||||
## A malha e ground_at compartilham as mesmas alturas; a ilha original não é modificada.
|
||||
|
||||
var _stage_enabled := false
|
||||
var _stage_center := Vector3.ZERO
|
||||
var _stage_sea := Vector3.FORWARD
|
||||
|
||||
|
||||
func prepare_coast(center: Vector3, sea: Vector3) -> void:
|
||||
_stage_center = center
|
||||
_stage_sea = sea
|
||||
_stage_enabled = true
|
||||
var terrain := get_node("Terrain")
|
||||
remove_child(terrain)
|
||||
terrain.free()
|
||||
_build_terrain()
|
||||
var material: StandardMaterial3D = get_node("Terrain").material_override
|
||||
material.albedo_color = Color("#777b80")
|
||||
|
||||
|
||||
func height_at(x: float, z: float) -> float:
|
||||
var original := super.height_at(x, z)
|
||||
if not _stage_enabled:
|
||||
return original
|
||||
var offset := Vector3(x - _stage_center.x, 0, z - _stage_center.z)
|
||||
var blend := 1.0 - smoothstep(4.2, 8.0, offset.length())
|
||||
var shelf := _stage_center.y - 3.5 * smoothstep(0.6, 5.5, offset.dot(_stage_sea))
|
||||
return lerpf(original, shelf, blend)
|
||||
|
||||
|
||||
func _terrain_color(h: float, slope: float, x: float, z: float) -> Color:
|
||||
var original := super._terrain_color(h, slope, x, z)
|
||||
if not _stage_enabled:
|
||||
return original
|
||||
var blend := 1.0 - smoothstep(5.0, 9.0, Vector2(x - _stage_center.x, z - _stage_center.z).length())
|
||||
var grain := _noise_detail.get_noise_2d(x * 2.0, z * 2.0) * 0.5 + 0.5
|
||||
return original.lerp(Color("#41464b").lerp(Color("#686b68"), grain), blend)
|
||||
@@ -0,0 +1,81 @@
|
||||
extends Node
|
||||
## Céu, sol (ou lua), névoa e cor do mar por hora do dia, com mistura entre duas horas
|
||||
## (a espera no costão passa da noite para o dia). Usa o ShaderMaterial do mar da ilha.
|
||||
##
|
||||
## const SkyRig := preload("res://library/castaways/sky.gd")
|
||||
## var sky := SkyRig.new(); add_child(sky)
|
||||
## sky.build(island.ocean_material(), direção_horizontal_do_sol)
|
||||
## sky.set_preset("dawn") # "dawn" | "day" | "dusk" | "night"
|
||||
## sky.blend_presets("night", "dawn", k)
|
||||
|
||||
const PRESETS := {
|
||||
"dawn": {"top": Color("#2f4a7a"), "horizon": Color("#f2b07a"), "ground_h": Color("#d39466"), "ground_b": Color("#1b2434"),
|
||||
"sun": Color("#ffc58f"), "energy": 1.35, "elev": 9.0, "ambient": 0.45, "exposure": 1.05,
|
||||
"deep": Color("#0e2438"), "shallow": Color("#2d5d64"), "tint": Color("#f0b07c"), "fog": Color("#e7b089")},
|
||||
"day": {"top": Color("#2d6fb3"), "horizon": Color("#b9d7ec"), "ground_h": Color("#9cc3d9"), "ground_b": Color("#1d3d55"),
|
||||
"sun": Color("#fff4e2"), "energy": 1.7, "elev": 50.0, "ambient": 0.48, "exposure": 1.0,
|
||||
"deep": Color("#04213a"), "shallow": Color("#0a6b75"), "tint": Color("#73a0c2"), "fog": Color("#b9d7ec")},
|
||||
"dusk": {"top": Color("#232c57"), "horizon": Color("#e48a55"), "ground_h": Color("#b06a45"), "ground_b": Color("#141a2c"),
|
||||
"sun": Color("#ff9f68"), "energy": 1.1, "elev": 5.0, "ambient": 0.34, "exposure": 1.1,
|
||||
"deep": Color("#0a1a2b"), "shallow": Color("#1b4a52"), "tint": Color("#e9945e"), "fog": Color("#c98060")},
|
||||
"night": {"top": Color("#040814"), "horizon": Color("#1b2a47"), "ground_h": Color("#121c30"), "ground_b": Color("#02040a"),
|
||||
"sun": Color("#a9bcff"), "energy": 0.9, "elev": 35.0, "ambient": 0.7, "exposure": 1.35,
|
||||
"deep": Color("#12324f"), "shallow": Color("#1b475b"), "tint": Color("#577baa"), "fog": Color("#243653")},
|
||||
}
|
||||
|
||||
var _sky_mat: ProceduralSkyMaterial
|
||||
var _env: Environment
|
||||
var _sun: DirectionalLight3D
|
||||
var _ocean: ShaderMaterial
|
||||
var _dir := Vector3.FORWARD
|
||||
|
||||
|
||||
func build(ocean: ShaderMaterial, sun_dir: Vector3) -> void:
|
||||
_ocean = ocean
|
||||
_dir = Vector3(sun_dir.x, 0, sun_dir.z).normalized()
|
||||
_sky_mat = ProceduralSkyMaterial.new()
|
||||
_sky_mat.sun_angle_max = 12.0
|
||||
var sky := Sky.new()
|
||||
sky.sky_material = _sky_mat
|
||||
_env = Environment.new()
|
||||
_env.background_mode = Environment.BG_SKY
|
||||
_env.sky = sky
|
||||
_env.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
|
||||
_env.ambient_light_color = Color("#a5b8d0")
|
||||
_env.tonemap_mode = Environment.TONE_MAPPER_ACES
|
||||
_env.fog_enabled = true
|
||||
_env.fog_density = 0.0011
|
||||
_env.fog_sky_affect = 0.12
|
||||
var we := WorldEnvironment.new()
|
||||
we.environment = _env
|
||||
add_child(we)
|
||||
_sun = DirectionalLight3D.new()
|
||||
_sun.shadow_enabled = true
|
||||
_sun.directional_shadow_max_distance = 70.0
|
||||
add_child(_sun)
|
||||
|
||||
|
||||
func set_preset(preset: String) -> void:
|
||||
blend_presets(preset, preset, 0.0)
|
||||
|
||||
|
||||
func blend_presets(a_name: String, b_name: String, k: float) -> void:
|
||||
var a: Dictionary = PRESETS[a_name]
|
||||
var b: Dictionary = PRESETS[b_name]
|
||||
var c := func(key: String) -> Color: return (a[key] as Color).lerp(b[key], k)
|
||||
var f := func(key: String) -> float: return lerpf(float(a[key]), float(b[key]), k)
|
||||
_sky_mat.sky_top_color = c.call("top")
|
||||
_sky_mat.sky_horizon_color = c.call("horizon")
|
||||
_sky_mat.ground_horizon_color = c.call("ground_h")
|
||||
_sky_mat.ground_bottom_color = c.call("ground_b")
|
||||
_env.ambient_light_energy = f.call("ambient")
|
||||
_env.tonemap_exposure = f.call("exposure")
|
||||
_env.fog_light_color = c.call("fog")
|
||||
_sun.light_color = c.call("sun")
|
||||
_sun.light_energy = f.call("energy")
|
||||
var elev := deg_to_rad(f.call("elev"))
|
||||
var to_sun := Vector3(_dir.x * cos(elev), sin(elev), _dir.z * cos(elev))
|
||||
_sun.basis = Basis.looking_at(-to_sun, Vector3.UP)
|
||||
_ocean.set_shader_parameter("deep_color", c.call("deep"))
|
||||
_ocean.set_shader_parameter("shallow_color", c.call("shallow"))
|
||||
_ocean.set_shader_parameter("sky_tint", c.call("tint"))
|
||||
@@ -0,0 +1,661 @@
|
||||
extends Node3D
|
||||
## Cena 3D do documentário: os náufragos da Ilha das Cobras (reconstituição do caso de 2019).
|
||||
## Elenilson (regata cinza, bermuda escura) e três companheiros, do naufrágio do pesqueiro ao
|
||||
## resgate pela lancha de mergulho, no costão da ilha da biblioteca (res://library/island).
|
||||
## Tudo depende só de (params, t): poses e barcos animados por tempo, sem física nem relógio.
|
||||
##
|
||||
## Modelo "castaways": params
|
||||
## moment: "arrival" | "sinking" | "swimming" | "waiting" | "rescue" | "boarding" | "departure"
|
||||
## camera: "medium" (padrão) | "close" (mais perto do Elenilson) | "wide" (mais aberto)
|
||||
## variant: inteiro; muda o ângulo da câmera (lado, altura e ponto de vista)
|
||||
##
|
||||
## Tom sóbrio: sem cobra, sem helicóptero, sem navio militar; a lancha do resgate é civil.
|
||||
|
||||
const Island := preload("res://library/castaways/shore.gd")
|
||||
const Person := preload("res://library/castaways/actor.gd")
|
||||
const Boat := preload("res://kits/boat.gd")
|
||||
const Cast := preload("res://library/castaways/cast.gd")
|
||||
const SkyRig := preload("res://library/castaways/sky.gd")
|
||||
|
||||
const MOMENTS := ["arrival", "sinking", "swimming", "waiting", "rescue", "boarding", "departure"]
|
||||
const ZOOM := {"medium": 1.12, "close": 1.0, "wide": 1.3}
|
||||
|
||||
var _p: Dictionary
|
||||
var _dur = 1.0
|
||||
var _moment = "arrival"
|
||||
var _variant = 0
|
||||
var _zoom = 1.0
|
||||
var _island: Node3D
|
||||
var _sky: Node
|
||||
var _camera: Camera3D
|
||||
var _people = {} # id → Person (Elenilson = "elenilson")
|
||||
var _boat: Node3D # pesqueiro (sinking) ou lancha de mergulho (rescue, boarding, departure)
|
||||
var _seats: Array = [] # pedras de apoio sob quem está sentado no costão
|
||||
var _rock_mat: StandardMaterial3D
|
||||
# Costão escolhido: c = onde o grupo fica; sea = direção do mar; tan = ao longo da costa.
|
||||
var _c = Vector3.ZERO
|
||||
var _sea = Vector3.FORWARD
|
||||
var _tan = Vector3.RIGHT
|
||||
var _spots = {} # id → Vector3 (posição no costão, y = chão)
|
||||
var _last_cam = Vector3.ZERO
|
||||
var _support_points: Dictionary = {}
|
||||
|
||||
|
||||
func setup(cfg: Dictionary, viewport_size: Vector2) -> void:
|
||||
_p = cfg.params
|
||||
_dur = maxf(float(cfg.video.duration), 0.1)
|
||||
_moment = str(_p.get("moment", "arrival"))
|
||||
if not (_moment in MOMENTS):
|
||||
_moment = "arrival"
|
||||
_variant = posmod(int(_p.get("variant", 0)), 6)
|
||||
_zoom = float(ZOOM.get(str(_p.get("camera", "medium")), 1.0))
|
||||
_island = Island.new()
|
||||
_island.name = "Island"
|
||||
add_child(_island)
|
||||
_island.setup({"params": {"embedded": true, "environment": false, "lighthouse": false, "sea_detail": true, "time": "day"}, "video": cfg.video}, viewport_size)
|
||||
_island.set_sea_state(1.7 if _moment == "sinking" else (1.0 if _moment == "swimming" else 0.7))
|
||||
_rock_mat = StandardMaterial3D.new()
|
||||
_rock_mat.albedo_color = Color("#57534d")
|
||||
_rock_mat.roughness = 1.0
|
||||
_find_coast()
|
||||
_island.prepare_coast(_c, _sea)
|
||||
for id in _spots:
|
||||
_spots[id] = _ground(_spots[id])
|
||||
_clear_stage()
|
||||
_sky = SkyRig.new()
|
||||
add_child(_sky)
|
||||
_sky.build(_island.ocean_material(), _sun_dir())
|
||||
match _moment:
|
||||
"sinking":
|
||||
_sky.set_preset("dusk")
|
||||
"swimming":
|
||||
_sky.set_preset("night")
|
||||
"arrival":
|
||||
_sky.set_preset("dawn")
|
||||
"waiting":
|
||||
_sky.set_preset("night")
|
||||
_:
|
||||
_sky.set_preset("day")
|
||||
_build_cast()
|
||||
_camera = Camera3D.new()
|
||||
_camera.fov = 52.0
|
||||
_camera.near = 0.08
|
||||
_camera.far = 9000.0
|
||||
_camera.keep_aspect = Camera3D.KEEP_HEIGHT
|
||||
add_child(_camera)
|
||||
_camera.current = true
|
||||
|
||||
|
||||
func apply(t: float) -> void:
|
||||
_island.apply(t)
|
||||
var p = clampf(t / _dur, 0.0, 1.0)
|
||||
match _moment:
|
||||
"sinking":
|
||||
_do_sinking(t, p)
|
||||
"swimming":
|
||||
_do_swimming(t, p)
|
||||
"waiting":
|
||||
_do_waiting(t, p)
|
||||
"rescue":
|
||||
_do_rescue(t, p)
|
||||
"boarding":
|
||||
_do_boarding(t, p)
|
||||
"departure":
|
||||
_do_departure(t, p)
|
||||
_:
|
||||
_do_arrival(t, p)
|
||||
if _moment in ["arrival", "waiting", "rescue"]:
|
||||
for id in ["elenilson", "ivan", "manoel", "iranildo"]:
|
||||
_fit_ground(_people[id], _moment == "arrival" and id == "elenilson")
|
||||
var shot: Array = _compose_shot(t, p)
|
||||
_place_camera(shot[0], shot[1], shot[2], t)
|
||||
|
||||
|
||||
func state_signature() -> String:
|
||||
var e: Node3D = _people.elenilson
|
||||
var ep = e.global_position if e.is_inside_tree() else e.position
|
||||
return "%.3f,%.3f,%.3f|%.3f,%.3f,%.3f" % [_last_cam.x, _last_cam.y, _last_cam.z, ep.x, ep.y, ep.z]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ costão e elenco
|
||||
|
||||
## Procura, na costa da ilha, um trecho de pedra baixo, pouco inclinado, perto da água e
|
||||
## longe das pedras grandes (determinístico: o terreno vem de sementes fixas).
|
||||
func _find_coast() -> void:
|
||||
var best = INF
|
||||
for side in [1.0, -1.0]:
|
||||
for xi in range(-54, 55, 2):
|
||||
var x = float(xi)
|
||||
var z = 0.0
|
||||
while z < 70.0 and _island.ground_at(x, z * side) > 1.1:
|
||||
z += 0.25
|
||||
if z >= 70.0:
|
||||
continue
|
||||
var n: Vector3 = _island.ground_normal(x, z * side)
|
||||
var sea = Vector2(n.x, n.z)
|
||||
if sea.length() < 0.05:
|
||||
continue
|
||||
sea = sea.normalized()
|
||||
var c = Vector2(x, z * side) - sea * 1.4
|
||||
var hmin = INF
|
||||
var hmax = -INF
|
||||
for k in 16:
|
||||
var a = TAU * k / 16.0
|
||||
for r in [1.0, 2.0, 2.8]:
|
||||
var h: float = _island.ground_at(c.x + cos(a) * r, c.y + sin(a) * r)
|
||||
hmin = minf(hmin, h)
|
||||
hmax = maxf(hmax, h)
|
||||
var water = 0.0
|
||||
while water < 10.0 and _island.ground_at(c.x + sea.x * water, c.y + sea.y * water) > -0.5:
|
||||
water += 0.25
|
||||
var clear = INF
|
||||
for rk in _island.rock_list():
|
||||
clear = minf(clear, Vector2(rk[0].x, rk[0].z).distance_to(c) - float(rk[1]))
|
||||
var score: float = (hmax - hmin) + water * 0.12 + maxf(0.0, 3.0 - clear) * 0.6
|
||||
if score < best:
|
||||
best = score
|
||||
_c = Vector3(c.x, _island.ground_at(c.x, c.y), c.y)
|
||||
_sea = Vector3(sea.x, 0, sea.y)
|
||||
_tan = Vector3(-_sea.z, 0, _sea.x)
|
||||
print("CASTAWAYS costao c=(%.2f, %.2f, %.2f) mar=(%.2f, %.2f) nota=%.2f" % [_c.x, _c.y, _c.z, _sea.x, _sea.z, best])
|
||||
# Lugares do grupo no costão (Elenilson mais perto do mar).
|
||||
_spots = {
|
||||
"elenilson": _ground(_c + _sea * 0.2),
|
||||
"ivan": _ground(_c + _tan * 1.7 - _sea * 0.5),
|
||||
"manoel": _ground(_c - _tan * 1.8 - _sea * 0.4),
|
||||
"iranildo": _ground(_c + _tan * 0.5 - _sea * 1.7),
|
||||
}
|
||||
|
||||
|
||||
## Abre somente a área de atuação nesta instância da ilha; a biblioteca original fica intacta.
|
||||
func _clear_stage() -> void:
|
||||
for node_name in ["Forest", "Rocks"]:
|
||||
var node: MultiMeshInstance3D = _island.get_node(node_name)
|
||||
var mm: MultiMesh = node.multimesh
|
||||
for i in mm.instance_count:
|
||||
var tr: Transform3D = mm.get_instance_transform(i)
|
||||
var delta_pos: Vector3 = (tr.origin - _c) * Vector3(1, 0, 1)
|
||||
var corridor: bool = node_name == "Rocks" and delta_pos.dot(_sea) > -4.0 and absf(delta_pos.dot(_tan)) < 12.0
|
||||
var camera_clear: bool = node_name == "Forest" and _moment == "rescue" and delta_pos.dot(_sea) > -40.0 and absf(delta_pos.dot(_tan)) < 8.0
|
||||
if delta_pos.length() < 10.0 or corridor or camera_clear:
|
||||
tr.origin.y -= 80.0
|
||||
mm.set_instance_transform(i, tr)
|
||||
|
||||
|
||||
func _ground(v: Vector3) -> Vector3:
|
||||
return Vector3(v.x, _island.ground_at(v.x, v.z), v.z)
|
||||
|
||||
|
||||
## Vértices reais das peças: apoio sobre o terreno depois de aplicar a pose articulada.
|
||||
func _cache_support(person: Node3D) -> void:
|
||||
var parts: Array = []
|
||||
for mesh in person.find_children("*", "MeshInstance3D", true, false):
|
||||
var vertices: PackedVector3Array = mesh.mesh.surface_get_arrays(0)[Mesh.ARRAY_VERTEX]
|
||||
parts.append([mesh, vertices])
|
||||
_support_points[person.name] = parts
|
||||
|
||||
|
||||
func _fit_ground(person: Node3D, only_raise: bool = false) -> void:
|
||||
var lift: float = -INF
|
||||
for part in _support_points[person.name]:
|
||||
var tr: Transform3D = part[0].global_transform
|
||||
for v in part[1]:
|
||||
var point: Vector3 = tr * v
|
||||
lift = maxf(lift, _island.ground_at(point.x, point.z) - point.y)
|
||||
person.position.y += (maxf(lift, 0.0) if only_raise else lift) + 0.012
|
||||
|
||||
|
||||
func _sun_dir() -> Vector3:
|
||||
match _moment:
|
||||
"sinking":
|
||||
return (_sea * 0.75 - _tan * 0.65).normalized()
|
||||
"swimming":
|
||||
return (-_sea * 0.6 + _tan * 0.8).normalized()
|
||||
"arrival", "waiting":
|
||||
return (_sea * 0.8 + _tan * 0.6).normalized()
|
||||
_:
|
||||
return (_sea * 0.45 + _tan * 0.9).normalized()
|
||||
|
||||
|
||||
func _build_cast() -> void:
|
||||
var ids = ["elenilson", "ivan", "manoel", "iranildo"]
|
||||
if _moment == "sinking":
|
||||
ids += ["crew_a", "crew_b"] # o pesqueiro saiu com seis homens
|
||||
for id in ids:
|
||||
var person = Person.new()
|
||||
person.name = id
|
||||
person.build(Cast.LOOKS[id])
|
||||
_people[id] = person
|
||||
_cache_support(person)
|
||||
match _moment:
|
||||
"sinking":
|
||||
_boat = _make_boat(Cast.FISHING_BOAT)
|
||||
for id in ids:
|
||||
_boat.deck().add_child(_people[id])
|
||||
"swimming", "arrival", "waiting":
|
||||
for id in ids:
|
||||
add_child(_people[id])
|
||||
_:
|
||||
_boat = _make_boat(Cast.DIVE_BOAT)
|
||||
_add_benches()
|
||||
for id in ["diver_a", "diver_b"]:
|
||||
var diver = Person.new()
|
||||
diver.name = id
|
||||
diver.build(Cast.LOOKS[id])
|
||||
_people[id] = diver
|
||||
_boat.deck().add_child(diver)
|
||||
for id in ids:
|
||||
add_child(_people[id])
|
||||
if _moment in ["arrival", "waiting", "rescue"]:
|
||||
for id in ["elenilson", "iranildo"]:
|
||||
_seats.append(_seat_rock())
|
||||
|
||||
|
||||
func _make_boat(look: Dictionary) -> Node3D:
|
||||
var boat = Boat.new()
|
||||
boat.name = "Boat"
|
||||
boat.build(look)
|
||||
add_child(boat)
|
||||
return boat
|
||||
|
||||
|
||||
## Bancos na popa da lancha (os quatro vão sentados).
|
||||
func _add_benches() -> void:
|
||||
var wood = StandardMaterial3D.new()
|
||||
wood.albedo_color = Color("#e4e1da")
|
||||
for sx in [-1.0, 1.0]:
|
||||
var mesh = BoxMesh.new()
|
||||
mesh.size = Vector3(0.42, 0.3, 2.3)
|
||||
var mi = MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
mi.material_override = wood
|
||||
mi.position = Vector3(sx * 0.84, Boat.DECK_Y + 0.15, 2.15)
|
||||
_boat.deck().add_child(mi)
|
||||
|
||||
|
||||
func _seat_rock() -> MeshInstance3D:
|
||||
var mesh = SphereMesh.new()
|
||||
mesh.radius = 0.34
|
||||
mesh.height = 0.46
|
||||
mesh.radial_segments = 8
|
||||
mesh.rings = 4
|
||||
var mi = MeshInstance3D.new()
|
||||
mi.mesh = mesh
|
||||
mi.material_override = _rock_mat
|
||||
mi.visible = false
|
||||
add_child(mi)
|
||||
return mi
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ apoio das poses
|
||||
|
||||
## Põe a pessoa no chão do costão: pés em pos (y = chão desenhado), olhando para facing;
|
||||
## align (0–1) inclina o corpo junto com a pedra (deitado = 1).
|
||||
func _on_ground(person: Node3D, pos: Vector3, facing: Vector3, align := 0.0, lift := 0.0) -> void:
|
||||
var yaw = atan2(-facing.x, -facing.z)
|
||||
var n: Vector3 = _island.ground_normal(pos.x, pos.z)
|
||||
var up = Vector3.UP.lerp(n, align).normalized()
|
||||
var tilt = Quaternion(Vector3.UP, up) if up.distance_to(Vector3.UP) > 0.0001 else Quaternion.IDENTITY
|
||||
person.basis = Basis(tilt) * Basis(Vector3.UP, yaw)
|
||||
person.position = Vector3(pos.x, _island.ground_at(pos.x, pos.z) + lift, pos.z)
|
||||
|
||||
|
||||
## Sentado numa pedra do costão, olhando para facing (pés à frente, quadril sobre a pedra).
|
||||
func _sit_on_rock(person: Node3D, seat: MeshInstance3D, pos: Vector3, facing: Vector3) -> void:
|
||||
var f = facing.normalized()
|
||||
var feet = _island.ground_at(pos.x + f.x * 0.42, pos.z + f.z * 0.42)
|
||||
var under = _island.ground_at(pos.x, pos.z)
|
||||
var y = maxf(feet, under - 0.3)
|
||||
person.basis = Basis(Vector3.UP, atan2(-f.x, -f.z))
|
||||
person.position = Vector3(pos.x, y, pos.z)
|
||||
seat.visible = true
|
||||
seat.position = Vector3(pos.x, y + 0.3 - 0.21, pos.z) - f * 0.04
|
||||
|
||||
|
||||
## Deitado de costas ao longo da costa; a altura acompanha o ponto mais alto sob o corpo.
|
||||
func _lie_on_ground(person: Node3D, pos: Vector3, along: Vector3) -> void:
|
||||
var a = along.normalized()
|
||||
var top = -INF
|
||||
for k in [-0.2, 0.3, 0.8, 1.3]:
|
||||
top = maxf(top, _island.ground_at(pos.x + a.x * k, pos.z + a.z * k))
|
||||
var n: Vector3 = _island.ground_normal(pos.x + a.x * 0.5, pos.z + a.z * 0.5)
|
||||
var tilt = Quaternion(Vector3.UP, n.lerp(Vector3.UP, 0.4).normalized())
|
||||
# A cabeça fica em +Z da pessoa: olhar para -along põe a cabeça em +along.
|
||||
person.basis = Basis(tilt) * Basis(Vector3.UP, atan2(a.x, a.z))
|
||||
person.position = Vector3(pos.x, top + 0.04, pos.z)
|
||||
|
||||
|
||||
## Respiração visível (peito e costas), somada à pose.
|
||||
func _breathe(person: Node3D, t: float, amount: float) -> void:
|
||||
person.joints.chest.rotation.x += sin(t * 2.6) * amount
|
||||
person.joints.spine.rotation.x += sin(t * 2.6 + 0.4) * amount * 0.6
|
||||
|
||||
|
||||
## Vira a cabeça (e um pouco o tronco) na direção de um ponto do mundo.
|
||||
func _look_head(person: Node3D, target: Vector3, amount := 1.0) -> void:
|
||||
var head: Node3D = person.joints.neck
|
||||
var local = person.global_transform.basis.inverse() * (target - head.global_position)
|
||||
var yaw = clampf(atan2(-local.x, -local.z), -1.4, 1.4) * amount
|
||||
person.joints.spine.rotation.y += yaw * 0.35
|
||||
person.joints.neck.rotation.y += yaw * 0.65
|
||||
|
||||
|
||||
func _seg(p: float, a: float, b: float) -> float:
|
||||
var q = clampf((p - a) / (b - a), 0.0, 1.0)
|
||||
return q * q * (3.0 - 2.0 * q)
|
||||
|
||||
|
||||
## Barco na água: acompanha a altura e a inclinação das ondas em (x, z), proa para heading.
|
||||
func _boat_on_sea(pos: Vector3, heading: Vector3, t: float, rock := 0.6) -> void:
|
||||
var h = heading.normalized()
|
||||
var right = Vector3(-h.z, 0, h.x)
|
||||
var bow: float = _island.sea_height(pos.x + h.x * 3.5, pos.z + h.z * 3.5, t)
|
||||
var stern: float = _island.sea_height(pos.x - h.x * 3.5, pos.z - h.z * 3.5, t)
|
||||
var sr: float = _island.sea_height(pos.x + right.x * 1.2, pos.z + right.z * 1.2, t)
|
||||
var sl: float = _island.sea_height(pos.x - right.x * 1.2, pos.z - right.z * 1.2, t)
|
||||
_boat.position = Vector3(pos.x, (bow + stern + sr + sl) * 0.25, pos.z)
|
||||
_boat.rotation = Vector3(atan2(bow - stern, 7.0) * 0.8, atan2(-h.x, -h.z), atan2(sr - sl, 2.4) * 0.8)
|
||||
_boat.float_on(t, rock)
|
||||
|
||||
|
||||
## Ponto do convés (coordenadas do barco) no mundo, já com o balanço deste quadro.
|
||||
func _on_boat(local: Vector3) -> Vector3:
|
||||
return _boat.deck().global_transform * local
|
||||
|
||||
|
||||
## Nadador na superfície (corpo meio submerso), indo para heading.
|
||||
func _swim_at(person: Node3D, pos: Vector3, heading: Vector3, t: float, phase: float) -> void:
|
||||
var h = heading.normalized()
|
||||
person.basis = Basis(Vector3.UP, atan2(-h.x, -h.z))
|
||||
person.position = Vector3(pos.x, _island.sea_height(pos.x, pos.z, t) - 0.06, pos.z)
|
||||
person.pose("swim", t * 0.85 + phase)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ momentos
|
||||
# Cada momento posiciona o elenco no instante t (p = t / duração).
|
||||
|
||||
func _do_arrival(t: float, p: float) -> void:
|
||||
var e: Node3D = _people.elenilson
|
||||
var land = _spots.elenilson
|
||||
var water = land + _sea * 0.4
|
||||
while water.distance_to(land) < 4.0 and _island.ground_at(water.x, water.z) > -0.55:
|
||||
water += _sea * 0.25
|
||||
# 0–35%: nadando os últimos metros; 35–60%: apoia as mãos e sobe; depois, de joelhos.
|
||||
var k_up = _seg(p, 0.3, 0.62)
|
||||
var pos = water.lerp(land, _seg(p, 0.0, 0.6))
|
||||
var swim_y: float = _island.sea_height(pos.x, pos.z, t) - 0.06
|
||||
var y = lerpf(swim_y, _island.ground_at(land.x, land.z), k_up)
|
||||
y = maxf(y, _island.ground_at(pos.x, pos.z) - 0.35 * (1.0 - k_up))
|
||||
_on_ground(e, pos, -_sea, 0.8 * k_up)
|
||||
e.position.y = y
|
||||
e.blend("swim", "kneel", lerpf(t * 0.8, 0.3, k_up), k_up)
|
||||
_breathe(e, t, 0.07 * k_up)
|
||||
e.joints.neck.rotation.x += 0.25 * k_up # cabeça baixa, recuperando o fôlego
|
||||
_place_group_resting(t, false)
|
||||
|
||||
|
||||
|
||||
## Os três companheiros descansando no costão (arrival e waiting).
|
||||
func _place_group_resting(t: float, night: bool) -> void:
|
||||
var ivan: Node3D = _people.ivan
|
||||
var manoel: Node3D = _people.manoel
|
||||
var iran: Node3D = _people.iranildo
|
||||
if night:
|
||||
_lie_on_ground(ivan, _spots.ivan, _tan)
|
||||
ivan.pose("lie", t)
|
||||
else:
|
||||
_on_ground(ivan, _spots.ivan, _sea.rotated(Vector3.UP, 0.4), 0.8)
|
||||
ivan.pose("kneel", t + 1.3)
|
||||
_breathe(ivan, t + 0.7, 0.06)
|
||||
ivan.joints.neck.rotation.x += 0.35
|
||||
_lie_on_ground(manoel, _spots.manoel, -_tan)
|
||||
manoel.pose("lie", t + 0.9)
|
||||
_sit_on_rock(iran, _seats[1], _spots.iranildo, _sea.rotated(Vector3.UP, -0.3))
|
||||
iran.pose("sit", t + 2.1)
|
||||
if night:
|
||||
iran.joints.neck.rotation.x += 0.45 # cochilando sentado
|
||||
|
||||
|
||||
func _do_waiting(t: float, p: float) -> void:
|
||||
# Noite → amanhecer → dia: o tempo da espera passando.
|
||||
_sky.blend_presets("night", "dawn", _seg(p, 0.4, 0.75))
|
||||
if p > 0.75:
|
||||
_sky.blend_presets("dawn", "day", _seg(p, 0.75, 1.0))
|
||||
var e: Node3D = _people.elenilson
|
||||
_sit_on_rock(e, _seats[0], _spots.elenilson, _sea)
|
||||
e.pose("sit", t)
|
||||
# Vigiando o horizonte: a cabeça varre o mar devagar.
|
||||
var scan = sin(p * PI * 1.6 + 0.3) * 0.5
|
||||
_look_head(e, _spots.elenilson + _sea.rotated(Vector3.UP, scan) * 200.0 + Vector3(0, 1.0, 0))
|
||||
_place_group_resting(t, true)
|
||||
|
||||
|
||||
|
||||
|
||||
func _do_sinking(t: float, p: float) -> void:
|
||||
var center = _c + _sea * 70.0
|
||||
var k_sink = _seg(p, 0.3, 1.0)
|
||||
_boat.sink(k_sink * 0.95)
|
||||
_boat_on_sea(center, _tan, t, 1.6 + k_sink * 0.6)
|
||||
# Homens no convés, se segurando enquanto o barco aderna (coordenadas do barco).
|
||||
var places = {
|
||||
"elenilson": [Vector3(-0.55, Boat.DECK_Y, 1.5), 0.0],
|
||||
"ivan": [Vector3(0.45, Boat.DECK_Y, 1.9), 1.1],
|
||||
"manoel": [Vector3(-0.35, Boat.DECK_Y, 2.8), 2.3],
|
||||
"iranildo": [Vector3(0.55, Boat.DECK_Y, 3.0), 0.6],
|
||||
"crew_a": [Vector3(0.0, Boat.DECK_Y, 1.0), 1.7],
|
||||
"crew_b": [Vector3(-0.2, Boat.DECK_Y, -2.2), 2.9],
|
||||
}
|
||||
for id in places.keys():
|
||||
var person: Node3D = _people[id]
|
||||
person.position = places[id][0]
|
||||
# Olhando para o lado que afunda (bombordo, -X do barco).
|
||||
person.rotation = Vector3(0, PI / 2.0 + float(places[id][1]) * 0.25 - 0.3, 0)
|
||||
person.blend("idle", "exhausted", t + float(places[id][1]), 0.35 + 0.5 * k_sink)
|
||||
|
||||
|
||||
|
||||
|
||||
func _do_swimming(t: float, p: float) -> void:
|
||||
# Mar escuro: os quatro nadam para a ilha (que aparece ao longe), Elenilson à frente.
|
||||
var heading = -_sea
|
||||
var start = _c + _sea * 46.0
|
||||
var e_pos = start + heading * (4.0 * p)
|
||||
var formation = {
|
||||
"elenilson": [Vector3.ZERO, 0.0],
|
||||
"ivan": [_tan * 2.1 + _sea * 1.6, 1.3],
|
||||
"manoel": [-_tan * 1.9 + _sea * 2.7, 2.4],
|
||||
"iranildo": [_tan * 0.7 + _sea * 4.3, 0.7],
|
||||
}
|
||||
for id in formation.keys():
|
||||
var drift = _tan * sin(t * 0.4 + float(formation[id][1])) * 0.25
|
||||
_swim_at(_people[id], e_pos + formation[id][0] + drift, heading, t, float(formation[id][1]))
|
||||
|
||||
|
||||
|
||||
|
||||
func _do_rescue(t: float, p: float) -> void:
|
||||
# Lancha de mergulho chegando do mar; o grupo no costão acenando.
|
||||
var d0 = _c + _sea * 32.0 + _tan * 1.5
|
||||
var d1 = _c + _sea * 18.0 + _tan * 1.0
|
||||
var k_boat = 1.0 - pow(1.0 - p, 1.6) # desacelerando
|
||||
var bpos = d0.lerp(d1, k_boat)
|
||||
_boat_on_sea(bpos, (d1 - d0), t, 0.5)
|
||||
_place_divers_rescue(t)
|
||||
var e: Node3D = _people.elenilson
|
||||
# Elenilson se levanta (0–30%) e acena com o grupo.
|
||||
var k_up = _seg(p, 0.05, 0.3)
|
||||
var standing_spot: Vector3 = _ground(_spots.elenilson + _sea * 0.65)
|
||||
var seat: MeshInstance3D = _seats[0]
|
||||
if k_up < 1.0:
|
||||
_sit_on_rock(e, seat, _spots.elenilson, _sea)
|
||||
e.position = e.position.lerp(standing_spot, k_up)
|
||||
e.blend("sit", "idle", t, k_up)
|
||||
else:
|
||||
_on_ground(e, standing_spot, _sea)
|
||||
e.blend("idle", "wave", t, _seg(p, 0.3, 0.42))
|
||||
seat.visible = true
|
||||
_seats[1].visible = false
|
||||
var waves = {"ivan": [0.08, 0.5], "manoel": [0.16, 1.7], "iranildo": [0.24, 2.6]}
|
||||
for id in waves.keys():
|
||||
var person: Node3D = _people[id]
|
||||
var spot: Vector3 = _spots[id]
|
||||
_on_ground(person, spot, (bpos - spot) * Vector3(1, 0, 1))
|
||||
person.blend("idle", "wave", t + float(waves[id][1]), _seg(p, float(waves[id][0]), float(waves[id][0]) + 0.15))
|
||||
|
||||
|
||||
|
||||
|
||||
func _place_divers_rescue(t: float) -> void:
|
||||
var a: Node3D = _people.diver_a
|
||||
a.position = Vector3(0.3, Boat.DECK_Y, -2.2)
|
||||
a.rotation = Vector3.ZERO
|
||||
a.pose("wave", t + 0.4)
|
||||
var b: Node3D = _people.diver_b
|
||||
b.position = Vector3(-0.4, Boat.DECK_Y, 1.4)
|
||||
b.rotation = Vector3(0, -0.3, 0)
|
||||
b.pose("idle", t)
|
||||
|
||||
|
||||
func _do_boarding(t: float, p: float) -> void:
|
||||
var center: Vector3 = _c + _sea * 16.0
|
||||
_boat_on_sea(center, _sea, t, 0.25)
|
||||
var diver: Node3D = _people.diver_a
|
||||
diver.position = Vector3(0.0, Boat.DECK_Y, 3.15)
|
||||
diver.rotation = Vector3(0, PI, 0)
|
||||
diver.pose("kneel", t)
|
||||
diver.joints.shoulder_l.rotation.x = 1.3
|
||||
diver.joints.elbow_l.rotation.x = 0.2
|
||||
var helm: Node3D = _people.diver_b
|
||||
helm.position = Vector3(-0.45, Boat.DECK_Y, 1.1)
|
||||
helm.rotation = Vector3(0, PI, 0)
|
||||
helm.pose("idle", t)
|
||||
_sit_on_boat(_people.ivan, -1.0, 1.7, t)
|
||||
_sit_on_boat(_people.manoel, 1.0, 1.7, t + 1.2)
|
||||
_board_person(_people.elenilson, t, p, 0.0, -1.0)
|
||||
_board_person(_people.iranildo, t, p, 0.22, 1.0)
|
||||
|
||||
|
||||
## A subida é primeiro vertical, depois sobre a popa, mantendo o corpo fora do casco.
|
||||
## Os dois últimos chegam em sequência; todos terminam sentados antes do fim da tomada.
|
||||
func _board_person(person: Node3D, t: float, p: float, delay: float, side: float) -> void:
|
||||
var q: float = clampf((p - delay) / 0.72, 0.0, 1.0)
|
||||
var shore: Vector3 = _c + _sea * 7.0 + _tan * side * 0.5
|
||||
var stern: Vector3 = _on_boat(Vector3(side * 0.2, 0, 5.25))
|
||||
var swim_pos: Vector3 = shore.lerp(stern, _seg(q, 0.0, 0.45))
|
||||
var up: float = _seg(q, 0.45, 0.68)
|
||||
var aboard: float = _seg(q, 0.68, 0.84)
|
||||
var seat: Vector3 = _on_boat(Vector3(side * 0.86, Boat.DECK_Y + 0.02, 2.9))
|
||||
var edge: Vector3 = _on_boat(Vector3(side * 0.2, Boat.DECK_Y + 0.12, 5.25))
|
||||
var pos: Vector3 = swim_pos.lerp(edge, up).lerp(seat, aboard)
|
||||
var water_y: float = _island.sea_height(swim_pos.x, swim_pos.z, t) - 0.06
|
||||
pos.y = lerpf(water_y, edge.y, up)
|
||||
pos.y = lerpf(pos.y, seat.y, aboard)
|
||||
person.position = pos
|
||||
var boat_basis: Basis = _boat.deck().global_basis.orthonormalized()
|
||||
person.basis = boat_basis * Basis(Vector3.UP, side * PI / 2.0 * aboard)
|
||||
if q < 0.68:
|
||||
person.blend("swim", "kneel", lerpf(t * 0.85, 0.3, up), up)
|
||||
else:
|
||||
person.blend("kneel", "sit", t, aboard)
|
||||
|
||||
|
||||
## Sentado num banco da lancha (lado sx = -1 bombordo, 1 boreste), virado para o meio.
|
||||
func _sit_on_boat(person: Node3D, sx: float, z: float, t: float) -> void:
|
||||
if person.get_parent() != _boat.deck():
|
||||
person.get_parent().remove_child(person)
|
||||
_boat.deck().add_child(person)
|
||||
person.position = Vector3(sx * 0.86, Boat.DECK_Y, z)
|
||||
person.rotation = Vector3(0, PI / 2.0 * sx, 0)
|
||||
person.pose("sit", t)
|
||||
|
||||
|
||||
func _do_departure(t: float, p: float) -> void:
|
||||
# A lancha se afasta da ilha; os quatro sentados, Elenilson olhando o costão.
|
||||
var start = _c + _sea * 16.0
|
||||
var center = start + _sea * (16.0 * p)
|
||||
_boat_on_sea(center, _sea, t, 0.55)
|
||||
var helm: Node3D = _people.diver_b
|
||||
helm.position = Vector3(0.45, Boat.DECK_Y, 0.95)
|
||||
helm.rotation = Vector3(0, 0.15, 0)
|
||||
helm.pose("idle", t)
|
||||
var diver: Node3D = _people.diver_a
|
||||
diver.position = Vector3(-0.5, Boat.DECK_Y, 0.95)
|
||||
diver.rotation = Vector3(0, -0.2, 0)
|
||||
diver.pose("idle", t + 2.0)
|
||||
_sit_on_boat(_people.elenilson, -1.0, 2.9, t)
|
||||
_sit_on_boat(_people.ivan, -1.0, 1.75, t + 0.8)
|
||||
_sit_on_boat(_people.manoel, 1.0, 2.9, t + 1.6)
|
||||
_sit_on_boat(_people.iranildo, 1.0, 1.75, t + 2.4)
|
||||
for id in ["ivan", "manoel", "iranildo"]:
|
||||
(_people[id] as Node3D).joints.neck.rotation.x += 0.35 # cabeças baixas, em silêncio
|
||||
var e: Node3D = _people.elenilson
|
||||
_look_head(e, _c + Vector3(0, 2.0, 0))
|
||||
|
||||
|
||||
|
||||
|
||||
## Composição vertical centralizada no elenco.
|
||||
func _compose_shot(_t: float, p: float) -> Array:
|
||||
var e: Node3D = _people.elenilson
|
||||
var k: float = _seg(p, 0.0, 1.0)
|
||||
var angle: float = [0.0, -0.38, 0.42][posmod(_variant, 3)]
|
||||
var target: Vector3
|
||||
var offset: Vector3
|
||||
match _moment:
|
||||
"arrival":
|
||||
target = (e.position + Vector3(0, 0.5, 0)).lerp(_c + Vector3(0, 0.7, 0), k)
|
||||
offset = (_sea * lerpf(6.0, 11.5, k) + _tan * 2.0).rotated(Vector3.UP, angle) + Vector3(0, lerpf(2.0, 4.0, k), 0)
|
||||
"waiting":
|
||||
target = _c + Vector3(0, 0.65, 0)
|
||||
offset = (_sea * 9.8 + _tan * lerpf(3.0, 2.2, k)).rotated(Vector3.UP, angle) + Vector3(0, 3.3, 0)
|
||||
"swimming":
|
||||
target = e.position + _sea * 1.2 + Vector3(0, 0.1, 0)
|
||||
offset = (-_sea * 9.5 + _tan * 3.5).rotated(Vector3.UP, angle) + Vector3(0, 3.8 + 0.3 * k, 0)
|
||||
"rescue":
|
||||
target = _c + _sea * 4.0 + Vector3(0, 0.8, 0)
|
||||
offset = (-_sea * 15.0 + _tan * 0.6).rotated(Vector3.UP, angle * 0.12) + Vector3(0, 7.5, 0)
|
||||
"boarding":
|
||||
target = _on_boat(Vector3(0, 0.8, 2.8))
|
||||
offset = _boat.basis * Vector3(13.0 if _variant % 2 == 0 else -13.0, 7.0 + float(_variant % 3), 10.0)
|
||||
"departure":
|
||||
target = _on_boat(Vector3(0, 1.2, 1.8))
|
||||
offset = _boat.basis * Vector3(6.0 if _variant % 2 == 0 else -6.0, 7.0 + float(_variant % 3) * 0.6, -11.0 - k * 2.0)
|
||||
_:
|
||||
target = _boat.position + Vector3(0, 0.8 - _seg(p, 0.3, 1.0) * 0.8, 0)
|
||||
offset = (_sea * 22.0 + _tan * 3.0).rotated(Vector3.UP, angle) + Vector3(0, 4.0 + float(_variant % 3), 0)
|
||||
return [target + offset, target, target]
|
||||
|
||||
|
||||
func _place_camera(pos: Vector3, target: Vector3, _focus: Vector3, t: float) -> void:
|
||||
var direction: Vector3 = (pos - target).normalized()
|
||||
var view_basis: Basis = Basis.looking_at(-direction, Vector3.UP)
|
||||
var required: float = pos.distance_to(target)
|
||||
# Enquadra as peças articuladas em x=8–92%, y=18–72%, inclusive durante a subida.
|
||||
for id in ["elenilson", "ivan", "manoel", "iranildo"]:
|
||||
for part in _support_points[id]:
|
||||
var mesh: MeshInstance3D = part[0]
|
||||
var bounds: AABB = mesh.mesh.get_aabb()
|
||||
for corner in 8:
|
||||
required = maxf(required, _required_distance(mesh.global_transform * bounds.get_endpoint(corner), target, view_basis))
|
||||
if _boat and _moment != "rescue":
|
||||
for x in [-1.4, 1.4]:
|
||||
for y in [-0.7, 4.1]:
|
||||
for z in [-4.1, 4.1]:
|
||||
required = maxf(required, _required_distance(_on_boat(Vector3(x, y, z)), target, view_basis))
|
||||
var cam: Vector3 = target + direction * required * _zoom
|
||||
# Nunca dentro da pedra nem da água.
|
||||
cam.y = maxf(cam.y, _island.ground_at(cam.x, cam.z) + 0.4)
|
||||
cam.y = maxf(cam.y, _island.sea_height(cam.x, cam.z, t) + 0.3)
|
||||
_camera.position = cam
|
||||
_camera.look_at(target, Vector3.UP)
|
||||
_island.set_sea_focus(cam.x, cam.z)
|
||||
_last_cam = cam
|
||||
|
||||
|
||||
func _required_distance(point: Vector3, target: Vector3, view_basis: Basis) -> float:
|
||||
var local: Vector3 = view_basis.inverse() * (point - target)
|
||||
var tangent: float = tan(deg_to_rad(_camera.fov * 0.5))
|
||||
var horizontal: float = absf(local.x) / (tangent * (9.0 / 16.0) * 0.84)
|
||||
var vertical: float = maxf(local.y / (tangent * 0.64), -local.y / (tangent * 0.44))
|
||||
return local.z + maxf(horizontal, vertical)
|
||||
@@ -0,0 +1,64 @@
|
||||
extends SceneTree
|
||||
## Verificação local: Godot --headless --path godot --script res://library/castaways/verify.gd
|
||||
## Compara todos os nós articulados ao buscar tempos em ordens diferentes.
|
||||
|
||||
const Scene := preload("res://library/castaways/template.gd")
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
call_deferred("_run")
|
||||
|
||||
|
||||
func _snapshot(node: Node) -> String:
|
||||
var parts: PackedStringArray = []
|
||||
if node is Node3D:
|
||||
parts.append(str(node.transform))
|
||||
for child in node.get_children():
|
||||
parts.append(_snapshot(child))
|
||||
return "|".join(parts)
|
||||
|
||||
|
||||
func _run() -> void:
|
||||
var checks := 0
|
||||
for moment in Scene.MOMENTS:
|
||||
for variant in 3:
|
||||
var scene := Scene.new()
|
||||
root.add_child(scene)
|
||||
scene.setup({"params": {"moment": moment, "variant": variant}, "video": {"duration": 5.0}}, Vector2(540, 960))
|
||||
for t in [0.0, 0.7, 2.5, 4.95]:
|
||||
scene.apply(t)
|
||||
var before := _snapshot(scene)
|
||||
scene.apply(4.99)
|
||||
scene.apply(0.0)
|
||||
scene.apply(t)
|
||||
if before != _snapshot(scene):
|
||||
printerr("FALHA determinismo %s variant=%d t=%.2f" % [moment, variant, t])
|
||||
quit(1)
|
||||
return
|
||||
if moment in ["arrival", "waiting", "rescue"] and (moment != "arrival" or t > 0.6):
|
||||
for id in ["elenilson", "ivan", "manoel", "iranildo"]:
|
||||
var clearance := INF
|
||||
for part in scene._support_points[id]:
|
||||
for vertex in part[1]:
|
||||
var point: Vector3 = part[0].global_transform * vertex
|
||||
clearance = minf(clearance, point.y - scene._island.ground_at(point.x, point.z))
|
||||
if clearance < -0.002 or clearance > 0.03:
|
||||
printerr("FALHA apoio %s %s: %.4f m" % [moment, id, clearance])
|
||||
quit(1)
|
||||
return
|
||||
checks += 1
|
||||
var previous := Vector3.ZERO
|
||||
var largest_step := 0.0
|
||||
for frame in 150:
|
||||
scene.apply(float(frame) / 30.0)
|
||||
var current: Vector3 = scene._people.elenilson.global_position
|
||||
if frame > 0:
|
||||
largest_step = maxf(largest_step, current.distance_to(previous))
|
||||
previous = current
|
||||
if largest_step > 0.4:
|
||||
printerr("FALHA continuidade %s variant=%d: %.3f m/quadro" % [moment, variant, largest_step])
|
||||
quit(1)
|
||||
return
|
||||
scene.free()
|
||||
print("CASTAWAYS_OK %d estados: determinismo por busca temporal e apoio dos personagens" % checks)
|
||||
quit(0)
|
||||
@@ -0,0 +1,112 @@
|
||||
{
|
||||
"id": "island",
|
||||
"kind": "doc3d",
|
||||
"label": "Ilha costeira",
|
||||
"description": "Ilha alongada com mata densa, costão de pedra e farol listrado num mar animado. Sobrevoo, chegada pelo mar, perto do farol ou rasante; de dia, entardecer ou noite. Outras cenas podem usá-la como cenário (params embedded: true, environment: false, sea_detail: true; métodos ground_at(x, z), sea_height(x, z, t), set_sea_state, set_sea_focus, rock_list e lighthouse_position()).",
|
||||
"keywords": [
|
||||
"ilha",
|
||||
"mar",
|
||||
"oceano",
|
||||
"costa",
|
||||
"costão",
|
||||
"rochedo",
|
||||
"farol",
|
||||
"aérea",
|
||||
"aéreo",
|
||||
"sobrevoo",
|
||||
"sobrevoa",
|
||||
"mata em 3d",
|
||||
"sobrevoo 3d",
|
||||
"vista",
|
||||
"horizonte"
|
||||
],
|
||||
"params": [
|
||||
{
|
||||
"name": "shot",
|
||||
"label": "Tomada",
|
||||
"type": "select",
|
||||
"default": "orbit",
|
||||
"options": [
|
||||
{
|
||||
"value": "orbit",
|
||||
"label": "Sobrevoo em volta",
|
||||
"keywords": [
|
||||
"aére",
|
||||
"sobrevoo",
|
||||
"sobrevoa",
|
||||
"mata em 3d",
|
||||
"sobrevoo 3d",
|
||||
"vista",
|
||||
"plano aéreo"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "approach",
|
||||
"label": "Chegada pelo mar",
|
||||
"keywords": [
|
||||
"afastamento",
|
||||
"aproxima",
|
||||
"chega",
|
||||
"chegada"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "lighthouse",
|
||||
"label": "Perto do farol",
|
||||
"keywords": [
|
||||
"farol"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "lowpass",
|
||||
"label": "Rasante na água",
|
||||
"keywords": [
|
||||
"rasante",
|
||||
"água",
|
||||
"ondas"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "time",
|
||||
"label": "Hora do dia",
|
||||
"type": "select",
|
||||
"default": "day",
|
||||
"options": [
|
||||
{
|
||||
"value": "day",
|
||||
"label": "Dia"
|
||||
},
|
||||
{
|
||||
"value": "sunset",
|
||||
"label": "Entardecer",
|
||||
"keywords": [
|
||||
"entardecer",
|
||||
"pôr do sol",
|
||||
"anoitecer",
|
||||
"crepúsculo"
|
||||
]
|
||||
},
|
||||
{
|
||||
"value": "night",
|
||||
"label": "Noite",
|
||||
"keywords": [
|
||||
"noite",
|
||||
"escuro",
|
||||
"madrugada",
|
||||
"temporal noturno"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lighthouse",
|
||||
"label": "Farol",
|
||||
"type": "bool",
|
||||
"default": true
|
||||
}
|
||||
],
|
||||
"createdBy": "Claude Code (CenaForge)",
|
||||
"createdAt": "2026-11-17"
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
extends Node3D
|
||||
## Cena 3D do documentário: uma ilha costeira estilizada (terreno por ruído, mata densa,
|
||||
## costão de pedra, farol) num mar animado por shader. Tudo depende só de (configuração, t):
|
||||
## sementes fixas, o mar recebe o tempo de cena por uniform (não usa TIME), então o render
|
||||
## é determinístico.
|
||||
##
|
||||
## Modelo "island": params
|
||||
## shot: "orbit" (sobrevoo em volta) | "approach" (chega do mar) | "lighthouse" (perto do
|
||||
## farol) | "lowpass" (rasante sobre a água) — padrão "orbit"
|
||||
## time: "day" | "sunset" — padrão "day"
|
||||
## lighthouse: true/false — padrão true
|
||||
## variant: inteiro; muda ângulo inicial, sentido da câmera e (ímpar) a hora do dia
|
||||
##
|
||||
## Como cenário de outra cena (params embedded: true; environment: false se a outra cena faz
|
||||
## céu e luz; sea_detail: true para tomadas rente à água): height_at / ground_at / ground_normal
|
||||
## (terreno), sea_height(x, z, t) e set_sea_state(escala) (mar), set_sea_focus(x, z) (centro da
|
||||
## malha fina do mar), rock_list() (pedras do costão) e lighthouse_position().
|
||||
|
||||
const ISLAND_A := 82.0 # semieixo maior (x), em metros da cena
|
||||
const ISLAND_B := 42.0 # semieixo menor (z)
|
||||
const GRID := 168 # resolução do terreno
|
||||
const TERRAIN_SIZE := 260.0
|
||||
const TREE_COUNT := 5200
|
||||
|
||||
const OCEAN_SHADER := """
|
||||
shader_type spatial;
|
||||
render_mode specular_schlick_ggx, cull_disabled;
|
||||
|
||||
uniform float scene_time = 0.0;
|
||||
uniform float wave_scale = 1.0;
|
||||
uniform vec3 deep_color : source_color = vec3(0.015, 0.13, 0.22);
|
||||
uniform vec3 shallow_color : source_color = vec3(0.04, 0.42, 0.46);
|
||||
uniform vec3 sky_tint : source_color = vec3(0.45, 0.62, 0.76);
|
||||
uniform vec2 island_axes = vec2(82.0, 42.0);
|
||||
|
||||
varying vec3 v_world;
|
||||
varying float v_crest;
|
||||
|
||||
void add_wave(vec2 p, vec2 dir, float len, float amp, float speed, inout float h, inout vec2 grad) {
|
||||
float k = 6.2831853 / len;
|
||||
float f = k * dot(p, normalize(dir)) + scene_time * speed;
|
||||
h += amp * sin(f);
|
||||
grad += amp * k * cos(f) * normalize(dir);
|
||||
}
|
||||
|
||||
void vertex() {
|
||||
vec3 w = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
|
||||
float h = 0.0;
|
||||
vec2 grad = vec2(0.0);
|
||||
add_wave(w.xz, vec2(1.0, 0.31), 41.0, 0.42, 1.05, h, grad);
|
||||
add_wave(w.xz, vec2(-0.37, 1.0), 27.3, 0.26, 1.33, h, grad);
|
||||
add_wave(w.xz, vec2(0.83, -0.57), 15.7, 0.13, 1.81, h, grad);
|
||||
add_wave(w.xz, vec2(-1.0, -0.23), 9.1, 0.07, 2.37, h, grad);
|
||||
add_wave(w.xz, vec2(0.21, -1.0), 5.3, 0.035, 3.1, h, grad);
|
||||
add_wave(w.xz, vec2(0.66, 0.75), 3.7, 0.02, 3.9, h, grad);
|
||||
h *= wave_scale;
|
||||
grad *= wave_scale;
|
||||
VERTEX.y += h;
|
||||
NORMAL = normalize(vec3(-grad.x, 1.0, -grad.y));
|
||||
v_world = w;
|
||||
v_crest = h;
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
// Água mais clara (turquesa) perto da ilha, escura no mar aberto.
|
||||
float d = length(v_world.xz / island_axes);
|
||||
float shallow = smoothstep(1.7, 1.0, d) * 0.85;
|
||||
vec3 col = mix(deep_color, shallow_color, shallow);
|
||||
col += vec3(0.05) * smoothstep(0.35, 0.8, v_crest);
|
||||
float fres = pow(1.0 - clamp(dot(NORMAL, VIEW), 0.0, 1.0), 5.0);
|
||||
ALBEDO = mix(col, sky_tint, fres * 0.22);
|
||||
ROUGHNESS = 0.07;
|
||||
METALLIC = 0.0;
|
||||
SPECULAR = 0.65;
|
||||
}
|
||||
"""
|
||||
|
||||
var _cfg: Dictionary
|
||||
var _p: Dictionary
|
||||
var _size := Vector2.ZERO
|
||||
var _dur := 1.0
|
||||
var _variant := 0
|
||||
var _camera: Camera3D
|
||||
var _ocean_mat: ShaderMaterial
|
||||
var _noise_shape: FastNoiseLite
|
||||
var _noise_ridge: FastNoiseLite
|
||||
var _noise_detail: FastNoiseLite
|
||||
var _lighthouse_pos := Vector3.ZERO
|
||||
var _lamp: MeshInstance3D
|
||||
var _t := 0.0
|
||||
var _last_cam := Vector3.ZERO
|
||||
var _night := false
|
||||
var _embedded := false
|
||||
var _ocean: MeshInstance3D
|
||||
var _wave_scale := 1.0
|
||||
var _heights := PackedFloat32Array() # alturas dos vértices do terreno (a malha desenhada)
|
||||
var _rocks: Array = [] # [centro, raio] de cada pedra do costão
|
||||
|
||||
## As mesmas ondas do OCEAN_SHADER (direção, comprimento, amplitude, velocidade), para
|
||||
## sea_height() devolver a altura da água que aparece na tela.
|
||||
const WAVES := [
|
||||
[Vector2(1.0, 0.31), 41.0, 0.42, 1.05],
|
||||
[Vector2(-0.37, 1.0), 27.3, 0.26, 1.33],
|
||||
[Vector2(0.83, -0.57), 15.7, 0.13, 1.81],
|
||||
[Vector2(-1.0, -0.23), 9.1, 0.07, 2.37],
|
||||
[Vector2(0.21, -1.0), 5.3, 0.035, 3.1],
|
||||
[Vector2(0.66, 0.75), 3.7, 0.02, 3.9],
|
||||
]
|
||||
|
||||
|
||||
## Para outras cenas da biblioteca: posição do farol (pé da torre) e altura do terreno.
|
||||
func lighthouse_position() -> Vector3:
|
||||
return _lighthouse_pos
|
||||
|
||||
|
||||
## Altura da superfície do terreno COMO DESENHADA (interpola os triângulos da malha, não o
|
||||
## ruído): use para apoiar pés, joelhos e pedras sem flutuar nem afundar na rocha.
|
||||
func ground_at(x: float, z: float) -> float:
|
||||
var step := TERRAIN_SIZE / float(GRID)
|
||||
var half := TERRAIN_SIZE / 2.0
|
||||
var fx := (x + half) / step
|
||||
var fz := (z / 0.7 + half) / step
|
||||
var i := clampi(int(floor(fx)), 0, GRID - 1)
|
||||
var j := clampi(int(floor(fz)), 0, GRID - 1)
|
||||
var u := clampf(fx - i, 0.0, 1.0)
|
||||
var v := clampf(fz - j, 0.0, 1.0)
|
||||
var ha := _heights[j * (GRID + 1) + i]
|
||||
var hb := _heights[j * (GRID + 1) + i + 1]
|
||||
var hc := _heights[(j + 1) * (GRID + 1) + i]
|
||||
var hd := _heights[(j + 1) * (GRID + 1) + i + 1]
|
||||
# Mesmos triângulos de _build_terrain: (a, b, c) e (b, d, c).
|
||||
if u + v <= 1.0:
|
||||
return ha + (hb - ha) * u + (hc - ha) * v
|
||||
return hd + (hc - hd) * (1.0 - u) + (hb - hd) * (1.0 - v)
|
||||
|
||||
|
||||
## Normal do terreno desenhado em (x, z).
|
||||
func ground_normal(x: float, z: float) -> Vector3:
|
||||
var e := 0.4
|
||||
var dx := ground_at(x + e, z) - ground_at(x - e, z)
|
||||
var dz := ground_at(x, z + e) - ground_at(x, z - e)
|
||||
return Vector3(-dx, 2.0 * e, -dz).normalized()
|
||||
|
||||
|
||||
## Pedras do costão: lista de [centro (Vector3), raio horizontal].
|
||||
func rock_list() -> Array:
|
||||
return _rocks
|
||||
|
||||
|
||||
## Altura da água em (x, z) no instante t (as mesmas ondas do shader).
|
||||
func sea_height(x: float, z: float, t: float) -> float:
|
||||
var h := 0.0
|
||||
for w in WAVES:
|
||||
var dir: Vector2 = (w[0] as Vector2).normalized()
|
||||
h += float(w[2]) * sin(TAU / float(w[1]) * dir.dot(Vector2(x, z)) + t * float(w[3]))
|
||||
return h * _wave_scale
|
||||
|
||||
|
||||
## Mar mais calmo (< 1) ou agitado (> 1). Padrão 1.
|
||||
func set_sea_state(scale: float) -> void:
|
||||
_wave_scale = scale
|
||||
_ocean_mat.set_shader_parameter("wave_scale", scale)
|
||||
|
||||
|
||||
## Com params.sea_detail = true, o mar é uma malha radial fina no centro; mova o centro para
|
||||
## perto da câmera a cada quadro (as ondas usam coordenada do mundo, então não "andam").
|
||||
func set_sea_focus(x: float, z: float) -> void:
|
||||
_ocean.position = Vector3(x, 0, z)
|
||||
|
||||
|
||||
func ocean_material() -> ShaderMaterial:
|
||||
return _ocean_mat
|
||||
|
||||
|
||||
func setup(cfg: Dictionary, viewport_size: Vector2) -> void:
|
||||
_cfg = cfg
|
||||
_p = cfg.params
|
||||
_size = viewport_size
|
||||
_dur = maxf(float(cfg.video.duration), 0.1)
|
||||
_variant = int(_p.get("variant", 0))
|
||||
_make_noises()
|
||||
var time := str(_p.get("time", "day"))
|
||||
_night = time == "night"
|
||||
# A hora vem do parâmetro; "variant" (Gerar de novo) muda só a câmera.
|
||||
var sunset := not _night and time == "sunset"
|
||||
# embedded = true: a ilha é cenário dentro de OUTRA cena da biblioteca (que cria a câmera).
|
||||
# environment = false: a outra cena também cuida do céu e da luz.
|
||||
_embedded = bool(_p.get("embedded", false))
|
||||
if bool(_p.get("environment", true)):
|
||||
_build_environment(sunset)
|
||||
_build_terrain()
|
||||
_build_trees()
|
||||
_build_rocks()
|
||||
if bool(_p.get("lighthouse", true)):
|
||||
_build_lighthouse(sunset)
|
||||
_build_ocean(sunset)
|
||||
if _embedded:
|
||||
return
|
||||
_camera = Camera3D.new()
|
||||
_camera.fov = 52.0
|
||||
_camera.near = 0.3
|
||||
_camera.far = 9000.0
|
||||
_camera.keep_aspect = Camera3D.KEEP_HEIGHT
|
||||
add_child(_camera)
|
||||
_camera.current = true
|
||||
|
||||
|
||||
func apply(t: float) -> void:
|
||||
_t = t
|
||||
_ocean_mat.set_shader_parameter("scene_time", t)
|
||||
if _lamp:
|
||||
# Lanterna do farol pulsando devagar.
|
||||
var mat := _lamp.get_surface_override_material(0) as StandardMaterial3D
|
||||
mat.emission_energy_multiplier = (4.0 if _night else 1.6) + 1.2 * (0.5 + 0.5 * sin(t * 2.4))
|
||||
if not _embedded:
|
||||
_place_camera(t)
|
||||
|
||||
|
||||
func state_signature() -> String:
|
||||
return "%.3f,%.3f,%.3f" % [_last_cam.x, _last_cam.y, _last_cam.z]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ terreno
|
||||
|
||||
func _make_noises() -> void:
|
||||
_noise_shape = FastNoiseLite.new()
|
||||
_noise_shape.seed = 7
|
||||
_noise_shape.frequency = 1.0
|
||||
_noise_shape.fractal_octaves = 3
|
||||
_noise_ridge = FastNoiseLite.new()
|
||||
_noise_ridge.seed = 21
|
||||
_noise_ridge.frequency = 1.0
|
||||
_noise_ridge.fractal_type = FastNoiseLite.FRACTAL_RIDGED
|
||||
_noise_ridge.fractal_octaves = 4
|
||||
_noise_detail = FastNoiseLite.new()
|
||||
_noise_detail.seed = 33
|
||||
_noise_detail.frequency = 1.0
|
||||
_noise_detail.fractal_octaves = 3
|
||||
|
||||
|
||||
## Altura do terreno (y = 0 é o nível do mar). A ilha é alongada, com uma crista central
|
||||
## alta, encostas íngremes e costão de pedra que cai direto no mar.
|
||||
func height_at(x: float, z: float) -> float:
|
||||
var nx := x / ISLAND_A
|
||||
var nz := z / ISLAND_B
|
||||
var d := sqrt(nx * nx + nz * nz) + _noise_shape.get_noise_2d(x * 0.018, z * 0.018) * 0.22
|
||||
var m := clampf((1.0 - d) / 0.6, 0.0, 1.0)
|
||||
m = m * m * (3.0 - 2.0 * m)
|
||||
var ridge := _noise_ridge.get_noise_2d(x * 0.022, z * 0.022) * 0.5 + 0.5
|
||||
var crest := 1.0 - absf(nz) * 0.9
|
||||
var h := m * (5.0 + 30.0 * pow(m, 0.8) * (0.55 + 0.45 * ridge) * crest)
|
||||
h += _noise_detail.get_noise_2d(x * 0.11, z * 0.11) * 1.6 * m
|
||||
# Fora da ilha: fundo do mar descendo.
|
||||
return h - 3.0 + (1.0 - m) * -6.0 * clampf(d - 0.9, 0.0, 1.0)
|
||||
|
||||
|
||||
func _terrain_color(h: float, slope: float, x: float, z: float) -> Color:
|
||||
var n := _noise_detail.get_noise_2d(x * 0.35, z * 0.35) * 0.5 + 0.5
|
||||
if h < -0.6:
|
||||
return Color("#1d4a52").lerp(Color("#2f6b6a"), clampf((h + 6.0) / 5.0, 0.0, 1.0))
|
||||
if h < 1.2:
|
||||
return Color("#6b6358").lerp(Color("#4f4a43"), n) # costão molhado
|
||||
if slope > 0.72:
|
||||
return Color("#4c4944").lerp(Color("#66615a"), n) # pedra exposta
|
||||
var forest := Color("#173a1d").lerp(Color("#2b5a27"), n) # chão sob a mata
|
||||
return forest.lerp(Color("#4a5a2c"), clampf((h - 28.0) / 14.0, 0.0, 0.35))
|
||||
|
||||
|
||||
func _build_terrain() -> void:
|
||||
var st := SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
var step := TERRAIN_SIZE / float(GRID)
|
||||
var half := TERRAIN_SIZE / 2.0
|
||||
_heights.resize((GRID + 1) * (GRID + 1))
|
||||
for j in GRID + 1:
|
||||
for i in GRID + 1:
|
||||
var x := -half + float(i) * step
|
||||
var z := (-half + float(j) * step) * 0.7 # ilha alongada: menos extensão em z
|
||||
var h := height_at(x, z)
|
||||
_heights[j * (GRID + 1) + i] = h
|
||||
var dx := height_at(x + 0.8, z) - height_at(x - 0.8, z)
|
||||
var dz := height_at(x, z + 0.8) - height_at(x, z - 0.8)
|
||||
var slope := clampf(Vector2(dx, dz).length() / 1.6 / 2.2, 0.0, 1.0)
|
||||
st.set_color(_terrain_color(h, slope, x, z))
|
||||
st.add_vertex(Vector3(x, h, z))
|
||||
for j in GRID:
|
||||
for i in GRID:
|
||||
var a := j * (GRID + 1) + i
|
||||
var b := a + 1
|
||||
var c := a + GRID + 1
|
||||
var d := c + 1
|
||||
st.add_index(a)
|
||||
st.add_index(b)
|
||||
st.add_index(c)
|
||||
st.add_index(b)
|
||||
st.add_index(d)
|
||||
st.add_index(c)
|
||||
st.generate_normals()
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.vertex_color_use_as_albedo = true
|
||||
mat.roughness = 0.95
|
||||
var node := MeshInstance3D.new()
|
||||
node.name = "Terrain"
|
||||
node.mesh = st.commit()
|
||||
node.material_override = mat
|
||||
add_child(node)
|
||||
|
||||
|
||||
func _build_trees() -> void:
|
||||
var crown := CylinderMesh.new()
|
||||
crown.top_radius = 0.0
|
||||
crown.bottom_radius = 1.9
|
||||
crown.height = 3.4
|
||||
crown.radial_segments = 7
|
||||
crown.rings = 1
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.vertex_color_use_as_albedo = true
|
||||
mat.roughness = 0.9
|
||||
crown.material = mat
|
||||
var mm := MultiMesh.new()
|
||||
mm.transform_format = MultiMesh.TRANSFORM_3D
|
||||
mm.use_colors = true
|
||||
mm.mesh = crown
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 4242
|
||||
var placed: Array[Transform3D] = []
|
||||
var colors: Array[Color] = []
|
||||
var tries := 0
|
||||
while placed.size() < TREE_COUNT and tries < TREE_COUNT * 6:
|
||||
tries += 1
|
||||
var x := rng.randf_range(-ISLAND_A, ISLAND_A)
|
||||
var z := rng.randf_range(-ISLAND_B, ISLAND_B)
|
||||
var h := height_at(x, z)
|
||||
if h < 1.6:
|
||||
continue
|
||||
var slope := Vector2(height_at(x + 0.8, z) - height_at(x - 0.8, z), height_at(x, z + 0.8) - height_at(x, z - 0.8)).length() / 3.2
|
||||
if slope > 0.85 or rng.randf() < slope * 0.6:
|
||||
continue
|
||||
var s := rng.randf_range(0.75, 1.45)
|
||||
var basis := Basis.from_euler(Vector3(rng.randf_range(-0.08, 0.08), rng.randf() * TAU, rng.randf_range(-0.08, 0.08))).scaled(Vector3(s, s * rng.randf_range(0.8, 1.3), s))
|
||||
placed.append(Transform3D(basis, Vector3(x, h + 1.4 * s, z)))
|
||||
colors.append(Color("#0d2610").lerp(Color("#2a5222"), rng.randf()).lerp(Color("#4a6a22"), rng.randf() * 0.2))
|
||||
mm.instance_count = placed.size()
|
||||
for i in placed.size():
|
||||
mm.set_instance_transform(i, placed[i])
|
||||
mm.set_instance_color(i, colors[i])
|
||||
var node := MultiMeshInstance3D.new()
|
||||
node.name = "Forest"
|
||||
node.multimesh = mm
|
||||
add_child(node)
|
||||
|
||||
|
||||
func _build_rocks() -> void:
|
||||
var rock := SphereMesh.new()
|
||||
rock.radius = 1.0
|
||||
rock.height = 1.4
|
||||
rock.radial_segments = 7
|
||||
rock.rings = 4
|
||||
var mat := StandardMaterial3D.new()
|
||||
mat.albedo_color = Color("#5e5b56")
|
||||
mat.roughness = 1.0
|
||||
rock.material = mat
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 909
|
||||
var mm := MultiMesh.new()
|
||||
mm.transform_format = MultiMesh.TRANSFORM_3D
|
||||
mm.mesh = rock
|
||||
var list: Array[Transform3D] = []
|
||||
for i in 420:
|
||||
var ang := rng.randf() * TAU
|
||||
var r := rng.randf_range(0.93, 1.08)
|
||||
var x := cos(ang) * ISLAND_A * r
|
||||
var z := sin(ang) * ISLAND_B * r
|
||||
var h := height_at(x, z)
|
||||
if h > 3.0 or h < -2.5:
|
||||
continue
|
||||
var s := rng.randf_range(0.8, 3.2)
|
||||
_rocks.append([Vector3(x, maxf(h, -0.4), z), s])
|
||||
list.append(Transform3D(Basis.from_euler(Vector3(rng.randf() * TAU, rng.randf() * TAU, 0)).scaled(Vector3(s, s * 0.7, s)), Vector3(x, maxf(h, -0.4), z)))
|
||||
mm.instance_count = list.size()
|
||||
for i in list.size():
|
||||
mm.set_instance_transform(i, list[i])
|
||||
var node := MultiMeshInstance3D.new()
|
||||
node.name = "Rocks"
|
||||
node.multimesh = mm
|
||||
add_child(node)
|
||||
|
||||
|
||||
func _build_lighthouse(sunset: bool) -> void:
|
||||
# No ponto mais alto da metade sudoeste da ilha.
|
||||
var best := Vector3(-ISLAND_A * 0.45, 0, ISLAND_B * 0.1)
|
||||
for i in 60:
|
||||
var x := -ISLAND_A * 0.7 + float(i % 10) * ISLAND_A * 0.06
|
||||
var z := -ISLAND_B * 0.3 + float(i / 10) * ISLAND_B * 0.1
|
||||
var h := height_at(x, z)
|
||||
if h > best.y:
|
||||
best = Vector3(x, h, z)
|
||||
_lighthouse_pos = best
|
||||
var root := Node3D.new()
|
||||
root.name = "Lighthouse"
|
||||
root.position = best - Vector3(0, 0.6, 0)
|
||||
add_child(root)
|
||||
var white := StandardMaterial3D.new()
|
||||
white.albedo_color = Color("#f2efe8")
|
||||
white.roughness = 0.6
|
||||
var red := StandardMaterial3D.new()
|
||||
red.albedo_color = Color("#b8322a")
|
||||
red.roughness = 0.6
|
||||
var tower_h := 11.0
|
||||
var bands := 5
|
||||
for b in bands:
|
||||
var seg := CylinderMesh.new()
|
||||
var t0 := float(b) / bands
|
||||
var t1 := float(b + 1) / bands
|
||||
seg.bottom_radius = lerpf(1.7, 1.15, t0)
|
||||
seg.top_radius = lerpf(1.7, 1.15, t1)
|
||||
seg.height = tower_h / bands
|
||||
seg.radial_segments = 20
|
||||
var mi := MeshInstance3D.new()
|
||||
mi.mesh = seg
|
||||
mi.material_override = red if b % 2 == 1 else white
|
||||
mi.position = Vector3(0, tower_h * (t0 + t1) / 2.0, 0)
|
||||
root.add_child(mi)
|
||||
var gallery := CylinderMesh.new()
|
||||
gallery.top_radius = 1.7
|
||||
gallery.bottom_radius = 1.7
|
||||
gallery.height = 0.35
|
||||
gallery.radial_segments = 20
|
||||
var gmi := MeshInstance3D.new()
|
||||
gmi.mesh = gallery
|
||||
gmi.material_override = red
|
||||
gmi.position = Vector3(0, tower_h + 0.15, 0)
|
||||
root.add_child(gmi)
|
||||
var lamp_mesh := CylinderMesh.new()
|
||||
lamp_mesh.top_radius = 0.95
|
||||
lamp_mesh.bottom_radius = 0.95
|
||||
lamp_mesh.height = 1.4
|
||||
lamp_mesh.radial_segments = 16
|
||||
var lamp_mat := StandardMaterial3D.new()
|
||||
lamp_mat.albedo_color = Color("#ffe9a8")
|
||||
lamp_mat.emission_enabled = true
|
||||
lamp_mat.emission = Color("#ffd27a")
|
||||
lamp_mat.emission_energy_multiplier = 2.0
|
||||
_lamp = MeshInstance3D.new()
|
||||
_lamp.mesh = lamp_mesh
|
||||
_lamp.set_surface_override_material(0, lamp_mat)
|
||||
_lamp.position = Vector3(0, tower_h + 1.0, 0)
|
||||
root.add_child(_lamp)
|
||||
var cap := CylinderMesh.new()
|
||||
cap.top_radius = 0.0
|
||||
cap.bottom_radius = 1.25
|
||||
cap.height = 1.2
|
||||
cap.radial_segments = 20
|
||||
var cmi := MeshInstance3D.new()
|
||||
cmi.mesh = cap
|
||||
cmi.material_override = red
|
||||
cmi.position = Vector3(0, tower_h + 2.3, 0)
|
||||
root.add_child(cmi)
|
||||
if sunset or _night:
|
||||
var glow := OmniLight3D.new()
|
||||
glow.light_color = Color("#ffcf7a")
|
||||
glow.light_energy = 2.0
|
||||
glow.omni_range = 18.0
|
||||
glow.position = Vector3(0, tower_h + 1.0, 0)
|
||||
root.add_child(glow)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ mar e céu
|
||||
|
||||
func _build_ocean(sunset: bool) -> void:
|
||||
var plane: Mesh
|
||||
if bool(_p.get("sea_detail", false)):
|
||||
plane = _radial_sea()
|
||||
else:
|
||||
plane = PlaneMesh.new()
|
||||
plane.size = Vector2(16000, 16000)
|
||||
plane.subdivide_width = 400
|
||||
plane.subdivide_depth = 400
|
||||
var shader := Shader.new()
|
||||
shader.code = OCEAN_SHADER
|
||||
_ocean_mat = ShaderMaterial.new()
|
||||
_ocean_mat.shader = shader
|
||||
_ocean_mat.set_shader_parameter("island_axes", Vector2(ISLAND_A, ISLAND_B))
|
||||
if _night:
|
||||
_ocean_mat.set_shader_parameter("deep_color", Color("#02070f"))
|
||||
_ocean_mat.set_shader_parameter("shallow_color", Color("#06202a"))
|
||||
_ocean_mat.set_shader_parameter("sky_tint", Color("#2a3d63"))
|
||||
elif sunset:
|
||||
_ocean_mat.set_shader_parameter("deep_color", Color("#0b1f33"))
|
||||
_ocean_mat.set_shader_parameter("shallow_color", Color("#1f5a63"))
|
||||
_ocean_mat.set_shader_parameter("sky_tint", Color("#f3a865"))
|
||||
var node := MeshInstance3D.new()
|
||||
node.name = "Ocean"
|
||||
node.mesh = plane
|
||||
node.material_override = _ocean_mat
|
||||
node.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
add_child(node)
|
||||
_ocean = node
|
||||
|
||||
|
||||
## Mar para tomadas rente à água: anéis cada vez mais espaçados a partir do centro
|
||||
## (~0,3 m perto, dezenas de metros no horizonte), para a onda desenhada bater com sea_height().
|
||||
func _radial_sea() -> ArrayMesh:
|
||||
var seg := 288
|
||||
var rings := 190
|
||||
var growth := pow(8000.0 / 0.35, 1.0 / float(rings))
|
||||
var st := SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
st.set_normal(Vector3.UP)
|
||||
st.add_vertex(Vector3.ZERO)
|
||||
for r in rings:
|
||||
var radius := 0.35 * pow(growth, float(r))
|
||||
for s in seg:
|
||||
var a := TAU * float(s) / float(seg)
|
||||
st.set_normal(Vector3.UP)
|
||||
st.add_vertex(Vector3(cos(a) * radius, 0, sin(a) * radius))
|
||||
for s in seg:
|
||||
st.add_index(0)
|
||||
st.add_index(1 + (s + 1) % seg)
|
||||
st.add_index(1 + s)
|
||||
for r in rings - 1:
|
||||
for s in seg:
|
||||
var a := 1 + r * seg + s
|
||||
var b := 1 + r * seg + (s + 1) % seg
|
||||
var c := a + seg
|
||||
var d := b + seg
|
||||
st.add_index(a)
|
||||
st.add_index(b)
|
||||
st.add_index(c)
|
||||
st.add_index(b)
|
||||
st.add_index(d)
|
||||
st.add_index(c)
|
||||
var mesh := st.commit()
|
||||
# A malha é plana, mas o shader levanta as ondas: AABB folgada evita sumir no recorte.
|
||||
mesh.custom_aabb = AABB(Vector3(-8000, -5, -8000), Vector3(16000, 10, 16000))
|
||||
return mesh
|
||||
|
||||
|
||||
func _build_environment(sunset: bool) -> void:
|
||||
var sky_mat := ProceduralSkyMaterial.new()
|
||||
if _night:
|
||||
sky_mat.sky_top_color = Color("#03060f")
|
||||
sky_mat.sky_horizon_color = Color("#1a2740")
|
||||
sky_mat.ground_horizon_color = Color("#141e33")
|
||||
sky_mat.ground_bottom_color = Color("#02040a")
|
||||
elif sunset:
|
||||
sky_mat.sky_top_color = Color("#2b3566")
|
||||
sky_mat.sky_horizon_color = Color("#f2a35e")
|
||||
sky_mat.ground_horizon_color = Color("#c7804f")
|
||||
sky_mat.ground_bottom_color = Color("#1a2238")
|
||||
else:
|
||||
sky_mat.sky_top_color = Color("#2d6fb3")
|
||||
sky_mat.sky_horizon_color = Color("#b9d7ec")
|
||||
sky_mat.ground_horizon_color = Color("#9cc3d9")
|
||||
sky_mat.ground_bottom_color = Color("#1d3d55")
|
||||
sky_mat.sun_angle_max = 20.0
|
||||
var sky := Sky.new()
|
||||
sky.sky_material = sky_mat
|
||||
var env := Environment.new()
|
||||
env.background_mode = Environment.BG_SKY
|
||||
env.sky = sky
|
||||
env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
|
||||
env.ambient_light_energy = 0.18 if _night else (0.45 if not sunset else 0.4)
|
||||
env.tonemap_mode = Environment.TONE_MAPPER_ACES
|
||||
env.tonemap_exposure = 1.05
|
||||
env.fog_enabled = true
|
||||
env.fog_light_color = sky_mat.sky_horizon_color
|
||||
env.fog_density = 0.00045 if not sunset else 0.0006
|
||||
env.fog_sky_affect = 0.15
|
||||
var we := WorldEnvironment.new()
|
||||
we.environment = env
|
||||
add_child(we)
|
||||
var sun := DirectionalLight3D.new()
|
||||
sun.light_color = Color("#9fb6ff") if _night else (Color("#ffd2a0") if sunset else Color("#fff4e2"))
|
||||
sun.light_energy = 0.35 if _night else (1.5 if sunset else 1.7)
|
||||
sun.rotation_degrees = Vector3(-14.0, -60.0, 0.0) if sunset else Vector3(-48.0, -35.0, 0.0)
|
||||
sun.shadow_enabled = true
|
||||
sun.directional_shadow_max_distance = 600.0
|
||||
add_child(sun)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ câmera
|
||||
|
||||
func _smooth(p: float) -> float:
|
||||
var q := clampf(p, 0.0, 1.0)
|
||||
return q * q * (3.0 - 2.0 * q)
|
||||
|
||||
|
||||
func _place_camera(t: float) -> void:
|
||||
var p := _smooth(t / _dur)
|
||||
var dir := 1.0 if _variant % 4 < 2 else -1.0
|
||||
var a0 := deg_to_rad(205.0 + float(_variant) * 47.0)
|
||||
var shot := str(_p.get("shot", "orbit"))
|
||||
var pos := Vector3.ZERO
|
||||
var target := Vector3(0, 10, 0)
|
||||
match shot:
|
||||
"approach":
|
||||
var r := lerpf(430.0, 175.0, p)
|
||||
var ang := a0 + dir * deg_to_rad(12.0) * p
|
||||
pos = Vector3(cos(ang) * r, lerpf(60.0, 34.0, p), sin(ang) * r)
|
||||
target = Vector3(0, lerpf(4.0, 12.0, p), 0)
|
||||
"lighthouse":
|
||||
var lp := _lighthouse_pos
|
||||
var ang := a0 + dir * deg_to_rad(55.0) * p
|
||||
pos = lp + Vector3(cos(ang) * 40.0, lerpf(24.0, 17.0, p), sin(ang) * 40.0)
|
||||
target = lp + Vector3(0, 8.0, 0)
|
||||
"lowpass":
|
||||
var ang := a0 + dir * deg_to_rad(28.0) * p
|
||||
pos = Vector3(cos(ang) * 135.0, 4.5 + 1.2 * sin(t * 0.7), sin(ang) * 135.0)
|
||||
target = Vector3(0, 14.0, 0)
|
||||
_:
|
||||
var ang := a0 + dir * deg_to_rad(42.0) * p
|
||||
pos = Vector3(cos(ang) * 190.0, lerpf(70.0, 52.0, p), sin(ang) * 190.0)
|
||||
target = Vector3(0, 8.0, 0)
|
||||
_camera.position = pos
|
||||
_camera.look_at(target, Vector3.UP)
|
||||
_last_cam = pos
|
||||
@@ -0,0 +1,37 @@
|
||||
; Projeto da prova de conceito CenaForge.
|
||||
; A cena é montada por código a partir de um JSON externo (ver ../config).
|
||||
; Testado com Godot 4.7.2 stable (official), renderizador Mobile.
|
||||
|
||||
config_version=5
|
||||
|
||||
[application]
|
||||
|
||||
config/name="CenaForge PoC"
|
||||
config/description="Cena narrativa descrita por JSON, animada por tempo de cena e renderizada pelo Movie Maker."
|
||||
run/main_scene="res://scenes/main.tscn"
|
||||
config/features=PackedStringArray("4.7", "Mobile")
|
||||
boot_splash/show_image=false
|
||||
boot_splash/bg_color=Color(0.08, 0.09, 0.11, 1)
|
||||
|
||||
[display]
|
||||
|
||||
; Resolução base = perfil de prévia. O lançador sobrescreve via override.cfg
|
||||
; para o perfil final (1080x1920), porque o Movie Maker fixa o tamanho na inicialização.
|
||||
window/size/viewport_width=540
|
||||
window/size/viewport_height=960
|
||||
window/size/window_width_override=405
|
||||
window/size/window_height_override=720
|
||||
window/stretch/mode="viewport"
|
||||
window/stretch/aspect="keep"
|
||||
|
||||
[editor]
|
||||
|
||||
movie_writer/fps=30
|
||||
|
||||
[rendering]
|
||||
|
||||
renderer/rendering_method="mobile"
|
||||
renderer/rendering_method.mobile="mobile"
|
||||
anti_aliasing/quality/msaa_3d=2
|
||||
lights_and_shadows/directional_shadow/size=4096
|
||||
environment/defaults/default_clear_color=Color(0.55, 0.7, 0.85, 1)
|
||||
@@ -0,0 +1,6 @@
|
||||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://scripts/doc/doc_main.gd" id="1_main"]
|
||||
|
||||
[node name="Doc" type="Node"]
|
||||
script = ExtResource("1_main")
|
||||
@@ -0,0 +1,6 @@
|
||||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://scripts/core/main.gd" id="1_main"]
|
||||
|
||||
[node name="Main" type="Node3D"]
|
||||
script = ExtResource("1_main")
|
||||
@@ -0,0 +1,112 @@
|
||||
extends RefCounted
|
||||
## Pinta fachadas simples de casas de bairro para os planos distantes, e as
|
||||
## texturas de asfalto e calçada. Tudo determinístico a partir de uma seed.
|
||||
##
|
||||
## As fachadas distantes são geradas uma vez por `tools/generate_backgrounds.gd`
|
||||
## e salvas em assets/backgrounds/. Se os PNGs não existirem, a cena gera as
|
||||
## mesmas imagens em memória (mesma função, mesmas seeds).
|
||||
|
||||
const FACADE_SIZE := Vector2i(256, 192)
|
||||
const FACADE_VARIANTS := 8
|
||||
|
||||
const WALL_COLORS := [
|
||||
Color("#E9C46A"), Color("#F4A261"), Color("#9BC1BC"), Color("#E5989B"),
|
||||
Color("#A8DADC"), Color("#F1EDE4"), Color("#B5C99A"), Color("#CDB4DB"),
|
||||
Color("#FFD6A5"), Color("#D9CAB3"),
|
||||
]
|
||||
const BRICK := Color("#B8673F")
|
||||
|
||||
|
||||
static func facade_file_name(variant: int) -> String:
|
||||
return "facade_%02d.png" % variant
|
||||
|
||||
|
||||
## Fachada opaca (sem transparência): casa de laje com platibanda, comum em
|
||||
## bairros brasileiros. Variantes ímpares podem ser de tijolo aparente.
|
||||
static func paint_facade(variant: int) -> Image:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 7919 * (variant + 1)
|
||||
var w := FACADE_SIZE.x
|
||||
var h := FACADE_SIZE.y
|
||||
var img := Image.create(w, h, false, Image.FORMAT_RGB8)
|
||||
|
||||
var brick := variant % 4 == 3
|
||||
var wall: Color = BRICK if brick else WALL_COLORS[rng.randi() % WALL_COLORS.size()]
|
||||
img.fill(wall)
|
||||
if brick:
|
||||
for y in range(0, h, 6):
|
||||
img.fill_rect(Rect2i(0, y, w, 1), wall.darkened(0.25))
|
||||
_noise(img, rng, 0.05)
|
||||
|
||||
# Platibanda (faixa do topo) e caixa d'água ocasional.
|
||||
var parapet := int(h * 0.12)
|
||||
img.fill_rect(Rect2i(0, 0, w, parapet), wall.lightened(0.18) if not brick else Color("#C9C2B5"))
|
||||
img.fill_rect(Rect2i(0, parapet, w, 3), wall.darkened(0.3))
|
||||
|
||||
# Dois andares em parte das variantes.
|
||||
var floors := 2 if rng.randf() < 0.6 else 1
|
||||
var floor_h := (h - parapet) / floors
|
||||
for f in floors:
|
||||
var top := parapet + f * floor_h
|
||||
var is_ground := f == floors - 1
|
||||
var windows := 2 + rng.randi() % 2
|
||||
var slot := w / (windows + (1 if is_ground else 0))
|
||||
for i in windows + (1 if is_ground else 0):
|
||||
var cx := int(slot * (i + 0.5))
|
||||
if is_ground and i == int((windows + 1) / 2):
|
||||
# Porta ou portão de garagem.
|
||||
var dw := int(slot * 0.45)
|
||||
var dh := int(floor_h * 0.78)
|
||||
var door_color := Color("#6B4F3A") if rng.randf() < 0.5 else Color("#7C8288")
|
||||
img.fill_rect(Rect2i(cx - dw / 2 - 2, top + floor_h - dh - 2, dw + 4, dh + 2), Color("#EDEDED"))
|
||||
img.fill_rect(Rect2i(cx - dw / 2, top + floor_h - dh, dw, dh), door_color)
|
||||
continue
|
||||
var ww := int(slot * 0.5)
|
||||
var wh := int(floor_h * 0.42)
|
||||
var wy := top + int(floor_h * 0.25)
|
||||
img.fill_rect(Rect2i(cx - ww / 2 - 3, wy - 3, ww + 6, wh + 6), Color("#F2F2F2"))
|
||||
img.fill_rect(Rect2i(cx - ww / 2, wy, ww, wh), Color("#2F3E4E").lerp(Color("#5B7A99"), rng.randf() * 0.5))
|
||||
img.fill_rect(Rect2i(cx - 1, wy, 2, wh), Color("#F2F2F2"))
|
||||
if not is_ground:
|
||||
# Linha da laje entre andares.
|
||||
img.fill_rect(Rect2i(0, top + floor_h - 3, w, 3), wall.darkened(0.22))
|
||||
# Rodapé
|
||||
img.fill_rect(Rect2i(0, h - 6, w, 6), wall.darkened(0.35))
|
||||
return img
|
||||
|
||||
|
||||
static func paint_asphalt(seed_value: int) -> Image:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = seed_value
|
||||
var img := Image.create(256, 256, false, Image.FORMAT_RGB8)
|
||||
img.fill(Color(0.29, 0.29, 0.3))
|
||||
_noise(img, rng, 0.07)
|
||||
# Remendos discretos para dar referência de movimento.
|
||||
for i in 6:
|
||||
var r := Rect2i(rng.randi_range(0, 200), rng.randi_range(0, 200), rng.randi_range(20, 56), rng.randi_range(14, 40))
|
||||
img.fill_rect(r, Color(0.25, 0.25, 0.26).lerp(Color(0.34, 0.34, 0.35), rng.randf()))
|
||||
_noise(img, rng, 0.03)
|
||||
img.generate_mipmaps()
|
||||
return img
|
||||
|
||||
|
||||
static func paint_sidewalk(seed_value: int) -> Image:
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = seed_value
|
||||
var img := Image.create(256, 256, false, Image.FORMAT_RGB8)
|
||||
img.fill(Color(0.74, 0.72, 0.68))
|
||||
_noise(img, rng, 0.05)
|
||||
# Juntas das placas de concreto (a textura cobre 2 m x 2 m).
|
||||
for k in [0, 128]:
|
||||
img.fill_rect(Rect2i(k, 0, 3, 256), Color(0.55, 0.53, 0.5))
|
||||
img.fill_rect(Rect2i(0, k, 256, 3), Color(0.55, 0.53, 0.5))
|
||||
img.generate_mipmaps()
|
||||
return img
|
||||
|
||||
|
||||
static func _noise(img: Image, rng: RandomNumberGenerator, amount: float) -> void:
|
||||
for y in img.get_height():
|
||||
for x in img.get_width():
|
||||
var c := img.get_pixel(x, y)
|
||||
var n := (rng.randf() - 0.5) * 2.0 * amount
|
||||
img.set_pixel(x, y, Color(clampf(c.r + n, 0, 1), clampf(c.g + n, 0, 1), clampf(c.b + n, 0, 1)))
|
||||
@@ -0,0 +1 @@
|
||||
uid://b02qpcs7n8ub8
|
||||
@@ -0,0 +1,207 @@
|
||||
extends RefCounted
|
||||
## Moto e entregador provisórios, feitos só com primitivas.
|
||||
##
|
||||
## Orientação local: frente em -Z, Y para cima, origem no chão entre as rodas.
|
||||
## Hierarquia devolvida:
|
||||
## root (posição da moto no mundo)
|
||||
## ├─ front_wheel / rear_wheel (pivôs no eixo; giram em X)
|
||||
## └─ body (pivô de arfagem e vibração: quadro, banco, caixa e entregador)
|
||||
## Um GLB futuro entra no lugar de `body`/rodas por meio de um nó adaptador
|
||||
## que corrige escala e orientação; esta convenção não vale para todo modelo.
|
||||
|
||||
const WHEEL_RADIUS := 0.3
|
||||
const FRONT_AXLE_Z := -0.68
|
||||
const REAR_AXLE_Z := 0.62
|
||||
|
||||
const JACKET := Color("#27496D")
|
||||
const PANTS := Color("#2B2B2E")
|
||||
const SKIN_GLOVE := Color("#1C1C1C")
|
||||
const HELMET := Color("#F2F2F2")
|
||||
const VISOR := Color("#1A2430")
|
||||
const TIRE := Color("#1B1B1B")
|
||||
const METAL := Color("#9EA4AA")
|
||||
const DARK := Color("#2A2C30")
|
||||
|
||||
var _materials := {}
|
||||
|
||||
|
||||
static func build(cfg: Dictionary) -> Dictionary:
|
||||
return load("res://scripts/builders/rider_builder.gd").new()._build(cfg)
|
||||
|
||||
|
||||
func _build(cfg: Dictionary) -> Dictionary:
|
||||
var bike_color: Color = cfg.rider.bike_color
|
||||
var box_color: Color = cfg.rider.box_color
|
||||
|
||||
var root := Node3D.new()
|
||||
root.name = "Rider"
|
||||
var body := Node3D.new()
|
||||
body.name = "Body"
|
||||
root.add_child(body)
|
||||
|
||||
var front := _wheel("FrontWheel", FRONT_AXLE_Z, bike_color)
|
||||
var rear := _wheel("RearWheel", REAR_AXLE_Z, bike_color)
|
||||
root.add_child(front)
|
||||
root.add_child(rear)
|
||||
|
||||
_build_bike(body, bike_color, box_color)
|
||||
_build_courier(body)
|
||||
return {"root": root, "body": body, "front_wheel": front, "rear_wheel": rear, "wheel_radius": WHEEL_RADIUS}
|
||||
|
||||
|
||||
func _wheel(node_name: String, axle_z: float, accent: Color) -> Node3D:
|
||||
var pivot := Node3D.new()
|
||||
pivot.name = node_name
|
||||
pivot.position = Vector3(0, WHEEL_RADIUS, axle_z)
|
||||
# Pneu: cilindro com eixo em X.
|
||||
var tire := _mesh(pivot, _cylinder(WHEEL_RADIUS, WHEEL_RADIUS, 0.11), TIRE, Vector3.ZERO)
|
||||
tire.rotation = Vector3(0, 0, PI * 0.5)
|
||||
var rim := _mesh(pivot, _cylinder(WHEEL_RADIUS * 0.68, WHEEL_RADIUS * 0.68, 0.125), METAL, Vector3.ZERO)
|
||||
rim.rotation = Vector3(0, 0, PI * 0.5)
|
||||
var hub := _mesh(pivot, _cylinder(0.06, 0.06, 0.16), accent, Vector3.ZERO)
|
||||
hub.rotation = Vector3(0, 0, PI * 0.5)
|
||||
# Raios escuros sobre o aro: deixam a rotação visível de lado.
|
||||
for k in 3:
|
||||
var spoke := _mesh(pivot, _box_mesh(Vector3(0.13, WHEEL_RADIUS * 1.3, 0.035)), DARK, Vector3.ZERO)
|
||||
spoke.rotation = Vector3(k * PI / 3.0, 0, 0)
|
||||
# Cravos claros na banda de rodagem: deixam a rotação visível por trás.
|
||||
for k in 10:
|
||||
var a := k * TAU / 10.0
|
||||
var lug := _mesh(pivot, _box_mesh(Vector3(0.09, 0.03, 0.06)), Color("#5A5A5A"), Vector3(0, cos(a), sin(a)) * (WHEEL_RADIUS + 0.004))
|
||||
lug.rotation = Vector3(a, 0, 0)
|
||||
return pivot
|
||||
|
||||
|
||||
func _build_bike(body: Node3D, bike_color: Color, box_color: Color) -> void:
|
||||
# Garfo dianteiro e suspensão traseira
|
||||
for x in [-0.09, 0.09]:
|
||||
_limb(body, Vector3(x, WHEEL_RADIUS, FRONT_AXLE_Z), Vector3(x, 1.0, -0.5), 0.032, METAL)
|
||||
_limb(body, Vector3(x * 1.6, WHEEL_RADIUS, REAR_AXLE_Z), Vector3(x * 1.6, 0.82, 0.38), 0.03, DARK)
|
||||
# Quadro (tubo principal) e balança traseira
|
||||
_limb(body, Vector3(0, 0.98, -0.5), Vector3(0, 0.62, 0.3), 0.05, DARK)
|
||||
_limb(body, Vector3(0, 0.42, 0.05), Vector3(0, WHEEL_RADIUS, REAR_AXLE_Z), 0.04, DARK)
|
||||
# Motor
|
||||
_mesh(body, _box_mesh(Vector3(0.3, 0.3, 0.42)), Color("#3B3E43"), Vector3(0, 0.42, -0.05))
|
||||
# Tanque e carenagem na cor da moto
|
||||
_mesh(body, _box_mesh(Vector3(0.34, 0.24, 0.55)), bike_color, Vector3(0, 0.82, -0.2))
|
||||
_mesh(body, _box_mesh(Vector3(0.3, 0.22, 0.42)), bike_color, Vector3(0, 0.72, 0.32))
|
||||
# Banco
|
||||
_mesh(body, _box_mesh(Vector3(0.3, 0.1, 0.66)), Color("#151515"), Vector3(0, 0.89, 0.18))
|
||||
# Para-lamas
|
||||
_mesh(body, _box_mesh(Vector3(0.16, 0.04, 0.42)), bike_color, Vector3(0, WHEEL_RADIUS * 2.0 + 0.06, FRONT_AXLE_Z + 0.02))
|
||||
_mesh(body, _box_mesh(Vector3(0.18, 0.04, 0.4)), bike_color, Vector3(0, 0.78, REAR_AXLE_Z + 0.22))
|
||||
# Escapamento
|
||||
_limb(body, Vector3(0.17, 0.38, -0.05), Vector3(0.18, 0.5, 0.78), 0.045, METAL)
|
||||
# Farol, painel e guidão
|
||||
_mesh(body, _box_mesh(Vector3(0.3, 0.22, 0.2)), bike_color, Vector3(0, 1.0, -0.58))
|
||||
var headlight := _mesh(body, _sphere(0.085), Color("#FFF6D8"), Vector3(0, 0.98, -0.69))
|
||||
headlight.material_override = _emissive(Color("#FFF6D8"), Color("#FFF1C2"), 0.6)
|
||||
_limb(body, Vector3(-0.36, 1.12, -0.47), Vector3(0.36, 1.12, -0.47), 0.025, DARK)
|
||||
for x in [-0.33, 0.33]:
|
||||
# Retrovisores
|
||||
_limb(body, Vector3(x * 0.8, 1.12, -0.47), Vector3(x * 0.95, 1.36, -0.5), 0.012, DARK)
|
||||
var mirror := _mesh(body, _cylinder(0.055, 0.055, 0.02), DARK, Vector3(x * 0.95, 1.38, -0.5))
|
||||
mirror.rotation = Vector3(PI * 0.5, 0, 0)
|
||||
# Lanterna traseira
|
||||
var tail := _mesh(body, _box_mesh(Vector3(0.14, 0.06, 0.04)), Color("#C81E1E"), Vector3(0, 0.8, REAR_AXLE_Z + 0.43))
|
||||
tail.material_override = _emissive(Color("#C81E1E"), Color("#FF2A2A"), 0.8)
|
||||
# Bagageiro e caixa de entrega (sem marca)
|
||||
_mesh(body, _box_mesh(Vector3(0.38, 0.035, 0.42)), DARK, Vector3(0, 0.93, REAR_AXLE_Z + 0.06))
|
||||
_mesh(body, _box_mesh(Vector3(0.5, 0.46, 0.48)), box_color, Vector3(0, 1.18, REAR_AXLE_Z + 0.08))
|
||||
_mesh(body, _box_mesh(Vector3(0.52, 0.05, 0.5)), box_color.darkened(0.25), Vector3(0, 1.43, REAR_AXLE_Z + 0.08))
|
||||
# Faixa refletiva na traseira da caixa
|
||||
_mesh(body, _box_mesh(Vector3(0.4, 0.06, 0.01)), Color("#F4F4F4"), Vector3(0, 1.2, REAR_AXLE_Z + 0.325))
|
||||
|
||||
|
||||
func _build_courier(body: Node3D) -> void:
|
||||
var pelvis := Vector3(0, 1.0, 0.16)
|
||||
var chest := Vector3(0, 1.42, -0.02)
|
||||
# Tronco inclinado para frente
|
||||
_limb(body, pelvis, chest, 0.17, JACKET)
|
||||
var back := _mesh(body, _box_mesh(Vector3(0.4, 0.2, 0.26)), JACKET, Vector3(0, 1.36, 0.0))
|
||||
back.rotation = Vector3(-0.35, 0, 0)
|
||||
# Pescoço e capacete (com viseira escura voltada para frente)
|
||||
_limb(body, chest + Vector3(0, 0.04, 0), Vector3(0, 1.58, -0.06), 0.06, PANTS)
|
||||
_mesh(body, _sphere(0.155), HELMET, Vector3(0, 1.69, -0.08))
|
||||
var visor := _mesh(body, _box_mesh(Vector3(0.24, 0.1, 0.06)), VISOR, Vector3(0, 1.69, -0.215))
|
||||
visor.rotation = Vector3(-0.15, 0, 0)
|
||||
_mesh(body, _box_mesh(Vector3(0.05, 0.05, 0.28)), Color("#D95437"), Vector3(0, 1.84, -0.06))
|
||||
for side in [-1.0, 1.0]:
|
||||
var shoulder := Vector3(side * 0.21, 1.42, -0.02)
|
||||
var elbow := Vector3(side * 0.31, 1.22, -0.26)
|
||||
var grip := Vector3(side * 0.33, 1.12, -0.47)
|
||||
_limb(body, shoulder, elbow, 0.062, JACKET)
|
||||
_limb(body, elbow, grip, 0.052, JACKET)
|
||||
_mesh(body, _sphere(0.055), SKIN_GLOVE, grip)
|
||||
var hip := Vector3(side * 0.13, 0.98, 0.16)
|
||||
var knee := Vector3(side * 0.21, 0.92, -0.24)
|
||||
var ankle := Vector3(side * 0.2, 0.42, -0.04)
|
||||
_limb(body, hip, knee, 0.085, PANTS)
|
||||
_limb(body, knee, ankle, 0.065, PANTS)
|
||||
# Pé apoiado na pedaleira
|
||||
_mesh(body, _box_mesh(Vector3(0.11, 0.09, 0.26)), Color("#141414"), ankle + Vector3(0, -0.03, -0.06))
|
||||
_limb(body, Vector3(side * 0.12, 0.38, -0.02), Vector3(side * 0.26, 0.38, -0.02), 0.018, METAL)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Utilidades
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
## Cápsula entre dois pontos (membros, tubos).
|
||||
func _limb(parent: Node3D, a: Vector3, b: Vector3, radius: float, color: Color) -> MeshInstance3D:
|
||||
var axis := b - a
|
||||
var capsule := CapsuleMesh.new()
|
||||
capsule.radius = radius
|
||||
capsule.height = axis.length() + radius * 2.0
|
||||
var node := _mesh(parent, capsule, color, (a + b) * 0.5)
|
||||
node.basis = Basis(Quaternion(Vector3.UP, axis.normalized()))
|
||||
return node
|
||||
|
||||
|
||||
func _mesh(parent: Node3D, mesh: Mesh, color: Color, position: Vector3) -> MeshInstance3D:
|
||||
var node := MeshInstance3D.new()
|
||||
node.mesh = mesh
|
||||
node.position = position
|
||||
node.material_override = _material(color)
|
||||
parent.add_child(node)
|
||||
return node
|
||||
|
||||
|
||||
func _material(color: Color) -> StandardMaterial3D:
|
||||
var key := color.to_html()
|
||||
if not _materials.has(key):
|
||||
var m := StandardMaterial3D.new()
|
||||
m.albedo_color = color
|
||||
m.roughness = 0.55
|
||||
_materials[key] = m
|
||||
return _materials[key]
|
||||
|
||||
|
||||
func _emissive(albedo: Color, emission: Color, energy: float) -> StandardMaterial3D:
|
||||
var m := StandardMaterial3D.new()
|
||||
m.albedo_color = albedo
|
||||
m.emission_enabled = true
|
||||
m.emission = emission
|
||||
m.emission_energy_multiplier = energy
|
||||
return m
|
||||
|
||||
|
||||
func _box_mesh(size: Vector3) -> BoxMesh:
|
||||
var m := BoxMesh.new()
|
||||
m.size = size
|
||||
return m
|
||||
|
||||
|
||||
func _cylinder(top: float, bottom: float, height: float) -> CylinderMesh:
|
||||
var m := CylinderMesh.new()
|
||||
m.top_radius = top
|
||||
m.bottom_radius = bottom
|
||||
m.height = height
|
||||
return m
|
||||
|
||||
|
||||
func _sphere(radius: float) -> SphereMesh:
|
||||
var m := SphereMesh.new()
|
||||
m.radius = radius
|
||||
m.height = radius * 2.0
|
||||
return m
|
||||
@@ -0,0 +1 @@
|
||||
uid://dl3txarp77f86
|
||||
@@ -0,0 +1,447 @@
|
||||
extends RefCounted
|
||||
## Monta rua, calçadas, casas próximas em 3D, postes, árvores, luz e o fundo
|
||||
## distante em planos com textura (fachadas fixas, sem billboard).
|
||||
##
|
||||
## Convenção da cena: Y é altura, a rua corre ao longo de Z e a moto anda
|
||||
## para -Z. A rua começa atrás da câmera e termina num cruzamento em z = -L,
|
||||
## de onde sobe um morro com casas em planos. Todas as escolhas aleatórias usam
|
||||
## RandomNumberGenerator com a seed da configuração (determinístico).
|
||||
|
||||
const FacadePainter := preload("res://scripts/builders/facade_painter.gd")
|
||||
|
||||
const SIDEWALK_WIDTH := 2.4
|
||||
const CURB_HEIGHT := 0.15
|
||||
const CROSS_STREET_WIDTH := 9.0
|
||||
const HILL_SLOPE := 0.32
|
||||
const STORY_HEIGHT := 2.9
|
||||
|
||||
const HOUSE_COLORS := [
|
||||
"#E9C46A", "#F4A261", "#9BC1BC", "#E5989B", "#A8DADC",
|
||||
"#F1EDE4", "#B5C99A", "#CDB4DB", "#FFD6A5", "#E07A5F",
|
||||
]
|
||||
const WALL_COLORS := ["#D8D2C4", "#BDB5A6", "#E9E4D8", "#C9C3B6", "#A9B4A0"]
|
||||
const ROOF_COLORS := ["#A5522F", "#B5653A", "#8F4A2C"]
|
||||
|
||||
const LIGHTING := {
|
||||
"warm_day": {
|
||||
"sun_color": Color(1.0, 0.95, 0.86), "sun_energy": 1.35, "sun_pitch": -42.0, "sun_yaw": -30.0,
|
||||
"sky_top": Color(0.32, 0.53, 0.84), "sky_horizon": Color(0.74, 0.81, 0.88),
|
||||
"ambient_energy": 0.55, "fog_density": 0.0045,
|
||||
},
|
||||
"golden_hour": {
|
||||
"sun_color": Color(1.0, 0.74, 0.5), "sun_energy": 1.2, "sun_pitch": -20.0, "sun_yaw": -38.0,
|
||||
"sky_top": Color(0.33, 0.43, 0.68), "sky_horizon": Color(0.97, 0.76, 0.56),
|
||||
"ambient_energy": 0.5, "fog_density": 0.006,
|
||||
},
|
||||
}
|
||||
|
||||
var _rng := RandomNumberGenerator.new()
|
||||
var _materials := {}
|
||||
var _parent: Node3D
|
||||
var _cfg: Dictionary
|
||||
var _stats := {"near_houses": 0, "distant_cards": 0, "facade_source": "none", "poles": 0, "trees": 0}
|
||||
|
||||
|
||||
## Constrói o cenário inteiro sob `parent`. Retorna estatísticas para o relatório.
|
||||
static func build(parent: Node3D, cfg: Dictionary, backgrounds_dir: String) -> Dictionary:
|
||||
var builder = load("res://scripts/builders/street_builder.gd").new()
|
||||
return builder._build(parent, cfg, backgrounds_dir)
|
||||
|
||||
|
||||
func _build(parent: Node3D, cfg: Dictionary, backgrounds_dir: String) -> Dictionary:
|
||||
_parent = parent
|
||||
_cfg = cfg
|
||||
_rng.seed = cfg.seed
|
||||
_build_environment(cfg.world.lighting_preset)
|
||||
_build_ground_and_road()
|
||||
_build_near_houses()
|
||||
_build_poles_and_wires()
|
||||
_build_trees()
|
||||
if cfg.world.background_mode == "cards":
|
||||
_build_background_cards(backgrounds_dir)
|
||||
return _stats
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Luz e ambiente
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
func _build_environment(preset_name: String) -> void:
|
||||
var p: Dictionary = LIGHTING[preset_name]
|
||||
var sky_material := ProceduralSkyMaterial.new()
|
||||
sky_material.sky_top_color = p.sky_top
|
||||
sky_material.sky_horizon_color = p.sky_horizon
|
||||
sky_material.ground_horizon_color = p.sky_horizon
|
||||
sky_material.ground_bottom_color = Color(0.35, 0.36, 0.33)
|
||||
var sky := Sky.new()
|
||||
sky.sky_material = sky_material
|
||||
|
||||
var env := Environment.new()
|
||||
env.background_mode = Environment.BG_SKY
|
||||
env.sky = sky
|
||||
env.ambient_light_source = Environment.AMBIENT_SOURCE_SKY
|
||||
env.ambient_light_energy = p.ambient_energy
|
||||
env.tonemap_mode = Environment.TONE_MAPPER_FILMIC
|
||||
env.fog_enabled = true
|
||||
env.fog_light_color = p.sky_horizon
|
||||
env.fog_density = p.fog_density
|
||||
env.fog_sky_affect = 0.0
|
||||
var world_env := WorldEnvironment.new()
|
||||
world_env.name = "WorldEnvironment"
|
||||
world_env.environment = env
|
||||
_parent.add_child(world_env)
|
||||
|
||||
var sun := DirectionalLight3D.new()
|
||||
sun.name = "Sun"
|
||||
# Sol atrás e à esquerda da câmera: ilumina as costas do entregador e as
|
||||
# fachadas voltadas para +Z; as sombras caem para frente e à direita.
|
||||
sun.rotation_degrees = Vector3(p.sun_pitch, p.sun_yaw, 0.0)
|
||||
sun.light_color = p.sun_color
|
||||
sun.light_energy = p.sun_energy
|
||||
sun.shadow_enabled = true
|
||||
sun.directional_shadow_max_distance = 80.0
|
||||
sun.directional_shadow_mode = DirectionalLight3D.SHADOW_PARALLEL_2_SPLITS
|
||||
_parent.add_child(sun)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Chão, pista, calçadas e sinalização
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
func _build_ground_and_road() -> void:
|
||||
var length: float = _cfg.world.street_length
|
||||
var road_w: float = _cfg.world.road_width
|
||||
var z_near := _z_near()
|
||||
var z_far := -length
|
||||
var span := z_near - z_far
|
||||
var z_mid := (z_near + z_far) * 0.5
|
||||
|
||||
# Terrenos atrás das casas (evita vazio entre as construções).
|
||||
_box(Vector3(260.0, 0.1, span + CROSS_STREET_WIDTH + 30.0), Vector3(0, -0.06, z_mid - CROSS_STREET_WIDTH * 0.5 - 6.0), _color_mat("#8A8F63", 1.0), false)
|
||||
|
||||
var asphalt := StandardMaterial3D.new()
|
||||
asphalt.albedo_texture = ImageTexture.create_from_image(FacadePainter.paint_asphalt(_cfg.seed))
|
||||
asphalt.uv1_triplanar = true
|
||||
asphalt.uv1_world_triplanar = true
|
||||
asphalt.uv1_scale = Vector3(0.2, 0.2, 0.2)
|
||||
asphalt.roughness = 0.95
|
||||
asphalt.texture_filter = BaseMaterial3D.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC
|
||||
_box(Vector3(road_w, 0.1, span), Vector3(0, -0.05, z_mid), asphalt, false)
|
||||
# Rua transversal no fim, para a avenida não terminar num muro.
|
||||
_box(Vector3(260.0, 0.1, CROSS_STREET_WIDTH), Vector3(0, -0.05, z_far - CROSS_STREET_WIDTH * 0.5), asphalt, false)
|
||||
|
||||
var sidewalk := StandardMaterial3D.new()
|
||||
sidewalk.albedo_texture = ImageTexture.create_from_image(FacadePainter.paint_sidewalk(_cfg.seed + 1))
|
||||
sidewalk.uv1_triplanar = true
|
||||
sidewalk.uv1_world_triplanar = true
|
||||
sidewalk.uv1_scale = Vector3(0.5, 0.5, 0.5)
|
||||
sidewalk.roughness = 0.9
|
||||
sidewalk.texture_filter = BaseMaterial3D.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC
|
||||
var curb := _color_mat("#D9D6CF", 0.9)
|
||||
for side in [-1.0, 1.0]:
|
||||
var x_curb: float = side * (road_w * 0.5 + 0.08)
|
||||
var x_walk: float = side * (road_w * 0.5 + 0.16 + SIDEWALK_WIDTH * 0.5)
|
||||
_box(Vector3(0.16, CURB_HEIGHT, span), Vector3(x_curb, CURB_HEIGHT * 0.5, z_mid), curb, false)
|
||||
_box(Vector3(SIDEWALK_WIDTH, CURB_HEIGHT, span), Vector3(x_walk, CURB_HEIGHT * 0.5, z_mid), sidewalk, false)
|
||||
# Calçada do outro lado do cruzamento.
|
||||
_box(Vector3(260.0, CURB_HEIGHT, SIDEWALK_WIDTH), Vector3(0, CURB_HEIGHT * 0.5, z_far - CROSS_STREET_WIDTH - SIDEWALK_WIDTH * 0.5), sidewalk, false)
|
||||
|
||||
# Faixa central amarela tracejada: referência forte de deslocamento.
|
||||
var paint := _color_mat("#E3B23C", 0.7)
|
||||
var z := z_near - 1.0
|
||||
while z > z_far + 6.0:
|
||||
_box(Vector3(0.12, 0.012, 2.6), Vector3(0, 0.006, z), paint, false)
|
||||
z -= 6.0
|
||||
# Faixa de pedestres antes do cruzamento.
|
||||
var zebra := _color_mat("#EDEDE6", 0.7)
|
||||
var x := -road_w * 0.5 + 0.6
|
||||
while x < road_w * 0.5 - 0.4:
|
||||
_box(Vector3(0.5, 0.012, 3.0), Vector3(x, 0.006, z_far + 2.2), zebra, false)
|
||||
x += 1.0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Casas próximas (3D)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
func _build_near_houses() -> void:
|
||||
var n: int = _cfg.world.near_houses_per_side
|
||||
if n <= 0:
|
||||
return
|
||||
var road_w: float = _cfg.world.road_width
|
||||
var z_a: float = _cfg.rider.start_position.z + 16.0
|
||||
var z_b: float = -_cfg.world.street_length + 0.5
|
||||
var lot := (z_a - z_b) / n
|
||||
for side in [-1.0, 1.0]:
|
||||
for i in n:
|
||||
var z1: float = z_a - i * lot
|
||||
_build_lot(side, z1, z1 - lot, road_w * 0.5 + 0.16 + SIDEWALK_WIDTH)
|
||||
_stats.near_houses = n * 2
|
||||
|
||||
|
||||
func _build_lot(side: float, z1: float, z2: float, x_property: float) -> void:
|
||||
var lot := z1 - z2
|
||||
var wall_color: String = WALL_COLORS[_rng.randi() % WALL_COLORS.size()]
|
||||
var house_color := Color(HOUSE_COLORS[_rng.randi() % HOUSE_COLORS.size()])
|
||||
if _rng.randf() < 0.35:
|
||||
wall_color = "#" + house_color.darkened(0.12).to_html(false)
|
||||
|
||||
# Muro com portão: traço típico de rua residencial brasileira.
|
||||
var wall_h := _rng.randf_range(1.6, 2.1)
|
||||
var x_wall := side * (x_property + 0.1)
|
||||
var gate_w := minf(3.0, lot * 0.35)
|
||||
var gate_center := _rng.randf_range(z2 + gate_w * 0.5 + 0.6, z1 - gate_w * 0.5 - 0.6)
|
||||
var wall_mat := _color_mat(wall_color, 0.95)
|
||||
_wall_segment(x_wall, z1 - 0.05, gate_center + gate_w * 0.5, wall_h, wall_mat)
|
||||
_wall_segment(x_wall, gate_center - gate_w * 0.5, z2 + 0.05, wall_h, wall_mat)
|
||||
var gate_mat := _color_mat(["#3C4248", "#5A4636", "#2F4F4F"][_rng.randi() % 3], 0.6, 0.4)
|
||||
_box(Vector3(0.08, wall_h - 0.15, gate_w), Vector3(x_wall, (wall_h - 0.15) * 0.5, gate_center), gate_mat)
|
||||
# Pilares do portão
|
||||
for zz in [gate_center + gate_w * 0.5 + 0.12, gate_center - gate_w * 0.5 - 0.12]:
|
||||
_box(Vector3(0.3, wall_h + 0.2, 0.24), Vector3(x_wall, (wall_h + 0.2) * 0.5, zz), wall_mat)
|
||||
|
||||
# Corpo da casa
|
||||
var setback := _rng.randf_range(2.2, 3.6)
|
||||
var depth := _rng.randf_range(8.0, 11.0)
|
||||
var width := maxf(4.0, lot - _rng.randf_range(1.2, 3.0))
|
||||
var z_center := (z1 + z2) * 0.5 + _rng.randf_range(-0.5, 0.5) * (lot - width)
|
||||
var stories := 2 if _rng.randf() < 0.4 else 1
|
||||
var height := STORY_HEIGHT * stories + 0.2
|
||||
var x_facade := side * (x_property + setback)
|
||||
var x_center := x_facade + side * depth * 0.5
|
||||
_box(Vector3(depth, height, width), Vector3(x_center, height * 0.5, z_center), _color_mat("#" + house_color.to_html(false), 0.9))
|
||||
|
||||
# Janelas e porta na fachada voltada para a rua (normal = -side em X).
|
||||
var x_detail := x_facade - side * 0.04
|
||||
var frame_mat := _color_mat("#F2F2EE", 0.6)
|
||||
var glass_mat := _color_mat("#33475B", 0.25, 0.1)
|
||||
var door_mat := _color_mat(["#6B4F3A", "#7C8288", "#4E5D6C"][_rng.randi() % 3], 0.7)
|
||||
var windows := maxi(1, int(width / 3.2))
|
||||
for s in stories:
|
||||
var base_y := s * STORY_HEIGHT
|
||||
var door_slot := _rng.randi() % (windows + 1) if s == 0 else -1
|
||||
var slots := windows + (1 if s == 0 else 0)
|
||||
for k in slots:
|
||||
var zz := z_center + width * 0.5 - (k + 0.5) * width / slots
|
||||
if k == door_slot:
|
||||
_box(Vector3(0.1, 2.25, 1.15), Vector3(x_detail + side * 0.02, 1.12, zz), frame_mat)
|
||||
_box(Vector3(0.1, 2.1, 0.95), Vector3(x_detail, 1.05, zz), door_mat)
|
||||
else:
|
||||
_box(Vector3(0.08, 1.3, 1.55), Vector3(x_detail + side * 0.02, base_y + 1.6, zz), frame_mat)
|
||||
_box(Vector3(0.1, 1.1, 1.35), Vector3(x_detail, base_y + 1.6, zz), glass_mat)
|
||||
if s < stories - 1:
|
||||
# Laje aparente entre andares
|
||||
_box(Vector3(depth + 0.16, 0.18, width + 0.16), Vector3(x_center, base_y + STORY_HEIGHT, z_center), _color_mat("#" + house_color.darkened(0.15).to_html(false), 0.9))
|
||||
|
||||
# Telhado: cerâmico de duas águas ou laje com platibanda e caixa d'água.
|
||||
if _rng.randf() < 0.55:
|
||||
var roof := MeshInstance3D.new()
|
||||
var prism := PrismMesh.new()
|
||||
var roof_h := _rng.randf_range(1.0, 1.5)
|
||||
prism.size = Vector3(depth + 0.8, roof_h, width + 0.6)
|
||||
roof.mesh = prism
|
||||
roof.material_override = _color_mat(ROOF_COLORS[_rng.randi() % ROOF_COLORS.size()], 0.85)
|
||||
roof.position = Vector3(x_center, height + roof_h * 0.5, z_center)
|
||||
_parent.add_child(roof)
|
||||
else:
|
||||
var parapet := _color_mat("#" + house_color.lightened(0.15).to_html(false), 0.9)
|
||||
_box(Vector3(depth + 0.1, 0.6, width + 0.1), Vector3(x_center, height + 0.3, z_center), parapet)
|
||||
if _rng.randf() < 0.6:
|
||||
var tank := MeshInstance3D.new()
|
||||
var cyl := CylinderMesh.new()
|
||||
cyl.top_radius = 0.55
|
||||
cyl.bottom_radius = 0.6
|
||||
cyl.height = 0.9
|
||||
tank.mesh = cyl
|
||||
tank.material_override = _color_mat("#3A6EA5", 0.5)
|
||||
tank.position = Vector3(x_center + side * _rng.randf_range(0.0, depth * 0.3), height + 0.6 + 0.45, z_center + _rng.randf_range(-width * 0.3, width * 0.3))
|
||||
_parent.add_child(tank)
|
||||
|
||||
|
||||
func _wall_segment(x: float, z_from: float, z_to: float, h: float, mat: Material) -> void:
|
||||
var length := z_from - z_to
|
||||
if length <= 0.05:
|
||||
return
|
||||
_box(Vector3(0.2, h, length), Vector3(x, h * 0.5, (z_from + z_to) * 0.5), mat)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Postes, fios e árvores: repetição que evidencia deslocamento e profundidade
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
func _build_poles_and_wires() -> void:
|
||||
var road_w: float = _cfg.world.road_width
|
||||
var x := road_w * 0.5 + 0.5
|
||||
var concrete := _color_mat("#9A9890", 0.9)
|
||||
var wire_mat := _color_mat("#1E1E1E", 0.8)
|
||||
var z := _z_near() - 4.0
|
||||
var tops: Array[Vector3] = []
|
||||
while z > -_cfg.world.street_length + 2.0:
|
||||
var pole := MeshInstance3D.new()
|
||||
var cyl := CylinderMesh.new()
|
||||
cyl.top_radius = 0.09
|
||||
cyl.bottom_radius = 0.14
|
||||
cyl.height = 8.5
|
||||
pole.mesh = cyl
|
||||
pole.material_override = concrete
|
||||
pole.position = Vector3(x, 4.25, z)
|
||||
_parent.add_child(pole)
|
||||
_box(Vector3(1.7, 0.1, 0.1), Vector3(x - 0.3, 8.0, z), concrete)
|
||||
tops.append(Vector3(x, 8.0, z))
|
||||
_stats.poles += 1
|
||||
z -= 15.0 + _rng.randf_range(-1.0, 1.0)
|
||||
for i in tops.size() - 1:
|
||||
var a := tops[i]
|
||||
var b := tops[i + 1]
|
||||
for offset in [Vector3(-0.9, 0.06, 0), Vector3(-0.3, 0.06, 0), Vector3(0.35, 0.06, 0), Vector3(0, -1.3, 0)]:
|
||||
var mid: Vector3 = (a + b) * 0.5 + offset
|
||||
_box(Vector3(0.035, 0.035, a.z - b.z), mid, wire_mat, false)
|
||||
|
||||
|
||||
func _build_trees() -> void:
|
||||
var road_w: float = _cfg.world.road_width
|
||||
var x := -(road_w * 0.5 + 1.0)
|
||||
var trunk := _color_mat("#6B4E37", 0.9)
|
||||
var leaves := [_color_mat("#4F7D3A", 0.9), _color_mat("#5E8C42", 0.9), _color_mat("#3F6B33", 0.9)]
|
||||
var z := _z_near() - 8.0
|
||||
while z > -_cfg.world.street_length + 6.0:
|
||||
if _rng.randf() < 0.8:
|
||||
var tz := z + _rng.randf_range(-3.0, 3.0)
|
||||
var t := MeshInstance3D.new()
|
||||
var cyl := CylinderMesh.new()
|
||||
cyl.top_radius = 0.1
|
||||
cyl.bottom_radius = 0.15
|
||||
cyl.height = 2.6
|
||||
t.mesh = cyl
|
||||
t.material_override = trunk
|
||||
t.position = Vector3(x, 1.3, tz)
|
||||
_parent.add_child(t)
|
||||
for k in 3:
|
||||
var crown := MeshInstance3D.new()
|
||||
var sphere := SphereMesh.new()
|
||||
var r := _rng.randf_range(0.9, 1.4)
|
||||
sphere.radius = r
|
||||
sphere.height = r * 1.7
|
||||
crown.mesh = sphere
|
||||
crown.material_override = leaves[_rng.randi() % leaves.size()]
|
||||
crown.position = Vector3(x + _rng.randf_range(-0.5, 0.5), 2.8 + k * 0.45, tz + _rng.randf_range(-0.6, 0.6))
|
||||
_parent.add_child(crown)
|
||||
_stats.trees += 1
|
||||
z -= 20.0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Fundo distante: morro com casas em planos texturizados (orientação fixa)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
func _build_background_cards(backgrounds_dir: String) -> void:
|
||||
var length: float = _cfg.world.street_length
|
||||
var z_hill := -length - CROSS_STREET_WIDTH - SIDEWALK_WIDTH - 1.0
|
||||
var angle := atan(HILL_SLOPE)
|
||||
|
||||
var hill := MeshInstance3D.new()
|
||||
var plane := PlaneMesh.new()
|
||||
plane.size = Vector2(320.0, 200.0)
|
||||
hill.mesh = plane
|
||||
hill.material_override = _color_mat("#6F8B4F", 1.0)
|
||||
hill.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
hill.rotation = Vector3(angle, 0, 0)
|
||||
hill.position = Vector3(0, sin(angle) * 100.0 - 0.05, z_hill - cos(angle) * 100.0)
|
||||
_parent.add_child(hill)
|
||||
# Cumeeira irregular: sem ela a borda do plano vira uma linha reta no céu.
|
||||
var ridge_y := sin(angle) * 200.0
|
||||
var ridge_z := z_hill - cos(angle) * 200.0
|
||||
var x_ridge := -170.0
|
||||
while x_ridge < 170.0:
|
||||
var bump := MeshInstance3D.new()
|
||||
var sphere := SphereMesh.new()
|
||||
var r := _rng.randf_range(22.0, 40.0)
|
||||
sphere.radius = r
|
||||
sphere.height = r * 2.0
|
||||
sphere.radial_segments = 24
|
||||
sphere.rings = 12
|
||||
bump.mesh = sphere
|
||||
bump.scale = Vector3(1.0, _rng.randf_range(0.35, 0.6), 0.8)
|
||||
bump.material_override = _color_mat("#6F8B4F", 1.0)
|
||||
bump.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
bump.position = Vector3(x_ridge, ridge_y - r * 0.15, ridge_z - r * 0.3)
|
||||
_parent.add_child(bump)
|
||||
x_ridge += r * _rng.randf_range(1.1, 1.6)
|
||||
|
||||
var textures: Array[ImageTexture] = []
|
||||
var loaded := 0
|
||||
for v in FacadePainter.FACADE_VARIANTS:
|
||||
var path := backgrounds_dir.path_join(FacadePainter.facade_file_name(v))
|
||||
var img: Image = null
|
||||
if FileAccess.file_exists(path):
|
||||
img = Image.load_from_file(path)
|
||||
if img != null:
|
||||
loaded += 1
|
||||
if img == null:
|
||||
img = FacadePainter.paint_facade(v)
|
||||
img.generate_mipmaps()
|
||||
textures.append(ImageTexture.create_from_image(img))
|
||||
_stats.facade_source = "png" if loaded == FacadePainter.FACADE_VARIANTS else ("mixed" if loaded > 0 else "generated")
|
||||
|
||||
var card_mats: Array[StandardMaterial3D] = []
|
||||
for tex in textures:
|
||||
var m := StandardMaterial3D.new()
|
||||
m.albedo_texture = tex
|
||||
m.roughness = 1.0
|
||||
m.texture_filter = BaseMaterial3D.TEXTURE_FILTER_LINEAR_WITH_MIPMAPS_ANISOTROPIC
|
||||
card_mats.append(m)
|
||||
|
||||
var quad_cache := {}
|
||||
for row in 7:
|
||||
var z := z_hill - 3.0 - row * 13.0
|
||||
var y_ground := (z_hill - z) * HILL_SLOPE
|
||||
var x := -75.0 + _rng.randf_range(0.0, 5.0)
|
||||
while x < 75.0:
|
||||
var w := _rng.randf_range(7.0, 9.5)
|
||||
var h := w * 0.75
|
||||
var key := "%.2f" % w
|
||||
if not quad_cache.has(key):
|
||||
var q := QuadMesh.new()
|
||||
q.size = Vector2(w, h)
|
||||
quad_cache[key] = q
|
||||
var card := MeshInstance3D.new()
|
||||
card.mesh = quad_cache[key]
|
||||
card.material_override = card_mats[_rng.randi() % card_mats.size()]
|
||||
card.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
# Base levemente enterrada no morro para não aparecer borda flutuando.
|
||||
card.position = Vector3(x + w * 0.5, y_ground + h * 0.5 - 0.6, z + _rng.randf_range(-1.5, 1.5))
|
||||
_parent.add_child(card)
|
||||
_stats.distant_cards += 1
|
||||
x += w + _rng.randf_range(0.6, 3.0)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Utilidades
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
func _z_near() -> float:
|
||||
return _cfg.rider.start_position.z + 40.0
|
||||
|
||||
|
||||
func _box(size: Vector3, position: Vector3, material: Material, cast_shadow := true) -> MeshInstance3D:
|
||||
var mesh := BoxMesh.new()
|
||||
mesh.size = size
|
||||
var node := MeshInstance3D.new()
|
||||
node.mesh = mesh
|
||||
node.material_override = material
|
||||
node.position = position
|
||||
if not cast_shadow:
|
||||
node.cast_shadow = GeometryInstance3D.SHADOW_CASTING_SETTING_OFF
|
||||
_parent.add_child(node)
|
||||
return node
|
||||
|
||||
|
||||
func _color_mat(hex: String, roughness: float, metallic := 0.0) -> StandardMaterial3D:
|
||||
var key := "%s|%.2f|%.2f" % [hex, roughness, metallic]
|
||||
if not _materials.has(key):
|
||||
var m := StandardMaterial3D.new()
|
||||
m.albedo_color = Color(hex)
|
||||
m.roughness = roughness
|
||||
m.metallic = metallic
|
||||
_materials[key] = m
|
||||
return _materials[key]
|
||||
@@ -0,0 +1 @@
|
||||
uid://dosp5vndi1ua7
|
||||
@@ -0,0 +1,296 @@
|
||||
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()
|
||||
@@ -0,0 +1 @@
|
||||
uid://cqmgnobpvhi0w
|
||||
@@ -0,0 +1,334 @@
|
||||
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) + "..."
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
uid://duthxk5m2w3tx
|
||||
@@ -0,0 +1,126 @@
|
||||
extends RefCounted
|
||||
## Relógio da cena. Tudo que se move é função pura do tempo de cena `t` (s),
|
||||
## nunca do relógio do sistema: avaliar o mesmo `t` com a mesma configuração
|
||||
## devolve o mesmo estado, em qualquer execução.
|
||||
##
|
||||
## Perfil de velocidade (convenção da cena: a moto avança em -Z):
|
||||
## parada -> rampa suave (accelSeconds) -> cruzeiro -> frenagem suave -> parada
|
||||
## As rampas usam smoothstep na velocidade, então velocidade E aceleração são
|
||||
## contínuas: não há tranco nem salto de posição entre as fases. A distância
|
||||
## chega exatamente em travelMeters no instante stopSeconds e fica ali.
|
||||
|
||||
const SceneConfig := preload("res://scripts/core/scene_config.gd")
|
||||
const CameraController := preload("res://scripts/view/camera_controller.gd")
|
||||
const OverlayController := preload("res://scripts/view/overlay_controller.gd")
|
||||
|
||||
## Amplitude da vibração vertical da carroceria em velocidade de cruzeiro (m).
|
||||
const BOB_AMPLITUDE := 0.006
|
||||
## Frequência espacial da vibração (rad/m): depende da distância, não do tempo.
|
||||
const BOB_SPATIAL_FREQUENCY := 7.0
|
||||
## Mergulho de frente por m/s² de aceleração (rad), limitado a ±2°.
|
||||
const PITCH_PER_ACCEL := 0.004
|
||||
const MAX_PITCH := 0.035
|
||||
|
||||
var _cfg: Dictionary
|
||||
var _wheel_radius: float
|
||||
var _t_start: float
|
||||
var _accel_len: float
|
||||
var _t_cruise: float
|
||||
var _t_brake: float
|
||||
var _brake_len: float
|
||||
var _t_stop: float
|
||||
var _speed: float
|
||||
var _travel: float
|
||||
var _start_position: Vector3
|
||||
var _distance_at_brake: float
|
||||
|
||||
|
||||
func _init(cfg: Dictionary, wheel_radius: float) -> void:
|
||||
_cfg = cfg
|
||||
_wheel_radius = wheel_radius
|
||||
var m: Dictionary = cfg.motion
|
||||
_t_start = m.start
|
||||
_accel_len = m.accel_seconds
|
||||
_t_cruise = _t_start + _accel_len
|
||||
_t_brake = m.brake_start
|
||||
_t_stop = m.stop
|
||||
_brake_len = _t_stop - _t_brake
|
||||
_travel = cfg.rider.travel
|
||||
_start_position = cfg.rider.start_position
|
||||
_speed = SceneConfig.cruise_speed(m, _travel)
|
||||
_distance_at_brake = _speed * (_accel_len * 0.5 + (_t_brake - _t_cruise))
|
||||
|
||||
|
||||
func cruise_speed() -> float:
|
||||
return _speed
|
||||
|
||||
|
||||
func distance_at(t: float) -> float:
|
||||
if t <= _t_start:
|
||||
return 0.0
|
||||
if t < _t_cruise:
|
||||
return _speed * _accel_len * _ramp_integral((t - _t_start) / _accel_len)
|
||||
if t < _t_brake:
|
||||
return _speed * (_accel_len * 0.5 + (t - _t_cruise))
|
||||
if t < _t_stop:
|
||||
var u := t - _t_brake
|
||||
return _distance_at_brake + _speed * (u - _brake_len * _ramp_integral(u / _brake_len))
|
||||
return _travel
|
||||
|
||||
|
||||
func speed_at(t: float) -> float:
|
||||
if t <= _t_start or t >= _t_stop:
|
||||
return 0.0
|
||||
if t < _t_cruise:
|
||||
return _speed * _smoothstep((t - _t_start) / _accel_len)
|
||||
if t < _t_brake:
|
||||
return _speed
|
||||
return _speed * (1.0 - _smoothstep((t - _t_brake) / _brake_len))
|
||||
|
||||
|
||||
func acceleration_at(t: float) -> float:
|
||||
if t <= _t_start or t >= _t_stop:
|
||||
return 0.0
|
||||
if t < _t_cruise:
|
||||
return _speed * _smoothstep_derivative((t - _t_start) / _accel_len) / _accel_len
|
||||
if t < _t_brake:
|
||||
return 0.0
|
||||
return -_speed * _smoothstep_derivative((t - _t_brake) / _brake_len) / _brake_len
|
||||
|
||||
|
||||
## Estado visual completo no instante `t`. É a única fonte que a cena consulta.
|
||||
func evaluate_at_time(t: float) -> Dictionary:
|
||||
var distance := distance_at(t)
|
||||
var speed := speed_at(t)
|
||||
var acceleration := acceleration_at(t)
|
||||
var position := _start_position + Vector3(0.0, 0.0, -distance)
|
||||
var speed_ratio := clampf(speed / _speed, 0.0, 1.0) if _speed > 0.0 else 0.0
|
||||
return {
|
||||
"t": t,
|
||||
"distance": distance,
|
||||
"speed": speed,
|
||||
"acceleration": acceleration,
|
||||
"rider_position": position,
|
||||
# Rotação em torno de X. Negativa para o topo da roda ir para -Z (frente).
|
||||
"wheel_angle": -distance / _wheel_radius,
|
||||
"body_bob": BOB_AMPLITUDE * speed_ratio * sin(distance * BOB_SPATIAL_FREQUENCY),
|
||||
"body_pitch": clampf(acceleration * PITCH_PER_ACCEL, -MAX_PITCH, MAX_PITCH),
|
||||
"camera": CameraController.evaluate(_cfg, t, position),
|
||||
"overlay": OverlayController.evaluate(_cfg, t),
|
||||
}
|
||||
|
||||
|
||||
static func _smoothstep(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return p * p * (3.0 - 2.0 * p)
|
||||
|
||||
|
||||
static func _smoothstep_derivative(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return 6.0 * p * (1.0 - p)
|
||||
|
||||
|
||||
## Integral de smoothstep de 0 a p (vale 0,5 em p = 1).
|
||||
static func _ramp_integral(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return p * p * p - 0.5 * p * p * p * p
|
||||
@@ -0,0 +1 @@
|
||||
uid://dditd5mb3m2te
|
||||
@@ -0,0 +1,500 @@
|
||||
extends Node2D
|
||||
## Desenho das cenas 2D do documentário. `apply(t)` guarda o tempo e redesenha;
|
||||
## tudo depende só de (configuração, t), então o render é determinístico.
|
||||
## Medidas proporcionais ao tamanho da tela: a mesma composição em 540x960 e 1080x1920.
|
||||
##
|
||||
## Modelos:
|
||||
## title { title, subtitle?, kicker? }
|
||||
## counter { value, decimals?, prefix?, suffix?, label?, note?, grid?: { cols, rows, highlight } }
|
||||
## map { preset?: "litoral-sp", title?, markers: [{ label, lat?, lon?, kind?: "city"|"island" }],
|
||||
## route?: { from, to, label? } } (from/to = rótulo ou índice do marcador)
|
||||
|
||||
const BG := Color("#0d0d10")
|
||||
const BG_2 := Color("#1a120c")
|
||||
const ACCENT := Color("#ff7a1a")
|
||||
const GLOW := Color("#ffb547")
|
||||
const TEXT := Color("#f5f2ee")
|
||||
const MUTED := Color("#b8b0a8")
|
||||
const SEA := Color("#0b1e2b")
|
||||
const SEA_2 := Color("#0f2a3a")
|
||||
const LAND := Color("#1f3326")
|
||||
const LAND_EDGE := Color("#4f7a5a")
|
||||
|
||||
## Litoral sul e centro de São Paulo (ilustrativo, sem escala exata): pontos da costa de
|
||||
## sudoeste para nordeste e um pequeno dicionário de lugares (lat, lon).
|
||||
const PRESETS := {
|
||||
"litoral-sp": {
|
||||
"bounds": {"north": -23.35, "south": -24.95, "west": -47.65, "east": -45.75},
|
||||
"coast": [
|
||||
[-24.95, -47.65], [-24.80, -47.62], [-24.70, -47.52], [-24.55, -47.28], [-24.42, -47.10],
|
||||
[-24.32, -47.00], [-24.25, -46.90], [-24.18, -46.79], [-24.12, -46.68], [-24.09, -46.62],
|
||||
[-24.03, -46.48], [-24.01, -46.41], [-23.98, -46.37], [-23.99, -46.30], [-24.00, -46.25],
|
||||
[-23.93, -46.18], [-23.85, -46.14], [-23.80, -45.98], [-23.77, -45.85], [-23.80, -45.75],
|
||||
],
|
||||
"places": {
|
||||
"São Paulo": [-23.55, -46.63], "Santos": [-23.96, -46.33], "Guarujá": [-23.99, -46.26],
|
||||
"São Vicente": [-23.96, -46.39], "Praia Grande": [-24.00, -46.42], "Mongaguá": [-24.09, -46.62],
|
||||
"Itanhaém": [-24.18, -46.79], "Peruíbe": [-24.32, -47.00], "Bertioga": [-23.85, -46.14],
|
||||
"Ilha da Queimada Grande": [-24.487, -46.674], "Queimada Grande": [-24.487, -46.674],
|
||||
"Ilha da Queimada Pequena": [-24.375, -46.795], "Queimada Pequena": [-24.375, -46.795],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var _cfg: Dictionary
|
||||
var _p: Dictionary
|
||||
var _size := Vector2.ZERO
|
||||
var _t := 0.0
|
||||
var _dur := 1.0
|
||||
var _font: SystemFont
|
||||
var _font_regular: SystemFont
|
||||
var _map_cache := {}
|
||||
var _glow_tex: GradientTexture2D
|
||||
|
||||
|
||||
func setup(cfg: Dictionary, viewport_size: Vector2) -> void:
|
||||
_cfg = cfg
|
||||
_p = cfg.params
|
||||
_size = viewport_size
|
||||
_dur = maxf(float(cfg.video.duration), 0.1)
|
||||
_font = _make_font(800)
|
||||
_font_regular = _make_font(500)
|
||||
RenderingServer.set_default_clear_color(BG)
|
||||
var g := Gradient.new()
|
||||
g.set_color(0, Color(1, 1, 1, 1))
|
||||
g.set_color(1, Color(1, 1, 1, 0))
|
||||
g.add_point(0.45, Color(1, 1, 1, 0.32))
|
||||
_glow_tex = GradientTexture2D.new()
|
||||
_glow_tex.gradient = g
|
||||
_glow_tex.fill = GradientTexture2D.FILL_RADIAL
|
||||
_glow_tex.fill_from = Vector2(0.5, 0.5)
|
||||
_glow_tex.fill_to = Vector2(1.0, 0.5)
|
||||
_glow_tex.width = 512
|
||||
_glow_tex.height = 512
|
||||
if cfg.template == "map":
|
||||
_map_cache = _prepare_map()
|
||||
|
||||
|
||||
func apply(t: float) -> void:
|
||||
_t = t
|
||||
queue_redraw()
|
||||
|
||||
|
||||
## Resumo do estado no instante atual (para o manifesto ser comparável entre execuções).
|
||||
func state_signature() -> String:
|
||||
return "%s|%.3f" % [_cfg.template, _ease_out(_progress(0.0, 1.0))]
|
||||
|
||||
|
||||
func _make_font(weight: int) -> SystemFont:
|
||||
var f := SystemFont.new()
|
||||
f.font_names = PackedStringArray(["Segoe UI", "Segoe UI Variable Display", "Arial", "DejaVu Sans", "Liberation Sans"])
|
||||
f.font_weight = weight
|
||||
f.antialiasing = TextServer.FONT_ANTIALIASING_GRAY
|
||||
return f
|
||||
|
||||
|
||||
func _draw() -> void:
|
||||
if _cfg.is_empty():
|
||||
return
|
||||
match str(_cfg.template):
|
||||
"title":
|
||||
_draw_title()
|
||||
"counter":
|
||||
_draw_counter()
|
||||
"map":
|
||||
_draw_map()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- utilidades
|
||||
|
||||
func _progress(start: float, length: float) -> float:
|
||||
return clampf((_t - start) / maxf(length, 0.001), 0.0, 1.0)
|
||||
|
||||
|
||||
static func _ease_in_out(p: float) -> float:
|
||||
return p * p * (3.0 - 2.0 * p)
|
||||
|
||||
|
||||
static func _ease_out(p: float) -> float:
|
||||
return 1.0 - pow(1.0 - p, 3.0)
|
||||
|
||||
|
||||
func _px(fraction: float) -> int:
|
||||
return int(round(_size.y * fraction))
|
||||
|
||||
|
||||
func _background(top: Color, bottom: Color) -> void:
|
||||
var r := Rect2(Vector2.ZERO, _size)
|
||||
draw_polygon(PackedVector2Array([r.position, Vector2(r.end.x, 0), r.end, Vector2(0, r.end.y)]),
|
||||
PackedColorArray([top, top, bottom, bottom]))
|
||||
|
||||
|
||||
func _glow(center: Vector2, radius: float, color: Color) -> void:
|
||||
# Brilho suave: textura de degradê radial (sem anéis em degrau).
|
||||
draw_texture_rect(_glow_tex, Rect2(center - Vector2(radius, radius), Vector2(radius, radius) * 2.0), false, Color(color.r, color.g, color.b, color.a * 0.45))
|
||||
|
||||
|
||||
## Texto (quebra por palavra) com o topo em `top_y`, centralizado ou alinhado à esquerda
|
||||
## (margem de (1 - width_fraction) / 2). Devolve a altura usada.
|
||||
func _text_block(text: String, top_y: float, size_px: int, color: Color, font: Font, width_fraction := 0.84, max_lines := 4, align := HORIZONTAL_ALIGNMENT_CENTER) -> float:
|
||||
if text.is_empty():
|
||||
return 0.0
|
||||
var width := _size.x * width_fraction
|
||||
var left := (_size.x - width) / 2.0
|
||||
var block := font.get_multiline_string_size(text, align, width, size_px, max_lines)
|
||||
var ascent := font.get_ascent(size_px)
|
||||
draw_multiline_string(font, Vector2(left, top_y + ascent), text, align, width, size_px, max_lines, color)
|
||||
return block.y
|
||||
|
||||
|
||||
func _with_alpha(c: Color, a: float) -> Color:
|
||||
return Color(c.r, c.g, c.b, c.a * clampf(a, 0.0, 1.0))
|
||||
|
||||
|
||||
## Número no formato brasileiro: 1.500 / 0,0055.
|
||||
static func _format_number(value: float, decimals: int) -> String:
|
||||
var negative := value < 0.0
|
||||
var v := absf(value)
|
||||
var int_part := int(floor(v))
|
||||
var frac := ""
|
||||
if decimals > 0:
|
||||
var scaled := int(round((v - float(int_part)) * pow(10.0, decimals)))
|
||||
if scaled >= int(pow(10.0, decimals)):
|
||||
int_part += 1
|
||||
scaled = 0
|
||||
frac = "," + str(scaled).pad_zeros(decimals)
|
||||
var digits := str(int_part)
|
||||
var grouped := ""
|
||||
var count := 0
|
||||
for i in range(digits.length() - 1, -1, -1):
|
||||
grouped = digits[i] + grouped
|
||||
count += 1
|
||||
if count % 3 == 0 and i > 0:
|
||||
grouped = "." + grouped
|
||||
return ("-" if negative else "") + grouped + frac
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- título
|
||||
|
||||
## Cores de destaque por variação ("gerar de novo"): brasa, ciano, violeta.
|
||||
const VARIANT_ACCENTS := [Color("#ff7a1a"), Color("#3fc1c9"), Color("#a78bfa")]
|
||||
|
||||
|
||||
func _variant() -> int:
|
||||
return int(_p.get("variant", 0))
|
||||
|
||||
|
||||
func _accent() -> Color:
|
||||
return VARIANT_ACCENTS[_variant() % VARIANT_ACCENTS.size()]
|
||||
|
||||
|
||||
func _draw_title() -> void:
|
||||
match _variant() % 3:
|
||||
1:
|
||||
_draw_title_editorial()
|
||||
2:
|
||||
_draw_title_lower()
|
||||
_:
|
||||
_draw_title_center()
|
||||
|
||||
|
||||
## Variação 1: editorial, alinhado à esquerda, barra vertical de destaque.
|
||||
func _draw_title_editorial() -> void:
|
||||
var accent := _accent()
|
||||
_background(BG, BG_2)
|
||||
_glow(Vector2(_size.x * 0.15, _size.y * 0.35), _size.x * 0.8, Color(accent.r, accent.g, accent.b, 0.5))
|
||||
var appear := _ease_out(_progress(0.15, 0.7))
|
||||
var bar := _ease_out(_progress(0.0, 0.7))
|
||||
var x0 := _size.x * 0.08
|
||||
var top := _size.y * 0.3
|
||||
var y := top + (1.0 - appear) * _px(0.02)
|
||||
var kicker := str(_p.get("kicker", ""))
|
||||
if not kicker.is_empty():
|
||||
y += _text_block(kicker.to_upper(), y, _px(0.022), _with_alpha(accent, appear), _font, 0.78, 1, HORIZONTAL_ALIGNMENT_LEFT) + _px(0.02)
|
||||
var h := _text_block(str(_p.get("title", "")), y, _px(0.066), _with_alpha(TEXT, appear), _font, 0.78, 5, HORIZONTAL_ALIGNMENT_LEFT)
|
||||
draw_rect(Rect2(Vector2(x0, top), Vector2(_px(0.007), (y - top + h) * bar)), accent)
|
||||
var sub_appear := _ease_out(_progress(0.55, 0.7))
|
||||
_text_block(str(_p.get("subtitle", "")), y + h + _px(0.03), _px(0.03), _with_alpha(MUTED, sub_appear), _font_regular, 0.78, 3, HORIZONTAL_ALIGNMENT_LEFT)
|
||||
|
||||
|
||||
## Variação 2: texto grande na parte de baixo-centro, sublinhado que corre, brilho embaixo.
|
||||
func _draw_title_lower() -> void:
|
||||
var accent := _accent()
|
||||
_background(BG_2, BG)
|
||||
_glow(Vector2(_size.x * 0.5, _size.y * 0.62), _size.x * 0.9 * (1.0 + 0.05 * sin(_t * 1.1)), Color(accent.r, accent.g, accent.b, 0.55))
|
||||
var appear := _ease_out(_progress(0.1, 0.8))
|
||||
var y := _size.y * 0.44 + (1.0 - appear) * _px(0.04)
|
||||
var kicker := str(_p.get("kicker", ""))
|
||||
if not kicker.is_empty():
|
||||
y += _text_block(kicker.to_upper(), y, _px(0.022), _with_alpha(accent, appear), _font, 0.8, 1) + _px(0.02)
|
||||
y += _text_block(str(_p.get("title", "")), y, _px(0.07), _with_alpha(TEXT, appear), _font, 0.88, 4) + _px(0.02)
|
||||
var line := _ease_out(_progress(0.5, 0.8))
|
||||
draw_rect(Rect2(Vector2(_size.x * 0.5 - _size.x * 0.25 * line, y), Vector2(_size.x * 0.5 * line, _px(0.005))), accent)
|
||||
var sub_appear := _ease_out(_progress(0.7, 0.7))
|
||||
_text_block(str(_p.get("subtitle", "")), y + _px(0.03), _px(0.03), _with_alpha(MUTED, sub_appear), _font_regular, 0.8, 3)
|
||||
|
||||
|
||||
## Variação 0: centralizado, barra que cresce do centro.
|
||||
func _draw_title_center() -> void:
|
||||
_background(BG, BG_2)
|
||||
var breathe := 1.0 + 0.04 * sin(_t * 1.3)
|
||||
_glow(Vector2(_size.x * 0.5, _size.y * 0.42), _size.x * 0.75 * breathe, Color(ACCENT.r, ACCENT.g, ACCENT.b, 0.55))
|
||||
var appear := _ease_out(_progress(0.15, 0.7))
|
||||
var slide := (1.0 - appear) * _size.y * 0.03
|
||||
var y := _size.y * 0.36 + slide
|
||||
var kicker := str(_p.get("kicker", ""))
|
||||
if not kicker.is_empty():
|
||||
y += _text_block(kicker.to_upper(), y, _px(0.022), _with_alpha(GLOW, appear), _font, 0.8, 1) + _px(0.02)
|
||||
# Barra de destaque que cresce do centro.
|
||||
var bar := _ease_out(_progress(0.0, 0.6))
|
||||
var bar_w := _size.x * 0.36 * bar
|
||||
draw_rect(Rect2(Vector2((_size.x - bar_w) / 2.0, y), Vector2(bar_w, _px(0.006))), ACCENT)
|
||||
y += _px(0.035)
|
||||
y += _text_block(str(_p.get("title", "")), y, _px(0.058), _with_alpha(TEXT, appear), _font, 0.84, 4) + _px(0.025)
|
||||
var sub_appear := _ease_out(_progress(0.55, 0.7))
|
||||
_text_block(str(_p.get("subtitle", "")), y + (1.0 - sub_appear) * _px(0.015), _px(0.03), _with_alpha(MUTED, sub_appear), _font_regular, 0.8, 3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- contador / infográfico
|
||||
|
||||
func _draw_counter() -> void:
|
||||
var accent := _accent()
|
||||
_background(BG, BG_2)
|
||||
_glow(Vector2(_size.x * 0.5, _size.y * 0.33), _size.x * 0.6, Color(accent.r, accent.g, accent.b, 0.5))
|
||||
var value := float(_p.get("value", 0))
|
||||
var decimals := int(_p.get("decimals", 0))
|
||||
var count_len := clampf(_dur * 0.45, 0.8, 2.4)
|
||||
var shown := value * _ease_out(_progress(0.2, count_len))
|
||||
var number := str(_p.get("prefix", "")) + _format_number(shown, decimals) + str(_p.get("suffix", ""))
|
||||
var pop := _ease_out(_progress(0.0, 0.5))
|
||||
var grid_mode := typeof(_p.get("grid")) == TYPE_DICTIONARY
|
||||
# Anel que fecha enquanto o número conta (sem grade: o anel é o elemento visual do infográfico).
|
||||
var ring_center := Vector2(_size.x * 0.5, _size.y * (0.27 if grid_mode else 0.36))
|
||||
var ring_r := _size.x * (0.27 if grid_mode else 0.33)
|
||||
var fill := _ease_out(_progress(0.2, count_len))
|
||||
draw_arc(ring_center, ring_r, 0.0, TAU, 128, Color(1, 1, 1, 0.07 * pop), _px(0.012), true)
|
||||
draw_arc(ring_center, ring_r, -PI / 2.0, -PI / 2.0 + TAU * fill, 128, _with_alpha(accent, pop), _px(0.012), true)
|
||||
if fill > 0.0:
|
||||
var tip := ring_center + Vector2(cos(-PI / 2.0 + TAU * fill), sin(-PI / 2.0 + TAU * fill)) * ring_r
|
||||
draw_circle(tip, _px(0.011), _with_alpha(accent.lightened(0.35), pop))
|
||||
var size_px := int(_px(0.12 if number.length() <= 4 else 0.095) * (0.85 + 0.15 * pop))
|
||||
var number_h := _font.get_multiline_string_size(number, HORIZONTAL_ALIGNMENT_CENTER, _size.x * 0.6, size_px, 1).y
|
||||
var kicker := str(_p.get("kicker", ""))
|
||||
if not kicker.is_empty():
|
||||
_text_block(kicker, ring_center.y - number_h * 0.5 - _px(0.04), _px(0.028), _with_alpha(MUTED, pop), _font_regular, 0.5, 1)
|
||||
_text_block(number, ring_center.y - number_h * 0.5, size_px, _with_alpha(accent.lightened(0.3), pop), _font, 0.6, 1)
|
||||
var label_appear := _ease_out(_progress(0.35, 0.6))
|
||||
var y := ring_center.y + ring_r + _px(0.035)
|
||||
y += _text_block(str(_p.get("label", "")), y, _px(0.036), _with_alpha(TEXT, label_appear), _font, 0.84, 2) + _px(0.03)
|
||||
|
||||
var grid = _p.get("grid")
|
||||
if typeof(grid) == TYPE_DICTIONARY:
|
||||
_draw_grid(grid, y)
|
||||
else:
|
||||
var note_appear := _ease_out(_progress(0.9, 0.7))
|
||||
_text_block(str(_p.get("note", "")), y + _px(0.02), _px(0.028), _with_alpha(MUTED, note_appear), _font_regular, 0.8, 4)
|
||||
|
||||
|
||||
func _draw_grid(grid: Dictionary, top: float) -> void:
|
||||
var cols := clampi(int(grid.get("cols", 10)), 1, 30)
|
||||
var rows := clampi(int(grid.get("rows", 10)), 1, 30)
|
||||
var highlight := clampi(int(grid.get("highlight", 1)), 0, cols * rows)
|
||||
var area_w := _size.x * 0.72
|
||||
var area_h := _size.y * 0.86 - top
|
||||
var cell := minf(area_w / cols, area_h / rows)
|
||||
var origin := Vector2((_size.x - cell * cols) / 2.0, top)
|
||||
var total := cols * rows
|
||||
var fill_len := clampf(_dur * 0.3, 0.6, 1.8)
|
||||
for i in total:
|
||||
var col := i % cols
|
||||
var row := i / cols
|
||||
# Células aparecem em onda (diagonal); as destacadas acendem depois.
|
||||
var appear := _ease_out(_progress(0.6 + float(col + row) / float(cols + rows) * fill_len, 0.3))
|
||||
if appear <= 0.0:
|
||||
continue
|
||||
var r := Rect2(origin + Vector2(col * cell, row * cell), Vector2(cell, cell)).grow(-cell * 0.12)
|
||||
var is_hl := i < highlight
|
||||
var lit := _ease_out(_progress(0.6 + fill_len + 0.2 + float(i) * 0.04, 0.35)) if is_hl else 0.0
|
||||
var base := Color(1, 1, 1, 0.10 * appear)
|
||||
draw_rect(r, base.lerp(Color(ACCENT.r, ACCENT.g, ACCENT.b, appear), lit))
|
||||
var note_appear := _ease_out(_progress(0.6 + fill_len + 0.6, 0.6))
|
||||
_text_block(str(_p.get("note", "")), origin.y + cell * rows + _px(0.02), _px(0.026), _with_alpha(MUTED, note_appear), _font_regular, 0.84, 3)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- mapa
|
||||
|
||||
func _prepare_map() -> Dictionary:
|
||||
var preset: Dictionary = PRESETS.get(str(_p.get("preset", "litoral-sp")), PRESETS["litoral-sp"])
|
||||
var places: Dictionary = preset.places
|
||||
# 1) Lugares citados (lat/lon dados ou do dicionário do preset).
|
||||
var resolved := []
|
||||
for m in _p.get("markers", []):
|
||||
if typeof(m) != TYPE_DICTIONARY:
|
||||
continue
|
||||
var label := str(m.get("label", ""))
|
||||
var lat = m.get("lat")
|
||||
var lon = m.get("lon")
|
||||
if (lat == null or lon == null) and places.has(label):
|
||||
lat = places[label][0]
|
||||
lon = places[label][1]
|
||||
if lat == null or lon == null:
|
||||
continue
|
||||
var lower := label.to_lower()
|
||||
var kind := str(m.get("kind", "island" if lower.contains("ilha") or lower.contains("queimada") else "city"))
|
||||
resolved.append({"label": label, "lat": float(lat), "lon": float(lon), "kind": kind})
|
||||
# 2) Enquadramento: em volta dos lugares citados (com folga), ou o preset inteiro.
|
||||
var b: Dictionary = preset.bounds.duplicate()
|
||||
if not resolved.is_empty():
|
||||
var n := -90.0
|
||||
var s_ := 90.0
|
||||
var w := 180.0
|
||||
var e := -180.0
|
||||
for m in resolved:
|
||||
n = maxf(n, m.lat)
|
||||
s_ = minf(s_, m.lat)
|
||||
w = minf(w, m.lon)
|
||||
e = maxf(e, m.lon)
|
||||
var pad_lat := maxf((n - s_) * 0.7, 0.22)
|
||||
var pad_lon := maxf((e - w) * 0.7, 0.22)
|
||||
b = {"north": n + pad_lat, "south": s_ - pad_lat, "west": w - pad_lon, "east": e + pad_lon}
|
||||
var area := Rect2(Vector2(_size.x * 0.06, _size.y * 0.2), Vector2(_size.x * 0.88, _size.y * 0.62))
|
||||
var mid_lat := deg_to_rad((float(b.north) + float(b.south)) / 2.0)
|
||||
var span_x := (float(b.east) - float(b.west)) * cos(mid_lat)
|
||||
var span_y := float(b.north) - float(b.south)
|
||||
var scale := minf(area.size.x / span_x, area.size.y / span_y)
|
||||
var offset := area.position + (area.size - Vector2(span_x, span_y) * scale) / 2.0
|
||||
var project := func(lat: float, lon: float) -> Vector2:
|
||||
return offset + Vector2((lon - float(b.west)) * cos(mid_lat), float(b.north) - lat) * scale
|
||||
var coast := PackedVector2Array()
|
||||
for pt in preset.coast:
|
||||
coast.append(project.call(float(pt[0]), float(pt[1])))
|
||||
# Terra = costa + cantos do norte (a costa paulista corre de sudoeste para nordeste).
|
||||
var pb: Dictionary = preset.bounds
|
||||
var land := coast.duplicate()
|
||||
# Cantos bem além da tela: no começo do voo o mapa aparece aberto (zoom 0,45).
|
||||
land.append(project.call(float(pb.south) - 1.0, float(pb.east) + 8.0))
|
||||
land.append(project.call(float(pb.north) + 8.0, float(pb.east) + 8.0))
|
||||
land.append(project.call(float(pb.north) + 8.0, float(pb.west) - 8.0))
|
||||
land.append(project.call(float(pb.south) - 8.0, float(pb.west) - 8.0))
|
||||
var markers := []
|
||||
for m in resolved:
|
||||
markers.append({"label": m.label, "pos": project.call(m.lat, m.lon), "lat": m.lat, "lon": m.lon, "kind": m.kind})
|
||||
var route := {}
|
||||
var r = _p.get("route")
|
||||
if typeof(r) == TYPE_DICTIONARY and markers.size() >= 2:
|
||||
var a := _find_marker(markers, r.get("from", 0))
|
||||
var z := _find_marker(markers, r.get("to", 1))
|
||||
if a >= 0 and z >= 0 and a != z:
|
||||
var label := str(r.get("label", ""))
|
||||
if label.is_empty():
|
||||
label = "%d km" % int(round(_haversine_km(markers[a].lat, markers[a].lon, markers[z].lat, markers[z].lon)))
|
||||
route = {"a": markers[a].pos, "b": markers[z].pos, "label": label}
|
||||
var focus: Vector2 = area.get_center()
|
||||
if not route.is_empty():
|
||||
focus = (route.a + route.b) / 2.0
|
||||
return {"coast": coast, "land": land, "markers": markers, "route": route, "focus": focus}
|
||||
|
||||
|
||||
static func _find_marker(markers: Array, key) -> int:
|
||||
if typeof(key) in [TYPE_INT, TYPE_FLOAT]:
|
||||
var i := int(key)
|
||||
return i if i >= 0 and i < markers.size() else -1
|
||||
for i in markers.size():
|
||||
if markers[i].label == str(key):
|
||||
return i
|
||||
return -1
|
||||
|
||||
|
||||
static func _haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
||||
var d_lat := deg_to_rad(lat2 - lat1)
|
||||
var d_lon := deg_to_rad(lon2 - lon1)
|
||||
var a := sin(d_lat / 2.0) ** 2 + cos(deg_to_rad(lat1)) * cos(deg_to_rad(lat2)) * sin(d_lon / 2.0) ** 2
|
||||
return 6371.0 * 2.0 * atan2(sqrt(a), sqrt(1.0 - a))
|
||||
|
||||
|
||||
func _draw_map() -> void:
|
||||
_background(SEA_2, SEA)
|
||||
var m := _map_cache
|
||||
# Voo: começa aberto (litoral inteiro) e desce até a rota; depois aproxima devagar.
|
||||
var focus: Vector2 = m.focus
|
||||
var center := _size / 2.0
|
||||
var intro := _ease_in_out(_progress(0.0, minf(1.6, _dur * 0.35)))
|
||||
var start_zoom := 0.45 if _variant() % 2 == 0 else 0.62
|
||||
var zoom := lerpf(start_zoom, 1.0, intro) + 0.1 * _ease_out(_progress(1.6, maxf(_dur - 1.6, 0.1)))
|
||||
var pivot := center.lerp(focus, intro)
|
||||
var shift := (center - focus) * 0.3 * intro
|
||||
draw_set_transform(pivot - pivot * zoom + shift, 0.0, Vector2(zoom, zoom))
|
||||
# Ondas do mar: linhas horizontais suaves que deslizam.
|
||||
for i in 18:
|
||||
var y := _size.y * (0.05 + float(i) * 0.055) + fmod(_t * 6.0, _size.y * 0.055)
|
||||
draw_line(Vector2(0, y), Vector2(_size.x, y), Color(1, 1, 1, 0.025), 2.0)
|
||||
var land_alpha := _ease_out(_progress(0.0, 0.6))
|
||||
draw_colored_polygon(m.land, _with_alpha(LAND, land_alpha))
|
||||
draw_polyline(m.coast, _with_alpha(LAND_EDGE, land_alpha), maxf(2.0, _size.y * 0.002), true)
|
||||
|
||||
var route: Dictionary = m.route
|
||||
if not route.is_empty():
|
||||
# A linha só começa quando o voo termina (1,5 s).
|
||||
var route_len := clampf(_dur * 0.3, 0.8, 2.0)
|
||||
var p := _ease_out(_progress(1.5, route_len))
|
||||
var a: Vector2 = route.a
|
||||
var b: Vector2 = route.b
|
||||
var end := a.lerp(b, p)
|
||||
# Linha tracejada que se desenha de A até B.
|
||||
var dash := _size.y * 0.012
|
||||
var length := a.distance_to(end)
|
||||
var dir := (b - a).normalized()
|
||||
var s := 0.0
|
||||
while s < length:
|
||||
draw_line(a + dir * s, a + dir * minf(s + dash, length), GLOW, maxf(3.0, _size.y * 0.003), true)
|
||||
s += dash * 1.8
|
||||
if p >= 1.0:
|
||||
var lp := _ease_out(_progress(1.5 + route_len, 0.5))
|
||||
# Pulso no destino: anéis que crescem e somem, a cada 1,2 s.
|
||||
for k in 2:
|
||||
var phase := fmod(maxf(_t - 1.5 - route_len, 0.0) + float(k) * 0.6, 1.2) / 1.2
|
||||
draw_arc(b, _size.y * (0.012 + 0.04 * phase), 0.0, TAU, 48, Color(GLOW.r, GLOW.g, GLOW.b, 0.8 * (1.0 - phase) * lp), maxf(2.0, _size.y * 0.002), true)
|
||||
var label := str(route.label)
|
||||
var fs := _px(0.03)
|
||||
var tw := _font.get_string_size(label, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
|
||||
# Ao lado da linha (perpendicular, para a direita), longe dos pontos.
|
||||
var normal := Vector2(-dir.y, dir.x)
|
||||
if normal.x < 0.0:
|
||||
normal = -normal
|
||||
var mid := (a + b) / 2.0 + normal * fs * 2.2
|
||||
var box := Rect2(mid - Vector2(0, fs * 0.7), Vector2(tw + fs, fs * 1.4))
|
||||
draw_rect(box, _with_alpha(Color(0, 0, 0, 0.7), lp))
|
||||
draw_string(_font, box.position + Vector2(fs * 0.5, fs * 1.0), label, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, _with_alpha(GLOW, lp))
|
||||
|
||||
var markers: Array = m.markers
|
||||
for i in markers.size():
|
||||
var mk: Dictionary = markers[i]
|
||||
var pop := _ease_out(_progress(0.4 + float(i) * 0.25, 0.4))
|
||||
if pop <= 0.0:
|
||||
continue
|
||||
var pos: Vector2 = mk.pos
|
||||
var fs := _px(0.026)
|
||||
if mk.kind == "island":
|
||||
var r := _size.y * 0.012 * pop
|
||||
draw_colored_polygon(PackedVector2Array([pos + Vector2(-r * 1.4, 0), pos + Vector2(-r * 0.6, -r), pos + Vector2(r * 0.8, -r * 0.8),
|
||||
pos + Vector2(r * 1.5, r * 0.1), pos + Vector2(r * 0.5, r * 0.9), pos + Vector2(-r * 0.9, r * 0.7)]), Color(LAND_EDGE, pop))
|
||||
draw_circle(pos, r * 2.6, Color(GLOW.r, GLOW.g, GLOW.b, 0.18 * pop))
|
||||
else:
|
||||
draw_circle(pos, _size.y * 0.007 * pop, Color(TEXT, pop))
|
||||
draw_circle(pos, _size.y * 0.004 * pop, Color(ACCENT, pop))
|
||||
var tw := _font.get_string_size(mk.label, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x
|
||||
var right_side := pos.x + tw + fs < _size.x * 0.95
|
||||
var text_pos := pos + (Vector2(fs * 0.8, fs * 0.35) if right_side else Vector2(-tw - fs * 0.8, fs * 0.35))
|
||||
if mk.kind == "island":
|
||||
# Ilha: nome centralizado embaixo (no mar), sem cruzar a costa.
|
||||
text_pos = pos + Vector2(-tw / 2.0, _size.y * 0.035 + fs * 0.6)
|
||||
text_pos.x = clampf(text_pos.x, _size.x * 0.03, _size.x * 0.97 - tw)
|
||||
draw_string(_font, text_pos + Vector2(2, 2), mk.label, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Color(0, 0, 0, 0.6 * pop))
|
||||
draw_string(_font, text_pos, mk.label, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, Color(TEXT, pop))
|
||||
|
||||
draw_set_transform(Vector2.ZERO, 0.0, Vector2.ONE)
|
||||
# Título no alto e aviso de mapa ilustrativo (fora do zoom).
|
||||
var title := str(_p.get("title", ""))
|
||||
if not title.is_empty():
|
||||
_text_block(title, _size.y * 0.07, _px(0.04), Color(TEXT, _ease_out(_progress(0.1, 0.6))), _font, 0.86, 2)
|
||||
draw_string(_font_regular, Vector2(_size.x * 0.05, _size.y * 0.965), "Mapa ilustrativo", HORIZONTAL_ALIGNMENT_LEFT, -1, _px(0.016), Color(1, 1, 1, 0.45))
|
||||
@@ -0,0 +1,84 @@
|
||||
extends RefCounted
|
||||
## Contrato das cenas do documentário:
|
||||
## { "id": "...", "kind": "doc2d" | "doc3d",
|
||||
## "video": { "width": 1080, "height": 1920, "fps": 30, "durationSeconds": 6.2 },
|
||||
## "template": <modelo do tipo>, "params": { ... } }
|
||||
## doc2d (motion graphics, doc2d_canvas.gd): "title" | "counter" | "map"
|
||||
## doc3d (cena 3D da biblioteca): o nome de uma pasta em godot/library/ ("island", ...)
|
||||
## A duração vem do áudio do trecho: a cena dura exatamente o que a narração dura.
|
||||
## params.variant (inteiro, opcional): variação de layout/câmera para "gerar de novo".
|
||||
|
||||
const TEMPLATES_2D := ["title", "counter", "map"]
|
||||
const LIBRARY_DIR := "res://library"
|
||||
|
||||
|
||||
## Script da cena 3D da biblioteca: res://library/<id>/template.gd.
|
||||
static func library_script(id: String) -> String:
|
||||
return "%s/%s/template.gd" % [LIBRARY_DIR, id]
|
||||
|
||||
|
||||
## Cenas 3D disponíveis (pastas da biblioteca com template.gd).
|
||||
static func library_templates() -> Array:
|
||||
var out := []
|
||||
var dir := DirAccess.open(LIBRARY_DIR)
|
||||
if dir == null:
|
||||
return out
|
||||
for name in dir.get_directories():
|
||||
if ResourceLoader.exists(library_script(name)):
|
||||
out.append(name)
|
||||
return out
|
||||
|
||||
|
||||
static func load_file(path: String) -> Dictionary:
|
||||
if not FileAccess.file_exists(path):
|
||||
return {"ok": false, "errors": ["arquivo não encontrado: %s" % path]}
|
||||
var parsed = JSON.parse_string(FileAccess.get_file_as_string(path))
|
||||
if typeof(parsed) != TYPE_DICTIONARY:
|
||||
return {"ok": false, "errors": ["JSON inválido ou não é objeto"]}
|
||||
return validate(parsed)
|
||||
|
||||
|
||||
static func validate(raw: Dictionary) -> Dictionary:
|
||||
var errors := []
|
||||
if typeof(raw.get("id")) != TYPE_STRING or str(raw.id).is_empty():
|
||||
errors.append("id: texto obrigatório")
|
||||
var kind := str(raw.get("kind", ""))
|
||||
if not (kind in ["doc2d", "doc3d"]):
|
||||
errors.append("kind: \"doc2d\" ou \"doc3d\"")
|
||||
var video = raw.get("video")
|
||||
if typeof(video) != TYPE_DICTIONARY:
|
||||
errors.append("video: objeto obrigatório")
|
||||
return {"ok": false, "errors": errors}
|
||||
for key in ["width", "height", "fps", "durationSeconds"]:
|
||||
if not (typeof(video.get(key)) in [TYPE_INT, TYPE_FLOAT]) or float(video.get(key)) <= 0.0:
|
||||
errors.append("video.%s: número positivo obrigatório" % key)
|
||||
if errors.is_empty():
|
||||
if float(video.durationSeconds) > 120.0:
|
||||
errors.append("video.durationSeconds: máximo 120 s por cena")
|
||||
if int(video.fps) < 1 or int(video.fps) > 60:
|
||||
errors.append("video.fps: entre 1 e 60")
|
||||
var template = raw.get("template")
|
||||
if kind == "doc2d" and not (template in TEMPLATES_2D):
|
||||
errors.append("template: um de %s para doc2d" % [TEMPLATES_2D])
|
||||
if kind == "doc3d" and not (typeof(template) == TYPE_STRING and ResourceLoader.exists(library_script(template))):
|
||||
errors.append("template: cena 3D \"%s\" não existe na biblioteca (godot/library/). Disponíveis: %s" % [template, library_templates()])
|
||||
var params = raw.get("params", {})
|
||||
if typeof(params) != TYPE_DICTIONARY:
|
||||
errors.append("params: objeto")
|
||||
elif template == "counter" and not (typeof(params.get("value")) in [TYPE_INT, TYPE_FLOAT]):
|
||||
errors.append("params.value: número obrigatório no modelo counter")
|
||||
elif template == "title" and str(params.get("title", "")).strip_edges().is_empty():
|
||||
errors.append("params.title: texto obrigatório no modelo title")
|
||||
elif template == "map" and typeof(params.get("markers", [])) != TYPE_ARRAY:
|
||||
errors.append("params.markers: lista")
|
||||
if not errors.is_empty():
|
||||
return {"ok": false, "errors": errors}
|
||||
var cfg := raw.duplicate(true)
|
||||
cfg.video.fps = int(video.fps)
|
||||
cfg.video.width = int(video.width)
|
||||
cfg.video.height = int(video.height)
|
||||
cfg.video.duration = float(video.durationSeconds)
|
||||
cfg.video.total_frames = int(round(float(video.durationSeconds) * float(video.fps)))
|
||||
if not cfg.has("params"):
|
||||
cfg.params = {}
|
||||
return {"ok": true, "config": cfg}
|
||||
@@ -0,0 +1,196 @@
|
||||
extends Node
|
||||
## Cenas do documentário: 2D (motion graphics: mapa, contador, título; doc2d_canvas.gd) e
|
||||
## 3D (cenas da BIBLIOTECA: res://library/<template>/template.gd), escolhidas pelo "kind" do JSON.
|
||||
## Cena 3D nova = pasta nova em godot/library/ (veja doc/godot/cenas.md); nada aqui muda.
|
||||
## Mesmo protocolo do main.gd (rua 3D), para o lançador tratar as duas igual:
|
||||
## --config <json> | --validate-only | --manifest <json> | --warmup-frames <n>
|
||||
## Render (Movie Maker): t = quadro / fps, quadros de aquecimento em t=0 e um
|
||||
## manifesto com quadros produzidos e um resumo determinístico do estado.
|
||||
|
||||
const DocConfig := preload("res://scripts/doc/doc_config.gd")
|
||||
const Doc2DCanvas := preload("res://scripts/doc/doc2d_canvas.gd")
|
||||
|
||||
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
|
||||
## Doc2DCanvas (Node2D) ou a cena 3D da biblioteca (Node3D): setup(cfg, tamanho), apply(t) e state_signature().
|
||||
var _canvas: Node
|
||||
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 _manifest_path := ""
|
||||
var _config_path := ""
|
||||
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())
|
||||
if not args.has("config"):
|
||||
printerr("ARGS_INVALID --config é obrigatório na cena do documentário")
|
||||
_halt(EXIT_INVALID_CONFIG)
|
||||
return
|
||||
_config_path = _resolve_path(str(args.config))
|
||||
_render_mode = Engine.get_write_movie_path() != ""
|
||||
_manifest_path = _resolve_path(str(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 := DocConfig.load_file(_config_path)
|
||||
if not result.ok:
|
||||
printerr("CONFIG_INVALID %s" % _config_path)
|
||||
for e in result.errors:
|
||||
printerr(" - " + str(e))
|
||||
_halt(EXIT_INVALID_CONFIG)
|
||||
return
|
||||
_cfg = result.config
|
||||
# Cena 3D da biblioteca: o script precisa compilar. Erro aqui reprova JÁ (na validação),
|
||||
# em vez de virar um laço infinito de quadros com "apply em Nil".
|
||||
var scene_script: GDScript = null
|
||||
if _cfg.kind == "doc3d":
|
||||
scene_script = load(DocConfig.library_script(_cfg.template)) as GDScript
|
||||
if scene_script == null or not scene_script.can_instantiate():
|
||||
printerr("SCENE_SCRIPT_INVALID %s: o template.gd não compila (veja os erros de GDScript acima)" % DocConfig.library_script(_cfg.template))
|
||||
_halt(EXIT_INVALID_CONFIG)
|
||||
return
|
||||
if args.has("validate-only"):
|
||||
print("CONFIG_OK %s (%s, %d quadros, modelo %s)" % [_cfg.id, _config_path, _cfg.video.total_frames, _cfg.template])
|
||||
_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:
|
||||
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" % 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 (use o lançador, que gera override.cfg)" % [viewport_size, expected])
|
||||
_halt(EXIT_ENVIRONMENT)
|
||||
return
|
||||
|
||||
if _cfg.kind == "doc3d":
|
||||
_canvas = scene_script.new()
|
||||
else:
|
||||
_canvas = Doc2DCanvas.new()
|
||||
if _canvas == null or not _canvas.has_method("apply") or not _canvas.has_method("setup"):
|
||||
printerr("SCENE_SCRIPT_INVALID a cena não tem setup(cfg, tamanho) e apply(t)")
|
||||
_halt(EXIT_INVALID_CONFIG)
|
||||
return
|
||||
_canvas.name = "Canvas"
|
||||
add_child(_canvas)
|
||||
_canvas.setup(_cfg, viewport_size)
|
||||
_canvas.apply(0.0)
|
||||
print("SCENE_READY id=%s mode=%s frames=%d fps=%d viewport=%dx%d template=%s" % [
|
||||
_cfg.id, "render" if _render_mode else "preview", _total_frames, _fps,
|
||||
int(viewport_size.x), int(viewport_size.y), _cfg.template])
|
||||
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if _cfg.is_empty() or _halted:
|
||||
return
|
||||
if not _render_mode:
|
||||
_preview_time = fmod(_preview_time + delta, maxf(_cfg.video.duration, 0.001))
|
||||
_canvas.apply(_preview_time)
|
||||
return
|
||||
if _warmup_done < _warmup_frames:
|
||||
_canvas.apply(0.0)
|
||||
_warmup_done += 1
|
||||
return
|
||||
var t := float(_frame) / float(_fps)
|
||||
_canvas.apply(t)
|
||||
_state_lines.append("%.4f|%s" % [t, _canvas.state_signature()])
|
||||
_frame += 1
|
||||
if _frame >= _total_frames:
|
||||
_finish_render()
|
||||
|
||||
|
||||
func _finish_render() -> void:
|
||||
var size := get_viewport().get_visible_rect().size
|
||||
var manifest := {
|
||||
"configId": _cfg.id,
|
||||
"configPath": _config_path,
|
||||
"kind": _cfg.kind,
|
||||
"template": _cfg.template,
|
||||
"fps": _fps,
|
||||
"durationSeconds": _cfg.video.duration,
|
||||
"framesRendered": _frame,
|
||||
"expectedFrames": _total_frames,
|
||||
"warmupFrames": _warmup_frames,
|
||||
"firstSceneFrameIndex": _warmup_frames,
|
||||
"pngFramesWritten": _warmup_frames + _frame,
|
||||
"viewport": [int(size.x), int(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,
|
||||
"scene": {"template": _cfg.template},
|
||||
"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 _resolve_path(path: String) -> String:
|
||||
var p := path.replace("\\", "/")
|
||||
if p.is_absolute_path():
|
||||
return p.simplify_path()
|
||||
var root := ProjectSettings.globalize_path("res://").trim_suffix("/").get_base_dir()
|
||||
return root.path_join(p).simplify_path()
|
||||
@@ -0,0 +1,38 @@
|
||||
extends RefCounted
|
||||
## Enquadramento por tempo. Preset único nesta prova: "third_person_follow".
|
||||
##
|
||||
## A câmera fica em `posição da moto + offset` (espaço do mundo; a moto anda em
|
||||
## -Z, então +Z é "atrás") e olha para `posição da moto + lookAtOffset`. Entre
|
||||
## transitionStartSeconds e transitionEndSeconds os dois offsets migram, com
|
||||
## curva suave, para endOffset/endLookAtOffset: é a mudança de enquadramento que
|
||||
## abre espaço para o texto final. O FOV é vertical (padrão da Camera3D).
|
||||
##
|
||||
## A câmera segue a posição-base da moto, sem a vibração da carroceria, para o
|
||||
## quadro ficar estável.
|
||||
|
||||
const MIN_HEIGHT := 0.5
|
||||
|
||||
|
||||
static func evaluate(cfg: Dictionary, t: float, rider_position: Vector3) -> Dictionary:
|
||||
var c: Dictionary = cfg.camera
|
||||
var k := _smootherstep(inverse_lerp(c.transition_start, c.transition_end, t))
|
||||
var offset: Vector3 = c.offset.lerp(c.end_offset, k)
|
||||
var look_offset: Vector3 = c.look_at_offset.lerp(c.end_look_at_offset, k)
|
||||
var position := rider_position + offset
|
||||
position.y = maxf(position.y, MIN_HEIGHT)
|
||||
return {
|
||||
"position": position,
|
||||
"look_at": rider_position + look_offset,
|
||||
"fov": c.fov,
|
||||
"blend": k,
|
||||
}
|
||||
|
||||
|
||||
static func apply(camera: Camera3D, state: Dictionary) -> void:
|
||||
camera.fov = state.fov
|
||||
camera.look_at_from_position(state.position, state.look_at, Vector3.UP)
|
||||
|
||||
|
||||
static func _smootherstep(p: float) -> float:
|
||||
p = clampf(p, 0.0, 1.0)
|
||||
return p * p * p * (p * (p * 6.0 - 15.0) + 10.0)
|
||||
@@ -0,0 +1 @@
|
||||
uid://cabudpjh3vqjs
|
||||
@@ -0,0 +1,144 @@
|
||||
extends CanvasLayer
|
||||
## Textos finais: chamada + duas opções visuais (sem votação real).
|
||||
##
|
||||
## `evaluate` é pura (depende só de t e da configuração); `apply` só copia o
|
||||
## resultado para os nós. As medidas são proporcionais à altura do viewport,
|
||||
## então a composição é a mesma em 540x960 e 1080x1920.
|
||||
##
|
||||
## Composição vertical (fração da altura):
|
||||
## título até 0.665 (cresce para cima se quebrar linha) | opção A 0.675 |
|
||||
## opção B 0.757 | 0.825..1.0 livre para a interface da plataforma.
|
||||
## Margens laterais de 9% da largura.
|
||||
|
||||
const STAGGER_SECONDS := 0.22
|
||||
const SLIDE_FRACTION := 0.025
|
||||
|
||||
const TITLE_BOTTOM_Y := 0.665
|
||||
const TITLE_BOX_HEIGHT := 0.15
|
||||
const CHOICE_A_Y := 0.675
|
||||
const CHOICE_B_Y := 0.757
|
||||
const CHOICE_HEIGHT := 0.068
|
||||
const SIDE_MARGIN := 0.09
|
||||
|
||||
const ACCENT_A := Color("#F2B134")
|
||||
const ACCENT_B := Color("#3FC1C9")
|
||||
|
||||
var _shade: TextureRect
|
||||
var _title: Label
|
||||
var _choice_a: PanelContainer
|
||||
var _choice_b: PanelContainer
|
||||
var _debug: Label
|
||||
var _size := Vector2.ZERO
|
||||
|
||||
|
||||
static func evaluate(cfg: Dictionary, t: float) -> Dictionary:
|
||||
var o: Dictionary = cfg.overlay
|
||||
var fade: float = maxf(o.fade_seconds, 0.001)
|
||||
return {
|
||||
"visible": t >= o.start,
|
||||
"shade": _ease(t, o.start - 0.2, fade + 0.2),
|
||||
"title": _ease(t, o.start, fade),
|
||||
"choice_a": _ease(t, o.start + STAGGER_SECONDS, fade),
|
||||
"choice_b": _ease(t, o.start + STAGGER_SECONDS * 2.0, fade),
|
||||
}
|
||||
|
||||
|
||||
static func _ease(t: float, start: float, length: float) -> float:
|
||||
var p := clampf((t - start) / length, 0.0, 1.0)
|
||||
return 1.0 - pow(1.0 - p, 3.0)
|
||||
|
||||
|
||||
func setup(cfg: Dictionary, viewport_size: Vector2, show_debug: bool) -> void:
|
||||
layer = 10
|
||||
_size = viewport_size
|
||||
var h := viewport_size.y
|
||||
var w := viewport_size.x
|
||||
|
||||
# Escurecimento suave na metade de baixo para o texto ter contraste
|
||||
# sobre qualquer cenário.
|
||||
var gradient := Gradient.new()
|
||||
gradient.set_color(0, Color(0, 0, 0, 0))
|
||||
gradient.set_color(1, Color(0, 0, 0, 0.72))
|
||||
var tex := GradientTexture2D.new()
|
||||
tex.gradient = gradient
|
||||
tex.fill_from = Vector2(0, 0)
|
||||
tex.fill_to = Vector2(0, 1)
|
||||
tex.width = 4
|
||||
tex.height = 256
|
||||
_shade = TextureRect.new()
|
||||
_shade.texture = tex
|
||||
_shade.stretch_mode = TextureRect.STRETCH_SCALE
|
||||
_shade.position = Vector2(0, h * 0.45)
|
||||
_shade.size = Vector2(w, h * 0.55)
|
||||
add_child(_shade)
|
||||
|
||||
_title = Label.new()
|
||||
_title.text = cfg.overlay.title
|
||||
_title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
_title.vertical_alignment = VERTICAL_ALIGNMENT_BOTTOM
|
||||
_title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
_title.add_theme_font_size_override("font_size", int(h * 0.044))
|
||||
_title.add_theme_color_override("font_color", Color.WHITE)
|
||||
_title.add_theme_color_override("font_outline_color", Color(0, 0, 0, 0.9))
|
||||
_title.add_theme_constant_override("outline_size", maxi(2, int(h * 0.007)))
|
||||
_title.add_theme_color_override("font_shadow_color", Color(0, 0, 0, 0.55))
|
||||
_title.add_theme_constant_override("shadow_offset_y", maxi(1, int(h * 0.003)))
|
||||
_title.size = Vector2(w * (1.0 - SIDE_MARGIN * 2.0), h * TITLE_BOX_HEIGHT)
|
||||
add_child(_title)
|
||||
|
||||
_choice_a = _make_choice(cfg.overlay.choice_a, ACCENT_A, viewport_size)
|
||||
_choice_b = _make_choice(cfg.overlay.choice_b, ACCENT_B, viewport_size)
|
||||
|
||||
_debug = Label.new()
|
||||
_debug.visible = show_debug
|
||||
_debug.position = Vector2(w * 0.03, h * 0.02)
|
||||
_debug.add_theme_font_size_override("font_size", int(h * 0.022))
|
||||
_debug.add_theme_color_override("font_color", Color.YELLOW)
|
||||
_debug.add_theme_color_override("font_outline_color", Color.BLACK)
|
||||
_debug.add_theme_constant_override("outline_size", 4)
|
||||
add_child(_debug)
|
||||
|
||||
|
||||
func _make_choice(text: String, accent: Color, viewport_size: Vector2) -> PanelContainer:
|
||||
var h := viewport_size.y
|
||||
var w := viewport_size.x
|
||||
var style := StyleBoxFlat.new()
|
||||
style.bg_color = Color(0.06, 0.07, 0.09, 0.82)
|
||||
style.border_color = accent
|
||||
style.set_border_width_all(maxi(2, int(h * 0.0035)))
|
||||
style.set_corner_radius_all(int(h * 0.016))
|
||||
style.content_margin_left = w * 0.05
|
||||
style.content_margin_right = w * 0.05
|
||||
|
||||
var panel := PanelContainer.new()
|
||||
panel.add_theme_stylebox_override("panel", style)
|
||||
panel.size = Vector2(w * (1.0 - SIDE_MARGIN * 2.0), h * CHOICE_HEIGHT)
|
||||
|
||||
var label := Label.new()
|
||||
label.text = text
|
||||
label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
|
||||
label.clip_text = true
|
||||
label.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
label.add_theme_font_size_override("font_size", int(h * 0.032))
|
||||
label.add_theme_color_override("font_color", Color.WHITE)
|
||||
panel.add_child(label)
|
||||
add_child(panel)
|
||||
return panel
|
||||
|
||||
|
||||
func apply(state: Dictionary, debug_text: String = "") -> void:
|
||||
var w := _size.x
|
||||
var h := _size.y
|
||||
var x := w * SIDE_MARGIN
|
||||
_shade.modulate.a = state.shade if state.visible else 0.0
|
||||
_place(_title, x, TITLE_BOTTOM_Y - TITLE_BOX_HEIGHT, state.title, state.visible)
|
||||
_place(_choice_a, x, CHOICE_A_Y, state.choice_a, state.visible)
|
||||
_place(_choice_b, x, CHOICE_B_Y, state.choice_b, state.visible)
|
||||
if _debug.visible:
|
||||
_debug.text = debug_text
|
||||
|
||||
|
||||
func _place(node: Control, x: float, y_fraction: float, amount: float, overlay_visible: bool) -> void:
|
||||
node.visible = overlay_visible and amount > 0.0
|
||||
node.modulate.a = amount
|
||||
node.position = Vector2(x, _size.y * (y_fraction + SLIDE_FRACTION * (1.0 - amount)))
|
||||
@@ -0,0 +1 @@
|
||||
uid://dl3x1lmypnlj1
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "demo-street",
|
||||
"seed": 42,
|
||||
"video": {
|
||||
"width": 540,
|
||||
"height": 960,
|
||||
"fps": 30,
|
||||
"durationSeconds": 12
|
||||
},
|
||||
"world": {
|
||||
"streetLengthMeters": 100,
|
||||
"roadWidthMeters": 8,
|
||||
"nearHousesPerSide": 9,
|
||||
"backgroundMode": "cards",
|
||||
"lightingPreset": "warm_day"
|
||||
},
|
||||
"rider": {
|
||||
"assetId": "placeholder-rider",
|
||||
"bikeColor": "#D95437",
|
||||
"startPosition": [
|
||||
1.8,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"travelMeters": 32
|
||||
},
|
||||
"motion": {
|
||||
"startSeconds": 1,
|
||||
"brakeStartSeconds": 9,
|
||||
"stopSeconds": 10
|
||||
},
|
||||
"camera": {
|
||||
"preset": "third_person_follow",
|
||||
"offset": [
|
||||
1.2,
|
||||
2.7,
|
||||
5.4
|
||||
],
|
||||
"lookAtOffset": [
|
||||
-0.2,
|
||||
1.0,
|
||||
-2.5
|
||||
],
|
||||
"fovDegrees": 55,
|
||||
"endOffset": [
|
||||
1.9,
|
||||
1.15,
|
||||
4.6
|
||||
],
|
||||
"endLookAtOffset": [
|
||||
-0.3,
|
||||
0.13,
|
||||
-1.0
|
||||
]
|
||||
},
|
||||
"overlay": {
|
||||
"startSeconds": 10,
|
||||
"title": "Uma entrega inesperada.",
|
||||
"choiceA": "A — Aceitar",
|
||||
"choiceB": "B — Continuar a rota"
|
||||
},
|
||||
"audio": {
|
||||
"enabled": true,
|
||||
"file": null,
|
||||
"offsetSeconds": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "demo-street",
|
||||
"seed": 42,
|
||||
"video": {
|
||||
"width": 540,
|
||||
"height": 960,
|
||||
"fps": 30,
|
||||
"durationSeconds": 12
|
||||
},
|
||||
"world": {
|
||||
"streetLengthMeters": 100,
|
||||
"roadWidthMeters": 8,
|
||||
"nearHousesPerSide": 9,
|
||||
"backgroundMode": "cards",
|
||||
"lightingPreset": "warm_day"
|
||||
},
|
||||
"rider": {
|
||||
"assetId": "placeholder-rider",
|
||||
"bikeColor": "#D95437",
|
||||
"startPosition": [
|
||||
1.8,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"travelMeters": 32
|
||||
},
|
||||
"motion": {
|
||||
"startSeconds": 5,
|
||||
"brakeStartSeconds": 4,
|
||||
"stopSeconds": 13
|
||||
},
|
||||
"camera": {
|
||||
"preset": "third_person_follow",
|
||||
"offset": [
|
||||
1.2,
|
||||
2.7,
|
||||
5.4
|
||||
],
|
||||
"lookAtOffset": [
|
||||
-0.2,
|
||||
1.0,
|
||||
-2.5
|
||||
],
|
||||
"fovDegrees": 55,
|
||||
"endOffset": [
|
||||
1.9,
|
||||
1.15,
|
||||
4.6
|
||||
],
|
||||
"endLookAtOffset": [
|
||||
-0.3,
|
||||
0.13,
|
||||
-1.0
|
||||
]
|
||||
},
|
||||
"overlay": {
|
||||
"startSeconds": 10,
|
||||
"title": "Uma entrega inesperada.",
|
||||
"choiceA": "A — Aceitar",
|
||||
"choiceB": "B — Continuar a rota"
|
||||
},
|
||||
"audio": {
|
||||
"enabled": false,
|
||||
"file": null,
|
||||
"offsetSeconds": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{ "schemaVersion": 1, "id": "quebrado",
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "demo-street",
|
||||
"seed": 42,
|
||||
"video": {
|
||||
"width": 540,
|
||||
"height": 960,
|
||||
"fps": 30,
|
||||
"durationSeconds": 12
|
||||
},
|
||||
"world": {
|
||||
"streetLengthMeters": 100,
|
||||
"roadWidthMeters": 8,
|
||||
"nearHousesPerSide": 9,
|
||||
"backgroundMode": "cards",
|
||||
"lightingPreset": "warm_day",
|
||||
"script": "OS.execute(\"cmd\")"
|
||||
},
|
||||
"rider": {
|
||||
"assetId": "placeholder-rider",
|
||||
"bikeColor": "#D95437",
|
||||
"startPosition": [
|
||||
1.8,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"travelMeters": 32
|
||||
},
|
||||
"motion": {
|
||||
"startSeconds": 1,
|
||||
"brakeStartSeconds": 9,
|
||||
"stopSeconds": 10
|
||||
},
|
||||
"camera": {
|
||||
"preset": "third_person_follow",
|
||||
"offset": [
|
||||
1.2,
|
||||
2.7,
|
||||
5.4
|
||||
],
|
||||
"lookAtOffset": [
|
||||
-0.2,
|
||||
1.0,
|
||||
-2.5
|
||||
],
|
||||
"fovDegrees": 55,
|
||||
"endOffset": [
|
||||
1.9,
|
||||
1.15,
|
||||
4.6
|
||||
],
|
||||
"endLookAtOffset": [
|
||||
-0.3,
|
||||
0.13,
|
||||
-1.0
|
||||
]
|
||||
},
|
||||
"overlay": {
|
||||
"startSeconds": 10,
|
||||
"title": "$(rm -rf /)",
|
||||
"choiceA": "A — Aceitar",
|
||||
"choiceB": "B — Continuar a rota"
|
||||
},
|
||||
"audio": {
|
||||
"enabled": false,
|
||||
"file": null,
|
||||
"offsetSeconds": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"schemaVersion": 99,
|
||||
"id": "demo-street",
|
||||
"seed": 42,
|
||||
"video": {
|
||||
"width": 540,
|
||||
"height": 960,
|
||||
"fps": 30,
|
||||
"durationSeconds": 12
|
||||
},
|
||||
"world": {
|
||||
"streetLengthMeters": 100,
|
||||
"roadWidthMeters": 8,
|
||||
"nearHousesPerSide": 9,
|
||||
"backgroundMode": "cards",
|
||||
"lightingPreset": "warm_day"
|
||||
},
|
||||
"rider": {
|
||||
"assetId": "placeholder-rider",
|
||||
"bikeColor": "#D95437",
|
||||
"startPosition": [
|
||||
1.8,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"travelMeters": 32
|
||||
},
|
||||
"motion": {
|
||||
"startSeconds": 1,
|
||||
"brakeStartSeconds": 9,
|
||||
"stopSeconds": 10
|
||||
},
|
||||
"camera": {
|
||||
"preset": "third_person_follow",
|
||||
"offset": [
|
||||
1.2,
|
||||
2.7,
|
||||
5.4
|
||||
],
|
||||
"lookAtOffset": [
|
||||
-0.2,
|
||||
1.0,
|
||||
-2.5
|
||||
],
|
||||
"fovDegrees": 55,
|
||||
"endOffset": [
|
||||
1.9,
|
||||
1.15,
|
||||
4.6
|
||||
],
|
||||
"endLookAtOffset": [
|
||||
-0.3,
|
||||
0.13,
|
||||
-1.0
|
||||
]
|
||||
},
|
||||
"overlay": {
|
||||
"startSeconds": 10,
|
||||
"title": "Uma entrega inesperada.",
|
||||
"choiceA": "A — Aceitar",
|
||||
"choiceB": "B — Continuar a rota"
|
||||
},
|
||||
"audio": {
|
||||
"enabled": false,
|
||||
"file": null,
|
||||
"offsetSeconds": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
extends SceneTree
|
||||
## Testes pequenos da lógica que não precisa de GPU (roda em --headless):
|
||||
## validação do contrato e avaliação temporal.
|
||||
##
|
||||
## Uso: godot --headless --path godot --script res://tests/run_tests.gd
|
||||
## Sai com código 0 se tudo passar, 1 se algo falhar.
|
||||
|
||||
const SceneConfig := preload("res://scripts/core/scene_config.gd")
|
||||
const Timeline := preload("res://scripts/core/timeline_controller.gd")
|
||||
const RiderBuilder := preload("res://scripts/builders/rider_builder.gd")
|
||||
|
||||
var _passed := 0
|
||||
var _failed := 0
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
var root := ProjectSettings.globalize_path("res://").trim_suffix("/").get_base_dir()
|
||||
var fixtures := ProjectSettings.globalize_path("res://tests/fixtures")
|
||||
|
||||
# --- configurações válidas ---
|
||||
var demo := SceneConfig.load_file(root.path_join("config/demo-street.json"))
|
||||
_check(demo.ok, "demo-street.json é válida", demo.errors)
|
||||
var variant := SceneConfig.load_file(root.path_join("config/demo-street-variant.json"))
|
||||
_check(variant.ok, "demo-street-variant.json é válida", variant.errors)
|
||||
|
||||
# --- rejeições ---
|
||||
_expect_error(SceneConfig.load_file(fixtures.path_join("invalid-json.json")), "JSON inválido", "JSON malformado é rejeitado")
|
||||
_expect_error(SceneConfig.load_file(fixtures.path_join("impossible-times.json")), "startSeconds < brakeStartSeconds", "intervalo de tempo impossível é rejeitado")
|
||||
_expect_error(SceneConfig.load_file(fixtures.path_join("unknown-version.json")), "schemaVersion 99", "versão desconhecida é rejeitada")
|
||||
_expect_error(SceneConfig.load_file(fixtures.path_join("audio-without-file.json")), "audio.file", "áudio habilitado sem arquivo é rejeitado")
|
||||
_expect_error(SceneConfig.load_file(fixtures.path_join("unknown-field.json")), "world.script", "campo desconhecido é rejeitado")
|
||||
_expect_error(SceneConfig.load_file(fixtures.path_join("nao-existe.json")), "não encontrado", "arquivo inexistente é rejeitado")
|
||||
_expect_error(SceneConfig.parse_text("[1, 2]"), "objeto", "raiz que não é objeto é rejeitada")
|
||||
|
||||
if demo.ok:
|
||||
var raw: Dictionary = JSON.parse_string(FileAccess.get_file_as_string(root.path_join("config/demo-street.json")))
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["motion", "stopSeconds"], 13)), "durationSeconds", "parada depois do fim do vídeo é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["motion", "brakeStartSeconds"], 1)), "startSeconds < brakeStartSeconds", "frenagem no mesmo instante da partida é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["video", "fps"], 0)), "video.fps", "FPS zero é rejeitado")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["video", "width"], -540)), "video.width", "largura negativa é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["video", "width"], 541)), "par", "largura ímpar é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["video", "fps"], "30")), "número finito", "número como texto é rejeitado")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["video", "durationSeconds"], 12.01)), "inteiro de quadros", "duração sem número inteiro de quadros é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["rider", "bikeColor"], "vermelho")), "#RRGGBB", "cor inválida é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["rider", "travelMeters"], 95)), "fim da rua", "percurso que passa do fim da rua é rejeitado")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["camera", "offset"], [0, -3, 2])), "altura", "câmera abaixo do chão é rejeitada")
|
||||
_expect_error(SceneConfig.validate(_patched(raw, ["overlay", "title"], "linha1\nlinha2")), "controle", "texto com caractere de controle é rejeitado")
|
||||
|
||||
_test_motion(demo.config)
|
||||
_test_determinism(raw)
|
||||
|
||||
print("\n%d passaram, %d falharam" % [_passed, _failed])
|
||||
quit(1 if _failed > 0 else 0)
|
||||
|
||||
|
||||
func _test_motion(cfg: Dictionary) -> void:
|
||||
var tl := Timeline.new(cfg, RiderBuilder.WHEEL_RADIUS)
|
||||
var start: Vector3 = cfg.rider.start_position
|
||||
var travel: float = cfg.rider.travel
|
||||
var m: Dictionary = cfg.motion
|
||||
|
||||
var s0 := tl.evaluate_at_time(0.0)
|
||||
_check(s0.rider_position == start, "posição inicial = startPosition", [str(s0.rider_position)])
|
||||
_check(tl.distance_at(m.start) == 0.0, "moto parada até startSeconds")
|
||||
var s_stop := tl.evaluate_at_time(m.stop)
|
||||
_check(is_equal_approx(s_stop.distance, travel), "distância = travelMeters no instante de parada", [str(s_stop.distance)])
|
||||
_check(tl.evaluate_at_time(cfg.video.duration).rider_position == start + Vector3(0, 0, -travel), "posição final exata e moto anda em -Z")
|
||||
_check(tl.speed_at(m.stop + 0.5) == 0.0 and tl.distance_at(m.stop + 0.5) == travel, "moto permanece parada após stopSeconds")
|
||||
|
||||
# Continuidade: com passo pequeno não pode haver salto de posição, e a
|
||||
# velocidade não pode mudar bruscamente nas fronteiras das fases.
|
||||
var dt := 0.0005
|
||||
var max_step := 0.0
|
||||
var max_speed_jump := 0.0
|
||||
var monotonic := true
|
||||
var prev_d := tl.distance_at(0.0)
|
||||
var prev_v := tl.speed_at(0.0)
|
||||
var t := dt
|
||||
while t <= cfg.video.duration:
|
||||
var d := tl.distance_at(t)
|
||||
var v := tl.speed_at(t)
|
||||
max_step = maxf(max_step, absf(d - prev_d))
|
||||
max_speed_jump = maxf(max_speed_jump, absf(v - prev_v))
|
||||
if d < prev_d - 1e-9:
|
||||
monotonic = false
|
||||
prev_d = d
|
||||
prev_v = v
|
||||
t += dt
|
||||
var v_cruise := tl.cruise_speed()
|
||||
_check(monotonic, "distância nunca diminui")
|
||||
_check(max_step <= v_cruise * dt * 1.01, "sem saltos de posição (maior passo %.5f m)" % max_step)
|
||||
_check(max_speed_jump < 0.01, "velocidade contínua nas fases (maior salto %.5f m/s)" % max_speed_jump)
|
||||
|
||||
# Em cada fronteira de fase, distância à esquerda e à direita coincidem.
|
||||
for boundary in [m.start, m.start + m.accel_seconds, m.brake_start, m.stop]:
|
||||
var left := tl.distance_at(boundary - 1e-6)
|
||||
var right := tl.distance_at(boundary + 1e-6)
|
||||
_check(absf(left - right) < 1e-4, "sem salto na fronteira t=%.3f" % boundary, [str(left), str(right)])
|
||||
|
||||
# Roda: ângulo = -distância / raio.
|
||||
var s4 := tl.evaluate_at_time(4.0)
|
||||
_check(is_equal_approx(s4.wheel_angle, -s4.distance / RiderBuilder.WHEEL_RADIUS), "ângulo da roda = distância / raio")
|
||||
_check(tl.evaluate_at_time(5.0).wheel_angle < s4.wheel_angle, "roda continua girando enquanto há deslocamento")
|
||||
|
||||
# Overlay
|
||||
_check(not tl.evaluate_at_time(cfg.overlay.start - 0.01).overlay.visible, "overlay oculto antes de startSeconds")
|
||||
_check(tl.evaluate_at_time(cfg.overlay.start + 1.5).overlay.choice_b == 1.0, "overlay completo após o fade")
|
||||
|
||||
|
||||
func _test_determinism(raw: Dictionary) -> void:
|
||||
var a := Timeline.new(SceneConfig.validate(raw.duplicate(true)).config, RiderBuilder.WHEEL_RADIUS)
|
||||
var b := Timeline.new(SceneConfig.validate(raw.duplicate(true)).config, RiderBuilder.WHEEL_RADIUS)
|
||||
var same := true
|
||||
for i in 361:
|
||||
var t := i / 30.0
|
||||
var sa := a.evaluate_at_time(t)
|
||||
var sb := b.evaluate_at_time(t)
|
||||
if var_to_str(sa) != var_to_str(sb):
|
||||
same = false
|
||||
break
|
||||
_check(same, "mesmo t produz o mesmo estado em duas instâncias")
|
||||
# Avaliar fora de ordem não pode alterar o resultado (sem estado acumulado).
|
||||
var forward := var_to_str(a.evaluate_at_time(7.3))
|
||||
a.evaluate_at_time(11.0)
|
||||
a.evaluate_at_time(0.0)
|
||||
_check(var_to_str(a.evaluate_at_time(7.3)) == forward, "avaliação não depende da ordem das chamadas")
|
||||
|
||||
|
||||
func _patched(raw: Dictionary, path: Array, value) -> Dictionary:
|
||||
var copy: Dictionary = raw.duplicate(true)
|
||||
var node: Dictionary = copy
|
||||
for i in path.size() - 1:
|
||||
node = node[path[i]]
|
||||
node[path[-1]] = value
|
||||
return copy
|
||||
|
||||
|
||||
func _expect_error(result: Dictionary, fragment: String, label: String) -> void:
|
||||
var found := false
|
||||
for e in result.errors:
|
||||
if e.contains(fragment):
|
||||
found = true
|
||||
_check(not result.ok and found, label, result.errors)
|
||||
|
||||
|
||||
func _check(condition: bool, label: String, details = []) -> void:
|
||||
if condition:
|
||||
_passed += 1
|
||||
print(" ok " + label)
|
||||
else:
|
||||
_failed += 1
|
||||
print(" FALHA " + label + (" " + str(details) if not details.is_empty() else ""))
|
||||
@@ -0,0 +1 @@
|
||||
uid://wi72iir0ra5v
|
||||
@@ -0,0 +1,23 @@
|
||||
extends SceneTree
|
||||
## Preparação de assets (sem renderização 3D; roda em --headless):
|
||||
## gera as fachadas distantes em godot/assets/backgrounds/facade_XX.png.
|
||||
##
|
||||
## Uso: godot --headless --path godot --script res://tools/generate_backgrounds.gd
|
||||
## As imagens são determinísticas: rodar de novo produz os mesmos pixels.
|
||||
|
||||
const FacadePainter := preload("res://scripts/builders/facade_painter.gd")
|
||||
|
||||
|
||||
func _initialize() -> void:
|
||||
var dir := ProjectSettings.globalize_path("res://assets/backgrounds")
|
||||
DirAccess.make_dir_recursive_absolute(dir)
|
||||
var failures := 0
|
||||
for v in FacadePainter.FACADE_VARIANTS:
|
||||
var path := dir.path_join(FacadePainter.facade_file_name(v))
|
||||
var err := FacadePainter.paint_facade(v).save_png(path)
|
||||
if err != OK:
|
||||
printerr("falha ao salvar %s (erro %d)" % [path, err])
|
||||
failures += 1
|
||||
else:
|
||||
print("ok %s" % path)
|
||||
quit(1 if failures > 0 else 0)
|
||||
@@ -0,0 +1 @@
|
||||
uid://dmea3x3modn7u
|
||||