Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

I have following function in 3ds Max Script to create a box with desired dimension…

  1. User

    I have following function in 3ds Max Script to create a box with desired dimension entered by user in specific format. And it even checks system units scale and display unit scale, and ask user to change it to decimal inches: -- Function to create the box based on parsed dimensions fn createBoxFromDimensions dimensions placement = ( -- Check if the input is empty if dimensions == "" then ( messageBox "Error: The input field is empty.\nPlease paste the dimensions from ALL3D portal in correct format as shown below:\n\nHeight\n0 Inches\nWidth\n0 Inches\nDepth\n0 Inches." title:"ALL3D Scene Validator" icon:#critical ) else ( -- Split input into lines and initialize variables local lines = filterString dimensions "\n" local height = undefined local width = undefined local depth = undefined local valid = true

            -- Check if there are enough lines to parse
            if lines.count >= 6 then
            (
                -- Parse lines for expected keywords and values
                for i = 1 to lines.count - 1 by 2 do
                (
                    case lines[i] of
                    (
                        "Height": height = (substituteString lines[i+1] " Inches" "") as float
                        "Width": width = (substituteString lines[i+1] " Inches" "") as float
                        "Depth": depth = (substituteString lines[i+1] " Inches" "") as float
                        default: valid = false
                    )
                )
                
                -- Validate all dimensions are defined
                if height == undefined or width == undefined or depth == undefined then valid = false
            )
            else
            (
                valid = false
            )
            
            -- Create box if valid, otherwise show an error
            if valid then
            (
                -- Create box at origin with parsed dimensions
                local boxObj = box length:depth width:width height:height pos:[0,0,0] name:"Overall_Dimension"
                boxObj.wirecolor = (color 255 0 0)
                case placement of (
                    1: boxObj.pivot = [boxObj.center.x, boxObj.center.y, boxObj.min.z]
                    2: boxObj.pivot = [boxObj.center.x, boxObj.center.y, boxObj.max.z]
                    3: boxObj.pivot = [boxObj.center.x, boxObj.max.y, boxObj.center.z]
                    default: boxObj.pivot = [boxObj.center.x, boxObj.center.y, boxObj.min.z]
                )
                boxObj.pos = [0,0,0]
                boxObj.boxmode = true
                
                -- Destroy the dialog
                if DimensionDialogFloater != undefined do closeRolloutFloater DimensionDialog
            )
            else
            (
                messageBox "Error: Please enter the dimensions in the correct format as shown below:\n\nHeight\n0 Inches\nWidth\n0 Inches\nDepth\n0 Inches" title:"ALL3D Scene Validator" icon:#critical
            )
        )
    )
    

    fn checkAndSetUnitsToInches = ( -- Check if system unit scale is set to inches local currentSystemUnit = units.systemtype local currentDisplayUnit = units.displayType

        if currentSystemUnit != #inches or currentDisplayUnit != #US then (
            -- Prompt user if they want to change the unit to inches
            local result = queryBox ("System unit scale is " + currentSystemUnit + " and display unit scale is " + currentDisplayUnit + ".\nWould you like to change both to inches?") title:"Unit Scale Check"
            if result == true then (
                -- Set system unit scale to inches
                units.systemtype = #Inches
                -- Set display unit scale to decimal inches
                units.DisplayType = #US
                units.USType = #Dec_In
                messageBox "System and display units have been set to inches." title:"Units Set"
            ) else (
                messageBox "Units remain unchanged." title:"No Changes Made"
            )
        ) else (
            format "System and display units are already set to inches.\n"
        )
    )
    
    -- UI Dialog
    rollout DimensionDialog "Dimension Box Creator"
    (
        editText dimensionsInput "Paste Dimensions:" height:100
        radioButtons dimensionPlacement "Placement:" labels:#("Floor", "Ceiling", "Wall")
        button createBoxButton "Create Dimension Box"
    
        -- Event handler for button click
        on createBoxButton pressed do
        (
            local dimensions = dimensionsInput.text
            local placement = dimensionPlacement.state
            createBoxFromDimensions dimensions placement
        )
    )
    

    Now, I want you to write similar functions for Maya 2022.

  2. Assistant

    Sure! Below is a Python script for Maya 2022 that replicates the functionality of your 3ds Max script. This script creates a box based on user-entered dimensions, checks and sets the unit system to inches if necessary, and provides a user interface for input.

    Script Overview

    1. Unit Checking and Setting:

      • The script checks Maya's current unit settings.
      • If the system units are not set to inches, it prompts the user to change them to inches.
    2. Dimension Parsing and Validation:

      • The script expects dimensions to be pasted in the following format:
        Height
        10 Inches
        Width
        5 Inches
        Depth
        8 Inches
        
      • It parses the input, validates the format, and extracts numerical values for height, width, and depth.
    3. Box Creation:

      • Creates a polygonal box with the specified dimensions.
      • Applies a red color to the box for easy identification.
      • Sets the pivot point based on the user's placement selection (Floor, Ceiling, or Wall).
    4. User Interface:

      • A dialog window allows users to paste dimensions, choose the placement, and create the box.

    Complete Python Script for Maya 2022

    import maya.cmds as cmds
    import maya.mel as mel
    
    def check_and_set_units_to_inches():
        """
        Check if the current unit system is set to inches.
        If not, prompt the user to change it to inches.
        """
        current_linear_unit = cmds.currentUnit(query=True, linear=True)
        
        if current_linear_unit.lower() != 'inch':
            result = cmds.confirmDialog(
                title='Unit Scale Check',
                message=f"Current linear unit is '{current_linear_unit}'.\nWould you like to change it to inches?",
                button=['Yes', 'No'],
                defaultButton='Yes',
                cancelButton='No',
                dismissString='No'
            )
            if result == 'Yes':
                cmds.currentUnit(linear='inch')
                cmds.confirmDialog(
                    title='Units Set',
                    message="System and display units have been set to inches.",
                    button=['OK'],
                    defaultButton='OK'
                )
            else:
                cmds.confirmDialog(
                    title='No Changes Made',
                    message="Units remain unchanged.",
                    button=['OK'],
                    defaultButton='OK'
                )
        else:
            cmds.confirmDialog(
                title='Units Check',
                message="System and display units are already set to inches.",
                button=['OK'],
                defaultButton='OK'
            )
    
    def create_box_from_dimensions(dimensions, placement):
        """
        Create a box based on the parsed dimensions and placement.
    
        Parameters:
        - dimensions: Multiline string containing Height, Width, and Depth.
        - placement: String indicating placement ('Floor', 'Ceiling', 'Wall').
        """
        if not dimensions.strip():
            cmds.confirmDialog(
                title='ALL3D Scene Validator',
                message=("Error: The input field is empty.\n"
                         "Please paste the dimensions from ALL3D portal in correct format as shown below:\n\n"
                         "Height\n10 Inches\nWidth\n5 Inches\nDepth\n8 Inches."),
                button=['OK'],
                icon='critical'
            )
            return
    
        # Split input into lines and initialize variables
        lines = [line.strip() for line in dimensions.strip().split('\n') if line.strip()]
        height = width = depth = None
        valid = True
    
        if len(lines) >= 6:
            try:
                for i in range(0, len(lines) - 1, 2):
                    key = lines[i].lower()
                    value = lines[i + 1].lower()
                    if 'inches' in value:
                        numeric_value = float(value.replace('inches', '').strip())
                    else:
                        valid = False
                        break
    
                    if key == 'height':
                        height = numeric_value
                    elif key == 'width':
                        width = numeric_value
                    elif key == 'depth':
                        depth = numeric_value
                    else:
                        valid = False
                        break
            except (ValueError, IndexError):
                valid = False
        else:
            valid = False
    
        # Validate all dimensions are defined
        if height is None or width is None or depth is None:
            valid = False
    
        if not valid:
            cmds.confirmDialog(
                title='ALL3D Scene Validator',
                message=("Error: Please enter the dimensions in the correct format as shown below:\n\n"
                         "Height\n10 Inches\nWidth\n5 Inches\nDepth\n8 Inches"),
                button=['OK'],
                icon='critical'
            )
            return
    
        # Create box at origin with parsed dimensions
        box_obj = cmds.polyCube(width=width, height=height, depth=depth, name='Overall_Dimension')[0]
    
        # Apply red color to the box
        shading_grp = cmds.sets(renderable=True, noSurfaceShader=True, empty=True, name=f"{box_obj}_SG")
        lambert = cmds.shadingNode('lambert', asShader=True, name=f"{box_obj}_lambert")
        cmds.setAttr(f"{lambert}.color", 1, 0, 0, type='double3')  # Red color
        cmds.connectAttr(f"{lambert}.outColor", f"{shading_grp}.surfaceShader", force=True)
        cmds.sets(box_obj, edit=True, forceElement=shading_grp)
    
        # Adjust pivot based on placement
        bbox = cmds.exactWorldBoundingBox(box_obj)
        min_x, min_y, min_z, max_x, max_y, max_z = bbox
        center_x = (min_x + max_x) / 2
        center_y = (min_y + max_y) / 2
    
        if placement == 'Floor':
            pivot = (center_x, center_y, min_z)
        elif placement == 'Ceiling':
            pivot = (center_x, center_y, max_z)
        elif placement == 'Wall':
            pivot = (max_x, center_y, (min_z + max_z) / 2)
        else:
            pivot = (center_x, center_y, min_z)  # Default to Floor
    
        cmds.xform(box_obj, centerPivots=True)
        cmds.move(pivot[0], pivot[1], pivot[2], box_obj, absolute=True, pivot=True)
    
    def dimension_box_creator_ui():
        """
        Create the user interface for the Dimension Box Creator.
        """
        window_name = "DimensionBoxCreatorWindow"
    
        if cmds.window(window_name, exists=True):
            cmds.deleteUI(window_name, window=True)
    
        window = cmds.window(window_name, title="Dimension Box Creator", widthHeight=(400, 200))
    
        cmds.columnLayout(adjustableColumn=True, rowSpacing=10, columnOffset=("both", 10))
    
        cmds.text(label="Paste Dimensions:", align='left')
        dimensions_input = cmds.scrollField(text='', wordWrap=True, height=100)
    
        cmds.text(label="Placement:", align='left')
        placement_radio = cmds.radioButtonGrp(
            name='placementRadio',
            label='Placement:',
            labelArray3=['Floor', 'Ceiling', 'Wall'],
            numberOfRadioButtons=3,
            select=1
        )
    
        cmds.separator(height=10, style='in')
    
        def on_create_box_pressed(*args):
            dimensions = cmds.scrollField(dimensions_input, query=True, text=True)
            selected = cmds.radioButtonGrp(placement_radio, query=True, select=True)
            placement = {1: 'Floor', 2: 'Ceiling', 3: 'Wall'}.get(selected, 'Floor')
            create_box_from_dimensions(dimensions, placement)
    
        cmds.button(label="Create Dimension Box", command=on_create_box_pressed)
    
        cmds.setParent('..')  # End columnLayout
        cmds.showWindow(window)
    
    def initialize_dimension_box_creator():
        """
        Initialize the Dimension Box Creator by checking units and launching the UI.
        """
        check_and_set_units_to_inches()
        dimension_box_creator_ui()
    
    # Run the script
    initialize_dimension_box_creator()
    

    How to Use the Script

    1. Open Maya 2022:

      • Start Maya 2022 and ensure you have a clean scene or are ready to add the dimension box.
    2. Access the Script Editor:

      • Go to Windows > General Editors > Script Editor.
    3. Create a New Python Tab:

      • In the Script Editor, switch to the Python tab if it's not already selected.
    4. Paste the Script:

      • Copy the entire script provided above and paste it into the Python tab.
    5. Execute the Script:

      • Press Ctrl + Enter (Windows) or Cmd + Enter (Mac) to execute the script.
      • This will open the Dimension Box Creator dialog.
    6. Set Units (If Prompted):

      • If your current unit system is not in inches, the script will prompt you to change it to inches.
      • Choose Yes to change units or No to keep them as is.
    7. Enter Dimensions:

      • In the Paste Dimensions field, paste your dimensions in the following format:
        Height
        10 Inches
        Width
        5 Inches
        Depth
        8 Inches
        
      • Ensure there are no typos and the format is consistent.
    8. Select Placement:

      • Choose where you want the pivot to be set for the box by selecting Floor, Ceiling, or Wall.
    9. Create the Box:

      • Click the Create Dimension Box button.
      • If the input is valid, a red-colored box with the specified dimensions will be created.
      • The pivot point will be adjusted based on your placement selection.
    10. Error Handling:

      • If the input is empty or incorrectly formatted, the script will display an error message prompting you to correct the input.

    Script Features and Details

    • Unit Management:

      • Utilizes cmds.currentUnit to get and set the current linear units.
      • Prompts the user with dialog boxes using cmds.confirmDialog for better user interaction.
    • Dimension Parsing:

      • Strips and splits the input text to extract dimensions.
      • Converts string values to floating-point numbers for precision.
    • Box Creation:

      • Uses cmds.polyCube to create the box with specified dimensions.
      • Applies a Lambert shader with red color to the box for visibility.
      • Adjusts the pivot point using cmds.xform and cmds.move based on the user's placement choice.
    • User Interface:

      • Built using Maya's cmds module with window, columnLayout, scrollField, radioButtonGrp, and button.
      • Ensures that only one instance of the window exists at a time by deleting any existing window with the same name before creating a new one.
    • Error Messages:

      • Provides clear and concise error messages using cmds.confirmDialog to guide the user in case of incorrect input or actions.

    Notes and Recommendations

    • Customization:

      • You can modify the script to change the box color, default placements, or add more placement options as needed.
    • Enhancements:

      • Implement additional validation to handle more edge cases or different unit formats.
      • Add options to position the box at different locations in the scene instead of the origin.
    • Saving the Script:

      • For repeated use, consider saving the script as a Python file and adding it to Maya's shelf or menu for quick access.

    By using this script, you can efficiently create dimension-based boxes in Maya 2022, ensuring consistency and accuracy in your scenes. If you have any further questions or need additional features, feel free to ask!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.