[Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-05 Thread Michael Boon
OK I ran out of time but I do have something. The interface is very rough - 
it only uses the first selected component, and I don't have it selecting 
the result at the end. However, it does process 90,000 faces in under 1 
second on my PC. So that's something :)

import math
import maya.api.OpenMaya as om

def getCoplanarFaceIds(fnMesh, ids, angle):
''' Accepts, and returns, a list of face IDs. '''
dot = math.cos(math.radians(angle))
itPoly = om.MItMeshPolygon(fnMesh.getPath())
# Keep track of ids both as a list and a set.
# Checking if an element is in a set is much faster than a list.
idSet = set(ids)
i = 0
while i < len(ids):
itPoly.setIndex(ids[i])
normal = itPoly.getNormal()
connectedIds = itPoly.getConnectedFaces()
for c in connectedIds:
if c not in idSet:
itPoly.setIndex(c)
if normal * itPoly.getNormal() > dot:
ids.append(c)
idSet.add(c)
i += 1
return ids

# Here's a rough script to drive the function. 
selList = om.MGlobal.getActiveSelectionList()
for i in range(selList.length()):
try:
dagPath, comp = selList.getComponent(i)
except TypeError:
continue # Probably a DG node, like a material.
if comp == om.MObject.kNullObj:
continue # Not a component
else:
if dagPath.hasFn(om.MFn.kMesh):
# Just as a quick test, use the first component we find.
# TODO: At least check it's meant to be a face!
fnMesh = om.MFnMesh(dagPath)
fnComp = om.MFnSingleIndexedComponent(comp)
id = fnComp.element(0)
print 'Using {}.f[{}]'.format(fnMesh.partialPathName(), id)
connectedFaceIds = getCoplanarFaceIds(fnMesh, [id], 15)
break
print len(connectedFaceIds)

Incidentally here's some profile info. I was wrong about appending to the 
list taking significant time. The missing time here would be mostly used by 
the "if c not in idSet" line, I expect.
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
10.0030.0030.6630.663 :2()
10.2080.2080.6590.659 :2(getCoplanarFaceIds)
90.2430.0000.2430.000 {method 'getConnectedFaces' 
of 'OpenMaya.MItMeshPolygon' objects}
   170.1750.0000.1750.000 {method 'getNormal' of 
'OpenMaya.MItMeshPolygon' objects}
   170.0120.0000.0120.000 {method 'setIndex' of 
'OpenMaya.MItMeshPolygon' objects}
80.0090.0000.0090.000 {method 'add' of 'set' 
objects}
80.0060.0000.0060.000 {method 'append' of 'list' 
objects}
900040.0060.0000.0060.000 {len}



On Thursday, 5 April 2018 17:06:33 UTC+10, Michael Boon wrote:
>
> 100,000 faces would take minutes. Growing a list one element at a time in 
> Python gets very slow as your list gets big.
>
> I start with a flattened list of faces, then I'm just looping on my list 
> until I get to the end. Inside the loop looks a bit like this:
> normal = face.getNormal()
> connected = face.connectedFaces()
> for f in connected:
> # If f is already in my list, continue
> # Test normal.dot(f.getNormal()) and add to the end of the list if it 
> passes
>
> That's pretty much it. I haven't needed to flatten any components (though 
> if you find a case where you think you do, I'd advise you try to use them 
> as they are, because a mesh component iterable is an API data structure, 
> and flattening it into individual mesh components involves a lot of Python 
> behind the scenes.
>
> If you want to use it on 100,000 faces and you don't want to learn how to 
> do it in C++ (which is fair enough), maybe try the Python API. One huge 
> advantage of the API is the array types, which manage their memory very 
> well and can be arbitrarily grown to 100,000 or even millions of elements 
> without slowing everything horribly like Python lists would*. The logic 
> would be very similar (using MItMeshPolygon instead of MeshFace) and I 
> don't think it would be much faster for smaller selections, but it could 
> handle larger ones better.
>
> (*Alternatively you can pre-assign the size of your Python lists, and keep 
> track of the number of used elements yourself. Sometimes that's easier.)
>
> Honestly I'm really intrigued now. Hopefully I'll have time tonight to try 
> to make a version that can handle big numbers.
>
> On Thursday, 5 April 2018 16:29:06 UTC+10, Darby Edelen wrote:
>>
>> There are definitely some intricacies of pymel that elude me. I don't 
>> know, for example, how to get a flattened list of connected faces without 
>> using ls. Or perhaps I don't need a flattened list? I assume that I need to 
>> getNormal on each face and compare against its connected faces in order to 
>> decide which faces to extend to on the next step. Can I do that if 
>> connectedFaces isn't giving 

[Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-05 Thread Michael Boon
100,000 faces would take minutes. Growing a list one element at a time in 
Python gets very slow as your list gets big.

I start with a flattened list of faces, then I'm just looping on my list 
until I get to the end. Inside the loop looks a bit like this:
normal = face.getNormal()
connected = face.connectedFaces()
for f in connected:
# If f is already in my list, continue
# Test normal.dot(f.getNormal()) and add to the end of the list if it 
passes

That's pretty much it. I haven't needed to flatten any components (though 
if you find a case where you think you do, I'd advise you try to use them 
as they are, because a mesh component iterable is an API data structure, 
and flattening it into individual mesh components involves a lot of Python 
behind the scenes.

If you want to use it on 100,000 faces and you don't want to learn how to 
do it in C++ (which is fair enough), maybe try the Python API. One huge 
advantage of the API is the array types, which manage their memory very 
well and can be arbitrarily grown to 100,000 or even millions of elements 
without slowing everything horribly like Python lists would*. The logic 
would be very similar (using MItMeshPolygon instead of MeshFace) and I 
don't think it would be much faster for smaller selections, but it could 
handle larger ones better.

(*Alternatively you can pre-assign the size of your Python lists, and keep 
track of the number of used elements yourself. Sometimes that's easier.)

Honestly I'm really intrigued now. Hopefully I'll have time tonight to try 
to make a version that can handle big numbers.

On Thursday, 5 April 2018 16:29:06 UTC+10, Darby Edelen wrote:
>
> There are definitely some intricacies of pymel that elude me. I don't 
> know, for example, how to get a flattened list of connected faces without 
> using ls. Or perhaps I don't need a flattened list? I assume that I need to 
> getNormal on each face and compare against its connected faces in order to 
> decide which faces to extend to on the next step. Can I do that if 
> connectedFaces isn't giving me a flattened list?
>
> As for the speed at which this script and the similar built-in selection 
> constraints operate, they are woefully slow in comparison to the cinema 4d 
> tool I'm trying to emulate. I think there must be some data built behind 
> the scenes to accelerate this sort of selection.
>
> Can you provide me with any further hints? Is your 8 line script able to 
> select upwards of 100,000 faces within an arbitrary angle tolerance in 
> under a second or should I adjust my expectations?
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to python_inside_maya+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/python_inside_maya/f99a3196-42d0-4287-b7ac-6355a13bebce%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-04 Thread Darby Edelen
There are definitely some intricacies of pymel that elude me. I don't know, for 
example, how to get a flattened list of connected faces without using ls. Or 
perhaps I don't need a flattened list? I assume that I need to getNormal on 
each face and compare against its connected faces in order to decide which 
faces to extend to on the next step. Can I do that if connectedFaces isn't 
giving me a flattened list?

As for the speed at which this script and the similar built-in selection 
constraints operate, they are woefully slow in comparison to the cinema 4d tool 
I'm trying to emulate. I think there must be some data built behind the scenes 
to accelerate this sort of selection.

Can you provide me with any further hints? Is your 8 line script able to select 
upwards of 100,000 faces within an arbitrary angle tolerance in under a second 
or should I adjust my expectations?

-- 
You received this message because you are subscribed to the Google Groups 
"Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to python_inside_maya+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/python_inside_maya/1198629a-8a12-4618-ae61-caf12936011a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


[Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-04 Thread Michael Boon
(I got a little cocky there. My script doesn't do a check for hard edges!)

On Thursday, 5 April 2018 15:51:55 UTC+10, Michael Boon wrote:
>
> It's a bit of a myth, or at least an over-simplification, to say that 
> PyMel is slower and maya.cmds is faster. MEL and maya.cmds tend to be slow 
> because they do string processing for almost everything (and for that 
> reason they're also error-prone once you get into scenes with instances). 
> PyMel tends to be slow because it often wraps maya.cmds, and then spends 
> more time creating Python objects for things, but it can also be faster 
> than cmds because it often wraps the API and sometimes you can get the API 
> to do the work under the hood where cmds would be juggling strings.
>
> So in general, like Justin suggested, profile your code (there's a profile 
> module in Python) and look for hot spots.
>
> In this case though, I have written a script using PyMel that I can't 
> share, but it's only 8 simple lines and I think it does what you want, 
> plenty fast for your needs. Sorry! That's rude I know, but I don't own it! 
> Use the MeshFace class, and its methods connectedFaces and getNormal. Don't 
> use ls or polyListComponentConversion at all in your loop - those can be 
> pathological examples of PyMel slowness.
>
> I hope that helps :)
>
>
> On Wednesday, 4 April 2018 14:44:28 UTC+10, Darby Edelen wrote:
>>
>> Hello,
>>
>> I'm new to the list and relatively new to Maya.
>>
>> I've been missing a tool in Cinema 4D that allows the user to select 
>> contiguous faces within boundaries defined by differences in polygon normal 
>> angles (boundaries = hard edges or an arbitrary angle), so I rolled my own 
>> Maya script.
>>
>> It seems to be working well, but it gets quite slow as the number of 
>> faces to select increases.  For example, on my home PC it takes about 6 
>> seconds to select 320 faces along the inside of a ring.
>>
>> If you have any ideas on how I could implement this more efficiently I 
>> would love your input.  I've heard that PyMEL tends to be the slowest of 
>> options for scripting, but it's super convenient to work in a more 
>> 'pythonic' mode.  I started playing with the OpenMaya API but found that it 
>> doesn't seem to have a polyListComponentConversion equivalent and my brain 
>> is fried enough that I can't think about implementing my own version using 
>> the API.  I have a suspicion that the polyListComponentConversion function 
>> is one of those adding the most time to execution;  I'm using it to find 
>> the boundary edges of the faces currently marked for selection.
>>
>> I've attached a .py file and pasted my code here as well:
>>
>> import pymel.core as pm
>> import time
>> import itertools
>>
>> def compare_normals(n1, n2):
>> #Take dot product of normals and convert to degrees difference
>> return 90.0 * (1.0 - n1*n2)
>>
>> def check_angle(edge, angle, hard_edges=True):
>> if edge.isOnBoundary():
>> #Boundary reached; no need to continue!
>> return False
>> 
>> soft = True
>> if hard_edges:
>> #Check for hard or soft edge
>> soft = edge.isSmooth()
>> 
>> #Get all faces connected to this edge
>> faces = pm.ls(edge.connectedFaces(), fl=True)
>> #Compare the face normals between edges to determine if the face 
>> should be selected
>> face_compare = {c for c in itertools.combinations(faces, 2) if 
>> compare_normals(c[0].getNormal(), c[1].getNormal()) > angle}
>> 
>> #Returns True if the face should be selected
>> return len(face_compare) == 0 and soft
>> 
>>
>> def get_connected_faces(faces, angle=0.0, hard_edges=True):
>> #Get edge boundary of current face selection
>> boundary = pm.ls(pm.polyListComponentConversion(faces, bo=True, 
>> te=True), fl=True)
>> #Combine currently selected faces with neighboring faces that pass 
>> the face normal test
>> new_faces = faces | set(pm.ls([edge.connectedFaces() for edge in 
>> boundary if \
>>check_angle(edge, angle, hard_edges)], 
>> fl=True))
>>
>> if new_faces != faces:
>> #Yield the new faces to select for as long as we haven't 
>> exhausted our supply
>> yield new_faces
>> #Stop when there are no more faces to select
>> raise StopIteration
>>
>> t1 = time.clock()
>>
>> angle_tolerance = 30.0
>> hard_edges = True
>>
>> #Get the initial selection
>> selection = pm.ls(sl=True, fl=True)
>> #Filter the selection to face components
>> selected_faces = {face for face in selection if isinstance(face, 
>> pm.general.MeshFace)}
>>
>> if selected_faces:
>> #Since there are faces selected...
>> try:
>> while True:
>> #Find new neighboring faces until no more meet the criteria
>> selected_faces = get_connected_faces(selected_faces, 
>> angle_tolerance).next()
>> except StopIteration:
>> #Select all faces found
>> pm.select(selected_faces)
>> t2 =

[Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-04 Thread Michael Boon
It's a bit of a myth, or at least an over-simplification, to say that PyMel 
is slower and maya.cmds is faster. MEL and maya.cmds tend to be slow 
because they do string processing for almost everything (and for that 
reason they're also error-prone once you get into scenes with instances). 
PyMel tends to be slow because it often wraps maya.cmds, and then spends 
more time creating Python objects for things, but it can also be faster 
than cmds because it often wraps the API and sometimes you can get the API 
to do the work under the hood where cmds would be juggling strings.

So in general, like Justin suggested, profile your code (there's a profile 
module in Python) and look for hot spots.

In this case though, I have written a script using PyMel that I can't 
share, but it's only 8 simple lines and I think it does what you want, 
plenty fast for your needs. Sorry! That's rude I know, but I don't own it! 
Use the MeshFace class, and its methods connectedFaces and getNormal. Don't 
use ls or polyListComponentConversion at all in your loop - those can be 
pathological examples of PyMel slowness.

I hope that helps :)


On Wednesday, 4 April 2018 14:44:28 UTC+10, Darby Edelen wrote:
>
> Hello,
>
> I'm new to the list and relatively new to Maya.
>
> I've been missing a tool in Cinema 4D that allows the user to select 
> contiguous faces within boundaries defined by differences in polygon normal 
> angles (boundaries = hard edges or an arbitrary angle), so I rolled my own 
> Maya script.
>
> It seems to be working well, but it gets quite slow as the number of faces 
> to select increases.  For example, on my home PC it takes about 6 seconds 
> to select 320 faces along the inside of a ring.
>
> If you have any ideas on how I could implement this more efficiently I 
> would love your input.  I've heard that PyMEL tends to be the slowest of 
> options for scripting, but it's super convenient to work in a more 
> 'pythonic' mode.  I started playing with the OpenMaya API but found that it 
> doesn't seem to have a polyListComponentConversion equivalent and my brain 
> is fried enough that I can't think about implementing my own version using 
> the API.  I have a suspicion that the polyListComponentConversion function 
> is one of those adding the most time to execution;  I'm using it to find 
> the boundary edges of the faces currently marked for selection.
>
> I've attached a .py file and pasted my code here as well:
>
> import pymel.core as pm
> import time
> import itertools
>
> def compare_normals(n1, n2):
> #Take dot product of normals and convert to degrees difference
> return 90.0 * (1.0 - n1*n2)
>
> def check_angle(edge, angle, hard_edges=True):
> if edge.isOnBoundary():
> #Boundary reached; no need to continue!
> return False
> 
> soft = True
> if hard_edges:
> #Check for hard or soft edge
> soft = edge.isSmooth()
> 
> #Get all faces connected to this edge
> faces = pm.ls(edge.connectedFaces(), fl=True)
> #Compare the face normals between edges to determine if the face 
> should be selected
> face_compare = {c for c in itertools.combinations(faces, 2) if 
> compare_normals(c[0].getNormal(), c[1].getNormal()) > angle}
> 
> #Returns True if the face should be selected
> return len(face_compare) == 0 and soft
> 
>
> def get_connected_faces(faces, angle=0.0, hard_edges=True):
> #Get edge boundary of current face selection
> boundary = pm.ls(pm.polyListComponentConversion(faces, bo=True, 
> te=True), fl=True)
> #Combine currently selected faces with neighboring faces that pass the 
> face normal test
> new_faces = faces | set(pm.ls([edge.connectedFaces() for edge in 
> boundary if \
>check_angle(edge, angle, hard_edges)], 
> fl=True))
>
> if new_faces != faces:
> #Yield the new faces to select for as long as we haven't exhausted 
> our supply
> yield new_faces
> #Stop when there are no more faces to select
> raise StopIteration
>
> t1 = time.clock()
>
> angle_tolerance = 30.0
> hard_edges = True
>
> #Get the initial selection
> selection = pm.ls(sl=True, fl=True)
> #Filter the selection to face components
> selected_faces = {face for face in selection if isinstance(face, 
> pm.general.MeshFace)}
>
> if selected_faces:
> #Since there are faces selected...
> try:
> while True:
> #Find new neighboring faces until no more meet the criteria
> selected_faces = get_connected_faces(selected_faces, 
> angle_tolerance).next()
> except StopIteration:
> #Select all faces found
> pm.select(selected_faces)
> t2 = time.clock()
> #Report our performance
> print("Selected {0} faces in {1:.2f} 
> seconds.".format(len(selected_faces), t2-t1))
>
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Python Programming for Autodesk Maya" group.

Re: [Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-04 Thread Tim Fowler
There's also a couple ways of doing this kind of thing in Maya...

In the Modeling Toolkit panel you can set the "Selection Constraint"
drop-down to "Angle" and then play with the value (which I think is the
angle in degrees bewteen the face normals).  That will transform every
selection you make to expand out based on the angle between the faces.  It
works on faces/edges/vertices.  You'll also see it highlight what it will
select when you have pre-select-highlight on, which can be usefull.

Then there's Select -> Similar.  Read the doc's on this one since it can do
something similar to what yiou want for components, but it also does stuff
for object selection.

The Select Similar component behaviour is based on selection constraints,
so you can also read the docs on polySelectConstraint and look at the UI
under Select -> Use Constraints.  That does have a lot of options, but
-anglePropagation is probably the main one you're looking for.

-Tim

-- 
You received this message because you are subscribed to the Google Groups 
"Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to python_inside_maya+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/python_inside_maya/CALKD2WqKvS-BSFoPMu0J%3Dmuskvi7RhUvjZj48sxGHSZQ8EBd0w%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


[Maya-Python] Re: Looking for Feedback on This Face Selection Script

2018-04-04 Thread justin hidair
You don't need to use one workflow you can use maya.cmds it has 
polyListComponentConversion , and the maya python api 2.0 ( 
maya.api.OpenMaya , which is pythonic AF  ) , yeah I suggest you get rid of 
pymel you don't need it

>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to python_inside_maya+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/python_inside_maya/5abf6c87-fad3-4627-99c3-93a7a100e054%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.