2
$\begingroup$

How to add primitives like box, cylinder, sphere, and capsule objects based on the bounding box or selected verts in edit mode of any object?

Example -

Object Mode

enter image description here

Edit Mode

enter image description here

$\endgroup$
6
  • $\begingroup$ Do you want to control the sphere size base on the cube? $\endgroup$
    – X Y
    Mar 22, 2022 at 6:22
  • $\begingroup$ yes, sphere size is based on the cube, any object or selected verts $\endgroup$
    – Karan
    Mar 22, 2022 at 8:12
  • 2
    $\begingroup$ Not all objects have a circumsphere, and 3 points have an infinite number $\endgroup$
    – Robin Betts
    Mar 22, 2022 at 9:54
  • 1
    $\begingroup$ I want to cover object bound box or mesh bound box with the sphere $\endgroup$
    – Karan
    Mar 22, 2022 at 9:58
  • $\begingroup$ Do you have the coordinates of the bbox? $\endgroup$
    – TheJeran
    Mar 22, 2022 at 11:10

1 Answer 1

1
$\begingroup$

Since the bounding box is a tetrahedron you can use Wolfram's Circumsphere entry for your calculations. Assuming an object at the origin, the following code will give you the sphere for that object's bounding box. v[0] is the lower left front corner as seen from front view. The other coordinates are the left top front, left bottom rear, and right bottom front, giving the relationship $(l_1, l_2, l_3)$ are the corresponding $(z, y, x)$ lengths.

import bpy
import bmesh

def vsub(a, b):
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])

def vlen(v):
    return sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2])

cube = bpy.data.objects['Cube']
    
v = cube.bound_box

l1 = vlen(vsub(v[0], v[1]))
l2 = vlen(vsub(v[0], v[3]))
l3 = vlen(vsub(v[0], v[4]))

d = sqrt(l1*l1 + l2*l2 + l3*l3) / 2


mesh = bpy.data.meshes.new('Sphere')
sphere = bpy.data.objects.new("Sphere", mesh)

bpy.context.collection.objects.link(sphere)

# Construct the bmesh sphere and assign it to the blender mesh.
bm = bmesh.new()
bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, diameter=d)
bm.to_mesh(mesh)
bm.free()

The vector math routines are because the bounding box is returned as an 8 x 3 matrix and it's easier to use the two subroutines than to convert the matrix into vectors.

$\endgroup$
2
  • $\begingroup$ How to add a sphere to the selected verts' bound box? $\endgroup$
    – Karan
    Mar 23, 2022 at 5:28
  • $\begingroup$ figure out what the bounding box is and use the above algorithm with the bounding box you generated rather than the object bounding box. $\endgroup$ Mar 23, 2022 at 15:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .