-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisonary_export.py
1430 lines (1030 loc) · 42.4 KB
/
visonary_export.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
#!BPY
"""
Name: 'Visonary (.ve)...'
Blender: 232
Group: 'Export'
Tooltip: 'Export selected meshes to Visionary File Format (.ve)'
"""
__author__ = "Robert Wlaschin"
__url__ = ("N/A")
__version__ = "Visonary 1.0.0.1"
__bpydoc__ = """\
This script exports meshes to Visionary file format.
Visionary is a full-featured private game engine. VE file format
composed of objects. Each object has a specifice data format.
Please see the Visionary Documentation for the description for
each of these objects. Each object is connected together by a
linked list. This data comes from the outliner in blender
Usage:<br>
Select meshes to be exported and run this script from "File->Export" menu.
Supported:<br>
Lights, Camera, Multiple models, Meshes, Materials, Specular Highlights,
and Vertex Colors
Missing:<br>
Animations, tracking of attached Scripts, Creation of Non-rendering
game objects (triggers), textures, and shared object sets
Enhancements:<br>
Implement an index'd array mech
Known issues:<br>
None, yet ;)
Notes:<br>
This file will change continously until Visionary is completed
"""
VERSION = 1.6
# $Id: visionary_export.py,v 1.6 2005/06/13 02:30:00 rwlaschin Exp $
#
# +---------------------------------------------------------+
# | Copyright (c) 2005 Robert Wlaschin |
# | http://www.geocities.com/raw77_m |
# | [email protected] |
# | June 23, 2005 |
# | Released under the Blender Artistic Licence (BAL) |
# | Import Export Suite v0.5 |
# +---------------------------------------------------------+
# | Write Visionary Object File Format (*.ve) |
# +---------------------------------------------------------+
import Blender, meshtools
from Blender import Types, Object, NMesh, Camera, Lamp, Scene, Mathutils
from Blender.Scene import Render
from Blender.Scene.Render import *
import warnings
import struct, cStringIO, time, operator, copy, math
import string, chunk, os, types
# Filter warnings for crc data structure
warnings.filterwarnings( "ignore", "hex/oct constants > sys.maxint will return positive values in Python 2.4 and up" )
# ===============================================
# === Visionary_export this is the interface
# === funtion, it is processes all of the selected
# === objects and dumps them into the VE format
# ===============================================
def visionary_export(filename = "start.ve"):
global hFile
print "-------------------------------------------------------"
print " start\n"
if filename.find('.ve', -3) <= 0: filename += '.ve'
start = time.clock()
# Try getting the names of all of the selected items in the scene
objects = Blender.Object.GetSelected()
if not objects:
meshtools.print_boxed("No objects are selected.")
return
objects.sort(lambda a,b: cmp(a.name,b.name))
# Call iterator and Parse Function
it = iter(objects)
parentInstance = ParseObjects( it.next(), it )
header = []
def addtoheader( name, dmp, size ):
if size > 0: header.append( (name,GenerateHashValue(name),dmp,size) )
# Build the shared information
(dmp, dsize) = PackSharedObjects()
addtoheader("shared", dmp, dsize)
# Build the object information
(dmp, dsize) = PackObject( parentInstance, 0 )
addtoheader("render", dmp, dsize)
if len(header) > 0:
# Build the header and offsets
(dump, size) = BuildFileHeader( header )
if len(dump) > 0:
hFile = open( filename, 'wb' )
if hFile is not None:
# Write to file
hFile.write( dump )
# Do Clean up
hFile.close()
# End If
# End If
end = time.clock()
# Print status message
seconds = " in %.2f %s" % (end-start, "seconds")
message = "Successfully exported " + os.path.basename(filename) + seconds
meshtools.print_boxed( message )
# ===============================================
# === ParseObject uses the iterator to walk
# === through the object list
# ===============================================
def ParseObjects( object, it ):
# print repr(it), object.name
if object is None:
return
# Get the object data
data = object.getData()
instancetype = 0x0b
# Pick the correct routine to handle the object type
if type(data) == Types.LampType:
GenerateType = GenerateLight
elif type(data) == Types.CameraType:
instancetype = 0x1a # special camera instance
GenerateType = GenerateCamera
elif type(data) == Types.NMeshType:
GenerateType = GenerateModel
else:
print "This object <%s> is unsupported! Oops!" % (type(data))
GenerateType = None
# End If
if GenerateType is not None:
# Create new instance header
instanceObject = InitializeHeader( instancetype, object.name )
# print "Creating Instance Object", object.name, "0x%02x 0x%08x" % (instanceObject.data.id.type, instanceObject.data.id.number)
instanceObject.sibling = GeneratePointer( None )
instanceObject.child = GeneratePointer( None )
instanceObject.pMatricies = []
instanceObject.nMatricies = 0
instanceObject.flags = -1
# Retrieve the matrix based on type
if type(data) == Types.CameraType:
matrix = object.getInverseMatrix()
else:
matrix = object.getMatrix()
# Skip matrix calcs for light (uses alternate method)
if type(data) != Types.LampType:
# At this level only a single matrix is defined
instanceObject.pMatricies.append( GeneratePointer( GenerateMatrix( object, data, matrix) ) )
instanceObject.nMatricies = 1
# End If
def NumUsers( o ):
try: return o.users
except: return 0
# Is shared data?
# print data.name, NumUsers(data)
# WARNING: this keeps objects that are not shared off the shared list!
# if NumUsers(data) > 1:
# Add to the list of shared objects!
# SharedObjects( data )
# create the object data
instanceObject.object = GeneratePointer( GenerateType( object, data, matrix ) )
try:
# recurse and attach
instanceObject.sibling = GeneratePointer( ParseObjects( it.next(), it ) )
except StopIteration:
instanceObject.sibling = None
return instanceObject
# print "Skipped", object.name, "not supported"
# skip object for now if not supported!
try:
return ParseObjects( it.next(), it )
except StopIteration:
return None
# ===============================================
# === Creates Binary Data for Header object
# ===============================================
def PackObject( object, size = 0 ):
if object is None:
return ("", 0)
PackCbf = { 0x14: PackMatrix,
0x16: PackVertexArray,
0x11: PackMaterial,
0x12: PackTexture,
0x15: PackVertexGroup,
0x0f: PackLight,
0x0e: PackCamera,
0x10: PackModel,
0x0b: PackInstance,
0x1a: PackInstance }
# print type(object), dir(object)
# Is the object a pointer type? If so no packing needs to be done!
# Call Object specific Pack function
if object.data.id.type in PackCbf:
# print "Packing Object", object.name, "0x%02x (%d) 0x%x (%d)" % (object.data.id.type, object.id.type, object.data.id.number, object.id.number)
# print PackCbf[object.data.id.type], type( PackCbf[object.data.id.type] )
(dump, size) = PackCbf[object.data.id.type]( object, size )
else:
print "Skipped Object", object.name, "0x%02x (%d) 0x%x (%d)" % (object.data.id.type, object.id.type, object.data.id.number, object.id.number)
dump = ""
# End If
result = PackHeader( object, size )
# Call Header specific Pack function (add header to front!)
return ( result[0] + dump, result[1] )
# End PackObject
# ===============================================
# === Creates binary data for Instance object
# ===============================================
def PackInstance( object, size = 0):
fmtptr = "Pl"
dump = ""
objectsize = 0
# general format
fmt = fmtptr * 2 + "Pii" + fmtptr
instancesize = struct.calcsize(fmt)
result = PackHeader(object, instancesize)
instancesize = result[1] # header does the addition for me ...
# calculate size for matrix ptrs
size += object.nMatricies * struct.calcsize(fmtptr)
matrixdump = ""
matrixsize = [0]
result = (0,0) # reset back to zero
# Get pack data for matricies
for ptr in object.pMatricies:
dump += struct.pack( fmtptr, instancesize+size+matrixsize[0], VerifyPointer(ptr) ) # vit_offset and value
# Get pack data for matrix
result = PackPointer( ptr, result[1] )
matrixdump += result[0]
# matrix size is for the ptr array
matrixsize = [result[1]] + matrixsize
# End For ptr
# matrix data
size += matrixsize[0]
dump += matrixdump
# Get Pack data for object
result = PackPointer( object.object, 0 )
dump += result[0]
size += result[1]
objectsize = result[1]
# print "Object Size, %x" % size, result[1]
# Get pack data for children
result = PackPointer( object.child, 0 )
dump += result[0]
size += result[1]
childsize = result[1]
# print "Child Size, %x" % size, result[1] # should be zero!
if matrixdump is not "":
offsetmatrix = instancesize
else:
offsetmatrix = 0
if object.object is not None and object.object.type != 0:
offsetobject = instancesize + object.nMatricies * struct.calcsize(fmtptr) + \
matrixsize[0]
# print "Object offset calc", offsetobject
else:
offsetobject = 0
if object.child is not None and object.child.type != 0:
# print "Child offset calc"
offsetchild = instancesize + object.nMatricies * struct.calcsize(fmtptr) + \
matrixsize[0] + objectsize
else:
offsetchild = 0
if object.sibling is not None and object.sibling.type != 0:
# print "Sibling offset calc"
offsetsibling = instancesize + object.nMatricies * struct.calcsize(fmtptr) + \
matrixsize[0] + objectsize + childsize
else:
offsetsibling = 0
# inline lambda function
# (lambda x: x*2)(3)
result = PackPointer( object.sibling, 0 )
print object.name, "<%x> Object offset 0x%x" % ( object.id.number, objectsize ), "child offset 0x%x" % offsetchild , "sibling offset 0x%x" % offsetsibling
return ( struct.pack( fmt, offsetchild, VerifyPointer(object.child),
offsetsibling, VerifyPointer(object.sibling),
offsetmatrix, object.nMatricies,
object.flags,
offsetobject, VerifyPointer(object.object) ) + \
dump + result[0], result[1] + size + struct.calcsize(fmt) ) # change 1
# instancesize + object.nMatricies * struct.calcsize(fmtptr) + matrixsize[0] + objectsize - 20 )
# End PackInstance
# ===============================================
# === Creates a hash id from string
# ===============================================
def GenerateHashValue( string ):
crctt = ~0
for char in string:
c = int(struct.unpack("b", char )[0]) # convert ascii char to int (unpack returns tuple, even on single items)
crctt = ( crctab[ (crctt ^ c) & 0xff ] ^ ( (crctt>>8) & 0x00FFFFFFL ) )
return crctt
# End GenerateHashValue
# ===============================================
# === Creates Generic header data, does not modify
# === size attribute
# ===============================================
def InitializeHeader( type, name ):
header = CCommonObjectHeader()
header.data = CCommonObjectData(type, GenerateHashValue(name)) # duplicate data to maintain integrity after pointer resolution
header.id = CCommonObjectIdentifier(type, header.data.id.number)
header.name = name # debug only! Please remove before finish!
# print "Creating Header %s 0x%02x 0x%8x" % (name, header.data.id.type, header.data.id.number)
return header
# End InitializeHeader
# ===============================================
# === Creates Binary Data for Header object
# ===============================================
def PackHeader( object, size = 0 ):
fmt = "Ilili"
size += struct.calcsize(fmt)
dump = struct.pack( fmt,
size,
object.data.id.number,
object.data.id.type,
object.id.number,
object.id.type )
return (dump, size)
# End PackHeader
# ===============================================
# === Creates Generic Pointer Object
# ===============================================
def GeneratePointer( header ):
# print "Type:", type(header)
# print "Is Instance:", isinstance( header, CCommonObjectPointer )
if not isinstance( header, CCommonObjectPointer ):
pointerObj = CCommonObjectPointer()
if header is not None:
pointerObj.type = header.data.id.type
pointerObj.ptr = header
return pointerObj
return header
# ===============================================
# === This function just verifies pointer and
# passes correct object through
# ===============================================
def PackPointer( object, size = 0 ):
if object is None:
return ("", 0)
# print object, type(object), dir(object)
# print "name", repr(object.ptr)
# print object.ptr, type(object.ptr), dir(object.ptr)
if type(object.ptr) == types.LongType:
return ("",0)
try:
return PackObject( object.ptr, size )
except AttributeError:
return PackObject(object, size)
# End PackPointer
# ===============================================
# === This function just verifies pointer and
# passes correct object through
# ===============================================
def VerifyPointer( object ):
if object is None:
return 0x00
# print " Verify:", object.type, object.ptr,isinstance( object.ptr, CCommonObjectHeader )
if object.ptr == None:
return 0x00
if isinstance( object.ptr, CCommonObjectHeader ):
return 0x08
return 0x07
# End VerifyPointer
# ===============================================
# === This function just verifies pointer and
# passes correct value through
# ===============================================
def VerifyOffset( object, offset ):
if object == None:
return 0
print " Verify:", object.type, object.ptr,isinstance( object.ptr, CCommonObjectHeader )
if isinstance( object.ptr, CCommonObjectHeader ):
return offset
if object.ptr == None:
return 0
return object.ptr
# End VerifyOffset
# ===============================================
# === Creates a Matrix object
# : Notes :
# Function only creates GL_MODELVIEW
# until discovery of matrix type variable
# ===============================================
def GenerateMatrix( object, data, matrix ):
# print "Creating Matrix", object.name
# Initialize a new matrix object
matrixObj = InitializeHeader( 0x14, data.name + ".Matrix" )
# Matrix
# header
# matrixMode - modelview ... etc
# matrix[16] - c style
matrixObj.matrixMode = 0x1700 # GL_MODELVIEW
matrixObj.matrix = []
for r in matrix:
for c in r:
matrixObj.matrix.append( c )
# End For i
return matrixObj
# End GenerateMatrix
# ===============================================
# === Creates Binary data for Matrix object
# ===============================================
def PackMatrix( object, size = 0 ):
dump = struct.pack( "i", object.matrixMode )
size += struct.calcsize( "i" )
for num in object.matrix:
dump += struct.pack( "f", num )
size += struct.calcsize( "f" )
# End For num
return (dump, size)
# End PackMatrix
# ===============================================
# === Creates a VertexArray object
# ===============================================
def GenerateVertexArray( object, data, type, size, verticies, state = ["", 0] ):
# make sure names don't collide
if state[0] != data.name:
state[0] = data.name
state[1] = 0
else:
state[1]+=1
vertexObj = InitializeHeader( 0x16, object.name + "." + data.name + ".VertexArray." + str(state[1]) )
vertexObj.vertexType = type
vertexObj.vertexsize = size
vertexObj.nVerticies = 0
vertexObj.verticies = []
# print verticies
for c in verticies:
# print c
for r in c:
# print r
vertexObj.verticies.append( r )
# End For r
# End For c
vertexObj.nVerticies = len( verticies )
# print "nVerticies:", vertexObj.nVerticies
return vertexObj
# End GenerateVertexArray
# ===============================================
# = Creates binary data for VertexArray
# ===============================================
def PackVertexArray( object, size = 0 ):
fmt = "iii"
dump = struct.pack( fmt, object.vertexType,object.vertexsize, object.nVerticies )
size += struct.calcsize( fmt )
for num in object.verticies:
dump += struct.pack( "f", num )
size += struct.calcsize( "f" )
# End For num
return (dump, size)
# End PackVertexArray
# This object is made of tuples
# (offset, object data)
# initially offset is 0 until binary is built
gObjectDict = {}
# ===============================================
# === Finds an object in the Global Look Up Table
# ===============================================
def GetObjectData( name, objDict = gObjectDict ):
# print "Shared Object:", name, type(name), (type(name) == types.StringType)
if name != None:
if type(name) == types.StringType:
name = GenerateHashValue(name)
string = "%xh" % name
if string in objDict:
return objDict[string]
# End if
# End if
return None
# End LookUpName
def SetObjectData( name, object, objDict = gObjectDict ):
if name != None:
if type(name) == types.StringType:
name = GenerateHashValue(name)
string = "%xh" % name
if string not in objDict:
tup = (0,object)
objDict[string] = tup
return tup
# End if
# End if
return None
# End SetObjectData
# ===============================================
# === Creates a Material object
# ===============================================
def FindCreateTexture( o, data, material, texture):
name = None
shobject = None
# print dir(texture)
# print texture.tex, "\n",dir(texture.tex)
# for o in dir(texture.tex):
# print o,
# try:
# try: print eval("texture.tex.%s()" % o)
# except: print eval("texture.tex.%s" % o)
# except: print
image = texture.tex.getImage()
# print image, "\n",dir(image)
if image == None:
# print "Object", object, "Does not use a supported texture type, texture must be loaded from a file"
return None
# End if
# get the file name ... see if it exists in the 'table'
name = image.name
shobject = GetObjectData( name )
# print "Shared Object:", shobject
# print "Name:", name
if shobject != None:
# print "object data found!", shobject, type(shobject)
shobject = shobject[1]
else:
# If no data, create texture data and attach to the global list
oDepthToSize = {32:4,24:3}
oDepthToGlDepth = {32:0x1908,24:0x1907}
shobject = InitializeHeader( 0x12, name )
# Build texture object!
# get width, height, wrap (x,y), alpha setting
# walk bits and build array!
# print object
shobject.iTexture = 0 # unassigned for internal use only
shobject.width, shobject.height = image.getSize()
shobject.xrepeat = 0x2900 # (gl_clamp) # image.xrep
shobject.yrepeat = 0x2900 # (gl_clamp)# image.yrep
depth = image.getDepth()
shobject.size = oDepthToSize[depth]
shobject.depth = oDepthToGlDepth[depth]
xrange = range(shobject.width)
yrange = range(shobject.height)
yrange.reverse()
shobject.bytes = [] # this is the texture data
print yrange
for x in xrange:
shobject.bytes += [ map(lambda a: a*0xFF, image.getPixelF(x,y)) for y in yrange ]
# End For
# print object, object.width, object.height, object.xrepeat, object.yrepeat, object.size, object.depth
# add the new object to the 'list'
SetObjectData(name, shobject)
# End if
pointerObj = CCommonObjectPointer()
pointerObj.type = shobject.id.type
pointerObj.ptr = shobject.id.number
# print "Shared Object:", shobject.name, shobject.id.number
# print pointerObj, pointerObj.type, pointerObj.ptr
return pointerObj
# End FindCreateTexture
def PackTexture( object, size = 0 ):
fmt = "iIiiiiii"
# Get size of header
headersize = PackHeader( object, 0 )[1]
size += headersize + struct.calcsize( fmt )
dump = struct.pack( fmt, object.iTexture,
object.width,
object.height,
object.xrepeat,
object.yrepeat,
object.size,
object.depth,
size)
# walk bytes and attach to end of dump
# keep track of size
texfmt = "B" * object.size
size += struct.calcsize(texfmt) * len(object.bytes)
# object.bytes.reverse()
# ... optmization ...
if object.size == 3:
for b in object.bytes: dump += struct.pack(texfmt,b[0],b[1],b[2])
elif object.size == 4:
for b in object.bytes: dump += struct.pack(texfmt,b[0],b[1],b[2],b[3])
else:
print "While creating texture, unknown depth count!"
return dump, size - headersize
# End PackTexture
# ===============================================
# === Creates a Material object
# ===============================================
def GenerateMaterial( object, data, material ):
textures = material.getTextures()
materialObj = InitializeHeader( 0x11, data.name )
materialObj.face = 0x0404 # GL_Front
materialObj.mode = 0x1602 # Gl_Ambient_and_Diffuse
materialObj.vertexArray = [0,0,0,0,0]
# print "Texture: ", len(textures), textures
materialObj.textureArray = []
# Create texture array ( blender has max of 8 but I don't need to allocate unused)
for t in textures:
if t: materialObj.textureArray += [ GeneratePointer( FindCreateTexture( object, data, material, t) ) ]
# End For
materialObj.nTextures = len( materialObj.textureArray )
materialObj.nTextureObjects = len( materialObj.textureArray )
# print "Texture:",materialObj.nTextureObjects,materialObj.textureArray
# generate array of pointers
# print "Rgb", material.rgbCol
# print "Amb", material.amb
# ambient
materialObj.vertexArray[0] = GeneratePointer( GenerateVertexArray( object, data, 0x1200, 4, [ [material.rgbCol[i]*material.amb for i in range(0,3)] + [material.alpha]] ))
# diffuse
materialObj.vertexArray[1] = GeneratePointer( GenerateVertexArray( object, data, 0x1201, 4, [ material.rgbCol + [material.alpha]] ))
# specular
materialObj.vertexArray[2] = GeneratePointer( GenerateVertexArray( object, data, 0x1202, 4, [ material.specCol + [material.alpha]] ))
# emissive
materialObj.vertexArray[3] = GeneratePointer( GenerateVertexArray( object, data, 0x1600, 4, [ [material.rgbCol[i] * material.emit for i in range(0,3)] + [material.alpha]] ))
# shiny (hard)
materialObj.vertexArray[4] = GeneratePointer( GenerateVertexArray( object, data, 0x1601, 1, [[material.hard/127.0]] )) # 127 becuase OpenGl rates shiny from 0->2.0, hard is 0->255
# GenerateVertexArray( object, data, 0x1601, 4, [[material.hard/127.0]] )) # 127 becuase OpenGl rates shiny from 0->2.0, hard is 0->255
return materialObj
# End GenerateMaterial
# ===============================================
# === Creates binary data for Material
# ===============================================
def PackMaterial( object, size = 0 ):
# print "initial object size", size
fmt = "ii", "iP"
fmtptr = "Pi"
headersize = PackHeader( object, 0 )[1]
(dump, objectsize) = ( struct.pack( fmt[0], object.face, object.mode ),
struct.calcsize( fmt[0] ) )
# calculate the total object size for offsets
objectsize += headersize + \
struct.calcsize( fmtptr ) * len( object.vertexArray ) + \
struct.calcsize( fmt[1] )
# print "Object Size", objectsize
# print "Offset Size %x" % (objectsize + size)
offset = [size + objectsize]
vertexarraydump = ""
for ptr in object.vertexArray:
dump += struct.pack( fmtptr, offset[0], VerifyPointer( ptr ) )
# Create data for
result = PackPointer( ptr, 0 )
# capture buffer data (to combine with dump)
vertexarraydump += result[0]
# Prep offset for next iteration
offset = [offset[0] + result[1]] + offset
# End For
texturearraydump = ""
dump += struct.pack( fmt[1], object.nTextures, offset[0] ) + vertexarraydump
if object.nTextures > 0:
# recalculate the next offset for the texture array
ptrsize = struct.calcsize( fmtptr * object.nTextures )
offset = [offset[0] + ptrsize] + offset
# create pointer array for textures
for ptr in object.textureArray:
# build pointer array
dump += struct.pack( fmtptr, VerifyOffset(ptr,offset[0]), VerifyPointer(ptr) )
result = PackPointer( ptr, 0 )
# capture buffer data (to combine with dump)
texturearraydump += result[0]
# Prep offset for next iteration
offset = [offset[0] + result[1]] + offset
# End For
else:
dump += struct.pack( fmt[1], object.nTextures, 0 )
# End If
# take off the header or it will be calculated twice
objectsize = (offset[0] - headersize)
# print "Material <%x, %d>" % (objectsize, objectsize)
# Patch the rest of the data
dump += texturearraydump
return ( dump, objectsize )
# End PackMaterial
# ===============================================
# === Creates a VertexGroup object
# ===============================================
def GenerateVertexGroup( object, data, faces, state = ["", 0] ):
# make sure names don't collide
if state[0] != object.name:
state[0] = object.name
state[1] = 0
else:
state[1]+=1
# print "GenerateVertexGroup", type(data), "::", type(face)
# VertexGroup
# header
# material - single instance
# primType
# nArrays
# vertexArray
vertexGroupObj = InitializeHeader( 0x15, "%s.VertexGroup.%i" % (data.name,state[1]) )
if data.materials == []:
print "Error: object <%s> does not have a material!" % object.name
# create material
vertexGroupObj.material = GeneratePointer( GenerateMaterial( object, data, data.materials[faces[0].materialIndex] ) )
# use uv coord if texture
# print face.uv # not used yet
#define GL_TRIANGLES 0x0004
#define GL_TRIANGLE_STRIP 0x0005
#define GL_TRIANGLE_FAN 0x0006
#define GL_QUADS 0x0007
#define GL_POLYGONS 0x0009
vertexGroupObj.nArrays = 0
vertexGroupObj.vertexArray = []
# ------------------------
# Please note Order Matters for the following statements!
# ------------------------
( lvertex,lnormal, luvs, luv, lcolor) = ( len( faces[0].v[0].co ), len( faces[0].no ), len( faces[0].uv ),0, 0 ) # number of points
( vertex, normal, color, uv ) = ( [], [], [], [] )
length = len(faces[0].v) # number of verticies
walkary = range(0,length)
# New partial hardcode
if length == 3: vertexGroupObj.primType = 0x04
elif length == 4: vertexGroupObj.primType = 0x07
else: vertexGroupObj.primType = 0x09
for face in faces:
if len(face.v[0].co) != lvertex:
print object.name, object.data, "Object was %i but now has alternate vertex count of %i, please fix!" % ( lvertex, len(face.v[0].co))
continue
# create vertex, normal, color, and uv arrays from the face data
if lvertex > 0: vertex += [ v.co for v in face.v ]
if luvs > 0: uv += [ v for v in face.uv ]
if lnormal > 0: normal += [ face.no for i in walkary ]
if face.col == []: color += [ vertexGroupObj.material.ptr.vertexArray[1].ptr.verticies for i in walkary ]
else: color += [ [col.r/255.0, col.g/255.0, col.b/255.0, col.a/255.0 ] for col in face.col ]
lcolor = len(color[0]) # only work first time
if uv != []: luv = len(uv[0])
# print "Vertex", lvertex, len(vertex), walkary
# print "Normal", lnormal, len(normal)
# print "Color", lcolor, len(color[0]), color[0][:4]
# print "UV", luv, len(uv)# , uv
# for coord in uv: print "\t(%0.2f,%0.2f) " % (coord[0:])
# print "Vertex %i" % len(vertex[i])," ","Normal %i" % len(normal[i])," ","Color %i" % len(color[i])
# for i in range(len(vertex)):
# for j in range(len(color[i])):
# try: print "%+0.3f\t" % vertex[i][j],
# except: print " \t",
# try: print "%+0.3f\t" % normal[i][j],
# except: print " \t",
# print "%+0.3f\t" % color[i][j]
# print
if vertex != []: vertexGroupObj.vertexArray.append( GeneratePointer( GenerateVertexArray( object, data, 0x0009, lvertex, vertex ) ) )
if normal != []: vertexGroupObj.vertexArray.append( GeneratePointer( GenerateVertexArray( object, data, 0x0009, lnormal, normal ) ) )
if color != []: vertexGroupObj.vertexArray.append( GeneratePointer( GenerateVertexArray( object, data, 0x0009, lcolor, color ) ) )
if uv != []: vertexGroupObj.vertexArray.append( GeneratePointer( GenerateVertexArray( object, data, 0x0009, luv, uv ) ) )
# print "vertlist: %d, normals: %d, color: %d" % (len(verts),len(no),len(col))
vertexGroupObj.nArrays = len( vertexGroupObj.vertexArray )
return vertexGroupObj
# End GenerateVertexGroup
# ===============================================
# === Creates binary data for vertex group
# ===============================================
def PackVertexGroup( object, size = 0 ):
fmt = "ii"
fmtptr = "Pi"