Newer
Older
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
if bRotacao:
ob.keyframe_insert(data_path="rotation_euler")
if bEscala:
ob.keyframe_insert(data_path="scale")
print("Importing Blender Frame: "+str(i+obi.RunFrom+1)+"\tof "+str(len(array)-1) + "\tValue: "+ str(ival))
obi.iSumImportFrames+=1
# Fim do ELSE otimizador
# Fim bNaoValorIgual
if obi.RunFrom>= tot:
bpy.context.scene.frame_current = 1
context.scene.imp_sound_to_anim.Info_Import="Done. Imported " + str(obi.iSumImportFrames) + " Frames"
from time import strftime
print('')
print("================================================================")
print("Imported: " +str(obi.iSumImportFrames) + " Key Frames")
print("Optimizer Pass 1 prepared to optimize: " +str(obi.iSumOptimizerP1) + " blocks of Frames")
print("Optimizer Pass 2 has optimized: " +str(obi.iSumOptimizerP2) + " Frames")
print("Optimizer Pass 3 has optimized: " +str(obi.iSumOptimizerP3) + " Frames")
print("Optimizer has optimized: " +str(obi.iSumOptimizerP1 + obi.iSumOptimizerP2 + obi.iSumOptimizerP3) + " Frames")
print(strftime("End Import: %H:%M:%S - by Vlassius"))
print("================================================================")
print('')
obi.RunFrom=0
obi.iSumImportFrames=0
obi.iSumOptimizerP1=0
obi.iSumOptimizerP2=0
obi.iSumOptimizerP3=0
return obi.RunFrom
else:
obi.RunFrom+= loop
context.scene.imp_sound_to_anim.Info_Import="Processing Frame " + str(obi.RunFrom+loop) + \
" of " + str(tot-1) + " Frames"
return obi.RunFrom
#wavimport(context)
#return{'FINISHED'}
context.scene.imp_sound_to_anim.Working= "wavimport"
bpy.ops.wm.modal_timer_operator()
def invoke(self, context, event):
self.execute(context)
#==================================================================================================
# Button - Sound Process
#==================================================================================================
#
class OBJECT_OT_Botao_Go(bpy.types.Operator):
''''''
bl_idname = "import.sound_animation_botao_go"
# change in API
bl_description = "Process a .wav file, take movement from the sound and import to the scene as Key"
bl_label = "Process Wav"
filter_glob = StringProperty(default="*.wav", options={'HIDDEN'})
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
path = StringProperty(name="File Path", description="Filepath used for importing the WAV file", \
maxlen= 1024, default= "")
filename = StringProperty(name="File Name", description="Name of the file")
directory = StringProperty(name="Directory", description="Directory of the file")
RunFrom=0
Wave_read=0
MaxAudio=0
def SoundConv(File, DivSens, Sensibil, Resol, context, bAutoSense, bRemoveBeat, bUseBeat, bMoreSensible, \
bLessSensible, AudioChannel, loop):
obg= OBJECT_OT_Botao_Go
#reseta contadores caso seja pedido
if context.scene.imp_sound_to_anim.timer_reset_func:
obc.RunFrom=0
Wave_read=0
MaxAudio=0
context.scene.imp_sound_to_anim.timer_reset_func=False
#abre arquivo se primeira rodada
if obg.RunFrom==0:
try:
obg.Wave_read= wave.open(File, 'rb')
except IOError as e:
print("File Open Error: ", e)
return False
NumCh= obg.Wave_read.getnchannels()
SampW= obg.Wave_read.getsampwidth() # 8, 16, 24 32 bits
FrameR= obg.Wave_read.getframerate()
NumFr= obg.Wave_read.getnframes()
ChkCompr= obg.Wave_read.getcomptype()
if ChkCompr != "NONE":
print('Sorry, this compressed Format is NOT Supported ', ChkCompr)
context.scene.imp_sound_to_anim.Info_Import= "Sorry, this compressed Format is NOT Supported "
return False
if SampW > 2:
context.scene.imp_sound_to_anim.Info_Import= "Sorry, supported .wav files 8 and 16 bits only"
print('Sorry, supported .wav files 8 and 16 bits only')
return False
context.scene.imp_sound_to_anim.Info_Import=""
# controla numero do canal
if AudioChannel > NumCh:
if obg.RunFrom==0:
print("Channel number " + str(AudioChannel) + " is selected but this audio file has just " + \
str(NumCh) + " channels, so selecting channel " \
+ str(NumCh) + "!")
AudioChannel = NumCh
# apenas para por na tela
tmpAudioChannel= AudioChannel
#used in index sum to find the channe, adjust to first byte sample index
AudioChannel -= 1
# se dois canais, AudioChannel=4 porque sao 4 bytes
if SampW ==2: AudioChannel*=2
# usado para achar contorno da onda - achando picos
# numero de audio frames para cada video frame
BytesResol= int(FrameR/Resol)
# com 8 bits/S - razao Sample/s por resolucao
# tamanho do array
BytesDadosTotProcess= NumFr // BytesResol
if obg.RunFrom==0: # primeira rodada
# inicia array
_Interna_Globals(BytesDadosTotProcess, context)
print('')
print("================================================================")
from time import strftime
print(strftime("Go! %H:%M:%S"))
print("================================================================")
print('')
print('Total Audio Time: \t ' + str(NumFr//FrameR) + 's (' + str(NumFr//FrameR//60) + 'min)')
print('Total # Interactions: \t', BytesDadosTotProcess)
print('Total Audio Frames: \t', NumFr)
print('Frames/s: \t\t ' + str(FrameR))
print('# Chanels in File: \t', NumCh)
print('Channel to use:\t\t', tmpAudioChannel)
print('Bit/Sample/Chanel: \t ' + str(SampW*8))
print('# Frames/Act: \t\t', DivSens)
if bAutoSense==0:
print('Audio Sensitivity: \t', Sensibil+1)
else:
print('Using Auto Audio Sentivity. This is pass 1 of 2.')
print('')
print ("Sample->[value]\tAudio Frame # \t\t[Graph Value]")
if obg.RunFrom==0 and bAutoSense!=0:
Sensibil=0 # if auto sense, Sensibil must be zero here
obg.MaxAudio=0 # valor maximo de audio encontrado
# verifica limite total do audio
looptot= int(BytesDadosTotProcess // DivSens)
if obg.RunFrom+loop > looptot:
loop= looptot-obg.RunFrom
j=0 # usado de indice
# laco total leitura bytes
# armazena dado de pico
for jj in range(loop):
# caso de 2 canais (esterio)
# uso apenas 2 bytes em 16 bits, ie, apenas canal esquerdo
# [0] e [1] para CH L
# [2] e [3] para CH R and so on
# mono:1 byte to 8 bits, 2 bytes to 16 bits
# sterio: 2 byte to 8 bits, 4 bytes to 16 bits
ValorPico=0
# leio o numero de frames de audio para cada frame de video, valor em torno de 1000
for i in range(BytesResol):
#loop exterior copia DivSens frames a cada frame calculado
frame = obg.Wave_read.readframes(DivSens)
if len(frame)==0: break
if bAutoSense==0: # AutoAudioSense Desligado
if SampW ==1:
if Sensibil ==5:
frame0= frame[AudioChannel] << 6 & 255
elif Sensibil ==4:
frame0= frame[AudioChannel] << 5 & 255
elif Sensibil ==3:
frame0= frame[AudioChannel] << 4 & 255
elif Sensibil ==2:
frame0= frame[AudioChannel] << 3 & 255
elif Sensibil ==1:
frame0= frame[AudioChannel] << 2 & 255
elif Sensibil ==0:
frame0= frame[AudioChannel]
if frame0> ValorPico:
ValorPico= frame0
if SampW ==2: # frame[0] baixa frame[1] ALTA BIT 1 TEM SINAL!
if frame[1+AudioChannel] <127: # se bit1 =0, usa o valor - se bit1=1 quer dizer numero negativo
if Sensibil ==0:
frame0= frame[1+AudioChannel]
elif Sensibil ==4:
frame0= ((frame[AudioChannel] & 0b11111100) >> 2) | ((frame[1+AudioChannel] & 0b00000011) << 6)
elif Sensibil ==3:
frame0= ((frame[AudioChannel] & 0b11110000) >> 4) | ((frame[1+AudioChannel] & 0b00001111) << 4)
elif Sensibil ==2:
frame0= ((frame[AudioChannel] & 0b11100000) >> 5) | ((frame[1+AudioChannel] & 0b00011111) << 3)
elif Sensibil ==1:
frame0= ((frame[AudioChannel] & 0b11000000) >> 6) | ((frame[1+AudioChannel] & 0b00111111) << 2)
elif Sensibil ==5:
frame0=frame[AudioChannel]
if frame0 > ValorPico:
ValorPico= frame0
else: # AutoAudioSense Ligado
if SampW ==1:
if frame[AudioChannel]> obg.MaxAudio:
obg.MaxAudio = frame[AudioChannel]
if frame[AudioChannel]> ValorPico:
ValorPico=frame[AudioChannel]
if SampW ==2:
if frame[1+AudioChannel] < 127:
tmpValorPico= frame[1+AudioChannel] << 8
tmpValorPico+= frame[AudioChannel]
if tmpValorPico > obg.MaxAudio:
obg.MaxAudio = tmpValorPico
if tmpValorPico > ValorPico:
ValorPico= tmpValorPico
if bAutoSense==0: #autoaudiosense desligado
# repito o valor de frames por actions (OTIMIZAR)
for ii in range(DivSens):
array[j+obg.RunFrom]=ValorPico # valor de pico encontrado
j +=1 # incrementa indice prox local
else:
idx=obg.RunFrom*2 # porque sao dois bytes
arrayAutoSense[j+idx]= (ValorPico & 0b0000000011111111) #copia valores baixos
arrayAutoSense[j+1+idx]= (ValorPico & 0b1111111100000000) >> 8 #copia valores altos
j+=2
if bAutoSense==0: #autoaudiosense desligado
igraph= ValorPico//10
else:
if SampW ==2:
igraph= ValorPico//1261
else:
igraph= ValorPico//10
stgraph="["
for iii in range(igraph):
stgraph+="+"
for iiii in range(26-igraph):
stgraph+=" "
stgraph+="]"
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
print ("Sample-> " + str(ValorPico) + "\tAudio Frame # " + str(jj+obg.RunFrom) + " of " + str(looptot-1) + "\t"+ stgraph)
# acabou primeira fase roda toda de uma vez
if obg.RunFrom+loop == looptot:
if bAutoSense==1:
print("")
print("================================================================")
print('Calculating Auto Audio Sentivity, pass 2 of 2.')
print("================================================================")
# caso usar batida, procurar por valores proximos do maximo e zerar restante.
# caso retirar batida, zerar valores proximos do maximo
UseMinim=0
UseMax=0
if bUseBeat==1:
print("Trying to use just the beat.")
UseMinim= obg.MaxAudio*0.8
if bMoreSensible:
UseMinim= obg.MaxAudio*0.7
elif bLessSensible:
UseMinim= obg.MaxAudio*0.9
if bRemoveBeat==1:
print("Trying to exclude the beat.")
UseMax= obg.MaxAudio*0.7
if bMoreSensible:
UseMax= obg.MaxAudio*0.8
elif bLessSensible:
UseMax= obg.MaxAudio*0.7
print("")
# para transformar 15 bits em 8 calibrando valor maximo -> fazer regra de 3
# obg.MaxAudio -> 255
# outros valores => valor calibrado= (255 * Valor) / obg.MaxAudio
scale= 255/obg.MaxAudio
j=0
jj=0
print ("Sample->[value]\tAudio Frame # \t\t[Graph Value]")
for i in range(BytesDadosTotProcess // DivSens):
ValorOriginal= arrayAutoSense[j+1] << 8
ValorOriginal+= arrayAutoSense[j]
if bUseBeat==1:
if ValorOriginal < UseMinim:
ValorOriginal = 0
elif bRemoveBeat==1:
if ValorOriginal > UseMax:
ValorOriginal = 0
ValorOriginal= ((round(ValorOriginal * scale)) & 0b11111111) #aplica a escala
for ii in range(DivSens):
array[jj] = ValorOriginal
jj += 1 # se autoaudiosense, o array tem dois bytes para cada valor
j+=2
igraph= round(array[jj-1]/10)
stgraph="["
for iii in range(igraph):
stgraph+="+"
for iiii in range(26-igraph):
stgraph+=" "
stgraph+="]"
print ("Sample-> " + str(array[jj-1]) + "\tAudio Frame # " + str(i) + " of " + str(looptot-1) + "\t"+ stgraph)
#limpa array tmp
del arrayAutoSense[:]
# mensagens finais
context.scene.imp_sound_to_anim.Info_Import= "Click \"Import Key frames\" to begin import" #this set the initial text
print("================================================================")
from time import strftime
print(strftime("End Process: %H:%M:%S"))
print("================================================================")
try:
obg.Wave_read.close()
except:
print('File Close Error')
obg.RunFrom=0
return obg.RunFrom # acabou tudo
else:#ainda nao acabou o arquivo todo if RunFrom+loop = looptot:
context.scene.imp_sound_to_anim.Info_Import="Processing " + str(obg.RunFrom) + " of " + str(looptot) +" Audio Frames"
# force update info text in UI
bpy.context.scene.frame_current= bpy.context.scene.frame_current
obg.RunFrom+=loop
return obg.RunFrom
def ProcessaSom(context, loop):
obg= OBJECT_OT_Botao_Go
# para de entrar o timer
context.scene.imp_sound_to_anim.Working=""
#reseta contadores caso seja pedido
if context.scene.imp_sound_to_anim.timer_reset_func:
obg.RunFrom=0
context.scene.imp_sound_to_anim.timer_reset_func=False
import os
f= os.path.join(context.scene.imp_sound_to_anim.directory, context.scene.imp_sound_to_anim.filename)
if obg.RunFrom==0:
print ("")
print ("")
print ("Selected file = ",f)
checktype = f.split('\\')[-1].split('.')[1]
if checktype.upper() != 'WAV':
print ("ERROR!! Selected file = ", f)
print ("ERROR!! Its not a .wav file")
return
#sensibilidade volume do audio 0 a 5. Quanto maior, mais sensibilidade
iAudioSensib= int(context.scene.imp_sound_to_anim.audio_sense)-1
if iAudioSensib <0: iAudioSensib=0
elif iAudioSensib>5: iAudioSensib=5
#act/s nao pode se maior que frames/s
if context.scene.imp_sound_to_anim.action_per_second > context.scene.imp_sound_to_anim.frames_per_second:
context.scene.imp_sound_to_anim.action_per_second = context.scene.imp_sound_to_anim.frames_per_second
#Frames por segundo para key frame
iFramesPorSeg= int(context.scene.imp_sound_to_anim.frames_per_second)
#Sensibilidade de movimento. 3= 3 movimentos por segundo
iMovPorSeg= int(context.scene.imp_sound_to_anim.action_per_second)
#iDivMovPorSeg Padrao - taxa 4/s ou a cada 0,25s => iFramesPorSeg/iDivMovPorSeg= ~0.25
for i in range(iFramesPorSeg):
iDivMovPorSeg=iFramesPorSeg/(i+1)
if iFramesPorSeg/iDivMovPorSeg >=iMovPorSeg:
break
bRemoveBeat= context.scene.imp_sound_to_anim.remove_beat
bUseBeat= context.scene.imp_sound_to_anim.use_just_beat
bLessSensible= context.scene.imp_sound_to_anim.beat_less_sensible
bMoreSensible= context.scene.imp_sound_to_anim.beat_more_sensible
AudioChannel= context.scene.imp_sound_to_anim.audio_channel_select
# chama funcao de converter som, retorna preenchendo _Interna_Globals.array
index= OBJECT_OT_Botao_Go.SoundConv(f, int(iDivMovPorSeg), iAudioSensib, iFramesPorSeg, context, \
context.scene.imp_sound_to_anim.action_auto_audio_sense, bRemoveBeat, \
bUseBeat, bMoreSensible, bLessSensible, AudioChannel, loop)
return index
def execute(self, context):
# copia dados dialof open wave
context.scene.imp_sound_to_anim.filter_glob= self.filter_glob
context.scene.imp_sound_to_anim.path = self.path
context.scene.imp_sound_to_anim.filename = self.filename
context.scene.imp_sound_to_anim.directory = self.directory
context.scene.imp_sound_to_anim.Working= "ProcessaSom"
bpy.ops.wm.modal_timer_operator()
#ProcessaSom(context)
return{'FINISHED'}
def invoke(self, context, event):
#need to set a path so so we can get the file name and path
wm = context.window_manager
wm.fileselect_add(self)
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
return {'RUNNING_MODAL'}
#
#==================================================================================================
# Button - Check Smart Render
#==================================================================================================
#
class OBJECT_OT_Botao_Check_SmartRender(bpy.types.Operator):
'''Check for Reduction'''
bl_idname = "import.sound_animation_botao_check_smartrender"
bl_label = "Check Smart Render"
RunFrom=0
Frames_Renderizar=0
Frames_Pular=0
def CheckSmartRender(context, loop):
obc= OBJECT_OT_Botao_Check_SmartRender
#reseta contadores caso seja pedido
if context.scene.imp_sound_to_anim.timer_reset_func:
obc.RunFrom=0
obc.Frames_Pular=0
obc.Frames_Renderizar=0
context.scene.imp_sound_to_anim.timer_reset_func=False
if obc.RunFrom==0:
if loop !=1: # loop==1 quando estou chamando de dentro da funcao render
print("")
print("================================================================")
print('Running Check Smart Render...')
#garante ao menos locrotscale ligado
if context.scene.imp_sound_to_anim.check_smartrender_loc_rot_sc==False and \
context.scene.imp_sound_to_anim.check_smartrender_material_basic==False and \
context.scene.imp_sound_to_anim.check_smartrender_material_transparence==False and \
context.scene.imp_sound_to_anim.check_smartrender_material_mirror==False:
context.scene.imp_sound_to_anim.check_smartrender_loc_rot_sc=True
chkLocRotSc= context.scene.imp_sound_to_anim.check_smartrender_loc_rot_sc
chkMatBas= context.scene.imp_sound_to_anim.check_smartrender_material_basic
chkMatTransp= context.scene.imp_sound_to_anim.check_smartrender_material_transparence
chkMatMirror= context.scene.imp_sound_to_anim.check_smartrender_material_mirror
ToRender=[]
origloop=loop
from copy import copy
RunMax= bpy.context.scene.frame_end - bpy.context.scene.frame_start+1
if obc.RunFrom+loop > RunMax:
loop= RunMax-obc.RunFrom
if loop<=0: #acabou
if origloop !=1: # loop==1 quando estou chamando de dentro da funcao render
print("")
print("Frames to copy: " + str(obc.Frames_Pular) + " Frames to really render= " + str(obc.Frames_Renderizar))
print("================================================================")
print("")
obc.RunFrom=0
obc.Frames_Pular=0
obc.Frames_Renderizar=0
return (ToRender, obc.RunFrom)
#move para o primeiro frame a renderizar
#RunFrom inicia em zero - frames inicia em 1
bpy.context.scene.frame_current = obc.RunFrom+bpy.context.scene.frame_start
for k in range(loop):
if obc.RunFrom==0 and k==0: #primeiro sempre renderiza
ToRender.append(bpy.context.scene.frame_current)
obc.Frames_Renderizar+=1
bpy.context.scene.frame_set(bpy.context.scene.frame_current + 1)
else:
if origloop !=1: # loop==1 quando estou chamando de dentro da funcao render
import sys
sys.stdout.write("\rChecking Frame "+str(bpy.context.scene.frame_current) + " ")
sys.stdout.flush()
#buffer de todos os objetos
a=[]
for obj in bpy.data.objects:
if chkLocRotSc:
# loc rot scale
a.append(copy(obj.location))
a.append(copy(obj.rotation_euler))
a.append(copy(obj.scale))
if hasattr(obj.data, 'materials') and obj.data.materials.keys()!=[] :
if bpy.context.scene.render.engine == "BLENDER_RENDER":
#pega somente primeiro material sempre
if chkMatBas:
# cores
a.append(copy(obj.data.materials[0].type))
a.append(copy(obj.data.materials[0].emit))
a.append(copy(obj.data.materials[0].diffuse_color))
a.append(copy(obj.data.materials[0].diffuse_intensity))
a.append(copy(obj.data.materials[0].specular_intensity))
a.append(copy(obj.data.materials[0].specular_color))
a.append(copy(obj.data.materials[0].alpha))
a.append(copy(obj.data.materials[0].diffuse_shader))
a.append(copy(obj.data.materials[0].specular_shader))
a.append(copy(obj.data.materials[0].specular_hardness))
if chkMatTransp:
# transp
a.append(copy(obj.data.materials[0].transparency_method))
a.append(copy(obj.data.materials[0].specular_alpha))
a.append(copy(obj.data.materials[0].raytrace_transparency.fresnel))
a.append(copy(obj.data.materials[0].raytrace_transparency.ior))
a.append(copy(obj.data.materials[0].raytrace_transparency.filter))
a.append(copy(obj.data.materials[0].raytrace_transparency.depth))
a.append(copy(obj.data.materials[0].translucency))
a.append(copy(obj.data.materials[0].specular_alpha))
if chkMatMirror:
#mirror
a.append(copy(obj.data.materials[0].raytrace_mirror.reflect_factor))
a.append(copy(obj.data.materials[0].raytrace_mirror.fresnel))
a.append(copy(obj.data.materials[0].raytrace_mirror.fresnel_factor))
a.append(copy(obj.data.materials[0].mirror_color))
a.append(copy(obj.data.materials[0].raytrace_mirror.depth))
a.append(copy(obj.data.materials[0].raytrace_mirror.gloss_factor))
# tenho todos os objetos em a[]
# incrementar um frame e checar se eh igual
bpy.context.scene.frame_set(bpy.context.scene.frame_current + 1)
j=0
dif=0
for obj in bpy.data.objects:
if chkLocRotSc:
if a[j]!= obj.location or a[j+1]!= obj.rotation_euler or a[j+2]!= obj.scale:
dif=1
#break
j+=3
if hasattr(obj.data, 'materials') and obj.data.materials.keys()!=[] :
if bpy.context.scene.render.engine == "BLENDER_RENDER":
if chkMatBas:
# cores
if a[j]!= obj.data.materials[0].type or a[j+1]!= obj.data.materials[0].emit or \
a[j+2]!= obj.data.materials[0].diffuse_color or \
a[j+3]!= obj.data.materials[0].diffuse_intensity or \
a[j+4]!= obj.data.materials[0].specular_intensity or \
a[j+5]!= obj.data.materials[0].specular_color or \
a[j+6]!= obj.data.materials[0].alpha or \
a[j+7]!= obj.data.materials[0].diffuse_shader or \
a[j+8]!= obj.data.materials[0].specular_shader or \
a[j+9]!= obj.data.materials[0].specular_hardness:
dif=1
print("mat")
j+= 10 # ajusta ponteiro j
if chkMatTransp: j+=8
if chkMatMirror: j+=6
break
j+=10
if chkMatTransp:
#transp
if a[j]!= obj.data.materials[0].transparency_method or a[j+1]!= obj.data.materials[0].specular_alpha or \
a[j+2]!= obj.data.materials[0].raytrace_transparency.fresnel or \
a[j+3]!= obj.data.materials[0].raytrace_transparency.ior or \
a[j+4]!= obj.data.materials[0].raytrace_transparency.filter or \
a[j+5]!= obj.data.materials[0].raytrace_transparency.depth or \
a[j+6]!= obj.data.materials[0].translucency or \
a[j+7]!= obj.data.materials[0].specular_alpha:
dif=1
j+= 8 # ajusta ponteiro j
if chkMatMirror: j+=6
break
j+=8
if chkMatMirror:
#mirror
if a[j]!= obj.data.materials[0].raytrace_mirror.reflect_factor or a[j+1]!= obj.data.materials[0].raytrace_mirror.fresnel or \
a[j+2]!= obj.data.materials[0].raytrace_mirror.fresnel_factor or \
a[j+3]!= obj.data.materials[0].mirror_color or \
a[j+4]!= obj.data.materials[0].raytrace_mirror.depth or \
a[j+5]!= obj.data.materials[0].raytrace_mirror.gloss_factor:
dif=1
j+= 6 # ajusta ponteiro j
break
j+=6
# finaliza
if dif==0:
obc.Frames_Pular+=1
else:
obc.Frames_Renderizar+=1
ToRender.append(bpy.context.scene.frame_current)
del a
# para nao sair do index - nunca chega nesse frame
ToRender.append(bpy.context.scene.frame_end+1)
if obc.RunFrom+loop < RunMax:
context.scene.imp_sound_to_anim.Info_check_smartrender= "["+str(obc.RunFrom+loop) + "/" + \
str(RunMax) + "] Frames to Render= " + str(obc.Frames_Renderizar) + \
" -> Reduction " + str(round((obc.Frames_Pular/RunMax)*100,1)) + "%"
else:
context.scene.imp_sound_to_anim.Info_check_smartrender= "Frames to Render= " + str(obc.Frames_Renderizar) + \
" -> Reduction " + str(round((obc.Frames_Pular/RunMax)*100,1)) + "%"
#incrementa indice
obc.RunFrom+= loop
return (ToRender, obc.RunFrom)
def execute(self, context):
context.scene.imp_sound_to_anim.Working= "CheckSmartRender"
#context.scene.imp_sound_to_anim.timer_reset_func=True
bpy.ops.wm.modal_timer_operator()
#CheckSmartRender(context)
return{'FINISHED'}
def invoke(self, context, event):
self.execute(context)
return {'FINISHED'}
#
#==================================================================================================
# Button - Smart Render
#==================================================================================================
#
class OBJECT_OT_Botao_SmartRender(bpy.types.Operator):
'''Render Only Modified Frames and Copy the Others'''
bl_idname = "import.sound_animation_smart_render"
bl_label = "Smart Render"
BaseRenderToCopy=0
def SmartRender(context):
obs=OBJECT_OT_Botao_SmartRender
index=0
pad=4
#calcula zero pad
if bpy.context.scene.frame_end //1000000 > 0: #default 999999 1000000//1000000=1
pad=7
elif bpy.context.scene.frame_end //100000 > 0: #default 99999 100000//100000=1
pad=6
elif bpy.context.scene.frame_end //10000 > 0: #default 9999 10000//10000=1
pad=5
#bpy.data.images['Render Result'].file_format ='PNG'
bpy.context.scene.render.image_settings.file_format = 'PNG'
#info dos arquivos
path= bpy.context.scene.render.filepath
import shutil
tot=bpy.context.scene.frame_end - bpy.context.scene.frame_start+1
i=0
# checa apenas 1 frame o indice é interno em ChackSmartRender
r= OBJECT_OT_Botao_Check_SmartRender.CheckSmartRender(context, 1)
ToRender= r[0] # tem numero do frame se for para renderizar
index= r[1]
#copia frame atual #se o frame ja não foi renderizado
if (obs.BaseRenderToCopy!=(index+bpy.context.scene.frame_start-1)) and index > 1: #index!=1 and index !=0:
print("Copying: " + str(obs.BaseRenderToCopy) + "-> " + str(index+bpy.context.scene.frame_start-1) + \
" To " + path + str(index+bpy.context.scene.frame_start-1).zfill(pad) + ".png")
shutil.copy2(path + str(obs.BaseRenderToCopy).zfill(pad) + ".png", path + \
str(index+bpy.context.scene.frame_start-1).zfill(pad) + ".png")
if ToRender.__len__()>1: #renderizar 1 item em ToRender nao renderiza, (sempre vem com no minimo 1)
if index==1:
print("================================================================")
from time import strftime
print(strftime("Running Smart Render: %H:%M:%S"))
print("================================================================")
BaseRenderToCopy=0
if ToRender[0] <= bpy.context.scene.frame_end:
#renderiza proximo frame
print("Rendering-> " + str(ToRender[0]))
obs.BaseRenderToCopy= ToRender[0]
bpy.ops.render.render(animation=False, write_still=False)
bpy.data.images['Render Result'].save_render(filepath=path + str(ToRender[0]).zfill(pad) + ".png")
i+=1
if index==tot:
print("================================================================")
from time import strftime
print(strftime("Finish Render: %H:%M:%S"))
print("================================================================")
print(".")
if index==tot+1:
obs.BaseRenderToCopy=0
return 0
return index
def execute(self, context):
# se for CYCLES, nao funciona com timer, preciso rodar direto
context.scene.imp_sound_to_anim.Working= "SmartRender"
bpy.ops.wm.modal_timer_operator()
#SmartRender(context)
return{'FINISHED'}
def invoke(self, context, event):
self.execute(context)
return {'FINISHED'}
#
#==================================================================================================
# Button - Cancel
#==================================================================================================
#
class OBJECT_OT_Botao_Cancel(bpy.types.Operator):
'''Cancel Actual Operation'''
bl_idname = "import.sound_animation_botao_cancel"
bl_label = "CANCEL"
def execute(self, context):
context.scene.imp_sound_to_anim.cancel_button_hit=True
return{'FINISHED'}
def invoke(self, context, event):
self.execute(context)
return {'FINISHED'}
#
#==================================================================================================
# TIMER - controla a execucao das funcoes
# Responsavel por rodar em partes usando o timer e possibilitando
# o cancelamento e textos informativos
#==================================================================================================
#
class ModalTimerOperator(bpy.types.Operator):
"""Internal Script Control"""
bl_idname = "wm.modal_timer_operator"
bl_label = "Internal Script Control"
_timer = None
Running= False
def CheckRunStop(self, context, func, index):
# forca update do UI
bpy.context.scene.frame_set(bpy.context.scene.frame_current)
if index!=0:
#configura timer para a funcao
context.scene.imp_sound_to_anim.Working= func
self.Running=True
return {'PASS_THROUGH'}
else: # posso desligar o timer e modal
if self._timer!= None:
context.window_manager.event_timer_remove(self._timer)
self._timer= None
return {'FINISHED'}
def modal(self, context, event):
if event.type == 'ESC'and self.Running:
print("-- ESC Pressed --")
self.cancel(context)
context.scene.imp_sound_to_anim.Working=""
self.Running=False
#reseta contadores
context.scene.imp_sound_to_anim.timer_reset_func=True
# forca update do UI
bpy.context.scene.frame_set(bpy.context.scene.frame_current)
return {'CANCELLED'}
if event.type == 'TIMER':
#print("timer")
#CheckSmartRender
if context.scene.imp_sound_to_anim.Working== "CheckSmartRender":
self.parar(context)
#5= frames para rodar antes de voltar [1]= indice de posicao atual
index= OBJECT_OT_Botao_Check_SmartRender.CheckSmartRender(context, 5)[1]
return self.CheckRunStop(context, "CheckSmartRender", index)
#SmartRender
elif context.scene.imp_sound_to_anim.Working== "SmartRender":
self.parar(context)
#render/copia 1 e volta index>=0 indice posicao atual
index= OBJECT_OT_Botao_SmartRender.SmartRender(context)
return self.CheckRunStop(context, "SmartRender", index)
#ProcessaSom
elif context.scene.imp_sound_to_anim.Working== "ProcessaSom":
self.parar(context)
# loop = numero de frames de audio index=0 se terminou ou >0 se não acabou
index= OBJECT_OT_Botao_Go.ProcessaSom(context, 50)
return self.CheckRunStop(context, "ProcessaSom", index)
#wavimport(context)
elif context.scene.imp_sound_to_anim.Working== "wavimport":
self.parar(context)
# 5= numero de frames to import por timer
index=OBJECT_OT_Botao_Import.wavimport(context, 50)
return self.CheckRunStop(context, "wavimport", index)
#passa por aqui quando as funcoes estao sendo executadas mas
#configuradas para nao entrar porque context.scene.imp_sound_to_anim.Working== ""
return {'PASS_THROUGH'}
# reseta e para tudo botao CANCEL pressionado
if context.scene.imp_sound_to_anim.cancel_button_hit==True:
context.scene.imp_sound_to_anim.Working=""
#pede reset contadores
context.scene.imp_sound_to_anim.timer_reset_func=True
if self._timer!= None:
context.window_manager.event_timer_remove(self._timer)
self._timer= None
print("-- Cancel Pressed --")
context.scene.imp_sound_to_anim.cancel_button_hit=False
return {'FINISHED'}
#print("modal")
# se o timer esta ativado, continua, (senao termina).
# desligar a chamada ao modal se caso chegar aqui (nao deveria)
if self._timer!= None:
return{'PASS_THROUGH'}
else:
return {'FINISHED'}
def execute(self, context):
if self._timer==None:
self._timer = context.window_manager.event_timer_add(0.2, context.window)
context.window_manager.modal_handler_add(self)
#para deixar rodar sem deligar o timer
context.scene.imp_sound_to_anim.timer_desligar=False
self.Running=True
return {'RUNNING_MODAL'}
def cancel(self, context):
if self._timer!= None:
context.window_manager.event_timer_remove(self._timer)
self._timer= None
return {'CANCELLED'}
def parar(self, context):
if self.Running:
context.scene.imp_sound_to_anim.Working=""
self.Running=False
#
#==================================================================================================
# Register - Unregister - MAIN
#==================================================================================================
#
def register():
bpy.utils.register_module(__name__)
bpy.types.Scene.imp_sound_to_anim = PointerProperty(type=ImpSoundtoAnim, name="Import: Sound to Animation", description="Extract movement from sound file. See the Object Panel at the end.")
try:
bpy.utils.unregister_module(__name__)
except:
pass
try:
bpy.types.INFO_MT_file_import.remove(WavFileImport)
except:
pass