Introduction........................................................................................................xxxi 3ds max 4 MAXScript Online Reference ................................................................................. xxxi MAXScript Overview .............................................................................................................. xxxii Using the MAXScript Documentation .................................................................................. xxxiii The MAXScript Utility Panel ...................................................................................................... xxxiv The MAXScript Listener Window ......................................................................................... xxxvi Using the MAXScript Listener .............................................................................................. xxxvii Listener Commands ............................................................................................................ xxxviii Using the ‘?’ Symbol................................................................................................................... xli Turning On the Listener Log...................................................................................................... xli Controlling the Listener Contents and the Insertion Point ..................................................... xlii The MAXScript Editor Windows .............................................................................................. xliv MAXScript Editor Commands.................................................................................................. xlvi Running Scripts ........................................................................................................................ xlix Accessing Scripted Utilities............................................................................................................ l The Macro Recorder....................................................................................................................... l General MAXScript Topics...............................................................................................................lii Error Messages ............................................................................................................................ liii Aborting Execution with the ESC Key ........................................................................................ lv MAXScript Desktop State ........................................................................................................... lvi Startup Scripts............................................................................................................................. lvi Running Scripts from the Command Line................................................................................ lvii Source Code Layout and Continuation Lines ........................................................................... lvii Including Scripts Within Scripts ................................................................................................ lix Encrypting Script Files ................................................................................................................. lx Syntax Definitions in This Document ..............................................................................................lx Objects and Classes in Object-Oriented Programming ................................................................lxii Inheritance and Polymorphism ............................................................................................... lxiii Properties, Methods, Operators, and Literals ........................................................................... lxiv
iv
Contents
Chapter 1 What’s New in 3ds max 4 MAXScript .................................................... 1 What’s New in 3ds max 4 MAXScript......................................................................................... 1 version 4 MAXScript New Features ................................................................................................. 9 Action Manager ............................................................................................................................... 9 ActiveX Controls in MAXScript Rollouts........................................................................................ 10 Asset Browser................................................................................................................................. 22 Asset Browser enhancements ..................................................................................................... 22 Bones.............................................................................................................................................. 23 Access to the node bone properties and methods ..................................................................... 23 Bone Creation............................................................................................................................. 25 Cache Modifiers ............................................................................................................................. 26 Point Cache Modifier ..................................................................................................................... 26 CallBack Notification Codes........................................................................................................... 27 Notify Callbacks for Animate button on and off Transitions.................................................... 27 RenderEffects Progress Callback Mechanism ............................................................................ 28 General Event Callback Mechanism .......................................................................................... 29 Color Manager ............................................................................................................................... 35 Combustion.................................................................................................................................... 38 Constraints ..................................................................................................................................... 39 Path Constraint .......................................................................................................................... 39 LookAt Constraint ...................................................................................................................... 40 Orientation Constraint Controller............................................................................................. 40 Position Constraint .................................................................................................................... 41 Link Controller for Constraints ................................................................................................. 42 Controller Functions for use with Constraint Assignments ...................................................... 42 Context Filters................................................................................................................................ 43 Custom Attributes.......................................................................................................................... 45 Scripted Custom Attributes ........................................................................................................ 45 Depth of Field ................................................................................................................................ 54 Edit Mesh ....................................................................................................................................... 54 ApplyOperation function ........................................................................................................... 54 Editable Patch ................................................................................................................................ 55 Patches ........................................................................................................................................ 55 Filters.............................................................................................................................................. 59 class id filter ................................................................................................................................ 59 Selection Filter ............................................................................................................................ 61 i-drop - drag and drop................................................................................................................... 62 Interfaces........................................................................................................................................ 67 Core Interfaces............................................................................................................................ 70 Other Interfaces .......................................................................................................................... 71 Inverse Kinematics ......................................................................................................................... 73 HD IK controller chains can be assigned to existing hierarchies .............................................. 73 IKLimb Solver ............................................................................................................................. 74 Materials ........................................................................................................................................ 75 Multi/Sub Material......................................................................................................................... 75 Menu Manager .............................................................................................................................. 75
Contents
Mesher ........................................................................................................................................... 82 Network Render Interface ............................................................................................................. 82 Node Handles................................................................................................................................. 83 Node vertexColorType................................................................................................................... 83 OLE Automation............................................................................................................................. 84 MAXScript.reg - Registery file..................................................................................................... 84 Parameter Wiring........................................................................................................................... 85 Plug-In Manager ............................................................................................................................ 86 Portable Licence Manager ............................................................................................................. 87 maxOps....................................................................................................................................... 87 Quad Menu .................................................................................................................................... 90 Reactors.......................................................................................................................................... 91 Reactor controller ....................................................................................................................... 91 Render Element Manager .............................................................................................................. 92 Scripted Plug-Ins ............................................................................................................................ 93 type:#integer parameters in scripted plug-in parameter blocks ................................................ 93 Scripted Plug-in Events............................................................................................................... 93 Scripted Cameras ........................................................................................................................... 94 Scripted Controllers ....................................................................................................................... 95 dependsOn For Scripted Controllers .......................................................................................... 95 Matrix3 Scripted Controller ....................................................................................................... 96 Scripted Manipulators ................................................................................................................... 97 Scripted Objects........................................................................................................................... 106 on detachedFromNode For Object Scripted Plug-ins ............................................................... 106 Scripted RenderEffects................................................................................................................. 107 RenderEffects Progress Callback Mechanism .......................................................................... 107 Scripted Rollouts .......................................................................................................................... 108 Multi-line editText UI items in Scripted Rollouts .................................................................... 108 Skin............................................................................................................................................... 109 Joint Angle Morph ....................................................................................................................... 109 Spring Controller ......................................................................................................................... 109 SubObject Mode .......................................................................................................................... 112 System Tools ................................................................................................................................ 112 Trackbar Interface ........................................................................................................................ 113 Trackviews.................................................................................................................................... 114 Visual MAXScript ......................................................................................................................... 117 Xref Objects ................................................................................................................................. 120 Zip-file Script Packages ................................................................................................................ 122 version 4 MAXScript Language Improvements .......................................................................... 127 Additional Keyword Parameter On pickObject() forceListenerFocus: ..................................... 127 Affect Region Function............................................................................................................. 127 “Apropos” and “ShowProperties” and now “Help” and “Show” ............................................ 128 BinStream for Binary Reading and Writing ............................................................................. 128 By Reference Parameter Passing ............................................................................................... 129 C++-style bracketing comments ............................................................................................... 131 Coercion of bitArray to array and integer arrays to bitArrays ................................................. 132 Command line -U MAXScript startup scripts .......................................................................... 133
v
vi
Contents
Detecting Deleted Nodes .......................................................................................................... 133 Dereferencing Operator ............................................................................................................ 133 forceUpdate Function added to UVWUnwrap......................................................................... 134 hasProperty() function ............................................................................................................. 135 Improved the Performance of Iterating and Indexing the ‘selection’ and ‘$’ Object Sets ...... 135 Readable/Writable Checks........................................................................................................ 135 isValidNode .............................................................................................................................. 136 RubberBanding in pickObject() Function ................................................................................ 136 SetDir ........................................................................................................................................ 136 Shortcut system replaced.......................................................................................................... 137 startObjectCreation()................................................................................................................ 138 Subanim Indexing Operator, [], on MAX Objects Now Takes Subanim Names...................... 139 superclasses read-only global variable...................................................................................... 139 Symbolic Pathnames ................................................................................................................ 140 System Information.................................................................................................................. 141 The Super Class ID and the Class ID ........................................................................................ 141 validModifier() function........................................................................................................... 142 Visible Class For ‘&’ Reference Values...................................................................................... 142 Controllers ................................................................................................................................... 143 List Controller .......................................................................................................................... 143 mapKeys() method ................................................................................................................... 144 moveKeys function................................................................................................................... 145 Geometry, Modifiers, Space Warps............................................................................................. 146 Hose - superclass: GeometryClass ............................................................................................ 146 Drag - superclass: SpacewarpObject ......................................................................................... 149 MultiRes - superclass: modifier................................................................................................. 153 Vortex - superclass: SpacewarpObject ...................................................................................... 156 Keys .............................................................................................................................................. 158 Object Inspector Functions .......................................................................................................... 159 Class and Object Inspector Functions Enhanced..................................................................... 159 Renderer....................................................................................................................................... 160 render() Function Re-entrant ................................................................................................... 160 SuperClasses................................................................................................................................. 161 Bitmap Manager – Function Published BMM control ............................................................. 161 Utilities, Global Utilities and Render Element plug-ins........................................................... 161 Renderer.................................................................................................................................... 162 2 New Scripted Plug-in Superclasses on apply handlers for scripted RenderEffects ................ 162 Globals and Locals ....................................................................................................................... 162 Definition Constructs Can Include Global Variable Declarations At Top Level ..................... 162 Changes to Undeclared Implicit Global Variables ................................................................... 163 Material Editor, Material and Textures ....................................................................................... 163 Accessing The Material Editor Active Slot................................................................................ 163 BitmapTex Reload and viewImage ........................................................................................... 164 BMP, PNG, JPEG and TGA I/O Interfaces ................................................................................ 164 Material Editor Access .............................................................................................................. 165 Material Level Show-in-viewport State .................................................................................... 166 showTextureMap() function .................................................................................................... 167
Contents
User Interface............................................................................................................................... 168 Angle UI element...................................................................................................................... 168 CreateDialog ............................................................................................................................. 169 Curve Control........................................................................................................................... 170 getTextExtent ........................................................................................................................... 175 isActive ..................................................................................................................................... 176 keyboard.escPressed.................................................................................................................. 176 macroScript Localization Support for CUI and menu files...................................................... 176 MAX Open & Save Dialogs....................................................................................................... 177 Menu and CUI Loading............................................................................................................ 178 mtlBrowser................................................................................................................................ 180 SetBackground Method ............................................................................................................ 180 mouseTrack() Function ............................................................................................................ 180 snapMode ................................................................................................................................. 182 Spinner UI Item setKeyBrackets ............................................................................................... 182 Timer UI element ..................................................................................................................... 183 TimeSlider on/off toggle........................................................................................................... 183 Undo/Redo Dropdown Labels .................................................................................................. 184 Zoom to Bounds ....................................................................................................................... 184 Command Panels and Rollout Pages........................................................................................... 185 Customize The Order of Rollup Pages...................................................................................... 185 MAXScript Dialogs and Rollout Floaters as Extended viewports............................................. 186 Rollout .Controls Property ....................................................................................................... 187 Rollout Systems ‘category’ Mechanism .................................................................................... 188 version 4 All Const and MAXScript Functions............................................................................. 188 Definitions for MAXScript internal organization .................................................................... 188 MAXScriptFunction List ........................................................................................................... 190 Const Class ............................................................................................................................... 191 Const Generic ........................................................................................................................... 195 Const MappedGeneric.............................................................................................................. 207 Const NodeGeneric .................................................................................................................. 209 Const Primitives ....................................................................................................................... 213 Const StructDef ........................................................................................................................ 231 Const StructDef Pages ................................................................................................................. 232 AttachCtrl const StructDef ....................................................................................................... 232 autoBackup const StructDef ..................................................................................................... 232 bit const StructDef.................................................................................................................... 233 boolObj const StructDef ........................................................................................................... 233 callbacks const StructDef.......................................................................................................... 233 cui const StructDef ................................................................................................................... 234 custAttributes const StructDef.................................................................................................. 234 DOF const StructDef................................................................................................................. 234 fileProperties const StructDef ................................................................................................... 235 flexOps const StructDef............................................................................................................ 235 gw const StructDef.................................................................................................................... 235 ik const StructDef ..................................................................................................................... 237 keyboard const StructDef ......................................................................................................... 237
Index ................................................................................................................. 1839
Introduction
3ds max 4 MAXScript Online Reference MAXScript is the built-in scripting language for 3ds max and 3D Studio VIZ. MAXScript provides 3ds max and 3DS VIZ users with the ability to: •
Script most aspects of the program’s use, such as modeling, animation, materials, rendering, and so on.
•
Control the program interactively through the command-line Listener window.
•
Package scripts within custom Utility panel rollouts or modeless windows, to give them a standard 3ds max or 3DS VIZ user interface.
•
Package scripts as a macro, and install these Macro Scripts as buttons in the 3ds max toolbars.
•
Extend or replace the user interface for objects, modifiers, materials, textures, render effects, and atmospheric effects.
•
Build scripted plug-ins for custom mesh objects, modifiers, and render effects.
•
Build custom import/export tools using the built-in file I/O.
•
Write procedural controllers that can access the entire state of the scene.
•
Build batch-processing tools, such as batch-rendering scripts.
•
Set up live interfaces to external systems through OLE Automation.
•
Record your actions in 3ds max as MAXScript commands.
•
Store in scene files the scripts to run for each of the notification events supported by 3ds max, such as pre- and post-scene file open, new, reset, scene file save, pre- and post-render, selection change, and so on.
Because the functionality of MAXScript is almost identical for both 3ds max and 3DS VIZ, this online reference refers to 3ds max to avoid using both product names redundantly. It also points out specific differences between MAXScript for 3ds max and 3DS VIZ.
xxxii
Chapter
|
Introduction
See also MAXScript Overview (p. xxxii) Using the MAXScript Documentation (p. xxxiii) The MAXScript Utility Panel (p. xxxiv) General MAXScript Topics (p. lii) Learning MAXScript (p. 577) Syntax Definitions in This Document (p. lx) Objects and Classes in Object-Oriented Programming (p. lxii) What’s New in MAXScript (p. 1) 3ds max 4 MAXScript Online Reference (p. xxxi)
MAXScript Overview The MAXScript language is specifically designed to complement 3ds max. It has many special features and constructs such as coordinate system contexts, object primitives and materials that mirror high-level concepts in the 3ds max user-interface. It has an animation mode with automatic keyframing and access to scene objects using hierarchical path names that match the 3ds max object hierarchy. The language syntax is simple enough for non-programmers, as it includes minimal punctuation and formatting rules. Coupled with the use of the command-line Listener window, the ability to install scripts as toolbar buttons, and the recording of user actions as MAXScript commands, MAXScript can be employed casually by the user while working in the 3ds max point-and-click user interface. MAXScript is also rich enough to enable sophisticated programming tasks, with capabilities such as 3D vector, matrix, and quaternion algebra. MAXScript is well suited to working with large collections of objects; for example, making complex procedural selections, constructing random star fields, or placing objects in numerically precise patterns. MAXScript allows scripts to be packaged as Utility panel rollouts, as modeless windows, and as 3ds max toolbar buttons. MAXScript can also be used to extend or replace the user interface for objects, modifiers, materials, textures, render effects, and atmospheric effects; or to create custom mesh objects, modifiers, and render effects. This allows job-specific tools to be scripted by the technical department and made available to artists and animators through standard 3ds max point-and-click user interfaces. MAXScript supports formatted text I/O, so it is possible to produce asset reports directly from 3ds max scene files and read files containing scene layout, naming, texture details, and so on, exported from other project management software. MAXScript can also be used as a high-level scene import utility. By outputting MAXScript scripts containing object creation commands, it is possible for other programs and packages to export directly using any of the high-level 3ds max constructs.
Using the MAXScript Documentation
Using the MAXScript Documentation This reference is written primarily for animators learning MAXScript. The topics are organized with the introductory material presented first, then descriptions of the MAXScript syntax and grammar, followed by a description of creating, accessing, and modifying the various 3ds max objects. These 3ds max objects include geometry objects, modifiers, controllers, materials, textures, and render effects. The MAXScript tools are then described, followed by descriptions of the methods for interacting with the 3ds max user interface, accessing external files, and establishing notifications to a script when an object or 3ds max state changes. Throughout these topics, the purpose and syntax of the commands in the MAXScript language are described. Although it’s helpful to have programming experience, the basic aspects of MAXScript do not require this or an in-depth understanding of the structure underlying 3ds max. Concepts presented in one topic do assume a basic understanding of the concepts presented in earlier topics. At the very least, the topics up to and including Controlling Program Flow (p. 691) should be read in order. By reading the topics in order, you will learn the MAXScript language starting with the basics, and work your way toward writing full-featured MAXScript utilities. In the later sections, features and techniques are presented for programmers with more advanced programming experience. For those new to MAXScript, Learning MAXScript (p. 577) provides an introduction to the features, syntax, and practical applications of MAXScript. For information about navigating this online reference, searching, and marking often-accessed topics, see topics in the last section, Using the HTML Help Viewer (p. 1715). To see what has been added to MAXScript in 3ds max 4, see What’s New in MAXScript (p. 1).
xxxiii
xxxiv
Chapter
|
Introduction
The MAXScript Utility Panel The Utility Panel user interface to MAXScript is described in the following topics. It consists of the MAXScript rollout in the Utilities panel, the Listener window, and MAXScript Editor windows. To access the MAXScript Utility panel rollout, open the Utilities panel and click the MAXScript Utility button.
The following options appear in the MAXScript rollout:
Using the MAXScript Documentation
Open Listener Opens the MAXScript Listener window, or restores and brings it to the front if it is minimized or is behind other 3ds max windows. The Listener window can also be opened by right-clicking in the Mini Listener in the 3ds max status bar and choosing Open Listener Window, by choosing MAXScript > MAXScript Listener in the 3ds max menu bar, or by pressing F11. For Listener window features and commands, see The MAXScript Listener Window (p. xxxvi) topic. New Script Opens a new MAXScript Editor window used for writing a new script. A new Editor window is also opened by choosing MAXScript > New Script in the 3ds max menu bar, or File > New Script in the Listener window menu bar. For Editor window features and commands, see The MAXScript Editor Windows (p. xliv) topic. Open Script Opens a common File Open dialog for choosing an existing script. A new MAXScript Editor window then displays the selected script. A script file can also be opened by choosing MAXScript > Open Script in the 3ds max menu bar, or File > Open Script in the Listener window menu bar. For Editor window features and commands, see The MAXScript Editor Windows (p. xliv) topic. Run Script Opens a common File Open dialog for choosing an existing script. MAXScript then reads and executes the selected script. Any output is printed to the Listener window. A script file can also be run by choosing MAXScript > Run Script in the 3ds max menu bar, or File > Run Script in the Listener window menu bar. For more information, see the Running Scripts (p. xlix) topic. Utilities Displays a list of available scripted utilities. A MAXScript defining a scripted utility must be executed before the scripted utility name appears in the Utilities list. For more information, see the Accessing Scripted Utilities (p. l) topic. Close Closes the MAXScript Utility rollout. Any scripted Utilities panel rollouts are also closed.
xxxv
xxxvi
Chapter
|
Introduction
The MAXScript Listener Window The MAXScript Listener window is an interactive interpreter for the MAXScript language and works similar to a DOS command prompt window. You enter MAXScript commands in this window, and when you press ENTER they are executed immediately. The Listener window is appropriate for performing interactive work and developing small code fragments. Extended blocks of code should be developed in a Script Editor Window (p. xliv). Each command you execute in Listener is actually an expression with a result which Listener prints out after each execution. All commands in MAXScript are expressions or function calls that can look like commands in other languages. The terms command and expression are synonymous in MAXScript. You can enter any MAXScript expression or sub-expression in Listener for evaluation, and Listener prints out its result.
You can open only one instance of the MAXScript Listener window at a time. To open Listener, choose the MAXScript utility on the Utilities panel and click Open Listener. Other methods for opening Listener are described in The MAXScript Utility Panel (p. xxxiv) topic. The Listener window is a resizable, modeless window. You can switch between it and 3ds max as you work. If you close the Listener window and then reopen it, the text in the window before it was
Using the MAXScript Listener
closed reappears. If Auto Open Listener on Output is checked in Customize > Preferences > MAXScript, the Listener window opens automatically when a script outputs to it. Listener is divided into two panes. The top (pink) pane is the Macro Recorder pane, and the bottom (white) pane is the output pane. When the Macro Recorder is enabled, everything recorded is displayed in the Macro Recorder pane. The output of results from scripts are displayed in the output pane. The output of code executed in the Macro Recorder pane is always directed to the output pane so as not to clutter the recordings. Both panes allow you to cut-and-paste, drag-and-drop, edit, select, and execute code. You can resize the panes by dragging on the split bar between them. The left-end of the 3ds max status panel contains a resizable Mini Listener. If the Mini Listener is not visible, drag on the vertical split bar at the left edge of the status panel to reveal the Mini Listener. The Mini Listener panes act as single-line sliding windows for the current line in the corresponding Listener panes. The Mini Listener panes always show what you are typing or where the edit cursor is placed in the Listener panes. Conversely, anything you type into a Mini Listener pane is entered into the corresponding Listener pane at the current edit cursor position. You can install Listener into a 3ds max viewport by right-clicking the viewport label, choosing Extended, and then MAXScript Listener.
See also Using the MAXScript Listener (p. xxxvii)
Using the MAXScript Listener The MAXScript Listener is a combination of text editor and command prompt window. MAXScript executes the commands you write when you press ENTER, but you can also scroll through the text to re-execute existing commands, or edit them and then have MAXScript execute the modified code. Listener has the following features: •
A line selection margin at the left window border. When you move the cursor into the left margin, it changes to a right-pointing arrow. A single-click selects an entire line, and click-dragging selects multiple lines.
•
Drag-and-drop for copying text within Listener and to and from script Editor windows.
•
Selected text is loaded automatically into the search text dialog field when you choose Search > Find or Search > Replace. This is useful for quickly finding other occurrences of the selected text.
xxxvii
xxxviii
Chapter
•
|
Introduction
Color-coding for distinguishing between input text, output text, and error message text. Three MAXScript system global variables control these colors, and you can assign them new colors to customize your Listener. Text Type
Variable
Default Color
typed input text
inputTextColor
black
output text
outputTextColor
blue
error message text
messageTextColor
red
For commands within the Listener window, see the Listener Commands (p. xxxviii) topic.
See also Using the ‘?’ Symbol (p. xli) Turning on the Listener Log (p. xli) Controlling the Listener Contents and the Insertion Point (p. xlii) Including Scripts Within Scripts (p. lix) Aborting Execution with the ESC Key (p. lv)
Listener Commands Menu Bar Commands and Keyboard Shortcuts The following menu bar commands and keyboard shortcuts are available in Listener. The edit commands listed are also available in the Listener right-click menu. The menu bar commands for Macro Recorder are described in The Macro Recorder (p. l) topic. File > Save As, CTRL+S Opens a common File Save dialog for choosing a file name to which the current contents of the active Listener pane is stored. All text in the active pane is saved to the specified file. File > New Script, CTRL+N Opens a new MAXScript Editor window used for writing a new script. File > Open Script, CTRL+O Opens a common File Open dialog for choosing an existing script file. A new MAXScript Editor window displays the contents of the selected script file. File > Run Script, CTRL+R Opens a common File Open dialog for choosing an existing script file. The selected script file contents are executed.
Listener Commands
Edit > Undo, CTRL+Z If the last change made to the Listener’s content was an edit, undoes that edit. Only one level of undo is supported. If the last change was a command evaluation, removes all the text printed in Listener by that command, making it easy to remove large print-outs. Pressing CTRL+Z a second time restores the removed text and also selects it. This feature can be used as a quick way to cut or copy a command’s output. Edit > Cut, CTRL+X Copies the selected text to the cut/paste buffer and deletes the text. Edit > Copy, CTRL+C Copies the selected text to the cut/paste buffer. Edit > Paste, CTRL+V Places the text in the cut/paste buffer at the cursor. If text is selected when executing this command, the selected text is replaced with the cut/paste buffer contents. Edit > Delete, DEL Deletes the selected text. Edit > Clear All Deletes all text in the active Listener pane. Edit > Select All, CTRL+A Selects all text in the active Listener pane. Search > Find, CTRL+F Displays Find dialog. Performs search in the active Listener pane for the Find What text. Search can be restricted to occurrences that are not part of a larger word, or are the exact combination of uppercase and lowercase letters as the Find What text. If matching text is found, the text is selected. Search > Find Next, CTRL+G Repeats the last Search > Find by finding and selecting the next occurrence of the Find What text in the active Listener pane. Search > Replace, CTRL+H Displays Replace dialog. Performs search in the active Listener pane for the Find What text, and replaces the matching text with the Replace With text. Search can be restricted to occurrences that are not part of a larger word, or are the exact combination of uppercase and lowercase letters is the specified text. Help > Help Displays the MAXScript 4 Online Reference.
xxxix
xl
Chapter
|
Introduction
Help > About MAXScript Displays About MAXScript dialog. CTRL+B Selects the text in the current bracket. Bracket balancer lets you check bracket balancing in long pieces of code. The balancer works with any of the following: (), [], and {}. To use it, place the cursor anywhere in the script text and press CTRL+B. If the cursor is next to a bracket, the code bracketed by it and its matching bracket will be selected and highlighted. If the cursor is not next to a bracket, the closest bracketed code containing the cursor will be selected. If you press CTRL+B again, the next outer bracketed fragment is selected, and so on. You can keep pressing CTRL+B to move out through bracket nestings. If at any point there is a bracket mismatch, the balancer will beep and not select any text. End-Of-Text Commands The simplest way to use the MAXScript Listener is to enter commands at the end of the existing text and press ENTER. This is called the end-of-text compilation. After each command is executed and any results are printed to the output pane, you can enter another command and press ENTER, and so on. When you write new commands at the end of the text in Listener, pressing ENTER executes the last line and inserts a new line. Editing and Executing Mid-Text Commands When you want to use or edit existing text in Listener, you can differentiate between inserting new lines and executing the current line as follows: •
Press ENTER to insert a new line at the current cursor position.
•
Press Number-Pad ENTER to execute the line that contains the cursor. When you reexecute an existing line, its output and any Error Messages (p. liii) are inserted after the current line if the output pane is active, or at the current edit cursor location in the output pane if the Macro Recorder pane is active.
If you do not have a number pad on your keyboard, SHIFT+ENTER is an alternative to the Number-Pad ENTER key. Selecting and Executing Commands You can select multiple text lines and press SHIFT+ENTER to execute all of the selected lines. Each command in the selection is executed in the order it appears in the selection and any output is inserted after the entire selection. You can also select a portion of text within a line and press SHIFT+ENTER to evaluate it, as long as it constitutes a valid MAXScript expression. For example, you can display the value of a sub-expression in a long equation by selecting and executing only that sub-expression within a line. The output is inserted after the current line if the output pane is active, or at the current edit cursor location in the output pane if the Macro Recorder pane is active.
Using the ‘?’ Symbol
Executing Code Blocks MAXScript commands may be single or multiline commands, or Block Expressions (p. 679). If you want to enter a block expression or a multiline command within existing text in the MAXScript Listener window, press ENTER to insert each line. Then drag-select all the lines in the command or block and press SHIFT+ENTER to execute the lines. If you enter multiline commands or a block expression at the end of the text in the MAXScript Listener window, remember that each line is compiled when you press ENTER. The multiline command isn’t executed until the end of the command is entered, nor are block expressions executed until the block is closed. While you cannot edit a faulty previous line within the multiline commands or block expression that has already been compiled but not yet executed, you can edit any text within the current line before you press ENTER. You can abort the current end-of-text compilation by pressing the ESC key to start over if necessary. Installing Code Blocks as Macro Scripts You can select one or more text lines and drag them to a 3ds max toolbar to create a Macro Script containing the selected lines. For more information, see the Defining Macro Scripts (p. 1521) topic.
Using the ‘?’ Symbol Each time you evaluate a command or code selection, the last evaluation result output to the Listener output pane is captured into an internal variable denoted by the ? symbol. You can access that value again with the ? symbol. You can use the ? anywhere you normally use a variable name and MAXScript evaluates the ? as the last Listener result. A common use is to capture the ? value into one of your own variables for later reuse, such as in the following statement: x = ?
See also Using the MAXScript Listener (p. xxxvii)
Turning On the Listener Log While you work in Listener, you can use the Listener logging feature to capture your entered text and all printed output into a text file. Only text entered in either pane and printed output to the output pane is captured. Macro Recorder output is not captured. You turn on logging with the openLog() method. openLog [ mode: “w” | “a” ] [ outputOnly: ]
where is a string literal or an expression that evaluates to a string, and specifies the name of the log file to be created. For example: openLog “my_log.txt”
or: logfile=”my_log.txt” openLog logfile
xli
xlii
Chapter
|
Introduction
The default mode (mode:”w”) creates a new file or overwrites an existing file. To append the log results to an existing file; specify mode:”a”. If the specified file does not exist, an error message will be generated. Both input and output are logged by default; specify outputOnly:true to log only MAXScript output. For example: openLog “my_log.txt” mode:”a” outputOnly:true
would append only the MAXScript output to file my_log.txt. If a log file is already open, the openlog() method will close that log file. MAXScript echoes Listener activity as it occurs to the log file until you stop logging. The log file data is not continuously written to the file, rather the log data is written to a buffer in memory, and when the buffer is full the data in the buffer is written to the file. You can use the flushLog() method to ensure the log’s buffer is flushed so that all output is written to the file: flushLog()
You can stop logging, flush the log’s buffer, and close the log file using the closeLog() method: closeLog()
No error message is generated if the flushLog() or closeLog() methods are called and no log file is open.
Controlling the Listener Contents and the Insertion Point The Listener output pane’s content and insertion point placement can be controlled with the following methods: clearListener()
Clears all text from the Listener output pane. setListenerSel #(,)
Sets the current text selection in Listener. The start and end values are the character offsets in the Listener output pane text, starting at 0. If the start and end values are the same, no text is selected and the insertion point is placed at the specified point. You can specify -1 for the start or end values, which specifies the end of the Listener output pane text. For example, the following would put the insertion point at the end of the text: setListenerSel #(-1,-1)
while the following would select all of the text in the Listener output pane text: setListenerSel #(0,-1)
and are integer literals, or expressions that evaluate to an integer. getListenerSel()
Returns the current text selection indexes as a two-element array, #(start, end). These values are the character offsets in the Listener output pane text, starting at 0. If there is no selection, but only an insertion point, the start and end values are equal. Only the
Controlling the Listener Contents and the Insertion Point
selections set using the setListenerSel() method are recognized by this method. If no selection has been set using the setListenerSel() method, the start and end values returned are the offset to the end of the Listener output pane text. getListenerSelText()
Returns the currently selected text, or an empty string if no text is selected and only the insertion point is showing. Only the selections set using the setListenerSel() method are recognized by this method. If no selection has been set using the setListenerSel() method, an empty string is returned. For example, the following lines would capture the entire contents of the Listener output pane to variable ListenerText: (
global ListenerText -- declare variable -- than inside just -- expression ( setListenerSel #(0,-1) -ListenerText=getListenerSelText() -setListenerSel #(-1,-1) --)
so its scope is higher the following block select all the text get selected text set insertion point at end of output pane
) setListenerSelText
Replaces the currently selected text with the replacement string. If no text is selected and only the insertion point is showing, setListenerSelText() inserts the replacement string at the insertion point. Only the selections set using the setListenerSel() method are recognized by this method. If no selection has been set using the setListenerSel() method, the insertion point is the end of the Listener output pane text. is a string literal or an expression that evaluates to a string. include
Inserts the specified file’s content into the Listener output pane. The inserted text is not evaluated. You can use this method to load a script and then step through it, executing any selected text with SHIFT+ENTER. is a string literal or an expression that evaluates to a string, and specifies the name of the file to insert. Example uses are: include “my_script.ms”
or: scriptfile=”c:\\my_scripts\\my_script.ms” include scriptfile
If you don’t explicitly specify a directory in the file name, the file will be searched for in the following directories, in the order listed:
xliii
xliv
Chapter
|
Introduction
•
The current MAXScript directory
•
The 3ds max executable main directory
•
The Windows NT 32-bit system directory (system32)
•
The Windows 16-bit system directory (system)
•
The Windows directory
•
The directories that are listed in the PATH environment variable
The MAXScript Editor Windows MAXScript Editor windows are text editor windows you can open within 3ds max and use to create or edit text files, notably MAXScript script files. Press Open Script on the MAXScript rollout, File > Open Script in the Listener menu bar, or MAXScript > Open Script in the 3ds max menu bar to open an existing script file. MAXScript opens the selected script in a modeless MAXScript Editor window, such as the one shown.
To create a fresh script, press New Script on the MAXScript rollout, File > New Script in the Listener menu bar, or MAXScript > New Script in the 3ds max menu bar to open a new, empty MAXScript Editor window. You can write and edit text, including drag-and-drop editing, in the MAXScript Editor as you would in other editors like WordPad. The menus are similar to those in many standard Windows text editors. You may have any number of MAXScript Editor windows open at the same time.
The MAXScript Editor Windows
MAXScript Editor is suited to developing longer scripts or code fragments you want to keep. You can edit and test parts of them until they are complete, then save your code in a script file for later use. This is a common method for developing large scripts, utilities, and function libraries. You can select one or more text lines and drag them to a 3ds max toolbar to create a Macro Script containing the selected lines. For more information, see the Defining Macro Scripts (p. 1521) topic. You can open a MAXScript Editor window from within the Listener or from other running scripts by calling the edit() method. The syntax for the edit() method is: edit
where is a string literal or an expression that evaluates to a string, and specifies the name of the file whose contents are to be loaded into the new MAXScript Editor window. Example uses are: edit “my_script.ms”
or: scriptfile=”my_script.ms” edit scriptfile
The file will be searched for in the following directories, in the order listed: •
The current MAXScsript directory
•
The 3ds max executable main directory
•
The Windows NT 32-bit system directory (system32)
•
The Windows 16-bit system directory (system)
•
The Windows directory
•
The directories that are listed in the PATH environment variable
You can create an empty MAXScript Editor window from within the Listener or from other running scripts by calling the newScript() method. The syntax for the newScript() method is: newScript()
Opens an empty MAXScript Editor window and returns a WindowStream value that may be used as the target for print and format operations. This is useful for directing output to a separate window for ease of inspection or editing, or later saving to a file. Output to a WindowStream is inserted at the current cursor position in that window. For example: debug = newScript() ... print $foo to:debug ... format “name is %\n” obj.name to:debug
If you need to locate the source of a scripted function, you can use the showSource() method. It displays a MAXScript Editor window containing the source file in which the function was defined, positioned at the function’s definition. The form is: showSource
xlv
xlvi
Chapter
|
Introduction
A MAXScript Editor window has the following features: •
Titles that display only the current script’s file name, rather than its full path name, so minimized MAXScript Editor windows can be easily distinguished.
•
A line selection margin at the left window border. When you move the cursor into the left margin, it changes to a right-pointing arrow. A single-click selects an entire line, and click-dragging selects multiple lines.
•
Drag-and-drop for copying text to and from other MAXScript Editor windows, the Listener window, or any other text editor window that supports Window’s drag-and-drop.
•
Selected text is loaded automatically into the search text dialog field when you choose Search > Find or Search > Replace. This is useful for quickly finding other occurrences of the selected text.
For commands use within the MAXScript Editor window, see the MAXScript Editor Commands (p. xlvi) topic.
MAXScript Editor Commands The following menu bar commands and keyboard shortcuts are available in the MAXScript Editor. The edit commands listed below are also available in the MAXScript Editor right-click menu. File > New, CTRL+N Opens a new MAXScript Editor window for writing a new script. File > Open, CTRL+O Opens a common File Open dialog for choosing an existing script. A new MAXScript Editor window then displays the selected script. File > Close, CTRL+W Saves the contents of the MAXScript Editor to the current file name, and then closes the Editor window. If there is not a current file name (that is, the MAXScript Editor window was opened with File > New), a common File Save dialog is opened. File > Save, CTRL+S Saves the contents of the MAXScript Editor to the current file name. If there is not a current file name (that is, the MAXScript Editor window was opened with File > New), a common File Save dialog is opened. File > Save As Opens a common File Save dialog for choosing a new file name used to store the existing script. File > Evaluate All, CTRL+E Evaluates the entire contents of the MAXScript Editor. This is similar to selecting all text, and then pressing SHIFT+ENTER. It has the advantage that the window’s scroll position does not change.
MAXScript Editor Commands
Edit > Undo, CTRL+Z Undoes the last change made to the MAXScript Editor’s content. Only one level of undo is supported. Edit > Cut, CTRL+X Copies the selected text to the cut/paste buffer and deletes the text. Edit > Copy, CTRL+C Copies the selected text to the cut/paste buffer. Edit > Paste, CTRL+V Places the text in the cut/paste buffer at the cursor. If text is selected when executing this command, the selected text is replaced with the cut/paste buffer contents. Edit > Delete, DEL Deletes the selected text. Edit > Select All, CTRL+A Selects all text in the MAXScript Editor. Search > Find, CTRL+F Displays Find dialog. Performs search in the MAXScript Editor for the Find What text. Search can be restricted to occurrences that are not part of a larger word, or are the exact combination of uppercase and lowercase letters as the Find What text. If matching text is found, the text is selected. Search > Find Next, CTRL+G Repeats the last Search > Find by finding and selecting the next occurrence of the Find What text. Search > Replace, CTRL+H Displays Replace dialog. Performs search in the MAXScript Editor for the Find What text, and replaces the matching text with the Replace With text. Search can be restricted to occurrences that are not part of a larger word, or are the exact combination of uppercase and lowercase letters in the specified text. Help > Help Displays the MAXScript 4 Online Reference. Help > About MAXScript Displays About MAXScript dialog. TAB, CTRL+I Indents selected lines of text by one tab width. SHIFT+TAB, SHIFT+CTRL+I Unindents selected lines of text by one tab width.
xlvii
xlviii
Chapter
|
Introduction
SHIFT+ENTER A MAXScript Editor can send code selections to Listener for evaluation. Select some text in MAXScript Editor and press SHIFT+ENTER to send the selected text to Listener. Listener compiles and evaluates it and prints out the result at the end of the current text in Listener. If you press SHIFT+ENTER with no text selected, the line containing the cursor is sent to Listener for evaluation. This behavior is similar to using SHIFT+ENTER in Listener, except that the results of the evaluations are printed in the Listener, not inserted into the MAXScript Editor text. If you have a number pad on your keyboard, the Number-Pad ENTER key is an alternative to SHIFT+ENTER and can be used to execute commands. You may find the Number-Pad ENTER key faster and easier to use. CTRL+Right-Click Displays a pop-up menu of all the utility, structure, user-interface item, function, handler, plug-in, tool, Macro Script, and rcmenu definitions that exist in the current script. Select one of the items in the pop-up menu to position that definition at the top of the MAXScript Editor window. This simplifies large script navigation.
Running Scripts
CTRL+B Selects the text in the current bracket. Bracket balancer lets you check bracket balancing in long bits of code. The balancer works with any of the following: (), [], and {}. To use it, place the cursor anywhere in the script text and press CTRL+B. If the cursor is next to a bracket, the code bracketed by it and its matching bracket will be selected and highlighted. If the cursor is not next to a bracket, the closest bracketed code containing the cursor will be selected. If you press CTRL+B again, the next outer bracketed fragment is selected, and so on. You can keep pressing CTRL+B to move out through bracket nestings. If at any point there is a bracket mismatch, the balancer will beep and not select any text. CTRL+D Performs a simple syntax coloring scheme in the MAXScript Editor. Each time you press CTRL+D, the window is redrawn with comments in green, MAXScript reserved words in blue, and string literals in light red. This often helps in reading large, complex programs. New text is always colored black and you have to press CTRL+D at some point to recolor the script. Syntax coloring is a programming aid and does not effect script execution. CTRL+R Places the cursor at the location where it was previously placed with a mouse click or a find operation. Consecutive uses of CTRL+R cycle through the last eight cursor positions. This feature is useful if you edit at one location, move the cursor elsewhere with find or scroll operations, and then want to return to the edit location. This feature allows you to quickly review the code pieces you recently worked on.
Running Scripts To run an existing script file, press Run Script on the MAXScript rollout, File > Run Script in the Listener menu bar, or MAXScript > Run Script in the 3ds max menu bar. This opens a common File Open dialog for choosing the script. MAXScript then reads and executes the selected script. Any output is printed to the Listener output pane. You can also run a script from Listener or from within other scripts using the fileIn() method: fileIn
[ quiet: ]
where is a string literal or an expression that evaluates to a string, and specifies the name of the script file whose content is executed. The script file content is executed one expression at a time, and halts processing if an error is encountered at any point. By default, the file is not listed as it is loaded; use quiet:false to get a running listing to the Listener. Example uses are: fileIn “my_script.ms”
or: scriptfile=”my_script.ms” fileIn scriptfile
xlix
l
Chapter
|
Introduction
The script file content is compiled in a global scope context, as opposed to the scope in effect when the filein() method is executed. For more information, see the Scope of Variables (p. 646) topic.
Accessing Scripted Utilities The Utilities list in the MAXScript rollout contains scripted utilities that have been defined in startup scripts or while working in MAXScript. For details about defining scripted utilities, see the Scripted Utility Panels (p. 1464) topic. As soon as you define a utility, MAXScript adds the utility’s name to the Utilities list. When you select a utility from this list, its rollout is added to the Utilities panel after the MAXScript rollout. You can open as many utilities as you need, and close each one with its designated Close button. If you modify and reexecute the script for an open utility rollout, that rollout is replaced immediately with the updated rollout. This lets you develop scripted utility rollouts incrementally with immediate, visual feedback.
The Macro Recorder The MAXScript Macro Recorder captures many of the actions performed by the user, and generates the MAXScript commands that correspond to those actions. Output from Macro Recorder is displayed in the Macro Recorder pane of the MAXScript Listener window. Several filtering options are available that control what types of user actions are recorded, whether the generated MAXScript commands contain explicit object references or are selection-relative, and whether the generated MAXScript commands contain explicit or relative transforms and coordinates. These options are set using the MacroRecorder menu in the Listener window. The default option settings are specified in the MAXScript page of the 3ds max Preferences dialog, as described in the MAXScript Preferences Settings topic in the 3ds max online help. These settings can also be changed or set by editing the [MAXScript] section of the 3dsmax.ini file. While many areas in 3ds max 4 generate Macro Recorder output, there are also many areas that do not. In general, most of the buttons on the 3ds max Menu Bar, toolbars, Status Bar, Create panel, and Modify panel will generate Macro Recorder output. If the button invokes a secondary dialog, changing setting or performing actions in the secondary dialog typically will not generate Macro Recorder output. In the Create and Modify panels, Macro Recorder output will be generated if the object or modifier can be created by MAXScript. In some cases, the plug-in implementing an object or modifier has not been updated to support Macro Recorder, so that object or modifier will not generate Macro Recorder output. Future versions of 3ds max and 3ds max plug-ins will be updated to support the Macro Recorder and will generate Macro Recorder output when used. MAXScript supports text drag-and-drop onto toolbars to create Macro Script buttons. You can select and drag text from any text window, such as Listener window panes or Editor windows, onto any visible toolbar. The cursor changes to an arrow with a + sign when it is OK to drop the text. If you drop it, a Macro Script button is added to the toolbar with the dropped text as the body of the Macro Script. The classic case here would be to drag text from the Macro Recorder pane onto a toolbar to
The Macro Recorder
make a button that does the sequence of events just recorded. For more information, see the Defining Macro Scripts (p. 1521) topic. The following Macro Recorder menu commands are available in Listener: Enable When Enable is selected the Macro Recorder will generate MAXScript commands. Explicit Scene Object Names/Selection-Relative Scene Object Names Specifies whether to use explicit scene object names or the selection set token in the generated commands if only one object is selected. If more than one object is selected, the selection set token is always used. For example, if Explicit Scene Object Names is enabled, a typical generated command would be: move $Sphere03 [55.6739,23.5,0]
If Selection-Relative Scene Object Names is enabled, a typical generated command would be: move $ [0,-47.8044,0]
By using Selection-Relative Scene Object Names, you can apply the recorded script to a different selection, thereby making it somewhat general. Use Explicit Scene Object Names if you want the script to always work on the same objects regardless of the current scene selection. Absolute Transform Assignments/Relative Transform Operations Specifies whether to use absolute or relative transform commands in the generated commands. For example, if Absolute Transform Assignments is enabled, a typical generated command when you move a selection in a viewport would be: $.position = [55.6739,23.5,0]
If Relative Transform Operations is enabled, a typical generated command would be: move $ [0,-47.8044,0]
When the Absolute Transform Assignments option is selected, absolute transform assignments are output only if a single object is transformed. If multiple objects are selected, relative transform operations are output. Explicit Sub-object Sets/Selection-Relative Sub-object Sets Specifies whether to use explicit sub-object identifiers or the sub-object selection set property in the generated commands. For example, if Explicit Sub-object Sets is enabled, a typical generated command would be: move $Sphere02.verts[#{20..32, 51..65}] [40.0986,10.3648,0]
If Selection-Relative Sub-object Sets is enabled, a typical generated command would be: move $Sphere02.selectedVerts [40.0986,10.3648,0]
li
lii
Chapter
|
Introduction
By using Selection-Relative Sub-object Sets, you can apply the recorded script to a different selection, thereby making it somewhat general. Use Explicit Sub-object Sets if you want the script to always work on the same sub-objects regardless of the current sub-object selection. Command Panel Switchings When Command Panel Switchings is selected, the Macro Recorder will generate MAXScript commands for command panel switches. In most cases, recording command panel switches is superfluous as most scripts are not dependent on the user interface mode to work. Tool Selections When Tool Selections is selected, the Macro Recorder will generate MAXScript commands for the selection of tools in the 3ds max toolbar. In most cases, recording the selection of tools is superfluous as most scripts are not dependent on the tool selection to work. Menu Item Selections When Menu Item Selections is selected, the Macro Recorder will generate MAXScript commands for the selection of menu items from the 3ds max menu bar.
General MAXScript Topics This section presents topics that supply information on general MAXScript topics. Error Messages (p. liii) Aborting Execution with the ESC Key (p. lv) MAXScript Desktop State (p. lvi) Startup Scripts (p. lvi) Running Scripts from the Command Line (p. lvii) The Scripts Included with 3ds max (p. 624) Source Code Layout and Continuation Lines (p. lvii) Including Scripts within Scripts (p. lix) Encrypting Script Files (p. lx)
Error Messages
Error Messages When MAXScript detects a runtime error in your script, it displays an error message and prints diagnostic information to the Listener output pane. If the error occurs in a controller script or rollout panel script, the error message is displayed in an Alert Box window, otherwise it is printed in the Listener output pane. The diagnostic information is in the form of a call stack trace-back which can help determine the cause and location of the error in your code. The call stack trace-back shows the nesting of called MAXScript functions at the point of error, deepest ones first to outermost ones last. The call stack trace-back also displays the values in all the local variables and function parameters at the levels they are declared or first used. Note that for loops produce separate entries in the call stack trace-back and include a variable dump for the loop variable and any locals in the loop body. As a further aid in locating the error, MAXScript shows the line in which the error occurred in an MAXScript Editor window if the running code was compiled from a source file (any code not entered directly in the Listener). If the source file is not currently open in a window, MAXScript opens the file in a new MAXScript Editor window. The line containing the code in which the error occurred is highlighted and scrolled into view. The error message is either displayed in a Alert Box window or the Listener window. In both cases, the Alert Box or Listener window is brought to the front and the MAXScript Editor window containing the code causing the error is immediately behind. All compile and runtime error messages reported in the Listener output pane are preceded by the comment symbol “--”, so you can reselect and evaluate code in Listener that might have embedded error messages and not have them cause syntax errors. In the following figure, an Editor and a Listener window are shown where an error was detected while running the script. The error occurred in the highlighted line in the Editor window. Looking at the call stack trace-back, we see the error occurred when the for loop variable i is equal to 6. In the line in error, the position of the object specified by the sixth element of array b is being set. After further investigation, it was found the array b only had five elements defined. Thus element b[i] contained the value undefined, which resulted in the error as there is no position property associated with undefined.
liii
liv
Chapter
|
Introduction
In the following figure, an error dialog and script controller dialog are shown. An error was detected while running the script assigned to a script controller. This error was caused by the deletion of object box02, whose position was used in the script.
Aborting Execution with the ESC Key
Aborting Execution with the ESC Key You can abort running MAXScript code by pressing and holding the ESC key. MAXScript may take a moment to respond, so hold the ESC key down until it does. The ESC key aborts any currently executing MAXScript code, whether it is in a scripted utility, a script controller, or running in the MAXScript Listener window. If the MAXScript code that is aborted is in a script controller, a Script Controller dialog is displayed showing the script used by the controller. Execution of the script controller will restart when you click the Close button. MAXScript code locks out the rest of 3ds max while it is executing. You cannot work interactively in 3ds max while MAXScript code is running to avoid conflicts between code actions and your actions. If 3ds max appears unresponsive at any time, it may be running MAXScript code which you can attempt to abort by pressing ESC. If you are testing scripts and 3ds max doesn’t return control to you within a reasonable time, press ESC to abort the code execution. You can also press ESC to abort a compilation of a multiline command in the MAXScript Listener window. Use the MAXScript global variable escapeEnable in scripts to turn on and off the ESC key interrupt detection.
lv
lvi
Chapter
|
Introduction
MAXScript Desktop State MAXScript remembers the state of its desktop (the location of active Editor and Listener windows) when you exit 3ds max and restores this state when you restart MAXScript. Any MAXScript Editor files missing when you restart will not have their windows reopened. The desktop state is stored in a file called maxscrpt.dsk in the 3ds max executable directory. You can rename this file and replace it if you want to keep several desktop setups configured, or simply delete it so the current desktop will not be restored.
Startup Scripts When the 3ds max is first started, MAXScript searches for any startup script files that it then automatically loads and runs. This feature is useful if you have function libraries you always use and want preloaded, or if you want to establish custom UI settings, define scripted plug-ins, or load scripted utility rollouts. The automatic loading of startup script files can be deactivated by turning off the Auto Start MAXScript option in the MAXScript page of the 3ds max Preferences dialog, as described in the MAXScript Preferences Settings topic in the 3ds max online help. MAXScript first searches for a file named startup.ms in the following directories, in the order listed: •
The Scripts directory (defined in the 3ds max Configure Paths dialog)
•
The Startup Scripts directory (defined in the 3ds max Configure Paths dialog)
•
The 3DS executable main directory
•
The Windows NT 32-bit system directory (system32)
•
The Windows 16-bit system directory (system)
•
The Windows directory
•
The directories that are listed in the PATH environment variable
MAXScript stops searching when it finds the first occurrence of startup.ms. MAXScript then recursively scans the 3ds max plug-ins and Startup Scripts directories (both defined in the 3ds max Configure Paths dialog) and directories nested within them for .ms and .mse script files and loads them. In this pass, any script files with the name startup.ms are ignored. This allows you to place your scripted plug-in scripts in the 3ds max plug-in folders for automatic loading. They can be managed like DLL plug-ins, and used to organize your startup scripts into groups in their own directories for easier management. You can prevent a nested directory from being scanned by placing its name in parentheses, for example “(old-versions)”, allowing you to enable and disable scripts in handy directory-based groupings.
Running Scripts from the Command Line
Running Scripts from the Command Line You can launch 3ds max from a DOS command line and have it run a specified launch script, which is useful for tasks such as unattended batch-rendering. This capability uses the existing -U 3ds max command line switch that names a utility to be run when 3ds max is started. The -U switch allows an optional extra argument which, for MAXScript, is taken to be the name of the launch script to run. The case of MAXScript must be as shown in the following example: c:\3dsmax\3dsmax -U MAXScript rendercams.ms
This example command line would launch the 3ds max executable in c:\3dsmax, start MAXScript, and then have it run the launch script rendercams.ms. The following example launch script loads two scenes, renders frames from each of the cameras in them, and then quits 3ds max: loadMaxFile “foo.max” for c in cameras do render camera:c outputfile:(”foo_”+c.name+”.bmp”) loadMaxFile “baz.max” for c in cameras do render camera:c outputfile:(”baz_”+c.name+”.bmp”) quitMax #noPrompt
This example makes use of the quitMax() method to exit 3ds max (see Exiting and Resetting 3ds max (p. 1669) ) when the script is finished. Launch scripts need not be batch scripts as in this example, but may be used to condition 3ds max for interactive use, for example by loading a scene file and setting some user-interface options. The normal startup scripts, startup.ms and those in the Startup Scripts directory, are run before the launch script. It is also possible to install scripts into individual scene files that run automatically when that scene is open or closed or at certain other events (see General Event Callback Mechanism (p. 29)).
Source Code Layout and Continuation Lines The layout rules for MAXScript code are unlike those of most programming languages and give you the advantages of freeform languages, such as C and C++, but without the need for extensive punctuation, like semicolons and parenthesized parameter lists. MAXScript lets you break statements and expressions across lines wherever you want, providing the line break is in the middle of an expression. MAXScript reads your code until the end of each line and determines whether it has a complete expression. If it does not, it continues to read subsequent lines until it finds the rest of the expression.
lvii
lviii
Chapter
|
Introduction
Take as an example the following line: a + b * c / d - e + f * g / h
This line can be broken after any of the operators. MAXScript continues to read the next line, because an operator needs another argument. For example: a + b * c / d - e + f * g / h
You cannot break the example line as shown next and get the same result, because the expression on the first line is a complete expression. MAXScript considers the two lines as separate expressions, and the second line is now syntactically wrong, because it starts with an operator. a + b * c / d - e + f * g / h
This scheme allows you to write the following forms of the same statement without using periods or semicolons, as you might in other freeform languages. For example, a if/then/else construct could be written as: if a < b then print c else print d
or, if a < b then print c else print d
or, if a < b then print c else print d
If you do want to break a line at the end of a sub-expression, you can use the backslash line continuation character: ‘\’. The previous example above of an invalid break can be made valid using the line continuation character after the ‘e’: a + b * c / d - e + f * g / h
\
Whenever MAXScript encounters a ‘\’ as the last character on a line, except for spaces, tabs, or comments, it continues to read the next line as though the line break were not present. Line continuations are often used to break up function calls with many arguments, as shown in many of the Expressions (p. 667) topics. MAXScript also lets you combine multiple statements and expressions in a single line. The statements or expressions are separated with a ‘;’.
Including Scripts Within Scripts
Examples: print “End of input data reached” to:f ; close f ; f = undefined if a < 0 do (print “value out of range”;a=0)
Comments in MAXScript begin with a double-hyphen (‘--’) and extend to the end of the current line. Many code examples in this help file use comments in this style. Example: -- special cases... if first do subanims[6]=undefined
-- subanims[6] is #Image_Motion_Blur_Multiplier
Including Scripts Within Scripts MAXScript provides a compile-time source-file include mechanism, allowing you to break up large scripts into smaller files that can be included at nearly any point in a script. You can use the include construct at any point in your code to effectively insert the contents of a file at that point in your code. The form is: include “filename_string”
This is a compile-time construct, therefore the file name specification must be a string literal, and not a variable or an expression. Example: utility foo “Baz” ( local a, b, c include “foo-ui.ms” rollout bar “Bar” ( include “bar-rollout.ms” ) include “foo-handlers.ms” )
The include construct is effectively replaced in the source code at that point with the contents of the named file. You can nest included files as deeply as needed; included files can include other files, and so on. Because include is a compile-time construct, the current MAXScript scope is maintained within the included file. This is opposed to the fileIn() method described in the Running Scripts (p. xlix) topic, whose script file content is compiled in a global scope context. For more information, see the Scope of Variables (p. 646) topic.
lix
lx
Chapter
|
Introduction
The include can appear at any point a new token is expected, such as a name, literal, or punctuation. This means that you could complete a partial expression with an included file. For example: include “op1.ms” + include “op2.ms” if include “test2.ms” then print a else print b
You cannot place an include within a token. For example, the following is not valid: timeval = 2:include “framenum.ms”.0
Encrypting Script Files MAXScript lets you create an encrypted copy of a specified script file with the same name prefix, but with the suffix .mse, in the same directory as the source script file. The encryption uses a fixed hidden key that lets it run on any 3ds max system, but effectively hides the source of the script. Encrypted script files have the suffix .mse. To encrypt a script, use the following MAXScript method: encryptScript
where is a string literal or an expression that evaluates to a string, and specifies the name of the script file whose contents are encrypted. Example uses are: encryptScript “my_script.ms”
The encrypted script file from the previous examples would be named my_script.mse. The Run Script button in the MAXScript rollout and the fileIn() method described in the Running Scripts (p. xlix) topic automatically support .mse encrypted scripts. You can couple this script source code encryption with the hardwareLockID variable and the encrypted file I/O functions to provide authorization-based protection for your scripts.
Syntax Definitions in This Document The ways you can write MAXScript tokens and clauses are given using a set of shorthand rules as shown in the following example: [-]{}[.{}][(e | E)[+ | -]{}+]
These rules, or syntax definitions, follow the standard EBNF notation (Extended Backus-Naur Form). The previous example shows the syntax for a decimal number in MAXScript. The rules typically contain a number of characters with special meanings. For example, brackets enclose optional items, such as the minus sign in front of the number. Braces enclose items you can use repeatedly, and bars separate multiple items from which you can choose one. Sometimes, rules are given names so they can be referred to in the documentation or as parts of other rules. The special characters in the rules have the following meaning:
-- items inside the brackets are optional -- choose one of the items separated by the bars -- you can specify the braced item ZERO or more times -- you can specify the braced item ONE or more times -- define a name for a syntax rule -- you can insert what is defined by the named rule -- characters or token as written
The previous number syntax example is interpreted as follows: Syntax
Definition
[-]{}
an optional minus sign (the sign), followed by 0 or more digits (the integer part), followed by
[.{}]
an optional sequence (the fraction part) comprised of: a period character, followed by 0 or more digits, followed by
[(e | E)[+ | -]{}+]
an optional sequence (the exponent part) comprised of: either an ‘e’ or ‘E’, followed by an optional plus or minus sign, followed by one or more digits.
Examples of valid numbers are: 123 1.456 -0.89e-7 1.536E23
The following numbers are not valid: 12x34 -0.45x10^3 0e
The syntax definitions in the MAXScript Grammar (p. 1681) topic are in the form of named rule definitions. For example: number ::=
[-]{}[.{}](e | E)[+ | -]{}+]
allowing the rule to be referred to by name in other rules in the grammar. An example of such a rule is: mod
modulo arithmetic, the remainder when is divided by Some definitions throughout this document also use the convention of showing alternative definitions for a rule on consecutive lines instead of separating them with the ‘|’ symbol.
lxi
lxii
Chapter
|
Introduction
Objects and Classes in Object-Oriented Programming To understand the terminology associated with MAXScript, a basic understanding of object-oriented programming is required. All of the values you work with in MAXScript have a well-defined type, such as integer, matrix3, or twist. The type of a value is also known as its class, following the convention of modern objectoriented languages. We’ve been using a somewhat neutral convention so far of calling the things you compute with values. The term for these things in object-oriented languages is, not surprisingly, object. The terms object and value are synonymous in this document. An object is a particular instance of an class. For example, in MAXScript Box is a class. It is not a box as shown in 3ds max, but rather defines the characteristics such a box has. These characteristics include the ways to create an instance of the Box class (a box object); the properties of a box object (such as Height, Width, and Length); and operations you can perform on a box object (such as move, copy, and delete). To create a box object, you would say: b=box()
In this line box() is a constructor - it causes a box object to be created, and returns a reference to the box object. This reference is then stored in variable b. No parameters (such as Height, Width, and Length) were supplied for the constructor, so the default values specified by the Box class are used. In the 3ds max viewports, the box object is displayed, and can be manipulated like any other object you create in 3ds max. If parameters are supplied for the constructor, these parameters replace the “()”. For example: b=box width:10 length:100
creates a box object with the supplied parameters. All unsupplied parameters will use their default values. MAXScript is internally object-oriented. All the built-in classes are arranged in an inheritance hierarchy and most of the built-in functions are polymorphic, terms we’ll explore below. You cannot, however, create new classes in MAXScript and the functions you can script are not polymorphic. This may change in later versions of MAXScript, but it is an advanced refinement that is not really necessary in an application scripting language, where the most important abstractions are the features of the host application and are already built-in.
See also Inheritance and Polymorphism (p. lxiii) Properties, Methods, Operators, and Literals (p. lxiv)
Inheritance and Polymorphism
Inheritance and Polymorphism Inheritance and polymorphism are the two defining characteristics of object-oriented languages. Inheritance is the ability of an object class to inherit the operations and properties of its parent class. Polymorphism is the ability of a single-named operation to work on different values of different object classes. We’ll explore them here to see how they are used in 3ds max and MAXScript. First and foremost, both characteristics depend on the system having a well-defined type, or class, for every value. Assigning classes to values divides all the values you can work with into groups, each of which have well-defined operations and properties for their values. In some languages, like standard C++, the class is only manifest at compile-time. In others, like Smalltalk and MAXScript, the classes are actual runtime entities and every value has a runtime class-tag that says what class it is. This is the main reason MAXScript can have type-free variables. It can look at the class-tag of the value in a variable at runtime to determine its class. Once the objects are grouped into classes, the groups themselves can be arranged into hierarchies. We do this all the time in real life. A classic example is the biological hierarchy, arranging real-life objects hierarchically into animals and plants and mammals and vertebrates and humans and adults and children, and so on. An object-oriented language provides a way to arrange value classes into hierarchies and, like the hierarchies we are used to, a class at some point in the hierarchy shares all the operations and properties of all its parent classes. This sharing is known as inheritance in object-oriented languages, and the operations and properties defined for a class are automatically inherited by all of its descendant classes. As an example, the following is the hierarchy for the Box class: Value MAXWrapper Node GeometryClass Box
Various characteristics are defined for a class, and each lower class inherits those characteristics. For example, the classOf() method is defined for class Value, and class Box inherits this method through its hierarchy. Thus you can specify a Box object as a parameter to the classOf() method. In the MAXScript Class Hierarchy (p. 1688) topic, all the built-in classes in MAXScript are laid out in their place in the hierarchy so you can see for each class the classes it inherits characteristics from. Some of the hierarchy comes from within 3ds max itself which is internally object-oriented. All of its objects, modifiers, controllers, and so on are arranged in a well-defined inheritance hierarchy. Once the objects have been grouped into classes, the symbology for the operations that can be performed on objects of each class can be simplified. The classic example of this comes from mathematics. The symbolic operators ‘+’, ‘-’, ‘*’, and ‘/’ are shared among many types of values (integers, reals, complex, vectors, matrices, and so on), and perform the correct action on the types they are applied to. This capability for a single-named operation to work on different types is called polymorphism. Object-oriented languages let you use the same name for different methods or operators across different classes, and the correct method to apply is automatically determined based on the class of the value it is used with.
lxiii
lxiv
Chapter
|
Introduction
In MAXScript, all math operators and methods are polymorphic in this sense and reflect the standard mathematical conventions. An interesting example for 3ds max use is the random() method. It takes two arguments and generates a random value between them. So, if you give it floats it gives you a float back; if you give it 3D points, it gives you a random point in the box they define the corners of; if you give it quaternions, it gives you back a random rotation between them, and so on. Further, all the methods that work on 3ds max objects are polymorphic within their hierarchies. So move, hide, and select work on all types of scene objects; time scaling and insertion work on all the types of controllers, and so on.
Properties, Methods, Operators, and Literals One principle of object-oriented programming is that how a class operates internally is hidden. All interactions with a class are defined by the external interfaces for the class. These external interfaces are broken up into several categories. Properties: Accessible parameters for objects of the class. Examples of properties are height, width, and length for boxes, and radius for spheres. Methods: Defines all the functions you can call for objects of the class. Examples of methods are moving or rotating a 3ds max object, adding a modifier to a 3ds max object, and accessing the position of vertices in a 3ds max object. The terms method and function are synonymous in this document. Operators: Defines the math and other symbolic operators that are defined on values in the class. An example of an operator is the ‘-’ operator, which will perform a mathematical operation on numbers, colors, vectors, and matrices, but will perform a Boolean subtraction when used with 3ds max objects. Constructors: The various ways you can create objects of the class. For example Point3 0 0 0 and as Point3 are constructors for the Point3 class. Executing either of these constructors will create a new Point3 object. Literals: Any literal form for objects of the class. For example [0,0,0] is a literal form for the Point3 class, and “Hello world” is a literal form for the String class.
Chapter 1:
What’s New in 3ds max 4 MAXScript
What’s New in 3ds max 4 MAXScript MAXScript has been greatly expanded in 3ds max 4 so that almost all actions in the software are now scriptable. Much of this exposure is due to Function Publishing and interfaces (p. 67). Additionally, the exposure is an automatic result of more plug-ins moving from ParamBlocks to ParamBlock2s. The remaining exposure used the MAXScript SDK to expose functions to MAXScript. Note: ParamBlock2s make it possible for plug-ins to host all of their user visible parameters in one or more parameter blocks, including complex parameters such as ReferenceTargets, Sub-Anims, dynamic parameter tables (Tabs<>), and class parameters. The parameter blocks handle old-version loading and reference management automatic. They augment the Parameter Map mechanism to provide automatic UI for the new parameter types including common MAX controls such as node pickers, texmap selectors, etc. as well as listboxes for tabular parameters and, further, to automate the construction of ParamMaps and ParamDlgs in common situations. Additionally, ParamBlock2’s provide a system that describes all the parameter blocks and parameters of a plug-in along with a metadata ‘reflection’ API so that systems like the MAXScript, the Macro Recorder, Schematic View, and custom exporters can access plug-in data automatically. This metadata includes version and position-independent parameter IDs and both localized and fixed machine-parsable names for all classes and parameters. This helps to address version compatibility and scripter/exporter localization issues. For design details see the 3ds max sdk help file topic “Parameter Blocks and Maps in Release 3”. Note: The MAXScript SDK is a set of Visual C++ headers and import libraries that C++ programmers can use to extend MAXScript. These extensions can be in the form of new built-in functions, new system globals or descriptors for new MAX plug-in class properties. This is useful for 3rd-party plug-in developers to write custom scripting interfaces for their plug-ins, and for programmers to do custom C++ performance code and drive it with scripts for hybrid tools.
2
Chapter 1
|
What’s New in 3ds max 4 MAXScript
The scripter SDK allows extensions to be added either incrementally through a MAXScript-specific DLL file type that is loaded by MAXScript or by runtime calls directly to MAXScript from within an existing plug-in. For design details see the 3ds max sdk help file topic “MAXScript SDK”. Note: The areas in this documentation exposed by Function Publishing will document the interface information provided by the “showInterfaces” function (p. 159), in three sections: Properties, Methods, and Actions. In the Properties section, each property exposed by the interface is listed along with its data type or enumeration values and whether the property can be read and written to. In the Methods section, each method is listed along with its return type and its argument list. The value type for each argument is shown. If the return type is shown as , the method returns a value of ‘ok’. Methods that are used by Actions are commented as such. These methods typically require that the object be selected and active in the appropriate command panel. In the Actions section, each Action is listed along with its category and action description as shown in the Customize User Interface dialog, and the shortcut keys, if any, assigned to the Action. The following topics are new to MAXScript: •
Learning MAXScript (p. 577): Walkthrough tutorial for beginning MAXScript users.
Additional Note: The name of the atmosphere in releases prior to 3ds max 4 known as the “Combustion effect” is now called “Fire Effect”. The following are new MAXScript features in 3ds max 4: Action Manager: Action Manager (p. 9) ActiveX Controls in MAXScript Rollouts: ActiveX Controls in MAXScript Rollouts (p. 10) Asset Browser: Asset Browser enhancements (p. 22) Bones: Access to the new node bone properties and methods (p. 23) Bone Creation (p. 25) Cache Modifiers: Point Cache Modifier (p. 26) CallBack Notification Codes: RenderEffect Progress Callback Mechanism (p. 28): You can control the main RenderEffects dialog progress bar using several callbacks. Notify Callbacks for Animate button on and off Transitions (p. 27) Color Manager: Color Manager (p. 35)
What’s New in 3ds max 4 MAXScript
Combustion: Combustion (p. 38) Constraints: Path Constraint (p. 39) LookAt Constraint (p. 40) Orientation Constraint Controller (p. 40) Position Constraint (p. 41) Link Controller for Constraints (p. 42) Controller Functions for use with Constraint Assignments (p. 42) Context Filters: Context Filters (p. 43) Custom Attributes: Scripted Custom Attributes (p. 45) Depth of Field: Depth of Field (p. 54) Edit Mesh: ApplyOperation function (p. 54) Editable Patch: Patches (p. 55) Filters: class id filter (p. 59) Selection Filter (p. 61) iDrop - drag and drop: iDrop - drag and drop (p. 62) Interfaces: Interfaces (p. 67) Core Interfaces (p. 70) Other Interfaces (p. 71) Inverse Kinematics: HD IK controller chains can be assigned to existing hierarchies (p. 73) IKLimb Solver (p. 74) Materials: Multi/Sub Material (p. 75) Menu Manager: Menu Manager (p. 75) Mesher: Mesher (p. 82) Network Render Interface: Network Render Interface (p. 82)
Trackviews: Trackviews (p. 114) Visual MAXScript: Visual MAXScript (p. 117) Xref Objects: Xref Objects (p. 120) Zip-file Script Packages: Zip-file Script Packages (p. 122) MAXScript Language Improvements in 3ds max 4: The following are new MAXScript methods for 3ds max 4: IsValidNode (p. 136) getTextExtent (p. 175) isActive (p. 1338) isActive (p. 1348) affectRegionVal (p. 1104) getMAXSaveFileName & getMAXOpenFileName (p. 1640) Language Improvements: Affect Region Function (p. 127) BinStream for Binary Reading and Writing (p. 128) By Reference Parameter Passing (p. 129) C++-style bracketing comments (p. 131) Coercion of bitArray to array and integer arrays to bitArrays (p. 132) Detecting Deleted Nodes (p. 133) Dereferencing Operator (p. 133) forceUpdate Function added to UVWUnwrap (p. 134) hasProperty() function (p. 135) Improved the Performance of Iterating and Indexing the ‘selection’ and ‘$’ Object Sets (p. 135) isValidNode (p. 136) Readable/Writable Checks (p. 135) RubberBanding in pickObject() Function (p. 136) SetDir (p. 136) Shortcut system replaced (p. 137) startObjectCreation() (p. 138) Subanim Indexing Operator, [], on MAX Objects Now Takes Subanim Names (p. 139) superclasses read-only global variable (p. 139) Symbolic Pathnames (p. 140) System Information (p. 141) validModifier() function (p. 142) Visible Class For ‘&’ Reference Values (p. 142)
5
6
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Controllers: List Controller (p. 143) mapKeys() method (p. 144) moveKeys function (p. 145) Keys: Bezier Keys inTangentLength and outTangentLength (p. 158) Object Inspector Functions: Class and Object Inspector Functions Enhanced (p. 159) Renderer: render() Function Re-entrant (p. 160) SuperClasses: Bitmap Manager - Function Published BMM control (p. 161) Utilities, Global Utilities and Render Element plug-ins (p. 161) Renderer (p. 162) 2 New Scripted Pug-in Superclasses (p. 162) Globals and Locals: Definition Constructs Can Include Global Variable Declarations At Top Level (p. 162) Changes to Undeclared Implicit Global Variables (p. 163) Material Editor, Material and Textures: Accessing The Material Editor Active Slot (p. 163) BitmapTex Reload and viewImage (p. 164) BMP, PNG, JPEG and TGA I/O Interfaces (p. 164) Material Editor Access (p. 165) Material Level Show-in-viewport State (p. 166) Maxops: maxOps (p. 87) User Interface: Angle UI element (p. 168) CreateDialog (p. 169) Curve Control (p. 170) isActive (p. 176) keyboard.escPressed (p. 176) MAX Open & Save Dialogs (p. 177) Menu and CUI Loading (p. 178) mtlBrowser (p. 180) SetBackground Method (p. 180) mouseTrack() Function (p. 180) snapMode (p. 182) Spinner UI Item setKeyBrackets (p. 182) Timer UI element (p. 183) TimeSlider on/off toggle (p. 183)
What’s New in 3ds max 4 MAXScript
Undo/Redo Dropdown Labels (p. 184) Zoom to Bounds (p. 184) Command Panels and Rollout Pages: Customize The Order of Rollup Pages (p. 185) MAXScript Dialogs and Rollout Floaters as Extended viewports (p. 186) Rollout .Controls Property (p. 187) Rollout Systems ‘category’ Mechanism (p. 188) All Const and MAXScript Functions in 3ds max 4: MAXScriptFunction List (p. 190) Const Class (p. 191) Const Generic (p. 195) Const MappedGeneric (p. 207) Const NodeGeneric (p. 209) Const Primitives (p. 213) Const StructDef (p. 231) New Classes in 3ds max 4: New Classes in release 4 (p. 259) New MAXScript Interfaces in 3ds max 4: Core Interfaces: Core Interfaces (p. 70) Other Interfaces: Other Interfaces (p. 71) The following topics contain updates to previous MAXScript documentation: •
General Event Callback Mechanism (p. 30): New notifications (everything from #systemPreReset down is new)
•
Defining Macro Scripts (p. 1524): Explanation of how the memory stack treats local macro script variables (only need to review the one paragraph -- “Normal locals are visible...”).
•
Editable Mesh : GeometryClass and TriMesh : Value (p. 1041): New MeshOps, including sub-object support.
version 4 MAXScript New Features Action Manager Topic: version 4 MAXScript New Features/Action Manager All Action Items are macro recorded when executed. This includes main menus items, CUI buttons, keyboard shortcuts and quad menu items. The code emitted for many action items looks like: actionMan.executeAction 0 “50002” -- Tools: Rotate Mode
The MAXScript Interface: actionMan (p. 353) has a function called “executeAction”. It takes as parameters the ID of the action table and the “persistent id” of the action. A comment string that includes the category and tooltip for the action follows it. Some action items have custom code emitters that emit better looking code. This interface is currently intended only for running macro recorded actions. Note: There is no way currently to query the action manager for all the available action items. actionMan.loadKeyboardFile “KbdFile.kbd”
This loads the named keyboard file from the current UI directory. actionMan.saveKeyboardFile “KbdFile.kbd”
Saves the current keyboard configuration into the given file name in the UI directory. actionMan.getKeyboardFile()
Returns the full path to the current keyboard file.
See Also Interface: actionMan (p. 353) The Macro Recorder (p. l) Defining Macro Scripts (p. 1521) The MAXScript Listener Window (p. xxxvi) Turning On the Listener Log (p. xli) Listener Commands (p. xxxviii)
9
10
Chapter 1
|
What’s New in 3ds max 4 MAXScript
ActiveX Controls in MAXScript Rollouts Topic: version 4 MAXScript New Features/ActiveX Controls in Rollouts This feature expands the number of controls that can be created in MAXScript by allowing any type of ActiveX Controls to be embedded in a rollout. Examples include: Simple controls ActiveMovieControl Object, Calendar Control, Microsoft TreeView …
Compound controls Microsoft Excel, Microsoft Internet Explorer Adobe Acrobat …
This provides numerous possibilities in MAXScript which include: •
Embed a web browser into a rollout and then navigate the user to a web site.
•
Embed an Excel spreadsheet into a rollout, extract the user entered values from cells and then create animation in Max.
•
Create an ActiveMovie player through MAXScript, load an Avi file and then synchronize the animation between the rendered Avi in ActiveMovie player to animation in Max.
The technology behind this feature is a MAXScript extension plug-in (MxsActiveX.dlx) making it MAXScript capable. It does not use ParamBlock2. The plug-in adds a new type of rollout control. The syntax is: activeXControl [ ] [ prop1: ] [ prop2: ] …
Parameters:
A string to create the control. The string must be formatted in one of the following ways: •
A Program ID such as “MSCAL.Calendar.7”
•
A Class ID such as “{8E27C92B-1264-101C-8A2F-040224009C02}”
•
A URL such as “http://www.microsoft.com”
•
A reference to an Active document such as “file://\\Documents\MyDoc.doc”
•
A fragment of HTML such as “MSHTML:This is a line of text HTML>”
What’s New in 3ds max 4 MAXScript
Note: “MSHTML:” must precede the HTML fragment so that it is designated as being a MSHTML stream. prop1: prop2: …
These are control specific keyword arguments. You can get a list of properties and their types by calling showProperties on the control. Examples: activeXControl ax “{05589FA1-C356-11CE-BF01-00AA0055595A}” height:200 \ width:300 align:#left
Examples: ----------------------------------------------------------------------- Creates a Windows media player in a rollout. -- Load an avi file by clicking the “Pick Avi” button and choosing an Avi file. -- When the play button is hit the “on timer...” is called -- This synchronizes the time slider with the active frame in the media player -- Clicking show properties to get all the properties listed in the listbox -- You can also set a property by picking a property from the listbox and entering the new value in the text below -------------------------------------------------------------------rollout rActiveX “Creates a Windows media player in a rollout” ( local val activeXControl ax “{05589FA1-C356-11CE-BF01-00AA0055595A}” height:200 width:300 align:#left button btnPick “Pick Avi” pos:[320, 10] button btnProps “Show Properties” pos:[320, 50] listBox lbProps “Properties:” pos:[420, 10] width:170 editText etValue “Value:”pos:[385, 170] width:200 labellblStatus““pos:[440, 190] on btnPick pressed do ( local f = getOpenFileName caption:”Pick Any Avi File” types:”*.avi” if f != undefined then ax.FileName = f ) on btnProps pressed do ( showProperties ax lbProps.items = getPropNames ax ) on lbProps selected sel do ( if lbProps.items.count > 0 then ( try ( val = getProperty ax lbProps.items[sel] )
11
12
Chapter 1
|
What’s New in 3ds max 4 MAXScript
catch ( val == undefined ) etValue.text = val as string ) ) on etValue entered text do ( try( setProperty ax lbProps.selected (text as (classof val)) ) catch( etValue.text = “Set Failed” ) ) on ax timer do ( sliderTime = animationRange.start + (ax.CurrentPosition * (animationRange.end animationRange.start))/(ax.selectionEnd - ax.selectionStart) ) on ax PositionChange oldPos newPos do ( format “[%, %]\n” oldPos newPos ) ) nf = newRolloutFloater “Test ActiveX” 650 300 addRollout rActiveX nf
activeXControl ax “e:\\test.xls” height:200 width:300 align:#left -------------------------------------------------------------------- creates a excel spreadsheet inside an embedded IE browser control -- also registers it as an extended viewport ------------------------------------------------------------------rollout rExcel “Excel” ( activeXControl ax “e:\\test.xls” height:250 width:370 align:#center ) fExcel = newRolloutFloater “Excel” 390 270 addRollout rExcel fExcel
What’s New in 3ds max 4 MAXScript
format “----Application----” showProperties rExcel.ax.application format “----Parent----” showProperties rExcel.ax.parent format “----Container----” showProperties rExcel.ax.container -- In case of MS Excel .document points to the msexcel.workbook workbook = rExcel.ax.document format “----Document----” showProperties workbook showHidden:true showMethods workbook showHidden:false props = getPropNames workbook sort props for prop in props do ( try ( format “\t%=%\n” (prop as string) (getProperty workbook prop) ) catch () )
13
14
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Properties There are 2 common properties for ActiveX controls, .pos and .size. Other ActiveX properties are control specific and vary from one control to another. Properties can be set like: ax.filename = true
where ax is the control name. Additionally, there is support for color properties. The internal representation of colors for ActiveX controls is COLORREF(unsigned integer) so you’ll always get them in integers but you can set them as follows: ax.forecolor = red -- if a .forecolor property exists
Methods All methods of ActiveX controls are control specific and vary from one control to another. Methods can be called like: ax.AboutBox() ax.loadURL “www.discreet.com”
Events Events are notifications sent by the ActiveX controls to the rollout, whenever an action is performed on the control, e.g.: clicking a button, browsing to a webpage. If supporting event handler is implemented for the event, in the rollout context, the handler is called with supporting arguments. Supporting Functions showAllActiveXControls [ to: ]
Prints a list of ActiveX controls with their progID and classID, registered on your system. showMethods [ to: ] [showHidden:]
Prints a list of methods and their arguments that can be invoked on the control showEvents [ to: ]
Prints a list of events and their arguments that are sent by the control showProperties [ to: ] [showHidden:]
Prints a list of the properties and their types, supported by the control. Some properties are marked read-only getPropNames [showHidden:]
Returns an array of the properties supported by the control
What’s New in 3ds max 4 MAXScript
Common Parameters to:
is the output stringstream. showHidden:
controls whether hidden properties/methods should be included in the enumeration. The default value is false. All supported COM datatypes are converted to an appropriate MAXScript wrapper when passed to and from a COM object. Here are the supported types and their mapping undefined - VT_EMPTY boolean - VT_BOOL integer - VT_UI1 integer - VT_UI2 integer - VT_UI4 integer - VT_UI8 integer - VT_I1 integer - VT_I2 integer - VT_I4 integer - VT_I8 float - VT_R4 float - VT_R8 string - VT_BSTR float - VT_CY date - VT_DATE error - VT_ERROR color - VT_COLOR MSDispatch - VT_DISPATCH font - VT_FONT undefined - VT_UNKNOWN ComArray - VT_SAFEARRAY ComArray - VT_CARRAY ComArray - VT_ARRAY
Valid string handling for property sets and method call arguments, you can safely do ax.Navigate “beta.discreet.com”
where: ax is the Microsoft Web Browser Control
15
16
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Note: Restricted functions like QueryInterface, AddRef, Release are displayed by showMethods() function. Examples: ---------------------------------------------------------- creates a IE browser control in a rollout as registers it an extended -- viewport. Pick “Web Page” from the Extended Views -- menu to display the rollout in the webpage. Also click various hypertext links -- to see the text change in the viewports --------------------------------------------------------rollout rWebpage “Web page” ( local txtObj local vpsz = getViewSize() activeXControl ax “www.yahoo.com” height:(vpsz.y-50) width:(vpsz.x-50) align:#center fn checkTextObject = ( if $text01 == undefined then ( txtObj = text text:”“ name:”text01” addModifier txtObj (extrude amount:10) txtObj.wirecolor = red ) else ( txtObj = $text01 ) ) on rWebpage open do ( checkTextObject() ) on ax TitleChange txt do ( checkTextObject() if not (matchPattern txt pattern:”http:”) then ( if txtObj.text != text then ( print txt txtObj.text = txt max tool zoomextents all ) ) ) ) fWebPage = newRolloutFloater “Web page” rWebpage.vpsz.x rWebpage.vpsz.y addRollout rWebPage fWebPage registerViewWindow fWebPage showProperties rWebpage.ax
These functions are used to access properties on activeX controls that require an integer index. Example: getIndexedProperty axListview.listitems.subitems 1 setIndexedProperty axListview.listitems.subitems 1 “Subitem1”
Disable 3ds max keyboard accelerators For most of the ActiveX controls there is no automatic way of determining if it supports keyboard input to disable Max’s accelerators. Therefore a new MAXScript system global called “enableAccelerators” can be set to false whenever an ActiveX control gets focus so that the user can type in the controls. Here is a sample that can be handy to enable/disable keyboard accelarators: rollout rAccelState “State” ( checkButton accelState “Test” on rAccelState open do
17
18
Chapter 1
|
What’s New in 3ds max 4 MAXScript
( accelState.text = if (enableAccelerators) then “Enabled” else “Disabled” accelState.checked = enableAccelerators ) on accelState changed state do ( enableAccelerators = state accelState.text = if (enableAccelerators) then “Enabled” else “Disabled” ) ) nf = newRolloutFloater ““ 100 100 addRollout rAccelState nf
shockwave flash object events Here is a sample script that creates a text object and sets the text to FSCommand event argument value sent by shockwave flash objects: rollout rFlash “Shockwave Flash Object” ( local txtObj fn checkTextObject = ( if $text01 == undefined then ( txtObj = text text:”“ name:”text01” addModifier txtObj (extrude amount:10) txtObj.wirecolor = red rotate txtObj 90 x_axis ) else ( txtObj = $text01 ) ) activeXControl axFlash “{D27CDB6E-AE6D-11CF-96B8-444553540000}” height:200 width:300 align:#left on axFlash OnReadyStateChange arg1 do format “handler: OnReadyStateChange : %\n” arg1 on axFlash OnProgress arg1 do format “handler: OnProgress : %\n” arg1 on axFlash FSCommand arg1 arg2 do ( checkTextObject() txtObj.text = arg1 + “+” + arg2 max tool zoomextents all
What’s New in 3ds max 4 MAXScript
) on rFlash open do ( axFlash.movie = “e:\\Movie1.swf” axFlash.movie = “e:\\Movie1.swf” -- need to load 2nd time sometimes checkTextObject(); ) ) flashFloater = newRolloutFloater “Shockwave Flash Object” 350 300 10 10 addRollout rFlash flashFloater
COM enums are now represented as MAXScript name internals Preforming a showProperties on Microsoft controls, like ListView, one of the properties returned is: .MousePointer : MousePointerConstants( #ccDefault | #ccArrow | #ccCross | #ccIBeam | #ccIcon | #ccSize | #ccSizeNESW | #ccSizeNS | #ccSizeNWSE | #ccSizeEW | #ccUpArrow | #ccHourglass | #ccNoDrop | #ccArrowHourglass | #ccArrowQuestion | #ccSizeAll | #ccCustom )
which you can set like ax.MousePointer = #ccArrow
19
20
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Properties which return arrays can be itterated For example, .listItems in the ListView control, returns IListItems. This can be looped through and also indexed. for li in ax.listItems do li.bold = true
or: ax.listItems[1].text = “foo”
.description property on any activeX control returns a description string of the format (TypeLib info) ? -
For example .description on a listview control on my system returned: “MSComctlLib (Microsoft Windows Common Controls 6.0 (SP4))?C:\WINNT\HELP\cmctl198.chm-210000”
MAXScript sample rollout controlR92 “Microsoft ListView Control, version 6.0” ( activeXControl ax “{BDD1F04B-858B-11D1-B16A-00C0F0283628}” height:200 width:300 align:#left --on ax Click do format “handler: Click\n” --on ax DblClick do format “handler: DblClick\n” on controlR92 open do ( showProperties ax ax.MousePointer = #ccArrow ax.GridLines = true ax.AllowColumnReorder = true ax.BorderStyle = #ccFixedSingle ax.view = #lvwReport chs = ax.columnHeaders --showProperties chs --showMethods chs hTargets = chs.Add()
What’s New in 3ds max 4 MAXScript
hWeights = chs.Add() hTargets.text = “Node” hWeights.text = “Weights” lis = ax.listItems for i=0 to 10 do ( local li li = lis.Add() li.text = “Item “ + i as string ) for li in ax.listItems do li.bold = true li = ax.HitTest 100 1500 if li != undefined do ( showProperties li li.text = “Just Hit Tested” showEvents controlR92.ax showMethods controlR92.ax ) ) ) nr92 = newRolloutFloater “Microsoft ListView Control, version 6.0” 350 300 10 10 addRollout ControlR92 nr92
See Also i-drop - drag and drop (p. 62) Visual MAXScript (p. 117) MAXScript Dialogs and Rollout Floaters as Extended viewports (p. 186)
21
22
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Asset Browser Asset Browser enhancements Topic: version 4 MAXScript New Features/Asset Browser The Asset Browser provides access from your desktop to design content on the World Wide Web. From within the program you can browse the Internet for texture samples and product models. This includes bitmap textures (BMP, JPG, GIF, TIF, and TGA), or geometry files (MAX, DWG, and so on). You can drag these samples and models into your scene for immediate visualization and presentation. You can use the CTRL key to drag geometry into predefined locations. You can also use the Asset Browser to browse thumbnail displays of bitmap textures and geometry files on your hard disk or shared network drives. Then you can either view them or drag them into your sceneor into valid map buttons or slots. •
Several special new icons are now used in Thumbnail view to represent script files (.ms, .mcr, .mse), dropScripts (.ds), and script zip packages (.mzp).
•
Now viewing or double-clicking script source files (.ms, .mcr, .ds) will open them in a MAXScript editor window, ready for editing and evaluation. You can also double-click .mzp script zip package files to open them in WinZip or some other zip utility if the type .mzp has been associated with that utility.
•
Executable script files (.ms, .mcr, .mse, .mzp) now have a Run... menu item available in the right-click menu on their thumbnail icons in the thumbnail view, allowing you to launch them directly from within the asset browser.
•
The home page for web views is now \web\maxindex.html.
Properties: assetBrowser.open ()
Return Value: Opens the asset browser if it is not already open. Properties: assetBrowser.gotoURL
Parameters:
Opens the given URL in the asset browser. Remarks: This can be a web URL or a local or network disc directory path name.
See Also Interface: browserMgr (p. 355) i-drop - drag and drop (p. 62) Zip-file Script Packages (p. 122)
Access to the node bone properties and methods
Bones Access to the node bone properties and methods Topic: version 4 MAXScript New Features/Bones There are several properties and methods accessible on scene nodes that correspond to the Bone parameters and functions in the node properties dialog. The new properties are: .boneEnable
boolean, read-only, see .setBoneEnable for the set method. .boneAutoAlign
boolean When turned off, the bone’s pivot point will not align to its child object. The translation of a child bone will not be converted into rotation of the parent. Instead the child will be allowed to move away from the parent’s X-axis. Note: Changing the state of this check box will not have an immediate visual effect on the skeleton. It only affects future behavior when bones are moved. This option is only available if Bone is off. .boneFreezeLength
boolean When turned on, the bone maintains its length. When turned off, the bone’s length is based on the translation of its child bone. This option is available only if Auto-Align is on. .boneScaleType
one of #scale, #squash, or #none None: No stretch takes place. Scale: Lets the bone scale. The stretch happens along one axis. Squash: Lets the bone squash. The bone gets fatter as it gets shorter, and thinner as it gets longer. .stretchTM
matrix3, read-only The new methods are: Prototype: .setBoneEnable
Remarks: Sets the Bone enable on or off.
23
24
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Parameters:
When turned on, the bone or object behaves as a bone. Turning this option off causes the node to stop behaving like a bone. There is no auto alignment or stretching. Note that turning this option on will not cause the object to immediately align or stretch. However future translations of children may cause rotation and stretching. Default=on for bone objects, off for other kinds of objects.
Specifies the time at which to calculate and store initial child position. This is usually user with the current time slider position. The time associated with the time slider can be queried and set using the sliderTime global variable. Time Control (p. 1580) Note: A very good macroscript example to review, which uses .setBoneEnable, can be found at ..\ui\macroscripts\Macro_Bones.mcr. Prototype: .realignBoneToChild ()
Remarks: When turned on, the bone or object behaves as a bone. Turning this option off causes the node to stop behaving like a bone. There is no auto alignment or stretching. Note that turning this option on will not cause the object to immediately align or stretch. However future translations of children may cause rotation and stretching. Default=on for bone objects, off for other kinds of objects. Prototype: .resetBoneStretch ()
Remarks: Resets the initial child position used to compute the stretch factor to the current child position. This will cause the stretch factor to become equal to one. If it was previously not equal to one then the object would snap to its original unstretched state.
See Also Node Common Properties, Operators, and Methods (p. 820) Bone Creation (p. 25) Bone : Helper (p. 978) Skin : Modifier (p. 1157) Bones : System (p. 991) Interface: BoneSys (p. 354)
Bone Creation
Bone Creation Topic: version 4 MAXScript New Features/Bones Interface: BoneSys (p. 354) There is a function published interface to create bone links. Prototype: BoneSys.createBone
Parameters:
The location of the new bone as point3
The direction (X axis) of the bone and the bone length as point3
The direction of the Z axis for the new bone node as point3 Return Value: It returns the new bone node that was created. Note: If the Z axis is not perpendicular to the X axis, the Z axis will be made perpendicular. To create a bone chain, call createBone repeatedly with the startPosition set to the value of the previous endPosition. Note that newly created bones are not linked to any parent. So to create a bone chain, the script would also need to link each newly created bone segment to the previous.
See Also Bones : System (p. 991) Core Interfaces (p. 70) Node Common Properties, Operators, and Methods (p. 820) Bone Creation (p. 25) Bone : Helper (p. 978) Skin : Modifier (p. 1157) Access to the new node bone properties and methods (p. 23) Bones_System
25
26
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Cache Modifiers Point Cache Modifier Topic: version 4 MAXScript New Features/Cache Modifiers/Point Cache Modifier Point Cache - superclass: modifier (p. 314) This is a simple point caching system. It lets you store modifier animation to a disk file that records only changes in vertex positions, and then play back the animation using the information in the disk file instead of the modifier keyframes. It caches the points of an object across time and then reads them from the disk on play back. It is useful when you have large intricate stacks that you want to speed up or modifiers such as flex that you want to bake. This modifier sacrifices memory for speed, it stores three caches of the points to allow for fast reading from the disk. You can instance this modifier but the instances must have the same number of points, otherwise the results will be inconsistent. This also only record point position it does not store mapping, topology changes etc. It also cannot deal with animated topology changes. Four MAXScript interface methods have been exposed to allow pressing the Record, Set Cache, EnableMods, and DisableMods buttons.
Methods Prototype: record()
Remarks: Stores the vertex animation to a disk file. Call Record to activate the Save Points dialog, which lets you specify a path and file name for the cache file. Click OK to record the file, and then load it into the Point Cache modifier, ready for playback. Prototype: setCache()
Remarks: Loads a vertex animation from a cache file on disk into the Point Cache modifier. If number of vertices in the cache file does not match the number of vertices in the object, a warning appears, but no error occurs. Prototype: enableMods()
Remarks: Turns on all stack modifiers below the Point Cache modifier. Use this when you want to change modifier settings.
Notify Callbacks for Animate button on and off Transitions
Prototype: disableMods()
Remarks: Turns off all the object’s stack modifiers below Point Cache so that only the cached vertex animation appears when you play back the animation. WSM component of Point Cache. PointCacheWSM interfaces: (p. 487) Note: The WSM is identical to the local space version except it records points in World Space and exist higher in the stack.
See Also PointCache interfaces: (p. 486) PointCache - superclass: modifier (p. 316)
CallBack Notification Codes Notify Callbacks for Animate button on and off Transitions Topic: version 4 MAXScript New Features/CallBack Notification Codes Notify callbacks for Animate button on and off transitions. The new codes for callback scripts are #animateOn and #animateOff.
See Also General Event Callback Mechanism (p. 29)
27
28
Chapter 1
|
What’s New in 3ds max 4 MAXScript
RenderEffects Progress Callback Mechanism You can control the main RenderEffects dialog progress bar using an on apply handler with progressCB, the progress callback interface object. The following syntax lets you do this: on apply progressCB: do
The first argument is the bitmap value to be modified by the effect, and progressCB is a progress callback interface object. This interface has several methods you can call during the course of processing the bitmap that control the progress bar and check for user cancellation.
Methods progressCB.setTitle
Sets the title on the progress bar. progressCB.progress
Indicates the progress of the rendering. Both arguments are integers; done indicates how much of the rendering has been completed, and total indicates how much there is to do. When this is called, the main render effects progress bar is updated to reflect this progress. This function also returns a boolean, which if true indicates that the user has hit the escape key to cancel the effect rendering. progressCB.check()
Indicates whether the user has hit the escape key to cancel the effect rendering. This function returns a boolean; false if processing should continue, and true if the user has cancelled the rendering. Example: on apply bm progressCB: do ( … progressCB.setTitle “My Effect Pass1” … escapeEnable = false -- turn on scripter escape processing for i in … ( … if progressCB.progress completed total then exit ) … escapeEnable = true … )
The progress bar update is done inside the main processing loop and the check for user cancel is done on the same call, causing the loop to exit prematurely in this example.
General Event Callback Mechanism
See Also RenderEffect : MAXWrapper (p. 1347) Scripted RenderEffect Plug-ins (p. 1566) Render Effects Common Properties, Operators, and Methods (p. 1347)
General Event Callback Mechanism MAXScript allows you to register callback scripts for all of the notification events supported by 3ds max, such as pre/post scene file open, new, reset, scene file save, pre/post render, selection change, etc. You can specify any number of callback scripts per notification event. Callback scripts can be bundled into ID’d sets, and can be deleted individually or all callback scripts in and ID’d set can be deleted. Callback scripts can be specified as persistent so that they are saved and loaded with the currently open file. The callbacks are maintained by the following set of functions: callbacks.addScript \ ( <script_string> | <script_stringstream> | \ fileName: ) \ [ id: ] [ persistent: ]
This method is used to register a new callback script. Requires as the first argument a name that specifies which type of notify event this script is associated with. The list of valid callback_type_name values is listed below. The script is supplied either as a direct String or StringStream value containing the text of the script to run, or as a fileName: keyword argument, in which case the named file is loaded and run whenever the event notification callback occurs. You can specify either a direct string or a fileName:, but not both. The optional id: parameter lets you tag one or a group of callbacks with a unique name so that you can remove them all as a group without interfering with other callbacks, perhaps registered by other scripted tools. The optional persistent: parameter lets you control whether the script is saved permanently in the currently open scene file or is a global callback script that remains in place no matter what file opening and closing is performed. A true value for the parameter specifies that the script should be stored in the current file and loaded and registered for callback whenever that file is opened again. Persistent callback scripts are always removed when a new file is loaded or a reset is performed so that persistent scripts in one file don’t accidentally get copied to a later file. The default for this parameter is false, indicating the script is a global script and is not persistent.
29
30
Chapter 1
|
What’s New in 3ds max 4 MAXScript
For example: callbacks.addScript #preRender “setUpRenderGeom()” \ id:#jbwRender
registers a new callback script that will be called just before a render is performed. The script invokes a function (that has presumably already been set up). An unique ID has been assigned to the script for later selective removal. callbacks.removeScripts [ ] [ id: ]
This method is used to unregister and remove one or more callback scripts. Specifying just a callback event type name removes all the callback scripts for that event. Specifying just an id: removes all callback scripts in all events with that ID. Specifying both limits the ID-based removal to the specified event type. callbacks.show ()
This method lists out the current callback scripts in the Listener window. callbacks.broadcastCallback
This method provides a way for you to simulate one of the events and have all the callback scripts for it executed. Within 3ds max, the #preRenderFrame and #preRenderFrame callbacks can only be called by the renderer. These callbacks can not be called by using this method. The following is a list of valid callback event type names: #unitsChange
Sent if the user changes the unit setting. #timeunitsChange
Sent if the user changes the time format setting. #viewportChange
Sent if the user changes the viewport layout. #spacemodeChange
Sent if the user changes the reference coordinate system. #modPanelSelChanged
Sent whenever the Modify panel opens on a new selection, either because the Modify panel was just selected or because a new selection is made in the scene. The notify occurs at a point just prior to panel redraw but after the selection has been established, so that callback functions can modify the panel state without it being overwritten.
System Notifications #systemPreReset
Sent before 3ds max is reset. #systemPostReset
Sent after 3ds max is reset. #postSystemStartup
Sent when the software goes live. #pluginLoa\ded
Sent whenever a plug-in is loaded.
General Event Callback Mechanism
#systemPreNew
Sent just before 3ds max is reset. #systemPostNew
Sent just after 3ds max is reset. #preSystemShutdown
Sent just before the software enters the shutdown process. #postSystemShutdown
Sent just before the software finishes the shutdown process. #colorChanged
Sent when the system is updating it’s custom colors.
File Notifications #filePreOpen
Sent before a new file is opened. #filePostOpen
Sent after a new file is opened successfully. #filePreMerge
Sent before a file is merged. #filePostMerge
Sent after a file is merged successfully. #filePreSave
Sent before a file is saved. #filePostSave
Sent after a file is saved.
Renderer Notifications #preRender
Sent before rendering is started. This notification is sent out before the renderer creates the render instance objects, which means that you can create nodes and other objects as a response to this event. When rendering multiple frames, this event is sent only once at the beginning of the rendering phase, and not on a per-frame basis. In the #preRender callback, you can’t change any of the render parameters (height, width, aliasing, etc) and effect the current render sessions. Those parameters have already been set up internally in 3ds max, and so changes to them won’t occur until the next render session occurs. #postRender
Sent after rendering has finished. This notification is sent out after the renderer destroys the render instance objects, which means that you can create nodes and other objects as a response to this event. When rendering multiple frames, this event is sent only once at the end of the rendering phase, and not on a per-frame basis. #preRenderEval
Sent just before the renderer starts evaluating objects.
31
32
Chapter 1
|
What’s New in 3ds max 4 MAXScript
#preRenderFrame
Sent just before each frame is rendered by the renderer. This notification is sent out after the renderer has taken a snapshot of the scene geometry. At the time of this call the scene cannot be modified. The renderer has already called GetRenderMesh() on all the object instances, and the materials and lights are already updated. If you don’t modify anything that is rendered, then it is okay to use this callback. The current frame being rendered is set into the MAXScript currentTime context and system global, so any references to other scene object properties will automatically be resolved at the currently rendering frame’s time. This notification is not sent out when the renderer is called to update the Material Editor sample spheres, only during output rendering. #postRenderFrame
Sent just after each frame is rendered by the renderer. The current frame being rendered is set into the MAXScript currentTime context and system global, so any references to other scene object properties will automatically be resolved at the currently rendering frame’s time. This notification is not sent out when the renderer is called to update the Material Editor sample spheres, only during output rendering. #renderParamsChanged
Sent whenever the common renderer parameters have changed.
Import/Export Notifications #preImport
Sent before a file is imported. #postImport
Sent after a file is imported successfully. #importFailed
Sent if import fails. #preExport
Sent before a file is exported. #postExport
Sent after a file is exported successfully. #exportFailed
Sent if export fails.
Node Related Notifications #nodeCreated
Sent when a node is created. #nodeRenamed
Sent if a scene node is renamed. #nodeHide
Sent when a node is hidden. #nodeUnhide
Sent when a node is unhidden.
General Event Callback Mechanism
#nodeFreeze
Sent when a node is frozen. #nodeUnfreeze
Sent when a node is unfrozen. #nodeLinked
Sent when a new parent-child link is made. #nodeUnlinked
Sent when a parent-child link is broken. #nodePreMaterial
Sent just before a node gets a new material #nodePostMaterial
Sent just after a node gets a new material #sceneNodeAdded
Sent just after a node is added to the scene. #selNodesPreDelete
Sent just before selected nodes are deleted. #selNodesPostDelete
Sent just after selected nodes are deleted. #nodeMaterialChanged
Sent after the material is changed for the selected nodes. #nodeWSCacheUpdated
Sent whenever the modifier stack display is reevaluated.
Material Library Notifications #matLibPreOpen
Sent just before loading a material library. #matLibPostOpen
Sent just after loading a material library. #matLibPreSave
Sent just before saving a material library. #matLibPostSave
Sent just after saving a material library. #matLibPreMerge
Sent just before merging a material library. #matLibPostMerge
Sent just after merging a material library.
33
34
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Asset Browser Notifications #abPreNavigate
Sent whenever a URL is loaded into the Asset Browser.
VIZ-Only Notifications #heightMenuChanged
Sent when a user operated the height menu. #fileLinkPreBind
Sent just before a file link bind. #fileLinkPostBind
Sent just after a file link bind. #fileLinkPreDetach
Sent just before a file link detach. #fileLinkPostDetach
Sent just after a file link detach. #fileLinkPreReload
Sent just before a file link reload. #fileLinkPostReload
Sent just after a file link reload. #fileLinkPreAttach
Sent just before a file link attach. #fileLinkPostAttach
Sent just after a file link attach.
Other Notifications #wmEnable
Sent when main window gets an wm_enable (BOOL enabled). #selectionSetChanged
Sent after the selection set has changed. #bitmapChanged
Sent after a bitmap is reloaded.
General Event Callback Mechanism
Color Manager Topic: version 4 MAXScript New Features/Color Manager There is a Function Published interface in MAXScript called “colorMan (p. 356)” that exports the color manager interface. All colors are represented as Point3 values of the form [red, green,blue], where each value runs from 0.0 to 1.0. colorMan.useStandardWindowsColors()
Returns true if the standard windows colors are used and false if custom colors are used. colorMan.setUseStandardWindowsColors onOff
Sets the value of “useStandardWindowsColors”. Passing in “true” tells the system to use the standard windows colors, and false tells the system to use the custom colors. colorMan.registerColor color name category defaultColor
This registers a new color with the system. This adds a color to the color manager database that is then accessible from the color customization UI. Example: colorMan.registerColor #myNewColor “My Own Color” “Ugly Colors” [1,0,0]
This registers a new color, with the name #myNewColor, with a default value of red. The category in the customization UI will be “Ugly Colors” and the name will be “My Own Color”. In other scripts you can access this color using: colorMan.getColor #myNewColor
Note: colorMan.registerColor should be called from a script in the “.\stdplugs\stdscripts” folder. These scripts are run when MAX starts, so the color will be available in the customization UI immediately. If the user customizes this color, its value will be saved in the MaxColors.clr file. colorMan.loadColorFile()
This method will load the specified color file from the current UI directory. colorMan.saveColorFile()
This brings up the file save dialog and lets the user save a new color file. colorMan.setColor color colorValue
This sets the value of the given color to the given value. Besides the colors that you register using registerColor, there is a set of built-in colors that you can set and get: #background #text #activeCommand #hilight #shadow #window windows #activeCaption #appWorkspace
---------
The The The The The The
background for all controls and buttons text for all controls and buttons color command mode buttons turn when pressed hilight color for 3d controls shadow color for 3d controls background color for edit boxes, list boxes and other
35
36
Chapter 1
|
What’s New in 3ds max 4 MAXScript
These two are currently unused, but would be used if a 3rd party developer uses the Windows colors in C++ code: GetCustSysColor(COLOR_APPWORKSPACE)
or: GetCustSysColor(COLOR_ACTIVECAPTION)
These were put in for completeness with the windows API. #toolTipBackground -- The background for viewport tool tips #toolTipText -- The text color for viewport tool tips #hilightText -- The hilight color in the stack view drop-down list #windowText -- The color used in edit boxes, list boxes and other windows #itemHilight -- Used as the highlight color on the stack-view drop down list of modifiers. #subObjectColor -- The color used to hilight sub-object levels in StackView #3dDarkShadow -- the dark shadow color on 3d controls #3dLight -- the light color on 3d controls #trackbarBg -- trackbar background #trackbarBgSel -- trackbar background for selected keys #trackbarText -- trackbar text #trackbarTicks -- trackbar ticks #trackbarKeys -- trackbar keys #trackbarSelKeys -- track bar selected keys #trackbarCursor -- track bar cursor #pressedButton -- background color for pressed buttons, like the transform constraints #timeSliderBg -- The background for the time slider bar. #viewportBorder -- The viewport border color #activeViewportBorder -- The active viewport border color #rollupTitleFace -- Rollout title background #rollupTitleText -- rollout title text #rollupTitleHilight-- rollout title 3d highlight #rollupTitleShadow -- rollout title 3d shadow #selectionRubberBand -- the selection marquee color #stackViewSelection -- the color of a selected item in stack view colorMan.getColor color
Gets the value of the given color. colorMan.getName color
Gets the name of the given color. colorMan.getCategory color
Gets the category of the given color. colorMan.getIconColorScale type which
Gets the value of the icon image processing value. type enums: {#disabledIcon|#enabledIcon} which enums: {#saturationScale|#valueScale|#alphaScale}
Returns a floating point value (in the range 0.0f to 1.0f) that is one of the scale factors applied to the specified icon type. These scale values used to do image processing on the icons at start-up time.
General Event Callback Mechanism
colorMan.setIconColorScale type which value
Sets the value of the icon image processing value. The value runs from 0.0 to 100.0. colorMan.getIconColorInvert type
Gets the value for inverting icon colors for the given type. colorMan.setIconColorInvert type value
Sets the value for inverting icon colors for the given type. “Value” can be true or false. colorMan.getFileName()
Returns the file name of the currently loaded color file. colorMan.getDefaultColor color
Returns the default color value for the given color. This is the color passed in as “defaultColor” in registerColor. colorMan.repaintUI type
Whenever you change a color with the color manager, you need to repaint the UI to see the effect. The value of “type” can be: #repaintAll #repaintTrackBar #repaintTimeBar
-- repaint all of MAX’s UI. Can be slow. -- just repaint the track bar -- just repaint the time slider
Here is a macroScript that turns the time slider and trackbar backgrounds blue: Example: macroScript BlueBar category: “Color” tooltip: “Blue Bar” ( on execute do ( colorMan.setColor #timeSliderBg [0, 0, .6] colorMan.repaintUI #repaintTimeBar colorMan.setColor #trackbarBg [0, 0, .6] colorMan.repaintUI #repaintTrackBar ) )
MAXScript calls that let you load, save and query color files. colorMan.loadColorFile “MyColors.clr”
Loads the given color file from the current UI directory. Returns true if it succeeds, and false otherwise. colorMan.saveColorFIle “MyColors.clr”
Saves the current color scheme into the named file in the current UI directory. Returns true if it succeeds, and false otherwise. colorMan.getColorFile()
Returns the full path to the current color file.
37
38
Chapter 1
|
What’s New in 3ds max 4 MAXScript
Example: To set the selected object color to red, you would use: SetUIColor 0 red colorMan.repaintUI #repaintall
See Also Interface: colorMan (p. 356) 3ds max User Interface Colors (p. 1604)
Combustion Topic: version 4 MAXScript New Features/Combustion With the Combustion map, you can create maps interactively using the Discreet combustion product and 3ds max at the same time. You use combustion software to paint on a bitmap, and the material updates automatically in the 3ds max Material Editor and in shaded viewports. Important: The combustion map works only if Discreet combustion is installed on your system. You can use combustion as a material map in 3ds max. With a Combustion map, you can create a material from a Paint or composite operator, and in turn apply that material to objects in a 3ds max scene. The Combustion map can include combustion effects, and it can be animated. In addition, with combustion you can import 3ds max scenes that have been rendered to a rich pixel file (RPF or RLA file). The imported rich pixel rendering becomes an element of your composite. You can adjust its 3D position relative to video elements of the composite, and you can apply combustion 3D Post effects to objects within it. See the combustion User’s Guide for more information. Note: Because 3ds max runs only on Windows, you cannot use combustion to create material maps on a Macintosh. Note: The environmental atmospheric effect known as “Combustion” in versions prior to 3ds max 4 is now known as the Fire effect. A Combustion map is a 2D map (p. 274). It is a combustion project used by the 3ds max Material Editor, so like any combustion project, it is vector-based, animatable, and fully editable. From within the Material Editor, you can have combustion create a new project from scratch, or use an existing composite or Paint branch. You can synchronize the combustion Timeline with the 3ds max time slider so animated materials synchronize with your 3D scene. A macroScript has been added that gets called by the render management system to output render element info to the combustion(tm) .cws file format. ../UI/MacroScripts/Macro_CombustionOutput.mcr Associated files include: RenderElements-fns.ms CombustionExport-fns.ms CombustionExport.ini
Path Constraint
Example: C = combustion()
See Also Combustion.coordinates - superclass: MAXObject (p. 274) Render Element Manager (p. 92) Material Common Properties, Operators, and Methods (p. 1203)
Constraints Path Constraint Topic: version 4 MAXScript New Features/Constraints Path Constraint - superclass: PositionController (p. 307) Path Constraint interfaces: (p. 468) A path constraint restricts an objects movement along a spline or at an averaged distance between multiple splines. Path Target Object A path target can be any type of Spline. The spline curve (target) defines a path of motion for the constrained object. Targets can be animated using any of the standard translation, rotation, scale tools. Setting keys on the path’s sub object level, such as vertex, or segment will animate the path while effecting the constrained object.
See Also path interfaces: (p. 462) LookAt Constraint (p. 40) Orientation Constraint Controller (p. 40) Link Controller for Constraints (p. 42) Controller Functions for use with Constraint Assignments (p. 42)
39
40
Chapter 1
|
What’s New in 3ds max 4 MAXScript
LookAt Constraint Topic: version 4 MAXScript New Features/Constraints LookAt Constraint - superclass: RotationController (p. 297) LookAt Constraint interfaces: (p. 455) Look-At Constraint constrains an object’s orientation so that it’s always looking at another object. Note: The old Look At Controller, which is a full transform controller, will be invisible to the user unless an old file is loaded. The new LookAt Constraint Controller is a rotation controller and NOT a TM controller which the old LookAt was. The old LookAt will be phased out. At this time, old LookAt.IsPublic returns zero, so that the users won’t see the old LookAt. However, the old MAX files will still load the old LookAt and the camera and the light will continue to use the old LookAt.
See Also Path Constraint (p. 39) Position Constraint (p. 41) Orientation Constraint Controller (p. 40) Link Controller for Constraints (p. 42) Controller Functions for use with Constraint Assignments (p. 42)
Orientation Constraint Controller Topic: version 4 MAXScript New Features/Constraints Orientation Constraint - superclass: RotationController (p. 306) Orientation Constraint interfaces: (p. 462) An Orientation Constraint causes an object’s orientation to follow the orientation of an object or averaged orientation of several objects. An Orientation Constrained object can be any type of object that inherits its rotation from a target object. Once constrained you can not rotate the object manually. You may move or scale the object as long as its not constrained in a manner that affects the object’s position or scale controller. The target object can be any type of object. The rotation of a target object drives the constrained object. Targets can be animated using any of the standard translation, rotation, scale tools.
Position Constraint
See Also Path Constraint (p. 39) Position Constraint (p. 41) LookAt Constraint (p. 40) Link Controller for Constraints (p. 42) Controller Functions for use with Constraint Assignments (p. 42)
Position Constraint Topic: version 4 MAXScript New Features/Constraints Position Constraint - superclass: PositionController (p. 320) Position Constraint interfaces: (p. 488) A position constraint causes an object to follow the position of an object or the averaged position of several objects. In order to activate, a position constraint requires an object and a target object. Once assigned the object becomes constrained to the target objects position. Animating the target’s position causes the constrained object to follow Each target has a weight value defining its influence. A value of 0 is equal to off. Any value greater than 0 will cause the target to influence the constrained object. Weight values may be animated to create effects such a ball being picked up from a table. Multiple targets can be used to influence a constrained object. When using multiple targets, each target’s weight value defines how much it influences the constrained object. For example if a sphere is Position constrained between 2 targets and each target’s weight value is 100. Then the sphere will maintain an equal distance between both targets even when they are in motion. If one of the weight values is 0 and the other is 50, then the Sphere is only influenced by the target with the higher value. Example: posCtrl = Position_Constraint() posConstraintInterface = posCtrl.constraints appendNode
Adds a node to the node list with a default weight of 50 appendWeightedNode
Adds a node to the node list with the specified weight getNode
Returns the node specified by the index. Index is a 1 based array setNode
Replaces the node with the given index with a new node getWeight