-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathumapBuilder.py
242 lines (199 loc) · 12.8 KB
/
umapBuilder.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
"""
Made by Arkait
Version: 0.1
Date: 03/08/2021
Filter umap file for another script for blender
"""
import json
import math
import bpy
import os
#Global var with default values
deleteOnStart = True
isTexturingModels = True
#@TODO MUST BE CHANGE
configPath = "D:\Documents\CodeFoureTout\The-Cycle-Umap-Exporter\config.json"
def deleteEverything():
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete(use_global=False)
bpy.ops.outliner.orphans_purge()
bpy.ops.outliner.orphans_purge()
bpy.ops.outliner.orphans_purge()
def main(pathFile, exportedGameAssetsPath):
"""
Filtre l'Umap pour ne garder que ce qui est intéressant
"""
print('Filtering umap : ' + pathFile + '\n')
#Ouvrir le fichier
if pathFile:
umap = None
with open(pathFile, 'r') as f:
umap = json.load(f)
jsonFiltered = []
#Parcourir chaque objet pour les filtrer
for obj in umap:
if(obj["Type"] == "SkeletalMeshComponent"):
#Tester si l'objet possède un attribut SkeletalMesh
if("SkeletalMesh" in obj["Properties"]):
#Convertir le chemin de l'objet en un chemin local du dossier exporté
obj["Properties"]["SkeletalMesh"]["ObjectPath"] = str(obj["Properties"]["SkeletalMesh"]["ObjectPath"]).replace("Prospect/Content/", "")
if ("OverrideMaterials" in obj["Properties"]):
for tmpMat in obj["Properties"]["OverrideMaterials"]:
if tmpMat != None:
tmpMat["ObjectPath"] = tmpMat["ObjectPath"].replace("Prospect/Content/", "")
jsonFiltered.append(obj)
elif(obj["Type"] == "StaticMeshComponent"):
#Tester si l'objet possède un attribut StaticMesh
if("StaticMesh" in obj["Properties"]):
#Convertir le chemin de l'objet en un chemin local du dossier exporté
obj["Properties"]["StaticMesh"]["ObjectPath"] = str(obj["Properties"]["StaticMesh"]["ObjectPath"]).replace("Prospect/Content/", "")
if ("OverrideMaterials" in obj["Properties"]):
for tmpMat in obj["Properties"]["OverrideMaterials"]:
if tmpMat != None:
tmpMat["ObjectPath"] = tmpMat["ObjectPath"].replace("Prospect/Content/", "")
jsonFiltered.append(obj)
"""
Building the blender file
"""
if deleteOnStart:
deleteEverything()
#Parcourir le json et importer les objets dans la scène
for obj in jsonFiltered:
#Construire le nom du fichier
pathObj = ""
if(obj["Type"] == "SkeletalMeshComponent"):
pathObj = exportedGameAssetsPath + obj["Properties"]["SkeletalMesh"]["ObjectPath"]
elif(obj["Type"] == "StaticMeshComponent"):
pathObj = exportedGameAssetsPath + obj["Properties"]["StaticMesh"]["ObjectPath"]
pathObj = pathObj.split('.')[0]
pathObj += ".gltf"
#Importer l'objet dans blender
bpy.ops.import_scene.gltf(filepath=str(pathObj))
#Déplacer
if("RelativeLocation" in obj["Properties"]):
bpy.ops.transform.translate(value=[obj["Properties"]["RelativeLocation"]["X"]/100, obj["Properties"]["RelativeLocation"]["Y"]/100, obj["Properties"]["RelativeLocation"]["Z"]/100])
#Tourner
if("RelativeRotation" in obj["Properties"]):
bpy.context.object.rotation_mode = 'XYZ'
bpy.ops.transform.rotate(value=math.radians(obj["Properties"]["RelativeRotation"]["Pitch"]), orient_axis='X')
bpy.ops.transform.rotate(value=math.radians(obj["Properties"]["RelativeRotation"]["Roll"]), orient_axis='Y')
bpy.ops.transform.rotate(value=math.radians(obj["Properties"]["RelativeRotation"]["Yaw"]), orient_axis='Z')
#Mettre à l'échelle
if("RelativeScale3D" in obj["Properties"]):
bpy.ops.transform.resize(value=[obj["Properties"]["RelativeScale3D"]["X"], obj["Properties"]["RelativeScale3D"]["Y"], obj["Properties"]["RelativeScale3D"]["Z"]])
"""
Gérer les matériaux
"""
#Enlever les matériaux dupliqué et les créer
for currentMat in bpy.context.object.material_slots:
i = -1
nameMat = currentMat.name.split('.')
if(len(nameMat) > 1):
#Si le mat est dupliqué, alors le remplacer
if(nameMat[0] in bpy.data.materials):
currentMat.material = bpy.data.materials[nameMat[0]]
else:
if isTexturingModels:
#Récupérer la localisation du mat
pathFicMat = ""
#Refaire ça, car overrideMaterials n'est que sur l'un des mat mais pas tous
if ("OverrideMaterials" in obj["Properties"]):
for tmp in obj["Properties"]["OverrideMaterials"]:
if tmp != None:
#Récupérer la localisation du mat
pathFicMat = exportedGameAssetsPath
pathFicMat += tmp["ObjectPath"].split('.')[0]
else:
#Récupérer la localisation du dossier
pathFicMat = '/'.join(pathObj.split('/')[:-1])
pathFicMat += '/'
pathFicMat += currentMat.name
#Récupérer et modifier le mat
tmpMat = bpy.data.materials.get(nameMat[0])
tmpMat.use_nodes = True
nodes = tmpMat.node_tree.nodes
#Test peut etre inutile par la suite
if(pathFicMat != ""):
pathFicMat += ".mat"
#Si besoin
pathFicMatDetail = pathFicMat.replace(".mat", ".props.txt")
print(pathFicMat)
#Trouver les textures
if (os.path.isfile(pathFicMat)):
f = open(pathFicMat, 'r')
lignes = f.readlines()
#Cette ligne est pour récupérer la texture M correcte
textureGenericName = '_'.join(lignes[0].split('=')[1].split('_')[:-1])
for ligne in lignes:
#Enlever les \n car ils interfèrent avec les noms des fichier
ligne = ligne.replace("\n", "")
tmp = ligne.split('=')
if (tmp[0] == "Diffuse"):
#Ajouter le mat dans les nodes
diffuseMatPath = '/'.join(pathFicMat.split('/')[:-1])
diffuseMatPath += '/'
diffuseMatPath += tmp[1]
diffuseMatPath += ".png"
if (os.path.isfile(diffuseMatPath)):
diffuseTextureNode = nodes.new("ShaderNodeTexImage")
diffuseTextureNode.image = bpy.data.images.load(diffuseMatPath, check_existing=False)
bpy.data.images[diffuseMatPath.split('/')[-1]].colorspace_settings.name = 'sRGB'
#Connect node
tmpMat.node_tree.links.new(diffuseTextureNode.outputs["Color"], nodes["Principled BSDF"].inputs["Base Color"])
elif (tmp[0] == "Normal"):
#Ajouter le mat dans les nodes
normalMatPath = '/'.join(pathFicMat.split('/')[:-1])
normalMatPath += '/'
normalMatPath += tmp[1]
normalMatPath += ".png"
if (os.path.isfile(normalMatPath)):
normalTextureNode = nodes.new("ShaderNodeTexImage")
normalTextureNode.image = bpy.data.images.load(normalMatPath, check_existing=False)
bpy.data.images[normalMatPath.split('/')[-1]].colorspace_settings.name = 'Non-Color'
normalMapNode = nodes.new("ShaderNodeNormalMap")
#Connect node
tmpMat.node_tree.links.new(normalTextureNode.outputs["Color"], normalMapNode.inputs["Color"])
tmpMat.node_tree.links.new(normalMapNode.outputs["Normal"], nodes["Principled BSDF"].inputs["Normal"])
elif (tmp[0] == "Emissive"):
#Ajouter le mat dans les nodes
emissiveMat = tmp[1]
#Récupérer M texture -> Faire attention car plusieurs textures M
elif (tmp[1].endswith("_M") and tmp[1].startswith(textureGenericName)):
#Ajouter le mat dans les nodes
maskMatPath = '/'.join(pathFicMat.split('/')[:-1])
maskMatPath += '/'
maskMatPath += tmp[1]
maskMatPath += ".png"
if (os.path.isfile(maskMatPath)):
maskTextureNode = nodes.new("ShaderNodeTexImage")
maskTextureNode.image = bpy.data.images.load(maskMatPath, check_existing=False)
bpy.data.images[maskMatPath.split('/')[-1]].colorspace_settings.name = 'Non-Color'
sepRGBNode = nodes.new("ShaderNodeSeparateRGB")
# mixRGBNode = nodes.new("ShaderNodeMixRGB")
# mixRGBNode.blend_type = 'MULTIPLY'
# mixRGBNode.inputs[0].default_value = 1
#Connect node
tmpMat.node_tree.links.new(maskTextureNode.outputs["Color"], sepRGBNode.inputs["Image"])
tmpMat.node_tree.links.new(sepRGBNode.outputs["R"], nodes["Principled BSDF"].inputs["Roughness"])
#Voir pour AO
# tmpMat.node_tree.links.new(sepRGBNode.outputs["G"], mixRGBNode.inputs["Color2"])
# if ((textureGenericName + "_D") in nodes):
# tmpMat.node_tree.links.new(nodes[textureGenericName + "_D"], mixRGBNode.inputs["Color1"])
# tmpMat.node_tree.links.new(mixRGBNode.outputs["Color"], nodes["Principled BSDF"].inputs["Base Color"])
tmpMat.node_tree.links.new(sepRGBNode.outputs["B"], nodes["Principled BSDF"].inputs["Metallic"])
f.close()
else:
print("File not found: " + pathFicMat)
#Enlever les mat qui ne sont plus utilisé du fichier Blender, nécessite un redémarage
bpy.ops.outliner.orphans_purge
#Lire et tester le fichier de configuration
with open(configPath, 'r') as f:
fJson = json.load(f)
if ("umapPath" in fJson and "exportedGameAssetsPath" in fJson):
if(fJson["umapPath"] != "" and fJson["exportedGameAssetsPath"] != ""):
if ("deleteExistingScene" in fJson):
deleteOnStart = fJson["deleteExistingScene"]
if ("texturingModels" in fJson):
isTexturingModels = fJson["texturingModels"]
#Si tout est OK, on lance le programme principal
main(fJson["umapPath"], fJson["exportedGameAssetsPath"])