forked from marv7000/FastValveMaterial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FastValveMaterial.py
495 lines (442 loc) · 23.1 KB
/
FastValveMaterial.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
""" Simple Source Material "PBR" generator
Prerequisites (Python 3.x):
pillow
MIT License
Copyright (c) 2024 Marvin Friedrich, hampta
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. """
import configparser
import os
import sys
import glob
import shutil
import sys
import logging
import json
import argparse
import multiprocessing
from urllib.request import urlopen
from ctypes import create_string_buffer
from dataclasses import dataclass
from pathlib import Path
from enum import Enum
from PIL import Image, ImageChops, ImageOps
import VTFLibWrapper.VTFLib as VTFLib
import VTFLibWrapper.VTFLibEnums as VTFLibEnums
vtf_lib = VTFLib.VTFLib()
version = "240213"
class TextureType(Enum):
DIFFUSE = 'c'
NORMAL = 'n'
EXPONENT = 'm'
VMT_TEMPLATE = """// Generated by FastValveMaterial v{version}
// Forked by hampta because the original sucks
// METALNESS: "{metallic_factor}" GAMMA: "{midtone}"
"VertexLitGeneric"
{{
"$basetexture" "{output_path}/{material_name}_c"
"$bumpmap" "{output_path}/{material_name}_n"
"$phongexponenttexture" "{output_path}/{material_name}_m"
"$color2" "[ .1 .1 .1 ]"
"$blendtintbybasealpha" "1"
"$phong" "1"
"$phongboost" "10"
"$phongalbedotint" "1"
{phong}
"$envmap" "env_cubemap"
"$basemapalphaenvmapmask" "1"
"$envmapfresnel" "0.4"
"$envmaptint" "[ .1 .1 .1 ]"
{proxies}
}}"""
VMT_NORMAL_TEMPLATE = """// Generated by FastValveMaterial v{version}
// Forked by hampta because the original sucks
// NORMALIZED MATERIAL!
"VertexLitGeneric"
{{
"$basetexture" "{output_path}/{material_name}_c"
"$bumpmap" "{output_path}/{material_name}_n"
"$phongexponenttexture" "{output_path}/{material_name}_m"
"$phong" "1"
"$phongboost" "1"
"$color2" "[ 0 0 0 ]"
"$phongexponent" "24"
"$phongalbedotint" "1"
"$additive" "1"
"$PhongFresnelRanges" "[ 2 4 6 ]"
{proxies}
}}"""
PROXIES_TEMPLATE = """\
"Proxies"
{
"MwEnvMapTint"
{
"min" "0"
"max" "0.015"
}
}"""
class Config:
def __init__(self, file="config.ini"):
__config = configparser.ConfigParser()
__config.read(file)
# Input
self.input_format = __config["Input"]["Format"]
self.input_scale = __config["Input"].getfloat("Scale")
self.input_color = __config["Input"]["Color"]
self.input_ao = __config["Input"]["AO"]
self.input_normal = __config["Input"]["Normal"]
self.input_metallic = __config["Input"]["Metallic"]
self.input_roughness = __config["Input"]["Roughness"]
self.input_path = Path(__config["Input"]["Path"])
# Output
self.output_path = Path(__config["Output"]["Path"])
self.midtone = __config["Output"].getint("Midtone")
self.export_images = __config["Output"].getboolean("ExportImages")
self.material_setup = __config["Output"]["MaterialSetup"]
# Debug
self.thread_count = __config["Debug"].getint("ThreadCount")
self.debug_messages = __config["Debug"].getboolean("DebugMessages")
self.info_config = __config["Debug"].getboolean("PrintConfig")
self.force_compression = __config["Debug"].getboolean("ForceCompression")
self.fast_export = __config["Debug"].getboolean("FastExport")
self.clear_exponent = __config["Debug"].getboolean("ClearExponent")
self.metallic_factor = __config["Debug"].getint("MetallicFactor")
self.material_proxies = __config["Debug"].getboolean("MaterialProxies")
self.orm = __config["Debug"].getboolean("ORM")
self.phongwarps = __config["Debug"].getboolean("Phongwarps")
if self.thread_count == -1:
self.thread_count = os.cpu_count()
@dataclass
class Material:
name: str
color_path: str
ao_path: str = None
normal_path: str = None
metallic_path: str = None
roughness_path: str = None
def list(self):
return [self.color_path, self.ao_path, self.normal_path, self.metallic_path, self.roughness_path]
def check_new_version():
# Check for new version from GitHub releases
try:
response = urlopen("https://api.github.com/repos/hampta/FastValveMaterial/releases/latest")
data = response.read()
data = json.loads(data)
vers = data.get("tag_name")
if version != vers:
logging.info(f"╔═════════════════════════════════════════════════════════════════════════════╗\n")
logging.info(f"║ New version available: v{vers} ║\n")
logging.info(f"║ Download it at: https://github.com/hampta/FastValveMaterial/releases/latest ║\n")
logging.info(f"╚═════════════════════════════════════════════════════════════════════════════╝\n")
except Exception as e:
logging.info(f"Could not check for new version: {e}\n")
all_processes = []
handler = logging.StreamHandler(sys.stdout)
handler.terminator = "\r"
# /////////////////////
# Logging setup
# /////////////////////
logging.basicConfig(format='[FVM] [%(levelname)s] %(message)s', level=logging.INFO, handlers=[handler])
def replace_list(string, list):
for i in list:
string = string.replace(i, "")
return string
class FastValveMaterial:
def __init__(self, config: Config, args: argparse.Namespace):
self.config: Config = config
if self.config.debug_messages:
logging.getLogger().setLevel(logging.DEBUG)
self.all_processes: list = []
self.vtf_lib = VTFLib.VTFLib()
self.vtf_lib.create_default_params_structure()
if args.input:
config.input_path = Path(args.input)
if args.output:
config.output_path = Path(args.output)
if args.threads:
config.thread_count = int(args.threads)
if args.debug:
config.debug_messages = True
if args.fast_export:
config.fast_export = True
if args.export:
config.export_images = True
def do_diffuse(self, color_image: Image.Image, ao_image: Image.Image,
metallic_image: Image.Image, glossiness_image: Image.Image, material_name: str):
final_diffuse = color_image.convert("RGBA")
if ao_image is None:
final_diffuse = ImageChops.blend(final_diffuse.convert("RGB"),
ImageChops.multiply(final_diffuse.convert("RGB"),
glossiness_image.convert("RGB")), 0.3).convert("RGBA")
else:
final_diffuse = ImageChops.multiply(final_diffuse.convert("RGB"),
ao_image.convert("RGB")).convert("RGBA")
r, g, b, a = final_diffuse.split()
a = Image.blend(a.convert("L"), metallic_image.convert("L"),
self.config.metallic_factor / 255 * 0.83).convert("L")
color_spc = (r, g, b, a)
final_diffuse = Image.merge("RGBA", color_spc)
logging.info(f"Exporting {material_name}_c...\n")
self.export_texture(final_diffuse, material_name, TextureType.DIFFUSE, 'DXT5')
def do_exponent(self, glossiness_image: Image.Image, material_name: str):
final_exponent = glossiness_image.convert("RGBA")
r, g, b, a = final_exponent.split()
layerImage = Image.new('RGBA',
[final_exponent.size[0], final_exponent.size[1]],
(0, 217, 0, 100))
blackImage = Image.new('RGBA',
[final_exponent.size[0], final_exponent.size[1]],
(0, 0, 0, 100))
final_exponent = Image.blend(final_exponent, layerImage, 0.5)
g = g.convert('RGBA')
b = b.convert('RGBA')
g = Image.blend(g, layerImage, 1).convert('L')
b = Image.blend(b, blackImage, 1).convert('L')
if self.config.clear_exponent:
g = Image.new('L', [final_exponent.size[0], final_exponent.size[1]], 255)
colorSpc = (r, g, b, a)
final_exponent = Image.merge('RGBA', colorSpc)
logging.info(f"Exporting {material_name}_m...\n")
self.export_texture(final_exponent, material_name,
TextureType.EXPONENT, 'DXT5' if self.config.force_compression else 'DXT1')
def do_normal(self, normalmap_image: Image.Image, glossiness_image: Image.Image, material_name: str):
final_normal = normalmap_image.convert('RGBA')
final_gloss = glossiness_image.convert('RGBA')
final_gloss = self.do_gamma(final_gloss, self.config.midtone)
r, g, b, a = final_normal.split()
a = Image.blend(a, final_gloss.convert('L'), 1).convert('L')
colorSpc = (r, g, b, a)
final_normal = Image.merge('RGBA', colorSpc)
logging.info(f"Exporting {material_name}_n...\n")
self.export_texture(final_normal, material_name,
TextureType.NORMAL, 'DXT5' if self.config.force_compression else 'RGBA8888')
def do_gamma(self, image: Image.Image, gamma: float):
gamma = 1
midToneNormal = gamma / 255
if gamma < 128:
midToneNormal = midToneNormal * 2
gamma = 1 + (9 * (1 - midToneNormal))
gamma = min(gamma, 9.99)
elif gamma > 128:
midToneNormal = (midToneNormal * 2) - 1
gamma = 1 - midToneNormal
gamma = max(gamma, 0.01)
gamma_correction = 1 / gamma
if gamma != 128:
return image.point(lambda x: ((x/255)**gamma_correction)*255)
return image
def fix_scale_mismatch(self, image: Image.Image, target: Image.Image, skip_factor=False):
if self.config.input_scale != 1.0:
target = target.resize((int(target.width * self.config.input_scale),
int(target.height * self.config.input_scale)),
Image.Resampling.LANCZOS)
if skip_factor:
return target
factor = image.width / target.width
return ImageOps.scale(target, factor, Image.Resampling.LANCZOS)
def do_material(self, material_name: str):
logging.debug(f"Creating material '{material_name}'\n")
if "materials" in self.config.output_path.parts:
texture_local_path = "/".join(self.config.output_path.parts[self.config.output_path.parts.index("materials") + 1:])
else:
texture_local_path = self.config.output_path
if self.config.clear_exponent:
writer = VMT_NORMAL_TEMPLATE.format(
version=version, config=self.config,
output_path=texture_local_path,
material_name=material_name,
proxies=PROXIES_TEMPLATE if self.config.material_proxies else "")
else:
writer = VMT_TEMPLATE.format(
version=version, config=self.config,
output_path=texture_local_path,
material_name=material_name,
metallic_factor=self.config.metallic_factor,
midtone=self.config.midtone,
phong=f'"$phongwarptexture" "{texture_local_path}/phongwarp_steel"' if self.config.phongwarps else '"$PhongFresnelRanges" "[ 4 3 10 ]"',
proxies=PROXIES_TEMPLATE if self.config.material_proxies else "")
Path(self.config.output_path).mkdir(parents=True, exist_ok=True)
with open(os.path.join(self.config.output_path, f"{material_name}.vmt"), "w") as f:
f.writelines(writer)
if self.config.phongwarps and not self.config.clear_exponent:
shutil.copy(os.path.join(os.path.dirname(__file__), "phongwarp_steel.vtf"), self.config.output_path)
logging.debug("Material exported\n")
def export_texture(self, texture: Image.Image, material_name: str, texture_type: TextureType, imageFormat=None):
image_name = f'{material_name}_{texture_type.value}.vtf'
output_path = Path(f'{self.config.output_path}\\{image_name}')
def_options = self.vtf_lib.create_default_params_structure()
if imageFormat.startswith('RGBA8888') or self.config.fast_export:
def_options.ImageFormat = VTFLibEnums.ImageFormat.ImageFormatRGBA8888
def_options.Flags |= VTFLibEnums.ImageFlag.ImageFlagEightBitAlpha
if imageFormat == 'RGBA8888Normal':
def_options.Flags |= VTFLibEnums.ImageFlag.ImageFlagNormal
elif imageFormat.startswith('DXT1'):
def_options.ImageFormat = VTFLibEnums.ImageFormat.ImageFormatDXT1
if imageFormat == 'DXT1Normal':
def_options.Flags |= VTFLibEnums.ImageFlag.ImageFlagNormal
elif imageFormat.startswith('DXT5'):
def_options.ImageFormat = VTFLibEnums.ImageFormat.ImageFormatDXT5
def_options.Flags |= VTFLibEnums.ImageFlag.ImageFlagEightBitAlpha
if imageFormat == 'DXT5Normal':
def_options.Flags |= VTFLibEnums.ImageFlag.ImageFlagNormal
else:
def_options.ImageFormat = VTFLibEnums.ImageFormat.ImageFormatRGBA8888
def_options.Flags |= VTFLibEnums.ImageFlag.ImageFlagEightBitAlpha
def_options.Resize = 1
w, h = texture.size
image_data = create_string_buffer(texture.tobytes())
self.vtf_lib.image_create_single(w, h, image_data, def_options)
self.vtf_lib.image_save(image_name)
self.vtf_lib.image_destroy()
if os.path.exists(output_path):
logging.debug(f"{texture_type.name} already exists, replacing!\n")
src = os.path.join(os.getcwd(), image_name)
dst = os.path.join(os.getcwd(), output_path)
shutil.copyfile(src, dst, follow_symlinks=True)
os.remove(os.path.join(os.getcwd(), image_name))
else:
Path(self.config.output_path).mkdir(parents=True, exist_ok=True)
shutil.move(image_name, os.path.join(os.getcwd(), self.config.output_path))
logging.debug(f"{texture_type.name} exported\n")
path = image_name.replace(".vtf", ".tga")
if self.config.export_images:
texture.save(os.path.join(self.config.output_path, path))
logging.debug(f"Exported {path} as TGA\n")
def convert_material(self, material: Material):
processes = []
if not self.config.orm:
logging.info(f"Color:\t\t\t{material.color_path}\n")
logging.info(f"Ambient Occlusion:\t\t{material.ao_path}\n")
logging.info(f"Normal:\t\t\t{material.normal_path}\n")
logging.info(f"Metallic:\t\t\t{material.metallic_path}\n")
logging.info(f"Roughness:\t\t\t{material.roughness_path}\n")
if self.config.input_normal != '':
normal_image = Image.open(material.normal_path)
normal_image = self.fix_scale_mismatch(normal_image, normal_image, True)
color_image = Image.open(material.color_path)
color_image = self.fix_scale_mismatch(normal_image, color_image)
if self.config.input_ao != '':
if material.ao_path is None:
ao_image = Image.new('RGB', color_image.size, (255, 255, 255))
else:
ao_image = Image.open(material.ao_path)
ao_image = self.fix_scale_mismatch(normal_image, ao_image)
if self.config.input_metallic != '':
if material.metallic_path is None:
metal_image = Image.new('RGB', color_image.size, (0, 0, 0))
else:
metal_image = Image.open(material.metallic_path)
metal_image = self.fix_scale_mismatch(normal_image, metal_image)
if self.config.input_roughness != '':
if material.roughness_path is None:
gloss_image = Image.new('RGB', color_image.size, (255, 255, 255))
else:
gloss_image = Image.open(material.roughness_path)
gloss_image = self.fix_scale_mismatch(normal_image, gloss_image)
if self.config.material_setup == "rough":
gloss_image = ImageOps.invert(gloss_image.convert('RGB'))
if self.config.input_ao != '':
processes.append(multiprocessing.Process(target=self.do_diffuse, args=(color_image, ao_image, metal_image, gloss_image, material.name,)))
else:
processes.append(multiprocessing.Process(target=self.do_diffuse, args=(color_image, None, metal_image, gloss_image, material.name,)))
else:
logging.info(f"Color:\t\t {material.color_path}\n")
logging.info(f"ORM:\t\t {material.ao_path}\n")
logging.info(f"Normal:\t\t {material.normal_path}\n")
color_image = Image.open(material.color_path)
ormImage = Image.open(material.ao_path)
normal_image = Image.open(material.normal_path)
if ormImage.width != color_image.width or ormImage.height != color_image.height:
ormImage = ormImage.resize((color_image.width, color_image.height),
Image.Resampling.LANCZOS)
try:
(ao_image, roughness, metal_image, _) = ormImage.split()
except Exception:
logging.info(
"ERROR: Could not convert color bands on ORM! (Do you have empty image channels?)\n")
gloss_image = ImageOps.invert(roughness.convert('RGB'))
processes.append(multiprocessing.Process(target=self.do_diffuse, args=(color_image, ao_image, metal_image, gloss_image, material.name,)))
processes.append(multiprocessing.Process(target=self.do_exponent, args=(gloss_image, material.name,)))
processes.append(multiprocessing.Process(target=self.do_normal, args=(normal_image, gloss_image, material.name,)))
processes.append(multiprocessing.Process(target=self.do_material, args=(material.name,)))
logging.info(f"Pre conversion for material '{material.name}.vmt' finished\n")
return processes
def find_materials(self): # Uses the color map to determine the current material name
list_stuff: list[Material] = []
for file in glob.glob(f"{self.config.input_path}/*{self.config.input_color}.{self.config.input_format}"):
if self.config.input_color in file:
name = file.replace(f"{self.config.input_path}\\", "")
name = name.replace(f"{self.config.input_color}.{self.config.input_format}", "")
list_stuff.append(Material(name, file))
# find other textures maps
for material in list_stuff:
for file in glob.glob(f"{self.config.input_path}/{material.name}*.{self.config.input_format}"):
if file.endswith(f"{self.config.input_ao}.{self.config.input_format}"):
material.ao_path = file
elif file.endswith(f"{self.config.input_normal}.{self.config.input_format}"):
material.normal_path = file
elif file.endswith(f"{self.config.input_metallic}.{self.config.input_format}"):
material.metallic_path = file
elif file.endswith(f"{self.config.input_roughness}.{self.config.input_format}"):
material.roughness_path = file
return list_stuff
def convert(self):
for material_name in self.find_materials(): # For every material in the input folder
all_processes.extend(self.convert_material(material_name))
# MAXIMUM THREAD COUNT
for i in range(0, len(all_processes), config.thread_count):
for process in all_processes[i:i + config.thread_count]:
process.start()
for process in all_processes[i:i + config.thread_count]:
process.join()
logging.info(f"Conversion finished, files saved to '{config.output_path}'\n")
if __name__ == "__main__":
# Nuitka fix for multiprocessing
multiprocessing.freeze_support()
# /////////////////////
# Argument parsing
# /////////////////////
args = argparse.ArgumentParser(description="FastValveMaterial")
args.add_argument("-c", "--config", help="Config file to use", default="config.ini")
args.add_argument("-i", "--input", help="Input folder to use")
args.add_argument("-o", "--output", help="Output folder to use")
args.add_argument("-t", "--threads", help="Thread count to use")
args.add_argument("-d", "--debug", help="Enable debug messages", action="store_true")
args.add_argument("-f", "--fast-export", help="Enable fast export", action="store_true")
args.add_argument("-e", "--export", help="Export images", action="store_true")
args = args.parse_args()
config = Config(args.config)
# /////////////////////
# Logging
# /////////////////////
logging.info(f"FastValveMaterial (v{version})\n")
logging.info(f"Using {config.thread_count} threads\n")
# /////////////////////
# Check for new version
# /////////////////////
check_new_version()
# /////////////////////
# Main loop
# /////////////////////
fast_valve_material = FastValveMaterial(config, args)
fast_valve_material.convert()
# /////////////////////
# Finish
# /////////////////////
logging.debug(f"v{version} finished with exit code 0: All conversions finished.\n")
if config.info_config:
logging.info("Config file dump:\n")
logging.info(config)