3.2.2 Language Directives

The POV Scene Language contains several statements called language directives which tell the file parser how to do its job. These directives can appear in almost any place in the scene file - even in the middle of some other statements. They are used to include other text files in the stream of commands, to declare identifiers, to define macros, conditional, or looped parsing and to control other important aspects of scene file processing.

Each directive begins with the hash character # (often called a number sign or pound sign). It is followed by a keyword and optionally other parameters.

In versions of POV-Ray prior to 3.0, the use of this # character was optional. Language directives could only be used between objects, camera or light_source statements and could not appear within those statements. The exception was the #include which could appear anywhere. Now that all language directives can be used almost anywhere, the # character is mandatory. The following keywords introduce language directives.

#break
#case
#debug
#declare
#default
#else
#end
#error
#fclose
#fopen
#if
#ifdef
#ifndef
#include
#local
#macro
#range
#read
#render
#statistics
#switch
#undef
#version
#warning
#while
#write

Earlier versions of POV-Ray considered the keyword #max_intersections and the keyword #max_trace_level to be language directives but they have been moved to the global_settings statement and should be placed there without the # sign. Their use as a directive still works but it generates a warning and may be discontinued in the future.

3.2.2.1 Include Files and the #include Directive

The language allows include files to be specified by placing the line

 #include "filename.inc"

at any point in the input file. The filename may be specified by any valid string expression but it usually is a literal string enclosed in double quotes. It may be up to 40 characters long (or your computer's limit), including the two double-quote characters.

The include file is read in as if it were inserted at that point in the file. Using include is almost the same as cutting and pasting the entire contents of this file into your scene.

Include files may be nested. You may have at most 10 nested include files. There is no limit on un-nested include files.

Generally, include files have data for scenes but are not scenes in themselves. By convention scene files end in .pov and include files end with .inc.

It is legal to specify drive and directory information in the file specification however it is discouraged because it makes scene files less portable between various platforms. Use of full lower case is also recommended but not required.

Note: if you ever intend to distribute any source files you make for POV-Ray, remember that some operating systems have case-sensitive file names).

It is typical to put standard include files in a special sub-directory. POV-Ray can only read files in the current directory or one referenced by the Library_Path option or +L switch. See section "Library Paths".

You may use the #local directive to declare identifiers which are temporary in duration and local to the include file in scope. For details see "#declare vs. #local".

3.2.2.2 The #declare and #local Directives

Identifiers may be declared and later referenced to make scene files more readable and to parameterize scenes so that changing a single declaration changes many values. There are several built-in identifiers which POV-Ray declares for you. See section "Float Expressions: Built-in Variables" and "Built-in Vector Identifiers" for details.

3.2.2.2.1 Declaring identifiers

An identifier is declared as follows.

DECLARATION:
    #declare IDENTIFIER = RVALUE |
    #local IDENTIFIER = RVALUE
RVALUE:
    FLOAT; | VECTOR; | COLOR; | STRING | OBJECT | TEXTURE |
    PIGMENT | NORMAL | FINISH | INTERIOR | MEDIA | DENSITY |
    COLOR_MAP | PIGMENT_MAP | SLOPE_MAP | NORMAL_MAP |
    DENSITY_MAP | CAMERA | LIGHT_SOURCE | FOG | RAINBOW |
    SKY_SPHERE | TRANSFORM

Where IDENTIFIER is the name of the identifier up to 40 characters long and RVALUE is any of the listed items. They are called that because they are values that can appear to the right of the equals sign. The syntax for each is in the corresponding section of this language reference. Here are some examples.

 #declare Rows = 5;
 #declare Count = Count+1;
 #local  Here = <1,2,3>;
 #declare White = rgb <1,1,1>;
 #declare Cyan = color blue 1.0 green 1.0;
 #declare Font_Name = "ariel.ttf"
 #declare Rod = cylinder {-5*x,5*x,1}
 #declare Ring = torus {5,1}
 #local  Checks = pigment { checker White, Cyan }
 object{ Rod scale y*5 }     // not "cylinder { Rod }"
 object {
  Ring
  pigment { Checks scale 0.5 }
  transform Skew
 }

Note: that there should be a semi-colon after the expression in all float, vector and color identifier declarations. This semi-colon is introduced in POV-Ray version 3.1. If omitted, it generates a warning and some macros may not work properly. Semicolons after other declarations are optional.

Declarations, like most language directives, can appear almost anywhere in the file - even within other statements. For example:

 #declare Here=<1,2,3>;
 #declare Count=0;         // initialize Count
 union {
  object { Rod translate Here*Count }
  #declare Count=Count+1;     // re-declare inside union
  object { Rod translate Here*Count }
  #declare Count=Count+1;     // re-declare inside union
  object { Rod translate Here*Count }
 }

As this example shows, you can re-declare an identifier and may use previously declared values in that re-declaration.

Note: object identifiers use the generic wrapper statement object{ ... }. You do not need to know what kind of object it is.

