GitLab Commit is coming up on August 3-4. Learn how to innovate together using GitLab, the DevOps platform. Register for free: gitlabcommitvirtual2021.com

eExport.py 17.8 KB
Newer Older
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
# ##### BEGIN GPL LICENSE BLOCK #####
#
#  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 2
#  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.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

#############################################################
#	(C) Krzysztof Solek, Mielec 2012
#############################################################

import bpy , os

###########################################################
#
#       Global variables
#
###########################################################
obj_names = []  # names of meshes in "C-suitable" format
vtx = []  # list of dictionaries for each mesh
faces = []  # list of lists
vl = []  # list of vertices for each mesh
nl = []  # list of normals for each mesh
uvl = []  # list of UV coords for each mesh
diffuse = []
specular = []
obj_mtx = []  # list of local transformations for each object
obj_cnt = 0  # object count
max_vcnt = 0  # qty of vertices for biggest mesh
start = ""
next = ""
Jan Scheffczyk's avatar
Jan Scheffczyk committed
43
transform = []
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


###########################################################
#
#   Round values of the 3D vector
#
###########################################################

def r3d(v):
    return round(v[0], 6), round(v[1], 6), round(v[2], 6)


###########################################################
#
#   Round values of the 2D vector
#
###########################################################

def r2d(v):
    return round(v[0], 6), round(v[1], 6)


###########################################################
#
#   Convert object name to be suitable for C definition
#
###########################################################

def clearName(name):
    tmp = name.upper()
    ret = ""
    for i in tmp:
        if (i in " ./\-+#$%^!@"):
            ret = ret + "_"
        else:
            ret = ret + i
    return ret


###########################################################
#
#   Build data for each object (MESH)
#
###########################################################

89
90
91
92
93
94
95
96
97

def getmount(path):
    path = os.path.realpath(os.path.abspath(path))
    while path != os.path.sep:
        if os.path.ismount(path):
            return path
        path = os.path.abspath(os.path.join(path, os.pardir))
    return path

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
def buildData(obj, msh, name):
    global obj_cnt
    global obj_names  # names of meshes in "C-suitable" format
    global vtx  # list of dictionaries for each mesh
    global faces  # list of lists
    global vl  # list of vertices for each mesh
    global nl  # list of normals for each mesh
    global uvl  # list of UV coords for each mesh
    global obj_mtx  # list of local transformations for each object
    global diffuse
    global specular


    lvdic = {}  # local dictionary
    lfl = []  # lcoal faces index list
    lvl = []  # local vertex list
    lnl = []  # local normal list
    luvl = []  # local uv list

    lvcnt = 0  # local vertices count
    isSmooth = False
    hasUV = True  # true by default, it will be verified below

    print("Building for: %s\n" % obj.name)

    if (len(msh.tessface_uv_textures) > 0):
        if (msh.tessface_uv_textures.active is None):
            hasUV = False
    else:
        hasUV = False

    if (hasUV):
        activeUV = msh.tessface_uv_textures.active.data

    img = " "

134
135
136
137
138
139
    if obj:
        for mat_slot in obj.material_slots:
            for mtex_slot in mat_slot.material.texture_slots:
                if mtex_slot:
                    if hasattr(mtex_slot.texture, 'image'):
                        print("\t\t%s" % mtex_slot.texture.image.filepath)
140

141
                        img = mtex_slot.texture.image.filepath;
142
143
144
                        img =bpy.path.relpath(img);
                        # img = bpy.path.abspath(img, "//")

145
146
147
                        img = img.replace('\\','/')

    diffuse.append(img);
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

    obj_names.append(name)
    obj_cnt += 1

    for i, f in enumerate(msh.tessfaces):
        isSmooth = f.use_smooth
        tmpfaces = []
        for j, v in enumerate(f.vertices):
            vec = msh.vertices[v].co
            vec = r3d(vec)

            if (isSmooth):  # use vertex normal
                nor = msh.vertices[v].normal
            else:  # use face normal
                nor = f.normal

            nor = r3d(nor)

            if (hasUV):
                co = activeUV[i].uv[j]
                co = r2d(co)
            else:
                co = (0.0, 0.0)

            key = vec, nor, co
            vinx = lvdic.get(key)

            if (vinx is None):  # vertex not found
                lvdic[key] = lvcnt
                lvl.append(vec)
                lnl.append(nor)
                luvl.append(co)
                tmpfaces.append(lvcnt)
                lvcnt += 1
            else:
                inx = lvdic[key]
                tmpfaces.append(inx)

        if (len(tmpfaces) == 3):
            lfl.append(tmpfaces)
        else:
            lfl.append([tmpfaces[0], tmpfaces[1], tmpfaces[2]])
            lfl.append([tmpfaces[0], tmpfaces[2], tmpfaces[3]])

    # update global lists and dictionaries
    vtx.append(lvdic)
    faces.append(lfl)
    vl.append(lvl)
    nl.append(lnl)
    uvl.append(luvl)
    obj_mtx.append(obj.matrix_local)

