PM Macro Programming Guide
PM Macro Programming Guide
PM Macro Programming Guide
Creating macros
You can create macros by:
▪ Recording (see page 2) a sequence of commands within
PowerMill.
▪ Writing your own macro (see page 5) using a text editor.
Editing macros
You can edit recorded macros to troubleshoot and correct any
errors.
1 Expand Macros and select the macro you want to edit.
Basic macro
This shows you how to create and run a basic macro using
PowerMill's programming language.
1 In a text editor such as WordPad enter:
PRINT "10 green bottles sitting on the wall"
PRINT "10 green bottles sitting on the wall"
PRINT "And if 1 green bottle should accidentally fall"
PRINT "There will be 9 green bottles sitting on the
wall"
2 Save the file as example.mac.
3 In PowerMill, click View tab > Window panel > User Interface >
Command Window.
▪ When you have defined a local variable you can use it as many
times as you want in a macro.
▪ You can define as many local variables as you want in a macro.
The empty lines are not necessary, but they make it easier
to read the macro.
2 Save the file as example.mac.
3 In PowerMill, Run the Macro. The command windows displays:
DO - WHILE loop
1 Edit the PrintBottles function in example.mac to:
FUNCTION PrintBottles(INT Count) {
IF statement
You can use an IF statement to ensure the 10 green bottles sitting on
the wall line is printed at least twice.
1 Edit the Main function in example.mac to:
FUNCTION Main (INT Count) {
Each code block or function can define its own set of local
variables; the scope of the variable is from its declaration
to the end of the enclosing block or function.
4 Add the NumberStr function into example.mac.
FUNCTION PrintBottles(INT Count, INT Number) {
This gives exactly the same output as the Returning values from
macros (see page 18) example. It shows you an alternative way of
creating the same output.
This gives exactly the same output as the Returning values from
macros (see page 18) example. It shows you an alternative way
of creating the same output.
Variables in macros
You can create variables in macros just as you can in a PowerMill
project. When you create a variable in a macro, it has the same
properties as a PowerMill parameter, and can store either a value or
an expression.
This command returns the name of the tool the user selected.
This example creates two folders, creates two tool in each folder,
then asks the user to select one of the tools:
// Create some tools in folders
CREATE FOLDER 'Tool' 'Endmills'
CREATE IN 'Tool\Endmills' TOOL 'End 20' ENDMILL
EDIT TOOL ; DIAMETER 20
CREATE IN 'Tool\Endmills' TOOL 'End 10' ENDMILL
EDIT TOOL ; DIAMETER 10
CREATE FOLDER 'Tool' 'Balls'
CREATE IN 'Tool\Balls' TOOL 'Ball 12' BALLNOSED
EDIT TOOL ; DIAMETER 12
CREATE IN 'Tool\Balls' TOOL 'Ball 10' BALLNOSED
EDIT TOOL ; DIAMETER 10
// Prompt user to pick one
STRING ToolName = ''
$ToolName = INPUT ENTITY TOOL "Please select a Tool."
You can also ask for the selection of a number of entities. The result
is the list of entities selected, which can be assigned to either a list
of strings, or list of entities.
ENTITY LIST $Selected_Toolpaths = INPUT ENTITY MULTIPLE
toolpath "which toolpaths do you want to check?"
STRING LIST ToolpathNames = INPUT ENTITY MULTIPLE
TOOLPATH "Select toolpaths to check"
You can then iterate over the user selection with a FOREACH loop:
FOREACH $tp in ToolpathNames {
ACTIVATE TOOLPATH $tp.Name
EDIT COLLISION APPLY
}
Lists
PowerMill also has a LIST type. The main difference between a list
and an array is that the list does not have a fixed size, so you can
add and remove items to it. You can create lists:
▪ that are empty to start with
▪ from an initialisation list
Using lists
A list, like an array, contains multiple values. You can create a list
with initial values:
FUNCTION Main() {
INT LIST MyList = {10,20,30,40}
CALL PrintArray(MyList)
}
You can access the elements of a list with a FOREACH loop, or you
can use the array subscripting notation:
INT Val = MyList[2]
FOREACH tp IN folder('Toolpath\MyFolder') {
INT Size = add_last(TpNames, tp.name)
}
Building a list
You can use the inbuilt member() function in a macro function to
build a list of tool names used by toolpaths or boundaries without
any duplicates:
FUNCTION ToolNames(STRING FolderName, OUTPUT STRING LIST
ToolNames) {
Subtract function
You can use the subtract() function to determine what happened
after carrying out a PowerMill command. For example, suppose you
to find out if any new toolpaths are created during a toolpath
verification. If you get the list of toolpath names before the
operation, and the list of names after the operation, and then
subtract the ‘before’ names from the ‘after’ names you are left with
the names of any new toolpaths.
FUNCTION GetNames(STRING FolderName, OUTPUT STRING LIST
Names) {
FOREACH item IN folder(FolderName) {
INT n = add_last(Names, item.Name)
}
}
FUNCTION Main() {
IF is_empty(NewNames) {
PRINT "No new toolpaths were created."
} ELSE {
PRINT "The new toolpaths created are:"
FOREACH item IN NewNames {
PRINT = item
Entity variables
PowerMill has a special variable type ENTITY. You can use ENTITY
variables to refer to existing PowerMill entities such as toolpaths,
tools, boundaries, patterns, workplanes, and so on. You cannot use
this command to create new entities.
For example:
// create an entity variable that references boundary
entity 'Duck'
ENTITY Daffy = entity('boundary','Duck')
The inbuilt functions, such as folder() return lists of entities so
you can store the result of the call in your own list and array
variables:
For example:
ENTITY List Toolpaths = folder('toolpath')
When looping over folder items in a FOREACH the loop variable that
is automatically created has the type ENTITY. Therefore the
following code is syntactically correct:
FOREACH tp IN folder('toolpath') {
ENTITY CurrentTP = tp
PRINT = CurrentTP.Name
}
You can also pass ENTITY variables to functions (and passed back
from function) by using an OUTPUT argument:
For example:
FUNCTION Test(OUTPUT ENTITY Ent) {
$Ent = entity('toolpath','2')
}
FUNCTION Main() {
ENTITY TP = entity('toolpath','1')
CALL Test(TP)
PRINT = TP.Name
}
Additionally, you can use an ENTITY variable anywhere in PowerMill
that is expecting an entity name.
For example:
ENTITY tp = entity('toolpath','1')
ACTIVATE TOOLPATH $tp
Comparing variables
Comparing variables enables you to check information and defines
the course of action to take when using IF (see page 53) statements
and WHILE (see page 62) statements.
The result of a comparison is either true or false. When true the
result is 1, when false the result is 0.
A simple comparison may consist of two variables with a relational
operator between them:
Relational operator Description
Symbol Text
== EQ is equal to
!= NE is not equal to
< LT is less than
Scope of variables
A variable exists from the time it is declared until the end of the
block of code within which it is declared. Blocks of code are macros
and control structures (WHILE, DO - WHILE, SWITCH, IF-ELSEIF-
ELSE, and FOREACH).
A variable, with a specific name, can only be defined once within
any block of code.
For example,
// Define a local variable 'Count'
INT Count = 5
// Define a second local variable 'Count'
INT Count = 2
Gives an error since Count is defined twice.
However, within an inner block of code you can define another
variable with the same name as a variable (already defined) in an
outer block:
INT Count = 5
IF Count > 0 {
// Define a new local variable 'Count'
INT Count = 3
// Print 3
PRINT $Count
// The local Count is no longer defined
}
// Print 5
PRINT $Count
A variable defined within an inner block of code hides any variable
declared in an outer block. This is also important if you use a name
for a variable which matches one of PowerMill’s parameters. For
example, if the toolpath stepover is 5 and in your macro you have:
// 'Hide' the global stepover by creating your own
variable
// Assignments
$Stepover = Tool.Diameter * factor
$factor = 0.75
Operator precedence
The order in which various parts of an expression are evaluated
affects the result. The operator precedence unambiguously
determines the order in which sub-expressions are evaluated.
▪ Multiplication and division are performed before addition and
subtraction.
For example, 3 * 4 +2 is the same as 2 + 3 * 4 and gives the
answer 14.
▪ Exponents and roots are performed before multiplication and
addition.
For example, 3 + 5 ^ 2 is the same as 3 + 5 and gives the
answer 28.
-3 ^ 2 is the same as -3 and gives the answer -9.
▪ Use brackets (parentheses) to avoid confusion.
For example, 2 + 3 * 4 is the same as 2 + (3 * 4) and gives the
answer 14.
▪ Parentheses change the order of precedence as terms inside in
parentheses are performed first.
For example, (2 + 3) * 4 gives the answer 20.
or, (3 + 5) ^2 is the same as (3 + 5) and gives the answer 64.
▪ You must surround the arguments of a function with
parentheses.
For example, y = sqrt(2), y = tan(x), y = sin(x + z).
▪ Relational operators are performed after addition and
subtraction.
For example, a+b >= c+d is the same as (a+b) >= (c+d).
▪ Logical operators are performed after relational operators,
though parentheses are often added for clarity.
For example:
5 == 2+3 OR 10 <= 3*3
is the same as:
Precedence
Order Operation Description
1 () function call, operations
grouped in parentheses
2 [] operations grouped in square
brackets
3 +-! unary prefix (unary operations
have only one operand, such
as, !x, -y)
4 cm mm um ft unit conversion
in th
5 ^ exponents and roots
6 */% multiplication, division, modulo
7 +- addition and subtraction
8 < <= > >= relational comparisons: less
(LT, LE, GT, than, less than or equal,
GE) greater than, greater than or
equal
9 == != (EQ, relational comparisons: equals,
NE) not equals
10 AND logical operator AND
11 NOT logical operator NOT
12 XOR logical operator XOR
13 OR logical operator OR
14 , separation of elements in a list
Examples of precedence:
Expression Equivalent
a*-2 a * (- 2)
!x == 0 (!x) == 0
$a = -b + c * d – e $a = ((-b) + (c * d)) – e
$a = b + c % d – e $a = (b + (c % d)) – e
$x = y == z $x = (y == z)
Main function
If a macro has any functions:
▪ It must have one, and only one, FUNCTION called Main.
▪ The Main function must be the first function called.
Function names are not case sensitive: MAIN, main, and MaIn all
refer to the same function.
Running a macro where the Main function is called with either the
wrong number of arguments or with types of arguments that do not
match, causes an error. For example:
MACRO MyTool.mac 6 "ToolName"
generates an error since the macro expects a string and then a
number, but is given a number and then a string.
If you want to repeat a sequence of commands at different points
within a macro, you can use a FUNCTION.
For example, if you want to remove any small islands that are
smaller than the tool diameter and smooth out any minor kinks
after a boundary calculation. One solution is to repeat the same
commands after each boundary calculation:
EDIT BOUNDARY ; SELECT AREA LT Boundary.Tool.Diameter
DELETE BOUNDARY ; SELECTED
EDIT BOUNDARY ; OFFSET "1 mm"
EDIT BOUNDARY ; OFFSET "-1 mm"
This is fine if you have a macro that creates one boundary, but if it
creates a number of boundaries you end up with a macro with
excessive repetition. However by using a FUNCTION you can define
the sequence once:
FUNCTION CleanBoundary(string name) {
REAL offset = 1 mm
REAL diam = entity('boundary';name).Tool.Diameter
INCLUDE common.inc
FUNCTION Main(input string bound) {
FOREACH bou IN folder(bound) {
CALL CleanBoundary(bou.Name)
}
}
To call this macro from PowerMill:
IF statement
The IF statement executes a series of commands when a certain
condition is met.
The basic control structure is:
IF <expression> {
Commands A
}
Commands B
The first brace must be the last item on the line and on the
same line as the IF.
The closing brace must be on a line by itself.
IF - ELSE statement
The IF - ELSE statement executes a series of commands when a
certain condition is met and a different series of commands
otherwise.
The basic control structure is:
IF <expression> {
Commands A
SWITCH statement
When you compare a variable with a number of possible values and
each value determines a different outcome, it is advisable to use the
SWITCH statement.
For example,
FOREACH item IN folder("path") {
Commands A
}
Commands B
Where <path> is a folder in the Explorer such as, Toolpath, Tool,
Toolpath\Finishing.
Within FOREACH loops, you can:
▪ Cancel the loop using the BREAK (see page 64) statement.
▪ Jump directly to the next iteration using the CONTINUE (see page
64) statement.
WHILE loop
A WHILE loop repeatedly executes a block of commands until its
conditional test is false.
The basic control structure is:
WHILE condition {
Commands A
}
Commands B
If condition is true, then Commands A are executed.
While condition remains true, then Commands A are executed.
DO - WHILE loop
The DO - WHILE loop executes a block of commands and then
performs its conditional test, whereas the WHILE loop checks its
conditional test first to decide whether to execute its commands or
not.
The basic control structure is:
DO {
Commands A
} WHILE condition
Commands B
Commands A are executed.
While condition remains true, then Commands A are executed.
When condition is false, Commands B are executed.
Creating sequences
Use the make_sequence and next_in_sequence functions to create
sequences. Sequences contain:
RETURN statement
If a macro contains functions, the RETURN statement immediately
exits the function. If the macro does not contain functions, the
RETURN statement immediately terminates the current macro. This
is useful if an error is detected and you do not want to continue with
the remaining commands in the macro.
The basic control structure is:
EDIT TOOLPATH $tp.Name CALCULATE
IF NOT Computed {
// terminate if toolpath did not calculate
RETURN
}
To immediately exit from a function:
IF NOT active(entity('toolpath',TpName).Tool.TipRadius)
{
// Error if toolpath does not use a tipradius tool
PRINT "Toolpath does not have TipRadius tool"
RETURN
}
FUNCTION Main() {
FOREACH tp IN folder('Toolpath') {
ACTIVATE TOOLPATH $tp.Name)
}
}
Terminating macros
The command MACRO ABORT immediately terminates the current
macro.
The command MACRO ABORT ALL terminates the all the macros that
are currently running. If you call MACRO ABORT ALL from within a
macro that has been called by another macro, then both macros are
terminated.
Built-in functions
This section details all the built-in functions that you can use in your
macros.
▪ General mathematical functions (see page 67).
▪ Trigonometrical functions (see page 68).
▪ Vector and point functions (see page 68).
▪ Workplane functions (see page 71).
▪ String functions (see page 71).
▪ List creation functions (see page 81).
▪ Path functions (see page 91) (Folder (see page 92), Directory
(see page 92), Base (see page 93), and Project (see page 93)
names).
▪ Conditional functions (see page 95).
▪ Evaluation functions (see page 95).
▪ Type conversion functions (see page 97).
▪ Parameter functions (see page 97).
▪ Statistical functions (see page 100).
Trigonometrical functions
The basic structure of the trigonometrical functions are:
Description of return value Function
Trigonometric sine real sin( angle )
Trigonometric cosine real cos( angle )
Trigonometric tangent real tan( angle )
Trigonometric arcsine real asin( real a )
Trigonometric arccosine real acos( real a )
Trigonometric arctangent real atan( real a )
Trigonometric arctangent of real atan2( real a, real
a/b, quadrant is determined b )
by the sign of the two
arguments
Length
The length() function returns the length of a vector.
For example:
REAL ARRAY V[] = {3,4,0}
// Prints 5.0
PRINT = length(V)
The inbuilt function unit() returns a vector that points in the same
direction as the input vector, but has a length of 1:
PRINT PAR "unit(V)"
// [0] (REAL) 0.6
// [1] (REAL) 0.8
// [2] (REAL) 0.0
// prints 1.0
PRINT = length(unit(V))
Parallel
The parallel() function returns TRUE if two vectors are either
parallel (pointing in the same direction) or anti-parallel (pointing in
the opposite direction) to each other.
For example:
// prints 0
PRINT = parallel(VecX,Vecy)
// prints 1
PRINT = parallel(VecX,VecX)
Print = parallel(MVecZ,VecZ)
Normal
The normal() function returns a vector that is normal to the plane
containing its two input vectors. If either vector is zero it returns an
error. If the input vectors are either parallel or anti-parallel a vector
of zero length is returned.
For example:
REAL ARRAY norm = normal(VecX,VecY)
Setting
The set_vector() and set_point() functions return the value 1 if
the vector or point is set.
For example:
REAL ARRAY Vec1[3] = {0,0,1}
REAL ARRAY Vec2[3] = {0,1,0}
REAL X = Block.Limits.XMax
REAL Y = Block.Limits.YMin
REAL Z = Block.Limits.ZMax
ok = set_point(ToolAxis.Origin, X,Y,Z)
Unit vector
The unit() function returns the unit vector equivalent of the given
vector.
For example:
REAL ARRAY V[3] = {3,4,5}
PRINT PAR "unit(V)"
BOOL ok = set_vector(V,0,0,6)
PRINT PAR "unit(V)"
String functions
PowerMill parameters and variables can contain strings of
characters. There are a number of inbuilt functions that you can use
to test and manipulate strings.
The basic structure of string functions are:
Description of return value Function
Returns the number of int length( string str )
characters in the string.
For more information see
Length function in a string
(see page 76).
Returns the position of the int position( string str,
string target from the start of string target[, numeric
the string str, or -1 if the start] )
target string is not found.
If you use the optional
argument start then scanning
begins from that position in
the string.
For more information see
Position function in a string
(see page 76).
Example
The following example shows how to use the time() function to
measure how long an activity takes:
INT old_time = time()
EDIT TOOLPATH ; CALCULATE
INT cumulative_time = time() - old_time
STRING msg = "Toolpath calculation took " +
(cumulative_time) + "secs"
MESSAGE INFO $msg
Example
Getting and formatting the current time:
INT tm=time()
STRING ARRAY $timestamp[] =
tokens(utc_time($tm).timestamp, "-") STRING clock =
$timestamp[3] + ":" + $timestamp[4] $clock = $clock + ":"
+ $timestamp[5] PRINT $clock
Another example:
STRING One = "One"
STRING Two = "Two"
STRING CountToTwo = One + ", " + Two
PRINT = length(CountToTwo)
The command window displays the result, 8.
Substrings
The substring function returns part of the string. You can define
where the substring starts and its length. The original string is
unchanged.
The basic structure is:
string substring( string str, int start, int length)
For example:
PRINT = substring("Scooby doo", 2, 4)
The command window displays the result, ooby.
Previously Draft_ConstZ was not renamed, but it is this time. All the
toolpath names are now upper case.
Whitespace in a string
Use the following functions to remove whitespace from a string:
▪ ltrim()— Removes leading whitespace.
▪ rtrim() — Removes trailing whitespace.
▪ trim() — Removes leading and trailing whitespace.
List functions
List functions control the content of a list or array.
The basic structure of list functions are:
Description Function
Returns the components (see list components( entity
page 82) of another object. entity )
Returns a list of specified size list fill (int size, object
containing elements with value )
specified value.
Returns a list of all the list folder( string folder
entities in the folder (see page )
83).
Determines if the list has any is_empty()
content (see page 84).
Determines if the list contains member()
a specific value (see page 84).
Adding (see page 85) a list or +
array to another list or array
Removes duplicate (see page remove_duplicates()
85) items from a list.
List components
The inbuilt components function returns the components of another
object.
List fill
The fill() function returns a list of a specified size, which contains
elements of a specified value.
The basic structure is:
list fill(int size, object value)
For example, if you wanted to create a list in which abc was
repeated three times:
STRING ARRAY str_arr[] = fill(3, "abc")
// str_arr = {"abc", "abc", "abc"}
If you wanted to create a list in which 5 was repeated five times:
INT LIST int_ls = fill(5, 5)
// int_ls = {5, 5, 5, 5, 5}
List folder
The folder() function returns a list of all entities within a folder,
including those in subfolders.
The basic structure is:
list folder( string folder )
The names of the root folders are:
▪ MachineTool
▪ NCProgram
▪ Toolpath
▪ Tool
The name of the folder is case sensitive, so you must use Tool
and not tool.
You can use a FOREACH loop to process all of the entities within a
folder. For example, to batch process tool holder profiles:
FOREACH tool IN folder ('Tool'){
EDIT TOOL $tool.Name UPDATE_TOOLPATHS_PROFILE
}
An example, to batch process all the boundaries in your project:
FOREACH bou IN folder('Boundary') {
EDIT BOUNDARY $bou.Name CALCULATE
}
Empty list
The is_empty() function queries a list to determine whether it is
empty or not.
REAL LIST MyList = {}
IF is_empty(MyList) {
PRINT "Empty List"
}
List member
The member() function returns TRUE if the given value is one of the
items in the list. For example, to check that a toolpath does not
occur in more than one NC program, you can loop over all
NCProgram and check that each toolpath is only seen once. Do this
by building a list of toolpath names and checking that each time you
add a name you have not already seen it.
// Create an empty list
STRING List names = {}
// Cycle through the NC programs
FOREACH ncp IN folder('NCProgram') {
// loop over the components in the nc program
FOREACH item IN components(ncp) {
Adding lists
The + function adds a list or array to another list or array. For
example, you can add two lists together to get a list of all the tools
used by the toolpaths and boundaries:
STRING LIST UsedToolNames = ToolpathTools + BoundaryTools
The FOREACH loop adds each item to the start of the list. As the
add_first command adds the next pattern to the start of the list.
So you end up with a list
{"Pattern_3","Pattern_2,"Pattern_1"}.
The WHILE loop takes the first item in the list, removes it from the
list and pints it. This gives:
Pattern_3
Pattern_2
Pattern_1
The FOREACH loop adds each item to the end of the list. As the
add_last command adds the next pattern to the end of the list. So
you end up with a list {"Pattern_1","Pattern_2,"Pattern_3"}.
The WHILE loop takes the last item in the list, removes it from the
list and pints it. This gives:
Pattern_3
Pattern_2
Pattern_1
To end up with the patterns in the same order as they are in the
Explorer either:
▪ In the FOREACH loop use the add_last command and in the
WHILE loop use the remove_first command; or
▪ In the FOREACH loop use the add_first command and in the
WHILE loop use the remove_last command.
Sorted list
The sort function sorts lists and arrays of scalars (numerics or
strings) or objects and entities. By default, the functions sort a list
in ascending order. If you want to sort the list in descending order,
you can apply the reverse function to the list.
If you are sorting a list of objects and entities, you must provide a
field name for the sort.
The following examples sort lists of scalar values (numerics and
strings):
STRING LIST l1 = {"The","Twelth","Night"}
$l1 = sort(l1)
// returns the list {"Night", "The", "Twelth"}
REAL ARRAY a1 = {23, 12, 4, 52, 32}
$a1 = sort(a1)
// Returns the list {4, 12, 23, 32, 52}
When sorting non-scalar values, such as entities or objects, you
must provide a sort field that is a scalar value:
CREATE TOOL ; BALLNOSED
EDIT TOOL ; DIAMETER 2.0
CREATE TOOLPATH 'bbb' RASTER
CREATE TOOL ; BALLNOSED
EDIT TOOL ; DIAMETER 1.0
CREATE TOOLPATH 'ccc' RASTER
CREATE TOOL ; BALLNOSED
EDIT TOOL ; DIAMETER 1.5
CREATE TOOLPATH 'aaa' RASTER
For example:
ENTITY LIST ents = sort(folder('toolpath'),'name')
// Returns the list of toolpath {'aaa','bbb','ccc'}
Path functions
The path functions returns part of the pathname of the entity,
The basic structure of the path functions are:
Description of return value Function
The Folder name (see page string pathname( entity
92) function returns the full ref )
folder name of the entity, or
an empty string if the entity
does not exist.
The Folder name (see page string pathname( string
92) function can also be used type, string name)
to return the full folder name
of the entity.
The Directory name (see page string dirname( string
92) function returns the path)
directory prefix from the path.
The Base name (see page 93) string basename( string
function returns the non- path)
directory suffix from the path.
The Project name (see page project_pathname(bool
93) functions returns the basename)
pathname of the current
project on disk.
The Active folder (see page String active_folder()
94) functions returns folder
names of active entities.
The Folder list (see page 94) String
functions returns the names folder_list(folder_name)
of folders in the PowerMill
project.
Directory name
The directory name function returns the directory prefix from the
path.
The basic structure is:
string dirname( string path)
For example you can use this to obtain the argument for the inbuilt
folder() function.
STRING folder = dirname(pathname('toolpath',Name))
Project name
The project pathname function returns the pathname of the current
project on disk.
The basic structure is:
project_pathname(bool basename)
The argument dirname_only gives a different result if it is true to if
it is false.
Conditional functions
The basic structure of conditional functions are:
Description of return value Function
Returns the value of variant select(
expression 1 if the conditional conditional-expression;
expression is true, otherwise expression1;expression2)
it returns the value of
expression 2.
Evaluation functions
The evaluation function evaluate a string argument as an
expression.
For example:
print = evaluate("5*5")
prints 25.
FUNCTION Main() {
/Set up some data
REAL ARRAY Data[] = {9,10,3,4,1,7,2,8,5,6}
// Sort in increasing value
CALL SortReals("List[Idx] > List[Idx+1]", Data)
PRINT PAR "Data"
REAL ARRAY Data1[] = {9,10,3,4,1,7,2,8,5,6}
// Sort in decreasing order
CALL SortReals("List[Idx] < List[Idx+1]", Data1)
PRINT PAR "Data1"
}
Enumerator parameter
The values() function returns a list of display names for an
enumerator parameter, such as Tool.Type, CutDirection, or
Strategy. The names are translated into the current language that a
user is working in. This list can be used to gather input from the
user with the CHOICE dialog. For example, to ask the user which
cut direction they would like to use, you can use the following code:
// Get names for the choices the user can make for this
parameter
STRING ARRAY Opts[] = values(CutDirection)
Parent parameter
The parent() function enables you to access and specify machine tool
parameters in a more user friendly way. For example:
//To change the opacity of a machine tool/Robot table
with AXIS ADDRESS T, the following syntax can be used
EDIT PAR "parent(machine_axis('T')).ModelList.Opacity"
"25"
//Check the way the 'parent' function works...
CREATE TOOL ; BALLNOSED
EDIT TOOL "1" DIAMETER "20"
real error = 0
$error = ERROR parent(Tool)
print $error
//returns 1.0 as it fails finding the parent of a root -
'TOOL' is the root
$error = ERROR parent(Tool.Diameter)
print $error
//returns 0 as it finds the parent Tool of Tool.Diameter
Statistical functions
The statistical functions enable you to return the minimum and
maximum values of any number of numeric arguments.
The basic structure of the statistical functions are:
Description of return value Function
Returns the largest value in a real max( list numeric a
list of numbers. )
Returns the smallest value in real min( list numeric a
a list of numbers. )
This example finds the maximum and minimum block height of the
toolpaths in the active NC program.
REAL maxz = -100000
REAM minz = abs(maxz)
FOREACH item IN components(entity('ncprogram','')) {
IF item.RootType == 'nctoolpath' {
$maxz = max(maxz,entity('toolpath',item.Name))
$minz - min(minz,entity('toolpath',item.Name))
}
}
MESSAGE "Min = " + string(minz) + ", max = " +
string(maxz)
Equivalence
You can use the inbuilt function geometry_equal() to test whether
two tools, or two workplanes are geometrically equivalent. For a
tool the test is based on the cutting geometry of the tool.
Number of segments
The inbuilt function segments() returns the number of segments in
a pattern or boundary:
IF segments(Pattern) == 0 {
PRINT "The pattern is empty"
}
To return the number of segments in a toolpath, use:
function toolpath_component_count(toolpath,type)
For example:
print par ${toolpath_component_count('toolpath', '1',
'links')}
print par ${toolpath_component_count('toolpath', '1',
'leads')}
print par ${toolpath_component_count('toolpath', '1',
'segments')}
Limits
The inbuilt function limits() returns an array of six elements
containing the XYZ limits of the given entity. The supported entities
are: pattern, boundary, toolpath, feature set, or model.
REAL ARRAY Lims[] = limits('model','MyModel')
The values in the array are:
REAL MinX = Lims[0]
REAL MaxX = Lims[1]
REAL MinY = Lims[2]
REAL MaxY = Lims[3]
REAL MinZ = Lims[4]
REAL MaxZ = Lims[5]
IF NOT entity_exists(entity('toolpath','')) {
PRINT "Please activate a toolpath and try again."
MACRO ABORT ALL
}
// Prints 4
PRINT = new_entity_name('workplane')
DELETE WORKPLANE 2
// Prints 2
PRINT = new_entity_name('workplane')
// Prints 2_1
PRINT = new_entity_name('workplane', '2')
Function Main(
STRING $Selected_Toolpath
)
{
// Create new project parameter to store the holder
clearance
BOOL $chk = 0
$chk = ERROR $project.clearance
Enter line and line without line breaks. The lines appear to
include line breaks here only because of the limited page width.
Model hierarchy
Model Component Functions
INT select_components(DATA components)
INT deselect_components(DATA components)
These functions select or deselect all of the components in the
passed-in data parameter. The data parameter must store a
ModelCompList or ModelCompSet. The return value is numeric, but
carries no information.
INT number_selected(DATA components)
Model Hierarchies
Some CAD systems store models in a hierarchical structure. When
PowerMILL reads these CAD files it creates a parameterised
representation of this structure. This structure can be navigated as
a tree, and there are two helper functions, one to retrieve a node
from the hierarchy by its path, and the other to retrieve the
hierarchy (or a subsection of the hierarchy) as a list that can be
filtered or iterated over.
Nodes
The hierarchy of a model is made up of nodes. These are maps with
typename "ModelHierarchyElement". They have the following
properties:
Property Type Description
Name STRING The name associated with the node
in the hierarchy. The root node’s
name will be the same as the
model’s name.
Path STRING The path to the node. It consists of
the names of the node’s ancestors,
starting with the root node,
separated by backslashes. It
includes the node’s name.
Parent MAP The parent of this node in the
(typename: hierarchy. The root node’s Parent is
ModelHierarchyElemen always an error. For all other
t) nodes, it will be a map of this type.
Children ARRAY of MAPs A list of the children of the node in
(typename: the hierarchy. Each child node is a
ModelHierarchyElemen map of this type.
t)
Compone DATA A list of the model components
nts {ModelCompList} associated with the node.
Parameter MAP Key-Value pairs associated with the
s (typename: node.
ModelMetadata)
SelectedIn BOOL This parameter is not currently
Model metadata
Exchange can extract the metadata from 3rd party CAD files and
communicate them to PowerMill during the translation process.
Metadata is accessible through parameters which are associated
with groups, workplanes and geometries. These are used to store
information relevant to the machining of an item.
Metadata on geometry
The components() parameter function is extended to include a data
parameter which stores a list of model components, including
surfaces, and returns a list of the components in a parameterised
form.
The parameterized components are objects with the following
properties:
Metadata on workplanes
There are parameters to represent workplanes in the hierarchy.
These are maps with the following properties:
Name — The name of the workplane.
Origin — The origin of the workplane. This is an array of 3 REALs.
XAxis — The X axis of the workplane. This is an array of 3 REALs.
YAxis — The Y axis of the workplane. This is an array of 3 REALs.
ZAxis — The Z axis of the workplane. This is an array of 3 REALs.
Parameters — A map of the metadata associated with the
workplane.
If a workplane in an imported model has the same name as an
existing workplane in PowerMill but a different origin or orientation,
the parameter will store the original name.
Feature Parameters
You can use the inbuilt components() function to loop over the
features within a feature set. Each feature has the following
parameters:
Name — Name of Feature.
ID — Id of Feature.
RootType — 'feature' as a string.
num_items — Number of sub-holes.
Type — Type of feature (pocket, slot, hole, boss).
Top — Top of feature, z-value relative to Origin.
Bottom — Bottom of feature, z-value relative to Origin.
Depth — Depth of feature, from top to bottom.
Diameter — Diameter of feature.
Draft — Draft angle.
Example
// get a list of all the files in the working directory
STRING LIST files = list_files("files",pwd())
How do I only loop over the items in a parent folder (and exclude any
subfolders)?
As described above, the folder() function returns items from a
parent folder and any subfolders. If you only want to loop over the
items in the parent folder, you need to filter the results. For
example, if you have the folder 'Semi-finishing' and the subfolder
'Not used', which contains temporary or alternative toolpaths, then
to access the toolpaths only in the 'Semi-finishing' folder, you need
to use the pathname and dirname functions:
STRING fld = ‘Toolpath\semi-finishing’
Note the use of ‘this’ in the $filt expression: when used in the
filter function, ‘this’ is an alias for the current list item that is
being filtered. In cases where you need to explicitly use the
list item, such as the one above, you should refer to it as
‘this’ in the expression.
The period (.) indicates the path to the local folder (currently, the
folder to which the project is saved). The tilde ( ) indicates your
Home directory.
2 To create a macro path, click , and use the Select Path dialog
to select the desired location. The path is added to the top of the
list.
3 To change the path order, select the path you want to move, and
use the and buttons to promote or demote the path.
4 Click Close.
7 Close and then restart PowerMill to check that the settings from
the pmuser macro are activated.
License
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS
OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR
"LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR
OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS
PROHIBITED.
BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU
ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS
LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO
BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF
SUCH TERMS AND CONDITIONS.
Can I use content from Autodesk online help to create new materials for
a specific audience?
Yes, if you want to help a specific audience learn how to optimize
the use of their Autodesk software, there is no need to start from
scratch. You can use, remix, or enrich the relevant help content and
include it in your book, instructions, examples, or workflows you
create, then Share-Alike with the community. Always be sure to
comply with the terms of the Creative Commons license under
which the learning content is released.
Trademarks
The following are registered trademarks or trademarks of Autodesk,
Inc., and/or its subsidiaries and/or affiliates in the USA and other
countries: 123D, 3ds Max, ADSK, Alias, ArtCAM, ATC, AutoCAD LT,
AutoCAD, Autodesk, the Autodesk logo, Autodesk 123D, Autodesk
Alias, Autodesk Forge, Autodesk Fusion, Autodesk Inventor,
AutoSnap, BIM 360, Buzzsaw, CADmep, CAMduct, Civil 3D,
Configurator 360, Dancing Baby (image), DWF, DWG, DWG
(design/logo), DWG Extreme, DWG TrueConvert, DWG TrueView,
DWGX, DXF, Eagle, ESTmep, FBX, FeatureCAM, Flame, FormIt 360,
Fusion 360, The Future of Making Things, Glue, Green Building
Studio, InfraWorks, Instructables, Instructables (stylized robot
design/logo), Inventor, Inventor HSM, Inventor LT, Make Anything,
Maya, Maya LT, Moldflow, MotionBuilder, Mudbox, Navisworks,
Netfabb, Opticore, PartMaker, Pier 9, PowerInspect, PowerMill,
PowerShape, Publisher 360, RasterDWG, RealDWG, ReCap, ReCap
360, Remake, Revit LT, Revit, Scaleform, Shotgun, Showcase,
Showcase 360, SketchBook, Softimage, Tinkercad, TrustedDWG,
VRED.
All other brand names, product names or trademarks belong to their
respective holders.
Disclaimer
THIS PUBLICATION AND THE INFORMATION CONTAINED HEREIN IS
MADE AVAILABLE BY AUTODESK, INC. "AS IS." AUTODESK, INC.
DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
REGARDING THESE MATERIALS.
A C
Active folder name • 94 Calling from other macros • 4
Adding items to a list • 34, 86 Carriage returns in dialogs • 29
Adding lists • 85 Comparing variables • 40, 42
Adding macro loops • 10 Components
Adding macro variables • 9 List components • 82
Arguments in macros • 50 Compound macros • 4
Function values • 52 Conditrional functions • 95
Running macros with arguments • 11 Constants • 67
Sharing functions • 53 Euler's number • 67
Arrays • 32 Pi • 67
Lists • 32 Converting numerics to strings • 75
Points • 40 Creating macros • 1
Using arrays • 24 Basic macro • 8
Vectors • 40 Creating variables (macros) • 26
Automate a sequence of edits or actions
• 100
D
Date and time functions • 73
B Decision making in macros • 13
Base name • 93 Decisions in macros
Basic macro • 8 BREAK statement • 59, 64
Adding macro loops • 10 IF - ELSE statement • 54
Adding macro variables • 9 IF - ELSEIF - ELSE statement • 55
Decision making in macros • 13 IF command • 53
Returning values from macros • 18 SWITCH statement • 56
Running macros with arguments • 11 Decrease options available to user • 30
Using a FOREACH loop • 21 Delete files or directories • See Working
Using arrays • 24 with files and directories
Using functions in macros • 15 Dialogs in macros • 27
BREAK statement • 59, 64 Carriage returns in dialogs • 29
Building a list • 36 Directory name • 92
Built-in functions • 67 DO - WHILE loop • 63
Decision making in macros • 13
W
Warning and error messages, turn off •
118
WHILE loop • 62
Whitespace in a string • 80
Working with files and directories • 110
Workplane origin • 71
Writing information to files • 111
Writing macros • 5