Declarations may be nested inside each other within limits. In the example in the previous section you could declare the entire union as a object. However for technical reasons there are instances where you may not use any language directive inside the declaration of floats, vectors or color expressions. Although these limits have been loosened somewhat since POV-Ray 3.1, they still exist.

Identifiers declared within #macro ... #end blocks are not created at the time the macro is defined. They are only created at the time the macro is actually invoked. Like all other items inside such a #macro definition, they are ignored when the macro is defined.

3.2.2.2.2 #declare vs. #local

Identifiers may be declared either global using #declare or local using the #local directive.

Those created by the #declare directive are permanent in duration and global in scope. Once created, they are available throughout the scene and they are not released until all parsing is complete or until they are specifically released using #undef. See "Destroying Identifiers".

Those created by the #local directive are temporary in duration and local in scope. They temporarily override any identifiers with the same name. See "Identifier Name Collisions".

If #local is used inside a #macro then the identifier is local to that macro. When the macro is invoked and the #local directive is parsed, the identifier is created. It persists until the #end directive of the macro is reached. At the #end directive, the identifier is destroyed. Subsequent invocations of the macro create totally new identifiers.

Use of #local within an include file but not in a macro, also creates a temporary identifier that is local to that include file. When the include file is included and the #local directive is parsed, the identifier is created. It persists until the end of the include file is reached. At the end of file the identifier is destroyed. Subsequent inclusions of the file create totally new identifiers.

Use of #local in the main scene file (not in an include file and not in a macro) is identical to #declare. For clarity sake you should not use #local in a main file except in a macro.

There is currently no way to create permanent, yet local identifiers in POV-Ray.

Local identifiers may be specifically released early using #undef but in general there is no need to do so. See "Destroying Identifiers".

3.2.2.2.3 Identifier Name Collisions

Local identifiers may have the same names as previously declared identifiers. In this instance, the most recent, most local identifier takes precedence. Upon entering an include file or invoking a macro, a new symbol table is created. When referencing identifiers, the most recently created symbol table is searched first, then the next most recent and so on back to the global table of the main scene file. As each macro or include file is exited, its table and identifiers are destroyed. Parameters passed by value reside in the same symbol table as the one used for identifiers local to the macro.

The rules for duplicate identifiers may seem complicated when multiple-nested includes and macros are involved, but in actual practice the results are generally what you intended.

Consider this example: You have a main scene file called myscene.pov and it contains

 #declare A = 123;
 #declare B = rgb<1,2,3>;
 #declare C = 0;
 #include "myinc.inc"

Inside the include file you invoke a macro called MyMacro(J,K,L). It is not important where MyMacro is defined as long as it is defined before it is invoked. In this example, it is important that the macro is invoked from within myinc.inc.

The identifiers A, B, and C are generally available at all levels. If either myinc.inc or MyMacro contain a line such as #declare C=C+1; then the value C is changed everywhere as you might expect.

Now suppose inside myinc.inc you do...

 #local A = 546;

The main version of A is hidden and a new A is created. This new A is also available inside MyMacro because MyMacro is nested inside myinc.inc. Once you exit myinc.inc, the local A is destroyed and the original A with its value of 123 is now in effect. Once you have created the local A inside myinc.inc, there is no way to reference the original global A unless you #undef A or exit the include file. Using #undef always undefines the most local version of an identifier.

Similarly if MyMacro contained...

 #local B = box{0,1}

then a new identifier B is created local to the macro only. The original value of B remains hidden but is restored when the macro is finished. The local B need not have the same type as the original.

The complication comes when trying to assign a new value to an identifier at one level that was declared local at an earlier level. Suppose inside myinc.inc you do...

 #local D = 789;

If you are inside myinc.inc and you want to increment D by one, you might try to do...

 #local D = D + 1;

but if you try to do that inside MyMacro you will create a new D which is local to MyMacro and not the D which is external to MyMacro but local to myinc.inc. Therefore you've said "create a MyMacro D from the value of myinc.inc's D plus one". That's probably not what you wanted. Instead you should do...

 #declare D = D + 1;

You might think this creates a new D that is global but it actually increments the myinc.inc version of D. Confusing isn't it? Here are the rules:

  1. When referencing an identifier, you always get the most recent, most local version. By "referencing" we mean using the value of the identifier in a POV-Ray statement or using it on the right of an equals sign in either a #declare or #local.
  2. When declaring an identifier using the #local keyword, the identifier which is created or has a new value assigned, is ALWAYS created at the current nesting level of macros or include files.
  3. When declaring a NEW, NON-EXISTANT identifier using #declare, it is created as fully global. It is put in the symbol table of the main scene file.
  4. When ASSIGNING A VALUE TO AN EXISTING identifier using #declare, it assigns it to the most recent, most local version at the time.

In summary, #local always means "the current level", and #declare means "global" for new identifiers and "most recent" for existing identifiers.

3.2.2.2.4 Destroying Identifiers with #undef

Identifiers created with #declare will generally persist until parsing is complete. Identifiers created with #local will persist until the end of the macro or include file in which they were created. You may however un-define an identifier using the #undef directive. For example:

 #undef MyValue