def buildMeta( obj ):
    global start
    global next
Jan Scheffczyk's avatar
Jan Scheffczyk committed
203
    global transform
204
205
206
207
208
209

    if obj.name.find('_')== -1:
        return

    if obj.name.find('_start') != -1:
        start = obj.matrix_world
210
        return
211
212
213
214


    if obj.name.find('_next') != -1:
        next = obj.matrix_world
215
        return
216

Jan Scheffczyk's avatar
Jan Scheffczyk committed
217
218
    transform.append(obj)

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


###########################################################
#
#   Write names of all exported objects to C file.
#   Each name is a index which can be used to refer
#   to values of single object
#
###########################################################

def writeAllObjectNames(file):
    for i, n in enumerate(obj_names):
        file.write("#define %s %d\n" % (n, i))


###########################################################
#
#   Write tranfsormations matrix (4x4) float values
#   into single table
#
###########################################################

def writeTransformations(file):
    file.write("/***************************************\n")
    file.write(" *          local transformations\n")
    file.write(" ***************************************/\n\n")
    file.write("float transformations[][16]={\n")
    for m in obj_mtx:
        file.write("\t{%ff, %ff, %ff, %ff, " % tuple(m.col[0]))
        file.write("%ff, %ff, %ff, %ff, " % tuple(m.col[1]))
        file.write("%ff, %ff, %ff, %ff, " % tuple(m.col[2]))
        file.write("%ff, %ff, %ff, %ff},\n " % tuple(m.col[3]))
    file.write("};\n")


###########################################################
#
#   Write all vertices to single table
#
###########################################################

def writeVertices(file):
    file.write("/***************************************\n")
    file.write(" *\tvertices definition\n")
    file.write(" ***************************************/\n")

    file.write("\nstruct vertex_struct {\n\tfloat x,y,z;\n\tfloat nx,ny,nz;\n\tfloat u,v;\n};\n")

    # write verictes table
    file.write("struct vertex_struct vertices[]={\n")
    for i, d in enumerate(vl):
        file.write("\t/* %s: %d vertices */\n" % (obj_names[i], len(d)))
        for j in range(0, len(d)):
            file.write("\t{%ff, %ff, %ff, " % tuple(vl[i][j]))
            file.write("%ff, %ff, %ff, " % tuple(nl[i][j]))
            file.write("%ff, %ff},\n" % tuple(uvl[i][j]))
    file.write("};\n\n")


###########################################################
#
#   Write faces indexes into single table
#
###########################################################

def writeFaces(file):
    if (max_vcnt <= 65535):
        file.write("#define INX_TYPE GL_UNSIGNED_SHORT\n")
        file.write("unsigned short indexes[]={\n")
    else:
        file.write("#define INX_TYPE GL_UNSIGNED_INT\n")
        file.write("unsigned int indexes[]={\n")

    for i in range(len(faces)):
        file.write("/* %s %d faces */\n" % (obj_names[i], len(faces[i])))
        for j, f in enumerate(faces[i]):
            file.write("%d, %d, %d, " % tuple(f))
        file.write("\n")
    file.write("};\n")





###########################################################
#
#   Write number of vertices and faces for each object
#   and generates offset tables for each object
#
###########################################################

