-
Notifications
You must be signed in to change notification settings - Fork 1
/
mstsexporter.py
2718 lines (2120 loc) · 100 KB
/
mstsexporter.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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
bl_info = { "name": "Export OpenRails/MSTS Shape File(.s)",
"author": "Wayne Campbell/Pete Willard",
"version": (4, 6),
"blender": (3, 6, 0),
"location": "File > Export > OpenRails/MSTS (.s)",
"description": "Export file to OpenRails/MSTS .S format",
"category": "Import-Export"}
# Updated for Blender 4.0+ compatibility with fallback for older versions
# Version 4.6
'''
COPYRIGHT 2019 by Wayne Campbell
This program 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 program 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.
A copy of the GNU General Public License is included in this distribution package
or may be found here <http://www.gnu.org/licenses/>.
For complete documentation, and CONTACT info see the Instructions included in the distribution package.
REVISION HISTORY
2024-12-12 Released V4.6 - pkw - Fix for the deprecated to.mesh in 4.x
2024-04-03 Released V4.5 - pkw - Handling issues created by Blender 4.1 deprecating smoothing related APIs.
2023-07-13 Released V4.4 - pkw
Added support for exporting texture references as DDS files instead of just ACE files using a checkbox.
Like the ACE file export, it changes *ALL* texture references to DDS when checked.
2019-07-23 Released V4.3
Improved instructions around linking a part to multiple LOD collections
Fixed program error - no material slots, or empty material slot
2019-07-21 Released V4.2 for testing
Added HierarchyOptimization
Added FastExport - improves speed 25 x
Restructured AddMesh, AddTriangle with MSTSMaterialsDetail structure to improve performance
Indexed vertices for faster export ( eg speedup by 3 times )
2019-07-18 Released V4.1 to beta testers
Modified install package to work with 'Install from file..'
Fixed ShapeViewer crashes on animations(0)
2019-07-17 Released V4.0 to beta testers
Updated for Blender 2.8
2017-09-12 Released as V 3.5
added SubObjID to SubObjectHeader per report from 'Spike'
added support for Auto Smoothing per http://www.elvastower.com/forums/index.php?/topic/30491-blender-auto-smooth-and-msts-export/
2016-01-11 Released as V 3.4
strip periods (.) from object names
fixes to LOD inheritance
remember RetainNames setting
file export dialog, default to .s extension
2016-01-10 Testing as V 3.3
Added RetainNames option
Fixed bounding sphere bug
Trimmed most numbers to 6 decimal places to reduce output file size
2016-01-10 Testing as V 3.2
Documented hidden option to use Railworks style LOD naming
Documented setting MAX values in Custom Properties
Fixed AttributeError: 'NoneType' object has no attribute 'game_settings'
2016-01-09 Testing as V 3.1
Added MipMapLODBias setting
Fixed bug, untextured faces - AttributeError: 'NoneType' object has no attribute 'name'
Implemented MSTS sub_object flags for sorting alpha blended faces ( not needed for OR )
Implement MSTS sub_object flags for specularity ( not needed for OR )
Added Alpha Sorted Transparency option to MSTS Material
Improved descriptions and naming of MSTS Material settings
Fixed MSTS Lighting value not being saved
Sped up iVertexAdd, iNormalAdd, etc, with spatial tree indexing, etc
2016-01-08 Testing as V 3.0
Fix for WHEELS13, WHEELS23
Changed use_shadeless, from selecting Cruciform, now done with MSTS Lighting
Added MSTS Material panel for lighting options, etc
Added support for Railworks style LOD naming
2015-11-11 Released as V 2
Changed prim_state labels to be compatible with Polymaster
2013-11-01 Initial Release as V 2.6.3
TODO FUTURE
- add a progress bar ( when available in the Blender API )
- document or remove hidden Normals override options ( superceded by Blender's new Normals Modifier )
IDEAS FUTURE
- add support for curves, particle systems, dupliverts
- support undocumented MSTS capability, eg
- Wrap, Clamp, Extend etc
- double sided faces
- bump mapping and environmental reflections
- AddATex, SubractATex, etc and other undocumented shaders
- zBias
- use of lod_control objects to improve LOD efficiency
- option to export texture files
- option to compress shape file
- options to generate .SD, .ENG, .WAG or .REF
'''
import bpy
import os
from math import radians
from bpy.props import StringProperty, EnumProperty, BoolProperty
import mathutils
from mathutils import *
class MyException( Exception ):
pass
MaxVerticesPerPrimitive = 8000 # 8000 OK 20000 Fails
MaxVerticesPerSubObject = 15000 # 15000 OK 20000 Fails, Note: Spike reports 14000 failed, he uses 12000
FastExport = True # do less compaction to reduce export time at cost of slightly larger file size
# no impact on frame rates for most files, very large files may see a couple of additional Draw calls
# eg L1-huge.blend exports in 28 sec vs 11 min 42 sec, file size = 63,628,192 vs 55,423,130 bytes
HierarchyOptimization = True # gives better triangle fill, reduces subobject splitting in middle of primitive,
# creates new subobjects for each hierarchy level
# should improve frame rates by reducing Draw Calls, and creating smaller vertex sets, where possible
# yet places multiple primitives in a subobject when vertex sharing across large vertex sets make sense
RetainNames = False # user option, when true, the exporter disables mesh
# consolidation and hierarchy collapse optimizations
# reduces frame rates due to more Draw Calls
UseDDS = False
BlenderVersion = bpy.app.version # returns tuple of (major, minor, subversion)
#####################################
from bpy_extras.io_utils import ExportHelper, ImportHelper # gives access to the FileSelectParams
ProgressIndicator = 0.0 # spins from 0 to 1
ProgressContext = None
def UpdateProgress(): # this is the little cursor counter progress indicator ( all thats available in Blender's API )
global ProgressIndicator
global ProgressContext
ProgressContext.window_manager.progress_update(ProgressIndicator)
ProgressIndicator += 0.0001
if ProgressIndicator > 1.0:
ProgressIndicator = 0
# Function to get mesh depending on Blender version
def get_evaluated_mesh(obj):
if BlenderVersion < (4, 1, 0):
# Pre-Blender 4.1, use the standard evaluated object approach
depsgraph = bpy.context.evaluated_depsgraph_get()
evaluated_obj = obj.evaluated_get(depsgraph)
mesh = evaluated_obj.to_mesh()
else:
# Blender 4.1+ requires alternate handling
depsgraph = bpy.context.evaluated_depsgraph_get()
evaluated_obj = obj.evaluated_get(depsgraph)
mesh = evaluated_obj.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph)
return mesh
class ExportHelper:
filepath : StringProperty(
name="File Path",
description="Filepath used for exporting the file",
maxlen=1024,
subtype='FILE_PATH',
)
# set up the FileSelectParams
filename_ext = ".s"
filter_glob : StringProperty(default="*.s", options={'HIDDEN'})
class MSTSExporter(bpy.types.Operator, ExportHelper):
bl_idname = "export.msts_s"
bl_description = 'Export to OpenRails/MSTS .s file'
bl_label = "Export OpenRails/MSTS S"
bl_space_type = "PROPERTIES"
bl_region_type = "WINDOW"
bl_options = {'UNDO'}
filepath : StringProperty(subtype='FILE_PATH')
def invoke(self, context, event):
settings = context.scene.msts
# set up default path
blend_filepath = context.blend_data.filepath
if not blend_filepath:
blend_filepath = "untitled"
else:
blend_filepath = os.path.splitext(blend_filepath)[0]
self.filepath = blend_filepath + self.filename_ext
# override with last used path if it looks good
if settings.SFilepath != "":
lastSavedPath = os.path.abspath( bpy.path.abspath( settings.SFilepath ) )
lastSavedFolder = os.path.split(lastSavedPath)[0]
if os.path.exists( lastSavedFolder ):
self.filepath = lastSavedPath
WindowManager = context.window_manager
WindowManager.fileselect_add(self)
return {"RUNNING_MODAL"}
def draw( self, context ):
settings = context.scene.msts
layout = self.layout
layout.prop( self, "filepath" )
layout.prop( settings, "RetainNames" )
layout.prop( settings, "UseDDS" )
def execute(self, context):
settings = context.scene.msts
global RetainNames
RetainNames = settings.RetainNames
global UseDDS
UseDDS = settings.UseDDS
#Append .s
exportPath = bpy.path.ensure_ext(self.filepath, ".s")
settings.SFilepath = TryGetRelPath( exportPath )
# Validate root object
rootName = 'MAIN'
rootCollection = bpy.context.scene.collection.children.get( rootName )
if rootCollection == None:
print()
print( "ERROR: MAIN not found in Scene Collection.")
self.report( {'ERROR'}, "MAIN not found in Scene Collection" )
return {'CANCELLED' }
#force out of edit mode
if bpy.context.mode != 'OBJECT':
bpy.ops.object.mode_set( mode = 'OBJECT' )
#Export
print()
print( "EXPORTING "+rootName + " TO " + exportPath )
print()
global ProgressContext
ProgressContext = context
context.window_manager.progress_begin( 0,1 ) # progress bar indication ( forthcoming feature )
UpdateProgress()
try:
ExportShapeFile( rootName, exportPath )
print( "FINISHED OK" )
self.report( {'INFO'}, "Finished OK" )
return {"FINISHED"}
except MyException as error: # when we raise an error it comes here
context.window_manager.progress_end()
print( "ERROR: " + ' '.join(error.args) )
self.report( {'WARNING'}, ' '.join(error.args) )
return { "CANCELLED" }
# all other exceptions are passed up for traceback
finally:
context.window_manager.progress_end()
def cancel( self, message ):
print( "ERROR: ", message )
self.report( {'ERROR'}, message )
return {'CANCELLED' }
def menu_func(self, context):
self.layout.operator(MSTSExporter.bl_idname, text="OpenRails/MSTS (.s)")
def register():
bpy.utils.register_class( msts_material_props) # define the new msts material properties
bpy.utils.register_class( msts_scene_props)
bpy.types.Material.msts = bpy.props.PointerProperty(type=msts_material_props) # add the properties to the material type
bpy.types.Scene.msts = bpy.props.PointerProperty(type=msts_scene_props)
bpy.utils.register_class( msts_material_panel ) # add a UI panel to the Materials window
bpy.utils.register_class( MSTSExporter ) # define the exporter dialog panel
bpy.types.TOPBAR_MT_file_export.append(menu_func) # add the exporter to the menu
def unregister():
bpy.types.TOPBAR_MT_file_export.remove(menu_func)
bpy.utils.unregister_class( MSTSExporter )
bpy.utils.unregister_class( msts_material_panel )
del bpy.types.Scene.msts
del bpy.types.Material.msts
bpy.utils.unregister_class( msts_scene_props)
bpy.utils.unregister_class( msts_material_props )
'''
************************ THE GUI *******************************
'''
#####################################
# find an image with the specified path, or create it
def GetImage( filepath ):
return bpy.data.images.load( filepath, check_existing = True )
#####################################
# recreate the shader nodes to represent the msts settings
def RecreateShaderNodes( m ):
# remove any existing nodes
m.use_nodes = True
m.node_tree.nodes.clear()
m.node_tree.links.clear()
# create the nodes
MNode = m.node_tree.nodes.new('ShaderNodeOutputMaterial')
BNode = m.node_tree.nodes.new('ShaderNodeBsdfPrincipled')
TNode = m.node_tree.nodes.new('ShaderNodeTexImage')
UNode = m.node_tree.nodes.new('ShaderNodeUVMap')
# layout the shader screen
MNode.location.x = 300
BNode.location.x = 0
TNode.location.x = -300
UNode.location.x = -550
# Set active node
MNode.select = False
BNode.select = False
TNode.select = False
UNode.select = False
m.node_tree.nodes.active = None
# setup specularity
if m.msts.Lighting == 'SPECULAR25':
BNode.inputs['Specular'].default_value = 0.1
BNode.inputs['Roughness'].default_value = 0.3
elif m.msts.Lighting == 'SPECULAR750':
BNode.inputs['Specular'].default_value = 0.1
BNode.inputs['Roughness'].default_value = 0.1
else:
BNode.inputs['Specular'].default_value = 0.0
BNode.inputs['Roughness'].default_value = 1.0
# setup image
if os.path.exists( bpy.path.abspath(m.msts.BaseColorFilepath) ):
TNode.image = GetImage( m.msts.BaseColorFilepath )
# setup uvs
UNode.uv_map = 'UVMap'
# link the nodes
m.node_tree.links.new(MNode.inputs['Surface'],BNode.outputs['BSDF'])
m.node_tree.links.new(BNode.inputs['Base Color'],TNode.outputs['Color'])
if m.msts.Transparency != "OPAQUE":
m.node_tree.links.new(BNode.inputs['Alpha'],TNode.outputs['Alpha'])
m.node_tree.links.new(TNode.inputs['Vector'],UNode.outputs['UV'])
# TODO Add support for additional msts lighting modes, eg cruciform, etc
#####################################
# called when the MSTS material panel settings are changed
def SetDefaultViewportShading( screenName ):
for screen in bpy.data.screens:
if screen.name == screenName:
area = next(area for area in screen.areas if area.type == 'VIEW_3D')
space = next(space for space in area.spaces if space.type == 'VIEW_3D')
space.shading.show_backface_culling = True
space.shading.color_type = 'TEXTURE'
space.shading.light = 'STUDIO'
return
print( "Warning: Screen " + screenName + " not found while setting viewport shading." )
# Show specified image in active UV window
def SetUVWindowImage( context, image ):
if image != None:
for eachArea in context.screen.areas:
if eachArea.type == 'IMAGE_EDITOR':
for eachSpace in eachArea.spaces:
if eachSpace.type == 'IMAGE_EDITOR':
eachSpace.image = image
return
return
# Show specified image path in active UV window
def SetUVWindowImagePath( context, imagePath ):
if os.path.exists( bpy.path.abspath(imagePath) ):
image = GetImage( imagePath )
SetUVWindowImage( context, image )
#####################################
# called when the image is changed in the MSTS material panel
# changes material name to match and updates material settings
def UpdateMSTSImage( self, context ):
if hasattr(context, 'material'):
if context.material != None:
mstsmaterial= context.material.msts
if mstsmaterial.UpdateNodes:
materialName = bpy.path.display_name_from_filepath( mstsmaterial.BaseColorFilepath )
if not materialName in bpy.data.materials:
context.material.name = materialName
#else:
# if the suggested material name already exists,
# then leave it up to the user to sort it out
SetUVWindowImagePath( context, mstsmaterial.BaseColorFilepath )
UpdateMSTSMaterial( self, context )
#####################################
# called when the MSTS material panel settings are changed
def UpdateMSTSMaterial( self, context ):
if hasattr(context, 'material'):
if context.material != None:
mstsmaterial= context.material.msts
if mstsmaterial.UpdateNodes:
blM = context.material
blM.use_backface_culling = True
if blM.msts.Transparency == "OPAQUE":
blM.blend_method = "OPAQUE"
elif blM.msts.Transparency == "CLIP":
blM.blend_method = "CLIP"
elif blM.msts.Transparency == "ALPHA":
blM.blend_method = "BLEND"
elif blM.msts.Transparency == "ALPHA_SORT":
blM.blend_method = "BLEND"
RecreateShaderNodes( blM )
SetDefaultViewportShading( 'Layout' )
SetDefaultViewportShading( 'UV Editing' )
#####################################
class msts_material_panel(bpy.types.Panel):
"""Creates a Panel in the material context of the properties editor"""
bl_label = "MSTS Materials"
bl_idname = "MATERIAL_PT_msts"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "material"
def draw(self, context): # see bpy.context for info on available context's
if context.material != None:
mstsmaterial= context.material.msts
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False
# Create a simple row.
col = layout.column(align = True )
col.prop(mstsmaterial, property="Transparency" )
col.prop(mstsmaterial, property="Lighting" )
col.prop(mstsmaterial, property="MipMapLODBias") # this should be a texture property
# not a material property
# but here is simpler for the user to find
col.prop(mstsmaterial, property="BaseColorFilepath" )
col.prop(mstsmaterial, property="UpdateNodes" )
#####################################
class msts_material_props(bpy.types.PropertyGroup):
# define custom material properties, ie material.msts.shadername note: these prop's will be saved in the blend file
Transparency : bpy.props.EnumProperty(
name="Transparency",
description="Controls handling of alpha channel.",
items = [ ( "OPAQUE", "Solid Opaque", "Alpha channel is ignored" ),
( "CLIP", "Transparency On/Off", "Transparent if alpha value below a threshold" ),
( "ALPHA", "Alpha Blended", "Alpha value blends from transparent up to opaque" ),
( "ALPHA_SORT","Alpha Sorted", "Alpha blending with depth sort" )
],
default="OPAQUE",
update= UpdateMSTSMaterial,
)
Lighting : bpy.props.EnumProperty(
name="Lighting",
description="Adjusts light and shadow",
items = [ ("NORMAL", "Normal", "Sun facing surfaces are lit and opposite are shaded" ),
("SPECULAR25", "Specular 25", "Strong specular highlight" ),
("SPECULAR750", "Specular 750", "Small specular highlight" ),
("FULLBRIGHT", "Full Bright", "Shaded surfaces appear lit" ),
("HALFBRIGHT", "Half Bright", "Shaded surfaces appear partly lit" ),
("DARK", "Dark", "Sun facing surfaces appear fully shaded" ),
("CRUCIFORM", "Cruciform", "Indirect ambient lighting only" ),
("EMISSIVE", "Emissive", "Surfaces emit light at night" )
],
default="NORMAL",
update= UpdateMSTSMaterial,
)
MipMapLODBias : bpy.props.FloatProperty(
name="Mip Bias",
description="Controls sharpness of the image, default = -3",
default = 0,
soft_max = 8,
soft_min = -8,
precision = 1,
step = 100
)
BaseColorFilepath : StringProperty(
description = 'The texture image file path.',
update= UpdateMSTSImage,
subtype='FILE_PATH',
)
UpdateNodes : BoolProperty(
name='Update Shader',
description = 'Change shader nodes to match these settings',
default = True ,
update= UpdateMSTSMaterial,
)
LightingOptions = { "NORMAL":-5,
"SPECULAR25":-6,
"SPECULAR750":-7,
"FULLBRIGHT":-8,
"HALFBRIGHT":-11,
"DARK":-12,
"CRUCIFORM":-9,
"EMISSIVE":-5
}
class msts_scene_props(bpy.types.PropertyGroup):
# these properties appear in the file export dialog
SFilepath : StringProperty( default = "" )
RetainNames : BoolProperty(name='Retain Names', description = 'Disables object merging optimizations', default = False )
UseDDS : BoolProperty(name='Use DDS', description = 'Export Texture type as DDS instead of ACE', default = False )
'''
This code converts from Blender data structures to MSTS data structures
from here down to the Library section, the code uses blender coordinate system unless specified as MSTS
'''
#####################################
def GetFileNameNoExtension( filepath ): # eg filePath = '//textures\\redtile.tga'
s = filepath.replace( '\\','/' ) # s = '//textures/redtile.tga'
parts = s.split( '/' ) # parts = ['','','textures','redtile.tga']
lastPart = parts[ len(parts)-1 ] # lastPart = 'redtile.tga'
noextension = os.path.splitext( lastPart )[0] # noextension = 'redtile'
return noextension
#####################################
# convert to path relative to this blend file if possible
# otherwise just return filepath
def TryGetRelPath( filepath ):
try:
return bpy.path.relpath( filepath )
except:
return filepath
#####################################
# specifies how normals are to be calculated
class Normals: # passed to AddFaceToSubObject to request special handling of normals
Face = 0 # flat normals
Smooth = 1 # smoothed ( can be overriden per face )
Out = 3 # normals radiate out from center of model Mesh or Material Property: NORMALS = OUT
Up = 4 # all normals face up Mesh or Material Property: NORMALS = UP
Fillet = 5 # bevels are modified to appear rounded Mesh or Material Property: NORMALS = FILLET
OutX = 6 # normals radiate out to the left and right along objects x=0,z=-4 axis
#####################################
# given a blender property override like NORMALS = UP, and an initialNormal,
# return the normal state after the override is applied
# propertyString represents eg "UP"
# initialNormal eg Normals.Face
def GetNormalsOverride( propertyString, initialNormal ):
if propertyString == 'UP':
return Normals.Up
elif propertyString == 'OUT':
return Normals.Out
elif propertyString == 'FILLET':
return Normals.Fillet
elif propertyString == "OUTX":
return Normals.OutX
return initialNormal
#####################################
def iShaderAdd( shaderName ):
if shaderName in ExportShape.Shaders:
iShader = ExportShape.Shaders.index(shaderName)
else:
iShader = len( ExportShape.Shaders )
ExportShape.Shaders.append( shaderName )
return iShader
#####################################
def iFilterAdd( filterName ):
if filterName in ExportShape.Filters:
iFilter = ExportShape.Filters.index( filterName )
else:
iFilter = len( ExportShape.Filters )
ExportShape.Filters.append( filterName )
return iFilter
#####################################
# imageName is in msts format, eg unionstop.ace
def iImageAdd( imageName ):
if imageName==None or imageName == '':
imageName = 'blank'
if UseDDS==False:
imageName = imageName + '.ace'
else:
imageName = imageName + '.dds'
for iImage in range(0, len( ExportShape.Images)):
if ExportShape.Images[iImage] == imageName:
return iImage
iImage = len( ExportShape.Images)
ExportShape.Images.append( imageName)
return iImage
#####################################
def iTextureAdd( imageName, mipMapLODBias ): # creates both texture and image entries
iImage = iImageAdd( imageName )
for iTexture in range( 0, len( ExportShape.Textures)):
texture = ExportShape.Textures[iTexture]
if texture.iImage == iImage and texture.MipMapLODBias == mipMapLODBias:
return iTexture
iTexture = len( ExportShape.Textures )
newTexture = Texture()
newTexture.iImage = iImage
newTexture.iFilter = iFilterAdd( 'MipLinear' )
newTexture.MipMapLODBias = mipMapLODBias
ExportShape.Textures.append( newTexture )
return iTexture
#####################################
def UVOpsMatch( opsList, specifierList ): # specifiers is a list ( operation, textureAddressMode ) pairs
if len( opsList ) != len( specifierList ):
return False
for i in range( 0, len( opsList ) ):
eachUVOp = opsList[i]
operation = specifierList[i][0]
if eachUVOp.__class__ != operation: return False
if operation == UVOpCopy and eachUVOp.TextureAddressMode != specifierList[i][1]: return False
elif operation == UVOpReflectMapFull: continue
return True
#####################################
def iLightConfigAdd( uvops ): # it a list of ( operation, textureAddressMode ) pairs
# see if its already set up
for i in range( 0, len( ExportShape.LightConfigs ) ):
if UVOpsMatch( ExportShape.LightConfigs[i].UVOps, uvops ):
return i
# no, so create it
i = len( ExportShape.LightConfigs )
newLightConfig = LightConfig()
for eachop in uvops:
if eachop[0] == UVOpCopy:
newUVOp = UVOpCopy()
newUVOp.TextureAddressMode = eachop[1]
elif op[0] == UVOpReflectMapFull:
newUVOp = UVOpReflectMapFull()
else:
raise Exception( "PROGRAM ERROR: UNDEFINED UV OPERATION" )
newLightConfig.UVOps.append( newUVOp )
ExportShape.LightConfigs.append( newLightConfig )
return i
#####################################
def iColorAdd( color ): # a r g b
global UniqueColors
return UniqueColors.IndexOf( color )
#####################################
def iLightMaterialAdd( lm ): # diff, amb, spec, emmisive, power
global UniqueLightMaterials
return UniqueLightMaterials.IndexOf( lm )
#####################################
def iVertexStateAdd( flags, iMatrix, iLightMaterial, iLightConfig ):
i = len( ExportShape.VertexStates ) # use the last correct entry - earlier ones will have a full vtx_set
while i > 0:
i -= 1
eachVertexState = ExportShape.VertexStates[i]
if eachVertexState.Flags == flags \
and eachVertexState.iMatrix == iMatrix \
and eachVertexState.iLightMaterial == iLightMaterial \
and eachVertexState.iLightConfig == iLightConfig:
# we found one
return i
# we didn't find it, so add it and add a corresponding vertex set to every sub_object
i = len( ExportShape.VertexStates )
newVertexState = VertexState()
newVertexState.Flags = flags
newVertexState.iMatrix = iMatrix
newVertexState.iLightMaterial = iLightMaterial
newVertexState.iLightConfig = iLightConfig
ExportShape.VertexStates.append( newVertexState )
# every vertex_state needs a matching vertex_set
for lodControl in ExportShape.LodControls:
for distanceLevel in lodControl.DistanceLevels:
for subobject in distanceLevel.SubObjects:
subobject.VertexSets.append( VertexSet() ) #Note: unused vertexSets are purged during write
return i
#####################################
def MatchList( lista, listb ):
if len(lista) != len(listb):
return False
for i in range( 0, len(lista) ):
if lista[i] != listb[i]:
return False
return True
#####################################
def ColorWord( floats ):
value = 0;
for f in floats:
value = value * 256
value = value + round( f * 255 )
return value
#####################################
def IsLinkedToBaseColor( imageNode ):
for eachLink in imageNode.outputs['Color'].links:
if eachLink.to_socket.name == 'Base Color' or \
eachLink.to_socket.name == 'Color':
return True
return False
#####################################
# return an msts format image name, eg unionstop.ace
def BaseColorImageFrom( material ):
if material == None:
return None
# if we specified a filepath in MSTS Material panel, use it
if material.msts.BaseColorFilepath != '':
return GetFileNameNoExtension( material.msts.BaseColorFilepath )
# Otherwise, look for an image in the shader node tree linked to a Color or Base Color input
if material.node_tree != None:
for eachNode in material.node_tree.nodes:
if eachNode.bl_idname == 'ShaderNodeTexImage':
if eachNode.image.source == 'FILE':
if IsLinkedToBaseColor( eachNode ):
return GetFileNameNoExtension( eachNode.image.filepath )
return None
#####################################
def iPrimStateAdd( iVertexState, zBias, iShader, alphaTestMode, iLightConfig, iTextures ):
global ExportShape
# see if this one's already set up
for i in range( 0, len( ExportShape.PrimStates ) ):
eachPrimState = ExportShape.PrimStates[i]
if eachPrimState.iVertexState == iVertexState \
and eachPrimState.zBias == zBias \
and eachPrimState.iShader == iShader \
and eachPrimState.AlphaTestMode == alphaTestMode \
and eachPrimState.iLightConfig == iLightConfig \
and MatchList( eachPrimState.iTextures, iTextures ):
return i
# we didn't find it so add it
i = len( ExportShape.PrimStates )
newPrimState = PrimState()
iHierarchy = ExportShape.VertexStates[iVertexState].iMatrix
newPrimState.Label = ExportShape.Matrices[iHierarchy].Label
if len( iTextures) > 0:
texture = ExportShape.Textures[iTextures[0]]
imagename = ExportShape.Images[texture.iImage]
newPrimState.Label = newPrimState.Label + '_' + os.path.splitext( imagename)[0]
for iTexture in iTextures:
newPrimState.iTextures.append(iTexture)
newPrimState.zBias = zBias
newPrimState.iVertexState = iVertexState
newPrimState.iShader = iShader
newPrimState.AlphaTestMode = alphaTestMode
newPrimState.iLightConfig = iLightConfig
ExportShape.PrimStates.append( newPrimState )
return i
#####################################
def iPrimitiveAppend( subObject, iPrimState ):
i = len( subObject.Primitives )
newPrimitive = Primitive()
newPrimitive.iPrimState = iPrimState
subObject.Primitives.append( newPrimitive )
return i
#####################################
def iPrimitiveAdd( subObject, iPrimState ):
i = len( subObject.Primitives )
while i > 0: # use the last correct entry - earlier ones could be full
i -= 1
primitive = subObject.Primitives[i]
if primitive.iPrimState == iPrimState:
return i
#we didn't find it, so add a new one
i = iPrimitiveAppend( subObject, iPrimState )
return i
#####################################
class UniqueArray:
def __init__(self, data, hash, tolerance ):
self.data = data
self.keys = {}
self.hash = hash
self.tolerance = tolerance
def __getitem__(self, i):
return self.data[i]
def Match( self, v1, v2 ):
for i in range( 0, len( v1 ) ):
if abs( v1[i] - v2[i] ) > self.tolerance:
return False
return True
def Key( self, value ):
key = 0.0
for v in value:
key += v
return round(key,self.hash)
def IndexOf( self, value ):
key = self.Key( value )
index = self.keys.get(key,-1)
while index != -1:
storedValue = self.data[index]
if self.Match( value, storedValue):
return index
key += .9 # in case of a hash collision, we advance the key this amount
index = self.keys.get(key,-1)
# Performance improvement, live with some duplicate values to speed up export
global FastExport
if FastExport:
if len( self.keys ) > 4000:
self.keys.clear()
# we didn't find it so add it
index = len( self.data )
self.data.append( value )
self.keys[ key ] = index
return index
#####################################
def iVertexAdd( iPoint, iNormal, iUVs, vertexSet, color1, color2 ):
# search index to see if a matching vertex exists
if iPoint in vertexSet.index:
for iVertex in vertexSet.index[iPoint]:
vertex = vertexSet.Vertices[iVertex]
if vertex.iPoint == iPoint and vertex.iNormal == iNormal and MatchList(vertex.iUVs,iUVs) and vertex.Color1 == color1 and vertex.Color2 == color2 :
return iVertex
#we didnt' find it so add a new one
vertex = Vertex()
vertex.iPoint = iPoint
vertex.iNormal = iNormal
vertex.Color1 = color1
vertex.Color2 = color2
for iUV in iUVs:
vertex.iUVs.append( iUV )
iVertex = len( vertexSet.Vertices )
vertexSet.Vertices.append( vertex )
#index on iPoint for speedup
if not iPoint in vertexSet.index:
vertexSet.index[iPoint] = []
vertexSet.index[iPoint].append( iVertex )
return iVertex
#####################################
def iUVPointAdd( uvPoint ):
global UniqueUVPoints
MSTSuvPoint = (uvPoint[0],1-uvPoint[1])
return UniqueUVPoints.IndexOf( MSTSuvPoint )
#####################################
def iNormalAdd( vector ):
global UniqueNormals
MSTSvector = (vector[0],vector[2],vector[1] )
return UniqueNormals.IndexOf( MSTSvector )
#####################################
# When a subObject is full, create a new empty
def SplitSubObject( subObject):
newSubObject = SubObject( subObject.DistanceLevel )
# DEBUG print( 'split subObject ',subObject.sequence,' into ',newSubObject.sequence )
newSubObject.Flags = subObject.Flags
newSubObject.Priority = subObject.Priority
newSubObject.iHierarchy = subObject.iHierarchy
for eachVertexSet in subObject.VertexSets:
newVertexSet = VertexSet()
newSubObject.VertexSets.append( newVertexSet ) #unused vertex sets are purged during write
subObject.DistanceLevel.SubObjects.append( newSubObject )
return newSubObject
########################################
# find the last subobject that uses the specified flags
# or return None of none found
def FindSubObject( distanceLevel, flags, priority, iHierarchy):
# starting at the end, look for one with the needed flags
iLast = len( distanceLevel.SubObjects ) - 1
while iLast >= 0:
subObject = distanceLevel.SubObjects[iLast]
if HierarchyOptimization:
if subObject.Flags == flags and subObject.Priority == priority and subObject.iHierarchy == iHierarchy:
return subObject
else:
if subObject.Flags == flags and subObject.Priority == priority:
return subObject
iLast -= 1
return None
#####################################
def ChildOf( ancestor, object ):
if object.parent == None:
return False
if object.parent == ancestor:
return True
if ChildOf( ancestor, object.parent ):
return True
return False
#####################################
def ConstructMatrix( ancestor, object ):
# construct a cumulative transfer matrix from object to ancestor
if object == ancestor:
return mathutils.Matrix.Translation((0,0,0))
if object.parent == None:
return object.matrix_local
if object.parent == ancestor:
return object.matrix_local
return ConstructMatrix( ancestor, object.parent ) @ object.matrix_local
#####################################
def IsMSTSDefinedName( name ):
#if its one of the automatically animated parts
# TODO Include any allcaps part