If multiple local nested versions of the identifier exist, the most local most recent version is deleted and any identically named identifiers which were created at higher levels will still exist.

See also "The #ifdef and #ifndef Directives".

3.2.2.3 File I/O Directives

You may open, read, write, append, and close plain ASCII text files while parsing POV-Ray scenes. This feature is primarily intended to help pass information between frames of an animation. Values such as an object's position can be written while parsing the current frame and read back during the next frame. Clever use of this feature could allow a POV-Ray scene to generate its own include files or write self-modifying scripts. We trust that users will come up with other interesting uses for this feature.

Note: some platform versions of POV-Ray (e.g. Windows) provide means to restrict the ability of scene files to read & write files.

3.2.2.3.1 The #fopen Directive

Users may open a text file using the #fopen directive. The syntax is as follows:

FOPEN_DIRECTIVE:
    #fopen IDENTIFIER "filename" OPEN_TYPE
OPEN_TYPE:
    read | write | append

Where IDENTIFIER is an undefined identifier used to reference this file as a file handle, "filename" is any string literal or string expression which specifies the file name. Files opened with the read are open for read only. Those opened with write create a new file with the specified name and it overwrites any existing file with that name. Those opened with append opens a file for writing but appends the text to the end of any existing file.

The file handle identifier created by #fopen is always global and remains in effect (and the file remains open) until the scene parsing is complete or until you #fclose the file. You may use #ifdef FILE_HANDLE_IDENTIFIER to see if a file is open.

3.2.2.3.2 The #fclose Directive

Files opened with the #fopen directive are automatically closed when scene parsing completes however you may close a file using the #fclose directive. The syntax is as follows:

FCLOSE_DIRECTIVE:
    #fclose FILE_HANDLE_IDENTIFIER

Where FILE_HANDLE_IDENTIFIER is previously opened file opened with the #fopen directive. See "The #fopen Directive".

3.2.2.3.3 The #read Directive

You may read string, float or vector values from a plain ASCII text file directly into POV-Ray variables using the #read directive. The file must first be opened in "read" mode using the #fopen directive. The syntax for #read is as follows:

READ_DIRECTIVE:
  #read (FILE_HANDLE_IDENTIFIER, DATA_IDENTIFIER[,DATA_IDENTIFIER]..)
DATA_IDENTIFIER:
  UNDECLARED_IDENTIFIER | FLOAT_IDENTIFIER | VECTOR_IDENTIFIER | 
  STRING_IDENTIFIER

Where FILE_HANDLE_IDENTIFIER is the previously opened file. It is followed by one or more DATA_IDENTIFIERs separated by commas. The parentheses around the identifier list are required. A DATA_IDENTIFIER is any undeclared identifier or any previously declared string identifier, float identifier, or vector identifier. Undefined identifiers will be turned into global identifiers of the type determined by the data which is read. Previously defined identifiers remain at whatever global/local status they had when originally created. Type checking is performed to insure that the proper type data is read into these identifiers.

The format of the data to be read must be a series of valid string literals, float literals, or vector literals separated by commas. Expressions or identifiers are not permitted in the data file however unary minus signs and exponential notation are permitted on float values.

If you attempt to read past end-of-file, the file is automatically closed and the FILE_HANDLE_IDENTIFIER is deleted from the symbol table. This means that the boolean function defined(IDENTIFIER) can be used to detect end-of-file. For example:

  #fopen MyFile "mydata.txt" read
  #while (defined(MyFile))
    #read (MyFile,Var1,Var2,Var3)
    ...
  #end
3.2.2.3.4 The #write Directive

You may write string, float or vector values to a plain ASCII text file from POV-Ray variables using the #write directive. The file must first be opened in either write or append mode using the #fopen directive. The syntax for #write is as follows:

WRITE_DIRECTIVE:
    #write( FILE_HANDLE_IDENTIFIER, DATA_ITEM[,DATA_ITEM]...)
DATA_ITEM:
    FLOAT | VECTOR | STRING

Where FILE_HANDLE_IDENTIFIER is the previously opened file. It is followed by one or more DATA_ITEMs separated by commas. The parentheses around the identifier list are required. A DATA_ITEM is any valid string expression, float expression, or vector expression. Float expressions are evaluated and written as signed float literals. If you require format control, you should use the str(VALUE,L,P) function to convert it to a formatted string. See "String Functions" for details on the str function. Vector expressions are evaluated into three signed float constants and are written with angle brackets and commas in standard POV-Ray vector notation. String expressions are evaluated and written as specified.

Note: data read by the #read directive must have comma delimiters between values and quotes around string data but the #write directive does not automatically output commas or quotes.

For example the following #read directive reads a string, float and vector.

 #read (MyFile,MyString,MyFloat,MyVect)

It expects to read something like:

 "A quote delimited string", -123.45, <1,2,-3>

The POV-Ray code to write this might be:

 #declare Val1 = -123.45;
 #declare Vect1 = <1,2,-3>;
 #write(MyFile,"\"A quote delimited string\",",Val1,",",Vect1,"\n")

