54 entries in MaxScript

“List” struct

Easily create associative array-like structures in 3dsmax

Friday, June 6th, 2008

As 3dsmax doesn’t allow for either associative arrays or dynamically-set object properties, it can be difficult to store unstructured, arbitrary variables.

Sometimes you just want to store lists of name/value pairs, to keep track of a few settings throughout your script, without relying on a host of variables, resorting to .ini files, or custom attributes.

Therefore, I set about writing a basic Dictionary, or List struct, similar to VB and other languages.

Example code

Here’s a really basic example of storing 5 named variables within a List:

names = #("five", "four", "three", "two", "one")
values = #(5,4,3,2,1)
lst = List()

for i = 1 to 5 do lst.addItem names[i] values[i]

So let’s get some data back out:

lst.getValue "two"
-- 2

lst.getIndex "two"
-- 4

lst.getValues()
-- #(5, 4, 3, 2, 1)

Or print the whole lot:

lst.print() -- unsorted

five:   5
four:   4
three:  3
two:    2
one:    1

How about some sorting:

lst.sort() -- by name, alphabetically

five:   5
four:   4
one:    1
three:  3
two:    2

lst.sort field:#value -- by value

one:    1
two:    2
three:  3
four:   4
five:   5

As you can see, it’s pretty straightforward stuff!

Properties and Methods

Properties

  • items – the key/value pairs.
    • Names can be a #name, “string”, or even an index
    • Values can be any MaxWrapper value (i.e. anything)

Setters

  • addItem – adds an item to the List, and if it already exists
  • setItem – synonym for the above

Getters

  • getValue – returns the value of the named item
  • getIndex – returns the index of the named item
  • getName – returns the name of the first item that matches the supplied value
  • getItem – returns the List item corresponding to the supplied name (typically, you wouldn’t use this, as you know the name component already, it’s just included for completeness)
  • getItems() – returns all items as an array of ListItem structs
  • getNames() – returns all names as an array
  • getValues() - returns all values as an array

Clear or delete

  • clear() – clears the lit of all items, and returns the empty ListItems array
  • deleteItem – deletes the named item from the list, and returns it
  • deleteIndex – deletes the item at the index, and returns it

Utilities

  • sort field: order: func: – sorts the list in a variety of ways, even supply a comparison function (see the max help on qsort)
  • print() – prints the List items to the Listener

Next version

Possible improvements in the next version might be:

  • .ini file integration, with save() and load() methods
  • Support for hierarchical Lists, perhaps getValue #(#parent, #child, #grandchild, …)

Download

Download List.struct.ms here.

Time Stamper – Meshops.attach() Case Study

Monday, May 26th, 2008

Overview

In response to a post on CG Talk, Optimization ideas needed, a few other developers and I us pitched in to help out with ideas to solve a puzzling problem.

The issue was that a loop to attach 7500 objects was taking up to 8 minutes to complete. Where did the problem lie? Was it in the transformation code, the attachment code, or somewhere else?

Well as luck would have it, today’s Bank Holiday has been totally washed out with rain, so I had nothing better to than to do some testing and find the cause, and in the process road test my recently-developed TimeStamper struct.

Approach

After turning undo and redraw off, as well as optimizing the transformation code within the script, which cut a 1000-object test scene’s processing time in half, surprisingly the 7500-object scene was still taking around 8 minutes.

I suspected that the problem may well be in the fact that as mesh gets larger, perhaps it becomes computationally more expensive to add new meshes, seeing as the entire array of points and faces needs to be evaluated every time a new mesh is added. Cumulatively, this could really add up.

I though that perhaps the right approach would be to split the attaching up into phases, using a 2D loop, and I suspected that perhaps the square-root of the total attaches might yield the optimal performance, ie for 10000 attaches I’d perform a 100 x 100 loop, creating 100 intermediate meshes, then attaching them all at the end.

Results

These are the results for various variations of 2D loops, limiting the amount of objects attached per loop. The results are impressive!

  • For 1000 objects, the optimum loop combination was 31 loops of 32, a speed increase of 12 times over a single loop
  • For 3000 objects, the optimum loop combination was 55 loops of 54, a speed increase of 22 times over a single loop
  • For 5000 objects, the optimum loop combination was 50 loops of 100, a speed increase of 28 times over a single loop
  • For 7500 objects, the optimum loop combination was 87 loops of 86, a speed increase of 30 times over a single loop

And yes, the square root approach was most successful 3 out of 4 times.

Here are the results in table format, with the optimum loop highlighted:

1D / 2D loop comparison

Compared to the 1D loop, the 2D loop was 30 times faster on 7500 attachments.

In minutes and seconds, that means a decrease from 6 minutes and 29 seconds to just 12 seconds!

In graph-form that looks like this:

Conclusion

It seems pretty safe to say that in this case, building up intermediate meshes and attaching at the end is the best way to go. It looks likely that adding to already-huge arrays carries with it an overhead that can have an extremely negative effect in a lengthy loop situation.

