add BLI_strcpy_rlen, replace strcat, which was used in misleading way.
[blender.git] / intern / cycles / render / osl.cpp
1 /*
2  * Copyright 2011, Blender Foundation.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  */
18
19 #include "device.h"
20
21 #include "graph.h"
22 #include "light.h"
23 #include "osl.h"
24 #include "scene.h"
25 #include "shader.h"
26
27 #ifdef WITH_OSL
28
29 #include "osl_globals.h"
30 #include "osl_services.h"
31 #include "osl_shader.h"
32
33 #include "util_foreach.h"
34 #include "util_md5.h"
35 #include "util_path.h"
36 #include "util_progress.h"
37
38 #endif
39
40 CCL_NAMESPACE_BEGIN
41
42 #ifdef WITH_OSL
43
44 /* Shared Texture and Shading System */
45
46 OSL::TextureSystem *OSLShaderManager::ts_shared = NULL;
47 int OSLShaderManager::ts_shared_users = 0;
48 thread_mutex OSLShaderManager::ts_shared_mutex;
49
50 OSL::ShadingSystem *OSLShaderManager::ss_shared = NULL;
51 OSLRenderServices *OSLShaderManager::services_shared = NULL;
52 int OSLShaderManager::ss_shared_users = 0;
53 thread_mutex OSLShaderManager::ss_shared_mutex;
54 thread_mutex OSLShaderManager::ss_mutex;
55
56 /* Shader Manager */
57
58 OSLShaderManager::OSLShaderManager()
59 {
60         texture_system_init();
61         shading_system_init();
62 }
63
64 OSLShaderManager::~OSLShaderManager()
65 {
66         shading_system_free();
67         texture_system_free();
68 }
69
70 void OSLShaderManager::reset(Scene *scene)
71 {
72         shading_system_free();
73         shading_system_init();
74 }
75
76 void OSLShaderManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
77 {
78         if(!need_update)
79                 return;
80
81         device_free(device, dscene, scene);
82
83         /* determine which shaders are in use */
84         device_update_shaders_used(scene);
85
86         /* create shaders */
87         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
88
89         foreach(Shader *shader, scene->shaders) {
90                 assert(shader->graph);
91
92                 if(progress.get_cancel()) return;
93
94                 /* we can only compile one shader at the time as the OSL ShadingSytem
95                  * has a single state, but we put the lock here so different renders can
96                  * compile shaders alternating */
97                 thread_scoped_lock lock(ss_mutex);
98
99                 OSLCompiler compiler((void*)this, (void*)ss, scene->image_manager);
100                 compiler.background = (shader == scene->shaders[scene->default_background]);
101                 compiler.compile(og, shader);
102
103                 if(shader->sample_as_light && shader->has_surface_emission)
104                         scene->light_manager->need_update = true;
105         }
106
107         /* setup shader engine */
108         og->ss = ss;
109         og->ts = ts;
110         og->services = services;
111
112         int background_id = scene->shader_manager->get_shader_id(scene->default_background);
113         og->background_state = og->surface_state[background_id & SHADER_MASK];
114         og->use = true;
115
116         foreach(Shader *shader, scene->shaders)
117                 shader->need_update = false;
118
119         need_update = false;
120         
121         /* set texture system */
122         scene->image_manager->set_osl_texture_system((void*)ts);
123
124         device_update_common(device, dscene, scene, progress);
125 }
126
127 void OSLShaderManager::device_free(Device *device, DeviceScene *dscene, Scene *scene)
128 {
129         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
130
131         device_free_common(device, dscene, scene);
132
133         /* clear shader engine */
134         og->use = false;
135         og->ss = NULL;
136         og->ts = NULL;
137
138         og->surface_state.clear();
139         og->volume_state.clear();
140         og->displacement_state.clear();
141         og->background_state.reset();
142 }
143
144 void OSLShaderManager::texture_system_init()
145 {
146         /* create texture system, shared between different renders to reduce memory usage */
147         thread_scoped_lock lock(ts_shared_mutex);
148
149         if(ts_shared_users == 0) {
150                 ts_shared = TextureSystem::create(true);
151
152                 ts_shared->attribute("automip",  1);
153                 ts_shared->attribute("autotile", 64);
154                 ts_shared->attribute("gray_to_rgb", 1);
155
156                 /* effectively unlimited for now, until we support proper mipmap lookups */
157                 ts_shared->attribute("max_memory_MB", 16384);
158         }
159
160         ts = ts_shared;
161         ts_shared_users++;
162 }
163
164 void OSLShaderManager::texture_system_free()
165 {
166         /* shared texture system decrease users and destroy if no longer used */
167         thread_scoped_lock lock(ts_shared_mutex);
168         ts_shared_users--;
169
170         if(ts_shared_users == 0) {
171                 OSL::TextureSystem::destroy(ts_shared);
172                 ts_shared = NULL;
173         }
174
175         ts = NULL;
176 }
177
178 void OSLShaderManager::shading_system_init()
179 {
180         /* create shading system, shared between different renders to reduce memory usage */
181         thread_scoped_lock lock(ss_shared_mutex);
182
183         if(ss_shared_users == 0) {
184                 services_shared = new OSLRenderServices();
185
186                 ss_shared = OSL::ShadingSystem::create(services_shared, ts_shared, &errhandler);
187                 ss_shared->attribute("lockgeom", 1);
188                 ss_shared->attribute("commonspace", "world");
189                 ss_shared->attribute("optimize", 2);
190                 //ss_shared->attribute("debug", 1);
191                 //ss_shared->attribute("statistics:level", 1);
192                 ss_shared->attribute("searchpath:shader", path_get("shader"));
193
194                 /* our own ray types */
195                 static const char *raytypes[] = {
196                         "camera",               /* PATH_RAY_CAMERA */
197                         "reflection",   /* PATH_RAY_REFLECT */
198                         "refraction",   /* PATH_RAY_TRANSMIT */
199                         "diffuse",              /* PATH_RAY_DIFFUSE */
200                         "gloss_sharedy",                /* PATH_RAY_GLOSSY */
201                         "singular",             /* PATH_RAY_SINGULAR */
202                         "transparent",  /* PATH_RAY_TRANSPARENT */
203                         "shadow",               /* PATH_RAY_SHADOW_OPAQUE */
204                         "shadow",               /* PATH_RAY_SHADOW_TRANSPARENT */
205                 };
206
207                 const int nraytypes = sizeof(raytypes)/sizeof(raytypes[0]);
208                 ss_shared->attribute("raytypes", TypeDesc(TypeDesc::STRING, nraytypes), raytypes);
209
210                 OSLShader::register_closures((OSLShadingSystem*)ss_shared);
211
212                 loaded_shaders.clear();
213         }
214
215         ss = ss_shared;
216         services = services_shared;
217         ss_shared_users++;
218 }
219
220 void OSLShaderManager::shading_system_free()
221 {
222         /* shared shading system decrease users and destroy if no longer used */
223         thread_scoped_lock lock(ss_shared_mutex);
224         ss_shared_users--;
225
226         if(ss_shared_users == 0) {
227                 OSL::ShadingSystem::destroy(ss_shared);
228                 ss_shared = NULL;
229
230                 delete services_shared;
231                 services_shared = NULL;
232         }
233
234         ss = NULL;
235         services = NULL;
236 }
237
238 bool OSLShaderManager::osl_compile(const string& inputfile, const string& outputfile)
239 {
240         vector<string> options;
241         string stdosl_path;
242
243         /* specify output file name */
244         options.push_back("-o");
245         options.push_back(outputfile);
246
247         /* specify standard include path */
248         options.push_back("-I" + path_get("shader"));
249         stdosl_path = path_get("shader/stdosl.h");
250
251         /* compile */
252         OSL::OSLCompiler *compiler = OSL::OSLCompiler::create();
253         bool ok = compiler->compile(inputfile, options, stdosl_path);
254         delete compiler;
255
256         return ok;
257 }
258
259 bool OSLShaderManager::osl_query(OSL::OSLQuery& query, const string& filepath)
260 {
261         string searchpath = path_user_get("shaders");
262         return query.open(filepath, searchpath);
263 }
264
265 static string shader_filepath_hash(const string& filepath, uint64_t modified_time)
266 {
267         /* compute a hash from filepath and modified time to detect changes */
268         MD5Hash md5;
269         md5.append((const uint8_t*)filepath.c_str(), filepath.size());
270         md5.append((const uint8_t*)&modified_time, sizeof(modified_time));
271
272         return md5.get_hex();
273 }
274
275 const char *OSLShaderManager::shader_test_loaded(const string& hash)
276 {
277         map<string, OSLShaderInfo>::iterator it = loaded_shaders.find(hash);
278         return (it == loaded_shaders.end())? NULL: it->first.c_str();
279 }
280
281 OSLShaderInfo *OSLShaderManager::shader_loaded_info(const string& hash)
282 {
283         map<string, OSLShaderInfo>::iterator it = loaded_shaders.find(hash);
284         return (it == loaded_shaders.end())? NULL: &it->second;
285 }
286
287 const char *OSLShaderManager::shader_load_filepath(string filepath)
288 {
289         size_t len = filepath.size();
290         string extension = filepath.substr(len - 4);
291         uint64_t modified_time = path_modified_time(filepath);
292
293         if(extension == ".osl") {
294                 /* .OSL File */
295                 string osopath = filepath.substr(0, len - 4) + ".oso";
296                 uint64_t oso_modified_time = path_modified_time(osopath);
297
298                 /* test if we have loaded the corresponding .OSO already */
299                 if(oso_modified_time != 0) {
300                         const char *hash = shader_test_loaded(shader_filepath_hash(osopath, oso_modified_time));
301
302                         if(hash)
303                                 return hash;
304                 }
305
306                 /* autocompile .OSL to .OSO if needed */
307                 if(oso_modified_time == 0 || (oso_modified_time < modified_time)) {
308                         OSLShaderManager::osl_compile(filepath, osopath);
309                         modified_time = path_modified_time(osopath);
310                 }
311                 else
312                         modified_time = oso_modified_time;
313
314                 filepath = osopath;
315         }
316         else {
317                 if(extension == ".oso") {
318                         /* .OSO File, nothing to do */
319                 }
320                 else if(path_dirname(filepath) == "") {
321                         /* .OSO File in search path */
322                         filepath = path_join(path_user_get("shaders"), filepath + ".oso");
323                 }
324                 else {
325                         /* unknown file */
326                         return NULL;
327                 }
328
329                 /* test if we have loaded this .OSO already */
330                 const char *hash = shader_test_loaded(shader_filepath_hash(filepath, modified_time));
331
332                 if(hash)
333                         return hash;
334         }
335
336         /* read oso bytecode from file */
337         string bytecode_hash = shader_filepath_hash(filepath, modified_time);
338         string bytecode;
339
340         if(!path_read_text(filepath, bytecode)) {
341                 fprintf(stderr, "Cycles shader graph: failed to read file %s\n", filepath.c_str());
342                 OSLShaderInfo info;
343                 loaded_shaders[bytecode_hash] = info; /* to avoid repeat tries */
344                 return NULL;
345         }
346
347         return shader_load_bytecode(bytecode_hash, bytecode);
348 }
349
350 const char *OSLShaderManager::shader_load_bytecode(const string& hash, const string& bytecode)
351 {
352         ss->LoadMemoryCompiledShader(hash.c_str(), bytecode.c_str());
353
354         /* this is a bit weak, but works */
355         OSLShaderInfo info;
356         info.has_surface_emission = (bytecode.find("\"emission\"") != string::npos);
357         info.has_surface_transparent = (bytecode.find("\"transparent\"") != string::npos);
358         info.has_surface_bssrdf = (bytecode.find("\"bssrdf\"") != string::npos);
359         loaded_shaders[hash] = info;
360
361         return loaded_shaders.find(hash)->first.c_str();
362 }
363
364 /* Graph Compiler */
365
366 OSLCompiler::OSLCompiler(void *manager_, void *shadingsys_, ImageManager *image_manager_)
367 {
368         manager = manager_;
369         shadingsys = shadingsys_;
370         image_manager = image_manager_;
371         current_type = SHADER_TYPE_SURFACE;
372         current_shader = NULL;
373         background = false;
374 }
375
376 string OSLCompiler::id(ShaderNode *node)
377 {
378         /* assign layer unique name based on pointer address + bump mode */
379         stringstream stream;
380         stream << "node_" << node->name << "_" << node;
381
382         return stream.str();
383 }
384
385 string OSLCompiler::compatible_name(ShaderNode *node, ShaderInput *input)
386 {
387         string sname(input->name);
388         size_t i;
389
390         /* strip whitespace */
391         while((i = sname.find(" ")) != string::npos)
392                 sname.replace(i, 1, "");
393         
394         /* if output exists with the same name, add "In" suffix */
395         foreach(ShaderOutput *output, node->outputs) {
396                 if (strcmp(input->name, output->name)==0) {
397                         sname += "In";
398                         break;
399                 }
400         }
401         
402         return sname;
403 }
404
405 string OSLCompiler::compatible_name(ShaderNode *node, ShaderOutput *output)
406 {
407         string sname(output->name);
408         size_t i;
409
410         /* strip whitespace */
411         while((i = sname.find(" ")) != string::npos)
412                 sname.replace(i, 1, "");
413         
414         /* if input exists with the same name, add "Out" suffix */
415         foreach(ShaderInput *input, node->inputs) {
416                 if (strcmp(input->name, output->name)==0) {
417                         sname += "Out";
418                         break;
419                 }
420         }
421         
422         return sname;
423 }
424
425 bool OSLCompiler::node_skip_input(ShaderNode *node, ShaderInput *input)
426 {
427         /* exception for output node, only one input is actually used
428          * depending on the current shader type */
429         
430         if(!(input->usage & ShaderInput::USE_OSL))
431                 return true;
432
433         if(node->name == ustring("output")) {
434                 if(strcmp(input->name, "Surface") == 0 && current_type != SHADER_TYPE_SURFACE)
435                         return true;
436                 if(strcmp(input->name, "Volume") == 0 && current_type != SHADER_TYPE_VOLUME)
437                         return true;
438                 if(strcmp(input->name, "Displacement") == 0 && current_type != SHADER_TYPE_DISPLACEMENT)
439                         return true;
440                 if(strcmp(input->name, "Normal") == 0)
441                         return true;
442         }
443         else if(node->name == ustring("bump")) {
444                 if(strcmp(input->name, "Height") == 0)
445                         return true;
446         }
447         else if(current_type == SHADER_TYPE_DISPLACEMENT && input->link && input->link->parent->name == ustring("bump"))
448                 return true;
449
450         return false;
451 }
452
453 void OSLCompiler::add(ShaderNode *node, const char *name, bool isfilepath)
454 {
455         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
456
457         /* load filepath */
458         if(isfilepath) {
459                 name = ((OSLShaderManager*)manager)->shader_load_filepath(name);
460
461                 if(name == NULL)
462                         return;
463         }
464
465         /* pass in fixed parameter values */
466         foreach(ShaderInput *input, node->inputs) {
467                 if(!input->link) {
468                         /* checks to untangle graphs */
469                         if(node_skip_input(node, input))
470                                 continue;
471                         /* already has default value assigned */
472                         else if(input->default_value != ShaderInput::NONE)
473                                 continue;
474
475                         string param_name = compatible_name(node, input);
476                         switch(input->type) {
477                                 case SHADER_SOCKET_COLOR:
478                                         parameter_color(param_name.c_str(), input->value);
479                                         break;
480                                 case SHADER_SOCKET_POINT:
481                                         parameter_point(param_name.c_str(), input->value);
482                                         break;
483                                 case SHADER_SOCKET_VECTOR:
484                                         parameter_vector(param_name.c_str(), input->value);
485                                         break;
486                                 case SHADER_SOCKET_NORMAL:
487                                         parameter_normal(param_name.c_str(), input->value);
488                                         break;
489                                 case SHADER_SOCKET_FLOAT:
490                                         parameter(param_name.c_str(), input->value.x);
491                                         break;
492                                 case SHADER_SOCKET_INT:
493                                         parameter(param_name.c_str(), (int)input->value.x);
494                                         break;
495                                 case SHADER_SOCKET_STRING:
496                                         parameter(param_name.c_str(), input->value_string);
497                                         break;
498                                 case SHADER_SOCKET_CLOSURE:
499                                 case SHADER_SOCKET_UNDEFINED:
500                                         break;
501                         }
502                 }
503         }
504
505         /* create shader of the appropriate type. we pass "surface" to all shaders,
506          * because "volume" and "displacement" don't work yet in OSL. the shaders
507          * work fine, but presumably these values would be used for more strict
508          * checking, so when that is fixed, we should update the code here too. */
509         if(current_type == SHADER_TYPE_SURFACE)
510                 ss->Shader("surface", name, id(node).c_str());
511         else if(current_type == SHADER_TYPE_VOLUME)
512                 ss->Shader("surface", name, id(node).c_str());
513         else if(current_type == SHADER_TYPE_DISPLACEMENT)
514                 ss->Shader("surface", name, id(node).c_str());
515         else
516                 assert(0);
517         
518         /* link inputs to other nodes */
519         foreach(ShaderInput *input, node->inputs) {
520                 if(input->link) {
521                         if(node_skip_input(node, input))
522                                 continue;
523
524                         /* connect shaders */
525                         string id_from = id(input->link->parent);
526                         string id_to = id(node);
527                         string param_from = compatible_name(input->link->parent, input->link);
528                         string param_to = compatible_name(node, input);
529
530                         ss->ConnectShaders(id_from.c_str(), param_from.c_str(), id_to.c_str(), param_to.c_str());
531                 }
532         }
533
534         /* test if we shader contains specific closures */
535         OSLShaderInfo *info = ((OSLShaderManager*)manager)->shader_loaded_info(name);
536
537         if(info) {
538                 if(info->has_surface_emission)
539                         current_shader->has_surface_emission = true;
540                 if(info->has_surface_transparent)
541                         current_shader->has_surface_transparent = true;
542                 if(info->has_surface_bssrdf)
543                         current_shader->has_surface_bssrdf = true;
544         }
545 }
546
547 void OSLCompiler::parameter(const char *name, float f)
548 {
549         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
550         ss->Parameter(name, TypeDesc::TypeFloat, &f);
551 }
552
553 void OSLCompiler::parameter_color(const char *name, float3 f)
554 {
555         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
556         ss->Parameter(name, TypeDesc::TypeColor, &f);
557 }
558
559 void OSLCompiler::parameter_point(const char *name, float3 f)
560 {
561         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
562         ss->Parameter(name, TypeDesc::TypePoint, &f);
563 }
564
565 void OSLCompiler::parameter_normal(const char *name, float3 f)
566 {
567         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
568         ss->Parameter(name, TypeDesc::TypeNormal, &f);
569 }
570
571 void OSLCompiler::parameter_vector(const char *name, float3 f)
572 {
573         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
574         ss->Parameter(name, TypeDesc::TypeVector, &f);
575 }
576
577 void OSLCompiler::parameter(const char *name, int f)
578 {
579         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
580         ss->Parameter(name, TypeDesc::TypeInt, &f);
581 }
582
583 void OSLCompiler::parameter(const char *name, const char *s)
584 {
585         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
586         ss->Parameter(name, TypeDesc::TypeString, &s);
587 }
588
589 void OSLCompiler::parameter(const char *name, ustring s)
590 {
591         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
592         const char *str = s.c_str();
593         ss->Parameter(name, TypeDesc::TypeString, &str);
594 }
595
596 void OSLCompiler::parameter(const char *name, const Transform& tfm)
597 {
598         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
599         ss->Parameter(name, TypeDesc::TypeMatrix, (float*)&tfm);
600 }
601
602 void OSLCompiler::parameter_array(const char *name, const float f[], int arraylen)
603 {
604         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
605         TypeDesc type = TypeDesc::TypeFloat;
606         type.arraylen = arraylen;
607         ss->Parameter(name, type, f);
608 }
609
610 void OSLCompiler::parameter_color_array(const char *name, const float f[][3], int arraylen)
611 {
612         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
613         TypeDesc type = TypeDesc::TypeColor;
614         type.arraylen = arraylen;
615         ss->Parameter(name, type, f);
616 }
617
618 void OSLCompiler::parameter_vector_array(const char *name, const float f[][3], int arraylen)
619 {
620         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
621         TypeDesc type = TypeDesc::TypeVector;
622         type.arraylen = arraylen;
623         ss->Parameter(name, type, f);
624 }
625
626 void OSLCompiler::parameter_normal_array(const char *name, const float f[][3], int arraylen)
627 {
628         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
629         TypeDesc type = TypeDesc::TypeNormal;
630         type.arraylen = arraylen;
631         ss->Parameter(name, type, f);
632 }
633
634 void OSLCompiler::parameter_point_array(const char *name, const float f[][3], int arraylen)
635 {
636         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
637         TypeDesc type = TypeDesc::TypePoint;
638         type.arraylen = arraylen;
639         ss->Parameter(name, type, f);
640 }
641
642 void OSLCompiler::parameter_array(const char *name, const int f[], int arraylen)
643 {
644         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
645         TypeDesc type = TypeDesc::TypeInt;
646         type.arraylen = arraylen;
647         ss->Parameter(name, type, f);
648 }
649
650 void OSLCompiler::parameter_array(const char *name, const char * const s[], int arraylen)
651 {
652         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
653         TypeDesc type = TypeDesc::TypeString;
654         type.arraylen = arraylen;
655         ss->Parameter(name, type, s);
656 }
657
658 void OSLCompiler::parameter_array(const char *name, const Transform tfm[], int arraylen)
659 {
660         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
661         TypeDesc type = TypeDesc::TypeMatrix;
662         type.arraylen = arraylen;
663         ss->Parameter(name, type, (const float *)tfm);
664 }
665
666 void OSLCompiler::find_dependencies(set<ShaderNode*>& dependencies, ShaderInput *input)
667 {
668         ShaderNode *node = (input->link)? input->link->parent: NULL;
669
670         if(node) {
671                 foreach(ShaderInput *in, node->inputs)
672                         if(!node_skip_input(node, in))
673                                 find_dependencies(dependencies, in);
674
675                 dependencies.insert(node);
676         }
677 }
678
679 void OSLCompiler::generate_nodes(const set<ShaderNode*>& nodes)
680 {
681         set<ShaderNode*> done;
682         bool nodes_done;
683
684         do {
685                 nodes_done = true;
686
687                 foreach(ShaderNode *node, nodes) {
688                         if(done.find(node) == done.end()) {
689                                 bool inputs_done = true;
690
691                                 foreach(ShaderInput *input, node->inputs)
692                                         if(!node_skip_input(node, input))
693                                                 if(input->link && done.find(input->link->parent) == done.end())
694                                                         inputs_done = false;
695
696                                 if(inputs_done) {
697                                         node->compile(*this);
698                                         done.insert(node);
699
700                                         if(node->has_surface_emission())
701                                                 current_shader->has_surface_emission = true;
702                                         if(node->has_surface_transparent())
703                                                 current_shader->has_surface_transparent = true;
704                                         if(node->has_surface_bssrdf())
705                                                 current_shader->has_surface_bssrdf = true;
706                                 }
707                                 else
708                                         nodes_done = false;
709                         }
710                 }
711         } while(!nodes_done);
712 }
713
714 void OSLCompiler::compile_type(Shader *shader, ShaderGraph *graph, ShaderType type)
715 {
716         OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
717
718         current_type = type;
719
720         ss->ShaderGroupBegin();
721
722         ShaderNode *output = graph->output();
723         set<ShaderNode*> dependencies;
724
725         if(type == SHADER_TYPE_SURFACE) {
726                 /* generate surface shader */
727                 find_dependencies(dependencies, output->input("Surface"));
728                 generate_nodes(dependencies);
729                 output->compile(*this);
730         }
731         else if(type == SHADER_TYPE_VOLUME) {
732                 /* generate volume shader */
733                 find_dependencies(dependencies, output->input("Volume"));
734                 generate_nodes(dependencies);
735                 output->compile(*this);
736         }
737         else if(type == SHADER_TYPE_DISPLACEMENT) {
738                 /* generate displacement shader */
739                 find_dependencies(dependencies, output->input("Displacement"));
740                 generate_nodes(dependencies);
741                 output->compile(*this);
742         }
743         else
744                 assert(0);
745
746         ss->ShaderGroupEnd();
747 }
748
749 void OSLCompiler::compile(OSLGlobals *og, Shader *shader)
750 {
751         if(shader->need_update) {
752                 OSL::ShadingSystem *ss = (OSL::ShadingSystem*)shadingsys;
753                 ShaderGraph *graph = shader->graph;
754                 ShaderNode *output = (graph)? graph->output(): NULL;
755
756                 /* copy graph for shader with bump mapping */
757                 if(output->input("Surface")->link && output->input("Displacement")->link)
758                         if(!shader->graph_bump)
759                                 shader->graph_bump = shader->graph->copy();
760
761                 /* finalize */
762                 shader->graph->finalize(false, true);
763                 if(shader->graph_bump)
764                         shader->graph_bump->finalize(true, true);
765
766                 current_shader = shader;
767
768                 shader->has_surface = false;
769                 shader->has_surface_emission = false;
770                 shader->has_surface_transparent = false;
771                 shader->has_surface_bssrdf = false;
772                 shader->has_volume = false;
773                 shader->has_displacement = false;
774
775                 /* generate surface shader */
776                 if(shader->used && graph && output->input("Surface")->link) {
777                         compile_type(shader, shader->graph, SHADER_TYPE_SURFACE);
778                         shader->osl_surface_ref = ss->state();
779
780                         if(shader->graph_bump) {
781                                 ss->clear_state();
782                                 compile_type(shader, shader->graph_bump, SHADER_TYPE_SURFACE);
783                         }
784
785                         shader->osl_surface_bump_ref = ss->state();
786                         ss->clear_state();
787
788                         shader->has_surface = true;
789                 }
790                 else {
791                         shader->osl_surface_ref = OSL::ShadingAttribStateRef();
792                         shader->osl_surface_bump_ref = OSL::ShadingAttribStateRef();
793                 }
794
795                 /* generate volume shader */
796                 if(shader->used && graph && output->input("Volume")->link) {
797                         compile_type(shader, shader->graph, SHADER_TYPE_VOLUME);
798                         shader->has_volume = true;
799
800                         shader->osl_volume_ref = ss->state();
801                         ss->clear_state();
802                 }
803                 else
804                         shader->osl_volume_ref = OSL::ShadingAttribStateRef();
805
806                 /* generate displacement shader */
807                 if(shader->used && graph && output->input("Displacement")->link) {
808                         compile_type(shader, shader->graph, SHADER_TYPE_DISPLACEMENT);
809                         shader->has_displacement = true;
810                         shader->osl_displacement_ref = ss->state();
811                         ss->clear_state();
812                 }
813                 else
814                         shader->osl_displacement_ref = OSL::ShadingAttribStateRef();
815         }
816
817         /* push state to array for lookup */
818         og->surface_state.push_back(shader->osl_surface_ref);
819         og->surface_state.push_back(shader->osl_surface_bump_ref);
820
821         og->volume_state.push_back(shader->osl_volume_ref);
822         og->volume_state.push_back(shader->osl_volume_ref);
823
824         og->displacement_state.push_back(shader->osl_displacement_ref);
825         og->displacement_state.push_back(shader->osl_displacement_ref);
826 }
827
828 #else
829
830 void OSLCompiler::add(ShaderNode *node, const char *name, bool isfilepath)
831 {
832 }
833
834 void OSLCompiler::parameter(const char *name, float f)
835 {
836 }
837
838 void OSLCompiler::parameter_color(const char *name, float3 f)
839 {
840 }
841
842 void OSLCompiler::parameter_vector(const char *name, float3 f)
843 {
844 }
845
846 void OSLCompiler::parameter_point(const char *name, float3 f)
847 {
848 }
849
850 void OSLCompiler::parameter_normal(const char *name, float3 f)
851 {
852 }
853
854 void OSLCompiler::parameter(const char *name, int f)
855 {
856 }
857
858 void OSLCompiler::parameter(const char *name, const char *s)
859 {
860 }
861
862 void OSLCompiler::parameter(const char *name, ustring s)
863 {
864 }
865
866 void OSLCompiler::parameter(const char *name, const Transform& tfm)
867 {
868 }
869
870 void OSLCompiler::parameter_array(const char *name, const float f[], int arraylen)
871 {
872 }
873
874 void OSLCompiler::parameter_color_array(const char *name, const float f[][3], int arraylen)
875 {
876 }
877
878 void OSLCompiler::parameter_vector_array(const char *name, const float f[][3], int arraylen)
879 {
880 }
881
882 void OSLCompiler::parameter_normal_array(const char *name, const float f[][3], int arraylen)
883 {
884 }
885
886 void OSLCompiler::parameter_point_array(const char *name, const float f[][3], int arraylen)
887 {
888 }
889
890 void OSLCompiler::parameter_array(const char *name, const int f[], int arraylen)
891 {
892 }
893
894 void OSLCompiler::parameter_array(const char *name, const char * const s[], int arraylen)
895 {
896 }
897
898 void OSLCompiler::parameter_array(const char *name, const Transform tfm[], int arraylen)
899 {
900 }
901
902 #endif /* WITH_OSL */
903
904 CCL_NAMESPACE_END
905