├── lib
└── kitfox
│ ├── __init__.py
│ ├── gui
│ ├── __init__.py
│ ├── events.py
│ ├── textInput.py
│ ├── label.py
│ ├── graphics.py
│ ├── panel.py
│ ├── layout.py
│ └── window.py
│ ├── math
│ ├── __init__.py
│ └── vecmath.py
│ └── blenderUtil.py
├── source
├── operators
│ ├── __init__.py
│ ├── TerrainHeightPickerMeshOperator.py
│ ├── SmoothingInfo.py
│ ├── TerrainSculptWorkspaceTool.py
│ ├── TerrainSculptMeshBrushPanel.py
│ ├── Common.py
│ ├── TerrainSculptMeshProperties.py
│ └── TerrainSculptMeshBrush.py
└── __init__.py
├── .gitignore
├── doc
└── image
│ ├── ramps.jpg
│ ├── slope.jpg
│ ├── sphereWorld.jpg
│ ├── simpleLandscape.jpg
│ └── simpleLandscape2.jpg
├── test
├── sculptTest.blend
└── sculptTest.blend1
├── experiments
├── testTerrain.blend
└── testTerrain.blend1
├── .github
└── FUNDING.yml
├── makeDeploy.py
├── make.py
├── README.md
└── LICENSE
/lib/kitfox/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/kitfox/math/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/source/operators/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 | /deploy
3 |
--------------------------------------------------------------------------------
/doc/image/ramps.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/doc/image/ramps.jpg
--------------------------------------------------------------------------------
/doc/image/slope.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/doc/image/slope.jpg
--------------------------------------------------------------------------------
/test/sculptTest.blend:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/test/sculptTest.blend
--------------------------------------------------------------------------------
/test/sculptTest.blend1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/test/sculptTest.blend1
--------------------------------------------------------------------------------
/doc/image/sphereWorld.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/doc/image/sphereWorld.jpg
--------------------------------------------------------------------------------
/doc/image/simpleLandscape.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/doc/image/simpleLandscape.jpg
--------------------------------------------------------------------------------
/doc/image/simpleLandscape2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/doc/image/simpleLandscape2.jpg
--------------------------------------------------------------------------------
/experiments/testTerrain.blend:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/experiments/testTerrain.blend
--------------------------------------------------------------------------------
/experiments/testTerrain.blend1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/blackears/blenderTerrainSculpt/HEAD/experiments/testTerrain.blend1
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: markmckay
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: kitfox_com
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 | #custom: paypal.me/kitfoxArtAndCode
--------------------------------------------------------------------------------
/makeDeploy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderTerrainSculpt).
4 | # Copyright (c) 2021 Mark McKay
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, version 3.
9 | #
10 | # This program is distributed in the hope that it will be useful, but
11 | # WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 | # General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 |
18 | import make
19 |
20 | make.make(createArchive = True)
21 |
22 |
--------------------------------------------------------------------------------
/source/__init__.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 |
17 | bl_info = {
18 | "name": "Terrain Sculpting Tools",
19 | "description": "Tools for creating and editing terrains.",
20 | "author": "Mark McKay",
21 | "version": (1, 0, 10),
22 | "blender": (5, 0, 0),
23 | "location": "View3D",
24 | # "wiki_url": "https://github.com/blackears/uvTools",
25 | # "tracker_url": "https://github.com/blackears/uvTools",
26 | "category": "View 3D"
27 | }
28 |
29 | import importlib
30 |
31 |
32 | if "bpy" in locals():
33 | if "TerrainSculptMeshBrushPanel" in locals():
34 | importlib.reload(TerrainSculptMeshBrushPanel)
35 | else:
36 | from .operators import TerrainSculptMeshBrushPanel
37 |
38 |
39 | else:
40 | from .operators import TerrainSculptMeshBrushPanel
41 |
42 | def register():
43 | TerrainSculptMeshBrushPanel.register()
44 |
45 |
46 | def unregister():
47 | TerrainSculptMeshBrushPanel.unregister()
48 |
49 |
--------------------------------------------------------------------------------
/lib/kitfox/blenderUtil.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import mathutils
21 |
22 | def redraw_all_viewports(context):
23 | for area in bpy.context.screen.areas: # iterate through areas in current screen
24 | if area.type == 'VIEW_3D':
25 | area.tag_redraw()
26 |
27 | #Wrap Blender's ray_cast, since the way the method was called changed in verison 2.91
28 | def ray_cast_scene(context, viewlayer, ray_origin, view_vector):
29 | if bpy.app.version >= (2, 91, 0):
30 | return context.scene.ray_cast(viewlayer.depsgraph, ray_origin, view_vector)
31 | else:
32 | return context.scene.ray_cast(viewlayer, ray_origin, view_vector)
33 |
34 |
35 | def mesh_bounds_world(obj):
36 |
37 | minCo = None
38 | maxCo = None
39 | mesh = obj.data
40 |
41 | for v in mesh.vertices:
42 | pos = mathutils.Vector(v.co)
43 | pos = obj.matrix_world @ pos
44 |
45 | # print("pos " + str(pos))
46 |
47 | if minCo == None:
48 | minCo = mathutils.Vector(pos)
49 | maxCo = mathutils.Vector(pos)
50 | else:
51 | minCo.x = min(minCo.x, pos.x)
52 | minCo.y = min(minCo.y, pos.y)
53 | minCo.z = min(minCo.z, pos.z)
54 | maxCo.x = max(maxCo.x, pos.x)
55 | maxCo.y = max(maxCo.y, pos.y)
56 | maxCo.z = max(maxCo.z, pos.z)
57 |
58 | return (minCo, maxCo)
59 |
--------------------------------------------------------------------------------
/source/operators/TerrainHeightPickerMeshOperator.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy
17 | from ..kitfox.math.vecmath import *
18 | from ..kitfox.blenderUtil import *
19 | from .Common import *
20 | from .TerrainSculptMeshProperties import *
21 |
22 |
23 | class TerrainHeightPickerMeshOperator(bpy.types.Operator):
24 | """Pick Terrain Height"""
25 | bl_idname = "kitfox.terrain_height_picker_mesh"
26 | bl_label = "Pick Normal"
27 | bl_options = {"REGISTER", "UNDO"}
28 |
29 | def __init__(self, *args, **kwargs):
30 | super().__init__(*args, **kwargs)
31 | self.picking = False
32 |
33 | def __del__(self):
34 | super().__del__()
35 |
36 | def modal(self, context, event):
37 | if event.type == 'MOUSEMOVE':
38 | if self.picking:
39 | context.window.cursor_set("EYEDROPPER")
40 | else:
41 | context.window.cursor_set("DEFAULT")
42 | return {'PASS_THROUGH'}
43 |
44 | elif event.type == 'LEFTMOUSE':
45 | self.picking = False
46 | pick_height(context, event)
47 | context.window.cursor_set("DEFAULT")
48 | return {'FINISHED'}
49 |
50 | elif event.type in {'RIGHTMOUSE', 'ESC'}:
51 | self.picking = False
52 | # print("pick target object cancelled")
53 | context.window.cursor_set("DEFAULT")
54 | return {'CANCELLED'}
55 | else:
56 | return {'PASS_THROUGH'}
57 |
58 | def invoke(self, context, event):
59 | if context.area.type == 'VIEW_3D':
60 |
61 | args = (self, context)
62 | self._context = context
63 |
64 | context.window_manager.modal_handler_add(self)
65 |
66 | context.window.cursor_set("EYEDROPPER")
67 | self.picking = True
68 |
69 | return {'RUNNING_MODAL'}
70 | else:
71 | self.report({'WARNING'}, "View3D not found, cannot run operator")
72 | return {'CANCELLED'}
73 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/events.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | #import sys
21 | #import mathutils
22 | from mathutils import *
23 | #import bgl
24 | #import blf
25 | #import gpu
26 | #from gpu_extras.batch import batch_for_shader
27 | #from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 | # from .graphics import DrawContext2D
32 | # from .layout import *
33 |
34 | #----------------------------------
35 |
36 | class MouseButton(Enum):
37 | LEFT = 1
38 | MIDDLE = 2
39 | RIGHT = 3
40 |
41 | #----------------------------------
42 |
43 | class MouseButtonEvent:
44 | def __init__(self, mouse_button = None, pos = Vector((0, 0)), screen_pos = Vector((0, 0)), left_down = False, middle_down = False, right_down = False, shift_down = False, ctrl_down = False, alt_down = False):
45 | self.mouse_button = mouse_button
46 | self.pos = pos.copy()
47 | self.screen_pos = screen_pos.copy()
48 | self.left_down = left_down
49 | self.middle_down = middle_down
50 | self.right_down = right_down
51 |
52 | self.shift_down = shift_down
53 | self.ctrl_down = ctrl_down
54 | self.alt_down = alt_down
55 |
56 | def copy(self):
57 | return MouseButtonEvent(self.mouse_button, self.pos, self.screen_pos)
58 |
59 | def __str__(self):
60 | return "bn:" + str(self.mouse_button) + " pos:" + str(self.pos) + " scrn_pos:" + str(self.screen_pos) + " "
61 |
62 | #----------------------------------
63 |
64 | class KeyEvent:
65 | def __init__(self, key = "A", shift = False, ctrl = False, alt = False):
66 | self.key = key
67 | self.shift = shift
68 | self.ctrl = ctrl
69 | self.alt = alt
70 |
71 | def copy(self):
72 | return KeyEvent(self.key, self.shift, self.ctrl, self.alt)
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
--------------------------------------------------------------------------------
/source/operators/SmoothingInfo.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy.utils.previews
17 | from ..kitfox.math.vecmath import *
18 | from ..kitfox.blenderUtil import *
19 |
20 |
21 | class SmoothingPointInfo:
22 | def __init__(self, coord, height):
23 | self.coord = coord
24 | self.centroidHeight = height
25 |
26 | class SmoothingInfo:
27 | def __init__(self):
28 | self.points = []
29 |
30 | def addPoint(self, wpos, height):
31 | self.points.append(SmoothingPointInfo(wpos, height))
32 |
33 | def getCentroidHeight(self, wpos, terrain_origin, world_shape_type, smooth_edge_snap_distance):
34 | #########
35 | # print("getCentroidHeight( wpos " + str(wpos))
36 | if world_shape_type == 'FLAT':
37 | down = -vecZ
38 | wpos_parallel = wpos.project(down)
39 | wpos_perp = wpos_parallel - wpos
40 |
41 | centroidHeight = 0
42 | count = 0
43 |
44 |
45 | for p in self.points:
46 | coord_parallel = p.coord.project(down)
47 | coord_perp = coord_parallel - p.coord
48 |
49 | # print ("coord_perp " + str(coord_perp))
50 | # print ("coord_perp - wpos_perp " + str(coord_perp - wpos_perp))
51 |
52 | if (coord_perp - wpos_perp).magnitude < smooth_edge_snap_distance:
53 | # print ("p.centroidHeight " + str(p.centroidHeight))
54 | centroidHeight += p.centroidHeight
55 | count += 1
56 | #return p.centroidHeight
57 |
58 | if count >= 1:
59 | # print ("centroidHeight / count " + str(centroidHeight / count))
60 | return centroidHeight / count
61 | return 0
62 | else:
63 | #This currently does not take into account meshes that meet at seams
64 | for p in self.points:
65 | if (p.coord - wpos).magnitude < .001:
66 | return p.centroidHeight
67 | return 0
68 |
69 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/textInput.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import sys
21 | #import mathutils
22 | from mathutils import *
23 | import bgl
24 | import blf
25 | import gpu
26 | from gpu_extras.batch import batch_for_shader
27 | from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 | from .graphics import DrawContext2D
32 | from .layout import *
33 | from .panel import *
34 | from .label import *
35 |
36 | #----------------------------------
37 |
38 | class InputType(Enum):
39 | DISPLAY = 0
40 | TEXT_INPUT = 1
41 |
42 | #----------------------------------
43 |
44 | class TextInput(Label):
45 | def __init__(self, text = "label"):
46 | super().__init__(text)
47 |
48 | self.set_background_color(Vector((.7, .7, .7, 1)))
49 | self.set_border_radius(4)
50 | self.set_align_x(AlignX.RIGHT)
51 |
52 | #index of character cursor is just before
53 | self.cursor_pos = 0
54 | self.input_mode = InputType.DISPLAY
55 |
56 | # def handle_event(self, context, event):
57 | # panel_pos = self.get_screen_position()
58 | # click_pos = event.
59 |
60 | # if event.value == "PRESS":
61 | # print ("TextInput press")
62 |
63 | # return False
64 |
65 | def draw_component(self, ctx):
66 | super().draw_component(ctx)
67 |
68 | if self.input_mode == InputType.TEXT_INPUT:
69 |
70 | pass
71 |
72 | def draw_cursor(self, ctx):
73 | first_part = self.text[self.cursor_pos]
74 | last_part = self.text[self.cursor_pos:]
75 |
76 | blf.size(self.font_id, self.font_size, self.font_dpi)
77 | text_first_w, text_first_h = blf.dimensions(self.font_id, first_part)
78 | text_last_w, text_last_h = blf.dimensions(self.font_id, last_part)
79 |
80 |
81 |
82 | bounds = self.bounds()
83 |
84 | def mouse_pressed(self, event):
85 | print ("TextINput pressed")
86 | print("event.pos" + str(event.pos))
87 | print("event.screen_pos" + str(event.screen_pos))
88 | return True
89 |
90 | def mouse_released(self, event):
91 | print ("TextINput released")
92 | print("event.pos" + str(event.pos))
93 | print("event.screen_pos" + str(event.screen_pos))
94 | return True
95 |
96 | def mouse_moved(self, event):
97 | return True
98 |
99 |
100 |
--------------------------------------------------------------------------------
/source/operators/TerrainSculptWorkspaceTool.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy
17 | import bpy.utils.previews
18 | from ..kitfox.math.vecmath import *
19 | from ..kitfox.blenderUtil import *
20 | from .Common import *
21 | from .SmoothingInfo import *
22 | from .TerrainSculptMeshProperties import *
23 | from .TerrainHeightPickerMeshOperator import *
24 |
25 |
26 | class TerrainSculptWorkspaceTool(bpy.types.WorkSpaceTool):
27 | bl_space_type = 'VIEW_3D'
28 | bl_context_mode = 'OBJECT'
29 |
30 | bl_idname = "kitfox_terrain.terrain_brush_draw"
31 | bl_label = "Terrain Brush Draw"
32 | bl_description = ("Raise or lower terrain under cursor to the current brush height.")
33 |
34 | bl_icon = "ops.gpencil.draw.poly"
35 | bl_widget = None
36 | bl_keymap = (
37 | ("kitfox.echo_tool", {"type": 'LEFTMOUSE', "value": 'PRESS'},
38 | {"properties": [("tool_mode", "DEFAULT" )]}),
39 | ("kitfox.echo_tool", {"type": 'LEFTMOUSE', "value": 'PRESS', "ctrl": True},
40 | {"properties": [("tool_mode", "CONTROL")]}),
41 | ("kitfox.echo_tool", {"type": 'LEFTMOUSE', "value": 'PRESS', "alt": True},
42 | {"properties": [("tool_mode", "ALT")]}),
43 | ("kitfox.echo_tool", {"type": 'LEFTMOUSE', "value": 'PRESS', "shift": True},
44 | {"properties": [("tool_mode", "SHIFT")]}),
45 | ("kitfox.echo_tool", {"type": 'LEFTMOUSE', "value": 'PRESS', "oskey": True},
46 | {"properties": [("tool_mode", "OSKEY")]}),
47 | ("kitfox.echo_tool", {"type": 'LEFTMOUSE', "value": 'PRESS', "oskey" : True , "alt": True},
48 | {"properties": [("tool_mode", "OS+ALT")]}),
49 | ("kitfox.echo_tool", {"type": 'MOUSEMOVE', "value": 'ANY' }, {"properties": []}),
50 | )
51 |
52 |
53 |
54 | class EchoToolOperator(bpy.types.Operator):
55 | """Echo tool"""
56 | bl_idname = "kitfox.echo_tool"
57 | bl_label = "Echo tool"
58 | bl_options = {"REGISTER", "UNDO"}
59 |
60 | is_running = False
61 |
62 | tool_mode : bpy.props.StringProperty(
63 | name="Tool Mode",
64 | description="Tool Mode",
65 | )
66 |
67 |
68 | def __init__(self, *args, **kwargs):
69 | super().__init__(*args, **kwargs)
70 | self.picking = False
71 |
72 | def modal(self, context, event):
73 | print("modal evTyp:%s evVal:%s mode:%s" % (str(event.type), str(event.value), self.tool_mode))
74 |
75 | if context.mode != 'OBJECT':
76 | EchoToolOperator.is_running = False
77 | return {'CANCELED'}
78 |
79 | return {'RUNNING_MODAL'}
80 |
81 | def invoke(self, context, event):
82 | print("invoke evTyp:%s evVal:%s mode:%s" % (str(event.type), str(event.value), self.tool_mode))
83 |
84 | context.window_manager.modal_handler_add(self)
85 |
86 | EchoToolOperator.is_running = True
87 |
88 | return {'RUNNING_MODAL'}
89 |
--------------------------------------------------------------------------------
/make.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/blenderTerrainSculpt).
4 | # Copyright (c) 2021 Mark McKay
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, version 3.
9 | #
10 | # This program is distributed in the hope that it will be useful, but
11 | # WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 | # General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 |
18 | import os
19 | import shutil
20 | import sys
21 | import getopt
22 | import platform
23 |
24 | projectName = 'terrainSculptTools'
25 |
26 |
27 | def copytree(src, dst):
28 | for item in os.listdir(src):
29 |
30 | s = os.path.join(src, item)
31 | d = os.path.join(dst, item)
32 | if os.path.isdir(s):
33 | if not os.path.exists(d):
34 | os.mkdir(d)
35 | copytree(s, d)
36 | else:
37 | filename, extn = os.path.splitext(item)
38 | print ("file " + filename + " extn " + extn)
39 | if (extn != ".py" and extn != ".png"):
40 | continue
41 |
42 | shutil.copy(s, d)
43 |
44 | def make(copyToBlenderAddons = False, createArchive = False, rebuildLibs = False):
45 |
46 | blenderHome = None
47 | # platSys = platform.system()
48 | # if platSys == 'Windows':
49 | # appData = os.getenv('APPDATA')
50 | # blenderHome = os.path.join(appData, "Blender Foundation/Blender/2.91")
51 |
52 | # elif platSys == 'Linux':
53 | # home = os.getenv('HOME')
54 | # blenderHome = os.path.join(home, ".config/blender/2.91/")
55 |
56 |
57 | blenderHome = os.getenv('BLENDER_HOME')
58 |
59 | #Rebuild library directory
60 | if rebuildLibs:
61 | if os.path.exists('lib'):
62 | shutil.rmtree('lib')
63 | os.mkdir('lib')
64 | copytree("../blenderCommon/source", "lib")
65 |
66 |
67 | #Create build directory
68 | curPath = os.getcwd()
69 | if os.path.exists('build'):
70 | shutil.rmtree('build')
71 | os.mkdir('build')
72 | os.mkdir('build/' + projectName)
73 |
74 | copytree("source", "build/" + projectName)
75 | # copytree("../blenderCommon/source", "build/" + projectName)
76 | copytree("lib", "build/" + projectName)
77 |
78 |
79 | #Build addon zip file
80 | if createArchive:
81 | if os.path.exists('deploy'):
82 | shutil.rmtree('deploy')
83 | os.mkdir('deploy')
84 |
85 | shutil.make_archive("deploy/" + projectName, "zip", "build")
86 |
87 |
88 | if copyToBlenderAddons:
89 | if blenderHome == None:
90 | print("Error: BLENDER_HOME not set. Files not copied to /script/addons.")
91 | return
92 |
93 | addonPath = os.path.join(blenderHome, "scripts/addons")
94 | destPath = os.path.join(addonPath, projectName)
95 |
96 | print("Copying to blender addons: " + addonPath)
97 | if os.path.exists(destPath):
98 | shutil.rmtree(destPath)
99 | copytree("build", addonPath);
100 |
101 |
102 | if __name__ == '__main__':
103 | copyToBlenderAddons = False
104 | createArchive = False
105 | rebuildLibs = False
106 |
107 | for arg in sys.argv[1:]:
108 | if arg == "-a":
109 | createArchive = True
110 | if arg == "-b":
111 | copyToBlenderAddons = True
112 | if arg == "-l":
113 | rebuildLibs = True
114 |
115 | make(copyToBlenderAddons, createArchive, rebuildLibs)
116 |
117 |
--------------------------------------------------------------------------------
/source/operators/TerrainSculptMeshBrushPanel.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy
17 | from ..kitfox.math.vecmath import *
18 | from ..kitfox.blenderUtil import *
19 | from .Common import *
20 | from .SmoothingInfo import *
21 | from .TerrainSculptMeshProperties import *
22 | from .TerrainSculptMeshBrush import *
23 | from .TerrainHeightPickerMeshOperator import *
24 | from .TerrainSculptWorkspaceTool import *
25 |
26 |
27 | #---------------------------
28 |
29 | class TerrainSculptMeshBrushPanel(bpy.types.Panel):
30 |
31 | """Properties Panel for the Terrain Sculpt Mesh Brush"""
32 | bl_label = "Terrain Sculpt Mesh Brush"
33 | bl_idname = "OBJECT_PT_terrain_sculpt_mesh_brush"
34 | bl_space_type = 'VIEW_3D'
35 | bl_region_type = 'UI'
36 | bl_category = "Kitfox: Terrain"
37 |
38 |
39 | @classmethod
40 | def poll(cls, context):
41 | obj = context.object
42 | return obj != None and (obj.mode == 'OBJECT')
43 |
44 | def draw(self, context):
45 | layout = self.layout
46 |
47 | scene = context.scene
48 | props = scene.terrain_sculpt_mesh_brush_props
49 |
50 | #--------------------------------
51 |
52 | col = layout.column();
53 | col.operator("kitfox.terrain_sculpt_mesh_brush_operator")
54 |
55 | col.prop(props, "radius")
56 | col.prop(props, "inner_radius")
57 | col.prop(props, "radius_relative_to_view")
58 | if props.brush_type == 'RAMP':
59 | col.prop(props, "strength_ramp")
60 | else:
61 | col.prop(props, "strength")
62 | col.prop(props, "use_pressure")
63 | col.prop(props, "terrain_origin")
64 | col.label(text="Brush Type:")
65 | col.prop(props, "brush_type", expand = True, text = "Brush Type")
66 | col.prop(props, "world_shape_type", text = "Land Shape")
67 |
68 | if props.brush_type == 'DRAW':
69 | col.prop(props, "draw_height")
70 | col.operator("kitfox.terrain_height_picker_mesh", text="Terrain height picker", icon="EYEDROPPER")
71 |
72 | if props.brush_type == 'ADD' or props.brush_type == 'SUBTRACT':
73 | col.prop(props, "add_amount")
74 |
75 | if props.brush_type == 'SMOOTH':
76 | col.prop(props, "smooth_edge_snap_distance")
77 |
78 | if props.brush_type == 'SLOPE':
79 | col.prop(props, "use_slope_angle")
80 | if props.use_slope_angle:
81 | col.prop(props, "slope_angle")
82 |
83 | if props.brush_type == 'RAMP':
84 | col.prop(props, "ramp_width")
85 | col.prop(props, "ramp_falloff")
86 |
87 | #---------------------------
88 |
89 |
90 |
91 | def register():
92 |
93 | #Register tools
94 | bpy.utils.register_class(TerrainSculptMeshProperties)
95 | bpy.utils.register_class(TerrainSculptMeshOperator)
96 | bpy.utils.register_class(TerrainHeightPickerMeshOperator)
97 | bpy.utils.register_class(TerrainSculptMeshBrushPanel)
98 |
99 | bpy.types.Scene.terrain_sculpt_mesh_brush_props = bpy.props.PointerProperty(type=TerrainSculptMeshProperties)
100 |
101 | def unregister():
102 | bpy.utils.unregister_class(TerrainSculptMeshProperties)
103 | bpy.utils.unregister_class(TerrainSculptMeshOperator)
104 | bpy.utils.unregister_class(TerrainHeightPickerMeshOperator)
105 | bpy.utils.unregister_class(TerrainSculptMeshBrushPanel)
106 |
107 | del bpy.types.Scene.terrain_sculpt_mesh_brush_props
108 |
109 |
110 | if __name__ == "__main__":
111 | register()
112 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/label.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import sys
21 | #import mathutils
22 | from mathutils import *
23 | import bgl
24 | import blf
25 | import gpu
26 | from gpu_extras.batch import batch_for_shader
27 | from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 | from .graphics import DrawContext2D
32 | from .layout import *
33 | from .panel import *
34 |
35 | #----------------------------------
36 |
37 | class Label(Panel):
38 | def __init__(self, text = "label"):
39 | super().__init__()
40 |
41 | self.position = Vector((0, 0))
42 | self.size = Vector((100, 100))
43 | self.text = text
44 | self.margin = Vector((2, 2, 2, 2))
45 | self.padding = Vector((2, 2, 2, 2))
46 |
47 | self.align_x = AlignX.LEFT
48 | self.align_y = AlignY.TOP
49 |
50 | def set_text(self, value):
51 | self.text = value
52 |
53 | def set_align_x(self, value):
54 | self.align_x = value
55 |
56 | def set_align_y(self, value):
57 | self.align_y = value
58 |
59 | def calc_preferred_size(self):
60 | blf.size(self.font_id, self.font_size, self.font_dpi)
61 |
62 | #Use 'My' to estimate font height
63 | my_w, my_h = blf.dimensions(self.font_id, "My")
64 |
65 | text_w, text_h = blf.dimensions(self.font_id, self.text)
66 | text_h = my_h
67 |
68 | w = text_w
69 | h = text_h
70 |
71 | if self.margin != None:
72 | w += self.margin[0] + self.margin[2]
73 | h += self.margin[1] + self.margin[3]
74 |
75 | if self.padding != None:
76 | w += self.padding[0] + self.padding[2]
77 | h += self.padding[1] + self.padding[3]
78 |
79 | return Vector((w, h))
80 |
81 | def draw_component(self, ctx):
82 | # print("drawing panel")
83 | super().draw_component(ctx)
84 |
85 | blf.size(self.font_id, self.font_size, self.font_dpi)
86 | text_w, text_h = blf.dimensions(self.font_id, self.text)
87 |
88 | bounds = self.bounds()
89 |
90 | # print("bounds " + str(bounds))
91 |
92 | if self.align_x == AlignX.LEFT:
93 | off_x = 0
94 | elif self.align_x == AlignX.CENTER:
95 | off_x = (bounds.width - text_w) / 2
96 | else:
97 | off_x = bounds.width - text_w
98 |
99 | if self.align_y == AlignY.TOP:
100 | off_y = 0
101 | elif self.align_y == AlignY.CENTER:
102 | off_y = (bounds.height - text_h) / 2
103 | else:
104 | off_y = bounds.height - text_h
105 |
106 | x = off_x
107 | y = off_y + text_h
108 |
109 | if self.margin != None:
110 | if self.align_x == AlignX.LEFT:
111 | x += self.margin[0]
112 | elif self.align_x == AlignX.RIGHT:
113 | x -= self.margin[0]
114 |
115 | if self.align_y == AlignY.TOP:
116 | y += self.margin[1]
117 | elif self.align_y == AlignY.BOTTOM:
118 | y -= self.margin[1]
119 |
120 | if self.padding != None:
121 | if self.align_x == AlignX.LEFT:
122 | x += self.padding[0]
123 | elif self.align_y == AlignX.RIGHT:
124 | x -= self.padding[0]
125 |
126 | if self.align_y == AlignY.TOP:
127 | y += self.padding[1]
128 | elif self.align_y == AlignY.BOTTOM:
129 | y -= self.padding[1]
130 |
131 | ctx.set_font_size(self.font_size)
132 | ctx.set_font_dpi(self.font_dpi)
133 | ctx.set_font_color(self.font_color)
134 | ctx.draw_text(self.text, x, y)
135 |
--------------------------------------------------------------------------------
/source/operators/Common.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy
17 | import mathutils
18 | import math
19 | from ..kitfox.math.vecmath import *
20 | from ..kitfox.blenderUtil import *
21 |
22 |
23 | def pick_object(ray_origin, ray_direction):
24 | hit_object = False
25 | best_loc = None
26 | best_normal = None
27 | best_face_idx = None
28 | best_obj = None
29 | best_matrix = None
30 | best_dist_sq = 0
31 |
32 | for obj in bpy.context.selected_objects:
33 | if obj.hide_select:
34 | continue
35 |
36 | l2w = obj.matrix_world
37 | w2l = l2w.inverted()
38 | n2w = w2l.transposed() #normal transform
39 | l_origin = w2l @ ray_origin
40 | l_offPt = w2l @ (ray_origin + ray_direction)
41 | l_direction = l_offPt - l_origin
42 |
43 | #print("testing " + obj.name + " orig " + str(ray_origin) + " dir " + str(ray_direction))
44 |
45 | success, location, normal, poly_index = obj.ray_cast(l_origin, l_direction)
46 | if not success:
47 | continue
48 |
49 | #print("hit " + obj.name)
50 |
51 | dist_sq = (location - l_origin).length_squared
52 |
53 | if not hit_object or dist_sq < best_dist_sq:
54 | hit_object = True
55 | best_loc = l2w @ location
56 | best_normal = (n2w @ normal).normalized()
57 | best_face_idx = poly_index
58 | best_obj = obj
59 | best_matrix = l2w
60 | best_dist_sq = dist_sq
61 |
62 | return (hit_object, best_loc, best_normal, best_face_idx, best_obj, best_matrix)
63 |
64 | #--------------------------------------
65 |
66 | def pick_height(context, event):
67 | mouse_pos = (event.mouse_region_x, event.mouse_region_y)
68 |
69 | ctx = bpy.context
70 |
71 | region = context.region
72 | rv3d = context.region_data
73 |
74 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos)
75 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos)
76 |
77 |
78 | viewlayer = bpy.context.view_layer
79 | #result, location, normal, index, object, matrix = ray_cast(context, viewlayer, ray_origin, view_vector)
80 |
81 | # hit_object, location, normal, face_index, object, matrix = ray_cast_scene(context, viewlayer, ray_origin, view_vector)
82 | hit_object, location, normal, face_index, object, matrix = pick_object(ray_origin, view_vector)
83 |
84 | if hit_object:
85 | #object.matrix_world @
86 | props = context.scene.terrain_sculpt_mesh_brush_props
87 | terrain_origin_obj = props.terrain_origin
88 | world_shape_type = props.world_shape_type
89 |
90 | terrain_origin = vecZero.copy()
91 | if terrain_origin_obj != None:
92 | terrain_origin = terrain_origin_obj.matrix_world.translation
93 |
94 |
95 | offset = location - terrain_origin
96 | down = -offset
97 |
98 | if world_shape_type == 'FLAT':
99 | offset = offset.project(vecZ)
100 | down = -vecZ
101 |
102 | len = offset.magnitude
103 | if offset.dot(down) > 0:
104 | len = -len
105 |
106 | context.scene.terrain_sculpt_mesh_brush_props.draw_height = len
107 |
108 |
109 | context.scene.terrain_sculpt_mesh_brush_props.normal = normal
110 | redraw_all_viewports(context)
111 |
112 |
113 | #Find matrix that will rotate Z axis to point along normal
114 | #coord - point in world space
115 | #normal - normal in world space
116 | def calc_vertex_transform_world(pos, norm):
117 | axis = norm.cross(vecZ)
118 | if axis.length_squared < .0001:
119 | axis = mathutils.Vector(vecX)
120 | else:
121 | axis.normalize()
122 | angle = -math.acos(norm.dot(vecZ))
123 |
124 | quat = mathutils.Quaternion(axis, angle)
125 | mR = quat.to_matrix()
126 | mR.resize_4x4()
127 |
128 | mT = mathutils.Matrix.Translation(pos)
129 |
130 | m = mT @ mR
131 | return m
132 |
--------------------------------------------------------------------------------
/source/operators/TerrainSculptMeshProperties.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy
17 | import bpy.utils.previews
18 | from ..kitfox.math.vecmath import *
19 | from ..kitfox.blenderUtil import *
20 | #from smoothingInfo import *
21 |
22 | class TerrainSculptMeshProperties(bpy.types.PropertyGroup):
23 |
24 | radius : bpy.props.FloatProperty(
25 | name = "Radius",
26 | description = "Radius of brush. Use [, ] keys to adjust.",
27 | default = 1,
28 | min = 0,
29 | soft_max = 4
30 | )
31 |
32 | inner_radius : bpy.props.FloatProperty(
33 | name = "Inner Radius",
34 | description = "Inner Radius of brush. Used for hardness of brush edge. Use Shift plus [, ] keys to adjust.",
35 | default = 0,
36 | min = 0,
37 | max = 1
38 | )
39 |
40 | radius_relative_to_view : bpy.props.BoolProperty(
41 | name = "Radius relative to View",
42 | description = "If true, adjust the brush radius to be proportionate to the viewport.",
43 | default = False
44 | )
45 |
46 | radius_relative_to_view_scale : bpy.props.FloatProperty(
47 | name = "Radius Relative To View Scale",
48 | description = "Fixed adjustment to brush radius when in proportional mode.",
49 | default = .1,
50 | min = 0,
51 | soft_max = 1
52 | )
53 |
54 | strength : bpy.props.FloatProperty(
55 | name = "Strength",
56 | description = "Strength of brush.",
57 | default = 1,
58 | min = 0,
59 | max = 1
60 | )
61 |
62 | strength_ramp : bpy.props.FloatProperty(
63 | name = "Ramp Strength",
64 | description = "Strength for ramp tool.",
65 | default = 1,
66 | min = 0,
67 | soft_max = 1
68 | )
69 |
70 | use_pressure : bpy.props.BoolProperty(
71 | name = "Pen Pressure",
72 | description = "If true, pen pressure is used to adjust strength.",
73 | default = False
74 | )
75 |
76 | terrain_origin : bpy.props.PointerProperty(
77 | name = "Terrain Origin",
78 | description = "Defines the origin point for modes that depend on a distance from the origin. World origin used if not set.",
79 | type = bpy.types.Object
80 | )
81 |
82 | brush_type : bpy.props.EnumProperty(
83 | items=(
84 | ('DRAW', "Draw (D)", "Draw terrain at the given height above the origin."),
85 | ('LEVEL', "Level (L)", "Make terrain the same height as the spot where you first place your brush."),
86 | ('ADD', "Add (A)", "Add to terrain height."),
87 | ('SUBTRACT', "Subtract (S)", "Subtract from terrain height."),
88 | ('SLOPE', "Slope (P)", "Use the slope of the surface under the brush to set height."),
89 | ('SMOOTH', "Smooth (M)", "Average out the terrain under the brush."),
90 | ('RAMP', "Ramp (R)", "Draw a ramp between where you press and release the mouse."),
91 | ),
92 | default='DRAW'
93 | )
94 |
95 | world_shape_type : bpy.props.EnumProperty(
96 | items=(
97 | ('FLAT', "Flat", "Terrain is flat and gravity points along -Z."),
98 | ('SPHERE', "Sphere", "Terrain is sphere shaped (like a planet) and gravity points toward the origin."),
99 | ),
100 | default='FLAT'
101 | )
102 |
103 | use_slope_angle : bpy.props.BoolProperty(
104 | name = "Use Slope Angle",
105 | description = "If true, uses the specified slope angle. Otherwise, slope will be calculated form current terrain slope.",
106 | default = False
107 | )
108 |
109 | slope_angle : bpy.props.FloatProperty(
110 | name = "Slope Angle",
111 | description = "Slope angle to use when drawing slopes.",
112 | default = 45,
113 | soft_min = 0,
114 | soft_max = 90
115 | )
116 |
117 | draw_height : bpy.props.FloatProperty(
118 | name = "Draw Height",
119 | description = "Distance above origin to draw terrain. Use Up, Down arrow to adjust.",
120 | default = 1,
121 | soft_min = 0,
122 | soft_max = 100
123 | )
124 |
125 | add_amount : bpy.props.FloatProperty(
126 | name = "Add Amount",
127 | description = "Amount to add or subtract when those modes are used.",
128 | default = 1,
129 | soft_min = 0,
130 | soft_max = 100
131 | )
132 |
133 | smooth_edge_snap_distance : bpy.props.FloatProperty(
134 | name = "Smooth Snap Distance",
135 | description = "When using the smooth tool with more than one mesh selected, this determines whether vertices in the different meshes are treated as if they're the same vertex. That is, if the two vertices are less than this distance apart when looking in the 'down' direction, they are treated as if they are connected.",
136 | default = .001,
137 | min = 0,
138 | soft_max = .1
139 | )
140 |
141 | ramp_width : bpy.props.FloatProperty(
142 | name = "Ramp Width",
143 | description = "The width of the ramp.",
144 | default = 1,
145 | min = 0,
146 | soft_max = 10
147 | )
148 |
149 | ramp_falloff : bpy.props.FloatProperty(
150 | name = "Ramp Falloff",
151 | description = "Softness of the edge of the ramp.",
152 | default = .2,
153 | min = 0,
154 | max = 1
155 | )
156 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Terrain Sculpting Tool for Blender
2 |
3 | A tool for sculpting in Blender with a focus on terrain. Blender's default sculpting tools are great for character models, but are difficult to use when you're trying to sculpt terrain. This tool suite provides options for leveling ground, creating ramps and constraining your changes to be perpendicular to the ground. It's meant to allow you to quickly block in a terrain in the early stages of your project.
4 |
5 | These tools can be accessed through the **Kitfox - Terrain** panel on the right of the 3D Viewport. You can also access them from the uv unwrap menu (press U while in edit mode).
6 |
7 | ### Basic usage
8 |
9 | Start by creating the mesh for your terrain (for example, a grid mesh that is 100 x 100 units). Make sure you are in Object mode. Select the object and click the **Terrain Brush for Meshes** button in the **Terrain Sculpt Mesh Brush** panel. The tool will start and a pink circle will appear under your mouse cursor. Click and drag on the mesh to sculpt your terrain.
10 |
11 | The tool will also work if you have multiple mesh objects selected. This can be used to create seamless transitions between two meshes.
12 |
13 | You might find that this tool is a bit laggy on larger meshes. The way to deal with that is to subdivide your mesh into smaller pieces. This way the brush only has to recalculate the mesh that is actually under the brush. If you need to draw over the seam between two meshes, just make sure that all meshes you want to draw on are selected before you start the tool.
14 |
15 | ### Terrain Sculpt Mesh Brush
16 |
17 | 
18 |
19 | Use sculpting tools to move vertices to create landscapes.
20 |
21 |
22 | #### Terrain Brush for Meshes
23 | Start the UV Brush tool. Pressing **Enter** will commit your changes, **ESC** will cancel your changes. You can press **Ctrl-Z** to undo a stroke or **Shift-Z** to redo a stroke.
24 |
25 | You will be unable to use the menu panel while the tool is active (this is a current limitation of Blender) - however, there are a number of keyboard shortcuts you can use to adjust to tool while it is running.
26 |
27 | #### Radius
28 | Radius of brush stroke. You can press the **[** and **]** keys to change the radius of the brush.
29 |
30 | #### Inner Radius
31 | Used to adjust the hardness of the brush. The space between the outer and inner radius provides a falloff region for your stroke. You can press the **Shift-[** and **Shift-]** keys to change the inner radius of the brush.
32 |
33 | #### Radius Relative to View
34 |
35 | When checked, the brush will automatically adjust it's size in proportion to how far away it is from the viewer, the same way the sculpting brushes do. Otherwise, the brush will have a fixed size no matter how far from the camera the cursor is.
36 |
37 | #### Strength
38 | Multiplier for the strength of your brush stroke.
39 |
40 | #### Pen Pressure
41 | If checked, the pressure you apply with your stylus will multiply the strength of your brush.
42 |
43 | #### Terrain Origin
44 | By default, the brushes use the world origin as the reference point for all measurements. However, if you would like to choose a different world center, you can specify it here. This is mostly useful for **Sphere** mode where you would like the center of your world to be in the middle of the mesh you are sculpting.
45 |
46 | #### Brush Type
47 |
48 | Select the behavior of the brush you are drawing with. You can press and hold **Shift** at any time to temporarily switch into Smooth mode.
49 |
50 | ##### Draw
51 |
52 | Shortcut **D**.
53 |
54 | Draws terrain under the brush up to the current **Draw Height**. This can be used to create a terraced landscape. Press and hold **Ctrl** to temporarily change the draw brush into the height picker. This can be used to quickly set a new height for your terraces. The **Up Arrow** and **Down Arrow** keys can be used to add and subtract a quarter of the brush radius to the terrain height.
55 |
56 | ##### Level
57 |
58 | Shortcut **L**.
59 |
60 | Same as Draw, but uses the height of the terrain where you start your brush stroke rather than referring to the **Draw Height**.
61 |
62 | ##### Add
63 |
64 | Shortcut **A**.
65 |
66 | Brush strokes will build up on top of existing geometry. Press and hold **Ctrl** to temporarily switch to Subtract mode.
67 |
68 | ##### Subtract
69 |
70 | Shortcut **S**.
71 |
72 | Brush strokes will dig trenches in existing geometry. Press and hold **Ctrl** to temporarily switch to Add mode.
73 |
74 | ##### Slope
75 |
76 | Shortcut **P**.
77 |
78 | Calculates the average slope under the cursor and uses that sloping plane to even out the vertices under it.
79 |
80 | 
81 |
82 | ##### Smooth
83 |
84 | Shortcut **M**.
85 |
86 | Calculates the average height under the cursor and then uses that height to draw a level surface.
87 |
88 |
89 | ##### Ramp
90 |
91 | Shortcut **R**.
92 |
93 | Click and drag from one location to another to create a ramp between those locations.
94 |
95 | 
96 |
97 |
98 | #### Land Shape
99 |
100 | Allows you to switch between Flat and Sphere mode. Flat mode presumes a flat work where down is always in the negative Z direction. Sphere mode is used for drawing on spheres for planet like terrains. In Sphere mode, is always the **Terrain Origin** if you have set is, or the world origin if you have not.
101 |
102 | 
103 |
104 |
105 | #### Draw Height
106 |
107 | In Draw mode, specifies the height above the world origin terrain will be drawn at in Draw mode.
108 |
109 | #### Terrain Height Picker
110 |
111 | Used to pick the terrain height be sampling your scene. Click the button to start the tool and then click a mesh in the viewport to set the new drawing height.
112 |
113 | #### Add Amount
114 |
115 | In Add and Subtract modes, a multiplier that modifies how much is added to subtracted when stroking the brush.
116 |
117 | #### Ramp Width
118 |
119 | In Ramp mode, indicates how wide the ramp you are drawing will be.
120 |
121 | #### Ramp Falloff
122 |
123 | In Ramp mode, indicates how much rounding will be applied to the edges of your ramp.
124 |
125 | #### Use Slope Angle
126 |
127 | By default, the slope tool will try to guess the slope by sampling the slope of the current area under the cursor. If this is checked, you can specify a specific slope for the brush to draw at. (The brush will still sample the area under the cursor to determine the directon the slope should face.)
128 |
129 | #### Slope Angle
130 |
131 | Angle the slope brush will draw at.
132 |
133 | ## Building
134 |
135 | To build, execute the *makeDeploy.py* script in the root of the project. It will create a directory called *deploy* that contains a zip file containing the addon.
136 |
137 | ## Installation
138 |
139 | To install, start Blender and select Edit > Preferences from the menubar. Select the Add-ons tab and then press the Install button. Browse to the .zip file that you built and select it. Finally, tick the checkbox next to Add Mesh: Terrain Sculpting Tools.
140 |
141 | ## Further Information
142 |
143 | This addon is available at the Blender market:
144 | https://github.com/blackears/blenderTerrainSculpt
145 |
146 | A video giving a quick tour of the addon is available here:
147 | [](https://youtu.be/YsFgJ-My7QY)
148 |
149 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/graphics.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import sys
21 | #import mathutils
22 | from mathutils import *
23 | import bgl
24 | import blf
25 | import gpu
26 | from gpu_extras.batch import batch_for_shader
27 | from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 |
32 | vertices = (
33 | (0, 0), (1, 0),
34 | (1, 1), (0, 1))
35 |
36 | # vertices = (
37 | # (100, 100), (300, 100),
38 | # (100, 200), (300, 200))
39 |
40 | # indices = (
41 | # (0, 1, 2), (2, 1, 3))
42 |
43 | shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
44 | #batch = batch_for_shader(shader, 'TRIS', {"pos": vertices}, indices=indices)
45 |
46 | batch = batch_for_shader(shader, 'TRI_FAN', {"pos": vertices})
47 | #batch = batch_for_shader(shader, 'TRI_FAN', {"pos": coordsSquare})
48 |
49 | #----------------------------------
50 |
51 | class DrawContext2D:
52 |
53 | def __init__(self, blender_ctx):
54 | self.blender_ctx = blender_ctx
55 |
56 | self.color = Vector((.5, .5, .5, 1))
57 | self.font_color = Vector((1, 1, 1, 1))
58 | self.font_dpi = 20
59 | self.font_size = 60
60 |
61 | self.transform_stack = []
62 | self.transform_stack.append(Matrix())
63 |
64 | # def set_color(self, color):
65 | # self.color = color
66 |
67 | def set_font_size(self, size):
68 | self.font_size = size
69 |
70 | def set_font_dpi(self, value):
71 | self.font_dpi = value
72 |
73 | def set_font_color(self, value):
74 | self.font_color = value
75 |
76 | def set_color(self, value):
77 | self.color = value
78 |
79 | def coords_to_screen_matrix(self):
80 | region = self.blender_ctx.region
81 | #rv3d = context.region_data
82 |
83 | mT = Matrix.Translation((0, region.height, 0))
84 | mS = Matrix.Diagonal((1, -1, 1, 1))
85 | return mT @ mS
86 |
87 | def push_transform(self):
88 | m = self.transform_stack[-1].copy()
89 | self.transform_stack.append(m)
90 |
91 | def pop_transform(self):
92 | self.transform_stack.pop()
93 |
94 | def transform_matrix(self):
95 | return self.transform_stack[-1]
96 |
97 | def translate(self, x, y):
98 | m = self.transform_stack[-1]
99 | self.transform_stack[-1] = Matrix.Translation(Vector((x, y, 0))) @ m
100 |
101 | # print("after translate " + str(self.transform_stack[-1]))
102 |
103 | def fill_rectangle(self, x, y, width, height):
104 | c2s = self.coords_to_screen_matrix()
105 |
106 | mXform = self.transform_matrix()
107 | mT = Matrix.Translation(Vector((x, y, 0)))
108 | mS = Matrix.Diagonal(Vector((width, height, 1, 1)))
109 |
110 | m = c2s @ mXform @ mT @ mS
111 |
112 | gpu.matrix.push()
113 |
114 | gpu.matrix.multiply_matrix(m)
115 |
116 |
117 | shader.bind()
118 | shader.uniform_float("color", self.color)
119 | batch.draw(shader)
120 |
121 | gpu.matrix.pop()
122 |
123 | def fill_round_rectangle(self, x, y, width, height, radius = 0):
124 | if radius <= 0:
125 | fill_rectangle(x, y, width, height)
126 | return
127 |
128 | c2s = self.coords_to_screen_matrix()
129 |
130 | max_radius = min(width, height) / 2
131 | radius = min(radius, max_radius)
132 |
133 | circle_segs = 8
134 | radian_inc = math.pi / (2 * circle_segs)
135 |
136 | verts = []
137 |
138 | # print ("+++++r rect")
139 |
140 | verts.append((x, y + radius))
141 | verts.append((x, y + height - radius))
142 |
143 | for i in range(1, circle_segs):
144 | xx = radius * math.cos(-radian_inc * i + math.pi) + x + radius
145 | yy = radius * math.sin(-radian_inc * i + math.pi) + y + height - radius
146 | verts.append((xx, yy))
147 | # print("v %f %f" % (xx, yy))
148 |
149 | verts.append((x + radius, y + height))
150 | verts.append((x + width - radius, y + height))
151 |
152 | for i in range(1, circle_segs):
153 | xx = radius * math.cos(-radian_inc * i + math.pi * 1 / 2) + x + width - radius
154 | yy = radius * math.sin(-radian_inc * i + math.pi * 1 / 2) + y + height - radius
155 | verts.append((xx, yy))
156 |
157 | verts.append((x + width, y + height - radius))
158 | verts.append((x + width, y + radius))
159 |
160 | for i in range(1, circle_segs):
161 | xx = radius * math.cos(-radian_inc * i) + x + width - radius
162 | yy = radius * math.sin(-radian_inc * i) + y + radius
163 | verts.append((xx, yy))
164 |
165 | verts.append((x + width - radius, y))
166 | verts.append((x + radius, y))
167 |
168 | for i in range(1, circle_segs):
169 | xx = radius * math.cos(-radian_inc * i + math.pi * 3 / 2) + x + radius
170 | yy = radius * math.sin(-radian_inc * i + math.pi * 3 / 2) + y + radius
171 | verts.append((xx, yy))
172 |
173 |
174 | # print ("-----")
175 | # for v in verts:
176 | # print("v %f %f" % (v[0], v[1]))
177 |
178 | batch_rr = batch_for_shader(shader, 'TRI_FAN', {"pos": verts})
179 |
180 |
181 | mXform = self.transform_matrix()
182 | # mT = Matrix.Translation(Vector((x, y, 0)))
183 | # mS = Matrix.Diagonal(Vector((width, height, 1, 1)))
184 |
185 | # m = c2s @ mXform @ mT @ mS
186 | m = c2s @ mXform
187 |
188 | gpu.matrix.push()
189 |
190 | gpu.matrix.multiply_matrix(m)
191 |
192 |
193 | shader.bind()
194 | shader.uniform_float("color", self.color)
195 | batch_rr.draw(shader)
196 |
197 | gpu.matrix.pop()
198 |
199 | def draw_text(self, text, x, y):
200 | c2s = self.coords_to_screen_matrix()
201 |
202 | mXform = self.transform_matrix()
203 |
204 | font_id = 0 # default font
205 | blf.color(font_id, self.font_color.x, self.font_color.y, self.font_color.z, self.font_color.w)
206 | blf.size(font_id, self.font_size, self.font_dpi)
207 | # text_w, text_h = blf.dimensions(font_id, text)
208 |
209 | screenPos = c2s @ mXform @ Vector((x, y, 0, 1))
210 |
211 | blf.position(font_id, screenPos.x, screenPos.y, 0)
212 | blf.draw(font_id, text)
213 |
214 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/panel.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import sys
21 | #import mathutils
22 | from mathutils import *
23 | import bgl
24 | import blf
25 | import gpu
26 | from gpu_extras.batch import batch_for_shader
27 | from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 | from .graphics import DrawContext2D
32 | from .layout import *
33 |
34 |
35 |
36 | #----------------------------------
37 |
38 | class AlignX(Enum):
39 | LEFT = 1
40 | CENTER = 2
41 | RIGHT = 3
42 |
43 | #----------------------------------
44 |
45 | class AlignY(Enum):
46 | TOP = 1
47 | CENTER = 2
48 | BOTTOM = 3
49 |
50 |
51 | #----------------------------------
52 |
53 | class Panel:
54 | def __init__(self):
55 | self.parent_layout = None
56 | self.background_color = None
57 | self.border_radius = 0
58 | self.border_color = None
59 | self.border_width = 1
60 | # self.background_color = Vector((.5, .5, .5, 1))
61 |
62 | self.font_color = Vector((1, 1, 1, 1))
63 | self.font_dpi = 20
64 | self.font_size = 50
65 | self.font_id = 0
66 |
67 | self.margin = None
68 | self.padding = None
69 | self.layout = None
70 | self.size = Vector((0, 0))
71 | self.maximum_size = Vector((sys.maxsize, sys.maxsize))
72 | self.minimum_size = Vector((0, 0))
73 | self.preferred_size = Vector((0, 0))
74 | self.expansion_type_x = ExpansionType.PREFERRED
75 | self.expansion_type_y = ExpansionType.PREFERRED
76 |
77 | self.position = Vector((0, 0))
78 |
79 | def dump(self, indent = ""):
80 | print(indent + "Panel " + str(self.bounds()))
81 | if self.layout != None:
82 | self.layout.dump(indent + " ")
83 |
84 | def get_parent_layout(self):
85 | return self.parent_layout
86 |
87 | def set_parent_layout(self, value):
88 | self.parent_layout = value
89 |
90 | def set_expansion_x(self, value):
91 | self.expansion_type_x = value
92 |
93 | def set_expansion_y(self, value):
94 | self.expansion_type_y = value
95 |
96 | def set_background_color(self, value):
97 | self.background_color = value
98 |
99 | def set_border_color(self, value):
100 | self.border_color = value
101 |
102 | def set_border_radius(self, value):
103 | self.border_radius = value
104 |
105 | def set_border_width(self, value):
106 | self.border_width = value
107 |
108 | def set_font_size(self, size):
109 | self.font_size = size
110 |
111 | def set_font_dpi(self, value):
112 | self.font_dpi = value
113 |
114 | def set_font_color(self, value):
115 | self.font_color = value
116 |
117 | def layout_components(self):
118 | if self.layout != None:
119 | self.layout.layout_components(self.bounds())
120 |
121 | def set_layout(self, layout):
122 | self.layout = layout
123 | layout.set_parent(self)
124 |
125 | def bounds(self):
126 | return Rectangle2D(self.position.x, self.position.y, self.size.x, self.size.y)
127 |
128 | def bounds_world(self):
129 | if parent_layout != None:
130 | window = parent_layout.get_window()
131 | if window != None:
132 | pass
133 |
134 | parent = parent_layout.get_parent()
135 | if parent != None:
136 | parent.position
137 | return Rectangle2D(self.position.x, self.position.y, self.size.x, self.size.y)
138 |
139 | def calc_minimum_size(self):
140 | # print("calc_minimum_size")
141 |
142 | if self.layout != None:
143 | layout_size = self.layout.calc_minimum_size()
144 | # print("layout_size " + str(layout_size))
145 | return Vector((max(layout_size.x, self.minimum_size.x), max(layout_size.y, self.minimum_size.y)))
146 | # print("layout_size " + str(layout_size))
147 |
148 | else:
149 | return self.minimum_size
150 |
151 | def calc_preferred_size(self):
152 | if self.layout != None:
153 | layout_size = self.layout.calc_preferred_size()
154 | return Vector((max(layout_size.x, self.preferred_size.x), max(layout_size.y, self.preferred_size.y)))
155 |
156 | else:
157 | return self.preferred_size
158 |
159 | def calc_maximum_size(self):
160 | if self.layout != None:
161 | layout_size = self.layout.calc_maximum_size()
162 | return Vector((max(layout_size.x, self.maximum_size.x), max(layout_size.y, self.maximum_size.y)))
163 |
164 | else:
165 | return self.maximum_size
166 |
167 | def draw(self, ctx):
168 | ctx.push_transform()
169 | ctx.translate(self.position.x, self.position.y)
170 |
171 | self.draw_component(ctx)
172 |
173 | if self.layout != None:
174 | self.layout.draw(ctx)
175 |
176 | ctx.pop_transform()
177 |
178 | def draw_component(self, ctx):
179 | if self.background_color != None:
180 | x = 0
181 | y = 0
182 | w = self.size[0]
183 | h = self.size[1]
184 |
185 | if self.margin != None:
186 | x += self.margin[0]
187 | y += self.margin[1]
188 | w -= self.margin[0] + self.margin[2]
189 | h -= self.margin[1] + self.margin[3]
190 |
191 | # if self.padding != None:
192 | # x -= self.padding[0] + self.padding[2]
193 | # y -= self.padding[1] + self.padding[3]
194 |
195 | ctx.set_color(self.background_color)
196 | ctx.fill_round_rectangle(x, y, w, h, self.border_radius)
197 |
198 | def handle_event_dispatch(self, context, event):
199 | if self.layout != None:
200 | result = self.layout.handle_event(context_event)
201 | if result:
202 | return True
203 |
204 | return handle_event(context, event)
205 |
206 | # def handle_event(self, context, event):
207 | # return False
208 |
209 | def get_screen_position(self):
210 | pos = self.position.copy()
211 |
212 | if self.parent_layout != None:
213 | pos += self.parent_layout.get_screen_position()
214 |
215 | return pos
216 |
217 | def get_parent_panel():
218 | if self.parent_layout != None:
219 | return self.parnt_layout.get_parent()
220 | return None
221 |
222 | #Get the child panel that exists at the given position
223 | def pick_panel_stack(self, pos):
224 | if self.layout != None:
225 | return self.layout.pick_panel_stack(pos)
226 |
227 | return []
228 |
229 |
230 | def mouse_pressed(self, event):
231 | # if self.layout != None:
232 | # result = self.layout.mouse_pressed(event)
233 | # if result:
234 | # return True
235 |
236 | return False
237 |
238 | def mouse_released(self, event):
239 | # if self.layout != None:
240 | # result = self.layout.mouse_released(event)
241 | # if result:
242 | # return True
243 |
244 | return False
245 |
246 | def mouse_moved(self, event):
247 | # if self.layout != None:
248 | # result = self.layout.mouse_moved(event)
249 | # if result:
250 | # return True
251 |
252 | return False
253 |
254 | def mouse_dragged(self, event):
255 | # if self.layout != None:
256 | # result = self.layout.mouse_dragged(event)
257 | # if result:
258 | # return True
259 |
260 | return False
261 |
262 |
263 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/layout.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import sys
21 | #import mathutils
22 | from mathutils import *
23 | import bgl
24 | import blf
25 | import gpu
26 | from gpu_extras.batch import batch_for_shader
27 | from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 | from .graphics import DrawContext2D
32 |
33 |
34 |
35 | #----------------------------------
36 | class Size2D:
37 | def __init__(width = 0, height = 0):
38 | self.width = width
39 | self.height = height
40 |
41 | #----------------------------------
42 |
43 | class Rectangle2D:
44 | def __init__(self, x = 0, y = 0, width = 0, height = 0):
45 | self.x = x
46 | self.y = y
47 | self.width = width
48 | self.height = height
49 |
50 | def contains(self, x, y):
51 | return x >= self.x and x < self.x + self.width and y >= self.y and y < self.y + self.height
52 |
53 | def __str__(self):
54 | return str(self.x) + ", " + str(self.y) + ", " + str(self.width) + ", " + str(self.height)
55 |
56 |
57 |
58 | #----------------------------------
59 |
60 | class Layout:
61 |
62 | def __init__(self):
63 | self.parent = None
64 | self.window = None
65 |
66 | def get_parent(self):
67 | return self.parent
68 |
69 | def set_parent(self, parent):
70 | self.parent = parent
71 |
72 | def get_window(self):
73 | return self.window
74 |
75 | def set_window(self, window):
76 | self.window = window
77 |
78 | def layout_components(self, bounds):
79 | pass
80 |
81 | def draw(self, ctx):
82 | pass
83 |
84 | def handle_event(self, context, event):
85 | return False
86 |
87 | def get_screen_position(self):
88 | if self.parent != None:
89 | return self.parent.get_screen_position()
90 | elif self.window != None:
91 | return self.window.get_screen_position()
92 | return Vector((0, 0))
93 |
94 | def mouse_pressed(self, event):
95 | return False
96 |
97 | def mouse_released(self, event):
98 | return False
99 |
100 | def mouse_moved(self, event):
101 | return False
102 |
103 | #----------------------------------
104 |
105 | class LayoutAxis(Enum):
106 | X = 1
107 | Y = 2
108 | #----------------------------------
109 |
110 | class ExpansionType(Enum):
111 | EXPAND = 1
112 | PREFERRED = 2
113 | # MIN = 3
114 | # MAX = 4
115 |
116 |
117 | #----------------------------------
118 |
119 |
120 | class LayoutBox(Layout):
121 | class Info:
122 | def __init__(self):
123 | self.span = 0
124 |
125 |
126 | def __init__(self, axis = Axis.X):
127 | super().__init__()
128 |
129 | self.axis = axis
130 | self.children = []
131 |
132 | def dump(self, indent = ""):
133 | print(indent + "LayoutBox " + str(self.axis))
134 |
135 | for child in self.children:
136 | child.dump(indent + " ")
137 |
138 |
139 | def add_child(self, child):
140 | self.children.append(child)
141 | child.set_parent_layout(self)
142 |
143 | def handle_event(self, context, event):
144 | for child in self.children:
145 | result = child.handle_event_dispatch(context, event)
146 | if result:
147 | return True
148 |
149 | return False
150 |
151 | def calc_minimum_size(self):
152 | span_x = 0
153 | span_y = 0
154 |
155 | for child in self.children:
156 | size = child.calc_minimum_size()
157 |
158 | if self.axis == Axis.X:
159 | span_x += size.x
160 | span_y = max(span_y, size.y)
161 | else:
162 | span_x = max(span_x, size.x)
163 | span_y += size.y
164 |
165 | return Vector((span_x, span_y))
166 |
167 | def calc_preferred_size(self):
168 | span_x = 0
169 | span_y = 0
170 |
171 | for child in self.children:
172 | size = child.calc_preferred_size()
173 |
174 | if self.axis == Axis.X:
175 | span_x += size.x
176 | span_y = max(span_y, size.y)
177 | else:
178 | span_x = max(span_x, size.x)
179 | span_y += size.y
180 |
181 | return Vector((span_x, span_y))
182 |
183 |
184 | def calc_maximum_size(self):
185 | span_x = 0
186 | span_y = 0
187 |
188 | for child in self.children:
189 | size = child.calc_maximum_size()
190 |
191 | if self.axis == Axis.X:
192 | span_x += size.x
193 | span_y = max(span_y, size.y)
194 | else:
195 | span_x = max(span_x, size.x)
196 | span_y += size.y
197 |
198 | return Vector((span_x, span_y))
199 |
200 |
201 | def layout_components(self, bounds):
202 | local_span = bounds.width if self.axis == Axis.X else bounds.height
203 |
204 | infoList = []
205 | total_span = 0
206 |
207 |
208 | #Allocate min sizes first
209 | # print("calc min")
210 | for i in range(len(self.children)):
211 | child = self.children[i]
212 | size = child.calc_minimum_size()
213 |
214 | info = self.Info()
215 | infoList.append(info)
216 | info.span = size.x if self.axis == Axis.X else size.y
217 | total_span += info.span
218 |
219 | # print("child %d: span %d" % (i, info.span))
220 |
221 | #Expand to preferred sizes if there is room
222 | # print("calc pref")
223 | for i in range(len(self.children)):
224 | if total_span < local_span:
225 | child = self.children[i]
226 | size = child.calc_preferred_size()
227 | pref_span = size.x if self.axis == Axis.X else size.y
228 | span_remaining = local_span - total_span
229 |
230 | # print("span_remaining " + str(span_remaining))
231 | # print("pref_span " + str(pref_span))
232 |
233 | info = infoList[i]
234 | # print("info.span " + str(info.span))
235 | span_to_add = min(span_remaining, pref_span - info.span)
236 | info.span += span_to_add
237 | total_span += span_to_add
238 |
239 | # print("child %d: span %d" % (i, info.span))
240 |
241 | #If there is space left, expand children with expand set
242 | # print("calc max")
243 | # print("local_span " + str(local_span))
244 | # print("total_span " + str(total_span))
245 | for i in range(len(self.children)):
246 | if total_span < local_span:
247 | child = self.children[i]
248 | info = infoList[i]
249 | # print("info.span " + str(info.span))
250 |
251 | if (self.axis == Axis.X and child.expansion_type_x == ExpansionType.EXPAND) or (self.axis == Axis.Y and child.expansion_type_y == ExpansionType.EXPAND):
252 | size = child.calc_maximum_size()
253 | max_span = size.x if self.axis == Axis.X else size.y
254 |
255 | expand_to = min(max_span, local_span - total_span + info.span)
256 |
257 | # print("max_span " + str(max_span))
258 | # print("expand_to " + str(expand_to))
259 |
260 | # info = infoList[i]
261 | # print("info.span " + str(info.span))
262 |
263 | span_to_add = expand_to - info.span
264 | info.span += span_to_add
265 | total_span += span_to_add
266 |
267 | # print("child %d: span %d" % (i, info.span))
268 |
269 | #Apply sizes
270 | cursor_offset = 0
271 | for i in range(len(self.children)):
272 | child = self.children[i]
273 | info = infoList[i]
274 |
275 | if self.axis == Axis.X:
276 | child.position.x = cursor_offset
277 | child.position.y = 0
278 | child.size.x = info.span
279 | child.size.y = bounds.height
280 | else:
281 | child.position.x = 0
282 | child.position.y = cursor_offset
283 | child.size.x = bounds.width
284 | child.size.y = info.span
285 |
286 | child.layout_components()
287 |
288 | cursor_offset += info.span
289 |
290 | def draw(self, ctx):
291 | for child in self.children:
292 | child.draw(ctx)
293 |
294 | def pick_panel_stack(self, pos):
295 | for child in self.children:
296 | child_pos = child.position
297 |
298 | #Bounds relative to parent
299 | bounds = child.bounds()
300 |
301 | # print ("testing bounds " + str(bounds))
302 | if bounds.contains(pos[0], pos[1]):
303 | # print ("bounds test passed")
304 |
305 | rel_pos = pos - child_pos
306 | result = child.pick_panel_stack(rel_pos)
307 |
308 | # if result:
309 | # return True
310 | result.insert(0, child)
311 | return result
312 |
313 | return []
314 |
315 | def mouse_pressed(self, event):
316 | # print ("layout mouse_pressed")
317 | # print ("in event " + str(event))
318 |
319 | for child in self.children:
320 | pos = child.position
321 |
322 | #Bounds relative to parent
323 | bounds = child.bounds()
324 |
325 | # print ("testing bounds " + str(bounds))
326 | if bounds.contains(event.pos[0], event.pos[1]):
327 | # print ("bounds test passed")
328 |
329 | evt = event.copy()
330 | evt.pos -= pos
331 | result = child.mouse_pressed(evt)
332 |
333 | if result:
334 | return True
335 |
336 | return False
337 |
338 | def mouse_released(self, event):
339 | for child in self.children:
340 | pos = child.position
341 |
342 | #Bounds relative to parent
343 | bounds = child.bounds()
344 | if bounds.contains(event.pos[0], event.pos[1]):
345 |
346 | evt = event.copy()
347 | evt.pos -= pos
348 | result = child.mouse_released(evt)
349 | if result:
350 | return True
351 |
352 | return False
353 |
354 | def mouse_moved(self, event):
355 | for child in self.children:
356 | pos = child.position
357 |
358 | #Bounds relative to parent
359 | bounds = child.bounds()
360 | if bounds.contains(event.pos[0], event.pos[1]):
361 |
362 | evt = event.copy()
363 | evt.pos -= pos
364 | result = child.mouse_moved(evt)
365 | if result:
366 | return True
367 |
368 | return False
369 |
--------------------------------------------------------------------------------
/lib/kitfox/gui/window.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import bpy
20 | import sys
21 | #import mathutils
22 | from mathutils import *
23 | import bgl
24 | import blf
25 | import gpu
26 | from gpu_extras.batch import batch_for_shader
27 | from ..math.vecmath import *
28 |
29 | from enum import Enum
30 |
31 | from .graphics import DrawContext2D
32 | from .layout import *
33 | from .panel import *
34 | from .label import *
35 | from .events import *
36 |
37 | #----------------------------------
38 |
39 | # class Inset2D:
40 | # def __init__(self, left = 0, top = 0, right = 0, bottom = 0):
41 | # self.left = left
42 | # self.top = top
43 | # self.right = right
44 | # self.bottom = bottom
45 |
46 | # def __str__(self):
47 | # return str(self.left) + ", " + str(self.top) + ", " + str(self.right) + ", " + str(self.bottom)
48 |
49 |
50 |
51 |
52 |
53 |
54 | #----------------------------------
55 |
56 | class FoldoutPanel(Panel):
57 | def __init__(self):
58 | super().__init__()
59 | self.position = Vector((0, 0))
60 |
61 |
62 |
63 | #----------------------------------
64 |
65 | class TitleBar(Label):
66 | def __init__(self, window):
67 | super().__init__()
68 | self.window = window
69 | self.dragging = False
70 |
71 |
72 | def mouse_pressed(self, event):
73 | if event.mouse_button == MouseButton.LEFT:
74 | self.dragging = True
75 | self.drag_start = event.screen_pos
76 | self.window_start = self.window.position.copy()
77 |
78 | # print ("TextINput pressed")
79 | # print("event.pos" + str(event.pos))
80 | # print("event.screen_pos" + str(event.screen_pos))
81 | return True
82 |
83 | def mouse_released(self, event):
84 | if event.mouse_button == MouseButton.LEFT:
85 | self.dragging = False
86 |
87 | # print ("TextINput released")
88 | # print("event.pos" + str(event.pos))
89 | # print("event.screen_pos" + str(event.screen_pos))
90 | return True
91 |
92 | def mouse_dragged(self, event):
93 | if self.dragging:
94 | offset = event.screen_pos - self.drag_start
95 | self.window.position = self.window_start + offset
96 |
97 | return True
98 |
99 |
100 | # def mouse_click(self, context, event):
101 | # c2s = self.coords_to_screen_matrix(context)
102 | # s2c = c2s.inverted()
103 | # mouse_pos = s2c @ Vector((event.mouse_region_x, event.mouse_region_y, 0, 1))
104 |
105 | # # print ("event.mouse_region_x " + str(event.mouse_region_x))
106 | # # print ("event.mouse_region_y " + str(event.mouse_region_y))
107 | # # print ("mouse_pos " + str(mouse_pos))
108 |
109 | # bounds = self.bounds()
110 |
111 | # # print ("bounds " + str(bounds))
112 |
113 | # if bounds.contains(mouse_pos.x, mouse_pos.y):
114 | # if event.value == "PRESS":
115 | # self.layout.dispatch_mouse_event
116 |
117 | # self.dragging = True
118 | # self.mouse_down_pos = mouse_pos
119 | # self.start_position = self.position.copy()
120 | # else:
121 | # self.dragging = False
122 | # # return {'consumed': True}
123 | # return True
124 |
125 | # # return {'consumed': False}
126 | # return False
127 |
128 | # def mouse_move(self, context, event):
129 | # c2s = self.coords_to_screen_matrix(context)
130 | # s2c = c2s.inverted()
131 | # mouse_pos = s2c @ Vector((event.mouse_region_x, event.mouse_region_y, 0, 1))
132 |
133 |
134 | # if self.dragging:
135 | # offset = mouse_pos - self.mouse_down_pos
136 |
137 | # self.position = self.start_position + offset.to_2d()
138 | # # return {'consumed': True}
139 | # return True
140 |
141 | # # return {'consumed': False}
142 | # return False
143 |
144 |
145 | #----------------------------------
146 |
147 | class PanelStack:
148 | def __init__(self, stack):
149 | self.stack = stack
150 |
151 | # def add(self, panel):
152 | # self.stack.append(panel)
153 |
154 | def window_to_local(self, window_pos):
155 | local_pos = window_pos.copy()
156 | for panel in self.stack:
157 | local_pos -= panel.position
158 | return local_pos
159 |
160 | def __str__(self):
161 | strn = ""
162 | for panel in self.stack:
163 | strn += "panel bounds " + str(panel.bounds()) + "\n"
164 | return strn
165 |
166 | #----------------------------------
167 |
168 | class Window:
169 | def __init__(self):
170 | self.position = Vector((100, 40))
171 | self.size = Vector((200, 400))
172 |
173 | self.background_color = Vector((.5, .5, .5, 1))
174 | self.font_color = Vector((1, 1, 1, 1))
175 | self.font_dpi = 20
176 | self.font_size = 60
177 |
178 | self.dragging = False
179 |
180 | self.layout = LayoutBox(Axis.Y)
181 | self.layout.set_window(self)
182 |
183 | self.title_panel = TitleBar(self)
184 | self.layout.add_child(self.title_panel)
185 | self.title_panel.set_font_size(60)
186 |
187 | self.main_panel = Panel()
188 | self.layout.add_child(self.main_panel)
189 | self.main_panel.expansion_type_x = ExpansionType.EXPAND
190 | self.main_panel.expansion_type_y = ExpansionType.EXPAND
191 |
192 |
193 | self.layout.layout_components(self.bounds())
194 |
195 | #Track mouse press events
196 | self.captured_panel_stack = None
197 | self.mouse_left_down = False
198 | self.mouse_middle_down = False
199 | self.mouse_right_down = False
200 |
201 |
202 | def get_title(self):
203 | return self.__title
204 |
205 | def set_title(self, title):
206 | self.__title = title
207 | self.title_panel.text = title
208 |
209 | def get_main_panel(self):
210 | return self.main_panel
211 |
212 | def get_screen_position(self):
213 | return self.position.copy()
214 |
215 | def bounds(self):
216 | return Rectangle2D(self.position.x, self.position.y, self.size.x, self.size.y)
217 |
218 | def coords_to_screen_matrix(self, context):
219 | region = context.region
220 | #rv3d = context.region_data
221 |
222 | mT = Matrix.Translation((0, region.height, 0))
223 | mS = Matrix.Diagonal((1, -1, 1, 1))
224 | return mT @ mS
225 |
226 |
227 | def draw(self, context):
228 | bgl.glDisable(bgl.GL_DEPTH_TEST)
229 |
230 | ctx = DrawContext2D(context)
231 |
232 | ctx.translate(self.position.x, self.position.y)
233 | ctx.color = self.background_color.copy()
234 | ctx.fill_round_rectangle(0, 0, self.size.x, self.size.y, 10)
235 |
236 | #Draw panel components
237 | self.layout.draw(ctx)
238 |
239 |
240 | def mouse_pos(self, context, event):
241 | c2s = self.coords_to_screen_matrix(context)
242 | s2c = c2s.inverted()
243 | screen_pos = s2c @ Vector((event.mouse_region_x, event.mouse_region_y, 0, 1))
244 | return screen_pos.to_2d()
245 |
246 | def window_to_local(self, window_pos):
247 | local_pos = window_pos.copy()
248 | for panel in stack:
249 | local_pos -= panel.position
250 | return local_pos
251 |
252 | def handle_event(self, context, event):
253 | bounds = self.bounds()
254 |
255 | # print("event typ:" + event.type + " val: " + event.value)
256 |
257 | mouse_button = None
258 |
259 | if event.type == 'LEFTMOUSE':
260 | mouse_button = MouseButton.LEFT
261 |
262 | if event.value == "PRESS":
263 | self.mouse_left_down = True
264 | elif event.value == "RELEASE":
265 | self.mouse_left_down = False
266 |
267 | if event.type == 'RIGHTMOUSE':
268 | mouse_button = MouseButton.RIGHT
269 |
270 | if event.value == "PRESS":
271 | self.mouse_right_down = True
272 | elif event.value == "RELEASE":
273 | self.mouse_right_down = False
274 |
275 | if event.type == 'MIDDLEMOUSE':
276 | mouse_button = MouseButton.MIDDLE
277 |
278 | if event.value == "PRESS":
279 | self.mouse_middle_down = True
280 | elif event.value == "RELEASE":
281 | self.mouse_middle_down = False
282 |
283 |
284 | if mouse_button != None:
285 | mouse_pos = self.mouse_pos(context, event)
286 | mouse_window_pos = mouse_pos - self.position
287 |
288 | if self.captured_panel_stack != None:
289 |
290 | # print("panel stack is captured")
291 |
292 | if event.value == "RELEASE":
293 | # print("RELEASE stack \n" + str(self.captured_panel_stack))
294 |
295 | local_pos = self.captured_panel_stack.window_to_local(mouse_window_pos)
296 | evt = MouseButtonEvent(
297 | mouse_button = mouse_button,
298 | pos = local_pos,
299 | screen_pos = mouse_pos,
300 | left_down = self.mouse_left_down,
301 | middle_down = self.mouse_middle_down,
302 | right_down = self.mouse_right_down,
303 | shift_down = event.shift,
304 | ctrl_down = event.ctrl,
305 | alt_down = event.alt
306 | )
307 |
308 | self.captured_panel_stack.stack[-1].mouse_released(evt)
309 |
310 | # print("self.mouse_left_down" + str(self.mouse_left_down))
311 | # print("self.mouse_right_down" + str(self.mouse_right_down))
312 |
313 | #If all buttons are released, end mouse capture
314 | if self.mouse_left_down == False and self.mouse_middle_down == False and self.mouse_right_down == False:
315 | # print("END capture")
316 | self.captured_panel_stack = None
317 |
318 | return True
319 |
320 | elif bounds.contains(mouse_pos[0], mouse_pos[1]):
321 | #evt = MouseButtonEvent(mouse_button = MouseButton.LEFT, pos = mouse_pos - self.position, screen_pos = mouse_pos)
322 |
323 | if event.value == "PRESS":
324 | stack = self.layout.pick_panel_stack(mouse_window_pos)
325 | self.captured_panel_stack = PanelStack(stack)
326 |
327 |
328 | # print("self.captured_panel_stack \n" + str(self.captured_panel_stack))
329 |
330 | local_pos = self.captured_panel_stack.window_to_local(mouse_window_pos)
331 | evt = MouseButtonEvent(
332 | mouse_button = mouse_button,
333 | pos = local_pos,
334 | screen_pos = mouse_pos,
335 | left_down = self.mouse_left_down,
336 | middle_down = self.mouse_middle_down,
337 | right_down = self.mouse_right_down,
338 | shift_down = event.shift,
339 | ctrl_down = event.ctrl,
340 | alt_down = event.alt
341 | )
342 | self.captured_panel_stack.stack[-1].mouse_pressed(evt)
343 |
344 | return True
345 |
346 |
347 | elif event.type == 'MOUSEMOVE':
348 | mouse_pos = self.mouse_pos(context, event)
349 | mouse_window_pos = mouse_pos - self.position
350 |
351 | if self.captured_panel_stack != None:
352 | # print("mouse DRAG")
353 | local_pos = self.captured_panel_stack.window_to_local(mouse_window_pos)
354 | evt = MouseButtonEvent(
355 | pos = local_pos,
356 | screen_pos = mouse_pos,
357 | left_down = self.mouse_left_down,
358 | middle_down = self.mouse_middle_down,
359 | right_down = self.mouse_right_down,
360 | shift_down = event.shift,
361 | ctrl_down = event.ctrl,
362 | alt_down = event.alt
363 | )
364 |
365 | self.captured_panel_stack.stack[-1].mouse_dragged(evt)
366 |
367 | return True
368 |
369 | elif bounds.contains(mouse_pos[0], mouse_pos[1]):
370 | # print("mouse MOVE")
371 | stack = self.layout.pick_panel_stack(mouse_window_pos)
372 | stack = PanelStack(stack)
373 |
374 | local_pos = stack.window_to_local(mouse_window_pos)
375 | evt = MouseButtonEvent(
376 | pos = local_pos,
377 | screen_pos = mouse_pos,
378 | left_down = self.mouse_left_down,
379 | middle_down = self.mouse_middle_down,
380 | right_down = self.mouse_right_down,
381 | shift_down = event.shift,
382 | ctrl_down = event.ctrl,
383 | alt_down = event.alt
384 | )
385 | stack.stack[-1].mouse_moved(evt)
386 |
387 | return True
388 |
389 | return False
390 |
391 |
--------------------------------------------------------------------------------
/lib/kitfox/math/vecmath.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Blender Common distribution (https://github.com/blackears/blenderCommon).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software; you can redistribute it and/or
5 | # modify it under the terms of the GNU Lesser General Public
6 | # License as published by the Free Software Foundation; either
7 | # version 3 of the License, or (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 | # Lesser General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU Lesser General Public License
15 | # along with this program; if not, write to the Free Software Foundation,
16 | # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 |
18 |
19 | import mathutils
20 | import math
21 | from bpy_extras import view3d_utils
22 | from enum import Enum
23 | import numpy as np
24 |
25 |
26 | vecX = mathutils.Vector((1, 0, 0))
27 | vecY = mathutils.Vector((0, 1, 0))
28 | vecZ = mathutils.Vector((0, 0, 1))
29 | vecZero = mathutils.Vector((0, 0, 0))
30 |
31 | circleSegs = 64
32 | coordsCircle = [(math.sin(((2 * math.pi * i) / circleSegs)), math.cos((math.pi * 2 * i) / circleSegs), 0) for i in range(circleSegs + 1)]
33 |
34 | coordsSquare = [(0, 0, 0), (1, 0, 0),
35 | (1, 1, 0), (0, 1, 0)
36 | ]
37 |
38 | coordsSquare_strip = [(0, 0, 0), (1, 0, 0),
39 | (1, 1, 0), (0, 1, 0),
40 | (0, 0, 0)
41 | ]
42 |
43 | coordsSquare2_strip = [(-1, -1, 0), (1, -1, 0),
44 | (1, 1, 0), (-1, 1, 0),
45 | (-1, -1, 0)
46 | ]
47 |
48 |
49 | coordsCube = [(0, 0, 0), (1, 0, 0),
50 | (1, 0, 0), (1, 1, 0),
51 | (1, 1, 0), (0, 1, 0),
52 | (0, 1, 0), (0, 0, 0),
53 |
54 | (0, 0, 0), (0, 0, 1),
55 | (1, 0, 0), (1, 0, 1),
56 | (1, 1, 0), (1, 1, 1),
57 | (0, 1, 0), (0, 1, 1),
58 |
59 | (0, 0, 1), (1, 0, 1),
60 | (1, 0, 1), (1, 1, 1),
61 | (1, 1, 1), (0, 1, 1),
62 | (0, 1, 1), (0, 0, 1),
63 | ]
64 |
65 | cubeVerts = [(0, 0, 0),
66 | (1, 0, 0),
67 | (0, 1, 0),
68 | (1, 1, 0),
69 | (0, 0, 1),
70 | (1, 0, 1),
71 | (0, 1, 1),
72 | (1, 1, 1),
73 | ]
74 |
75 | cubeFaces = [(2, 3, 1, 0),
76 | (4, 5, 7, 6),
77 | (0, 1, 5, 4),
78 | (6, 7, 3, 2),
79 | (1, 3, 7, 5),
80 | (2, 0, 4, 6),
81 | ]
82 |
83 | cubeUvs = [
84 | ((0, 0), (1, 0), (1, 1), (0, 1)),
85 | ((0, 0), (1, 0), (1, 1), (0, 1)),
86 | ((0, 0), (1, 0), (1, 1), (0, 1)),
87 | ((0, 0), (1, 0), (1, 1), (0, 1)),
88 | ((0, 0), (1, 0), (1, 1), (0, 1)),
89 | ((0, 0), (1, 0), (1, 1), (0, 1))
90 | ]
91 |
92 | def unitCube():
93 | coords = []
94 | normals = []
95 | uvs = []
96 |
97 | v000 = mathutils.Vector((-1, -1, -1))
98 | v100 = mathutils.Vector((1, -1, -1))
99 | v010 = mathutils.Vector((-1, 1, -1))
100 | v110 = mathutils.Vector((1, 1, -1))
101 | v001 = mathutils.Vector((-1, -1, 1))
102 | v101 = mathutils.Vector((1, -1, 1))
103 | v011 = mathutils.Vector((-1, 1, 1))
104 | v111 = mathutils.Vector((1, 1, 1))
105 |
106 | nx0 = mathutils.Vector((-1, 0, 0))
107 | nx1 = mathutils.Vector((1, 0, 0))
108 | ny0 = mathutils.Vector((0, -1, 0))
109 | ny1 = mathutils.Vector((0, 1, 0))
110 | nz0 = mathutils.Vector((0, 0, -1))
111 | nz1 = mathutils.Vector((0, 0, 1))
112 |
113 | uv00 = mathutils.Vector((0, 0))
114 | uv10 = mathutils.Vector((1, 0))
115 | uv01 = mathutils.Vector((0, 1))
116 | uv11 = mathutils.Vector((1, 1))
117 |
118 | #Face -x
119 | coords.append(v010)
120 | coords.append(v000)
121 | coords.append(v001)
122 |
123 | coords.append(v010)
124 | coords.append(v001)
125 | coords.append(v011)
126 |
127 | for i in range(6):
128 | normals.append(nx0)
129 |
130 | uvs.append(uv00)
131 | uvs.append(uv10)
132 | uvs.append(uv11)
133 | uvs.append(uv00)
134 | uvs.append(uv11)
135 | uvs.append(uv01)
136 |
137 |
138 | #Face +x
139 | coords.append(v100)
140 | coords.append(v110)
141 | coords.append(v111)
142 |
143 | coords.append(v100)
144 | coords.append(v111)
145 | coords.append(v101)
146 |
147 | for i in range(6):
148 | normals.append(nx1)
149 |
150 | uvs.append(uv00)
151 | uvs.append(uv10)
152 | uvs.append(uv11)
153 | uvs.append(uv00)
154 | uvs.append(uv11)
155 | uvs.append(uv01)
156 |
157 | #Face -y
158 | coords.append(v000)
159 | coords.append(v100)
160 | coords.append(v101)
161 |
162 | coords.append(v000)
163 | coords.append(v101)
164 | coords.append(v001)
165 |
166 | for i in range(6):
167 | normals.append(ny0)
168 |
169 | uvs.append(uv00)
170 | uvs.append(uv10)
171 | uvs.append(uv11)
172 | uvs.append(uv00)
173 | uvs.append(uv11)
174 | uvs.append(uv01)
175 |
176 |
177 | #Face +y
178 | coords.append(v110)
179 | coords.append(v010)
180 | coords.append(v011)
181 |
182 | coords.append(v110)
183 | coords.append(v011)
184 | coords.append(v111)
185 |
186 | for i in range(6):
187 | normals.append(ny1)
188 |
189 | uvs.append(uv00)
190 | uvs.append(uv10)
191 | uvs.append(uv11)
192 | uvs.append(uv00)
193 | uvs.append(uv11)
194 | uvs.append(uv01)
195 |
196 |
197 | #Face -z
198 | coords.append(v010)
199 | coords.append(v110)
200 | coords.append(v100)
201 |
202 | coords.append(v010)
203 | coords.append(v100)
204 | coords.append(v000)
205 |
206 | for i in range(6):
207 | normals.append(nz0)
208 |
209 | uvs.append(uv00)
210 | uvs.append(uv10)
211 | uvs.append(uv11)
212 | uvs.append(uv00)
213 | uvs.append(uv11)
214 | uvs.append(uv01)
215 |
216 |
217 | #Face +z
218 | coords.append(v001)
219 | coords.append(v101)
220 | coords.append(v111)
221 |
222 | coords.append(v001)
223 | coords.append(v111)
224 | coords.append(v011)
225 |
226 | for i in range(6):
227 | normals.append(nz1)
228 |
229 | uvs.append(uv00)
230 | uvs.append(uv10)
231 | uvs.append(uv11)
232 | uvs.append(uv00)
233 | uvs.append(uv11)
234 | uvs.append(uv01)
235 |
236 | return (coords, normals, uvs)
237 |
238 | def unitCylinder(segs = 16, radius0 = 1, radius1 = 1, bottom_cap = False, top_cap = False):
239 | coords = []
240 | normals = []
241 | uvs = []
242 |
243 | vc0 = mathutils.Vector((0, 0, -1))
244 | vc1 = mathutils.Vector((0, 0, 1))
245 | uvc = mathutils.Vector((.5, .5))
246 |
247 | for s in range(segs):
248 | sin0 = math.sin(math.radians(360 * s / segs))
249 | cos0 = math.cos(math.radians(360 * s / segs))
250 | sin1 = math.sin(math.radians(360 * (s + 1) / segs))
251 | cos1 = math.cos(math.radians(360 * (s + 1) / segs))
252 |
253 | v00 = mathutils.Vector((sin0 * radius0, cos0 * radius0, -1))
254 | v10 = mathutils.Vector((sin1 * radius0, cos1 * radius0, -1))
255 | v01 = mathutils.Vector((sin0 * radius1, cos0 * radius1, 1))
256 | v11 = mathutils.Vector((sin1 * radius1, cos1 * radius1, 1))
257 |
258 | tan0 = mathutils.Vector((cos0, sin0, 0))
259 | n00 = (v01 - v00).cross(tan0)
260 | n00.normalize()
261 | n01 = n00
262 | tan1 = mathutils.Vector((cos1, sin1, 0))
263 | n10 = (v11 - v10).cross(tan1)
264 | n10.normalize()
265 | n11 = n10
266 |
267 | uv00 = mathutils.Vector((s / segs, 0))
268 | uv10 = mathutils.Vector(((s + 1) / segs, 0))
269 | uv01 = mathutils.Vector((s / segs, 1))
270 | uv11 = mathutils.Vector(((s + 1) / segs, 1))
271 |
272 | if radius0 != 0:
273 | coords.append(v00)
274 | coords.append(v10)
275 | coords.append(v11)
276 |
277 | normals.append(n00)
278 | normals.append(n10)
279 | normals.append(n11)
280 |
281 | uvs.append(uv00)
282 | uvs.append(uv10)
283 | uvs.append(uv11)
284 |
285 | if radius1 != 0:
286 | coords.append(v00)
287 | coords.append(v11)
288 | coords.append(v01)
289 |
290 | normals.append(n00)
291 | normals.append(n11)
292 | normals.append(n01)
293 |
294 | uvs.append(uv00)
295 | uvs.append(uv11)
296 | uvs.append(uv01)
297 |
298 | if top_cap and radius1 != 0:
299 | coords.append(v01)
300 | coords.append(v11)
301 | coords.append(vc1)
302 |
303 | normals.append(vecZ)
304 | normals.append(vecZ)
305 | normals.append(vecZ)
306 |
307 | uvs.append(mathutils.Vector((sin0, cos0)))
308 | uvs.append(mathutils.Vector((sin1, cos1)))
309 | uvs.append(uvc)
310 |
311 | if bottom_cap and radius0 != 0:
312 | coords.append(v00)
313 | coords.append(v10)
314 | coords.append(vc0)
315 |
316 | normals.append(-vecZ)
317 | normals.append(-vecZ)
318 | normals.append(-vecZ)
319 |
320 | uvs.append(mathutils.Vector((sin0, cos0)))
321 | uvs.append(mathutils.Vector((sin1, cos1)))
322 | uvs.append(uvc)
323 |
324 |
325 | return (coords, normals, uvs)
326 |
327 |
328 | def unitCone(segs = 16, radius = 1, cap = False):
329 | return unitCylinder(segs, radius, 0, cap, False)
330 |
331 |
332 | def unitSphere(segs_lat = 8, segs_long = 16):
333 | coords = []
334 | normals = []
335 | uvs = []
336 |
337 |
338 | for la in range(segs_lat):
339 | z0 = math.cos(math.radians(180 * la / segs_lat))
340 | z1 = math.cos(math.radians(180 * (la + 1) / segs_lat))
341 | r0 = math.sin(math.radians(180 * la / segs_lat))
342 | r1 = math.sin(math.radians(180 * (la + 1) / segs_lat))
343 |
344 | for lo in range(segs_long):
345 | cx0 = math.sin(math.radians(360 * lo / segs_long))
346 | cx1 = math.sin(math.radians(360 * (lo + 1) / segs_long))
347 | cy0 = math.cos(math.radians(360 * lo / segs_long))
348 | cy1 = math.cos(math.radians(360 * (lo + 1) / segs_long))
349 |
350 | v00 = mathutils.Vector((cx0 * r0, cy0 * r0, z0))
351 | v10 = mathutils.Vector((cx1 * r0, cy1 * r0, z0))
352 | v01 = mathutils.Vector((cx0 * r1, cy0 * r1, z1))
353 | v11 = mathutils.Vector((cx1 * r1, cy1 * r1, z1))
354 |
355 | if la != 0:
356 | coords.append(v00)
357 | coords.append(v11)
358 | coords.append(v10)
359 |
360 | normals.append(v00)
361 | normals.append(v10)
362 | normals.append(v11)
363 |
364 | uvs.append((lo / segs_long, la / segs_lat))
365 | uvs.append(((lo + 1) / segs_long, la / segs_lat))
366 | uvs.append(((lo + 1) / segs_long, (la + 1) / segs_lat))
367 |
368 | if la != segs_lat - 1:
369 | coords.append(v00)
370 | coords.append(v01)
371 | coords.append(v11)
372 |
373 | normals.append(v00)
374 | normals.append(v11)
375 | normals.append(v01)
376 |
377 | uvs.append((lo / segs_long, la / segs_lat))
378 | uvs.append(((lo + 1) / segs_long, (la + 1) / segs_lat))
379 | uvs.append((lo / segs_long, (la + 1) / segs_lat))
380 |
381 | return (coords, normals, uvs)
382 |
383 |
384 | def unitTorus(radius = 1, ring_radius = .2, segs_u = 16, segs_v = 8):
385 | coords = []
386 | normals = []
387 | uvs = []
388 |
389 | # print("--Build torus")
390 |
391 | for i in range(segs_u):
392 | cx0 = math.sin(math.radians(360 * i / segs_u)) * radius
393 | cy0 = math.cos(math.radians(360 * i / segs_u)) * radius
394 | cx1 = math.sin(math.radians(360 * (i + 1) / segs_u)) * radius
395 | cy1 = math.cos(math.radians(360 * (i + 1) / segs_u)) * radius
396 |
397 | c0 = mathutils.Vector((cx0, cy0, 0))
398 | c1 = mathutils.Vector((cx1, cy1, 0))
399 |
400 | # print("c0 %s" % (str(c0)))
401 |
402 | for j in range(segs_v):
403 | dir0 = c0 * ring_radius / c0.magnitude
404 | dir1 = c1 * ring_radius / c1.magnitude
405 |
406 | tan0 = dir0.cross(vecZ)
407 | tan1 = dir1.cross(vecZ)
408 |
409 | # print("dir0 %s" % (str(dir0)))
410 | # print("tan0 %s" % (str(tan0)))
411 |
412 | q00 = mathutils.Quaternion(tan0, math.radians(360 * j / segs_v))
413 | q01 = mathutils.Quaternion(tan0, math.radians(360 * (j + 1) / segs_v))
414 | q10 = mathutils.Quaternion(tan1, math.radians(360 * j / segs_v))
415 | q11 = mathutils.Quaternion(tan1, math.radians(360 * (j + 1) / segs_v))
416 |
417 | # m00 = q00.to_matrix()
418 | # m01 = q01.to_matrix()
419 | # m10 = q10.to_matrix()
420 | # m11 = q11.to_matrix()
421 |
422 | # print("m00 %s" % (str(m00)))
423 |
424 | # p00 = m00 @ dir0 + c0
425 | # p01 = m01 @ dir0 + c0
426 | # p10 = m10 @ dir1 + c1
427 | # p11 = m11 @ dir1 + c1
428 |
429 | # print("p00 %s" % (str(p00)))
430 |
431 | # p00 = q00 @ dir0 @ q00.conjugated() + c0
432 | # p01 = q01 @ dir0 @ q01.conjugated() + c0
433 | # p10 = q10 @ dir1 @ q10.conjugated() + c1
434 | # p11 = q11 @ dir1 @ q11.conjugated() + c1
435 |
436 | p00 = q00 @ dir0 + c0
437 | p01 = q01 @ dir0 + c0
438 | p10 = q10 @ dir1 + c1
439 | p11 = q11 @ dir1 + c1
440 |
441 | vu = p10 - p00
442 | vv = p01 - p00
443 | norm = vu.cross(vv)
444 | norm.normalize()
445 |
446 | uv00 = mathutils.Vector((i / segs_u, j / segs_v))
447 | uv10 = mathutils.Vector(((i + 1) / segs_u, j / segs_v))
448 | uv01 = mathutils.Vector((i / segs_u, (j + 1) / segs_v))
449 | uv11 = mathutils.Vector(((i + 1) / segs_u, (j + 1) / segs_v))
450 |
451 | coords.append(p00)
452 | coords.append(p10)
453 | coords.append(p11)
454 |
455 | coords.append(p00)
456 | coords.append(p11)
457 | coords.append(p01)
458 |
459 | for k in range(6):
460 | normals.append(norm)
461 |
462 | uvs.append(uv00)
463 | uvs.append(uv10)
464 | uvs.append(uv11)
465 |
466 | uvs.append(uv00)
467 | uvs.append(uv11)
468 | uvs.append(uv01)
469 |
470 | return (coords, normals, uvs)
471 |
472 |
473 | class Axis(Enum):
474 | X = 1
475 | Y = 2
476 | Z = 3
477 |
478 |
479 | class Face(Enum):
480 | X_POS = 0
481 | X_NEG = 1
482 | Y_POS = 2
483 | Y_NEG = 3
484 | Z_POS = 4
485 | Z_NEG = 5
486 |
487 | #Multiply a vector by a 4x4 matrix. Returns 3d vector.
488 | def mul_vector(matrix, vector):
489 | v0 = vector.to_4d()
490 | v0.w = 0
491 | v1 = matrix @ v0
492 | return v1.to_3d()
493 |
494 |
495 |
496 |
497 | #Returns the fraction of the viewport that a sphere of radius 1 will occupy
498 | def dist_from_viewport_center3(pos, region, rv3d):
499 |
500 | w2v = rv3d.view_matrix
501 | v2w = w2v.inverted()
502 | #view_origin = v2w.translation.copy()
503 | j = v2w.col[1].to_3d()
504 |
505 | # print("v2w " + str(v2w))
506 | # print("j " + str(j))
507 |
508 | persp = rv3d.perspective_matrix
509 |
510 | pos0_win = persp @ pos.to_4d()
511 | pos0_win /= pos0_win.w
512 | p0 = pos0_win.to_2d()
513 |
514 | # print("pos0_win " + str(pos0_win))
515 | # print("p0 " + str(p0))
516 |
517 | pos1_win = persp @ (pos + j).to_4d()
518 | pos1_win /= pos1_win.w
519 | p1 = pos1_win.to_2d()
520 |
521 | # print("pos1_win " + str(pos1_win))
522 | # print("p1 " + str(p1))
523 |
524 | dist = (p1 - p0).magnitude
525 |
526 | # print("dist " + str(dist))
527 |
528 | # return dist / region.height
529 | # return 1 / dist
530 | # return region.height / dist
531 | return dist
532 |
533 |
534 | def calc_unit_scale3(pos, region, rv3d):
535 |
536 | w2win = rv3d.window_matrix @ rv3d.perspective_matrix @ rv3d.view_matrix
537 |
538 | p0 = pos.to_4d()
539 | p1 = (pos + vecZ).to_4d()
540 |
541 | q0 = w2win @ p0
542 | q1 = w2win @ p1
543 |
544 | q0 /= q0.w
545 | q1 /= q1.w
546 |
547 | dq = q1 - q0
548 | dq.z = 0
549 |
550 | print("p0 " + str(q0))
551 | print("p1 " + str(q1))
552 | print("dq " + str(dq))
553 |
554 | return dq.magnitude
555 |
556 |
557 | #Returns scalar s to multiply line_dir by so that line_point + s * line_dir lies on plane
558 | # note that plane_norm does not need to be normalized
559 | def isect_line_plane(line_point, line_dir, plane_point, plane_norm):
560 | to_plane = (plane_point - line_point).project(plane_norm)
561 | dir_par_to_norm = line_dir.project(plane_norm)
562 |
563 | if dir_par_to_norm.magnitude == 0:
564 | return None
565 |
566 | scalar = to_plane.magnitude / dir_par_to_norm.magnitude
567 | if to_plane.dot(dir_par_to_norm) < 0:
568 | scalar = -scalar
569 | return scalar
570 |
571 |
572 | #Returns scalar s to multiply line_dir0 by so that line_point0 + s * line_dir0 is as close as possible to the other line
573 | def closest_point_to_line(line_point0, line_dir0, line_point1, line_dir1):
574 | #vector perpendicular to both line 0 and line 1
575 | r = line_dir0.cross(line_dir1)
576 | norm = r.cross(line_dir1)
577 | return isect_line_plane(line_point0, line_dir0, line_point1, norm)
578 |
579 |
580 | #Returns the ray of the intersection of two planes
581 | def isect_planes(point0, normal0, point1, normal1):
582 | ray_normal = normal0.cross(normal1)
583 | ray_normal.normalize()
584 |
585 | perp = ray_normal.cross(normal0)
586 |
587 | s = isect_line_plane(point0, perp, point1, normal1)
588 | ray_point = point0 + s * perp
589 |
590 | return ray_point, ray_normal
591 |
592 |
593 | #Finds the best s such that v1 = s * v0. Presumes vectors are parallel
594 | def findVectorScalar(v0, v1):
595 | xx = abs(v1.x - v0.x)
596 | yy = abs(v1.y - v0.y)
597 | zz = abs(v1.z - v0.z)
598 |
599 | if xx > yy and xx > zz:
600 | return v1.x / v0.x
601 | elif yy > zz:
602 | return v1.y / v0.y
603 | else:
604 | return z1.y / v0.z
605 |
606 |
607 | def lerp(a, b, t):
608 | return a * (1 - t) + b * t
609 |
610 | def abs_vector(vector):
611 | return mathutils.Vector((abs(vector.x), abs(vector.y), abs(vector.z)))
612 |
613 | def floor_vector(vector):
614 | return mathutils.Vector((math.floor(vector.x), math.floor(vector.y), math.floor(vector.z)))
615 |
616 | def mult_vector(matrix, vector):
617 | v = vector.copy()
618 | v.resize_4d()
619 | v.w = 0
620 | v = matrix @ v
621 | v.resize_3d()
622 | return v
623 |
624 | def mult_normal(matrix, normal):
625 | m = matrix.copy()
626 | m.invert()
627 | m.transpose()
628 | return mult_vector(m, normal)
629 |
630 | def closest_axis(vector):
631 | xx = abs(vector.x)
632 | yy = abs(vector.y)
633 | zz = abs(vector.z)
634 |
635 | if xx > yy and xx > zz:
636 | return Axis.X
637 | elif yy > zz:
638 | return Axis.Y
639 | else:
640 | return Axis.Z
641 |
642 | def create_matrix(i, j, k, translation):
643 | ii = i.to_4d()
644 | ii.w = 0
645 | jj = j.to_4d()
646 | jj.w = 0
647 | kk = k.to_4d()
648 | kk.w = 0
649 | tt = translation.to_4d()
650 | m = mathutils.Matrix([ii, jj, kk, tt])
651 | m.transpose()
652 | return m
653 |
654 |
655 |
656 | def project_point_onto_plane(point, plane_pt, plane_norm):
657 | proj = (point - plane_pt).project(plane_norm)
658 | return point - proj
659 |
660 | #return vector of coefficients [a, b, c] such that vec = a * v0 + b * v1 + c * v2
661 | def express_in_basis(vec, v0, v1, v2):
662 | v = mathutils.Matrix((v0, v1, v2)) #row order
663 | if v.determinant() == 0:
664 | return mathutils.Vector((0, 0, 0))
665 |
666 | vI = v.copy()
667 | vI.transpose()
668 | vI.invert()
669 | return vI @ vec
670 |
671 | def snap_to_grid(pos, unit):
672 | p = mathutils.Vector(pos)
673 | p /= unit
674 | p += mathutils.Vector((.5, .5, .5))
675 |
676 | p.x = math.floor(p.x)
677 | p.y = math.floor(p.y)
678 | p.z = math.floor(p.z)
679 |
680 | p *= unit
681 |
682 | return p
683 |
684 | def snap_to_grid_plane(pos, unit, plane_point, plane_normal):
685 | sp = snap_to_grid(pos, unit)
686 |
687 | axis = closest_axis(plane_normal)
688 |
689 | if axis == Axis.X:
690 | s = isect_line_plane(sp, vecX, plane_point, plane_normal)
691 | return sp + s * vecX
692 | elif axis == Axis.Y:
693 | s = isect_line_plane(sp, vecY, plane_point, plane_normal)
694 | return sp + s * vecY
695 | else:
696 | s = isect_line_plane(sp, vecZ, plane_point, plane_normal)
697 | return sp + s * vecZ
698 |
699 | def intersect_triangle(p0, p1, p2, pickOrigin, pickRay):
700 | v10 = p1 - p0
701 | v20 = p2 - p0
702 | v21 = p2 - p1
703 | norm = v10.cross(v20)
704 | norm.normalize()
705 |
706 | scalar = isect_line_plane(pickOrigin, pickRay, p0, norm)
707 | if scalar == None:
708 | return None
709 |
710 | hitPoint = pickOrigin + scalar * pickRay
711 |
712 | vh0 = hitPoint - p0
713 | vh1 = hitPoint - p1
714 | v01 = -v10
715 |
716 | if vh0.cross(v20).dot(v10.cross(v20)) < 0:
717 | return None
718 | if vh0.cross(v10).dot(v20.cross(v10)) < 0:
719 | return None
720 | if vh1.cross(v21).dot(v01.cross(v21)) < 0:
721 | return None
722 |
723 | return hitPoint
724 |
725 | #Finds the vector x such the function f(x) = A @ x - b is minimized.
726 | # A and b must be numpy matricies and have the same number of rows.
727 | # return value is a numpy vector
728 | def least_squares_fit(A, b):
729 | aa = A.T @ A
730 |
731 | if np.isfinite(np.linalg.cond(aa)):
732 | aa = np.linalg.inv(aa)
733 | else:
734 | return (False, [])
735 |
736 | x = aa @ A.T @ b
737 |
738 | return (True, x)
739 |
740 | # #points is an array of 3D points.
741 | # # @returns [point, normal] of plane that best fits points
742 | # def fit_points_to_plane(points):
743 | # P = np.array(points)
744 | # rows = P.shape[0]
745 |
746 | # ones = np.ones(rows).reshape((rows, 1))
747 |
748 | # aa = P[:, 0:-1]
749 | # A = np.hstack((aa, ones))
750 |
751 | # b = P[:, -1]
752 |
753 | # valid, C = least_squares_fit(A, b)
754 | # if valid == False:
755 | # return (False, vecZero, vecZero)
756 | # pos = mathutils.Vector((0, 0, C[2]))
757 |
758 | # norm = mathutils.Vector((C[0], C[1], -1))
759 | # norm.normalize()
760 |
761 | # return (True, pos, norm)
762 |
763 | #points is an array of 3D points.
764 | # @returns [point, normal] of plane that best fits points
765 | def fit_points_to_plane(points):
766 | if len(points) == 0:
767 | return (False, vecZero, vecZero)
768 |
769 | # print("*** num points " + str(len(points)))
770 |
771 | P = np.array(points)
772 | rows = P.shape[0]
773 |
774 | centroid = P.sum(axis=0) / rows
775 |
776 | #Centered points
777 | Pc = P - centroid
778 |
779 | A = Pc[:, 0:-1]
780 | b = P[:, -1]
781 |
782 | valid, C = least_squares_fit(A, b)
783 | if valid == False:
784 | return (False, vecZero, vecZero)
785 | pos = mathutils.Vector(centroid)
786 |
787 | norm = mathutils.Vector((C[0], C[1], -1))
788 | norm.normalize()
789 |
790 | return (True, pos, norm)
791 |
792 | # #points is an array of 3D points.
793 | # # @returns [point, normal] of plane that best fits points
794 | # def fit_points_to_plane2(points):
795 | # #Equation of plane we're trying to fit is ax + by + cz + d = 0
796 | # # is the normal of the plane
797 |
798 | # P = np.array(points)
799 | # rows = P.shape[0]
800 |
801 | # centroid = P.sum(axis=0) / rows
802 |
803 | # #Centered points
804 | # Pc = P - centroid
805 |
806 | # # ones = np.ones(rows).reshape((rows, 1))
807 |
808 | # # A = np.hstack((P, ones))
809 | # A = Pc
810 |
811 | # # b = P[:, -1]
812 | # b = np.zeros(rows).reshape((rows, 1))
813 |
814 | # #Coefficients of ax + by + cz + d = 0
815 | # valid, C = least_squares_fit(A, b)
816 | # if valid == False:
817 | # return (False, vecZero, vecZero)
818 |
819 | # #Point on plane where x = 0, y = 0
820 | # pos = mathutils.Vector(centroid)
821 |
822 | # norm = mathutils.Vector((C[0], C[1], C[2]))
823 | # norm.normalize()
824 |
825 | # return (True, pos, norm)
826 |
827 |
828 | class Bounds:
829 | def __init__(self, point):
830 | self.minBound = point.copy()
831 | self.maxBound = point.copy()
832 |
833 | def include_point(self, point):
834 | self.minBound.x = min(self.minBound.x, point.x)
835 | self.maxBound.x = max(self.maxBound.x, point.x)
836 | self.minBound.y = min(self.minBound.y, point.y)
837 | self.maxBound.y = max(self.maxBound.y, point.y)
838 | self.minBound.z = min(self.minBound.z, point.z)
839 | self.maxBound.z = max(self.maxBound.z, point.z)
840 |
841 | def include_bounds(self, bounds):
842 | include_point(bounds.minBound)
843 | include_point(bounds.maxBound)
844 |
845 | def __intersect_edge(self, p0, p1, ray_origin, ray_dir, ray_radius):
846 | dir = p1 - p0
847 | s = closest_point_to_line(p0, dir, ray_origin, ray_dir)
848 | if math.isnan(s):
849 | return False
850 | # print("ray_origin " + str(ray_origin))
851 | # print("ray_dir " + str(ray_dir))
852 | # print("ray_radius " + str(ray_radius))
853 |
854 | # print("p0 " + str(p0))
855 | # print("p1 " + str(p1))
856 | # print("s " + str(s))
857 |
858 | s = max(min(s, 1), 0)
859 | p = p0 + s * dir
860 |
861 | # print("p " + str(p))
862 |
863 | offset_from_ray_origin = p - ray_origin
864 | offset_parallel = offset_from_ray_origin.project(ray_dir)
865 | offset_perp = offset_from_ray_origin - offset_parallel
866 |
867 | # print("offset_perp " + str(offset_perp))
868 | # print("offset_perp.length " + str(offset_perp.length))
869 |
870 | if offset_perp.dot(offset_perp) < ray_radius * ray_radius:
871 | #We intersect with cube edge
872 | return True
873 | return False
874 |
875 | def __intersect_face(self, p0, p1, p2, ray_origin, ray_dir):
876 | # print ("__intersect_face ")
877 | # print("p0 " + str(p0))
878 | # print("p1 " + str(p1))
879 | # print("p2 " + str(p2))
880 | # print("ray_origin " + str(ray_origin))
881 | # print("ray_dir " + str(ray_dir))
882 |
883 | v1 = p1 - p0
884 | v2 = p2 - p0
885 | normal = v1.cross(v2)
886 | s = isect_line_plane(ray_origin, ray_dir, p0, normal)
887 | if s == None:
888 | #Parallel to face
889 | return False
890 | hit = ray_origin + s * ray_dir
891 | v_hit = hit - p0
892 |
893 | # print("hit " + str(hit))
894 |
895 | #Express v_hit as a linear combination of v1 and v2
896 | # V = mathutils.Matrix(((v1.x, v2.x, normal.x), (v1.y, v2.y, normal.y), (v1.z, v2.z, normal.z)))
897 | V = mathutils.Matrix((v1, v2, normal))
898 | if V.determinant() == 0:
899 | return False
900 |
901 | V.transpose()
902 | V_i = V.inverted()
903 | co = V_i @ v_hit
904 |
905 | if co.x >= 0 and co.x <= 1 and co.y >= 0 and co.y <= 1:
906 | return True
907 |
908 | return False
909 |
910 | def intersect_with_ray(self, ray_origin, ray_dir, ray_radius = 0, boundsXform = None):
911 | p000 = mathutils.Vector((self.minBound.x, self.minBound.y, self.minBound.z))
912 | p001 = mathutils.Vector((self.minBound.x, self.minBound.y, self.maxBound.z))
913 | p010 = mathutils.Vector((self.minBound.x, self.maxBound.y, self.minBound.z))
914 | p011 = mathutils.Vector((self.minBound.x, self.maxBound.y, self.maxBound.z))
915 | p100 = mathutils.Vector((self.maxBound.x, self.minBound.y, self.minBound.z))
916 | p101 = mathutils.Vector((self.maxBound.x, self.minBound.y, self.maxBound.z))
917 | p110 = mathutils.Vector((self.maxBound.x, self.maxBound.y, self.minBound.z))
918 | p111 = mathutils.Vector((self.maxBound.x, self.maxBound.y, self.maxBound.z))
919 |
920 | # print("p000 " + str(p000))
921 | # print("p001 " + str(p001))
922 | # print("p010 " + str(p010))
923 | # print("p011 " + str(p011))
924 | # print("p100 " + str(p100))
925 | # print("p101 " + str(p101))
926 | # print("p110 " + str(p110))
927 | # print("p111 " + str(p111))
928 |
929 | if boundsXform != None:
930 | p000 = boundsXform @ p000
931 | p001 = boundsXform @ p001
932 | p010 = boundsXform @ p010
933 | p011 = boundsXform @ p011
934 | p100 = boundsXform @ p100
935 | p101 = boundsXform @ p101
936 | p110 = boundsXform @ p110
937 | p111 = boundsXform @ p111
938 |
939 | # print("after xform")
940 | # print("p000 " + str(p000))
941 | # print("p001 " + str(p001))
942 | # print("p010 " + str(p010))
943 | # print("p011 " + str(p011))
944 | # print("p100 " + str(p100))
945 | # print("p101 " + str(p101))
946 | # print("p110 " + str(p110))
947 | # print("p111 " + str(p111))
948 |
949 | #Check for edge intersections
950 | if ray_radius > 0:
951 | if self.__intersect_edge(p000, p100, ray_origin, ray_dir, ray_radius):
952 | return True
953 | if self.__intersect_edge(p000, p010, ray_origin, ray_dir, ray_radius):
954 | return True
955 | if self.__intersect_edge(p010, p110, ray_origin, ray_dir, ray_radius):
956 | return True
957 | if self.__intersect_edge(p100, p110, ray_origin, ray_dir, ray_radius):
958 | return True
959 | if self.__intersect_edge(p000, p001, ray_origin, ray_dir, ray_radius):
960 | return True
961 | if self.__intersect_edge(p100, p101, ray_origin, ray_dir, ray_radius):
962 | return True
963 | if self.__intersect_edge(p010, p011, ray_origin, ray_dir, ray_radius):
964 | return True
965 | if self.__intersect_edge(p110, p111, ray_origin, ray_dir, ray_radius):
966 | return True
967 | if self.__intersect_edge(p001, p101, ray_origin, ray_dir, ray_radius):
968 | return True
969 | if self.__intersect_edge(p001, p011, ray_origin, ray_dir, ray_radius):
970 | return True
971 | if self.__intersect_edge(p011, p111, ray_origin, ray_dir, ray_radius):
972 | return True
973 | if self.__intersect_edge(p101, p111, ray_origin, ray_dir, ray_radius):
974 | return True
975 |
976 | if self.__intersect_face(p000, p010, p100, ray_origin, ray_dir):
977 | return True
978 | if self.__intersect_face(p000, p001, p100, ray_origin, ray_dir):
979 | return True
980 | if self.__intersect_face(p100, p101, p110, ray_origin, ray_dir):
981 | return True
982 | if self.__intersect_face(p010, p110, p011, ray_origin, ray_dir):
983 | return True
984 | if self.__intersect_face(p000, p001, p010, ray_origin, ray_dir):
985 | return True
986 | if self.__intersect_face(p001, p101, p011, ray_origin, ray_dir):
987 | return True
988 |
989 | return False
990 |
991 | def __str__(self):
992 | return "bounds [" + str(self.minBound) + " " + str(self.maxBound) + "]"
993 |
994 | def mesh_bounds_fast(obj, world = False):
995 | bounds = None
996 |
997 | # print("mesh_bounds_fast()")
998 | for co in obj.bound_box:
999 | pos = mathutils.Vector(co)
1000 |
1001 | # print("pos " + str(pos))
1002 |
1003 | if world:
1004 | pos = obj.matrix_world @ pos
1005 |
1006 | if bounds == None:
1007 | bounds = Bounds(pos)
1008 | else:
1009 | bounds.include_point(pos)
1010 |
1011 | return bounds
1012 |
1013 | def mesh_bounds(obj, world = True, selected_faces_only = False):
1014 |
1015 | bounds = None
1016 |
1017 | mesh = obj.data
1018 |
1019 | for p in mesh.polygons:
1020 | if selected_faces_only and not p.select:
1021 | continue
1022 |
1023 | for vIdx in p.vertices:
1024 | v = mesh.vertices[vIdx]
1025 | pos = mathutils.Vector(v.co)
1026 |
1027 | if world:
1028 | pos = obj.matrix_world @ pos
1029 |
1030 | if bounds == None:
1031 | bounds = Bounds(pos)
1032 | else:
1033 | bounds.include_point(pos)
1034 |
1035 | return bounds
1036 |
1037 |
1038 |
1039 | def bmesh_bounds(obj, bmesh, world = True, selected_faces_only = False):
1040 |
1041 | bounds = None
1042 |
1043 | for f in bmesh.faces:
1044 | if selected_faces_only and not p.select:
1045 | continue
1046 |
1047 | for v in f.verts:
1048 | pos = mathutils.Vector(v.co)
1049 | if world:
1050 | pos = obj.matrix_world @ pos
1051 |
1052 | if bounds == None:
1053 | bounds = Bounds(pos)
1054 | else:
1055 | bounds.include_point(pos)
1056 |
1057 | return bounds
1058 |
1059 |
1060 |
1061 |
1062 |
1063 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/source/operators/TerrainSculptMeshBrush.py:
--------------------------------------------------------------------------------
1 | # This file is part of the Kitfox Normal Brush distribution (https://github.com/blackears/terrainSculpt).
2 | # Copyright (c) 2021 Mark McKay
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, version 3.
7 | #
8 | # This program is distributed in the hope that it will be useful, but
9 | # WITHOUT ANY WARRANTY; without even the implied warranty of
10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 | # General Public License for more details.
12 | #
13 | # You should have received a copy of the GNU General Public License
14 | # along with this program. If not, see .
15 |
16 | import bpy
17 | import gpu
18 | import mathutils
19 | import math
20 | import bmesh
21 | from ..kitfox.math.vecmath import *
22 | from ..kitfox.blenderUtil import *
23 | from .Common import *
24 | from .SmoothingInfo import *
25 | from .TerrainSculptMeshProperties import *
26 | from .TerrainHeightPickerMeshOperator import *
27 |
28 | from gpu_extras.batch import batch_for_shader
29 | from bpy_extras import view3d_utils
30 |
31 | shader = gpu.shader.from_builtin('UNIFORM_COLOR')
32 | batchCircle = batch_for_shader(shader, 'LINE_STRIP', {"pos": coordsCircle})
33 | batchSquare = batch_for_shader(shader, 'LINE_STRIP', {"pos": coordsSquare_strip})
34 |
35 | brush_radius_increment = .9
36 |
37 | #--------------------------------------
38 |
39 | def draw_viewport_callback(self, context):
40 | pass
41 |
42 |
43 | def find_area():
44 | try:
45 | for a in bpy.data.window_managers[0].windows[0].screen.areas:
46 | if a.type == "VIEW_3D":
47 | return a
48 | return None
49 | except:
50 | return None
51 |
52 | def draw_circle(mCursor):
53 | #Tangent to mesh
54 | gpu.matrix.push()
55 |
56 | gpu.matrix.multiply_matrix(mCursor)
57 |
58 | shader.uniform_float("color", (1, 0, 1, 1))
59 | batchCircle.draw(shader)
60 | gpu.matrix.pop()
61 |
62 | def get_adjust_brush_viewport_scale(self, radius_relative_to_view_scale):
63 | area = find_area()
64 | if area:
65 | #RegionView3D
66 | r3d = area.spaces[0].region_3d
67 | proj_mat = r3d.window_matrix
68 |
69 | if r3d.is_perspective and self.cursor_pos:
70 | cam_offset = self.cursor_pos - self.ray_origin
71 | brush_scale = cam_offset.length * radius_relative_to_view_scale / proj_mat[1][1]
72 | #print("self.cursor_pos ", self.cursor_pos, " self.ray_origin ", self.ray_origin, " brush_scale ", brush_scale)
73 | # brush_radius = brush_radius * brush_scale
74 | # inner_radius = inner_radius * brush_scale
75 | return brush_scale
76 |
77 | return 1
78 |
79 |
80 | def draw_callback(self, context):
81 | ctx = bpy.context
82 |
83 | region = context.region
84 | rv3d = context.region_data
85 |
86 | viewport_center = (region.x + region.width / 2, region.y + region.height / 2)
87 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, viewport_center)
88 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, viewport_center)
89 |
90 | props = context.scene.terrain_sculpt_mesh_brush_props
91 | brush_radius = props.radius
92 | inner_radius = props.inner_radius
93 | brush_type = props.brush_type
94 | ramp_width = props.ramp_width
95 | draw_height = props.draw_height
96 | world_shape_type = props.world_shape_type
97 | terrain_origin_obj = props.terrain_origin
98 | radius_relative_to_view = props.radius_relative_to_view
99 | radius_relative_to_view_scale = props.radius_relative_to_view_scale
100 |
101 | terrain_origin = vecZero.copy()
102 | if terrain_origin_obj != None:
103 | terrain_origin = terrain_origin_obj.matrix_world.translation
104 |
105 | shader.bind();
106 |
107 | # print("draw_callback")
108 |
109 | if radius_relative_to_view:
110 | brush_scale = get_adjust_brush_viewport_scale(self, radius_relative_to_view_scale)
111 | brush_radius = brush_radius * brush_scale
112 | inner_radius = inner_radius * brush_scale
113 |
114 | #Draw cursor
115 | if self.show_cursor:
116 |
117 | if brush_type == 'RAMP':
118 | if self.dragging:
119 | ramp_start = self.start_location
120 | ramp_span = self.cursor_pos - ramp_start
121 |
122 | if ramp_span.length_squared > .001:
123 |
124 | if world_shape_type == 'FLAT':
125 | up = vecZ
126 | else:
127 | up = self.start_location - terrain_origin
128 | up.normalize()
129 |
130 | binormal = ramp_span.normalized()
131 | tangent = binormal.cross(up)
132 | normal = tangent.cross(binormal)
133 |
134 | m = create_matrix(tangent, binormal, normal, self.start_location)
135 |
136 | #m = calc_vertex_transform_world(self.start_location, normal);
137 | mS = mathutils.Matrix.Diagonal((ramp_width * 2, ramp_span.length, 1, 1))
138 | mT = mathutils.Matrix.Translation((-.5, 0, 0))
139 |
140 | mCursor = m @ mS @ mT
141 |
142 |
143 | gpu.matrix.push()
144 |
145 | gpu.matrix.multiply_matrix(mCursor)
146 |
147 | shader.uniform_float("color", (1, 0, 1, 1))
148 | batchSquare.draw(shader)
149 | gpu.matrix.pop()
150 |
151 | elif brush_type == 'DRAW':
152 | # print("drawing DRAW brush")
153 |
154 | # print("found radius check")
155 | # area = find_area()
156 | # if area:
157 | # #RegionView3D
158 | # r3d = area.spaces[0].region_3d
159 | # proj_mat = r3d.window_matrix
160 |
161 | # if r3d.is_perspective:
162 | # cam_offset = self.cursor_pos - self.ray_origin
163 | # brush_scale = cam_offset.length * radius_relative_to_view_scale / proj_mat[1][1]
164 | # #print("self.cursor_pos ", self.cursor_pos, " self.ray_origin ", self.ray_origin, " brush_scale ", brush_scale)
165 | # brush_radius = brush_radius * brush_scale
166 | # inner_radius = inner_radius * brush_scale
167 |
168 |
169 |
170 | offset_from_origin = self.cursor_pos - terrain_origin
171 | if world_shape_type == 'FLAT':
172 | # print("world_shape_type " + str(world_shape_type))
173 | offset_from_origin = offset_from_origin.project(vecZ)
174 | down = -vecZ
175 | else:
176 | down = -offset_from_origin.normalized()
177 |
178 | draw_pos = self.cursor_pos - offset_from_origin - down * draw_height
179 | m = calc_vertex_transform_world(draw_pos, -down);
180 |
181 | draw_base_pos = self.cursor_pos - offset_from_origin
182 | mBase = calc_vertex_transform_world(draw_base_pos, -down);
183 |
184 | #outer
185 | mS = mathutils.Matrix.Scale(brush_radius, 4)
186 | mCursor = m @ mS
187 |
188 | draw_circle(mCursor)
189 |
190 | draw_circle(mBase @ mS)
191 |
192 | #inner
193 | mS = mathutils.Matrix.Scale(brush_radius * inner_radius, 4)
194 | mCursor = m @ mS
195 |
196 | draw_circle(mCursor)
197 | draw_circle(mBase @ mS)
198 |
199 | else:
200 |
201 | #Orient to mesh surface
202 | m = calc_vertex_transform_world(self.cursor_pos, self.cursor_normal);
203 |
204 | #outer
205 | mS = mathutils.Matrix.Scale(brush_radius, 4)
206 | mCursor = m @ mS
207 |
208 | draw_circle(mCursor)
209 |
210 | #inner
211 | mS = mathutils.Matrix.Scale(brush_radius * inner_radius, 4)
212 | mCursor = m @ mS
213 |
214 | draw_circle(mCursor)
215 |
216 |
217 | def rotate_axis_angle(vector, axis, angle):
218 | #Rodrigues' formula
219 | sin_a = math.sin(angle)
220 | cos_a = math.cos(angle)
221 | return vector * cos_a + axis.cross(vector) * sin_a + axis * axis.dot(vector) * (1 - cos_a)
222 |
223 |
224 |
225 | #-------------------------------------
226 |
227 | class TerrainSculptMeshOperator(bpy.types.Operator):
228 | """Sculpt your terrain using a brush."""
229 | bl_idname = "kitfox.terrain_sculpt_mesh_brush_operator"
230 | bl_label = "UV Brush"
231 | bl_options = {"REGISTER", "UNDO"}
232 |
233 | def __init__(self, *args, **kwargs):
234 | super().__init__(*args, **kwargs)
235 | self.dragging = False
236 |
237 | self.cursor_pos = None
238 | self.ray_origin = None
239 | self.show_cursor = False
240 | self.edit_object = None
241 | self.stroke_trail = []
242 |
243 | self.history = []
244 | self.history_idx = -1
245 | self.history_limit = 10
246 | self.history_bookmarks = {}
247 |
248 | def __del__(self):
249 | # print("End")
250 | super().__del__()
251 |
252 |
253 | def free_snapshot(self, map):
254 | for obj in map:
255 | bm = map[obj]
256 | bm.free()
257 |
258 | #if bookmark is other than -1, snapshot added to bookmark library rather than undo stack
259 | def history_snapshot(self, context, bookmark = -1):
260 | map = {}
261 | for obj in context.selected_objects:
262 | if obj.type == 'MESH':
263 | bm = bmesh.new()
264 |
265 | mesh = obj.data
266 | bm.from_mesh(mesh)
267 | map[obj] = bm
268 |
269 | if bookmark != -1:
270 | self.history_bookmarks[bookmark] = map
271 |
272 | else:
273 | #Remove first element if history queue is maxed out
274 | if self.history_idx == self.history_limit:
275 | self.free_snapshot(self.history[0])
276 | self.history.pop(0)
277 |
278 | self.history_idx += 1
279 |
280 | #Remove all history past current pointer
281 | while self.history_idx < len(self.history) - 1:
282 | self.free_snapshot(self.history[-1])
283 | self.history.pop()
284 |
285 | self.history.append(map)
286 | self.history_idx += 1
287 |
288 | def history_undo(self, context):
289 | if (self.history_idx == 0):
290 | return
291 |
292 | self.history_undo_to_snapshot(context, self.history_idx - 1)
293 |
294 | def history_redo(self, context):
295 | if (self.history_idx == len(self.history) - 1):
296 | return
297 |
298 | self.history_undo_to_snapshot(context, self.history_idx + 1)
299 |
300 |
301 | def history_restore_bookmark(self, context, bookmark):
302 | map = self.history[bookmark]
303 |
304 | for obj in context.selected_objects:
305 | if obj.type == 'MESH':
306 | bm = map[obj]
307 |
308 | mesh = obj.data
309 | bm.to_mesh(mesh)
310 | mesh.update()
311 |
312 | def history_undo_to_snapshot(self, context, idx):
313 | if idx < 0 or idx >= len(self.history):
314 | return
315 |
316 | self.history_idx = idx
317 |
318 | map = self.history[self.history_idx]
319 |
320 | for obj in context.selected_objects:
321 | if obj.type == 'MESH':
322 | bm = map[obj]
323 |
324 | mesh = obj.data
325 | bm.to_mesh(mesh)
326 | mesh.update()
327 |
328 | def history_clear(self, context):
329 | for key in self.history_bookmarks:
330 | map = self.history_bookmarks[key]
331 | self.free_snapshot(map)
332 |
333 | for map in self.history:
334 | self.free_snapshot(map)
335 |
336 | self.history = []
337 | self.history_idx = -1
338 |
339 | def stroke_falloff(self, x):
340 | # return 1 - x * x
341 | return -x * x + 2 * x
342 |
343 | def calc_offset_from_origin(self, wpos, terrain_origin, world_shape_type):
344 | offset_from_origin = wpos - terrain_origin
345 | if world_shape_type == 'FLAT':
346 | offset_from_origin = offset_from_origin.project(vecZ)
347 | down = -vecZ
348 | else:
349 | down = -offset_from_origin.normalized()
350 |
351 | return (offset_from_origin, down)
352 |
353 | def dab_brush(self, context, event, start_stroke = False):
354 | mouse_pos = (event.mouse_region_x, event.mouse_region_y)
355 |
356 | region = context.region
357 | rv3d = context.region_data
358 |
359 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos)
360 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos)
361 |
362 | # print("dab_brush " + " mouse_pos " + str(mouse_pos))
363 | # print("ray_orig " + str(ray_origin) + "view_vec " + str(view_vector))
364 |
365 | viewlayer = bpy.context.view_layer
366 |
367 | hit_object = None
368 | location = None
369 | normal = None
370 | index = None
371 |
372 | # hit_object, location, normal, face_index, object, matrix = ray_cast_scene(context, viewlayer, ray_origin, view_vector)
373 | hit_object, location, normal, face_index, object, matrix = pick_object(ray_origin, view_vector)
374 |
375 | if not hit_object or object.select_get() == False or object.type != 'MESH':
376 | return
377 |
378 | props = context.scene.terrain_sculpt_mesh_brush_props
379 | brush_radius = props.radius
380 | inner_radius = props.inner_radius
381 | strength = props.strength
382 | use_pressure = props.use_pressure
383 | brush_type = props.brush_type
384 | world_shape_type = props.world_shape_type
385 | draw_height = props.draw_height
386 | add_amount = props.add_amount
387 | ramp_width = props.ramp_width
388 | terrain_origin_obj = props.terrain_origin
389 | smooth_edge_snap_distance = props.smooth_edge_snap_distance
390 | radius_relative_to_view = props.radius_relative_to_view
391 | radius_relative_to_view_scale = props.radius_relative_to_view_scale
392 | slope_angle = props.slope_angle
393 | use_slope_angle = props.use_slope_angle
394 |
395 | if radius_relative_to_view:
396 | brush_scale = get_adjust_brush_viewport_scale(self, radius_relative_to_view_scale)
397 | brush_radius = brush_radius * brush_scale
398 | inner_radius = inner_radius * brush_scale
399 |
400 | terrain_origin = vecZero.copy()
401 | if terrain_origin_obj != None:
402 | terrain_origin = terrain_origin_obj.matrix_world.translation
403 |
404 | if event.shift:
405 | #Shift key overrides for smooth mode
406 | brush_type = 'SMOOTH'
407 |
408 |
409 | if world_shape_type == 'FLAT':
410 | hit_down = -vecZ
411 | hit_offset = (location - terrain_origin).project(vecZ)
412 | else:
413 | hit_down = terrain_origin - location
414 | hit_offset = -hit_down
415 |
416 | if start_stroke:
417 | self.start_height = hit_offset.dot(vecZ)
418 |
419 | if brush_type == 'SMOOTH':
420 | #Calculate relaxed location for each relevant point
421 |
422 | smoothing_info = SmoothingInfo()
423 |
424 | for obj in context.scene.objects:
425 | if not obj.select_get():
426 | continue
427 |
428 | if obj.type != 'MESH':
429 | continue
430 |
431 | l2w = obj.matrix_world
432 |
433 | #Bounding box check
434 | bounds = mesh_bounds_fast(obj)
435 | bbox_check = bounds.intersect_with_ray(location, hit_down, brush_radius, l2w)
436 | if not bbox_check:
437 | continue
438 |
439 | mesh = obj.data
440 | if obj.mode == 'EDIT':
441 | bm = bmesh.from_edit_mesh(mesh)
442 | elif obj.mode == 'OBJECT':
443 | bm = bmesh.new()
444 | bm.from_mesh(mesh)
445 |
446 | for v in bm.verts:
447 | wpos = l2w @ v.co
448 |
449 | offset_from_origin, down = self.calc_offset_from_origin(wpos, terrain_origin, world_shape_type)
450 |
451 | # offset_from_origin = wpos - terrain_origin
452 | # if world_shape_type == 'FLAT':
453 | # # print("world_shape_type " + str(world_shape_type))
454 | # offset_from_origin = offset_from_origin.project(vecZ)
455 | # down = -vecZ
456 | # else:
457 | # down = -offset_from_origin.normalized()
458 |
459 | offset = wpos - location
460 | offset_parallel = offset.project(down)
461 | offset_perp = offset - offset_parallel
462 |
463 | dist = offset_perp.magnitude
464 | if dist < brush_radius:
465 | centroidHeight = 0
466 | count = 0
467 | # print("Smoothing Vertex #" + str(v.index))
468 |
469 | for e in v.link_edges:
470 | v1 = e.other_vert(v)
471 | # print("linked edge #" + str(v1.index))
472 |
473 | v1Wpos = l2w @ v1.co
474 | offset_from_originP, downP = self.calc_offset_from_origin(v1Wpos, terrain_origin, world_shape_type)
475 | #offset_parallel = offset.project(down)
476 |
477 | # print("offset_from_originP.magnitude " + str(offset_from_originP.magnitude))
478 |
479 | offset = offset_from_originP.magnitude
480 | if offset_from_originP.dot(downP) < 0:
481 | offset = -offset
482 | centroidHeight += offset
483 | count += 1
484 | #offset = (v1Wpos - wpos).normalized()
485 |
486 | centroidHeight /= count
487 | smoothing_info.addPoint(wpos, centroidHeight)
488 |
489 | # print("centroidHeight " + str(centroidHeight))
490 |
491 | if obj.mode == 'OBJECT':
492 | bm.free()
493 |
494 | if brush_type == 'SLOPE':
495 | weight_sum = 0
496 | weighted_len_sum = 0
497 |
498 | for obj in context.scene.objects:
499 | if not obj.select_get():
500 | continue
501 |
502 | if obj.type != 'MESH':
503 | continue
504 |
505 | l2w = obj.matrix_world
506 |
507 | #Bounding box check
508 | bounds = mesh_bounds_fast(obj)
509 | bbox_check = bounds.intersect_with_ray(location, hit_down, brush_radius, l2w)
510 | if not bbox_check:
511 | continue
512 |
513 | mesh = obj.data
514 | if obj.mode == 'EDIT':
515 | bm = bmesh.from_edit_mesh(mesh)
516 | elif obj.mode == 'OBJECT':
517 | bm = bmesh.new()
518 | bm.from_mesh(mesh)
519 |
520 | smooth_points = []
521 |
522 | for v in bm.verts:
523 |
524 | wpos = l2w @ v.co
525 |
526 | offset_from_origin = wpos - terrain_origin
527 | if world_shape_type == 'FLAT':
528 | # print("world_shape_type " + str(world_shape_type))
529 | offset_from_origin = offset_from_origin.project(vecZ)
530 | down = -vecZ
531 | else:
532 | down = -offset_from_origin.normalized()
533 |
534 | offset = wpos - location
535 | offset_parallel = offset.project(down)
536 | offset_perp = offset - offset_parallel
537 |
538 | dist = offset_perp.magnitude
539 | if dist < brush_radius:
540 | if brush_type == 'SLOPE':
541 | smooth_points.append(wpos)
542 |
543 | if obj.mode == 'OBJECT':
544 | bm.free()
545 |
546 | if brush_type == 'SLOPE':
547 |
548 | smooth_valid, smooth_plane_pos, smooth_plane_norm = fit_points_to_plane(smooth_points)
549 |
550 | if use_slope_angle:
551 | #slope_angle
552 | up = mathutils.Vector((0, 0, 1))
553 | binorm = smooth_plane_norm.cross(up)
554 | binorm = binorm.normalized()
555 | #smooth_plane_norm = mathutils.Vector((0, 0, 1))
556 | smooth_plane_norm = rotate_axis_angle(up, binorm, slope_angle * math.pi / 180)
557 |
558 |
559 | for obj in context.scene.objects:
560 | if not obj.select_get():
561 | continue
562 |
563 | l2w = obj.matrix_world
564 | w2l = l2w.inverted()
565 |
566 | if obj.type != 'MESH':
567 | continue
568 |
569 | #Bounding box check
570 | bounds = mesh_bounds_fast(obj)
571 | bbox_check = bounds.intersect_with_ray(location, hit_down, brush_radius, l2w)
572 | # print("bbox_check " + str(bbox_check))
573 | if not bbox_check:
574 | continue
575 |
576 | # print("=====")
577 | # print ("obj.name " + str(obj.name))
578 |
579 | if brush_type in ('DRAW', 'ADD', 'SUBTRACT', 'LEVEL', 'SLOPE', 'SMOOTH'):
580 |
581 | mesh = obj.data
582 | if obj.mode == 'EDIT':
583 | bm = bmesh.from_edit_mesh(mesh)
584 | elif obj.mode == 'OBJECT':
585 | bm = bmesh.new()
586 | bm.from_mesh(mesh)
587 |
588 |
589 | # print ("location " + str(location))
590 | for v in bm.verts:
591 |
592 | wpos = l2w @ v.co
593 | woffset = wpos - location
594 |
595 | offset_from_origin = wpos - terrain_origin
596 | if world_shape_type == 'FLAT':
597 | # print("world_shape_type " + str(world_shape_type))
598 | offset_from_origin = offset_from_origin.project(vecZ)
599 | down = -vecZ
600 | else:
601 | down = -offset_from_origin.normalized()
602 |
603 | offset_down = woffset.project(down)
604 | offset_perp = woffset - offset_down
605 |
606 | dist_sq = offset_perp.dot(offset_perp)
607 |
608 | if dist_sq < brush_radius * brush_radius:
609 | dist = math.sqrt(dist_sq)
610 | frac = dist / brush_radius
611 | # offset_in_brush = 1 - dist / brush_radius
612 | atten = 1 if frac <= inner_radius else (1 - frac) / (1 - inner_radius)
613 | atten = self.stroke_falloff(atten)
614 |
615 | atten *= strength
616 | if use_pressure:
617 | atten *= event.pressure
618 |
619 |
620 | len = offset_from_origin.magnitude
621 | if offset_from_origin.dot(down) > 0:
622 | len = -len
623 |
624 | # print("---")
625 | # print("wpos " + str(wpos))
626 | # print("offset_from_origin " + str(offset_from_origin))
627 | # print("down " + str(down))
628 | # print("len " + str(len))
629 | # print("draw_height " + str(draw_height))
630 | # print("atten " + str(atten))
631 | # print("smooth_plane_pos " + str(smooth_plane_pos))
632 | # print("smooth_plane_norm " + str(smooth_plane_norm))
633 |
634 | if brush_type == 'DRAW':
635 | new_offset = (wpos - offset_from_origin) + -down * lerp(len, draw_height, atten)
636 | elif brush_type == 'ADD':
637 | adjust = add_amount * atten
638 | if event.ctrl:
639 | adjust = -adjust
640 | new_offset = (wpos - offset_from_origin) + -down * (len + adjust)
641 | elif brush_type == 'SUBTRACT':
642 | adjust = add_amount * atten
643 | if event.ctrl:
644 | adjust = -adjust
645 | new_offset = (wpos - offset_from_origin) + -down * (len - adjust)
646 | elif brush_type == 'LEVEL':
647 | new_offset = (wpos - offset_from_origin) + -down * lerp(len, self.start_height, atten)
648 | elif brush_type == 'SMOOTH':
649 | centroid_height = smoothing_info.getCentroidHeight(wpos, terrain_origin, world_shape_type, smooth_edge_snap_distance)
650 | new_offset = (wpos - offset_from_origin) + -down * lerp(len, -centroid_height, atten)
651 | # print("Applying smooth dab")
652 | # print("len " + str(len))
653 | # print("centroid_height " + str(centroid_height))
654 | # new_offset = (wpos - offset_from_origin) + -down * lerp(len, smooth_height, atten)
655 | elif brush_type == 'SLOPE':
656 | if smooth_valid:
657 | s = isect_line_plane(wpos, down, smooth_plane_pos, smooth_plane_norm)
658 | target = wpos + s * down
659 | new_offset = mathutils.Vector(lerp(wpos, target, atten))
660 | else:
661 | new_offset = wpos
662 |
663 | v.co = w2l @ new_offset
664 |
665 |
666 |
667 | if obj.mode == 'EDIT':
668 | bmesh.update_edit_mesh(mesh)
669 | elif obj.mode == 'OBJECT':
670 | bm.to_mesh(mesh)
671 | bm.free()
672 |
673 | #mesh.calc_normals_split()
674 |
675 |
676 | def draw_ramp(self, context, event):
677 | mouse_pos = (event.mouse_region_x, event.mouse_region_y)
678 | region = context.region
679 | rv3d = context.region_data
680 |
681 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos)
682 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos)
683 |
684 | viewlayer = bpy.context.view_layer
685 | result, location, normal, face_index, object, matrix = pick_object(ray_origin, view_vector)
686 |
687 | if not result or object.select_get() == False or object.type != 'MESH':
688 | return
689 |
690 | props = context.scene.terrain_sculpt_mesh_brush_props
691 | strength_ramp = props.strength_ramp
692 | ramp_width = props.ramp_width
693 | ramp_falloff = props.ramp_falloff
694 | world_shape_type = props.world_shape_type
695 | terrain_origin_obj = props.terrain_origin
696 |
697 | terrain_origin = vecZero.copy()
698 | if terrain_origin_obj != None:
699 | terrain_origin = terrain_origin_obj.matrix_world.translation
700 |
701 |
702 | ramp_start = self.start_location
703 | ramp_span = location - self.start_location
704 |
705 | l2w = object.matrix_world
706 | w2l = l2w.inverted()
707 |
708 |
709 | for obj in context.scene.objects:
710 | if not obj.select_get():
711 | continue
712 |
713 | if obj.type != 'MESH':
714 | continue
715 |
716 | l2w = obj.matrix_world
717 | w2l = l2w.inverted()
718 |
719 | mesh = obj.data
720 | if obj.mode == 'EDIT':
721 | bm = bmesh.from_edit_mesh(mesh)
722 | elif obj.mode == 'OBJECT':
723 | bm = bmesh.new()
724 | bm.from_mesh(mesh)
725 |
726 |
727 | for v in bm.verts:
728 | wpos = l2w @ v.co
729 |
730 | vert_offset = wpos - ramp_start
731 | vert_parallel = vert_offset.project(ramp_span)
732 | vert_perp = vert_offset - vert_parallel
733 |
734 | offset_from_origin = wpos - terrain_origin
735 | if world_shape_type == 'FLAT':
736 | offset_from_origin = offset_from_origin.project(vecZ)
737 | down = -vecZ
738 | else:
739 | down = -offset_from_origin.normalized()
740 |
741 | binormal = down.cross(ramp_span)
742 | binormal.normalize()
743 | vert_binormal = vert_offset.project(binormal)
744 |
745 | # if vert_parallel.dot(ramp_span) > 0 and vert_parallel.length_squared < ramp_span.length_squared and vert_perp.length_squared < ramp_width * ramp_width:
746 | if vert_parallel.dot(ramp_span) > 0 and vert_parallel.length_squared < ramp_span.length_squared and vert_binormal.length_squared < ramp_width * ramp_width:
747 | frac = vert_parallel.length / ramp_span.length
748 | ramp_height = ramp_start + ramp_span * frac
749 | falloff_span = ramp_width * ramp_falloff
750 |
751 | vert_parallel_len = vert_parallel.length
752 | vert_parallel_len = min(vert_parallel_len, ramp_span.length - vert_parallel_len)
753 |
754 | attenParallel = 1
755 | if vert_parallel_len < falloff_span:
756 | attenParallel = vert_parallel_len / falloff_span
757 |
758 | vert_perp_frac = vert_binormal.length / ramp_width
759 | attenPerp = 1 if vert_perp_frac < (1 - ramp_falloff) else (1 - vert_perp_frac) / ramp_falloff
760 |
761 |
762 | s = closest_point_to_line(wpos, down, ramp_start, ramp_span)
763 | clamped_to_ramp = wpos + down * s
764 | newWpos = lerp(wpos, clamped_to_ramp, strength_ramp * attenParallel * attenPerp)
765 |
766 | v.co = w2l @ newWpos
767 |
768 |
769 | if obj.mode == 'EDIT':
770 | bmesh.update_edit_mesh(mesh)
771 | elif obj.mode == 'OBJECT':
772 | bm.to_mesh(mesh)
773 | bm.free()
774 |
775 | #mesh.calc_normals_split()
776 |
777 |
778 |
779 | def mouse_move(self, context, event):
780 | mouse_pos = (event.mouse_region_x, event.mouse_region_y)
781 |
782 | ctx = bpy.context
783 |
784 | region = context.region
785 | rv3d = context.region_data
786 |
787 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos)
788 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos)
789 |
790 | viewlayer = bpy.context.view_layer
791 | result, location, normal, index, object, matrix = pick_object(ray_origin, view_vector)
792 |
793 | props = context.scene.terrain_sculpt_mesh_brush_props
794 | brush_type = props.brush_type
795 |
796 | if brush_type == 'DRAW' and event.ctrl:
797 | context.window.cursor_set("EYEDROPPER")
798 | self.show_cursor = False
799 | return
800 |
801 | context.window.cursor_set("PAINT_BRUSH")
802 | #print("MOSUE move")
803 |
804 | #Brush cursor display
805 | if result:
806 | self.show_cursor = True
807 | self.cursor_pos = location
808 | self.ray_origin = ray_origin
809 | self.cursor_normal = normal
810 | self.cursor_object = object
811 | self.cursor_matrix = matrix
812 |
813 | else:
814 | self.show_cursor = False
815 |
816 | if self.dragging:
817 | self.dab_brush(context, event)
818 |
819 |
820 | def mouse_click(self, context, event):
821 | if event.value == "PRESS":
822 | mouse_pos = (event.mouse_region_x, event.mouse_region_y)
823 | region = context.region
824 | rv3d = context.region_data
825 |
826 | view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, mouse_pos)
827 | ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, mouse_pos)
828 |
829 | viewlayer = bpy.context.view_layer
830 | # result, location, normal, index, object, matrix = ray_cast_scene(context, viewlayer, ray_origin, view_vector)
831 | result, location, normal, index, object, matrix = pick_object(ray_origin, view_vector)
832 |
833 |
834 | if result == False or object.select_get() == False or object.type != 'MESH':
835 | return {'RUNNING_MODAL'}
836 |
837 | self.dragging = True
838 | self.stroke_trail = []
839 | self.start_location = location.copy()
840 |
841 | props = context.scene.terrain_sculpt_mesh_brush_props
842 | brush_type = props.brush_type
843 |
844 | if brush_type == 'DRAW' and event.ctrl:
845 | context.window.cursor_set("EYEDROPPER")
846 | pick_height(context, event)
847 | return {'RUNNING_MODAL'}
848 |
849 | context.window.cursor_set("DEFAULT")
850 |
851 | self.dab_brush(context, event, start_stroke = True)
852 |
853 |
854 |
855 | elif event.value == "RELEASE":
856 | props = context.scene.terrain_sculpt_mesh_brush_props
857 | brush_type = props.brush_type
858 |
859 | if brush_type == 'RAMP':
860 | self.draw_ramp(context, event)
861 |
862 |
863 | self.dragging = False
864 | # self.edit_object = None
865 |
866 | self.history_snapshot(context)
867 | context.window.cursor_set("DEFAULT")
868 |
869 |
870 | return {'RUNNING_MODAL'}
871 |
872 | @classmethod
873 | def poll(cls, context):
874 | return context.active_object is not None
875 |
876 | def modal(self, context, event):
877 | # print("modal evTyp:%s evVal:%s" % (str(event.type), str(event.value)))
878 | context.area.tag_redraw()
879 |
880 |
881 | # window_result = self.window.handle_event(context, event)
882 | # # print ("window_result " + str(window_result))
883 |
884 | # if window_result:
885 | # return {'RUNNING_MODAL'}
886 |
887 | if event.type in {'MIDDLEMOUSE', 'WHEELUPMOUSE', 'WHEELDOWNMOUSE'}:
888 | # allow navigation
889 | return {'PASS_THROUGH'}
890 |
891 | elif event.type == 'MOUSEMOVE':
892 | #context.window.cursor_set("PAINT_BRUSH")
893 | self.mouse_move(context, event)
894 |
895 | if self.dragging:
896 | return {'RUNNING_MODAL'}
897 | else:
898 | return {'RUNNING_MODAL'}
899 |
900 | elif event.type == 'LEFTMOUSE':
901 | return self.mouse_click(context, event)
902 |
903 | elif event.type in {'Z'}:
904 | if event.ctrl:
905 | if event.shift:
906 | if event.value == "RELEASE":
907 | self.history_redo(context)
908 | return {'RUNNING_MODAL'}
909 | else:
910 | if event.value == "RELEASE":
911 | self.history_undo(context)
912 |
913 | return {'RUNNING_MODAL'}
914 |
915 | return {'RUNNING_MODAL'}
916 |
917 | elif event.type in {'RET'}:
918 | if event.value == 'RELEASE':
919 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
920 | bpy.types.SpaceView3D.draw_handler_remove(self._handle_viewport, 'WINDOW')
921 | self.history_clear(context)
922 | bpy.context.window.cursor_set("DEFAULT")
923 | return {'FINISHED'}
924 | return {'RUNNING_MODAL'}
925 |
926 | elif event.type in {'PAGE_UP', 'RIGHT_BRACKET'}:
927 | if event.value == "PRESS":
928 | if event.shift:
929 | brush_radius = context.scene.terrain_sculpt_mesh_brush_props.inner_radius
930 | brush_radius = brush_radius + .1
931 | context.scene.terrain_sculpt_mesh_brush_props.inner_radius = brush_radius
932 | else:
933 | brush_radius = context.scene.terrain_sculpt_mesh_brush_props.radius
934 | # brush_radius = brush_radius + .1
935 | brush_radius /= brush_radius_increment
936 | context.scene.terrain_sculpt_mesh_brush_props.radius = brush_radius
937 | return {'RUNNING_MODAL'}
938 |
939 | elif event.type in {'PAGE_DOWN', 'LEFT_BRACKET'}:
940 | if event.value == "PRESS":
941 | if event.shift:
942 | brush_radius = context.scene.terrain_sculpt_mesh_brush_props.inner_radius
943 | brush_radius = max(brush_radius - .1, .1)
944 | context.scene.terrain_sculpt_mesh_brush_props.inner_radius = brush_radius
945 | else:
946 | brush_radius = context.scene.terrain_sculpt_mesh_brush_props.radius
947 | # brush_radius = max(brush_radius - .1, .1)
948 | brush_radius *= brush_radius_increment
949 | context.scene.terrain_sculpt_mesh_brush_props.radius = brush_radius
950 | return {'RUNNING_MODAL'}
951 |
952 | elif event.type in {'UP_ARROW'}:
953 | if event.value == "PRESS":
954 | brush_radius = context.scene.terrain_sculpt_mesh_brush_props.radius
955 | draw_height = context.scene.terrain_sculpt_mesh_brush_props.draw_height
956 | draw_height += brush_radius / 4
957 | context.scene.terrain_sculpt_mesh_brush_props.draw_height = draw_height
958 | return {'RUNNING_MODAL'}
959 |
960 | elif event.type in {'DOWN_ARROW'}:
961 | if event.value == "PRESS":
962 | brush_radius = context.scene.terrain_sculpt_mesh_brush_props.radius
963 | draw_height = context.scene.terrain_sculpt_mesh_brush_props.draw_height
964 | draw_height -= brush_radius / 4
965 | context.scene.terrain_sculpt_mesh_brush_props.draw_height = draw_height
966 | return {'RUNNING_MODAL'}
967 |
968 | elif event.type in {'D'}:
969 | if event.value == "PRESS":
970 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'DRAW'
971 | return {'RUNNING_MODAL'}
972 |
973 | elif event.type in {'L'}:
974 | if event.value == "PRESS":
975 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'LEVEL'
976 | return {'RUNNING_MODAL'}
977 |
978 | elif event.type in {'A'}:
979 | if event.value == "PRESS":
980 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'ADD'
981 | return {'RUNNING_MODAL'}
982 |
983 | elif event.type in {'S'}:
984 | if event.value == "PRESS":
985 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'SUBTRACT'
986 | return {'RUNNING_MODAL'}
987 |
988 | elif event.type in {'P'}:
989 | if event.value == "PRESS":
990 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'SLOPE'
991 | return {'RUNNING_MODAL'}
992 |
993 | elif event.type in {'M'}:
994 | if event.value == "PRESS":
995 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'SMOOTH'
996 | return {'RUNNING_MODAL'}
997 |
998 | elif event.type in {'R'}:
999 | if event.value == "PRESS":
1000 | context.scene.terrain_sculpt_mesh_brush_props.brush_type = 'RAMP'
1001 | return {'RUNNING_MODAL'}
1002 |
1003 | elif event.type == 'ESC':
1004 | if event.value == 'RELEASE':
1005 | bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
1006 | bpy.types.SpaceView3D.draw_handler_remove(self._handle_viewport, 'WINDOW')
1007 | self.history_restore_bookmark(context, 0)
1008 | self.history_clear(context)
1009 | bpy.context.window.cursor_set("DEFAULT")
1010 | return {'CANCELLED'}
1011 | return {'RUNNING_MODAL'}
1012 |
1013 | return {'PASS_THROUGH'}
1014 |
1015 | # def execute(self, context):
1016 | # print("execute SimpleOperator")
1017 | # return {'FINISHED'}
1018 |
1019 | def invoke(self, context, event):
1020 | if context.area.type == 'VIEW_3D':
1021 | # print("invoke evTyp:%s evVal:%s" % (str(event.type), str(event.value)))
1022 |
1023 | args = (self, context)
1024 | self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback, args, 'WINDOW', 'POST_VIEW')
1025 | self._handle_viewport = bpy.types.SpaceView3D.draw_handler_add(draw_viewport_callback, args, 'WINDOW', 'POST_PIXEL')
1026 |
1027 | bpy.context.window.cursor_set("PAINT_BRUSH")
1028 |
1029 | redraw_all_viewports(context)
1030 | self.history_clear(context)
1031 | self.history_snapshot(context)
1032 | self.history_snapshot(context, 0)
1033 |
1034 | context.window_manager.modal_handler_add(self)
1035 | context.area.tag_redraw()
1036 |
1037 | return {'RUNNING_MODAL'}
1038 | else:
1039 | self.report({'WARNING'}, "View3D not found, cannot run operator")
1040 | return {'CANCELLED'}
1041 |
1042 |
1043 |
1044 |
1045 |
--------------------------------------------------------------------------------