Export_3ds: Improved distance cue node search
[blender-addons.git] / render_povray / scenography.py
blob26828cf547144a8e95c5ba64b337ff5bbd436a08
1 # SPDX-FileCopyrightText: 2021-2022 Blender Foundation
3 # SPDX-License-Identifier: GPL-2.0-or-later
5 """With respect to camera frame and optics distortions, also export environment
7 with world, sky, atmospheric effects such as rainbows or smoke """
9 import bpy
11 import os
12 from imghdr import what # imghdr is a python lib to identify image file types
13 from math import atan, pi, sqrt, degrees
14 from . import voxel_lib # for smoke rendering
15 from .model_primitives import write_object_modifiers
18 # -------- find image texture # used for export_world -------- #
21 def image_format(img_f):
22 """Identify input image filetypes to transmit to POV."""
23 # First use the below explicit extensions to identify image file prospects
24 ext = {
25 "JPG": "jpeg",
26 "JPEG": "jpeg",
27 "GIF": "gif",
28 "TGA": "tga",
29 "IFF": "iff",
30 "PPM": "ppm",
31 "PNG": "png",
32 "SYS": "sys",
33 "TIFF": "tiff",
34 "TIF": "tiff",
35 "EXR": "exr",
36 "HDR": "hdr",
37 }.get(os.path.splitext(img_f)[-1].upper(), "")
38 # Then, use imghdr to really identify the filetype as it can be different
39 if not ext:
40 # maybe add a check for if path exists here?
41 print(" WARNING: texture image has no extension") # too verbose
43 ext = what(img_f) # imghdr is a python lib to identify image file types
44 return ext
47 def img_map(ts):
48 """Translate mapping type from Blender UI to POV syntax and return that string."""
49 image_map = ""
50 texdata = bpy.data.textures[ts.texture]
51 if ts.mapping == "FLAT":
52 image_map = "map_type 0 "
53 elif ts.mapping == "SPHERE":
54 image_map = "map_type 1 "
55 elif ts.mapping == "TUBE":
56 image_map = "map_type 2 "
58 # map_type 3 and 4 in development (?) (ENV in pov 3.8)
59 # for POV-Ray, currently they just seem to default back to Flat (type 0)
60 # elif ts.mapping=="?":
61 # image_map = " map_type 3 "
62 # elif ts.mapping=="?":
63 # image_map = " map_type 4 "
64 if ts.use_interpolation: # Available if image sampling class reactivated?
65 image_map += " interpolate 2 "
66 if texdata.extension == "CLIP":
67 image_map += " once "
68 # image_map += "}"
69 # if ts.mapping=='CUBE':
70 # image_map+= "warp { cubic } rotate <-90,0,180>"
71 # no direct cube type mapping. Though this should work in POV 3.7
72 # it doesn't give that good results(best suited to environment maps?)
73 # if image_map == "":
74 # print(" No texture image found ")
75 return image_map
78 def img_map_transforms(ts):
79 """Translate mapping transformations from Blender UI to POV syntax and return that string."""
80 # XXX TODO: unchecked textures give error of variable referenced before assignment XXX
81 # POV-Ray "scale" is not a number of repetitions factor, but ,its
82 # inverse, a standard scale factor.
83 # 0.5 Offset is needed relatively to scale because center of the
84 # scale is 0.5,0.5 in blender and 0,0 in POV
85 # Strange that the translation factor for scale is not the same as for
86 # translate.
87 # TODO: verify both matches with other blender renderers / internal in previous versions.
88 image_map_transforms = ""
89 image_map_transforms = "scale <%.4g,%.4g,%.4g> translate <%.4g,%.4g,%.4g>" % (
90 ts.scale[0],
91 ts.scale[1],
92 ts.scale[2],
93 ts.offset[0],
94 ts.offset[1],
95 ts.offset[2],
97 # image_map_transforms = (" translate <-0.5,-0.5,0.0> scale <%.4g,%.4g,%.4g> translate <%.4g,%.4g,%.4g>" % \
98 # ( 1.0 / ts.scale.x,
99 # 1.0 / ts.scale.y,
100 # 1.0 / ts.scale.z,
101 # (0.5 / ts.scale.x) + ts.offset.x,
102 # (0.5 / ts.scale.y) + ts.offset.y,
103 # ts.offset.z))
104 # image_map_transforms = (
105 # "translate <-0.5,-0.5,0> "
106 # "scale <-1,-1,1> * <%.4g,%.4g,%.4g> "
107 # "translate <0.5,0.5,0> + <%.4g,%.4g,%.4g>" % \
108 # (1.0 / ts.scale.x,
109 # 1.0 / ts.scale.y,
110 # 1.0 / ts.scale.z,
111 # ts.offset.x,
112 # ts.offset.y,
113 # ts.offset.z)
115 return image_map_transforms
118 def img_map_bg(wts):
119 """Translate world mapping from Blender UI to POV syntax and return that string."""
120 tex = bpy.data.textures[wts.texture]
121 image_mapBG = ""
122 # texture_coords refers to the mapping of world textures:
123 if wts.texture_coords in ["VIEW", "GLOBAL"]:
124 image_mapBG = " map_type 0 "
125 elif wts.texture_coords == "ANGMAP":
126 image_mapBG = " map_type 1 "
127 elif wts.texture_coords == "TUBE":
128 image_mapBG = " map_type 2 "
130 if tex.use_interpolation:
131 image_mapBG += " interpolate 2 "
132 if tex.extension == "CLIP":
133 image_mapBG += " once "
134 # image_mapBG += "}"
135 # if wts.mapping == 'CUBE':
136 # image_mapBG += "warp { cubic } rotate <-90,0,180>"
137 # no direct cube type mapping. Though this should work in POV 3.7
138 # it doesn't give that good results(best suited to environment maps?)
139 # if image_mapBG == "":
140 # print(" No background texture image found ")
141 return image_mapBG
144 def path_image(image):
145 """Conform a path string to POV syntax to avoid POV errors."""
146 return bpy.path.abspath(image.filepath, library=image.library).replace("\\", "/")
147 # .replace("\\","/") to get only forward slashes as it's what POV prefers,
148 # even on windows
151 # end find image texture
152 # -----------------------------------------------------------------------------
155 def export_camera(file, scene, global_matrix, render, tab_write):
156 """Translate camera from Blender UI to POV syntax and write to exported file."""
157 camera = scene.camera
159 # DH disabled for now, this isn't the correct context
160 active_object = None # bpy.context.active_object # does not always work MR
161 matrix = global_matrix @ camera.matrix_world
162 focal_point = camera.data.dof.focus_distance
164 # compute resolution
165 q_size = render.resolution_x / render.resolution_y
166 tab_write(file, "#declare camLocation = <%.6f, %.6f, %.6f>;\n" % matrix.translation[:])
167 tab_write(
168 file,
170 "#declare camLookAt = <%.6f, %.6f, %.6f>;\n"
171 % tuple(degrees(e) for e in matrix.to_3x3().to_euler())
175 tab_write(file, "camera {\n")
176 if scene.pov.baking_enable and active_object and active_object.type == "MESH":
177 tab_write(file, "mesh_camera{ 1 3\n") # distribution 3 is what we want here
178 tab_write(file, "mesh{%s}\n" % active_object.name)
179 tab_write(file, "}\n")
180 tab_write(file, "location <0,0,.01>")
181 tab_write(file, "direction <0,0,-1>")
183 else:
184 if camera.data.type == "ORTHO":
185 # XXX todo: track when SensorHeightRatio was added to see if needed (not used)
186 sensor_height_ratio = (
187 render.resolution_x * camera.data.ortho_scale / render.resolution_y
189 tab_write(file, "orthographic\n")
190 # Blender angle is radian so should be converted to degrees:
191 # % (camera.data.angle * (180.0 / pi) )
192 # but actually argument is not compulsory after angle in pov ortho mode
193 tab_write(file, "angle\n")
194 tab_write(file, "right <%6f, 0, 0>\n" % -camera.data.ortho_scale)
195 tab_write(file, "location <0, 0, 0>\n")
196 tab_write(file, "look_at <0, 0, -1>\n")
197 tab_write(file, "up <0, %6f, 0>\n" % (camera.data.ortho_scale / q_size))
199 elif camera.data.type == "PANO":
200 tab_write(file, "panoramic\n")
201 tab_write(file, "location <0, 0, 0>\n")
202 tab_write(file, "look_at <0, 0, -1>\n")
203 tab_write(file, "right <%s, 0, 0>\n" % -q_size)
204 tab_write(file, "up <0, 1, 0>\n")
205 tab_write(file, "angle %f\n" % (360.0 * atan(16.0 / camera.data.lens) / pi))
206 elif camera.data.type == "PERSP":
207 # Standard camera otherwise would be default in pov
208 tab_write(file, "location <0, 0, 0>\n")
209 tab_write(file, "look_at <0, 0, -1>\n")
210 tab_write(file, "right <%s, 0, 0>\n" % -q_size)
211 tab_write(file, "up <0, 1, 0>\n")
212 tab_write(
213 file,
214 "angle %f\n"
215 % (2 * atan(camera.data.sensor_width / 2 / camera.data.lens) * 180.0 / pi),
218 tab_write(
219 file,
220 "rotate <%.6f, %.6f, %.6f>\n" % tuple(degrees(e) for e in matrix.to_3x3().to_euler()),
223 tab_write(file, "translate <%.6f, %.6f, %.6f>\n" % matrix.translation[:])
224 if camera.data.dof.use_dof and (focal_point != 0 or camera.data.dof.focus_object):
225 tab_write(
226 file, "aperture %.3g\n" % (1 / (camera.data.dof.aperture_fstop * 10000) * 1000)
228 tab_write(
229 file,
230 "blur_samples %d %d\n"
231 % (camera.data.pov.dof_samples_min, camera.data.pov.dof_samples_max),
233 tab_write(file, "variance 1/%d\n" % camera.data.pov.dof_variance)
234 tab_write(file, "confidence %.3g\n" % camera.data.pov.dof_confidence)
235 if camera.data.dof.focus_object:
236 focal_ob = scene.objects[camera.data.dof.focus_object.name]
237 matrix_blur = global_matrix @ focal_ob.matrix_world
238 tab_write(file, "focal_point <%.4f,%.4f,%.4f>\n" % matrix_blur.translation[:])
239 else:
240 tab_write(file, "focal_point <0, 0, %f>\n" % focal_point)
241 if camera.data.pov.normal_enable:
242 tab_write(
243 file,
244 "normal {%s %.4f turbulence %.4f scale %.4f}\n"
246 camera.data.pov.normal_patterns,
247 camera.data.pov.cam_normal,
248 camera.data.pov.turbulence,
249 camera.data.pov.scale,
252 tab_write(file, "}\n")
255 exported_lights_count = 0
258 def export_lights(lamps, file, scene, global_matrix, tab_write):
259 """Translate lights from Blender UI to POV syntax and write to exported file."""
261 from .render import write_matrix, tab_write
263 # Incremented after each lamp export to declare its target
264 # currently used for Fresnel diffuse shader as their slope vector:
265 global exported_lights_count
266 # Get all lamps and keep their count in a global variable
267 for exported_lights_count, ob in enumerate(lamps, start=1):
268 lamp = ob.data
270 matrix = global_matrix @ ob.matrix_world
272 # Color is no longer modified by energy
273 # any way to directly get bpy_prop_array as tuple?
274 color = tuple(lamp.color)
276 tab_write(file, "light_source {\n")
277 tab_write(file, "< 0,0,0 >\n")
278 tab_write(file, "color srgb<%.3g, %.3g, %.3g>\n" % color)
280 if lamp.type == "POINT":
281 pass
282 elif lamp.type == "SPOT":
283 tab_write(file, "spotlight\n")
285 # Falloff is the main radius from the centre line
286 tab_write(file, "falloff %.2f\n" % (degrees(lamp.spot_size) / 2.0)) # 1 TO 179 FOR BOTH
287 tab_write(
288 file, "radius %.6f\n" % ((degrees(lamp.spot_size) / 2.0) * (1.0 - lamp.spot_blend))
291 # Blender does not have a tightness equivalent, 0 is most like blender default.
292 tab_write(file, "tightness 0\n") # 0:10f
294 tab_write(file, "point_at <0, 0, -1>\n")
295 if lamp.pov.use_halo:
296 tab_write(file, "looks_like{\n")
297 tab_write(file, "sphere{<0,0,0>,%.6f\n" % lamp.shadow_soft_size)
298 tab_write(file, "hollow\n")
299 tab_write(file, "material{\n")
300 tab_write(file, "texture{\n")
301 tab_write(file, "pigment{rgbf<1,1,1,%.4f>}\n" % (lamp.pov.halo_intensity * 5.0))
302 tab_write(file, "}\n")
303 tab_write(file, "interior{\n")
304 tab_write(file, "media{\n")
305 tab_write(file, "emission 1\n")
306 tab_write(file, "scattering {1, 0.5}\n")
307 tab_write(file, "density{\n")
308 tab_write(file, "spherical\n")
309 tab_write(file, "color_map{\n")
310 tab_write(file, "[0.0 rgb <0,0,0>]\n")
311 tab_write(file, "[0.5 rgb <1,1,1>]\n")
312 tab_write(file, "[1.0 rgb <1,1,1>]\n")
313 tab_write(file, "}\n")
314 tab_write(file, "}\n")
315 tab_write(file, "}\n")
316 tab_write(file, "}\n")
317 tab_write(file, "}\n")
318 tab_write(file, "}\n")
319 tab_write(file, "}\n")
320 elif lamp.type == "SUN":
321 tab_write(file, "parallel\n")
322 tab_write(file, "point_at <0, 0, -1>\n") # *must* be after 'parallel'
324 elif lamp.type == "AREA":
325 # Area lights have no falloff type, so always use blenders lamp quad equivalent
326 # for those?
327 tab_write(file, "fade_power %d\n" % 2)
328 size_x = lamp.size
329 samples_x = lamp.pov.shadow_ray_samples_x
330 if lamp.shape == "SQUARE":
331 size_y = size_x
332 samples_y = samples_x
333 else:
334 size_y = lamp.size_y
335 samples_y = lamp.pov.shadow_ray_samples_y
337 tab_write(
338 file,
339 "area_light <%.6f,0,0>,<0,%.6f,0> %d, %d\n"
340 % (size_x, size_y, samples_x, samples_y),
342 tab_write(file, "area_illumination\n")
343 if lamp.pov.shadow_ray_sample_method == "CONSTANT_JITTERED":
344 if lamp.pov.use_jitter:
345 tab_write(file, "jitter\n")
346 else:
347 tab_write(file, "adaptive 1\n")
348 tab_write(file, "jitter\n")
350 # No shadow checked either at global or light level:
351 if not scene.pov.use_shadows or (lamp.pov.shadow_method == "NOSHADOW"):
352 tab_write(file, "shadowless\n")
354 # Sun shouldn't be attenuated. Area lights have no falloff attribute so they
355 # are put to type 2 attenuation a little higher above.
356 if lamp.type not in {"SUN", "AREA"}:
357 tab_write(file, "fade_power %d\n" % 2) # Use blenders lamp quad equivalent
359 write_matrix(file, matrix)
361 tab_write(file, "}\n")
363 # v(A,B) rotates vector A about origin by vector B.
364 file.write(
365 "#declare lampTarget%s= vrotate(<%.4g,%.4g,%.4g>,<%.4g,%.4g,%.4g>);\n"
367 exported_lights_count,
368 -ob.location.x,
369 -ob.location.y,
370 -ob.location.z,
371 ob.rotation_euler.x,
372 ob.rotation_euler.y,
373 ob.rotation_euler.z,
378 def export_world(file, world, scene, global_matrix, tab_write):
379 """write world as POV background and sky_sphere to exported file"""
380 render = scene.pov
381 agnosticrender = scene.render
382 camera = scene.camera
383 # matrix = global_matrix @ camera.matrix_world # view dependant for later use NOT USED
384 if not world:
385 return
387 # These lines added to get sky gradient (visible with PNG output)
389 # For simple flat background:
390 if not world.pov.use_sky_blend:
391 # No alpha with Sky option:
392 if render.alpha_mode == "SKY" and not agnosticrender.film_transparent:
393 tab_write(
394 file, "background {rgbt<%.3g, %.3g, %.3g, 0>}\n" % (world.pov.horizon_color[:])
397 elif render.alpha_mode == "STRAIGHT" or agnosticrender.film_transparent:
398 tab_write(
399 file, "background {rgbt<%.3g, %.3g, %.3g, 1>}\n" % (world.pov.horizon_color[:])
401 else:
402 # Non fully transparent background could premultiply alpha and avoid
403 # anti-aliasing display issue
404 tab_write(
405 file,
406 "background {rgbft<%.3g, %.3g, %.3g, %.3g, 0>}\n"
408 world.pov.horizon_color[0],
409 world.pov.horizon_color[1],
410 world.pov.horizon_color[2],
411 render.alpha_filter,
415 world_tex_count = 0
416 # For Background image textures
417 for t in world.pov_texture_slots: # risk to write several sky_spheres but maybe ok.
418 if t:
419 tex = bpy.data.textures[t.texture]
420 if tex.type is not None:
421 world_tex_count += 1
422 # XXX No enable checkbox for world textures yet (report it?)
423 # if t and tex.type == 'IMAGE' and t.use:
424 if tex.type == "IMAGE":
425 image_filename = path_image(tex.image)
426 if tex.image.filepath != image_filename:
427 tex.image.filepath = image_filename
428 if image_filename != "" and t.use_map_blend:
429 textures_blend = image_filename
430 # colvalue = t.default_value
431 t_blend = t
433 # Commented below was an idea to make the Background image oriented as camera
434 # taken here:
435 # http://news.pov.org/pov.newusers/thread/%3Cweb.4a5cddf4e9c9822ba2f93e20@news.pov.org%3E/
436 # Replace 4/3 by the ratio of each image found by some custom or existing
437 # function
438 # mapping_blend = (" translate <%.4g,%.4g,%.4g> rotate z*degrees" \
439 # "(atan((camLocation - camLookAt).x/(camLocation - " \
440 # "camLookAt).y)) rotate x*degrees(atan((camLocation - " \
441 # "camLookAt).y/(camLocation - camLookAt).z)) rotate y*" \
442 # "degrees(atan((camLocation - camLookAt).z/(camLocation - " \
443 # "camLookAt).x)) scale <%.4g,%.4g,%.4g>b" % \
444 # (t_blend.offset.x / 10 , t_blend.offset.y / 10 ,
445 # t_blend.offset.z / 10, t_blend.scale.x ,
446 # t_blend.scale.y , t_blend.scale.z))
447 # using camera rotation valuesdirectly from blender seems much easier
448 if t_blend.texture_coords == "ANGMAP":
449 mapping_blend = ""
450 else:
451 # POV-Ray "scale" is not a number of repetitions factor, but its
452 # inverse, a standard scale factor.
453 # 0.5 Offset is needed relatively to scale because center of the
454 # UV scale is 0.5,0.5 in blender and 0,0 in POV
455 # Further Scale by 2 and translate by -1 are
456 # required for the sky_sphere not to repeat
458 mapping_blend = (
459 "scale 2 scale <%.4g,%.4g,%.4g> translate -1 "
460 "translate <%.4g,%.4g,%.4g> rotate<0,0,0> "
462 (1.0 / t_blend.scale.x),
463 (1.0 / t_blend.scale.y),
464 (1.0 / t_blend.scale.z),
465 0.5 - (0.5 / t_blend.scale.x) - t_blend.offset.x,
466 0.5 - (0.5 / t_blend.scale.y) - t_blend.offset.y,
467 t_blend.offset.z,
471 # The initial position and rotation of the pov camera is probably creating
472 # the rotation offset should look into it someday but at least background
473 # won't rotate with the camera now.
474 # Putting the map on a plane would not introduce the skysphere distortion and
475 # allow for better image scale matching but also some waay to chose depth and
476 # size of the plane relative to camera.
477 tab_write(file, "sky_sphere {\n")
478 tab_write(file, "pigment {\n")
479 tab_write(
480 file,
481 'image_map{%s "%s" %s}\n'
482 % (image_format(textures_blend), textures_blend, img_map_bg(t_blend)),
484 tab_write(file, "}\n")
485 tab_write(file, "%s\n" % mapping_blend)
486 # The following layered pigment opacifies to black over the texture for
487 # transmit below 1 or otherwise adds to itself
488 tab_write(file, "pigment {rgb 0 transmit %s}\n" % tex.intensity)
489 tab_write(file, "}\n")
490 # tab_write(file, "scale 2\n")
491 # tab_write(file, "translate -1\n")
493 # For only Background gradient
495 if world_tex_count == 0 and world.pov.use_sky_blend:
496 tab_write(file, "sky_sphere {\n")
497 tab_write(file, "pigment {\n")
498 # maybe Should follow the advice of POV doc about replacing gradient
499 # for skysphere..5.5
500 tab_write(file, "gradient y\n")
501 tab_write(file, "color_map {\n")
503 if render.alpha_mode == "TRANSPARENT":
504 tab_write(
505 file,
506 "[0.0 rgbft<%.3g, %.3g, %.3g, %.3g, 0>]\n"
508 world.pov.horizon_color[0],
509 world.pov.horizon_color[1],
510 world.pov.horizon_color[2],
511 render.alpha_filter,
514 tab_write(
515 file,
516 "[1.0 rgbft<%.3g, %.3g, %.3g, %.3g, 0>]\n"
518 world.pov.zenith_color[0],
519 world.pov.zenith_color[1],
520 world.pov.zenith_color[2],
521 render.alpha_filter,
524 if agnosticrender.film_transparent or render.alpha_mode == "STRAIGHT":
525 tab_write(file, "[0.0 rgbt<%.3g, %.3g, %.3g, 0.99>]\n" % (world.pov.horizon_color[:]))
526 # aa premult not solved with transmit 1
527 tab_write(file, "[1.0 rgbt<%.3g, %.3g, %.3g, 0.99>]\n" % (world.pov.zenith_color[:]))
528 else:
529 tab_write(file, "[0.0 rgbt<%.3g, %.3g, %.3g, 0>]\n" % (world.pov.horizon_color[:]))
530 tab_write(file, "[1.0 rgbt<%.3g, %.3g, %.3g, 0>]\n" % (world.pov.zenith_color[:]))
531 tab_write(file, "}\n")
532 tab_write(file, "}\n")
533 tab_write(file, "}\n")
534 # Sky_sphere alpha (transmit) is not translating into image alpha the same
535 # way as 'background'
537 # if world.pov.light_settings.use_indirect_light:
538 # scene.pov.radio_enable=1
540 # Maybe change the above to a function copyInternalRenderer settings when
541 # user pushes a button, then:
542 # scene.pov.radio_enable = world.pov.light_settings.use_indirect_light
543 # and other such translations but maybe this would not be allowed either?
545 # -----------------------------------------------------------------------------
547 mist = world.mist_settings
549 if mist.use_mist:
550 tab_write(file, "fog {\n")
551 if mist.falloff == "LINEAR":
552 tab_write(file, "distance %.6f\n" % ((mist.start + mist.depth) * 0.368))
553 elif mist.falloff in ["QUADRATIC", "INVERSE_QUADRATIC"]: # n**2 or squrt(n)?
554 tab_write(file, "distance %.6f\n" % ((mist.start + mist.depth) ** 2 * 0.368))
555 tab_write(
556 file,
557 "color rgbt<%.3g, %.3g, %.3g, %.3g>\n"
558 % (*world.pov.horizon_color, (1.0 - mist.intensity)),
560 # tab_write(file, "fog_offset %.6f\n" % mist.start) #create a pov property to prepend
561 # tab_write(file, "fog_alt %.6f\n" % mist.height) #XXX right?
562 # tab_write(file, "turbulence 0.2\n")
563 # tab_write(file, "turb_depth 0.3\n")
564 tab_write(file, "fog_type 1\n") # type2 for height
565 tab_write(file, "}\n")
566 if scene.pov.media_enable:
567 tab_write(file, "media {\n")
568 tab_write(
569 file,
570 "scattering { %d, rgb %.12f*<%.4g, %.4g, %.4g>\n"
572 int(scene.pov.media_scattering_type),
573 scene.pov.media_diffusion_scale,
574 *(scene.pov.media_diffusion_color[:]),
577 if scene.pov.media_scattering_type == "5":
578 tab_write(file, "eccentricity %.3g\n" % scene.pov.media_eccentricity)
579 tab_write(file, "}\n")
580 tab_write(
581 file,
582 "absorption %.12f*<%.4g, %.4g, %.4g>\n"
583 % (scene.pov.media_absorption_scale, *(scene.pov.media_absorption_color[:])),
585 tab_write(file, "\n")
586 tab_write(file, "samples %.d\n" % scene.pov.media_samples)
587 tab_write(file, "}\n")
590 # -----------------------------------------------------------------------------
591 def export_rainbows(rainbows, file, scene, global_matrix, tab_write):
592 """write all POV rainbows primitives to exported file"""
594 from .render import write_matrix, tab_write
596 pov_mat_name = "Default_texture"
597 for ob in rainbows:
598 povdataname = ob.data.name # enough? XXX not used nor matrix fn?
599 angle = degrees(ob.data.spot_size / 2.5) # radians in blender (2
600 width = ob.data.spot_blend * 10
601 distance = ob.data.shadow_buffer_clip_start
602 # eps=0.0000001
603 # angle = br/(cr+eps) * 10 #eps is small epsilon variable to avoid dividing by zero
604 # width = ob.dimensions[2] #now let's say width of rainbow is the actual proxy height
605 # formerly:
606 # cz-bz # let's say width of the rainbow is height of the cone (interfacing choice
608 # v(A,B) rotates vector A about origin by vector B.
609 # and avoid a 0 length vector by adding 1
611 # file.write("#declare %s_Target= vrotate(<%.6g,%.6g,%.6g>,<%.4g,%.4g,%.4g>);\n" % \
612 # (povdataname, -(ob.location.x+0.1), -(ob.location.y+0.1), -(ob.location.z+0.1),
613 # ob.rotation_euler.x, ob.rotation_euler.y, ob.rotation_euler.z))
615 direction = ( # XXX currently not used (replaced by track to?)
616 ob.location.x,
617 ob.location.y,
618 ob.location.z,
619 ) # not taking matrix into account
620 rmatrix = global_matrix @ ob.matrix_world
622 # ob.rotation_euler.to_matrix().to_4x4() * mathutils.Vector((0,0,1))
623 # XXX Is result of the below offset by 90 degrees?
624 up = ob.matrix_world.to_3x3()[1].xyz # * global_matrix
626 # XXX TO CHANGE:
627 # formerly:
628 # tab_write(file, "#declare %s = rainbow {\n"%povdataname)
630 # clumsy for now but remove the rainbow from instancing
631 # system because not an object. use lamps later instead of meshes
633 # del data_ref[dataname]
634 tab_write(file, "rainbow {\n")
636 tab_write(file, "angle %.4f\n" % angle)
637 tab_write(file, "width %.4f\n" % width)
638 tab_write(file, "distance %.4f\n" % distance)
639 tab_write(file, "arc_angle %.4f\n" % ob.pov.arc_angle)
640 tab_write(file, "falloff_angle %.4f\n" % ob.pov.falloff_angle)
641 tab_write(file, "direction <%.4f,%.4f,%.4f>\n" % rmatrix.translation[:])
642 tab_write(file, "up <%.4f,%.4f,%.4f>\n" % (up[0], up[1], up[2]))
643 tab_write(file, "color_map {\n")
644 tab_write(file, "[0.000 color srgbt<1.0, 0.5, 1.0, 1.0>]\n")
645 tab_write(file, "[0.130 color srgbt<0.5, 0.5, 1.0, 0.9>]\n")
646 tab_write(file, "[0.298 color srgbt<0.2, 0.2, 1.0, 0.7>]\n")
647 tab_write(file, "[0.412 color srgbt<0.2, 1.0, 1.0, 0.4>]\n")
648 tab_write(file, "[0.526 color srgbt<0.2, 1.0, 0.2, 0.4>]\n")
649 tab_write(file, "[0.640 color srgbt<1.0, 1.0, 0.2, 0.4>]\n")
650 tab_write(file, "[0.754 color srgbt<1.0, 0.5, 0.2, 0.6>]\n")
651 tab_write(file, "[0.900 color srgbt<1.0, 0.2, 0.2, 0.7>]\n")
652 tab_write(file, "[1.000 color srgbt<1.0, 0.2, 0.2, 1.0>]\n")
653 tab_write(file, "}\n")
655 # tab_write(file, "texture {%s}\n"%pov_mat_name)
656 write_object_modifiers(ob, file)
657 # tab_write(file, "rotate x*90\n")
658 # matrix = global_matrix @ ob.matrix_world
659 # write_matrix(file, matrix)
660 tab_write(file, "}\n")
661 # continue #Don't render proxy mesh, skip to next object
664 def export_smoke(file, smoke_obj_name, smoke_path, comments, global_matrix):
665 """export Blender smoke type fluids to pov media using df3 library"""
667 from .render import write_matrix, tab_write
669 flowtype = -1 # XXX todo: not used yet? should trigger emissive for fire type
670 depsgraph = bpy.context.evaluated_depsgraph_get()
671 smoke_obj = bpy.data.objects[smoke_obj_name].evaluated_get(depsgraph)
672 domain = None
673 smoke_modifier = None
674 # Search smoke domain target for smoke modifiers
675 for mod in smoke_obj.modifiers:
676 if mod.type == "FLUID":
677 if mod.fluid_type == "DOMAIN":
678 domain = smoke_obj
679 smoke_modifier = mod
681 elif mod.fluid_type == "FLOW":
682 if mod.flow_settings.flow_type == "BOTH":
683 flowtype = 2
684 elif mod.flow_settings.flow_type == "FIRE":
685 flowtype = 1
686 elif mod.flow_settings.flow_type == "SMOKE":
687 flowtype = 0
688 eps = 0.000001 # XXX not used currently. restore from corner case ... zero div?
689 if domain is not None:
690 mod_set = smoke_modifier.domain_settings
691 channeldata = []
692 for v in mod_set.density_grid:
693 channeldata.append(v.real)
694 print(v.real)
695 # -------- Usage in voxel texture:
696 # channeldata = []
697 # if channel == 'density':
698 # for v in mod_set.density_grid:
699 # channeldata.append(v.real)
701 # if channel == 'fire':
702 # for v in mod_set.flame_grid:
703 # channeldata.append(v.real)
705 resolution = mod_set.resolution_max
706 big_res = [
707 mod_set.domain_resolution[0],
708 mod_set.domain_resolution[1],
709 mod_set.domain_resolution[2],
712 if mod_set.use_noise:
713 big_res[0] = big_res[0] * (mod_set.noise_scale + 1)
714 big_res[1] = big_res[1] * (mod_set.noise_scale + 1)
715 big_res[2] = big_res[2] * (mod_set.noise_scale + 1)
716 # else:
717 # p = []
718 # -------- gather smoke domain settings
719 # BBox = domain.bound_box
720 # p.append([BBox[0][0], BBox[0][1], BBox[0][2]])
721 # p.append([BBox[6][0], BBox[6][1], BBox[6][2]])
722 # mod_set = smoke_modifier.domain_settings
723 # resolution = mod_set.resolution_max
724 # smokecache = mod_set.point_cache
725 # ret = read_cache(smokecache, mod_set.use_noise, mod_set.noise_scale + 1, flowtype)
726 # res_x = ret[0]
727 # res_y = ret[1]
728 # res_z = ret[2]
729 # density = ret[3]
730 # fire = ret[4]
732 # if res_x * res_y * res_z > 0:
733 # -------- new cache format
734 # big_res = []
735 # big_res.append(res_x)
736 # big_res.append(res_y)
737 # big_res.append(res_z)
738 # else:
739 # max = domain.dimensions[0]
740 # if (max - domain.dimensions[1]) < -eps:
741 # max = domain.dimensions[1]
743 # if (max - domain.dimensions[2]) < -eps:
744 # max = domain.dimensions[2]
746 # big_res = [int(round(resolution * domain.dimensions[0] / max, 0)),
747 # int(round(resolution * domain.dimensions[1] / max, 0)),
748 # int(round(resolution * domain.dimensions[2] / max, 0))]
750 # if mod_set.use_noise:
751 # big_res = [big_res[0] * (mod_set.noise_scale + 1),
752 # big_res[1] * (mod_set.noise_scale + 1),
753 # big_res[2] * (mod_set.noise_scale + 1)]
755 # if channel == 'density':
756 # channeldata = density
758 # if channel == 'fire':
759 # channeldata = fire
761 # sc_fr = '%s/%s/%s/%05d' % (
762 # efutil.export_path,
763 # efutil.scene_filename(),
764 # bpy.context.scene.name,
765 # bpy.context.scene.frame_current
767 # if not os.path.exists( sc_fr ):
768 # os.makedirs(sc_fr)
770 # smoke_filename = '%s.smoke' % bpy.path.clean_name(domain.name)
771 # smoke_path = '/'.join([sc_fr, smoke_filename])
773 # with open(smoke_path, 'wb') as smoke_file:
774 # # Binary densitygrid file format
776 # # File header
777 # smoke_file.write(b'SMOKE') #magic number
778 # smoke_file.write(struct.pack('<I', big_res[0]))
779 # smoke_file.write(struct.pack('<I', big_res[1]))
780 # smoke_file.write(struct.pack('<I', big_res[2]))
781 # Density data
782 # smoke_file.write(struct.pack('<%df'%len(channeldata), *channeldata))
784 # LuxLog('Binary SMOKE file written: %s' % (smoke_path))
786 # return big_res[0], big_res[1], big_res[2], channeldata
788 mydf3 = voxel_lib.df3(big_res[0], big_res[1], big_res[2])
789 sim_sizeX, sim_sizeY, sim_sizeZ = mydf3.size()
790 for x in range(sim_sizeX):
791 for y in range(sim_sizeY):
792 for z in range(sim_sizeZ):
793 mydf3.set(x, y, z, channeldata[((z * sim_sizeY + y) * sim_sizeX + x)])
794 try:
795 mydf3.exportDF3(smoke_path)
796 except ZeroDivisionError:
797 print("Show smoke simulation in 3D view before export")
798 print("Binary smoke.df3 file written in preview directory")
799 if comments:
800 file.write("\n//--Smoke--\n\n")
802 # Note: We start with a default unit cube.
803 # This is mandatory to read correctly df3 data - otherwise we could just directly use
804 # bbox coordinates from the start, and avoid scale/translate operations at the end...
805 file.write("box{<0,0,0>, <1,1,1>\n")
806 file.write(" pigment{ rgbt 1 }\n")
807 file.write(" hollow\n")
808 file.write(" interior{ //---------------------\n")
809 file.write(" media{ method 3\n")
810 file.write(" emission <1,1,1>*1\n") # 0>1 for dark smoke to white vapour
811 file.write(" scattering{ 1, // Type\n")
812 file.write(" <1,1,1>*0.1\n")
813 file.write(" } // end scattering\n")
814 file.write(' density{density_file df3 "%s"\n' % smoke_path)
815 file.write(" color_map {\n")
816 file.write(" [0.00 rgb 0]\n")
817 file.write(" [0.05 rgb 0]\n")
818 file.write(" [0.20 rgb 0.2]\n")
819 file.write(" [0.30 rgb 0.6]\n")
820 file.write(" [0.40 rgb 1]\n")
821 file.write(" [1.00 rgb 1]\n")
822 file.write(" } // end color_map\n")
823 file.write(" } // end of density\n")
824 file.write(" samples %i // higher = more precise\n" % resolution)
825 file.write(" } // end of media --------------------------\n")
826 file.write(" } // end of interior\n")
828 # START OF TRANSFORMATIONS
830 # Size to consider here are bbox dimensions (i.e. still in object space, *before* applying
831 # loc/rot/scale and other transformations (like parent stuff), aka matrix_world).
832 bbox = smoke_obj.bound_box
833 dim = [
834 abs(bbox[6][0] - bbox[0][0]),
835 abs(bbox[6][1] - bbox[0][1]),
836 abs(bbox[6][2] - bbox[0][2]),
839 # We scale our cube to get its final size and shapes but still in *object* space (same as Blender's bbox).
840 file.write("scale<%.6g,%.6g,%.6g>\n" % (dim[0], dim[1], dim[2]))
842 # We offset our cube such that (0,0,0) coordinate matches Blender's object center.
843 file.write("translate<%.6g,%.6g,%.6g>\n" % (bbox[0][0], bbox[0][1], bbox[0][2]))
845 # We apply object's transformations to get final loc/rot/size in world space!
846 # Note: we could combine the two previous transformations with this matrix directly...
847 write_matrix(file, global_matrix @ smoke_obj.matrix_world)
849 # END OF TRANSFORMATIONS
851 file.write("}\n")
853 # file.write(" interpolate 1\n")
854 # file.write(" frequency 0\n")
855 # file.write(" }\n")
856 # file.write("}\n")