See "String Literals" and "Text Formatting" for details on writing special characters such as quotes, newline, etc.

3.2.2.4 The #default Directive

POV-Ray creates a default texture when it begins processing. You may change those defaults as described below. Every time you specify a texture statement, POV-Ray creates a copy of the default texture. Anything you put in the texture statement overrides the default settings. If you attach a pigment, normal, or finish to an object without any texture statement then POV-Ray checks to see if a texture has already been attached. If it has a texture then the pigment, normal or finish will modify the existing texture. If no texture has yet been attached to the object then the default texture is copied and the pigment, normal or finish will modify that texture.

You may change the default texture, pigment, normal or finish using the language directive #default as follows:

DEFAULT_DIRECTIVE:
    #default {DEFAULT_ITEM }
DEFAULT_ITEM:
    TEXTURE | PIGMENT | NORMAL | FINISH

For example:

 #default {
   texture {
     pigment { rgb <1,0,0> }
     normal { bumps 0.3 }
     finish { ambient 0.4 }
   }
 }

This means objects will default to red bumps and slightly high ambient finish. Also you may change just part of it like this:

 #default {
  pigment {rgb <1,0,0>}
 }

This still changes the pigment of the default texture. At any time there is only one default texture made from the default pigment, normal and finish. The example above does not make a separate default for pigments alone.

Note: the special textures tiles and material_map or a texture with a texture_map may not be used as defaults.

You may change the defaults several times throughout a scene as you wish. Subsequent #default statements begin with the defaults that were in effect at the time. If you wish to reset to the original POV-Ray defaults then you should first save them as follows:

 //At top of file
 #declare Original_Default = texture {}

later after changing defaults you may restore it with...

 #default {texture {Original_Default}}

If you do not specify a texture for an object then the default texture is attached when the object appears in the scene. It is not attached when an object is declared. For example:

 #declare My_Object =
  sphere{ <0,0,0>, 1 } // Default texture not applied
  object{ My_Object }  // Default texture added here

You may force a default texture to be added by using an empty texture statement as follows:

 #declare My_Thing =
  sphere { <0,0,0>, 1 texture {} } // Default texture applied

The original POV-Ray defaults for all items are given throughout the documentation under each appropriate section.

3.2.2.5 The #version Directive

As POV-Ray has evolved from version 1.0 through 3.6 we have made every effort to maintain some amount of backwards compatibility with earlier versions. Some old or obsolete features can be handled directly without any special consideration by the user. Some old or obsolete features can no longer be handled at all. However some old features can still be used if you warn POV-Ray that this is an older scene. The #version directive can be used to switch version compatibility to different setting several times throughout a scene file. The syntax is:

VERSION_DIRECTIVE: 
    #version FLOAT;

Note: there should be a semi-colon after the float expression in a #version directive. This semi-colon is introduced in POV-Ray version 3.1. If omitted, it generates a warning and some macros may not work properly.

Additionally you may use the Version=n.n option or the +MVn.n switch to establish the initial setting. See "Language Version" for details. For example one feature introduced in 2.0 that was incompatible with any 1.0 scene files is the parsing of float expressions. Using #version 1.0 turns off expression parsing as well as many warning messages so that nearly all 1.0 files will still work. Naturally the default setting for this option is #version 3.5.

Note: Some obsolete or re-designed features are totally unavailable in the current version of POV-Ray REGARDLES OF THE VERSION SETTING. Details on these features are noted throughout this documentation.

The built-in float identifier version contains the current setting of the version compatibility option. See "Float Expressions: Built-in Variables". Together with the built-in version identifier the #version directive allows you to save and restore the previous values of this compatibility setting. The new #local identifier option is especially useful here. For example suppose mystuff.inc is in version 1 format. At the top of the file you could put:

 #local Temp_Vers = version;  // Save previous value
 #version 1.0;         // Change to 1.0 mode
 ... // Version 1.0 stuff goes here...
 #version Temp_Vers;      // Restore previous version

Future versions of POV-Ray may not continue to maintain full backward compatibility even with the #version directive. We strongly encourage you to phase in current version syntax as much as possible.

3.2.2.6 Conditional Directives

POV-Ray allows a variety of language directives to implement conditional parsing of various sections of your scene file. This is especially useful in describing the motion for animations but it has other uses as well. Also available is a #while loop directive. You may nest conditional directives 200 levels deep.

3.2.2.6.1 The #if...#else...#end Directives

The simplest conditional directive is a traditional #if directive. It is of the form...

IF_DIRECTIVE:
    #if ( Cond ) TOKENS... [#else TOKENS...] #end

The TOKENS are any number of POV-Ray keyword, identifiers, or punctuation and ( Cond ) is a float expression that is interpreted as a boolean value. The parentheses are required. The #end directive is required. A value of 0.0 is false and any non-zero value is true.

Note: extremely small values of about 1e-10 are considered zero in case of round off errors.

