Το κείμενο του εγγράφου

s graphic interface can also be done using a text-based scripting language. These keyboard commands can also be used in sequenceas a scripting language to create macros, or even to edit saved

.hip

Þles. You canalternate between text and graphic commands. Text commands can be edited inscripts and executed by Houdini. You can minimize typing by using abbreviations,aliases, variables and script macros.There are several places where the scripting language can be accessed. The Textportin Houdini allows you to type commands directly and see the output immediately.The Operator Macros allows pre-deÞned scripts to be executed with a graphicalinterface to set their parameters. The stand-alone application

hscript

provides a non-graphical version of Houdini.Houdini uses type-ahead which allows you to type commands before Houdini hasÞnished executing the current text or graphic command.The text command facilities enable you to work more efÞciently because some com-plex operations can be achieved with a few keystrokes rather than many buttonclicks and cursor movements. For example, to add 1000 objects and lay them out ina grid can be completed with less than 10 lines of script.For more information on the structure and uses of Houdinis scripting language, seethe

User Guide

s chapter on

Scripting

.

1.1 OPENING A TEXTPORT

Y

ou can open a Textport by selecting the

Textport

from any pane

Types

menu.

Intr

oduction

80

1

Houdini

6.0

Reference

1.2 NAVIGATING WITHIN THE TEXTPORT

KEYBOARD SHORTCUTS

[

Select text. Selected text becomes red. You can onlyselect a single line of text at a time.

]

Paste text.

\

Scroll Textport. Mouse pointer changes into a handcursor which allows you to pan the text area in muchthe same way as you can pan the Layout area.

U

/

V

Scroll text up / down, one page at a time.

Q

/

Z

Returns you to the beginning / end of the Textportentries (maximum of 2000 lines).

COP

YING AND PASTINGcopying

Select te

xt within the Textport by dragging across the text with the left mouse (

[

).The text becomes highlighted in red and is copied to the clipboard as soon as yourelease the mouse button. You can copy only one line of text at a time.

pasting

T

ext from the clipboard (i.e. the last text that was higlighted) can be pasted by click-ing within the Textport with the middle mouse (

]

).

The Scripting Language

12 - Scripting

1

81

2 THE SC

RIPTING LANGUAGE

2.1 ORDER OF EX

PANSION

Expansion of a Houdini command follo

ws the C shell expansion standards veryclosely. There are some subtle differences.

LIMITATIONS



The maximum line length for a Houdini command is 8 Kb (expanded) The maximum number of arguments on a command line is 1024 The maximum number of number of nested

if

statements in a single source Þle is128 The maximum number of source Þles is limited by the system limit on open Þles There is no limit for nested loops

LEXICAL STRUCTURE

Houdini splits input lines into w

ords at space characters, except as noted below. Thecharacters ; < > ( ) = form separate words and Houdini will insert spaces aroundthese characters except as noted below. By preceding a special character by a back-slash (\), its special meaning can be suppressed.

evaluation of quotes

Strings enclosed in a matched pair of quotes forms a partial w

ord. Within doublequotes (), expansion will occur. Within single quotes () expansion will not bedone. Within back-quotes (`) the enclosed string will be evaluated as a Houdiniexpression and the result will be considered to be a partial word. Unlike csh, inside amatched pair of quotes, the quote character may be protected by preceding the slashwith a back-slash.Back-quotes are evalutated with a higher priority than double quotes. This meansthat if a double-quoted argument encloses a back-quoted string, the back-quotedstring may contain double quotes without terminating the initial double quote delim-iter. For example, the string:

"fooch("/obj/geo1/tx")"

will be parsed as a single ar

gument.

N

ote:

As a general rule, do not include spaces between your back quotation marksand what lies between them. Houdini may not evaluate them if there are extraspaces.

comments

The character # introduces a comment which continues to the end of the line.

Thischaracter can be protected by a back-slash (\) or by enclosing the character inquotes.

The Scripting Language

82

1

Houdini

6.0

Reference

COM

MAND STRUCTURE

The output of a Houdini command can be redirected to a

UNIX

Þ

le by using themeta-character >. The output can be appended to a

UNIX

Þ

le by using >>. To redi-rect the error output and the standard output of a command to a

UNIX

Þ

le, the char-acter sequence >& can be used.Multiple commands can be speciÞed on the same line by separating them with semi-colons (;).

EXP

ANSION

Expansion is done in the follo

wing order: History substitution, Alias expansion,Variable & Expression expansion.History substitution is not as sophisticated as the csh history mechanism. The sup-ported substitutions are:

!!

Repeat last command

!str

Repeat last command matching str

!num

Repeat command num from the history list

!-5

Repeat the command run Þ

ve commands previousWith the !! substitution, characters following the !! are appended to the command.The resulting command is displayed in the Textport before the command is run.Alias expansion is also not as sophisticated as csh. For example, one current limita-tion is that there is no recursive alias expansion. For example, the followingsequence of commands will not produce the expected result:

houdini -> alias opcd opcf

houdini -> alias cd opcd

The cd alias will result in an unkno

wn command opcd since the alias expansionterminates after the Þrst expansion. As well, alias expansion does not include thehistory meta-character substitution that csh supports.Variable and expression evaluation are done at the same time and have equal prece-dence. Variables are delimited by a dollar sign ($) followed by the variable name. Avariable name must begin with letter or an underscore (_) followed by any numberof letters, numbers or underscores. As well, the variable name may be delimited bycurly braces ({}) in which case the contents of the curly braces is expanded beforethe variable name is resolved. This allows for pseudo array operations on variables.For example:

houdini -> set foo1 = bob

houdini -> set foo2 = sue

houdini -> for i = 1 to 2

> echo ${foo${i}}

> end

bob

sue

The Scripting Language

12 - Scripting

1

83

Expression e

valuation is done on the string contained within matching back-quotes(



). Inside the back-quotes, expression expansion is performed as opposed to com-mand line expansion. The expression is evaluated, and the resulting string is usedto replace the expression on the command line. If the expression evaluates to a typeother than a string, the result is cast to a string and this is the value used.

COM

MAND EXPRESSIONS

These dif

fer from general Houdini expressions, though Houdini expressions can beused inside of command expressions. The command expressions are used in thewhile and if commands. The order of operations in a command expression is asfollows:

( )

P

arentheses

== != < > <= >=

Equal, Not Equal, Less

Than, Greater Than, Less Thanor Equal, Greater Than or Equal

&& ||

Logical

And and Logical OrExpressions can be enclosed in parentheses for clarity, but this is not necessary.

2.2 V

ARIABLES

There are tw

o types of variables in Houdini, local variables and system or globalvariables. Local variables are local to Houdini (or the script being executed). Whenthe script terminates, these variables will automatically be unset. Global variableswill remain in the scope of all scripts and also to any

UNIX

programs started by

Houdini. The set command will create local variables, while the

setenv

commandwill create global variables. For example:houdini -> setenv agent = 99houdini -> set local_agent = 45houdini -> echo Agent $agent, this is agent $local_agent\nAgent 99, this is agent 45houdini -> unix echo Agent $agent, this is agent $local_agentlocal_agent - Undefined variableNote, the single quotes prevent Houdini from expanding the contents of the com-mand (see order of expansion).All variables created by loops are considered local variables (i.e. the for loop willuse local variables).The Scripting Language841Houdini6.0Reference2.3PATTERN MATCHINGMany of theopandchcommands allow patterns to specify multiple objects or chan-nels. These patterns allow wildcards which will match all or parts of strings.*Match any sequence of characters?Match any single character[set]Match any characters enclosed in the square brackets.In Houdini, the [a-g] format is not currently supported,the characters must be listed.@ [group name]Expands all the items in the group. Since each group

belongs to a network, you can specify a path before the@group identiÞer.EXAMPLESopcf /obj ; opls -d @geoThis example lists all the objects in the group named geoopcf /obj/geo1; chadd @xform_sops tx ty tzThis example adds channels (tx,ty, andtz) to all theSOPs contained in the

Pattern Matchingp. 38.2.4 COMMAND LOOPSThere are three different looping constructs in the Houdini scripting language:Theforloop will loop from thestart, up to and including theend.foreachwill cyclethrough every element in theelement_listassigning the variable value to be a differ-ent element each iteration through the loop.All variables in theforandforeachloops are local variables. To export the variableto other scripts (or toUNIXcommands), simply set a global variable usingsetenvinside the loop. Seeforp. 112,foreachp. 112, andwhilep. 120.for variable = start to end [step increment]...endforeach variable (element_list)...endwhile (expression)...endfor loopforeach loopwhile loopThe Scripting Language12 - Scripting185EXAMPLEYou can use a loop to perform repetitive tasks for you. For example, if you wantedto wanted to merge 255 SOPs, it would be faster to write a short script than to do allthat wiring manually. For example, if you named your SOPs consistently, like:model-0, model-1, model-2... model-255then you could execute the following script in a Textport:for i = 0 to 255opwire model-$i -$i merge1endIf you havent been consistent with naming, you could also do it with aforeach.2.5 CONDITIONAL STATEMENTSThe if command provides the ability for a script to check a condition and thenexecute one set of commands if the condition is true or an alternate set of commandsif the condition is false. It should have anendifto signify the end. Seeifp. 114.if ( expr ) [then]...else if (expr2) [then]...else...endif2.6 ALIASES AND MULTIPLE COMMANDSSome frequently used commands can be represented with a single word, an alias.For example:houdini-> alias greet echo hello worldhoudini-> greethello worldhoudini-> alias mine opset -d off * ; opset -d on geo1houdini-> mineThis will execute the string attached to the alias mine and turn off the display ofall the objects then turn on objectgeo1.The next two commands list, then undeÞne, an alias:houdini-> aliasgreet hello worldmine opset -d off * ; opset -d on geo1houdini-> alias -u greetHoudini accepts several commands on the same command line separated by a semi-colon. This does not apply to semicolons embedded in quotes. Aliases can containcommands embedded in quotes.Note:Alias expansion is not performed if the local variablenoaliasis set.The Scripting Language861Houdini6.0Reference2.7 USING ARGUMENTS IN SCRIPTSThesourcecommand, when entered at the c-shell prompt, can have arguments afterthe.cmdÞle name. These arguments are set to Houdini variables so that they can beused by the script. For example:houdini-> source repeat.cmd1 10 2 blockheadwhererepeat.cmdcontains the Houdini script,echo Hello, my name is $arg4for i = $arg1 to $arg2 step $arg3

echo I said, my name is $arg4endNote that there are four variables in the script:arg1, arg2, arg3andarg4. These areset to thesourcearguments1, 10, 2andblockheadrespectively. This mechanismworks well with the-g

options of thercwriteandopdumpcommands, which causeobject names to be written out generically, as$arg1, $arg2and so on. In this way,names of objects can be changed when reading them as scripts.$ARG0 – NAME OF THE SCRIPTYou can get the name of the script being run from$arg0. For example:source myscript.cmd 1 4.5 7 balloonwill come into the script with$argc = 5$arg0 = myscript.cmd$arg1 = 1$arg2 = 4.5$arg3 = 7$arg4 = balloonThis allows usages such as:if $argc != 5 thenecho USAGE: source $arg0 numclowns clownsize numtoys toytypeexitendif$ARGC – NUMBER OF ARGUMENTS PASSED TO SCRIPTThe number of arguments passed to the script can be retrieved with the variable$argc, for example, from thelookat.cmdscript:# USAGE: lookat.cmdeyeobject focusobjectif $argc!= 2 thenecho USAGE: source lookat.cmdeyeobject focusobjectexitendifThe Scripting Language12 - Scripting187SHIFT COMMANDIn addition to using arguments, scripts can do very simple parsing of the commandline using theshiftcommand. Shift will shift the argument index one argument tothe right. For example, the script for lattices sets the number of lattices (NL) todefault to3, however, if the Þrst argument passed to it is-nthen theNLwill be set tothat argument; and the arguments shifted:# lattice.cmd- builds a lattice deformation box around an objectset NL = 3if $arg1 == -n thenshiftset NL = $arg1shiftendif...Note that parsing occurs by shifting; this implies that the argumentsmust be passedin a speciÞc order.2.8 EXECUTING SCRIPTSYou can execute a list of commands located in aUNIXtext Þle by running thesourcecommand. The following is fetched from the standard Houdini directory containingscripts,$HH/scriptshoudini->source sixcreate.cmdNormally, Houdini executes all the commands in any command Þle before redraw-ing the screen.2.9 EXAMPLE SCRIPTTEXTPORT EXAMPLE – WIRING OPSYou can use a loop to perform repetitive tasks for you. For example, if you wantedto wanted to merge 255 SOPs, it would be faster to write a short script than to do allthat wiring manually. For example, if you named your SOPs consistently, like:model-0, model-1, model-2... model-255then you could execute the following script in a Textport:for i = 0 to 255opwire model-$i -$i merge1endIf you havent been consistent with naming, you could also do it with aforeach.The Scripting Language881Houdini6.0ReferenceGUESSING GAMEThe following is a simple script which illustrates the use of loops, conditional exe-cution, and variables. For more examples, see theScriptingsection of theUserGuide.# Houdini command script for the guessing game (guess.cmd)# First, lets get a random seedset foo = `system(date)`set seed = `substr($foo, 14, 2)``substr($foo, 17, 2)`# Then, pick a random numberset num = `int(rand($seed)*100)+1`set guess = -1echo Guess a random number between 1 and 100.while ( $guess != $num )echo -n Enter guess (q to quit): read guessif ( $guess == q || $guess == ) thenbreak;endif# Ensure they entered a number - i.e. convert to a numberset iguess = `atof($guess)`if ( $iguess < $num ) thenecho Too lowelse if ( $iguess > $num ) thenecho Too highelseecho Spot on!endifend# Come here if they selected q to quit:echo The number to guess was $num891Houdini6.0Reference  12 - Scripting3 SCRIPTING WITH HSCRIPT AND THE C-SHELLIn many cases an animator or Technical director will not want to use the full graphi-cal version of Houdini, but simply deal with the text version -hscriptand use the Cshell. The main advantage to this is the animator can write automated scripts torender sequences of frames without the need for an attendant animator.Houdini'shscriptallows you to accomplish virtually everything that you could withthe full GUI interface, but with text-based commands.hscriptalso makes the transi-tion from the GUI to the text version relatively easy with theopscriptcommand.This section assumes that you're relatively familiar withhscriptand Houdini's text-port commands and provides you with an explanation of how to incorporatehscriptand C shell commands. The following discussion centers around writing renderscripts, though much of this information can be used to write other kinds of scripts(such as adding in composite operations or Þle operations).3.1 THE BASICS OF INCORPORATING C SHELL AND HSCRIPTIf youve usedhscriptwithin the conÞnes of Houdinis textport, then youll realizethathscriptexpects keyboard input. The trick to incorporatinghscriptand C shell isto redirect commands coming from the C shell so they appear to be keyboard input.Once this is done, commands can be sent tohscriptas if you were typing the com-mands from the textport.Following, is the basic form a script to do this takes:#! /bin/csh -f#add any standard C shell commands here.hscript<<ENDCAT#any text that follows here is redirected to hscript#so enter hscript commands here#stop processing hscript commandsENDCAT#add supplementary standard C shell commands#end of shell script3.2 SYMBOLS  AND & EXPLAINEDThe lineshscript<<ENDCATandENDCATare signiÞcant. What does the<< ENDCATmean? Simply put, anything between these lines is interpreted ashscriptcommandsand any commands placed outside these lines is interpreted as standard C shell com-mands. Actually you dont have to useENDCAT it could be any word that is not areserved word in C shell orhscript. However its better to pick a standard and stickto what works.Scripting With Hscript and the c-shell901Houdini6.0ReferenceDo not incorporate extra spaces or comments on the line that contains theENDCATterminator. If you do, you'll get an unknown variable error.Alternatively, you might see (and use) the linehscript<<ENDCAT >& renlogor

something similar. Weve seen what<< ENDCATmeans  now for the>& renlog.The>&means any error messages that normally would appear on screen are insteadwritten to a Þle. In this case the Þle is calledrenlog.You should note thatrenlogcan be any Þle name.3.3EXAMPLES – RENDERING SCRIPTSEXAMPLE 1 – BASIC RENDERLooking at a very simple example, the following script works with two parametersthe.hipÞle to render and the Þle name to send the rendered image to. The script isnamedsimple_renand would be invoked as follows:basic_rendertest.hip

/usr/tmp/test_image.pic

source#! /bin/csh -f#check to see if user suppled the correct number of arguments#- exit if notif ($#argv < 2) thenecho USEAGE: ren_script <hip_file> <out_file>exitendif# set up user supplied argumentsset HIP_FILE = $1set OUT_FILE = $2# start up hscript and allow commands to be sent from C shellhscript << ENDCAT >& renlogmread $HIP_FILEopcd \/out# set the ouput file name for the render output driveropparm mantra1 picture ( $OUT_FILE )#start the renderrender mantra1#signal an end to commands sent to hscriptENDCATScripting With Hscript and the c-shell12 - Scripting191explanation#! /bin/csh -fThis line is required to be at the beginning of each C shell script to denote that itcontains commands that can be executed as a C shell script.if (#$argv < 2) thenecho USEAGE: ren_script <hip_file> <out_file>exitendifThese lines check to see if you entered the correct number of arguments. The varia-ble#$argvcontains the number of parameters passed to the C shell script from thecommand line. For example, if you typedbasic_render test.hip, the variable#$argvwould be set to 1, and an error message would be generated because you omitted adestination image Þle as part of the command string.set HIP_FILE = $1set OUT_FILE = $2These lines set the variables$HIP_FILEand$OUT_FILEto the parameters sent tothe C shell from the command line. For instance, if you typedbasic_render test.hip/usr/tmp/test.pic,$1and$2and, consequently,$HIP_FILEand$OUT_FILE, wouldbe set totest.hipand/usr/tmp/test.picrespectively.hscript << ENDCAT >& renlogCommands following this line will be interpreted ashscriptcommands up until itencounters the wordENDCAT.Also any error messages encountered inhscriptwill besent to a Þle calledrenlog.mread $HIP_FILEReads the.hipÞle speciÞed by this variable.opparm mantra1 picture ( $OUT_FILE )Changes the default output paramter so the rendered image is sent to the Þle speci-Þed by$OUT_FILE(the default setting is ip).render mantra1Render the image using themantra1output driver. Note that this case assumes thatthe output drivermantra1exists in the saved.hipÞle.ENDCATThis signals the C shell to stop redirecting commands tohscript. Don't insert extraspaces or comments or you will get the following error:ENDCAT - << terminator not foundEXAMPLE 2 – RENDERING SEQUENCES OF FRAMES#! /bin/csh -f#check to see if user suppled the correct number of arguments#- exit if notScripting With Hscript and the c-shell921Houdini6.0Referenceif ($#argv < 4) thenecho "USEAGE: ren_script <hip_file> <out_file> <start><end>"exitendif# set up user-supplied argumentsset HIP_FILE = $1set OUT_FILE = $2set START = $3set END = $4# start up hscript and allow commands to be sent from C shellhscript<<ENDCAT>&renlogmread $HIP_FILEopcd \/out# set the ouput file name for the render output driveropparm mantra1 picture ("$OUT_FILE")# turn on the frame range option and give it appropriate range.opparm mantra1 trange ( on ) f ( $START $END 1 )#start the renderrender mantra1# this signals and end to our commands to hscriptENDCATEXAMPLE 3 – FOR – NEXT LOOP#! /bin/csh -f#check to see if user suppled the correct number of arguments#- exit if notif ($#argv < 4) thenecho "USEAGE: ren_script <hip_file> <out_file> <start><end>"exitendif# set up user supplied argumentsset HIP_FILE = $1set OUT_FILE = $2set START = $3set END = $4Scripting With Hscript and the c-shell12 - Scripting193# start up hscript and allow commands to be sent from C shellhscript<<ENDCAT>&renlogmread $HIP_FILEopcd \/out# set the ouput file name for the render output driveropparm mantra1 picture ("$OUT_FILE")opcookfor FRAME = $START to $ENDecho "Rendering framefcur \$FRAME

render mantra1end# this signals and end to our commands to hscriptENDCAT3.4 VARIABLE CAVEATSLooking at the above listing, you might have noticed that some variables are pre-pended by a "\". This is to avoid theunknown variablemessage that occurs in Cshell. Well delve into this a little more deeply here. In short, prepending a backslashonto a variable name prevents C shell from expanding the variable before it gets tohscript.From Houdini's textport you may do something like the following:set hello_var = "Hello good citizen..."echo $hello_varorfor frame = 1 to 100 step 1echo "Rendering frame $frame...endThis would work well. However, you will run into problems when you incorporatethis same set of commands using C shell andhscript. For example:hscript << ENDCATfor frame = 1 to 100echo "Rendering frame $frame..."endENDCATScripting With Hscript and the c-shell941Houdini6.0ReferenceRunning this script would give you the error:frame - Undefined variableIn

order to correct this you prepend a "\" to any variables you are manipulating (allthose variable names that you would put a '$' in front of). The above example wouldbe corrected as follows:hscript << ENDCATfor frame = 1 to 100echo "Rendering frame \$frame..."endENDCATWhen the C shell encounters a$it tries to expand that variable into a value. How-ever, you don't want C shell to do this, you wanthscriptto expand it instead. Thebackslash prevents the C shell from expanding the variable before it gets tohscript.3.5 C SHELL SCRIPTING NOTESThere are several conventions to adhere to when writing shell scripts. make sure the Þrst line in your script starts with#! /bin/csh -fmake sure that the script is made executable with thechmod()function. For exam-plechmod 555 simple_renmakes the scriptsimple_renreadable and executableby everyone. watch what you put on the line containing the terminatorENDCAT. Be wary of of prepending variables declared inhscript, when runninghscriptfrom the C shell. These must be prepended by a "\" in order to work properly.3.6 OBTAINING PARAMETERS FOR OUTPUT DRIVERS AND OTHER OPSOPSCRIPT COMMANDUp to this point weve used theopparmcommand to set up the parameters for ourrenders. Just how and where do we get these parameters? The easiest method ofobtaining them is through the use of theopscriptcommand.Theopscriptcommand allows you to obtain the paramters (in text format) of anyOperator available in Houdini. This means that you can create your scene and outputdrivers with Houdinis graphical interface and then use theopscriptcommand towrite these parameters to a Þle for use in shell scripts.DUMPING OPSCRIPT PARAMETERSTo write an operators parameters from the graphical interface to a Þle for inclusionin a script, do the following:1.Create a new output driver with Houdinis graphical interface (or modify anexisting one likemantra1);2.Open the Textport (AS

t);3.Typeopcd /outin theTextport. This moves you to the output directory;Scripting With Hscript and the c-shell12 - Scripting1954.Typeopscript <drivername> > <filename>. If the driver name is calledmantra1and the Þlename you want to save to is called/usr/tmp/driver.cmdthentype:opscript mantra1 > /usr/tmp/friver.cmdSAMPLE OUTPUTS FROM OPSCRIPTThe following output was generated with theopscriptcommand:opscript mantra1 > /usr/tmp/driver.cmd:1: # Node mantra12: opadd -n mantra mantra13: oplocate -x 0 -y 0 mantra14: opparm mantra1 execute ( 0 ) trange ( on ) f ( 1 150 1 ) \5: renderer ( Mantra2 ) camera ( cam1 ) visible ( * ) tscript ( off ) \6: script ( /usr/tmp/test.cmd ) binary ( off ) picture ( $HIP/$F.pic ) \7: dof ( on ) jitter ( 1 ) dither ( 0.004 ) gamma ( 1 ) sample ( 3 3 ) \8: field ( frame ) blur ( deform ) tres ( on ) res ( 320 243) \9: resmenu ( 640 486 1.0 ) aspect ( 1 ) command ( mantra3 )10: opset -d off -r off -t off -l off -s off -u off -c off -C off -p off mantra111: opcf /outLines 4-9 specify parameters for the ouput drivermantra1. Normally they wouldappear as one line but have been formatted on multiple lines here for the sake of leg-iblity.To use this information in a script, you would remove lines 3, 10, and 11, (these arenot necessary unless you are importing it into the graphical version of Houdini)leaving you with:1: # Node mantra12: opadd -n mantra mantra14: opparm mantra1 execute ( 0 ) trange ( on ) f ( 1 150 1 ) \5: renderer ( Mantra2 ) camera ( cam1 ) visible ( * ) tscript ( off ) \6: script ( /usr/tmp/test.cmd ) binary ( off ) picture ( $HIP/$F.pic ) \7: dof ( on ) jitter ( 1 ) dither ( 0.004 ) gamma ( 1 ) sample ( 3 3 ) \8: field ( frame ) blur ( deform ) tres ( on ) res ( 320 243) \9: resmenu ( 640 486 1.0 ) aspect ( 1 ) command ( mantra3 )This fragment adds an output driver calledmantra1which tellshscriptto renderusingmantra. It then uses theopparmparameter to set the requisite parameters.At Þrst glance, the number of parameters used with theopparmcommand seemscumbersome. In many cases, you might want to use default settings and just tweakone or two parameters. For example, assume that the only thing you want to changefrom the defaults is the size of the output image. To accomplish this, your scriptfragment might look like the following:opadd -n mantra mantra1opparm tres ( on ) res (640 480 )In this case you are overriding the default resolution withtres ( on )and specifyingthe custom resolution withres (640 480 ). To use this in a Þle you could do twothings:1.Copy these lines into your C shell script (the approach used thus far), or;2.Reference this Þle in the C shell using thesourcecommand.Scripting With Hscript and the c-shell961Houdini6.0Reference3.7 USE OF THE SOURCE COMMANDThough it hardly seems a chore to simply copy these lines into your shell script inthese simple cases, imagine that you have many script fragments that are changedrepeatedly during a production by your Technical Director and these are stored in acentral repository. Instead of having the Technical Director or the animator makethese changes in the C shell script, all that is necessary is to change the.cmdÞleitself and the changes are automatically reßected. The use of the source commandcan make a Þle cleaner and easier to maintain, but it depends on the individual andthe overall complexity of the script.The two examples below outline render scripts that are functionally equivalent,except the Þrst example uses thesourcecommand to reference a Þle created byopscript, while the second reproduces the code inline.USING SOURCE#! /bin/csh -fset HIP_FILE = /usr/temp/test.hiphscript << ENDCAT # start up hscript and allow commands to bemread $HIP_FILE # sent from the C shell#CREATE RENDER OUTPUT DRIVER#source in the render.cmd file that we have previously created

source /usr/tmp/render.cmd#start the renderrender mantra1ENDCAT # this signals and end to our commands to hscriptWITHOUT USING SOURCE#! /bin/csh -fset HIP_FILE = /usr/temp/test.hiphscript << ENDCAT # start up hscript and allow commands to bemread $HIP_FILE # sent from the C shell#CREATE RENDER OUTPUT DRIVER# Node mantra1opadd -n mantra mantra1opparm mantra1 execute ( 0 ) trange ( on ) f ( 1 150 1 ) \renderer ( Mantra2 ) camera ( cam1 ) visible ( * ) tscript ( off ) \script ( /usr/tmp/test.cmd ) binary ( off ) picture ( $HIP/$F.pic ) \dof ( on ) jitter ( 1 ) dither ( 0.004 ) gamma ( 1 ) sample ( 3 3 ) \field ( frame ) blur ( deform ) tres ( on ) res ( 320 243) \resmenu ( 640 486 1.0 ) aspect ( 1 ) command ( mantra3 )#start the renderrender mantra1ENDCAT # this signals an end to our commands to hscriptScripting With Hscript and the c-shell12 - Scripting1973.8 DEFAULT PARAMETERS FOR OUTPUT DRIVERSThe following are the default parameters set for each output driver when using theopaddcommand or when adding a new driver in the graphical interface.It is not necessary to include all parameters available when executing anopscriptcommandjust the ones you want changed from the defaults. Also note that someparameters remain consistent for each driver and should not be changed. Theseinclude: execute (0) renderer ( Mantra2 ) resmenu ( 640 486 1.0 )PARAMETER MEANINGStrange (on/off)when rendering, this parameter determines whether ornot to use the frame range speciÞed byf ( ). When off,only the current frame will be rendered.f (start end inc)speciÞes the frame range that is rendered.camera (cam)speciÞes which camera is used for the render.visible ( scope)speciÞes which objects are rendered. The wildcard *means all objects are made visible in the render.tscript (on/off)speciÞes whether or not to generate the.ifd(instanta-neous frame description formantra) or a.rib(Render-Man interface bytestream for Renderman) instead of arendered picture. This option will override that set withthepicture ( )parameter.script (script_name)speciÞes the name of the script generated when thetscript ( )option is on.binary (on/off)speciÞes whether the output Þle will be saved inASCIIor binary format.picture (Þle_name)the name of the output Þle when generating images.dof (on/off)speciÞes whether to use depth of Þeld.jitter (value)speciÞes the jitter value used in conjuction with anti-aliasing techniques.dither (value)sets the dither level.gamma (value)sets the gamma value for the frame.sample (xval yval)sets the number of supersamples in the horizontal andvertcal directions on a per pixel basis.Scripting With Hscript and the c-shell981Houdini6.0ReferenceÞeld (frame/even/odd)allows you to specify full frame, even Þeld or odd Þelddominance.blur (off/deformation/transformation )

speciÞes what type of motion blur to use for Mantraand Renderman.tres (on/off)speciÞes whether to override the default camera resolu-tion.res (x y )speciÞes resolution of frame in pixels whentres()is on.aspect (value)speciÞes the aspect ratio.3.9 OUTPUT DRIVER SAMPLESMANTRAopparm mantra1 execute ( 0 ) trange ( off ) f ( 1 150 1 )renderer ( Mantra2 ) camera ( cam1 ) visible ( * ) tscript ( off )script (  ) binary ( on ) picture ( ip ) dof ( off ) jitter ( 1 )dither ( 0.004 ) gamma ( 1 ) sample ( 3 3 ) field ( frame )blur ( none ) tres ( off ) res ( 320 243 ) resmenu ( 640 486 1.0 )aspect ( 1 ) command ( mantra3 -v 0.015 )RENDERMANopparm rman1 execute ( 0 ) trange ( off ) f ( 1 150 1 )renderer ( Mantra2 ) camera ( cam1 ) visible ( * ) tscript ( off )script (  ) binary ( on ) picture ( ip ) dof ( off ) jitter ( 1 )dither ( 0.004 ) gamma ( 1 ) sample ( 3 3 ) field ( frame )blur ( none ) tres ( off ) res ( 320 243 ) resmenu ( 640 486 1.0 )aspect ( 1 ) command ( render ) device ( framebuffer )COPopparm cop1 execute ( 0 ) trange ( off ) f ( 1 150 1 )icenetname (  ) copname (  ) copoutput ( ip ) tres ( off )res ( 320 243 ) fraction ( 1 )GEOMETRYopparm geometry1 execute ( 0 ) trange ( off ) f ( 1 150 1 )objectname ( geo1 ) sopname ( font1 ) sopoutput ( $HIP/$F.bgeo )SCENEopparm scene1 execute ( 0 ) trange ( off ) f ( 1 150 1 )renderer ( Mantra2 ) camera ( cam1 ) visible ( * ) tscript ( off )script (  ) binary ( on ) picture ( ip ) dof ( off ) jitter ( 1 )dither ( 0.004 ) gamma ( 1 ) sample ( 3 3 ) field ( frame )blur ( none ) tres ( off ) res ( 320 243 ) resmenu ( 640 486 1.0 )aspect ( 1 ) command ( mantra )Scripting With Hscript and the c-shell12 - Scripting1993.10 A FINAL EXAMPLE (RENDERING AND COMPOSITING)This example is slightly contrived, but it is a good example of things you can dowith scripting. Lets say you have two animators who are working on the samescene and at the end of the day, you want to render their contributions and make aside by side comparison to see which one is better.Well assume that we have two different .hip Þles  one from each animator. Wethen want to render a sequence of frames from each.hipÞle and then use the com-positor in Houdini to place them side by side and then write the resulting compari-sion frames out to disk. You want to be able to do this automatically at night andthen come in the next morning to see the results.This involves two steps: Render the two sequences of frames, using a variation of the Þrst render scriptexample. Compositing the images together, and then writing them out to disk.We'll build ourCOPnetwork interactively in Houdini and save it out as a .hipÞle.We'll then change the parameters of the composite from the C shell based on therender parameters we give it. This makes life much easier while still giving you allthe ßexibility you need. You could build the entire compositing section with hscript.This is included as listing 5 for comparision purposes.BUILDING THE COP NETWORKThe idea will be to take a neutral background colour (like black) which is double thesize of the two input images, then use the OverCOPto position and overlay theimages correctly over the background.1.Start Houdini and create a newCOPnetwork. Call itcompare.2.In the compositor place down a constantCOP. Set alpha to zero, so it is com-pletely transparent and make sure its name is "color1".3.Place two FileCOPs making sure their names areÞle1andÞle2.4.Append an OverCOPto each of the ÞleCOPs and in theSpatial Shifttab selecttheno scalecheckbox, making sure they are namedover1andover2.5.Attach the output from the ConstantCOP(color1) into the second inputs of eachof the OverCOPs.6.Put down another OverCOPand run the outputs from the Þrst two OverCOPs

into the inputs of the third Over.7.Go to the Output Editor, and place a Composite output driver, making sure it iscalledcop1.8.Save this Þle and call itcompare.hip. (Dont worry about other parameters, suchas the resolution of the images, since well be setting those in the C shell.)Scripting With Hscript and the c-shell1001Houdini6.0ReferenceWRITING THE RENDER SCRIPTCreate a render script calledcompareand save it in the same directory ascom-pare.hip. The full script is below and makes several assumptions. First, the.hipÞlesthat are the animator-supplied.hipÞles, must both have an output driver calledmantra1. Second, the render script is calledcompareand is located in the samedirectory as thecompare.hipÞle.usagecompare <hipfile1> <hipfile2> <from> <to> <xres> <yres>examplecompare animator1.hip animator2.hip 1 50 640 480This will render out frames 1 to 1 50 from each of the Þles calledanimator1.hipandanimator2.hipat 640480 resolution and the composite the images together usingthecompare.hipÞle created above.CODE FOR COMPARE RENDER SCRIPT#! /bin/csh -f#check to see if the user supplied the correct number of arguments#- exit if notif ($#argv < 6) thenecho "USEAGE: ren_script <hipfile1> <hipfile2> <from> <to> <xres> <yres>"exitendifset HIP_FILE1 = $1 # set up user supplied argumentsset HIP_FILE2 = $2set START = $3set END = $4set XRES = $5set YRES = $6set OUT_FILE1 = sequence1_\$F.picset OUT_FILE2 = sequence2_\$F.picset COMP_OUTPUT = comp_\$F.pic#Render out the first sequence of images#hscript <<ENDCAT>&renlog # start up hscriptmread $HIP_FILE1 # read in the first .hip file# set the ouput file name for the render output driveropcd \/outopparm trange ( on ) f ( $START $END 1 )opparm tres (on ) res ( $XRES $YRES )opparm mantra1 picture ( '$OUT_FILE1' )render mantra1#this signals an end to C shell to stop sendng commands to hscriptENDCAT#Render out the second sequence of images#hscript <<ENDCAT>&renlogmread $HIP_FILE2 #read in the second .hip fileopcd \/outopparm mantra1 trange ( on ) f ( $START $END 1 )opparm mantra1 tres (on ) res ( $XRES $YRES )opparm mantra1 picture ( '$OUT_FILE2' )render mantra1#stop sending commands to hscript (effectively quitting hscript)ENDCAT#Do the composite, putting both images side by side#hscript<<ENDCAT>&renlog # start up hscriptmread "compare.hip" # read in the compositing .hip fileScripting With Hscript and the c-shell12 - Scripting1101opcd \/comp\/compareopparm file1 source ( '$OUT_FILE1' )opparm file2 source ( '$OUT_FILE2' )opparm color1 size ( \`$XRES*2\` $YRES )opparm over2 offoffpixel ( $XRES 0 )opcd \/outopparm cop1 icenetname ( compare ) copname ( over3 )opparm cop1 trange ( on ) f ( $START $END 1 )opparm cop1 copoutput ( '$COMP_OUTPUT' )render cop1ENDCATNOTES ON THE RENDER SCRIPTThe Þrst half of the script is nothing new. It merely sets up our user-supplied param-eters, and then renders a sequence of images from the two .hip Þles supplied as com-mand line paramters. The third section which does the actual composite is a littledifferent, but if you understand the rendering sections, you should have little troubleunderstanÞng how the compositing section works.The trickiest part in this whole script is the line:opparm color1 size ( \`$XRES\*2\` $YRES )Note the backslashes here.These are necessary because we are dealing with the Cshell. Inhscriptwe could just type in something likeecho `1+1`and get 2. If we

try this through the C shell we get an error. So the general rule is if you're trying todo arithmetic inhscriptvia the C shell, put a \ in front of the backquote `.The compositing section works by setting up all of the compositing parameters onthe ßy. It Þrst tells the FileCOPs where to Þnd the Þles. It then tells the ColorCOPto

resize itself so it is double the X reolution of the two rendered images (so we canplace them side by side). Finally it tells the two OverCOPs where to put the two ren-dered images in relation to the background (in this case image one is shifted up tothe halfway mark and image two is shifted over to the right and up half way).The Þnal step is to tell the composite output driver the frame range and Þle namesfor output.THINGS TO WATCH OUT FORThis is a small list of things to watch out for when using hscript within the C shell.Readng this will probably save you a lot of aggravation and time if you Þnd yourscripts don't work as they should. Many errors can be attributed to the C shellexpanding strings and variables when in fact, you don't want them to.One other thing to keep in mind is that hscript and C shell are not syntactically thesamethough it may appear to be at Þrst glance. Entries that you make in Houdini'stextport may need some editing when you use them as input from the C shell.Read the compare script above to see some of following items put into practice.Passing in strings to hscriptPassing variable strings tohscriptshould be encapsulated by single forwardquotes. So if you set a variable string such asset OUT = image_$F.picthen makesure when you use it withhscriptyou type in'$OUT'.If you want to pass in a string with spaces in it (like"hello there"), make sure toput it in double quotes.Scripting With Hscript and the c-shell1021Houdini6.0ReferenceVariables passed in as numerics

Any variable passed intohscriptas a numeric can be left as is (unless you are per-forming arithmetic with it).Specifying Directories and using '/'If you change directories inhscript(e.g.opcd /out) then make sure that any for-ward slashes are protected by a backslash (opcd \/out).ArithmeticIf you want to do some arithmetic viahscriptfrom within C shell, make sure thatany arithmetic is surrounded by a \` to prevent C shell from doing any expansionwith the backquote. For instance inhscriptyou might type:echo `1+2`. If you aredoing this within C shell you would use:echo \`1+2\`.Watch the ENDCATWhen you have thehscript<<ENDCAT ... ENDCATsequence, take care not toput any trailing spaces or comments after theENDCAT. C shell is very literalwhen looking for the terminating token. Look at the example scripts to see howthey are laid out.Make sure your C shell script starts with the line : #! /bin/csh -fThis tellsUNIXthat it is dealing with a C shell script.Also make sure that thisentry is on a line by itself.Make sure scripts are executableYour C shell scripts have to be executable or you won't be able to run them.To make this a little clearer, lets look at a script segment that works when type man-ually into Houdinis textport, and then compare that with a version that must bemodiÞed to work with C shell. The differences are set in bold type.segment 1 (as it would appear manually typed into houdini's textport)set OUT_FILE1 = source1_\$F.picset OUT_FILE2 = source2_\$F.picset COMP_OUTPUT = comp_\$F.picset XRES = 256set YRES = 256opcd/comp/compareopparm file1 source ($OUT_FILE1)opparm file2 source ($OUT_FILE2)opparm color1 size (`$XRES*2`$YRES )opparm over2 offoffpixel ( $XRES 0 )segment 2 (modified for use with c shell)set OUT_FILE1 = source1_\$F.picset OUT_FILE2 = source2_\$F.picset COMP_OUTPUT = comp_\$F.picset XRES = 256set YRES = 256opcd\/comp\/compare#directory operationopparm file1 source ('$OUT_FILE1') #using a string variableopparm file2 source ('$OUT_FILE2') #directory operationopparm color1 size (\`$XRES*2\`$YRES ) #doing arithmeticopparm over2 offoffpixel ( $XRES 0 )Scripting With Hscript and the c-shell12 - Scripting11033.11 BUILDING COMPLEX FILENAMESThere are many times when you want to build complex Þlenames, based on framenumbers or based on a Þlename referenced by the user. For example, passing in a.hip Þle to your script, then converting this Þlename to a .pic Þle (i.e. convertinput.hip to output.pic). Below are C shell example fragments.EXTRACTING THE BASE FILENAME, PATH AND EXTENSIONset HIP_FILE = \/usr\/tmp\/myfile.hipset HIP_PATH = $HIP_FILE:h #keep the path/drop filenameset FILE_NAME = $HIP_FILE:t #keep the filename/drop pathset BASE = $FILE_NAME:r #drop the extensionset EXT = $FILE_NAME:e #just keep the extensionThe variables would have the following values:$HIP_FILE = /usr/tmp/myfile.hip$HIP_PATH = /usr/tmp$FILE_NAME = myfile.hip$BASE = myfile$EXT = hipBUILDING A FILE NAME WITH A NEW EXTENSIONContinuing from above we will build a new Þlename with a new extension. We haveall of the individual components and now we want to put them back together again.set NEW_EXT = .picset NEW_FILE = $HIP_PATH\/$BASE${NEW_EXT}Notice the braces.This allows you to put togther two variables as one string. Notethat you could say$BASE$NEW_EXT, but its good to get in the habit of using thebraces, as it might save you trouble later on. Also notice that we put in a \/. If youlook closely at the results of$HIP_PATH, it doesnt include the trailing forwardslash, so we have to include it ourselves.Now we end up with the following results:$HIP_FILE = /usr/tmp/myfile.hip$HIP_PATH = /usr/tmp$FILE_NAME = myfile.hip$BASE = myfile$EXT = .hip$NEW_EXT = .pic$NEW_FILE = /usr/tmp/myfile.picWe could have accomplished the same thing much more quickly. All we reallywanted to do was change the extension. The following would be equivalent:set $HIP_FILE = \/usr\/tmp\/myfile.hipset FILE_NAME = $HIP_FILE:r #keep all but extensionset NEW_EXT = .picset $NEW_FILE = $FILE_NAME${NEW_EXT}The reason for breaking up the full path into its individual components is so that youcan change the individual components and put them back together again.Scripting With Hscript and the c-shell1041Houdini6.0ReferenceMEANING OF :H, :R, :E, :TMore information on the following, can be found by doing aman cshand searchingforHistory Substitution.:h Remove a trailing pathname component, leaving the head.:r Remove a trailing suffix of the form `.xxx', leaving thebasename.:e Remove all but the suffix.:t Remove all leading pathname components, leaving the tail.ScriptingTricks12 - Scripting11054 SCRIPTING TRICKS4.1 GROUP NAMES IN SCRIPTING COMMANDSYou specify a group within scripting commands by using the @ character before thegroup name. For exampe, if you wanted to turn on/off the display of all objects in agroup, you would use theopsetcommand (e.g.opset -d on/off geo*). In the com-mand, we can specify an OP name (e.g. geo1), a pattern for an OP name (e.g. geo*),or OP Groups (e.g. @myGroup).To test this, use the Object EditorsEdit > Edit OP Groups...menu command to cre-ate an object group called myGroup. It should contain geo1, geo2, and ambient1.You can list the objects included inmyGroupwith theopglscommand:/obj -> opset -d on @myGroupTurns on the display ßags for all the objects listed inmyGroup.Using the @ character to expand a group name can also be applied to any otherHoudini scripting command that normally accepts only object names.Tip:Try assigning this to a Function Key using theEdit > Edit Aliases...dialog.4.2 EMBEDDING COMMANDSWithout the Group expransion using the @ character, we would have to turn on/offdisplay of all the objects in a group by using theopglscommand delimited with sin-gle quotes. For example, if you didnt have the @ character, you would need to usesomething like:-> opcf /obj/obj -> opgls -l myGroupmyGroupgeo1geo2ambient1/obj -> opset -d on `run("opgls -l myGroup")`This works, because where it expects an object name (or pattern), youre telling it toevaluate what is within the single quotes as the name(s). Theopglscommand simplylists all the objects contained in the speciÞed group. So, in effect, what youre doingis listing the names of all the objects within your group by having theopglscom-mand list them out for you. Youll get a single error (this doesnt affect correct oper-ation however), because the actual group name (i.e. myGroup) is listed along withall the object names in that group, andhscriptwont Þnd it as a valid object.ScriptingTricks1061Houdini6.0Reference4.3 SETTING ACCORDING TO THE DISPLAY FLAGIf you want to set all the objects within a group (say bugs) but only if their Dis-play ßag is set (Object Editor), you can use aforeachloop to check and set the statusof objects in the group which have their Display ßag on. For example:opcf /obj#Loop through all the objects in the groupforeach obj ( run("opglob @bugs") )opset -l on $obj/opflag($obj, "d")4.4 TRAVERSING AN OBJECT HIERARCHYThe following script can be used to traverse an object hierarchy. This script simplyprints out the hierarchy (with appropriate indenting), however, it can easily be mod-iÞed to do other things.# hscript command file to traverse a hierarchy of nodesif ( $argc != 2 && $argc != 3 ) thenecho "Invalid usage: $arg0 opname [prefix]exitendifif ( $argc == 2 ) thenset indent = ""set level = 1elseset indent = ""for i = 0 to $arg2set indent = "$indent "endset level = $arg2 + 2endifecho "$indent"$arg1set nout = opnoutputs($arg1)-1if ( $nout != -1 ) thenfor i = 0 to $nout step 1source $arg0 opoutput($arg1, $i) $levelendendifIntrinsic Commands12 - Scripting21072 Scripting

CommandsFollowing, is a list of scripting commands available in the Houdini scripting lan-guage. Commands can be broken up into different logical groups.For C-shell scripting commands, consult a text onUNIX.1 INTRINSIC COMMANDSThis set of commands provide an intrinsic level of control for scripting. These com-mands are most like theircshequivalents.1.1 ALIASSYNTAXalias [name [value]]alias -salias -u name [name2...]EXPLANATIONCreates an alias for a command or sequence of commands.Aliases may containsemi-colon separated statements.-sDisplay a list of current aliases in source-able format

so they can be sourced into otherHIPÞles.-uWill undeÞne the aliases listed.EXAMPLEalias ls oplsThis alias command changes theopls(operator list) command to the abbreviatedcharacter stringls.Intrinsic Commands1082Houdini6.0ReferenceTEMPORARILY DISABLING ALIASINGIn the Houdini shell, if the local variablenoaliasis set, then alias expansion is notdone on commands in the script. This variable can be used to force scripts to use theoriginal commands instead of user aliases. Since local variables are local per script,once the script exits, alias expansion will continue as before. However, if the varia-ble is set, all subsequent (nested) scripts will have alias expansion turned off. Exam-ple:alias echo "This is a bad alias"set noalias = 1echo "foo bar"set -u noaliasIn this script, even though the alias is set, the echo statement will work (since thenoalias variable is set).1.2 BREAKSYNTAXbreak [n]EXPLANATIONBreaks out of a loop without executing any of the remaining statements. The loopwill be terminated without completing its iterations. The integer speciÞed by ndetermines how many loops to break out of. By default,n== 1.EXAMPLEbreak 3This command string would break you out of three levels.1.3 CMDREADSYNTAXcmdread [-q] filenameEXPLANATIONCmdread runs the commands in the Þlename speciÞed. If the-qoption is speciÞed,no warnings about missing Þlenames will be displayed. See also:source.Intrinsic Commands12 - Scripting21091.4 CONTINUESYNTAXcontinue [n]EXPLANATIONContinue a loop without executing the statements following the continue statement.The loop will continue iterating. The integer speciÞed byndetermines how manyloops to affect.EXAMPLEcontinue 3This command executes the script, omitting the next three loops.1.5 ECHOSYNTAXecho [-n] listEXPLANATIONThe words in list are displayed. The-noption will prevent a trailing line feed frombeing displayed.EXAMPLEecho bafflegabThis command would produce the textbafßegabbelow the command line.echo `npoints(/objects/object_name/sop_name)`echo `npoints(/objects/gg/s)`If object isggand theSOPis s then following expression will display the number ofpoints in theSOP

s.1.6 EXCATSYNTAXexcat [pattern]Intrinsic Commands1102Houdini6.0ReferenceEXPLANATIONThis command displays the source for all expression functions in the current .hipÞle. If a pattern is speciÞed, only those expression functions matching the patternare displayed.EXAMPLEexcat fpsThis will display all expressions in the .hip Þle that containfps.1.7EXEDITSYNTAXexedit [pattern]EXPLANATIONThis command allows you to edit expression functions. If no pattern is speciÞed,you can add new functions to the current list. If a pattern is speciÞed, the functionswhich match the pattern will be edited.Warning:If a function is renamed or removed from the edit session, this doesnotmean that the old function will be removed from the current function list. This mustbe done through theexrmcommand.EXAMPLEexedit $FAllows you to edit the expression functions containing$F.Tip:You can also edit expression functions using the dialog displayed from theEdit> Edit Aliases/Variables...menu command.1.8 EXHELPSYNTAXexhelp [pattern]EXPLANATIONDisplays help text for all expression functions matching the pattern speciÞed. If nopattern is speciÞed help for all the expressions is shown.EXAMPLEexhelp sinIntrinsic Commands12 - Scripting2111Displays the online help for the command chadd.1.9 EXLSSYNTAXexlsEXPLANATIONList all the current expression functions.1.10 EXREADSYNTAXexread diskfile [diskfile2...]EXPLANATIONThis command reads external Þles of expression functions.EXAMPLEexread /n/usr/staff/betty/[filename]This command reads the expression functions in the path and Þle(s) speciÞed.1.11 EXRMSYNTAXexrm [pattern]EXPLANATIONAll expression functions matching the pattern will be removed.1.12 EXITSYNTAXexitIntrinsic Commands1122Houdini6.0ReferenceEXPLANATIONTerminates a source Þle. This will terminate all if statements and for loops cor-rectly. It is not possible to specify an exit status, except that thesetenvcommand canbe used to return a status in a global variable.1.13FORSYNTAXforVARIABLE= START to END [step INC]EXPLANATIONThe for loop construct.The loop will set the value ofvarto start. On each itera-tion of the loop, the value ofvarwill haveincadded to its value. The loop will ter-minate after the end is passed. If the end value is achieved exactly, the loop williterate for this value. By default, the step size is 1. The end of the for loop isßagged by the end command. For example:houdini -> for i = 1 to 3> echo -n $i,> end1, 2, 3,The variable you specify loops from the beginning to the end according to the incre-ment you set.EXAMPLEfor i = 1 to 3for i = 1 to 100 step 3In the examples above, the variableiwill loop, in the Þrst instance, from one tothree. In the second instance, the variable will loop from one to one hundred inincrements of three.1.14FOREACHSYNTAXforeachVAR(list)EXPLANATIONTheforeachloop construct. The loop will set the value ofVARto a different word inthe list for each iteration of the loop. The list is processed in the order speciÞed. Theend of aforeachloop is always signiÞed by theendcommand. For example:> foreach obj ( `execute(opls)` )> echo -n $obj,Intrinsic Commands12 - Scripting2113> endcam1, geo1, geo2, light1, light2,1.15 HELPSYNTAXhelp [command_pattern] [-kexpression]EXPLANATIONIf no command is speciÞed, a list of available commands is displayed.If a command is speciÞed, help for that command will be displayed.The -k option allows you to search for keywords. All commands which contain thekeyword will be displayed.EXAMPLEhelp echoDisplays the help available for theechocommand.help -k expressionchkey excat exedit exhelp exls exread exrm opcopy opfindEach of these commands has the word expression somewhere in the help for thecommand.1.16 HISTORYSYNTAXhistory [-c]EXPLANATIONDisplays the command history. If you employ the-coption, the command history iscleared.Intrinsic Commands1142Houdini6.0Reference1.17IFSYNTAXif ( expr ) [then]...else if (expr2) [then]...else...endifEXPLANATIONIfexpris true, the commands up to the Þrstelseare executed. Ifexpris false andexpr2is true, then the commands between the twoelsestatements are executed. Ifexpr2is false, the commands between theelseand theendifare executed. It is notnecessary to specify the twoelsestatements.It is not possible to specify commands following theifstatement. Any arguments(except the trailingthen) are considered to be parts of the condition.A matchingendifstatement should always be used after anifstatement if theifstatement is more than one line.1.18 JOBSYNTAXjob [unix_path]EXPLANATIONSets the job variable to the path you specify.EXAMPLEjob /n/usr/caesarThis command line changes the job directory.1.19 MEMORYSYNTAXmemoryEXPLANATIONDisplays the current memory usage of the application that is running.Intrinsic Commands12 - Scripting21151.20 PROMPTSYNTAXprompt [new_prompt]EXPLANATIONChange the current prompt. Before the prompt is displayed, the value of the promptis expanded. Therefore, it is possible to set the prompt to something very meaning-ful.EXAMPLEhoudini -> prompt $HIPNAME Frame $y -> untitled1.hip Frame 1 ->1.21 PRINTSYNTAXprint label expressionEXPLANATIONDisplays the value of the expression to stdout and returns the same expression value.This can be used to diagnose parameters in OPs or channels.Note:print in shell-speak doesnt actually print to the printer, but displays theresult in the shell in which the command is executed.EXAMPLEprint("wheel:", sin($T))1.22 QUITSYNTAXquitEXPLANATIONTerminates the application. Some applications will not warn of quitting without sav-ing (i.e. hscript), while others will (i.e. Houdini).Intrinsic Commands1162Houdini6.0Reference1.23 READSYNTAXread [-g] variable_name [variablename2...]EXPLANATIONWill read the following line into the variable names speciÞed. The Þrst argumentwill be put into the Þrst variable. The last variable speciÞed will contain the remain-ing arguments of the input line. If the-goption is speciÞed, the variables will be setas global variables instead of local variables. The -g option makes the variables glo-bal (seesetp. 117).1.24 RKILLSYNTAXrkill [process]EXPLANATIONAny background render which has a process ID matching the process pattern speci-Þed on the command line will be terminated. Since the process argument speciÞedcan be a pattern, it is possible to kill multiple renders at once.EXAMPLErkill 9382rkill *The Þrst example stops the speciÞc background rendering process, while the secondstops all background rendering in progress.1.25 RPSSYNTAXrpsEXPLANATIONThis command lists active background render processes. The command lists theprocess identiÞcation number, the host on which the command is running, and thename of the command being run.Intrinsic Commands12 - Scripting21171.26 SETSYNTAXset [-g] varname = valueset -p name = valueset -u nameset [-s]EXPLANATIONThesetcommand is used to assign local variables to the value given (use thesetenvcommand to set global variables). With no arguments, it will list all current variablesand their current values.The-g(global) option on thesetcommand makes it work likesetenv, otherwise thevariable will be Local to the script Þle where the command is executed.If no name is speciÞed and the -s option is given, it will output the list of variables ina form which is useful for sourcing into another .hip Þle. This makes it easier tomove variables from one .hip Þle to another.The -p option will set the variable in the caller (or parent) script. If the currently run-ning script is at the topmost level, then this option has no effect. This option lets youreturn values from within sourced scripts. For example, to set a return value into thevariable name passed into our script as the Þrst parameter, you would do somethinglike:set -p $arg1 = $returnValueThe -u option will un-set the speciÞed variable.See also:setenv.EXAMPLEsetenv -l HOUDINI_LOD = 2Temporarily changes the Houdini Level of Detail to2within the current script.THE DIFFERENCE BETWEEN SET AND SETENVUsing thesetenvcommand in the scripting language is different than using thesetcommand in two ways:1.Thesetcommand is local to the script which is currently running. This meansthat when another script is called, or the current script exits, the variable is nolonger visible. Also, this means that you can re-use variables within differentscripts without over-writing their values.2.Thesetenvcommand will create a global variable. Thesetenvcommand will alsoexport all variables to any processes started from Houdini. For example:hscript-> set foo = 0 ; unix echo '$foo'foo undefined variableIntrinsic Commands1182Houdini6.0Referencehscript-> setenv foo = 0 ; unix echo '$foo'01.27 SETENVSYNTAXsetenv [-l] varname = valuesetenv -u namesetenv [-s]EXPLANATIONThesetenvcommand sets the global variable you specify by name to the value spec-iÞed. If you do not provide a name, a list of all variables is displayed. When not pro-viding a name, and using the-soption, the command will produce output suitablefor loading as a script.The-l(local) option onsetenvmakes it work likeset forcing the variable to actlocally, meaning their values are discarded once the current script Þle ends.If no name is speciÞed and the -s option is given, it will output the list of variables ina form which is useful for sourcing into another .hip Þle. This makes it easier tomove variables from one .hip Þle to another.The-uoption will un-set the speciÞed variable.See also:set.Note:It is important to note that this command actually sets a realUNIXenviron-ment variable, its inßuence is therefore both within the Houdini shell, and in yourstandardUNIXshell.You can Þnd a complete list of Houdini-related environmentvariables in:Environment Variablesp. 211.1.28 SHIFTSYNTAXshiftEXPLANATIONWhen a script is sourced, the arguments are set to variables$arg0,$arg1... Theshift command will shift the arguments so that$arg1goes into$arg0,$arg2goesinto$arg1etc. The$argcvariable is decremented to reßect the changes.Intrinsic Commands12 - Scripting21191.29SOURCESYNTAXsource filename [arg1...]EXPLANATIONSources a command script and executes the commands contained in the script untilthe exit command is reached or the end of Þle is reached. The arguments to thescript are passed in local variables$arg0...$argn. The number of arguments ispassed as$argc. This command is often used to load in Þles generated byopscriptandopwrite.EXAMPLEsource 123.cmdThis command runs the commands in the Þle123.cmd.1.30 TIMESYNTAXtime [command]EXPLANATIONTheTimecommand allows you to time other commands (i.e. a render command or asourcecommand). The time displayed shows how much user/system and real timethe command took.EXAMPLE0.0u 0.0s 0.0r% time render mantra10.1u 0.2s 18.7rThis indicates that Houdini took .1 seconds of CPU, .2 seconds of system time and

then had to wait 18.7 seconds of real time formantrato Þnish rendering.1.31 UNDOCTRLSYNTAXundoctrl [on|off]undoctrl -sIntrinsic Commands1202Houdini6.0ReferenceEXPLANATIONThis can turn on or off the undo mechanism in Houdini. With no options, the currentstate will be printed out. Please use this command with extreme caution. Turning offthe undo mechanism can cause scripts to execute with greater speed, but the changesmade by the script will not be undo-able. As well, be careful to restore the undostate at the conclusion of the script.The second usage with the -s option queries the memory usage of the undo mecha-nism.Note: Be careful to restore the undo state at the conclusion of the script! It wouldbe a shame to lose hours of work because a script forgot to turn undos back on.1.32 VERSIONSYNTAXversionEXPLANATIONDisplays the current version of the program you are running.1.33WHILESYNTAXwhile (expression)...endEXPLANATIONThewhileloop construct. Awhileloop will iterate continuously while theexpres-sionevaluates true. When theexpressionis false, the loop will terminate. Thismeans you will have to manually include a variable within the expression, andincrement that variable somewhere within the body of the loop in order for a whileloop to Þnish its execution.Warning:It is very easy to create endless loops which will not terminate if you arenot careful about incrementing the variable within the expression somewhere withinthe body of your loop. You may want to use theforeachandforloop constructswhich implicitly increment your variable.EXAMPLEset i = 0while ( $i < 10 )set i = `$i+1`Intrinsic Commands12 - Scripting2121echo $iendoutput: 1 2 3 4 5 6 7 8 9Unix Related Commands1222Houdini6.0Reference2 UNIX RELATED COMMANDSThese commands provide a minimal interface to theUNIXshell.2.1 UCDSYNTAXucd [path]EXPLANATIONChanges the current working directory to the one you specify in the path statement.EXAMPLEucd /n/usr/staff/mulderIn this example the working directory would be altered tomulder.2.2 UPWDSYNTAXupwdEXPLANATIONThis command displays the currentUNIXworking directory.2.3 UNIXSYNTAXunix command [argument1...]EXPLANATIONRuns theUNIXcommand you specify. The command will be run in its own csh.EXAMPLEunix csh -f -cIn the example above, the csh will be started.Plug-In Commands12 - Scripting21233 PLUG-IN COMMANDSThese commands are provided through plug-in modules. These plug-ins do not haveto be loaded, but provide extra functionality if they are.For an example of how to create a Tcl/Tk script, seeScriptingchapter of theUserGuide.3.1 TCLSYNTAXtcl [args]EXPLANATIONThis command allows you to run scripts written in the Tcl language from withinHoudini, and is useful for customising Houdinis interface and dialog boxes.Tcl starts a tcl shell with the arguments given. There is an additional command in tclhscript which can be used to run any Houdini command. tcl is a public domainscripting language which has many powerful features (see tk).You can run a sample Tcl script by typingtk hbrowser.tkin the Textport. This scriptsimply brings up a Þle requester style browser which shows the Houdini objectsinstead of Þles. By double clicking on an object, you will see the contents of theobject. This is a quick way of seeing what objects are available.Tcl is a scripting language which is in common use around the world. Tk is anextension to Tcl which allows you to create Windows and interface elementsthrough the scripting language. You should be able to Þnd books that discuss Tcl/Tk(commonly pronounced tickle) in any computer book store.3.2 TKSYNTAXtk [args]EXPLANATIONTk is a version of Tcl which supports X11 and Motif extensions. This allows you tobuild custom user interfaces in scripts. Again, there are several books whichdescribe the tk language as well as a wealth of information on the world wide web.There are some simple example scripts installed in$HH/scripts/tk.Channel and Operator Commands1242Houdini6.0Reference4 CHANNEL AND OPERATOR COMMANDSThese commands deal with channels and operators in general. The commands havebeen written so there is a minimal number to become familiar with, yet powerfulenough to do almost anything that can be done through the graphical interface.4.1 BONECONVERTSYNTAXboneconvert [-r | -m] [-x] [-t]EXPLANATIONThis command is used to update old hip Þles to use the new bones introduced inHoudini 5. The conversions performed are: All bones which have lock channels in their translate parameters matching:lock(0), lock(0), lock(-ch(strcat("../", strcat(opinput(".", 0), "/length"))))

are changed to:lock(0), lock(0), lock(0).The new bone objects have an output transform that places all child objects at theirend points. To force this conversion, use the -t option. TheTop CapandBottomparameters in the CRegion SOP of bone objects have theirmultiplication factor removed and multiplied into the values of the object-level cre-gion parameters. This will only be performed if the object-level cregion parametershave no channels. To deal with special cases, please see the options described below. All bone objects have their xray ßag turned on. Use the -x option to avoid doing thisconversion. Adds the command "boneÞxchops $OPSUBNAME" to the delete script.OPTIONSThe -r option forces the conversion of the CRegion SOP parameters even if theobject-level cregion parameters already have channels. This option is useful if youhave channel references in the object-level parameters that mirror other captureregions. The CRegion SOP parameters are forced to be correct without interpreta-tion of the parameter.The -m option not only forces the conversion of the CRegion SOP parameters like:-r, but it will also attempt to add the multiplication factor if the object-level parame-ters have channels on them. This option will not have different behaviour if theobject-level cregion parameters do not have channels. It will also fail to add the mul-tiplication factor if the cregion SOP parameters do not have an expression of theform <number>*<expression> .Channel and Operator Commands12 - Scripting21254.2 BONEFIXCHOPSSYNTAXbonefixchops [-r] bone_objectEXPLANATIONThis command is used to clean up InverseKin CHOPs that may reference the givenbone object before the bone is deleted. For example, if an InverseKin CHOP is usingan Inverse Kinematics solver on a bone chain from bone1 to bone4, and you execute"boneÞxchops bone4", this CHOP will be changed to apply its solver to the chainfrom bone1 to bone3. If you have an InverseKin CHOP that is using an Inverse Kin-ematics solver on bone1 only, and you execute "boneÞxchops bone1", the CHOPwill be deleted. This command is used in the default delete script of bone objects.If the -r option is used, then it will recursively destroy all outputs of the foundInverseKin CHOPs as well.4.3 BONEMOVEENDSYNTAXbonemoveend bone_object [-f "world"|"parent"] [-x xpos] [-y ypos][-z zpos]EXPLANATIONThis command adjusts the length and rest angles of the given bone object so that inthe rest chain the bone would end at the speciÞed position.4.4 BOOKMARKSYNTAXbookmark [-a path] [-l] [-r path_pattern]EXPLANATIONThis command is used to add, list and remove path bookmarks.OPTIONS-a pathAdd path to bookmarks.-r path_patternRemove path from bookmarks, wildcards such as *, ?and [ ] are valid.-lList current bookmarks.Channel and Operator Commands1262Houdini6.0Reference4.5 CHCPSYNTAXchcp source_channel_name destination_channel_nameEXPLANATIONCopies the contents of one channel to another. If the destination channel alreadyexists, its contents are deleted Þrst.EXAMPLESchcp /obj/logo/tx /obj/sky/tx_copyCopies the previously created tx channel of the logo object to be a spare channel ofskynamed tx_copy.chcp /obj/logo/tx /obj/logo/tyCopies the previously created tx channel of thelogoobject to the ty channel, over-writing any existing keyframe information of ty.chcp /obj/logo/tx /obj/skyCopies the previously created tx channel of thelogoobject to the sky object.

The new channel is named /obj/sky/tx.4.6 CHADDSYNTAXchadd [-f fstart fend] [-t tstart tend]objects name1[name2...][-f fstart fend]Represents the frame range you want to add the chan-nel to.[-t tstart tend]Represents the time range you want to add the channelto.objects nameRepresents name of the object you wish to add a chan-nel to.EXPLANATIONAdds channels to the speciÞed objects. You can specify objects using pattern match-ing i.e.geo*. By default, the channels have a segment stretching from the beginningto the end of the animation. Specifying a frame, or time, range causes the segment toadopt that range.EXAMPLEchaddgeo*tx ty tz spare1Channel and Operator Commands12 - Scripting2127Adds channels tx, ty, tz and spare1 to all objects matchinggeo*.4.7 CHGADDSYNTAXchgadd -f group_name [second_name...]EXPLANATIONThis command creates a new channel group (or groups). If thegroup_namespeci-Þed already exists,chgaddwill not add a new group. The-foption can forcechgaddto add a group. If there is already a group by that name, the new group is given aunique name.EXAMPLEchgadd bisonCreates the channel groupbison.4.8 CHCOMMITSYNTAXchcommit [-l] [channel_pattern...]EXPLANATIONSimulates adding a keyframe (i.e. clicking the redKeybutton in the Playbar). The-loption will not modify, but only list pending keyframe changes to the Textport. If nochannel_patternis speciÞed, all pending keyframes changes are assumed.4.9 CHGLSSYNTAXchgls [-l][-g] [pattern...]EXPLANATIONThis command lists channel groups.The-loption lists the contents of the channelgroup as well. The-goption generates commands which can be used to re-create thechannel group (or groups) speciÞed. If a pattern is speciÞed, then only the groupsmatching the pattern are listed.Channel and Operator Commands1282Houdini6.0ReferenceEXAMPLEchgls -lLists the contents of all available channel groups4.10 CHGOPSYNTAXchgop group_name operation channel_pattern [second_pattern...]EXPLANATIONThis command performs operations on groups of channels. It allows for the additionor removal of channels from a group.group_namedesignates the name of the chan-nel group to modify. Theoperationvariable permits three actions on the group:setSets the contents of the groupaddAdds channels to a groupremoveRemoves channels from a groupThechannel_paternvariable designates the list of channels to work on.EXAMPLEchgop group1 set /o*/g*/r?Sets the groups contents to the channels.chgop group1 add /o*/g*/t?Adds channels to group one.chgop group1 remove /o*/g*/txRemovestxchannels from group one.4.11 CHGRMSYNTAXchgrm group_patternEXPLANATIONThis command remove a channel group or groups.EXAMPLEchgrm bisonChannel and Operator Commands12 - Scripting2129Removes the channel groupbison.4.12 CHHOLDUSAGEchhold [-b | -e] [channel_patterns]Or: chhold [-s] [-l]Allows you to put channels into a hold (or pending) state at the current time. Thiscan be used in conjunction with the chcommit command to force the creation ofkeys.OPTIONS-b (begin)Turn on the hold status for the given channels so thatthey remain in a pending state even if time changes. Ifno patterns are given, then all currently scoped chan-nels will be affected.-e (end)Releases the previously held channels. If no patternsare given, then it will release all held channels.-s (status)Queries the current hold status.-l (list)Lists currently held channels.4.13 CHKEYSYNTAXchkey [-f frame] [-t time] [-v value] [-m slope] [-a accel] [-Ffunction] channel_patternEdit or insert a key frame by specifying the following:-vThe value at the key frame-mThe slope at the k