glTF: update shader after Principled changes
[blender-addons.git] / add_mesh_extra_objects / add_mesh_3d_function_surface.py
blob6ba565ace967abae7e11be2c0d8f510798021b90
1 # SPDX-FileCopyrightText: 2010-2022 Blender Foundation
3 # SPDX-License-Identifier: GPL-2.0-or-later
5 # Original by Buerbaum Martin (Pontiac), Elod Csirmaz
7 import bpy
8 import math
9 import numpy
10 from mathutils import *
11 from math import *
12 from bpy.types import Operator
13 from bpy.props import (
14 StringProperty,
15 IntProperty,
16 FloatProperty,
17 BoolProperty,
21 # List of safe functions for eval()
22 safe_list = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh',
23 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot',
24 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians',
25 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'gcd']
27 # Use the list to filter the local namespace
28 safe_dict = dict((k, globals().get(k, None)) for k in safe_list)
29 safe_dict['math'] = math
30 safe_dict['numpy'] = safe_dict['np'] = numpy
31 safe_dict['lcm'] = numpy.lcm
32 safe_dict['max'] = max
33 safe_dict['min'] = min
36 # Stores the values of a list of properties and the
37 # operator id in a property group ('recall_op') inside the object
38 # Could (in theory) be used for non-objects.
39 # Note: Replaces any existing property group with the same name!
40 # ob ... Object to store the properties in
41 # op ... The operator that should be used
42 # op_args ... A dictionary with valid Blender
43 # properties (operator arguments/parameters)
46 # Create a new mesh (object) from verts/edges/faces
47 # verts/edges/faces ... List of vertices/edges/faces for the
48 # new mesh (as used in from_pydata)
49 # name ... Name of the new mesh (& object)
51 def create_mesh_object(context, verts, edges, faces, name):
53 # Create new mesh
54 mesh = bpy.data.meshes.new(name)
56 # Make a mesh from a list of verts/edges/faces
57 mesh.from_pydata(verts, edges, faces)
59 # Update mesh geometry after adding stuff
60 mesh.update()
62 from bpy_extras import object_utils
63 return object_utils.object_data_add(context, mesh, operator=None)
66 # A very simple "bridge" tool
68 def createFaces(vertIdx1, vertIdx2, closed=False, flipped=False):
69 faces = []
71 if not vertIdx1 or not vertIdx2:
72 return None
74 if len(vertIdx1) < 2 and len(vertIdx2) < 2:
75 return None
77 fan = False
78 if (len(vertIdx1) != len(vertIdx2)):
79 if (len(vertIdx1) == 1 and len(vertIdx2) > 1):
80 fan = True
81 else:
82 return None
84 total = len(vertIdx2)
86 if closed:
87 # Bridge the start with the end
88 if flipped:
89 face = [
90 vertIdx1[0],
91 vertIdx2[0],
92 vertIdx2[total - 1]]
93 if not fan:
94 face.append(vertIdx1[total - 1])
95 faces.append(face)
97 else:
98 face = [vertIdx2[0], vertIdx1[0]]
99 if not fan:
100 face.append(vertIdx1[total - 1])
101 face.append(vertIdx2[total - 1])
102 faces.append(face)
104 # Bridge the rest of the faces
105 for num in range(total - 1):
106 if flipped:
107 if fan:
108 face = [vertIdx2[num], vertIdx1[0], vertIdx2[num + 1]]
109 else:
110 face = [vertIdx2[num], vertIdx1[num],
111 vertIdx1[num + 1], vertIdx2[num + 1]]
112 faces.append(face)
113 else:
114 if fan:
115 face = [vertIdx1[0], vertIdx2[num], vertIdx2[num + 1]]
116 else:
117 face = [vertIdx1[num], vertIdx2[num],
118 vertIdx2[num + 1], vertIdx1[num + 1]]
119 faces.append(face)
121 return faces
124 class AddZFunctionSurface(Operator):
125 bl_idname = "mesh.primitive_z_function_surface"
126 bl_label = "Add Z Function Surface"
127 bl_description = "Add a surface defined defined by a function z=f(x,y)"
128 bl_options = {'REGISTER', 'UNDO', 'PRESET'}
130 equation: StringProperty(
131 name="Z Equation",
132 description="Equation for z=f(x,y)",
133 default="1 - ( x**2 + y**2 )"
135 div_x: IntProperty(
136 name="X Subdivisions",
137 description="Number of vertices in x direction",
138 default=16,
139 min=3,
140 max=256
142 div_y: IntProperty(
143 name="Y Subdivisions",
144 description="Number of vertices in y direction",
145 default=16,
146 min=3,
147 max=256
149 size_x: FloatProperty(
150 name="X Size",
151 description="Size of the x axis",
152 default=2.0,
153 min=0.01,
154 max=100.0,
155 unit="LENGTH"
157 size_y: FloatProperty(
158 name="Y Size",
159 description="Size of the y axis",
160 default=2.0,
161 min=0.01,
162 max=100.0,
163 unit="LENGTH"
166 def execute(self, context):
167 equation = self.equation
168 div_x = self.div_x
169 div_y = self.div_y
170 size_x = self.size_x
171 size_y = self.size_y
173 verts = []
174 faces = []
176 delta_x = size_x / (div_x - 1)
177 delta_y = size_y / (div_y - 1)
178 start_x = -(size_x / 2.0)
179 start_y = -(size_y / 2.0)
181 edgeloop_prev = []
183 if equation:
184 try:
185 expr_args = (
186 compile(equation, __file__, 'eval'),
187 {"__builtins__": None},
188 safe_dict)
189 except:
190 import traceback
191 # WARNING is used to prevent the constant pop-up spam
192 self.report({'WARNING'},
193 "Error parsing expression: {} "
194 "(Check the console for more info)".format(equation))
195 print("\n[Add Z Function Surface]:\n\n", traceback.format_exc(limit=1))
197 return {'CANCELLED'}
199 for row_x in range(div_x):
200 edgeloop_cur = []
201 x = start_x + row_x * delta_x
203 for row_y in range(div_y):
204 y = start_y + row_y * delta_y
205 z = 0.0
207 safe_dict['x'] = x
208 safe_dict['y'] = y
210 # Try to evaluate the equation.
211 try:
212 z = float(eval(*expr_args))
213 except:
214 import traceback
215 self.report({'WARNING'},
216 "Error evaluating expression: {} "
217 "(Check the console for more info)".format(equation))
218 print("\n[Add Z Function Surface]:\n\n", traceback.format_exc(limit=1))
220 return {'CANCELLED'}
222 edgeloop_cur.append(len(verts))
223 verts.append((x, y, z))
225 if len(edgeloop_prev) > 0:
226 faces_row = createFaces(edgeloop_prev, edgeloop_cur)
227 faces.extend(faces_row)
229 edgeloop_prev = edgeloop_cur
231 base = create_mesh_object(context, verts, [], faces, "Z Function")
232 else:
233 self.report({'WARNING'}, "Z Equation - No expression is given")
235 return {'CANCELLED'}
237 return {'FINISHED'}
240 def xyz_function_surface_faces(self, x_eq, y_eq, z_eq,
241 range_u_min, range_u_max, range_u_step, wrap_u,
242 range_v_min, range_v_max, range_v_step, wrap_v,
243 a_eq, b_eq, c_eq, f_eq, g_eq, h_eq, n, close_v):
245 verts = []
246 faces = []
248 # Distance of each step in Blender Units
249 uStep = (range_u_max - range_u_min) / range_u_step
250 vStep = (range_v_max - range_v_min) / range_v_step
252 # Number of steps in the vertex creation loops.
253 # Number of steps is the number of faces
254 # => Number of points is +1 unless wrapped.
255 uRange = range_u_step + 1
256 vRange = range_v_step + 1
258 if wrap_u:
259 uRange = uRange - 1
261 if wrap_v:
262 vRange = vRange - 1
264 try:
265 expr_args_x = (
266 compile(x_eq, __file__.replace(".py", "_x.py"), 'eval'),
267 {"__builtins__": None},
268 safe_dict)
269 expr_args_y = (
270 compile(y_eq, __file__.replace(".py", "_y.py"), 'eval'),
271 {"__builtins__": None},
272 safe_dict)
273 expr_args_z = (
274 compile(z_eq, __file__.replace(".py", "_z.py"), 'eval'),
275 {"__builtins__": None},
276 safe_dict)
277 expr_args_a = (
278 compile(a_eq, __file__.replace(".py", "_a.py"), 'eval'),
279 {"__builtins__": None},
280 safe_dict)
281 expr_args_b = (
282 compile(b_eq, __file__.replace(".py", "_b.py"), 'eval'),
283 {"__builtins__": None},
284 safe_dict)
285 expr_args_c = (
286 compile(c_eq, __file__.replace(".py", "_c.py"), 'eval'),
287 {"__builtins__": None},
288 safe_dict)
289 expr_args_f = (
290 compile(f_eq, __file__.replace(".py", "_f.py"), 'eval'),
291 {"__builtins__": None},
292 safe_dict)
293 expr_args_g = (
294 compile(g_eq, __file__.replace(".py", "_g.py"), 'eval'),
295 {"__builtins__": None},
296 safe_dict)
297 expr_args_h = (
298 compile(h_eq, __file__.replace(".py", "_h.py"), 'eval'),
299 {"__builtins__": None},
300 safe_dict)
301 except:
302 import traceback
303 self.report({'WARNING'}, "Error parsing expression(s) - "
304 "Check the console for more info")
305 print("\n[Add X, Y, Z Function Surface]:\n\n", traceback.format_exc(limit=1))
306 return [], []
308 for vN in range(vRange):
309 v = range_v_min + (vN * vStep)
311 for uN in range(uRange):
312 u = range_u_min + (uN * uStep)
314 safe_dict['u'] = u
315 safe_dict['v'] = v
317 safe_dict['n'] = n
319 # Try to evaluate the equations.
320 try:
321 safe_dict['a'] = float(eval(*expr_args_a))
322 safe_dict['b'] = float(eval(*expr_args_b))
323 safe_dict['c'] = float(eval(*expr_args_c))
324 safe_dict['f'] = float(eval(*expr_args_f))
325 safe_dict['g'] = float(eval(*expr_args_g))
326 safe_dict['h'] = float(eval(*expr_args_h))
328 verts.append((
329 float(eval(*expr_args_x)),
330 float(eval(*expr_args_y)),
331 float(eval(*expr_args_z))))
332 except:
333 import traceback
334 self.report({'WARNING'}, "Error evaluating expression(s) - "
335 "Check the console for more info")
336 print("\n[Add X, Y, Z Function Surface]:\n\n", traceback.format_exc(limit=1))
337 return [], []
339 for vN in range(range_v_step):
340 vNext = vN + 1
342 if wrap_v and (vNext >= vRange):
343 vNext = 0
345 for uN in range(range_u_step):
346 uNext = uN + 1
348 if wrap_u and (uNext >= uRange):
349 uNext = 0
351 faces.append([(vNext * uRange) + uNext,
352 (vNext * uRange) + uN,
353 (vN * uRange) + uN,
354 (vN * uRange) + uNext])
356 if close_v and wrap_u and (not wrap_v):
357 for uN in range(1, range_u_step - 1):
358 faces.append([
359 range_u_step - 1,
360 range_u_step - 1 - uN,
361 range_u_step - 2 - uN])
362 faces.append([
363 range_v_step * uRange,
364 range_v_step * uRange + uN,
365 range_v_step * uRange + uN + 1])
367 return verts, faces
370 # Original Script "Parametric.py" by Ed Mackey.
371 # -> http://www.blinken.com/blender-plugins.php
372 # Partly converted for Blender 2.5 by tuga3d.
374 # Sphere:
375 # x = sin(2*pi*u)*sin(pi*v)
376 # y = cos(2*pi*u)*sin(pi*v)
377 # z = cos(pi*v)
378 # u_min = v_min = 0
379 # u_max = v_max = 1
381 # "Snail shell"
382 # x = 1.2**v*(sin(u)**2 *sin(v))
383 # y = 1.2**v*(sin(u)*cos(u))
384 # z = 1.2**v*(sin(u)**2 *cos(v))
385 # u_min = 0
386 # u_max = pi
387 # v_min = -pi/4,
388 # v max = 5*pi/2
390 class AddXYZFunctionSurface(Operator):
391 bl_idname = "mesh.primitive_xyz_function_surface"
392 bl_label = "Add X, Y, Z Function Surface"
393 bl_description = ("Add a surface defined defined by 3 functions:\n"
394 "x=F1(u,v), y=F2(u,v) and z=F3(u,v)")
395 bl_options = {'REGISTER', 'UNDO', 'PRESET'}
397 x_eq: StringProperty(
398 name="X equation",
399 description="Equation for x=F(u,v). "
400 "Also available: n, a, b, c, f, g, h",
401 default="cos(v)*(1+cos(u))*sin(v/8)"
403 y_eq: StringProperty(
404 name="Y equation",
405 description="Equation for y=F(u,v). "
406 "Also available: n, a, b, c, f, g, h",
407 default="sin(u)*sin(v/8)+cos(v/8)*1.5"
409 z_eq: StringProperty(
410 name="Z equation",
411 description="Equation for z=F(u,v). "
412 "Also available: n, a, b, c, f, g, h",
413 default="sin(v)*(1+cos(u))*sin(v/8)"
415 range_u_min: FloatProperty(
416 name="U min",
417 description="Minimum U value. Lower boundary of U range",
418 min=-100.00,
419 max=0.00,
420 default=0.00
422 range_u_max: FloatProperty(
423 name="U max",
424 description="Maximum U value. Upper boundary of U range",
425 min=0.00,
426 max=100.00,
427 default=2 * pi
429 range_u_step: IntProperty(
430 name="U step",
431 description="U Subdivisions",
432 min=1,
433 max=1024,
434 default=32
436 wrap_u: BoolProperty(
437 name="U wrap",
438 description="U Wrap around",
439 default=True
441 range_v_min: FloatProperty(
442 name="V min",
443 description="Minimum V value. Lower boundary of V range",
444 min=-100.00,
445 max=0.00,
446 default=0.00
448 range_v_max: FloatProperty(
449 name="V max",
450 description="Maximum V value. Upper boundary of V range",
451 min=0.00,
452 max=100.00,
453 default=4 * pi
455 range_v_step: IntProperty(
456 name="V step",
457 description="V Subdivisions",
458 min=1,
459 max=1024,
460 default=128
462 wrap_v: BoolProperty(
463 name="V wrap",
464 description="V Wrap around",
465 default=False
467 close_v: BoolProperty(
468 name="Close V",
469 description="Create faces for first and last "
470 "V values (only if U is wrapped)",
471 default=False
473 n_eq: IntProperty(
474 name="Number of objects (n=0..N-1)",
475 description="The parameter n will be the index "
476 "of the current object, 0 to N-1",
477 min=1,
478 max=100,
479 default=1
481 a_eq: StringProperty(
482 name="A helper function",
483 description="Equation for a=F(u,v). Also available: n",
484 default="0"
486 b_eq: StringProperty(
487 name="B helper function",
488 description="Equation for b=F(u,v). Also available: n",
489 default="0"
491 c_eq: StringProperty(
492 name="C helper function",
493 description="Equation for c=F(u,v). Also available: n",
494 default="0"
496 f_eq: StringProperty(
497 name="F helper function",
498 description="Equation for f=F(u,v). Also available: n, a, b, c",
499 default="0"
501 g_eq: StringProperty(
502 name="G helper function",
503 description="Equation for g=F(u,v). Also available: n, a, b, c",
504 default="0"
506 h_eq: StringProperty(
507 name="H helper function",
508 description="Equation for h=F(u,v). Also available: n, a, b, c",
509 default="0"
511 show_wire : BoolProperty(
512 name="Show wireframe",
513 default=True,
514 description="Add the object’s wireframe over solid drawing"
516 edit_mode : BoolProperty(
517 name="Show in edit mode",
518 default=True,
519 description="Show in edit mode"
522 def execute(self, context):
523 for n in range(0, self.n_eq):
524 verts, faces = xyz_function_surface_faces(
525 self,
526 self.x_eq,
527 self.y_eq,
528 self.z_eq,
529 self.range_u_min,
530 self.range_u_max,
531 self.range_u_step,
532 self.wrap_u,
533 self.range_v_min,
534 self.range_v_max,
535 self.range_v_step,
536 self.wrap_v,
537 self.a_eq,
538 self.b_eq,
539 self.c_eq,
540 self.f_eq,
541 self.g_eq,
542 self.h_eq,
544 self.close_v
546 if not verts:
547 return {'CANCELLED'}
549 obj = create_mesh_object(context, verts, [], faces, "XYZ Function")
551 if self.show_wire:
552 context.active_object.show_wire = True
553 else:
554 context.active_object.show_wire = False
556 if self.edit_mode:
557 bpy.ops.object.mode_set(mode = 'EDIT')
558 else:
559 bpy.ops.object.mode_set(mode = 'OBJECT')
561 return {'FINISHED'}