If Cond is true, the first group of tokens is parsed normally and the second set is skipped. If false, the first set is skipped and the second set is parsed. For example:

 #declare Which=1;
 #if (Which)
   box { 0, 1 }
 #else
   sphere { 0, 1 }
 #end

The box is parsed and the sphere is skipped. Changing the value of Which to 0 means the box is skipped and the sphere is used. The #else directive and second token group is optional. For example:

 #declare Which=1;
 #if (Which)
   box { 0, 1 }
 #end

Changing the value of Which to 0 means the box is removed.

At the beginning of the chapter "Language Directives" it was stated that "These directives can appear in almost any place in the scene file....". The following is an example where it will not work, it will confuse the parser:

   #if( #if(yes) yes #end ) #end
3.2.2.6.2 The #ifdef and #ifndef Directives

The #ifdef and #ifndef directive are similar to the #if directive however they are used to determine if an identifier has been previously declared.

IFDEF_DIRECTIVE:
    #ifdef ( IDENTIFIER ) TOKENS... [#else TOKENS...] #end
IFNDEF_DIRECTIVE:
    #ifndef ( IDENTIFIER ) TOKENS... [#else TOKENS...] #end

If the IDENTIFIER exists then the first group of tokens is parsed normally and the second set is skipped. If false, the first set is skipped and the second set is parsed. This is especially useful for replacing an undefined item with a default. For example:

  #ifdef (User_Thing)
  // This section is parsed if the
  // identifier "User_Thing" was
  // previously declared
  object{User_Thing} // invoke identifier
 #else
  // This section is parsed if the
  // identifier "User_Thing" was not
  // previously declared
  box{<0,0,0>,<1,1,1>} // use a default
 #end
  // End of conditional part

The #ifndef directive works the opposite. The first group is parsed if the identifier is not defined. As with the #if directive, the #else clause is optional and the #end directive is required.

The #ifdef and #ifndef directives can be used to determine whether a specific element of an array has been assigned.

 #declare MyArray=array[10]
 //#declare MyArray[0]=7;
 #ifdef(MyArray[0])
    #debug "first element is assigned\n"
 #else 
    #debug "first element is not assigned\n"
 #end
3.2.2.6.3 The #switch, #case, #range and #break Directives

A more powerful conditional is the #switch directive. The syntax is as follows...

SWITCH_DIRECTIVE:
   #switch ( Switch_Value ) SWITCH_CLAUSE... [#else TOKENS...] #end
SWITCH_CLAUSE:
   #case( Case_Value ) TOKENS... [#break] |
   #range( Low_Value , High_Value ) TOKENS... [#break]

The TOKENS are any number of POV-Ray keyword, identifiers, or punctuation and ( Switch_Value ) is a float expression. The parentheses are required. The #end directive is required. The SWITCH_CLAUSE comes in two varieties. In the #case variety, the float Switch_Value is compared to the float Case_Value. If they are equal, the condition is true.

Note: that values whose difference is less than 1e-10 are considered equal in case of round off errors.

In the #range variety, Low_Value and High_Value are floats separated by a comma and enclosed in parentheses. If Low_Value <= Switch_Value and Switch_Value<=High_Value then the condition is true.

In either variety, if the clause's condition is true, that clause's tokens are parsed normally and parsing continues until a #break, #else or #end directive is reached. If the condition is false, POV-Ray skips until another #case or #range is found.

There may be any number of #case or #range clauses in any order you want. If a clause evaluates true but no #break is specified, the parsing will fall through to the next #case or #range and that clause conditional is evaluated. Hitting #break while parsing a successful section causes an immediate jump to the #end without processing subsequent sections, even if a subsequent condition would also have been satisfied.

An optional #else clause may be the last clause. It is only executed if the clause before it was a false clause.

Here is an example:

 #switch (VALUE)
  #case (TEST_1)
   // This section is parsed if VALUE=TEST_1
  #break //First case ends
  #case (TEST_2)
   // This section is parsed if VALUE=TEST_2
  #break //Second case ends
  #range (LOW_1,HIGH_1)
   // This section is parsed if (VALUE>=LOW_1)&(VALUE<=HIGH_1)
  #break //Third case ends
  #range (LOW_2,HIGH_2)
   // This section is parsed if (VALUE>=LOW_2)&(VALUE<=HIGH_2)
  #break //Fourth case ends
  #else
   // This section is parsed if no other case or
   // range is true.
 #end // End of conditional part
3.2.2.6.4 The #while...#end Directive

The #while directive is a looping feature that makes it easy to place multiple objects in a pattern or other uses.

WHILE_DIRECTIVE:
    #while ( Cond ) TOKENS... #end

The TOKENS are any number of POV-Ray keyword, identifiers, or punctuation marks which are the body of the loop. The #while directive is followed by a float expression that evaluates to a boolean value. A value of 0.0 is false and any non-zero value is true.

Note: extremely small values of about 1e-10 are considered zero in case of round off errors.

