forked from katiemorrisfx/KMFX-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmfx_paintpresets.py
210 lines (157 loc) · 6.67 KB
/
kmfx_paintpresets.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
import fx, sys, json, glob, os
from fx import *
fx.prefs.add("KMFX.Paint Presets Path","")
class GenericJSONEncoder(json.JSONEncoder):
def default(self, obj):
try:
return super().default(obj)
except TypeError:
pass
cls = type(obj)
result = {
'__custom__': True,
'__name__': cls.__name__}
if cls == Point3D:
result["data"] = {"x":obj.x,"y":obj.y,"z":obj.z}
elif cls == Rect:
result["data"] = {"size":obj.size}
else:
result["data"] = obj.__dict__ if not hasattr(cls, '__json_encode__') else obj.__json_encode__
return result
class GenericJSONDecoder(json.JSONDecoder):
def simpledecode(self,t):
if t['__name__'] == "Point3D":
return Point3D(t["data"]["x"],t["data"]["y"],t["data"]["z"])
elif t['__name__'] == "Rect":
temp = Rect(0,0,0,0)
temp.setSize(t["data"]["size"][0],t["data"]["size"][1])
return temp
else:
return t
def decode(self, str):
result = super().decode(str)
mresult = {}
for key in result.keys():
if isinstance(result[key],list):
#print(result[key],"\n")
mresult[key] = []
for n in range(0,len(result[key])):
mresult[key].append(self.simpledecode(result[key][n]))
else:
if not isinstance(result[key], dict) or not result[key].get('__custom__', False):
#print("regular",result)
mresult[key] = result[key]
else:
#print(result[key],type(result[key]),"\n")
if isinstance(result[key],list):
#print(result[key],"\n")
for n in range(0,len(result[key])):
mresult[key][n] = simpledecode(result[key][n])
else:
if result[key]['__name__'] == "Point3D":
#print("x",result[key]["data"][0])
mresult[key] = Point3D(result[key]["data"]["x"],result[key]["data"]["y"],result[key]["data"]["z"])
elif result[key]['__name__'] == "Rect":
mresult[key] = Rect(0,0,0,0)
# print(result[key]["data"]["size"])
mresult[key].setSize(result[key]["data"]["size"][0],result[key]["data"]["size"][1])
#instance.__dict__.update(result['data'])
return mresult
class KMFXpaintPresets(Action):
"""this will save/load the actual state of the paint node to/from disk"""
def __init__(self,):
Action.__init__(self, "KMFX|Paint Presets")
def available(self):
pass # verification on execution
def execute(self,**kwargs):
# fx.beginUndo("KMFX Paint Presets") # undo is not working on this
paint_presets_path = fx.prefs["KMFX.Paint Presets Path"] if fx.prefs["KMFX.Paint Presets Path"]!= "" else os.environ["SFX_SCRIPT_PATH"] + "/KMscripts/paint_presets/"
#### check if the custom pref path exists and warn user if its wrong
if paint_presets_path == fx.prefs["KMFX.Paint Presets Path"]:
if not os.path.exists(paint_presets_path):
displayError("The custom path '%s' could be wrong or\nwas not found or can't be read,\nplease check your KMFX preferences!\nFalling back to default path\n %s " % (paint_presets_path,os.environ["SFX_SCRIPT_PATH"] + "/KMscripts/paint_presets/"))
# print("The custom path '%s' could be wrong / was not found / can't be read, please check your preferences\n falling back to default path\n %s " % (paint_presets_path,os.environ["SFX_SCRIPT_PATH"] + "/KMscripts/paint_presets/"))
paint_presets_path = os.environ["SFX_SCRIPT_PATH"] + "/KMscripts/paint_presets/"
mode = kwargs["mode"] if "mode" in kwargs.keys() else "save"
node = activeNode()
if node.type == "PaintNode":
'''
the actual brush used it saved on the <item type="string" id="brush"> on the preset.
looks like the settings for the rest of the preset are not necessary
'''
fx.activeProject().save() ##small hack to force the state to update
if mode == "save":
fname = { "id" : "fname", "label" : "Filename", "value" : "Default"}
result = getInput(fields=[fname])
current = fx.paint.preset
override = False
if result != None:
dpath = paint_presets_path+"/"+result["fname"]+"/"
directory = os.path.dirname(dpath)
if os.path.exists(directory):
ov=askQuestion("Preset already exists, override?")
if ov == False:
return # do not use this with UNDO
try:
if not os.path.exists(directory):
os.makedirs(directory)
except:
print("Error creating preset directory, check folder write permissions?\n %s" % directory)
for i in range(0,10):
fpath = paint_presets_path+"/"+result["fname"]+"/"+result["fname"]+"_"+str(i)+'.json'
try:
fx.paint.preset= i
if len(node.state["preset"+str(i)]) > 0:
dic = node.state["preset"+str(i)]
ppreset = json.dumps(dic,cls=GenericJSONEncoder)
with open(fpath, 'w') as file:
file.write(ppreset)
print("Saved preset %s @ %s" % (i,fpath))
except:
print("Preset %s skipped"% i)
if os.path.exists(fpath):
os.remove(fpath)
print("Old Preset %s removed"% i)
# e = sys.exc_info()
# print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
try:
fx.paint.preset = current ## go back to original active preset
except:
pass
elif mode == "load":
jsonFiles = glob.glob(paint_presets_path+"/**/*.json",recursive=True)
filelist = {}
namecollection = []
presetsfound = False
if len(jsonFiles) > 0:
for f in jsonFiles:
name = os.path.basename(f)
name = str(name).rsplit("_",1)[0]
namecollection.append(name)
namecollection= list(set(namecollection))
presetsfound = True
else:
resulterror = getInput(title="Error", msg="No presets found")
if presetsfound:
lista = { "id" : "list", "label" : "List", "value" : namecollection[0], "items" : namecollection }
result = getInput(fields=[lista])
loadedpresets = []
if result != None:
for i in range(0,10):
fx.paint.preset = i
try:
node.setState("preset"+str(i),None)
with open(paint_presets_path+"/"+result["list"]+"/"+result["list"]+"_"+str(i)+'.json') as complex_data:
data = complex_data.read()
b = json.loads(data, cls=GenericJSONDecoder)
for ii in b.keys():
fx.paint.setState(ii,b[ii])
fx.paint.savePreset(i)
loadedpresets.append(i)
except:
pass
fx.paint.preset = min(loadedpresets) ## loads the first available preset
# e = sys.exc_info()
# print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)
# fx.endUndo() # undo is not working on this
addAction(KMFXpaintPresets())