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

delaunay_voronoi.py « add_advanced_objects_panels - git.blender.org/blender-addons.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ec8f330a05f3639a0c58a948953947a23b59abd5 (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
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
# -*- coding:utf-8 -*-

# ##### 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 #####

bl_info = {
    "name": "Delaunay Voronoi",
    "description": "Points cloud Delaunay triangulation in 2.5D "
                   "(suitable for terrain modelling) or Voronoi diagram in 2D",
    "author": "Domlysz, Oscurart",
    "version": (1, 3),
    "blender": (2, 7, 0),
    "location": "View3D > Tools > GIS",
    "warning": "",
    "wiki_url": "https://github.com/domlysz/BlenderGIS/wiki",
    "category": "Add Mesh"
    }



import bpy
from .DelaunayVoronoi import (
        computeVoronoiDiagram,
        computeDelaunayTriangulation,
        )
from bpy.types import (
        Operator,
        Panel,
        )
from bpy.props import EnumProperty


# Globals
# set to True to enable debug_prints
DEBUG = False


def debug_prints(text=""):
    global DEBUG
    if DEBUG and text:
        print(text)


class Point:
    def __init__(self, x, y, z):
        self.x, self.y, self.z = x, y, z


def unique(L):
    """Return a list of unhashable elements in s, but without duplicates.
    [[1, 2], [2, 3], [1, 2]] >>> [[1, 2], [2, 3]]"""
    # For unhashable objects, you can sort the sequence and
    # then scan from the end of the list, deleting duplicates as you go
    nDupli = 0
    nZcolinear = 0
    # sort() brings the equal elements together; then duplicates
    # are easy to weed out in a single pass
    L.sort()
    last = L[-1]
    for i in range(len(L) - 2, -1, -1):
        if last[:2] == L[i][:2]:    # XY coordinates compararison
            if last[2] == L[i][2]:  # Z coordinates compararison
                nDupli += 1         # duplicates vertices
            else:  # Z colinear
                nZcolinear += 1
            del L[i]
        else:
            last = L[i]
    # list data type is mutable, input list will automatically update
    # and doesn't need to be returned
    return (nDupli, nZcolinear)


def checkEqual(lst):
    return lst[1:] == lst[:-1]


class ToolsPanelDelaunay(Panel):
    bl_category = "Create"
    bl_label = "Delaunay Voronoi"
    bl_space_type = "VIEW_3D"
    bl_context = "objectmode"
    bl_region_type = "TOOLS"
    bl_options = {"DEFAULT_CLOSED"}

    def draw(self, context):
        layout = self.layout
        adv_obj = context.scene.advanced_objects

        box = layout.box()
        col = box.column(align=True)
        col.label("Point Cloud:")
        col.operator("delaunay.triangulation")
        col.operator("voronoi.tesselation")


class OBJECT_OT_TriangulateButton(Operator):
    bl_idname = "delaunay.triangulation"
    bl_label = "Triangulation"
    bl_description = ("Terrain points cloud Delaunay triangulation in 2.5D\n"
                      "Needs an existing Active Mesh Object")
    bl_options = {"REGISTER", "UNDO"}

    @classmethod
    def poll(cls, context):
        obj = context.active_object
        return (obj is not None and obj.type == "MESH")

    def execute(self, context):
        # move the check into the poll
        obj = context.active_object

        # Get points coodinates
        r = obj.rotation_euler
        s = obj.scale
        mesh = obj.data
        vertsPts = [vertex.co for vertex in mesh.vertices]

        # Remove duplicate
        verts = [[vert.x, vert.y, vert.z] for vert in vertsPts]
        nDupli, nZcolinear = unique(verts)
        nVerts = len(verts)

        debug_prints(text=str(nDupli) + " duplicate points ignored")
        debug_prints(str(nZcolinear) + " z colinear points excluded")

        if nVerts < 3:
            self.report({"WARNING"},
                        "Not enough points to continue. Operation Cancelled")

            return {"CANCELLED"}

        # Check colinear
        xValues = [pt[0] for pt in verts]
        yValues = [pt[1] for pt in verts]

        if checkEqual(xValues) or checkEqual(yValues):
            self.report({'ERROR'}, "Points are colinear")
            return {'FINISHED'}

        # Triangulate
        debug_prints(text="Triangulate " + str(nVerts) + " points...")

        vertsPts = [Point(vert[0], vert[1], vert[2]) for vert in verts]
        triangles = computeDelaunayTriangulation(vertsPts)
        # reverse point order --> if all triangles are specified anticlockwise then all faces up
        triangles = [tuple(reversed(tri)) for tri in triangles]

        debug_prints(text=str(len(triangles)) + " triangles")

        # Create new mesh structure
        debug_prints(text="Create mesh...")
        tinMesh = bpy.data.meshes.new("TIN")        # create a new mesh
        tinMesh.from_pydata(verts, [], triangles)   # Fill the mesh with triangles
        tinMesh.update(calc_edges=True)             # Update mesh with new data

        # Create an object with that mesh
        tinObj = bpy.data.objects.new("TIN", tinMesh)

        # Place object
        tinObj.location = obj.location.copy()
        tinObj.rotation_euler = r
        tinObj.scale = s

        # Update scene
        bpy.context.scene.objects.link(tinObj)  # Link object to scene
        bpy.context.scene.objects.active = tinObj
        tinObj.select = True
        obj.select = False

        self.report({"INFO"},
                     "Mesh created (" + str(len(triangles)) + " triangles)")

        return {'FINISHED'}


class OBJECT_OT_VoronoiButton(Operator):
    bl_idname = "voronoi.tesselation"
    bl_label = "Diagram"
    bl_description = ("Points cloud Voronoi diagram in 2D\n"
                      "Needs an existing Active Mesh Object")
    bl_options = {"REGISTER", "UNDO"}

    meshType = EnumProperty(
            items=[('Edges', "Edges", "Edges Only - do not fill Faces"),
                   ('Faces', "Faces", "Fill Faces in the new Object")],
            name="Mesh type",
            description="Type of geometry to generate"
            )

    @classmethod
    def poll(cls, context):
        obj = context.active_object
        return (obj is not None and obj.type == "MESH")

    def execute(self, context):
        # move the check into the poll
        obj = context.active_object

        # Get points coodinates
        r = obj.rotation_euler
        s = obj.scale
        mesh = obj.data
        vertsPts = [vertex.co for vertex in mesh.vertices]

        # Remove duplicate
        verts = [[vert.x, vert.y, vert.z] for vert in vertsPts]
        nDupli, nZcolinear = unique(verts)
        nVerts = len(verts)

        debug_prints(text=str(nDupli) + " duplicates points ignored")
        debug_prints(text=str(nZcolinear) + " z colinear points excluded")

        if nVerts < 3:
            self.report({"WARNING"},
                        "Not enough points to continue. Operation Cancelled")

            return {"CANCELLED"}

        # Check colinear
        xValues = [pt[0] for pt in verts]
        yValues = [pt[1] for pt in verts]

        if checkEqual(xValues) or checkEqual(yValues):
            self.report({"WARNING"},
                        "Points are colinear. Operation Cancelled")

            return {"CANCELLED"}

        # Create diagram
        debug_prints(text="Tesselation... (" + str(nVerts) + " points)")

        xbuff, ybuff = 5, 5
        zPosition = 0
        vertsPts = [Point(vert[0], vert[1], vert[2]) for vert in verts]

        if self.meshType == "Edges":
            pts, edgesIdx = computeVoronoiDiagram(
                                vertsPts, xbuff, ybuff,
                                polygonsOutput=False, formatOutput=True
                                )
        else:
            pts, polyIdx = computeVoronoiDiagram(
                                vertsPts, xbuff, ybuff, polygonsOutput=True,
                                formatOutput=True, closePoly=False
                                )

        pts = [[pt[0], pt[1], zPosition] for pt in pts]

        # Create new mesh structure
        voronoiDiagram = bpy.data.meshes.new("VoronoiDiagram")  # create a new mesh

        if self.meshType == "Edges":
            # Fill the mesh with triangles
            voronoiDiagram.from_pydata(pts, edgesIdx, [])
        else:
            # Fill the mesh with triangles
            voronoiDiagram.from_pydata(pts, [], list(polyIdx.values()))

        voronoiDiagram.update(calc_edges=True)  # Update mesh with new data
        # create an object with that mesh
        voronoiObj = bpy.data.objects.new("VoronoiDiagram", voronoiDiagram)
        # place object
        voronoiObj.location = obj.location.copy()
        voronoiObj.rotation_euler = r
        voronoiObj.scale = s

        # update scene
        bpy.context.scene.objects.link(voronoiObj)  # Link object to scene
        bpy.context.scene.objects.active = voronoiObj
        voronoiObj.select = True
        obj.select = False

        # Report
        if self.meshType == "Edges":
            self.report({"INFO"}, "Mesh created (" + str(len(edgesIdx)) + " edges)")
        else:
            self.report({"INFO"}, "Mesh created (" + str(len(polyIdx)) + " polygons)")

        return {'FINISHED'}

# Register
def register():
    bpy.utils.register_class(OBJECT_OT_VoronoiButton)
    bpy.utils.register_class(OBJECT_OT_TriangulateButton)
    bpy.utils.register_class(ToolsPanelDelaunay)


def unregister():
    bpy.utils.unregister_class(OBJECT_OT_VoronoiButton)
    bpy.utils.unregister_class(OBJECT_OT_TriangulateButton)
    bpy.utils.unregister_class(ToolsPanelDelaunay)


if __name__ == "__main__":
    register()