forked from regcs/AliceLG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightfield_render.py
1919 lines (1363 loc) · 69 KB
/
lightfield_render.py
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ##### BEGIN GPL LICENSE BLOCK #####
#
# Copyright © 2021 Christian Stolze
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ##### END GPL LICENSE BLOCK #####
# MODULE DESCRIPTION:
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# This includes everything that is related the quilt rendering
# ------------------ INTERNAL MODULES --------------------
from .globals import *
from .ui import LookingGlassAddonSettingsWM
from .ui import LookingGlassAddonSettingsScene
# ------------------- EXTERNAL MODULES -------------------
import bpy
import time
import sys, os, platform, shutil, json
import numpy as np
from math import *
from mathutils import *
# append the add-on's path to Blender's python PATH
sys.path.insert(0, LookingGlassAddon.path)
sys.path.insert(0, LookingGlassAddon.libpath)
# TODO: Would be better, if from .lib import pylightio could be called,
# but for some reason that does not import all modules and throws
# "AliceLG.lib.pylio has no attribute 'lookingglass'"
import pylightio as pylio
# ---------------- GLOBAL ADDON LOGGER -------------------
import logging
LookingGlassAddonLogger = logging.getLogger('Alice/LG')
# ------------------ QUILT RENDERING --------------------
# a class whose instances will store the variables required to control the
# internal rendering jobs
class RenderJob:
def __init__(self, scene, animation, use_lockfile, use_multiview, blocking):
# INITIALIZE ATTRIBUTES
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# NOTE: Attributes with a leading "_" won't be saved in the lockfile
# general attributes
self.init = True
self.add_suffix = False
self.scene = scene
self.animation = animation
self._use_lockfile = use_lockfile
self.use_multiview = use_multiview
self.blocking = blocking
# render job control attributes
self._state = 'INVOKE_RENDER' # possible states: 'INVOKE_RENDER', 'INIT_RENDER', 'PRE_RENDER', 'POST_RENDER', 'COMPLETE_RENDER', 'CANCEL_RENDER''IDLE'
self.frame = 1
self.subframe = 0.0
self.view = 0
self.view_start = None
self.view_end = None
self.seed = None
self.view_width = None
self.view_height = None
self.rows = None
self.columns = None
self.total_views = None
self.quilt_aspect = None
self.view_cone = None
# path attributes
self.lockfile_path = None
self.outputpath = None
self.file_use_temp = False
self.file_temp_name = "Quilt Render Result"
self.file_dirname = None
self.file_basename = None
self.file_extension = None
self.file_quilt_suffix = None
self.file_force_keep = False
# camera attributes
self._camera_temp_basename = '_quilt_render_cam'
self._camera_temp = []
self._camera_active = None
self._camera_original = None
self._multiview_view_basename = 'quilt_v'
self._view_matrix = None
self._view_matrix_inv = None
# image attributes
self._view_image = None
self._view_images_pixels = []
self._quilt_image = None
# INITIALIZE OUTPUT PATH ATTRIBUTES
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# if a valid scene was given
if type(self.scene) == bpy.types.Scene:
# store the suffix option
self.add_suffix = self.scene.addon_settings.render_add_suffix
# store the output path in an attribute
self.outputpath = bpy.path.abspath(bpy.context.scene.render.filepath)
# try to obtain the basename of the given path
self.file_dirname, self.file_basename = os.path.split(self.outputpath)
self.file_basename, self.file_extension = os.path.splitext(self.file_basename)
# if the basename is not empty
if self.file_basename:
# if the extension shall be automatically added AND the user didn't input an extension
if self.scene.render.use_file_extension and not self.file_extension:
# add the extension
self.file_basename = bpy.path.ensure_ext(self.file_basename, bpy.context.scene.render.file_extension)
# store the filename and the extension in separate variables
self.file_basename, self.file_extension = os.path.splitext(self.file_basename)
# if the given path exists AND basename is not empty
elif not self.file_basename:
# use temporary files
self.file_use_temp = True
self.file_basename, self.file_extension = (self.file_temp_name, bpy.context.scene.render.file_extension)
# FILE PATH HANDLING
# ++++++++++++++++++++++++++++++++++
# return the filename of the quilt file
def get_quilt_suffix(self):
# metadata for HoloPlay Studio etc. is stored in the file name as a suffix
# example of the format convention: quiltfilename_qs5x9a1.6.png
if self.add_suffix:
if len(str(self.quilt_aspect)) > 3:
return f'_qs{self.columns}x{self.rows}a{self.quilt_aspect:.2f}'
else:
return f'_qs{self.columns}x{self.rows}a{self.quilt_aspect}'
else:
return ''
# return the filename of the quilt file
def quilt_filepath(self, frame=None):
# if no frame is given
if frame is None: frame = self.frame
# if an animation is rendered
if self.animation:
return os.path.join(self.file_dirname, self.file_basename + "_f" + str(frame).zfill(len(str(self.scene.frame_end))) + self.get_quilt_suffix() + self.file_extension)
# if an animation is rendered
elif not self.animation:
return os.path.join(self.file_dirname, self.file_basename + self.get_quilt_suffix() + self.file_extension)
# return the filename of the view file
def view_filepath(self, view=None, frame=None):
# if no frame is given
if view is None: view = self.view
if frame is None: frame = self.frame
# if an animation is rendered
if self.animation:
return os.path.join(self.file_dirname, self.file_basename + "_f" + str(frame).zfill(len(str(self.scene.frame_end))) + self.get_quilt_suffix() + "_v" + str(view).zfill(len(str(self.total_views - 1))) + self.file_extension)
# if an animation is rendered
elif not self.animation:
return os.path.join(self.file_dirname, self.file_basename + self.get_quilt_suffix() + "_v" + str(view).zfill(len(str(self.total_views - 1))) + self.file_extension)
# RENDER JOB HANDLING
# ++++++++++++++++++++++++++++++++++
# invoke a new render job
def invoke(self):
# if this is the first view of this render job
# NOTE: - we do it this way in case the camera is animated and its position changes each frame
if self.init:
# log debug info
LookingGlassAddonLogger.debug("Invoking new render job.")
# FRAME AND VIEW
# ++++++++++++++++++++++
# set the current frame to be rendered
self.scene.frame_set(self.frame, subframe=self.subframe)
# get the subframe, that will be rendered
self.subframe = self.scene.frame_subframe
# CYCLES: RANDOMIZE SEED
# ++++++++++++++++++++++
# NOTE: This randomizes the noise pattern from view to view.
# In theory, this enables a higher quilt quality at lower
# render sampling rates due to the overlap of views in the
# Looking Glass.
if self.scene.render.engine == "CYCLES":
# if this is the first view of the current frame
if self.view == 0:
# use the user setting as seed basis
self.seed = self.scene.cycles.seed
# if the "use_animated_seed" option is active,
if self.scene.cycles.use_animated_seed:
# increment the seed value with th frame number AND the view number
self.scene.cycles.seed = self.seed + self.frame + self.view
else:
# increment the seed value only with the view number
self.scene.cycles.seed = self.seed + self.view
# FILEPATH
# ++++++++++++++++++++++
# SINGLE-CAMERA RENDERING
if not self.use_multiview:
# set the current quilt filepath
bpy.context.scene.render.filepath = self.view_filepath()
# SINGLE-CAMERA RENDERING
elif self.use_multiview:
# set the current quilt filepath
bpy.context.scene.render.filepath = self.quilt_filepath()
# CAMERA SETUP
# ++++++++++++++++++++++
self.setup_camera()
# update status variable
self.init = False
# setup the camera (system) for rendering
def setup_camera(self):
# check, if there is an active camera marker in this frame
marker_camera_found = False
marker_cameras = [marker for marker in bpy.context.scene.timeline_markers if marker.camera is not None]
if marker_cameras:
marker = next((marker for marker, next_marker in zip(marker_cameras, marker_cameras[1:] + [None]) if marker.frame <= self.scene.frame_current and (next_marker is None or self.scene.frame_current < next_marker.frame)), None)
if marker is not None:
marker_camera_found = True
elif marker_cameras[0].frame > self.scene.frame_current:
marker = marker_cameras[0]
marker_camera_found = True
# SINGLE-CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
if not self.use_multiview:
# if this is the first view of this render job
# NOTE: - we do it this way in case the camera is animated and its position changes each frame
if self.init:
# if a marker camera was found AND the active camera synchronization is active
if marker_camera_found:
# use the marker camera
self._camera_active = marker.camera
else:
# use the camera selected by the user for the Looking Glass
self._camera_active = self.scene.addon_settings.lookingglassCamera
# remember the origingally active camera of the scene
self._camera_original = self._camera_active
# CAMERA SETTINGS: GET VIEW & PROJECTION MATRICES
# +++++++++++++++++++++++++++++++++++++++++++++++
# get camera's modelview matrix
self._view_matrix = self._camera_active.matrix_world.copy()
# correct for the camera scaling
self._view_matrix = self._view_matrix @ Matrix.Scale(1/self._camera_active.scale.x, 4, (1, 0, 0))
self._view_matrix = self._view_matrix @ Matrix.Scale(1/self._camera_active.scale.y, 4, (0, 1, 0))
self._view_matrix = self._view_matrix @ Matrix.Scale(1/self._camera_active.scale.z, 4, (0, 0, 1))
# calculate the inverted view matrix because this is what the draw_view_3D function requires
self._view_matrix_inv = self._view_matrix.inverted_safe()
# COPY CAMERA
# +++++++++++++++++++++++++++++++++++++++++++++++
# create a new, temporary camera using a copy of the
# originals camera data, if it not already exists
if not self._camera_temp: self._camera_temp.append(bpy.data.objects.new(self._camera_temp_basename, self._camera_active.data.copy()))
# use this new camera for rendering
self._camera_active = self._camera_temp[-1]
# apply location and perspective of the original camera
self._camera_active.matrix_world = self._view_matrix.copy()
# if a marker camera was found
if marker_camera_found:
# set the marker camera to this temporary camera
marker.camera = self._camera_active
# if no marker camera was found
elif not marker_camera_found:
# set the scenes active camera to this temporary camera
self.scene.camera = self._camera_active
# NOTE: In contrast to multiview rendering, linking is not
# required for single cameras. Rendering still works,
# which is nice, because the camera remains invisible.
# Leave this here for debugging purposes.
# # add this camera to the master collection of the scene
# self.scene.collection.objects.link(self._camera_active)
# CAMERA SETTINGS: APPLY POSITION AND SHIFT
# +++++++++++++++++++++++++++++++++++++++++++++++
# adjust the camera settings to the correct view point
# The field of view set by the camera
# NOTE 1: - the Looking Glass Factory documentation suggests to use a FOV of 14°. We use the focal length of the Blender camera instead.
fov = self._camera_active.data.angle
# calculate cameraSize from its distance to the focal plane and the FOV
cameraDistance = self.scene.addon_settings.focalPlane
cameraSize = cameraDistance * tan(fov / 2)
# start at view_cone * 0.5 and go up to -view_cone * 0.5
offsetAngle = (0.5 - self.view / (self.total_views - 1)) * radians(self.view_cone)
# calculate the offset that the camera should move
offset = cameraDistance * tan(offsetAngle)
# translate the camera by the calculated offset in x-direction
# NOTE: the matrix multiplications first transform the camera location into camera coordinates,
# then we apply the offset and transform back to world coordinates
self._camera_active.matrix_world = self._view_matrix @ (Matrix.Translation((-offset, 0, 0)) @ (self._view_matrix_inv @ self._camera_original.matrix_world.copy()))
# modify the projection matrix, relative to the camera size
self._camera_active.data.shift_x = self._camera_original.data.shift_x + 0.5 * offset / cameraSize
# MULTIVIEW CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
elif self.use_multiview:
# if this is the first view of this render job
# NOTE: - we do it this way in case the camera is animated and its position changes each frame
if self.init:
# set to view format to
self.scene.render.views_format = 'MULTIVIEW'
self.scene.render.image_settings.views_format = "INDIVIDUAL"
# deactivate 'left' and 'right' view
self.scene.render.views['left'].use = False
self.scene.render.views['right'].use = False
# if a marker camera was found AND the active camera synchronization is active
if marker_camera_found:
# use the marker camera
self._camera_active = marker.camera
else:
# use the camera selected by the user for the Looking Glass
self._camera_active = self.scene.addon_settings.lookingglassCamera
# remember the origingally active camera of the scene
self._camera_original = self._camera_active
# CAMERA SETTINGS: GET VIEW & PROJECTION MATRICES
# +++++++++++++++++++++++++++++++++++++++++++++++
# get camera's modelview matrix
self._view_matrix = self._camera_active.matrix_world.copy()
# correct for the camera scaling
self._view_matrix = self._view_matrix @ Matrix.Scale(1/self._camera_active.scale.x, 4, (1, 0, 0))
self._view_matrix = self._view_matrix @ Matrix.Scale(1/self._camera_active.scale.y, 4, (0, 1, 0))
self._view_matrix = self._view_matrix @ Matrix.Scale(1/self._camera_active.scale.z, 4, (0, 0, 1))
# calculate the inverted view matrix because this is what the draw_view_3D function requires
self._view_matrix_inv = self._view_matrix.inverted_safe()
# loop through all views
for view in range(self.view_start, self.view_end):
# COPY CAMERA
# +++++++++++++++++++++++++++++++++++++++++++++++
# if the cameras not already exist
if not len(self._camera_temp) == self.total_views:
# create a new, temporary camera using a copy of the original camera
self._camera_temp.append(bpy.data.objects.new(self._camera_temp_basename + "_v" + str(view).zfill(len(str(self.total_views - 1))), self._camera_active.data.copy()))
# set up view
render_view = self.scene.render.views.new(self._multiview_view_basename + str(view).zfill(len(str(self.total_views - 1))))
render_view.camera_suffix = '_v' + str(view).zfill(len(str(self.total_views - 1)))
render_view.use = True
# add this camera to the master collection of the scene
self.scene.collection.objects.link(self._camera_temp[view - self.view_start])
# use this camera for rendering
self._camera_active = self._camera_temp[view - self.view_start]
# apply same location and perspective like the original camera
self._camera_active.matrix_world = self._view_matrix.copy()
# CAMERA SETTINGS: APPLY POSITION AND SHIFT
# +++++++++++++++++++++++++++++++++++++++++++++++
# adjust the camera settings to the correct view point
# The field of view set by the camera
# NOTE 1: - the Looking Glass Factory documentation suggests to use a FOV of 14°. We use the focal length of the Blender camera instead.
fov = self._camera_active.data.angle
# calculate cameraSize from its distance to the focal plane and the FOV
cameraDistance = self.scene.addon_settings.focalPlane
cameraSize = cameraDistance * tan(fov / 2)
# start at view_cone * 0.5 and go up to -view_cone * 0.5
offsetAngle = (0.5 - view / (self.total_views - 1)) * radians(self.view_cone)
# calculate the offset that the camera should move
offset = cameraDistance * tan(offsetAngle)
# translate the camera by the calculated offset in x-direction
# NOTE: the matrix multiplications first transform the camera location into camera coordinates,
# then we apply the offset and transform back to world coordinates
self._camera_active.matrix_world = self._view_matrix @ (Matrix.Translation((-offset, 0, 0)) @ (self._view_matrix_inv @ self._camera_original.matrix_world.copy()))
# modify the projection matrix, relative to the camera size
self._camera_active.data.shift_x = self._camera_original.data.shift_x + 0.5 * offset / cameraSize
# if a marker camera was found
if marker_camera_found:
# set the marker camera and scene camera to the last temporary camera
marker.camera = self._camera_active
self.scene.camera = self._camera_active
# if no marker camera was found
elif not marker_camera_found:
# set the scenes active camera to this temporary camera
self.scene.camera = self._camera_active
# assemble quilt
def assemble_quilt(self):
LookingGlassAddonLogger.info("Assembling the quilt from the rendered views:")
# GET THE PIXEL DATA OF THE RENDERED VIEWS
# ++++++++++++++++++++++++++++++++++++++++++++
# clear the quilt pixel data for the (next) quilt
self._view_images_pixels.clear()
# iterate through all views
for view in range(0, self.total_views):
# if the file exists
if os.path.exists(self.view_filepath(view)):
LookingGlassAddonLogger.debug(" [#] Loading file for view %i: %s" % (view, self.view_filepath(view)))
# load the view image
self._view_image = bpy.data.images.load(self.view_filepath(view))
# store the pixel data in an numpy array
tmp_pixels = np.empty(len(self._view_image.pixels), np.float32)
self._view_image.pixels.foreach_get(tmp_pixels)
# append the pixel data to the list of views
self._view_images_pixels.append(tmp_pixels)
# delete the Blender image of this view
bpy.data.images.remove(self._view_image)
# if the file does not exist
else:
LookingGlassAddonLogger.debug(" [#] Could not find file for view %i: %s" % (view, self.view_filepath(view)))
LookingGlassAddonLogger.debug(" [#] Cancel render job continuation.")
# cancel the operator
self._state = "CANCEL_RENDER"
return None
LookingGlassAddonLogger.info(" [#] Loaded all views into memory.")
# ASSEMBLE THE QUILT
# ++++++++++++++++++++++++++++++++++++++++++++
# TODO: Would be good to implement the quilt assembly via pyLightIO
#
# then assemble the quilt from the views
verticalStack = []
horizontalStack = []
for row in range(0, self.rows):
for column in range(0, self.columns):
# get pixel data and reshape into a reasonable format for stacking
viewPixels = self._view_images_pixels[row * self.columns + column]
viewPixels = viewPixels.reshape((self.scene.render.resolution_y, self.scene.render.resolution_x, 4))
# append the pixel data to the current horizontal stack
horizontalStack.append(viewPixels)
# log info
LookingGlassAddonLogger.debug(" [#] Stacking view %i with shape %s." % (row * self.columns + column, viewPixels.shape))
# append the complete horizontal stack to the vertical stacks
verticalStack.append(np.hstack(horizontalStack.copy()))
# clear this horizontal stack
horizontalStack.clear()
# reshape the pixel data of all images into the quilt shape
quiltPixels = np.vstack(verticalStack.copy())
quiltPixels = np.reshape(quiltPixels, (self.columns * self.rows * (self.scene.render.resolution_x * self.scene.render.resolution_y * 4)))
# log info
LookingGlassAddonLogger.info(" [#] Assembled quilt in memory.")
# copy the viewfile
# NOTE: We use copyfile() instead of copy(), because the latter failed
# on network drives. Are there any downsides to this?
shutil.copyfile(self.view_filepath(), self.quilt_filepath())
# delete the current image data block of the quilt render result
# NOTE: This is required to prevent image data block accumulation
if bpy.data.images.find(os.path.basename(self.quilt_filepath())) != -1:
bpy.data.images.remove(bpy.data.images[os.path.basename(self.quilt_filepath())], do_unlink=True, do_id_user=True, do_ui_user=True)
elif bpy.data.images.find(self.file_temp_name) != -1:
bpy.data.images.remove(bpy.data.images[self.file_temp_name], do_unlink=True, do_id_user=True, do_ui_user=True)
# load the view image
self._quilt_image = bpy.data.images.load(filepath=self.quilt_filepath())
# log debug info
LookingGlassAddonLogger.info(" [#] Saved quilt file to: " + self._quilt_image.filepath)
# NOTE: Creating a new image via the dedicated operators and methods
# didn't apply the correct image formats and settings
# and therefore, we use the created image
self._quilt_image.scale(self.scene.render.resolution_x * self.columns, self.scene.render.resolution_y * self.rows)
# log info
LookingGlassAddonLogger.info(" [#] Reading quilt pixel data into the image data block.")
# apply the assembled quilt pixel data
self._quilt_image.pixels.foreach_set(quiltPixels)
# set "view as render" based on the image format
if self._quilt_image.file_format == 'OPEN_EXR_MULTILAYER' or self._quilt_image.file_format == 'OPEN_EXR':
self._quilt_image.use_view_as_render = True
else:
self._quilt_image.use_view_as_render = False
# save the quilt in a file
self._quilt_image.save()
# give the result image the temporary quilt file name
self._quilt_image.name = self.file_temp_name
# log info
LookingGlassAddonLogger.info(" [#] Done.")
# return the quilt image
return self._quilt_image
# delete the files
def delete_files(self, frame=None):
# for all views of the given frame
for view in range(0, self.total_views):
# delete this file, if it exists
if os.path.isfile(self.view_filepath(view, frame)):
os.remove(self.view_filepath(view, frame))
# delete the quilt file, if the user initially specified no file name
# AND this is not an animation
# NOTE: This is done, because this is Blenders behavior for normal renders
# if no filename is specifed
file_dirname, file_basename = os.path.split(self.outputpath)
if not file_basename and not self.animation:
# delete the quilt file, if it exists
if os.path.isfile(self.quilt_filepath(frame)):
os.remove(self.quilt_filepath(frame))
# clear the pixel data
self._view_images_pixels.clear()
# setup the camera system for rendering
def clean_up(self):
LookingGlassAddonLogger.info("Cleaning up camera setup.")
# if there is an active camera marker in this frame
marker_camera_found = False
marker_cameras = [marker for marker in bpy.context.scene.timeline_markers if marker.camera is not None]
if marker_cameras:
marker = next((marker for marker, next_marker in zip(marker_cameras, marker_cameras[1:] + [None]) if marker.frame <= self.scene.frame_current and (next_marker is None or self.scene.frame_current < next_marker.frame)), None)
if marker is not None:
marker_camera_found = True
# restore the original marker camera
marker.camera = self._camera_original
elif marker_cameras[0].frame > self.scene.frame_current:
marker = marker_cameras[0]
marker_camera_found = True
# restore the original marker camera
marker.camera = self._camera_original
# SINGLE-CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
if not self.use_multiview:
# if no marker camera was found
if not marker_camera_found:
# restore the original active camera
self.scene.camera = self._camera_original
# delete the temporarily created camera data block
if bpy.data.objects.find(self._camera_temp_basename) != -1:
LookingGlassAddonLogger.info(" [#] Delete temporary camera: %s" % (bpy.data.objects[self._camera_temp_basename]))
# remove the data blocks
bpy.data.cameras.remove(bpy.data.objects[self._camera_temp_basename].data, do_unlink=True, do_id_user=True, do_ui_user=True)
# clear the list
self._camera_temp.clear()
LookingGlassAddonLogger.info(" [#] Setting scene camera to the original camera: %s" % (self._camera_original))
# MULTIVIEW CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
elif self.use_multiview:
# if no marker camera was found
if not marker_camera_found:
# restore the original active camera
self.scene.camera = self._camera_original
# loop through all views
for view, camera in enumerate(self._camera_temp):
# delete the temporarily created camera data block
LookingGlassAddonLogger.info(" [#] Delete temporary camera: %s" % (camera))
bpy.data.cameras.remove(camera.data, do_unlink=True, do_id_user=True, do_ui_user=True)
# remove the corresponding temporary multiview data block
if self.scene.render.views.find(self._multiview_view_basename + str(view).zfill(len(str(self.total_views - 1)))) != -1:
LookingGlassAddonLogger.info(" [#] Delete render view: %s" % (self.scene.render.views[self._multiview_view_basename + str(view).zfill(len(str(self.total_views - 1)))]))
self.scene.render.views.remove(self.scene.render.views[self._multiview_view_basename + str(view).zfill(len(str(self.total_views - 1)))])
# clear the list
self._camera_temp.clear()
LookingGlassAddonLogger.info(" [#] Setting scene camera to the original camera: %s" % (self._camera_original))
LookingGlassAddonLogger.info(" [#] Remaining Cameras: %i" % len(self._camera_temp))
# set to view format to
self.scene.render.views_format = 'STEREO_3D'
# deactivate 'left' and 'right' view
self.scene.render.views['left'].use = True
self.scene.render.views['right'].use = True
# update the progress bar
def update_progress(self):
# SINGLE-CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
if not self.use_multiview:
# if a single frame shall be rendered
if self.animation == False:
return int(self.view / ((self.total_views - 1)) * 100)
# for animations
else:
return int(((self.frame - self.scene.frame_start) * (self.total_views - 1) + self.view) / ((self.total_views - 1) * (self.scene.frame_end - self.scene.frame_start + 1)) * 100)
# MULTIVIEW CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
elif self.use_multiview:
# if a single frame shall be rendered
if self.animation == False:
return int(self.view / ((self.total_views - 1)) * 100)
# for animations
else:
return int(((self.frame - self.scene.frame_start) * (self.total_views - 1) + self.view) / ((self.total_views - 1) * (self.scene.frame_end - self.scene.frame_start + 1)) * 100)
# CALLBACK FUNCTIONS / APPLICATION HANDLERS
# +++++++++++++++++++++++++++++++++++++++++++++++
def init_render(self, Scene, depsgraph):
# update operator state
self._state = "INIT_RENDER"
# log info
LookingGlassAddonLogger.info("Rendering job initialized. (lockfile: %s, init: %s)" % (self._use_lockfile, self.init))
# function that is called before rendering starts
def pre_render(self, Scene, depsgraph):
# update operator state
self._state = "PRE_RENDER"
# SINGLE-CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
if not self.use_multiview:
# output current status
LookingGlassAddonLogger.info("Rendering view is going to be prepared.")
LookingGlassAddonLogger.info(" [#] active camera: %s" % self._camera_active)
LookingGlassAddonLogger.info(" [#] current frame: %s" % self.frame)
LookingGlassAddonLogger.info(" [#] current subframe: %s" % self.subframe)
LookingGlassAddonLogger.info(" [#] current view: %s" % self.view)
LookingGlassAddonLogger.info(" [#] current quilt file: %s" % self.quilt_filepath())
LookingGlassAddonLogger.info(" [#] current view file: %s" % self.view_filepath())
# MULTIVIEW CAMERA RENDERING
# ++++++++++++++++++++++++++++++++++
elif self.use_multiview:
# output current status
LookingGlassAddonLogger.info("Rendering multiview is going to be prepared.")
LookingGlassAddonLogger.info(" [#] active camera: %s" % self._camera_active)
LookingGlassAddonLogger.info(" [#] current frame: %s" % self.frame)
LookingGlassAddonLogger.info(" [#] current subframe: %s" % self.subframe)
LookingGlassAddonLogger.info(" [#] current view: all (multiview)")
LookingGlassAddonLogger.info(" [#] current quilt file: %s" % self.quilt_filepath())
LookingGlassAddonLogger.info(" [#] current view file: %s" % self.view_filepath())
# function that is called after rendering finished
def post_render(self, Scene, depsgraph):
# update operator state
self._state = "POST_RENDER"
LookingGlassAddonLogger.info("Saving view file: %s" % self.view_filepath())
# save the rendered image in a file
#bpy.data.images["Render Result"].save_render(filepath=self.view_filepath(), scene=self.scene)
# function that is called when the renderjob is completed
def completed_render(self, Scene, depsgraph):
# update operator state
self._state = "COMPLETE_RENDER"
# function that is called if rendering was cancelled
def cancel_render(self, Scene, depsgraph):
# set render job state to CANCEL
self._state = "CANCEL_RENDER"
self.scene.addon_settings.render_stop = True
LookingGlassAddonLogger.info("Rendering job was cancelled.")
# a class whose instances will store Blender's RenderSettings attribute
class RenderSettings:
# currently selected device
device = None
# current quilt settings
qs = None
# scene which is rendered
scene = None
# define some specific "bpy.types.Scene" keys that need to be handled separately
specific_keys = ['eevee', 'cycles', 'cycles_curves', 'frame_start', 'frame_end', 'frame_step']
# original bpy.types.RenderSettings object reference
original = None
# scene which is rendered
use_lockfile = None
# is an animation rendered?
animation = None
# scene which is rendered
job = None
# view parameters
view_start = None
view_end = None
# initiate the class instance
def __init__(self, BlenderScene, animation, use_lockfile, use_multiview, blocking):
# get initialization parameters
self.scene = BlenderScene
self.animation = animation
self._use_lockfile = use_lockfile
self.use_multiview = use_multiview
self.blocking = blocking
# if a valid scene was given
if self.scene and type(self.scene) == bpy.types.Scene:
# COMMAND LINE ARGUMENTS
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# check if Blender is run in background mode
if LookingGlassAddon.background:
# if an output path was specified
if "-o" in LookingGlassAddon.addon_arguments or "--render-output" in LookingGlassAddon.addon_arguments:
# get the file name position
try:
index = LookingGlassAddon.addon_arguments.index("-o") + 1
except ValueError:
index = LookingGlassAddon.addon_arguments.index("--render-output") + 1
# set the file name
self.scene.render.filepath = LookingGlassAddon.addon_arguments[index]
# deactivate the "Add Metadata option"
self.scene.addon_settings.render_add_suffix = False
# if an starting frame was specified
if "-s" in LookingGlassAddon.addon_arguments or "--frame-start" in LookingGlassAddon.addon_arguments:
# get the file name position
try:
index = LookingGlassAddon.addon_arguments.index("-s") + 1
except ValueError:
index = LookingGlassAddon.addon_arguments.index("--frame-start") + 1
# set the frame start
self.scene.frame_start = int(LookingGlassAddon.addon_arguments[index])
# if an end frame was specified
if "-e" in LookingGlassAddon.addon_arguments or "--frame-end" in LookingGlassAddon.addon_arguments:
# get the file name position
try:
index = LookingGlassAddon.addon_arguments.index("-e") + 1
except ValueError:
index = LookingGlassAddon.addon_arguments.index("--frame-end") + 1
# set the end frame
self.scene.frame_end = int(LookingGlassAddon.addon_arguments[index])
# if a frame step was specified
if "-j" in LookingGlassAddon.addon_arguments or "--frame-jump" in LookingGlassAddon.addon_arguments:
# get the file name position
try:
index = LookingGlassAddon.addon_arguments.index("-j") + 1
except ValueError:
index = LookingGlassAddon.addon_arguments.index("--frame-jump") + 1
# set the frame step
self.scene.frame_step = int(LookingGlassAddon.addon_arguments[index])
# if a rendering frame was specified
if "-f" in LookingGlassAddon.addon_arguments or "--render-frame" in LookingGlassAddon.addon_arguments:
# get the file name position
try:
index = LookingGlassAddon.addon_arguments.index("-f") + 1
except ValueError:
index = LookingGlassAddon.addon_arguments.index("--render-frame") + 1
# if a relative frame number is given
if LookingGlassAddon.addon_arguments[index][0] == "+":
# set the current frame
self.scene.frame_current += int(LookingGlassAddon.addon_arguments[index])
# if a relative frame number is given
elif LookingGlassAddon.addon_arguments[index][0] == "-":
# set the current frame
self.scene.frame_current += int(LookingGlassAddon.addon_arguments[index])
else:
# set the current frame
self.scene.frame_current = int(LookingGlassAddon.addon_arguments[index])
# if a rendering frame was specified
if "-v" in LookingGlassAddon.addon_arguments or "--render-view" in LookingGlassAddon.addon_arguments:
# get the view index
try:
index = LookingGlassAddon.addon_arguments.index("-v") + 1
except ValueError:
index = LookingGlassAddon.addon_arguments.index("--render-view") + 1
# set the current frame
self.view_start = int(LookingGlassAddon.addon_arguments[index])
self.view_end = int(LookingGlassAddon.addon_arguments[index]) + 1
# set the view range start
if "--view-range" in LookingGlassAddon.addon_arguments:
# get the view index
index = LookingGlassAddon.addon_arguments.index("--view-range") + 1
# set the view range start
self.view_start = int(LookingGlassAddon.addon_arguments[index])
# set the current frame
self.view_end = int(LookingGlassAddon.addon_arguments[index + 1]) + 1
# INITIALIZATION
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# make an internal variable for the add-on settings,
# which can be accessed from methods that have no "context" parameter
self.addon_settings = self.scene.addon_settings
# initialize the rendering job variables
self.job = RenderJob(self.scene, self.animation, self._use_lockfile, self.use_multiview, self.blocking)
# copy the attributes of the original bpy.types.RenderSettings object
for key in dir(self.scene.render):
# if the attribute is one of the following types: bool, int, float, str, list, dict
if not "__" in key and isinstance(getattr(self.scene.render, key), (bool, int, float, str, list, dict)):
setattr(self, key, getattr(self.scene.render, key))
# SPECIFIC SCENE SETTINGS
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# NOTE: These are specific keys that are not inside the bpy.types.RenderSettings
# object, but in the bpy.types.Scene object and which are relevant
# for the rendering process
for key in dir(self.scene):
# if the attribute is one of the following types: bool, int, float, str, list, dict
if key in self.specific_keys:
setattr(self, key, getattr(self.scene, key))
# DEVICE SETTINGS
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# get active Looking Glass
if not self.blocking and (self.addon_settings.render_use_device == True and pylio.DeviceManager.get_active()):
self._device = pylio.DeviceManager.get_active()
self._quilt_preset = self.addon_settings.quiltPreset
# or the selected emulated device
elif self.blocking or self.addon_settings.render_use_device == False:
self._device = pylio.DeviceManager.get_device(key="index", value=int(self.addon_settings.render_device_type))
self._quilt_preset = self.addon_settings.render_quilt_preset
# get all quilt presets from pylio
self._qs = pylio.LookingGlassQuilt.formats.get()
# set view range to default if None was given
if self.view_start is None: self.view_start = 0
if self.view_end is None: self.view_end = self._qs[int(self._quilt_preset)]["total_views"]
# PATH SETTINGS
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++