1% Copyright 2009-present Contributors to the Open Shading Language project. 2% SPDX-License-Identifier: CC-BY-4.0 3% SPDX-License-Identifier: BSD-3-Clause 4% https://github.com/AcademySoftwareFoundation/OpenShadingLanguage 5 6\documentclass[11pt,letterpaper]{book} 7\setlength{\oddsidemargin}{0.5in} 8\setlength{\topmargin}{0in} 9\setlength{\evensidemargin}{0.3in} 10\setlength{\textwidth}{5.75in} 11\setlength{\textheight}{8.5in} 12%\setlength{\oddsidemargin}{1.25in} 13%\setlength{\evensidemargin}{0.5in} 14 15% don't do this \usepackage{times} % Better fonts than Computer Modern 16\renewcommand{\sfdefault}{phv} 17\renewcommand{\rmdefault}{ptm} 18% don't replace tt -- old is better \renewcommand{\ttdefault}{pcr} 19%\usepackage{apalike} 20\usepackage{pslatex} 21\usepackage{techref} 22%\usepackage{epsfig} 23\usepackage{verbatim} 24\usepackage{moreverb} 25\usepackage{graphicx} 26\usepackage{xspace} 27%\usepackage{multicol} 28%\usepackage{color} 29\usepackage{hyperref} 30%\usepackage{version} 31\usepackage{makeidx} 32\usepackage[chapter]{algorithm} 33\floatname{algorithm}{Listing} 34 35\usepackage{syntax} 36 37\widowpenalty=1000 38\clubpenalty=1000 39 40\usepackage{fancyhdr} 41\pagestyle{fancy} 42\fancyhead[LE,RO]{\bfseries\thepage} 43\fancyhead[LO]{\bfseries\rightmark} 44\fancyhead[RE]{\bfseries\leftmark} 45\fancyfoot[C]{\bfseries Open Shading Language Specification} 46\renewcommand{\footrulewidth}{1pt} 47 48 49\def\langname{Open Shading Language\xspace} 50\def\product{{\sffamily Open Shading Language}\xspace} 51\def\versionnumber{1.11} 52\def\productver{\product\ {\sffamily \versionnumber}\xspace} 53 54 55\title{ 56{\Huge{\bf \product} 57%\textregistered\ 58{\bf\sffamily \versionnumber} \medskip \\ \huge 59Language Specification 60} \bigskip } 61\author{ 62\copyright\ Copyright 2009-present Contributors to the Open Shading Language project. \\ 63All rights reserved. 64 \bigskip \\ 65\vspace{1in} \\ 66Editor: Larry Gritz \\ 67\emph{lg@imageworks.com} 68} 69\date{{\large Date: 11 Aug 2020 \\ 70% (with corrections, 21 Jul 2020) 71} 72\bigskip 73\bigskip 74\bigskip 75\bigskip 76} 77 78 79 80\include{macros} 81 82\def\color{{\cf color}\xspace} 83\def\float{{\cf float}\xspace} 84\def\inttype{{\cf int}\xspace} 85\def\matrix{{\cf matrix}\xspace} 86\def\normal{{\cf normal}\xspace} 87\def\point{{\cf point}\xspace} 88\def\vector{{\cf vector}\xspace} 89\def\void{{\cf void}\xspace} 90\def\C{{\cf Ci}\xspace} 91\def\Ci{{\cf Ci}\xspace} 92%\def\opacity{{\cf Oi}\xspace} 93\def\Oi{{\cf Oi}\xspace} 94\def\I{{\cf I}\xspace} 95\def\N{{\cf N}\xspace} 96\def\Ng{{\cf Ng}\xspace} 97\def\P{{\cf P}\xspace} 98\def\dPdu{{\cf dPdu}\xspace} 99\def\dPdv{{\cf dPdv}\xspace} 100\def\commonspace{{\cf "common"} space\xspace} 101\def\shaderspace{{\cf "shader"} space\xspace} 102\def\worldspace{{\cf "world"} space\xspace} 103\def\cameraspace{{\cf "camera"} space\xspace} 104\def\objectspace{{\cf "object"} space\xspace} 105\def\rgbspace{{\cf "rgb"} space\xspace} 106\def\noise{{\cf noise()}\xspace} 107\def\snoise{{\cf snoise()}\xspace} 108\def\pnoise{{\cf pnoise()}\xspace} 109\def\psnoise{{\cf psnoise()}\xspace} 110\def\cellnoise{{\cf cellnoise()}\xspace} 111\def\hashnoise{{\cf hashnoise()}\xspace} 112\def\illuminance{{\cf illuminance}\xspace} 113\def\illuminate{{\cf illuminate}\xspace} 114 115\def\closure{{\cf closure}\xspace} 116\def\colorclosure{{\cf closure color}\xspace} 117\def\closurecolor{{\cf closure color}\xspace} 118\def\closurecolors{{\cf closure color}s\xspace} 119 120 121\makeindex 122 123\begin{document} 124\frontmatter 125 126\maketitle 127 128\newpage 129\label{speccopyr} 130 131\vspace*{0.2in} 132 133\noindent The Open Shading Language specification, source code, and 134documentation are: 135 136\vspace*{0.2in} 137 138Copyright \textcopyright\ 2009-present, Contributors to the Open Shading 139Language project. All Rights Reserved. 140 141\vspace{0.5in} 142 143The code that implements Open Shading Language is licensed under 144the BSD 3-clause (also sometimes known as ``new BSD'') license: 145 146\vspace{0.25in} 147 148Redistribution and use in source and binary forms, with or without 149modification, are permitted provided that the following conditions are 150met: 151 152\begin{itemize} 153\item Redistributions of source code must retain the above copyright 154 notice, this list of conditions and the following disclaimer. 155\item Redistributions in binary form must reproduce the above copyright 156 notice, this list of conditions and the following disclaimer in the 157 documentation and/or other materials provided with the distribution. 158\item Neither the name of the copyright holder nor the names of its 159 contributors may be used to endorse or promote products derived from 160 this software without specific prior written permission. 161\end{itemize} 162 163THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 164"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 165LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 166A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 167OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 168SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 169LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 170DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 171THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 172(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 173OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 174 175 176\vspace{0.5in} 177 178This specification and other text documentation about Open Shading 179Language is licensed under a the Creative Commons Attribution 4.0 180Unported License. \\ 181 182\smallskip 183\spc \includegraphics[width=0.85in]{Figures/CC-BY.png} 184\spc http://creativecommons.org/licenses/by/4.0/ 185 \bigskip 186 187 188 189\newpage 190 191 192 193 194\setcounter{tocdepth}{1} 195\tableofcontents 196 197\mainmatter 198 199%\part{Part name} 200 201%\include{blah} 202 203 204\chapter{Introduction} 205\label{chap:intro} 206 207 208Welcome to Open Shading Language! 209 210\vspace*{0.2in} 211 212Open Shading Language (OSL) is a small but rich language for 213programmable shading in advanced renderers and other applications, ideal 214for describing materials, lights, displacement, and pattern generation. 215 216OSL was developed by Sony Pictures Imageworks for use in its in-house 217renderer used for feature film animation and visual effects. The 218language specification was developed with input by other visual effects 219and animation studios who also wish to use it. 220 221OSL is distributed under the ``New BSD'' license. In short, you are free 222to use it in your own applications, whether they are free or commercial, 223open or proprietary, as well as to modify the OSL code as you desire, 224provided that you retain the original copyright notices as described in 225the license. 226 227 228\section*{How OSL is different from other shading languages} 229 230OSL has syntax similar to C, as well as other shading languages. 231However, it is specifically designed for advanced rendering algorithms 232and has features such as radiance closures, BSDFs, and deferred ray 233tracing as first-class concepts. 234 235OSL has several unique characteristics not found in other shading 236languages (certainly not all together). Here are some things you will 237find are different in OSL compared to other languages: 238 239\subsubsection*{Surface and volume shaders compute radiance closures, not final colors.} 240 241 OSL's surface and volume shaders compute an explicit symbolic 242 description, called a ``closure,'' of the way a surface or volume 243 scatters light, in units of radiance. These radiance closures may be 244 evaluated in particular directions, sampled to find important 245 directions, or saved for later evaluation and re-evaluation. 246 This new approach is ideal for a physically-based renderer that 247 supports ray tracing and global illumination. 248 249 In contrast, other shading languages usually compute just a surface 250 color as visible from a particular direction. These old shaders are 251 ``black boxes'' that a renderer can do little with but execute to for 252 this once piece of information (for example, there is no effective way 253 to discover from them which directions are important to sample). 254 Furthermore, the physical units of lights and surfaces are often 255 underspecified, making it very difficult to ensure that shaders are 256 behaving in a physically correct manner. 257 258\subsubsection*{Surface and volume shaders do not loop over lights or shoot rays.} 259 260 There are no ``light loops'' or explicitly traced rays in OSL surface 261 shaders. Instead, surface shaders compute a radiance closure 262 describing how the surface scatters light, and a part of the renderer 263 called an ``integrator'' evaluates the closures for a particular set of 264 light sources and determines in which directions rays should be 265 traced. Effects that would ordinarily require explicit ray tracing, 266 such as reflection and refraction, are simply part of the radiance 267 closure and look like any other BSDF. 268 269 Advantages of this approach include that integration and sampling may 270 be batched or re-ordered to increase ray coherence; a ``ray budget'' can 271 be allocated to optimally sample the BSDF; the closures may be used by 272 for bidirectional ray tracing or Metropolis light transport; and the 273 closures may be rapidly re-evaluated with new lighting without having 274 to re-run the shaders. 275 276\subsubsection*{Surface and light shaders are the same thing.} 277 278 OSL does not have a separate kind of shader for light sources. Lights 279 are simply surfaces that are emissive, and all lights are area lights. 280 281\subsubsection*{Transparency is just another kind of illumination.} 282 283 You don't need to explicitly set transparency/opacity variables in the 284 shader. Transparency is just another way for light to interact with a 285 surface, and is included in the main radiance closure computed by a 286 surface shader. 287 288\subsubsection*{Renderer outputs (AOV's) are specified using ``light path expressions.''} 289 290 Sometimes it is desirable to output images containing individual 291 lighting components such as specular, diffuse, reflection, individual 292 lights, etc. In other languages, this is usually accomplished by 293 adding a plethora of ``output variables'' to the shaders that collect 294 these individual quantities. 295 296 OSL shaders need not be cluttered with any code or output variables to 297 accomplish this. Instead, there is a regular-expression-based 298 notation for describing which light paths should contribute to which 299 outputs. This is all done on the renderer side (though supported by 300 the OSL implementation). If you desire a new output, there is no need 301 to modify the shaders at all; you only need to tell the renderer the 302 new light path expression. 303 304\subsubsection*{Shaders are organized into networks.} 305 306 OSL shaders are not monolithic, but rather can be organized into 307 networks of shaders (sometimes called a shader group, graph, or DAG), 308 with named outputs of some nodes being connected to named inputs of 309 other nodes within the network. These connections may be done 310 dynamically at render time, and do not affect compilation of 311 individual shader nodes. Furthermore, the individual nodes are 312 evaluated lazily, only their outputs are ``pulled'' from the later nodes 313 that depend on them (shader writers may remain blissfully unaware of 314 these details, and write shaders as if everything is evaluated 315 normally). 316 317\subsubsection*{No ``uniform'' and ``varying'' keywords in the language.} 318 319 OSL shaders are evaluated in SIMD fashion, executing shaders on many 320 points at once, but there is no need to burden shader writers with 321 declaring which variables need to be uniform or varying. 322 323 In the open source OSL implementation, this is done both automatically 324 and dynamically, meaning that a variable can switch back and forth 325 between uniform and varying, on an instruction-by-instruction basis, 326 depending on what is assigned to it. 327 328\subsubsection*{Arbitrary derivatives without grids or extra shading points.} 329 330 In OSL, you can take derivatives of any computed quantity in a shader, 331 and use arbitrary quantities as texture coordinates and expect correct 332 filtering. This does not require that shaded points be arranged in a 333 rectangular grid, or have any particular connectivity, or that any 334 "extra points" be shaded. 335 336 In the open source OSL implementation, this is possible because 337 derivatives are not computed by finite differences with neighboring 338 points, but rather by ``automatic differentiation,'' computing partial 339 differentials for the variables that lead to derivatives, without any 340 intervention required by the shader writer. 341 342 343\vspace{0.5in} 344 345 346\section*{Acknowledgments} 347 348The original designer and project leader of OSL is Larry Gritz. Other early 349developers of OSL are (in order of joining the project): Cliff Stein, Chris 350Kulla, Alejandro Conty, Jay Reynolds, Solomon Boulos, Adam Martinez, Brecht 351Van Lommel. 352 353Additionally, many others have contributed features, bug fixes, and other 354changes: Steve Agland, Shane Ambler, Martijn Berger, Farchad Bidgolirad, 355Nicholas Bishop, Stefan Büttner, Matthaus G. Chajdas, Thomas Dinges, Henri 356Fousse, Syoyo Fujita, Derek Haase, Sven-Hendrik Haase, John Haddon, Daniel 357Heckenberg, Ronan Keryell, Elvic Liang, Max Liani, Bastien Montagne, Erich 358Ocean, Mikko Ohtamaa, Alex Schworer, Sergey Sharybin, Stephan Steinbach, 359Esteban Tovagliari, Alexander von Knorring, Roman Zulak. (Listed 360alphabetically; if we've left anybody out, please let us know.) 361 362We cannot possibly express sufficient gratitude to the managers at Sony 363Pictures Imageworks who allowed this project to proceed, supported it 364wholeheartedly, and permitted us to release the source, especially Rob 365Bredow, Brian Keeney, Barbara Ford, Rene Limberger, and Erik Strauss. 366 367Huge thanks also go to the crack shading team at SPI, and the brave 368lookdev TDs and CG supes willing to use OSL on their shows. They served 369as our guinea pigs, inspiration, testers, and a fantastic source of 370feedback. Thank you, and we hope we've been responsive to your needs. 371 372OSL was not developed in isolation. We owe a debt to the individuals 373and studios who patiently read early drafts of the language 374specification and gave us very helpful feedback and additional ideas, 375and especially to those at other companies who have taken the risk of 376incorporating OSL into their products and pipelines. 377 378\bigskip 379The open source OSL implementation incorporates or depends upon several 380other open source packages: 381 382\begin{itemize} 383\item {\cf OpenImageIO} \copyright\ 2008 Larry Gritz et al. 384\url{http://openimageio.org} 385\item Ilmbase \copyright\ 2006, Industrial Light \& Magic. 386\url{http://www.openexr.com} 387\item Boost \copyright\ various authors. \url{http://www.boost.org} 388\item LLVM \copyright\ 2003-2010 University of Illinois at 389 Urbana-Champaign. \url{http://llvm.org} 390\end{itemize} 391 392These other packages are all distributed under licenses that allow them 393to be used by and distributed with \product. 394 395\bigskip 396 397% \section*{Annotations} 398% 399% \begin{annotate} 400% When you see text in this style, it's an annotation. These annotations 401% will not be in the final draft of this document. They are notes to the 402% readers of early drafts, sometimes questions, sometimes guideposts 403% to uncertain areas, sometimes explanations of what is to come but that 404% has not yet been fully fleshed out. 405% 406% \begin{comment} 407% Short annotations will sometimes spring up anywhere, but there's also a 408% full chapter of discussion of design choices 409% (Chapter~\ref{chap:discussion}). Opinionated readers should pay 410% particular attention to this chapter, as these big decisions will be the 411% hardest to change later. 412%\end{comment} 413% \end{annotate} 414 415 416\chapter{The Big Picture} 417\label{chap:shaderstructure} 418\label{chap:bigpicture} 419 420This chapter attempts to lay out the major concepts of \langname, 421define key nomenclature, and sketch out how individual shaders fit 422together in the context of a renderer as a whole. 423 424% \begin{annotate} 425% Other than the background material of this chapter, the rest of this 426% specification deals strictly with the language itself. In the future, 427% there will be separate (shorter) documents explaining in detail the use 428% of the language compiler, the renderer-side issues, the library and APIs 429% for how a renderer actually causes shaders to be evaluated, and so on. 430% \end{annotate} 431 432\subsection*{A shader is code that performs a discrete task} 433 434A shader is a program, with inputs and outputs, that performs a specific 435task when rendering a scene, such as determining the appearance behavior 436of a material or light. The program code is written in \langname, the 437specification of which comprises this document. 438 439For example, here is a simple {\cf gamma} shader that performs 440simple gamma correction on is {\cf Cin} input, storing the result 441in its output {\cf Cout}: 442\bigskip 443 444\includegraphics{Figures/shaderschematic} 445 446\medskip 447 448The shader's inputs and outputs are called \emph{shader parameters}. 449Parameters have default values, specified in the shader code, but may 450also be given new values by the renderer at runtime. 451 452\subsection*{Shader instances} 453 454A particular shader may be used many times in a scene, on different 455objects or as different layers in a shader group. Each separate use of 456a shader is called a \emph{shader instance}. Although all instances of 457a shader are comprised of the same program code, each instance may 458override any or all of its default parameter values with its own set of 459\emph{instance values}. 460 461Below is a 462schematic showing a {\cf gamma} instance with the {\cf gam} parameter 463overridden with an instance-specific value of {\cf 2.2}. 464 465\bigskip 466 467\bigspc\spc \includegraphics{Figures/instanceschematic} 468 469\medskip 470 471 472 473\subsection*{Shader groups, layers, and connections} 474 475A \emph{shader group}\index{shader group} is an ordered sequence of 476individual shaders called \emph{layers}\index{layer}\index{shader layer} 477that are executed in turn. Output parameters of an earlier-executed layer 478may be \emph{connected} to an input parameter of a later-executed layer. 479This connected network of layers is sometimes called a \emph{shader network} 480or a \emph{shader DAG} (directed acyclic graph). Of course, it is fine for 481the shader group to consist of a single shader layer. 482 483Below is a schematic showing how several shader instances may be 484connected to form a shader group. 485 486\bigskip 487 488\noindent \includegraphics{Figures/groupschematic} 489 490\bigskip 491 492\noindent And here is sample pseudo-code shows how the above network may 493be assembled using an API in the renderer\footnote{This document does 494not dictate a specific renderer API for declaring shader instances, 495groups, and connections; the code above is just an example of how 496it might be done.}: 497 498\begin{code} 499 ShaderGroupBegin () 500 Shader ("texturemap", /* shader name */ 501 "tex1", /* layer name */ 502 "string name", "rings.tx") /* instance variable */ 503 Shader ("texturemap", "tex2", "string name", "grain.tx") 504 Shader ("gamma", "gam1", "float gam", 2.2) 505 Shader ("gamma", "gam2", "float gam", 1) 506 Shader ("wood", "wood1") 507 ConnectShaders ("tex1", /* layer name A */ 508 "Cout", /* an output parameter of A */ 509 "gam1", /* layer name B */ 510 "Cin") /* Connect this layer of B to A's Cout */ 511 ConnectShaders ("tex2", "Cout", "gam2", "Cin") 512 ConnectShaders ("gam1", "Cout", "wood1", "rings") 513 ConnectShaders ("gam2", "Cout", "wood1", "grain") 514 ShaderGroupEnd () 515\end{code} 516 517\noindent Or, expressed as serialized text (as detailed in 518Chapter~\ref{sec:serialize}): 519 520\begin{code} 521 param string name "rings.tx" ; 522 shader "texturemap" "tex1" ; 523 param string name "grain.tx" ; 524 shader "texturemap" "tex2" ; 525 param float gam 2.2 ; 526 shader "gamma" "gam1" ; 527 param float gam 1.0 ; 528 shader "gamma" "gam2" ; 529 shader "wood" "wood1" ; 530 connect tex1.Cout gam1.Cin ; 531 connect tex2.Cout gam2.Cin ; 532 connect gam1.Cout wood1.rings ; 533 connect gam2.Cout wood1.grain ; 534\end{code} 535 536The rules for which data types may be connected are generally the same as 537the rules determining which variables may be assigned to each other in OSL 538source code: 539\begin{itemize} 540\item {\cf source} and {\cf dest} are the same data type. 541\item {\cf source} and {\cf dest} are both \emph{triples} (\color, \point, 542\vector, or \normal), even if they are not the same kind of triple. 543\item {\cf source} is an {\cf int} and {\cf dest} is a {\cf float}. 544\item {\cf source} is a {\cf float} or {\cf int} and {\cf dest} is a 545\emph{triple} (the scalar value will be replicated for all three components 546of the triple). 547\item {\cf source} is a single component of an aggregate type (e.g. one 548channel of a {\cf color}) and {\cf dest} is a {\cf float} (or vice versa). 549\end{itemize} 550 551\subsection*{Geometric primitives} 552 553The \emph{scene} consists of primarily of geometric primitives, 554light sources, and cameras. 555 556\emph{Geometric primitives} are shapes such as NURBS, subdivision surfaces, 557polygons, and curves. The exact set of supported primitives may vary 558from renderer to renderer. 559 560Each geometric primitive carries around a set of named \emph{primitive 561variables} (also sometimes called \emph{interpolated values} or 562\emph{user data}). Nearly all shape types will have, among their primitive 563variables, control point positions that, when interpolated, actually 564designate the shape. Some shapes will also allow the specification of 565normals or other shape-specific data. Arbitrary user data may also be 566attached to a shape as primitive variables. Primitive variables may be 567interpolated in a variety of ways: one constant value per primitive, one 568constant value per face, or per-vertex values that are interpolated 569across faces in various ways. 570 571If a shader input parameter's name and type match the name and type 572of a primitive variable on the object (and that input parameters is 573not already explicitly connected to another layer's output), the 574interpolated primitive variable will override the instance value or 575default. 576 577 578\subsection*{Attribute state and shader assignments} 579 580Every geometric primitive has a collection of \emph{attributes} (sometimes 581called the \emph{graphics state}) that includes its transformation 582matrix, the list of which lights illuminate it, whether it is one-sided 583or two-sided, shader assignments, etc. There may also be a long list of 584renderer-specific or user-designated attributes associated with each 585object. A particular attribute state may be shared among many geometric 586primitives. 587 588The attribute state also includes shader assignments --- the shaders or 589shader groups for each of several \emph{shader uses}, such as surface 590shaders that designate how light reflects or emits from each point on a shape, 591displacement shaders that can add fine detail to the shape on a 592point-by-point basis, and volume shaders that describe how light is 593scattered within a region of space. A particular renderer may have 594additional shader types that it supports. 595 596 597\subsection*{Shader execution state: parameter binding and global variables} 598 599When the body of code of an individual shader is about to execute, all 600its parameters are \emph{bound} --- that is, take on specific values 601(from connections from other layers, interpolated primitive variables, 602instance values, or defaults, in that order). 603 604Certain state about the position on the surface where the shading is 605being run is stored in so-called \emph{global variables}. This includes 606such useful data as the 3D coordinates of the point being shaded, the 607surface normal and tangents at that point, etc. 608 609Additionally, the shader may query other information about other 610elements of the attribute state attached to the primitive, and 611information about the renderer as a whole (rendering options, etc.). 612 613\subsection*{Surface and volume shaders compute closures} 614 615Surface shaders (and volume shaders) do not by themselves compute the 616final color of light emanating from the surface (or along a volume). 617Rather, they compute a \emph{closure}, which is a symbolic representation 618describing the appearance of the surface, that may be more fully 619evaluated later. This is in effect a parameterized formula, in which 620some inputs have definite numeric values, but others may depend on 621quantities not yet known (such as the direction from which the surface 622is being viewed, and the amount of light from each source that is 623arriving at the surface). 624 625For example, a surface shader may compute its result like this: 626 627\begin{code} 628 color paint = texture ("file.tx", u, v); 629 Ci = paint * diffuse (N); 630\end{code} 631 632\noindent In this example, the variable {\cf paint} will take on a 633specific numeric value (by looking up from a texture map). But the {\cf 634 diffuse()} function returns a \colorclosure, not a definite numeric 635\color. The output variable {\cf Ci} that represents the appearance of 636the surface is also a \colorclosure, whose numeric value is not known 637yet, except that it will be the product of {\cf paint} and a Lambertian 638reflectance. 639 640\bigskip 641 642\includegraphics{Figures/shaderexecschematic} 643 644\medskip 645 646The closures output by surface and volume shaders can do a number of 647interesting things that a mere number cannot: 648 649\begin{itemize} 650\item Evaluate: given input and output light directions, compute the 651 proportion of light propagating from input to output. 652\item Sample: given just an input (or output) direction, choose a 653 scattering direction with a probability distribution that is 654 proportional to the amount of light that will end up going in various 655 directions. 656\item Integrate: given all lights and a view direction, compute 657 the total amount of light leaving the surface in the view direction. 658\item Recompute: given changes only to lights (or only to one light), 659 recompute the integrated result without recomputing other lights or 660 any of the calculations that went into assembling constants in the 661 closure (such as texture lookups, noise functions, etc.). 662\end{itemize} 663 664% \begin{annotate} 665% At present, we are assuming that the primitive closure functions (such 666% as {\cf diffuse}, {\cf ward}, {\cf cooktorrance}, etc.) are all built 667% into the renderer, or implemented as renderer plugins. At a later time, 668% possibly in a later draft or maybe not until a truly later version of 669% the spec, we will fully spec it out so that closure primitive functions 670% may be written in \langname. But I fear that if we do it too soon, 671% we'll screw it up. But, yes, the eventual goal is for you to be able to 672% write these primitive functions in the language itself. 673% \end{annotate} 674 675\subsection*{Integrators} 676 677The renderer contains a number of \emph{integrators} (selectable via the 678renderer's API) which will combine the color closures computed by 679surfaces and volumes with the light sources and view-dependent 680information, to yield the amount of light visible to the camera. 681 682\bigskip 683 684\includegraphics{Figures/integratorschematic} 685 686\medskip 687 688% \begin{annotate} 689% At present, this document is written as if the integrators are built 690% into the renderer itself (or implemented as renderer plug-ins). At a 691% later time, we intend to make it possible for integrators themselves 692% to be written in \langname. 693% \end{annotate} 694 695\subsection*{Units} 696 697You can tell the renderer (through a global option) what units the scene 698is using for distance and time. Then the shader has a built-in function 699called {\cf transformu()} that works a lot like {\cf transform()}, but 700instead of converting between coordinate systems, it converts among 701units. For example, 702 703\begin{code} 704 displacement bumpy (float bumpdist = 1, 705 string bumpunits = "cm") 706 { 707 // convert bumpdist to common units 708 float spacing = transformu (bumpunits, "common", bumpdist); 709 float n = noise (P / spacing); 710 displace (n); 711 } 712\end{code} 713 714So you can write a shader to achieve some effect in real world units, 715and that shader is totally reusable on another show that used different 716modeling units. 717 718It knows all the standard names like \qkw{cm}, \qkw{in}, \qkw{km}, 719etc., and can convert among any of those, as well as between named 720coordinate systems. For example, 721 722\begin{code} 723 float x = transformu ("object", "mm", 1); 724\end{code} 725 726now {\cf x} is the number of millimeters per unit of \objectspace on 727that primitive. 728 729 730\chapter{Lexical structure} 731\label{chap:lexical} 732 733\section{Characters} 734\label{sec:lexical:chars} 735\index{character set} 736 737Source code for \langname consists of ASCII or UTF-8 characters. 738 739The characters for space, tab, carriage return, and linefeed are 740collectively referred to as \emph{whitespace}. Whitespace characters 741delimit identifiers, keywords, or other symbols, but other than that 742have no syntactic meaning. Multiple whitespace characters in a row 743are equivalent to a single whitespace character. \index{whitespace} 744 745Source code may be split into multiple lines, separated by end-of-line 746markers (carriage return and/or linefeed). Lines may be of any length 747and end-of-line markers carry no significant difference from other 748whitespace, except that they terminate {\cf //} comments and delimit 749preprocessor directives. 750 751\section{Identifiers} 752\label{sec:identifiers} 753\index{identifiers} 754 755\emph{Identifiers} are the names of variables, parameters, functions, 756and shaders. In \langname, identifiers consist of one or more 757characters. The first character may be a letter ({\cf A}-{\cf Z} or 758{\cf a}-{\cf z}) or underscore (\verb|_|), and subsequent characters may 759be letters, underscore, or numerals ({\cf 0}-{\cf 9}). Examples of 760valid and invalid identifiers are: 761 762\begin{code} 763 opacity // valid 764 Long_name42 // valid - letters, underscores, numbers are ok 765 _foo // valid - ok to start with an underscore 766 767 2smart // invalid - starts with a numeral 768 bigbuck$ // invalid - $ is an illegal character 769\end{code} 770 771 772\section{Comments} 773\label{sec:comments} 774\index{comments} 775 776\emph{Comments} are text that are for the human reader of programs, and 777are ignored entirely by the \langname compiler. Just like in C++, there 778are two ways to designate comments in \langname: 779 780\begin{enumerate} 781\item Any text enclosed by {\cf /*} and {\cf */} will be considered 782a comment, even if the comment spans several lines. 783 784\begin{code} 785 /* this is a comment */ 786 787 /* this is also 788 a comment, spanning 789 several lines */ 790\end{code} 791 792\item Any text following {\cf //}, up to the end of the current line, 793will be considered a comment. 794 795\begin{code} 796 // This is a comment 797 a = 3; // another comment 798\end{code} 799\end{enumerate} 800 801 802\section{Keywords and reserved words} 803\label{sec:lexical:keyreserved} 804 805There are two sets of names that you may not use as identifiers: 806keywords and reserved words. 807 808The following are \emph{keywords} that have special meaning in 809\langname: \index{keywords} 810 811\begin{quote} {\cf 812 813and break closure color continue do else emit float for if illuminance 814illuminate int matrix normal not or output point public return string struct 815vector void while 816 817} 818\end{quote} 819 820The following are \emph{reserved words} that currently have no special 821meaning in \langname, but we reserve them for possible future use, or 822because they are confusingly similar to keywords in related programming 823languages: \index{reserved words} 824 825\begin{quote} {\cf 826 827bool case catch char class const delete default double 828enum extern false friend 829goto inline long new operator private protected 830short signed sizeof static 831switch template this throw true try typedef 832uniform union unsigned varying virtual volatile 833 834} 835\end{quote} 836 837 838\section{Preprocessor} 839\label{sec:preprocessor} 840\index{preprocessor} \index{C preprocessor|see{preprocessor}} 841\indexapi{\#define} 842\indexapi{\#undef} 843\indexapi{\#if} 844\indexapi{\#ifdef} 845\indexapi{\#ifndef} 846\indexapi{\#elif} 847\indexapi{\#else} 848\indexapi{\#endif} 849\indexapi{\#include} 850\indexapi{\#pragma} 851 852Shader source code is passed through a standard C preprocessor as a 853first step in parsing. 854 855Preprocessor directives are designated by a hash mark ({\cf \#}) as the 856first character on a line, followed by a preprocessor directive name. 857Whitespace may optionally appear between the hash and the directive 858name. 859 860\langname compilers support the full complement of C/C++ preprocessing 861directives, including: 862 863\begin{code} 864 #define 865 #undef 866 #if 867 #ifdef 868 #ifndef 869 #elif 870 #else 871 #endif 872 #include 873 #pragma once 874\end{code} 875 876\noindent Additionally, the following preprocessor symbols will already be 877defined by the compiler: 878 879\smallskip 880 881\begin{tabular}{p{1.5in} p{3.5in}} 882{\cf OSL_VERSION_MAJOR} & Major version (e.g., 1) \\[0.5ex] 883{\cf OSL_VERSION_MINOR} & Minor version (e.g., 9) \\[0.5ex] 884{\cf OSL_VERSION_PATCH} & Patch version (e.g., 3) \\[0.5ex] 885{\cf OSL_VERSION} & Combined version number = 10000*major + 100*minor + patch 886(e.g., 10903 for version 1.9.3) 887\end{tabular} 888 889 890\chapter{Gross syntax, shader types, parameters} 891\label{chap:grosssyntax} 892 893The overall structure of a shader is as follows: 894\medskip 895 896\begin{quote} 897\em 898optional-function-or-struct-declarations \\ 899 900shader-type shader-name {\cf (} optional-parameters {\cf )} \\ 901\rm 902{\cf \{ } \\ 903\em 904\spc statements 905 906{\cf \} } 907\end{quote} 908 909Note that \emph{statements} may include function or structure 910definitions, local variable declarations, or public methods, as well as 911ordinary execution instructions (such as assignments, etc.). 912 913\section{Shader types} 914\label{sec:shadertypes} 915\index{shader types} \index{types!shader} 916 917Shader types include the following: {\cf surface}, {\cf displacement}, 918{\cf light}, {\cf volume}, and generic {\cf shader}. Some operations 919may only be performed from within certain types of shaders (e.g., one 920may only call {\cf displace()} or alter \P in a displacement shader), 921and some global variables may only be accessed from within certain types 922of shaders (e.g., {\cf dPdu} is not defined inside a volume shader). 923 924Following are brief descriptions of the basic types of shaders: 925 926 927\subsection*{{\cf surface} shaders} 928 929Surface shaders determine the basic material properties of a surface and 930how it reacts to light. They are responsible for computing a 931\colorclosure that describes the material, and optionally setting 932other user-defined output variables. They may not alter 933the position of the surface. 934 935Surface shaders are written as if they describe the behavior of a single 936point on the primitive, and the renderer will choose the positions 937surface at which the shader must be evaluated. 938 939Surface shaders also are used to describe emissive objects, i.e., light 940sources. OSL does not need a separate shader type to describe lights. 941 942\subsection*{{\cf displacement} shaders} 943 944Displacement shaders alter the position and shading normal (or, 945optionally, just the shading normal) to make a piece of geometry appear 946deformed, wrinkled, or bumpy. They are the only kind of shader that 947is allowed to alter a primitive's position. 948 949\subsection*{{\cf volume} shaders} 950 951Volume shaders describe how a participating medium (air, smoke, glass, 952etc.) reacts to light and affects the appearance of objects on the other 953side of the medium. They are similar to {\cf surface} shaders, except 954that they may be called from positions that do not lie upon (and are not 955necessarily associated with) any particular primitive. 956 957 958 959\subsection*{{\cf shader} generic shaders} 960 961Generic shaders are used for utility code, generic routines that may be 962called as individual layers in a shader group. Generic shaders need not 963specify a shader type, and therefore may be reused from inside surface, 964displacement, or volume shader groups. But as a result, they may 965not contain any functionality that cannot be performed from inside all 966shader types (for example, they may not alter \P, which can only be done 967from within a displacement shader). 968 969 970\section{Shader parameters} 971\label{sec:shaderparams} 972\index{shader parameters} \index{parameters!shader} 973 974An individual shader has (optionally) many \emph{parameters} whose 975values may be set in a number of ways so that a single shader may have 976different behaviors or appearances when used on different objects. 977 978\subsection{Shader parameter syntax} 979 980Shader parameters are specified in the shader declaration, in 981parentheses after the shader's name. This is much like the parameters 982to an OSL function (or a function in C or similar languages), 983except that shader parameters must have an \emph{initializer}, giving a 984default value for the parameter. Shader parameter default initializers 985may be expressions (i.e., may be computed rather than restricted to 986numeric constants), and are evaluated in the order that the parameters 987are declared, and may include references to previously-declared 988parameters. Formally, the grammar for a simple parameter 989declaration looks like this: 990 991\medskip 992\spc \emph{type parametername = default-expression} 993\medskip 994 995\noindent where \emph{type} is one of the data types described 996in Chapter~\ref{chap:types}, \emph{parametername} is the name of the 997parameter, and \emph{default-expression} is a valid expression 998(see Section~\ref{sec:expressions}). Multiple parameters are 999simply separated by commas: 1000 1001\medskip 1002\spc \emph{type1 ~ parameter1 = expr1} {\cf ,} \emph{type2 ~ parameter2 = expr2} {\cf ,} ... 1003\medskip 1004 1005 1006Fixed-length, one-dimensional array parameters are declared as follows: 1007 1008\medskip 1009\spc \emph{type parametername} {\cf [ } \emph{array-length} {\cf ] = \{ } \emph{expr0} 1010 {\cf ,} \emph{expr1} ... {\cf \} } 1011\medskip 1012 1013\noindent where \emph{array-length} is a positive integer constant 1014giving the length of the array, and the initializer is a series of 1015initializing expressions listed between curly braces. The first 1016initializing expression provides the initializer for the first element 1017of the array, the second expression provides the initializer for the 1018second element of the array, and so on. If the number of initializing 1019expressions is less than the length of the array, any additional array 1020elements will have undefined values. 1021 1022Arrays may also be declared without a set length: 1023 1024\medskip 1025\spc \emph{type parametername} {\cf [ ] = \{ } \emph{expr0} 1026 {\cf ,} \emph{expr1} ... {\cf \} } 1027\medskip 1028 1029\noindent where no array length is found between the square brackets. 1030This indicates that the array's length will be determined based on 1031whatever is passed in --- a connection from the output of another shader 1032in the group (take on the length of that output), an instance value 1033(take on the length specified by the declaration of the instance value), 1034or a primitive variable (length determined by its declaration on the 1035primitive). If no instance value, primitive value, or connection is 1036supplied, then the number of initializing expressions will determine the 1037length, as well as the default values, of the array. 1038 1039Structure parameters are also straightforward to declare: 1040 1041\medskip 1042\spc \emph{structure-type parametername} {\cf = \{ } \emph{expr0} 1043 {\cf ,} \emph{expr1} ... {\cf \} } 1044\medskip 1045 1046\noindent where \emph{structure-type} is the name of a 1047previously-declared {\cf struct} type, and the \emph{expr} initializers 1048correspond to each respective field within the structure. An 1049initializer of appropriate type is required for every field of the 1050structure. 1051 1052\subsection{Shader output parameters} 1053\index{shader output parameters} \index{output parameters!shader} 1054 1055Shader parameters are, by default, read-only in the body of the 1056shader. However, special \emph{output parameters} may be altered 1057by execution of the shader. Parameters may be designated outputs 1058by use of the {\cf output} keyword immediately prior to the 1059type declaration of the parameter: 1060 1061\medskip 1062\spc {\cf output} \emph{type parametername} {\cf = } \emph{expr} 1063\medskip 1064 1065\noindent (Output parameters may be arrays and structures, but we will 1066omit spelling out the obvious syntax here.) 1067 1068Output parameters may be connected to inputs of later-run shader layers 1069in the shader group, may be queried by later-run shaders in the group 1070via message passing (i.e., {\cf getmessage()} calls), or used by the 1071renderer as an output image channel (in a manner described through the 1072renderer's API). 1073 1074\subsection{Shader parameter example} 1075 1076Here is an example of a shader declaration, with several parameters: 1077 1078\begin{code} 1079 surface wood ( 1080 /* Simple params with constant initializers */ 1081 float Kd = 0.5, 1082 color woodcolor = color (.7, .5, .3), 1083 string texturename = "wood.tx", 1084 /* Computed from an earlier parameter */ 1085 color ringcolor = 0.25 * woodcolor, 1086 /* Fixed-length array */ 1087 color paintcolors[3] = { color(0,.25,0.7), color(1,1,1), 1088 color(0.75,0.5,0.2) }, 1089 /* variable-length array */ 1090 int pattern[] = { 2, 4, 2, 1 }, 1091 /* output parameter */ 1092 output color Cunlit = 0 1093 ) 1094 { 1095 ... 1096 } 1097\end{code} 1098 1099\subsection{How shader parameters get their values} 1100 1101Shader parameters get their values in the following manner, 1102in order of decreasing priority: 1103 1104\begin{itemize} 1105\item If the parameter has been designated by the renderer to be 1106 connected to an output parameter of a previously-executed shader layer 1107 within the shader group, that is the value it will get. 1108\item If the parameter matches the name and type of a per-primitive, 1109 per-face, or per-vertex \emph{primitive variable} on the particular 1110 piece of geometry being shaded, the parameter's value will be computed 1111 by interpolating the primitive variable for each position that must be 1112 shaded. 1113\item If there is no connection or primitive variable, the parameter may 1114 will take on an \emph{instance value}, if that parameter was given an 1115 explicit per-instance value at the time that the renderer referenced 1116 the shader (associating it with an object or set of objects). 1117\item If none of these overrides is present, the parameter's value will 1118 be determined by executing the parameter initialization code in the 1119 shader. 1120\end{itemize} 1121 1122This triage is performed per parameter, in order of declaration. So, 1123for example, in the code sample above where the default value for {\cf 1124 ringcolor} is a scaled version of {\cf woodcolor}, this relationship 1125would hold whether {\cf woodcolor} was the default, an instance value, 1126an interpolated primitive value, or was connected to another layer's 1127output. Unless {\cf ringcolor} itself was given an instance, primitive, 1128or connection value, in which case that's what would be used. 1129 1130 1131 1132\section{Shader metadata} 1133\label{sec:metadata} 1134\index{metadata} \index{shader metadata} 1135 1136A shader may optionally include \emph{metadata} (data \emph{about} the 1137shader, as opposed to data \emph{used by} the shader). Metadata may be 1138used to annotate the shader or any of its individual parameters with 1139additional hints or information that will be compiled into the shader 1140and may be queried by applications. A common use of metadata is to 1141specify user interface hints about shader parameters --- for example, 1142that a particular parameter should only take on integer values, should 1143have an on/off checkbox, is intended to be a filename, etc. 1144 1145Metadata is specified inside double brackets {\cf [[} and {\cf ]]} 1146enclosing a comma-separated list of metadata items. Each metadatum 1147looks like a parameter declaration --- having a data type, name, and 1148initializer. However, metadata may only be simple types or arrays 1149of simple types (not structs or closures) 1150and their value initializers must be numeric or 1151string constants (not computed expressions). 1152 1153Metadata about the shader as a whole is placed between the shader name 1154and the parameter list. Metadata about shader parameters are placed 1155immediately after the parameter's initializing expression, but before 1156the comma or closing parentheses that terminates the parameter 1157description. 1158 1159Below is an example shader declaration showing the use of shader and 1160parameter metadata: 1161 1162\begin{code} 1163 surface wood 1164 [[ string help = "Realistic wood shader" ]] 1165 ( 1166 float Kd = 0.5 1167 [[ string help = "Diffuse reflectivity", 1168 float min = 0, float max = 1 ]] , 1169 color woodcolor = color (.7, .5, .3) 1170 [[ string help = "Base color of the wood" ]], 1171 color ringcolor = 0.25 * woodcolor 1172 [[ string help = "Color of the dark rings" ]], 1173 string texturename = "wood.tx" 1174 [[ string help = "Texture map for the grain", 1175 string widget = "filename" ]], 1176 int pattern = 0 1177 [[ string widget = "mapper", 1178 string options = "oak:0|elm:1|walnut:2" ]] 1179 ) 1180 { 1181 ... 1182 } 1183\end{code} 1184 1185The metadata are not semantically meaningful; that is, the metadata does 1186not affect the actual execution of the shader. Most metadata exist only 1187to be embedded in the compiled shader and able to be queried by other 1188applications, such as to construct user interfaces for shader assignment 1189that allow usage tips, appropriate kinds of widgets for setting each 1190parameter, etc. 1191 1192The choice of metadata and their meaning is completely up to the shader 1193writer and/or modeling system. However, we propose some conventions 1194below. These conventions are not intended to be comprehensive, nor to 1195meet all your needs --- merely to establish a common nomenclature for 1196the most common metadata uses. 1197 1198The use of metadata is entirely optional on the part of the shader 1199writer, and any application that queries shader metadata is free to 1200honor or ignore any metadata it finds. 1201 1202\apiitem{string label} 1203A short label to be displayed in the UI for this parameter. If not 1204present, the parameter name itself should be used as the widget label. 1205\apiend 1206 1207\apiitem{string help} 1208Help text that describes the purpose and use of the shader or parameter. 1209\apiend 1210 1211\apiitem{string page} 1212Helps to group related widgets by ``page.'' 1213\apiend 1214 1215\apiitem{string widget} 1216The type of widget that should be used to adjust this parameter. 1217Suggested widget types: 1218 1219\apiitem{"number"} 1220\vspace{12pt} 1221Provide a slider and/or numeric input. This is the default widget type 1222for {\cf float} or {\cf int} parameters. Numeric inputs also may be 1223influenced by the following metadata: \qkw{min}, \qkw{max}, 1224\qkw{sensitivity}, \qkw{digits}, \qkw{slider}, \qkw{slidermin}, 1225\qkw{slidermax}, \qkw{slidercenter}, \qkw{sliderexponent}. 1226\apiend 1227\vspace{-16pt} 1228 1229\apiitem{"string"} 1230\vspace{12pt} 1231Provide a text entry widget. This is the default widget type for 1232{\cf string} parameters. 1233\apiend 1234\vspace{-16pt} 1235 1236\apiitem{"boolean"} 1237\vspace{12pt} 1238Provide a pop-up menu with ``Yes'' and ``No'' options. Works on strings 1239or numbers. With strings, ``Yes'' and ``No'' values are used, with 1240numbers, 0 and 1 are used. 1241\apiend 1242\vspace{-16pt} 1243 1244\apiitem{"checkBox"} 1245\vspace{12pt} 1246A boolean widget displayed as a checkbox. Works on strings or 1247numbers. With strings, ``Yes'' and ``No'' values are used, with numbers, 12480 and 1 are used. 1249\apiend 1250\vspace{-12pt} 1251 1252\apiitem{"popup"} 1253\vspace{12pt} 1254A pop-up menu of literal choices. This widget further requires 1255parameter metadata \qkw{options} (a string listing the supported 1256menu items, delimited by the `{\cf |}' character), and optionally \qkw{editable} 1257(an integer, which if nonzero means the widget should allow the 1258text field should be directly editable). For example: 1259\begin{code} 1260 string wrap = "default" 1261 [[ string widget = "popup", 1262 string options = "default|black|clamp|periodic|mirror" ]] 1263\end{code} 1264\apiend 1265\vspace{-16pt} 1266 1267\apiitem{"mapper"} 1268\vspace{12pt} 1269A pop-up with associative choices (an enumerated type, if the values 1270are integers). This widget further requires 1271parameter metadata \qkw{options}, a `{\cf |}'-delimited string with 1272``key:value'' pairs. For example: 1273\begin{code} 1274 int pattern = 0 1275 [[ string widget = "mapper", 1276 string options = "oak:0|elm:1|walnut:2" ]] 1277\end{code} 1278\apiend 1279\vspace{-16pt} 1280 1281\apiitem{"filename"} 1282\vspace{12pt} 1283A file selection dialog. 1284\apiend 1285\vspace{-16pt} 1286 1287\apiitem{"null"} 1288\vspace{12pt} 1289A hidden widget. 1290\apiend 1291\vspace{-16pt} 1292 1293\apiend 1294 1295\apiitem{float min\\ float max \\[0.5ex] int min \\ int max} 1296The minimum and/or maximum value that the parameter may take on. 1297\apiend 1298 1299\apiitem{float sensitivity \\ int sensitivity} 1300The precision or step size for incrementing or decrementing the value 1301(within the appropriate min/max range). 1302\apiend 1303 1304\apiitem{int digits} 1305The number of digits to show (-1 for full precision). 1306\apiend 1307 1308\apiitem{int slider} 1309If nonzero, enables display of a slider sub-widget. This also respects 1310the following additional metadata that control the slider specifically: 1311\qkw{slidermin} (minimum value for the slider, \qkw{slidermax} (maximum 1312value for the slider), \qkw{slidercenter} (origin value for 1313the slider), \qkw{sliderexponent} (nonlinear slider options). 1314\apiend 1315 1316\apiitem{string URL} 1317Provides a URL for full documentation of the shader or parameter. 1318\apiend 1319 1320\apiitem{string units} 1321Gives the assumed units, if any, for the parameter (e.g., \qkw{cm}, 1322\qkw{sec}, \qkw{degrees}). 1323The compiler or renderer may issue a warning if it detects that this 1324assumption is being violated (for example, the compiler can warn 1325if a \qkw{degrees} variable is passed as the argument to {\cf cos}). 1326\apiend 1327 1328%\apiitem{string UIenabler} 1329%The name of another parameter that, only if nonzero (or the 1330%non-empty string) unlocks adjustment of this parameter. For example, 1331%a parameter called \qkw{Kr} (reflectivity) may be en enabler for 1332%the \qkw{reflectionblur} parameter; zero reflectivity would gray-out 1333%the blur controls, which would be ignored if there were no reflection. 1334%\apiend 1335 1336 1337 1338 1339\newpage 1340\section{Public methods} 1341\label{sec:publicmethods} 1342\indexapi{public} 1343\index{public methods} 1344 1345Ordinary (non-public) functions inside a shader may be called only from 1346within the shader; they do not generate entry points that the renderer 1347is aware of. 1348 1349A \emph{public method} is a function that may be directly called by the 1350renderer. Only top-level local functions of a shader --- that is, 1351declared within the braces that define the local scope of the shader, 1352but not within any other such function --- may be public methods. A 1353function may be designated a public method by using the {\cf public} 1354keyword immediately before the function declaration: 1355 1356\begin{quote} 1357\em shader-type shader-name ( params ) \\ 1358{\rm\cf \{} 1359 1360\spc {\rm\cf public} \em ~ return-type ~ function-name ~ {\rm \cf (} 1361optional-parameters {\rm \cf )} \\ 1362\spc {\rm \cf \{ } \\ 1363\spc\spc statements \\ 1364\spc {\rm \cf \} } \\ 1365 1366\spc ...\\ 1367{\rm\cf \}} 1368\end{quote} 1369 1370 1371% \begin{annotate} 1372% A given renderer will publish a list of public methods (names, arguments 1373% expected, and return value) that has particular meaning for that 1374% renderer. For example, a renderer may honor a public method 1375% \begin{code} 1376% public float maxdisplacement () 1377% \end{code} 1378% \noindent that computes and returns the maximum distance 1379% that a displacement shader will move any surface points. 1380 1381% At some later point, this spec will recommend several ``standard'' 1382% public methods that should be honored by most renderers. 1383% \end{annotate} 1384 1385 1386 1387\chapter{Data types} 1388\label{chap:types} 1389\index{types|(} 1390 1391\langname provides several built-in simple data types for performing 1392computations inside your shader: 1393\smallskip 1394 1395\noindent\begin{tabular}{|p{0.75in}|p{4.75in}|} 1396\hline 1397{\cf int} & Integer data \\[1ex] 1398%\hline 1399{\cf float} & Scalar floating-point data (numbers) \\[1ex] 1400%\hline 1401{\cf point 1402vector 1403normal} & Three-dimensional positions, directions, and surface 1404 orientations \\[7ex] 1405%\hline 1406{\cf color} & Spectral reflectivities and light energy values \\[1ex] 1407%\hline 1408{\cf matrix} & $4 \times 4$ transformation matrices \\[1ex] 1409%\hline 1410{\cf string} & Character strings (such as filenames) \\[1ex] 1411{\cf void} & Indicates functions that do not return a value \\[1ex] 1412\hline 1413\end{tabular} 1414 1415In addition, you may create arrays and structures (much like C), and 1416\langname has a new type of data structure called a \emph{closure}. 1417 1418The remainder of this chapter will describe the simple and aggregate 1419data types available in \langname. 1420 1421\section{{\cf int}} 1422\label{sec:types:int} 1423\indexapi{int} \index{types!{\cf int}} 1424 1425The basic type for discrete numeric values is {\cf int}. The size of 1426the {\cf int} type is renderer-dependent, but is guaranteed to be at 1427least 32 bits. 1428 1429Integer constants are constructed the same way as in C. The following 1430are examples of {\cf int} constants: {\cf 1}, {\cf -32}, etc. Integer 1431constants may be specified as hexidecimal, for example: {\cf 0x01cf}. 1432 1433Unlike C, no unsigned, bool, char, short, or long types are supplied. 1434This is to simplify the process of writing shaders (as well as 1435implementing shading systems). 1436 1437The following operators may be used with \inttype values (in order of 1438decreasing precedence, with each box holding operators of the same 1439precedence): 1440 1441\smallskip 1442 1443\noindent \begin{tabular}{|p{1in}|p{0.5in}|p{3.75in}|} 1444operation & result & ~ \\ 1445\hline 1446\inttype\ {\ce ++} & \inttype & post-increment by 1 \\[0.5ex] 1447\inttype\ {\ce --} & \inttype & post-decrement by 1 \\[0.5ex] 1448\hline 1449{\ce ++} \inttype & \inttype & pre-increment by 1 \\[0.5ex] 1450{\ce --} \inttype & \inttype & pre-decrement by 1 \\[0.5ex] 1451{\cf {\bfseries -} int} & \inttype & unary negation \\[0.5ex] 1452{\ce \textasciitilde} {\cf int} & \inttype & bitwise complement (1 and 0 bits flipped) \\[0.5ex] 1453{\cf {\bfseries !} int} & \inttype & boolean `not' (1 if operand is zero, otherwise 0) \\[0.5ex] 1454\hline 1455{\cf int {\bfseries *} int} & \inttype & multiplication \\[0.5ex] 1456{\cf int {\bfseries /} int} & \inttype & division \\[0.5ex] 1457{\cf int {\bfseries \%} int} & \inttype & modulus \\[0.5ex] 1458\hline 1459{\cf int {\bfseries +} int} & \inttype & addition \\[0.5ex] 1460{\cf int {\bfseries -} int} & \inttype & subtraction \\[0.5ex] 1461\hline 1462{\cf int {\bfseries <<} int} & \inttype & shift left \\[0.5ex] 1463{\cf int {\bfseries >>} int} & \inttype & shift right \\[0.5ex] 1464\hline 1465{\cf int {\bfseries <} int} & \inttype & 1 if the first value is less 1466than the second, else 0 \\[0.5ex] 1467{\cf int {\bfseries <=} int} & \inttype & 1 if the first value is less 1468or equal to the second, else 0 \\[0.5ex] 1469{\cf int {\bfseries >} int} & \inttype & 1 if the first value is 1470greater than the second, else 0 \\[0.5ex] 1471{\cf int {\bfseries >=} int} & \inttype & 1 if the first value is 1472greater than or equal to the second, else 0 \\[0.5ex] 1473\hline 1474{\cf int {\bfseries ==} int} & \inttype & 1 if the two values are equal, 1475else 0 \\[0.5ex] 1476{\cf int {\bfseries !=} int} & \inttype & 1 if the two values are different, 1477else 0 \\[0.5ex] 1478\hline 1479{\cf int {\bfseries \&} int} & \inttype & bitwise and \\[0.5ex] 1480\hline 1481{\cf int {\bfseries \textasciicircum} int} & \inttype & bitwise exclusive or \\[0.5ex] 1482\hline 1483{\cf int {\bfseries |} int} & \inttype & bitwise or \\[0.5ex] 1484\hline 1485{\cf int {\bfseries \&\&} int} & \inttype & boolean and (1 if both operands are 1486nonzero, otherwise 0) \\[0.5ex] 1487\hline 1488{\cf int {\bfseries ||} int} & \inttype & boolean or (1 if either operand is 1489nonzero, otherwise 0) \\[0.5ex] 1490\hline 1491\end{tabular} 1492 1493\medskip 1494 1495\noindent Note that the {\cf not}, {\cf and}, and {\cf or} keywords are 1496synonyms for {\cf !}, {\cf \&\&}, and {\cf ||}, respectively. 1497 1498 1499 1500\section{{\cf float}} 1501\label{sec:types:float} 1502\indexapi{float} \index{types!{\cf float}} 1503 1504The basic type for scalar floating-point numeric values is \float. The 1505size of the {\cf float} type is renderer-dependent, but is guaranteed to 1506be at least IEEE 32-bit float (the standard C \float data type). 1507Individual renderer implementations may choose to implement \float with 1508even more precision (such as using the C {\cf double} as the underlying 1509representation). 1510 1511Floating-point constants are constructed the same way as in C. 1512The following are examples of {\cf float} constants: {\cf 1.0}, 1513{\cf 2.48}, {\cf -4.3e2}. 1514 1515An \inttype may be used in place of a \float when used with any valid 1516\float operator. In such cases, the \inttype will be promoted to a 1517\float and the resulting expression will be \float. An \inttype may 1518also be passed to a function that expects a \float parameters, with the 1519\inttype automatically promoted to \float. 1520 1521The following operators may be used with \float values (in order of 1522decreasing precedence, with each box holding operators of the same 1523precedence): 1524 1525\medskip 1526 1527\noindent \begin{tabular}{|p{1.25in}|p{0.5in}|p{3.5in}|} 1528operation & result & ~ \\ 1529\hline 1530\float\ {\ce ++} & \float & post-increment by 1 \\[0.5ex] 1531\float\ {\ce --} & \float & post-decrement by 1 \\[0.5ex] 1532\hline 1533{\ce ++} \float & \float & pre-increment by 1 \\[0.5ex] 1534{\ce --} \float & \float & pre-decrement by 1 \\[0.5ex] 1535{\cf {\bfseries -} float} & \float & unary negation \\[0.5ex] 1536\hline 1537{\cf float {\bfseries *} float} & \float & multiplication \\[0.5ex] 1538{\cf float {\bfseries /} float} & \float & division \\[0.5ex] 1539\hline 1540{\cf float {\bfseries +} float} & \float & addition \\[0.5ex] 1541{\cf float {\bfseries -} float} & \float & subtraction \\[0.5ex] 1542\hline 1543{\cf float {\bfseries <} float} & \inttype & 1 if the first value is less 1544than the second, else 0 \\[0.5ex] 1545{\cf float {\bfseries <=} float} & \inttype & 1 if the first value is less 1546or equal to the second, else 0 \\[0.5ex] 1547{\cf float {\bfseries >} float} & \inttype & 1 if the first value is 1548greater than the second, else 0 \\[0.5ex] 1549{\cf float {\bfseries >=} float} & \inttype & 1 if the first value is 1550greater than or equal to the second, else 0 \\[0.5ex] 1551\hline 1552{\cf float {\bfseries ==} float} & \inttype & 1 if the two values are equal, 1553else 0 \\[0.5ex] 1554{\cf float {\bfseries !=} float} & \inttype & 1 if the two values are different, 1555else 0 \\[0.5ex] 1556\hline 1557\end{tabular} 1558 1559 1560 1561\section{{\cf color}} 1562\label{sec:types:color} 1563\indexapi{color} \index{types!{\cf color}} 1564 1565The \color type is used to represent 3-component (RGB) spectral 1566reflectivities and light energies. You can assemble a 1567color out of three floats, either representing an RGB triple or some 1568other color space known to the renderer, as well as from a single 1569float (replicated for all three channels). Following are some examples: 1570 1571\begin{code} 1572 color (0, 0, 0) // black 1573 color ("rgb", .75, .5, .5) // pinkish 1574 color ("hsv", .2, .5, .63) // specify in "hsv" space 1575 color (0.5) // same as color (0.5, 0.5, 0.5) 1576\end{code} 1577 1578All these expressions above return colors in \rgbspace. Even 1579the third example returns a color in \rgbspace\ --- specifically, the 1580RGB value of the color that is equivalent to hue 0.2, saturation 0.5, 1581and value 0.63. In other words, when assembling a color from components 1582given relative to a specific color space in this manner, there is an 1583implied transformation to \rgbspace. Table~\ref{tab:colorspacenames} 1584lists the built-in color spaces. 1585 1586\begin{table}[htbp] 1587\caption{Names of color spaces.}\label{tab:colorspacenames} 1588\begin{tabular}{|p{0.7in}|p{4.7in}|} 1589\hline 1590{\cf "rgb"} & The coordinate system that all colors start out in, and 1591in which the renderer expects to find colors that are set by 1592your shader. \\ 1593\hline 1594{\cf "hsv"} & hue, saturation, and value. \\ 1595\hline 1596{\cf "hsl"} & hue, saturation, and lightness. \\ 1597\hline 1598{\cf "YIQ"} & the color space used for the NTSC television standard. \\ 1599\hline 1600{\cf "XYZ"} & CIE \emph{XYZ} coordinates. \\ 1601\hline 1602{\cf "xyY"} & CIE \emph{xyY} coordinates. \\ 1603\hline 1604\end{tabular} 1605\end{table} 1606 1607Colors may be assigned another color or a \float value (which sets 1608all three components to the value). For example: 1609 1610\begin{code} 1611 color C; 1612 C = color (0, 0.3, 0.3); 1613 C = 0.5; // same as C = color (0.5, 0.5, 0.5) 1614\end{code} 1615 1616Colors can have their individual components examined and set using the 1617{\cf []} array access notation. For example: 1618 1619\begin{code} 1620 color C; 1621 float g = C[1]; // get the green component 1622 C[0] = 0.5; // set the red component 1623\end{code} 1624 1625\noindent Components 0, 1, and 2 are red, green, and blue, respectively. 1626It is an error to access a color component with an index outside the 1627$[0...2]$ range. 1628 1629Color variables may also have their components referenced using 1630``named components'' that look like accessing structure fields named 1631{\cf r}, {\cf g}, and {\cf b}, as synonyms for {\cf [0]}, {\cf [1]}, and 1632{\cf [2]}, respectively: 1633 1634\begin{code} 1635 float green = C.g; // get the green component 1636 C.r = 0.5; // set the red component 1637\end{code} 1638 1639The following operators may be used with \color values (in order of 1640decreasing precedence, with each box holding operators of the same 1641precedence): 1642 1643\medskip 1644 1645\noindent \begin{tabular}{|p{1.5in}|p{0.5in}|p{3.25in}|} 1646operation & result & ~ \\ 1647\hline 1648\color\ {\ce [} \inttype {\ce ]} & \float & component access \\[0.5ex] 1649\hline 1650{\ce -} \color & \color & unary negation \\[0.5ex] 1651\hline 1652\color\ {\ce *} \color & \color & component-wise multiplication \\[0.5ex] 1653\color\ {\ce *} \float & \color & scaling \\[0.5ex] 1654\float\ {\ce *} \color & \color & scaling \\[0.5ex] 1655\color\ {\ce /} \color & \color & component-wise division \\[0.5ex] 1656\color\ {\ce /} \float & \color & scaling \\[0.5ex] 1657\float\ {\ce /} \color & \color & scaling \\[0.5ex] 1658\hline 1659\color\ {\ce +} \color & \color & component-wise addition \\[0.5ex] 1660\color\ {\ce -} \color & \color & component-wise subtraction \\[0.5ex] 1661\hline 1662\color\ {\ce ==} \color & \inttype & 1 if the two values are equal, 1663else 0 \\[0.5ex] 1664\color\ {\ce !=} \color & \inttype & 1 if the two values are different, 1665else 0 \\[0.5ex] 1666\hline 1667\end{tabular} 1668 1669All of the binary operators may combine a scalar value (\float or 1670\inttype) with a \color, treating the scalar if it were a \color with 1671three identical components. 1672 1673 1674\section{Point-like types: {\cf point}, {\cf vector}, {\cf normal}} 1675\label{sec:types:point} 1676\indexapi{point} \indexapi{vector} \indexapi{normal} 1677\index{types!{\cf point}} \index{types!{\cf vector}} \index{types!{\cf normal}} 1678 1679Points, vectors, and normals are similar data types with identical 1680structures but subtly different semantics. We will frequently refer to 1681them collectively as the ``point-like'' data types when making 1682statements that apply to all three types. 1683 1684A \point is a position in 3D space. A \vector has a length and 1685direction, but does not exist in a particular location. A \normal is a 1686special type of vector that is \emph{perpendicular} to a surface, and 1687thus describes the surface's orientation. Such a perpendicular vector 1688uses different transformation rules than ordinary vectors, as we will 1689describe below. 1690 1691All of these point-like types are internally represented by three 1692floating-point numbers that uniquely describe a position or 1693direction relative to the three axes of some coordinate system. 1694 1695All points, vectors, and normals are described relative to some 1696coordinate system. All data provided to a shader (surface information, 1697graphics state, parameters, and vertex data) are relative to one 1698particular coordinate system that we call the {\cf "common"} coordinate 1699system. The {\cf "common"} coordinate system is one that is convenient 1700for the renderer's shading calculations. 1701\label{sect:commonspace} 1702 1703You can ``assemble'' a point-like type out of three floats using a 1704constructor: 1705 1706\begin{code} 1707 point (0, 2.3, 1) 1708 vector (a, b, c) 1709 normal (0, 0, 1) 1710\end{code} 1711 1712\noindent These expressions are interpreted as a point, vector, and normal 1713whose three components are the floats given, relative to \commonspace\ . 1714 1715As with colors, you may also specify the coordinates relative to some other 1716coordinate system: 1717 1718\begin{code} 1719 Q = point ("object", 0, 0, 0); 1720\end{code} 1721 1722This example assigns to {\cf Q} the point at the origin of 1723\objectspace. However, this statement does \emph{not} set the 1724components of {\cf Q} to (0,0,0)! Rather, {\cf Q} will contain the 1725\commonspace\ coordinates of the point that is at the same location as 1726the origin of \objectspace. In other words, the point constructor that 1727specifies a space name implicitly specifies a transformation 1728to \commonspace. This type of constructor also can be used for vectors 1729and normals. 1730 1731The choice of \commonspace is renderer-dependent, though will usually 1732be equivalent to either \cameraspace or \worldspace. 1733 1734Some computations may be easier in a coordinate system other than 1735\commonspace. For example, it is much more convenient to apply a 1736``solid texture'' to a moving object in its \objectspace than in 1737\commonspace. For these reasons, OSL provides a built-in 1738{\cf transform} function that 1739allows you to transform points, vectors, and normals 1740among different coordinate systems (see Section~\ref{sec:stdlib:geom}). Note, 1741however, that \langname does not keep track of which point variables are 1742in which coordinate systems. It is the responsibility of the shader 1743programmer to keep track of this and ensure that, for example, lighting 1744computations are performed using quantities in \commonspace. 1745 1746Several coordinate systems are predefined by name, listed in 1747Table~\ref{tab:spacenames}. Additionally, a renderer will probably 1748allow for additional coordinate systems to be named in the scene 1749description, and these names may also be referenced inside your shader 1750to designate transformations. 1751 1752\begin{table}[htbp] 1753\caption{Names of predeclared geometric spaces.\label{tab:spacenames}} 1754\begin{tabular}{|p{0.7in}|p{4.7in}|} 1755\hline 1756{\cf "common"} & The coordinate system that all spatial values start out in and 1757the one in which all lighting calculations are carried out. Note that 1758the choice of {\cf "common"} space may be different on each renderer. \\ 1759\hline 1760{\cf "object"} & The local coordinate system of the graphics primitive (sphere, 1761patch, etc.) that we are shading. \\ 1762\hline 1763{\cf "shader"} & The local coordinate system active at the time that the shader 1764was instanced. \\ 1765\hline 1766{\cf "world"} & The world coordinate system designated in the scene. \\ 1767\hline 1768{\cf "camera"} & The coordinate system with its origin at the center of 1769the camera lens, $x$-axis pointing right, $y$-axis pointing up, and 1770$z$-axis pointing into the screen. \\ 1771\hline 1772{\cf "screen"} & The coordinate system of the camera's image plane 1773(after perspective transformation, if any). Coordinate (0,0) of {\cf 1774"screen"} space is looking along the $z$-axis of \cameraspace. \\ 1775\hline 1776{\cf "raster"} & 2D pixel coordinates, with (0,0) as the upper-left 1777corner of the image and (xres, yres) as the lower-right corner. \\ 1778\hline 1779{\cf "NDC"} & 2D Normalized Device Coordinates --- like raster space, but 1780normalized so that $x$ and $y$ both run from 0 to 1 across the whole 1781image, with (0,0) being at the upper left of the image, and (1,1) being 1782at the lower right. \\ 1783\hline 1784\end{tabular} 1785\end{table} 1786 1787Point types can have their individual components examined and set using 1788the {\cf []} array access notation. For example: 1789 1790\begin{code} 1791 point P; 1792 float y = P[1]; // get the y component 1793 P[0] = 0.5; // set the x component 1794\end{code} 1795 1796\noindent Components 0, 1, and 2 are $x$, $y$, and $z$, respectively. 1797It is an error to access a point component with an index outside the 1798$[0...2]$ range. 1799 1800Point-like variables may also have their components referenced using 1801``named components'' that look like accessing structure fields named 1802{\cf x}, {\cf y}, and {\cf z}, as synonyms for {\cf [0]}, {\cf [1]}, and 1803{\cf [2]}, respectively: 1804 1805\begin{code} 1806 float yval = P.y; // get the [1] or y component 1807 P.x = 0.5; // set the [0] or x component 1808\end{code} 1809 1810The following operators may be used with point-like values (in order of 1811decreasing precedence, with each box holding operators of the same 1812precedence): 1813 1814\medskip 1815 1816\noindent \begin{tabular}{|p{1.5in}|p{0.5in}|p{3.25in}|} 1817operation & result & ~ \\ 1818\hline 1819\emph{ptype}\ {\ce [} \inttype {\ce ]} & \float & component access \\[0.5ex] 1820\hline 1821{\ce -} \emph{ptype} & \vector & component-wise unary negation \\[0.5ex] 1822\hline 1823\emph{ptype}\ {\ce *} \emph{ptype} & \emph{ptype} & component-wise multiplication \\[0.5ex] 1824\float\ {\ce *} \emph{ptype} & \emph{ptype} & scaling of all components \\[0.5ex] 1825\emph{ptype}\ {\ce *} \float & \emph{ptype} & scaling of all components \\[0.5ex] 1826\emph{ptype}\ {\ce /} \emph{ptype} & \emph{ptype} & component-wise division \\[0.5ex] 1827\emph{ptype}\ {\ce /} \float & \emph{ptype} & division of all components \\[0.5ex] 1828\float\ {\ce /} \emph{ptype} & \emph{ptype} & division by all components \\[0.5ex] 1829\hline 1830\emph{ptype}\ {\ce +} \emph{ptype} & \emph{ptype} & component-wise addition \\[0.5ex] 1831\emph{ptype}\ {\ce -} \emph{ptype} & \vector & component-wise subtraction \\[0.5ex] 1832\hline 1833\emph{ptype}\ {\ce ==} \emph{ptype} & \inttype & 1 if the two values are equal, 1834else 0 \\[0.5ex] 1835\emph{ptype}\ {\ce !=} \emph{ptype} & \inttype & 1 if the two values are different, 1836else 0 \\[0.5ex] 1837\hline 1838\end{tabular} 1839 1840\smallskip 1841 1842\noindent The generic \emph{ptype} is listed in places where any 1843of \point, \vector, or \normal may be used. 1844 1845All of the binary operators may combine a scalar value (\float or 1846\inttype) with a point-like type, treating the scalar if it were 1847point-like with three identical components. 1848 1849 1850\section{{\cf matrix}} 1851\label{sec:types:matrix} 1852\indexapi{matrix} \index{types!{\cf matrix}} 1853 1854\langname has a \matrix type that represents the transformation matrix 1855required to transform points and vectors between one coordinate system 1856and another. Matrices are represented internally by 16 floats (a $4 1857\times 4$ homogeneous transformation matrix). 1858 1859A \matrix can be constructed from a single float or 16 floats. For 1860example: 1861 1862\begin{code} 1863 matrix zero = 0; // makes a matrix with all 0 components 1864 matrix ident = 1; // makes the identity matrix 1865 1866 // Construct a matrix from 16 floats 1867 matrix m = matrix (m00, m01, m02, m03, m10, m11, m12, m13, 1868 m20, m21, m22, m23, m30, m31, m32, m33); 1869\end{code} 1870 1871\noindent Assigning a single floating-point number $x$ to a matrix will result 1872in a matrix with diagonal components all being $x$ and other 1873components being zero (i.e., $x$ times the identity matrix). 1874Constructing a matrix with 16 floats will create the matrix whose 1875components are those floats, in row-major order. 1876 1877Similar to point-like types, a {\cf matrix} may be constructed in 1878reference to a named space: 1879 1880\begin{code} 1881 // Construct matrices relative to something other than "common" 1882 matrix q = matrix ("shader", 1); 1883 matrix m = matrix ("world", m00, m01, m02, m03, m10, m11, m12, m13, 1884 m20, m21, m22, m23, m30, m31, m32, m33); 1885\end{code} 1886 1887\noindent The first form creates the matrix that transforms points from 1888\shaderspace to \commonspace. Transforming points by this matrix 1889is identical to calling {\cf transform("shader", "common", ...)}. 1890The second form prepends the current-to-world transformation matrix 1891onto the $4 \times 4$ matrix with components $m_{0,0} ... m_{3,3}$. 1892Note that although we have used {\cf "shader"} and {\cf "world"} 1893space in our examples, any named space is acceptable. 1894 1895A matrix may also be constructed from the names of two coordinate 1896systems, yielding the matrix that transforms coordinates from the 1897first named space to the second named space: 1898 1899\begin{code} 1900 matrix m = matrix ("object", "world"); 1901\end{code} 1902 1903\noindent The example returns the \emph{object-to-world} transformation 1904matrix. 1905 1906Matrix variables can be tested for equality and inequality with the 1907{\cf ==} and {\cf !=} boolean operators. Also, the {\cf *} operator 1908between matrices denotes matrix multiplication, while {\cf m1 / m2} 1909denotes multiplying {\cf m1} by the inverse of matrix {\cf m2}. Thus, 1910a matrix can be inverted by writing {\cf 1/m}. In addition, some 1911functions will accept matrix variables as arguments, as described in 1912Section~\ref{chap:stdlibrary}. 1913 1914Individual components of a matrix variable may be set or accessed 1915using array notation, for example, 1916 1917\begin{code} 1918 matrix M; 1919 float x = M[row][col]; 1920 M[row][col] = 1; 1921\end{code} 1922 1923Valid component indices are integers on $[0...3]$. It is an error to 1924access a matrix component with either a row or column outside this 1925range. 1926 1927The following operators may be used with matrices (in order of 1928decreasing precedence, with each box holding operators of the same 1929precedence): 1930 1931\medskip 1932\noindent \begin{tabular}{|p{1.5in}|p{0.5in}|p{3.25in}|} 1933operation & result & ~ \\ 1934\hline 1935\matrix\ {\ce [} \inttype {\ce ][} \inttype {\ce ]} & \float & component 1936access (row, column) \\[0.5ex] 1937\hline 1938{\ce -} \matrix & \matrix & unary negation \\[0.5ex] 1939\hline 1940\matrix\ {\ce *} \matrix & \matrix & matrix multiplication \\[0.5ex] 1941\matrix\ {\ce *} \float & \matrix & component-wise scaling \\[0.5ex] 1942\float\ {\ce *} \matrix & \matrix & component-wise scaling \\[0.5ex] 1943\matrix\ {\ce /} \matrix & \matrix & multiply the first matrix by the 1944\emph{inverse} of the second \\[0.5ex] 1945\matrix\ {\ce /} \float & \matrix & component-wise division \\[0.5ex] 1946\float\ {\ce /} \matrix & \matrix & multiply the \float by the 1947\emph{inverse} of the matrix \\[0.5ex] 1948\hline 1949%\matrix\ {\ce +} \matrix & \matrix & component-wise addition \\[0.5ex] 1950%\matrix\ {\ce -} \matrix & \matrix & component-wise subtraction \\[0.5ex] 1951%\hline 1952\matrix\ {\ce ==} \matrix & \inttype & 1 if the two values are equal, 1953else 0 \\[0.5ex] 1954\matrix\ {\ce !=} \matrix & \inttype & 1 if the two values are different, 1955else 0 \\[0.5ex] 1956\hline 1957\end{tabular} 1958 1959 1960\section{{\cf string}} 1961\label{sec:types:string} 1962\indexapi{string} \index{types!{\cf string}} 1963 1964The {\cf string} type may hold character strings. The main application 1965of strings is to provide the names of files where textures may be 1966found. Strings can be compared using {\cf ==} and {\cf !=}. 1967 1968String constants are denoted by surrounding the characters with double 1969quotes, as in \qkw{I am a string literal}. As in C programs, string 1970literals may contain escape sequences such as \verb|\n| (newline), 1971\verb|\r| (carriage return), \verb|\t| (tab), \verb|\"| (double quote), 1972\verb|\\| (backslash). 1973 1974Two quote-quoted string literals that are separated only by whitespace 1975(spaces, tabs, or newlines) will be automatically concatenated into a 1976single string literal. In other words, 1977\begin{code} 1978 "foo" "bar" 1979\end{code} 1980\noindent is exactly equivalent to \qkw{foobar}. 1981 1982\section{\void} 1983\label{sec:types:void} 1984\indexapi{void} \index{types!{\cf void}} 1985 1986The \void type is used to designate a function that does not return 1987a value. No variable may have type \void. 1988 1989\section{Arrays} 1990\label{sec:types:arrays} 1991\index{arrays} \index{types!arrays} 1992 1993Arrays of any of the basic types are supported, provided that they 1994are 1D and statically sized, using the usual syntax for C-like languages: 1995 1996\begin{code} 1997 float d[10]; // Declare an uninitialized array 1998 float c[3] = { 0.1, 0.2, 3.14 }; // Initialize the array 1999 2000 float f = c[1]; // Access one element 2001\end{code} 2002 2003The built-in function {\cf arraylength()} returns the number of elements 2004in an array. For example: 2005 2006\begin{code} 2007 float c[3]; 2008 int clen = arraylength(c); // should return 3 2009\end{code} 2010 2011There are two circumstances when arrays do not need to have a declared 2012length --- an array parameter to a function, and a shader parameter that 2013is an array. This is indicated by empty array brackets, as shown in the 2014following example: 2015 2016\begin{code} 2017 float sum (float x[]) 2018 { 2019 float s = 0; 2020 for (int i = 0; i < arraylength(x); ++i) 2021 s += x[i]; 2022 return s; 2023 } 2024\end{code} 2025 2026It is allowed in OSL to copy an entire array at once using the {\cf =} 2027operator, provided that the arrays contain elements of the same type 2028and that the destination array is at least as long as the source 2029array. For example: 2030 2031\begin{code} 2032 float array[4], anotherarray[4]; 2033 ... 2034 anotherarray = array; 2035\end{code} 2036 2037 2038\section{Structures} 2039\label{sec:types:struct} 2040\indexapi{struct} \index{types!structures} \index{structures|see{{\cf struct}}} 2041 2042Structures are used to group several fields of potentially different 2043types into a single object that can be referred to by name. You may 2044then use the structure type name to declare structure variables as you 2045would for any of the built-in types. Structure elements are accessed 2046using the `dot' operator. The syntax for declaring and using structures 2047is similar to C or C++: 2048 2049\begin{code} 2050 struct RGBA { // Define a structure type 2051 color rgb; 2052 float alpha; 2053 }; 2054 2055 RGBA col; // Declare a structure 2056 r.rgb = color (1, 0, 0); // Assign to one field 2057 color c = r.rgb; // Read from a structure field 2058 2059 RGBA b = { color(.1,.2,.3), 1 }; // Member-by-member initialization 2060\end{code} 2061 2062You can use ``constructor expressions'' for a your struct types much like 2063you can construct built-in types like \color or \point: 2064 2065\vspace{10pt} 2066\hspace{0.25in} \emph{struct\_name ( first\_member\_value, ... )} 2067\vspace{10pt} 2068 2069\noindent For example, 2070 2071\begin{code} 2072 RGBA c = RGBA(col,alpha); // Constructor syntax 2073 2074 RGBA add (RGBA a, RGBA b) 2075 { 2076 return RGBA (a.rgb+b.rgb, a.a+b.a); // return expression 2077 } 2078 2079 // pass constructor expression as a parameter: 2080 RGBA d = add (c, RGBA(color(.3,.4,.5), 0)); 2081\end{code} 2082 2083You may also use the \emph{compound initializer list} syntax to construct a 2084type when it can be deduced from context which compound type is required. 2085For example, this is equivalent to the preceding example: 2086 2087\begin{code} 2088 RGBA c = {col,alpha}; // deduce by what is being assigned to 2089 2090 RGBA add (RGBA a, RGBA b) 2091 { 2092 return { a.rgb+b.rgb, a.a+b.a }; // deduce by func return type 2093 } 2094 2095 RGBA d = add (c, {{.3,.4,.5}, 0}); // deduce by expected arg type 2096\end{code} 2097 2098It is permitted to have a structure field that is an array, as well as to 2099have an array of structures. But it is not currently permitted to ``nest'' 2100arrays (that is, to have an array of structs which contain members that are 2101arrays). 2102 2103\begin{code} 2104 struct A { 2105 color a; 2106 float b[4]; // Ok: struct may contain an array 2107 }; 2108 2109 RGBA vals[4]; // Ok: Array of structures 2110 vals[0].a = 0; 2111 2112 A d[5]; // NO: Array of structures that contain arrays 2113\end{code} 2114 2115 2116\index{types|)} % end of chapter 2117 2118 2119\section{Closures} 2120\label{sec:types:closures} 2121 2122A \closure is an expression or function call that will be stored, along 2123with necessary contextual information, to be evaluated at a later time. 2124 2125In general, the type ``\closure \emph{gentype}'' behaves exactly like a 2126\emph{gentype}, except that its numeric values may not be examined or 2127used for the duration of the shader's execution. For example, a 2128\colorclosure behaves mostly like a color --- you can multiply it by a 2129scalar, assign it to a \colorclosure variable, etc. --- but you may not 2130assign it to an ordinary \color or examine its individual component's 2131numeric values. 2132 2133It is legal to assign {\cf 0} to a closure, which is understood to mean 2134setting it to a \emph{null closure} (even though in all other 2135circumstances, assigning a {\cf float} to a \closure would not be 2136allowed). 2137 2138At present, the only type of \closure supported by \langname is the 2139\colorclosure, and the only allowed operations are those that let you 2140form a linear combination of \colorclosure's. Additional closure types 2141and operations are reserved for future use. 2142 2143Allowable operations on \colorclosure include: 2144 2145\medskip 2146\noindent \begin{tabular}{|p{2.25in}|p{1.25in}|p{1.75in}|} 2147operation & result & ~ \\ 2148\hline 2149{\ce -} \colorclosure & \colorclosure & unary negation \\[0.5ex] 2150\hline 2151\color\ {\ce *} \colorclosure & \colorclosure & component-wise scaling \\[0.5ex] 2152\colorclosure\ {\ce *} \color & \colorclosure & component-wise scaling \\[0.5ex] 2153\float\ {\ce *} \colorclosure & \colorclosure & scaling \\[0.5ex] 2154\colorclosure\ {\ce *} \float & \colorclosure & scaling \\[0.5ex] 2155\hline 2156\colorclosure\ {\ce +} \colorclosure & \colorclosure & component-wise addition \\[0.5ex] 2157% \colorclosure\ {\ce -} \colorclosure & \colorclosure & component-wise subtraction \\[0.5ex] 2158\hline 2159\end{tabular} 2160 2161\medskip 2162 2163 2164 2165 2166\chapter{Language Syntax} 2167\label{chap:syntax} 2168 2169The body of a shader is a sequence of individual \emph{statements}. 2170This chapter describes the types of statements and control-flow patterns 2171in \langname. 2172 2173Statements in \langname include the following types of constructs: 2174 2175\begin{itemize} 2176\item Scoped statements. 2177\item Variable declarations. 2178\item Expressions. 2179\item Assignments. 2180\item Control flow: {\cf if, else, while, do, for, break, continue} 2181\item Function declarations. 2182\end{itemize} 2183 2184\subsection*{Scoping} 2185 2186Any place where it is legal to have a statement, it is legal to have 2187multiple statements enclosed by curly braces {\cf \{ \}}. This is 2188called a \emph{scope}. Any variables or functions declared 2189within a scope are only visible within that scope, and only may be used 2190after their declaration. Variables or functions that are referenced 2191will always resolve to the matching name in the innermost scope relative 2192to its use. For example 2193 2194\begin{code} 2195 float a = 1; // Call this the "outer" 'a' 2196 float b = 2; 2197 { 2198 float a = 3; // Call this the "inner" 'a' 2199 float c = 1; 2200 b = a; // b gets 3, because a is resolved to the inner scope 2201 } 2202 b += c; // ERROR -- c was only in the inner scope 2203 2204\end{code} 2205 2206 2207 2208\section{Variable declarations and assignments} 2209\label{sec:vardeclsassignments} 2210 2211\subsection{Variable declarations} 2212\label{sec:vardecls} 2213\index{variable declarations} 2214 2215The syntax for declaring a variable in \langname is: 2216 2217\vspace{12pt} 2218\spc \emph{type} \emph{name} 2219 2220\spc \emph{type} \emph{name} = \emph{value} 2221\vspace{12pt} 2222 2223\noindent where 2224 2225\begin{itemize} 2226\item \emph{type} is one of the basic data types, described earlier. 2227\item \emph{name} is the name of the variable you are declaring. 2228\item If you wish to initialize your variable an initial value, you may 2229immediately assign it a \emph{value}, which may be any valid expression. 2230\end{itemize} 2231 2232You may declare several variables of the same type in a single 2233declaration by separating multiple variable names by commas: 2234 2235\vspace{12pt} 2236\spc \emph{type} \emph{name1} {\cf ,} ~ \emph{name2} ... 2237 2238\spc \emph{type} \emph{name1} [ = \emph{value1}] {\cf ,} ~ \emph{name2} [ = 2239 \emph{value2} ] ... 2240\vspace{12pt} 2241 2242 2243\noindent Some examples of variable declarations are 2244 2245\begin{code} 2246 float a; // Declare; current value is undefined 2247 float b = 1; // Declare and assign a constant initializer 2248 float c = a*b; // Computed initializer 2249 float d, e = 2, f; // Declare several variables of the same type 2250\end{code} 2251 2252\subsection{Arrays} 2253\indexapi{arrays} \index{types!arrays} 2254 2255Arrays are also supported, declared as follows: 2256 2257\vspace{12pt} 2258\spc \emph{type} \emph{variablename} 2259 {\cf [} \emph{arraylen} {\cf ]} 2260 2261\spc \emph{type} \emph{variablename} 2262 {\cf [} \emph{arraylen} {\cf ]} = {\cf \{ } 2263 \emph{init0}{\cf ,} \emph{init1} ... {\cf \}} 2264\vspace{12pt} 2265 2266\noindent Array variables in \langname must have a constant length 2267(though function parameters and shader parameters may have undetermined 2268length). Some examples of array variable declarations are: 2269 2270\begin{code} 2271 float d[10]; // Declare an uninitialized array 2272 float c[3] = { 0.1, 0.2, 3.14 }; // Initialize the array 2273\end{code} 2274 2275\subsection{Structures} 2276\indexapi{struct} 2277 2278Structures are used to group several fields of potentially different 2279types into a single object that can be referred to by name. The syntax 2280for declaring a structure type is: 2281 2282\vspace{12pt} 2283\spc {\cf struct} \emph{structname} {\cf \{} 2284 2285\spc\spc \emph{type1} \emph{fieldname1} {\cf ;} 2286 2287\spc\spc ... 2288 2289\spc\spc \emph{typeN} \emph{fieldnameN} {\cf ;} 2290 2291\spc {\cf \} ;} 2292\vspace{12pt} 2293 2294You may then use the structure type name to declare structure variables 2295as you would for any of the built-in types: 2296 2297\vspace{12pt} 2298\spc \emph{structname} \emph{variablename} {\cf ;} 2299 2300\spc \emph{structname} \emph{variablename} {\cf = \{ } 2301\emph{initializer1} {\cf ,} ... \emph{initializerN} {\cf \} ;} 2302\vspace{12pt} 2303 2304If initializers are supplied, each field of the structure will be 2305initialized with the initializer in the corresponding position, which 2306is expected to be of the appropriate type. 2307 2308Structure elements are accessed in the same way as other C-like 2309languages, using the `dot' operator: 2310 2311\vspace{12pt} 2312\spc \emph{variablename}{\cf .} \emph{fieldname} 2313\vspace{12pt} 2314 2315Examples of declaration and use of structures: 2316 2317\begin{code} 2318 struct ray { 2319 point pos; 2320 vector dir; 2321 }; 2322 2323 ray r; // Declare a structure 2324 ray s = { point(0,0,0), vector(0,0,1) }; // declare and initialize 2325 r.pos = point (1, 0, 0); // Assign to one field 2326\end{code} 2327 2328It is permitted to have a structure field that is an array, as well as 2329to have an array of structures. But it is not permitted for one 2330structure to have a field that is another structure. 2331 2332Please refer to Section~\ref{sec:types:struct} for more information 2333on using {\cf struct}. 2334 2335 2336\section{Expressions} 2337\label{sec:expressions} 2338\index{expressions} 2339 2340The expressions available in \langname include the following: 2341 2342\begin{itemize} 2343\item Constants: integer (e.g., {\cf 1}, {\cf 42}), floating-point 2344 (e.g. {\cf 1.0}, {\cf 3}, {\cf -2.35e4}), or string literals (e.g., {\cf 2345 "hello"}) 2346 2347\item point, vector, normal, or matrix constructors, for example: 2348 2349\begin{code} 2350 color (1, 0.75, 0.5) 2351 point ("object", 1, 2, 3) 2352\end{code} 2353 2354If all the arguments to a constructor are themselves constants, the 2355constructed point is treated like a constant and has no runtime cost. 2356That is, {\cf color(1,2,3)} is treated as a single constant entity, not 2357assembled bit by bit at runtime. 2358 2359\item Variable or parameter references 2360 2361\item An individual element of an array (using {\cf [ ] }) 2362 2363\item An individual component of a \color, 2364\point, \vector, \normal (using {\cf [ ]}), 2365or of a \matrix (using {\cf [][]}) 2366 2367\item prefix and postfix increment and decrement operators: 2368 2369\begin{tabbing} 2370\hspace{.25in} \= \hspace{2in} \= (negation) \kill \\ 2371\> \emph{varref} {\cf ++} \hspace{1in} \= (post-increment) \\ 2372\> \emph{varref} {\cf --} \hspace{1in} \= (post-decrement) \\ 2373\> {\cf ++} \emph{varref} \hspace{1in} \= (pre-increment) \\ 2374\> {\cf --} \emph{varref} \hspace{1in} \= (pre-decrement) \\ 2375\end{tabbing} 2376 2377The post-increment and post-decrement (e.g., {\cf a++}) returns the old 2378value, then increments or decrements the variable; the pre-increment and 2379pre-decrement ({\cf ++a}) will first increment or decrement the 2380variable, then return the new value. 2381 2382\item Unary and binary arithmetic operators on other expressions: 2383 2384\begin{tabbing} 2385\hspace{0.25in} {\cf -} \emph{expr} \hspace{1in} \= (negation) \\ 2386\hspace{0.25in} {\cf \textasciitilde} \emph{expr} \> (bitwise complement) \\ 2387\hspace{0.25in} \emph{expr} {\cf *} \emph{expr} \> (multiplication) \\ 2388\hspace{0.25in} \emph{expr} {\cf /} \emph{expr} \> (division) \\ 2389\hspace{0.25in} \emph{expr} {\cf +} \emph{expr} \> (addition) \\ 2390\hspace{0.25in} \emph{expr} {\cf -} \emph{expr} \> (subtraction) \\ 2391\hspace{0.25in} \emph{expr} {\cf \%} \emph{expr} \> (integer modulus) \\ 2392\hspace{0.25in} \emph{expr} {\cf <<} \emph{expr} \> (integer shift left) \\ 2393\hspace{0.25in} \emph{expr} {\cf >>} \emph{expr} \> (integer shift right) \\ 2394\hspace{0.25in} \emph{expr} {\cf \&} \emph{expr} \> (bitwise and) \\ 2395\hspace{0.25in} \emph{expr} {\cf |} \emph{expr} \> (bitwise or) \\ 2396\hspace{0.25in} \emph{expr} {\cf \textasciicircum} \emph{expr} \> (bitwise exclusive or) \\ 2397\end{tabbing} 2398 2399The operators {\cf +}, {\cf -}, {\cf *}, {\cf /}, and the unary {\cf -} 2400(negation) may be used on most of the numeric types. For multicomponent 2401types (\color, \point, \vector, \normal, \matrix), these operators 2402combine their arguments on a component-by-component basis. 2403The only operators that may be applied to the \matrix type are 2404{\cf *} and {\cf /}, which respectively denote matrix-matrix 2405multiplication and matrix multiplication by the inverse of another 2406matrix. 2407 2408The integer and bit-wise operators {\cf \%}, {\cf <<}, {\cf >>}, 2409{\cf \&}, {\cf |}, {\cf \textasciicircum}, and {\cf \textasciitilde} may only be 2410used with expressions of type \inttype. 2411 2412For details on which operators are allowed, please consult the operator 2413tables for each individual type in Chapter~\ref{chap:types}. 2414 2415\item Relational operators (all lower precedence than the arithmetic 2416operators): 2417 2418\begin{tabbing} 2419\hspace{0.25in} \emph{expr} {\cf ==} \emph{expr} \hspace{1in} \= (equal to) \\ 2420\hspace{0.25in} \emph{expr} {\cf !=} \emph{expr} \> (not equal to) \\ 2421\hspace{0.25in} \emph{expr} {\cf <} \emph{expr} \> (less then) \\ 2422\hspace{0.25in} \emph{expr} {\cf <=} \emph{expr} \> (less than or equal to) \\ 2423\hspace{0.25in} \emph{expr} {\cf >} \emph{expr} \> (greater than) \\ 2424\hspace{0.25in} \emph{expr} {\cf >=} \emph{expr} \> (greater than or equal) \\ 2425\end{tabbing} 2426 2427The {\cf ==} and {\cf !=} operators may be performed between any two 2428values of equal type, and are performed component-by-component for 2429multi-component types. The {\cf <}, {\cf <=}, {\cf >}, {\cf >=} may not 2430be used to compare multi-component types. 2431 2432An \inttype expression may be compared to a \float (and is treated as if 2433they are both \float). A \float expression may be compared to a 2434multi-component type (and is treated as a multi-component type as if 2435constructed from a single float). 2436 2437Relation comparisons produce Boolean (true/false) values. These 2438are implemented as \inttype values, 0 if false and 1 if true. 2439 2440\item Logical unary and binary operators: 2441 2442\hspace{0.5in} {\cf !} \emph{expr} 2443 2444\hspace{0.5in} \emph{expr1} {\cf \&\&} \emph{expr2} 2445 2446\hspace{0.5in} \emph{expr1} {\cf ||} \emph{expr2} 2447 2448\noindent Note that the {\cf not}, {\cf and}, and {\cf or} keywords are 2449synonyms for {\cf !}, {\cf \&\&}, and {\cf ||}, respectively. 2450 2451For the logical operators, numeric expressions (\inttype or \float) are 2452considered \emph{true} if nonzero, \emph{false} if zero. 2453Multi-component types (such as \color) are considered \emph{true} any 2454component is nonzero, \emph{false} all components are zero. Strings are 2455considered \emph{true} if they are nonempty, \emph{false} if they are 2456the empty string (\qkw{}). 2457 2458\item another expression enclosed in parentheses: {\cf ( )}. 2459 Parentheses may be used to guarantee associativity of operations. 2460 2461\item Type casts, specified either by having the type name in 2462parentheses in front of the value to cast (C-style typecasts) 2463or the type name called as a constructor (C++-style type constructors): 2464\begin{code} 2465 (vector) P /* cast a point to a vector */ 2466 (point) f /* cast a float to a point */ 2467 (color) P /* cast a point to a color! */ 2468 2469 vector (P) /* Means the same thing */ 2470 point (f) 2471 color (P) 2472\end{code} 2473 2474The three-component types (\color, \point, \vector, \normal) 2475may be cast to other three-component types. A \float 2476may be cast to any of the three-component types (by placing the 2477float in all three components) or to a {\cf matrix} (which makes a 2478matrix with all diagonal components being the {\cf float}). 2479Obviously, there are some type casts that are not allowed because 2480they make no sense, like casting a {\cf point} to a {\cf float}, or 2481casting a {\cf string} to a numerical type. 2482 2483\item function calls 2484 2485\item assignment expressions: 2486same thing as {\cf var = var OP expr} : 2487 2488\begin{tabbing} 2489\hspace{0.25in} \emph{var} {\cf =} \emph{expr} \hspace{1in} \= (assign) \\ 2490\hspace{0.25in} \emph{var} {\cf +=} \emph{expr} \> (add) \\ 2491\hspace{0.25in} \emph{var} {\cf -=} \emph{expr} \> (subtract) \\ 2492\hspace{0.25in} \emph{var} {\cf *=} \emph{expr} \> (multiply) \\ 2493\hspace{0.25in} \emph{var} {\cf /=} \emph{expr} \> (divide) \\ 2494\hspace{0.25in} \emph{int-var} {\cf \&=} \emph{int-expr} \> (bitwise and) \\ 2495\hspace{0.25in} \emph{int-var} {\cf |=} \emph{int-expr} \> (bitwise or) \\ 2496\hspace{0.25in} \emph{int-var} \verb|^=| \emph{int-expr} \> (bitwise 2497exclusive or) \\ 2498\hspace{0.25in} \emph{int-var} {\cf <<=} \emph{int-expr} \> (integer 2499shift left) \\ 2500\hspace{0.25in} \emph{int-var} {\cf >>=} \emph{int-expr} \> (integer 2501shift right) \\ 2502\end{tabbing} 2503 2504Note that the integer and bit-wise operators are only allowed with 2505\inttype variables and expressions. In general, {\cf var OP= expr} is 2506allowed only if {\cf var = var OP expr} is allowed, and means exactly 2507the same thing. Please consult the operator tables for each individual 2508type in Chapter~\ref{chap:types}. 2509 2510\item ternary operator, just like C: 2511 2512\hspace{0.5in} \emph{condition} {\cf ?} \emph{expr1} {\cf :} \emph{expr2} 2513 2514This expression takes on the value of \emph{expr1} if \emph{condition} 2515is true (nonzero), or \emph{expr2} if \emph{condition} is false (zero). 2516 2517\end{itemize} 2518 2519Please refer to Chapter~\ref{chap:types}, where the section describing 2520each data type describes the full complement of operators that may be 2521used with the type. Operator precedence in \langname is identical to 2522that of C. 2523 2524 2525\section{Control flow: {\cf if, while, do, for}} 2526\label{sec:controlflow} 2527 2528Conditionals in \langname just like in C or C++: 2529\indexapi{if} 2530 2531\begin{tabbing} 2532\hspace{0.5in} \= \hspace{0.3in} \= \kill 2533\> {\cf if (} \emph{condition} {\cf )} \\ 2534\> \> \emph{truestatement} 2535\end{tabbing} 2536 2537\noindent and 2538 2539\begin{tabbing} 2540\hspace{0.5in} \= \hspace{0.3in} \= \kill 2541\> {\cf if (} \emph{condition} {\cf )} \\ 2542\> \> \emph{truestatement} \\ 2543\> {\cf else} \\ 2544\> \> \emph{falsestatement} 2545\end{tabbing} 2546 2547\noindent The statements can also be entire blocks, surrounded by curly 2548braces. For example, 2549 2550\begin{code} 2551 if (s > 0.5) { 2552 x = s; 2553 y = 1; 2554 } else { 2555 x = s+t; 2556 } 2557\end{code} 2558 2559\noindent The \emph{condition} may be any valid expression, including: 2560 2561\begin{itemize} 2562\item The result of any comparison operator (such as {\cf <}, {\cf ==}, 2563 etc.). 2564\item Any numeric expression (\inttype, \color, \point, \vector, 2565 \normal, \matrix), which is considered ``true'' if nonzero and 2566 ``false'' if zero. 2567\item Any string expression, which is considered ``true'' if it is a 2568 nonempty string, ``false'' if it is the empty string (\qkw{}). 2569\item A \closure, which is considered ``true'' if it's empty (not 2570 assigned, or initialized with {\cf =0}), and ``false'' if anything 2571 else has been assigned to it. 2572\item A logical combination of expressions using the operators {\cf !} 2573 (not), {\cf \&\&} (logical ``and''), or {\cf ||} (logical ``or''). 2574 Note that {\cf \&\&} and {\cf ||} \emph{short circuit} as in C, 2575 i.e. {\cf A \&\& B} will only evaluate B if A is true, and {\cf A || 2576 B} will only evaluate B if A is false. 2577\end{itemize} 2578 2579Repeated execution of statements for as long as a condition is true is 2580possible with a {\cf while} statement: 2581\indexapi{while} 2582 2583\begin{tabbing} 2584\hspace{0.5in} \= \hspace{0.3in} \= \kill 2585\> {\cf while (} \emph{condition} {\cf )} \\ 2586\> \> \emph{statement} 2587\end{tabbing} 2588 2589Or the test may happen after the body of the loop, with a {\cf do/while} 2590loop: 2591\indexapi{do/while} 2592 2593\begin{tabbing} 2594\hspace{0.5in} \= \hspace{0.3in} \= \kill 2595\> {\cf do } \\ 2596\> \> \emph{statement} \\ 2597\> {\cf while (} \emph{condition} {\cf );} \\ 2598\end{tabbing} 2599 2600\noindent Also, {\cf for} loops are also allowed: 2601 2602\begin{tabbing} 2603\hspace{0.5in} \= \hspace{0.3in} \= \kill 2604\> {\cf for (} \emph{initialization-statement} {\cf ;} \emph{condition} {\cf ;} \emph{iteration-statement} {\cf )} \\ 2605\> \> \emph{body} 2606\end{tabbing} 2607 2608\indexapi{for} 2609As in C++, a {\cf for} loop's initialization may contain variable 2610declarations and initializations, which are scoped locally to the {\cf for} 2611loop itself. For example, 2612 2613\begin{code} 2614 for (int i = 0; i < 3; ++i) { 2615 ... 2616 } 2617\end{code} 2618 2619As with {\cf if} statements, loop conditions may be relations or 2620numerical quantities (which are considered ``true'' if nonzero, 2621``false'' if zero), or strings (considered ``true'' if nonempty, 2622``false'' if the empty string \qkw{}). 2623 2624Inside the body of a loop, the {\cf break} statement terminates the loop 2625altogether, and the {\cf continue} statement skip to the end of the body 2626and proceeds to the next iteration of the loop. 2627 2628\section{Functions} 2629\label{sec:functions} 2630 2631\subsection{Function calls} 2632\label{sec:syntax:functioncalls} 2633\index{function calls} 2634 2635Function calls are very similar to C and related programming languages: 2636 2637\begin{tabbing} 2638\hspace{0.5in} \= \hspace{0.3in} \= \kill 2639\> \emph{functionname} {\cf (} \emph{arg1} {\cf ,} ... {\cf ,} \emph{argn} {\cf )} \\ 2640\end{tabbing} 2641 2642If the function returns a value (not \void), you may use its value as 2643an expression. It is fine to completely ignore the value of even 2644a non-\void function. 2645 2646In \langname, all arguments are passed by reference. This generally 2647will not be noticeably different from C-style ``pass by value'' 2648semantics, except if you pass the same variable as two separate 2649arguments to a function that modifies an argument's value. 2650 2651 2652\subsection{Function definitions} 2653\label{sec:syntax:functiondefinitions} 2654\index{functions!definitions} 2655 2656You may define functions much like in C or C++. 2657 2658\begin{quote} 2659\em 2660return-type ~ function-name ~ {\rm\cf (} optional-parameters {\rm\cf )} \\ 2661\rm 2662{\cf \{ } \\ 2663\em 2664\spc statements 2665 2666{\cf \} } 2667\end{quote} 2668 2669Parameters to functions are similar to shader parameters, except that 2670they do not permit initializers. A function call must pass values for 2671all formal parameters. Function parameters in \langname are all 2672\emph{passed by reference}, and are read-only within the body of the 2673function unless they are also designated as {\cf output} (in the same 2674manner as output shader parameters). 2675 2676Like for shaders, statements inside functions may be actual executions 2677(assignments, function call, etc.), local variable declarations (visible 2678only from within the body of the function), or local function 2679declarations (callable only from within the body of the function). 2680 2681The return type may be any simple data type, a {\cf struct}, or a {\cf 2682 closure}. Functions may not return arrays. The return type may be 2683{\cf void}, indicating that the function does not return a value (and 2684should not contain a {\cf return} statement). A {\cf return} statement 2685inside the body of the function will halt execution of the function at 2686that point, and designates the value that will be returned (if not a 2687{\cf void} function). 2688 2689Functions may be \emph{overloaded}. That is, multiple functions may be 2690defined to have the same name, as long as they have differently-typed 2691parameters, so that when the function is called the list of arguments can 2692select which version of the function is desired. When there are multiple 2693potential matches, function versions whose argument types match exactly are 2694favored, followed by those that match with type coercion (for example, 2695passing an {\cf int} when the function expects a {\cf float}, or passing a 2696{\cf float} when the function expects a \color), and finally by trying to 2697match the return value to the type of variable the result is assigned to. 2698 2699\subsection{Operator overloading} 2700\label{sec:syntax:operatoroverloading} 2701\index{operator overloading} 2702 2703OSL permits \emph{operator overloading}, which is the practice of providing 2704a function that will be called when you use an operator like {\cf +} or 2705{\cf *}. This is especially handy when you use {\cf struct} to define 2706mathematical types and wish for the usual math operators to work with them. 2707Here is a typical example, which also shows the special naming convention 2708that allows operator overloading: 2709 2710\begin{code} 2711 struct vector4 { 2712 float x, y, z, w; 2713 }; 2714 2715 vector4 __operator__add__ (vector4 a, vector4 b) { 2716 return vector4 (a.x+b.x, a.y+b.y, a.z+b.z, a.w+b.w); 2717 } 2718 2719 shader test () 2720 { 2721 vector4 a = vector4 (.2, .3, .4, .5); 2722 vector4 b = vector4 (1, 2, 3, 4); 2723 2724 vector4 c = a + b; // Will call __operator__add__(vector4,vector4) 2725 printf ("a+b = %g %g %g %g\n", c.x, c.y, c.z, c.w); 2726 } 2727\end{code} 2728 2729\noindent The full list of these special function names is as follows (in 2730order of decreasing operator precedence): 2731 2732\smallskip 2733 2734\begin{tabular}{ p{0.5in} p{2in} p{1.75in}} 2735%op & overload function name & ~ \\ 2736%\hline 2737{\cf \bfseries -} & {\cf __operator__neg__} & unary negation \\ 2738{\cf \bfseries \textasciitilde} & {\cf __operator__compl__} & unary bitwise complement \\ 2739{\cf \bfseries !} & {\cf __operator__not__} & unary boolean `not' \\[1.5ex] 2740{\cf \bfseries *} & {\cf __operator__mul__} & \\ 2741{\cf \bfseries /} & {\cf __operator__div__} & \\ 2742{\cf \bfseries \%} & {\cf __operator__mod__} & \\ 2743{\cf \bfseries +} & {\cf __operator__add__} & \\ 2744{\cf \bfseries -} & {\cf __operator__sub__} & \\[1.5ex] 2745{\cf \bfseries <<} & {\cf __operator__shl__} & \\ 2746{\cf \bfseries >>} & {\cf __operator__shr__} & \\[1.5ex] 2747{\cf \bfseries <} & {\cf __operator__lt__} & \\ 2748{\cf \bfseries <=} & {\cf __operator__le__} & \\ 2749{\cf \bfseries >} & {\cf __operator__gt__} & \\ 2750{\cf \bfseries >=} & {\cf __operator__ge__} & \\ 2751{\cf \bfseries ==} & {\cf __operator__eq__} & \\ 2752{\cf \bfseries !=} & {\cf __operator__ne__} & \\[1.5ex] 2753{\cf \bfseries \&} & {\cf __operator__bitand__} & \\ 2754{\cf \bfseries \textasciicircum} & {\cf __operator__xor__} & \\ 2755{\cf \bfseries |} & {\cf __operator__bitor__} & \\ 2756%{\cf \bfseries \&\&} & {\cf __operator__and__} & boolean and \\ 2757%{\cf \bfseries ||} & {\cf __operator__or__} & boolean or \\ 2758%\hline 2759\end{tabular} 2760 2761 2762\section{Global variables} 2763\label{sec:globalvars} 2764\index{global variables|(} 2765 2766\emph{Global variables} (sometimes called \emph{graphics state 2767variables}) contain the basic information that the renderer knows 2768about the point being shaded, such as position, surface orientation, and 2769default surface color. You need not declare these variables; they are 2770simply available by default in your shader. Global variables available 2771in shaders are listed in Table~\ref{tab:globalvars}. 2772 2773\begin{table}[H] 2774\begin{tabular}{|p{1.5in}p{4in}|} 2775\hline 2776{\bf Variable} & {\bf Description} \\ 2777\hline 2778\point\ {\ce P} & Position of the point you are shading. In a 2779displacement shader, changing this variable displaces the surface. \\ 2780\hline 2781\vector\ {\ce I} & The \emph{incident} ray direction, pointing from the 2782 viewing position to the shading position \P. \\ 2783\hline 2784\normal\ {\ce N} & The surface ``Shading'' normal of the surface at 2785\P. Changing \N yields bump mapping. \\ 2786\hline 2787\normal\ {\ce Ng} & The true surface normal at {\cf P}. This can differ 2788 from {\cf N}; {\cf N} can be overridden in various ways including bump 2789 mapping and user-provided vertex normals, but {\cf Ng} is always the 2790 true surface geometric normal 2791 of the surface at \P. \\ 2792\hline 2793\float\ {\ce u}, {\ce v} & The 2D parametric coordinates of \P (on the 2794 particular geometric primitive you are shading). \\ 2795\hline 2796\vector\ {\ce dPdu}, {\ce dPdv} & Partial derivatives $\partial 2797P/\partial u$ and $\partial P/\partial v$ tangent to the surface at \P. \\ 2798%\hline 2799%\vector\ {\ce L} & Direction of incoming light (points from {\cf Ps} to 2800% {\cf Pl}). \\ 2801%\hline 2802%\color\ {\ce Cl} & Incoming light color at P. \\ 2803\hline 2804\point\ {\ce Ps} & Position at which the light is being queried 2805 (currently only used for light attenuation shaders) \\ 2806%\\ 2807%\hline 2808%\normal\ {\ce Ns} & Axis about which the light is being queried 2809% (i.e., the axis passed to \illuminance), or the surface's \N if no 2810% axis was passed to \illuminance). 2811%\\ 2812%\hline 2813%\point\ {\ce Pl} & Position of the light source. \\ 2814%\hline 2815%\normal\ {\ce Nl} & Normal on the light (area light sources only). \\[1ex] 2816\hline 2817\float\ {\ce time} & Current shutter time for the point being shaded. \\ 2818\hline 2819\float\ {\ce dtime} & The amount of time covered by this shading sample. \\ 2820\hline 2821\vector\ {\ce dPdtime} & How the surface position \P is moving per unit time.\\ 2822\hline 2823\closurecolor\ {\ce \Ci} & Incident radiance --- a closure representing the color of the light leaving the surface from \P in the direction {\cf -I}. \\ 2824\hline 2825%\color\ {\ce \opacity} & Incident ray opacity --- the degree to which the viewer can ``see through'' the surface at \P. \\[1ex] 2826\end{tabular} 2827\caption{Global variables available inside shaders. 2828\label{tab:globalvars}} 2829\end{table} 2830 2831 2832\begin{comment} % old table 2833\begin{table} 2834\begin{tabular}{|p{1in}p{0.75in}p{0.75in}p{0.75in}p{1.7in}|} 2835\hline 2836{\bf Variable} & surface & displacement & volume & light \\ 2837\hline 2838\P & R & RW & R & R \\ 2839\I & R & & R & \\ 2840\N & RW & RW & & \\ 2841{\cf Ng} & R & R & & \\ 2842{\cf dPdu} & R & R & & \\ 2843{\cf dPdv} & R & R & & \\ 2844{\cf u, v} & R & R & R$^1$ & R$^1$ \\ 2845{\cf time} & R & R & R & R \\ 2846{\cf dtime} & R & R & R & R \\ 2847{\cf dPdtime} & R & R & R & R \\ 2848\Ci & RW & & RW & \\ 2849%\Oi & RW & & RW & \\ 2850%{\cf L} & R$^2$ & & R$^2$ & RW \\ 2851{\cf L} & & & & RW \\ 2852%{\cf Cl} & R$^2$ & & R$^2$ & RW \\ 2853{\cf Cl} & & & & RW \\ 2854{\cf Ps} & & & & R \\ 2855{\cf Ns} & & & & R \\ 2856%{\cf Pl} & & & R$^2$ & R \\ 2857%{\cf Nl} & & & R$^2$ & R \\ 2858{\cf Pl} & & & & R \\ 2859{\cf Nl} & & & & R \\ 2860\hline 2861\end{tabular} 2862\end{table} 2863\end{comment} 2864 2865\begin{table} 2866\begin{tabular}{|p{1in}p{0.75in}p{0.75in}p{0.75in}|} 2867\hline 2868{\bf Variable} & surface & displacement & volume \\ 2869\hline 2870\P & R & RW & R \\ 2871\I & R & & R \\ 2872\N & RW & RW & \\ 2873{\cf Ng} & R & R & \\ 2874{\cf dPdu} & R & R & \\ 2875{\cf dPdv} & R & R & \\ 2876{\cf Ps} & & & R \\ 2877{\cf u, v} & R & R & R \\ 2878{\cf time} & R & R & R \\ 2879{\cf dtime} & R & R & R \\ 2880{\cf dPdtime} & R & R & R \\ 2881\Ci & RW & & RW \\ 2882\hline 2883\end{tabular} 2884 2885%$^1$Certain surface variables (including \N, \Ng, \I, etc.) are readable 2886%in light or volume shaders, but in that case store the values for the 2887%surface whose shading triggered execution of the shader. Use caution: 2888%light may be gathered from a completely different place (for example, 2889%when stepping through a volume). 2890 2891%$^2$Light variables may be read in surface and volume shaders, but only 2892%inside \illuminance loops, and they refer to the current light being 2893%examined by the loop. 2894 2895\caption{Accessibility of variables by shader type 2896\label{tab:globalvaraccess}} 2897\end{table} 2898 2899\index{global variables|)} 2900 2901 2902\chapter{Standard Library Functions} 2903\label{chap:stdlibrary} 2904 2905%\apiitem{ret {\ce func} (args)} 2906%\indexapi{func()} 2907%\endapi 2908 2909\def\floatcolorpoint{The \emph{type} may be any of \float, \color, 2910 \point, \vector, or \normal. For \color and \point-like types, the 2911 computations are performed component-by-component (separately for $x$, 2912 $y$, and $z$).\xspace} 2913 2914\section{Basic math functions} 2915\label{sec:stdlib:math} 2916 2917\subsection{Mathematical constants} 2918\index{mathematical constants} 2919 2920\langname defines several mathematical constants: 2921 2922\medskip 2923 2924\begin{tabular}{p{1in} p{3in}} 2925{\cf M\_PI} & $\pi$ \\[0.5ex] 2926{\cf M\_PI\_2} & $\pi/2$ \\[0.5ex] 2927{\cf M\_PI\_4} & $\pi/4$ \\[0.5ex] 2928{\cf M\_2\_PI} & $2/\pi$ \\[0.5ex] 2929{\cf M\_2PI} & $2\pi$ \\[0.5ex] 2930{\cf M\_4PI} & $4\pi$ \\[0.5ex] 2931{\cf M\_2\_SQRTPI} & $2/\sqrt{\pi}$ \\[0.5ex] 2932{\cf M\_E} & $e$ \\[0.5ex] 2933{\cf M\_LN2} & $\ln 2$ \\[0.5ex] 2934{\cf M\_LN10} & $\ln 10$ \\[0.5ex] 2935{\cf M\_LOG2E} & $\log_2 e$ \\[0.5ex] 2936{\cf M\_LOG10E} & $\log_{10} e$ \\[0.5ex] 2937{\cf M\_SQRT2} & $\sqrt{2}$ \\[0.5ex] 2938{\cf M\_SQRT1\_2} & $\sqrt{1/2}$ \\[0.5ex] 2939\end{tabular} 2940 2941\subsection{Mathematical functions} 2942\index{mathematical functions} 2943\index{functions!mathematical} 2944 2945Most of these functions operate on a generic \emph{type} that my be any 2946of \float, \color, \point, \vector, or \normal. For \color and 2947\point-like types, the computations are performed component-by-component 2948(separately for $x$, $y$, and $z$). 2949 2950\medskip 2951 2952\apiitem{\emph{type} {\ce radians} (\emph{type} deg) \\ 2953\emph{type} {\ce degrees} (\emph{type} rad)} 2954\indexapi{radians()} \indexapi{degrees()} 2955Convert degrees to radians or radians to degrees. 2956\apiend 2957 2958\index{trigonometry} 2959\index{functions!trigonometric} 2960 2961\apiitem{\emph{type} {\ce cos} (\emph{type} x) \\ 2962\emph{type} {\ce sin} (\emph{type} x) \\ 2963\emph{type} {\ce tan} (\emph{type} x) } 2964\indexapi{cos()} \indexapi{sin()} \indexapi{tan()} 2965Computes the cosine, sine, or tangent of $x$ (measured in radians). 2966\apiend 2967 2968\apiitem{void {\ce sincos} (\emph {type} x, output \emph{type} sinval, output 2969\emph{type} cosval)} 2970\indexapi{sincos()} 2971Computes both the sine and cosine of $x$ (measured in radians). If both 2972are needed, this function is less expensive than calling {\cf sin()} and 2973{\cf cos()} separately. 2974\apiend 2975 2976\apiitem{\emph{type} {\ce acos} (\emph{type} x) \\ 2977\emph{type} {\ce asin} (\emph{type} y) \\ 2978\emph{type} {\ce atan} (\emph{type} y\_over\_x) \\ 2979\emph{type} {\ce atan2} (\emph{type} y, \emph{type} x)} 2980\indexapi{acos()} \indexapi{asin()} \indexapi{atan()} \indexapi{atan2()} 2981Compute the principal value of the arc cosine, arc sine, and arc 2982For {\cf acos()} and {\cf asin()}, the value of the argument 2983will first be clamped to $[-1,1]$ to avoid invalid domain. 2984 2985For {\cf acos()}, the result will always be in the range of $[0, \pi]$, 2986and for {\cf asin()} and {\cf atan()}, the result will always be in the 2987range of $[-\pi/2, \pi/2]$. For {\cf atan2()}, the signs of both 2988arguments are used to determine the quadrant of the return value. 2989\apiend 2990 2991\apiitem{\emph{type} {\ce cosh} (\emph{type} x) \\ 2992\emph{type} {\ce sinh} (\emph{type} x) \\ 2993\emph{type} {\ce tanh} (\emph{type} x) } 2994\indexapi{cosh()} \indexapi{sinh()} \indexapi{tanh()} 2995Computes the hyperbolic cosine, sine, and tangent of $x$ (measured in radians). 2996\apiend 2997 2998\apiitem{\emph{type} {\ce pow} (\emph{type} x, \emph{type} y) \\ 2999\emph{type} {\ce pow} (\emph{type} x, float y)} 3000\indexapi{pow()} 3001Computes $x^y$. This function will return 0 for ``undefined'' 3002operations, such as {\cf pow(-1,0.5)}. 3003\apiend 3004 3005\apiitem{\emph{type} {\ce exp} (\emph{type} x) \\ 3006\emph{type} {\ce exp2} (\emph{type} x) \\ 3007\emph{type} {\ce expm1} (\emph{type} x)} 3008\indexapi{exp()} \indexapi{exp2()} \indexapi{expm1()} 3009Computes $e^x$, $2^x$, and $e^x-1$, respectively. Note that 3010{\cf expm1(x)} is accurate even for very small values of $x$. 3011\apiend 3012 3013\apiitem{\emph{type} {\ce log} (\emph{type} x) \\ 3014\emph{type} {\ce log2} (\emph{type} x) \\ 3015\emph{type} {\ce log10} (\emph{type} x) \\ 3016\emph{type} {\ce log} (\emph{type} x, float b)} 3017\indexapi{log()} \indexapi{log2()} \indexapi{log10()} 3018Computes the logarithm of $x$ in base $e$, 2, 10, or arbitrary base $b$, 3019respectively. 3020\apiend 3021 3022\apiitem{\emph{type} {\ce logb} (\emph{type} x)} 3023\indexapi{logb()} 3024Returns the exponent of x, as a floating-point number. 3025\apiend 3026 3027\apiitem{\emph{type} {\ce sqrt} (\emph{type} x) \\ 3028\emph{type} {\ce inversesqrt} (\emph{type} x)} 3029\indexapi{sqrt()} \indexapi{inversesqrt()} 3030Computes $\sqrt{x}$ and $1/\sqrt{x}$. Returns 0 if $x<0$. 3031\apiend 3032 3033\apiitem{\emph{type} {\ce cbrt} (\emph{type} x)} 3034\indexapi{cbrt()} 3035Computes $\sqrt[3]{x}$. The sign of the return value will match $x$. 3036\apiend 3037 3038\apiitem{float {\ce hypot} (float x, float y) \\ 3039float {\ce hypot} (float x, float y, float z)} 3040\indexapi{hypot()} 3041Computes $\sqrt{x^2+y^2}$ and $\sqrt{x^2+y^2+z^z}$, respectively. 3042\apiend 3043 3044\apiitem{\emph{type} {\ce abs} (\emph{type} x) \\ 3045\emph{type} {\ce fabs} (\emph{type} x)} 3046\indexapi{abs()} \indexapi{fabs()} 3047Absolute value of $x$. (The two functions are synonyms.) 3048\apiend 3049 3050%\begin{annotate} 3051%Should we fully return to C conventions, with abs() being for integers 3052%and fabs being for float? Or should abs() simply be overloaded, like 3053%you'd do in C++ if we were starting from scratch today? 3054%\end{annotate} 3055 3056\apiitem{\emph{type} {\ce sign} (\emph{type} x)} 3057\indexapi{sign()} 3058Returns 1 if $x>0$, -1 if $x<0$, 0 if $x=0$. 3059\apiend 3060 3061\apiitem{\emph{type} {\ce floor} (\emph{type} x) \\ 3062\emph{type} {\ce ceil} (\emph{type} x) \\ 3063\emph{type} {\ce round} (\emph{type} x) \\ 3064\emph{type} {\ce trunc} (\emph{type} x) } 3065\indexapi{floor()} \indexapi{ceil()} \indexapi{round()} \indexapi{trunc()} 3066 3067Various rounding methods: {\cf floor} returns the largest integer less 3068than or equal to $x$; {\cf ceil} returns the smallest integer greater than 3069or equal to $x$; {\cf round} returns the closest integer to $x$, in 3070either direction; and {\cf trunc} returns the integral part of $x$ 3071(equivalent to {\cf floor} if $x>0$ and {\cf ceil} if $x<0$). 3072\apiend 3073 3074\apiitem{\emph{type} {\ce fmod} (\emph{type} a, \emph{type} b) \\ 3075\emph{type} {\ce mod} (\emph{type} a, \emph{type} b)} 3076\indexapi{fmod()} 3077\indexapi{mod()} 3078 3079The {\cf fmod()} function returns the floating-point remainder of $a/b$, 3080i.e., is the floating-point equivalent of the integer {\cf \%} operator. 3081It is nearly identical to the C or C++ {\cf fmod} function, except that 3082in OSL, {\cf fmod(a,0)} returns {\cf 0}, rather than {\cf NaN}. Note 3083that if $a < 0$, the return value will be negative. 3084 3085The {\cf mod()} function returns $a - b*\mbox{floor}(a/b)$, which will 3086always be a positive number or zero. 3087As an example, {\cf fmod(-0.25,1.0) = -0.25}, but {\cf mod(-0.25,1.0) = 3088 0.75}. For positive {\cf a} they return the same value. 3089 3090For both functions, the \emph{type} may be any of {\cf float}, \point, 3091\vector, \normal, or \color. 3092\apiend 3093 3094\apiitem{\emph{type} {\ce min} (\emph{type} a, \emph{type} b) \\ 3095\emph{type} {\ce max} (\emph{type} a, \emph{type} b) \\ 3096\emph{type} {\ce clamp} (\emph{type} x, \emph{type} minval, \emph{type} maxval)} 3097\indexapi{min()} \indexapi{max()} \indexapi{clamp()} 3098The {\cf min()} and {\cf max()} functions return the minimum or maximum, 3099respectively, of a list of two or more values. The {\cf clamp} 3100function returns 3101 3102\hspace{2em} {\cf min(max(x,minval),maxval)}, 3103 3104\noindent that is, the value $x$ clamped to the specified range. 3105\apiend 3106 3107\apiitem{\emph{type} {\ce mix} (\emph{type} x, \emph{type} y, \emph{type} alpha) \\ 3108\emph{type} {\ce mix} (\emph{type} x, \emph{type} y, float alpha)} 3109\indexapi{mix()} 3110The {\cf mix} function returns a linear blending : 3111$ x*(1-\alpha) + y*(\alpha) $ 3112\apiend 3113 3114\apiitem{\emph{type} {\ce select} (\emph{type} x, \emph{type} y, \emph{type} cond) \\ 3115\emph{type} {\ce select} (\emph{type} x, \emph{type} y, float cond) \\ 3116\emph{type} {\ce select} (\emph{type} x, \emph{type} y, int cond)} 3117\indexapi{mix()} 3118The {\cf select} function returns {\cf x} if {\cf cond} is zero, or {\cf y} 3119if {\cf cond} is nonzero. This is roughly equivalent to {\cf (cond ? y : x)}, 3120except that if {\cf cond} is a component-based type (such as {\cf color}), 3121the selection happens on a component-by-component basis. It is presumed 3122that the underlying implementation is not a true conditional and will not 3123incur any branching penalty. 3124\apiend 3125 3126\apiitem{int {\ce isnan} (float x) \\ 3127int {\ce isinf} (float x) \\ 3128int {\ce isfinite} (float x)} 3129\indexapi{isnan()} \indexapi{isinf()} \indexapi{isfinite()} 3130The {\cf isnan()} function returns 1 if $x$ is a not-a-number (NaN) 3131value, 0 otherwise. The {\cf isinf()} function returns 1 if $x$ is an 3132infinite (Inf or --Inf) value, 0 otherwise. The {\cf isfinite()} 3133function returns 1 if $x$ is an ordinary number (neither infinite nor 3134NaN), 0 otherwise. \apiend 3135 3136\apiitem{float {\ce erf} (float x) \\ 3137float {\ce erfc} (float x)} 3138\indexapi{erf()} \indexapi{erfc()} 3139The {\cf erf()} function returns the error function 3140${\mathrm{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2}} dt$. 3141The {\cf erfc} returns the complementary error function {\cf 1-erf(x)} 3142(useful in maintaining precision for large values of $x$). 3143\apiend 3144 3145\section{Geometric functions} 3146\label{sec:stdlib:geom} 3147\index{geometric functions} 3148\index{functions!geometric} 3149 3150\apiitem{\emph{ptype} {\ce ptype} (float f) \\ 3151\emph{ptype} {\ce ptype} (float x, float y, float z)} 3152\indexapi{point()} 3153\indexapi{vector()} 3154\indexapi{normal()} 3155 3156Constructs a point-like value (\emph{ptype} may be any of \point, 3157\vector, or \normal) from individual \float values. If constructed 3158from a single \float, the value will be replicated for $x$, $y$, and $z$. 3159 3160\apiend 3161 3162\apiitem{\emph{ptype} {\ce ptype} (string space, f) \\ 3163\emph{ptype} {\ce ptype} (string space, float x, float y, float z)} 3164\indexapi{point()} \indexapi{vector()} \indexapi{normal()} 3165Constructs a point-like value (\emph{ptype} may be any of \point, 3166\vector, or \normal) from individual \float coordinates, relative 3167to the named coordinate system. In other words, 3168\begin{code} 3169 point (space, x, y, z) 3170\end{code} 3171\noindent is equivalent to 3172\begin{code} 3173 transform (space, "common", point(x,y,z)) 3174\end{code} 3175(And similarly for \vector/\normal.) 3176\apiend 3177 3178\apiitem{float {\ce dot} (vector A, vector B)} 3179\indexapi{dot()} 3180Returns the inner product of the two vectors (or normals), i.e., 3181$A \cdot B = A_x B_x + A_y B_y + A_z C_z$. 3182\apiend 3183 3184\apiitem{vector {\ce cross} (vector A, vector B)} 3185\indexapi{cross()} 3186Returns the cross product of two vectors (or normals), i.e., 3187$A \times B$. 3188\apiend 3189 3190\apiitem{float {\ce length} (vector V) \\ 3191float {\ce length} (normal V)} 3192\indexapi{length()} 3193Returns the length of a vector or normal. 3194\apiend 3195 3196\apiitem{float {\ce distance} (point P0, point P1)} 3197\indexapi{distance()} 3198Returns the distance between two points. 3199\apiend 3200 3201\apiitem{float {\ce distance} (point P0, point P1, point Q)} 3202\indexapi{distance()} 3203Returns the distance from {\cf Q} to the closest point on the line 3204segment joining {\cf P0} and {\cf P1}. 3205\apiend 3206 3207\apiitem{vector {\ce normalize} (vector V) \\ 3208normal {\ce normalize} (normal V)} 3209\indexapi{normalize()} 3210Return a vector in the same direction as $V$ but with length 1, 3211that is, {\cf V / length(V)} . 3212\apiend 3213 3214\apiitem{vector {\ce faceforward} (vector N, vector I, vector Nref) \\ 3215vector {\ce faceforward} (vector N, vector I)} 3216\indexapi{faceforward()} 3217If {\cf dot (Nref, I)} $<0$, returns {\cf N}, otherwise returns {\cf -N}. 3218For the version with only two arguments, {\cf Nref} is implicitly {\cf 3219Ng}, the true surface normal. The point of these routines is to 3220return a version of {\cf N} that faces towards the camera --- in the 3221direction ``opposite'' of {\cf I}. 3222 3223To further clarify the situation, here is the implementation of 3224{\cf faceforward} expressed in \langname: 3225 3226\begin{code} 3227vector faceforward (vector N, vector I, vector Nref) 3228{ 3229 return (I.Nref > 0) ? -N : N; 3230} 3231 3232vector faceforward (vector N, vector I) 3233{ 3234 return faceforward (N, I, Ng); 3235} 3236\end{code} 3237\apiend 3238 3239\apiitem{vector {\ce reflect} (vector I, vector N)} 3240\indexapi{reflect()} 3241For incident vector {\cf I} and surface orientation {\cf N}, returns the 3242reflection direction {\cf R = I - 2*(N.I)*N}. Note that {\cf N} must be 3243normalized (unit length) for this formula to work properly. 3244\apiend 3245 3246\apiitem{vector {\ce refract} (vector I, vector N, float eta)} 3247\indexapi{refract()} 3248For incident vector {\cf I} and surface orientation {\cf N}, 3249returns the refraction direction using Snell's law. The {\cf eta} 3250parameter is the ratio of the index of refraction of the volume containing 3251{\cf I} divided by the index of refraction of the volume being entered. 3252The result is not necessarily normalized and a zero-length vector is 3253returned in the case of total internal reflection. 3254For reference, here is the equivalent \langname of the implementation: 3255 3256\begin{code} 3257vector refract (vector I, vector N, float eta) 3258{ 3259 float IdotN = dot (I, N); 3260 float k = 1 - eta*eta * (1 - IdotN*IdotN); 3261 return (k < 0) ? vector(0,0,0) : (eta*I - N * (eta*IdotN + sqrt(k))); 3262} 3263\end{code} 3264\apiend 3265 3266\apiitem {void {\ce fresnel} (vector I, normal N, float eta, \\ 3267 \mbox{\hspace{1in}} output float Kr, output float Kt, \\ 3268 \mbox{\hspace{1in}} output vector R, output vector T); } 3269\indexapi{fresnel()} 3270According to Snell's law and the Fresnel equations, {\cf fresnel} 3271computes the reflection and transmission direction vectors {\cf R} and 3272{\cf T}, respectively, as well as the scaling factors for reflected 3273and transmitted light, {\cf Kr} and {\cf Kt}. The {\cf I} parameter 3274is the normalized incident ray, {\cf N} is the normalized surface normal, 3275and {\cf eta} is the ratio of refractive index of the medium 3276containing {\cf I} to that on the opposite side of the surface. 3277\apiend 3278 3279\apiitem{point {\ce rotate} (point Q, float angle, point P0, point P1) \\ 3280point {\ce rotate} (point Q, float angle, vector axis)} 3281\indexapi{rotate()} 3282Returns the point computed by rotating point {\cf Q} by {\cf angle} 3283radians about the axis that passes from point {\cf P0} to {\cf P1}, 3284or about the {\cf axis} vector centered on the origin. 3285\apiend 3286 3287\apiitem{\emph{ptype} {\ce transform} (string tospace, \emph{ptype} p) \\ 3288\emph{ptype} {\ce transform} (string fromspace, string tospace, \emph{ptype} p) \\ 3289\emph{ptype} {\ce transform} (matrix Mto, \emph{ptype} p)} 3290\indexapi{transform()} 3291 3292Transform a \point, \vector, or \normal (depending on the type of the 3293\emph{ptype p} argument) from the coordinate system named by 3294\emph{fromspace} to the one named by \emph{tospace}. If 3295\emph{fromspace} is not supplied, $p$ is assumed to be in \commonspace 3296coordinates, so the transformation will be from \commonspace to 3297\emph{tospace}. A $4 \times 4$ matrix may be passed directly rather 3298than specifying coordinate systems by name. 3299 3300Depending on the type of the passed point $p$, different transformation 3301semantics will be used. A \point will transform as a position, a 3302\vector as a direction without regard to positioning, and a \normal will 3303transform subtly differently than a \vector in order to preserve 3304orthogonality to the surface under nonlinear 3305scaling.\footnote{Technically, what happens is this: The \emph{from} and 3306 \emph{to} spaces determine a $4 \times 4$ matrix. A \point $(x,y,z)$ 3307 will transform the 4-vector $(x,y,z,1)$ by the matrix; a \vector will 3308 transform $(x,y,z,0)$ by the matrix; a \normal will transform 3309 $(x,y,z,0)$ by the inverse of the transpose of the matrix.} 3310 3311\apiend 3312 3313 3314\apiitem{float {\ce transformu} (string tounits, float x) \\ 3315float {\ce transformu} (string fromunits, string tounits, float x)} 3316\indexapi{transformu()} 3317\index{units} 3318 3319Transform a measurement from \emph{fromunits} to \emph{tounits}. If 3320\emph{fromunits} is not supplied, $x$ will be assumed to be in 3321\commonspace units. 3322 3323For length conversions, unit names may be any of: \qkw{mm}, \qkw{cm}, 3324\qkw{m}, \qkw{km}, \qkw{in}, \qkw{ft}, \qkw{mi}, or the name of any 3325coordinate system, including \qkw{common}, \qkw{world}, \qkw{shader}, or 3326any other named coordinate system that the renderer knows about. 3327 3328For time conversions, units may be any of: \qkw{s}, \qkw{frames}, or 3329\qkw{common} (which indicates whatever timing units the renderer is 3330using). 3331 3332It is only valid to convert length units to other length units, or time 3333units to other time units. Attempts to convert length to time or vice 3334versa will result in an error. Don't even think about trying to convert 3335monetary units to time. 3336\apiend 3337 3338 3339 3340\section{Color functions} 3341\label{sec:stdlib:color} 3342\index{color functions} 3343\index{functions!color} 3344 3345\apiitem{color {\ce color} (float f) \\ 3346color {\ce color} (float r, float g, float b)} 3347\indexapi{color()} 3348Constructs a \color from individual \float values. If constructed 3349from a single \float, the value will be replicated for $r$, $g$, and $b$. 3350\apiend 3351 3352\apiitem{color {\ce color} (string colorspace, f) \\ 3353color {\ce color} (string colorspace, float r, float g, float b)} 3354\indexapi{color()} 3355Constructs an RGB \color that is equivalent to the individual \float values in a 3356named color space. In other words, 3357\begin{code} 3358 color (colorspace, r, g, b) 3359\end{code} 3360\noindent is equivalent to 3361\begin{code} 3362 transformc (colorspace, "rgb", color(r, g, b)) 3363\end{code} 3364\apiend 3365 3366\apiitem{float {\ce luminance} (color rgb)} 3367\indexapi{luminance()} 3368Returns the linear luminance of the color \emph{rgb}, which is 3369implemented per the ITU-R standard as $0.2126 R + 0.7152 G + 0.0722 B$. 3370\apiend 3371 3372\apiitem{color {\ce blackbody} (float temperatureK)} 3373\indexapi{blackbody()} 3374 3375The {\cf blackbody()} function returns the blackbody emission (the 3376incandescent glow of warm bodies) expected from a material of the given 3377temperature in Kelvin, in units of $W/m^2$. Note that {\cf emission()} has units 3378of radiance, so will require a scaling factor of $1/\pi$ on surfaces, and 3379$1/4\pi$ on volumes to convert to $W/m^2/sr$. 3380\apiend 3381 3382\apiitem{color {\ce wavelength_color} (float wavelength_nm)} 3383\indexapi{wavelength_color()} 3384Returns an RGB color corresponding as closely as possible to the 3385perceived color of a pure spectral color of the given wavelength (in nm). 3386\apiend 3387 3388\apiitem{color {\ce transformc} (string fromspace, string tospace, color Cfrom)\\ 3389color {\ce transformc} (string tospace, color Cfrom)} 3390\indexapi{transformc()} 3391Transforms color \emph{Cfrom} from color space \emph{fromspace} to 3392color space \emph{tospace}. If \emph{fromspace} is not supplied, 3393it is assumed to be transforming from \rgbspace. 3394 3395%\begin{annotate} 3396%\QUESTION Should this be renamed `ctransform' to match RMan? 3397%\end{annotate} 3398\apiend 3399 3400 3401\section{Matrix functions} 3402\label{sec:stdlib:matrix} 3403\index{matrix functions} 3404\index{functions!matrix} 3405 3406\apiitem{matrix {\ce matrix} (float m00, float m01, float m02, float m03, \\ 3407\bigspc\spc float m10, float m11, float m12, float m13, \\ 3408\bigspc\spc float m20, float m21, float m22, float m23, \\ 3409\bigspc\spc float m30, float m31, float m32, float m33)} 3410\indexapi{matrix()} 3411Constructs a \matrix from 16 individual \float values, in row-major 3412order. 3413\apiend 3414 3415\apiitem{matrix {\ce matrix} (float f)} 3416\indexapi{matrix()} 3417Constructs a \matrix with $f$ in all diagonal components, 0 in all other 3418components. In other words, {\cf matrix(1)} is the identity matrix, and 3419{\cf matrix(f)} is {\cf f*matrix(1)}. 3420\apiend 3421 3422\apiitem{matrix {\ce matrix} (string fromspace, float m00, ..., float m33) \\ 3423matrix {\ce matrix} (string fromspace, float f)} 3424\indexapi{matrix()} 3425Constructs a \matrix relative to the named space, multiplying it by the 3426{\cf space}-to-{\cf common} transformation matrix. If the coordinate 3427system name is unknown, it will be assumed to be the identity matrix. 3428 3429Note that {\cf matrix (space, 1)} returns the 3430\emph{space}-to-{\cf common} transformation matrix. If the coordinate 3431system name is unknown, it will be assumed to be the identity matrix. 3432\apiend 3433 3434\apiitem{matrix {\ce matrix} (string fromspace, string tospace)} 3435\indexapi{matrix()} 3436Constructs a \matrix that can be used to transform coordinates from 3437\emph{fromspace} to \emph{tospace}. If either of the coordinate 3438system names are unknown, they will be assumed to be the identity matrix. 3439\apiend 3440 3441\apiitem{int {\ce getmatrix} (string fromspace, string tospace, output 3442 matrix M)} 3443\indexapi{getmatrix()} 3444 3445Sets \emph{M} to the \matrix that transforms coordinates from 3446\emph{fromspace} to \emph{tospace}. Return 1 upon success, or 0 if 3447either of the coordinate system names are unknown (in which case 3448\emph{M} will not be modified). This is very similar to the 3449{\cf matrix(from,to)} constructor, except that {\cf getmatrix} allows 3450the shader to gracefully handle unknown coordinate system names. 3451\apiend 3452 3453\apiitem{float {\ce determinant} (matrix M)} 3454\indexapi{determinant()} 3455Computes the determinant of matrix $M$. 3456\apiend 3457 3458\apiitem{matrix {\ce transpose} (matrix M)} 3459\indexapi{transpose()} 3460Computes the transpose of matrix $M$. 3461\apiend 3462 3463 3464 3465\section{Pattern generation} 3466\label{sec:stdlib:pattern} 3467\index{pattern generation functions} 3468\index{functions!pattern generation} 3469 3470\apiitem{float {\ce step} (float edge, float x) \\ 3471\emph{type} {\ce step} (\emph{type} edge, \emph{type} x)} 3472\indexapi{step()} 3473Returns 0 if $x < {\mathit edge}$ and 1 if $x \ge {\mathit edge}$. 3474 3475The \emph{type} may be any of of \float, \color, \point, \vector, or 3476\normal. For \color and \point-like types, the computations are 3477performed component-by-component (separately for $x$, $y$, and $z$). 3478\apiend 3479 3480\apiitem{float {\ce linearstep} (float edge0, float edge1, float x) \\ 3481\emph{type} {\ce linearstep} (\emph{type} edge0, \emph{type} edge1, \emph{type} x)} 3482\indexapi{linearstep()} 3483Returns 0 if $x \le {\mathit edge0}$, and 1 if $x \ge {\mathit edge1}$, 3484and performs a linear 3485interpolation between 0 and 1 when ${\mathit edge0} < x < {\mathit edge1}$. 3486This is equivalent to {\cf step(edge0, x)} when {\cf edge0 == edge1}. 3487For \color and \point-like types, the computations are 3488performed component-by-component (separately for $x$, $y$, and $z$). 3489\apiend 3490 3491\apiitem{float {\ce smoothstep} (float edge0, float edge1, float x) \\ 3492\emph{type} {\ce smoothstep} (\emph{type} edge0, \emph{type} edge1, \emph{type} x)} 3493\indexapi{smoothstep()} 3494Returns 0 if $x \le {\mathit edge0}$, and 1 if $x \ge {\mathit edge1}$, 3495and performs a smooth Hermite 3496interpolation between 0 and 1 when ${\mathit edge0} < x < {\mathit edge1}$. 3497This is useful in cases where you would want a thresholding function 3498with a smooth transition. 3499 3500The \emph{type} may be any of of \float, \color, \point, \vector, or 3501\normal. For \color and \point-like types, the computations are 3502performed component-by-component. 3503\apiend 3504 3505\apiitem{float {\ce smooth_linearstep} (float edge0, float edge1, float x, float eps) \\ 3506\emph{type} {\ce smooth_linearstep} (\emph{type} edge0, \emph{type} edge1, \emph{type} x, \emph{type} eps)} 3507\indexapi{smooth_linearstep()} 3508This function is strictly linear between ${\mathit edge0}+{\mathit eps}$ and ${\mathit edge1}-{\mathit eps}$ 3509but smoothly ramps to 0 between ${\mathit edge0}-{\mathit eps}$ and ${\mathit edge0}+{\mathit eps}$ 3510and smoothly ramps to 1 between ${\mathit edge1}-{\mathit eps}$ and ${\mathit edge1}+{\mathit eps}$. 3511It is 0 when $x \le {\mathit edge0}-{\mathit eps}$, and 1 if $x \ge {\mathit edge1}+{\mathit eps}$, 3512and performs a linear 3513interpolation between 0 and 1 when ${\mathit edge0} < x < {\mathit edge1}$. 3514For \color and \point-like types, the computations are 3515performed component-by-component. 3516\apiend 3517 3518 3519%\section{Noise functions} 3520%\label{sec:stdlib:noise} 3521% 3522%Noise functions (sometimes called ``Perlin noise'') 3523 3524\apiitem{\emph{type} {\ce noise} (string noisetype, float u, ...) \\ 3525\emph{type} {\ce noise} (string noisetype, float u, float v, ...) \\ 3526\emph{type} {\ce noise} (string noisetype, point p, ...) \\ 3527\emph{type} {\ce noise} (string noisetype, point p, float t, ...) 3528} 3529\indexapi{noise()} 3530 3531Returns a continuous, pseudo-random (but repeatable) scalar field 3532defined on a domain of dimension 1 (\float), 2 (2 \float's), 3 (\point), 3533or 4 (\point and \float), with a return value of either 1D (\float) or 3D 3534(\color, \point, \vector, or \normal). 3535 3536The {\cf noisename} specifies which of a variety of possible noise 3537functions will be used. 3538 3539\apiitem{"perlin", "snoise"} 3540\vspace{12pt} 3541 3542A signed Perlin-like gradient noise with an output range of $[-1,1]$, 3543approximate average value of $0$, and is exactly $0$ at integer lattice 3544points. This is equivalent to the {\cf snoise()} function. 3545 3546\apiend 3547\vspace{-16pt} 3548 3549\apiitem{"uperlin", "noise"} 3550\vspace{12pt} 3551An unsigned Perlin-like gradient noise with an output range of $(0,1)$, 3552approximate average value of $0.5$, and is exactly $0.5$ at integer 3553lattice points. This is equivalent to the {\cf noise()} function (the 3554one that doesn't take a name string). 3555\apiend 3556\vspace{-16pt} 3557 3558\apiitem{"cell"} 3559\vspace{12pt} 3560A discrete function that is constant on $[i,i+1)$ for all integers $i$ 3561(i.e., {\cf cellnoise(x) == cellnoise(floor(x))}), but has a different 3562and uncorrelated value at every integer. The range is $[0,1]$, its 3563large-scale average is 0.5, and its values are evenly distributed over 3564$[0,1]$. 3565\apiend 3566 3567\apiitem{"hash"} 3568\vspace{12pt} 3569A function that returns a different, uncorrelated (but deterministic and 3570repeatable) value at every real input coordinate. The range is $[0,1]$, its 3571large-scale average is 0.5, and its values are evenly distributed over 3572$[0,1]$. 3573\apiend 3574 3575\apiitem{"simplex"} 3576\vspace{12pt} 3577A signed simplex noise with an output range of $[-1,1]$, 3578approximate average value of $0$. 3579\apiend 3580 3581\apiitem{"usimplex"} 3582\vspace{12pt} 3583An unsigned simplex noise with an output range of $[0,1]$, 3584approximate average value of $0.5$. 3585\apiend 3586 3587\apiitem{"gabor"} 3588\vspace{12pt} 3589A band-limited, filtered, sparse convolution noise based on the 3590Gabor impulse function (see Lagae et al., SIGGRAPH 2012). Our Gabor 3591noise is designed to have somewhat similar frequency content and range 3592as Perlin noise (range $[-1,1]$, approximately large-scale average of 3593$0$). It is significantly more expensive than Perlin noise, but its 3594advantage is that it correctly filters automatically based on the input 3595derivatives. Gabor noise allows several optional parameters to the 3596{\cf noise()} call: 3597 3598\apiitem{"anisotropic", <int> \\ 3599"direction", <vector>} 3600\vspace{12pt} 3601If {\cf anisotropic} is 0 (the default), Gabor noise 3602will be isotropic. If {\cf anisotropic} is 1, the Gabor noise will 3603be anisotropic with the 3D frequency given by the {\cf direction} 3604vector (which defaults to {\cf (1,0,0)}). If {\cf anisotropic} is 36052, a hybrid mode will be used which is anisotropic along the 3606{\cf direction} vector, but radially isotropic perpendicular to that 3607vector. The {\cf direction} vector is not used if {\cf anisotropic} 3608is 0. 3609\apiend 3610\vspace{-16pt} 3611 3612\apiitem{"bandwidth", <float>} 3613\vspace{12pt} 3614Controls the bandwidth for Gabor noise. 3615The default is 1.0. 3616\apiend 3617\vspace{-16pt} 3618 3619\apiitem{"impulses", <float>} 3620\vspace{12pt} 3621Controls the number of impulses per cell for Gabor noise. 3622The default is 16. 3623\apiend 3624\vspace{-16pt} 3625 3626\apiitem{"do_filter", <int>} 3627\vspace{12pt} 3628If {\cf do_filter} is 0, no filtering/antialiasing will 3629be performed. The default is 1 (yes, do filtering). There is probably 3630no good reason to ever turn off the filtering, it is primarily to test 3631that the filtering is working properly. 3632\apiend 3633\vspace{-16pt} 3634 3635\apiend 3636 3637%\vspace{-16pt} 3638 3639Note that some of the noise varieties have an output range of $[-1,1]$ 3640but others have range $[0,1]$; some may automatically antialias their 3641output (based on the derivatives of the lookup coordinates) and others 3642may not, and various other properties may differ. The user should be 3643aware of which noise varieties are useful in various circumstances. 3644 3645A particular renderer's implementation of OSL may supply additional 3646noise varieties not described here. 3647 3648The {\cf noise()} functions take optional arguments after their 3649coordinates, passed as token/value pairs (similarly to optional texture 3650arguments). Generally, such arguments are specific to the type of 3651noise, and are ignored for noise types that don't understand them. 3652 3653\apiend 3654 3655 3656 3657\apiitem{\emph{type} {\ce pnoise} (string noisetype, float u, float uperiod) \\ 3658\emph{type} {\ce pnoise} (string noisetype, float u, float v, float uperiod, float vperiod) \\ 3659\emph{type} {\ce pnoise} (string noisetype, point p, point pperiod) \\ 3660\emph{type} {\ce pnoise} (string noisetype, point p, float t, point pperiod, float tperiod) 3661} 3662\indexapi{pnoise()} 3663 3664Periodic version of {\cf noise}, in which the domain wraps with the given 3665period(s). Generally, only integer-valued periods are supported. 3666\apiend 3667 3668 3669 3670 3671\apiitem{\emph{type} {\ce noise} (float u) \\ 3672\emph{type} {\ce noise} (float u, float v) \\ 3673\emph{type} {\ce noise} (point p) \\ 3674\emph{type} {\ce noise} (point p, float t) 3675\smallskip \\ 3676\emph{type} {\ce snoise} (float u) \\ 3677\emph{type} {\ce snoise} (float u, float v) \\ 3678\emph{type} {\ce snoise} (point p) \\ 3679\emph{type} {\ce snoise} (point p, float t)} 3680\indexapi{snoise()} 3681\indexapi{noise()} 3682 3683The old {\cf noise(...coords...)} function is equivalent to 3684{\cf noise("uperlin",...coords...)} and {\cf snoise(...coords...)} 3685is equivalent to {\cf noise("perlin",...coords...)}. 3686\apiend 3687 3688 3689\apiitem{\emph{type} {\ce pnoise} (float u, float uperiod) \\ 3690\emph{type} {\ce pnoise} (float u, float v, float uperiod, float vperiod) \\ 3691\emph{type} {\ce pnoise} (point p, point pperiod) \\ 3692\emph{type} {\ce pnoise} (point p, float t, point pperiod, float tperiod) 3693\smallskip \\ 3694\emph{type} {\ce psnoise} (float u, float uperiod) \\ 3695\emph{type} {\ce psnoise} (float u, float v, float uperiod, float vperiod) \\ 3696\emph{type} {\ce psnoise} (point p, point pperiod) \\ 3697\emph{type} {\ce psnoise} (point p, float t, point pperiod, float tperiod)} 3698\indexapi{pnoise()} 3699\indexapi{psnoise()} 3700 3701The old {\cf pnoise(...coords...)} function is equivalent to 3702{\cf pnoise("uperlin",...coords...)} and {\cf psnoise(...coords...)} 3703is equivalent to {\cf pnoise("perlin",...coords...)}. 3704\apiend 3705 3706\apiitem{\emph{type} {\ce cellnoise} (float u) \\ 3707\emph{type} {\ce cellnoise} (float u, float v) \\ 3708\emph{type} {\ce cellnoise} (point p) \\ 3709\emph{type} {\ce cellnoise} (point p, float t)} 3710\indexapi{cellnoise()} 3711The old {\cf cellnoise(...coords...)} function is equivalent to 3712{\cf noise("cell",...coords...)}. 3713\apiend 3714 3715\apiitem{\emph{type} {\ce hashnoise} (float u) \\ 3716\emph{type} {\ce hashnoise} (float u, float v) \\ 3717\emph{type} {\ce hashnoise} (point p) \\ 3718\emph{type} {\ce hashnoise} (point p, float t)} 3719\indexapi{hashnoise()} 3720Returns a deterministic, repeatable \emph{hash} of the 1-, 2-, 3-, or 37214-D coordinates. The return values will be evenly 3722distributed on $[0,1]$ and be completely repeatable when passed the same 3723coordinates again, yet will be uncorrellated to hashes of any other 3724positions (including nearby points). This is like having a random value 3725indexed spatially, but that will be repeatable from frame to frame of an 3726animation (provided its input is \emph{precisely} identical). 3727\apiend 3728 3729\apiitem{int {\ce hash} (float u) \\ 3730int {\ce hash} (float u, float v) \\ 3731int {\ce hash} (point p) \\ 3732int {\ce hash} (point p, float t) \\ 3733int {\ce hash} (int i)} 3734\indexapi{hash()} 3735Returns a deterministic, repeatable integer \emph{hash} of the 1-, 2-, 3-, 3736or 4-D coordinates. 3737\apiend 3738 3739\apiitem{\emph{type} {\ce spline} (string basis, float x, \emph{type} $\mathtt{y}_0$, \emph{type} $\mathtt{y}_1$, ... \emph{type} $\mathtt{y}_{n-1}$)\\ 3740\emph{type} {\ce spline} (string basis, float x, \emph{type} y[]) \\ 3741\emph{type} {\ce spline} (string basis, float x, int nknots, \emph{type} y[])} 3742\indexapi{spline()} 3743 3744As $x$ varies from 0 to 1, {\cf spline} returns the value of a cubic 3745interpolation of uniformly-spaced knots $y_0$...$y_{n-1}$, or 3746$y[0]$...$y[n-1]$ for the array version of the call (where $n$ is the 3747length of the array), or $y[0]$...$y[nknots-1]$ for the version that 3748explicitly specifies the number of knots (which may be less than the 3749full array length). The input value $x$ will be clamped to lie 3750on $[0,1]$. The \emph{type} may be any of \float, \color, 3751\point, \vector, or \normal; for multi-component types (e.g. \color), 3752each component will be interpolated separately. 3753 3754The type of interpolation is specified by the \emph{basis} name, 3755\emph{basis} parameter, which may be any of: \qkw{catmull-rom}, 3756\qkw{bezier}, \qkw{bspline}, \qkw{hermite}, \qkw{linear}, or 3757\qkw{constant}. Some basis 3758types require particular numbers of knot values -- Bezier splines 3759require $3n+1$ values, Hermite splines require $2n+2$ values, and all of 3760Catmull-Rom, linear, and constant requires $3+n$, where in all cases, 3761$n \ge 1$ is the number of spline segments. 3762 3763To maintain consistency with the other spline types, \qkw{linear} splines will 3764ignore the first and last data value; interpolating piecewise-linearly 3765between $y_1$ and $y_{n-2}$, and \qkw{constant} splines ignore the first 3766and the two last data values. 3767\apiend 3768 3769\apiitem{float {\ce splineinverse} (string basis, float v, float $\mathtt{y}_0$, ... float $\mathtt{y}_{n-1}$)\\ 3770float {\ce splineinverse} (string basis, float v, float y[]) \\ 3771float {\ce splineinverse} (string basis, float v, int nknots, float y[])} 3772\indexapi{splineinverse()} 3773 3774Computes the \emph{inverse} of the {\cf spline()} function, i.e., returns 3775the value $x$ for which \\ 3776 \spc {\cf spline (basis, x, y...)}\\ 3777would return value 3778$v$. Results are undefined if the knots do not specifiy a monotonic 3779(only increasing or only decreasing) set of values. 3780 3781Note that the combination of {\cf spline} and {\cf splineinverse} makes 3782it possible to compute a full spline-with-nonuniform-abscissae: 3783\begin{smallcode} 3784 float v = splineinverse (basis, x, nknots, abscissa); 3785 result = spline (basis, v, nknots, value); 3786\end{smallcode} 3787\apiend 3788 3789 3790\newpage 3791\section{Derivatives and area operators} 3792\label{sec:stdlib:derivs} 3793\index{derivative functions} 3794\index{functions!derivatives and area} 3795\index{derivatives} 3796 3797\apiitem{float {\ce Dx} (float a), {\ce Dy} (float a), {\ce Dz} (float a) \\ 3798vector {\ce Dx} (point a), {\ce Dy} (point a), {\ce Dz} (point a) \\ 3799vector {\ce Dx} (vector a), {\ce Dy} (vector a), {\ce Dz} (vector a)\\ 3800color {\ce Dx} (color a), {\ce Dy} (color a), {\ce Dz} (color a)} 3801\indexapi{Dx()} \indexapi{Dy()} 3802Compute an approximation to the partial derivatives of $a$ with respect to 3803each of two principal directions, $\partial a / \partial x$ and 3804$\partial a / \partial y$. Depending on the renderer 3805implementation, those directions may be aligned to the image plane, 3806on the surface of the object, or something else. 3807 3808The {\cf Dz()} function is only meaningful for volumetric shading, and 3809is expected to return {\cf 0} in other contexts. It is also possible 3810that particular OSL implementations may only return ``correct'' {\cf Dz} 3811values for particular inputs (such as \P). 3812\apiend 3813 3814\apiitem{float {\ce filterwidth} (float x) \\ 3815vector {\ce filterwidth} (point x) \\ 3816vector {\ce filterwidth} (vector x)} 3817\indexapi{filterwidth()} 3818Compute differentials of the argument $x$, i.e., the approximate change 3819in $x$ between adjacent shading samples. 3820\apiend 3821 3822 3823\apiitem{float {\ce area} (point p)} 3824\indexapi{area()} 3825Returns the differential area of position $p$ corresponding to this 3826shading sample. If $p$ is the actual surface position \P, then 3827{\ce area(P)} will return the surface area of the section of the 3828surface that is ``covered'' by this shading sample. 3829\apiend 3830 3831\apiitem{vector {\ce calculatenormal} (point p)} 3832\indexapi{calculatenormal()} 3833Returns a vector perpendicular to the surface that is defined by point 3834$p$ (as $p$ is computed at all points on the currently-shading surface), 3835taking into account surface orientation. 3836\apiend 3837 3838\apiitem{float {\ce aastep} (float edge, float s) \\ 3839float {\ce aastep} (float edge, float s, float ds) \\ 3840float {\ce aastep} (float edge, float s, float dedge, float ds)} 3841\indexapi{aastep()} 3842Computes an antialiased step function, similar to {\cf step(edge,s)} but 3843filtering the edge to take into account how rapidly {\cf s} and {\cf edge} 3844are changing over the surface. If the differentials {\cf ds} and/or 3845{\cf dedge} are not passed explicitly, they will be automatically 3846computed (using {\cf filterwidth()}). 3847\apiend 3848 3849 3850\section{Displacement functions} 3851\label{sec:stdlib:displace} 3852\index{displacement} 3853\index{bump mapping} 3854\index{functions!displacement} 3855 3856\apiitem{void {\ce displace} (float amp) \\ 3857void {\ce displace} (string space, float amp) \\ 3858void {\ce displace} (vector offset)} 3859\indexapi{displace()} 3860 3861Displace the surface in the direction of the shading normal \N by 3862\emph{amp} units as measured in the named \emph{space} (or \commonspace 3863if none is specified). Alternately, the surface may be moved by a fully 3864general \emph{offset}, which does not need to be in the direction of the 3865surface normal. 3866 3867In either case, this function both displaces the surface and adjusts the 3868shading normal \N to be the new surface normal of the displaced surface 3869(properly handling both continuously smooth surfaces as well as 3870interpolated normals on faceted geometry, without introducing faceting 3871artifacts). 3872\apiend 3873 3874\apiitem{void {\ce bump} (float amp) \\ 3875void {\ce bump} (string space, float amp) \\ 3876void {\ce bump} (vector offset)} 3877\indexapi{bump()} 3878 3879Adjust the shading normal \N to be the surface normal as if the 3880surface had been displaced by the given amount (see the {\cf displace()} 3881function description), but without actually moving the surface 3882positions. 3883\apiend 3884 3885 3886\section{String functions} 3887\label{sec:stdlib:string} 3888\index{string functions} 3889\index{functions!string} 3890 3891\apiitem{void {\ce printf} (string fmt, ...)} 3892\indexapi{printf()} 3893 3894Much as in C, {\cf printf()} takes a format string {\cf fmt} and an 3895argument list, and prints the resulting formatted string to the console. 3896 3897Where the {\cf fmt} contains a format string similar to {\cf printf} in 3898the C language. The {\cf \%d}, {\cf \%i}, {\cf \%o}, and {\cf \%x} 3899arguments expect an {\cf int} argument. The {\cf \%f}, {\cf \%g}, and 3900{\cf \%e} expect a \float, \color, point-like, or \matrix argument (for 3901multi-component types such as \color, the format will be applied to each 3902of the components). The {\cf \%s} expects a {\cf string} or 3903{\cf closure} argument. 3904 3905All of the substition commands follow the usual C/C++ formatting rules, 3906so format commands such as {\cf "\%6.2f"}, etc., should work as 3907expected. 3908\apiend 3909 3910\apiitem{string {\ce format} (string fmt, ...)} 3911\indexapi{format()} 3912The {\cf format} function works similarly to {\cf printf}, except that 3913instead of printing the results, it returns the formatted text as a 3914{\cf string}. 3915\apiend 3916 3917\apiitem{void {\ce error} (string fmt, ...) \\ 3918void {\ce warning} (string fmt, ...)} 3919\indexapi{error()} \indexapi{warning()} 3920The {\cf error()} and {\cf warning()} functions work similarly to {\cf printf}, but the 3921results will be printed as a renderer error or warning message, possibly including 3922information about the name of the shader and the object being shaded, 3923and other diagnostic information. 3924\apiend 3925 3926\apiitem{void {\ce fprintf} (string filename, string fmt, ...)} 3927\indexapi{fprintf()} 3928The {\cf fprintf()} function works similarly to {\cf printf}, but rather 3929than printing to the default text output stream, the results will be 3930concatentated onto the end of the text file named by {\cf filename}. 3931\apiend 3932 3933\apiitem{string {\ce concat} (string s1, ..., string sN)} 3934\indexapi{concat()} 3935Concatenates a list of strings, returning the aggregate string. 3936\apiend 3937 3938\apiitem{int {\ce strlen} (string s)} 3939\indexapi{strlen()} 3940Return the number of characters in string {\ce s}. 3941\apiend 3942 3943\apiitem{int {\ce startswith} (string s, string prefix)} 3944\indexapi{startswith()} 3945Return 1 if string {\cf s} begins with the substring {\cf prefix}, 3946otherwise return 0. 3947\apiend 3948 3949\apiitem{int {\ce endswith} (string s, string suffix)} 3950\indexapi{startswith()} 3951Return 1 if string {\cf s} ends with the substring {\cf suffix}, 3952otherwise return 0. 3953\apiend 3954 3955\apiitem{int {\ce stoi} (string str)} 3956\indexapi{stoi()} 3957Convert/decode the initial part of {\cf str} to an {\cf int} 3958representation. Base 10 is assumed. 3959The return value will be {\cf 0} if the string doesn't appear to hold 3960valid representation of the destination type. 3961\apiend 3962 3963\apiitem{float {\ce stof} (string str)} 3964\indexapi{stof()} 3965Convert/decode the initial part of {\cf str} to a {\cf float} representation. 3966The return value will be {\cf 0} if the string doesn't appear to hold 3967valid representation of the destination type. 3968\apiend 3969 3970\apiitem{int {\ce split} (string str, output string results[], string sep, int maxsplit) \\ 3971int {\ce split} (string str, output string results[], string sep) \\ 3972int {\ce split} (string str, output string results[])} 3973\indexapi{split()} 3974 3975Fills the {\cf result} array with the words in the string {\cf str}, 3976using {\cf sep} as the delimiter string. If {\cf maxsplit} is supplied, 3977at most {\cf maxsplit} splits are done. If {\cf sep} is {\cf ""} (or if 3978not supplied), any whitespace string is a separator. The value returned 3979is the number of elements (separated strings) written to the {\cf results} 3980array. 3981\apiend 3982 3983\apiitem{string {\ce substr} (string s, int start, int length)\\ 3984string {\ce substr} (string s, int start)} 3985\indexapi{substr()} 3986Return at most \emph{length} characters from \emph{s}, starting with the 3987character indexed by \emph{start} (beginning with 0). If \emph{length} 3988is omitted, return the rest of \emph{s}, starting with \emph{start}. If 3989\emph{start} is negative, it counts backwards from the end of the string 3990(for example, {\cf substr(s,-1)} returns just the last character of 3991\emph{s}). 3992\apiend 3993 3994\apiitem{int {\ce getchar} (string s, int n)} 3995\indexapi{getchar()} 3996Returns the numeric value of the $n^{\mathrm{th}}$ character of the string, 3997or {\cf 0} if {\cf n} does not index a valid character of the string. 3998\apiend 3999 4000\apiitem{int {\ce hash} (string s)} 4001\indexapi{hash()} 4002Returns a deterministic, repeatable \emph{hash} of the string. 4003\apiend 4004 4005\apiitem{int {\ce regex_search} (string subject, string regex) \\ 4006int {\ce regex_search} (string subject, int results[], string regex)} 4007\indexapi{regex_search()} 4008Returns 1 if any substring of \emph{subject} matches a standard POSIX 4009regular expression \emph{regex}, 0 if it does not. 4010 4011In the form that also supplies a {\cf results} array, when a match is 4012found, the array will be filled in as follows: 4013 4014\begin{tabular}{p{1.5in} p{3.5in}} 4015{\cf\small results[0]} & the character index of the start of the 4016 sequence that matched the regular expression. \\ 4017{\cf\small results[1]} & the character index of the end (i.e., 4018 one past the last matching character) of the sequence that matched the 4019 regular expression. \\ 4020{\cf\small results[}$2i$ {\cf ]} & the character index of the 4021 start of the sequence that matched sub-expression $i$ of the regular 4022 expression. \\ 4023{\cf\small results[}$2i+1$ {\cf]} & the character index of the 4024 end (i.e., one past the last matching character) of the sequence that 4025 matched sub-expression $i$ of the regular expression. 4026\end{tabular} 4027 4028\noindent Sub-expressions are denoted by surrounding them in 4029parentheses. in the regular expression. 4030 4031A few examples illustrate regular expression searching: 4032 4033\begin{code} 4034 regex_search ("foobar.baz", "bar") = 1 4035 regex_search ("foobar.baz", "bark") = 0 4036 4037 int match[2]; 4038 regex_search ("foobar.baz", match, "[Oo]{2}") = 1 4039 (match[0] == 1, match[1] == 3) 4040 substr ("foobar.baz", match[0], match[1]-match[0]) = "oo" 4041 4042 int match[6]; 4043 regex_search ("foobar.baz", match, "(f[Oo]{2}).*(.az)") = 1 4044 substr ("foobar.baz", match[0], match[1]-match[0]) = "foobar.baz" 4045 substr ("foobar.baz", match[2], match[3]-match[2]) = "foo" 4046 substr ("foobar.baz", match[4], match[5]-match[4]) = "baz" 4047\end{code} 4048 4049\apiend 4050 4051\apiitem{int {\ce regex_match} (string subject, string regex) \\ 4052int {\ce regex_match} (string subject, int results[], string regex)} 4053\indexapi{regex_match()} 4054Identical to {\cf regex_search}, except that it must match the 4055\emph{whole} {\cf subject} string, not merely a substring. 4056\apiend 4057 4058 4059%\begin{annotate} 4060%Should we look at Pystring and add useful things here? 4061%\end{annotate} 4062 4063 4064\section{Texture} 4065\label{sec:stdlib:texture} 4066\index{texture functions} 4067\index{functions!texture} 4068\index{texture mapping} 4069 4070\apiitem{\emph{type} \textbf{texture} (string filename, float s, float t, \pl) \\ 4071\emph{type} \textbf{texture} (string filename, float s, float t, \\ 4072\spc\spc\spc float dsdx, float dtdx, float dsdy, float dtdy, \pl)} 4073\indexapi{texture()} 4074 4075Perform a texture lookup of an image file, indexed by 2D coordinates 4076$(s,t)$, antialiased over a region defined by the differentials 4077\emph{dsdx, dtdx, dsdy} and \emph{dtdy} (which are computed 4078automatically from $s$ and $t$, if not supplied). Whether the results 4079are assigned to a \float or a \color (or type cast to one of those) 4080determines whether the texture lookup is a single channel or three 4081channels. 4082 4083The 2D lookup coordinate(s) may be followed by optional token/value 4084arguments that control the behavior of {\cf texture()}: 4085 4086\apiitem{"blur", <float>} 4087\vspace{12pt} 4088Additional blur when looking up the texture value (default: 0). The 4089blur amount is relative to the size of the texture (i.e., 0.1 blurs by a 4090kernel that is 10\% of the full width and height of the texture). 4091 4092The blur may be specified separately in the $s$ and $t$ directions by 4093using the \qkw{sblur} and \qkw{tblur} parameters, respectively. 4094\apiend 4095\vspace{-16pt} 4096 4097\apiitem{"width", <float>} 4098\vspace{12pt} 4099Scale (multiply) the size of the filter as defined by the differentials 4100(or implicitly by the differentials of $s$ and $t$). The default is 4101{\cf 1}, meaning that no special scaling is performed. A width of 4102{\cf 0} would effectively turn off texture filtering entirely. 4103 4104The width value may be specified separately in the $s$ and $t$ 4105directions by using the \qkw{swidth} and \qkw{twidth} parameters, 4106respectively. 4107\apiend 4108\vspace{-16pt} 4109 4110\apiitem{"wrap", <string>} 4111\vspace{12pt} 4112 4113Specifies how the texture \emph{wraps} coordinates outside the $[0,1]$ 4114range. Supported wrap modes include: \qkw{black}, \qkw{periodic}, 4115\qkw{clamp}, \qkw{mirror}, and \qkw{default} (which is the default). A 4116value of \qkw{default} indicates that the renderer should use any wrap 4117modes specified in the texture file itself (a non-\qkw{default} value 4118overrides any wrap mode specified by the file). 4119 4120The wrap modes may be specified separately in the $s$ and $t$ directions 4121by using the \qkw{swrap} and \qkw{twrap} parameters, respectively. 4122\apiend 4123\vspace{-16pt} 4124 4125\apiitem{"firstchannel", <int>} 4126\vspace{12pt} 4127The first channel to look up from the texture map (default: 0). 4128\apiend 4129\vspace{-16pt} 4130 4131\apiitem{"subimage", <int> \\ 4132"subimage", <string>} 4133\vspace{12pt} 4134Specify the subimage (by numerical index, or name) of the subimage 4135within a multi-image texture file (default: subimage 0). 4136\apiend 4137\vspace{-16pt} 4138 4139\apiitem{"fill", <float>} 4140\vspace{12pt} 4141The value to return for any channels that are requested, 4142but not present in the texture file (default: 0). 4143\apiend 4144\vspace{-16pt} 4145 4146\apiitem{"missingcolor", <color>, "missingalpha", <float>} 4147\vspace{12pt} 4148If present, supplies a missing color (and alpha value) that will 4149be used for missing or broken textures -- \emph{instead of} treating 4150it as an error. If you want a missing or broken texture to be reported 4151as an error, you must not supply the optional \qkw{missingcolor} 4152parameter. 4153\apiend 4154\vspace{-16pt} 4155 4156\apiitem{"alpha", <floatvariable>} 4157\vspace{12pt} 4158The alpha channel (presumed to be the next channel following the 4159channels returned by the {\cf texture()} call) will be stored in the 4160variable specified. This allows for RGBA lookups in a single call to 4161{\cf texture()}. 4162\apiend 4163\vspace{-16pt} 4164 4165\apiitem{"errormessage", <stringvariable>} 4166\vspace{12pt} 4167If this option is supplied, any error messages generated by the texture 4168system will be stored in the specified variable rather than issuing error 4169calls to the renderer, thus leaving it up to the shader to handle any 4170errors. The error message stored will be \qkw{} if no error occurred. 4171\apiend 4172\vspace{-16pt} 4173 4174\apiitem{"interp", <string>} 4175\vspace{12pt} 4176Overrides the texture interpolation method: \qkw{smartcubic} (the 4177default), \qkw{cubic}, \qkw{linear}, or \qkw{closest}. 4178\apiend 4179\vspace{-16pt} 4180 4181\apiend 4182 4183\apiitem{\emph{type} \textbf{texture3d} (string filename, point p, \pl) \\ 4184\emph{type} \textbf{texture3d} (string filename, point p, vector dpdx, 4185vector dpdy, \\ \bigspc\bigspc vector dpdz, \pl)} 4186\indexapi{texture3d()} 4187 4188Perform a 3D lookup of a volume texture, indexed by 3D coordinate 4189$p$, antialiased over a region defined by the differentials 4190\emph{dpdx, dpdy}, and \emph{dpdz} (which are computed 4191automatically from $p$, if not supplied). Whether the results 4192are assigned to a \float or a \color (or type cast to one of those) 4193determines whether the texture lookup is a single channel or three 4194channels. 4195 4196The {\cf p} coordinate (and {\cf dpdx}, {\cf dpdy}, and {\cf dpdz} 4197derivatives, if supplied) are assumed to be in \commonspace and will be 4198automatically transformed into volume local coordinates, if such a 4199transormation is specified in the volume file itself. 4200 4201The 3D lookup coordinate may be followed by optional token/value 4202arguments that control the behavior of {\cf texture3d()}: 4203 4204\apiitem{"blur", <float>} 4205\vspace{12pt} 4206Additional blur when looking up the texture value (default: 0). The 4207blur amount is relative to the size of the texture (i.e., 0.1 blurs by a 4208kernel that is 10\% of the full width, height, and depth of the texture). 4209 4210The blur may be specified separately in the $s$, $t$, and $r$ directions by 4211using the \qkw{sblur}, \qkw{tblur}, and \qkw{rblur} parameters, respectively. 4212\apiend 4213\vspace{-16pt} 4214 4215\apiitem{"width", <float>} 4216\vspace{12pt} 4217Scale (multiply) the size of the filter as defined by the differentials 4218(or implicitly by the differentials of $s$, $t$, and $r$). The default is 4219{\cf 1}, meaning that no special scaling is performed. A width of 4220{\cf 0} would effectively turn off texture filtering entirely. 4221 4222The width value may be specified separately in the $s$, $t$, and $r$ 4223directions by using the \qkw{swidth}, \qkw{twidth}, and \qkw{rwidth} parameters, 4224respectively. 4225\apiend 4226\vspace{-16pt} 4227 4228\apiitem{"wrap", <string>} 4229\vspace{12pt} 4230 4231Specifies how the texture \emph{wraps} coordinates outside the $[0,1]$ 4232range. Supported wrap modes include: \qkw{black}, \qkw{periodic}, 4233\qkw{clamp}, \qkw{mirror}, and \qkw{default} (which is the default). A 4234value of \qkw{default} indicates that the renderer should use any wrap 4235modes specified in the texture file itself (a non-\qkw{default} value 4236overrides any wrap mode specified by the file). 4237 4238The wrap modes may be specified separately in the $s$, $t$, and $r$ 4239directions by using the \qkw{swrap}, \qkw{twrap}, and \qkw{rwrap} 4240parameters, respectively. 4241\apiend 4242\vspace{-16pt} 4243 4244\apiitem{"firstchannel", <int>} 4245\vspace{12pt} 4246The first channel to look up from the texture map (default: 0). 4247\apiend 4248\vspace{-16pt} 4249 4250\apiitem{"subimage", <int> \\ 4251"subimage", <string>} 4252\vspace{12pt} 4253Specify the subimage (by numerical index, or name) of the subimage 4254within a multi-image texture file (default: subimage 0). 4255\apiend 4256\vspace{-16pt} 4257 4258\apiitem{"fill", <float>} 4259\vspace{12pt} 4260The value to return for any channels that are requested, 4261but not present in the texture file (default: 0). 4262\apiend 4263\vspace{-16pt} 4264 4265\apiitem{"missingcolor", <color>, "missingalpha", <float>} 4266\vspace{12pt} 4267If present, supplies a missing color (and alpha value) that will 4268be used for missing or broken textures -- \emph{instead of} treating 4269it as an error. If you want a missing or broken texture to be reported 4270as an error, you must not supply the optional \qkw{missingcolor} 4271parameter. 4272\apiend 4273\vspace{-16pt} 4274 4275\apiitem{"time", <float>} 4276\vspace{12pt} 4277A time value to use if the volume texture specifies a time-varying 4278local transformation (default: 0). 4279\apiend 4280\vspace{-16pt} 4281 4282\apiitem{"alpha", <floatvariable>} 4283\vspace{12pt} 4284The alpha channel (presumed to be the next channel following the 4285channels returned by the {\cf texture3d()} call) will be stored in the 4286variable specified. This allows for RGBA lookups in a single call to 4287{\cf texture3d()}. 4288\apiend 4289\vspace{-16pt} 4290 4291\apiend 4292 4293\apiitem{\emph{type} \textbf{environment} (string filename, vector R, \pl) \\ 4294\emph{type} \textbf{environment} (string filename, vector R, \\ 4295\bigspc\bigspc vector dRdx, vector dRdy, \pl)} 4296\indexapi{environment()} 4297 4298Perform an environment map lookup of an image file, indexed by direction 4299$R$, antialiased over a region defined by the differentials 4300\emph{dRdx, dRdy} (which are computed 4301automatically from $R$, if not supplied). Whether the results 4302are assigned to a \float or a \color (or type cast to one of those) 4303determines whether the texture lookup is a single channel or three 4304channels. 4305 4306The lookup direction (and optional derivatives) may be followed by optional token/value 4307arguments that control the behavior of {\cf environment()}: 4308 4309\apiitem{"blur", <float>} 4310\vspace{12pt} 4311Additional blur when looking up the texture value (default: 0). The 4312blur amount is relative to the size of the texture (i.e., 0.1 blurs by a 4313kernel that is 10\% of the full width and height of the texture). 4314 4315The blur may be specified separately in the $s$ and $t$ directions by 4316using the \qkw{sblur} and \qkw{tblur} parameters, respectively. 4317\apiend 4318\vspace{-16pt} 4319 4320\apiitem{"width", <float>} 4321\vspace{12pt} 4322Scale (multiply) the size of the filter as defined by the differentials 4323(or implicitly by the differentials of $s$ and $t$). The default is 4324{\cf 1}, meaning that no special scaling is performed. A width of 4325{\cf 0} would effectively turn off texture filtering entirely. 4326 4327The width value may be specified separately in the $s$ and $t$ 4328directions by using the \qkw{swidth} and \qkw{twidth} parameters, 4329respectively. 4330\apiend 4331\vspace{-16pt} 4332 4333\apiitem{"firstchannel", <int>} 4334\vspace{12pt} 4335The first channel to look up from the texture map (default: 0). 4336\apiend 4337\vspace{-16pt} 4338 4339\apiitem{"fill", <float>} 4340\vspace{12pt} 4341The value to return for any channels that are requested, but 4342not present in the texture file (default: 0). 4343\apiend 4344\vspace{-16pt} 4345 4346\apiitem{"missingcolor", <color>, "missingalpha", <float>} 4347\vspace{12pt} 4348If present, supplies a missing color (and alpha value) that will 4349be used for missing or broken textures -- \emph{instead of} treating 4350it as an error. If you want a missing or broken texture to be reported 4351as an error, you must not supply the optional \qkw{missingcolor} 4352parameter. 4353\apiend 4354\vspace{-16pt} 4355 4356\apiitem{"alpha", <floatvariable>} 4357\vspace{12pt} 4358The alpha channel (presumed to be the next channel following the 4359channels returned by the {\cf environment()} call) will be stored in the 4360variable specified. This allows for RGBA lookups in a single call to 4361{\cf environment()}. 4362\apiend 4363\vspace{-16pt} 4364 4365\apiend 4366 4367 4368\newpage 4369\apiitem{int {\ce gettextureinfo} (string texturename, string paramname,\\ 4370\bigspc\bigspc output \emph{type} destination)} 4371\indexapi{gettextureinfo()} 4372 4373Retrieves a parameter from a named texture file. If the file is found, 4374and has a parameter that matches the name and type specified, its value 4375will be stored in \emph{destination} and {\cf gettextureinfo} will 4376return {\cf 1}. If the file is not found, or doesn't have a matching 4377parameter (including if the type does not match), \emph{destination} 4378will not be modified and {\cf gettextureinfo} will return {\cf 0}. Valid 4379parameters recognized are listed below: 4380 4381\smallskip 4382 4383\begin{tabular}{p{1.1in} p{0.5in} p{3.4in}} 4384{\bf Name} & {\bf Type} & {\bf Description} \\ 4385\hline 4386 4387\qkw{exists} & {\cf int} & Result is 1 if the file exists 4388and is an texture format that \product can read, or 0 if the file 4389does not exist, or could not be properly read as a texture. Note that unlike 4390all other queries, this query will ``succeed'' (return {\cf 1}) if the 4391file does not exist. \\[0.75ex] 4392 4393\qkw{resolution} & {\cf int[2]} & The resolution ($x$ and $y$) of the 4394highest MIPmap level stored in the texture map. \\[0.75ex] 4395 4396\qkw{resolution} & {\cf int[3]} & The resolution ($x$, $y$, and $z$) of 4397the highest MIPmap level stored in the 3D texture map. If it isn't a 4398volumetric texture, the third component ($z$ resolution) will be 43991.\\[0.75ex] 4400 4401\qkw{channels} & \inttype & The number of channels in the texture 4402map. \\[0.75ex] 4403 4404\qkw{type} & {\cf string} & Returns the semantic type of the texture, 4405one of: \qkws{Plain Texture}, \qkws{Shadow}, \qkws{Environment}, 4406\qkws{Volume Texture}. \\[0.75ex] 4407 4408\qkw{subimages} & {\cf int} & Returns the number of subimages in the 4409texture file. \\[0.75ex] 4410 4411\qkw{textureformat} & {\cf string} & Returns the texture format, one of: 4412\qkws{Plain Texture}, \qkws{Shadow}, \qkws{CubeFace Shadow}, \qkws{Volume 4413 Shadow}, \qkws{CubeFace Environment}, \qkws{LatLong Environment}, 4414\qkws{Volume Texture}. Note that this differs from \qkw{type} in that it 4415specifically distinguishes between the different types of shadows and 4416environment maps. \\[0.75ex] 4417 4418\qkw{datawindow} & {\cf int[]} & 4419Returns the pixel data window of the image. The argument is an {\cf int} 4420array either of length 4 or 6, in which will be placed the (xmin, ymin, 4421xmax, ymax) or (xmin, ymin, zmin, xmax, ymax, zmax), respectively. 4422(N.B. the $z$ values may be useful for 3D/volumetric images; for 2D images 4423they will be 0). \\[0.75ex] 4424 4425\qkw{displaywindow} & {\cf int[]} & 4426Returns the display (a.k.a.\ full) window of the image. The argument is an {\cf int} 4427array either of length 4 or 6, in which will be placed the (xmin, ymin, 4428xmax, ymax) or (xmin, ymin, zmin, xmax, ymax, zmax), respectively. 4429(N.B. the $z$ values may be useful for 3D/volumetric images; for 2D images 4430they will be 0). \\[0.75ex] 4431 4432\noindent ...continued... 4433\end{tabular} 4434 4435\begin{tabular}{p{1.1in} p{0.5in} p{3.4in}} 4436{\bf Name} & {\bf Type} & {\bf Description} \\ 4437\hline 4438 4439\qkw{worldtocamera} & \matrix & If the texture is a rendered image, 4440retrieves the world-to-camera 3D transformation matrix that was used when it 4441was created.\\[0.75ex] 4442 4443\qkw{worldtoscreen} & \matrix & If the texture is a rendered image, 4444retrieves the matrix that projected points from world space into a 2D screen 4445coordinate system where $x$ and $y$ range from $-1$ to $+1$. \\[0.75ex] 4446 4447\qkw{averagecolor} & {\cf color} & 4448Retrieves the average color (first three channels) of the texture. \\[0.75ex] 4449 4450\qkw{averagealpha} & {\cf float} & 4451Retrieves the average alpha (the channel with \qkw{A} name) of the texture. \\[0.75ex] 4452 4453\emph{anything else} & \emph{any} & Searches for matching name and 4454type in the metadata or other header information of the texture file. 4455%\hline 4456\end{tabular} 4457\apiend 4458 4459 4460 4461\newpage 4462\apiitem{int {\ce pointcloud_search} (string ptcname, point pos, float radius,\\ 4463\bigspc\bigspc int maxpoints, [int sort,] 4464 string attr, Type data[],\\ 4465\bigspc\bigspc ..., string attrN, Type dataN[] )} 4466\indexapi{pointcloud_search} 4467 4468Search the named point cloud for the {\cf maxpoints} closest points to 4469{\cf pos} within the given {\cf radius}, 4470returning the values of any named attributes of those points in the the 4471given {\cf data} arrays. If the optional {\cf sort} parameter is present 4472and is nonzero, the ordering of the points 4473found will be sorted by distance from {\cf pos}, from closest to farthest; 4474otherwise, the results are guaranteed to be the {\cf maxpoints} closest 4475to {\cf pos}, but not necessarily sorted by distance (this may be 4476faster for some implementations than when sorted results are 4477required). The return value is the number of points returned, ranging 4478from 0 (nothing found in the neighborhood) to the lesser of {\cf maxpoints} 4479and the actual lengths of the arrays (the arrays will never be written 4480beyond their actual length). 4481 4482These attribute names are reserved: 4483 4484\begin{tabular}{p{1.2in} p{0.5in} p{3.2in}} 4485\qkw{position} & {\cf point} & The position of each point \\ 4486\qkw{distance} & {\cf float} & The distance between the point and {\cf pos} \\ 4487\qkw{index} & {\cf int} & The point's unique index within the cloud 4488\end{tabular} 4489 4490Note that the named point cloud will be created, if it does not yet 4491exist in memory, and that it will be initialized by reading a point 4492cloud from disk, if there is one matching the name. 4493 4494Generally, the element type of the data arrays must match exactly the type 4495of the point data attribute, or else you will get a runtime error. But there 4496are two exceptions: (1) ``triple'' types (\color, \point, \vector, \normal) 4497are considered interchangeable; and (2) it is legal to retrieve {\cf float} 4498arrays (e.g., a point cloud attribute that is {\cf float[4]}) into a regular 4499array of {\cf float}, and the results will simply be concatenated into the 4500larger array (which must still be big enough, in total, to hold {\cf 4501maxpoints} of the data type in the file). 4502 4503\noindent Example: 4504 4505\begin{code} 4506 float r = 3.0; 4507 point pos[10]; 4508 color col[10]; 4509 int n = pointcloud_search ("particles.ptc", P, r, 10, 4510 "position", pos, "color", col); 4511 printf ("Found %d particles within radius %f of (%p)\n", r, P); 4512 for (int i = 0; i < n; ++i) 4513 printf (" position (%f) -> color (%g)\n", pos[i], col[i]); 4514\end{code} 4515 4516\apiend 4517 4518\apiitem{int {\ce pointcloud_get} (string ptcname, int indices[], \\ 4519\bigspc\bigspc int count, string attr, \emph{type} data[])} 4520\indexapi{pointcloud_get} 4521 4522Given a point cloud and a list of points {\cf indices[0..count-1]}, 4523store the attribute named by {\cf attr} for each point, respectively, in 4524{\cf data[0..count-1]}. Return 1 if successful, 0 for failure, which 4525could include the attribute not matching the type of {\cf data}, invalid 4526indices, or an unknown point cloud file. 4527 4528This can be used in conjunction with {\cf pointcloud_search()}, as 4529in the following example: 4530 4531\begin{code} 4532 float r = 3.0; 4533 int indices[10]; 4534 int n = pointcloud_search ("particles.ptc", P, r, 10, 4535 "index", indices); 4536 float temp[10]; // presumed to be "float" attribute 4537 float quaternions[40]; // presumed to be "float[4]" attribute 4538 int ok = pointcloud_get ("particles.ptc", indices, n, 4539 "temperature", temp, 4540 "quat", quaternions); 4541\end{code} 4542 4543As with {\cf pointcloud_search}, the element type of the data array must 4544either be equivalent to the point cloud attribute being retrieved, or else 4545when retrieving {\cf float} arrays (e.g., a point cloud attribute 4546that is {\cf float[4]}) into a regular array of {\cf float}, and the 4547results will simply be concatenated into the larger array (which must 4548still be big enough, in total, to hold {\cf maxpoints} of the data type 4549in the file). 4550\apiend 4551 4552 4553 4554\apiitem{int {\ce pointcloud_write} (string ptcname, point pos, \\ 4555\bigspc\bigspc string attr1, \emph{type} data1, ...)} 4556\indexapi{pointcloud_write} 4557 4558Save the tuple (\emph{attr1}, \emph{data1}, ..., \emph{attrN}, 4559\emph{dataN}) at position \emph{pos} in a named point cloud. The point 4560cloud will be saved when the frame is finished computing. Return 1 if 4561successful, 0 for failure, which could include the attributes not 4562matching names or types at different positions in the point cloud. 4563 4564Example: 4565\begin{code} 4566 color C = ...; 4567 int ok = pointcloud_write ("particles.ptc", P, "normal", N, "color", C); 4568\end{code} 4569\apiend 4570 4571 4572\newpage 4573\section{Material Closures} 4574\label{sec:stdlib:light} 4575\label{sec:stdlib:closures} 4576\index{material closure functions} 4577\index{functions!closures} 4578 4579For \closurecolor functions, the return ``value'' is symbolic and is may 4580be passed to an output variable or assigned to \Ci, to be evaluated at a 4581later time convenient to the renderer in order to compute the exitant 4582radiance in the direction {\cf -I}. But the shader itself cannot 4583examine the numeric values of the \colorclosure. 4584 4585The intent of this specification is to give a minimal but useful set of 4586material closures that you can expect any renderer implementation to 4587provide. Individual renderers may supply additional closures that are 4588specific to the workings of that renderer. Additionally, invidual 4589renderers may allow additional parameters or controls on the standard 4590closures, passed as token/value pairs following the required arguments 4591(much like the optional arguments to the {\cf texture()} function). 4592Consult the documentation for your specific renderer for details. 4593 4594 4595 4596\subsection{Surface material closures} 4597 4598\apiitem{\colorclosure\ {\ce diffuse} (normal N)} 4599\indexapi{diffuse()} 4600Returns a \colorclosure that represents the Lambertian diffuse 4601reflectance of a smooth surface, 4602$$ \int_{\Omega}{\frac{1}{\pi} \max(0, N \cdot \omega) Cl(P,\omega) d\omega} $$ 4603where $N$ is the unit-length forward-facing surface normal at \P, 4604$\Omega$ is the set of all outgoing directions in the hemisphere 4605surrounding $N$, and $Cl(P,\omega)$ is the incident radiance at 4606\P coming from the direction $-\omega$. 4607\apiend 4608 4609\apiitem{\colorclosure\ {\ce phong} (normal N, float exponent)} 4610\indexapi{phong()} 4611Returns a \colorclosure that represents specular reflectance of the 4612surface using the Phong BRDF. The \emph{exponent} parameter 4613indicates how smooth or rough the material is (higher \emph{exponent} 4614values indicate a smoother surface). 4615\apiend 4616 4617 4618\apiitem{\colorclosure\ {\ce oren_nayar} (normal N, float sigma)} 4619\indexapi{oren_nayar()} 4620 4621Returns a \colorclosure that represents the diffuse reflectance of a 4622rough surface, implementing the Oren-Nayar reflectance formula. The 4623\emph{sigma} parameter indicates how smooth or rough the 4624microstructure of the material is, with 0 being perfectly smooth and 4625giving an appearance identical to {\cf diffuse()}. 4626 4627The Oren-Nayar reflection model is described in M.\ Oren and S.\ K.\ 4628Nayar, ``Generalization of Lambert's Reflectance Model,'' Proceedings of 4629SIGGRAPH 1994, pp.239-246 (July, 1994). 4630 4631\begin{comment} 4632Like all \closurecolors, the return ``value'' is symbolic and is may be 4633evaluated at a later time convenient to the renderer in order to compute 4634the exitant radiance in the direction {\cf -I}. But aside from the 4635fact that the shader cannot examine the numeric values of the 4636\colorclosure, you may program \emph{as if} {\cf oren_nayar()} was 4637implemented as follows: 4638 4639\begin{code} 4640 normal Nf = faceforward (normalize(N), I); 4641 vector V = -normalize(I); 4642 float sigma2 = sigma * sigma; 4643 float A = 1 - 0.5 * sigma2 / (sigma2 + 0.33); 4644 float B = 0.45 * sigma2 / (sigma2 + 0.09); 4645 float theta_r = acos (dot (V, Nf)); // Angle between V and N 4646 vector V_perp_N = normalize(V-Nf*dot(V,Nf)); // Part of V perpendicular to N 4647 color C = 0; 4648 for all lights within the hemisphere defined by (P, Nf, PI/2) { 4649 /* L is the direction of light i, Cl is its incoming radiance */ 4650 vector LN = normalize(L); 4651 float cos_theta_i = dot(LN, N); 4652 float cos_phi_diff = dot (V_perp_N, normalize(LN - Nf*cos_theta_i)); 4653 float theta_i = acos (cos_theta_i); 4654 float alpha = max (theta_i, theta_r); 4655 float beta = min (theta_i, theta_r); 4656 C += Cl * cos_theta_i * 4657 (A + B * max(0,cos_phi_diff) * sin(alpha) * tan(beta)); 4658 } 4659 return C; 4660\end{code} 4661\end{comment} 4662 4663\apiend 4664 4665\apiitem{\colorclosure\ {\ce ward} (normal N, vector T, 4666 float xrough, float yrough)} 4667\indexapi{ward()} 4668 4669Returns a \colorclosure that represents the anisotropic specular 4670reflectance of the surface at \P. The \N and {\cf T} vectors, both 4671presumed to be unit-length, are the surface normal and tangent, used to 4672establish a local coordinate system for the anisotropic effects. The 4673\emph{xrough} and \emph{yrough} specify the amount of roughness in the 4674tangent ({\cf T}) and bitangent ({\cf N} $\times$ {\cf T}) directions, 4675respectively. 4676 4677The Ward BRDF is described in Ward, G., ``Measuring and Modeling 4678Anisotropic Reflection,'' Proceedings of SIGGRAPH 1992. 4679 4680\begin{comment} 4681Like all \closurecolors, the return ``value'' is symbolic and is may be 4682evaluated at a later time convenient to the renderer in order to compute 4683the exitant radiance in the direction {\cf -I}. But aside from the 4684fact that the shader cannot examine the numeric values of the 4685\colorclosure, you may program \emph{as if} {\cf ward()} was 4686implemented as follows: 4687 4688\begin{code} 4689 float sqr (float x) { return x*x; } 4690 4691 vector V = -normalize(I); 4692 float cos_theta_r = clamp (dot(N,V), 0.0001, 1); 4693 vector X = T / xroughness; 4694 vector Y = cross(T,N) / yroughness; 4695 color C = 0; 4696 for all lights within the hemisphere defined by (P, N, PI/2) { 4697 /* L is the direction of light i, Cl is its incoming radiance */ 4698 vector LN = normalize (L); 4699 float cos_theta_i = dot (LN,N); 4700 if (cos_theta_i > 0.0) { 4701 vector H = normalize (V + LN); 4702 float rho = exp (-2 * (sqr(dot(X,H)) + 4703 sqr(dot(Y,H))) / (1 + dot(H,N))) 4704 / sqrt (cos_theta_i * cos_theta_r); 4705 C += Cl * cos_theta_i * rho; 4706 } 4707 } 4708 return C / (4 * xroughness * yroughness); 4709\end{code} 4710\end{comment} 4711\apiend 4712 4713 4714\apiitem{\colorclosure\ {\ce microfacet} (string distribution, normal N, vector 4715U, \\ \bigspc\bigspc float xalpha, float yalpha, float eta, int refract)} 4716\indexapi{microfacet()} 4717 4718Returns a \colorclosure that represents scattering on the 4719surface using some microfacet distribution such as \qkw{beckmann} or \qkw{ggx} (as 4720described in Walter et al., ``Microfacet Models for Refraction through Rough 4721Surfaces,'' Eurographics Symposium on Rendering, 2007). 4722Both {\cf xalpha} and {\cf yalpha} control how rough the microstructure of the 4723surface is, possibly in an anisotropic way if they are different. In the 4724anisotropic case {\cf U} must be a vector orthogonal to {\cf N} to specify the 4725direction. These values are expected to be the alpha values of the distribution 4726as it appears in the literature, not a universal roughness measure. 4727The {\cf eta} parameter is the index of refraction of the material, and 4728{\cf refract} is a enumeration flag that controls if the BSDF is reflective ({\cf 0}), 4729refractive ({\cf 1}) or both at once ({\cf 2}). The implementation must not rely on 4730{\cf U} when the roughness is isotropic or the given vector is zero. 4731 4732The list of supported distributions will change from renderer to renderer, and 4733also the behavior when an unsupported distribution is requested. It is up to the 4734implementation to issue an error or to default to a supported one. Also it is 4735expected that the alias \qkw{default} must work as a distribution in any renderer. 4736 4737\apiend 4738 4739 4740\apiitem{\colorclosure\ {\ce microfacet} (string distribution, normal N, 4741\\ \bigspc\bigspc float alpha, float eta, int refract)} 4742\indexapi{microfacet()} 4743 4744Returns a \colorclosure that represents scattering on the 4745surface using some microfacet distribution. A simplified isotropic version of 4746the previous function. 4747 4748\apiend 4749 4750 4751\apiitem{\colorclosure\ {\ce reflection} (normal N, float eta)} 4752\indexapi{reflection()} 4753 4754Returns a \colorclosure that represents sharp mirror-like reflection 4755from the surface. The reflection direction will be automatically computed 4756based on the incident angle. The {\cf eta} parameter is the index of 4757refraction of the material. The {\cf reflection} closure behaves 4758as if it were implemented as follows: 4759 4760\begin{code} 4761 vector R = reflect (I, N); 4762 return raytrace (R); 4763\end{code} 4764 4765\apiend 4766 4767 4768\apiitem{\colorclosure\ {\ce refraction} (normal N, float eta)} 4769\indexapi{refraction()} 4770 4771Returns a \colorclosure that represents sharp glass-like refraction of 4772objects ``behind'' the surface. The \emph{eta} parameter is the ratio 4773of the index of refraction of the medium on the ``inside'' of the 4774surface divided by the index of refration of the medium on the 4775``outside'' of the surface. The ``outside'' direction is the one 4776specified by \N. 4777The refraction direction will be automatically computed based on the 4778incident angle and \emph{eta}, and the radiance returned will be 4779automatically scaled by the Fresnel factor for dielectrics. 4780The {\cf refraction} closure behaves as if it were 4781implemented as follows: 4782 4783\begin{code} 4784 float Kr, Kt; 4785 vector R, T; 4786 fresnel (I, N, eta, Kr, Kt, R, T); 4787 return Kt * raytrace (T); 4788\end{code} 4789\apiend 4790 4791 4792\apiitem{\colorclosure\ {\ce transparent} ( )} 4793\indexapi{transparent()} 4794 4795Returns a \colorclosure that shows the light \emph{behind} the surface 4796without any refractive bending of the light directions. 4797The {\cf transparent()} closure behaves as if it were implemented 4798as follows: 4799 4800\begin{code} 4801 return raytrace (I); 4802\end{code} 4803 4804\apiend 4805 4806\apiitem{\colorclosure\ {\ce translucent} ( )} 4807\indexapi{translucent()} 4808 4809Returns a \colorclosure that represents the Lambertian diffuse 4810translucence of a smooth surface, which is much like {\cf diffuse()} 4811except that it gathers light from the \emph{far} side of the surface. 4812The {\cf translucent()} closure behaves as if it were implemented 4813as follows: 4814 4815\begin{code} 4816 return diffuse (-N); 4817\end{code} 4818 4819\apiend 4820 4821 4822\begin{comment} 4823\apiitem{\colorclosure\ {\ce subsurface} ( )} 4824\indexapi{subsurface} 4825Returns a \colorclosure that represents the amount of \emph{subsurface 4826scattering} exhibited by the surface. 4827 4828% \begin{annotate} 4829% We'll determine later what the arguments to {\cf subsurface} need to be. 4830% FIXME 4831% \end{annotate} 4832\apiend 4833\end{comment} 4834 4835 4836\subsection{Volumetric material closures} 4837 4838\apiitem{\colorclosure\ {\ce isotropic} ( )} 4839\indexapi{isotropic} 4840Returns a \colorclosure that represents the scattering of an isotropic 4841volumetric material, scattering light evenly in all directions, 4842regardless of its original direction. 4843\apiend 4844 4845 4846\apiitem{\colorclosure\ {\ce henyey_greenstein} (float g)} 4847\indexapi{henyey_greenstein} 4848Returns a \colorclosure that represents the directional volumetric 4849scattering by small suspended particles. The {\cf g} parameter is the 4850anisotropy factor, ranging from $-1$ to $1$), with positive values 4851indicating predominantly forward-scattering, negative values indicating 4852predominantly back-scattering, and value of $g=0$ resulting in isotropic 4853scattering. 4854\apiend 4855 4856 4857\apiitem{\colorclosure\ {\ce absorption} ( )} 4858\indexapi{absorption} 4859Returns a \colorclosure that does not represent any additional 4860light scattering, but rather signals to the renderer the absorption 4861represents the scattering of an isotropic 4862volumetric material, scattering light evenly in all directions, 4863regardless of its original direction. 4864\apiend 4865 4866 4867\subsection{Light emission closures} 4868 4869\apiitem{\colorclosure\ {\ce emission} ( )} 4870\indexapi{emission} 4871Returns a \colorclosure that represents a glowing/emissive material. 4872When called in the context of a surface shader group, it implies that 4873light is emitted in a full hemisphere centered around the surface 4874normal. When called in the context of a volume shader group, it implies 4875that light is emitted evenly in all directions around the point being 4876shaded. 4877 4878The weight of the emission closure has units of radiance (e.g., 4879$\mathrm{W}\cdot\mathrm{sr}^{-1}\cdot\mathrm{m}^{-2}$). This means that a surface 4880directly seen by the camera will directly reproduce the closure weight in the 4881final pixel, regardless of being a surface or a volume. 4882 4883For surface emission, If you divide {\cf emission()} by 4884{\cf surfacearea() * M_PI}, then you can easily specify the total emissive 4885power of the light (e.g., $\mathrm{W}$), regardless of its physical size. 4886\apiend 4887 4888 4889\apiitem{\colorclosure\ {\ce background} ( )} 4890\indexapi{background} 4891Returns a \colorclosure that represents the radiance of the 4892``background'' infinitely far away in the view direction. The 4893implementation is renderer-specific, but often involves looking 4894up from an HDRI environment map. 4895\apiend 4896 4897 4898\subsection{Signaling closures} 4899 4900\apiitem{\colorclosure\ {\ce holdout} ( )} 4901\indexapi{holdout()} 4902Returns a \colorclosure that does not represent any additional light 4903reflection from the surface, but does signal to the renderer that 4904the surface is a \emph{holdout object} (appears transparent in 4905the final output yet hides objects behind it). ``Partial holdouts'' 4906may be designated by weighting the {\cf holdout()} closure by a 4907weight that is less than 1.0. 4908\apiend 4909 4910 4911\apiitem{\colorclosure\ {\ce debug} (string outputname)} 4912\indexapi{debug()} 4913Returns a \colorclosure that does not represent any additional light 4914reflection from the surface, but does signal to the renderer to add 4915the weight of the closure (which may be a {\cf float} or a \color) 4916to the named output (i.e., AOV). 4917\apiend 4918 4919 4920 4921 4922\newpage 4923\section{Renderer state and message passing} 4924\label{sec:stdlib:state} 4925\index{functions!renderer state} 4926\index{message passing} 4927 4928\apiitem{int {\ce getattribute} (string name, output \emph{type} destination) \\ 4929int {\ce getattribute} (string name, int arrayindex, output \emph{type} 4930destination)\\ 4931int {\ce getattribute} (string object, string name, output \emph{type} destination) \\ 4932int {\ce getattribute} (string object, string name, int arrayindex, \\ 4933\bigspc\spc\spc output \emph{type} destination)} 4934\indexapi{getattribute()} 4935Retrieves a named renderer attribute or the value of an interpolated 4936geometric variable. 4937If an object is explicitly named, that is the only place that will be 4938searched (\qkw{global} means the global scene-wide attributes). For the 4939forms of the function with no object name, or if the object name is the 4940empty string \qkw{}, the renderer will first search 4941per-object attributes on the current object (or interpolated variables 4942with that name attached to the object), then if not found it will search 4943searching global scene-wide attributes. 4944 4945If the attribute is found and can be converted to the type of 4946\emph{destination}, the attribute's value will be stored in 4947\emph{destination} and {\cf getattribute} will return {\cf 1}. If not 4948found, or the type cannot be converted, \emph{destination} will not be 4949modified and {\cf getattribute} will return {\cf 0}. 4950 4951The automatic type conversions include those that are allowed by 4952assignment in OSL source code: {\cf int} to {\cf float}, {\cf float} to 4953{\cf int} (truncation), {\cf float} (or {\cf int}) to \emph{triple} 4954(replicating the value), any \emph{triple} to any other \emph{triple}. 4955Additionally, the following conversions which are not allowed by 4956assignment in OSL source code will also be performed by this call: 4957{\cf float} (or {\cf int}) to {\cf float[2]} (replication into both 4958array elements), {\cf float[2]} to \emph{triple} (setting the third 4959component to 0). 4960 4961The forms of this function that have the the {\cf arrayindex} parameter 4962will retrieve the individual indexed element of the named array. In this 4963case, \emph{name} must be an array attribute, the type of 4964\emph{destination} must be the type of the array element (not the type 4965of the whole array), and the value of \emph{arrayindex} must be a valid 4966index given the array's size. 4967 4968Tables giving ``standardized'' names for different kinds of attributes may 4969be found below. All renderers are expected to use the same names for these 4970attributes, but are free to choose any names for additional attributes they 4971wish to make queryable. 4972 4973\apiend 4974 4975\begin{table}[htbp] 4976\caption{Names of standard attributes that may be retrieved.}\label{tab:stdattributes} 4977\begin{tabular}{|p{1.8in}|p{0.6in}|p{2.8in}|} 4978\hline 4979{\bf Name} & {\bf Type} & {\bf Description} \\ 4980\hline 4981{\cf "osl:version"} & {\cf int} & Major*10000 + Minor*100 + patch. \\ 4982{\cf "shader:shadername"} & {\cf string} & Name of the shader master. \\ 4983{\cf "shader:layername"} & {\cf string} & Name of the layer instance. \\ 4984{\cf "shader:groupname"} & {\cf string} & Name of the shader group. \\ 4985\hline 4986\end{tabular} 4987\end{table} 4988 4989\begin{table}[htbp] 4990\caption{Names of standard camera attributes that may be retrieved. 4991If the {\cf getattribute()} function specifies an {\cf objectname} parameter 4992and it is the name of a valid camera, the value specific to that camera 4993is retrieved. If no specific camera is named, the global or default 4994camera is implied. 4995}\label{tab:cameraattributes} 4996\begin{tabular}{|p{1.8in}|p{0.6in}|p{2.8in}|} 4997\hline 4998{\bf Name} & {\bf Type} & {\bf Description} \\ 4999\hline 5000{\cf "camera:resolution"} & {\cf int[2]} & Image resolution. \\ 5001{\cf "camera:pixelaspect"} & {\cf float} & Pixel aspect ratio. \\ 5002{\cf "camera:projection"} & {\cf string} & Projection type (e.g., 5003 \qkw{perspective}, \qkw{orthographic}, etc.) \\ 5004{\cf "camera:fov"} & {\cf float} & Field of fiew. \\ 5005{\cf "camera:clip_near"} & {\cf float} & Near clip distance. \\ 5006{\cf "camera:clip_far"} & {\cf float} & Far clip distance. \\ 5007{\cf "camera:clip"} & {\cf float[2]} & Near and far clip distances. \\ 5008{\cf "camera:shutter_open"} & {\cf float} & Shutter open time. \\ 5009{\cf "camera:shutter_close"} & {\cf float} & Shutter close time. \\ 5010{\cf "camera:shutter"} & {\cf float[2]} & Shutter open and close times. \\ 5011{\cf "camera:screen_window"} & {\cf float[4]} & Screen window (xmin, ymin, xmax, ymax). \\ 5012\hline 5013\end{tabular} 5014\end{table} 5015 5016\newpage 5017 5018\apiitem{void {\ce setmessage} (string name, output \emph{type} value)} 5019\indexapi{setmessage()} 5020Store a \emph{name}/\emph{value} pair in an area where it can later be 5021retrieved by other shaders attached to the same object. If there is 5022already a message with the same name attached to this shader invocation, 5023it will be replaced by the new value. 5024The message \emph{value} may be any basic scalar type, array, or closure, 5025but may not be a {\cf struct}. 5026\apiend 5027 5028%\apiitem{int {\ce getmessage} (string source, string name, output \emph{type} destination)} 5029\apiitem{int {\ce getmessage} (string name, output \emph{type} 5030 destination) \\ 5031int {\ce getmessage} (string source, string name, output \emph{type} destination)} 5032\indexapi{getmessage()} 5033\label{sec:getmessage} 5034 5035Retrieve a message from another shader attached to the same object. 5036If a message is found 5037with the given name, and whose type matches that of \emph{destination}, 5038the value will be stored in \emph{destination} and {\cf getmessage()} 5039will return {\cf 1}. If no message is found that matches both the name 5040and type, \emph{destination} will be unchanged and {\cf getmessage()} 5041will return {\cf 0}. 5042 5043The \emph{source}, if supplied, designates from where the message should 5044be retrieved, and may have any of the following values: 5045 5046\vspace{-8pt} 5047 5048%\apiitem{"surface", "displacement", "volume"} 5049%\vspace{10pt} 5050%Retrieve the message from the named shader type present on the object 5051%being shaded. 5052%\apiend 5053%\vspace{-20pt} 5054%\end{comment} 5055 5056\apiitem{"trace"} 5057\vspace{10pt} 5058Retrieves data about the object hit by the last {\cf trace} call made. 5059Data recognized include: 5060 5061\begin{tabular}{p{0.8in} p{0.5in} p{3.3in}} 5062\qkw{hit} & {\cf int} & Zero if the ray hit nothing, 1 if it hit. \\ 5063\qkw{hitdist} & {\cf float} & The distance to the hit. \\ 5064\qkw{geom:name} & {\cf string} & The name of the object hit. \\ 5065\emph{other} & & Retrieves the named global (\P, \N, etc.), shader 5066 parameter, or set message of the closest object hit 5067 (only if it was a shaded ray). 5068\end{tabular} 5069 5070Note that which information may be retrieved depends on whether the 5071ray was traced with the optional \qkw{shade} parameter indicating 5072whether or not the shader ought to execute on the traced ray. If 5073\qkw{shade} was 0, you may retrieve ``globals'' (\P, \N, etc.), interpolated 5074vertex variables, shader instance values, or graphics state 5075attributes (object name, etc.). But \qkw{shade} must be nonzero to 5076correctly retrieve shader output variables or messages that are set 5077by the shader (via {\cf setmessage()}). 5078 5079\apiend 5080\vspace{-20pt} 5081 5082%\apiitem{"parent"} 5083%\vspace{10pt} 5084%Retrieve the message from the shader (potentially on another object) 5085%that spawned the ray that caused the current shader to be executed. 5086%\apiend 5087%\vspace{-20pt} 5088 5089%\apiitem{"primitive"} 5090%\vspace{10pt} 5091%Retrieve the value by interpolating the named user variable attached 5092%to the geometric primitive that is being shaded (regardless of whether 5093%it is a parameter to the shader). 5094%\apiend 5095 5096%First, {\cf getmessage()} will search the source's message list as set 5097%by {\cf setmessage()} when that shader ran. If not found, then the 5098%source's shader parameters will be searched. If multiple shaders of 5099%the same type are present, they will be searched starting with the 5100%last one executed, and moving backwards in execution order (in other 5101%words, later-executed shaders in the network effectively take precedence 5102%over parameteters or messages from earlier-executed shaders). 5103%\end{comment} 5104 5105\apiend 5106 5107\apiitem{float {\ce surfacearea} ()} 5108\indexapi{surfacearea()} 5109Returns the surface area of the area light geometry being shaded. This 5110is meant to be used in conjunction with {\cf emission()} in order to 5111produce the correct emissive radiance given a user preference for a 5112total wattage for the area light source. The value of this function 5113is not expected to be meaningful for non-light shaders. 5114\apiend 5115 5116%\apiitem{int {\ce raylevel} ()} 5117%\indexapi{raylevel()} 5118%Returns the \emph{ray level} of the current shading sample --- {\cf 0} 5119%if the surface is viewed directly by the camera, {\cf 1} if it is a 5120%first-level reflection or refraction, {\cf 2} if it is a 5121%reflection/refraction visible in a reflection/refraction, etc. 5122%\apiend 5123 5124\apiitem{int {\ce raytype} (string name)} 5125\indexapi{raytype()} 5126Returns {\cf 1} if ray being shaded is of the given type, or {\cf 0} if 5127the ray is not of that type or if the ray type name is not recognized by 5128the renderer. 5129 5130The set of ray type names is customizeable for renderers supporting 5131OSL, but is expected to include at a minimum \qkw{camera}, 5132\qkw{shadow}, \qkw{diffuse}, \qkw{glossy}, \qkw{reflection}, 5133\qkw{refraction}. They are not necessarily mutually exclusive, with the 5134exception that camera rays should be of class \qkw{camera} and no other. 5135\apiend 5136 5137\apiitem{int {\ce backfacing} ()} 5138\indexapi{backfacing()} 5139Returns 1 if the surface is being sampled as if ``seen'' from the back 5140of the surface (or the ``inside'' of a closed object). Returns 0 if seen 5141from the ``front'' or the ``outside'' of a closed object. 5142\apiend 5143 5144\apiitem{int {\ce isconnected} (\emph{type} parameter)} 5145\indexapi{isconnected()} 5146Returns {\cf 1} if the argument is a shader parameter and is connected 5147to an earlier layer in the shader group, 5148{\cf 2} if the argument is a shader output parameter connected 5149to a later layer in the shader group, {\cf 3} if connected to both 5150earlier and later layers, otherwise returns {\cf 0}. 5151Remember that function arguments in OSL are always pass-by-reference, 5152so {\cf isconnected()} applied to a function parameter will depend on 5153what was passed in as the actual parameter. 5154\apiend 5155 5156\apiitem{int {\ce isconstant} (\emph{type} expr)} 5157\indexapi{isconstant()} 5158Returns {\cf 1} if the expression can, at runtime (knowing the values of all 5159the shader group's parameter values and connections), be discerned to be 5160reducible to a constant value, otherwise returns {\cf 0}. 5161 5162This is primarily a debugging aid for advanced shader writers to verify 5163their assumptions about what expressions can end up being constant-folded 5164by the runtime optimizer. 5165\apiend 5166 5167 5168\section{Dictionary Lookups} 5169\label{sec:stdlib:dictionaries} 5170 5171\apiitem{int {\ce dict_find} (string dictionary, string query) \\ 5172int {\ce dict_find} (int nodeID, string query)} 5173\indexapi{dict_find()} 5174 Find a node in the dictionary by a query. The {\cf dictionary} is 5175 either a string containing the actual dictionary text, or the name 5176 of a file containing the dictionary. (The system can easily 5177 distinguish between them.) XML dictionaries are currently 5178 supported, and additional formats may be supported in the future. 5179 The query is expressed in ``XPath 1.0'' syntax (or a reasonable subset 5180 therof). 5181 5182 The return value is a \emph{Node ID}, an opaque integer identifier 5183 that is the handle of a node within the dictionary data. The value 5184 0 is reserved to mean ``query not found'' and the value -1 indicates 5185 that the dictionary was not a valid syntax (or, if a file, could not 5186 be read). If more than one node within 5187 the dictionary matched the query, the node ID of the first match is 5188 returned, and {\cf dict_next()} may be used to step to the next 5189 matching node. 5190 5191 The version that takes a nodeID rather than a dictionary string 5192 simply interprets the query as being relative to the node 5193 specified by nodeID, as opposed to relative to the root of the 5194 dictionary. 5195 5196 All expensive operations (such as reading the dictionary from a file 5197 and the initial parsing of the dictionary) are performed only once, 5198 and subsequent lookups merely copy data and are thus inexpensive. 5199 The {\cf dictionary} string is, therefore, used as a hash into a 5200 cached data structure holding the parsed dictionary database. 5201 Implementations may also cache individual node lookups or type 5202 conversions behind the scenes. 5203\apiend 5204 5205\apiitem{int {\ce dict_next} (int nodeID)} 5206\indexapi{dict_next()} 5207 Return the node ID of the next node that matched the query that 5208 returned nodeID, or 0 if nodeID was the last matching node for its 5209 query. 5210\apiend 5211 5212\apiitem{int {\ce dict_value} (int nodeID, string attribname, output 5213 \emph{type} value)} 5214\indexapi{dict_value()} 5215 5216 Retrieves the named attribute of the given dictionary node, or the 5217 value of the node itself if {\cf attribname} is the empty string 5218 {\cf ""}. If the attribute is found, its value will be stored in 5219 {\cf value} and 1 will be returned. If the requested attribute is 5220 not found on the node, or if the type of {\cf value} does not appear 5221 to match that of the named node, {\cf value} will be unmodified and 5222 0 will be returned. 5223 5224 Type conversions are straightforward: anything may be retrieved as a 5225 string; to retrieve as an int or float, the value must parse as a 5226 single integer or floating point value; to retrieve as a point, 5227 vector, normal, color, or matrix (or any array), the value must 5228 parse as the correct number of values, separated by spaces and/or 5229 commas. 5230\apiend 5231 5232 5233\apiitem{int {\ce trace} (point pos, vector dir, ...)} 5234%, float mindist, float maxdist, int shade)} 5235\indexapi{trace} 5236 5237Trace a ray from pos in the direction dir. The ray is traced 5238immediately, and may incur significant expense compared to rays that 5239might be traced incidentally to evaluating the Ci closure. Also, beware 5240that this can be easily abused in such a way as to introduce 5241view-dependence into shaders. 5242The return value is 0 if the ray missed all geometry, 1 if it hit 5243anything within the distance range. 5244 5245Optional parameters include: 5246 5247\begin{tabular}{p{1.2in} p{0.5in} p{3.2in}} 5248\qkw{mindist} & {\cf float} & Minimum hit distance (default: zero) \\ 5249\qkw{maxdist} & {\cf float} & Maximum hit distance (default: infinite) \\ 5250\qkw{shade} & {\cf int} & Whether objects hit will be shaded 5251 (default: 0) \\ 5252\qkw{traceset} & {\cf string} & An optional named set of objects to 5253 ray trace (if preceded by a `{\cf -}' 5254 character, it means to exclude that set). 5255\end{tabular} 5256 5257Information about the closest object hit by the ray may be retrieved 5258using \\ {\cf getmessage("trace",...)} (see Section~\ref{sec:getmessage}). 5259 5260The main purpose of this function is to allow shaders to ``probe'' 5261nearby geometry, for example to apply a projected texture that can be 5262blocked by geometry, apply more ``wear'' to exposed geometry, or make 5263other ambient occlusion-like effects. 5264 5265% Any messages set by setmessage() prior to calling trace may be 5266% retrieved by the shaders running on the object hit by the ray, via 5267% {\cf getmessage("parent",...)}. 5268 5269 5270\apiend 5271 5272 5273\section{Miscellaneous} 5274\label{sec:stdlib:misc} 5275 5276\apiitem{int {\ce arraylength} (\emph{type} A[])} 5277\indexapi{arraylength()} 5278Returns the length of the referenced array, which may be of any type. 5279\apiend 5280 5281\apiitem{void {\ce exit} ()} 5282\indexapi{exit()} 5283Exits the shader without further execution. Within the main body of a 5284shader, this is equivalent to calling {\cf return}, but inside a 5285function, {\cf exit()} will exit the entire shader, whereas {\cf return} 5286would only exit the enclosing function. 5287\apiend 5288 5289 5290\index{standard library functions|)} % end of chapter 5291 5292 5293 5294\chapter{Formal Language Grammar} 5295\label{chap:grammar} 5296 5297This section gives the complete syntax of \langname. Syntactic 5298structures that have a name ending in ``-opt'' are optional. Structures 5299surrounded by curly braces \{ \} may be repeated 0 or more times. Text 5300in {\cf typewriter} face indicates literal text. The $\epsilon$ 5301character is used to indicate that it is acceptable for there to be 5302nothing (empty, no token). 5303 5304\setlength{\grammarindent}{2cm} 5305 5306\section*{Lexical elements} 5307 5308\begin{grammar} 5309 5310<digit> ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" 5311 5312<digit-sequence> ::= <digit> \{ <digit> \} 5313 5314<hexdigit> ::= <digit> | "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" | "E" | "f" | "F" 5315 5316<hexdigit-sequence> ::= <hexdigit> \{ <hexdigit> \} 5317 5318<integer> ::= <sign> <digit-sequence> 5319\alt <sign> "0x" <hexdigit-sequence> 5320 5321<floating-point> ::= <digit-sequence> <decimal-part-opt> <exponent-opt> 5322\alt <decimal-part> <exponent-opt> 5323 5324<decimal-part> ::= `.' \{ <digit> \} 5325 5326<exponent> ::= `e' <sign> <digit-sequence> 5327 5328<sign> ::= `-' | `+' | $\epsilon$ 5329 5330<number> ::= <integer> 5331\alt <floating-point> 5332 5333<char-sequence> ::= \{ <any-char> \} 5334 5335<stringliteral> ::= `"' <char-sequence> `"' 5336 5337<identifier> ::= <letter-or-underscore> \{ <letter-or-underscore-or-digit> \} 5338 5339\end{grammar} 5340 5341\section*{Overall structure} 5342 5343\begin{grammar} 5344<shader-file> ::= \{ <global-declaration> \} 5345 5346<global-declaration> ::= <function-declaration> 5347\alt <struct-declaration> 5348\alt <shader-declaration> 5349 5350<shader-declaration> ::= \spc \\ 5351 <shadertype> <identifier> <metadata-block-opt> 5352 "(" <shader-formal-params-opt> ")" "{" <statement-list> "}" 5353 5354<shadertype> ::= "displacement" | "shader" | "surface" | "volume" 5355 5356<shader-formal-params> ::= <shader-formal-param> \{ "," <shader-formal-param> \} 5357 5358<shader-formal-param> ::= <outputspec> <typespec> <identifier> 5359 <initializer> <metadata-block-opt> 5360\alt <outputspec> <typespec> <identifier> <arrayspec> 5361 <initializer-list> <metadata-block-opt> 5362 5363<metadata-block> ::= "[[" <metadata> \{ "," <metadata> \} "]]" 5364 5365<metadata> ::= <simple-typespec> <identifier> <initializer> 5366 5367\end{grammar} 5368 5369 5370\section*{Declarations} 5371\begin{grammar} 5372 5373<function-declaration> ::= \spc \\ <typespec> <identifier> 5374 "(" <function-formal-params-opt> ")" "{" <statement-list> "}" 5375 5376<function-formal-params> ::= <function-formal-param> \{ "," <function-formal-param> \} 5377 5378<function-formal-param> ::= <outputspec> <typespec> <identifier> <arrayspec-opt> 5379 5380<outputspec> ::= "output" | $\epsilon$ 5381 5382<struct-declaration> ::= "struct" <identifier> "{" <field-declarations> "}" ";" 5383 5384<field-declarations> ::= <field-declaration> \{ <field-declaration> \} 5385 5386<field-declaration> ::= <typespec> <typed-field-list> ";" 5387 5388<typed-field-list> ::= <typed-field> \{ "," <typed-field> \} 5389 5390<typed-field> ::= <identifier> <arrayspec-opt> 5391 5392<local-declaration> ::= <function-declaration> 5393\alt <variable-declaration> 5394 5395<arrayspec> ::= "[" <integer> "]" 5396\alt "[" "]" 5397 5398<variable-declaration> ::= <typespec> <def-expressions> ";" 5399 5400<def-expressions> ::= <def-expression> \{ "," <def-expression> \} 5401 5402<def-expression> ::= <identifier> <initializer-opt> 5403\alt <identifier> <arrayspec> <initializer-list-opt> 5404 5405<initializer> ::= "=" <expression> 5406 5407<initializer-list> ::= "=" <compound-initializer> 5408 5409<compound-initializer> ::= "{" <init-expression-list> "}" 5410 5411<init-expression-list> ::= <init-expression> \{ "," <init-expression> \} 5412 5413<init-expression> ::= <expression> | <compound-initializer> 5414 5415<typespec> ::= <simple-typename> 5416\alt "closure" <simple-typename> 5417\alt <identifier-structname> 5418 5419<simple-typename> ::= 5420"color" 5421| "float" 5422| "matrix" 5423| "normal" 5424| "point" 5425| "string" 5426| "vector" 5427| "void" 5428 5429\end{grammar} 5430 5431 5432\section*{Statements} 5433\begin{grammar} 5434 5435<statement-list> ::= <statement> \{ <statement> \} 5436 5437<statement> ::= 5438<compound-expression-opt> ";" 5439\alt <scoped-statements> 5440\alt <local-declaration> 5441\alt <conditional-statement> 5442\alt <loop-statement> 5443\alt <loopmod-statement> 5444%\alt <lighting-statement> 5445\alt <return-statement> 5446 5447<scoped-statements> ::= "{" <statement-list-opt> "}" 5448 5449<conditional-statement> ::= \spc \\ "if" "(" <compound-expression> ")" <statement> 5450\alt "if" "(" <compound-expression> ")" <statement> "else" <statement> 5451 5452<loop-statement> ::= \spc \\ "while" "(" <compound-expression> ")" <statement> 5453\alt "do" <statement> "while" "(" <compound-expression> ")" ";" 5454\alt "for" "(" <for-init-statement-opt> <compound-expression-opt> ";" 5455 <compound-expression-opt> ")" <statement> 5456 5457<for-init-statement> ::= \spc \\ <expression-opt> ";" 5458\alt <variable-declaration> 5459 5460<loopmod-statement> ::= "break" ";" 5461\alt "continue" ";" 5462 5463%<lighting-statement> ::= \spc \\ "emit" "(" <expression-list-opt> ")" <statement> 5464%\alt "lights" "(" <expression-list-opt> ")" <statement> 5465%\alt "trace" "(" <expression-list-opt> ")" <statement> 5466 5467<return-statement> ::= "return" <expression-opt> ";" 5468 5469\end{grammar} 5470 5471 5472\section*{Expressions} 5473\begin{grammar} 5474 5475<expression-list> ::= <expression> \{ "," <expression> \} 5476 5477<expression> ::= <number> 5478\alt <stringliteral> 5479\alt <type-constructor> 5480\alt <incdec-op> <variable-ref> 5481\alt <expression> <binary-op> <expression> 5482\alt <unary-op> <expression> 5483\alt "(" <compound-expression> ")" 5484\alt <function-call> 5485\alt <assign-expression> 5486\alt <ternary-expression> 5487\alt <typecast-expression> 5488\alt <variable-ref> 5489\alt <compound-initializer> 5490 5491<compound-expression> ::= <expression> \{ "," <expression> \} 5492 5493<variable-lvalue> ::= <identifier> <array-deref-opt> <component-deref-opt> 5494\alt <variable_lvalue> "[" <expression> "]" 5495\alt <variable_lvalue> "." <identifier> 5496 5497<variable-ref> ::= <identifier> <array-deref-opt> 5498 5499<array-deref> ::= "[" <expression> "]" 5500 5501<component-deref> ::= "[" <expression> "]" 5502\alt "." <component-field> 5503 5504<component-field> ::= "x" | "y" | "z" | "r" | "g" | "b" 5505 5506<binary-op> ::= "*" | "/" | "\%" 5507\alt "+" | "-" 5508\alt "<<" | ">>" 5509\alt "<" | "<=" | ">" | ">=" 5510\alt "==" | "!=" 5511\alt "&" 5512\alt "^" 5513\alt "|" 5514\alt "&&" | "and" 5515\alt "||" | "or" 5516 5517<unary-op> ::= "-" | "~" | "!" | "not" 5518 5519<incdec-op> ::= "++" | "--" 5520 5521<type-constructor> ::= <typespec> "(" <expression-list> ")" 5522 5523<function-call> ::= <identifier> "(" <function-args-opt> ")" 5524 5525<function-args> ::= <expression> \{ "," <expression> \} 5526 5527<assign-expression> ::= <variable-lvalue> <assign-op> <expression> 5528 5529<assign-op> ::= "=" | "*=" | "/=" | "+=" | "-=" | "&=" | "|=" | "^=" | 5530"<<=" | ">>=" 5531 5532<ternary-expression> ::= <expression> "?" <expression> ":" <expression> 5533 5534<typecast-expression> ::= "(" <simple-typename> ")" <expression> 5535 5536\end{grammar} 5537 5538 5539\chapter{Describing shader groups} 5540\label{chap:describingshadergroups} 5541\label{sec:serialize} 5542 5543Below, we propose a simple grammar giving a standard way to serialize (i.e., 5544express as text) a full shader group, including instance values and 5545connectivity of the shader layers. There are only three 5546statements/operations: set an instance value, make a shader instance, and 5547connect two instances. 5548 5549\apiitem{{\ce param} {\rm \emph{type} \emph{paramname} \emph{value...}} {\ce ;} \\ 5550{\ce param} {\rm \emph{type} \emph{paramname} \emph{value...}} {\ce [[}{\rm\emph{metadata...}}{\ce ]] ;} } 5551 5552Declare an instance value of a shader parameter to be applied to the next 5553{\cf shader} statement. We refer to the parameter values set, which have 5554not yet had their shader declared, as \emph{pending parameters}. 5555 5556The \emph{paramname} is the name of the parameter whose instance values are 5557being specified. 5558 5559The \emph{type} is one of the basic numeric or 5560string data types described in Chapter~\ref{chap:types} ({\cf int}, {\cf 5561float}, {\cf color}, {\cf point}, {\cf vector}, {\cf normal}, {\cf matrix}, 5562or {\cf string}), or an array thereof (indicated by the usual notation of 5563{\cf [{\rm\emph{size}}]}). The \emph{type} must match the declared type 5564of the parameter in the shader. 5565 5566The actual values are listed individually, with multiple values (in the 5567case of an array or an aggregate such as a \color) simply separated by 5568whitespace. If fewer values are supplied than the total number of array 5569elements or aggregate components, the remainder will be understood to be 5570filled with 0 values. String values must be enclosed in double quotes 5571({\cf "like this"}). 5572 5573The {\cf param} statement is terminated by a semicolon ({\cf ;}). 5574 5575Optionally, metadata hints may be supplied enclosed by double brackets, 5576immediately before the semicolon. 5577\apiend 5578 5579 5580\apiitem{{\ce shader} {\rm \emph{shadername} \emph{layername}} {\ce ;}} 5581Declares a shader instance, which will receive any pending parameters that 5582were declared since the previous {\cf shader} statement (and in the process, 5583clear the list of pending parameters). 5584 5585The {\cf shadername} is an identifier that specifies the name of the shader 5586to use as the master for this instance. The {\cf layername} is an identifier 5587that names the layer (e.g., to subsequently specify it as a source or 5588destination for connections). 5589 5590The {\cf shader} statement is terminated by a semicolon ({\cf ;}). 5591\apiend 5592 5593 5594\apiitem{{\ce connect} {\rm \emph{source_layername}{\ce .}\emph{paramname} ~ 5595 \emph{destination_layername}{\ce .}\emph{paramname}} {\ce ;}} 5596 5597Establish a connection between an output parameter of a source layer and an 5598input parameter of a destination layer, both of which have been previously 5599declared within this group. The source layer must have preceded the 5600destination layer when they were declared, and the parameters must exist and 5601be of a compatible type so that it is meaningful to establish a connection 5602(for example, you may connect a \color to a \color, but you may not connect 5603a \color to a \matrix). 5604 5605If the named parameters are structures, the two structures must have 5606identical data layout, and establishing the connection will connect each 5607corresponding data member. It is also possible to make a connection of just 5608a single member of a structure by using the usual ``dot'' syntax, for 5609example, for layers {\cf A} and {\cf B}, \qkw{connect A.c.x B.y} might 5610connect A's parameter {\cf c}, member {\cf x}, to B's parameter {\cf y} (the 5611types of {\cf c.x} in A and {\cf y} in B must match). 5612 5613The {\cf connect} statement is terminated by a semicolon ({\cf ;}). 5614\apiend 5615 5616\subsection*{Example} 5617 5618\begin{tabular}{p{3.25in} p{2.5in}} 5619 {\cf param string name "rings.tx" ; } & \emph{set pending `name'} \\ 5620 {\cf param float scale 3.5 ; } & \emph{set pending `scale'} \\ 5621 {\cf shader "texturemap" "tex1" ; } & \emph{tex1 layer, picks up `name', `scale'} \\ 5622 {\cf param string name "grain.tx" ; } & \\ 5623 {\cf shader "texturemap" "tex2" ; } & \emph{} \\ 5624 {\cf param float gam 2.2 ; } & \emph{} \\ 5625 {\cf shader "gamma" "gam1" ; } & \emph{} \\ 5626 {\cf param float gam 1.0 ; } & \emph{} \\ 5627 {\cf shader "gamma" "gam2" ; } & \emph{} \\ 5628 {\cf param color woodcolor 0.42 0.38 0.22 ; } & \emph{example of a color param} \\ 5629 {\cf shader "wood" "wood1" ; } & \emph{} \\ 5630 {\cf connect tex1.Cout gam1.Cin ; } & \emph{connect tex1's Cout to gam1's Cin} \\ 5631 {\cf connect tex2.Cout gam2.Cin ; } & \emph{} \\ 5632 {\cf connect gam1.Cout wood1.rings ; } & \emph{} \\ 5633 {\cf connect gam2.Cout wood1.grain ; } & \emph{} \\ 5634\end{tabular} 5635 5636 5637\begin{comment} 5638 5639\chapter{Example Shaders} 5640\label{chap:exampleshaders} 5641 5642% \begin{annotate} 5643% Sorry, I haven't done this yet. Eventually, this chapter will have 5644% several simple (but useful and fully functional) shaders to illustrate 5645% how all these concepts fit together. 5646% \end{annotate} 5647 5648\end{comment} 5649 5650 5651\begin{comment} 5652\chapter{Design Discussion} 5653\label{chap:discussion} 5654\begin{annotate} 5655 5656In this chapter, we discuss and justify some of the design choices we've 5657made. This specification is a living document. Nothing is permanently 5658set in stone. There will someday be a 2.0 spec. It's easier to add 5659things we left out than to take out things that turned out to be 5660unnecessary things or a bad idea. 5661 5662Right now, this is just a hodge-podge of topics. Some day I will give 5663it a more coherent form. 5664 5665\medskip 5666 5667{\bf Meta-discussion: the editing of this chapter has NOT kept pace with 5668 development and solidification of the rest of the spec. It's largely 5669 written as questioning design choices -- questions that were 5670 appropriate in much older versions of this spec, but which now are set 5671 in stone and will not be changed for version 1.0. Some of the 5672 discussion is truly anachronistic, debating ``A versus B'' when we in 5673 fact have long since chosen C. In any case, until I clean this up, 5674 please view this chapter as insight into some of the early design 5675 choices, NOT as a list of actual outstanding issues to be addressed.} 5676 5677\section{Variables, Functions, and Scoping} 5678 5679\subsection{Separate namespace for functions?} 5680 5681RSL and GSL had separate symbol tables for functions and for all other 5682variables, for example allowing a variable or parameter "foo" and also a 5683function called "foo". This is not for any principled reason, but just a 5684historical accident or arbitrary choice. Once you do something like 5685that, you can never change it, because then you'll break old shaders. 5686 5687One of the nice things that came from having separate function and 5688variable namespaces is that it's perfectly ok to have a shader parameter 5689that happens to have the same name as a built-in function (for example, 5690surprisingly many RenderMan shaders have a parameter named 5691"diffuse"!). If you've ever tried to duplicate a set of shaders from a 56923rd party package (such as making a set of shaders that duplicate all 5693the Maya built-in nodes) you're very happy for separate symbol tables, 5694so that you can pick param names that are the same as the Maya parameter 5695names, without regard to whether their names happen to conflict with 5696your built-in functions, otherwise you need to mangle the symbols 5697somehow. 5698 5699C, C++, and related languages tend to have a single symbol table for 5700functions and variables. In other words, if you have a function named 5701"foo", you can't have a variable named "foo" in the same scope, and vice 5702versa. Part of the reason for this is that these languages can pass 5703functions as parameters, take their address, etc., so they use a single 5704namespace (though I think they could have separate namespace and still 5705disambiguate based on the use). 5706 5707So should we have separate function and variable namespaces (similar 5708to RMan, possibly handy to avoid name clashes, but arbitrarily different 5709than C's scoping rules), or single namespace (more "standard" in modern 5710programming language design)? 5711 5712\section{Data types} 5713 5714\subsection{Should \color be spectral?} 5715 5716This spec is written assuming that \color should explicitly be 57173-component RGB. Alternately, we could add global \inttype\ {\cf ncomps} that gives the 5718numer of components in a \color, and eliminate any built-in operations 5719and library functions that seem to require or imply a 3-component color 5720model (including type casting between \color and the 3-component 5721\point-like types). 5722 5723Spectral color is a nice abstraction. It allows implementations to use 5724a different number of color components if they choose to. It allows 5725shaders to potentially be more physically accurate or perform computions 5726that require more spectral samples. 5727 5728On the other hand, \langname is designed for production rendering. 5729Think about the vast number of things that shaders do that assume a 57303-channel model: convert back and forth to HSV, tweak the red channel, 5731generate {\cf color noise} (that's really 3D noise underneath), read 3 5732channels of texture, read channel \#4 and assume it's alpha, etc. There 5733are no scanners (outside the lab) to capture, and no paint programs to 5734generate, $n$-channel textures. No compositing software to handle 5735spectral images. No output media for $n$-channel images. With 57363-channel input and 3-channel output, if the only $n$-channel operations 5737are internal to shaders, users could do it with arrays if they really 5738wanted to. 5739 5740Abstraction is nice, but so is concreteness and explicitness about what 5741a shader is really doing and how the system really works. If all 5742implementations are likely to be 3-components underneath, why maintain 5743the pretense of $n$-components and in the process sacrifice shader 5744clarity and performance by pretending to support an abstraction that 5745doesn't really exist? 5746 5747RenderMan was specified using spectral colors, but (1) nobody ever 5748implemented it with ncomps $\ne 3$, and (2) if you really looked hard at 5749what would be required to do so, you quickly realized that there were 5750all sorts of ways that a 3-component model crept into other aspects of 5751the language, the implementation, the renderer APIs, and the shaders 5752themselves. Actually implementing an $n$-component model would have 5753been hugely disruptive. When I designed and implemented Gelato's 5754shading language (GSL), I decided that, after 15 years of RenderMan 5755never implementing spectral colors nor users requesting it, I should 5756drop the pretense. So GSL explicitly had a 3-component color model. It 5757was easier to implement RGB (for example, certain internals that 5758operated on \point-like types could be reused for \color without 5759embarrassment), and no user ever complainted. 5760 5761It seems to me that after 20 years of RSL having $n$-colors that nobody 5762has ever used, and 6 years of GSL leaving it out without negative 5763consequence, we can probably assume that we can live without it for 5764several more years, if not forever. 5765 5766Does anybody want to argue that we should nonetheless specify the 5767language as $n$-component colors? Should we use it for a while and 5768later consider a 2.0 revision that either changes the definition of 5769\color or else adds a new {\cf spectral} type that has a varying 5770number of components, for those shaders that wish to operate that way? 5771 5772 5773\subsection{4-channel colors, color/alpha combinations} 5774 5775Some shading languages have 4-channel colors (RGBA). This spec 5776(like RSL and GSL before it) does not. 5777 5778I strongly disagree with the notion of the basic \color type having an 5779embedded alpha. It mixes two concepts that don't belong together. The 5780\color type should be spectral (even if explicitly 3-channel). 5781 5782I feel less strongly about having a second type that combines a 5783\color and an alpha value (for the sake of argument, let's call it 5784a {\cf colora}). The most important benefit of doing so 5785would be to simplify the common operation of reading both color and 5786alpha data from a 4-channel texture, which awkwardly required two 5787separate texture reads in RenderMan's shading language. Gelato's 5788shading language avoided this in the same manner as OSL, namely by 5789having an argument to the texture command that allows you to return 5790an alpha: 5791 5792\begin{code} 5793 float alphavalue; 5794 color C = texture ("name.tx", s, t, "alpha", alphavalue); 5795\end{code} 5796 5797\noindent This is slightly awkward inasmuch as it does not combine 5798the color and alpha into a single ``return value,'' but at least it 5799avoids two texture calls, as well as avoiding cluttering the language 5800with another type that exists just to make this texture call simpler. 5801 5802But I can see that others may disagree. Does anybody want to argue 5803for a {\cf colora} type that explicitly combines color and alpha as a 5804core type? 5805 5806 5807\subsection{Array operations} 5808 5809As written, the only array operations allowed are element access (read 5810and write), and passing an array by reference to a function. This 5811roughly corresponds to C's and C++'s array functionality. Does 5812anybody want to argue for any of the following to be included? 5813 5814\begin{itemize} 5815\item Array assignment: {\cf A = B}, legal as long as {\cf A} and {\cf 5816 B} are the same type and have the same number of elements length? 5817\item Casting to built-in types: Ability to assign an array of length 3 5818 to a \color, \point, \vector, or \normal, and vice versa? 5819\item Array arithmetic: {\cf A + B}, and so on, defined as 5820 element-by-element addition, subtraction, etc., legal as long as the 5821 two arrays are the same type and have the same number of elements? 5822\item Anything else you feel strongly that arrays should be able to do? 5823\end{itemize} 5824 5825 5826\subsection{Recursive structures} 5827 5828We have defined structures as being allowed to consist only of basic 5829types and arrays thereof --- not structures of structures. This 5830restriction makes for a simpler grammar and implementation, simplier 5831renderer-side APIs for passing data to shaders, and simpler APIs for 5832libraries that query parameters of compiled shaders. But if people 5833strongly feel like structures-of-structures is an important feature, we 5834can consider generalizing in this way. Or, if we discover later that 5835it's more helpful than we had once thought, we can always add it in 5836future version of the spec. 5837 5838 5839\section{Syntax} 5840 5841\subsection{More C++-like overall syntax} 5842 5843I've considered that rather than the RSL-like 5844 5845\begin{code} 5846 surface plastic (float Kd = 0.5, float Ks = 0.5) 5847 { 5848 Ci = Kd * diffuse() + Ks * specular(); 5849 } 5850\end{code} 5851 5852\noindent or its method-like equivalent: 5853 5854\begin{code} 5855 surface plastic (float Kd = 0.5, float Ks = 0.5) 5856 { 5857 public void main () { 5858 Ci = Kd * diffuse() + Ks * specular(); 5859 } 5860 } 5861\end{code} 5862 5863\noindent that we switch to a syntax that even more closely mimics C++, 5864such as: 5865 5866\begin{code} 5867 class plastic : public surface 5868 { 5869 public: 5870 float Kd = 0.5; 5871 float Ks = 0.5; 5872 5873 void main (output color Ci) { 5874 Ci = Kd * diffuse() + Ks * specular(); 5875 } 5876 } 5877\end{code} 5878 5879So the idea is that instead of a shader type, you ``inherit'' from the 5880kind of shader you want; instead of parameters, you have public member 5881variables; and so on. 5882 5883But this is not really clean. Notice that the assignment of default 5884values to the ``parameters'' (now public data members) is not really 5885correct C++ syntax. I guess we could move to having a constructor: 5886 5887\begin{code} 5888 class plastic : public surface 5889 { 5890 ... 5891 plastic () : Kd(0.5), Ks(0.5) 5892 { 5893 } 5894 ... 5895 } 5896\end{code} 5897 5898But is this really any better? Are we just cluttering things up in a 5899slavish attempt to exactly replicate C++? And we leave behind the nice 5900semantics we had before where one parameter's default value could 5901actually depend on another parameter's actual value. In a number of 5902ways, OSL is NOT C++, and maybe it makes things more confusing if it 5903looks just like C++ but doesn't act just like it, or if some things look 5904just like C++ but others clearly aren't. 5905 5906I'm currently inclined to stick to the syntax in this document, and not 5907to exactly replicate C++'s class structure. But it's something we 5908could consider for future releases of the spec if people feel strongly 5909about it. 5910 5911 5912\section{Global variables} 5913 5914\subsection{Nomenclature} 5915 5916Does anybody have a perference for \dPdu and \dPdv (borrowing the 5917RenderMan names, but awkward for primitives without a consistent $u,v$ 5918parameterization?), versus something more generic such as {\cf T} and 5919{\cf B} (tangent and bitangent, without explicitly saying how they are 5920allegedly computed)? 5921 5922In this document, I'm tentatively using the RenderMan-inspired {\cf Ci} 5923and for output radiance. (The ``i'' is for 5924\emph{incident}.) In Gelato, we used {\cf C}, which I 5925think was slightly less obtuse (though loses the advantage of being 5926familiar to RenderMan experts). 5927 5928 5929\subsection{Global variables and view-dependence} 5930 5931Should we allow access to \I (incident viewing ray) from anyplace except 5932inside the integrator? 5933 5934On one hand, it's just an invitation to inadvertently build 5935view-dependence into material descriptions. 5936 5937On the other hand, view-independence is less important than 5938light-direction-independence, and we can always warn (or optionally 5939error, if a compiler flag is set) if view dependence is detected. It's 5940hard to tell if there are shader effects we will want that can only be 5941done (or be drastically easier) using old fashioned view-dependent code. 5942Perhaps we should allow it, and all due caveats and warnings to those 5943who dare use it instead of the recommended view-independent closures. 5944 5945I'm leaning toward allowing \I, for when it's needed, but warning and 5946making it easy to avoid using it. Anybody want to argue that we should 5947flat-out ban \I and other view-dependencies? 5948 5949\subsection{Normals} 5950 5951If you're not supposed to use \I or have explicit view-dependence in the 5952shaders, then what becomes of {\cf faceforward()}? Do we assume that \N 5953is already frontfacing by the time the shader runs? Do we add a {\cf 5954 Nf} that's the faceforward-ed version? Do we let \N be the natural 5955normal and assume models will always be consistently-facing (which has 5956never worked)? Force the renderer to explicitly mark ``double-sided'' 5957geometry and potentially double-shade so that normals are always 5958consistent for each ``side?'' 5959 5960\section{Closures and Illumination} 5961 5962\subsection{Light loops -- to be, or not to be?} 5963 5964With closures, can we remove all facilities for an explicit loop over 5965lights (i.e., what RenderMan calls {\cf illuminance})? At least, 5966unless/until we allow people to code integrators in the language itself? 5967 5968Or does it makes sense to allow explicit light loops, in case somebody 5969wants/needs them, but any shader that uses them loses all ability to 5970cheaply re-evaluate itself under moving cameras or changing lights, and 5971possibly loses the ability to interact with smart global illumination 5972integrators that depend on sampling their BRDF's? 5973 5974My current inclination is to leave light loops out entirely, and 5975consider adding them later if it turns out that we've made a mistake. 5976 5977\subsection{Integrators and closure implementations -- in the shading language?} 5978 5979For now, I'm assuming that the integrator itself, as well as the 5980implementations of the ``primitive'' closure functions, are a hard-coded 5981part of the renderer itself, or implemented as plug-ins in a way that's 5982proprietary to the renderer. 5983 5984It's very tempting to extend the language itself to be able to express a 5985primitive closure function or an integrator. But I fear that (1) this 5986will be more expensive than we want; and (2) we don't know the best way 5987to do it yet; (3) it will require a variety of syntaxes, functions, and 5988complications in the language that would not otherwise be needed. 5989 5990So I'm currently leaning toward leaving this out of the language for 5991now, and considering it for a future revision. Comments? 5992 5993\section{Transparency, Opacity, and Holdout mattes} 5994 5995Transparency is a tricky subject. There are at least four slightly 5996different concepts at play here: (1) Gathering illumination from the 5997back side of a surface; (2) Proper coherent refraction of objects 5998``behind'' the primitive being shaded (usually employing ray tracing); 5999(3) Seeing an undistored image (unrefracted) image of what's behind the 6000primitive, usually employing a ``compositing'' method; (4) making an 6001object ``disappear'' to form a ``stencil'' effect under shader control. 6002 6003It is clear that \#1 and \#2 are properly handled with our usual 6004material closures ({\cf translucent} and {\cf refraction()}, 6005respectively). 6006 6007The real question is how to handle the kind of compositing opacity of 6008\#3 and \#4. The ``usual'' way (in renderers I've written before, 6009anyway), is to have a special variable that holds the opacity of the 6010surface. In RenderMan, this is called {\cf Oi}, in Gelato it was the 6011less obscure {\cf opacity}. It defaults to (1,1,1). The shader is 6012responsible for scaling reflectivities by this amount. The renderer 6013accumulates this for all subpixel samples, filters it, and reduces this 6014to a single \emph{alpha} for each pixel (usually by averaging the 6015channels, or using a luminance transformation). 6016 6017There is usually a special case for \emph{holdout mattes} --- objects 6018that leave a ``hole'' with $\alpha = 0$ in the final image, yet still 6019hide any in-render objects behind it. In RenderMan and Gelato, objects 6020were designated as holdouts via the renderer API, not under shader 6021control (in fact, shaders generally aren't even run on holdout objects). 6022In PRMan and Entropy, this was extended so that holdout objects would 6023run their shaders, and the computed opacity (\Oi) was used to control 6024\emph{partial matteness}, allowing shaders to ``fade'' matteness in, or 6025use a pattern to programmatically define the matte area in the shader. 6026It was still really hard to have full shader control over all aspects of 6027matteing, such as wanting an object to completely block what's behind it 6028in-scene but leave a non-zero and non-one value in the image's 6029\emph{alpha} channel, and it still depended on the object being tagged 6030as ``matte'' through the renderer API (a clever shader couldn't do it on 6031its own). 6032 6033I've under-specified how this should work in this document, presumably 6034falling back to the RenderMan-like behavior as our default position. 6035But I want to throw a few additional options out here for debate: 6036 6037\begin{itemize} 6038\item Default / RenderMan way: shader sets \Oi $< 1$ for ``compositing 6039 transparency'', renderer auto-composites objects behind the surface 6040 (without refraction), accumulated opacity directly translates into 6041 alpha channel, holdout mattes designated through renderer API. 6042\item Separate opacity/alpha controls: \Oi controls compositing 6043 transparency; a separate {\cf alpha} global variable can be set that 6044 becomes the opacity (if not set by the shader, it will be set to the 6045 \Oi result). In other words, a holdout matte could be controlled by 6046 the shader with {\cf Oi=1, alpha=0}, that blocks visibility of 6047 in-render objects, but puts a hole in the output image's alpha 6048 channel. 6049\item Similar to the last item, but instead of the confusing {\cf Oi, 6050 alpha} nomenclature, use {\cf Oi} and {\cf holdout} (defaulting to 0, 6051 i.e., the object is not a holdout object). Partial holdoutness can be 6052 set. The renderer handles how the holdoutness affects the image 6053 channels and compositing. So a shader would make a holdout matte with 6054 {\cf Oi=1, holdout=1}, transparency with {\cf Oi<1, holdout=0}. 6055\item No explicit \Oi at all (!), but rather make a material closure 6056 primitive function {\cf transparency()} that the renderer understands. 6057 So compositing transparency could be explicit in the lighting 6058 function: 6059 \begin{code} 6060 opac = ...compute...; 6061 Ci = opac * diffuse() + (1-opac) * transparency(); 6062 \end{code} 6063 Or even, {\cf refraction()} could serve the same purpose, and the 6064 renderer could just know that if the index of refraction is 1, it 6065 should use the compositing trick. 6066 6067 Holdout mattes don't fall into this scheme especially well, so there's 6068 an orthogonal problem of whether to have a {\cf holdout} variable to 6069 set, or a renderer API function. 6070\end{itemize} 6071 6072What do you guys think? I'm kind of leaning toward the third solution 6073--- having shaders set {\cf Oi} and {\cf holdout} variables, allowing 6074full control in the shader. 6075 6076\end{annotate} 6077\end{comment} 6078 6079 6080 6081%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 6082 6083\part*{Appendices} 6084\begin{appendix} 6085 6086\chapter{Glossary} 6087\label{chap:glossary} 6088 6089\begin{description} 6090 6091\item[Attribute state.] The set of variables that determines all the 6092 properties (other than shape) of a \emph{geometric primitive} --- such 6093 as its local transformation matrix, the surface, displacement, and 6094 volume shaders to be used, which light sources illuminate objects that 6095 share the attribute state, whether surfaces are one-sided or 6096 two-sided, etc. Basically all of the options that determine the 6097 behavior and appearance of the primitives, that are not determined by 6098 the shape itself or the code of the shaders. A single attribute state 6099 may be shared among multiple geometric primitives. Also sometimes 6100 called \emph{graphics state}. 6101 6102\item[Built-in function.] A function callable from within a shader, where 6103 the implementation of the function is provided by the renderer (as 6104 opposed to a function that the shader author writes in \langname 6105 itself). 6106 6107\item[Closure.] A symbolic representation of a function to be called, 6108 and values for its parameters, that are packaged up to be evaluated 6109 at a later time to yield a final numeric value. 6110 6111\item[Connection.] A routing of the value of an \emph{output parameter} 6112 of one \emph{shader layer} to an \emph{input paramter} of another 6113 shader layer within the same \emph{shader group}. 6114 6115\item[Default parameter value.] The initial value of a \emph{shader 6116 parameter}, if the renderer does not override it with an 6117 \emph{instance value}, an interpolated \emph{primitive variable}, or a 6118 \emph{connection} to an output parameter of another \emph{layer} 6119 within the \emph{group}. The default value of a shader parameter 6120 is explicitly given in the code for that shader, and may either be 6121 a constant or a computed expression. 6122 6123\item[Geometric primitive.] A single shape, such as a NURBS patch, a 6124 polygon or subdivision mesh, a hair primitive, etc. 6125 6126\item[Global variables.] The set of ``built-in'' variables describing the 6127 common renderer inputs to all shaders (as opposed to shader-specific 6128 parameters). These include position (\P), surface normal (\N), 6129 surface tangents (\dPdu, \dPdv), as well as standard radiance output (\Ci). 6130 Different \emph{shader types} support 6131 different subsets of the global variables. 6132 6133\item[Graphics state.] See \emph{attribute state}. 6134 6135\item[Group.] See \emph{shader group}. 6136 6137\item[Input parameter.] A read-only \emph{shader parameter} that provides 6138 a value to control a shader's behavior. Can also refer to a read-only 6139 parameter to a \emph{shader function}. 6140 6141\item[Instance value.] A constant value that overrides a \emph{default 6142 parameter value} for a particular \emph{shader instance}. Each 6143 instance of a shader may have a completely different set of instance 6144 values for its parameters. 6145 6146\item[Layer.] See \emph{shader layer}. 6147 6148\item[Output parameter.] A read/write \emph{shader parameter} allows a 6149 shader to provide outputs beyond the \emph{global variables} such as 6150 \Ci. Can also refer to a read/write parameter to a 6151 \emph{shader function}, allowing a function to provide more outputs 6152 than a simple return value. 6153 6154\item[Primitive.] Usually refers to a \emph{geometric primitive}. 6155 6156\item[Primitive variable.] A named variable, and values, attached to an 6157 individual geometric primitive. Primitive variables may have one of 6158 serveral \emph{interpolation methods} --- such as a single value for 6159 the whole primitive, a value for each piece or face of the primitive, 6160 or per-vertex values that are smoothly interpolated across the 6161 surface. 6162 6163\item[Public method.] A function within a shader that has an entry point 6164 that is visible and directly callable by the renderer, as opposed to 6165 merely being called from other code within the shader. Public methods 6166 must be \emph{top-level} (not defined within other functions) and must 6167 be preceeded by the {\cf public} keyword. 6168 6169\item[Shader.] A small self-contained program written in \langname, used 6170 to extend the functionality of a renderer with custom behavior of 6171 materials and lights. A particular shader may have multiple 6172 \emph{shader instances} within a scene, each of which has ts unique 6173 \emph{instance parameters}, transformation, etc. 6174 6175\item[Shader function.] A function written in \langname that may be 6176 called from within a shader. 6177 6178\item[Shader group.] An ordered collection of \emph{shader instances} 6179 (individually called the \emph{layers} of a group) that are executed 6180 to collectively determine material properties or displacement of a 6181 geometric primitive, emission of a light source, or scattering 6182 properties of a volume. In addition to executing sequentially, layers 6183 within a group may optionally have any of their input parameters 6184 explicitly connected to output parameters of other layers within the 6185 group in an acyclic manner (thus, sometimes being referred to as a 6186 \emph{shader network}). 6187 6188\item[Shader instance.] A particular reference to a \emph{shader}, with 6189 a unique set of {\cf instance values}, transformation, and potentially 6190 other attributes. Each shader instance is a separate entity, despite 6191 their sharing executable code. 6192 6193\item[Shader network.] See \emph{shader group}. 6194 6195\item[Shader layer.] An individual \emph{shader instance} within a 6196 \emph{shader group}. 6197 6198\item[Shader parameter.] A named input or output variable of a shader. 6199 \emph{Input parameters} provide ``knobs'' that control the behavior of 6200 a shader; \emph{output parameters} additional provide a way for 6201 shaders to produce additional output beyond the usual \emph{global 6202 variables}. 6203 6204\item[Shading.] The computations within a renderer that implement the 6205 behavior and visual appearance of materials and lights. 6206 6207\end{description} 6208 6209\end{appendix} 6210 6211\backmatter 6212 6213%\bibliographystyle{alpha} %% Select for [FB95] 6214\bibliographystyle{apalike} %% Select for (Foo and Bar, 1995) 6215%\addcontentsline{toc}{chapter}{Bibliography} 6216%\bibliography{mybib} 6217 6218\addcontentsline{toc}{chapter}{Index} 6219\printindex 6220 6221\end{document} 6222 6223 6224% Canonical figure 6225%\begin{figure}[ht] 6226%\noindent 6227%\includegraphics[width=5in]{Figures/foo} 6228%\caption{Caption 6229%\label{fig:foo}} 6230%\end{figure} 6231 6232 6233%\apiitem{ret {\ce func} (args)} 6234%\indexapi{func()} 6235%\endapi 6236