Merge branch 'blender-v2.92-release'
[blender-addons.git] / add_mesh_extra_objects / add_mesh_3d_function_surface.py
blob2faae6054b78197a9609948f2ca2779494465230
1 # GPL # original by Buerbaum Martin (Pontiac), Elod Csirmaz
3 import bpy
4 from mathutils import *
5 from math import *
6 from bpy.types import Operator
7 from bpy.props import (
8 StringProperty,
9 IntProperty,
10 FloatProperty,
11 BoolProperty,
15 # List of safe functions for eval()
16 safe_list = ['math', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
17 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
18 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians',
19 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
21 # Use the list to filter the local namespace
22 safe_dict = dict((k, globals().get(k, None)) for k in safe_list)
25 # Stores the values of a list of properties and the
26 # operator id in a property group ('recall_op') inside the object
27 # Could (in theory) be used for non-objects.
28 # Note: Replaces any existing property group with the same name!
29 # ob ... Object to store the properties in
30 # op ... The operator that should be used
31 # op_args ... A dictionary with valid Blender
32 # properties (operator arguments/parameters)
35 # Create a new mesh (object) from verts/edges/faces
36 # verts/edges/faces ... List of vertices/edges/faces for the
37 # new mesh (as used in from_pydata)
38 # name ... Name of the new mesh (& object)
40 def create_mesh_object(context, verts, edges, faces, name):
42 # Create new mesh
43 mesh = bpy.data.meshes.new(name)
45 # Make a mesh from a list of verts/edges/faces
46 mesh.from_pydata(verts, edges, faces)
48 # Update mesh geometry after adding stuff
49 mesh.update()
51 from bpy_extras import object_utils
52 return object_utils.object_data_add(context, mesh, operator=None)
55 # A very simple "bridge" tool
57 def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False):
58 faces = []
60 if not vertIdx1 or not vertIdx2:
61 return None
63 if len(vertIdx1) < 2 and len(vertIdx2) < 2:
64 return None
66 fan = False
67 if (len(vertIdx1) != len(vertIdx2)):
68 if (len(vertIdx1) == 1 and len(vertIdx2) > 1):
69 fan = True
70 else:
71 return None
73 total = len(vertIdx2)
75 if closed:
76 # Bridge the start with the end
77 if flipped:
78 face = [
79 vertIdx1[0],
80 vertIdx2[0],
81 vertIdx2[total - 1]]
82 if not fan:
83 face.append(vertIdx1[total - 1])
84 faces.append(face)
86 else:
87 face = [vertIdx2[0], vertIdx1[0]]
88 if not fan:
89 face.append(vertIdx1[total - 1])
90 face.append(vertIdx2[total - 1])
91 faces.append(face)
93 # Bridge the rest of the faces
94 for num in range(total - 1):
95 if flipped:
96 if fan:
97 face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]]
98 else:
99 face = [vertIdx2[num], vertIdx1[num],
100 vertIdx1[num + 1], vertIdx2[num + 1]]
101 faces.append(face)
102 else:
103 if fan:
104 face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]]
105 else:
106 face = [vertIdx1[num], vertIdx2[num],
107 vertIdx2[num + 1], vertIdx1[num + 1]]
108 faces.append(face)
110 return faces
113 class AddZFunctionSurface(Operator):
114 bl_idname = "mesh.primitive_z_function_surface"
115 bl_label = "Add Z Function Surface"
116 bl_description = "Add a surface defined defined by a function z=f(x,y)"
117 bl_options = {'REGISTER', 'UNDO', 'PRESET'}
119 equation: StringProperty(
120 name="Z Equation",
121 description="Equation for z=f(x,y)",
122 default="1 - ( x**2 + y**2 )"
124 div_x: IntProperty(
125 name="X Subdivisions",
126 description="Number of vertices in x direction",
127 default=16,
128 min=3,
129 max=256
131 div_y: IntProperty(
132 name="Y Subdivisions",
133 description="Number of vertices in y direction",
134 default=16,
135 min=3,
136 max=256
138 size_x: FloatProperty(
139 name="X Size",
140 description="Size of the x axis",
141 default=2.0,
142 min=0.01,
143 max=100.0,
144 unit="LENGTH"
146 size_y: FloatProperty(
147 name="Y Size",
148 description="Size of the y axis",
149 default=2.0,
150 min=0.01,
151 max=100.0,
152 unit="LENGTH"
155 def execute(self, context):
156 equation = self.equation
157 div_x = self.div_x
158 div_y = self.div_y
159 size_x = self.size_x
160 size_y = self.size_y
162 verts = []
163 faces = []
165 delta_x = size_x / (div_x - 1)
166 delta_y = size_y / (div_y - 1)
167 start_x = -(size_x / 2.0)
168 start_y = -(size_y / 2.0)
170 edgeloop_prev = []
172 if equation:
173 try:
174 expr_args = (
175 compile(equation, __file__, 'eval'),
176 {"__builtins__": None},
177 safe_dict)
178 except:
179 import traceback
180 # WARNING is used to prevent the constant pop-up spam
181 self.report({'WARNING'},
182 "Error parsing expression: {} "
183 "(Check the console for more info)".format(equation))
184 print("\n[Add Z Function Surface]:\n\n", traceback.format_exc(limit=1))
186 return {'CANCELLED'}
188 for row_x in range(div_x):
189 edgeloop_cur = []
190 x = start_x + row_x * delta_x
192 for row_y in range(div_y):
193 y = start_y + row_y * delta_y
194 z = 0.0
196 safe_dict['x'] = x
197 safe_dict['y'] = y
199 # Try to evaluate the equation.
200 try:
201 z = float(eval(*expr_args))
202 except:
203 import traceback
204 self.report({'WARNING'},
205 "Error evaluating expression: {} "
206 "(Check the console for more info)".format(equation))
207 print("\n[Add Z Function Surface]:\n\n", traceback.format_exc(limit=1))
209 return {'CANCELLED'}
211 edgeloop_cur.append(len(verts))
212 verts.append((x, y, z))
214 if len(edgeloop_prev) > 0:
215 faces_row = createFaces(edgeloop_prev, edgeloop_cur)
216 faces.extend(faces_row)
218 edgeloop_prev = edgeloop_cur
220 base = create_mesh_object(context, verts, [], faces, "Z Function")
221 else:
222 self.report({'WARNING'}, "Z Equation - No expression is given")
224 return {'CANCELLED'}
226 return {'FINISHED'}
229 def xyz_function_surface_faces(self, x_eq, y_eq, z_eq,
230 range_u_min, range_u_max, range_u_step, wrap_u,
231 range_v_min, range_v_max, range_v_step, wrap_v,
232 a_eq, b_eq, c_eq, f_eq, g_eq, h_eq, n, close_v):
234 verts = []
235 faces = []
237 # Distance of each step in Blender Units
238 uStep = (range_u_max - range_u_min) / range_u_step
239 vStep = (range_v_max - range_v_min) / range_v_step
241 # Number of steps in the vertex creation loops.
242 # Number of steps is the number of faces
243 # => Number of points is +1 unless wrapped.
244 uRange = range_u_step + 1
245 vRange = range_v_step + 1
247 if wrap_u:
248 uRange = uRange - 1
250 if wrap_v:
251 vRange = vRange - 1
253 try:
254 expr_args_x = (
255 compile(x_eq, __file__.replace(".py", "_x.py"), 'eval'),
256 {"__builtins__": None},
257 safe_dict)
258 expr_args_y = (
259 compile(y_eq, __file__.replace(".py", "_y.py"), 'eval'),
260 {"__builtins__": None},
261 safe_dict)
262 expr_args_z = (
263 compile(z_eq, __file__.replace(".py", "_z.py"), 'eval'),
264 {"__builtins__": None},
265 safe_dict)
266 expr_args_a = (
267 compile(a_eq, __file__.replace(".py", "_a.py"), 'eval'),
268 {"__builtins__": None},
269 safe_dict)
270 expr_args_b = (
271 compile(b_eq, __file__.replace(".py", "_b.py"), 'eval'),
272 {"__builtins__": None},
273 safe_dict)
274 expr_args_c = (
275 compile(c_eq, __file__.replace(".py", "_c.py"), 'eval'),
276 {"__builtins__": None},
277 safe_dict)
278 expr_args_f = (
279 compile(f_eq, __file__.replace(".py", "_f.py"), 'eval'),
280 {"__builtins__": None},
281 safe_dict)
282 expr_args_g = (
283 compile(g_eq, __file__.replace(".py", "_g.py"), 'eval'),
284 {"__builtins__": None},
285 safe_dict)
286 expr_args_h = (
287 compile(h_eq, __file__.replace(".py", "_h.py"), 'eval'),
288 {"__builtins__": None},
289 safe_dict)
290 except:
291 import traceback
292 self.report({'WARNING'}, "Error parsing expression(s) - "
293 "Check the console for more info")
294 print("\n[Add X, Y, Z Function Surface]:\n\n", traceback.format_exc(limit=1))
295 return [], []
297 for vN in range(vRange):
298 v = range_v_min + (vN * vStep)
300 for uN in range(uRange):
301 u = range_u_min + (uN * uStep)
303 safe_dict['u'] = u
304 safe_dict['v'] = v
306 safe_dict['n'] = n
308 # Try to evaluate the equations.
309 try:
310 safe_dict['a'] = float(eval(*expr_args_a))
311 safe_dict['b'] = float(eval(*expr_args_b))
312 safe_dict['c'] = float(eval(*expr_args_c))
313 safe_dict['f'] = float(eval(*expr_args_f))
314 safe_dict['g'] = float(eval(*expr_args_g))
315 safe_dict['h'] = float(eval(*expr_args_h))
317 verts.append((
318 float(eval(*expr_args_x)),
319 float(eval(*expr_args_y)),
320 float(eval(*expr_args_z))))
321 except:
322 import traceback
323 self.report({'WARNING'}, "Error evaluating expression(s) - "
324 "Check the console for more info")
325 print("\n[Add X, Y, Z Function Surface]:\n\n", traceback.format_exc(limit=1))
326 return [], []
328 for vN in range(range_v_step):
329 vNext = vN + 1
331 if wrap_v and (vNext >= vRange):
332 vNext = 0
334 for uN in range(range_u_step):
335 uNext = uN + 1
337 if wrap_u and (uNext >= uRange):
338 uNext = 0
340 faces.append([(vNext * uRange) + uNext,
341 (vNext * uRange) + uN,
342 (vN * uRange) + uN,
343 (vN * uRange) + uNext])
345 if close_v and wrap_u and (not wrap_v):
346 for uN in range(1, range_u_step - 1):
347 faces.append([
348 range_u_step - 1,
349 range_u_step - 1 - uN,
350 range_u_step - 2 - uN])
351 faces.append([
352 range_v_step * uRange,
353 range_v_step * uRange + uN,
354 range_v_step * uRange + uN + 1])
356 return verts, faces
359 # Original Script "Parametric.py" by Ed Mackey.
360 # -> http://www.blinken.com/blender-plugins.php
361 # Partly converted for Blender 2.5 by tuga3d.
363 # Sphere:
364 # x = sin(2*pi*u)*sin(pi*v)
365 # y = cos(2*pi*u)*sin(pi*v)
366 # z = cos(pi*v)
367 # u_min = v_min = 0
368 # u_max = v_max = 1
370 # "Snail shell"
371 # x = 1.2**v*(sin(u)**2 *sin(v))
372 # y = 1.2**v*(sin(u)*cos(u))
373 # z = 1.2**v*(sin(u)**2 *cos(v))
374 # u_min = 0
375 # u_max = pi
376 # v_min = -pi/4,
377 # v max = 5*pi/2
379 class AddXYZFunctionSurface(Operator):
380 bl_idname = "mesh.primitive_xyz_function_surface"
381 bl_label = "Add X, Y, Z Function Surface"
382 bl_description = ("Add a surface defined defined by 3 functions:\n"
383 "x=F1(u,v), y=F2(u,v) and z=F3(u,v)")
384 bl_options = {'REGISTER', 'UNDO', 'PRESET'}
386 x_eq: StringProperty(
387 name="X equation",
388 description="Equation for x=F(u,v). "
389 "Also available: n, a, b, c, f, g, h",
390 default="cos(v)*(1+cos(u))*sin(v/8)"
392 y_eq: StringProperty(
393 name="Y equation",
394 description="Equation for y=F(u,v). "
395 "Also available: n, a, b, c, f, g, h",
396 default="sin(u)*sin(v/8)+cos(v/8)*1.5"
398 z_eq: StringProperty(
399 name="Z equation",
400 description="Equation for z=F(u,v). "
401 "Also available: n, a, b, c, f, g, h",
402 default="sin(v)*(1+cos(u))*sin(v/8)"
404 range_u_min: FloatProperty(
405 name="U min",
406 description="Minimum U value. Lower boundary of U range",
407 min=-100.00,
408 max=0.00,
409 default=0.00
411 range_u_max: FloatProperty(
412 name="U max",
413 description="Maximum U value. Upper boundary of U range",
414 min=0.00,
415 max=100.00,
416 default=2 * pi
418 range_u_step: IntProperty(
419 name="U step",
420 description="U Subdivisions",
421 min=1,
422 max=1024,
423 default=32
425 wrap_u: BoolProperty(
426 name="U wrap",
427 description="U Wrap around",
428 default=True
430 range_v_min: FloatProperty(
431 name="V min",
432 description="Minimum V value. Lower boundary of V range",
433 min=-100.00,
434 max=0.00,
435 default=0.00
437 range_v_max: FloatProperty(
438 name="V max",
439 description="Maximum V value. Upper boundary of V range",
440 min=0.00,
441 max=100.00,
442 default=4 * pi
444 range_v_step: IntProperty(
445 name="V step",
446 description="V Subdivisions",
447 min=1,
448 max=1024,
449 default=128
451 wrap_v: BoolProperty(
452 name="V wrap",
453 description="V Wrap around",
454 default=False
456 close_v: BoolProperty(
457 name="Close V",
458 description="Create faces for first and last "
459 "V values (only if U is wrapped)",
460 default=False
462 n_eq: IntProperty(
463 name="Number of objects (n=0..N-1)",
464 description="The parameter n will be the index "
465 "of the current object, 0 to N-1",
466 min=1,
467 max=100,
468 default=1
470 a_eq: StringProperty(
471 name="A helper function",
472 description="Equation for a=F(u,v). Also available: n",
473 default="0"
475 b_eq: StringProperty(
476 name="B helper function",
477 description="Equation for b=F(u,v). Also available: n",
478 default="0"
480 c_eq: StringProperty(
481 name="C helper function",
482 description="Equation for c=F(u,v). Also available: n",
483 default="0"
485 f_eq: StringProperty(
486 name="F helper function",
487 description="Equation for f=F(u,v). Also available: n, a, b, c",
488 default="0"
490 g_eq: StringProperty(
491 name="G helper function",
492 description="Equation for g=F(u,v). Also available: n, a, b, c",
493 default="0"
495 h_eq: StringProperty(
496 name="H helper function",
497 description="Equation for h=F(u,v). Also available: n, a, b, c",
498 default="0"
500 show_wire : BoolProperty(
501 name="Show wireframe",
502 default=True,
503 description="Add the object’s wireframe over solid drawing"
505 edit_mode : BoolProperty(
506 name="Show in edit mode",
507 default=True,
508 description="Show in edit mode"
511 def execute(self, context):
512 for n in range(0, self.n_eq):
513 verts, faces = xyz_function_surface_faces(
514 self,
515 self.x_eq,
516 self.y_eq,
517 self.z_eq,
518 self.range_u_min,
519 self.range_u_max,
520 self.range_u_step,
521 self.wrap_u,
522 self.range_v_min,
523 self.range_v_max,
524 self.range_v_step,
525 self.wrap_v,
526 self.a_eq,
527 self.b_eq,
528 self.c_eq,
529 self.f_eq,
530 self.g_eq,
531 self.h_eq,
533 self.close_v
535 if not verts:
536 return {'CANCELLED'}
538 obj = create_mesh_object(context, verts, [], faces, "XYZ Function")
540 if self.show_wire:
541 obj.show_wire = True
543 if self.edit_mode:
544 bpy.ops.object.mode_set(mode = 'EDIT')
545 else:
546 bpy.ops.object.mode_set(mode = 'OBJECT')
548 return {'FINISHED'}