Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gltf2_blender_primitive.py « imp « blender « io_scene_gltf2 - git.blender.org/blender-addons.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0696673dde6bb313a40ce6af34829cf809499a4d (plain)
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
# Copyright 2018-2019 The glTF-Blender-IO authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import bpy
from mathutils import Vector

from .gltf2_blender_material import BlenderMaterial
from ..com.gltf2_blender_conversion import loc_gltf_to_blender
from ...io.imp.gltf2_io_binary import BinaryData


class BlenderPrimitive():
    """Blender Primitive."""
    def __new__(cls, *args, **kwargs):
        raise RuntimeError("%s should not be instantiated" % cls)

    @staticmethod
    def create(gltf, pyprimitive, verts, edges, faces):
        """Primitive creation."""
        pyprimitive.blender_texcoord = {}

        current_length = len(verts)
        pos = BinaryData.get_data_from_accessor(gltf, pyprimitive.attributes['POSITION'])
        if pyprimitive.indices is not None:
            indices = BinaryData.get_data_from_accessor(gltf, pyprimitive.indices)
        else:
            indices = [(i,) for i in range(len(pos))]

        pyprimitive.tmp_indices = indices

        # Manage only vertices that are in indices tab
        indice_equivalents = {}
        new_pos = []
        new_pos_idx = 0
        for i in indices:
            if i[0] not in indice_equivalents.keys():
                indice_equivalents[i[0]] = new_pos_idx
                new_pos.append(pos[i[0]])
                new_pos_idx += 1

        prim_verts = [loc_gltf_to_blender(vert) for vert in new_pos]

        mode = 4 if pyprimitive.mode is None else pyprimitive.mode
        prim_edges, prim_faces = BlenderPrimitive.edges_and_faces(mode, indices)

        verts.extend(prim_verts)
        pyprimitive.vertices_length = len(prim_verts)
        edges.extend(
            tuple(indice_equivalents[y] + current_length for y in e)
            for e in prim_edges
        )
        faces.extend(
            tuple(indice_equivalents[y] + current_length for y in f)
            for f in prim_faces
        )

        # manage material of primitive
        if pyprimitive.material is not None:

            vertex_color = None
            if 'COLOR_0' in pyprimitive.attributes.keys():
                vertex_color = 'COLOR_0'

            # Create Blender material if needed
            if vertex_color is None:
                if None not in gltf.data.materials[pyprimitive.material].blender_material.keys():
                    BlenderMaterial.create(gltf, pyprimitive.material, vertex_color)
            else:
                if vertex_color not in gltf.data.materials[pyprimitive.material].blender_material.keys():
                    BlenderMaterial.create(gltf, pyprimitive.material, vertex_color)


        return verts, edges, faces

    @staticmethod
    def edges_and_faces(mode, indices):
        """Converts the indices in a particular primitive mode into standard lists of
        edges (pairs of indices) and faces (tuples of CCW indices).
        """
        es = []
        fs = []

        if mode == 0:
            # POINTS
            pass
        elif mode == 1:
            # LINES
            #   1   3
            #  /   /
            # 0   2
            es = [
                (indices[i][0], indices[i + 1][0])
                for i in range(0, len(indices), 2)
            ]
        elif mode == 2:
            # LINE LOOP
            #   1---2
            #  /     \
            # 0-------3
            es = [
                (indices[i][0], indices[i + 1][0])
                for i in range(0, len(indices) - 1)
            ]
            es.append((indices[-1][0], indices[0][0]))
        elif mode == 3:
            # LINE STRIP
            #   1---2
            #  /     \
            # 0       3
            es = [
                (indices[i][0], indices[i + 1][0])
                for i in range(0, len(indices) - 1)
            ]
        elif mode == 4:
            # TRIANGLES
            #   2     3
            #  / \   / \
            # 0---1 4---5
            fs = [
                (indices[i][0], indices[i + 1][0], indices[i + 2][0])
                for i in range(0, len(indices), 3)
            ]
        elif mode == 5:
            # TRIANGLE STRIP
            # 0---2---4
            #  \ / \ /
            #   1---3
            def alternate(i, xs):
                even = i % 2 == 0
                return xs if even else (xs[0], xs[2], xs[1])
            fs = [
                alternate(i, (indices[i][0], indices[i + 1][0], indices[i + 2][0]))
                for i in range(0, len(indices) - 2)
            ]
        elif mode == 6:
            # TRIANGLE FAN
            #   3---2
            #  / \ / \
            # 4---0---1
            fs = [
                (indices[0][0], indices[i][0], indices[i + 1][0])
                for i in range(1, len(indices) - 1)
            ]
        else:
            raise Exception('primitive mode unimplemented: %d' % mode)

        return es, fs

    def set_normals(gltf, pyprimitive, mesh, offset, custom_normals):
        """Set Normal."""
        if 'NORMAL' in pyprimitive.attributes.keys():
            original_normal_data = BinaryData.get_data_from_accessor(gltf, pyprimitive.attributes['NORMAL'])

            tmp_indices = {}
            tmp_idx = 0
            normal_data = []
            for i in pyprimitive.tmp_indices:
                if i[0] not in tmp_indices.keys():
                    tmp_indices[i[0]] = tmp_idx
                    tmp_idx += 1
                    normal_data.append(original_normal_data[i[0]])

            for poly in mesh.polygons:
                if gltf.import_settings['import_shading'] == "NORMALS":
                    calc_norm_vertices = []
                    for loop_idx in range(poly.loop_start, poly.loop_start + poly.loop_total):
                        vert_idx = mesh.loops[loop_idx].vertex_index
                        if vert_idx in range(offset, offset + pyprimitive.vertices_length):
                            cpt_vert = vert_idx - offset
                            mesh.vertices[vert_idx].normal = normal_data[cpt_vert]
                            custom_normals[vert_idx] = list(normal_data[cpt_vert])
                            calc_norm_vertices.append(vert_idx)

                        if len(calc_norm_vertices) == 3:
                            # Calcul normal
                            vert0 = mesh.vertices[calc_norm_vertices[0]].co
                            vert1 = mesh.vertices[calc_norm_vertices[1]].co
                            vert2 = mesh.vertices[calc_norm_vertices[2]].co
                            calc_normal = (vert1 - vert0).cross(vert2 - vert0).normalized()

                            # Compare normal to vertex normal
                            for i in calc_norm_vertices:
                                cpt_vert = vert_idx - offset
                                vec = Vector(
                                    (normal_data[cpt_vert][0], normal_data[cpt_vert][1], normal_data[cpt_vert][2])
                                )
                                if not calc_normal.dot(vec) > 0.9999999:
                                    poly.use_smooth = True
                                    break
                elif gltf.import_settings['import_shading'] == "FLAT":
                    poly.use_smooth = False
                elif gltf.import_settings['import_shading'] == "SMOOTH":
                    poly.use_smooth = True
                else:
                    pass  # Should not happen

        offset = offset + pyprimitive.vertices_length
        return offset

    def set_UV(gltf, pyprimitive, obj, mesh, offset):
        """Set UV Map."""
        for texcoord in [attr for attr in pyprimitive.attributes.keys() if attr[:9] == "TEXCOORD_"]:
            if texcoord not in mesh.uv_layers:
                mesh.uv_layers.new(name=texcoord)
            pyprimitive.blender_texcoord[int(texcoord[9:])] = texcoord

            original_texcoord_data = BinaryData.get_data_from_accessor(gltf, pyprimitive.attributes[texcoord])


            tmp_indices = {}
            tmp_idx = 0
            texcoord_data = []
            for i in pyprimitive.tmp_indices:
                if i[0] not in tmp_indices.keys():
                    tmp_indices[i[0]] = tmp_idx
                    tmp_idx += 1
                    texcoord_data.append(original_texcoord_data[i[0]])

            for poly in mesh.polygons:
                for loop_idx in range(poly.loop_start, poly.loop_start + poly.loop_total):
                    vert_idx = mesh.loops[loop_idx].vertex_index
                    if vert_idx in range(offset, offset + pyprimitive.vertices_length):
                        obj.data.uv_layers[texcoord].data[loop_idx].uv = \
                            Vector((texcoord_data[vert_idx - offset][0], 1 - texcoord_data[vert_idx - offset][1]))

        offset = offset + pyprimitive.vertices_length
        return offset

    def set_UV_in_mat(gltf, pyprimitive, obj, vertex_color):
        """After nodetree creation, set UVMap in nodes."""
        if pyprimitive.material is None:
            return
        if gltf.data.materials[pyprimitive.material].extensions \
                and "KHR_materials_pbrSpecularGlossiness" in \
                    gltf.data.materials[pyprimitive.material].extensions.keys():
            if pyprimitive.material is not None \
                    and gltf.data.materials[pyprimitive.material].extensions[
                        'KHR_materials_pbrSpecularGlossiness'
                    ]['diffuse_type'] in [gltf.TEXTURE, gltf.TEXTURE_FACTOR]:
                BlenderMaterial.set_uvmap(gltf, pyprimitive.material, pyprimitive, obj, vertex_color)
            else:
                if pyprimitive.material is not None \
                        and gltf.data.materials[pyprimitive.material].extensions[
                            'KHR_materials_pbrSpecularGlossiness'
                        ]['specgloss_type'] in [gltf.TEXTURE, gltf.TEXTURE_FACTOR]:
                    BlenderMaterial.set_uvmap(gltf, pyprimitive.material, pyprimitive, obj, vertex_color)

        else:
            if pyprimitive.material is not None \
                    and gltf.data.materials[pyprimitive.material].pbr_metallic_roughness.color_type in \
                    [gltf.TEXTURE, gltf.TEXTURE_FACTOR]:
                BlenderMaterial.set_uvmap(gltf, pyprimitive.material, pyprimitive, obj, vertex_color)
            else:
                if pyprimitive.material is not None \
                        and gltf.data.materials[pyprimitive.material].pbr_metallic_roughness.metallic_type in \
                        [gltf.TEXTURE, gltf.TEXTURE_FACTOR]:
                    BlenderMaterial.set_uvmap(gltf, pyprimitive.material, pyprimitive, obj, vertex_color)

    def assign_material(gltf, pyprimitive, obj, bm, offset, cpt_index_mat):
        """Assign material to faces of primitives."""
        if pyprimitive.material is not None:

            vertex_color = None
            if 'COLOR_0' in pyprimitive.attributes.keys():
                vertex_color = 'COLOR_0'

            obj.data.materials.append(bpy.data.materials[gltf.data.materials[pyprimitive.material].blender_material[vertex_color]])
            for vert in bm.verts:
                if vert.index in range(offset, offset + pyprimitive.vertices_length):
                    for loop in vert.link_loops:
                        face = loop.face.index
                        bm.faces[face].material_index = cpt_index_mat
            cpt_index_mat += 1
        offset = offset + pyprimitive.vertices_length
        return offset, cpt_index_mat