def writeVertexAndFacesCountTables(file):
    global max_vcnt

    file.write("/***************************************\n")
    file.write(" *\tfaces count for each mesh \n")
    file.write(" ***************************************/\n")
    file.write("unsigned int faces_count[]={")
    for i, f in enumerate(faces):
        file.write("%d" % len(f))
        if (i < (len(faces) - 1)):
            file.write(", ")
        else:
            file.write("};\n\n")

    file.write("/***************************************\n")
    file.write(" *\tvertices count for each mesh \n")
    file.write(" ***************************************/\n")
    file.write("unsigned int vertex_count[]={")
    vlsize = len(vl)
    for i, list in enumerate(vl):
        file.write("%d" % len(list))
        if (max_vcnt < len(list)):
            max_vcnt = len(list)

        if (i < (vlsize - 1)):
            file.write(", ")
    file.write("};\n\n")

    file.write("/***************************************\n")
    file.write(" *\toffset tables for each mesh  \n")
    file.write(" ***************************************/\n")
    file.write("unsigned int vertex_offset_table []={\n\t");
    voffset = 0
    for i in vl:
        file.write("%d, " % voffset)
        voffset += len(i)
    file.write("\n};\n")

    file.write("unsigned int indices_offset_table []={\n\t")
    foffset = 0
    for f in faces:
        file.write("%d, " % foffset)
        foffset += (len(f) * 3)
    file.write("\n};\n")

355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
def writeObstacles( file , depth):
    for ob in transform:
        m = ob.matrix_world
        clearName = ob.name[1:]
        file.write(tDepth(depth + 1) + "<mat4 type=\"" + clearName + "\">\n")
        file.write(tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[0]))
        file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[1]))
        file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[2]))
        file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[3]))
        file.write("</vec4>\n")
        file.write(tDepth(depth + 1) + "</mat4>\n")
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

def writePlane( file , index, depth):
    file.write(tDepth(depth) + "<plane>\n")

    m = obj_mtx[index]

    file.write(tDepth(depth + 1) + "<mat4>\n")
    file.write(tDepth(depth + 2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[0]))
    file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[1]))
    file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[2]))
    file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[3]))
    file.write("</vec4>\n")
    file.write(tDepth(depth + 1) + "</mat4>\n")

    d = vl[index]
    for j in range(0, len(d)):
        file.write(tDepth(depth + 1) + "<vec3>")
        file.write("%ff, %ff, %ff " % tuple(vl[index][j]))
        file.write("</vec3>\n")

    file.write(tDepth(depth) + "</plane>\n")

def writeMesh(file, index , depth):
Jan Scheffczyk's avatar
Jan Scheffczyk committed
397
    file.write(tDepth(depth)+"<mesh name=\""+obj_names[index]+"\">\n")
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
    file.write(tDepth(depth+1))
    file.write("<indices amount=\""+str(len(faces[index]))+"\">")
    for j, f in enumerate(faces[index]):
        file.write("%d, %d, %d, " % tuple(f))
    file.write("</indices>\n")

    file.write(tDepth(depth+1)+"<diffuse>"+diffuse[index]+"</diffuse>\n")

    m = obj_mtx[index]

    file.write(tDepth(depth+1) + "<mat4>\n")
    file.write(tDepth(depth+2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[0]))
    file.write("</vec4>\n" + tDepth(depth+2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[1]))
    file.write("</vec4>\n" + tDepth(depth+2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[2]))
    file.write("</vec4>\n" + tDepth(depth+2) + "<vec4>")
    file.write("%ff, %ff, %ff, %ff " % tuple(m.col[3]))
    file.write("</vec4>\n")
    file.write(tDepth(depth+1) + "</mat4>\n")

    d = vl[index]
    for j in range(0, len(d)):
        file.write(tDepth(depth+1)+"<vertex>")
        file.write("%ff, %ff, %ff, " % tuple(vl[index][j]))
        file.write("%ff, %ff, %ff, " % tuple(nl[index][j]))
        file.write("%ff, %ff" % tuple(uvl[index][j]))
        file.write("</vertex>\n")


    file.write(tDepth(depth)+"</mesh>\n")

def writeMeta( file , depth ):
    file.write(tDepth(depth)+"<meta>\n")
    file.write(tDepth(depth+1) + "<difficulty>0</difficulty>\n")
    file.write(tDepth(depth + 1) + "<type>0</type>\n")
    file.write(tDepth(depth + 1) + "<rot>0.0</rot>\n")
    m = start