The parentheses around the expression are required. If the condition is true parsing continues normally until an #end directive is reached. At the end, POV-Ray loops back to the #while directive and the condition is re-evaluated. Looping continues until the condition fails. When it fails, parsing continues after the #end directive.

Note: it is possible for the condition to fail the first time and the loop is totally skipped. It is up to the user to insure that something inside the loop changes so that it eventually terminates.

Here is a properly constructed loop example:

 #declare Count=0;
 #while (Count < 5)
  object { MyObject translate x*3*Count }
  #declare Count=Count+1;
 #end

This example places five copies of MyObject in a row spaced three units apart in the x-direction.

3.2.2.7 User Message Directives

With the addition of conditional and loop directives, the POV-Ray language has the potential to be more like an actual programming language. This means that it will be necessary to have some way to see what is going on when trying to debug loops and conditionals. To fulfill this need we have added the ability to print text messages to the screen. You have a choice of five different text streams to use including the ability to generate a fatal error if you find it necessary. Limited formatting is available for strings output by this method.

3.2.2.7.1 Text Message Streams

The syntax for a text message is any of the following:

TEXT_STREAM_DIRECTIVE:
    #debug STRING | #error STRING | #warning STRING

Where STRING is any valid string of text including string identifiers or functions which return strings. For example:

 #switch (clock*360)
  #range (0,180)
   #debug "Clock in 0 to 180 range\n"
  #break
  #range (180,360)
   #debug "Clock in 180 to 360 range\n"
  #break
  #else
   #warning "Clock outside expected range\n"
   #warning concat("Value is:",str(clock*360,5,0),"\n")
 #end

There are seven distinct text streams that POV-Ray uses for output. You may output only to three of them. On some versions of POV-Ray, each stream is designated by a particular color. Text from these streams are displayed whenever it is appropriate so there is often an intermixing of the text. The distinction is only important if you choose to turn some of the streams off or to direct some of the streams to text files. On some systems you may be able to review the streams separately in their own scroll-back buffer. See "Directing Text Streams to Files" for details on re-directing the streams to a text file.

Here is a description of how POV-Ray uses each stream. You may use them for whatever purpose you want except note that use of the #error stream causes a fatal error after the text is displayed.

Debug: This stream displays debugging messages. It was primarily designed for developers but this and other streams may also be used by the user to display messages from within their scene files.

Error: This stream displays fatal error messages. After displaying this text, POV-Ray will terminate. When the error is a scene parsing error, you may be shown several lines of scene text that leads up to the error.

Warning: This stream displays warning messages during the parsing of scene files and other warnings. Despite the warning, POV-Ray can continue to render the scene.

The #render and #statistsics could be accessed in previous versions. Their output is now redirected to the #debug stream. The #banner and #status streams can not be accessed by the user.

3.2.2.7.2 Text Formatting

Some escape sequences are available to include non-printing control characters in your text. These sequences are similar to those used in string literals in the C programming language. The sequences are:

"\a" Bell or alarm, 0x07
"\b" Backspace, 0x08
"\f" Form feed, 0x0C
"\n" New line (line feed) 0x0A
"\r" Carriage return 0x0D
"\t" Horizontal tab 0x09
"\uNNNN" Unicode character code NNNN 0xNNNN
"\v" Vertical tab 0x0B
"\0" Null 0x00
"\\" Backslash 0x5C
"\'" Single quote 0x27
"\"" Double quote 0x22

For example:

 #debug "This is one line.\nBut this is another"\n

Depending on what platform you are using, they may not be fully supported for console output. However they will appear in any text file if you re-direct a stream to a file.

3.2.2.8 User Defined Macros

POV-Ray 3.1 introduced user defined macros with parameters. This feature, along with the ability to declare #local variables, turned the POV-Ray Language into a fully functional programming language. Consequently, it is now possible to write scene generation tools in POV-Ray's own language that previously required external utilities.

3.2.2.8.1 The #macro Directive

The syntax for declaring a macro is:

MACRO_DEFINITION:
#macro IDENTIFIER ([PARAM_IDENT] [, PARAM_IDENT]... ) TOKENS... #end

Where IDENTIFIER is the name of the macro and PARAM_IDENTs are a list of zero or more formal parameter identifiers separated by commas and enclosed by parentheses. The parentheses are required even if no parameters are specified.

The TOKENS are any number of POV-Ray keyword, identifiers, or punctuation marks which are the body of the macro. The body of the macro may contain almost any POV-Ray syntax items you desire. It is terminated by the #end directive.

Note: any conditional directives such as #if...#end, #while...#end, etc. must be fully nested inside or outside the macro so that the corresponding #end directives pair-up properly.

A macro must be declared before it is invoked. All macro names are global in scope and permanent in duration. You may redefine a macro by another #macro directive with the same name. The previous definition is lost. Macro names respond to #ifdef, #ifndef, and #undef directives. See "The #ifdef and #ifndef Directives" and "Destroying Identifiers with #undef".

3.2.2.8.2 Invoking Macros

