-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvi_operators.py
4562 lines (3683 loc) · 222 KB
/
vi_operators.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 2
# 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 #####
import bpy, datetime, mathutils, os, bmesh, shutil, sys, shlex, itertools, inspect, aud, multiprocessing, threading, gc
import subprocess
import numpy
from numpy import arange, histogram, array, int8, int16, int32, float16, empty, uint8, transpose, where, ndarray, place, zeros, average, float32, float64, concatenate, ones, array2string, square
from numpy import sum as nsum
from numpy import max as nmax
from numpy import mean as nmean
from scipy import signal
from scipy.io import wavfile
from scipy import signal
from bpy_extras.io_utils import ExportHelper, ImportHelper
from subprocess import Popen, PIPE, call
from collections import OrderedDict
from datetime import datetime as dt
from math import cos, sin, pi, ceil, tan, radians, log
from time import sleep
from mathutils import Euler, Vector, Matrix
from xml.dom.minidom import parseString
from .livi_export import radgexport, createoconv, createradfile, gen_octree, radpoints
from .envi_export import enpolymatexport, pregeo
from .envi_mat import envi_materials, envi_constructions, envi_embodied, envi_eclasstype
from .envi_func import write_ec, write_ob_ec
from .vi_func import selobj, joinobj, solarPosition, viparams, wind_compass
from .flovi_func import ofheader, fvcdwrite, fvvarwrite, fvsolwrite, fvschwrite, fvtpwrite, fvmtwrite
from .flovi_func import fvdcpwrite, write_ffile, write_bound, fvtppwrite, fvgwrite, fvrpwrite, fvprefwrite, oftomesh, fvmodwrite
from .vi_func import ret_plt, logentry, rettree, cmap, fvprogressfile, fvprogressbar
from .vi_func import windnum, wind_rose, create_coll, create_empty_coll, move_to_coll, retobjs, progressfile, progressbar, au_pb
from .vi_func import chunks, clearlayers, clearscene, clearfiles, objmode, clear_coll, bm_to_stl
from .livi_func import retpmap
from .auvi_func import rir2sti
from .vi_chart import chart_disp, hmchart_disp, ec_pie, wlc_line, com_line
from .vi_dicts import rvuerrdict, pmerrdict
import OpenImageIO
OpenImageIO.attribute("missingcolor", "0,0,0")
from OpenImageIO import ImageInput, ImageBuf
if sys.platform != 'win32':
if multiprocessing.get_start_method() != 'fork':
multiprocessing.set_start_method('fork', force=True)
try:
import netgen
from netgen.meshing import MeshingParameters, FaceDescriptor, Element2D, Mesh, MeshingStep
from netgen.stl import STLGeometry
from pyngcore import SetNumThreads, TaskManager
except Exception as e:
print(e)
try:
import matplotlib
#if sys.platform != 'darwin':
matplotlib.use('qtagg', force=True)
import matplotlib.cm as mcm
import matplotlib.colors as mcolors
from matplotlib import pyplot as plt
plt.set_loglevel("error")
#plt.ion()
from .windrose import WindroseAxes
mp = 1
except Exception as e:
print("No matplotlib: {}".format(e))
mp = 0
# if mp:
# plt = ret_plt()
# if plt:
# from .windrose import WindroseAxes
# try:
# import psutil
# psu = 1
# except Exception as e:
# #print("No psutil: {}".format(e))
# psu = 0
try:
import pyroomacoustics as pra
pra_rt = True
pra.constants.set("num_threads", 8)
ra = 1
except:
ra = 0
c_freqs = [125, 250, 500, 1000, 2000, 4000, 8000]
class ADDON_OT_PyInstall(bpy.types.Operator):
bl_idname = "addon.pyimport"
bl_label = "Install Python dependencies"
bl_description = "Installs matplotlib, PyQt6, kivy and netgen"
def execute(self, context):
if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform, 'pip')):
gp_cmd = '{} {} --target {}'.format(sys.executable, os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'get-pip.py'),
os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform))
Popen(shlex.split(gp_cmd))
if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform, 'kivy')):
kivy_cmd = '{} -m pip install kivy --target {}'.format(sys.executable,
os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform))
Popen(shlex.split(kivy_cmd))
if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform, 'PyQt6')):
pyqt_cmd = '{} -m pip install PyQt6 --target {}'.format(sys.executable,
os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform))
Popen(shlex.split(pyqt_cmd))
if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform, 'matplotlib')):
mp_cmd = '{} -m pip install matplotlib --target {}'.format(sys.executable,
os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform))
Popen(shlex.split(mp_cmd))
if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform, 'netgen')):
ng_cmd = '{} -m pip install netgen --target {}'.format(sys.executable,
os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform))
Popen(shlex.split(ng_cmd))
if not os.path.isdir(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform, 'netgen')):
ng_cmd = '{} -m pip install pyroomacoustics --target {}'.format(sys.executable,
os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), 'Python', sys.platform))
Popen(shlex.split(ng_cmd))
return {'FINISHED'}
class NODE_OT_ASCImport(bpy.types.Operator, ImportHelper):
bl_idname = "node.ascimport"
bl_label = "Select ESRI Grid file"
bl_description = "Select the ESRI Grid file to process"
filename = ""
filename_ext = ".asc"
filter_glob: bpy.props.StringProperty(default="*.asc", options={'HIDDEN'})
bl_register = True
bl_undo = False
def draw(self, context):
layout = self.layout
row = layout.row()
row.label(text="Open an asc file with the file browser", icon='WORLD_DATA')
def execute(self, context):
scene = context.scene
asccoll = create_coll(context, 'Terrain')
startxs, startys, vlen = [], [], 0
rp = os.path.dirname(os.path.realpath(self.filepath))
ascfiles = [self.filepath] if self.node.single else [os.path.join(rp, file) for file in os.listdir(rp) if file.endswith('.asc')]
obs = []
hd = {'ncols': 0, 'nrows': 0, 'xllcorner': 0, 'yllcorner': 0, 'cellsize': 0, 'NODATA_value': 0}
for file in ascfiles:
basename = file.split(os.sep)[-1].split('.')[0]
me = bpy.data.meshes.new("{} mesh".format(basename))
bm = bmesh.new()
li = 0
with open(file, 'r') as ascfile:
lines = ascfile.readlines()
while len(lines[li].split()) == 2:
if lines[li].split()[0] in hd:
hd[lines[li].split()[0]] = eval(lines[li].split()[1])
li += 1
vlen = hd['nrows'] * hd['ncols']
startxs.append(hd['xllcorner'])
startys.append(hd['yllcorner'])
x, y = 0, hd['nrows']
for li, line in enumerate(lines[li:]):
for zval in line.split():
[bm.verts.new((x * hd['cellsize'], y * hd['cellsize'], float(zval)))]
x += 1
x = 0
y -= 1
bm.verts.ensure_lookup_table()
faces = [(i+1, i, i + hd['ncols'], i + hd['ncols'] + 1) for i in range(0, vlen - hd['ncols']) if (i+1) % hd['ncols']]
[bm.faces.new([bm.verts[fv] for fv in face]) for face in faces]
if self.node.clear_nodata == '1':
bmesh.ops.delete(bm, geom=[v for v in bm.verts if v.co[2] == hd['NODATA_value']], context=1)
elif self.node.clear_nodata == '0':
for v in bm.verts:
if v.co[2] == hd['NODATA_value']:
v.co[2] = 0
bm.to_mesh(me)
bm.free()
ob = bpy.data.objects.new(basename, me)
if ob.name not in asccoll.objects:
asccoll.objects.link(ob)
if ob.name in scene.collection.objects:
scene.collection.objects.unlink(ob)
obs.append(ob)
minstartx, minstarty = min(startxs), min(startys)
for o, ob in enumerate(obs):
ob.location = (startxs[o] - minstartx, startys[o] - minstarty, 0)
return {'FINISHED'}
def invoke(self, context, event):
self.node = context.node
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class NODE_OT_TextUpdate(bpy.types.Operator):
bl_idname = "node.textupdate"
bl_label = "Update a text file"
bl_description = "Update a text file"
def execute(self, context):
tenode = context.node
tenode.textupdate(tenode['bt'])
return {'FINISHED'}
class NODE_OT_WindRose(bpy.types.Operator):
bl_idname = "node.windrose"
bl_label = "Wind Rose"
bl_description = "Create a Wind Rose"
bl_register = True
bl_undo = True
def invoke(self, context, event):
scene = context.scene
svp = scene.vi_params
simnode = context.node
wrcoll = create_coll(context, 'WindRoses')
context.view_layer.layer_collection.children[wrcoll.name].exclude = 0
plt = ret_plt()
if viparams(self, scene):
return {'CANCELLED'}
if not plt:
self.report({'ERROR'}, "There is something wrong with your matplotlib installation")
return {'FINISHED'}
simnode.export()
locnode = simnode.inputs['Location in'].links[0].from_node
svp['viparams']['resnode'], svp['viparams']['restree'] = simnode.name, simnode.id_data.name
svp['viparams']['vidisp'], svp.vi_display = 'wr', 0
svp['viparams']['visimcontext'] = 'Wind'
rl = locnode['reslists']
cdoys = [float(c) for c in [r[4].split() for r in rl if r[0] == '0' and r[1] == 'Time' and r[2] == 'Time' and r[3] == 'DOS'][0]]
cwd = [float(c) for c in [r[4].split() for r in rl if r[0] == '0' and r[1] == 'Climate' and r[2] == 'Exterior' and r[3] == 'Wind Direction (deg)'][0]]
if simnode.temp:
cd = [float(c) for c in [r[4].split() for r in rl if r[0] == '0' and r[1] == 'Climate' and r[2] == 'Exterior' and r[3] == 'Temperature (degC)'][0]]
else:
cd = [float(c) for c in [r[4].split() for r in rl if r[0] == '0' and r[1] == 'Climate' and r[2] == 'Exterior' and r[3] == 'Wind Speed (m/s)'][0]]
doys = list(range(simnode.sdoy, simnode.edoy + 1)) if simnode.edoy > simnode.sdoy else list(range(1, simnode.edoy + 1)) + list(range(simnode.sdoy, 366))
awd = array([wd for di, wd in enumerate(cwd) if cdoys[di] in doys])
ad = array([d for di, d in enumerate(cd) if cdoys[di] in doys])
validdata = where(awd > 0) if max(cwd) == 360 else where(awd > -1)
vawd = awd[validdata]
vad = ad[validdata]
simnode['maxres'], simnode['minres'], simnode['avres'] = max(cd), min(cd), sum(cd)/len(cd)
sbinvals = arange(0, int(ceil(max(vad))), 2)
dbinvals = arange(-11.25, 372.25, 22.5)
dfreq = histogram(awd, bins=dbinvals)[0]
dfreq[0] = dfreq[0] + dfreq[-1]
dfreq = dfreq[:-1]
fig = plt.figure(figsize=(8, 8), dpi=150, facecolor='w', edgecolor='w')
rect = [0.1, 0.1, 0.8, 0.8]
ax = WindroseAxes(fig, rect, facecolor='w')
fig.add_axes(ax)
if simnode.wrtype == '0':
ax.bar(vawd, vad, bins=sbinvals, normed=True, opening=0.8, edgecolor='white', cmap=mcm.get_cmap(svp.vi_scatt_col))
elif simnode.wrtype == '1':
ax.box(vawd, vad, bins=sbinvals, normed=True, cmap=mcm.get_cmap(svp.vi_scatt_col))
elif simnode.wrtype in ('2', '3', '4'):
ax.contourf(vawd, vad, bins=sbinvals, normed=True, cmap=mcm.get_cmap(svp.vi_scatt_col))
if simnode.max_freq == '1':
ax.set_rmax(simnode.max_freq_val)
else:
ax.set_rmax(100*nmax(dfreq)/len(awd) + 0.5)
plt.savefig(svp['viparams']['newdir']+'/disp_wind.svg')
wrme = bpy.data.meshes.new("Wind_rose")
wro = bpy.data.objects.new('Wind Rose', wrme)
if wro.name not in wrcoll.objects:
wrcoll.objects.link(wro)
if wro.name in scene.collection.objects:
scene.collection.objects.unlink(wro)
selobj(context.view_layer, wro)
(wro, scale) = wind_rose(wro, (simnode['maxres'], simnode.max_freq_val)[simnode.max_freq == '1'], svp['viparams']['newdir']+'/disp_wind.svg', simnode.wrtype, mcolors)
wro = joinobj(context.view_layer, wro)
ovp = wro.vi_params
ovp['maxres'], ovp['minres'], ovp['avres'], ovp['nbins'], ovp['VIType'] = max(ad), min(ad), sum(ad)/len(ad), len(sbinvals), 'Wind_Plane'
simnode['maxfreq'] = 100*nmax(dfreq)/len(awd)
windnum((100*nmax(dfreq)/len(awd) + 0.5, simnode.max_freq_val)[simnode.max_freq == '1'], (0, 0, 0), scale, wind_compass((0, 0, 0), scale, wro, wro.data.materials['wr-000000']))
plt.close()
ovp['table'] = array([["", 'Minimum', 'Average', 'Maximum'],
[('Speed (m/s)', 'Temperature (C)')[simnode.temp], ovp['minres'], '{:.1f}'.format(ovp['avres']), ovp['maxres']],
['Direction (\u00B0)', min(awd), '{:.1f}'.format(sum(awd)/len(awd)), max(awd)]])
ovp['d'] = ad.reshape(len(doys), 24).T.tolist()
ovp['wd'] = awd.reshape(len(doys), 24).T.tolist()
ovp['days'] = array(doys, dtype=float)
ovp['hours'] = arange(0, 24, dtype=float)
ovp['maxfreq'] = 100*nmax(dfreq)/len(awd)
simnode['nbins'] = len(sbinvals)
simnode['d'] = array(cd).reshape(365, 24).T.tolist()
simnode['wd'] = array(cwd).reshape(365, 24).T.tolist()
simnode['days'] = arange(1, 366, dtype=float)
simnode['hours'] = arange(0, 24, dtype=float)
return {'FINISHED'}
class NODE_OT_SVF(bpy.types.Operator):
bl_idname = "node.svf"
bl_label = "Sky View Factor"
bl_description = "Undertake a sky view factor study"
bl_register = True
bl_undo = False
def invoke(self, context, event):
scene = context.scene
svp = scene.vi_params
svp.vi_display = 0
context.evaluated_depsgraph_get()
if viparams(self, scene):
return {'CANCELLED'}
shadobs = retobjs('livig')
if not shadobs:
self.report({'ERROR'}, "No shading objects with a material attached.")
return {'CANCELLED'}
simnode = context.node
svp['viparams']['restree'] = simnode.id_data.name
clearscene(context, self)
for o in scene.objects:
o.vi_params.vi_type_string = ''
calcobs = retobjs('ssc')
if not calcobs:
self.report({'ERROR'}, "No objects have a light sensor material attached.")
return {'CANCELLED'}
svp['viparams']['visimcontext'] = 'SVF'
if not svp.get('liparams'):
svp['liparams'] = {}
svp['liparams']['cp'], svp['liparams']['unit'], svp['liparams']['type'] = simnode.cpoint, 'SVF (%)', 'VI Shadow'
simnode.preexport()
(svp['liparams']['fs'], svp['liparams']['fe']) = (scene.frame_current, scene.frame_current) if simnode.animmenu == 'Static' else (simnode.startframe, simnode.endframe)
svp['viparams']['resnode'], simnode['Animation'] = simnode.name, simnode.animmenu
(scmaxres, scminres, scavres) = [[x] * (svp['liparams']['fe'] - svp['liparams']['fs'] + 1) for x in (0, 1, 0)]
frange = range(svp['liparams']['fs'], svp['liparams']['fe'] + 1)
x, y, z = [], [], []
if simnode.skypatches == '0':
alts = (6, 18, 30, 42, 54, 66, 78, 90)
azis = (30, 30, 24, 24, 18, 12, 6, 1)
elif simnode.skypatches == '1':
alts = [(rrow+0.5)*90/(2*7+0.5) for rrow in range(0, 15)]
azis = (60, 60, 60, 60, 48, 48, 48, 48, 36, 36, 24, 24, 12, 12, 1)
elif simnode.skypatches == '2':
alts = [(rrow+0.5)*90/(4*7+0.5) for rrow in range(0, 29)]
azis = (120, 120, 120, 120, 120, 120, 120, 120, 96, 96, 96, 96, 96, 96, 96, 96, 72, 72, 72, 72, 48, 48, 48, 48, 24, 24, 24, 24, 1)
for a, azi in enumerate(azis):
for az in arange(0, 360, 360/azi):
x.append(sin(az * pi/180) * cos(alts[a] * pi/180))
y.append(cos(az * pi/180) * cos(alts[a] * pi/180))
z.append(sin(alts[a] * pi/180))
valdirecs = [v for v in zip(x, y, z)]
lvaldirecs = len(valdirecs)
calcsteps = len(frange) * sum(len([f for f in o.data.polygons if o.data.materials[f.material_index].vi_params.mattype == '1']) for o in calcobs)
curres, reslists = 0, []
pfile = progressfile(svp['viparams']['newdir'], datetime.datetime.now(), calcsteps)
kivyrun = progressbar(os.path.join(svp['viparams']['newdir'], 'viprogress'), 'Sky View')
for o in calcobs:
ovp = o.vi_params
for k in [k for k in ovp.keys()]:
del ovp[k]
if any([s < 0 for s in o.scale]):
logentry('Negative scaling on calculation object {}. Results may not be as expected'.format(o.name))
self.report({'WARNING'}, 'Negative scaling on calculation object {}. Results may not be as expected'.format(o.name))
ovp['omin'], ovp['omax'], ovp['oave'] = {}, {}, {}
bm = bmesh.new()
bm.from_mesh(o.to_mesh())
o.to_mesh_clear()
clearlayers(bm, 'a')
bm.transform(o.matrix_world)
bm.normal_update()
geom = bm.faces if simnode.cpoint == '0' else bm.verts
geom.layers.int.new('cindex')
cindex = geom.layers.int['cindex']
[geom.layers.float.new('svf{}'.format(fi)) for fi in frange]
avres, minres, maxres, g = [], [], [], 0
if simnode.cpoint == '0':
gpoints = [f for f in geom if o.data.materials[f.material_index].vi_params.mattype == '1']
elif simnode.cpoint == '1':
gpoints = [v for v in geom if any([o.data.materials[f.material_index].vi_params.mattype == '1' for f in v.link_faces])]
for g, gp in enumerate(gpoints):
gp[cindex] = g + 1
for frame in frange:
g = 0
scene.frame_set(frame)
shadtree = rettree(scene, [ob for ob in shadobs if ob.visible_get()], ('', '1')[simnode.signore])
shadres = geom.layers.float['svf{}'.format(frame)]
if gpoints:
posis = [gp.calc_center_median() + gp.normal.normalized() * simnode.offset for gp in gpoints] if simnode.cpoint == '0' else [gp.co + gp.normal.normalized() * simnode.offset for gp in gpoints]
for chunk in chunks(gpoints, int(svp['viparams']['nproc']) * 200):
for gp in chunk:
pointres = array([(0, 1)[not shadtree.ray_cast(posis[g], direc)[3]] for direc in valdirecs], dtype=int8)
gp[shadres] = (100*(nsum(pointres)/lvaldirecs)).astype(int8)
g += 1
curres += len(chunk)
if pfile.check(curres) == 'CANCELLED':
return {'CANCELLED'}
shadres = [gp[shadres] for gp in gpoints]
ovp['omin']['svf{}'.format(frame)], ovp['omax']['svf{}'.format(frame)], ovp['oave']['svf{}'.format(frame)] = min(shadres), max(shadres), sum(shadres)/len(shadres)
reslists.append([str(frame), 'Zone spatial', o.name, 'X', ' '.join(['{:.3f}'.format(p[0]) for p in posis])])
reslists.append([str(frame), 'Zone spatial', o.name, 'Y', ' '.join(['{:.3f}'.format(p[1]) for p in posis])])
reslists.append([str(frame), 'Zone spatial', o.name, 'Z', ' '.join(['{:.3f}'.format(p[2]) for p in posis])])
reslists.append([str(frame), 'Zone spatial', o.name, 'SVF', ' '.join(['{:.3f}'.format(sr) for sr in shadres])])
avres.append(ovp['oave']['svf{}'.format(frame)])
minres.append(ovp['omin']['svf{}'.format(frame)])
maxres.append(ovp['omax']['svf{}'.format(frame)])
reslists.append(['All', 'Frames', 'Frames', 'Frames', ' '.join(['{}'.format(f) for f in frange])])
reslists.append(['All', 'Zone spatial', o.name, 'Minimum', ' '.join(['{:.3f}'.format(mr) for mr in minres])])
reslists.append(['All', 'Zone spatial', o.name, 'Average', ' '.join(['{:.3f}'.format(mr) for mr in avres])])
reslists.append(['All', 'Zone spatial', o.name, 'Maximum', ' '.join(['{:.3f}'.format(mr) for mr in maxres])])
bm.transform(o.matrix_world.inverted())
bm.to_mesh(o.data)
bm.free()
o.vi_params.vi_type_string = 'LiVi Calc'
svp.vi_leg_max, svp.vi_leg_min = 100, 0
if kivyrun.poll() is None:
kivyrun.kill()
scene.frame_start, scene.frame_end = svp['liparams']['fs'], svp['liparams']['fe']
svp['viparams']['vidisp'] = 'svf'
simnode['reslists'] = reslists
simnode['frames'] = [f for f in frange]
simnode.postexport(scene)
return {'FINISHED'}
class NODE_OT_Shadow(bpy.types.Operator):
bl_idname = "node.shad"
bl_label = "Shadow Map"
bl_description = "Undertake a shadow mapping"
bl_register = True
bl_undo = False
def invoke(self, context, event):
scene = context.scene
svp = scene.vi_params
bpy.context.evaluated_depsgraph_get()
svp.vi_display = 0
if viparams(self, scene):
return {'CANCELLED'}
shadobs = retobjs('livig')
if not shadobs:
self.report({'ERROR'}, "No shading objects or none with a material attached.")
return {'CANCELLED'}
simnode = context.node
svp['viparams']['restree'] = simnode.id_data.name
clearscene(context, self)
for o in scene.objects:
o.vi_params.vi_type_string = ''
calcobs = retobjs('ssc')
if not calcobs:
self.report({'ERROR'}, "No objects have a light sensor material attached.")
return {'CANCELLED'}
svp['viparams']['visimcontext'] = 'Shadow'
if not svp.get('liparams'):
svp['liparams'] = {}
svp['liparams']['cp'], svp['liparams']['unit'], svp['liparams']['type'] = simnode.cpoint, 'Sunlit (% hrs)', 'VI Shadow'
simnode.preexport()
(svp['liparams']['fs'], svp['liparams']['fe']) = (scene.frame_current, scene.frame_current) if simnode.animmenu == 'Static' else (simnode.startframe, simnode.endframe)
cmap(svp)
if simnode.starthour > simnode.endhour:
self.report({'ERROR'}, "End hour is before start hour.")
return {'CANCELLED'}
svp['viparams']['resnode'], simnode['Animation'] = simnode.name, simnode.animmenu
(scmaxres, scminres, scavres) = [[x] * (svp['liparams']['fe'] - svp['liparams']['fs'] + 1) for x in (0, 100, 0)]
frange = range(svp['liparams']['fs'], svp['liparams']['fe'] + 1)
time = datetime.datetime(2018, simnode.sdate.month, simnode.sdate.day, simnode.starthour)
y = 2018 if simnode.edoy >= simnode.sdoy else 2019
endtime = datetime.datetime(y, simnode.edate.month, simnode.edate.day, simnode.endhour)
interval = datetime.timedelta(hours=1/simnode.interval)
times = [time + interval*t for t in range(int((endtime - time)/interval) + simnode.interval) if simnode.starthour <= (time + interval*t).hour <= simnode.endhour]
sps = array([solarPosition(t.timetuple().tm_yday, t.hour+t.minute/60, svp.latitude, svp.longitude)[2:] for t in times])
valmask = array([sp[0] > 0 for sp in sps], dtype=int8)
direcs = array([(-sin(sp[1]), -cos(sp[1]), tan(sp[0])) for sp in sps])
valdirecs = [mathutils.Vector((-sin(sp[1]), -cos(sp[1]), tan(sp[0]))) for sp in sps if sp[0] > 0]
lvaldirecs = len(valdirecs)
ilvaldirecs = 1/lvaldirecs
calcsteps = len(frange) * sum(len([f for f in o.data.polygons if o.data.materials[f.material_index].vi_params.mattype == '1']) for o in calcobs)
curres, reslists = 0, []
pfile = progressfile(svp['viparams']['newdir'], datetime.datetime.now(), calcsteps)
kivyrun = progressbar(os.path.join(scene.vi_params['viparams']['newdir'], 'viprogress'), 'Shadow Map')
logentry(f'Conducting shadow map calculation with {simnode.interval} samples per hour for {int(len(direcs)/simnode.interval)} total hours and {lvaldirecs} available sun hours')
for frame in frange:
reslists.append([str(frame), 'Time', 'Time', 'Month', ' '.join([str(t.month) for t in times])])
reslists.append([str(frame), 'Time', 'Time', 'Day', ' '.join([str(t.day) for t in times])])
reslists.append([str(frame), 'Time', 'Time', 'Hour', ' '.join([str(t.hour) for t in times])])
reslists.append([str(frame), 'Time', 'Time', 'DOS', ' '.join([str(t.timetuple().tm_yday - times[0].timetuple().tm_yday) for t in times])])
for oi, o in enumerate(calcobs):
ovp = o.vi_params
for k in [k for k in ovp.keys()]:
del ovp[k]
if any([s < 0 for s in o.scale]):
logentry('Negative scaling on calculation object {}. Results may not be as expected'.format(o.name))
self.report({'WARNING'}, 'Negative scaling on calculation object {}. Results may not be as expected'.format(o.name))
ovp['omin'], ovp['omax'], ovp['oave'] = {}, {}, {}
if simnode.sdoy <= simnode.edoy:
ovp['days'] = arange(simnode.sdoy, simnode.edoy + 1, dtype=float)
else:
ovp['days'] = arange(simnode.sdoy, simnode.edoy + 1, dtype=float)
ovp['hours'] = arange(simnode.starthour, simnode.endhour + 1, 1/simnode.interval, dtype=float)
bm = bmesh.new()
bm.from_mesh(o.to_mesh())
o.to_mesh_clear()
clearlayers(bm, 'a')
bm.transform(o.matrix_world)
bm.normal_update()
geom = bm.faces if simnode.cpoint == '0' else bm.verts
geom.layers.int.new('cindex')
cindex = geom.layers.int['cindex']
[geom.layers.float.new('sm{}'.format(fi)) for fi in frange]
[geom.layers.float.new('hourres{}'.format(fi)) for fi in frange]
avres, minres, maxres, g = [], [], [], 0
if simnode.cpoint == '0':
gpoints = [f for f in geom if o.data.materials[f.material_index].vi_params.mattype == '1']
elif simnode.cpoint == '1':
gpoints = [v for v in geom if any([o.data.materials[f.material_index].vi_params.mattype == '1' for f in v.link_faces])]
for g, gp in enumerate(gpoints):
gp[cindex] = g + 1
for frame in frange:
g = 0
scene.frame_set(frame)
shadtree = rettree(scene, [ob for ob in shadobs if ob.visible_get()], ('', '1')[simnode.signore])
shadres = geom.layers.float['sm{}'.format(frame)]
if gpoints:
posis = [gp.calc_center_median() + gp.normal.normalized() * simnode.offset for gp in gpoints] if simnode.cpoint == '0' else [gp.co + gp.normal.normalized() * simnode.offset for gp in gpoints]
allpoints = zeros((len(gpoints), len(direcs)), dtype=int8)
for chunk in chunks(gpoints, int(svp['viparams']['nproc']) * 200):
for gp in chunk:
pointres = array([(0, 1)[not shadtree.ray_cast(posis[g], direc)[3]] and gp.normal.normalized().dot(direc) > 0 for direc in valdirecs], dtype=int8)
place(allpoints[g], valmask == 1, pointres)
gp[shadres] = (100 * (nsum(pointres) * ilvaldirecs)).astype(float16)
g += 1
curres += len(chunk)
if pfile.check(curres) == 'CANCELLED':
return {'CANCELLED'}
ap = average(allpoints, axis=0)
shadres = [gp[shadres] for gp in gpoints]
hsr = array(100 * ap)
ovp['ss{}'.format(frame)] = hsr.reshape(len(ovp['days']), len(ovp['hours'])).T.tolist()
reslists.append([str(frame), 'Zone temporal', o.name, 'Sunlit %', ' '.join([str(ss) for ss in hsr])])
ovp['omin']['sm{}'.format(frame)] = min(shadres)
ovp['omax']['sm{}'.format(frame)] = max(shadres)
ovp['oave']['sm{}'.format(frame)] = sum(shadres)/len(shadres)
reslists.append([str(frame), 'Zone spatial', o.name, 'X', ' '.join(['{:.3f}'.format(p[0]) for p in posis])])
reslists.append([str(frame), 'Zone spatial', o.name, 'Y', ' '.join(['{:.3f}'.format(p[1]) for p in posis])])
reslists.append([str(frame), 'Zone spatial', o.name, 'Z', ' '.join(['{:.3f}'.format(p[2]) for p in posis])])
reslists.append([str(frame), 'Zone spatial', o.name, 'Sunlit %', ' '.join(['{:.3f}'.format(sr) for sr in shadres])])
avres.append(ovp['oave']['sm{}'.format(frame)])
minres.append(ovp['omin']['sm{}'.format(frame)])
maxres.append(ovp['omax']['sm{}'.format(frame)])
reslists.append(['All', 'Frames', 'Frames', 'Frames', ' '.join(['{}'.format(f) for f in frange])])
reslists.append(['All', 'Zone spatial', o.name, 'Min. sunlit %', ' '.join(['{:.3f}'.format(mr) for mr in minres])])
reslists.append(['All', 'Zone spatial', o.name, 'Ave. sunlit %', ' '.join(['{:.3f}'.format(mr) for mr in avres])])
reslists.append(['All', 'Zone spatial', o.name, 'Max. sunlit %', ' '.join(['{:.3f}'.format(mr) for mr in maxres])])
bm.transform(o.matrix_world.inverted())
bm.to_mesh(o.data)
bm.free()
o.vi_params.vi_type_string = 'LiVi Calc'
svp.vi_leg_max, svp.vi_leg_min = 100, 0
if kivyrun.poll() is None:
kivyrun.kill()
scene.frame_start, scene.frame_end = svp['liparams']['fs'], svp['liparams']['fe']
simnode['reslists'] = reslists
simnode['frames'] = [f for f in frange]
simnode.postexport(scene)
svp['viparams']['vidisp'] = 'ss'
return {'FINISHED'}
class OBJECT_OT_EcS(bpy.types.Operator):
bl_idname = "object.ec_save"
bl_label = "Embodied material save"
def execute(self, context):
'''ID, Quantity, unit, density, weight, ec per unit, ec per kg'''
ob = context.object if context.object else context.collection
ovp = ob.vi_params
envi_ecs = envi_embodied()
envi_ecs.update()
if ovp.ec_unit == 'kg':
weight = f'{ovp.ec_amount:.4f}'
eckg = ovp.ec_du/ovp.ec_amount
ecdu = ovp.ec_du
elif ovp.ec_unit == 'tonnes':
weight = f'{ovp.ec_amount*1000:.4f}'
eckg = ovp.ec_du/ovp.ec_amount*1000
ecdu = ovp.ec_du
elif ovp.ec_unit == 'm2':
weight = f'{ovp.ec_weight:.4f}'
eckg = ovp.ec_du/ovp.ec_weight
ecdu = ovp.ec_du
elif ovp.ec_unit == 'm3':
weight = f'{ovp.ec_amount * ovp.ec_density:.4f}'
eckg = ovp.ec_du/(ovp.ec_amount * ovp.ec_density)
ecdu = ovp.ec_du
else:
weight = f'{ovp.ec_weight:.4f}'
ecdu = ovp.ec_du
eckg = ovp.ec_du/ovp.ec_weight
ec_dict = envi_ecs.get_dat()
if ovp.ec_class not in ec_dict and ovp.ec_class.upper() in [ec_class.upper() for ec_class in ec_dict]:
self.report({'ERROR'}, 'A class with this spelling but a different case already exists. Pick a different class name')
return{'CANCELLED'}
elif ovp.ec_class not in ec_dict:
#print(ovp.ec_class, ec_dict)
ec_dict[ovp.ec_class] = {}
ec_dict[ovp.ec_class][ovp.ec_type] = {}
ec_dict[ovp.ec_class][ovp.ec_type][ovp.ec_name] = {"id": ovp.ec_id,
"quantity": '{:.4f}'.format(ovp.ec_amount),
"unit": ovp.ec_unit,
"density": '{:.4f}'.format(ovp.ec_density),
"weight": weight,
"ecdu": '{:.4f}'.format(ecdu),
"eckg": '{:.4f}'.format(eckg),
"modules": ovp.ec_mod}
elif ovp.ec_type not in ec_dict[ovp.ec_class]:
ec_dict[ovp.ec_class][ovp.ec_type] = {}
ec_dict[ovp.ec_class][ovp.ec_type][ovp.ec_name] = {"id": ovp.ec_id,
"quantity": '{:.4f}'.format(ovp.ec_amount),
"unit": ovp.ec_unit,
"density": '{:.4f}'.format(ovp.ec_density),
"weight": weight,
"ecdu": '{:.4f}'.format(ecdu),
"eckg": '{:.4f}'.format(eckg),
"modules": ovp.ec_mod}
else:
ec_dict[ovp.ec_class][ovp.ec_type][ovp.ec_name] = {"id": ovp.ec_id,
"quantity": '{:.4f}'.format(ovp.ec_amount),
"unit": ovp.ec_unit,
"density": '{:.4f}'.format(ovp.ec_density),
"weight": weight,
"ecdu": '{:.4f}'.format(ecdu),
"eckg": '{:.4f}'.format(eckg),
"modules": ovp.ec_mod}
# if ovp.ec_class not in ec_dict and ovp.ec_class.upper() in [ec_class.upper() for ec_class in ec_dict]:
# self.report({'ERROR'}, 'A class with this spelling but a different case already exists. Pick a different class name')
# return{'CANCELLED'}
envi_ecs.set_dat(ec_dict)
envi_ecs.ec_save()
ovp.ee.update()
envi_eclasstype(ovp, context)
ovp.embodiedclass = ovp.ec_class
ovp.embodiedtype = ovp.ec_type
ovp.embodiedname = ovp.ec_name
return {'FINISHED'}
class OBJECT_OT_EcE(bpy.types.Operator):
bl_idname = "object.ec_edit"
bl_label = "Embodied material edit"
def execute(self, context):
ob = context.object if context.object else context.collection
ovp = ob.vi_params
envi_ecs = envi_embodied()
envi_ecs.update()
ec_dict = envi_ecs.get_dat()
ob_dict = ec_dict[ovp.embodiedclass][ovp.embodiedtype][ovp.embodiedmat]
ovp.ec_type = ovp.embodiedtype
ovp.ec_class = ovp.embodiedclass
ovp.ec_id = ob_dict['id']
ovp.ec_amount = float(ob_dict['quantity'])
ovp.ec_density = float(ob_dict['density'])
ovp.ec_mod = ob_dict['modules']
ovp.ec_unit = ob_dict['unit']
ovp.ec_name = ovp.embodiedmat
ovp.ec_du = float(ob_dict['ecdu'])
ovp.embodiedclass = 'Custom'
return {'FINISHED'}
class NODE_OT_EcE(bpy.types.Operator):
bl_idname = "node.ec_edit"
bl_label = "Embodied material edit"
def execute(self, context):
ob = context.object if context.object else context.collection
node = context.node
#ovp = ob.vi_params
envi_ecs = envi_embodied()
envi_ecs.update()
ec_dict = envi_ecs.get_dat()
node_dict = ec_dict[node.embodiedclass][node.embodiedtype][node.embodiedmat]
node.ec_class = node.embodiedclass
node.ec_type = node.embodiedtype
node.ec_id = node_dict['id']
try:
node.ec_amount = float(node_dict['quantity'])
except:
node.ec_amount = 0
try:
node.ec_density = float(node_dict['density'])
except:
node.ec_density = 0
try:
node.ec_mod = node_dict['modules']
except:
node.ec_mod = 'A1-A3'
try:
node.ec_unit = node_dict['unit']
except:
node.ec_unit = 'kg'
node.ec_name = node.embodiedmat
node.ec_du = float(node_dict['ecdu'])
node.embodiedclass = 'Custom'
return {'FINISHED'}
class NODE_OT_Li_Geo(bpy.types.Operator):
bl_idname = "node.ligexport"
bl_label = "LiVi geometry export"
def execute(self, context):
scene = context.scene
svp = scene.vi_params
svp.vi_display = 0
if viparams(self, scene):
return {'CANCELLED'}
svp['viparams']['vidisp'] = ''
svp['viparams']['viexpcontext'] = 'LiVi Geometry'
objmode()
# clearfiles(svp['liparams']['objfilebase'])
clearfiles(svp['liparams']['lightfilebase'])
node = context.node
node.preexport(scene)
radgexport(self, node)
node.postexport(scene)
return {'FINISHED'}
class NODE_OT_Li_Con(bpy.types.Operator, ExportHelper):
bl_idname = "node.liexport"
bl_label = "LiVi context export"
bl_description = "Export the scene to the Radiance file format"
bl_register = True
bl_undo = False
def invoke(self, context, event):
scene = context.scene
self.svp = scene.vi_params
self.svp.vi_display = 0
if viparams(self, scene):
return {'CANCELLED'}
node = context.node
self.svp['viparams']['vidisp'] = ''
self.svp['viparams']['viexpcontext'] = 'LiVi {}'.format(node.contextmenu)
self.svp['viparams']['connode'] = '{}@{}'.format(node.name, node.id_data.name)
self.svp.vi_views = 1
objmode()
node.preexport()
if not node.export(scene, self):
node.postexport()
return {'FINISHED'}
class NODE_OT_FileSelect(bpy.types.Operator, ImportHelper):
bl_idname = "node.fileselect"
bl_label = "Select file"
filename = ""
bl_register = True
bl_undo = True
def draw(self, context):
layout = self.layout
row = layout.row()
row.label(text="Import {} file with the file browser".format(self.filename), icon='WORLD_DATA')
row = layout.row()
def execute(self, context):
if self.filepath.split(".")[-1] in self.fextlist:
if self.nodeprop == 'epwname':
self.node.epwname = self.filepath
elif self.nodeprop == 'hdrname':
self.node.hdrname = self.filepath
elif self.nodeprop == 'skyname':
self.node.skyname = self.filepath
elif self.nodeprop == 'mtxname':
self.node.mtxname = self.filepath
elif self.nodeprop == 'resfilename':
self.node.resfilename = self.filepath
elif self.nodeprop == 'idffilename':
self.node.idffilename = self.filepath
elif self.nodeprop == 'wavname':
self.node.wavname = self.filepath
if " " in self.filepath:
self.report({'ERROR'}, "There is a space either in the filename or its directory location. Remove this space and retry opening the file.")
return {'FINISHED'}
def invoke(self, context, event):
self.node = context.node
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class NODE_OT_HdrSelect(NODE_OT_FileSelect):
bl_idname = "node.hdrselect"
bl_label = "Select HDR/VEC file"
bl_description = "Select the HDR sky image or vector file"
filename_ext = ".HDR;.hdr;"
filter_glob: bpy.props.StringProperty(default="*.HDR;*.hdr;", options={'HIDDEN'})
nodeprop = 'hdrname'
filepath: bpy.props.StringProperty(subtype='FILE_PATH', options={'HIDDEN', 'SKIP_SAVE'})
fextlist = ("HDR", "hdr")
# BSDF Operators
class OBJECT_OT_Li_GBSDF(bpy.types.Operator):
bl_idname = "object.gen_bsdf"
bl_label = "Gen BSDF"
bl_description = "Generate a BSDF for the current selected object"
bl_register = True
bl_undo = False
def modal(self, context, event):
if self.bsdfrun.poll() is None:
if self.pfile.check(0) == 'CANCELLED':
self.bsdfrun.kill()
if psu:
for proc in psutil.process_iter():
if 'rcontrib' in proc.name():
proc.kill()
else:
self.report({'ERROR'}, 'psutil not found. Kill rcontrib processes manually')
self.o.vi_params.bsdf_running = 0
return {'CANCELLED'}
else:
return {'PASS_THROUGH'}
else:
self.o.vi_params.bsdf_running = 0
filepath = os.path.join(context.scene.vi_params['viparams']['newdir'], 'bsdfs', '{}.xml'.format(self.mat.name))
if self.kivyrun.poll() is None:
self.kivyrun.kill()
with open(filepath, 'r') as bsdffile:
self.mat.vi_params['bsdf']['xml'] = bsdffile.read()
bsdf = parseString(self.mat.vi_params['bsdf']['xml'])
self.mat.vi_params['bsdf']['direcs'] = [path.firstChild.data for path in bsdf.getElementsByTagName('WavelengthDataDirection')]
self.mat.vi_params['bsdf']['type'] = [path.firstChild.data for path in bsdf.getElementsByTagName('AngleBasisName')][0]
self.mat.vi_params['bsdf']['filepath'] = filepath
self.mat.vi_params['bsdf']['proxied'] = self.o.vi_params.li_bsdf_proxy
context.scene.vi_params['viparams']['vidisp'] = 'bsdf'
return {'FINISHED'}
def execute(self, context):
scene = context.scene
svp = scene.vi_params
dp = bpy.context.evaluated_depsgraph_get()
vl = context.view_layer
self.o = context.object
ovp = self.o.vi_params
vl.objects.active = None
if viparams(self, scene):
return {'CANCELLED'}
bsdfmats = [mat for mat in self.o.data.materials if mat.vi_params.radmatmenu == '8']
if bsdfmats:
self.mat = bsdfmats[0]
mvp = self.mat.vi_params
mvp['bsdf'] = {}
else:
self.report({'ERROR'}, '{} does not have a BSDF material attached'.format(self.o.name))
bm = bmesh.new()
bm.from_object(self.o, dp)
bm.transform(self.o.matrix_world)
bm.normal_update()
bsdffaces = [face for face in bm.faces if self.o.material_slots[face.material_index].material.vi_params.radmatmenu == '8']
if bsdffaces:
fvec = bsdffaces[0].normal
# mvp['bsdf']['up'] = '{0[0]:.4f} {0[1]:.4f} {0[2]:.4f}'.format(fvec)
else:
self.report({'ERROR'}, '{} does not have a BSDF material associated with any faces'.format(self.o.name))
return
self.pfile = progressfile(svp['viparams']['newdir'], datetime.datetime.now(), 100)
self.kivyrun = progressbar(os.path.join(svp['viparams']['newdir'], 'viprogress'), 'BSDF')
zvec, yvec = mvp.li_bsdf_up, mathutils.Vector((0, 1, 0))
svec = mathutils.Vector.cross(fvec, zvec)
bsdfrotz = mathutils.Matrix.Rotation(mathutils.Vector.angle(fvec, zvec), 4, svec)
bm.transform(bsdfrotz)