Jan Scheffczyk's avatar
Jan Scheffczyk committed
437
438
439
440
441
442
443
444
445
446
447
448
    if(m!=""):
        file.write(tDepth(depth+1) + "<mat4 type=\"start\">\n")
        file.write(tDepth(depth+2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[0]))
        file.write("</vec4>\n" + tDepth(depth+2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[1]))
        file.write("</vec4>\n" + tDepth(depth+2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[2]))
        file.write("</vec4>\n" + tDepth(depth+2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[3]))
        file.write("</vec4>\n")
        file.write(tDepth(depth+1) + "</mat4>\n")
449
450

    m = next
Jan Scheffczyk's avatar
Jan Scheffczyk committed
451
452
453
454
455
456
457
458
459
460
461
462
    if m != "" :
        file.write(tDepth(depth + 1) + "<mat4 type=\"next\">\n")
        file.write(tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[0]))
        file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[1]))
        file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[2]))
        file.write("</vec4>\n" + tDepth(depth + 2) + "<vec4>")
        file.write("%ff, %ff, %ff, %ff " % tuple(m.col[3]))
        file.write("</vec4>\n")
        file.write(tDepth(depth + 1) + "</mat4>\n")
463

464

Jan Scheffczyk's avatar
Jan Scheffczyk committed
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
    file.write(tDepth(depth) + "</meta>\n")
###########################################################
#
#       Save data to C header file
#
###########################################################
def tDepth(i):
    string = ""
    for k in range(i):
        string = string + "\t"
    return string


def save(filename):
    file = open(filename, "w", newline="\n")
    # file.write("#ifndef _BLENDER_EXPORT_H_\n#define _BLENDER_EXPORT_H_\n\n")
    # file.write("#define OBJECTS_COUNT %d\n"%obj_cnt)
    # writeAllObjectNames(file)
    # writeTransformations (file)
    # writeVertexAndFacesCountTables(file)
    # writeVertices(file)
    # writeFaces(file)
    file.write("<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n")
    file.write("<TunnelSegment>\n")
    writeMeta(file , 1)

    N = len(obj_names)
    for i in range(N):
        print("writing "+obj_names[i])
        if obj_names[i].find('_') != -1:
            if obj_names[i].find('_cPl') != -1:
                writePlane( file , i , 1)
        else:
            #it is a mesh
            writeMesh(file, i, 1)

502
503
    writeObstacles( file , 0)

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
    file.write("</TunnelSegment>")
    file.close()
###########################################################
#
#       Export MESH object. By default export whole scene
#
###########################################################

def export( entire_scene=True):
    global obj_cnt
    global obj_names  # names of meshes in "C-suitable" format
    global vtx  # list of dictionaries for each mesh
    global faces  # list of lists
    global vl  # list of vertices for each mesh
    global nl  # list of normals for each mesh
    global uvl  # list of UV coords for each mesh
    global obj_mtx  # list of local transformations for each object

    global start
    global next
    global diffuse
    global specular

    print("--------------------------------------------------\n")
    print("Starting script:\n")


    # clear all gloabl variables
    obj_names = []  # names of meshes in "C-suitable" format
    vtx = []  # list of dictionaries for each mesh
    faces = []  # list of lists
    vl = []  # list of vertices for each mesh
    nl = []  # list of normals for each mesh
    uvl = []  # list of UV coords for each mesh
    obj_mtx = []  # list of local transformations for each object
    obj_cnt = 0  # object count
    max_vcnt = 0  # qty of vertices for biggest mesh

    sc = bpy.context.scene  # export MESHes from active scene

    if (entire_scene):
        for o in sc.objects:
            if (o.type == "MESH"):  # export ONLY meshes
                msh = o.to_mesh(sc, True, "PREVIEW")  # prepare MESH
                buildData(o, msh, o.name)
                bpy.data.meshes.remove(msh)
            else:
                buildMeta( o )

    else:
        o = sc.objects.active
        msh = o.to_mesh(sc, True, 'PREVIEW')
        buildData(o, msh, o.name)
        bpy.data.meshes.remove(msh)

    fname = bpy.path.basename(bpy.data.filepath)
    fname = os.path.splitext(fname)[0]
    fname = fname + ".xml"

    save(fname)
564

565

566
567
568
569
570
    print("Done\n")
    return {'FINISHED'}


export(True)