Code refactor: add ProjectionTransform separate from regular Transform.
[blender-staging.git] / intern / cycles / kernel / osl / osl_services.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /* TODO(sergey): There is a bit of headers dependency hell going on
18  * here, so for now we just put here. In the future it might be better
19  * to have dedicated file for such tweaks.
20  */
21 #if (defined(__GNUC__) && !defined(__clang__)) && defined(NDEBUG)
22 #  pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
23 #  pragma GCC diagnostic ignored "-Wuninitialized"
24 #endif
25
26 #include <string.h>
27
28 #include "render/mesh.h"
29 #include "render/object.h"
30 #include "render/scene.h"
31
32 #include "kernel/osl/osl_closures.h"
33 #include "kernel/osl/osl_globals.h"
34 #include "kernel/osl/osl_services.h"
35 #include "kernel/osl/osl_shader.h"
36
37 #include "util/util_foreach.h"
38 #include "util/util_logging.h"
39 #include "util/util_string.h"
40
41 #include "kernel/kernel_compat_cpu.h"
42 #include "kernel/split/kernel_split_data_types.h"
43 #include "kernel/kernel_globals.h"
44 #include "kernel/kernel_random.h"
45 #include "kernel/kernel_projection.h"
46 #include "kernel/kernel_differential.h"
47 #include "kernel/kernel_montecarlo.h"
48 #include "kernel/kernel_camera.h"
49 #include "kernel/kernels/cpu/kernel_cpu_image.h"
50 #include "kernel/geom/geom.h"
51 #include "kernel/bvh/bvh.h"
52
53 #include "kernel/kernel_projection.h"
54 #include "kernel/kernel_accumulate.h"
55 #include "kernel/kernel_shader.h"
56
57 #ifdef WITH_PTEX
58 #  include <Ptexture.h>
59 #endif
60
61 CCL_NAMESPACE_BEGIN
62
63 /* RenderServices implementation */
64
65 static void copy_matrix(OSL::Matrix44& m, const Transform& tfm)
66 {
67         // TODO: remember when making affine
68         Transform t = transform_transpose(tfm);
69         memcpy(&m, &t, sizeof(m));
70 }
71
72 static void copy_matrix(OSL::Matrix44& m, const ProjectionTransform& tfm)
73 {
74         ProjectionTransform t = projection_transpose(tfm);
75         memcpy(&m, &t, sizeof(m));
76 }
77
78 /* static ustrings */
79 ustring OSLRenderServices::u_distance("distance");
80 ustring OSLRenderServices::u_index("index");
81 ustring OSLRenderServices::u_world("world");
82 ustring OSLRenderServices::u_camera("camera");
83 ustring OSLRenderServices::u_screen("screen");
84 ustring OSLRenderServices::u_raster("raster");
85 ustring OSLRenderServices::u_ndc("NDC");
86 ustring OSLRenderServices::u_object_location("object:location");
87 ustring OSLRenderServices::u_object_index("object:index");
88 ustring OSLRenderServices::u_geom_dupli_generated("geom:dupli_generated");
89 ustring OSLRenderServices::u_geom_dupli_uv("geom:dupli_uv");
90 ustring OSLRenderServices::u_material_index("material:index");
91 ustring OSLRenderServices::u_object_random("object:random");
92 ustring OSLRenderServices::u_particle_index("particle:index");
93 ustring OSLRenderServices::u_particle_random("particle:random");
94 ustring OSLRenderServices::u_particle_age("particle:age");
95 ustring OSLRenderServices::u_particle_lifetime("particle:lifetime");
96 ustring OSLRenderServices::u_particle_location("particle:location");
97 ustring OSLRenderServices::u_particle_rotation("particle:rotation");
98 ustring OSLRenderServices::u_particle_size("particle:size");
99 ustring OSLRenderServices::u_particle_velocity("particle:velocity");
100 ustring OSLRenderServices::u_particle_angular_velocity("particle:angular_velocity");
101 ustring OSLRenderServices::u_geom_numpolyvertices("geom:numpolyvertices");
102 ustring OSLRenderServices::u_geom_trianglevertices("geom:trianglevertices");
103 ustring OSLRenderServices::u_geom_polyvertices("geom:polyvertices");
104 ustring OSLRenderServices::u_geom_name("geom:name");
105 ustring OSLRenderServices::u_geom_undisplaced("geom:undisplaced");
106 ustring OSLRenderServices::u_is_smooth("geom:is_smooth");
107 ustring OSLRenderServices::u_is_curve("geom:is_curve");
108 ustring OSLRenderServices::u_curve_thickness("geom:curve_thickness");
109 ustring OSLRenderServices::u_curve_tangent_normal("geom:curve_tangent_normal");
110 ustring OSLRenderServices::u_curve_random("geom:curve_random");
111 ustring OSLRenderServices::u_path_ray_length("path:ray_length");
112 ustring OSLRenderServices::u_path_ray_depth("path:ray_depth");
113 ustring OSLRenderServices::u_path_diffuse_depth("path:diffuse_depth");
114 ustring OSLRenderServices::u_path_glossy_depth("path:glossy_depth");
115 ustring OSLRenderServices::u_path_transparent_depth("path:transparent_depth");
116 ustring OSLRenderServices::u_path_transmission_depth("path:transmission_depth");
117 ustring OSLRenderServices::u_trace("trace");
118 ustring OSLRenderServices::u_hit("hit");
119 ustring OSLRenderServices::u_hitdist("hitdist");
120 ustring OSLRenderServices::u_N("N");
121 ustring OSLRenderServices::u_Ng("Ng");
122 ustring OSLRenderServices::u_P("P");
123 ustring OSLRenderServices::u_I("I");
124 ustring OSLRenderServices::u_u("u");
125 ustring OSLRenderServices::u_v("v");
126 ustring OSLRenderServices::u_empty;
127 ustring OSLRenderServices::u_at_bevel("@bevel");
128
129 OSLRenderServices::OSLRenderServices()
130 {
131         kernel_globals = NULL;
132         osl_ts = NULL;
133
134 #ifdef WITH_PTEX
135         size_t maxmem = 16384 * 1024;
136         ptex_cache = PtexCache::create(0, maxmem);
137 #endif
138 }
139
140 OSLRenderServices::~OSLRenderServices()
141 {
142         if(osl_ts) {
143                 VLOG(2) << "OSL texture system stats:\n"
144                         << osl_ts->getstats();
145         }
146 #ifdef WITH_PTEX
147         ptex_cache->release();
148 #endif
149 }
150
151 void OSLRenderServices::thread_init(KernelGlobals *kernel_globals_, OSL::TextureSystem *osl_ts_)
152 {
153         kernel_globals = kernel_globals_;
154         osl_ts = osl_ts_;
155 }
156
157 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform, float time)
158 {
159         /* this is only used for shader and object space, we don't really have
160          * a concept of shader space, so we just use object space for both. */
161         if(xform) {
162                 const ShaderData *sd = (const ShaderData *)xform;
163                 KernelGlobals *kg = sd->osl_globals;
164                 int object = sd->object;
165
166                 if(object != OBJECT_NONE) {
167 #ifdef __OBJECT_MOTION__
168                         Transform tfm;
169
170                         if(time == sd->time)
171                                 tfm = sd->ob_tfm;
172                         else
173                                 tfm = object_fetch_transform_motion_test(kg, object, time, NULL);
174 #else
175                         Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
176 #endif
177                         copy_matrix(result, tfm);
178
179                         return true;
180                 }
181                 else if(sd->type == PRIMITIVE_LAMP) {
182                         copy_matrix(result, sd->ob_tfm);
183
184                         return true;
185                 }
186         }
187
188         return false;
189 }
190
191 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform, float time)
192 {
193         /* this is only used for shader and object space, we don't really have
194          * a concept of shader space, so we just use object space for both. */
195         if(xform) {
196                 const ShaderData *sd = (const ShaderData *)xform;
197                 KernelGlobals *kg = sd->osl_globals;
198                 int object = sd->object;
199
200                 if(object != OBJECT_NONE) {
201 #ifdef __OBJECT_MOTION__
202                         Transform itfm;
203
204                         if(time == sd->time)
205                                 itfm = sd->ob_itfm;
206                         else
207                                 object_fetch_transform_motion_test(kg, object, time, &itfm);
208 #else
209                         Transform itfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
210 #endif
211                         copy_matrix(result, itfm);
212
213                         return true;
214                 }
215                 else if(sd->type == PRIMITIVE_LAMP) {
216                         copy_matrix(result, sd->ob_itfm);
217
218                         return true;
219                 }
220         }
221
222         return false;
223 }
224
225 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from, float time)
226 {
227         KernelGlobals *kg = kernel_globals;
228
229         if(from == u_ndc) {
230                 copy_matrix(result, kernel_data.cam.ndctoworld);
231                 return true;
232         }
233         else if(from == u_raster) {
234                 copy_matrix(result, kernel_data.cam.rastertoworld);
235                 return true;
236         }
237         else if(from == u_screen) {
238                 copy_matrix(result, kernel_data.cam.screentoworld);
239                 return true;
240         }
241         else if(from == u_camera) {
242                 copy_matrix(result, kernel_data.cam.cameratoworld);
243                 return true;
244         }
245         else if(from == u_world) {
246                 result.makeIdentity();
247                 return true;
248         }
249
250         return false;
251 }
252
253 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring to, float time)
254 {
255         KernelGlobals *kg = kernel_globals;
256
257         if(to == u_ndc) {
258                 copy_matrix(result, kernel_data.cam.worldtondc);
259                 return true;
260         }
261         else if(to == u_raster) {
262                 copy_matrix(result, kernel_data.cam.worldtoraster);
263                 return true;
264         }
265         else if(to == u_screen) {
266                 copy_matrix(result, kernel_data.cam.worldtoscreen);
267                 return true;
268         }
269         else if(to == u_camera) {
270                 copy_matrix(result, kernel_data.cam.worldtocamera);
271                 return true;
272         }
273         else if(to == u_world) {
274                 result.makeIdentity();
275                 return true;
276         }
277
278         return false;
279 }
280
281 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform)
282 {
283         /* this is only used for shader and object space, we don't really have
284          * a concept of shader space, so we just use object space for both. */
285         if(xform) {
286                 const ShaderData *sd = (const ShaderData *)xform;
287                 int object = sd->object;
288
289                 if(object != OBJECT_NONE) {
290 #ifdef __OBJECT_MOTION__
291                         Transform tfm = sd->ob_tfm;
292 #else
293                         KernelGlobals *kg = sd->osl_globals;
294                         Transform tfm = object_fetch_transform(kg, object, OBJECT_TRANSFORM);
295 #endif
296                         copy_matrix(result, tfm);
297
298                         return true;
299                 }
300                 else if(sd->type == PRIMITIVE_LAMP) {
301                         copy_matrix(result, sd->ob_tfm);
302
303                         return true;
304                 }
305         }
306
307         return false;
308 }
309
310 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, OSL::TransformationPtr xform)
311 {
312         /* this is only used for shader and object space, we don't really have
313          * a concept of shader space, so we just use object space for both. */
314         if(xform) {
315                 const ShaderData *sd = (const ShaderData *)xform;
316                 int object = sd->object;
317
318                 if(object != OBJECT_NONE) {
319 #ifdef __OBJECT_MOTION__
320                         Transform tfm = sd->ob_itfm;
321 #else
322                         KernelGlobals *kg = sd->osl_globals;
323                         Transform tfm = object_fetch_transform(kg, object, OBJECT_INVERSE_TRANSFORM);
324 #endif
325                         copy_matrix(result, tfm);
326
327                         return true;
328                 }
329                 else if(sd->type == PRIMITIVE_LAMP) {
330                         copy_matrix(result, sd->ob_itfm);
331
332                         return true;
333                 }
334         }
335
336         return false;
337 }
338
339 bool OSLRenderServices::get_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring from)
340 {
341         KernelGlobals *kg = kernel_globals;
342
343         if(from == u_ndc) {
344                 copy_matrix(result, kernel_data.cam.ndctoworld);
345                 return true;
346         }
347         else if(from == u_raster) {
348                 copy_matrix(result, kernel_data.cam.rastertoworld);
349                 return true;
350         }
351         else if(from == u_screen) {
352                 copy_matrix(result, kernel_data.cam.screentoworld);
353                 return true;
354         }
355         else if(from == u_camera) {
356                 copy_matrix(result, kernel_data.cam.cameratoworld);
357                 return true;
358         }
359
360         return false;
361 }
362
363 bool OSLRenderServices::get_inverse_matrix(OSL::ShaderGlobals *sg, OSL::Matrix44 &result, ustring to)
364 {
365         KernelGlobals *kg = kernel_globals;
366         
367         if(to == u_ndc) {
368                 copy_matrix(result, kernel_data.cam.worldtondc);
369                 return true;
370         }
371         else if(to == u_raster) {
372                 copy_matrix(result, kernel_data.cam.worldtoraster);
373                 return true;
374         }
375         else if(to == u_screen) {
376                 copy_matrix(result, kernel_data.cam.worldtoscreen);
377                 return true;
378         }
379         else if(to == u_camera) {
380                 copy_matrix(result, kernel_data.cam.worldtocamera);
381                 return true;
382         }
383         
384         return false;
385 }
386
387 bool OSLRenderServices::get_array_attribute(OSL::ShaderGlobals *sg, bool derivatives, 
388                                             ustring object, TypeDesc type, ustring name,
389                                             int index, void *val)
390 {
391         return false;
392 }
393
394 static bool set_attribute_float3(float3 f[3], TypeDesc type, bool derivatives, void *val)
395 {
396         if(type == TypeDesc::TypePoint || type == TypeDesc::TypeVector ||
397            type == TypeDesc::TypeNormal || type == TypeDesc::TypeColor)
398         {
399                 float *fval = (float *)val;
400
401                 fval[0] = f[0].x;
402                 fval[1] = f[0].y;
403                 fval[2] = f[0].z;
404
405                 if(derivatives) {
406                         fval[3] = f[1].x;
407                         fval[4] = f[1].y;
408                         fval[5] = f[1].z;
409
410                         fval[6] = f[2].x;
411                         fval[7] = f[2].y;
412                         fval[8] = f[2].z;
413                 }
414
415                 return true;
416         }
417         else if(type == TypeDesc::TypeFloat) {
418                 float *fval = (float *)val;
419                 fval[0] = average(f[0]);
420
421                 if(derivatives) {
422                         fval[1] = average(f[1]);
423                         fval[2] = average(f[2]);
424                 }
425
426                 return true;
427         }
428
429         return false;
430 }
431
432 static bool set_attribute_float3(float3 f, TypeDesc type, bool derivatives, void *val)
433 {
434         float3 fv[3];
435
436         fv[0] = f;
437         fv[1] = make_float3(0.0f, 0.0f, 0.0f);
438         fv[2] = make_float3(0.0f, 0.0f, 0.0f);
439
440         return set_attribute_float3(fv, type, derivatives, val);
441 }
442
443 static bool set_attribute_float(float f[3], TypeDesc type, bool derivatives, void *val)
444 {
445         if(type == TypeDesc::TypePoint || type == TypeDesc::TypeVector ||
446            type == TypeDesc::TypeNormal || type == TypeDesc::TypeColor)
447         {
448                 float *fval = (float *)val;
449                 fval[0] = f[0];
450                 fval[1] = f[1];
451                 fval[2] = f[2];
452
453                 if(derivatives) {
454                         fval[3] = f[1];
455                         fval[4] = f[1];
456                         fval[5] = f[1];
457
458                         fval[6] = f[2];
459                         fval[7] = f[2];
460                         fval[8] = f[2];
461                 }
462
463                 return true;
464         }
465         else if(type == TypeDesc::TypeFloat) {
466                 float *fval = (float *)val;
467                 fval[0] = f[0];
468
469                 if(derivatives) {
470                         fval[1] = f[1];
471                         fval[2] = f[2];
472                 }
473
474                 return true;
475         }
476
477         return false;
478 }
479
480 static bool set_attribute_float(float f, TypeDesc type, bool derivatives, void *val)
481 {
482         float fv[3];
483
484         fv[0] = f;
485         fv[1] = 0.0f;
486         fv[2] = 0.0f;
487
488         return set_attribute_float(fv, type, derivatives, val);
489 }
490
491 static bool set_attribute_int(int i, TypeDesc type, bool derivatives, void *val)
492 {
493         if(type.basetype == TypeDesc::INT && type.aggregate == TypeDesc::SCALAR && type.arraylen == 0) {
494                 int *ival = (int *)val;
495                 ival[0] = i;
496
497                 if(derivatives) {
498                         ival[1] = 0;
499                         ival[2] = 0;
500                 }
501
502                 return true;
503         }
504
505         return false;
506 }
507
508 static bool set_attribute_string(ustring str, TypeDesc type, bool derivatives, void *val)
509 {
510         if(type.basetype == TypeDesc::STRING && type.aggregate == TypeDesc::SCALAR && type.arraylen == 0) {
511                 ustring *sval = (ustring *)val;
512                 sval[0] = str;
513
514                 if(derivatives) {
515                         sval[1] = OSLRenderServices::u_empty;
516                         sval[2] = OSLRenderServices::u_empty;
517                 }
518
519                 return true;
520         }
521
522         return false;
523 }
524
525 static bool set_attribute_float3_3(float3 P[3], TypeDesc type, bool derivatives, void *val)
526 {
527         if(type.vecsemantics == TypeDesc::POINT && type.arraylen >= 3) {
528                 float *fval = (float *)val;
529
530                 fval[0] = P[0].x;
531                 fval[1] = P[0].y;
532                 fval[2] = P[0].z;
533
534                 fval[3] = P[1].x;
535                 fval[4] = P[1].y;
536                 fval[5] = P[1].z;
537
538                 fval[6] = P[2].x;
539                 fval[7] = P[2].y;
540                 fval[8] = P[2].z;
541
542                 if(type.arraylen > 3)
543                         memset(fval + 3*3, 0, sizeof(float)*3*(type.arraylen - 3));
544                 if(derivatives)
545                         memset(fval + type.arraylen*3, 0, sizeof(float)*2*3*type.arraylen);
546
547                 return true;
548         }
549
550         return false;
551 }
552
553 static bool set_attribute_matrix(const Transform& tfm, TypeDesc type, void *val)
554 {
555         if(type == TypeDesc::TypeMatrix) {
556                 Transform transpose = transform_transpose(tfm);
557                 memcpy(val, &transpose, sizeof(Transform));
558                 return true;
559         }
560
561         return false;
562 }
563
564 static bool get_mesh_element_attribute(KernelGlobals *kg, const ShaderData *sd, const OSLGlobals::Attribute& attr,
565                                const TypeDesc& type, bool derivatives, void *val)
566 {
567         if(attr.type == TypeDesc::TypePoint || attr.type == TypeDesc::TypeVector ||
568            attr.type == TypeDesc::TypeNormal || attr.type == TypeDesc::TypeColor)
569         {
570                 float3 fval[3];
571                 fval[0] = primitive_attribute_float3(kg, sd, attr.desc,
572                                                      (derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
573                 return set_attribute_float3(fval, type, derivatives, val);
574         }
575         else if(attr.type == TypeDesc::TypeFloat) {
576                 float fval[3];
577                 fval[0] = primitive_attribute_float(kg, sd, attr.desc,
578                                                     (derivatives) ? &fval[1] : NULL, (derivatives) ? &fval[2] : NULL);
579                 return set_attribute_float(fval, type, derivatives, val);
580         }
581         else {
582                 return false;
583         }
584 }
585
586 static bool get_mesh_attribute(KernelGlobals *kg, const ShaderData *sd, const OSLGlobals::Attribute& attr,
587                                const TypeDesc& type, bool derivatives, void *val)
588 {
589         if(attr.type == TypeDesc::TypeMatrix) {
590                 Transform tfm = primitive_attribute_matrix(kg, sd, attr.desc);
591                 return set_attribute_matrix(tfm, type, val);
592         }
593         else {
594                 return false;
595         }
596 }
597
598 static void get_object_attribute(const OSLGlobals::Attribute& attr, bool derivatives, void *val)
599 {
600         size_t datasize = attr.value.datasize();
601
602         memcpy(val, attr.value.data(), datasize);
603         if(derivatives)
604                 memset((char *)val + datasize, 0, datasize * 2);
605 }
606
607 bool OSLRenderServices::get_object_standard_attribute(KernelGlobals *kg, ShaderData *sd, ustring name,
608                                                       TypeDesc type, bool derivatives, void *val)
609 {
610         /* todo: turn this into hash table? */
611
612         /* Object Attributes */
613         if(name == u_object_location) {
614                 float3 f = object_location(kg, sd);
615                 return set_attribute_float3(f, type, derivatives, val);
616         }
617         else if(name == u_object_index) {
618                 float f = object_pass_id(kg, sd->object);
619                 return set_attribute_float(f, type, derivatives, val);
620         }
621         else if(name == u_geom_dupli_generated) {
622                 float3 f = object_dupli_generated(kg, sd->object);
623                 return set_attribute_float3(f, type, derivatives, val);
624         }
625         else if(name == u_geom_dupli_uv) {
626                 float3 f = object_dupli_uv(kg, sd->object);
627                 return set_attribute_float3(f, type, derivatives, val);
628         }
629         else if(name == u_material_index) {
630                 float f = shader_pass_id(kg, sd);
631                 return set_attribute_float(f, type, derivatives, val);
632         }
633         else if(name == u_object_random) {
634                 float f = object_random_number(kg, sd->object);
635                 return set_attribute_float(f, type, derivatives, val);
636         }
637
638         /* Particle Attributes */
639         else if(name == u_particle_index) {
640                 int particle_id = object_particle_id(kg, sd->object);
641                 float f = particle_index(kg, particle_id);
642                 return set_attribute_float(f, type, derivatives, val);
643         }
644         else if(name == u_particle_random) {
645                 int particle_id = object_particle_id(kg, sd->object);
646                 float f = hash_int_01(particle_index(kg, particle_id));
647                 return set_attribute_float(f, type, derivatives, val);
648         }
649
650         else if(name == u_particle_age) {
651                 int particle_id = object_particle_id(kg, sd->object);
652                 float f = particle_age(kg, particle_id);
653                 return set_attribute_float(f, type, derivatives, val);
654         }
655         else if(name == u_particle_lifetime) {
656                 int particle_id = object_particle_id(kg, sd->object);
657                 float f = particle_lifetime(kg, particle_id);
658                 return set_attribute_float(f, type, derivatives, val);
659         }
660         else if(name == u_particle_location) {
661                 int particle_id = object_particle_id(kg, sd->object);
662                 float3 f = particle_location(kg, particle_id);
663                 return set_attribute_float3(f, type, derivatives, val);
664         }
665 #if 0   /* unsupported */
666         else if(name == u_particle_rotation) {
667                 int particle_id = object_particle_id(kg, sd->object);
668                 float4 f = particle_rotation(kg, particle_id);
669                 return set_attribute_float4(f, type, derivatives, val);
670         }
671 #endif
672         else if(name == u_particle_size) {
673                 int particle_id = object_particle_id(kg, sd->object);
674                 float f = particle_size(kg, particle_id);
675                 return set_attribute_float(f, type, derivatives, val);
676         }
677         else if(name == u_particle_velocity) {
678                 int particle_id = object_particle_id(kg, sd->object);
679                 float3 f = particle_velocity(kg, particle_id);
680                 return set_attribute_float3(f, type, derivatives, val);
681         }
682         else if(name == u_particle_angular_velocity) {
683                 int particle_id = object_particle_id(kg, sd->object);
684                 float3 f = particle_angular_velocity(kg, particle_id);
685                 return set_attribute_float3(f, type, derivatives, val);
686         }
687         
688         /* Geometry Attributes */
689         else if(name == u_geom_numpolyvertices) {
690                 return set_attribute_int(3, type, derivatives, val);
691         }
692         else if((name == u_geom_trianglevertices || name == u_geom_polyvertices)
693                      && sd->type & PRIMITIVE_ALL_TRIANGLE)
694         {
695                 float3 P[3];
696
697                 if(sd->type & PRIMITIVE_TRIANGLE)
698                         triangle_vertices(kg, sd->prim, P);
699                 else
700                         motion_triangle_vertices(kg, sd->object, sd->prim, sd->time, P);
701
702                 if(!(sd->object_flag & SD_OBJECT_TRANSFORM_APPLIED)) {
703                         object_position_transform(kg, sd, &P[0]);
704                         object_position_transform(kg, sd, &P[1]);
705                         object_position_transform(kg, sd, &P[2]);
706                 }
707
708                 return set_attribute_float3_3(P, type, derivatives, val);
709         }
710         else if(name == u_geom_name) {
711                 ustring object_name = kg->osl->object_names[sd->object];
712                 return set_attribute_string(object_name, type, derivatives, val);
713         }
714         else if(name == u_is_smooth) {
715                 float f = ((sd->shader & SHADER_SMOOTH_NORMAL) != 0);
716                 return set_attribute_float(f, type, derivatives, val);
717         }
718         /* Hair Attributes */
719         else if(name == u_is_curve) {
720                 float f = (sd->type & PRIMITIVE_ALL_CURVE) != 0;
721                 return set_attribute_float(f, type, derivatives, val);
722         }
723         else if(name == u_curve_thickness) {
724                 float f = curve_thickness(kg, sd);
725                 return set_attribute_float(f, type, derivatives, val);
726         }
727         else if(name == u_curve_tangent_normal) {
728                 float3 f = curve_tangent_normal(kg, sd);
729                 return set_attribute_float3(f, type, derivatives, val);
730         }
731         else
732                 return false;
733 }
734
735 bool OSLRenderServices::get_background_attribute(KernelGlobals *kg, ShaderData *sd, ustring name,
736                                                  TypeDesc type, bool derivatives, void *val)
737 {
738         if(name == u_path_ray_length) {
739                 /* Ray Length */
740                 float f = sd->ray_length;
741                 return set_attribute_float(f, type, derivatives, val);
742         }
743         else if(name == u_path_ray_depth) {
744                 /* Ray Depth */
745                 PathState *state = sd->osl_path_state;
746                 int f = state->bounce;
747                 return set_attribute_int(f, type, derivatives, val);
748         }
749         else if(name == u_path_diffuse_depth) {
750                 /* Diffuse Ray Depth */
751                 PathState *state = sd->osl_path_state;
752                 int f = state->diffuse_bounce;
753                 return set_attribute_int(f, type, derivatives, val);
754         }
755         else if(name == u_path_glossy_depth) {
756                 /* Glossy Ray Depth */
757                 PathState *state = sd->osl_path_state;
758                 int f = state->glossy_bounce;
759                 return set_attribute_int(f, type, derivatives, val);
760         }
761         else if(name == u_path_transmission_depth) {
762                 /* Transmission Ray Depth */
763                 PathState *state = sd->osl_path_state;
764                 int f = state->transmission_bounce;
765                 return set_attribute_int(f, type, derivatives, val);
766         }
767         else if(name == u_path_transparent_depth) {
768                 /* Transparent Ray Depth */
769                 PathState *state = sd->osl_path_state;
770                 int f = state->transparent_bounce;
771                 return set_attribute_int(f, type, derivatives, val);
772         }
773         else if(name == u_path_transmission_depth) {
774                 /* Transmission Ray Depth */
775                 PathState *state = sd->osl_path_state;
776                 int f = state->transmission_bounce;
777                 return set_attribute_int(f, type, derivatives, val);
778         }
779         else if(name == u_ndc) {
780                 /* NDC coordinates with special exception for otho */
781                 OSLThreadData *tdata = kg->osl_tdata;
782                 OSL::ShaderGlobals *globals = &tdata->globals;
783                 float3 ndc[3];
784
785                 if((globals->raytype & PATH_RAY_CAMERA) && sd->object == OBJECT_NONE && kernel_data.cam.type == CAMERA_ORTHOGRAPHIC) {
786                         ndc[0] = camera_world_to_ndc(kg, sd, sd->ray_P);
787
788                         if(derivatives) {
789                                 ndc[1] = camera_world_to_ndc(kg, sd, sd->ray_P + sd->ray_dP.dx) - ndc[0];
790                                 ndc[2] = camera_world_to_ndc(kg, sd, sd->ray_P + sd->ray_dP.dy) - ndc[0];
791                         }
792                 }
793                 else {
794                         ndc[0] = camera_world_to_ndc(kg, sd, sd->P);
795
796                         if(derivatives) {
797                                 ndc[1] = camera_world_to_ndc(kg, sd, sd->P + sd->dP.dx) - ndc[0];
798                                 ndc[2] = camera_world_to_ndc(kg, sd, sd->P + sd->dP.dy) - ndc[0];
799                         }
800                 }
801
802                 return set_attribute_float3(ndc, type, derivatives, val);
803         }
804         else
805                 return false;
806 }
807
808 bool OSLRenderServices::get_attribute(OSL::ShaderGlobals *sg, bool derivatives, ustring object_name,
809                                       TypeDesc type, ustring name, void *val)
810 {
811         if(sg == NULL || sg->renderstate == NULL)
812                 return false;
813
814         ShaderData *sd = (ShaderData *)(sg->renderstate);
815         return get_attribute(sd, derivatives, object_name, type, name, val);
816 }
817
818 bool OSLRenderServices::get_attribute(ShaderData *sd, bool derivatives, ustring object_name,
819                                       TypeDesc type, ustring name, void *val)
820 {
821         KernelGlobals *kg = sd->osl_globals;
822         int prim_type = 0;
823         int object;
824
825         /* lookup of attribute on another object */
826         if(object_name != u_empty) {
827                 OSLGlobals::ObjectNameMap::iterator it = kg->osl->object_name_map.find(object_name);
828
829                 if(it == kg->osl->object_name_map.end())
830                         return false;
831
832                 object = it->second;
833         }
834         else {
835                 object = sd->object;
836                 prim_type = attribute_primitive_type(kg, sd);
837
838                 if(object == OBJECT_NONE)
839                         return get_background_attribute(kg, sd, name, type, derivatives, val);
840         }
841
842         /* find attribute on object */
843         object = object*ATTR_PRIM_TYPES + prim_type;
844         OSLGlobals::AttributeMap& attribute_map = kg->osl->attribute_map[object];
845         OSLGlobals::AttributeMap::iterator it = attribute_map.find(name);
846
847         if(it != attribute_map.end()) {
848                 const OSLGlobals::Attribute& attr = it->second;
849
850                 if(attr.desc.element != ATTR_ELEMENT_OBJECT) {
851                         /* triangle and vertex attributes */
852                         if(get_mesh_element_attribute(kg, sd, attr, type, derivatives, val))
853                                 return true;
854                         else
855                                 return get_mesh_attribute(kg, sd, attr, type, derivatives, val);
856                 }
857                 else {
858                         /* object attribute */
859                         get_object_attribute(attr, derivatives, val);
860                         return true;
861                 }
862         }
863         else {
864                 /* not found in attribute, check standard object info */
865                 bool is_std_object_attribute = get_object_standard_attribute(kg, sd, name, type, derivatives, val);
866
867                 if(is_std_object_attribute)
868                         return true;
869
870                 return get_background_attribute(kg, sd, name, type, derivatives, val);
871         }
872
873         return false;
874 }
875
876 bool OSLRenderServices::get_userdata(bool derivatives, ustring name, TypeDesc type, 
877                                      OSL::ShaderGlobals *sg, void *val)
878 {
879         return false; /* disabled by lockgeom */
880 }
881
882 bool OSLRenderServices::has_userdata(ustring name, TypeDesc type, OSL::ShaderGlobals *sg)
883 {
884         return false; /* never called by OSL */
885 }
886
887 bool OSLRenderServices::texture(ustring filename,
888                                 TextureHandle *texture_handle,
889                                 TexturePerthread *texture_thread_info,
890                                 TextureOpt &options,
891                                 OSL::ShaderGlobals *sg,
892                                 float s, float t,
893                                 float dsdx, float dtdx, float dsdy, float dtdy,
894                                 int nchannels,
895                                 float *result,
896                                 float *dresultds,
897                                 float *dresultdt)
898 {
899         OSL::TextureSystem *ts = osl_ts;
900         ShaderData *sd = (ShaderData *)(sg->renderstate);
901         KernelGlobals *kg = sd->osl_globals;
902
903         if(texture_thread_info == NULL) {
904                 OSLThreadData *tdata = kg->osl_tdata;
905                 texture_thread_info = tdata->oiio_thread_info;
906         }
907
908 #ifdef WITH_PTEX
909         /* todo: this is just a quick hack, only works with particular files and options */
910         if(string_endswith(filename.string(), ".ptx")) {
911                 float2 uv;
912                 int faceid;
913
914                 if(!primitive_ptex(kg, sd, &uv, &faceid))
915                         return false;
916
917                 float u = uv.x;
918                 float v = uv.y;
919                 float dudx = 0.0f;
920                 float dvdx = 0.0f;
921                 float dudy = 0.0f;
922                 float dvdy = 0.0f;
923
924                 Ptex::String error;
925                 PtexPtr<PtexTexture> r(ptex_cache->get(filename.c_str(), error));
926
927                 if(!r) {
928                         //std::cerr << error.c_str() << std::endl;
929                         return false;
930                 }
931
932                 bool mipmaplerp = false;
933                 float sharpness = 1.0f;
934                 PtexFilter::Options opts(PtexFilter::f_bicubic, mipmaplerp, sharpness);
935                 PtexPtr<PtexFilter> f(PtexFilter::getFilter(r, opts));
936
937                 f->eval(result, options.firstchannel, nchannels, faceid, u, v, dudx, dvdx, dudy, dvdy);
938
939                 for(int c = r->numChannels(); c < nchannels; c++)
940                         result[c] = result[0];
941
942                 return true;
943         }
944 #endif
945         bool status = false;
946
947         if(filename.length() && filename[0] == '@') {
948                 if(filename == u_at_bevel) {
949                         /* Bevel shader hack. */
950                         if(nchannels >= 3) {
951                                 PathState *state = sd->osl_path_state;
952                                 int num_samples = (int)s;
953                                 float radius = t;
954                                 float3 N = svm_bevel(kg, sd, state, radius, num_samples);
955                                 result[0] = N.x;
956                                 result[1] = N.y;
957                                 result[2] = N.z;
958                                 status = true;
959                         }
960                 }
961                 else {
962                         /* Packed texture. */
963                         int slot = atoi(filename.c_str() + 1);
964                         float4 rgba = kernel_tex_image_interp(kg, slot, s, 1.0f - t);
965
966                         result[0] = rgba[0];
967                         if(nchannels > 1)
968                                 result[1] = rgba[1];
969                         if(nchannels > 2)
970                                 result[2] = rgba[2];
971                         if(nchannels > 3)
972                                 result[3] = rgba[3];
973                         status = true;
974                 }
975         }
976         else {
977                 if(texture_handle != NULL) {
978                         status = ts->texture(texture_handle,
979                                              texture_thread_info,
980                                              options,
981                                              s, t,
982                                              dsdx, dtdx,
983                                              dsdy, dtdy,
984                                              nchannels,
985                                              result,
986                                              dresultds, dresultdt);
987                 }
988                 else {
989                         status = ts->texture(filename,
990                                              options,
991                                              s, t,
992                                              dsdx, dtdx,
993                                              dsdy, dtdy,
994                                              nchannels,
995                                              result,
996                                              dresultds, dresultdt);
997                 }
998         }
999
1000         if(!status) {
1001                 if(nchannels == 3 || nchannels == 4) {
1002                         result[0] = 1.0f;
1003                         result[1] = 0.0f;
1004                         result[2] = 1.0f;
1005
1006                         if(nchannels == 4)
1007                                 result[3] = 1.0f;
1008                 }
1009                 /* This might be slow, but prevents error messages leak and
1010                  * other nasty stuff happening.
1011                  */
1012                 string err = ts->geterror();
1013                 (void)err;
1014         }
1015
1016         return status;
1017 }
1018
1019 bool OSLRenderServices::texture3d(ustring filename,
1020                                   TextureHandle *texture_handle,
1021                                   TexturePerthread *texture_thread_info,
1022                                   TextureOpt &options,
1023                                   OSL::ShaderGlobals *sg,
1024                                   const OSL::Vec3 &P,
1025                                   const OSL::Vec3 &dPdx,
1026                                   const OSL::Vec3 &dPdy,
1027                                   const OSL::Vec3 &dPdz,
1028                                   int nchannels,
1029                                   float *result,
1030                                   float *dresultds,
1031                                   float *dresultdt,
1032                                   float *dresultdr)
1033 {
1034         OSL::TextureSystem *ts = osl_ts;
1035         ShaderData *sd = (ShaderData *)(sg->renderstate);
1036         KernelGlobals *kg = sd->osl_globals;
1037
1038         if(texture_thread_info == NULL) {
1039                 OSLThreadData *tdata = kg->osl_tdata;
1040                 texture_thread_info = tdata->oiio_thread_info;
1041         }
1042
1043         bool status;
1044         if(filename.length() && filename[0] == '@') {
1045                 int slot = atoi(filename.c_str() + 1);
1046                 float4 rgba = kernel_tex_image_interp_3d(kg, slot, P.x, P.y, P.z, INTERPOLATION_NONE);
1047
1048                 result[0] = rgba[0];
1049                 if(nchannels > 1)
1050                         result[1] = rgba[1];
1051                 if(nchannels > 2)
1052                         result[2] = rgba[2];
1053                 if(nchannels > 3)
1054                         result[3] = rgba[3];
1055                 status = true;
1056         }
1057         else {
1058                 if(texture_handle != NULL) {
1059                         status = ts->texture3d(texture_handle,
1060                                                texture_thread_info,
1061                                                options,
1062                                                P,
1063                                                dPdx, dPdy, dPdz,
1064                                                nchannels,
1065                                                result,
1066                                                dresultds, dresultdt, dresultdr);
1067                 }
1068                 else {
1069                         status = ts->texture3d(filename,
1070                                                options,
1071                                                P,
1072                                                dPdx, dPdy, dPdz,
1073                                                nchannels,
1074                                                result,
1075                                                dresultds, dresultdt, dresultdr);
1076                 }
1077         }
1078
1079         if(!status) {
1080                 if(nchannels == 3 || nchannels == 4) {
1081                         result[0] = 1.0f;
1082                         result[1] = 0.0f;
1083                         result[2] = 1.0f;
1084
1085                         if(nchannels == 4)
1086                                 result[3] = 1.0f;
1087                 }
1088                 /* This might be slow, but prevents error messages leak and
1089                  * other nasty stuff happening.
1090                  */
1091                 string err = ts->geterror();
1092                 (void)err;
1093         }
1094
1095         return status;
1096 }
1097
1098 bool OSLRenderServices::environment(ustring filename, TextureOpt &options,
1099                                     OSL::ShaderGlobals *sg, const OSL::Vec3 &R,
1100                                     const OSL::Vec3 &dRdx, const OSL::Vec3 &dRdy,
1101                                     int nchannels, float *result)
1102 {
1103         OSL::TextureSystem *ts = osl_ts;
1104         ShaderData *sd = (ShaderData *)(sg->renderstate);
1105         KernelGlobals *kg = sd->osl_globals;
1106         OSLThreadData *tdata = kg->osl_tdata;
1107         OIIO::TextureSystem::Perthread *thread_info = tdata->oiio_thread_info;
1108
1109         OIIO::TextureSystem::TextureHandle *th = ts->get_texture_handle(filename, thread_info);
1110
1111         bool status = ts->environment(th, thread_info,
1112                                       options, R, dRdx, dRdy,
1113                                       nchannels, result);
1114
1115         if(!status) {
1116                 if(nchannels == 3 || nchannels == 4) {
1117                         result[0] = 1.0f;
1118                         result[1] = 0.0f;
1119                         result[2] = 1.0f;
1120
1121                         if(nchannels == 4)
1122                                 result[3] = 1.0f;
1123                 }
1124         }
1125
1126         return status;
1127 }
1128
1129 bool OSLRenderServices::get_texture_info(OSL::ShaderGlobals *sg, ustring filename, int subimage,
1130                                          ustring dataname,
1131                                          TypeDesc datatype, void *data)
1132 {
1133         OSL::TextureSystem *ts = osl_ts;
1134         return ts->get_texture_info(filename, subimage, dataname, datatype, data);
1135 }
1136
1137 int OSLRenderServices::pointcloud_search(OSL::ShaderGlobals *sg, ustring filename, const OSL::Vec3 &center,
1138                                          float radius, int max_points, bool sort,
1139                                          size_t *out_indices, float *out_distances, int derivs_offset)
1140 {
1141         return 0;
1142 }
1143
1144 int OSLRenderServices::pointcloud_get(OSL::ShaderGlobals *sg, ustring filename, size_t *indices, int count,
1145                                       ustring attr_name, TypeDesc attr_type, void *out_data)
1146 {
1147         return 0;
1148 }
1149
1150 bool OSLRenderServices::pointcloud_write(OSL::ShaderGlobals *sg,
1151                                          ustring filename, const OSL::Vec3 &pos,
1152                                          int nattribs, const ustring *names,
1153                                          const TypeDesc *types,
1154                                          const void **data)
1155 {
1156         return false;
1157 }
1158
1159 bool OSLRenderServices::trace(TraceOpt &options, OSL::ShaderGlobals *sg,
1160         const OSL::Vec3 &P, const OSL::Vec3 &dPdx,
1161         const OSL::Vec3 &dPdy, const OSL::Vec3 &R,
1162         const OSL::Vec3 &dRdx, const OSL::Vec3 &dRdy)
1163 {
1164         /* todo: options.shader support, maybe options.traceset */
1165         ShaderData *sd = (ShaderData *)(sg->renderstate);
1166
1167         /* setup ray */
1168         Ray ray;
1169
1170         ray.P = TO_FLOAT3(P);
1171         ray.D = TO_FLOAT3(R);
1172         ray.t = (options.maxdist == 1.0e30f)? FLT_MAX: options.maxdist - options.mindist;
1173         ray.time = sd->time;
1174
1175         if(options.mindist == 0.0f) {
1176                 /* avoid self-intersections */
1177                 if(ray.P == sd->P) {
1178                         bool transmit = (dot(sd->Ng, ray.D) < 0.0f);
1179                         ray.P = ray_offset(sd->P, (transmit)? -sd->Ng: sd->Ng);
1180                 }
1181         }
1182         else {
1183                 /* offset for minimum distance */
1184                 ray.P += options.mindist*ray.D;
1185         }
1186
1187         /* ray differentials */
1188         ray.dP.dx = TO_FLOAT3(dPdx);
1189         ray.dP.dy = TO_FLOAT3(dPdy);
1190         ray.dD.dx = TO_FLOAT3(dRdx);
1191         ray.dD.dy = TO_FLOAT3(dRdy);
1192
1193         /* allocate trace data */
1194         OSLTraceData *tracedata = (OSLTraceData*)sg->tracedata;
1195         tracedata->ray = ray;
1196         tracedata->setup = false;
1197         tracedata->init = true;
1198         tracedata->sd.osl_globals = sd->osl_globals;
1199
1200         /* Raytrace, leaving out shadow opaque to avoid early exit. */
1201         uint visibility = PATH_RAY_ALL_VISIBILITY - PATH_RAY_SHADOW_OPAQUE;
1202         return scene_intersect(sd->osl_globals, ray, visibility, &tracedata->isect, NULL, 0.0f, 0.0f);
1203 }
1204
1205
1206 bool OSLRenderServices::getmessage(OSL::ShaderGlobals *sg, ustring source, ustring name,
1207         TypeDesc type, void *val, bool derivatives)
1208 {
1209         OSLTraceData *tracedata = (OSLTraceData*)sg->tracedata;
1210
1211         if(source == u_trace && tracedata->init) {
1212                 if(name == u_hit) {
1213                         return set_attribute_int((tracedata->isect.prim != PRIM_NONE), type, derivatives, val);
1214                 }
1215                 else if(tracedata->isect.prim != PRIM_NONE) {
1216                         if(name == u_hitdist) {
1217                                 float f[3] = {tracedata->isect.t, 0.0f, 0.0f};
1218                                 return set_attribute_float(f, type, derivatives, val);
1219                         }
1220                         else {
1221                                 ShaderData *sd = &tracedata->sd;
1222                                 KernelGlobals *kg = sd->osl_globals;
1223
1224                                 if(!tracedata->setup) {
1225                                         /* lazy shader data setup */
1226                                         shader_setup_from_ray(kg, sd, &tracedata->isect, &tracedata->ray);
1227                                         tracedata->setup = true;
1228                                 }
1229
1230                                 if(name == u_N) {
1231                                         return set_attribute_float3(sd->N, type, derivatives, val);
1232                                 }
1233                                 else if(name == u_Ng) {
1234                                         return set_attribute_float3(sd->Ng, type, derivatives, val);
1235                                 }
1236                                 else if(name == u_P) {
1237                                         float3 f[3] = {sd->P, sd->dP.dx, sd->dP.dy};
1238                                         return set_attribute_float3(f, type, derivatives, val);
1239                                 }
1240                                 else if(name == u_I) {
1241                                         float3 f[3] = {sd->I, sd->dI.dx, sd->dI.dy};
1242                                         return set_attribute_float3(f, type, derivatives, val);
1243                                 }
1244                                 else if(name == u_u) {
1245                                         float f[3] = {sd->u, sd->du.dx, sd->du.dy};
1246                                         return set_attribute_float(f, type, derivatives, val);
1247                                 }
1248                                 else if(name == u_v) {
1249                                         float f[3] = {sd->v, sd->dv.dx, sd->dv.dy};
1250                                         return set_attribute_float(f, type, derivatives, val);
1251                                 }
1252
1253                                 return get_attribute(sd, derivatives, u_empty, type, name, val);
1254                         }
1255                 }
1256         }
1257
1258         return false;
1259 }
1260
1261 CCL_NAMESPACE_END