You invoke the macro by specifying the macro name followed by a list of zero or more actual parameters enclosed in parentheses and separated by commas. The number of actual parameters must match the number of formal parameters in the definition. The parentheses are required even if no parameters are specified. The syntax is:

MACRO_INVOCATION:
    MACRO_IDENTIFIER ( [ACTUAL_PARAM] [, ACTUAL_PARAM]... )
ACTUAL_PARAM:
    IDENTIFIER | RVALUE

An RVALUE is any value that can legally appear to the right of an equals sign in a #declare or #local declaration. See "Declaring identifiers" for information on RVALUEs. When the macro is invoked, a new local symbol table is created. The actual parameters are assigned to formal parameter identifiers as local, temporary variables. POV-Ray jumps to the body of the macro and continues parsing until the matching #end directive is reached. There, the local variables created by the parameters are destroyed as well as any local identifiers expressly created in the body of the macro. It then resumes parsing at the point where the macro was invoked. It is as though the body of the macro was cut and pasted into the scene at the point where the macro was invoked.

Note: it is possible to invoke a macro that was declared in another file. This is quite normal and in fact is how many "plug-ins" work (such as the popular Lens Flare macro). However, be aware that calling a macro that was declared in a file different from the one that it is being called from involves more overhead than calling one in the same file.

This is because POV-Ray does not tokenize and store its language. Calling a macro in another file therefore requires that the other file be opened and closed for each call. Normally, this overhead is inconsequential; however, if you are calling the macro many thousands of times, it can cause significant delays. A future version of the POV-Ray language will remove this problem.

Here is a simple macro that creates a window frame object when you specify the inner and outer dimensions.

#macro Make_Frame(OuterWidth,OuterHeight,InnerWidth,
                  InnerHeight,Depth)
  #local Horz = (OuterHeight-InnerHeight)/2;
  #local Vert = (OuterWidth-InnerWidth)/2;
  difference {
    box{
	  <0,0,0>,<OuterWidth,OuterHeight,Depth>
	}
    box{
	  <Vert,Horz,-0.1>,
      <OuterWidth-Vert,OuterHeight-Horz,Depth+0.1>
	}
  }
#end
Make_Frame(8,10,7,9,1) //invoke the macro

In this example, the macro has five float parameters. The actual parameters (the values 8, 10, 7, 9, and 1) are assigned to the five identifiers in the #macro formal parameter list. It is as though you had used the following five lines of code.

 #local OuterWidth = 8;
 #local OuterHeight = 10;
 #local InnerWidth, = 7;
 #local InnerHeight = 9;
 #local Depth = 1;

These five identifiers are stored in the same symbol table as any other local identifier such as Horz or Vert in this example. The parameters and local variables are all destroyed when the #end statement is reached. See "Identifier Name Collisions" for a detailed discussion of how local identifiers, parameters, and global identifiers work when a local identifier has the same name as a previously declared identifier.

3.2.2.8.3 Are POV-Ray Macros a Function or a Macro?

POV-Ray macros are a strange mix of macros and functions. In traditional computer programming languages, a macro works entirely by token substitution. The body of the routine is inserted into the invocation point by simply copying the tokens and parsing them as if they had been cut and pasted in place. Such cut-and-paste substitution is often called macro substitution because it is what macros are all about. In this respect, POV-Ray macros are exactly like traditional macros in that they use macro substitution for the body of the macro. However traditional macros also use this cut-and-paste substitution strategy for parameters but POV-Ray does not.

Suppose you have a macro in the C programming language Typical_Cmac(Param) and you invoke it as Typical_Cmac(else A=B). Anywhere that Param appears in the macro body, the four tokens else, A, =, and B are substituted into the program code using a cut-and-paste operation. No type checking is performed because anything is legal. The ability to pass an arbitrary group of tokens via a macro parameter is a powerful (and sadly often abused) feature of traditional macros.

After careful deliberation, we have decided against this type of parameters for our macros. The reason is that POV-Ray uses commas more frequently in its syntax than do most programming languages. Suppose you create a macro that is designed to operate on one vector and two floats. It might be defined OurMac(V,F1,F2). If you allow arbitrary strings of tokens and invoke a macro such as OurMac(<1,2,3>,4,5) then it is impossible to tell if this is a vector and two floats or if its 5 parameters with the two tokens < and 1 as the first parameter. If we design the macro to accept 5 parameters then we cannot invoke it like this... OurMac(MyVector,4,5).

Function parameters in traditional programming languages do not use token substitution to pass values. They create temporary, local variables to store parameters that are either constant values or identifier references which are in effect a pointer to a variable. POV-Ray macros use this function-like system for passing parameters to its macros. In our example OurMac(<1,2,3>,4,5), POV-Ray sees the < and knows it must be the start of a vector. It parses the whole vector expression and assigns it to the first parameter exactly as though you had used the statement #local V=<1,2,3>;.