I’ve no doubt that this approach most likely extends to other mesh / array / hash based computations as well, so splitting up large cumulatively-expensive calculations into smaller chunks could well be a great time-saver in other tasks as well.

So – a shame about the rain, but perhaps a bonus in disguise!

Resources

  • View the Time Stamper page
  • Download TimeStamper.ms
  • Download the test script that generates the 1000’s of spheres that get attached, and performs the benchmarking
  • Download the Excel report that was built using TimeStamper getReport() function in Excel 2003 or Excel 2007

Transform Presets

Save and restore transformations as presets to objects such as cameras, IK handles, etc.

Saturday, May 17th, 2008

Transform Presets is a pretty simple plugin – it allows you to store multiple transformations of an object (and it’s target, if there is one) in a list, to call up when you like.

You apply it to any object, and it adds a custom rollout to the base object, with a small interface that you can use when the object is selected.

I built it for fun in response to a thread on CGTalk.

Screenshots

Here it is working on a target camera. Note both the camera and target are transformed.

And here it is working with an IK handle. Note the swivel angle is updated as well as the transform.

Download and installation

Download TransformPresets.mzp and then drag the .mzp file onto one of your 3dsmax viewports, which will install the script in the correct directory. Then you can add the script to a toolbar / quad by going to:

  • Customize > Customize User Interface…
  • Then look under the Animation Tools category for Transform Presets

Particle Visualizer and Papervision3D Exporter

A script to visualize particle motion and export particle and camera data to Flash's Papervision 3D

Saturday, May 10th, 2008

Papervision 3D is the latest in 3D development for the Adobe Flash platform. It supports a variety of methods for creating 3D content, from basic primitives, to import via the Collada file format. However, being XML-based, Collada files are pretty huge – getting a 300 frame, 150 particle animation into Flash was creating files that were about 22MB!

After trying various approaches to get animation data from 3dsmax to Flash, Good Technology got in contact with me to write an exporter in Max Script for their latest Papervision job for the Audi RS6 microsite.

The plugin has 2 main functions:

  • Visualize particle motion before export
  • Export particle and camera data from max’s Z-up coordinate system to Papervision’s Y-up coordinate system

More information and screengrabs are available on my portfolio site.

Screenshot

Interface

As with all interfaces I write for 3dsmax, I do my best to provide as much feedback as possible. Note:

  • Group titles are updated with the latest information
  • Dropdowns have an update button
  • Tasks have multiple customization options
  • Progress bars and dialog preferences come as standard

Download

This plugin is not available for download, however please contact me if you wish to discuss custom Papervision3D or any other development.

Time Stamper

A struct to make light work of timing tasks, benchmarking, etc

Friday, May 9th, 2008

This struct basically makes timing things much easier by packaging a few useful methods together.

Now, instead of writing and retrieving timestamp variables, and formatting strings to the listener, you simply call struct methods such as start(), end(), and print(), or see a report of the process with getReport().

Example Code

Create a new Time Stamper, assigning a task name:

ts = timeStamper "Testing"

Time something, and alert the results in a messagebox:

ts.start()
-- your code here
ts.alert()

Benchmark a series of tests, and print the results to the listener when completed:

for i = 1 to 10 do (
        ts.start()
        -- your code here
        ts.end()
)
ts.print average:true
-- Average processing time for 'Testing' was 24.6162 seconds, based on 10 timed sessions.

Methods

Starting and stopping

  • start() – start timing. Returns start time
  • end() – end timing. Returns last timing duration
  • reset() – reset all timing data

Getting results in English

  • print average: difference: – end timing and print results to listener
  • prompt average: difference: – end timing and prompt results to notification area
  • alert average: difference: – end timing and alert the results in a messagebox

For the above methods, the following keyword arguments can be supplied:

  • average – returns the average result of all the timed tests since the TimeStamper was instantiated or last reset
  • difference – returns the comparative difference between another TimeStamper, in English, e.g.“Test 1′ was 2.58 times quicker than ‘Test 2′”

Getting results as numbers

  • getLast() – gets the last single timed session (alias for duration property)
  • getTotal() – gets the total of all timed sessions
  • getAverage() – gets the average of all timed sessions
  • getDifference difference: average: – Returns a 3-element array representing how much quicker one time stamper is than another.

The array’s elements are ordered like so:

  1. – how many times quicker the quickest Time Stamper was
  2. – the task name of the quicker time stamper
  3. – the task name of the slower time stamper

Getting results as an Excel-compatible report

  • getReport columns: step: output: – gets all timed sessions as a customizable report

The step property defines how many iterations to average/total values for, and defaults to 10.

