How do I align the UVW_Modifier's Gizmo to a selected face?

The following code implements the "Normal Align" feature of the UVW_Map modifier. The "Normal Align" button is not directly accessible to MAXScript. This function can be used as a replacement, and might help you understand the usefulness of the Vector Cross Product.

SCRIPT

clearListener()
try(DestroyDialog AlignRollout)catch()
Rollout AlignRollout "Align Gizmo"
(    

    button bn_test "Align Gizmo"

     fn alignUVGizmo theObj theFace =
     (         
        -- First get the face normal vector.
        local faceNormal = coordsys theObj (polyop.getFaceNormal theObj theFace)

        -- Get the face center from the editable poly to put the gizmo at that place
        local translation                 = [0,0,0]
        local FaceVertexsIndicesArray    = (polyop.GetFaceVerts theObj theFace)
        local numVerts = FaceVertexsIndicesArray.count
        for i in FaceVertexsIndicesArray do(
            translation += (theObj.GetVertex i)    --Assuming it's an editable poly object
        )
        translation /= numVerts

        -- Create a matrix from the normal
        local theMatrix = MatrixFromNormal faceNormal
        theMatrix.translation = translation --Set our computed translation to be on the face

        -- Create UVWMap modifier
        theMap = Uvwmap()
        -- Add it to the selection
        modPanel.addModToSelection theMap ui:on
        -- Set the transform on it
        theMap.gizmo.transform = theMatrix
    )


    on bn_test pressed do
    (
        if (undefined != $)do
        (
            convertToPoly $        

            -- Align the gizmo of the uv map modifier to the first face of the mesh
            alignUVGizmo $ 2
        )
    )


)
CreateDialog AlignRollout