Although we say that POV-Ray parameters are more like traditional function parameters than macro parameters, there still is one difference. Most languages require you to declare the type of each parameter in the definition before you use it but POV-Ray does not. This should be no surprise because most languages require you to declare the type of any identifier before you use it but POV-Ray does not. This means that if you pass the wrong type value in a POV-Ray macro parameter, it may not generate an error until you reference the identifier in the macro body. No type checking is performed as the parameter is passed. So in this very limited respect, POV-Ray parameters are somewhat macro-like but are mostly function-like.

3.2.2.8.4 Returning a Value Like a Function

POV-Ray macros have a variety of uses. Like most macros, they provide a parameterized way to insert arbitrary code into a scene file. However most POV-Ray macros will be used like functions or procedures in a traditional programming language. Macros are designed to fill all of these roles.

When the body of a macro consists of statements that create an entire item such as an object, texture, etc. then the macro acts like a function which returns a single value. The Make_Frame macro example in the section "Invoking Macros" above is such a macro which returns a value that is an object. Here are some examples of how you might invoke it.

 union {  //make a union of two objects
   object{ Make_Frame(8,10,7,9,1) translate  20*x}
   object{ Make_Frame(8,10,7,9,1) translate -20*x}
 }
 #declare BigFrame = object{ Make_Frame(8,10,7,9,1)}
 #declare SmallFrame = object{ Make_Frame(5,4,4,3,0.5)}

Because no type checking is performed on parameters and because the expression syntax for floats, vectors, and colors is identical, you can create clever macros which work on all three. See the sample scene MACRO3.POV which includes this macro to interpolate values.

// Define the macro.  Parameters are:
//   T:  Middle value of time
//   T1: Initial time
//   T2: Final time
//   P1: Initial position (may be float, vector or color)
//   P2: Final position (may be float, vector or color)
//   Result is a value between P1 and P2 in the same proportion
//    as T is between T1 and T2.
#macro Interpolate(T,T1,T2,P1,P2)
   (P1+(T1+T/(T2-T1))*(P2-P1))
#end

You might invoke it with P1 and P2 as floats, vectors, or colors as follows.

sphere{
  Interpolate(I,0,15,<2,3,4>,<9,8,7>), //center location is vector
  Interpolate(I,0,15,3.0,5.5)          //radius is float
  pigment {
    color Interpolate(I,0,15,rgb<1,1,0>,rgb<0,1,1>)
  }
}

As the float value I varies from 0 to 15, the location, radius, and color of the sphere vary accordingly.

There is a danger in using macros as functions. In a traditional programming language function, the result to be returned is actually assigned to a temporary variable and the invoking code treats it as a variable of a given type. However macro substitution may result in invalid or undesired syntax. The definition of the macro Interpolate above has an outermost set of parentheses. If those parentheses are omitted, it will not matter in the examples above, but what if you do this...

 #declare Value = Interpolate(I,0,15,3.0,5.5)*15;

The end result is as if you had done...

 #declare Value = P1+(T1+T/(T2-T1))*(P2-P1) * 15;

which is syntactically legal but not mathematically correct because the P1 term is not multiplied. The parentheses in the original example solves this problem. The end result is as if you had done...

 #declare Value = (P1+(T1+T/(T2-T1))*(P2-P1)) * 15;

which is correct.

3.2.2.8.5 Returning Values Via Parameters

Sometimes it is necessary to have a macro return more than one value or you may simply prefer to return a value via a parameter as is typical in traditional programming language procedures. POV-Ray macros are capable of returning values this way. The syntax for POV-Ray macro parameters says that the actual parameter may be an IDENTIFIER or an RVALUE. Values may only be returned via a parameter if the parameter is an IDENTIFIER. Parameters that are RVALUES are constant values that cannot return information. An RVALUE is anything that legally may appear to the right of an equals sign in a #declare or #local directive. For example consider the following trivial macro which rotates an object about the x-axis.

 #macro Turn_Me(Stuff,Degrees)
   #declare Stuff = object{Stuff rotate x*Degrees}
 #end

This attempts to re-declare the identifier Stuff as the rotated version of the object. However the macro might be invoked with Turn_Me(box{0,1},30) which uses a box object as an RVALUE parameter. This will not work because the box is not an identifier. You can however do this

   #declare MyObject=box{0,1}
   Turn_Me(MyObject,30)

The identifier MyObject now contains the rotated box.

See "Identifier Name Collisions" for a detailed discussion of how local identifiers, parameters, and global identifiers work when a local identifier has the same name as a previously declared identifier.

While it is obvious that MyObject is an identifier and box{0,1} is not, it should be noted that Turn_Me(object{MyObject},30) will not work because object{MyObject} is considered an object statement and is not a pure identifier. This mistake is more likely to be made with float identifiers versus float expressions. Consider these examples.

  #declare Value=5.0;
  MyMacro(Value)     //MyMacro can change the value of Value but...
  MyMacro(+Value)    //This version and the rest are not lone
  MyMacro(Value+0.0) // identifiers. They are float expressions
  MyMacro(Value*1.0) // which cannot be changed.

Although all four invocations of MyMacro are passed the value 5.0, only the first may modify the value of the identifier.

More about "#macro"

More about "texture"