### Access point components with array notation Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to read and write individual components of a point using the [] operator. The example gets the y component and sets the x component. ```osl point P; float y = P[1]; // get the y component P[0] = 0.5; // set the x component ``` -------------------------------- ### pointcloud_search example Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Searches a point cloud for the closest points within a radius and retrieves attributes. The example prints the number of found particles and their positions and colors. Note that the point cloud is created if it does not exist and initialized from disk if a matching file is found. ```OSL float r = 3.0; point pos[10]; color col[10]; int n = pointcloud_search ("particles.ptc", P, r, 10, "position", pos, "color", col); printf ("Found %d particles within radius %f of (%p)\n", r, P); for (int i = 0; i < n; ++i) printf (" position (%f) -> color (%g)\n", pos[i], col[i]); ``` -------------------------------- ### Example shader group serialization Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/shadergroups.html This example shows a complete shader group description using the `param`, `shader`, and `connect` statements. It sets pending parameters, declares shader instances, and connects outputs to inputs. Note that parameters are applied to the next `shader` statement, and connections require the source layer to precede the destination layer. ```osl param string name "rings.tx" ; # set pending `name' param float scale 3.5 ; # set pending `scale' shader "texturemap" "tex1" ; # tex1 layer, picks up `name', `scale' param string name "grain.tx" ; shader "texturemap" "tex2" ; param float gam 2.2 ; shader "gamma" "gam1" ; param float gam 1.0 ; shader "gamma" "gam2" ; param color woodcolor 0.42 0.38 0.22 ; # example of a color param shader "wood" "wood1" ; connect tex1.Cout gam1.Cin ; # connect tex1's Cout to gam1's Cin connect tex2.Cout gam2.Cin ; connect gam1.Cout wood1.rings ; connect gam2.Cout wood1.grain ; ``` -------------------------------- ### startswith Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Checks if a string starts with a given prefix. ```APIDOC ## startswith ### Description Return 1 if string `s` begins with the substring `prefix`, otherwise return 0. ### Function Signature - `int startswith(string s, string prefix)` ### Parameters - `s` (string) - Required - The string to check. - `prefix` (string) - Required - The prefix to look for. ### Return Value - (int) - 1 if `s` starts with `prefix`, 0 otherwise. ``` -------------------------------- ### pointcloud_get example Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Retrieves attributes for a list of point indices obtained from pointcloud_search. The example fetches a float attribute and a float[4] attribute into separate arrays. Returns 1 on success, 0 on failure (e.g., type mismatch, invalid indices, or unknown file). ```OSL float r = 3.0; int indices[10]; int n = pointcloud_search ("particles.ptc", P, r, 10, "index", indices); float temp[10]; // presumed to be "float" attribute float quaternions[40]; // presumed to be "float[4]" attribute int ok = pointcloud_get ("particles.ptc", indices, n, "temperature", temp, "quat", quaternions); ``` -------------------------------- ### Constructor examples for color and point Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Shows how to construct color and point values using constructor syntax. Constant arguments make the constructed value a compile-time constant with no runtime cost. ```osl color (1, 0.75, 0.5) point ("object", 1, 2, 3) ``` -------------------------------- ### Array declaration, initialization, access, and invalid multi-dimensional example Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Illustrates array declaration, initialization, element access, and shows that multi-dimensional arrays are not supported. ```osl float d[10]; // Declare an uninitialized array float c[3] = { 0.1, 0.2, 3.14 }; // Initialize the array float f = c[1]; // Access one element float d[10][3]; // Invalid, multi-dimensional arrays not supported ``` -------------------------------- ### OSL operator overloading example with __operator__add__ Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Shows how to define a struct and overload the '+' operator for it using the special function name __operator__add__. The example defines a vector4 struct, implements addition, and demonstrates the overloaded operator in a shader, printing the result. ```OSL struct vector4 { float x, y, z, w; }; vector4 __operator__add__ (vector4 a, vector4 b) { return vector4 (a.x+b.x, a.y+b.y, a.z+b.z, a.w+b.w); } shader test () { vector4 a = vector4 (.2, .3, .4, .5); vector4 b = vector4 (1, 2, 3, 4); vector4 c = a + b; // Will call __operator__add__(vector4,vector4) printf ("a+b = %g %g %g %g\n", c.x, c.y, c.z, c.w); } ``` -------------------------------- ### Type cast examples: C-style and constructor-style Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Illustrates casting between types using C-style parentheses and C++-style constructor calls. Both forms are equivalent. Note that casting a point to a color is allowed. ```osl (vector) P /* cast a point to a vector */ (point) f /* cast a float to a point */ (color) P /* cast a point to a color! */ vector (P) /* Means the same thing */ point (f) color (P) ``` -------------------------------- ### Using arraylength() to get array size Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to use the built-in function arraylength() to get the number of elements in an array. ```osl float c[3]; int clen = arraylength(c); // should return 3 ``` -------------------------------- ### regex_search examples with POSIX regex Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Illustrates regex_search usage: simple boolean checks, filling a match array with start/end indices, and extracting sub-expressions using parentheses. The example shows that regex_search returns 1 for a substring match and 0 otherwise, and that the results array is filled with character indices (start and end) for the overall match and each sub-expression. ```osl r = regex_search ("foobar.baz", "bar"); // = 1 r = regex_search ("foobar.baz", "bark"); // = 0 int match[2]; regex_search ("foobar.baz", match, "[Oo]{2}") = 1 (match[0] == 1, match[1] == 3) substr ("foobar.baz", match[0], match[1]-match[0]) = "oo" int match[6]; regex_search ("foobar.baz", match, "(f[Oo]{2}).*(.az)") = 1 substr ("foobar.baz", match[0], match[1]-match[0]) = "foobar.baz" substr ("foobar.baz", match[2], match[3]-match[2]) = "foo" substr ("foobar.baz", match[4], match[5]-match[4]) = "baz" ``` -------------------------------- ### OSL shader declaration with various parameters Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/grosssyntax.html Example shader declaration showing simple parameters with constant initializers, a computed parameter referencing an earlier one, fixed-length and variable-length arrays, and an output parameter. The body is omitted with '...'. ```osl surface wood ( /* Simple params with constant initializers */ float Kd = 0.5, color woodcolor = color (.7, .5, .3), string texturename = "wood.tx", /* Computed from an earlier parameter */ color ringcolor = 0.25 * woodcolor, /* Fixed-length array */ color paintcolors[3] = { color(0,.25,0.7), color(1,1,1), color(0.75,0.5,0.2) }, /* variable-length array */ int pattern[] = { 2, 4, 2, 1 }, /* output parameter */ output color Cunlit = 0 ) { ... } ``` -------------------------------- ### Access and set point components using named components Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to read and write point-like components using named fields x, y, and z as synonyms for indices [0], [1], and [2]. The comment indicates that P.y gets the [1] component and P.x sets the [0] component. ```osl float yval = P.y; // get the [1] or y component P.x = 0.5; // set the [0] or x component ``` -------------------------------- ### Variable declaration examples Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Illustrates various ways to declare variables in OSL: uninitialized, with constant initializer, with computed initializer, and multiple variables of the same type in one declaration. ```osl float a; // Declare; current value is undefined float b = 1; // Declare and assign a constant initializer float c = a*b; // Computed initializer float d, e = 2, f; // Declare several variables of the same type ``` -------------------------------- ### OSL shader with metadata Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/grosssyntax.html Example shader declaration showing metadata for the shader and its parameters. Metadata is placed in double brackets after the shader name and after each parameter's initializer. Metadata does not affect shader execution and is used for UI hints and other annotations. ```osl surface wood [[ string help = "Realistic wood shader" ]] ( float Kd = 0.5 [[ string help = "Diffuse reflectivity", float min = 0, float max = 1 ]] , color woodcolor = color (.7, .5, .3) [[ string help = "Base color of the wood" ]], color ringcolor = 0.25 * woodcolor [[ string help = "Color of the dark rings" ]], string texturename = "wood.tx" [[ string help = "Texture map for the grain", string widget = "filename" ]], int pattern = 0 [[ string widget = "mapper", string options = "oak:0|elm:1|walnut:2" ]] ) { ... } ``` -------------------------------- ### pointcloud_write example Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Saves a tuple of attributes at a given position in a named point cloud. The point cloud is saved when the frame finishes computing. Returns 1 on success, 0 on failure (e.g., attribute name/type mismatch across positions). ```OSL color C = ...; int ok = pointcloud_write ("particles.ptc", P, "normal", N, "color", C); ``` -------------------------------- ### if/else conditional example Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Shows an if/else block in OSL. The condition can be any valid expression; numeric values are true if nonzero, strings true if nonempty, closures true if empty. The else branch is optional. ```osl if (s > 0.5) { x = s; y = 1; } else { x = s+t; } ``` -------------------------------- ### for loop with local variable declaration Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Example of a for loop in OSL. The initialization may declare variables scoped locally to the loop. Loop conditions follow the same truthiness rules as if conditions. ```osl for (int i = 0; i < 3; ++i) { ... } ``` -------------------------------- ### Structure declaration and use Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Demonstrates how to define a structure type, declare structure variables, initialize them, and access fields using the dot operator. Also notes that structure fields cannot be other structures. ```osl struct ray { point pos; vector dir; }; ray r; // Declare a structure ray s = { point(0,0,0), vector(0,0,1) }; // declare and initialize r.pos = point (1, 0, 0); // Assign to one field ``` -------------------------------- ### Construct point, vector, and normal from floats Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to create point-like values using constructors with three float arguments. The values are interpreted in 'common' space by default. ```osl point (0, 2.3, 1) vector (a, b, c) normal (0, 0, 1) ``` -------------------------------- ### Scoping example with inner and outer variables Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Shows how variable scoping works in OSL. Variables declared inside a block are only visible within that block, and references resolve to the innermost scope. The example demonstrates that assigning 'b = a' uses the inner 'a', and referencing 'c' outside its scope causes an error. ```osl float a = 1; // Call this the "outer" 'a' float b = 2; { float a = 3; // Call this the "inner" 'a' float c = 1; b = a; // b gets 3, because a is resolved to the inner scope } b += c; // ERROR -- c was only in the inner scope ``` -------------------------------- ### String literal concatenation example Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows that two string literals separated only by whitespace are automatically concatenated into a single string literal. ```osl "foo" "bar" ``` -------------------------------- ### Operator Overloading Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html OSL allows operator overloading by defining functions with special names. This example shows how to overload the `+` operator for a custom struct. ```APIDOC ## Operator Overloading ### Description OSL permits operator overloading by defining functions with special names. This example shows how to overload the `+` operator for a custom struct. ### Example ``` struct vector4 { float x, y, z, w; }; vector4 __operator__add__ (vector4 a, vector4 b) { return vector4 (a.x+b.x, a.y+b.y, a.z+b.z, a.w+b.w); } shader test () { vector4 a = vector4 (.2, .3, .4, .5); vector4 b = vector4 (1, 2, 3, 4); vector4 c = a + b; // Will call __operator__add__(vector4,vector4) printf ("a+b = %g %g %g %g\n", c.x, c.y, c.z, c.w); } ``` ### Operator Overload Function Names | Operator | Overload function name | Notes | |----------|------------------------|-------| | `-` | `__operator__neg__` | unary negation | | `~` | `__operator__compl__` | unary bitwise | | `!` | `__operator__not__` | unary boolean 'not' | | `*` | `__operator__mul__` | | | `/` | `__operator__div__` | | | `%` | `__operator__mod__` | | | `+` | `__operator__add__` | | | `-` | `__operator__sub__` | | | `<<` | `__operator__shl__` | | | `>>` | `__operator__shr__` | | | `<` | `__operator__lt__` | | | `<=` | `__operator__le__` | | | `>` | `__operator__gt__` | | | `>=` | `__operator__ge__` | | | `==` | `__operator__eq__` | | | `!=` | `__operator__neq__` | | | `&` | `__operator__bitand__` | | | `^` | `__operator__xor__` | | | `|` | `__operator__bitor__` | | ``` -------------------------------- ### Point constructor with coordinate space Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Shows that `point (space, x, y, z)` is equivalent to `transform (space, "common", point(x,y,z))` for constructing point-like values in a named coordinate system. ```OSL point (space, x, y, z) ``` ```OSL transform (space, "common", point(x,y,z)) ``` -------------------------------- ### Valid and invalid OSL identifiers Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/lexical.html Shows examples of valid identifiers (opacity, Long_name42, _foo) and invalid ones (2smart, bigbuck$) with comments explaining why. ```osl opacity // valid Long_name42 // valid - letters, underscores, numbers are ok _foo // valid - ok to start with an underscore 2smart // invalid - starts with a numeral bigbuck$ // invalid - $ is an illegal character ``` -------------------------------- ### texture() and environment() Options Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Optional parameters for the texture() and environment() functions, including missingcolor, colorspace, alpha, and errormessage. ```APIDOC ## texture() and environment() Options ### Description Optional parameters that can be supplied to the texture() and environment() functions to control behavior for missing textures, color space, alpha channel storage, and error handling. ### Parameters - **"missingcolor"** (color) - Optional - Supplies a missing color (and alpha value) used for missing or broken textures instead of treating it as an error. If not supplied, missing textures are reported as errors. - **"missingalpha"** (float) - Optional - Supplies a missing alpha value used for missing or broken textures. - **"colorspace"** (string) - Optional - Specifies the color space of the data in the texture file. (Added in OSL 1.14.) - **"alpha"** (float variable) - Optional - The alpha channel (presumed to be the next channel following the channels returned by the environment() call) will be stored in the specified variable. Allows RGBA lookups in a single call. - **"errormessage"** (string variable) - Optional - If supplied, any error messages generated by the texture system will be stored in the specified variable rather than issuing error calls to the renderer. The error message will be "" if no error occurred. ``` -------------------------------- ### Construct matrix from two coordinate systems Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Constructs a matrix that transforms coordinates from the first named space to the second. The example returns the object-to-world transformation matrix. ```osl matrix m = matrix ("object", "world"); ``` -------------------------------- ### Constructing colors in OSL Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to create color values from RGB triples, other color spaces like "hsv", or a single float replicated to all channels. All expressions return colors in "rgb" space, with an implied transformation when specifying a non-RGB space. ```osl color (0, 0, 0) // black color ("rgb", .75, .5, .5) // pinkish color ("hsv", .2, .5, .63) // specify in "hsv" space color (0.5) // same as color (0.5, 0.5, 0.5) ``` -------------------------------- ### Construct matrix from scalar or 16 floats Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to create a matrix from a single float (0 or 1) and from 16 floats in row-major order. The single-float form sets diagonal components to that value and others to zero. ```osl matrix zero = 0; // makes a matrix with all 0 components matrix ident = 1; // makes the identity matrix // Construct a matrix from 16 floats matrix m = matrix (m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); ``` -------------------------------- ### printf Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Prints a formatted string to the console, similar to C's printf. ```APIDOC ## printf ### Description Much as in C, `printf` takes a format string `fmt` and an argument list, and prints the resulting formatted string to the console. The format string follows C printf conventions. ### Function Signature - `void printf(string fmt, ...)` ### Parameters - `fmt` (string) - Required - The format string. - `...` (variadic) - Optional - Arguments to be formatted according to `fmt`. ### Format Specifiers - `%d`, `%i`, `%o`, `%x` - Expect an `int` argument. - `%f`, `%g`, `%e` - Expect a `float`, `color`, point-like, or `matrix` argument. For multi-component types, the format is applied to each component. - `%s` - Expects a `string` or `closure` argument. ### Return Value - None (void). ``` -------------------------------- ### OSL Compound Initializer List for Structures Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Demonstrates compound initializer list syntax where the type is deduced from context, such as assignment, function return type, or expected argument type. ```osl RGBA c = {col,alpha}; // deduce by what is being assigned to RGBA add (RGBA a, RGBA b) { return { a.rgb+b.rgb, a.a+b.a }; // deduce by func return type } RGBA d = add (c, {{.3,.4,.5}, 0}); // deduce by expected arg type ``` -------------------------------- ### Array variable declarations Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/syntax.html Shows how to declare arrays in OSL. Arrays must have a constant length, except for function and shader parameters. The example includes an uninitialized array and an array with an initializer list. ```osl float d[10]; // Declare an uninitialized array float c[3] = { 0.1, 0.2, 3.14 }; // Initialize the array ``` -------------------------------- ### OSL Structure Constructor Expressions Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows constructor syntax for struct types, including direct construction, returning a constructed struct, and passing a constructor expression as a parameter. ```osl RGBA c = RGBA(col,alpha); // Constructor syntax RGBA add (RGBA a, RGBA b) { return RGBA (a.rgb+b.rgb, a.a+b.a); // return expression } // pass constructor expression as a parameter: RGBA d = add (c, RGBA(color(.3,.4,.5), 0)); ``` -------------------------------- ### transformu() unit conversion in displacement shader Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/bigpicture.html Example of a displacement shader that converts a bump distance from a specified unit to common units using transformu(). The shader is reusable across scenes with different modeling units. ```OSL displacement bumpy (float bumpdist = 1, string bumpunits = "cm") { // convert bumpdist to common units float spacing = transformu (bumpunits, "common", bumpdist); float n = noise (P / spacing); displace (n); } ``` -------------------------------- ### Accessing color components with array notation in OSL Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to read and write individual color components using the `[]` array access notation, where indices 0, 1, and 2 correspond to red, green, and blue. Accessing an index outside [0...2] is an error. ```osl color C; float g = C[1]; // get the green component C[0] = 0.5; // set the red component ``` -------------------------------- ### Access matrix components with array notation Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Shows how to read and write individual matrix components using row and column indices. Valid indices are integers from 0 to 3; accessing outside this range is an error. ```osl matrix M; float x = M[row][col]; M[row][col] = 1; ``` -------------------------------- ### Function with unsized array parameter Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/datatypes.html Demonstrates declaring an array parameter without a length using empty brackets, and using arraylength() inside the function. ```osl float sum (float x[]) { float s = 0; for (int i = 0; i < arraylength(x); ++i) s += x[i]; return s; } ``` -------------------------------- ### Compute a color closure with diffuse() Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/bigpicture.html Example of a surface shader computing a color closure. The texture lookup returns a numeric color, while diffuse() returns a color closure. The output variable Ci is also a color closure, not a definite numeric color. ```osl color paint = texture ("file.tx", u, v); Ci = paint * diffuse (N); ``` -------------------------------- ### Assemble shader group with renderer API Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/bigpicture.html Pseudo-code showing how to build a shader group with layers and connections using a renderer API. It creates texture, gamma, and wood shader layers and connects their parameters. ```pseudo-code ShaderGroupBegin () Shader ("texturemap", /* shader name */ "tex1", /* layer name */ "string name", "rings.tx") /* instance variable */ Shader ("texturemap", "tex2", "string name", "grain.tx") Shader ("gamma", "gam1", "float gam", 2.2) Shader ("gamma", "gam2", "float gam", 1) Shader ("wood", "wood1") ConnectShaders ("tex1", /* layer name A */ "Cout", /* an output parameter of A */ "gam1", /* layer name B */ "Cin") /* Connect this layer of B to A's Cout */ ConnectShaders ("tex2", "Cout", "gam2", "Cin") ConnectShaders ("gam1", "Cout", "wood1", "rings") ConnectShaders ("gam2", "Cout", "wood1", "grain") ShaderGroupEnd () ``` -------------------------------- ### matrix(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) Source: https://open-shading-language.readthedocs.io/en/v1.15.7.0/stdlib.html Constructs a matrix from 16 individual float values in row-major order. ```APIDOC ## matrix(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) ### Description Constructs a matrix from 16 individual float values, in row-major order. ### Parameters - **m00** (float) - Required - First component (row 0, column 0) - **m01** (float) - Required - Second component (row 0, column 1) - **m02** (float) - Required - Third component (row 0, column 2) - **m03** (float) - Required - Fourth component (row 0, column 3) - **m10** (float) - Required - Fifth component (row 1, column 0) - **m11** (float) - Required - Sixth component (row 1, column 1) - **m12** (float) - Required - Seventh component (row 1, column 2) - **m13** (float) - Required - Eighth component (row 1, column 3) - **m20** (float) - Required - Ninth component (row 2, column 0) - **m21** (float) - Required - Tenth component (row 2, column 1) - **m22** (float) - Required - Eleventh component (row 2, column 2) - **m23** (float) - Required - Twelfth component (row 2, column 3) - **m30** (float) - Required - Thirteenth component (row 3, column 0) - **m31** (float) - Required - Fourteenth component (row 3, column 1) - **m32** (float) - Required - Fifteenth component (row 3, column 2) - **m33** (float) - Required - Sixteenth component (row 3, column 3) ### Returns - **matrix** - The constructed matrix. ```