Cycles microdisplacement: move subdivision options to subsurf modifier
[blender-staging.git] / intern / cycles / render / mesh.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 #include "bvh.h"
18 #include "bvh_build.h"
19
20 #include "camera.h"
21 #include "curves.h"
22 #include "device.h"
23 #include "graph.h"
24 #include "shader.h"
25 #include "light.h"
26 #include "mesh.h"
27 #include "nodes.h"
28 #include "object.h"
29 #include "scene.h"
30
31 #include "osl_globals.h"
32
33 #include "util_foreach.h"
34 #include "util_logging.h"
35 #include "util_progress.h"
36 #include "util_set.h"
37
38 CCL_NAMESPACE_BEGIN
39
40 /* Triangle */
41
42 void Mesh::Triangle::bounds_grow(const float3 *verts, BoundBox& bounds) const
43 {
44         bounds.grow(verts[v[0]]);
45         bounds.grow(verts[v[1]]);
46         bounds.grow(verts[v[2]]);
47 }
48
49 /* Curve */
50
51 void Mesh::Curve::bounds_grow(const int k, const float3 *curve_keys, const float *curve_radius, BoundBox& bounds) const
52 {
53         float3 P[4];
54
55         P[0] = curve_keys[max(first_key + k - 1,first_key)];
56         P[1] = curve_keys[first_key + k];
57         P[2] = curve_keys[first_key + k + 1];
58         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
59
60         float3 lower;
61         float3 upper;
62
63         curvebounds(&lower.x, &upper.x, P, 0);
64         curvebounds(&lower.y, &upper.y, P, 1);
65         curvebounds(&lower.z, &upper.z, P, 2);
66
67         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
68
69         bounds.grow(lower, mr);
70         bounds.grow(upper, mr);
71 }
72
73 void Mesh::Curve::bounds_grow(const int k,
74                               const float3 *curve_keys,
75                               const float *curve_radius,
76                               const Transform& aligned_space,
77                               BoundBox& bounds) const
78 {
79         float3 P[4];
80
81         P[0] = curve_keys[max(first_key + k - 1,first_key)];
82         P[1] = curve_keys[first_key + k];
83         P[2] = curve_keys[first_key + k + 1];
84         P[3] = curve_keys[min(first_key + k + 2, first_key + num_keys - 1)];
85
86         P[0] = transform_point(&aligned_space, P[0]);
87         P[1] = transform_point(&aligned_space, P[1]);
88         P[2] = transform_point(&aligned_space, P[2]);
89         P[3] = transform_point(&aligned_space, P[3]);
90
91         float3 lower;
92         float3 upper;
93
94         curvebounds(&lower.x, &upper.x, P, 0);
95         curvebounds(&lower.y, &upper.y, P, 1);
96         curvebounds(&lower.z, &upper.z, P, 2);
97
98         float mr = max(curve_radius[first_key + k], curve_radius[first_key + k + 1]);
99
100         bounds.grow(lower, mr);
101         bounds.grow(upper, mr);
102 }
103
104 /* SubdFace */
105
106 float3 Mesh::SubdFace::normal(const Mesh *mesh) const
107 {
108         float3 v0 = mesh->verts[mesh->subd_face_corners[start_corner+0]];
109         float3 v1 = mesh->verts[mesh->subd_face_corners[start_corner+1]];
110         float3 v2 = mesh->verts[mesh->subd_face_corners[start_corner+2]];
111
112         return safe_normalize(cross(v1 - v0, v2 - v0));
113 }
114
115
116 /* Mesh */
117
118 NODE_DEFINE(Mesh)
119 {
120         NodeType* type = NodeType::add("mesh", create);
121
122         static NodeEnum displacement_method_enum;
123         displacement_method_enum.insert("bump", DISPLACE_BUMP);
124         displacement_method_enum.insert("true", DISPLACE_TRUE);
125         displacement_method_enum.insert("both", DISPLACE_BOTH);
126         SOCKET_ENUM(displacement_method, "Displacement Method", displacement_method_enum, DISPLACE_BUMP);
127
128         SOCKET_UINT(motion_steps, "Motion Steps", 3);
129         SOCKET_BOOLEAN(use_motion_blur, "Use Motion Blur", false);
130
131         SOCKET_INT_ARRAY(triangles, "Triangles", array<int>());
132         SOCKET_POINT_ARRAY(verts, "Vertices", array<float3>());
133         SOCKET_INT_ARRAY(shader, "Shader", array<int>());
134         SOCKET_BOOLEAN_ARRAY(smooth, "Smooth", array<bool>());
135
136         SOCKET_POINT_ARRAY(curve_keys, "Curve Keys", array<float3>());
137         SOCKET_FLOAT_ARRAY(curve_radius, "Curve Radius", array<float>());
138         SOCKET_INT_ARRAY(curve_first_key, "Curve First Key", array<int>());
139         SOCKET_INT_ARRAY(curve_shader, "Curve Shader", array<int>());
140
141         return type;
142 }
143
144 Mesh::Mesh()
145 : Node(node_type)
146 {
147         need_update = true;
148         need_update_rebuild = false;
149         transform_applied = false;
150         transform_negative_scaled = false;
151         transform_normal = transform_identity();
152         bounds = BoundBox::empty;
153
154         bvh = NULL;
155
156         tri_offset = 0;
157         vert_offset = 0;
158
159         curve_offset = 0;
160         curvekey_offset = 0;
161
162         patch_offset = 0;
163         face_offset = 0;
164         corner_offset = 0;
165
166         num_subd_verts = 0;
167
168         attributes.triangle_mesh = this;
169         curve_attributes.curve_mesh = this;
170         subd_attributes.subd_mesh = this;
171
172         geometry_flags = GEOMETRY_NONE;
173
174         has_volume = false;
175         has_surface_bssrdf = false;
176
177         num_ngons = 0;
178
179         subdivision_type = SUBDIVISION_NONE;
180 }
181
182 Mesh::~Mesh()
183 {
184         delete bvh;
185 }
186
187 void Mesh::resize_mesh(int numverts, int numtris)
188 {
189         verts.resize(numverts);
190         triangles.resize(numtris * 3);
191         shader.resize(numtris);
192         smooth.resize(numtris);
193
194         if(subd_faces.size()) {
195                 triangle_patch.resize(numtris);
196                 vert_patch_uv.resize(numverts);
197         }
198
199         attributes.resize();
200 }
201
202 void Mesh::reserve_mesh(int numverts, int numtris)
203 {
204         /* reserve space to add verts and triangles later */
205         verts.reserve(numverts);
206         triangles.reserve(numtris * 3);
207         shader.reserve(numtris);
208         smooth.reserve(numtris);
209
210         if(subd_faces.size()) {
211                 triangle_patch.reserve(numtris);
212                 vert_patch_uv.reserve(numverts);
213         }
214
215         attributes.resize(true);
216 }
217
218 void Mesh::resize_curves(int numcurves, int numkeys)
219 {
220         curve_keys.resize(numkeys);
221         curve_radius.resize(numkeys);
222         curve_first_key.resize(numcurves);
223         curve_shader.resize(numcurves);
224
225         curve_attributes.resize();
226 }
227
228 void Mesh::reserve_curves(int numcurves, int numkeys)
229 {
230         curve_keys.reserve(numkeys);
231         curve_radius.reserve(numkeys);
232         curve_first_key.reserve(numcurves);
233         curve_shader.reserve(numcurves);
234
235         curve_attributes.resize(true);
236 }
237
238 void Mesh::resize_subd_faces(int numfaces, int num_ngons_, int numcorners)
239 {
240         subd_faces.resize(numfaces);
241         subd_face_corners.resize(numcorners);
242         num_ngons = num_ngons_;
243
244         subd_attributes.resize();
245 }
246
247 void Mesh::reserve_subd_faces(int numfaces, int num_ngons_, int numcorners)
248 {
249         subd_faces.reserve(numfaces);
250         subd_face_corners.reserve(numcorners);
251         num_ngons = num_ngons_;
252
253         subd_attributes.resize(true);
254 }
255
256 void Mesh::clear()
257 {
258         /* clear all verts and triangles */
259         verts.clear();
260         triangles.clear();
261         shader.clear();
262         smooth.clear();
263
264         triangle_patch.clear();
265         vert_patch_uv.clear();
266
267         curve_keys.clear();
268         curve_radius.clear();
269         curve_first_key.clear();
270         curve_shader.clear();
271
272         subd_faces.clear();
273         subd_face_corners.clear();
274
275         num_subd_verts = 0;
276
277         attributes.clear();
278         curve_attributes.clear();
279         subd_attributes.clear();
280         used_shaders.clear();
281
282         transform_applied = false;
283         transform_negative_scaled = false;
284         transform_normal = transform_identity();
285         geometry_flags = GEOMETRY_NONE;
286 }
287
288 int Mesh::split_vertex(int vertex)
289 {
290         /* copy vertex location and vertex attributes */
291         add_vertex_slow(verts[vertex]);
292
293         foreach(Attribute& attr, attributes.attributes) {
294                 if(attr.element == ATTR_ELEMENT_VERTEX) {
295                         vector<char> tmp(attr.data_sizeof());
296                         memcpy(&tmp[0], attr.data() + tmp.size()*vertex, tmp.size());
297                         attr.add(&tmp[0]);
298                 }
299         }
300
301         foreach(Attribute& attr, subd_attributes.attributes) {
302                 if(attr.element == ATTR_ELEMENT_VERTEX) {
303                         vector<char> tmp(attr.data_sizeof());
304                         memcpy(&tmp[0], attr.data() + tmp.size()*vertex, tmp.size());
305                         attr.add(&tmp[0]);
306                 }
307         }
308
309         return verts.size() - 1;
310 }
311
312 void Mesh::add_vertex(float3 P)
313 {
314         verts.push_back_reserved(P);
315
316         if(subd_faces.size()) {
317                 vert_patch_uv.push_back_reserved(make_float2(0.0f, 0.0f));
318         }
319 }
320
321 void Mesh::add_vertex_slow(float3 P)
322 {
323         verts.push_back_slow(P);
324
325         if(subd_faces.size()) {
326                 vert_patch_uv.push_back_slow(make_float2(0.0f, 0.0f));
327         }
328 }
329
330 void Mesh::add_triangle(int v0, int v1, int v2, int shader_, bool smooth_)
331 {
332         triangles.push_back_reserved(v0);
333         triangles.push_back_reserved(v1);
334         triangles.push_back_reserved(v2);
335         shader.push_back_reserved(shader_);
336         smooth.push_back_reserved(smooth_);
337
338         if(subd_faces.size()) {
339                 triangle_patch.push_back_reserved(-1);
340         }
341 }
342
343 void Mesh::add_curve_key(float3 co, float radius)
344 {
345         curve_keys.push_back_reserved(co);
346         curve_radius.push_back_reserved(radius);
347 }
348
349 void Mesh::add_curve(int first_key, int shader)
350 {
351         curve_first_key.push_back_reserved(first_key);
352         curve_shader.push_back_reserved(shader);
353 }
354
355 void Mesh::add_subd_face(int* corners, int num_corners, int shader_, bool smooth_)
356 {
357         size_t start_corner = subd_face_corners.size();
358
359         for(int i = 0; i < num_corners; i++) {
360                 subd_face_corners.push_back_reserved(corners[i]);
361         }
362
363         int ptex_offset = 0;
364
365         if(subd_faces.size()) {
366                 SubdFace& s = subd_faces[subd_faces.size()-1];
367                 ptex_offset = s.ptex_offset + s.num_ptex_faces();
368         }
369
370         SubdFace face = {start_corner, num_corners, shader_, smooth_, ptex_offset};
371         subd_faces.push_back_reserved(face);
372 }
373
374 void Mesh::compute_bounds()
375 {
376         BoundBox bnds = BoundBox::empty;
377         size_t verts_size = verts.size();
378         size_t curve_keys_size = curve_keys.size();
379
380         if(verts_size + curve_keys_size > 0) {
381                 for(size_t i = 0; i < verts_size; i++)
382                         bnds.grow(verts[i]);
383
384                 for(size_t i = 0; i < curve_keys_size; i++)
385                         bnds.grow(curve_keys[i], curve_radius[i]);
386
387                 Attribute *attr = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
388                 if(use_motion_blur && attr) {
389                         size_t steps_size = verts.size() * (motion_steps - 1);
390                         float3 *vert_steps = attr->data_float3();
391         
392                         for(size_t i = 0; i < steps_size; i++)
393                                 bnds.grow(vert_steps[i]);
394                 }
395
396                 Attribute *curve_attr = curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
397                 if(use_motion_blur && curve_attr) {
398                         size_t steps_size = curve_keys.size() * (motion_steps - 1);
399                         float3 *key_steps = curve_attr->data_float3();
400         
401                         for(size_t i = 0; i < steps_size; i++)
402                                 bnds.grow(key_steps[i]);
403                 }
404
405                 if(!bnds.valid()) {
406                         bnds = BoundBox::empty;
407
408                         /* skip nan or inf coordinates */
409                         for(size_t i = 0; i < verts_size; i++)
410                                 bnds.grow_safe(verts[i]);
411
412                         for(size_t i = 0; i < curve_keys_size; i++)
413                                 bnds.grow_safe(curve_keys[i], curve_radius[i]);
414                         
415                         if(use_motion_blur && attr) {
416                                 size_t steps_size = verts.size() * (motion_steps - 1);
417                                 float3 *vert_steps = attr->data_float3();
418                 
419                                 for(size_t i = 0; i < steps_size; i++)
420                                         bnds.grow_safe(vert_steps[i]);
421                         }
422
423                         if(use_motion_blur && curve_attr) {
424                                 size_t steps_size = curve_keys.size() * (motion_steps - 1);
425                                 float3 *key_steps = curve_attr->data_float3();
426                 
427                                 for(size_t i = 0; i < steps_size; i++)
428                                         bnds.grow_safe(key_steps[i]);
429                         }
430                 }
431         }
432
433         if(!bnds.valid()) {
434                 /* empty mesh */
435                 bnds.grow(make_float3(0.0f, 0.0f, 0.0f));
436         }
437
438         bounds = bnds;
439 }
440
441 static float3 compute_face_normal(const Mesh::Triangle& t, float3 *verts)
442 {
443         float3 v0 = verts[t.v[0]];
444         float3 v1 = verts[t.v[1]];
445         float3 v2 = verts[t.v[2]];
446
447         float3 norm = cross(v1 - v0, v2 - v0);
448         float normlen = len(norm);
449
450         if(normlen == 0.0f)
451                 return make_float3(1.0f, 0.0f, 0.0f);
452
453         return norm / normlen;
454 }
455
456 void Mesh::add_face_normals()
457 {
458         /* don't compute if already there */
459         if(attributes.find(ATTR_STD_FACE_NORMAL))
460                 return;
461         
462         /* get attributes */
463         Attribute *attr_fN = attributes.add(ATTR_STD_FACE_NORMAL);
464         float3 *fN = attr_fN->data_float3();
465
466         /* compute face normals */
467         size_t triangles_size = num_triangles();
468         bool flip = transform_negative_scaled;
469
470         if(triangles_size) {
471                 float3 *verts_ptr = &verts[0];
472
473                 for(size_t i = 0; i < triangles_size; i++) {
474                         fN[i] = compute_face_normal(get_triangle(i), verts_ptr);
475
476                         if(flip)
477                                 fN[i] = -fN[i];
478                 }
479         }
480
481         /* expected to be in local space */
482         if(transform_applied) {
483                 Transform ntfm = transform_inverse(transform_normal);
484
485                 for(size_t i = 0; i < triangles_size; i++)
486                         fN[i] = normalize(transform_direction(&ntfm, fN[i]));
487         }
488 }
489
490 void Mesh::add_vertex_normals()
491 {
492         bool flip = transform_negative_scaled;
493         size_t verts_size = verts.size();
494         size_t triangles_size = num_triangles();
495
496         /* static vertex normals */
497         if(!attributes.find(ATTR_STD_VERTEX_NORMAL)) {
498                 /* get attributes */
499                 Attribute *attr_fN = attributes.find(ATTR_STD_FACE_NORMAL);
500                 Attribute *attr_vN = attributes.add(ATTR_STD_VERTEX_NORMAL);
501
502                 float3 *fN = attr_fN->data_float3();
503                 float3 *vN = attr_vN->data_float3();
504
505                 /* compute vertex normals */
506                 memset(vN, 0, verts.size()*sizeof(float3));
507
508                 if(triangles_size) {
509
510                         for(size_t i = 0; i < triangles_size; i++)
511                                 for(size_t j = 0; j < 3; j++)
512                                         vN[get_triangle(i).v[j]] += fN[i];
513                 }
514
515                 for(size_t i = 0; i < verts_size; i++) {
516                         vN[i] = normalize(vN[i]);
517                         if(flip)
518                                 vN[i] = -vN[i];
519                 }
520         }
521
522         /* motion vertex normals */
523         Attribute *attr_mP = attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
524         Attribute *attr_mN = attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
525
526         if(has_motion_blur() && attr_mP && !attr_mN) {
527                 /* create attribute */
528                 attr_mN = attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
529
530                 for(int step = 0; step < motion_steps - 1; step++) {
531                         float3 *mP = attr_mP->data_float3() + step*verts.size();
532                         float3 *mN = attr_mN->data_float3() + step*verts.size();
533
534                         /* compute */
535                         memset(mN, 0, verts.size()*sizeof(float3));
536
537                         if(triangles_size) {
538                                 for(size_t i = 0; i < triangles_size; i++) {
539                                         for(size_t j = 0; j < 3; j++) {
540                                                 float3 fN = compute_face_normal(get_triangle(i), mP);
541                                                 mN[get_triangle(i).v[j]] += fN;
542                                         }
543                                 }
544                         }
545
546                         for(size_t i = 0; i < verts_size; i++) {
547                                 mN[i] = normalize(mN[i]);
548                                 if(flip)
549                                         mN[i] = -mN[i];
550                         }
551                 }
552         }
553 }
554
555 void Mesh::pack_normals(Scene *scene, uint *tri_shader, float4 *vnormal)
556 {
557         Attribute *attr_vN = attributes.find(ATTR_STD_VERTEX_NORMAL);
558
559         float3 *vN = attr_vN->data_float3();
560         uint shader_id = 0;
561         uint last_shader = -1;
562         bool last_smooth = false;
563
564         size_t triangles_size = num_triangles();
565         int *shader_ptr = (shader.size())? &shader[0]: NULL;
566
567         bool do_transform = transform_applied;
568         Transform ntfm = transform_normal;
569
570         /* save shader */
571         for(size_t i = 0; i < triangles_size; i++) {
572                 if(shader_ptr[i] != last_shader || last_smooth != smooth[i]) {
573                         last_shader = shader_ptr[i];
574                         last_smooth = smooth[i];
575                         Shader *shader = (last_shader < used_shaders.size()) ?
576                                 used_shaders[last_shader] : scene->default_surface;
577                         shader_id = scene->shader_manager->get_shader_id(shader, this, last_smooth);
578                 }
579
580                 tri_shader[i] = shader_id;
581         }
582
583         size_t verts_size = verts.size();
584
585         for(size_t i = 0; i < verts_size; i++) {
586                 float3 vNi = vN[i];
587
588                 if(do_transform)
589                         vNi = normalize(transform_direction(&ntfm, vNi));
590
591                 vnormal[i] = make_float4(vNi.x, vNi.y, vNi.z, 0.0f);
592         }
593 }
594
595 void Mesh::pack_verts(const vector<uint>& tri_prim_index,
596                       uint4 *tri_vindex,
597                       uint *tri_patch,
598                       float2 *tri_patch_uv,
599                       size_t vert_offset,
600                       size_t tri_offset)
601 {
602         size_t verts_size = verts.size();
603
604         if(verts_size && subd_faces.size()) {
605                 float2 *vert_patch_uv_ptr = &vert_patch_uv[0];
606
607                 for(size_t i = 0; i < verts_size; i++) {
608                         tri_patch_uv[i] = vert_patch_uv_ptr[i];
609                 }
610         }
611
612         size_t triangles_size = num_triangles();
613
614         if(triangles_size) {
615                 for(size_t i = 0; i < triangles_size; i++) {
616                         Triangle t = get_triangle(i);
617                         tri_vindex[i] = make_uint4(t.v[0] + vert_offset,
618                                                    t.v[1] + vert_offset,
619                                                    t.v[2] + vert_offset,
620                                                    tri_prim_index[i + tri_offset]);
621
622                         tri_patch[i] = (!subd_faces.size()) ? -1 : (triangle_patch[i]*8 + patch_offset);
623                 }
624         }
625 }
626
627 void Mesh::pack_curves(Scene *scene, float4 *curve_key_co, float4 *curve_data, size_t curvekey_offset)
628 {
629         size_t curve_keys_size = curve_keys.size();
630
631         /* pack curve keys */
632         if(curve_keys_size) {
633                 float3 *keys_ptr = &curve_keys[0];
634                 float *radius_ptr = &curve_radius[0];
635
636                 for(size_t i = 0; i < curve_keys_size; i++)
637                         curve_key_co[i] = make_float4(keys_ptr[i].x, keys_ptr[i].y, keys_ptr[i].z, radius_ptr[i]);
638         }
639
640         /* pack curve segments */
641         size_t curve_num = num_curves();
642
643         if(curve_num) {
644                 for(size_t i = 0; i < curve_num; i++) {
645                         Curve curve = get_curve(i);
646                         int shader_id = curve_shader[i];
647                         Shader *shader = (shader_id < used_shaders.size()) ?
648                                 used_shaders[shader_id] : scene->default_surface;
649                         shader_id = scene->shader_manager->get_shader_id(shader, this, false);
650
651                         curve_data[i] = make_float4(
652                                 __int_as_float(curve.first_key + curvekey_offset),
653                                 __int_as_float(curve.num_keys),
654                                 __int_as_float(shader_id),
655                                 0.0f);
656                 }
657         }
658 }
659
660 void Mesh::pack_patches(uint *patch_data, uint vert_offset, uint face_offset, uint corner_offset)
661 {
662         size_t num_faces = subd_faces.size();
663         int ngons = 0;
664
665         if(num_faces) {
666                 for(size_t f = 0; f < num_faces; f++) {
667                         SubdFace face = subd_faces[f];
668
669                         if(face.is_quad()) {
670                                 int c[4];
671                                 memcpy(c, &subd_face_corners[face.start_corner], sizeof(int)*4);
672
673                                 *(patch_data++) = c[0] + vert_offset;
674                                 *(patch_data++) = c[1] + vert_offset;
675                                 *(patch_data++) = c[2] + vert_offset;
676                                 *(patch_data++) = c[3] + vert_offset;
677
678                                 *(patch_data++) = f+face_offset;
679                                 *(patch_data++) = face.num_corners;
680                                 *(patch_data++) = face.start_corner + corner_offset;
681                                 *(patch_data++) = 0;
682                         }
683                         else {
684                                 for(int i = 0; i < face.num_corners; i++) {
685                                         int c[4];
686                                         c[0] = subd_face_corners[face.start_corner + mod(i + 0, face.num_corners)];
687                                         c[1] = subd_face_corners[face.start_corner + mod(i + 1, face.num_corners)];
688                                         c[2] = verts.size() - num_subd_verts + ngons;
689                                         c[3] = subd_face_corners[face.start_corner + mod(i - 1, face.num_corners)];
690
691                                         *(patch_data++) = c[0] + vert_offset;
692                                         *(patch_data++) = c[1] + vert_offset;
693                                         *(patch_data++) = c[2] + vert_offset;
694                                         *(patch_data++) = c[3] + vert_offset;
695
696                                         *(patch_data++) = f+face_offset;
697                                         *(patch_data++) = face.num_corners | (i << 16);
698                                         *(patch_data++) = face.start_corner + corner_offset;
699                                         *(patch_data++) = subd_face_corners.size() + ngons + corner_offset;
700                                 }
701
702                                 ngons++;
703                         }
704                 }
705         }
706 }
707
708
709 void Mesh::compute_bvh(DeviceScene *dscene,
710                        SceneParams *params,
711                        Progress *progress,
712                        int n,
713                        int total)
714 {
715         if(progress->get_cancel())
716                 return;
717
718         compute_bounds();
719
720         if(need_build_bvh()) {
721                 string msg = "Updating Mesh BVH ";
722                 if(name == "")
723                         msg += string_printf("%u/%u", (uint)(n+1), (uint)total);
724                 else
725                         msg += string_printf("%s %u/%u", name.c_str(), (uint)(n+1), (uint)total);
726
727                 Object object;
728                 object.mesh = this;
729
730                 vector<Object*> objects;
731                 objects.push_back(&object);
732
733                 if(bvh && !need_update_rebuild) {
734                         progress->set_status(msg, "Refitting BVH");
735                         bvh->objects = objects;
736                         bvh->refit(*progress);
737                 }
738                 else {
739                         progress->set_status(msg, "Building BVH");
740
741                         BVHParams bparams;
742                         bparams.use_spatial_split = params->use_bvh_spatial_split;
743                         bparams.use_qbvh = params->use_qbvh;
744                         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
745                                                       params->use_bvh_unaligned_nodes;
746
747                         delete bvh;
748                         bvh = BVH::create(bparams, objects);
749                         MEM_GUARDED_CALL(progress, bvh->build, *progress);
750                 }
751         }
752
753         need_update = false;
754         need_update_rebuild = false;
755 }
756
757 void Mesh::tag_update(Scene *scene, bool rebuild)
758 {
759         need_update = true;
760
761         if(rebuild) {
762                 need_update_rebuild = true;
763                 scene->light_manager->need_update = true;
764         }
765         else {
766                 foreach(Shader *shader, used_shaders)
767                         if(shader->has_surface_emission)
768                                 scene->light_manager->need_update = true;
769         }
770
771         scene->mesh_manager->need_update = true;
772         scene->object_manager->need_update = true;
773 }
774
775 bool Mesh::has_motion_blur() const
776 {
777         return (use_motion_blur &&
778                 (attributes.find(ATTR_STD_MOTION_VERTEX_POSITION) ||
779                  curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION)));
780 }
781
782 bool Mesh::need_build_bvh() const
783 {
784         return !transform_applied || has_surface_bssrdf;
785 }
786
787 bool Mesh::is_instanced() const
788 {
789         /* Currently we treat subsurface objects as instanced.
790          *
791          * While it might be not very optimal for ray traversal, it avoids having
792          * duplicated BVH in the memory, saving quite some space.
793          */
794         return !transform_applied || has_surface_bssrdf;
795 }
796
797 /* Mesh Manager */
798
799 MeshManager::MeshManager()
800 {
801         bvh = NULL;
802         need_update = true;
803         need_flags_update = true;
804 }
805
806 MeshManager::~MeshManager()
807 {
808         delete bvh;
809 }
810
811 void MeshManager::update_osl_attributes(Device *device, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
812 {
813 #ifdef WITH_OSL
814         /* for OSL, a hash map is used to lookup the attribute by name. */
815         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
816
817         og->object_name_map.clear();
818         og->attribute_map.clear();
819         og->object_names.clear();
820
821         og->attribute_map.resize(scene->objects.size()*ATTR_PRIM_TYPES);
822
823         for(size_t i = 0; i < scene->objects.size(); i++) {
824                 /* set object name to object index map */
825                 Object *object = scene->objects[i];
826                 og->object_name_map[object->name] = i;
827                 og->object_names.push_back(object->name);
828
829                 /* set object attributes */
830                 foreach(ParamValue& attr, object->attributes) {
831                         OSLGlobals::Attribute osl_attr;
832
833                         osl_attr.type = attr.type();
834                         osl_attr.elem = ATTR_ELEMENT_OBJECT;
835                         osl_attr.value = attr;
836                         osl_attr.offset = 0;
837
838                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][attr.name()] = osl_attr;
839                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][attr.name()] = osl_attr;
840                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][attr.name()] = osl_attr;
841                 }
842
843                 /* find mesh attributes */
844                 size_t j;
845
846                 for(j = 0; j < scene->meshes.size(); j++)
847                         if(scene->meshes[j] == object->mesh)
848                                 break;
849
850                 AttributeRequestSet& attributes = mesh_attributes[j];
851
852                 /* set object attributes */
853                 foreach(AttributeRequest& req, attributes.requests) {
854                         OSLGlobals::Attribute osl_attr;
855
856                         if(req.triangle_element != ATTR_ELEMENT_NONE) {
857                                 osl_attr.elem = req.triangle_element;
858                                 osl_attr.offset = req.triangle_offset;
859
860                                 if(req.triangle_type == TypeDesc::TypeFloat)
861                                         osl_attr.type = TypeDesc::TypeFloat;
862                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
863                                         osl_attr.type = TypeDesc::TypeMatrix;
864                                 else
865                                         osl_attr.type = TypeDesc::TypeColor;
866
867                                 if(req.std != ATTR_STD_NONE) {
868                                         /* if standard attribute, add lookup by geom: name convention */
869                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
870                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][stdname] = osl_attr;
871                                 }
872                                 else if(req.name != ustring()) {
873                                         /* add lookup by mesh attribute name */
874                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_TRIANGLE][req.name] = osl_attr;
875                                 }
876                         }
877
878                         if(req.curve_element != ATTR_ELEMENT_NONE) {
879                                 osl_attr.elem = req.curve_element;
880                                 osl_attr.offset = req.curve_offset;
881
882                                 if(req.curve_type == TypeDesc::TypeFloat)
883                                         osl_attr.type = TypeDesc::TypeFloat;
884                                 else if(req.curve_type == TypeDesc::TypeMatrix)
885                                         osl_attr.type = TypeDesc::TypeMatrix;
886                                 else
887                                         osl_attr.type = TypeDesc::TypeColor;
888
889                                 if(req.std != ATTR_STD_NONE) {
890                                         /* if standard attribute, add lookup by geom: name convention */
891                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
892                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][stdname] = osl_attr;
893                                 }
894                                 else if(req.name != ustring()) {
895                                         /* add lookup by mesh attribute name */
896                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_CURVE][req.name] = osl_attr;
897                                 }
898                         }
899
900                         if(req.subd_element != ATTR_ELEMENT_NONE) {
901                                 osl_attr.elem = req.subd_element;
902                                 osl_attr.offset = req.subd_offset;
903
904                                 if(req.subd_type == TypeDesc::TypeFloat)
905                                         osl_attr.type = TypeDesc::TypeFloat;
906                                 else if(req.subd_type == TypeDesc::TypeMatrix)
907                                         osl_attr.type = TypeDesc::TypeMatrix;
908                                 else
909                                         osl_attr.type = TypeDesc::TypeColor;
910
911                                 if(req.std != ATTR_STD_NONE) {
912                                         /* if standard attribute, add lookup by geom: name convention */
913                                         ustring stdname(string("geom:") + string(Attribute::standard_name(req.std)));
914                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][stdname] = osl_attr;
915                                 }
916                                 else if(req.name != ustring()) {
917                                         /* add lookup by mesh attribute name */
918                                         og->attribute_map[i*ATTR_PRIM_TYPES + ATTR_PRIM_SUBD][req.name] = osl_attr;
919                                 }
920                         }
921                 }
922         }
923 #else
924         (void)device;
925         (void)scene;
926         (void)mesh_attributes;
927 #endif
928 }
929
930 void MeshManager::update_svm_attributes(Device *device, DeviceScene *dscene, Scene *scene, vector<AttributeRequestSet>& mesh_attributes)
931 {
932         /* for SVM, the attributes_map table is used to lookup the offset of an
933          * attribute, based on a unique shader attribute id. */
934
935         /* compute array stride */
936         int attr_map_stride = 0;
937
938         for(size_t i = 0; i < scene->meshes.size(); i++)
939                 attr_map_stride = max(attr_map_stride, (mesh_attributes[i].size() + 1)*ATTR_PRIM_TYPES);
940
941         if(attr_map_stride == 0)
942                 return;
943         
944         /* create attribute map */
945         uint4 *attr_map = dscene->attributes_map.resize(attr_map_stride*scene->objects.size());
946         memset(attr_map, 0, dscene->attributes_map.size()*sizeof(uint));
947
948         for(size_t i = 0; i < scene->objects.size(); i++) {
949                 Object *object = scene->objects[i];
950                 Mesh *mesh = object->mesh;
951
952                 /* find mesh attributes */
953                 size_t j;
954
955                 for(j = 0; j < scene->meshes.size(); j++)
956                         if(scene->meshes[j] == mesh)
957                                 break;
958
959                 AttributeRequestSet& attributes = mesh_attributes[j];
960
961                 /* set object attributes */
962                 int index = i*attr_map_stride;
963
964                 foreach(AttributeRequest& req, attributes.requests) {
965                         uint id;
966
967                         if(req.std == ATTR_STD_NONE)
968                                 id = scene->shader_manager->get_attribute_id(req.name);
969                         else
970                                 id = scene->shader_manager->get_attribute_id(req.std);
971
972                         if(mesh->num_triangles()) {
973                                 attr_map[index].x = id;
974                                 attr_map[index].y = req.triangle_element;
975                                 attr_map[index].z = as_uint(req.triangle_offset);
976
977                                 if(req.triangle_type == TypeDesc::TypeFloat)
978                                         attr_map[index].w = NODE_ATTR_FLOAT;
979                                 else if(req.triangle_type == TypeDesc::TypeMatrix)
980                                         attr_map[index].w = NODE_ATTR_MATRIX;
981                                 else
982                                         attr_map[index].w = NODE_ATTR_FLOAT3;
983                         }
984
985                         index++;
986
987                         if(mesh->num_curves()) {
988                                 attr_map[index].x = id;
989                                 attr_map[index].y = req.curve_element;
990                                 attr_map[index].z = as_uint(req.curve_offset);
991
992                                 if(req.curve_type == TypeDesc::TypeFloat)
993                                         attr_map[index].w = NODE_ATTR_FLOAT;
994                                 else if(req.curve_type == TypeDesc::TypeMatrix)
995                                         attr_map[index].w = NODE_ATTR_MATRIX;
996                                 else
997                                         attr_map[index].w = NODE_ATTR_FLOAT3;
998                         }
999
1000                         index++;
1001
1002                         if(mesh->subd_faces.size()) {
1003                                 attr_map[index].x = id;
1004                                 attr_map[index].y = req.subd_element;
1005                                 attr_map[index].z = as_uint(req.subd_offset);
1006
1007                                 if(req.subd_type == TypeDesc::TypeFloat)
1008                                         attr_map[index].w = NODE_ATTR_FLOAT;
1009                                 else if(req.subd_type == TypeDesc::TypeMatrix)
1010                                         attr_map[index].w = NODE_ATTR_MATRIX;
1011                                 else
1012                                         attr_map[index].w = NODE_ATTR_FLOAT3;
1013                         }
1014
1015                         index++;
1016                 }
1017
1018                 /* terminator */
1019                 for(int i = 0; i < ATTR_PRIM_TYPES; i++) {
1020                         attr_map[index].x = ATTR_STD_NONE;
1021                         attr_map[index].y = 0;
1022                         attr_map[index].z = 0;
1023                         attr_map[index].w = 0;
1024
1025                         index++;
1026                 }
1027         }
1028
1029         /* copy to device */
1030         dscene->data.bvh.attributes_map_stride = attr_map_stride;
1031         device->tex_alloc("__attributes_map", dscene->attributes_map);
1032 }
1033
1034 static void update_attribute_element_size(Mesh *mesh,
1035                                           Attribute *mattr,
1036                                           AttributePrimitive prim,
1037                                           size_t *attr_float_size,
1038                                           size_t *attr_float3_size,
1039                                           size_t *attr_uchar4_size)
1040 {
1041         if(mattr) {
1042                 size_t size = mattr->element_size(mesh, prim);
1043
1044                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1045                         /* pass */
1046                 }
1047                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1048                         *attr_uchar4_size += size;
1049                 }
1050                 else if(mattr->type == TypeDesc::TypeFloat) {
1051                         *attr_float_size += size;
1052                 }
1053                 else if(mattr->type == TypeDesc::TypeMatrix) {
1054                         *attr_float3_size += size * 4;
1055                 }
1056                 else {
1057                         *attr_float3_size += size;
1058                 }
1059         }
1060 }
1061
1062 static void update_attribute_element_offset(Mesh *mesh,
1063                                             vector<float>& attr_float,
1064                                             size_t& attr_float_offset,
1065                                             vector<float4>& attr_float3,
1066                                             size_t& attr_float3_offset,
1067                                             vector<uchar4>& attr_uchar4,
1068                                             size_t& attr_uchar4_offset,
1069                                             Attribute *mattr,
1070                                             AttributePrimitive prim,
1071                                             TypeDesc& type,
1072                                             int& offset,
1073                                             AttributeElement& element)
1074 {
1075         if(mattr) {
1076                 /* store element and type */
1077                 element = mattr->element;
1078                 type = mattr->type;
1079
1080                 /* store attribute data in arrays */
1081                 size_t size = mattr->element_size(mesh, prim);
1082
1083                 if(mattr->element == ATTR_ELEMENT_VOXEL) {
1084                         /* store slot in offset value */
1085                         VoxelAttribute *voxel_data = mattr->data_voxel();
1086                         offset = voxel_data->slot;
1087                 }
1088                 else if(mattr->element == ATTR_ELEMENT_CORNER_BYTE) {
1089                         uchar4 *data = mattr->data_uchar4();
1090                         offset = attr_uchar4_offset;
1091
1092                         assert(attr_uchar4.capacity() >= offset + size);
1093                         for(size_t k = 0; k < size; k++) {
1094                                 attr_uchar4[offset+k] = data[k];
1095                         }
1096                         attr_uchar4_offset += size;
1097                 }
1098                 else if(mattr->type == TypeDesc::TypeFloat) {
1099                         float *data = mattr->data_float();
1100                         offset = attr_float_offset;
1101
1102                         assert(attr_float.capacity() >= offset + size);
1103                         for(size_t k = 0; k < size; k++) {
1104                                 attr_float[offset+k] = data[k];
1105                         }
1106                         attr_float_offset += size;
1107                 }
1108                 else if(mattr->type == TypeDesc::TypeMatrix) {
1109                         Transform *tfm = mattr->data_transform();
1110                         offset = attr_float3_offset;
1111
1112                         assert(attr_float3.capacity() >= offset + size * 4);
1113                         for(size_t k = 0; k < size*4; k++) {
1114                                 attr_float3[offset+k] = (&tfm->x)[k];
1115                         }
1116                         attr_float3_offset += size * 4;
1117                 }
1118                 else {
1119                         float4 *data = mattr->data_float4();
1120                         offset = attr_float3_offset;
1121
1122                         assert(attr_float3.capacity() >= offset + size);
1123                         for(size_t k = 0; k < size; k++) {
1124                                 attr_float3[offset+k] = data[k];
1125                         }
1126                         attr_float3_offset += size;
1127                 }
1128
1129                 /* mesh vertex/curve index is global, not per object, so we sneak
1130                  * a correction for that in here */
1131                 if(element == ATTR_ELEMENT_VERTEX)
1132                         offset -= mesh->vert_offset;
1133                 else if(element == ATTR_ELEMENT_VERTEX_MOTION)
1134                         offset -= mesh->vert_offset;
1135                 else if(element == ATTR_ELEMENT_FACE) {
1136                         if(prim == ATTR_PRIM_TRIANGLE)
1137                                 offset -= mesh->tri_offset;
1138                         else
1139                                 offset -= mesh->face_offset;
1140                 }
1141                 else if(element == ATTR_ELEMENT_CORNER || element == ATTR_ELEMENT_CORNER_BYTE) {
1142                         if(prim == ATTR_PRIM_TRIANGLE)
1143                                 offset -= 3*mesh->tri_offset;
1144                         else
1145                                 offset -= mesh->corner_offset;
1146                 }
1147                 else if(element == ATTR_ELEMENT_CURVE)
1148                         offset -= mesh->curve_offset;
1149                 else if(element == ATTR_ELEMENT_CURVE_KEY)
1150                         offset -= mesh->curvekey_offset;
1151                 else if(element == ATTR_ELEMENT_CURVE_KEY_MOTION)
1152                         offset -= mesh->curvekey_offset;
1153         }
1154         else {
1155                 /* attribute not found */
1156                 element = ATTR_ELEMENT_NONE;
1157                 offset = 0;
1158         }
1159 }
1160
1161 void MeshManager::device_update_attributes(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1162 {
1163         progress.set_status("Updating Mesh", "Computing attributes");
1164
1165         /* gather per mesh requested attributes. as meshes may have multiple
1166          * shaders assigned, this merges the requested attributes that have
1167          * been set per shader by the shader manager */
1168         vector<AttributeRequestSet> mesh_attributes(scene->meshes.size());
1169
1170         for(size_t i = 0; i < scene->meshes.size(); i++) {
1171                 Mesh *mesh = scene->meshes[i];
1172
1173                 scene->need_global_attributes(mesh_attributes[i]);
1174
1175                 foreach(Shader *shader, mesh->used_shaders) {
1176                         mesh_attributes[i].add(shader->attributes);
1177                 }
1178         }
1179
1180         /* mesh attribute are stored in a single array per data type. here we fill
1181          * those arrays, and set the offset and element type to create attribute
1182          * maps next */
1183
1184         /* Pre-allocate attributes to avoid arrays re-allocation which would
1185          * take 2x of overall attribute memory usage.
1186          */
1187         size_t attr_float_size = 0;
1188         size_t attr_float3_size = 0;
1189         size_t attr_uchar4_size = 0;
1190         for(size_t i = 0; i < scene->meshes.size(); i++) {
1191                 Mesh *mesh = scene->meshes[i];
1192                 AttributeRequestSet& attributes = mesh_attributes[i];
1193                 foreach(AttributeRequest& req, attributes.requests) {
1194                         Attribute *triangle_mattr = mesh->attributes.find(req);
1195                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1196                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1197
1198                         update_attribute_element_size(mesh,
1199                                                       triangle_mattr,
1200                                                       ATTR_PRIM_TRIANGLE,
1201                                                       &attr_float_size,
1202                                                       &attr_float3_size,
1203                                                       &attr_uchar4_size);
1204                         update_attribute_element_size(mesh,
1205                                                       curve_mattr,
1206                                                       ATTR_PRIM_CURVE,
1207                                                       &attr_float_size,
1208                                                       &attr_float3_size,
1209                                                       &attr_uchar4_size);
1210                         update_attribute_element_size(mesh,
1211                                                       subd_mattr,
1212                                                       ATTR_PRIM_SUBD,
1213                                                       &attr_float_size,
1214                                                       &attr_float3_size,
1215                                                       &attr_uchar4_size);
1216                 }
1217         }
1218
1219         vector<float> attr_float(attr_float_size);
1220         vector<float4> attr_float3(attr_float3_size);
1221         vector<uchar4> attr_uchar4(attr_uchar4_size);
1222
1223         size_t attr_float_offset = 0;
1224         size_t attr_float3_offset = 0;
1225         size_t attr_uchar4_offset = 0;
1226
1227         /* Fill in attributes. */
1228         for(size_t i = 0; i < scene->meshes.size(); i++) {
1229                 Mesh *mesh = scene->meshes[i];
1230                 AttributeRequestSet& attributes = mesh_attributes[i];
1231
1232                 /* todo: we now store std and name attributes from requests even if
1233                  * they actually refer to the same mesh attributes, optimize */
1234                 foreach(AttributeRequest& req, attributes.requests) {
1235                         Attribute *triangle_mattr = mesh->attributes.find(req);
1236                         Attribute *curve_mattr = mesh->curve_attributes.find(req);
1237                         Attribute *subd_mattr = mesh->subd_attributes.find(req);
1238
1239                         update_attribute_element_offset(mesh,
1240                                                         attr_float, attr_float_offset,
1241                                                         attr_float3, attr_float3_offset,
1242                                                         attr_uchar4, attr_uchar4_offset,
1243                                                         triangle_mattr,
1244                                                         ATTR_PRIM_TRIANGLE,
1245                                                         req.triangle_type,
1246                                                         req.triangle_offset,
1247                                                         req.triangle_element);
1248
1249                         update_attribute_element_offset(mesh,
1250                                                         attr_float, attr_float_offset,
1251                                                         attr_float3, attr_float3_offset,
1252                                                         attr_uchar4, attr_uchar4_offset,
1253                                                         curve_mattr,
1254                                                         ATTR_PRIM_CURVE,
1255                                                         req.curve_type,
1256                                                         req.curve_offset,
1257                                                         req.curve_element);
1258
1259                         update_attribute_element_offset(mesh,
1260                                                         attr_float, attr_float_offset,
1261                                                         attr_float3, attr_float3_offset,
1262                                                         attr_uchar4, attr_uchar4_offset,
1263                                                         subd_mattr,
1264                                                         ATTR_PRIM_SUBD,
1265                                                         req.subd_type,
1266                                                         req.subd_offset,
1267                                                         req.subd_element);
1268
1269                         if(progress.get_cancel()) return;
1270                 }
1271         }
1272
1273         /* create attribute lookup maps */
1274         if(scene->shader_manager->use_osl())
1275                 update_osl_attributes(device, scene, mesh_attributes);
1276
1277         update_svm_attributes(device, dscene, scene, mesh_attributes);
1278
1279         if(progress.get_cancel()) return;
1280
1281         /* copy to device */
1282         progress.set_status("Updating Mesh", "Copying Attributes to device");
1283
1284         if(attr_float.size()) {
1285                 dscene->attributes_float.copy(&attr_float[0], attr_float.size());
1286                 device->tex_alloc("__attributes_float", dscene->attributes_float);
1287         }
1288         if(attr_float3.size()) {
1289                 dscene->attributes_float3.copy(&attr_float3[0], attr_float3.size());
1290                 device->tex_alloc("__attributes_float3", dscene->attributes_float3);
1291         }
1292         if(attr_uchar4.size()) {
1293                 dscene->attributes_uchar4.copy(&attr_uchar4[0], attr_uchar4.size());
1294                 device->tex_alloc("__attributes_uchar4", dscene->attributes_uchar4);
1295         }
1296 }
1297
1298 void MeshManager::mesh_calc_offset(Scene *scene)
1299 {
1300         size_t vert_size = 0;
1301         size_t tri_size = 0;
1302
1303         size_t curve_key_size = 0;
1304         size_t curve_size = 0;
1305
1306         size_t patch_size = 0;
1307         size_t face_size = 0;
1308         size_t corner_size = 0;
1309
1310         foreach(Mesh *mesh, scene->meshes) {
1311                 mesh->vert_offset = vert_size;
1312                 mesh->tri_offset = tri_size;
1313
1314                 mesh->curvekey_offset = curve_key_size;
1315                 mesh->curve_offset = curve_size;
1316
1317                 mesh->patch_offset = patch_size;
1318                 mesh->face_offset = face_size;
1319                 mesh->corner_offset = corner_size;
1320
1321                 vert_size += mesh->verts.size();
1322                 tri_size += mesh->num_triangles();
1323
1324                 curve_key_size += mesh->curve_keys.size();
1325                 curve_size += mesh->num_curves();
1326
1327                 if(mesh->subd_faces.size()) {
1328                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1329                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1330                 }
1331                 face_size += mesh->subd_faces.size();
1332                 corner_size += mesh->subd_face_corners.size();
1333         }
1334 }
1335
1336 void MeshManager::device_update_mesh(Device *device,
1337                                      DeviceScene *dscene,
1338                                      Scene *scene,
1339                                      bool for_displacement,
1340                                      Progress& progress)
1341 {
1342         /* Count. */
1343         size_t vert_size = 0;
1344         size_t tri_size = 0;
1345
1346         size_t curve_key_size = 0;
1347         size_t curve_size = 0;
1348
1349         size_t patch_size = 0;
1350
1351         foreach(Mesh *mesh, scene->meshes) {
1352                 vert_size += mesh->verts.size();
1353                 tri_size += mesh->num_triangles();
1354
1355                 curve_key_size += mesh->curve_keys.size();
1356                 curve_size += mesh->num_curves();
1357
1358                 if(mesh->subd_faces.size()) {
1359                         Mesh::SubdFace& last = mesh->subd_faces[mesh->subd_faces.size()-1];
1360                         patch_size += (last.ptex_offset + last.num_ptex_faces()) * 8;
1361                 }
1362         }
1363
1364         /* Create mapping from triangle to primitive triangle array. */
1365         vector<uint> tri_prim_index(tri_size);
1366         if(for_displacement) {
1367                 /* For displacement kernels we do some trickery to make them believe
1368                  * we've got all required data ready. However, that data is different
1369                  * from final render kernels since we don't have BVH yet, so can't
1370                  * really use same semantic of arrays.
1371                  */
1372                 foreach(Mesh *mesh, scene->meshes) {
1373                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1374                                 tri_prim_index[i + mesh->tri_offset] = 3 * (i + mesh->tri_offset);
1375                         }
1376                 }
1377         }
1378         else {
1379                 PackedBVH& pack = bvh->pack;
1380                 for(size_t i = 0; i < pack.prim_index.size(); ++i) {
1381                         if ((pack.prim_type[i] & PRIMITIVE_ALL_TRIANGLE) != 0) {
1382                                 tri_prim_index[pack.prim_index[i]] = pack.prim_tri_index[i];
1383                         }
1384                 }
1385         }
1386
1387         /* Fill in all the arrays. */
1388         if(tri_size != 0) {
1389                 /* normals */
1390                 progress.set_status("Updating Mesh", "Computing normals");
1391
1392                 uint *tri_shader = dscene->tri_shader.resize(tri_size);
1393                 float4 *vnormal = dscene->tri_vnormal.resize(vert_size);
1394                 uint4 *tri_vindex = dscene->tri_vindex.resize(tri_size);
1395                 uint *tri_patch = dscene->tri_patch.resize(tri_size);
1396                 float2 *tri_patch_uv = dscene->tri_patch_uv.resize(vert_size);
1397
1398                 foreach(Mesh *mesh, scene->meshes) {
1399                         mesh->pack_normals(scene,
1400                                            &tri_shader[mesh->tri_offset],
1401                                            &vnormal[mesh->vert_offset]);
1402                         mesh->pack_verts(tri_prim_index,
1403                                          &tri_vindex[mesh->tri_offset],
1404                                          &tri_patch[mesh->tri_offset],
1405                                          &tri_patch_uv[mesh->vert_offset],
1406                                          mesh->vert_offset,
1407                                          mesh->tri_offset);
1408                         if(progress.get_cancel()) return;
1409                 }
1410
1411                 /* vertex coordinates */
1412                 progress.set_status("Updating Mesh", "Copying Mesh to device");
1413
1414                 device->tex_alloc("__tri_shader", dscene->tri_shader);
1415                 device->tex_alloc("__tri_vnormal", dscene->tri_vnormal);
1416                 device->tex_alloc("__tri_vindex", dscene->tri_vindex);
1417                 device->tex_alloc("__tri_patch", dscene->tri_patch);
1418                 device->tex_alloc("__tri_patch_uv", dscene->tri_patch_uv);
1419         }
1420
1421         if(curve_size != 0) {
1422                 progress.set_status("Updating Mesh", "Copying Strands to device");
1423
1424                 float4 *curve_keys = dscene->curve_keys.resize(curve_key_size);
1425                 float4 *curves = dscene->curves.resize(curve_size);
1426
1427                 foreach(Mesh *mesh, scene->meshes) {
1428                         mesh->pack_curves(scene, &curve_keys[mesh->curvekey_offset], &curves[mesh->curve_offset], mesh->curvekey_offset);
1429                         if(progress.get_cancel()) return;
1430                 }
1431
1432                 device->tex_alloc("__curve_keys", dscene->curve_keys);
1433                 device->tex_alloc("__curves", dscene->curves);
1434         }
1435
1436         if(patch_size != 0) {
1437                 progress.set_status("Updating Mesh", "Copying Patches to device");
1438
1439                 uint *patch_data = dscene->patches.resize(patch_size);
1440
1441                 foreach(Mesh *mesh, scene->meshes) {
1442                         mesh->pack_patches(&patch_data[mesh->patch_offset], mesh->vert_offset, mesh->face_offset, mesh->corner_offset);
1443                         if(progress.get_cancel()) return;
1444                 }
1445
1446                 device->tex_alloc("__patches", dscene->patches);
1447         }
1448
1449         if(for_displacement) {
1450                 float4 *prim_tri_verts = dscene->prim_tri_verts.resize(tri_size * 3);
1451                 foreach(Mesh *mesh, scene->meshes) {
1452                         for(size_t i = 0; i < mesh->num_triangles(); ++i) {
1453                                 Mesh::Triangle t = mesh->get_triangle(i);
1454                                 size_t offset = 3 * (i + mesh->tri_offset);
1455                                 prim_tri_verts[offset + 0] = float3_to_float4(mesh->verts[t.v[0]]);
1456                                 prim_tri_verts[offset + 1] = float3_to_float4(mesh->verts[t.v[1]]);
1457                                 prim_tri_verts[offset + 2] = float3_to_float4(mesh->verts[t.v[2]]);
1458                         }
1459                 }
1460                 device->tex_alloc("__prim_tri_verts", dscene->prim_tri_verts);
1461         }
1462 }
1463
1464 void MeshManager::device_update_bvh(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1465 {
1466         /* bvh build */
1467         progress.set_status("Updating Scene BVH", "Building");
1468
1469         VLOG(1) << (scene->params.use_qbvh ? "Using QBVH optimization structure"
1470                                            : "Using regular BVH optimization structure");
1471
1472         BVHParams bparams;
1473         bparams.top_level = true;
1474         bparams.use_qbvh = scene->params.use_qbvh;
1475         bparams.use_spatial_split = scene->params.use_bvh_spatial_split;
1476         bparams.use_unaligned_nodes = dscene->data.bvh.have_curves &&
1477                                       scene->params.use_bvh_unaligned_nodes;
1478
1479         delete bvh;
1480         bvh = BVH::create(bparams, scene->objects);
1481         bvh->build(progress);
1482
1483         if(progress.get_cancel()) return;
1484
1485         /* copy to device */
1486         progress.set_status("Updating Scene BVH", "Copying BVH to device");
1487
1488         PackedBVH& pack = bvh->pack;
1489
1490         if(pack.nodes.size()) {
1491                 dscene->bvh_nodes.reference((float4*)&pack.nodes[0], pack.nodes.size());
1492                 device->tex_alloc("__bvh_nodes", dscene->bvh_nodes);
1493         }
1494         if(pack.leaf_nodes.size()) {
1495                 dscene->bvh_leaf_nodes.reference((float4*)&pack.leaf_nodes[0], pack.leaf_nodes.size());
1496                 device->tex_alloc("__bvh_leaf_nodes", dscene->bvh_leaf_nodes);
1497         }
1498         if(pack.object_node.size()) {
1499                 dscene->object_node.reference((uint*)&pack.object_node[0], pack.object_node.size());
1500                 device->tex_alloc("__object_node", dscene->object_node);
1501         }
1502         if(pack.prim_tri_index.size()) {
1503                 dscene->prim_tri_index.reference((uint*)&pack.prim_tri_index[0], pack.prim_tri_index.size());
1504                 device->tex_alloc("__prim_tri_index", dscene->prim_tri_index);
1505         }
1506         if(pack.prim_tri_verts.size()) {
1507                 dscene->prim_tri_verts.reference((float4*)&pack.prim_tri_verts[0], pack.prim_tri_verts.size());
1508                 device->tex_alloc("__prim_tri_verts", dscene->prim_tri_verts);
1509         }
1510         if(pack.prim_type.size()) {
1511                 dscene->prim_type.reference((uint*)&pack.prim_type[0], pack.prim_type.size());
1512                 device->tex_alloc("__prim_type", dscene->prim_type);
1513         }
1514         if(pack.prim_visibility.size()) {
1515                 dscene->prim_visibility.reference((uint*)&pack.prim_visibility[0], pack.prim_visibility.size());
1516                 device->tex_alloc("__prim_visibility", dscene->prim_visibility);
1517         }
1518         if(pack.prim_index.size()) {
1519                 dscene->prim_index.reference((uint*)&pack.prim_index[0], pack.prim_index.size());
1520                 device->tex_alloc("__prim_index", dscene->prim_index);
1521         }
1522         if(pack.prim_object.size()) {
1523                 dscene->prim_object.reference((uint*)&pack.prim_object[0], pack.prim_object.size());
1524                 device->tex_alloc("__prim_object", dscene->prim_object);
1525         }
1526
1527         dscene->data.bvh.root = pack.root_index;
1528         dscene->data.bvh.use_qbvh = scene->params.use_qbvh;
1529 }
1530
1531 void MeshManager::device_update_flags(Device * /*device*/,
1532                                       DeviceScene * /*dscene*/,
1533                                       Scene * scene,
1534                                       Progress& /*progress*/)
1535 {
1536         if(!need_update && !need_flags_update) {
1537                 return;
1538         }
1539         /* update flags */
1540         foreach(Mesh *mesh, scene->meshes) {
1541                 mesh->has_volume = false;
1542                 foreach(const Shader *shader, mesh->used_shaders) {
1543                         if(shader->has_volume) {
1544                                 mesh->has_volume = true;
1545                         }
1546                         if(shader->has_surface_bssrdf) {
1547                                 mesh->has_surface_bssrdf = true;
1548                         }
1549                 }
1550         }
1551         need_flags_update = false;
1552 }
1553
1554 void MeshManager::device_update_displacement_images(Device *device,
1555                                                     DeviceScene *dscene,
1556                                                     Scene *scene,
1557                                                     Progress& progress)
1558 {
1559         progress.set_status("Updating Displacement Images");
1560         TaskPool pool;
1561         ImageManager *image_manager = scene->image_manager;
1562         set<int> bump_images;
1563         foreach(Mesh *mesh, scene->meshes) {
1564                 if(mesh->need_update) {
1565                         foreach(Shader *shader, mesh->used_shaders) {
1566                                 if(shader->graph_bump == NULL) {
1567                                         continue;
1568                                 }
1569                                 foreach(ShaderNode* node, shader->graph_bump->nodes) {
1570                                         if(node->special_type != SHADER_SPECIAL_TYPE_IMAGE_SLOT) {
1571                                                 continue;
1572                                         }
1573                                         if(device->info.pack_images) {
1574                                                 /* If device requires packed images we need to update all
1575                                                  * images now, even if they're not used for displacement.
1576                                                  */
1577                                                 image_manager->device_update(device,
1578                                                                              dscene,
1579                                                                              progress);
1580                                                 return;
1581                                         }
1582                                         ImageSlotTextureNode *image_node = static_cast<ImageSlotTextureNode*>(node);
1583                                         int slot = image_node->slot;
1584                                         if(slot != -1) {
1585                                                 bump_images.insert(slot);
1586                                         }
1587                                 }
1588                         }
1589                 }
1590         }
1591         foreach(int slot, bump_images) {
1592                 pool.push(function_bind(&ImageManager::device_update_slot,
1593                                         image_manager,
1594                                         device,
1595                                         dscene,
1596                                         slot,
1597                                         &progress));
1598         }
1599         pool.wait_work();
1600 }
1601
1602 void MeshManager::device_update(Device *device, DeviceScene *dscene, Scene *scene, Progress& progress)
1603 {
1604         if(!need_update)
1605                 return;
1606
1607         VLOG(1) << "Total " << scene->meshes.size() << " meshes.";
1608
1609         /* Update normals. */
1610         foreach(Mesh *mesh, scene->meshes) {
1611                 foreach(Shader *shader, mesh->used_shaders) {
1612                         if(shader->need_update_attributes)
1613                                 mesh->need_update = true;
1614                 }
1615
1616                 if(mesh->need_update) {
1617                         mesh->add_face_normals();
1618                         mesh->add_vertex_normals();
1619
1620                         if(progress.get_cancel()) return;
1621                 }
1622         }
1623
1624         /* Update images needed for true displacement. */
1625         bool true_displacement_used = false;
1626         bool old_need_object_flags_update = false;
1627         foreach(Mesh *mesh, scene->meshes) {
1628                 if(mesh->need_update &&
1629                    mesh->displacement_method != Mesh::DISPLACE_BUMP)
1630                 {
1631                         true_displacement_used = true;
1632                         break;
1633                 }
1634         }
1635         if(true_displacement_used) {
1636                 VLOG(1) << "Updating images used for true displacement.";
1637                 device_update_displacement_images(device, dscene, scene, progress);
1638                 old_need_object_flags_update = scene->object_manager->need_flags_update;
1639                 scene->object_manager->device_update_flags(device,
1640                                                            dscene,
1641                                                            scene,
1642                                                            progress,
1643                                                            false);
1644         }
1645
1646         /* Device update. */
1647         device_free(device, dscene);
1648
1649         mesh_calc_offset(scene);
1650         if(true_displacement_used) {
1651                 device_update_mesh(device, dscene, scene, true, progress);
1652         }
1653         if(progress.get_cancel()) return;
1654
1655         device_update_attributes(device, dscene, scene, progress);
1656         if(progress.get_cancel()) return;
1657
1658         /* Update displacement. */
1659         bool displacement_done = false;
1660         foreach(Mesh *mesh, scene->meshes) {
1661                 if(mesh->need_update &&
1662                    displace(device, dscene, scene, mesh, progress))
1663                 {
1664                         displacement_done = true;
1665                 }
1666         }
1667
1668         /* TODO: properly handle cancel halfway displacement */
1669         if(progress.get_cancel()) return;
1670
1671         /* Device re-update after displacement. */
1672         if(displacement_done) {
1673                 device_free(device, dscene);
1674
1675                 device_update_attributes(device, dscene, scene, progress);
1676                 if(progress.get_cancel()) return;
1677         }
1678
1679         /* Update bvh. */
1680         size_t i = 0, num_bvh = 0;
1681         foreach(Mesh *mesh, scene->meshes) {
1682                 if(mesh->need_update && mesh->need_build_bvh()) {
1683                         num_bvh++;
1684                 }
1685         }
1686
1687         TaskPool pool;
1688
1689         foreach(Mesh *mesh, scene->meshes) {
1690                 if(mesh->need_update) {
1691                         pool.push(function_bind(&Mesh::compute_bvh,
1692                                                 mesh,
1693                                                 dscene,
1694                                                 &scene->params,
1695                                                 &progress,
1696                                                 i,
1697                                                 num_bvh));
1698                         if(mesh->need_build_bvh()) {
1699                                 i++;
1700                         }
1701                 }
1702         }
1703
1704         TaskPool::Summary summary;
1705         pool.wait_work(&summary);
1706         VLOG(2) << "Objects BVH build pool statistics:\n"
1707                 << summary.full_report();
1708
1709         foreach(Shader *shader, scene->shaders) {
1710                 shader->need_update_attributes = false;
1711         }
1712
1713 #ifdef __OBJECT_MOTION__
1714         Scene::MotionType need_motion = scene->need_motion(device->info.advanced_shading);
1715         bool motion_blur = need_motion == Scene::MOTION_BLUR;
1716 #else
1717         bool motion_blur = false;
1718 #endif
1719
1720         /* Update objects. */
1721         vector<Object *> volume_objects;
1722         foreach(Object *object, scene->objects) {
1723                 object->compute_bounds(motion_blur);
1724         }
1725
1726         if(progress.get_cancel()) return;
1727
1728         device_update_bvh(device, dscene, scene, progress);
1729         if(progress.get_cancel()) return;
1730
1731         device_update_mesh(device, dscene, scene, false, progress);
1732         if(progress.get_cancel()) return;
1733
1734         need_update = false;
1735
1736         if(true_displacement_used) {
1737                 /* Re-tag flags for update, so they're re-evaluated
1738                  * for meshes with correct bounding boxes.
1739                  *
1740                  * This wouldn't cause wrong results, just true
1741                  * displacement might be less optimal ot calculate.
1742                  */
1743                 scene->object_manager->need_flags_update = old_need_object_flags_update;
1744         }
1745 }
1746
1747 void MeshManager::device_free(Device *device, DeviceScene *dscene)
1748 {
1749         device->tex_free(dscene->bvh_nodes);
1750         device->tex_free(dscene->bvh_leaf_nodes);
1751         device->tex_free(dscene->object_node);
1752         device->tex_free(dscene->prim_tri_verts);
1753         device->tex_free(dscene->prim_tri_index);
1754         device->tex_free(dscene->prim_type);
1755         device->tex_free(dscene->prim_visibility);
1756         device->tex_free(dscene->prim_index);
1757         device->tex_free(dscene->prim_object);
1758         device->tex_free(dscene->tri_shader);
1759         device->tex_free(dscene->tri_vnormal);
1760         device->tex_free(dscene->tri_vindex);
1761         device->tex_free(dscene->tri_patch);
1762         device->tex_free(dscene->tri_patch_uv);
1763         device->tex_free(dscene->curves);
1764         device->tex_free(dscene->curve_keys);
1765         device->tex_free(dscene->patches);
1766         device->tex_free(dscene->attributes_map);
1767         device->tex_free(dscene->attributes_float);
1768         device->tex_free(dscene->attributes_float3);
1769         device->tex_free(dscene->attributes_uchar4);
1770
1771         dscene->bvh_nodes.clear();
1772         dscene->object_node.clear();
1773         dscene->prim_tri_verts.clear();
1774         dscene->prim_tri_index.clear();
1775         dscene->prim_type.clear();
1776         dscene->prim_visibility.clear();
1777         dscene->prim_index.clear();
1778         dscene->prim_object.clear();
1779         dscene->tri_shader.clear();
1780         dscene->tri_vnormal.clear();
1781         dscene->tri_vindex.clear();
1782         dscene->tri_patch.clear();
1783         dscene->tri_patch_uv.clear();
1784         dscene->curves.clear();
1785         dscene->curve_keys.clear();
1786         dscene->patches.clear();
1787         dscene->attributes_map.clear();
1788         dscene->attributes_float.clear();
1789         dscene->attributes_float3.clear();
1790         dscene->attributes_uchar4.clear();
1791
1792 #ifdef WITH_OSL
1793         OSLGlobals *og = (OSLGlobals*)device->osl_memory();
1794
1795         if(og) {
1796                 og->object_name_map.clear();
1797                 og->attribute_map.clear();
1798                 og->object_names.clear();
1799         }
1800 #endif
1801 }
1802
1803 void MeshManager::tag_update(Scene *scene)
1804 {
1805         need_update = true;
1806         scene->object_manager->need_update = true;
1807 }
1808
1809 bool Mesh::need_attribute(Scene *scene, AttributeStandard std)
1810 {
1811         if(std == ATTR_STD_NONE)
1812                 return false;
1813         
1814         if(scene->need_global_attribute(std))
1815                 return true;
1816
1817         foreach(Shader *shader, used_shaders)
1818                 if(shader->attributes.find(std))
1819                         return true;
1820         
1821         return false;
1822 }
1823
1824 bool Mesh::need_attribute(Scene * /*scene*/, ustring name)
1825 {
1826         if(name == ustring())
1827                 return false;
1828
1829         foreach(Shader *shader, used_shaders)
1830                 if(shader->attributes.find(name))
1831                         return true;
1832         
1833         return false;
1834 }
1835
1836 CCL_NAMESPACE_END
1837