The columns property can take any of the following name values:

  • #index – the numeric index of the row, e.g. 1, 2, 3
  • #step – the current step, e.g. 1, 11, 21
  • #stepaverage – the average of all measurements from the current step
  • #steptotal – the total of all the measurements from the current step
  • #slower – how much slower the current step was than the fastest step
  • #quicker – how much quicker the current step was than the slowest step
  • #total – the cumulative total from all measurements so far

The output property defines where the generate report will be output to. Values can be:

  • No value – the report will be returned as a string
  • “path/to/file.txt” – a file path. If the file exists it will be overwritten, if not it will be created
  • #window – a new script window
  • – a reference to a windowstream
  • – a reference to a stringstream

Download a report that was built using calls to getReport() in Excel 2007 or in Excel 2003

Properties

  • duration – the duration of the last timed session
  • durations – an array of all timed sessions
  • task – the name of the current timed task

Demo and case study

Check out a case study and download a demo script here:

Download

Download TimeStamper.ms.

Progress Bar Updater

A struct to simply and easily update a progress bar by providing just start and end values, and calling update()

Thursday, May 1st, 2008

Updating a progress bar is fairly simple in conceptual terms, but it always takes a slightly different bit of code to do it right:

  • What if the sequence is backwards?
  • What if you’re incrementing in units of 2, or 3, or 10?
  • How big is the progress jump?

It makes sense to abstract the process and stick it in a struct. The progressBarUpdater does just that, and really is as simple as:

  1. Create a struct instance
  2. Initialize it with a reference to a progress bar, and the known start and end values of the calculation
  3. Call update() for each loop iteration.

In code, starting with a 2-line initialization, it looks like this:

pbu = progressBarUpdater()
pbu.init pb1 startValue endValue

And to update the progress bar, this is the only command you need to place in the loop:

pbu.update()

The pbUpdater struct already knows everything it needs to know, so it’s just one call.

Download

Download progressBarUpdater.ms.

UI Manager

Save and load rollout settings, such as size, position, control states, items, etc to a preferences file

Thursday, May 1st, 2008

A struct containing methods to save and load rollout settings, such as size, position, control states, items, etc
to a preferences file, as well as methods to accomplish UI control tasks for example keeping one spinner higher or lower
than another when editing ranges.

Usage

To manage a rollout or dialog, you simply:

  1. create a struct instance
  2. initialize it with a reference to a rollout
  3. Manage the rollout by calling the struct’s methods

In code, that’s as easy as this:

ui = uiManager()
ui.initialize roTools
ui.loadPosition()

All settings are saved to an .ini file named after the rollout title, so in this case, an ini file named “Tools.ini” would be saved to your max installation’s /plugcfg folder.

Methods

This is a work in progress, and will be updated from time to time with new methods.

Dialog functions

  • savePosition - save the dialog position
  • loadPosition - load the dialog position
  • saveSize - save the dialog size
  • loadSize - restore the dialog size

Rollout functions

  • autoSizeFloater - resize the floater to exactly the size of all open rollouts
  • toggleRollout - set one or several rollouts open
  • loadRolloutStates - save all rolled-up / down states (not yet implemented)
  • saveRolloutStates - load all rolled-up / down states (not yet implemented)

Control functions

  • updateSpinnerPair - ensure that spinners react as a pair, eg one can never go higher than the other
  • moveListboxItem – move selected Listbox items up or down, and have them remain selected
  • moveMultiListboxItems – move multiple MultiListbox selections up or down, and have them remain selected
  • getValue - abstract function to get a control’s value (not yet implimented)
  • setValue - abstract function to set a controls’s value (not yet implimented)

Preference functions (WIP)

  • saveValue - save a control’s value
  • loadValue - load a control’s value
  • saveAllValues - save all controls’ values
  • loadAllValues - load all controls’ values

Downloads

Download uiManager0.52.ms. Place in your scripts/startup directory, or just include the file when you need it.

These example files will get you started:

  • Preferences functionality – save and restore a dialog’s position when re-running a script
  • Floater functionality – open only selected rollouts, and automatically resize when opening rollouts

Network-Render all Cameras

Automatically submit all cameras to a network render, rendering the correct frames, and save the output to the correct directories

Friday, October 26th, 2007

This MAXScript entry has not yet been completed…
(more…)

ActiveX TreeView Functions

A set of functions for manipulating ActiveX Treeviews

Sunday, October 21st, 2007

This MAXScript entry has not yet been completed…
(more…)

Copy Object Properties

A quad-menu shortcut to quickly copy properties from another object

Monday, October 1st, 2007

A quad-menu shortcut to quickly copy properties from another object. Currently works on base-object properties, but at some point I may update it to work with modifiers.

Works on multiple selections, and attempts all property names, so you can do things like update the radii of spheres from cones, for example.

Interface

Download and Installation

Download and run Copy Object Properties.ms from 3dsmax.

It will create the macroscript in the correct directory for your max version, then you can add the script to a toolbar by going to:

  • Customize > Customize User Interface…
  • and looking under the Tools category for Copy Object Properties.