Files
2026-09-30 21:10:51 -03:00

265 lines
11 KiB
Python

# -*- coding: utf-8 -*-
"""Cena Blender do robô (rodar: blender -b -P cena_blender.py -- <modo> <saida> [opções])
modos:
campus : robô sobre o caminho da foto unicap_22 (fundo transparente + shadow catcher)
estudio : robô isolado, iluminação de estúdio, fundo transparente (para slides)
"""
import bpy, bmesh, math, os, sys, json
from mathutils import Vector, Euler
ROOT = os.path.expanduser("~/robo_movel/render")
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
MODE = argv[0] if argv else "campus"
OUTP = argv[1] if len(argv) > 1 else os.path.join(ROOT, "teste.png")
OPTS = dict(a.split("=") for a in argv[2:])
RES = float(OPTS.get("res", "0.25"))
SPP = int(OPTS.get("spp", "64"))
# ------------------------------------------------------------------ cena limpa
bpy.ops.wm.read_factory_settings(use_empty=True)
scn = bpy.context.scene
scn.unit_settings.system = "METRIC"
# ------------------------------------------------------------------ importa robô (cache .blend)
CACHE = os.path.join(ROOT, "robo_import.blend")
def import_robot():
if os.path.exists(CACHE):
with bpy.data.libraries.load(CACHE, link=False) as (src, dst):
dst.objects = src.objects
col = bpy.data.collections.new("Robo")
scn.collection.children.link(col)
for o in dst.objects:
col.objects.link(o)
return list(dst.objects)
bpy.ops.wm.obj_import(filepath=os.path.join(ROOT, "robo.obj"), up_axis="Z", forward_axis="Y")
objs = [o for o in scn.objects if o.type == "MESH"]
for o in objs:
bm = bmesh.new()
bm.from_mesh(o.data)
bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
bm.to_mesh(o.data)
bm.free()
me = o.data
if hasattr(me, "set_sharp_from_angle"):
me.shade_smooth()
me.set_sharp_from_angle(angle=math.radians(35))
# salva cache (só os objetos do robô)
bpy.data.libraries.write(CACHE, set(objs), fake_user=True)
return objs
objs = import_robot()
# ------------------------------------------------------------------ materiais
def principled(name, color, rough=0.45, metal=0.0, spec=0.5, alpha=1.0, coat=0.0, transm=0.0):
m = bpy.data.materials.get("R_" + name) or bpy.data.materials.new("R_" + name)
m.use_nodes = True
nt = m.node_tree
b = nt.nodes.get("Principled BSDF")
b.inputs["Base Color"].default_value = (*color, 1)
b.inputs["Roughness"].default_value = rough
b.inputs["Metallic"].default_value = metal
if "Coat Weight" in b.inputs:
b.inputs["Coat Weight"].default_value = coat
if "Transmission Weight" in b.inputs:
b.inputs["Transmission Weight"].default_value = transm
b.inputs["Alpha"].default_value = alpha
return m, nt, b
def srgb(c):
return tuple(((x + 0.055) / 1.055) ** 2.4 if x > 0.04045 else x / 12.92 for x in c)
def mdf_material():
m, nt, b = principled("mdf", srgb((0.74, 0.58, 0.40)), rough=0.72)
tc = nt.nodes.new("ShaderNodeTexCoord")
noise = nt.nodes.new("ShaderNodeTexNoise")
noise.inputs["Scale"].default_value = 180.0
noise.inputs["Detail"].default_value = 8.0
ramp = nt.nodes.new("ShaderNodeValToRGB")
ramp.color_ramp.elements[0].color = (*srgb((0.52, 0.36, 0.22)), 1)
ramp.color_ramp.elements[1].color = (*srgb((0.66, 0.48, 0.31)), 1)
nt.links.new(tc.outputs["Object"], noise.inputs["Vector"])
nt.links.new(noise.outputs["Fac"], ramp.inputs["Fac"])
nt.links.new(ramp.outputs["Color"], b.inputs["Base Color"])
bump = nt.nodes.new("ShaderNodeBump")
bump.inputs["Strength"].default_value = 0.08
nt.links.new(noise.outputs["Fac"], bump.inputs["Height"])
nt.links.new(bump.outputs["Normal"], b.inputs["Normal"])
return m
MATS = {
"mdf": mdf_material,
"preto": lambda: principled("preto", (0.012, 0.012, 0.013), 0.42)[0],
"grafite": lambda: principled("grafite", (0.03, 0.03, 0.035), 0.5)[0],
"borracha": lambda: principled("borracha", (0.035, 0.035, 0.04), 0.85)[0],
"aco": lambda: principled("aco", (0.55, 0.56, 0.58), 0.28, 1.0)[0],
"zincado": lambda: principled("zincado", (0.40, 0.41, 0.43), 0.5, 1.0)[0],
"aluminio": lambda: principled("aluminio", (0.80, 0.81, 0.83), 0.22, 1.0)[0],
"aco_preto": lambda: principled("aco_preto", (0.035, 0.035, 0.04), 0.35, 0.85)[0],
"latao": lambda: principled("latao", (0.78, 0.60, 0.25), 0.3, 1.0)[0],
"ouro": lambda: principled("ouro", (0.90, 0.68, 0.25), 0.25, 1.0)[0],
"cobre": lambda: principled("cobre", (0.85, 0.45, 0.25), 0.3, 1.0)[0],
"pcb_azul": lambda: principled("pcb_azul", srgb((0.03, 0.22, 0.55)), 0.3, coat=0.4)[0],
"pcb_verm": lambda: principled("pcb_verm", srgb((0.72, 0.06, 0.05)), 0.3, coat=0.4)[0],
"pcb_preto": lambda: principled("pcb_preto", (0.01, 0.01, 0.012), 0.3, coat=0.4)[0],
"pcb_verde": lambda: principled("pcb_verde", srgb((0.05, 0.33, 0.14)), 0.3, coat=0.4)[0],
}
def mat_for(name, kd, d):
base = name.replace("_transp", "")
if base in MATS:
m = MATS[base]() if callable(MATS[base]) else MATS[base]
MATS[base] = m
return m
m, nt, b = principled(name, srgb(kd), 0.4)
if name.endswith("_transp"):
b.inputs["Alpha"].default_value = max(0.25, d)
if "Transmission Weight" in b.inputs:
b.inputs["Transmission Weight"].default_value = 0.6
return m
kd = {}
mtl = os.path.join(ROOT, "robo.mtl")
cur = None
for line in open(mtl):
s = line.split()
if not s:
continue
if s[0] == "newmtl":
cur = s[1]
kd[cur] = [(0.5, 0.5, 0.5), 1.0]
elif s[0] == "Kd":
kd[cur][0] = tuple(map(float, s[1:4]))
elif s[0] == "d":
kd[cur][1] = float(s[1])
for o in objs:
for slot in o.material_slots:
if slot.material is None:
continue
nm = slot.material.name.split(".")[0]
if nm.startswith("R_"):
continue
c, dd = kd.get(nm, [(0.5, 0.5, 0.5), 1.0])
slot.material = mat_for(nm, c, dd)
import collections
print("MATERIAIS_EM_USO", collections.Counter(s.material.name for o in objs for s in o.material_slots if s.material).most_common(8))
# ------------------------------------------------------------------ render
scn.render.engine = "CYCLES"
prefs = bpy.context.preferences.addons["cycles"].preferences
for dev in ("OPTIX", "CUDA"):
try:
prefs.compute_device_type = dev
prefs.get_devices()
for dv in prefs.devices:
dv.use = True
scn.cycles.device = "GPU"
print("dispositivo", dev)
break
except Exception as ex:
print("sem", dev, ex)
scn.cycles.samples = SPP
scn.cycles.use_denoising = True
scn.render.film_transparent = True
scn.view_settings.view_transform = "AgX"
scn.view_settings.look = "AgX - Medium High Contrast"
scn.view_settings.exposure = float(OPTS.get("exp", "0"))
scn.render.image_settings.file_format = "PNG"
scn.render.image_settings.color_mode = "RGBA"
# robô: centro da base na origem
rob = bpy.data.objects.new("RoboRoot", None)
scn.collection.objects.link(rob)
for o in objs:
o.parent = rob
world = bpy.data.worlds.new("Mundo")
scn.world = world
world.use_nodes = True
wn = world.node_tree
bg = wn.nodes.get("Background")
sky = wn.nodes.new("ShaderNodeTexSky")
try:
sky.sky_type = "NISHITA"
except Exception:
pass
sky.sun_elevation = math.radians(55)
if hasattr(sky, "sun_disc"):
sky.sun_disc = False # o sol vem da lâmpada SUN (evita luz dobrada)
sky.sun_rotation = math.radians(float(OPTS.get("sunrot", "210")))
wn.links.new(sky.outputs["Color"], bg.inputs["Color"])
bg.inputs["Strength"].default_value = float(OPTS.get("sky", "0.12"))
if MODE == "campus":
W, H = 4160, 2773
scn.render.resolution_x, scn.render.resolution_y = W, H
scn.render.resolution_percentage = int(RES * 100)
cam_d = bpy.data.cameras.new("Cam")
cam_d.sensor_fit = "HORIZONTAL"
cam_d.sensor_width = 36.0
cam_d.lens = float(OPTS.get("lens", "30"))
cam = bpy.data.objects.new("Cam", cam_d)
scn.collection.objects.link(cam)
scn.camera = cam
cam.location = (0, 0, float(OPTS.get("camh", "1.45")))
cam.rotation_euler = Euler((math.radians(90 + float(OPTS.get("tilt", "5.5"))), 0, 0), "XYZ")
# robô no caminho: distância e deslocamento lateral
rob.location = (float(OPTS.get("rx", "-0.25")), float(OPTS.get("ry", "6.0")), 0)
rob.rotation_euler = (0, 0, math.radians(float(OPTS.get("rrot", "155")))) # frente (câmera) virada p/ a câmera
# régua opcional: blocos 20 x 10 cm (piso intertravado) ao lado do robô
if OPTS.get("regua"):
for k in range(int(OPTS.get("regua"))):
bpy.ops.mesh.primitive_cube_add(size=1)
b = bpy.context.active_object
b.scale = (0.10, 0.20, 0.004)
b.location = (rob.location.x + 0.45 + (k % 2) * 0.105, rob.location.y - 0.3 + (k // 2) * 0.205, 0.002)
b.data.materials.append(principled("regua%d" % (k % 2), (0.9, 0.1, 0.1) if k % 2 else (0.1, 0.1, 0.9), 0.5)[0])
# plano coletor de sombra
bpy.ops.mesh.primitive_plane_add(size=40, location=(0, 10, 0))
gp = bpy.context.active_object
gp.is_shadow_catcher = True
gp.data.materials.append(principled("chao", (0.45, 0.43, 0.40), 0.9)[0])
# sol suave (dia nublado claro)
sun_d = bpy.data.lights.new("Sol", "SUN")
sun_d.energy = float(OPTS.get("sun", "2.2"))
sun_d.angle = math.radians(float(OPTS.get("sunang", "25")))
sun = bpy.data.objects.new("Sol", sun_d)
scn.collection.objects.link(sun)
sun.rotation_euler = Euler((math.radians(35), 0, math.radians(float(OPTS.get("sunrot", "210")))), "XYZ")
else:
scn.render.resolution_x, scn.render.resolution_y = int(OPTS.get("w", "2000")), int(OPTS.get("h", "2400"))
scn.render.resolution_percentage = int(RES * 100)
cam_d = bpy.data.cameras.new("Cam")
cam_d.lens = float(OPTS.get("lens", "85"))
cam = bpy.data.objects.new("Cam", cam_d)
scn.collection.objects.link(cam)
scn.camera = cam
target = Vector((0, 0, 0.52))
az, el, dist = math.radians(float(OPTS.get("az", "142"))), math.radians(float(OPTS.get("el", "20"))), float(OPTS.get("dist", "5.2"))
cam.location = target + Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el))) * dist
d = target - cam.location
cam.rotation_euler = d.to_track_quat("-Z", "Y").to_euler()
# chão: coletor de sombra (sombra suave no PNG transparente)
bpy.ops.mesh.primitive_plane_add(size=20, location=(0, 0, 0))
gp = bpy.context.active_object
gp.is_shadow_catcher = True
for nm, e, loc, size in (("Key", 900, (-2.5, -2.8, 3.2), 2.5), ("Fill", 300, (3.0, -1.5, 1.8), 3.0), ("Rim", 600, (0.5, 3.2, 2.8), 2.0)):
ld = bpy.data.lights.new(nm, "AREA")
ld.energy = e * float(OPTS.get("lux", "1.0"))
ld.size = size
lo = bpy.data.objects.new(nm, ld)
scn.collection.objects.link(lo)
lo.location = loc
lo.rotation_euler = (Vector((0, 0, 0.5)) - Vector(loc)).to_track_quat("-Z", "Y").to_euler()
scn.render.filepath = OUTP
bpy.ops.render.render(write_still=True)
print("salvo", OUTP)