-
Notifications
You must be signed in to change notification settings - Fork 4
/
latk_rw.py
1776 lines (1647 loc) · 69.6 KB
/
latk_rw.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
# READ / WRITE
import bpy
import bpy_extras
from mathutils import Vector, Matrix
import os
import zipfile
import io
from io import BytesIO
from . latk import *
from . latk_mesh import *
from . latk_mtl import *
from . latk_tools import *
from . latk_draw import *
from . latk_svg import *
def writeBrushStrokes(filepath=None, bake=True, roundValues=True, numPlaces=7, zipped=False, useScaleAndOffset=True, globalScale=Vector((0.1, 0.1, 0.1)), globalOffset=Vector((0.0, 0.0, 0.0))):
if(bake == True):
bakeFrames()
latkObj = fromGpToLatk(bake=bake, skipLocked=False, useScaleAndOffset=useScaleAndOffset, globalScale=globalScale, globalOffset=globalOffset)
latkObj.write(filepath=filepath, zipped=zipped, useScaleAndOffset=useScaleAndOffset, globalScale=globalScale, globalOffset=globalOffset)
#~
return {'FINISHED'}
def readBrushStrokes(filepath=None, resizeTimeline=True, useScaleAndOffset=True, doPreclean=False, limitPalette=0, globalScale=Vector((10.0, 10.0, 10.0)), globalOffset=Vector((0.0, 0.0, 0.0)), clearExisting=False, cleanFactor=0.01):
latkObj = Latk()
latkObj.read(filepath=filepath, useScaleAndOffset=useScaleAndOffset, globalScale=globalScale, globalOffset=globalOffset)
#~
if (doPreclean == True):
latkObj.clean(epsilon=cleanFactor)
#~
fromLatkToGp(la=latkObj, resizeTimeline=resizeTimeline, useScaleAndOffset=useScaleAndOffset, limitPalette=limitPalette, globalScale=globalScale, globalOffset=globalOffset, clearExisting=clearExisting)
#~
if (resizeTimeline==True):
doResizeTimeline()
#~
return {'FINISHED'}
rb = readBrushStrokes
wb = writeBrushStrokes
def fromGpToLatk(bake=False, skipLocked=False, useScaleAndOffset=False, globalScale=(1.0, 1.0, 1.0), globalOffset=(0.0, 0.0, 0.0)):
print("Begin building Latk object from Grease Pencil...")
if(bake == True):
bakeFrames()
gp = getActiveGp()
palette = getActivePalette()
#~
la = Latk()
la.frame_rate = getSceneFps()
#~
for layer in gp.data.layers:
if (skipLocked == False or layer.lock == False):
laLayer = LatkLayer(name=layer.info.replace(" ", "_"))
if (layer.parent == True):
laLayer.parent = layer.parent.name
for frame in layer.frames:
laFrame = LatkFrame(frame_number=frame.frame_number)
if (layer.parent == True):
laFrame.parent_location = layer.parent.location
for stroke in frame.strokes:
laStroke = LatkStroke()
color = (0,0,0,1)
fill_color = (0,0,0,1)
try:
color = palette[stroke.material_index].grease_pencil.color
fill_color = palette[stroke.material_index].grease_pencil.fill_color
except:
pass
laStroke.color = color
laStroke.fill_color = fill_color
for point in stroke.points:
x = point.co[0]
y = point.co[1]
z = point.co[2]
pressure = 1.0
pressure = point.pressure
strength = 1.0
strength = point.strength
vertex_color = (0.0,0.0,0.0,0.0)
vertex_color = point.vertex_color
#~
if (useScaleAndOffset == True):
x = (x * globalScale[0]) + globalOffset[0]
y = (y * globalScale[1]) + globalOffset[1]
z = (z * globalScale[2]) + globalOffset[2]
#~
laPoint = LatkPoint((x, y, z), pressure, strength, vertex_color)
laStroke.points.append(laPoint)
laFrame.strokes.append(laStroke)
laLayer.frames.append(laFrame)
la.layers.append(laLayer)
print("...end building Latk object from Grease Pencil.")
return la
def fromLatkToGp(la=None, resizeTimeline=True, useScaleAndOffset=False, limitPalette=0, globalScale=(1.0, 1.0, 1.0), globalOffset=(0.0, 0.0, 0.0), clearExisting=False):
print("Begin building Grease Pencil from Latk object...")
if (clearExisting == True):
clearAll()
#gp = getActiveGp()
gp = createGp(_newMaterial=False, _newLayer=False)
longestFrameNum = 1
#~
for laLayer in la.layers:
layer = gp.data.layers.new(laLayer.name.replace(" ", "_"), set_active=True)
#~
for i, laFrame in enumerate(laLayer.frames):
try:
frame = layer.frames.new(laLayer.frames[i].frame_number)
except:
frame = layer.frames.new(i)
if (frame.frame_number > longestFrameNum):
longestFrameNum = frame.frame_number
for laStroke in laFrame.strokes:
strokeColor = (0,0,0)
try:
color = laStroke.color
strokeColor = (color[0], color[1], color[2])
except:
pass
if (limitPalette == 0):
createColor(strokeColor)
else:
createAndMatchColorPalette(strokeColor, limitPalette, 5) # num places
stroke = frame.strokes.new()
stroke.display_mode = '3DSPACE'
#stroke.line_width = 100 # for 2.79
#stroke.line_width = 10 # for 2.93
stroke.line_width = 1 # for 3.5
stroke.material_index = gp.active_material_index
laPoints = laStroke.points
stroke.points.add(len(laPoints))
for l, laPoint in enumerate(laPoints):
co = laPoint.co
x = co[0]
y = co[1]
z = co[2]
pressure = 1.0
strength = 1.0
vertex_color = (0.0,0.0,0.0,0.0)
if (useScaleAndOffset == True):
x = (x * globalScale[0]) + globalOffset[0]
y = (y * globalScale[1]) + globalOffset[1]
z = (z * globalScale[2]) + globalOffset[2]
#~
if (laPoint.pressure != None):
pressure = laPoint.pressure
if (laPoint.strength != None):
strength = laPoint.strength
if (laPoint.vertex_color != None):
vertex_color = laPoint.vertex_color
createPoint(stroke, l, (x, y, z), pressure, strength, vertex_color)
#~
if (resizeTimeline == True):
setStartEnd(0, longestFrameNum, pad=False)
print("...end building Grease Pencil from Latk object.")
'''
def readBrushStrokesAlt(filepath=None, resizeTimeline=True, useScaleAndOffset=False, doPreclean=False, limitPalette=0, globalScale=Vector((10, 10, 10)), globalOffset=Vector((0, 0, 0))):
url = filepath # compatibility with gui keywords
#~
gp = getActiveGp()
data = None
#~
filename = os.path.split(url)[1].split(".")
filetype = filename[len(filename)-1].lower()
if (filetype == "latk" or filetype == "zip"):
imz = InMemoryZip()
imz.readFromDisk(url)
# https://stackoverflow.com/questions/6541767/python-urllib-error-attributeerror-bytes-object-has-no-attribute-read/6542236
data = json.loads(imz.files[0].decode("utf-8"))
else:
with open(url) as data_file:
data = json.load(data_file)
#~
longestFrameNum = 1
for layerJson in data["grease_pencil"][0]["layers"]:
layer = gp.data.layers.new(layerJson["name"], set_active=True)
palette = getActivePalette()
#~
for i, frameJson in enumerate(layerJson["frames"]):
try:
frame = layer.frames.new(layerJson["frames"][i]["frame_number"])
except:
frame = layer.frames.new(i)
if (frame.frame_number > longestFrameNum):
longestFrameNum = frame.frame_number
for strokeJson in frameJson["strokes"]:
strokeColor = (0,0,0)
try:
colorJson = strokeJson["color"]
strokeColor = (colorJson[0], colorJson[1], colorJson[2])
except:
pass
if (limitPalette == 0):
createColor(strokeColor)
else:
createAndMatchColorPalette(strokeColor, limitPalette, 5) # num places
stroke = frame.strokes.new(getActiveColor().name)
stroke.draw_mode = "3DSPACE" # either of ("SCREEN", "3DSPACE", "2DSPACE", "2DIMAGE")
pointsJson = strokeJson["points"]
stroke.points.add(len(pointsJson)) # add 4 points
for l, pointJson in enumerate(pointsJson):
coJson = pointJson["co"]
x = coJson[0]
y = coJson[2]
z = coJson[1]
pressure = 1.0
strength = 1.0
if (useScaleAndOffset == True):
x = (x * globalScale.x) + globalOffset.x
y = (y * globalScale.y) + globalOffset.y
z = (z * globalScale.z) + globalOffset.z
#~
if ("pressure" in pointJson):
pressure = pointJson["pressure"]
if ("strength" in pointJson):
strength = pointJson["strength"]
#stroke.points[l].co = (x, y, z)
createPoint(stroke, l, (x, y, z), pressure, strength)
#~
if (resizeTimeline == True):
setStartEnd(0, longestFrameNum, pad=False)
#~
if (doPreclean == True):
latkObj = fromGpToLatk()
latkObj.clean()
fromLatkToGp(latkObj)
return {'FINISHED'}
# http://blender.stackexchange.com/questions/24694/query-grease-pencil-strokes-from-python
def writeBrushStrokesAlt(filepath=None, bake=True, roundValues=True, numPlaces=7, zipped=False, useScaleAndOffset=False, globalScale=Vector((0.1, 0.1, 0.1)), globalOffset=Vector((0, 0, 0))):
url = filepath # compatibility with gui keywords
#~
if(bake == True):
bakeFrames()
gp = bpy.context.scene.grease_pencil
palette = getActivePalette()
#~
sg = []
sg.append("{")
sg.append("\t\"creator\": \"blender\",")
sg.append("\t\"grease_pencil\": [")
sg.append("\t\t{")
sg.append("\t\t\t\"frame_rate\": " + str(getSceneFps()) + ",")
sg.append("\t\t\t\"layers\": [")
#~
sl = []
for f, layer in enumerate(gp.data.layers):
sb = []
for h, frame in enumerate(layer.frames):
currentFrame = h
goToFrame(h)
sb.append("\t\t\t\t\t\t{") # one frame
sb.append("\t\t\t\t\t\t\t\"frame_number\": " + str(frame.frame_number) + ",")
if (layer.parent == True):
sb.append("\t\t\t\t\t\t\t\"parent_location\": " + "[" + str(layer.parent.location[0]) + ", " + str(layer.parent.location[1]) + ", " + str(layer.parent.location[2]) + "],")
sb.append("\t\t\t\t\t\t\t\"strokes\": [")
if (len(frame.strokes) > 0):
sb.append("\t\t\t\t\t\t\t\t{") # one stroke
for i, stroke in enumerate(frame.strokes):
color = (0,0,0)
alpha = 0.9
fill_color = (1,1,1)
fill_alpha = 0.0
try:
col = palette.colors[stroke.colorname]
color = col.color
alpha = col.alpha
fill_color = col.fill_color
fill_alpha = col.fill_alpha
except:
pass
sb.append("\t\t\t\t\t\t\t\t\t\"color\": [" + str(color[0]) + ", " + str(color[1]) + ", " + str(color[2])+ "],")
sb.append("\t\t\t\t\t\t\t\t\t\"alpha\": " + str(alpha) + ",")
sb.append("\t\t\t\t\t\t\t\t\t\"fill_color\": [" + str(fill_color[0]) + ", " + str(fill_color[1]) + ", " + str(fill_color[2])+ "],")
sb.append("\t\t\t\t\t\t\t\t\t\"fill_alpha\": " + str(fill_alpha) + ",")
sb.append("\t\t\t\t\t\t\t\t\t\"points\": [")
for j, point in enumerate(stroke.points):
x = point.co.x
y = point.co.z
z = point.co.y
pressure = 1.0
pressure = point.pressure
strength = 1.0
strength = point.strength
#~
if useScaleAndOffset == True:
x = (x * globalScale.x) + globalOffset.x
y = (y * globalScale.y) + globalOffset.y
z = (z * globalScale.z) + globalOffset.z
#~
if roundValues == True:
sb.append("\t\t\t\t\t\t\t\t\t\t{\"co\": [" + roundVal(x, numPlaces) + ", " + roundVal(y, numPlaces) + ", " + roundVal(z, numPlaces) + "], \"pressure\": " + roundVal(pressure, numPlaces) + ", \"strength\": " + roundVal(strength, numPlaces))
else:
sb.append("\t\t\t\t\t\t\t\t\t\t{\"co\": [" + str(x) + ", " + str(y) + ", " + str(z) + "], \"pressure\": " + str(pressure) + ", \"strength\": " + str(strength))
#~
if j == len(stroke.points) - 1:
sb[len(sb)-1] +="}"
sb.append("\t\t\t\t\t\t\t\t\t]")
if (i == len(frame.strokes) - 1):
sb.append("\t\t\t\t\t\t\t\t}") # last stroke for this frame
else:
sb.append("\t\t\t\t\t\t\t\t},") # end stroke
sb.append("\t\t\t\t\t\t\t\t{") # begin stroke
else:
sb[len(sb)-1] += "},"
if i == len(frame.strokes) - 1:
sb.append("\t\t\t\t\t\t\t]")
else:
sb.append("\t\t\t\t\t\t\t]")
if h == len(layer.frames) - 1:
sb.append("\t\t\t\t\t\t}")
else:
sb.append("\t\t\t\t\t\t},")
#~
sf = []
sf.append("\t\t\t\t{")
sf.append("\t\t\t\t\t\"name\": \"" + layer.info + "\",")
if (layer.parent):
sf.append("\t\t\t\t\t\"parent\": \"" + layer.parent.name + "\",")
sf.append("\t\t\t\t\t\"frames\": [")
sf.append("\n".join(sb))
sf.append("\t\t\t\t\t]")
if (f == len(gp.data.layers)-1):
sf.append("\t\t\t\t}")
else:
sf.append("\t\t\t\t},")
sl.append("\n".join(sf))
#~
sg.append("\n".join(sl))
sg.append("\t\t\t]")
sg.append("\t\t}")
sg.append("\t]")
sg.append("}")
#~
if (zipped == True):
filenameRaw = os.path.split(url)[1].split(".")
filename = ""
for i in range(0, len(filenameRaw)-1):
filename += filenameRaw[i]
imz = InMemoryZip()
imz.append(filename + ".json", "\n".join(sg))
imz.writetofile(url)
else:
with open(url, "w") as f:
f.write("\n".join(sg))
f.closed
print("Wrote " + url)
#~
return {'FINISHED'}
'''
def doResizeTimeline():
longestFrameNum = 1
gp = getActiveGp()
for layer in gp.data.layers:
if (len(layer.frames) > longestFrameNum):
longestFrameNum = len(layer.frames)
setStartEnd(0, longestFrameNum, pad=False)
def exportAlembic(url="test.abc"):
bpy.ops.wm.alembic_export(filepath=url, vcolors=True, face_sets=True, renderable_only=False)
def exportForUnity(filepath=None, sketchFab=True):
#origFilepath = ""
#if not filepath:
#filepath = getFilePath()
#else:
filepath = filepath.split(".fbx")[0] + "_"
rootFilepath = filepath.split(getFileName())[0]
#~
start, end = getStartEnd()
target = matchName("latk")
sketchFabList = []
sketchFabListNum = []
for tt in range(0, len(target)):
deselect()
for i in range(start, end):
deselect()
goToFrame(i)
if (target[tt].hide==False):
deselect()
target[tt].select=True
exportName = target[tt].name
exportName = exportName.split("latk_")[1]
exportName = exportName.split("_mesh")[0]
exporter(url=filepath, manualSelect=True, fileType="fbx", name=exportName, legacyFbx=True)
sketchFabList.append(str(1.0/getSceneFps()) + " " + getFileName() + "_" + exportName + ".fbx\r") #"0.083 " + exportName + ".fbx\r")
sketchFabListNum.append(float(exportName.split("_")[len(exportName.split("_"))-1]))
break
if (sketchFab==True):
print("before sort: ")
print(sketchFabList)
print(sketchFabListNum)
# this sorts entries by number instead of order in Outliner pane
sketchFabList.sort(key=lambda x: x[0])
ind = [i[0] for i in sorted(enumerate(sketchFabListNum),key=lambda x: x[1])]
sketchFabList = [i[0] for i in sorted(zip(sketchFabList, ind),key=lambda x: x[1])]
#~
print(getFilePath() + getFileName())
tempName = exportName.split("_")
tempString = ""
for i in range(0, len(tempName)-1):
tempString += str(tempName[i])
if (i < len(tempName)-1):
tempString += "_"
print("after sort: ")
print(sketchFabList)
#writeTextFile(filepath + getFileName() + "_" + tempString + ".sketchfab.timeframe", sketchFabList)
writeTextFile(rootFilepath + "sketchfab.timeframe", sketchFabList)
def exporter(name="test", url=None, winDir=False, manualSelect=False, fileType="fbx", legacyFbx=False):
if not url:
url = getFilePath()
if (winDir==True):
url += "\\"
else:
url += "/"
#~
if (fileType.lower() == "alembic"):
bpy.ops.wm.alembic_export(filepath=name + ".abc", vcolors=True, face_sets=True, renderable_only=False)
else:
if (manualSelect == True):
if (fileType.lower()=="fbx"):
if (legacyFbx == True):
bpy.ops.export_scene.fbx(filepath=url + name + ".fbx", use_selection=True, version="ASCII6100") # legacy version
else:
bpy.ops.export_scene.fbx(filepath=url + name + ".fbx", use_selection=True, version="BIN7400")
else:
bpy.ops.export_scene.obj(filepath=url + name + ".obj", use_selection=True)
else:
for j in range(bpy.context.scene.frame_start, bpy.context.scene.frame_end + 1):
bpy.ops.object.select_all(action='DESELECT')
goToFrame(j)
for i in range(0, len(bpy.data.objects)):
if (bpy.data.objects[i].hide == False):
bpy.data.objects[i].select = True
#bpy.context.scene.update()
#~
if (fileType=="fbx"):
if (legacyFbx == True):
bpy.ops.export_scene.fbx(filepath=url + name + "_" + str(j) + ".fbx", use_selection=True, version="ASCII6100") # legacy version
else:
bpy.ops.export_scene.fbx(filepath=url + name + "_" + str(j) + ".fbx", use_selection=True, version="BIN7400")
else:
bpy.ops.export_scene.obj(filepath=url + name + "_" + str(j) + ".obj", use_selection=True)
def importAppend(blendfile, section, obj, winDir=False):
# http://blender.stackexchange.com/questions/38060/how-to-link-append-with-a-python-script
# blendfile = "D:/path/to/the/repository.blend"
# section = "\\Action\\"
# obj = "myaction"
#~
url = blendfile + section + obj
if (winDir==True):
section = blendfile + "\\" + section + "\\"
else:
section = blendfile + "/" + section + "/"
#~
bpy.ops.wm.append(filepath=url, filename=obj, directory=section)
def writeTextFile(name="test.txt", lines=None):
file = open(name,"w")
for line in lines:
file.write(line)
file.close()
def readTextFile(name="text.txt"):
file = open(name, "r")
return file.read()
def newFile():
bpy.ops.wm.read_homefile()
def saveFile(name, format=True):
if (format==True):
name = getFilePath() + name + ".blend"
bpy.ops.wm.save_as_mainfile(filepath=name)
def openFile(name, format=True):
if (format==True):
name = getFilePath() + name + ".blend"
bpy.ops.wm.open_mainfile(filepath=name)
def writeSvg(filepath=None):
# Note: keep fps at 12 or below to prevent timing artifacts.
# Last frame in timeline must be empty.
minLineWidth=3
camera = getActiveCamera()
palette = getActivePalette()
fps = float(getSceneFps())
start, end = getStartEnd()
duration = float(end - start) / fps
gp = getActiveGp()
#url = getFilePath() + name
url = filepath
print(url)
sW = getSceneResolution()[0]
sH = getSceneResolution()[1]
svg = []
#~
# HEADER
svg.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r");
svg.append("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\r")
svg.append("<svg version=\"1.1\" id=\"Layer_1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"\r")
svg.append("\t" + "width=\"" + str(sW) + "px\" height=\"" + str(sH) + "px\" viewBox=\"0 0 " + str(sW) + " " + str(sH) + "\" enable-background=\"new 0 0 " + str(sW) + " " + str(sH) +"\" xml:space=\"preserve\">\r")
#~
# BODY
for layer in gp.data.layers:
layerInfo = layer.info.replace(" ", "_").replace(".", "_")
svg.append("\t" + "<g id=\"" + layerInfo + "\">\r")
for i, frame in enumerate(layer.frames):
goToFrame(frame.frame_number)
svg.append("\t\t" + "<g id=\"" + layerInfo + "_frame" + str(i) + "\">\r")
for stroke in frame.strokes:
width = stroke.line_width
if (width == None or width < minLineWidth):
width = minLineWidth
#color = palette.colors[stroke.colorname]
color = palette[stroke.material_index].grease_pencil
#print("found color: " + color.name)
cStroke = (color.color[0], color.color[1], color.color[2], color.color[3])
cFill = (color.fill_color[0], color.fill_color[1], color.fill_color[2], color.fill_color[3])
svg.append("\t\t\t" + svgStroke(points=stroke.points, stroke=(cStroke[0], cStroke[1], cStroke[2]), fill=(cFill[0], cFill[1], cFill[2]), strokeWidth=minLineWidth, strokeOpacity=cStroke[3], fillOpacity=cFill[3], camera=camera) + "\r")
#~
svg.append("\t\t\t" + svgAnimate(frame=frame.frame_number, fps=fps, duration=duration) + "\r")
svg.append("\t\t" + "</g>\r")
svg.append("\t" + "</g>\r")
#~
# FOOTER
svg.append("</svg>\r")
#~
writeTextFile(url, svg)
def svgAnimate(frame=0, fps=12, duration=10, startFrame=False, endFrame=False):
keyIn = (float(frame) / float(fps)) / float(duration)
keyOut = keyIn + (1.0/float(fps))
returns = "<animate attributeName=\"display\" repeatCount=\"indefinite\" dur=\"" + str(duration) + "s\" keyTimes=\"0;" + str(keyIn) + ";" + str(keyOut) + ";1\" values=\"none;inline;none;none\"/>"
return returns
def svgStroke(points=None, stroke=(0,0,1), fill=(1,0,0), strokeWidth=2.0, strokeOpacity=1.0, fillOpacity=1.0, camera=None, closed=False):
# https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path
returns = "<path stroke=\""+ normRgbToHex(stroke) + "\" fill=\""+ normRgbToHex(fill) + "\" stroke-width=\"" + str(strokeWidth) + "\" stroke-opacity=\"" + str(strokeOpacity) + "\" fill-opacity=\"" + str(fillOpacity) + "\" d=\""
for i, point in enumerate(points):
co = getWorldCoords(co=point.co, camera=camera)
if (i == 0):
returns += "M" + str(co[0]) + " " + str(co[1]) + " "
elif (i > 0 and i < len(points)-1):
returns += "L" + str(co[0]) + " " + str(co[1]) + " "
elif (i == len(points)-1):
if (closed==True):
returns += "L" + str(co[0]) + " " + str(co[1]) + " z"
else:
returns += "L" + str(co[0]) + " " + str(co[1])
returns += "\"/>"
return returns
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
def writeAeJsx(filepath=None, useNulls=False):
header = aeHeader(useNulls)
footer = aeFooter()
camera = getActiveCamera()
gp = getActiveGp()
palette = getActivePalette()
body = []
body.append("var layer, group, shape, pathGroup, pathFill, pathStroke;")
body.append("var counter = 1;")
body.append("var nullCounter = 1;")
lastFrameNumber = bpy.context.scene.frame_end
for h in reversed(range(0, len(gp.data.layers))):
layer = gp.data.layers[h]
for i, frame in enumerate(layer.frames):
goToFrame(frame.frame_number)
frameLines = None
if (len(layer.frames) < 2):
frameLines = aeFrame(layer, frame.frame_number, lastFrameNumber)
else:
if (i < len(layer.frames)-1):
frameLines = aeFrame(layer, frame.frame_number, layer.frames[i+1].frame_number)
else:
frameLines = aeFrame(layer, frame.frame_number, lastFrameNumber)
for line in frameLines:
body.append(line)
for stroke in frame.strokes:
# 2.7 color handling
#color = palette.colors[stroke.colorname]
color = palette[stroke.material_index].grease_pencil
strokeColor = (color.color[0], color.color[1], color.color[2])
fillColor = (color.fill_color[0], color.fill_color[1], color.fill_color[2])
# 2.7 color handling
#fillAlpha = color.fill_alpha
fillAlpha = color.fill_color[3]
strokeLines = aeStroke(stroke, camera, strokeColor, fillColor, fillAlpha, useNulls)
for line in strokeLines:
body.append(line)
jsx = []
for line in header:
jsx.append(line + "\r")
for line in body:
jsx.append("\t" + line + "\r")
for line in footer:
jsx.append(line + "\r")
writeTextFile(filepath, jsx)
def aeStroke(stroke, camera, strokeColor, fillColor, fillAlpha, useNulls):
offsetW = bpy.context.scene.render.resolution_x / 2.0
offsetH = bpy.context.scene.render.resolution_y / 2.0
returns = []
points = []
for point in stroke.points:
points.append(getWorldCoords(co=point.co, camera=camera, useRenderScale=False))
verts2D = "["
for i, point in enumerate(points):
verts2D += "[" + str(point[0] - offsetW) + "," + str(point[1] - offsetH) + "]"
if (i < len(points)-1):
verts2D += ","
verts2D += "]"
verts = "["
if (useNulls == True):
for i, point in enumerate(stroke.points):
verts += "[" + str(point.co[0] * 100) + "," + str(point.co[1] * 100) + "," + str(point.co[2] * 100) + "]"
if (i < len(stroke.points)-1):
verts += ","
verts += "]"
returns.append("")
returns.append("shape = new Shape();")
returns.append("shape.closed = false;")
returns.append("shape.vertices = " + verts2D + ";")
returns.append("pathGroup = group.content.addProperty(\"ADBE Vector Shape - Group\");")
returns.append("pathGroup.property(\"ADBE Vector Shape\").setValue(shape);")
returns.append("pathStroke = group.content.addProperty(\"ADBE Vector Graphic - Stroke\");")
returns.append("pathStroke.color.setValue([" + str(strokeColor[0]) + "," + str(strokeColor[1]) + "," + str(strokeColor[2]) + "]);")
if (fillAlpha > 0.001):
returns.append("pathFill = group.content.addProperty(\"ADBE Vector Graphic - Fill\");")
returns.append("pathFill.color.setValue([" + str(fillColor[0]) + "," + str(fillColor[1]) + "," + str(fillColor[2]) + "]);")
if (useNulls == True):
returns.append("var pathHierarchy = [];")
returns.append("var nullSet = [];")
returns.append("var pathPoints = " + verts + ";")
returns.append("for (var i = 0, ii = pathPoints.length; i < ii; i++) {")
returns.append("\tvar nullName = layer.name + \"_\" + nullCounter;")
returns.append("\tnullCounter++;")
returns.append("\tnullSet.push(\"thisComp.layer(\\\"\" + nullName + \"\\\")\");")
returns.append("")
returns.append("\tvar newNull = myComp.layers.addNull();")
returns.append("\tnewNull.threeDLayer = true;")
returns.append("\tnewNull.moveBefore(layer);")
returns.append("\tnewNull.name = nullName;")
returns.append("\tnewNull.label = 11;")
returns.append("\tnewNull.position.setValue(pathPoints[i]);")
returns.append("}")
returns.append("")
returns.append("group.property(\"Contents\").property(\"Path \" + counter).property(\"Path\").expression =")
returns.append("\t\t\t\"var nullLayers = [ \" + nullSet.join(\",\") + \" ]; \\r\" +")
returns.append("\t\t\t\"var origPath = thisProperty; \\r\" +")
returns.append("\t\t\t\"var origPoints = origPath.points(); \\r\" +")
returns.append("\t\t\t\"var origInTang = origPath.inTangents(); \\r\" +")
returns.append("\t\t\t\"var origOutTang = origPath.outTangents(); \\r\" +")
returns.append("\t\t\t\"\\r\" +")
returns.append("\t\t\t\"for (var i=0; i<origPoints.length; i++) {\\r\" +")
returns.append("\t\t\t\" origPoints[i] = fromCompToSurface(nullLayers[i].toComp(nullLayers[i].anchorPoint));\\r\" +")
returns.append("\t\t\t\"}\\r\" +")
returns.append("\t\t\t\"createPath(origPoints, origInTang, origOutTang, origPath.isClosed());\";")
returns.append("counter++;")
return returns
def aeFrame(layer, inPoint, outPoint):
name = layer.info + "_" + str(inPoint);
fps = float(bpy.context.scene.render.fps)
startTime = float(inPoint) / fps
endTime = float(outPoint) / fps
returns = []
returns.append("layer = myComp.layers.addShape();")
returns.append("layer.name = \"" + name + "\";")
returns.append("layer.startTime = " + str(startTime) + ";")
returns.append("layer.outPoint = " + str(endTime) + ";")
returns.append("group = layer.content.addProperty(\"ADBE Vector Group\");")
return returns
def aeHeader(useNulls):
returns = []
gp = getActiveGp()
compName = gp.name
compW = str(bpy.context.scene.render.resolution_x)
compH = str(bpy.context.scene.render.resolution_y)
fps = str(bpy.context.scene.render.fps)
#compL = str(float32((bpy.context.scene.frame_end / bpy.context.scene.render.fps)))
compL = str((bpy.context.scene.frame_end / bpy.context.scene.render.fps))
returns.append("{ //start script")
returns.append("\t" + "app.beginUndoGroup(\"Create Comp from Grease Pencil\");")
returns.append("")
returns.append("\t" + "// create project if necessary")
returns.append("\t" + "var proj = app.project;")
returns.append("\t" + "if(!proj) proj = app.newProject();")
returns.append("")
returns.append("\t" + "// create new comp")
returns.append("\t" + "var compW = " + compW + "; // comp width")
returns.append("\t" + "var compH = " + compH + "; // comp height")
returns.append("\t" + "var compL = " + compL + "; // comp length (seconds)")
returns.append("\t" + "var compRate = " + fps + "; // comp frame rate")
returns.append("\t" + "var compBG = [0/255,0/255,0/255] // comp background color")
returns.append("\t" + "var myItemCollection = app.project.items;")
returns.append("\t" + "var myComp = myItemCollection.addComp(\"" + compName + "\",compW,compH,1,compL,compRate);")
returns.append("\t" + "myComp.bgColor = compBG;")
returns.append("")
return returns
def aeFooter():
returns = []
returns.append("")
returns.append("\t" + "app.endUndoGroup();")
returns.append("} //end script")
return returns
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
def writePainter(filepath=None):
camera=getActiveCamera()
outputFile = []
dim = (float(getSceneResolution()[0]), float(getSceneResolution()[1]), 0.0)
outputFile.append(painterHeader(dim))
#~
strokes = []
gp = getActiveGp()
palette = getActivePalette()
for layer in gp.data.layers:
if (layer.lock == False):
for stroke in layer.active_frame.strokes:
strokes.append(stroke)
counter = 0
for stroke in strokes:
color = palette.colors[stroke.color.name].color
points = []
for point in stroke.points:
co = getWorldCoords(co=point.co, camera=camera)
x = co[0]
y = co[1]
prs = point.pressure
point = (x, y, prs, counter)
counter += 1
points.append(point)
outputFile.append(painterStroke(points, color))
#~
outputFile.append(painterFooter())
writeTextFile(filepath, outputFile)
def painterHeader(dim=(1024,1024,1024), bgColor=(1,1,1)):
s = "script_version_number version 10\r"
s += "artist_name \"\"\r"
s += "start_time date Wed, May 24, 2017 time 3:23 PM\r"
s += "start_random 1366653360 1884255589\r"
#s += "variant \"Painter Brushes\" \"F-X\" \"Big Wet Luscious\"\r"
#s += "max_size_slider 14.00000\r"
#s += "min_radius_fraction_slider 0.20599\r"
s += "build\r"
s += "penetration_slider 100 percent\r"
#s += "texture \"Paper Textures\" \"<str t=17500 i=001>\"\r"
s += "grain_inverted unchecked\r"
s += "directional_grain unchecked\r"
s += "scale_slider 1.00000\r"
s += "paper_brightness_slider 0.50000\r"
s += "paper_contrast_slider 1.00000\r"
s += "portfolio_change \"\"\r"
#s += "gradation \"Painter Gradients.gradients\" \"<str t=17503 i=001>\"\r"
#s += "weaving \"Painter Weaves.weaves\" \"<str t=17504 i=001>\"\r"
#s += "pattern_change \"Painter Patterns\" \"<str t=17001 i=001>\"\r"
#s += "path_library_change \"Painter Selections\"\r"
#s += "nozzle_change \"Painter Nozzles\" \"<str t=17000 i=001>\"\r"
s += "use_brush_grid unchecked\r"
s += "new_tool 1\r"
s += "gradation_options type 0 order 0 angle 0.00 spirality 1.000\r"
s += "pattern_options pattern_type 1 offset 0.594\r"
s += "preserve_transparency unchecked\r"
s += "wind_direction 4.712389\r"
#s += "color red 1 green 109 blue 255\r"
#s += "background_color red 255 green 4 blue 4\r"
#s += "change_file \"ntitled-1\"\r"
s += "new_3 \"Untitled-1\" width " + str(int(dim[0])) + " height " + str(int(dim[1])) + " resolution 72.00000 width_unit 1 height_unit 1 resolution_unit 1 paper_color red " + str(int(bgColor[0] * 255.0)) + " green " + str(int(bgColor[1] * 255.0)) + " blue " + str(int(bgColor[2] * 255.0)) + " movie 0 frames 1\r"
return s
def painterFooter():
s = "end_time date Wed, May 24, 2017 time 3:25 PM\r"
return s
def painterStroke(points, color=(0,0,0)):
s = "color red " + str(int(color[0]*255.0)) + " green " + str(int(color[1]*255.0)) + " blue " + str(int(color[2]*255.0)) + "\r"
s += "stroke_start\r"
for point in points:
s += painterPoint(point)
s += "stroke_end\r"
return s
def painterPoint(point):
x = point[0]
y = point[1]
time = point[3]
s = "pnt x " + str(x) + " y " + str(y) + " time " + str(time) + " prs " + str(roundVal(point[2], 2)) + " tlt 0.00 brg 0.00 whl 1.00 rot 0.00\r"
return s
# ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
def importVRDoodler(filepath=None):
globalScale = Vector((1, 1, 1))
globalOffset = Vector((0, 0, 0))
useScaleAndOffset = True
#numPlaces = 7
#roundValues = True
with open(filepath) as data_file:
data = data_file.readlines()
vrd_strokes = []
vrd_points = []
for line in data:
if str(line).startswith("l") == True:
if (len(vrd_points) > 0):
vrd_strokes.append(vrd_points)
vrd_points = []
elif str(line).startswith("v") == True:
vrd_pointRaw = line.split()
vrd_point = (-1 * float(vrd_pointRaw[1]), float(vrd_pointRaw[2]), float(vrd_pointRaw[3]))
vrd_points.append(vrd_point)
gp = getActiveGp()
layer = gp.data.layers.new("VRDoodler_layer", set_active=True)
start, end = getStartEnd()
frame = layer.frames.new(start)
for vrd_stroke in vrd_strokes:
strokeColor = (0.5,0.5,0.5)
createColor(strokeColor)
stroke = frame.strokes.new(getActiveColor().name)
stroke.draw_mode = "3DSPACE" # either of ("SCREEN", "3DSPACE", "2DSPACE", "2DIMAGE")
stroke.points.add(len(vrd_stroke)) # add 4 points
for l, vrd_point in enumerate(vrd_stroke):
x = vrd_point[0]
y = vrd_point[2]
z = vrd_point[1]
pressure = 1.0
strength = 1.0
if useScaleAndOffset == True:
x = (x * globalScale.x) + globalOffset.x
y = (y * globalScale.y) + globalOffset.y
z = (z * globalScale.z) + globalOffset.z
#~
createPoint(stroke, l, (x, y, z), pressure, strength)
def importPainter(filepath=None):
globalScale = Vector((1, 1, -1))
globalOffset = Vector((0, 0, 0))
useScaleAndOffset = True
#numPlaces = 7
#roundValues = True
gp = getActiveGp()
layer = gp.data.layers.new("Painter_layer", set_active=True)
start, end = getStartEnd()
frame = getActiveFrame()
if not frame:
frame = layer.frames.new(start)
width = 0
height = 0
points = []
pressures = []
with open(filepath) as data_file:
data = data_file.readlines()
for line in data:
if (line.startswith("new")):
vals = line.split(" ")
for i, val in enumerate(vals):
if (val == "width"):
width = float(vals[i+1])
elif (val == "height"):
height = float(vals[i+1])
elif (line.startswith("color")):
r = 0
g = 0
b = 0
vals = line.split(" ")
for i, val in enumerate(vals):
if (val == "red"):
r = float(vals[i+1]) / 255.0
if (val == "green"):
g = float(vals[i+1]) / 255.0
if (val == "blue"):
b = float(vals[i+1]) / 255.0
createColor((r, g, b))
elif (line.startswith("stroke_start")):
points = []
pressures = []
elif (line.startswith("pnt")):
vals = line.split(" ")
x = 0
y = 0
z = 0
pressure = 0
for i, val in enumerate(vals):
if (val == "x"):
x = float(vals[i+1]) / width
elif (val == "y"):
y = float(vals[i+1]) / height
elif (val == "prs"):
pressure = float(vals[i+1])
points.append((x, y, z))
pressures.append(pressure)
elif (line.startswith("stroke_end")):
stroke = frame.strokes.new(getActiveColor().name)
stroke.draw_mode = "3DSPACE"
stroke.points.add(len(points))
for i in range(0, len(points)):
point = points[i]
x = point[0]
y = point[2]
z = point[1]
pressure = pressures[i]
strength = 1.0
if useScaleAndOffset == True:
x = (x * globalScale.x) + globalOffset.x
y = (y * globalScale.y) + globalOffset.y
z = (z * globalScale.z) + globalOffset.z
createPoint(stroke, i, (x, y, z), pressure, strength)
def importNorman(filepath=None):
globalScale = Vector((1, 1, 1))
globalOffset = Vector((0, 0, 0))
useScaleAndOffset = True
#numPlaces = 7
#roundValues = True
#~
with open(filepath) as data_file:
data = json.load(data_file)
#~
frames = []
for i in range(0, len(data["data"])):
strokes = []
for j in range(0, len(data["data"][i])):
points = []
for k in range(0, len(data["data"][i][j])):
points.append((data["data"][i][j][k]["x"], data["data"][i][j][k]["y"], data["data"][i][j][k]["z"]))
strokes.append(points)
frames.append(strokes)
#~
gp = getActiveGp()
layer = gp.data.layers.new("Norman_layer", set_active=True)
for i in range(0, len(frames)):
frame = layer.frames.new(i)
for j in range(0, len(frames[i])):
strokeColor = (0.5,0.5,0.5)
createColor(strokeColor)
stroke = frame.strokes.new(getActiveColor().name)
stroke.draw_mode = "3DSPACE" # either of ("SCREEN", "3DSPACE", "2DSPACE", "2DIMAGE")
stroke.points.add(len(frames[i][j])) # add 4 points
for l in range(0, len(frames[i][j])):
x = 0.0
y = 0.0
z = 0.0
pressure = 1.0
strength = 1.0
if useScaleAndOffset == True:
x = (frames[i][j][l][0] * globalScale.x) + globalOffset.x
y = (frames[i][j][l][2] * globalScale.y) + globalOffset.y
z = (frames[i][j][l][1] * globalScale.z) + globalOffset.z
else:
x = frames[i][j][l][0]
y = frames[i][j][l][2]
z = frames[i][j][l][1]
#~