-
Notifications
You must be signed in to change notification settings - Fork 0
/
xcftotexture.py
448 lines (333 loc) · 9.58 KB
/
xcftotexture.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
import os
import shutil
from argparse import ArgumentParser, Action, RawDescriptionHelpFormatter
from pathlib import Path
import logging
import tracemalloc
from typing import Union, TextIO, IO
from copy import copy
import yaml
from PIL import Image, ImageChops
from gimpformats.gimpXcfDocument import GimpDocument, flattenAll
from gimpformats.GimpLayer import GimpLayer
logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
class Document(GimpDocument):
def __init__(self, filename):
self.stat = os.stat(filename)
# gimpformats requires an explicit string otherwise it falls back to BytesIO
super().__init__(str(filename))
self.layer_tree = self.get_layers_as_tree()
apply_masks(self.layer_tree)
def get_layers_as_tree(self):
layer_tree = {
'children': [],
}
for idx, layer in enumerate(self.layers):
parent = layer_tree
if layer.itemPath:
layer.itemPath.pop()
parent = layer_tree
for level_idx in layer.itemPath:
parent = parent['children'][level_idx]
if layer.isGroup:
parent['children'].append({
'layer': layer,
'children': [],
})
else:
parent['children'].append(layer)
return layer_tree
DOCUMENT_CACHE = {} # maintain a cache of opened GimpDocuments
VARIANT_TYPES = (
'diffuse',
'norm',
'bump',
'gloss',
'glow',
'pants',
'shirt',
)
TEXTURE_VARIANTS = VARIANT_TYPES
def get_document(name: str, cache: dict = DOCUMENT_CACHE) -> Document:
if name in cache:
return cache[name]
filepath = os.path.join('src', name + '.xcf')
document = Document(filepath)
apply_masks(document.layer_tree)
cache[name] = document
return document
def get_layer(document: GimpDocument, name: str) -> Union[GimpLayer, None]:
for layer in document.layers:
if layer.name == name:
return layer
return None
def get_layer_tree(document: GimpDocument):
layer_tree = {
'children': [],
}
for idx, layer in enumerate(document.layers):
parent = layer_tree
if layer.itemPath:
layer.itemPath.pop()
parent = layer_tree
for level_idx in layer.itemPath:
parent = parent['children'][level_idx]
if layer.isGroup:
parent['children'].append({
'layer': layer,
'children': [],
})
else:
parent['children'].append(layer)
return layer_tree
def apply_masks(group: dict, parent_mask: Image = None):
group_mask = None
if 'layer' in group:
group_mask = getattr(group['layer'], 'mask')
if parent_mask is None:
mask = getattr(group_mask, 'image', None)
else:
if group_mask is None:
mask = parent_mask
else:
mask = ImageChops.multiply(
parent_mask,
group_mask,
)
for layerOrGroup in group.get('children', []):
if isinstance(layerOrGroup, dict) and 'children' in layerOrGroup:
apply_masks(layerOrGroup, mask)
else:
if layerOrGroup.mask is not None:
layerOrGroup.image.putalpha(
layerOrGroup.mask.image
)
if mask is not None:
if layerOrGroup.image.mode == 'RGB':
layerOrGroup.image.putalpha(
mask
)
else:
layerOrGroup.image.putalpha(
ImageChops.multiply(
mask,
layerOrGroup.image.getchannel('A'),
)
)
if 'layer' in group:
group['layer'].visible = False
def render_textures(textures: dict, output_dir: str):
for texture_name, texture_def in textures.items():
document = get_document(texture_def['src'])
for variant_name in TEXTURE_VARIANTS:
layers = texture_def.get(variant_name, [])
if layers:
image = render_texture(
document,
layers,
)
if variant_name == 'diffuse':
filename = "%s.tga" % texture_name
else:
filename = "%s_%s.tga" % (texture_name, variant_name)
filepath = Path(os.path.join(output_dir, filename))
if not filepath.parent.exists():
os.mkdir(filepath.parent)
log.info("Save to %s" % filepath)
image.save(filepath)
class Texture:
def __init__(self, name, document, definition):
self.name = name
self.document = document
self.definition = definition
self.width = document.width
self.height = document.height
apply_masks(self.document.layer_tree)
def render(self) -> dict:
variants = {}
for variant_name, variant_definition in [
(k, v)
for k, v
in self.definition.items()
if k in TEXTURE_VARIANTS
]:
variants[variant_name] = TextureVariant(self.document, variant_definition).render()
if 'bump' not in variants:
variants['bump'] = self.default_bump()
if 'gloss' not in variants:
variants['gloss'] = self.default_gloss()
return variants
def has_variant(self, variant_type) -> bool:
if variant_type in self.variants:
return True
return False
def default_gloss(self) -> Image:
# create new black image
return Image.new(
'RGBA',
(self.width, self.height),
(0, 0, 0, 255),
)
def default_bump(self) -> Image:
# create new grey image
return Image.new(
'RGBA',
(self.width, self.height),
(128, 128, 128, 255),
)
class TextureVariant:
def __init__(self, document, definition):
self.document = document
self.definition = definition
self.width = document.width
self.height = document.height
def render(self) -> Image:
document = copy(self.document)
for layer in document.layers:
if layer.name == 'Background' or layer.name in self.definition:
layer.visible = True
else:
layer.visible = False
return flattenAll(
document,
(
self.width,
self.height,
)
)
def new_render_textures(source_directory: Path, definitions: dict):
document_cache = DocumentCache(source_directory)
textures = {}
for name, definition in definitions.items():
xcf_document_name = definition['src']
xcf_document = document_cache.get(xcf_document_name)
textures[name] = Texture(name, xcf_document, definition).render()
return textures
class DocumentCache:
def __init__(self, source_directory: Path):
self.source_directory = source_directory
self.cache = {}
def _make_filepath(self, name: str) -> Path:
log.debug(Path(self.source_directory, f"{name}.xcf"))
return Path(self.source_directory, f"{name}.xcf")
def get(self, name: str) -> Document:
if name in self.cache:
return self.cache[name]
log.debug(f"name: {name}")
filepath = self._make_filepath(name)
log.debug(f"filepath: {filepath}")
document = Document(filepath)
# log.debug(dir(document))
self.cache[name] = document
return document
class TextureBuilder:
def __init__(
self,
texture_definitions: dict,
source_directory: Path,
):
self.texture_definitions = texture_definitions
self.cache = DocumentCache(source_directory)
def save(self, destination_directory: Path, extension: str = "tga"):
for name, definition in self.texture_definitions.items():
xcf_document_name = definition['src']
xcf_document = self.cache.get(xcf_document_name)
diffuse_filepath = self.get_variant_filepath(
name,
'diffuse',
extension,
destination_directory,
)
try:
diffuse_mtime = os.stat(diffuse_filepath).st_mtime
# If the source file hasn't changed, don't re-render
if diffuse_mtime > xcf_document.stat.st_mtime:
log.debug(f"Skipping {diffuse_filepath}")
continue
except FileNotFoundError:
pass
texture = Texture(name, xcf_document, definition).render()
for variant_type, variant_image in texture.items():
variant_filepath = self.get_variant_filepath(
name,
variant_type,
extension,
destination_directory,
)
if not variant_filepath.parent.exists():
os.mkdir(variant_filepath.parent)
log.info(f"Saving {variant_filepath.resolve()}")
variant_image.save(variant_filepath.resolve())
def get_variant_filepath(self, name, variant_type, extension, destination_directory):
if variant_type == 'diffuse':
filename = f"{name}.{extension}"
else:
filename = f"{name}_{variant_type}.{extension}"
return destination_directory.joinpath(filename)
class ResolvePathAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
values = values.expanduser().resolve()
setattr(namespace, self.dest, values)
class LogLevelMapperAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
values = logging._nameToLevel[values.upper()]
setattr(namespace, self.dest, values)
if __name__ == "__main__":
parser = ArgumentParser(
description="Generate texture variants, from a set of definitions, directly from XCF files.",
epilog='''Example: python $(prog) xcftotexture.yml ~/.darkplaces/id1_tex/textures/''',
formatter_class=RawDescriptionHelpFormatter,
)
parser.add_argument(
"infile",
type=Path,
action=ResolvePathAction,
help="Texture definition YAML file"
)
parser.add_argument(
"outdir",
type=Path,
action=ResolvePathAction,
help="Output directory"
)
parser.add_argument(
"-s",
"--src",
default="src",
type=Path,
action=ResolvePathAction,
help="Directory containing the XCF source images (DEFAULT: src)"
)
parser.add_argument(
"-v",
"--variants",
default="all",
type=str,
help="Comma-separated list of texture variants to build (DEFAULT: all)"
)
parser.add_argument(
"-f",
"--format",
default="tga",
type=str,
help="Image format to use. (TODO)"
)
parser.add_argument(
"-l",
"--log-level",
default=logging.INFO,
action=LogLevelMapperAction,
help="Log level"
)
args = parser.parse_args()
log.setLevel(args.log_level)
tracemalloc.start()
with open(args.infile, 'r') as yaml_file:
texture_defs = yaml.safe_load(yaml_file)
texture_builder = TextureBuilder(texture_defs, args.src)
texture_builder.save(args.outdir)
current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"Current memory usage is {current / 10**6}MB; Peak was {peak / 10**6}MB")