-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommunity_render.py
2428 lines (1996 loc) · 85.3 KB
/
community_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 #####
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
"""Community Render Add-on for taking user inputs and standardizing outputs.
Used to quickly and dynamically load multiple blend files, transform into a
standardized state, and help render them out to files.
Tool for preparing multiple blend files for rendering out in standard way. The
idea is the users (or 'authors') have submitted blend files through e.g. a
Google Form. Each blend file is loaded into a separately prepared template file
(template assigns render settings and lighting), some prep work done to
standardize the pulled in file, and then render it out to disk.
Some key factors for how this addon works:
- Blend files are assumed to have a single scene.
- This single scene is loaded in and instanced as an empty.
- The addon then "processes" the scene based on whatever is fit for the project
(such as centering and selecting the intended object, clearing animations,
fixing broken material links with default materials, and resizing to fit the
render).
- Addon keeps tracks and can output the overall metadata status of the renders
created (e.g. to keep track of what ended up being included).
"""
import csv
from difflib import SequenceMatcher as SM
import os
import random
import time
from typing import Any, Dict, Optional, Sequence, Tuple
from bpy.app.handlers import persistent
import mathutils
import bpy
bl_info = {
"name": "Community Render",
"author": "Patrick W. Crawford",
"version": (2, 1),
"blender": (2, 90, 0),
"location": "Properties > Scene > Community Render",
"description": "Help load, transform, and render many blend files",
"warning": "",
"doc_url": "",
"category": "Render",
}
CSV_META_PATH = "//csv_metadata.csv"
CSV_OUTPUT = "//csv_output.csv"
# Label of the the project, used in some places such as the panel.
PROJECT_NAME = "Community Render"
# This is name of the collection in the master template to clear and load in
# scenes; this is NOT meant to be a collection name in each user's submitted
# files, there is no dependency on user-submitted naming convention.
LOCAL_COLLECTION_NAME = "load_scene"
# Text objects to update based on user loaded blend.
# Note: For maximum inclusive output, set up the source template with UTF8
# fonts to support special characters. Blender will not throw errors, but
# display boxes, if it cannot render certain characters.
AUTHOR_TEXT_OBJ = "author_text"
COUNTRY_TEXT_OBJ = "country_text"
# Image (next to render template) to use for any material has missing images.
REPLACEMENT_IMAGE = "default_texture.png"
# Enum value names for reuse.
READY = "ready"
DONE = "done"
SKIP = "skip"
NOT_QUEUED = "not_queued"
# Used to temporarily save render samples before thumbnail render.
PRIOR_RENDER = ()
# Stats used in UI, cached to avoid slow draws + enums.
scene_stats = {}
NON_BLEND = "non_blend"
BLEND_COUNT = "blends"
RENDERED = "rendered"
NUM_QC_ERR = "num_qc_error"
NO_FORM_MATCH = "no_form_match"
# Flag to skip the finish render handler, after doing the thumbnail render.
_MID_RENDER = False
# Time in s that the current render started.
_RENDER_START = 0
# Number of renders completed this session.
_RENDER_COUNT = 0
# Used to avoid repeat calls to OS filesystem, which can be quite slow if
# using a fuse system. Assumed to use and clear immediately around loop, not
# for keeping long term cache of file precense.
_EXISTING_FILE_CACHE = []
# Listing of qc errors that exist across all files, pre-split.
_QC_ERROR_LIST_CACHE = []
# Selected object to center on, cached from load for specific uses on render.
_CENTRAL_OBJ = None
# Cache for the form data itself, since used multiple times.
_FORM_DATA = {}
# Reusable error names, if used more than once
ERR_NOT_LATEST_ENTRY = "Not the latest entry for this email"
ERR_CRASHED = "crashed"
ERR_SKIP = "skip"
ERR_NO_FORM_ID = "No form id match"
# -----------------------------------------------------------------------------
# General utilities
# -----------------------------------------------------------------------------
def generate_context_override(obj_list: Sequence[bpy.types.Object] = None
) -> Dict[str, Any]:
"""Generate a custom override with custom object list."""
if obj_list is None:
obj_list = [ob for ob in bpy.context.view_layer.objects
if ob.select_get()]
for window in bpy.context.window_manager.windows:
screen = window.screen
for area in screen.areas:
if area.type == 'VIEW_3D':
override = {
'window': window,
'screen': screen,
'area': area,
'selected_objects': obj_list,
}
break
return override
def disable_auto_py(context) -> None:
"""Security measure to ensure auto-run python scripts is turned off."""
prefs = context.preferences
prefs.filepaths.use_scripts_auto_execute = False
# Alt, less wide-reaching option: Add the current blends path to exclusion:
# ind = len(prefs.autoexec_paths)
# preferences.autoexec_path_add(index=...)
def format_seconds(seconds: float) -> str:
"""Take in seconds, return HH:MM:SS format."""
hours = int(seconds // 3600)
remain = seconds % 3600
sec = int(remain % 60)
minutes = int(remain // 60)
return f"{hours:02d}:{minutes:02d}:{sec:02d}"
def cache_os_paths(context) -> Sequence[str]:
"""Returns a list of absolute paths for all files in particular folders.
This is memory intensive (especially being absolute paths), but faster.
"""
global _EXISTING_FILE_CACHE
cache_paths = ["qc_errors", "render_full", "render_small"]
ext = ['.txt', '.png', '.jpg', '.jpeg']
props = context.scene.crp_props
for path in cache_paths:
sub = os.path.join(bpy.path.abspath(props.config_folder), path)
if not os.path.isdir(sub):
continue
print("\tCaching folder", sub)
files = [os.path.join(sub, this) for this in os.listdir(sub)
if os.path.isfile(os.path.join(sub, this))
and os.path.splitext(this.lower())[-1] in ext]
_EXISTING_FILE_CACHE.extend(files)
# -----------------------------------------------------------------------------
# Main process functions, used within operators
# -----------------------------------------------------------------------------
def get_responses_path(context) -> str:
"""Return the path for the expected TSV file."""
default_name = "form_responses.tsv"
props = context.scene.crp_props
return bpy.path.abspath(os.path.join(props.config_folder, default_name))
def get_blend_file_list(context) -> Sequence[str]:
abs_path = bpy.path.abspath(context.scene.crp_props.source_folder)
dirname = os.path.dirname(abs_path)
if not dirname:
print("Target path is blank, no blends to load")
return []
if not os.path.isdir(dirname):
print(f"Target folder does not exist: {dirname}")
return []
files = [blend for blend in os.listdir(dirname)
if os.path.isfile(os.path.join(dirname, blend))
and blend.lower().endswith(".blend")]
count_all = len([blend for blend in os.listdir(dirname)
if os.path.isfile(os.path.join(dirname, blend))])
# Update global stats
scene_stats[NON_BLEND] = count_all - len(files)
return sorted(files)
def qc_error_path(context, src_blend: str) -> str:
"""Return a the path for a given blend file's qc_error file."""
props = context.scene.crp_props
subpath = os.path.join(bpy.path.abspath(props.config_folder), "qc_errors")
if not os.path.isdir(subpath):
os.mkdir(subpath)
path = os.path.join(subpath, f"{src_blend}.txt")
return path
def read_qc_error(src_blend, context) -> Optional[str]:
"""Read the QC error text if any has been saved to disk."""
path = qc_error_path(context, src_blend)
lines = ""
# Exit early if cache is set and not populated.
if _EXISTING_FILE_CACHE and path not in _EXISTING_FILE_CACHE:
return lines
# Otherwise, load the file.
if os.path.isfile(path):
with open(path, 'r') as fd:
lines = fd.read()
return lines
def save_qc_error(self, context) -> None:
"""Save out error as txt, not overwriting if one exists already."""
path = qc_error_path(context, self.src_blend)
if self.qc_error and not os.path.isfile(path):
print(f"To save QC error: {path}")
with open(path, 'w') as fd:
fd.write(self.qc_error)
def get_all_qc_errors(context) -> Sequence[str]:
"""Pull any and all QC errors, for use in dropdown filters."""
global _QC_ERROR_LIST_CACHE
if _QC_ERROR_LIST_CACHE:
return _QC_ERROR_LIST_CACHE
props = context.scene.crp_props
qc_dir = os.path.join(bpy.path.abspath(props.config_folder), "qc_errors")
results = []
for subpath in os.listdir(qc_dir):
if not subpath.lower().endswith(".txt"):
continue
with open(os.path.join(qc_dir, subpath), 'r') as fd:
lines = fd.read()
qc_errors = lines.split(";")
for err in qc_errors:
base_name = err.split(":")[0] # Chop off e.g. :2 for counts.
if base_name not in results:
results.append(base_name)
_QC_ERROR_LIST_CACHE = results
return results
def get_crash_cache_path(context) -> str:
"""Return the path used for saving cache output."""
cache_name = "crash_cache_blend.txt"
props = context.scene.crp_props
return bpy.path.abspath(os.path.join(props.config_folder, cache_name))
def load_crash_cache(context) -> None:
"""Check if a blend file's crash cache file is still present.
We assume that if this blend file exists at the time this function runs,
it means that it had crashed the prior time.
"""
print("Checking for crash cache")
path = get_crash_cache_path(context)
if not os.path.isfile(path):
return
with open(path, 'r') as fd:
crashed_blend = fd.read()
clear_blend_crash_cach(context)
props = context.scene.crp_props
applied = False
for row in props.file_list:
if row.src_blend != crashed_blend:
continue
extend_qc_error(row, ERR_CRASHED, increment=True)
print("Detected a crash! Applied QC error to " + row.src_blend)
applied = True
break
if not applied:
print("Detected crash! **But QC lookup failed** " + crashed_blend)
def save_blend_to_crash_cache(context) -> None:
"""Save a target blend file to a cache file to detect crashing."""
# Idnetify and process any cache before applying the new cache.
load_crash_cache(context)
props = context.scene.crp_props
this_row = props.file_list[props.file_list_index]
with open(get_crash_cache_path(context), 'w') as fd:
fd.write(this_row.src_blend)
print("\tSaved crash cache")
def clear_blend_crash_cach(context) -> None:
"""Remove the blend cache file, either on success or next run."""
try:
os.remove(get_crash_cache_path(context))
# pass
except OSError:
pass
def load_active_row(context) -> None:
"""Load the active row's input."""
print("")
print("Processing row to load:")
load_active_selection(context) # First, replace the loaded collection.
process_open_file(context) # Now run the process function
update_scene_stats(context) # QC may have updated
# Reduce effect of memory leak over time, since we don't outright
# delete references (since it was causing crashing/instability).
# bpy.ops.outliner.orphans_purge()
# Nope, this too can cause crashes. Plus it didn't save memory ultimately.
def load_active_selection(context) -> None:
"""Load the selection referenced in the UI list."""
disable_auto_py(context)
props = context.scene.crp_props
blend = props.file_list[props.file_list_index].src_blend
full_file = os.path.join(props.source_folder, blend)
abs_path = bpy.path.abspath(full_file)
if not os.path.isfile(abs_path):
raise RuntimeError("Blend file not found: " + blend)
print(f"Preparing to load: {blend}")
prior_scenes = bpy.data.scenes[:]
with bpy.data.libraries.load(abs_path, link=True) as (data_from, data_to):
# Ensure only loading the first scene
load_scn = data_from.scenes[0]
data_to.scenes = [load_scn]
current_scenes = bpy.data.scenes[:]
new_scene_list = list(set(current_scenes) - set(prior_scenes))
if not new_scene_list:
raise Exception("Could not fetch loaded scene, maybe non loaded.")
new_scene = new_scene_list[0]
new_scene.name = blend
# If scene was previously loaded, reset transform (doubles load time). This
# ensures that "load original" will work even after loading with process
# occurred once.
# Note: While technically better behavior, this actually causes crashing.
# if props.load_original:
# new_scene.library.reload()
obj = replace_view_layer(context, new_scene)
context.view_layer.objects.active = obj
obj.select_set(True)
row = props.file_list[props.file_list_index]
obj.name = row.label
update_use_text(None, context)
print(f"Loaded {blend}:{new_scene.name} into object {obj.name}")
def remove_object(context, obj: bpy.types.Object) -> None:
"""Unlink an object from the scene, and remove from data."""
print(f" > Removing object: {obj.name}")
try:
context.scene.collection.objects.unlink(obj)
except RuntimeError:
pass # if not in master collection
colls = list(obj.users_collection)
for coll in colls:
coll.objects.unlink(obj)
obj.user_clear()
# Common cause of crash, try periodic operator purge or file load instead.
# bpy.data.objects.remove(obj)
def get_or_create_layercoll(context,
collection_name: str) -> bpy.types.LayerCollection:
"""Returns or creates the layer collection for a given name.
Only searches within same viewlayer; not exact match but a non-case
sensitive contains-text of collection_name check. If the collection exists
elsewhere by name, ignore (could be used for something else) and generate
a new one; maybe cause any existing collection to be renamed, but is still
left unaffected in whatever view layer it exists.
"""
master_vl = context.view_layer.layer_collection
response_vl = None
for child in master_vl.children:
if collection_name.lower() not in child.name.lower():
continue
response_vl = child
break
if response_vl is None:
new_coll = bpy.data.collections.new(collection_name)
context.scene.collection.children.link(new_coll)
# assumes added to scene's active view layer root via link above
response_vl = master_vl.children[new_coll.name]
return response_vl
def get_loaded_scene(context) -> Optional[bpy.types.Scene]:
"""Return the reference to the loaded scene if any."""
view_layer = get_or_create_layercoll(context, LOCAL_COLLECTION_NAME)
if not view_layer.collection.all_objects:
return # Nothing has been loaded yet.
child = view_layer.collection.all_objects[0]
if not (child.instance_type == 'COLLECTION' or child.instance_collection):
print("Nothing loaded")
raise Exception("Nothing loaded to remove")
scene = [scn for scn in bpy.data.scenes
if scn.collection == child.instance_collection]
if len(scene) != 1:
print("Expected single scene source")
return None
return scene[0]
def replace_view_layer(context, scene: bpy.types.Scene) -> bpy.types.Object:
"""Add and return an instance object of a given scene by reference."""
view_layer = get_or_create_layercoll(context, LOCAL_COLLECTION_NAME)
old_scene = get_loaded_scene(context)
if old_scene is not None:
bpy.data.scenes.remove(old_scene)
this_empty = None
for child in view_layer.collection.all_objects:
if this_empty is None and child.type == 'EMPTY':
this_empty = child
continue
remove_object(context, child) # Should just be the empty with instance
if this_empty is None:
obj = bpy.data.objects.new(scene.name, None)
else:
obj = this_empty
obj.instance_type = 'COLLECTION'
obj.instance_collection = scene.collection
if this_empty is None:
# Link since we just added it
view_layer.collection.objects.link(obj)
obj.empty_display_type = 'CUBE'
obj.empty_display_size = 0.1
return obj
def load_csv_metadata(context) -> Dict:
"""Load in the local C(T)SV metadata download of user form responses."""
global _FORM_DATA
path = get_responses_path(context)
if not os.path.isfile(path):
print("TSV file not found!")
return {}
data = {}
header = None
email_cache = set()
with open(path, 'r', encoding='utf-8') as fd:
rd = csv.reader(fd, delimiter="\t", quotechar='"')
# Using iterator directly would be better performance, but we need to
# look at entries in reverse, and so we list-ify.
all_rows = list(rd)
header = all_rows[0]
if "blend_filename" not in header:
raise Exception("blend_filename not in CSV header")
if "full_name" not in header or "country" not in header:
raise Exception("full_name/country not in CSV header")
for row in reversed(all_rows[:-1]):
key = row[header.index("blend_filename")]
user_name = row[header.index("full_name")]
country = row[header.index("country")]
url = row[header.index("blend_url")]
# Instead of using timestamp, assume earlier rows = earlier entries,
# and so we only included latest entry per email because we are
# going in reverse order.
email = row[header.index("email")]
if email in email_cache:
latest = False
else:
latest = True
email_cache.add(email)
data[key] = {0: user_name, 1: country, 2: url, 3: latest}
# Save to global var for reuse.
_FORM_DATA = data
def process_open_file(context) -> None:
"""Transform the loaded scene into a standardized, desired format.
Runs once directly after a blend file is loaded from the target folder,
noting that the file is library linked in as a scene. This ensures nothing
gets saved into the currently open file, and there is little concern for
doing "cleanup" between opening different scenes (since data is not saved
to the open file).
The processing needed will vary for a given community project. Some sample
utilities are included by default.
"""
# process_generic_scene(context)
process_as_donut(context)
def process_generic_scene(context) -> None:
"""Sample implementation of a scene transformation.
This simple sample implementation performs a few useful tasks:
- Clears all object-level animations, to ensure any object transforms
can be simply performed
- Remove / hide objects which are in an excluded collection view layer or
hidden in the viewport or render in the source scene. A blender quirk is
that a hidden or excluded collection in a scene will be visible if that
scene is loaded as in instance into another scene (as this add-on does).
- Scales and re-centers the scene around the visible meshes.
"""
global _CENTRAL_OBJ
_CENTRAL_OBJ = None
props = context.scene.crp_props
this_row = props.file_list[props.file_list_index]
# Get the current blend metadata, if needed for anything.
# this_row = props.file_list[props.file_list_index]
if props.load_original is True:
print("Skip process step, not modifying loaded scene")
return
# delete all but allowed mesh types
view_layer = get_or_create_layercoll(context, LOCAL_COLLECTION_NAME)
coll = view_layer.collection
if len(coll.all_objects) != 1:
print("Expected only a single object in collection, found:")
print(f"{len(coll.all_objects)} in {coll.name}")
raise Exception("Issue - more than one object in collection!")
# Center the actual source scene itself back to the origin.
scene_obj = coll.all_objects[0]
scene_obj.location = (0, 0, 0)
scene = get_loaded_scene(context)
# Now run any of the transformation steps. This are directly modifying the
# scene as if objects were actually appended into the file, though indeed
# it is actually library linked and so would reset on reload/open.
clear_all_animation(scene)
unlink_excluded_objects(scene)
# Keep materials the same, just replace missing texture with a default.
# update_materials(context, scene)
# Completely clear and re-generate any materials missing images.
# regenerate_missing_materials(scene)
# Find the largest object in the scene which is a mesh, and has enough
# geometry that it's not likely a backdrop or floor.
avg_pos = None
xy_scale = None
target_obj = None
for obj in scene.collection.all_objects:
if obj.type != 'MESH':
continue
using_geo_nodes = len(
[mod for mod in obj.modifiers if mod.type == "NODES"]) > 0
if using_geo_nodes:
print("not skipping geo nodes")
if len(obj.data.polygons) < 100 and not using_geo_nodes:
# Likely a plane or backdrop.
continue
this_pos, this_scale = get_avg_pos_and_scale(context, obj)
if target_obj is None or this_scale > xy_scale:
avg_pos = this_pos
xy_scale = this_scale
target_obj = obj
if target_obj is None:
extend_qc_error(this_row, "Could not select target object")
print("No objects remain")
return
else:
print(f"Selected target object {target_obj.name}")
# Assign the center for the scene to use by adjusting the instance offset.
scene.collection.instance_offset = this_pos
# Update the scale of the scene instance (not changing scale in source).
target_width = 1.0 # Meters.
if xy_scale > 0.000001:
transform_scale = target_width / xy_scale
else:
transform_scale = 1
print(f"XY scale is: {xy_scale} and pos avg {avg_pos}")
empty_inst = context.view_layer.objects.active
empty_inst.scale = [transform_scale] * 3
# Finally, cache the base selected object
_CENTRAL_OBJ = target_obj
def process_as_donut(context):
"""Process the open file assuming it should be a donut.
This function is very bespoke to the specific project at hand. In this
case, about transforming donuts to be centered in the frame and removing
everything else. This functions by editing the library linked in scene,
which means that the changes performed by this function are reverted if the
library (or open blend file) are ever reloaded. It is not formally using
library overrides as part of the blender UI, as those have their own
limitations. Plus, we don't want to save override data as we want to fully
refresh data between loading one file and the next.
"""
global _CENTRAL_OBJ
_CENTRAL_OBJ = None
props = context.scene.crp_props
this_row = props.file_list[props.file_list_index]
if props.load_original is True:
print("Skip process step, not modifying loaded scene")
return
# delete all but allowed mesh types
view_layer = get_or_create_layercoll(context, LOCAL_COLLECTION_NAME)
coll = view_layer.collection
if len(coll.all_objects) != 1:
print("Expected only a single object in collection, found:")
print(f"{len(coll.all_objects)} in {coll.name}")
raise Exception("Issue - more than one object in collection!")
# Center the actual source scene itself back to the origin.
scene_obj = coll.all_objects[0]
scene_obj.location = (0, 0, 0)
scn = get_loaded_scene(context)
clear_all_animation(scn)
hide_ineligible_for_donut(context, scn)
unlink_excluded_objects(scn)
if not scn.collection.all_objects[:]:
extend_qc_error(this_row, "No objects (post QC)")
print("No objects remain")
return
# Find best candidate for base donut and icing
base_donut, from_icing, icing_candidates = get_interest_objects(
context, scn, this_row)
# Move out the remaining candidates.
# Note: This still causes some issues where objects were badly moved.
# if from_icing is True:
# for remaining in base_with_icing:
# if remaining == donut:
# continue
# remaining.location[0] += 10
# elif from_icing is False:
# for remaining in base_candidates:
# if remaining == donut:
# continue
# remaining.location[0] += 10
if base_donut is None:
print("base_donut is None; Self-script error, this shouldn't happen")
extend_qc_error(this_row, "Bad script state where base_donut none")
return
print(f"Final choice for base donut: {base_donut.name}")
# Force ensure the z-rotation is cleared, which would rotate bounding box,
# which inflates the size of the donut (thus making it show up smaller)
rot = base_donut.rotation_euler[2]
base_donut.rotation_euler[2] = 0
context.view_layer.update()
if base_donut.hide_get() or base_donut.hide_viewport or base_donut.hide_render:
base_donut.hide_render = False
err = "Donut hidden in source scene"
print(err)
extend_qc_error(this_row, err)
avg_pos, xy_scale = get_avg_pos_and_scale(context, base_donut)
orig_loc = base_donut.location.copy()
base_donut.location -= avg_pos # Center, even with bad origin
# Reverse rotate.
base_donut.rotation_euler[2] = rot
context.view_layer.update()
target_width = 0.1 # In cm
if xy_scale > 0.000001:
transform_scale = target_width / xy_scale
else:
transform_scale = 1
print(f"XY scale is: {xy_scale} and pos avg {avg_pos}")
empty_inst = context.view_layer.objects.active
empty_inst.scale = [transform_scale] * 3
update_non_donuts(context, scn, base_donut, orig_loc, avg_pos,
transform_scale, icing_candidates)
update_materials(context, scn)
# Finally, cache the selected object
_CENTRAL_OBJ = base_donut
def get_interest_objects(context, scn, this_row):
"""Return the selected base donut and candidate icing objects."""
base_candidates = []
for ob in scn.collection.all_objects:
if ob.type != 'MESH':
print("Cont' due to not mesh", ob.name)
continue
if ob.parent:
# Normally, we would just exclude this object as a donut candidate
# if there is a parent object. But let some of the below situations
# allow us to ignore there's a parent and consider using the donut
# anyways. For instance if the parent is just a plate, or table,
# or an empty mesh, or if the parent is excluded/hidden anyways.
# Otherwise, we normally assume having a parent means this is icing
phide = ob.parent.hide_get() or ob.parent.hide_viewport
phide = phide or ob.parent.hide_render
phide = phide or ineligible_donut_name(ob.parent.name)
# Weird case where an empty object was used as the parent,
# treat as if it's an empty
mesh = ob.parent.type == 'MESH' and len(
ob.parent.data.polygons) < 2
phide = phide or mesh
if ob.parent.type == 'EMPTY':
phide = True # Don't exclude if only parented to an empty.
if not phide:
continue
else:
# Clear the parent so that relocation works
ob.parent = None
using_geo_nodes = len(
[mod for mod in ob.modifiers if mod.type == "NODES"]) > 0
if using_geo_nodes:
print("Using geometry nodes, not skipping based on polycount")
if using_geo_nodes and not using_geo_nodes:
print("not skipping geo nodes")
if len(ob.data.polygons) < 150 and not using_geo_nodes:
print("Contd due to poly count", ob.name)
continue
base_candidates.append(ob)
if not base_candidates:
extend_qc_error(this_row, "No base mesh found")
print("No valid meshes for base")
return
icing_candidates = []
print("Detecting icing objects")
sm1 = time.time()
for ob in scn.collection.all_objects:
if ob.type != 'MESH':
continue
if not ob.particle_systems:
continue
if len(ob.data.polygons) < 150:
continue
icing_candidates.append(ob)
# # Making icing objects smooth shaded.
# Disabled, as it was going slow.
# print("\t\tSmoothing object")
# for f in ob.data.polygons:
# f.use_smooth = True
sm2 = time.time()
icing_time = sm2 - sm1
print(f"\tSmoothing took {icing_time:.02f}s")
# Find candidates which have icing attached
base_with_icing = []
for ob in base_candidates:
any_icing = False
for child in ob.children:
if child in icing_candidates:
any_icing = True
break
# TODO: Consider doing check also for any non-parented objects, that
# are in icing_candidates and have similar bounding box.
if any_icing:
base_with_icing.append(ob)
from_icing = None
if base_with_icing:
print("Identified possible base meshes, which have icing on top:")
print(base_with_icing)
print("Moving all but one of then to the middle")
iterate_options = base_with_icing
from_icing = True
elif base_candidates:
iterate_options = base_candidates
from_icing = False
else:
iterate_options = []
size = 0
base_donut = None
for donut in iterate_options:
_, xy_scale = get_avg_pos_and_scale(context, donut)
if xy_scale > size:
size = xy_scale
base_donut = donut
return base_donut, from_icing, icing_candidates
def clear_all_animation(scene: bpy.types.Scene) -> None:
"""Remove all animation from the open scene."""
for ob in scene.collection.all_objects:
ob.animation_data_clear()
def unlink_excluded_objects(scene: bpy.types.Scene) -> None:
"""Actively unlink objects that are excluded in the source scene.
Will also attempt to remove archived or default hidden collections
"""
master = scene.view_layers[0].layer_collection
recursive_children = [[master, child] for child in list(master.children)]
for parent, child in recursive_children:
excluded = child.exclude is True
# archive = "archive" not in child.name.lower()
hidden = child.collection.hide_viewport or child.collection.hide_render
hidden = hidden or child.hide_viewport # Like hide_get() for objects.
# If collection is archive, always exclude it.
# Initially was removing if "archive", but some scenes actually did
# have their scenes in the scene "archive", so need to not remove that.
if not (excluded or hidden):
if child.children:
recursive_children += [
[child, sub] for sub in list(child.children)]
continue
# Just unlink this view layer. Deleting objects would likely mean
# that the sprinkles would get deleted too.
print(f"\tUnlinked excluded layer: {child.collection.name}")
parent.collection.children.unlink(child.collection)
def ineligible_donut_name(compare_name):
"""Return true if the name contains a word known to not be a donut."""
rm_name_prefix = [
'cup', 'plate', 'plato', 'taza', 'cup', 'mug', 'table', 'floor',
'ground']
for rm_name in rm_name_prefix:
if rm_name in compare_name.lower():
return True
return False
def hide_ineligible_for_donut(context, scn: bpy.types.Scene) -> None:
"""Hide (or delete) ineligible objects for render."""
print(f"Collection scene is {scn.name}")
allow_types = ['EMPTY', 'MESH']
# Remove items that are clearly meant to not be donuts
del_objects = []
for ob in scn.collection.all_objects:
if ob.type not in allow_types:
del_objects.append(ob)
elif ineligible_donut_name(ob.name):
del_objects.append(ob)
for obj in del_objects:
# Could hide instead of delete for stability, encountered crashes here.
# obj.hide_render = True
# obj.hide_viewport = True
remove_object(context, obj)
# Cannot use operator override, since in a collection in another scene.
# override = generate_context_override(del_objects)
# bpy.ops.object.delete(override, use_global=True)
def get_avg_pos_and_scale(
context, obj: bpy.types.Object) -> Tuple[mathutils.Vector, float]:
"""Return the average position and scale for the give object.
Returns:
average position: XYZ position based on bounding box, not origin.
scale: Width of object (average of xy individually).
"""
context.view_layer.update() # Helps for geometry nodes bounds.
sum_pos = mathutils.Vector([0, 0, 0])
min_x = None
max_x = None
min_y = None
max_y = None
min_z = None
max_z = None
# Counteract rotation so that bounding box isn't enlarged unnecessarily.
# Note: Below is not fully correct, and for sake of simplicity, opted to
# rotate and then un-rotate the selected object instead.
# zrot = obj.rotation_euler[2]
# counter_rot = mathutils.Matrix.Rotation((zrot), 4, 'Z')
bounds = [obj.matrix_world @ mathutils.Vector(corner) # @ counter_rot
for corner in obj.bound_box]
for bound in bounds:
sum_pos += bound
if not min_x or bound[0] < min_x:
min_x = bound[0]
if not max_x or bound[0] > max_x:
max_x = bound[0]
if not min_y or bound[1] < min_y:
min_y = bound[1]
if not max_y or bound[1] > max_y:
max_y = bound[1]
if not min_z or bound[2] < min_z:
min_z = bound[2]
if not max_z or bound[2] > max_z:
max_z = bound[2]
current_size = mathutils.Vector([
max_x - min_x,
max_y - min_y,
max_z - min_z])
avg_pos = sum_pos / 8 # Div by 8 for the number of bound box corners.
xy_scale = (current_size[0] + current_size[1]) / 2.0
return avg_pos, xy_scale
def update_non_donuts(context,
scn: bpy.types.Scene,
base_donut: bpy.types.Object,
orig_loc: mathutils.Vector,
avg_pos: mathutils.Vector,
scale: float,
icing: Sequence[bpy.types.Object]) -> None:
"""Update other objects in the scene based on selections so far."""
# For low poly objects like sprinkles, for simplicity, just move it away
for ob in scn.collection.all_objects:
if ob.type != 'MESH':
ob.location[0] += 100
continue
using_geo_nodes = len(
[mod for mod in ob.modifiers if mod.type == "NODES"]) > 0
if len(ob.data.polygons) >= 150 or using_geo_nodes:
continue
if ob == base_donut:
continue # Should already meet with above conditions, safeguard.
ob.location[0] += 100
# Optional: remove modifiers.
# for mod in ob.modifiers:
# ob.modifiers.remove(mod)