Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script replacing objects with the cubes

Tags:

python

maya

I am trying to create a Python script to generate cubes in Maya which represent the object space bounding boxes of objects.

For example, if I create random objects (sphere, cube, pyramid, cone, etc.) in Maya, I want to replace those selected objects with a cube which has the dimensions of that object's bounding box.

So if I create 3 different objects, (for instance a cone, a sphere, and a pyramid), there should be three individual cubes that are the bounding boxes of those objects.

Here is the script that I tried to build, but I am stuck right after this.

Steps that I followed:

  1. create a sphere. (Manually by clicking the 'generate sphere button' on Maya program)

  2. after step 1, run the script I built

import maya.cmds as cmds

sel = cmds.ls(sl=True)
print sel
bbox = cmds.exactWorldBoundingBox(sel)
print bbox
cmds.polyCube()
like image 743
user3059072 Avatar asked Dec 07 '13 19:12

user3059072


1 Answers

You might as well pull the 6 values out into useful variables on the bounding box line:

x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(sel)

Also, polyCube returns a list of 2 items. We want the first one - the transform:

cube = cmds.polyCube()[0]

Now we need the center point in each dimension, so we average the edges:

xc = (x2 + x1) / 2.0
yc = (y2 + y1) / 2.0
zc = (z2 + z1) / 2.0

We also want the dimensions, so we can scale up our unit-scale poly cube:

xw = x2 - x1
yw = y2 - y1
zw = z2 - z1

Now we can just move and scale the poly cube transform to those values:

cmds.move(xc, yc, zc, cube)
cmds.scale(xw, yw, zw, cube)

That moves the transform of the polyCube to match, but if you just want to move the components, you can do this (note that I had to use the calculateExactly flag for it to work correctly in my test:

sel = cmds.ls(sl=True)

x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(sel, calculateExactly=True)

cube = cmds.polyCube()[0]
cmds.move(x1, '%s.f[5]' % cube, x=True)
cmds.move(y1, '%s.f[3]' % cube, y=True)
cmds.move(z1, '%s.f[2]' % cube, z=True)
cmds.move(x2, '%s.f[4]' % cube, x=True)
cmds.move(y2, '%s.f[1]' % cube, y=True)
cmds.move(z2, '%s.f[0]' % cube, z=True)
like image 133
Gary Fixler Avatar answered Sep 22 '22 20:09

Gary Fixler