-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path__init__.py
591 lines (533 loc) · 24.7 KB
/
__init__.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
# Copyright 2020 Campbell Barton, Bastien Montagne
# Copyright 2020-2021 Dragorn421, z64me, Sauraen
#
# This objex2 addon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This objex2 addon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this objex2 addon. If not, see <https://www.gnu.org/licenses/>.
"""
Based on the io_scene_obj addon shipped with Blender 2.79b
Removed import feature
By default: triangulate, no edges, and other default values changed
Removed use_animation 'Write out an OBJ for each frame'
Added vertex colors support
WIP interface
Added writing skeletons and animations
Added writing weights, and option to only write maximum weight for each vertex
Refactor, cut the giant write-obj function into a few pieces into the ObjexWriter class, hopefully made the code more readable
Removed edge, nurb and "by material" exports
Removed a lot from write_mtl
Added a bunch of export options
Added addon preferences
Added a draw function to export operator
"""
bl_info = {
'name': 'Objex Exporter for N64 romhacking',
'author': 'Campbell Barton, Bastien Montagne, OoT modding community',
'version': (2, 5, 1),
'blender': (2, 80, 0),
'location': 'File > Export',
'description': 'Allows to export to objex and provides new features for further customization',
'warning': '',
'wiki_url': 'TODO manual',
'support': 'COMMUNITY',
'category': 'Import-Export'}
import bpy
if bpy.app.version < (2, 80, 0):
bl_info['blender'] = (2, 79, 0)
from bpy.props import (
BoolProperty,
IntProperty,
FloatProperty,
StringProperty,
)
from bpy_extras.io_utils import (
ExportHelper,
path_reference_mode,
axis_conversion,
)
import os
try:
import progress_report
except ImportError:
import bpy_extras.wm_utils.progress_report as progress_report
# import/reload files
import importlib
loc = locals()
for n in (
'export_objex', 'export_objex_mtl', 'export_objex_anim',
'properties', 'interface', 'const_data', 'util', 'logging_util',
'rigging_helpers', 'data_updater', 'view3d_copybuffer_patch',
'addon_updater', 'addon_updater_ops', 'blender_version_compatibility',
'node_setup_helpers', 'template', 'export_so'
):
if n in loc:
importlib.reload(loc[n])
else:
importlib.import_module('.%s' % n, __package__)
del importlib
from . import export_objex
from . import logging_util
from . import blender_version_compatibility
from . import util
from . import addon_updater_ops
from . import rigging_helpers
from . import properties
from . import data_updater
from . import interface
from . import node_setup_helpers
from . import view3d_copybuffer_patch
class OBJEX_OT_export_base():
"""Save an OBJEX File"""
bl_idname = 'objex.export'
bl_label = 'Export OBJEX'
bl_options = {'PRESET'}
filename_ext = '.objex'
filter_glob = StringProperty(
default='*.objex',
options={'HIDDEN'},
)
# context group
use_selection = BoolProperty(
name='Selection Only',
description='Export selected objects only',
default=False,
)
include_armatures_from_selection = BoolProperty(
name='Used armatures',
description='Also export any armature used by the selection, even if it is not selected',
default=True,
)
use_collection = StringProperty(
name='Collection',
description='Export objects from a collection',
default='',
)
# object group
use_mesh_modifiers = BoolProperty(
name='Apply Modifiers',
description='Apply modifiers',
default=export_objex.ObjexWriter.default_options['APPLY_MODIFIERS'],
)
use_mesh_modifiers_render = BoolProperty(
name='Use Modifiers Render Settings',
description='Use render settings when applying modifiers to mesh objects',
default=export_objex.ObjexWriter.default_options['APPLY_MODIFIERS_RENDER'],
)
apply_unused_armature_deform = BoolProperty(
name='Apply unused deform',
description='Apply armature deform modifiers when the armature is not being exported',
default=export_objex.ObjexWriter.default_options['APPLY_UNUSED_ARMATURE_DEFORM'],
)
apply_modifiers_after_armature_deform = BoolProperty(
name='Apply modifiers after deform',
description='Apply modifiers after the armature deform modifier.\n'
'If they are applied, it would be as if the armature deform was '
'last in the stack, since it would only be "applied" later (for example, '
'in-game) when the mesh is displayed animated.',
default=export_objex.ObjexWriter.default_options['APPLY_MODIFIERS_AFTER_ARMATURE_DEFORM'],
)
# extra data group
use_smooth_groups = BoolProperty(
name='Smooth Groups',
description='Write sharp edges as smooth groups',
default=export_objex.ObjexWriter.default_options['EXPORT_SMOOTH_GROUPS'],
)
use_smooth_groups_bitflags = BoolProperty(
name='Bitflag Smooth Groups',
description='Same as Smooth Groups, but generate smooth groups IDs as bitflags '
'(produces at most 32 different smooth groups, usually much less)',
default=export_objex.ObjexWriter.default_options['EXPORT_SMOOTH_GROUPS_BITFLAGS'],
)
use_normals = BoolProperty(
name='Write Normals',
description='Export one normal per vertex and per face, to represent flat faces and sharp edges',
default=export_objex.ObjexWriter.default_options['EXPORT_NORMALS'],
)
use_vertex_colors = BoolProperty(
name='Write Vertex Colors',
description='Export one color per vertex and per face',
default=export_objex.ObjexWriter.default_options['EXPORT_VERTEX_COLORS'],
)
use_uvs = BoolProperty(
name='Include UVs',
description='Write out the active UV coordinates',
default=export_objex.ObjexWriter.default_options['EXPORT_UV'],
)
use_materials = BoolProperty(
name='Write Materials',
description='Write out the MTLEX file',
default=export_objex.ObjexWriter.default_options['EXPORT_MTL'],
)
use_skeletons = BoolProperty(
name='Write Skeletons',
description='Write out the SKEL file',
default=export_objex.ObjexWriter.default_options['EXPORT_SKEL'],
)
use_animations = BoolProperty(
name='Write Animations',
description='Write out the ANIM file',
default=export_objex.ObjexWriter.default_options['EXPORT_ANIM'],
)
link_anim_bin = BoolProperty(
name='Write Link anim BINs',
description='Write binary animation data for Link',
default=export_objex.ObjexWriter.default_options['EXPORT_LINK_ANIM_BIN'],
)
link_bin_scale = FloatProperty(
name='Link bin scale',
description='If your Link is about 4 (young) / 6 (adult) units tall, this should be 1000',
soft_min=1.0, soft_max=1000.0,
default=export_objex.ObjexWriter.default_options['LINK_BIN_SCALE'],
)
use_weights = BoolProperty(
name='Write Weights',
description='Write out the vertex weights',
default=export_objex.ObjexWriter.default_options['EXPORT_WEIGHTS'],
)
use_unique_weights = BoolProperty(
name='Write one weight per vertex',
description="Use vertex group with maximum weight, with weight 1.0 (doesn't write any weight if there is no vertex group assigned)",
default=export_objex.ObjexWriter.default_options['UNIQUE_WEIGHTS'],
)
use_triangles = BoolProperty(
name='Triangulate Faces',
description='Convert all faces to triangles',
default=export_objex.ObjexWriter.default_options['TRIANGULATE'],
)
export_packed_images = BoolProperty(
name='Export packed images',
description='Save packed images outside the blend file',
default=export_objex.ObjexWriter.default_options['EXPORT_PACKED_IMAGES'],
)
export_packed_images_dir = StringProperty(
name='Export packed images directory',
description='Where to save packed images',
default=export_objex.ObjexWriter.default_options['EXPORT_PACKED_IMAGES_DIR'],
)
keep_vertex_order = BoolProperty(
name='Keep Vertex Order',
description='',
default=export_objex.ObjexWriter.default_options['KEEP_VERTEX_ORDER'],
)
# logging
logging_level_console = IntProperty(
name='Log level',
description=(
'Affects logging in the system console.\n'
'The lower, the more logs.\n'
'%s'
) % logging_util.debug_levels_str,
default=logging_util.default_level_console,
min=logging_util.minimum_level,
max=logging_util.maximum_level,
)
logging_level_report = IntProperty(
name='Report level',
description=(
'What logs to report to Blender.\n'
'When the import is done, warnings and errors, if any, are shown in the UI.\n'
'The lower, the more logs.\n'
'%s'
) % logging_util.debug_levels_str,
default=logging_util.default_level_report,
min=logging_util.minimum_level,
max=logging_util.maximum_level,
)
logging_file_enable = BoolProperty(
name='Log to file',
description='Log everything (all levels) to a file',
default=True, # 421todo better write logs by default during testing
)
logging_file_path = StringProperty(
name='Log file path',
description=(
'The file to write logs to.\n'
'Path can be relative (to export location) or absolute.'
),
default='objex_export_log.txt',
)
path_mode = path_reference_mode
check_extension = True
def draw(self, context):
if self.use_selection:
box = self.layout.box()
box.prop(self, 'use_selection')
box.prop(self, 'include_armatures_from_selection')
elif hasattr(bpy.data, 'collections'): # 2.80+
box = self.layout.box()
box.prop(self, 'use_selection')
box.prop_search(self, 'use_collection', bpy.data, 'collections')
if self.use_collection:
box.prop(self, 'include_armatures_from_selection')
else: # < 2.80
self.layout.prop(self, 'use_selection')
if self.use_mesh_modifiers:
box = self.layout.box()
box.prop(self, 'use_mesh_modifiers')
box.prop(self, 'use_mesh_modifiers_render')
box.prop(self, 'apply_unused_armature_deform')
box.prop(self, 'apply_modifiers_after_armature_deform')
else:
self.layout.prop(self, 'use_mesh_modifiers')
self.layout.prop(self, 'use_uvs')
self.layout.prop(self, 'use_normals')
self.layout.prop(self, 'use_vertex_colors')
if self.use_smooth_groups:
box = self.layout.box()
box.prop(self, 'use_smooth_groups')
box.prop(self, 'use_smooth_groups_bitflags')
else:
self.layout.prop(self, 'use_smooth_groups')
self.layout.prop(self, 'use_materials')
if self.use_skeletons:
box = self.layout.box()
box.prop(self, 'use_skeletons')
if self.use_animations:
box2 = box.box()
box2.prop(self, 'use_animations')
box2.prop(self, 'link_anim_bin')
box2.prop(self, 'link_bin_scale')
else:
box.prop(self, 'use_animations')
if self.use_weights:
box2 = box.box()
box2.prop(self, 'use_weights')
box2.prop(self, 'use_unique_weights')
else:
box.prop(self, 'use_weights')
else:
self.layout.prop(self, 'use_skeletons')
self.layout.prop(self, 'axis_forward')
self.layout.prop(self, 'axis_up')
self.layout.prop(self, 'keep_vertex_order')
self.layout.prop(self, 'use_triangles')
if self.export_packed_images:
box = self.layout.box()
box.prop(self, 'export_packed_images')
box.prop(self, 'export_packed_images_dir')
else:
self.layout.prop(self, 'export_packed_images')
box = self.layout.box()
box.prop(self, 'logging_level_console')
box.prop(self, 'logging_level_report')
box.prop(self, 'logging_file_enable')
if self.logging_file_enable:
box.prop(self, 'logging_file_path')
self.layout.prop(self, 'path_mode')
def execute(self, context:bpy.types.Context):
from mathutils import Matrix
keywords = self.as_keywords(ignore=('axis_forward',
'axis_up',
'check_existing',
'filter_glob',
'logging_level_console',
'logging_level_report',
'logging_file_enable',
'logging_file_path',
))
global_matrix = blender_version_compatibility.matmul(
Matrix.Scale(context.scene.objex_bonus.blend_scale, 4),
axis_conversion(to_forward=self.axis_forward,
to_up=self.axis_up,
).to_4x4())
keywords['global_matrix'] = global_matrix
if hasattr(bpy.data, 'collections'): # 2.80+
keywords['use_collection'] = bpy.data.collections.get(self.use_collection)
else:
del keywords['use_collection']
log = logging_util.getLogger('OBJEX_OT_export')
try:
logging_util.setConsoleLevel(self.logging_level_console)
if self.logging_file_enable:
logfile_path = self.logging_file_path
if not os.path.isabs(logfile_path):
export_dir, _ = os.path.split(self.filepath)
logfile_path = '%s/%s' % (export_dir, logfile_path)
log.info('Writing logs to {}', logfile_path)
logging_util.setLogFile(logfile_path)
logging_util.setLogOperator(self, self.logging_level_report)
def progress_report_print(*args, **kwargs):
"""
Typical print() arguments called from progress_report:
args = ('Progress: 1.85%\r',)
kwargs = {'end': ''}
args = (' ( 0.1298 sec | 0.1198 sec) Objex Export Finished\nProgress: 100.00%\r',)
kwargs = {'end': ''}
args = ('\n',)
kwargs = {}
"""
# ignore kwargs['flush'] and kwargs['file']
message = '%s%s' % (kwargs.get('sep', ' ').join(args), kwargs.get('end','\n'))
for line in message.split('\n'):
if not line:
print() # \n
elif line[-1] == '\r':
print(line, end='')
else:
log.info(line)
progress_report.print = progress_report_print
# Warn about using texture (face texture) shading in < 2.80
if (any(material.objex_bonus.is_objex_material for material in bpy.data.materials)
and any(
any(space.viewport_shade == 'TEXTURED'
for space in area.spaces
if space.type != 'VIEW_3D'
and hasattr(space, 'viewport_shade') # < 2.80
) for area in bpy.context.screen.areas
if area.type == 'VIEW_3D'
)
):
log.warning('There is a 3d view area in the current screen which is\n'
'using Texture as Viewport Shading and not Material,\n'
'which is required to correctly preview objex-enabled materials.',
shading_type)
view_transform = context.scene.view_settings.view_transform
if bpy.app.version < (2, 80, 0):
view_transform_ok = 'Default'
else:
view_transform_ok = 'Standard'
if view_transform != view_transform_ok:
log.warning('Scene uses view_transform={!r} which changes how colors are '
'displayed in the viewport, reducing the preview accuracy.\n'
'This can be changed under Color Management in {} properties.\n'
'Recommended value: {}',
view_transform, 'Scene' if bpy.app.version < (2, 80, 0) else 'Render',
view_transform_ok)
display_device = context.scene.display_settings.display_device
# 421fixme 'Rec709' is also available in 2.79, idk what it is but it's mentioned in
# the tooltip for the Linear value of the Color Space property of image texture nodes
display_device_ok = 'None'
if context.scene.objex_bonus.colorspace_strategy != 'QUIET' and display_device != display_device_ok:
log.warning('Scene uses display_device={!r} which changes how colors are '
'displayed in the viewport, reducing the preview accuracy.\n'
'This can be changed under Color Management in {} properties.\n'
'Note that this should also be kept consistent with the '
'Color Space property of image texture nodes '
'(display_device="None", Color Space="Linear").\n'
'{}'
'Recommended value: {}',
display_device,
'Scene' if bpy.app.version < (2, 80, 0) else 'Render',
'In Blender 2.7x, "Color Space" can be found in the Image Editor.\n'
if bpy.app.version < (2, 80, 0) else '',
display_device_ok)
return export_objex.save(context, **keywords)
except util.ObjexExportAbort as abort:
log.error('Export abort: {}', abort.reason)
return {'CANCELLED'}
except:
log.exception('Uncaught exception')
raise
finally:
progress_report.print = print
logging_util.resetLoggingSettings()
axis_forward = '-Z'
axis_up='Y'
from bpy_extras.io_utils import orientation_helper
@orientation_helper(axis_forward=axis_forward, axis_up=axis_up)
class OBJEX_OT_export(bpy.types.Operator, OBJEX_OT_export_base, ExportHelper):
pass
def menu_func_export(self, context):
self.layout.operator(OBJEX_OT_export.bl_idname, text='Objex2 (.objex)')
class OBJEX_AddonPreferences(bpy.types.AddonPreferences, logging_util.AddonLoggingPreferences, addon_updater_ops.AddonUpdaterPreferences):
bl_idname = __package__
colorspace_default_strategy = bpy.props.EnumProperty(
items=[
('AUTO','Auto','Default to "Warn non-linear" (for now)',0)
] + [
# copied from properties.ObjexSceneProperties.colorspace_strategy
('QUIET','Do nothing + silence',
'Do nothing and do not warn about using a non-linear color space.',1),
('WARN','Warn non-linear',
'Warn on export about using a non-linear color space.',2),
],
name='Default Color Space Strategy',
description='Default value for the scene Color Space Strategy property.',
default='AUTO'
)
# see view3d_copybuffer_patch.py
monkeyPatch_view3d_copybuffer = bpy.props.EnumProperty(
items=[
('AUTO','Auto','Default to "Wrap copying - delete" (for now)',1),
('NOTHING','Do nothing','Do not disable "Ctrl+C" (or any other or change anything else)',2),
('DISABLE','Disable Ctrl+C','Disable "Ctrl+C", the key combo will do nothing',3),
('WRAPPER_DELETE','Wrap copying - delete',
'Disable vanilla copy operator shortcut (usually Ctrl+C) and remap it to '
'an operator that deletes the data causing issues before copying',4),
# 421todo cf comments in OBJEX_OT_view3d_copybuffer_wrapper in view3d_copybuffer_patch.py
#('WRAPPER_PACK','Wrap copying - pack','Disable vanilla copy operator shortcut (usually Ctrl+C) and remap it to an operator that encodes the data causing issues before copying, and also wrap the paste operator to decode that data',5),
],
name='"Fix" copy',
# Specifically, the addon-defined sockets *seem* to be at fault
description='Method to use for "fixing" (read: circumventing an issue) "Ctrl+C" (or any shortcut mapped to the copy operator view3d.copybuffer) which crashed Blender when copying objects using Objex-enabled materials',
default='AUTO' if bpy.app.version < (2, 80, 0) else 'NOTHING',
update=view3d_copybuffer_patch.monkeyPatch_view3d_copybuffer_update
)
# what were the user settings for view3d.copybuffer before the addon changed it (for internal use)
monkeyPatch_view3d_copybuffer_active_user = bpy.props.EnumProperty(
items=[
('None', '','',1), # settings not overwritten by addon
('True', '','',2),
('False','','',3),
],
default='None'
)
def draw(self, context):
addon_updater_ops.check_for_update_background()
logging_util.AddonLoggingPreferences.draw(self, context)
self.layout.prop(self, 'colorspace_default_strategy')
self.layout.prop(self, 'monkeyPatch_view3d_copybuffer')
addon_updater_ops.update_settings_ui(self, context)
addon_updater_ops.update_notice_box_ui(self, context)
classes = (
OBJEX_OT_export,
OBJEX_AddonPreferences,
)
def register():
util.addon_version = bl_info['version']
# must register OBJEX_AddonPreferences before registerLogging
for cls in classes:
blender_version_compatibility.make_annotations(cls)
bpy.utils.register_class(cls)
addon_updater_ops.register(bl_info)
logging_util.registerLogging('objex')
_MT_file_export = bpy.types.INFO_MT_file_export if hasattr(bpy.types, 'INFO_MT_file_export') else bpy.types.TOPBAR_MT_file_export
_MT_file_export.append(menu_func_export)
rigging_helpers.register()
properties.register_properties()
data_updater.register()
interface.register_interface()
node_setup_helpers.register()
view3d_copybuffer_patch.register()
from . import export_objex_anim
bpy.utils.register_class(export_objex_anim.OBJEX_OT_export_link_anim_bin)
bpy.utils.register_class(export_objex_anim.OBJEX_OT_import_link_anim_bin)
# reverse register() order
def unregister():
from . import export_objex_anim
bpy.utils.unregister_class(export_objex_anim.OBJEX_OT_export_link_anim_bin)
bpy.utils.unregister_class(export_objex_anim.OBJEX_OT_import_link_anim_bin)
view3d_copybuffer_patch.unregister()
node_setup_helpers.unregister()
interface.unregister_interface()
data_updater.unregister()
properties.unregister_properties()
rigging_helpers.unregister()
_MT_file_export = bpy.types.INFO_MT_file_export if hasattr(bpy.types, 'INFO_MT_file_export') else bpy.types.TOPBAR_MT_file_export
_MT_file_export.remove(menu_func_export)
logging_util.unregisterLogging()
addon_updater_ops.unregister()
# must not unregister OBJEX_AddonPreferences before unregisterLogging
for cls in reversed(classes):
bpy.utils.unregister_class(cls)
if __name__ == '__main__':
register()