forked from ldo/render-useful
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender-batch
More file actions
executable file
·605 lines (582 loc) · 21.2 KB
/
render-batch
File metadata and controls
executable file
·605 lines (582 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
#!/bin/bash
#+
# This script invokes Blender to render the specified .blend file. It
# allows the specification of various rendering settings directly from
# the command line, overriding settings from the .blend file. It also
# has the option for stereoscopic rendering, by doing the render twice,
# offsetting the camera along its local X axis, and combining the
# resulting images to produce a stereo pair. Besides Blender, it also
# needs the Qahirah wrapper <https://github.com/ldo/qahirah> for the
# Cairo graphics library. Invoke it as follows:
#
# render-batch [options...] blendfile
#
# where the options are
#
# --animation
# specifies that an animation sequence is to be rendered.
# If omitted, a single frame is rendered.
# --arrange=[across]|down[:n]
# specifies how the images are to be arranged, if multiple
# cameras are specified: across (the default) or down. The
# optional n specifies how many images are to fit in one
# row (if across) or column (if down).
# --blender=blender
# specifies the path to the Blender executable. Defaults to
# searching for the name “blender” in your PATH.
# --camera=camera
# specifies the name of the camera to use. May be specified
# more than once, to render images from multiple cameras
# across or down (depending on --arrange).
# --preexec=script
# executes the specified Python code prior to the rendering.
# --existing=error|overwrite|skip
# specifies what to do if an output image file already exists:
# error -- signal an error and abort the render
# overwrite -- overwrite the output file
# skip -- skip rendering this frame. If rendering an
# animation, the rendering continues with any
# remaining frames.
# If omitted, the default is error.
# --frame=framenr
# --frames=[[start],[end][,step]]
# specifies the frame number (if a single frame) or frame
# range (if an animation) to be rendered.
# --stereo=offset
# specifies that a stereoscopic image is to be rendered.
# offset is the distance in BU to offset the camera to each
# side from its initial position to generate the image for
# each eye. If omitted, a single image is rendered.
# --out=dest
# the name to give the output PNG file if rendering a single
# frame, or the name of the directory into which to save the
# numbered frames for an animation. Must be specified when
# rendering an animation. If omitted for a single frame,
# defaults to the basename of the input blend file with
# “.png” appended, saved in the current directory.
# --percent=percent
# specifies the percentage of the render size at which to
# generate the images. If omitted, the default is 100 if
# --resolution is specified, otherwise the default is
# the setting in the .blend file.
# --resolution=width:height
# specifies the dimensions in pixels of each rendered image.
# --rotate=angle
# rotates the images by the specified angle in
# degrees (which must be a whole multiple of 90).
# --samples=samples
# the number of samples per pixel (Cycles renderer only).
# --scene=scene
# specifies the scene to render.
#
# Unless otherwise specified, omitted options default to the
# values saved in the blend file.
#
# For stereoscopic rendering, the output file will contain the
# two eye images side-by-side, the image for the right eye on
# the left and vice versa, for viewing as “cross-eyed” stereo.
#
# Copyright 2013-2015 by Lawrence D'Oliveiro <ldo@geek-central.gen.nz>.
# Licensed under CC-BY-SA <http://creativecommons.org/licenses/by-sa/4.0/>.
#-
opterror()
{
echo "$0: $1" 1>&2
exit 3
} # opterror
blender=blender
nr_cameras=0
arrange=
scene=
samples=
stereo_offset=
digits=4
render_percentage=
render_width=
render_height=
rotate=
out=
existing=error
animation=
crossed=
preexec=
for ((;;)); do
if [ "${1:0:2}" != "--" ]; then
break
fi
opt="${1:2:${#1}}"
shift
val="${opt#*=}"
opt="${opt%%=*}"
if [ "$opt" = "animation" ]; then
animation=1
elif [ "$opt" = "arrange" ]; then
val1="${val%%:*}"
if [ "$val1" != "$val" ]; then
val2="${val#*:}"
else
val2=""
fi
if [ "$val1" != "across" -a "$val1" != "down" ]; then
opterror "--arrange type must be “across” or “down”"
fi
if [[ "$val2" = *[^0-9]* ]]; then
opterror "--arrange value must be integer"
fi
arrange="$val"
elif [ "$opt" = "blender" ]; then
blender="$val"
elif [ "$opt" = "camera" ]; then
nr_cameras=$((nr_cameras + 1))
export RENDER_camera_${nr_cameras}="$val"
elif [ "$opt" = "crossed" ]; then
crossed=1
elif [ "$opt" = "digits" ]; then
digits="$val"
elif [ "$opt" = "existing" ]; then
if [ "$val" != "error" -a "$val" != "overwrite" -a "$val" != "skip" ]; then
opterror "--existing value must be “error”, “overwrite” or “skip”"
fi
existing="$val"
elif [ "$opt" = "frame" -o "$opt" = "frames" ]; then
frame_spec="$val"
elif [ "$opt" = "out" ]; then
out="$val"
elif [ "$opt" = "percent" ]; then
render_percentage="$val"
elif [ "$opt" = "preexec" ]; then
preexec="$val"
elif [ "$opt" = "resolution" ]; then
IFS=':' read -a items <<<"$val"
render_width="${items[0]}"
render_height="${items[1]}"
if [ -z "$render_percentage" ]; then
render_percentage=100
fi
elif [ "$opt" = "rotate" ]; then
if [ $(($val % 90)) != 0 ]; then
opterror "--rotate value must be multiple of 90"
fi
rotate=$(($val / 90))
elif [ "$opt" = "samples" ]; then
samples="$val"
elif [ "$opt" = "scene" ]; then
scene="$val"
elif [ "$opt" = "stereo" ]; then
stereo_offset="$val"
else
opterror "bad option $opt"
fi
done
if [ -z "$(type -p "$blender")" ]; then
opterror "no such executable “$blender”"
fi
if [ $# != 1 ]; then
opterror $'Usage:\n\t'"$0 "$'<blendfile>'
fi
blendfile="$1"
if [ -n "$stereo_offset" -a $nr_cameras -gt 1 ]; then
opterror "cannot specify --stereo with more than one --camera"
fi
if [ $nr_cameras -ne 0 ]; then
unset RENDER_camera_$((nr_cameras + 1)) # just in case
fi
# pass parameters to Python script in environment variables to avoid
# problems with special characters
export RENDER_stereo_offset="$stereo_offset"
if [ $animation ]; then
if [ -z "$out" -o ! -d "$out" ]; then
opterror "must specify --out directory for animation frames"
fi
IFS=',' read -a frame_spec <<<"$frame_spec"
export RENDER_frame_start="${frame_spec[0]}"
export RENDER_frame_end="${frame_spec[1]}"
export RENDER_frame_step="${frame_spec[2]}"
echo "frames from $RENDER_frame_start to $RENDER_frame_end via $RENDER_frame_step" # debug
else
export RENDER_frame_start="$frame_spec"
fi
export RENDER_animation="$animation"
if [ -n "$out" ]; then
RENDER_out="$out"
else
RENDER_out="${blendfile##*/}"
RENDER_out="${RENDER_out%%.*}.png"
fi
export RENDER_out
export RENDER_arrange="$arrange"
export RENDER_existing="$existing"
export RENDER_scene="$scene"
export RENDER_samples="$samples"
export RENDER_percentage="$render_percentage"
export RENDER_width="$render_width"
export RENDER_height="$render_height"
export RENDER_rotate="$rotate"
export RENDER_preexec="$preexec"
export RENDER_crossed="$crossed"
export RENDER_digits="$digits"
exec "$blender" -b "$blendfile" -P <(cat <<'EOD'
import sys
import os
import time
import tempfile
import bpy
import mathutils
import qahirah as qah
from qahirah import \
CAIRO, \
Colour, \
Rect, \
Vector
os.wait() # gobble zombie child of shell which was previously in this process slot
#+
# Useful stuff
#-
units = \
( # sequence of quadruples, first element is multiplier to apply to
# previous quadruple, or nr of seconds for first quadruple, second
# element is abbreviated unit name, third element is singular unit
# name, fourth element is plural unit name.
(1, "s", "second", "seconds"),
(60, "m", "minute", "minutes"),
(60, "h", "hour", "hours"),
(24, "d", "day", "days"),
(7, "wk", "week", "weeks"),
)
def format_elapsed(interval, long_form = False, seconds_places = 0) :
"returns an accurate indication of the specified interval in seconds." \
" long_form indicates whether to display the units in long form or short form," \
" while seconds_places indicates the number of decimal places to use for showing" \
" the seconds."
unitindex = 0
result = ""
while True :
if unitindex == len(units) :
break
unit = units[unitindex]
if unitindex + 1 < len(units) :
factor = units[unitindex + 1][0]
place = interval % factor
else :
factor = None
place = interval
#end if
if unitindex == 0 :
format = "%%.%df" % seconds_places
else :
format = "%d"
#end if
place = format % place + (unit[1], " " + unit[2:4][place != 1])[long_form]
result = place + ("", (" ", (", ", " and " )[unitindex == 1])[long_form])[unitindex > 0] + result
if factor == None :
break
interval //= factor
if interval == 0 :
break
unitindex += 1
#end while
return \
result
#end format_elapsed
class DummyTempDir :
"a replacement for tempfile.TemporaryDirectory for when I\n" \
"don’t actually need a temp directory."
def __init__(self) :
pass
#end __init__
def __enter__(self) :
return "dummy" # got to return something usable as part of a pathname
#end __enter__
def __exit__(self, exception_type, exception_value, traceback) :
pass
#end __exit__
#end DummyTempDir
#+
# Mainline
#-
def get_optional_env(varname, convert = None) :
# returns the value of the specified environment variable, converted
# by applying the convert function if specified; returns None if
# the value of the variable was not specified or empty.
val = os.getenv(varname, "")
if val != "" :
if convert != None :
val = convert(val)
#end if
else :
val = None
#end if
return \
val
#end get_optional_env
def get_image_from_png(filename) :
# loads the contents of a PNG file as an ImageSurface, applying any
# appropriate rotation.
image = qah.ImageSurface.create_from_png(filename)
if rotate != 0 :
image_format = image.format
src_dimensions = image.dimensions
if rotate & 1 != 0 :
dst_dimensions = Vector(src_dimensions.y, src_dimensions.x)
else :
dst_dimensions = src_dimensions
#end if
rotate_point = \
Vector \
(
x = (src_dimensions.y, src_dimensions.x, src_dimensions.x)[rotate - 1],
y = (src_dimensions.y, src_dimensions.y, src_dimensions.x)[rotate - 1],
)
src = \
(qah.Pattern.create_for_surface(image)
.set_matrix(qah.Matrix.rotate(- rotate / 4 * qah.circle, rotate_point / 2))
)
image = qah.ImageSurface.create \
(
format = image_format,
dimensions = dst_dimensions
)
(qah.Context.create(image)
.set_source(src)
.paint()
)
image.flush()
#end if
return \
image
#end get_image_from_png
stereo_offset = get_optional_env("RENDER_stereo_offset", float)
render_percentage = get_optional_env("RENDER_percentage", int)
render_width = get_optional_env("RENDER_width", int)
render_height = get_optional_env("RENDER_height", int)
rotate = get_optional_env("RENDER_rotate", int)
if rotate != None :
rotate %= 4
else :
rotate = 0
#end if
animation = os.getenv("RENDER_animation", "") != ""
preexec = get_optional_env("RENDER_preexec")
crossed = os.getenv("RENDER_crossed", "") != ""
digits = int(os.getenv("RENDER_digits"))
render_out = os.getenv("RENDER_out")
existing_action = os.getenv("RENDER_existing")
frame_start = get_optional_env("RENDER_frame_start", int)
frame_end = get_optional_env("RENDER_frame_end", int)
frame_step = get_optional_env("RENDER_frame_step", int)
render_samples = get_optional_env("RENDER_samples", int)
scene_name = get_optional_env("RENDER_scene")
camera_names = []
i = 0
while True :
i += 1
camera_name = get_optional_env("RENDER_camera_%d" % i)
if camera_name == None :
break
camera_names.append(camera_name)
#end while
arrange = get_optional_env("RENDER_arrange")
arrange_limit = None
if arrange != None :
arrange = arrange.split(":")
if len(arrange) > 1 :
arrange, arrange_limit = arrange
arrange_limit = int(arrange_limit)
else :
arrange = arrange[0]
#end if
#end if
need_tempfile = len(camera_names) > 1 or stereo_offset != None or rotate != 0
with (DummyTempDir, tempfile.TemporaryDirectory)[need_tempfile]() as tempdir :
temp_image_names = None
if len(camera_names) > 1 :
temp_image_names = tuple("camera_%d" % (i + 1) for i in range(len(camera_names)))
elif stereo_offset != None :
temp_image_names = ("left", "right")
elif rotate != 0 :
temp_image_names = ("unrotated",)
#end if
if temp_image_names != None :
temp_image_names = tuple(os.path.join(tempdir, name) + ".png" for name in temp_image_names)
#end if
if scene_name != None :
bpy.context.screen.scene = bpy.data.scenes[scene_name]
#end if
if len(camera_names) == 1 :
bpy.context.scene.camera = bpy.data.objects[camera_names[0]]
#end if
if (
render_samples != None
and
hasattr(bpy.context.scene, "cycles")
and
bpy.context.scene.render.engine == "CYCLES"
) :
bpy.context.scene.cycles.samples = render_samples
#end if
active_scene = bpy.context.scene
active_camera = active_scene.camera
orig_camera_matrix = active_camera.matrix_basis.copy()
if frame_start == None :
frame_start = (active_scene.frame_current, active_scene.frame_start)[animation]
#end if
if animation :
if frame_end == None :
frame_end = active_scene.frame_end
#end if
if frame_step == None :
frame_step = active_scene.frame_step
#end if
else :
frame_end = frame_start
frame_step = 1
#end if
frame_end += 1 # make it exclusive
if render_percentage != None :
active_scene.render.resolution_percentage = render_percentage
#end if
if render_width != None :
active_scene.render.resolution_x = render_width
#end if
if render_height != None :
active_scene.render.resolution_y = render_height
#end if
active_scene.render.image_settings.file_format = "PNG"
compose_offset = None
if preexec != None :
exec(preexec)
#end if
start_time = time.time()
frames_done = 0
for frame_nr in range(frame_start, frame_end, frame_step) :
active_scene.frame_set(frame_nr)
if animation :
out_image_name = os.path.join(render_out, "%%0%dd.png" % digits % frame_nr)
else :
out_image_name = render_out
#end if
if existing_action == "overwrite" or not os.path.exists(out_image_name) :
if len(camera_names) > 1 :
for i in range(len(camera_names)) :
bpy.context.scene.camera = bpy.data.objects[camera_names[i]]
active_scene.render.filepath = temp_image_names[i]
bpy.ops.render.render(write_still = True)
#end for
for i in range(len(temp_image_names)) :
image = get_image_from_png(temp_image_names[i])
if i == 0 :
image_dimensions = image.dimensions
compose_step = Vector \
(
(0, 1)[arrange == "across"],
(0, 1)[arrange == "down"]
)
if arrange_limit != None and arrange_limit < len(temp_image_names) :
compose_step_2 = Vector(compose_step.y, compose_step.x)
composite_steps = \
(
compose_step * arrange_limit
+
compose_step_2
*
((len(temp_image_names) + arrange_limit - 1) // arrange_limit)
)
else :
compose_step_2 = None
composite_steps = Vector(1, 1) + compose_step * (len(temp_image_names) - 1)
#end if
concat = qah.ImageSurface.create \
(
format = CAIRO.FORMAT_RGB24,
dimensions = image_dimensions * composite_steps
)
compose = \
(qah.Context.create(concat)
.set_operator(CAIRO.OPERATOR_SOURCE)
.set_source_colour(Colour.grey(0, 0))
.paint()
)
#end if
if compose_step_2 != None :
compose_pos = \
(
image_dimensions
*
(
compose_step * (i % arrange_limit)
+
compose_step_2 * (i // arrange_limit)
)
)
else :
compose_pos = image_dimensions * compose_step * i
#end if
compose.set_source_surface(image, compose_pos)
compose.rectangle(Rect.from_dimensions(image_dimensions) + compose_pos)
compose.fill()
#end for
concat.flush()
concat.write_to_png(out_image_name)
elif stereo_offset != None :
for sign in (-1, +1) : # left eye, then right eye
active_scene.render.filepath = temp_image_names[sign > 0]
active_camera.matrix_basis = \
(
orig_camera_matrix
*
mathutils.Matrix.Translation(mathutils.Vector((sign * stereo_offset, 0, 0)))
)
bpy.ops.render.render(write_still = True)
#end for
left_eye = get_image_from_png(temp_image_names[0])
right_eye = get_image_from_png(temp_image_names[1])
if crossed :
left_eye, right_eye = right_eye, left_eye
#end if
if compose_offset == None :
compose_offset = left_eye.width
image_height = left_eye.height
#end if
stereo = qah.ImageSurface.create \
(
format = CAIRO.FORMAT_RGB24,
dimensions = (compose_offset * 2, image_height)
)
(qah.Context.create(stereo)
.set_operator(CAIRO.OPERATOR_SOURCE)
.set_source_colour(Colour.grey(0, 0))
.paint()
.set_source_surface(right_eye, (0, 0))
.rectangle(Rect(0, 0, compose_offset, image_height))
.fill()
.set_source_surface(left_eye, (compose_offset, 0))
.rectangle(Rect(compose_offset, 0, compose_offset, image_height))
.fill()
)
stereo.flush()
stereo.write_to_png(out_image_name)
elif rotate != 0 :
active_scene.render.filepath = temp_image_names[0]
bpy.ops.render.render(write_still = True)
get_image_from_png(temp_image_names[0]).write_to_png(out_image_name)
else :
active_scene.render.filepath = out_image_name
bpy.ops.render.render(write_still = True)
#end if
frames_done += 1
elif existing_action == "skip" :
sys.stdout.write("Skipped %s\n" % out_image_name)
else :
raise RuntimeError("Output image “%s” already exists" % out_image_name)
#end if
#end for
now = time.time()
sys.stdout.write \
(
"Rendered %d %s in %s\n"
%
(frames_done, ("frame", "frames")[frames_done != 1], format_elapsed(now - start_time))
)
#end with
EOD
)