Cycles: Cleanup, naming of variable
[blender-staging.git] / intern / cycles / blender / blender_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 "render/mesh.h"
18 #include "render/object.h"
19 #include "render/scene.h"
20 #include "render/camera.h"
21
22 #include "blender/blender_sync.h"
23 #include "blender/blender_session.h"
24 #include "blender/blender_util.h"
25
26 #include "subd/subd_patch.h"
27 #include "subd/subd_split.h"
28
29 #include "util/util_algorithm.h"
30 #include "util/util_foreach.h"
31 #include "util/util_logging.h"
32 #include "util/util_math.h"
33
34 #include "mikktspace.h"
35
36 CCL_NAMESPACE_BEGIN
37
38 /* Per-face bit flags. */
39 enum {
40         /* Face has no special flags. */
41         FACE_FLAG_NONE      = (0 << 0),
42         /* Quad face was split using 1-3 diagonal. */
43         FACE_FLAG_DIVIDE_13 = (1 << 0),
44         /* Quad face was split using 2-4 diagonal. */
45         FACE_FLAG_DIVIDE_24 = (1 << 1),
46 };
47
48 /* Get vertex indices to create triangles from a given face.
49  *
50  * Two triangles has vertex indices in the original Blender-side face.
51  * If face is already a quad tri_b will not be initialized.
52  */
53 inline void face_split_tri_indices(const int face_flag,
54                                    int tri_a[3],
55                                    int tri_b[3])
56 {
57         if(face_flag & FACE_FLAG_DIVIDE_24) {
58                 tri_a[0] = 0;
59                 tri_a[1] = 1;
60                 tri_a[2] = 3;
61
62                 tri_b[0] = 2;
63                 tri_b[1] = 3;
64                 tri_b[2] = 1;
65         }
66         else /*if(face_flag & FACE_FLAG_DIVIDE_13)*/ {
67                 assert(face_flag & FACE_FLAG_DIVIDE_13);
68
69                 tri_a[0] = 0;
70                 tri_a[1] = 1;
71                 tri_a[2] = 2;
72
73                 tri_b[0] = 0;
74                 tri_b[1] = 2;
75                 tri_b[2] = 3;
76         }
77 }
78
79 /* Tangent Space */
80
81 struct MikkUserData {
82         MikkUserData(const BL::Mesh& b_mesh,
83                      BL::MeshTextureFaceLayer *layer,
84                      int num_faces)
85                 : b_mesh(b_mesh),
86                   layer(layer),
87                   num_faces(num_faces)
88         {
89                 tangent.resize(num_faces*4);
90         }
91
92         BL::Mesh b_mesh;
93         BL::MeshTextureFaceLayer *layer;
94         int num_faces;
95         vector<float4> tangent;
96 };
97
98 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
99 {
100         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
101         return userdata->num_faces;
102 }
103
104 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context, const int face_num)
105 {
106         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
107         BL::MeshTessFace f = userdata->b_mesh.tessfaces[face_num];
108         int4 vi = get_int4(f.vertices_raw());
109
110         return (vi[3] == 0)? 3: 4;
111 }
112
113 static void mikk_get_position(const SMikkTSpaceContext *context, float P[3], const int face_num, const int vert_num)
114 {
115         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
116         BL::MeshTessFace f = userdata->b_mesh.tessfaces[face_num];
117         int4 vi = get_int4(f.vertices_raw());
118         BL::MeshVertex v = userdata->b_mesh.vertices[vi[vert_num]];
119         float3 vP = get_float3(v.co());
120
121         P[0] = vP.x;
122         P[1] = vP.y;
123         P[2] = vP.z;
124 }
125
126 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context, float uv[2], const int face_num, const int vert_num)
127 {
128         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
129         if(userdata->layer != NULL) {
130                 BL::MeshTextureFace tf = userdata->layer->data[face_num];
131                 float3 tfuv;
132
133                 switch(vert_num) {
134                         case 0:
135                                 tfuv = get_float3(tf.uv1());
136                                 break;
137                         case 1:
138                                 tfuv = get_float3(tf.uv2());
139                                 break;
140                         case 2:
141                                 tfuv = get_float3(tf.uv3());
142                                 break;
143                         default:
144                                 tfuv = get_float3(tf.uv4());
145                                 break;
146                 }
147
148                 uv[0] = tfuv.x;
149                 uv[1] = tfuv.y;
150         }
151         else {
152                 int vert_idx = userdata->b_mesh.tessfaces[face_num].vertices()[vert_num];
153                 float3 orco =
154                         get_float3(userdata->b_mesh.vertices[vert_idx].undeformed_co());
155                 float2 tmp = map_to_sphere(make_float3(orco[0], orco[1], orco[2]));
156                 uv[0] = tmp.x;
157                 uv[1] = tmp.y;
158         }
159 }
160
161 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
162 {
163         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
164         BL::MeshTessFace f = userdata->b_mesh.tessfaces[face_num];
165         float3 vN;
166
167         if(f.use_smooth()) {
168                 int4 vi = get_int4(f.vertices_raw());
169                 BL::MeshVertex v = userdata->b_mesh.vertices[vi[vert_num]];
170                 vN = get_float3(v.normal());
171         }
172         else {
173                 vN = get_float3(f.normal());
174         }
175
176         N[0] = vN.x;
177         N[1] = vN.y;
178         N[2] = vN.z;
179 }
180
181 static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
182 {
183         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
184
185         userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
186 }
187
188 static void mikk_compute_tangents(BL::Mesh& b_mesh,
189                                   BL::MeshTextureFaceLayer *b_layer,
190                                   Mesh *mesh,
191                                   const vector<int>& nverts,
192                                   const vector<int>& face_flags,
193                                   bool need_sign,
194                                   bool active_render)
195 {
196         /* setup userdata */
197         MikkUserData userdata(b_mesh, b_layer, nverts.size());
198
199         /* setup interface */
200         SMikkTSpaceInterface sm_interface;
201         memset(&sm_interface, 0, sizeof(sm_interface));
202         sm_interface.m_getNumFaces = mikk_get_num_faces;
203         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
204         sm_interface.m_getPosition = mikk_get_position;
205         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
206         sm_interface.m_getNormal = mikk_get_normal;
207         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
208
209         /* setup context */
210         SMikkTSpaceContext context;
211         memset(&context, 0, sizeof(context));
212         context.m_pUserData = &userdata;
213         context.m_pInterface = &sm_interface;
214
215         /* compute tangents */
216         genTangSpaceDefault(&context);
217
218         /* create tangent attributes */
219         Attribute *attr;
220         ustring name;
221         if(b_layer != NULL)
222                 name = ustring((string(b_layer->name().c_str()) + ".tangent").c_str());
223         else
224                 name = ustring("orco.tangent");
225
226         if(active_render)
227                 attr = mesh->attributes.add(ATTR_STD_UV_TANGENT, name);
228         else
229                 attr = mesh->attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
230
231         float3 *tangent = attr->data_float3();
232
233         /* create bitangent sign attribute */
234         float *tangent_sign = NULL;
235
236         if(need_sign) {
237                 Attribute *attr_sign;
238                 ustring name_sign;
239                 if(b_layer != NULL)
240                         name_sign = ustring((string(b_layer->name().c_str()) + ".tangent_sign").c_str());
241                 else
242                         name_sign = ustring("orco.tangent_sign");
243
244                 if(active_render)
245                         attr_sign = mesh->attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
246                 else
247                         attr_sign = mesh->attributes.add(name_sign, TypeDesc::TypeFloat, ATTR_ELEMENT_CORNER);
248
249                 tangent_sign = attr_sign->data_float();
250         }
251
252         for(int i = 0; i < nverts.size(); i++) {
253                 int tri_a[3], tri_b[3];
254                 face_split_tri_indices(face_flags[i], tri_a, tri_b);
255
256                 tangent[0] = float4_to_float3(userdata.tangent[i*4 + tri_a[0]]);
257                 tangent[1] = float4_to_float3(userdata.tangent[i*4 + tri_a[1]]);
258                 tangent[2] = float4_to_float3(userdata.tangent[i*4 + tri_a[2]]);
259                 tangent += 3;
260
261                 if(tangent_sign) {
262                         tangent_sign[0] = userdata.tangent[i*4 + tri_a[0]].w;
263                         tangent_sign[1] = userdata.tangent[i*4 + tri_a[1]].w;
264                         tangent_sign[2] = userdata.tangent[i*4 + tri_a[2]].w;
265                         tangent_sign += 3;
266                 }
267
268                 if(nverts[i] == 4) {
269                         tangent[0] = float4_to_float3(userdata.tangent[i*4 + tri_b[0]]);
270                         tangent[1] = float4_to_float3(userdata.tangent[i*4 + tri_b[1]]);
271                         tangent[2] = float4_to_float3(userdata.tangent[i*4 + tri_b[2]]);
272                         tangent += 3;
273
274                         if(tangent_sign) {
275                                 tangent_sign[0] = userdata.tangent[i*4 + tri_b[0]].w;
276                                 tangent_sign[1] = userdata.tangent[i*4 + tri_b[1]].w;
277                                 tangent_sign[2] = userdata.tangent[i*4 + tri_b[2]].w;
278                                 tangent_sign += 3;
279                         }
280                 }
281         }
282 }
283
284 /* Create Volume Attribute */
285
286 static void create_mesh_volume_attribute(BL::Object& b_ob,
287                                          Mesh *mesh,
288                                          ImageManager *image_manager,
289                                          AttributeStandard std,
290                                          float frame)
291 {
292         BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
293
294         if(!b_domain)
295                 return;
296
297         Attribute *attr = mesh->attributes.add(std);
298         VoxelAttribute *volume_data = attr->data_voxel();
299         bool is_float, is_linear;
300         bool animated = false;
301
302         volume_data->manager = image_manager;
303         volume_data->slot = image_manager->add_image(
304                 Attribute::standard_name(std),
305                 b_ob.ptr.data,
306                 animated,
307                 frame,
308                 is_float,
309                 is_linear,
310                 INTERPOLATION_LINEAR,
311                 EXTENSION_CLIP,
312                 true);
313 }
314
315 static void create_mesh_volume_attributes(Scene *scene,
316                                           BL::Object& b_ob,
317                                           Mesh *mesh,
318                                           float frame)
319 {
320         /* for smoke volume rendering */
321         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_DENSITY))
322                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_DENSITY, frame);
323         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_COLOR))
324                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_COLOR, frame);
325         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_FLAME))
326                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_FLAME, frame);
327         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_HEAT))
328                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_HEAT, frame);
329         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_VELOCITY))
330                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_VELOCITY, frame);
331 }
332
333 /* Create vertex color attributes. */
334 static void attr_create_vertex_color(Scene *scene,
335                                      Mesh *mesh,
336                                      BL::Mesh& b_mesh,
337                                      const vector<int>& nverts,
338                                      const vector<int>& face_flags,
339                                      bool subdivision)
340 {
341         if(subdivision) {
342                 BL::Mesh::vertex_colors_iterator l;
343
344                 for(b_mesh.vertex_colors.begin(l); l != b_mesh.vertex_colors.end(); ++l) {
345                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
346                                 continue;
347
348                         Attribute *attr = mesh->subd_attributes.add(ustring(l->name().c_str()),
349                                                                     TypeDesc::TypeColor,
350                                                                     ATTR_ELEMENT_CORNER_BYTE);
351
352                         BL::Mesh::polygons_iterator p;
353                         uchar4 *cdata = attr->data_uchar4();
354
355                         for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
356                                 int n = p->loop_total();
357                                 for(int i = 0; i < n; i++) {
358                                         float3 color = get_float3(l->data[p->loop_start() + i].color());
359                                         *(cdata++) = color_float_to_byte(color_srgb_to_scene_linear_v3(color));
360                                 }
361                         }
362                 }
363         }
364         else {
365                 BL::Mesh::tessface_vertex_colors_iterator l;
366                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
367                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
368                                 continue;
369
370                         Attribute *attr = mesh->attributes.add(ustring(l->name().c_str()),
371                                                                TypeDesc::TypeColor,
372                                                                ATTR_ELEMENT_CORNER_BYTE);
373
374                         BL::MeshColorLayer::data_iterator c;
375                         uchar4 *cdata = attr->data_uchar4();
376                         size_t i = 0;
377
378                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
379                                 int tri_a[3], tri_b[3];
380                                 face_split_tri_indices(face_flags[i], tri_a, tri_b);
381
382                                 uchar4 colors[4];
383                                 colors[0] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color1())));
384                                 colors[1] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color2())));
385                                 colors[2] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color3())));
386                                 if(nverts[i] == 4) {
387                                         colors[3] = color_float_to_byte(color_srgb_to_scene_linear_v3(get_float3(c->color4())));
388                                 }
389
390                                 cdata[0] = colors[tri_a[0]];
391                                 cdata[1] = colors[tri_a[1]];
392                                 cdata[2] = colors[tri_a[2]];
393
394                                 if(nverts[i] == 4) {
395                                         cdata[3] = colors[tri_b[0]];
396                                         cdata[4] = colors[tri_b[1]];
397                                         cdata[5] = colors[tri_b[2]];
398                                         cdata += 6;
399                                 }
400                                 else
401                                         cdata += 3;
402                         }
403                 }
404         }
405 }
406
407 /* Create uv map attributes. */
408 static void attr_create_uv_map(Scene *scene,
409                                Mesh *mesh,
410                                BL::Mesh& b_mesh,
411                                const vector<int>& nverts,
412                                const vector<int>& face_flags,
413                                bool subdivision,
414                                bool subdivide_uvs)
415 {
416         if(subdivision) {
417                 BL::Mesh::uv_layers_iterator l;
418                 int i = 0;
419
420                 for(b_mesh.uv_layers.begin(l); l != b_mesh.uv_layers.end(); ++l, ++i) {
421                         bool active_render = b_mesh.uv_textures[i].active_render();
422                         AttributeStandard std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
423                         ustring name = ustring(l->name().c_str());
424
425                         /* UV map */
426                         if(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)) {
427                                 Attribute *attr;
428
429                                 if(active_render)
430                                         attr = mesh->subd_attributes.add(std, name);
431                                 else
432                                         attr = mesh->subd_attributes.add(name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
433
434                                 if(subdivide_uvs) {
435                                         attr->flags |= ATTR_SUBDIVIDED;
436                                 }
437
438                                 BL::Mesh::polygons_iterator p;
439                                 float3 *fdata = attr->data_float3();
440
441                                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
442                                         int n = p->loop_total();
443                                         for(int j = 0; j < n; j++) {
444                                                 *(fdata++) = get_float3(l->data[p->loop_start() + j].uv());
445                                         }
446                                 }
447                         }
448                 }
449         }
450         else if(b_mesh.tessface_uv_textures.length() != 0) {
451                 BL::Mesh::tessface_uv_textures_iterator l;
452
453                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
454                         bool active_render = l->active_render();
455                         AttributeStandard std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
456                         ustring name = ustring(l->name().c_str());
457
458                         /* UV map */
459                         if(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)) {
460                                 Attribute *attr;
461
462                                 if(active_render)
463                                         attr = mesh->attributes.add(std, name);
464                                 else
465                                         attr = mesh->attributes.add(name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
466
467                                 BL::MeshTextureFaceLayer::data_iterator t;
468                                 float3 *fdata = attr->data_float3();
469                                 size_t i = 0;
470
471                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
472                                         int tri_a[3], tri_b[3];
473                                         face_split_tri_indices(face_flags[i], tri_a, tri_b);
474
475                                         float3 uvs[4];
476                                         uvs[0] = get_float3(t->uv1());
477                                         uvs[1] = get_float3(t->uv2());
478                                         uvs[2] = get_float3(t->uv3());
479                                         if(nverts[i] == 4) {
480                                                 uvs[3] = get_float3(t->uv4());
481                                         }
482
483                                         fdata[0] = uvs[tri_a[0]];
484                                         fdata[1] = uvs[tri_a[1]];
485                                         fdata[2] = uvs[tri_a[2]];
486                                         fdata += 3;
487
488                                         if(nverts[i] == 4) {
489                                                 fdata[0] = uvs[tri_b[0]];
490                                                 fdata[1] = uvs[tri_b[1]];
491                                                 fdata[2] = uvs[tri_b[2]];
492                                                 fdata += 3;
493                                         }
494                                 }
495                         }
496
497                         /* UV tangent */
498                         std = (active_render)? ATTR_STD_UV_TANGENT: ATTR_STD_NONE;
499                         name = ustring((string(l->name().c_str()) + ".tangent").c_str());
500
501                         if(mesh->need_attribute(scene, name) || (active_render && mesh->need_attribute(scene, std))) {
502                                 std = (active_render)? ATTR_STD_UV_TANGENT_SIGN: ATTR_STD_NONE;
503                                 name = ustring((string(l->name().c_str()) + ".tangent_sign").c_str());
504                                 bool need_sign = (mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std));
505
506                                 mikk_compute_tangents(b_mesh,
507                                                       &(*l),
508                                                       mesh,
509                                                       nverts,
510                                                       face_flags,
511                                                       need_sign,
512                                                       active_render);
513                         }
514                 }
515         }
516         else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
517                 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
518                 mikk_compute_tangents(b_mesh,
519                                       NULL,
520                                       mesh,
521                                       nverts,
522                                       face_flags,
523                                       need_sign,
524                                       true);
525         }
526 }
527
528 /* Create vertex pointiness attributes. */
529
530 /* Compare vertices by sum of their coordinates. */
531 class VertexAverageComparator {
532 public:
533         VertexAverageComparator(const array<float3>& verts)
534                 : verts_(verts) {
535         }
536
537         bool operator()(const int& vert_idx_a, const int& vert_idx_b)
538         {
539                 const float3 &vert_a = verts_[vert_idx_a];
540                 const float3 &vert_b = verts_[vert_idx_b];
541                 if(vert_a == vert_b) {
542                         /* Special case for doubles, so we ensure ordering. */
543                         return vert_idx_a > vert_idx_b;
544                 }
545                 const float x1 = vert_a.x + vert_a.y + vert_a.z;
546                 const float x2 = vert_b.x + vert_b.y + vert_b.z;
547                 return x1 < x2;
548         }
549
550 protected:
551         const array<float3>& verts_;
552 };
553
554 static void attr_create_pointiness(Scene *scene,
555                                    Mesh *mesh,
556                                    BL::Mesh& b_mesh,
557                                    bool subdivision)
558 {
559         if(!mesh->need_attribute(scene, ATTR_STD_POINTINESS)) {
560                 return;
561         }
562         const int num_verts = b_mesh.vertices.length();
563         if(num_verts == 0) {
564                 return;
565         }
566         /* STEP 1: Find out duplicated vertices and point duplicates to a single
567          *         original vertex.
568          */
569         vector<int> sorted_vert_indeices(num_verts);
570         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
571                 sorted_vert_indeices[vert_index] = vert_index;
572         }
573         VertexAverageComparator compare(mesh->verts);
574         sort(sorted_vert_indeices.begin(), sorted_vert_indeices.end(), compare);
575         /* This array stores index of the original vertex for the given vertex
576          * index.
577          */
578         vector<int> vert_orig_index(num_verts);
579         for(int sorted_vert_index = 0;
580             sorted_vert_index < num_verts;
581             ++sorted_vert_index)
582         {
583                 const int vert_index = sorted_vert_indeices[sorted_vert_index];
584                 const float3 &vert_co = mesh->verts[vert_index];
585                 bool found = false;
586                 for(int other_sorted_vert_index = sorted_vert_index + 1;
587                     other_sorted_vert_index < num_verts;
588                     ++other_sorted_vert_index)
589                 {
590                         const int other_vert_index =
591                                 sorted_vert_indeices[other_sorted_vert_index];
592                         const float3 &other_vert_co = mesh->verts[other_vert_index];
593                         /* We are too far away now, we wouldn't have duplicate. */
594                         if((other_vert_co.x + other_vert_co.y + other_vert_co.z) -
595                            (vert_co.x + vert_co.y + vert_co.z) > 3 * FLT_EPSILON)
596                         {
597                                 break;
598                         }
599                         /* Found duplicate. */
600                         if(len_squared(other_vert_co - vert_co) < FLT_EPSILON) {
601                                 found = true;
602                                 vert_orig_index[vert_index] = other_vert_index;
603                                 break;
604                         }
605                 }
606                 if(!found) {
607                         vert_orig_index[vert_index] = vert_index;
608                 }
609         }
610         /* Make sure we always points to the very first orig vertex. */
611         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
612                 int orig_index = vert_orig_index[vert_index];
613                 while(orig_index != vert_orig_index[orig_index]) {
614                         orig_index = vert_orig_index[orig_index];
615                 }
616                 vert_orig_index[vert_index] = orig_index;
617         }
618         sorted_vert_indeices.free_memory();
619         /* STEP 2: Calculate vertex normals taking into account their possible
620          *         duplicates which gets "welded" together.
621          */
622         vector<float3> vert_normal(num_verts, make_float3(0.0f, 0.0f, 0.0f));
623         /* First we accumulate all vertex normals in the original index. */
624         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
625                 const float3 normal = get_float3(b_mesh.vertices[vert_index].normal());
626                 const int orig_index = vert_orig_index[vert_index];
627                 vert_normal[orig_index] += normal;
628         }
629         /* Then we normalize the accumulated result and flush it to all duplicates
630          * as well.
631          */
632         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
633                 const int orig_index = vert_orig_index[vert_index];
634                 vert_normal[vert_index] = normalize(vert_normal[orig_index]);
635         }
636         /* STEP 3: Calculate pointiness using single ring neighborhood. */
637         vector<int> counter(num_verts, 0);
638         vector<float> raw_data(num_verts, 0.0f);
639         vector<float3> edge_accum(num_verts, make_float3(0.0f, 0.0f, 0.0f));
640         BL::Mesh::edges_iterator e;
641         EdgeMap visited_edges;
642         int edge_index = 0;
643         memset(&counter[0], 0, sizeof(int) * counter.size());
644         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
645                 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
646                           v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
647                 if(visited_edges.exists(v0, v1)) {
648                         continue;
649                 }
650                 visited_edges.insert(v0, v1);
651                 float3 co0 = get_float3(b_mesh.vertices[v0].co()),
652                        co1 = get_float3(b_mesh.vertices[v1].co());
653                 float3 edge = normalize(co1 - co0);
654                 edge_accum[v0] += edge;
655                 edge_accum[v1] += -edge;
656                 ++counter[v0];
657                 ++counter[v1];
658         }
659         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
660                 const int orig_index = vert_orig_index[vert_index];
661                 if(orig_index != vert_index) {
662                         /* Skip duplicates, they'll be overwritten later on. */
663                         continue;
664                 }
665                 if(counter[vert_index] > 0) {
666                         const float3 normal = vert_normal[vert_index];
667                         const float angle =
668                                 safe_acosf(dot(normal,
669                                                edge_accum[vert_index] / counter[vert_index]));
670                         raw_data[vert_index] = angle * M_1_PI_F;
671                 }
672                 else {
673                         raw_data[vert_index] = 0.0f;
674                 }
675         }
676         /* STEP 3: Blur vertices to approximate 2 ring neighborhood. */
677         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
678         Attribute *attr = attributes.add(ATTR_STD_POINTINESS);
679         float *data = attr->data_float();
680         memcpy(data, &raw_data[0], sizeof(float) * raw_data.size());
681         memset(&counter[0], 0, sizeof(int) * counter.size());
682         edge_index = 0;
683         visited_edges.clear();
684         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++edge_index) {
685                 const int v0 = vert_orig_index[b_mesh.edges[edge_index].vertices()[0]],
686                           v1 = vert_orig_index[b_mesh.edges[edge_index].vertices()[1]];
687                 if(visited_edges.exists(v0, v1)) {
688                         continue;
689                 }
690                 visited_edges.insert(v0, v1);
691                 data[v0] += raw_data[v1];
692                 data[v1] += raw_data[v0];
693                 ++counter[v0];
694                 ++counter[v1];
695         }
696         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
697                 data[vert_index] /= counter[vert_index] + 1;
698         }
699         /* STEP 4: Copy attribute to the duplicated vertices. */
700         for(int vert_index = 0; vert_index < num_verts; ++vert_index) {
701                 const int orig_index = vert_orig_index[vert_index];
702                 data[vert_index] = data[orig_index];
703         }
704 }
705
706 /* Create Mesh */
707
708 static void create_mesh(Scene *scene,
709                         Mesh *mesh,
710                         BL::Mesh& b_mesh,
711                         const vector<Shader*>& used_shaders,
712                         bool subdivision = false,
713                         bool subdivide_uvs = true)
714 {
715         /* count vertices and faces */
716         int numverts = b_mesh.vertices.length();
717         int numfaces = (!subdivision) ? b_mesh.tessfaces.length() : b_mesh.polygons.length();
718         int numtris = 0;
719         int numcorners = 0;
720         int numngons = 0;
721         bool use_loop_normals = b_mesh.use_auto_smooth() && (mesh->subdivision_type != Mesh::SUBDIVISION_CATMULL_CLARK);
722
723         BL::Mesh::vertices_iterator v;
724         BL::Mesh::tessfaces_iterator f;
725         BL::Mesh::polygons_iterator p;
726
727         if(!subdivision) {
728                 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
729                         int4 vi = get_int4(f->vertices_raw());
730                         numtris += (vi[3] == 0)? 1: 2;
731                 }
732         }
733         else {
734                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
735                         numngons += (p->loop_total() == 4)? 0: 1;
736                         numcorners += p->loop_total();
737                 }
738         }
739
740         /* allocate memory */
741         mesh->reserve_mesh(numverts, numtris);
742         mesh->reserve_subd_faces(numfaces, numngons, numcorners);
743
744         /* create vertex coordinates and normals */
745         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
746                 mesh->add_vertex(get_float3(v->co()));
747
748         AttributeSet& attributes = (subdivision)? mesh->subd_attributes: mesh->attributes;
749         Attribute *attr_N = attributes.add(ATTR_STD_VERTEX_NORMAL);
750         float3 *N = attr_N->data_float3();
751
752         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
753                 *N = get_float3(v->normal());
754         N = attr_N->data_float3();
755
756         /* create generated coordinates from undeformed coordinates */
757         if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
758                 Attribute *attr = attributes.add(ATTR_STD_GENERATED);
759                 attr->flags |= ATTR_SUBDIVIDED;
760
761                 float3 loc, size;
762                 mesh_texture_space(b_mesh, loc, size);
763
764                 float3 *generated = attr->data_float3();
765                 size_t i = 0;
766
767                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
768                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
769         }
770
771         /* create faces */
772         vector<int> nverts(numfaces);
773         vector<int> face_flags(numfaces, FACE_FLAG_NONE);
774         int fi = 0;
775
776         if(!subdivision) {
777                 for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f, ++fi) {
778                         int4 vi = get_int4(f->vertices_raw());
779                         int n = (vi[3] == 0)? 3: 4;
780                         int shader = clamp(f->material_index(), 0, used_shaders.size()-1);
781                         bool smooth = f->use_smooth() || use_loop_normals;
782
783                         if(use_loop_normals) {
784                                 BL::Array<float, 12> loop_normals = f->split_normals();
785                                 for(int i = 0; i < n; i++) {
786                                         N[vi[i]] = make_float3(loop_normals[i * 3],
787                                                                loop_normals[i * 3 + 1],
788                                                                loop_normals[i * 3 + 2]);
789                                 }
790                         }
791
792                         /* Create triangles.
793                          *
794                          * NOTE: Autosmooth is already taken care about.
795                          */
796                         if(n == 4) {
797                                 if(is_zero(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) ||
798                                    is_zero(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])))
799                                 {
800                                         mesh->add_triangle(vi[0], vi[1], vi[3], shader, smooth);
801                                         mesh->add_triangle(vi[2], vi[3], vi[1], shader, smooth);
802                                         face_flags[fi] |= FACE_FLAG_DIVIDE_24;
803                                 }
804                                 else {
805                                         mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
806                                         mesh->add_triangle(vi[0], vi[2], vi[3], shader, smooth);
807                                         face_flags[fi] |= FACE_FLAG_DIVIDE_13;
808                                 }
809                         }
810                         else {
811                                 mesh->add_triangle(vi[0], vi[1], vi[2], shader, smooth);
812                         }
813
814                         nverts[fi] = n;
815                 }
816         }
817         else {
818                 vector<int> vi;
819
820                 for(b_mesh.polygons.begin(p); p != b_mesh.polygons.end(); ++p) {
821                         int n = p->loop_total();
822                         int shader = clamp(p->material_index(), 0, used_shaders.size()-1);
823                         bool smooth = p->use_smooth() || use_loop_normals;
824
825                         vi.resize(n);
826                         for(int i = 0; i < n; i++) {
827                                 /* NOTE: Autosmooth is already taken care about. */
828                                 vi[i] = b_mesh.loops[p->loop_start() + i].vertex_index();
829                         }
830
831                         /* create subd faces */
832                         mesh->add_subd_face(&vi[0], n, shader, smooth);
833                 }
834         }
835
836         /* Create all needed attributes.
837          * The calculate functions will check whether they're needed or not.
838          */
839         attr_create_pointiness(scene, mesh, b_mesh, subdivision);
840         attr_create_vertex_color(scene, mesh, b_mesh, nverts, face_flags, subdivision);
841         attr_create_uv_map(scene, mesh, b_mesh, nverts, face_flags, subdivision, subdivide_uvs);
842
843         /* for volume objects, create a matrix to transform from object space to
844          * mesh texture space. this does not work with deformations but that can
845          * probably only be done well with a volume grid mapping of coordinates */
846         if(mesh->need_attribute(scene, ATTR_STD_GENERATED_TRANSFORM)) {
847                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED_TRANSFORM);
848                 Transform *tfm = attr->data_transform();
849
850                 float3 loc, size;
851                 mesh_texture_space(b_mesh, loc, size);
852
853                 *tfm = transform_translate(-loc)*transform_scale(size);
854         }
855 }
856
857 static void create_subd_mesh(Scene *scene,
858                              Mesh *mesh,
859                              BL::Object& b_ob,
860                              BL::Mesh& b_mesh,
861                              const vector<Shader*>& used_shaders,
862                              float dicing_rate,
863                              int max_subdivisions)
864 {
865         BL::SubsurfModifier subsurf_mod(b_ob.modifiers[b_ob.modifiers.length()-1]);
866         bool subdivide_uvs = subsurf_mod.use_subsurf_uv();
867
868         create_mesh(scene, mesh, b_mesh, used_shaders, true, subdivide_uvs);
869
870         /* export creases */
871         size_t num_creases = 0;
872         BL::Mesh::edges_iterator e;
873
874         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
875                 if(e->crease() != 0.0f) {
876                         num_creases++;
877                 }
878         }
879
880         mesh->subd_creases.resize(num_creases);
881
882         Mesh::SubdEdgeCrease* crease = mesh->subd_creases.data();
883         for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e) {
884                 if(e->crease() != 0.0f) {
885                         crease->v[0] = e->vertices()[0];
886                         crease->v[1] = e->vertices()[1];
887                         crease->crease = e->crease();
888
889                         crease++;
890                 }
891         }
892
893         /* set subd params */
894         if(!mesh->subd_params) {
895                 mesh->subd_params = new SubdParams(mesh);
896         }
897         SubdParams& sdparams = *mesh->subd_params;
898
899         PointerRNA cobj = RNA_pointer_get(&b_ob.ptr, "cycles");
900
901         sdparams.dicing_rate = max(0.1f, RNA_float_get(&cobj, "dicing_rate") * dicing_rate);
902         sdparams.max_level = max_subdivisions;
903
904         scene->camera->update();
905         sdparams.camera = scene->camera;
906         sdparams.objecttoworld = get_transform(b_ob.matrix_world());
907 }
908
909 /* Sync */
910
911 static void sync_mesh_fluid_motion(BL::Object& b_ob, Scene *scene, Mesh *mesh)
912 {
913         if(scene->need_motion() == Scene::MOTION_NONE)
914                 return;
915
916         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
917
918         if(!b_fluid_domain)
919                 return;
920
921         /* If the mesh has modifiers following the fluid domain we can't export motion. */
922         if(b_fluid_domain.fluid_mesh_vertices.length() != mesh->verts.size())
923                 return;
924
925         /* Find or add attribute */
926         float3 *P = &mesh->verts[0];
927         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
928
929         if(!attr_mP) {
930                 attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
931         }
932
933         /* Only export previous and next frame, we don't have any in between data. */
934         float motion_times[2] = {-1.0f, 1.0f};
935         for(int step = 0; step < 2; step++) {
936                 float relative_time = motion_times[step] * scene->motion_shutter_time() * 0.5f;
937                 float3 *mP = attr_mP->data_float3() + step*mesh->verts.size();
938
939                 BL::DomainFluidSettings::fluid_mesh_vertices_iterator fvi;
940                 int i = 0;
941
942                 for(b_fluid_domain.fluid_mesh_vertices.begin(fvi); fvi != b_fluid_domain.fluid_mesh_vertices.end(); ++fvi, ++i) {
943                         mP[i] = P[i] + get_float3(fvi->velocity()) * relative_time;
944                 }
945         }
946 }
947
948 Mesh *BlenderSync::sync_mesh(BL::Object& b_ob,
949                              bool object_updated,
950                              bool hide_tris)
951 {
952         /* When viewport display is not needed during render we can force some
953          * caches to be releases from blender side in order to reduce peak memory
954          * footprint during synchronization process.
955          */
956         const bool is_interface_locked = b_engine.render() &&
957                                          b_engine.render().use_lock_interface();
958         const bool can_free_caches = BlenderSession::headless || is_interface_locked;
959
960         /* test if we can instance or if the object is modified */
961         BL::ID b_ob_data = b_ob.data();
962         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
963         BL::Material material_override = render_layer.material_override;
964
965         /* find shader indices */
966         vector<Shader*> used_shaders;
967
968         BL::Object::material_slots_iterator slot;
969         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
970                 if(material_override) {
971                         find_shader(material_override, used_shaders, scene->default_surface);
972                 }
973                 else {
974                         BL::ID b_material(slot->material());
975                         find_shader(b_material, used_shaders, scene->default_surface);
976                 }
977         }
978
979         if(used_shaders.size() == 0) {
980                 if(material_override)
981                         find_shader(material_override, used_shaders, scene->default_surface);
982                 else
983                         used_shaders.push_back(scene->default_surface);
984         }
985
986         /* test if we need to sync */
987         int requested_geometry_flags = Mesh::GEOMETRY_NONE;
988         if(render_layer.use_surfaces) {
989                 requested_geometry_flags |= Mesh::GEOMETRY_TRIANGLES;
990         }
991         if(render_layer.use_hair) {
992                 requested_geometry_flags |= Mesh::GEOMETRY_CURVES;
993         }
994         Mesh *mesh;
995
996         if(!mesh_map.sync(&mesh, key)) {
997                 /* if transform was applied to mesh, need full update */
998                 if(object_updated && mesh->transform_applied);
999                 /* test if shaders changed, these can be object level so mesh
1000                  * does not get tagged for recalc */
1001                 else if(mesh->used_shaders != used_shaders);
1002                 else if(requested_geometry_flags != mesh->geometry_flags);
1003                 else {
1004                         /* even if not tagged for recalc, we may need to sync anyway
1005                          * because the shader needs different mesh attributes */
1006                         bool attribute_recalc = false;
1007
1008                         foreach(Shader *shader, mesh->used_shaders)
1009                                 if(shader->need_update_attributes)
1010                                         attribute_recalc = true;
1011
1012                         if(!attribute_recalc)
1013                                 return mesh;
1014                 }
1015         }
1016
1017         /* ensure we only sync instanced meshes once */
1018         if(mesh_synced.find(mesh) != mesh_synced.end())
1019                 return mesh;
1020
1021         mesh_synced.insert(mesh);
1022
1023         /* create derived mesh */
1024         array<int> oldtriangle = mesh->triangles;
1025
1026         /* compares curve_keys rather than strands in order to handle quick hair
1027          * adjustments in dynamic BVH - other methods could probably do this better*/
1028         array<float3> oldcurve_keys = mesh->curve_keys;
1029         array<float> oldcurve_radius = mesh->curve_radius;
1030
1031         mesh->clear();
1032         mesh->used_shaders = used_shaders;
1033         mesh->name = ustring(b_ob_data.name().c_str());
1034
1035         if(requested_geometry_flags != Mesh::GEOMETRY_NONE) {
1036                 /* mesh objects does have special handle in the dependency graph,
1037                  * they're ensured to have properly updated.
1038                  *
1039                  * updating meshes here will end up having derived mesh referencing
1040                  * freed data from the blender side.
1041                  */
1042                 if(preview && b_ob.type() != BL::Object::type_MESH)
1043                         b_ob.update_from_editmode();
1044
1045                 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
1046
1047                 mesh->subdivision_type = object_subdivision_type(b_ob, preview, experimental);
1048
1049                 /* Disable adaptive subdivision while baking as the baking system
1050                  * currently doesnt support the topology and will crash.
1051                  */
1052                 if(scene->bake_manager->get_baking()) {
1053                         mesh->subdivision_type = Mesh::SUBDIVISION_NONE;
1054                 }
1055
1056                 BL::Mesh b_mesh = object_to_mesh(b_data,
1057                                                  b_ob,
1058                                                  b_scene,
1059                                                  true,
1060                                                  !preview,
1061                                                  need_undeformed,
1062                                                  mesh->subdivision_type);
1063
1064                 if(b_mesh) {
1065                         if(render_layer.use_surfaces && !hide_tris) {
1066                                 if(mesh->subdivision_type != Mesh::SUBDIVISION_NONE)
1067                                         create_subd_mesh(scene, mesh, b_ob, b_mesh, used_shaders,
1068                                                          dicing_rate, max_subdivisions);
1069                                 else
1070                                         create_mesh(scene, mesh, b_mesh, used_shaders, false);
1071
1072                                 create_mesh_volume_attributes(scene, b_ob, mesh, b_scene.frame_current());
1073                         }
1074
1075                         if(render_layer.use_hair && mesh->subdivision_type == Mesh::SUBDIVISION_NONE)
1076                                 sync_curves(mesh, b_mesh, b_ob, false);
1077
1078                         if(can_free_caches) {
1079                                 b_ob.cache_release();
1080                         }
1081
1082                         /* free derived mesh */
1083                         b_data.meshes.remove(b_mesh, false);
1084                 }
1085         }
1086         mesh->geometry_flags = requested_geometry_flags;
1087
1088         /* fluid motion */
1089         sync_mesh_fluid_motion(b_ob, scene, mesh);
1090
1091         /* tag update */
1092         bool rebuild = false;
1093
1094         if(oldtriangle.size() != mesh->triangles.size())
1095                 rebuild = true;
1096         else if(oldtriangle.size()) {
1097                 if(memcmp(&oldtriangle[0], &mesh->triangles[0], sizeof(int)*oldtriangle.size()) != 0)
1098                         rebuild = true;
1099         }
1100
1101         if(oldcurve_keys.size() != mesh->curve_keys.size())
1102                 rebuild = true;
1103         else if(oldcurve_keys.size()) {
1104                 if(memcmp(&oldcurve_keys[0], &mesh->curve_keys[0], sizeof(float3)*oldcurve_keys.size()) != 0)
1105                         rebuild = true;
1106         }
1107
1108         if(oldcurve_radius.size() != mesh->curve_radius.size())
1109                 rebuild = true;
1110         else if(oldcurve_radius.size()) {
1111                 if(memcmp(&oldcurve_radius[0], &mesh->curve_radius[0], sizeof(float)*oldcurve_radius.size()) != 0)
1112                         rebuild = true;
1113         }
1114
1115         mesh->tag_update(scene, rebuild);
1116
1117         return mesh;
1118 }
1119
1120 void BlenderSync::sync_mesh_motion(BL::Object& b_ob,
1121                                    Object *object,
1122                                    float motion_time)
1123 {
1124         /* ensure we only sync instanced meshes once */
1125         Mesh *mesh = object->mesh;
1126
1127         if(mesh_motion_synced.find(mesh) != mesh_motion_synced.end())
1128                 return;
1129
1130         mesh_motion_synced.insert(mesh);
1131
1132         /* ensure we only motion sync meshes that also had mesh synced, to avoid
1133          * unnecessary work and to ensure that its attributes were clear */
1134         if(mesh_synced.find(mesh) == mesh_synced.end())
1135                 return;
1136
1137         /* for motion pass always compute, for motion blur it can be disabled */
1138         int time_index = 0;
1139
1140         if(scene->need_motion() == Scene::MOTION_BLUR) {
1141                 if(!mesh->use_motion_blur)
1142                         return;
1143
1144                 /* see if this mesh needs motion data at this time */
1145                 vector<float> object_times = object->motion_times();
1146                 bool found = false;
1147
1148                 foreach(float object_time, object_times) {
1149                         if(motion_time == object_time) {
1150                                 found = true;
1151                                 break;
1152                         }
1153                         else
1154                                 time_index++;
1155                 }
1156
1157                 if(!found)
1158                         return;
1159         }
1160         else {
1161                 if(motion_time == -1.0f)
1162                         time_index = 0;
1163                 else if(motion_time == 1.0f)
1164                         time_index = 1;
1165                 else
1166                         return;
1167         }
1168
1169         /* skip empty meshes */
1170         const size_t numverts = mesh->verts.size();
1171         const size_t numkeys = mesh->curve_keys.size();
1172
1173         if(!numverts && !numkeys)
1174                 return;
1175
1176         /* skip objects without deforming modifiers. this is not totally reliable,
1177          * would need a more extensive check to see which objects are animated */
1178         BL::Mesh b_mesh(PointerRNA_NULL);
1179
1180         /* fluid motion is exported immediate with mesh, skip here */
1181         BL::DomainFluidSettings b_fluid_domain = object_fluid_domain_find(b_ob);
1182         if(b_fluid_domain)
1183                 return;
1184
1185         if(ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview)) {
1186                 /* get derived mesh */
1187                 b_mesh = object_to_mesh(b_data,
1188                                         b_ob,
1189                                         b_scene,
1190                                         true,
1191                                         !preview,
1192                                         false,
1193                                         Mesh::SUBDIVISION_NONE);
1194         }
1195
1196         if(!b_mesh) {
1197                 /* if we have no motion blur on this frame, but on other frames, copy */
1198                 if(numverts) {
1199                         /* triangles */
1200                         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1201
1202                         if(attr_mP) {
1203                                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1204                                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1205                                 float3 *P = &mesh->verts[0];
1206                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1207
1208                                 memcpy(attr_mP->data_float3() + time_index*numverts, P, sizeof(float3)*numverts);
1209                                 if(attr_mN)
1210                                         memcpy(attr_mN->data_float3() + time_index*numverts, N, sizeof(float3)*numverts);
1211                         }
1212                 }
1213
1214                 if(numkeys) {
1215                         /* curves */
1216                         Attribute *attr_mP = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1217
1218                         if(attr_mP) {
1219                                 float3 *keys = &mesh->curve_keys[0];
1220                                 memcpy(attr_mP->data_float3() + time_index*numkeys, keys, sizeof(float3)*numkeys);
1221                         }
1222                 }
1223
1224                 return;
1225         }
1226
1227         /* TODO(sergey): Perform preliminary check for number of verticies. */
1228         if(numverts) {
1229                 /* Find attributes. */
1230                 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
1231                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
1232                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
1233                 bool new_attribute = false;
1234                 /* Add new attributes if they don't exist already. */
1235                 if(!attr_mP) {
1236                         attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
1237                         if(attr_N)
1238                                 attr_mN = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
1239
1240                         new_attribute = true;
1241                 }
1242                 /* Load vertex data from mesh. */
1243                 float3 *mP = attr_mP->data_float3() + time_index*numverts;
1244                 float3 *mN = (attr_mN)? attr_mN->data_float3() + time_index*numverts: NULL;
1245                 /* NOTE: We don't copy more that existing amount of vertices to prevent
1246                  * possible memory corruption.
1247                  */
1248                 BL::Mesh::vertices_iterator v;
1249                 int i = 0;
1250                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end() && i < numverts; ++v, ++i) {
1251                         mP[i] = get_float3(v->co());
1252                         if(mN)
1253                                 mN[i] = get_float3(v->normal());
1254                 }
1255                 if(new_attribute) {
1256                         /* In case of new attribute, we verify if there really was any motion. */
1257                         if(b_mesh.vertices.length() != numverts ||
1258                            memcmp(mP, &mesh->verts[0], sizeof(float3)*numverts) == 0)
1259                         {
1260                                 /* no motion, remove attributes again */
1261                                 if(b_mesh.vertices.length() != numverts) {
1262                                         VLOG(1) << "Topology differs, disabling motion blur for object "
1263                                                 << b_ob.name();
1264                                 }
1265                                 else {
1266                                         VLOG(1) << "No actual deformation motion for object "
1267                                                 << b_ob.name();
1268                                 }
1269                                 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_POSITION);
1270                                 if(attr_mN)
1271                                         mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_NORMAL);
1272                         }
1273                         else if(time_index > 0) {
1274                                 VLOG(1) << "Filling deformation motion for object " << b_ob.name();
1275                                 /* motion, fill up previous steps that we might have skipped because
1276                                  * they had no motion, but we need them anyway now */
1277                                 float3 *P = &mesh->verts[0];
1278                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
1279                                 for(int step = 0; step < time_index; step++) {
1280                                         memcpy(attr_mP->data_float3() + step*numverts, P, sizeof(float3)*numverts);
1281                                         if(attr_mN)
1282                                                 memcpy(attr_mN->data_float3() + step*numverts, N, sizeof(float3)*numverts);
1283                                 }
1284                         }
1285                 }
1286                 else {
1287                         if(b_mesh.vertices.length() != numverts) {
1288                                 VLOG(1) << "Topology differs, discarding motion blur for object "
1289                                         << b_ob.name() << " at time " << time_index;
1290                                 memcpy(mP, &mesh->verts[0], sizeof(float3)*numverts);
1291                                 if(mN != NULL) {
1292                                         memcpy(mN, attr_N->data_float3(), sizeof(float3)*numverts);
1293                                 }
1294                         }
1295                 }
1296         }
1297
1298         /* hair motion */
1299         if(numkeys)
1300                 sync_curves(mesh, b_mesh, b_ob, true, time_index);
1301
1302         /* free derived mesh */
1303         b_data.meshes.remove(b_mesh, false);
1304 }
1305
1306 CCL_NAMESPACE_END