7135e938afb099ea139ed1c620eb1aa9029b0934
[blender.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  
18 #include "mesh.h"
19 #include "object.h"
20 #include "scene.h"
21
22 #include "blender_sync.h"
23 #include "blender_session.h"
24 #include "blender_util.h"
25
26 #include "subd_mesh.h"
27 #include "subd_patch.h"
28 #include "subd_split.h"
29
30 #include "util_foreach.h"
31 #include "util_logging.h"
32 #include "util_math.h"
33
34 #include "mikktspace.h"
35
36 CCL_NAMESPACE_BEGIN
37
38 /* Tangent Space */
39
40 struct MikkUserData {
41         MikkUserData(const BL::Mesh mesh_, BL::MeshTextureFaceLayer *layer_, int num_faces_)
42         : mesh(mesh_), layer(layer_), num_faces(num_faces_)
43         {
44                 tangent.resize(num_faces*4);
45         }
46
47         BL::Mesh mesh;
48         BL::MeshTextureFaceLayer *layer;
49         int num_faces;
50         vector<float4> tangent;
51 };
52
53 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
54 {
55         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
56         return userdata->num_faces;
57 }
58
59 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context, const int face_num)
60 {
61         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
62         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
63         int4 vi = get_int4(f.vertices_raw());
64
65         return (vi[3] == 0)? 3: 4;
66 }
67
68 static void mikk_get_position(const SMikkTSpaceContext *context, float P[3], const int face_num, const int vert_num)
69 {
70         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
71         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
72         int4 vi = get_int4(f.vertices_raw());
73         BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
74         float3 vP = get_float3(v.co());
75
76         P[0] = vP.x;
77         P[1] = vP.y;
78         P[2] = vP.z;
79 }
80
81 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context, float uv[2], const int face_num, const int vert_num)
82 {
83         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
84         if(userdata->layer != NULL) {
85                 BL::MeshTextureFace tf = userdata->layer->data[face_num];
86                 float3 tfuv;
87
88                 switch (vert_num) {
89                         case 0:
90                                 tfuv = get_float3(tf.uv1());
91                                 break;
92                         case 1:
93                                 tfuv = get_float3(tf.uv2());
94                                 break;
95                         case 2:
96                                 tfuv = get_float3(tf.uv3());
97                                 break;
98                         default:
99                                 tfuv = get_float3(tf.uv4());
100                                 break;
101                 }
102
103                 uv[0] = tfuv.x;
104                 uv[1] = tfuv.y;
105         }
106         else {
107                 int vert_idx = userdata->mesh.tessfaces[face_num].vertices()[vert_num];
108                 float3 orco =
109                         get_float3(userdata->mesh.vertices[vert_idx].undeformed_co());
110                 float2 tmp = map_to_sphere(make_float3(orco[0], orco[1], orco[2]));
111                 uv[0] = tmp.x;
112                 uv[1] = tmp.y;
113         }
114 }
115
116 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
117 {
118         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
119         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
120         float3 vN;
121
122         if(f.use_smooth()) {
123                 int4 vi = get_int4(f.vertices_raw());
124                 BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
125                 vN = get_float3(v.normal());
126         }
127         else {
128                 vN = get_float3(f.normal());
129         }
130
131         N[0] = vN.x;
132         N[1] = vN.y;
133         N[2] = vN.z;
134 }
135
136 static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
137 {
138         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
139
140         userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
141 }
142
143 static void mikk_compute_tangents(BL::Mesh b_mesh, BL::MeshTextureFaceLayer *b_layer, Mesh *mesh, const vector<int>& nverts, bool need_sign, bool active_render)
144 {
145         /* setup userdata */
146         MikkUserData userdata(b_mesh, b_layer, nverts.size());
147
148         /* setup interface */
149         SMikkTSpaceInterface sm_interface;
150         memset(&sm_interface, 0, sizeof(sm_interface));
151         sm_interface.m_getNumFaces = mikk_get_num_faces;
152         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
153         sm_interface.m_getPosition = mikk_get_position;
154         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
155         sm_interface.m_getNormal = mikk_get_normal;
156         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
157
158         /* setup context */
159         SMikkTSpaceContext context;
160         memset(&context, 0, sizeof(context));
161         context.m_pUserData = &userdata;
162         context.m_pInterface = &sm_interface;
163
164         /* compute tangents */
165         genTangSpaceDefault(&context);
166
167         /* create tangent attributes */
168         Attribute *attr;
169         ustring name;
170         if(b_layer != NULL)
171                 name = ustring((string(b_layer->name().c_str()) + ".tangent").c_str());
172         else
173                 name = ustring("orco.tangent");
174
175         if(active_render)
176                 attr = mesh->attributes.add(ATTR_STD_UV_TANGENT, name);
177         else
178                 attr = mesh->attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
179
180         float3 *tangent = attr->data_float3();
181
182         /* create bitangent sign attribute */
183         float *tangent_sign = NULL;
184
185         if(need_sign) {
186                 Attribute *attr_sign;
187                 ustring name_sign;
188                 if(b_layer != NULL)
189                         name_sign = ustring((string(b_layer->name().c_str()) + ".tangent_sign").c_str());
190                 else
191                         name_sign = ustring("orco.tangent_sign");
192
193                 if(active_render)
194                         attr_sign = mesh->attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
195                 else
196                         attr_sign = mesh->attributes.add(name_sign, TypeDesc::TypeFloat, ATTR_ELEMENT_CORNER);
197
198                 tangent_sign = attr_sign->data_float();
199         }
200
201         for(int i = 0; i < nverts.size(); i++) {
202                 tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
203                 tangent[1] = float4_to_float3(userdata.tangent[i*4 + 1]);
204                 tangent[2] = float4_to_float3(userdata.tangent[i*4 + 2]);
205                 tangent += 3;
206
207                 if(tangent_sign) {
208                         tangent_sign[0] = userdata.tangent[i*4 + 0].w;
209                         tangent_sign[1] = userdata.tangent[i*4 + 1].w;
210                         tangent_sign[2] = userdata.tangent[i*4 + 2].w;
211                         tangent_sign += 3;
212                 }
213
214                 if(nverts[i] == 4) {
215                         tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
216                         tangent[1] = float4_to_float3(userdata.tangent[i*4 + 2]);
217                         tangent[2] = float4_to_float3(userdata.tangent[i*4 + 3]);
218                         tangent += 3;
219
220                         if(tangent_sign) {
221                                 tangent_sign[0] = userdata.tangent[i*4 + 0].w;
222                                 tangent_sign[1] = userdata.tangent[i*4 + 2].w;
223                                 tangent_sign[2] = userdata.tangent[i*4 + 3].w;
224                                 tangent_sign += 3;
225                         }
226                 }
227         }
228 }
229
230 /* Create Volume Attribute */
231
232 static void create_mesh_volume_attribute(BL::Object b_ob, Mesh *mesh, ImageManager *image_manager, AttributeStandard std, float frame)
233 {
234         BL::SmokeDomainSettings b_domain = object_smoke_domain_find(b_ob);
235
236         if(!b_domain)
237                 return;
238         
239         Attribute *attr = mesh->attributes.add(std);
240         VoxelAttribute *volume_data = attr->data_voxel();
241         bool is_float, is_linear;
242         bool animated = false;
243
244         volume_data->manager = image_manager;
245         volume_data->slot = image_manager->add_image(
246                 Attribute::standard_name(std),
247                 b_ob.ptr.data,
248                 animated,
249                 frame,
250                 is_float,
251                 is_linear,
252                 INTERPOLATION_LINEAR,
253                 EXTENSION_REPEAT,
254                 true);
255 }
256
257 static void create_mesh_volume_attributes(Scene *scene, BL::Object b_ob, Mesh *mesh, float frame)
258 {
259         /* for smoke volume rendering */
260         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_DENSITY))
261                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_DENSITY, frame);
262         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_COLOR))
263                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_COLOR, frame);
264         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_FLAME))
265                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_FLAME, frame);
266         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_HEAT))
267                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_HEAT, frame);
268         if(mesh->need_attribute(scene, ATTR_STD_VOLUME_VELOCITY))
269                 create_mesh_volume_attribute(b_ob, mesh, scene->image_manager, ATTR_STD_VOLUME_VELOCITY, frame);
270 }
271
272 /* Create vertex color attributes. */
273 static void attr_create_vertex_color(Scene *scene,
274                                      Mesh *mesh,
275                                      BL::Mesh b_mesh,
276                                      const vector<int>& nverts)
277 {
278         BL::Mesh::tessface_vertex_colors_iterator l;
279         for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
280                 if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
281                         continue;
282
283                 Attribute *attr = mesh->attributes.add(
284                         ustring(l->name().c_str()), TypeDesc::TypeColor, ATTR_ELEMENT_CORNER_BYTE);
285
286                 BL::MeshColorLayer::data_iterator c;
287                 uchar4 *cdata = attr->data_uchar4();
288                 size_t i = 0;
289
290                 for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
291                         cdata[0] = color_float_to_byte(color_srgb_to_scene_linear(get_float3(c->color1())));
292                         cdata[1] = color_float_to_byte(color_srgb_to_scene_linear(get_float3(c->color2())));
293                         cdata[2] = color_float_to_byte(color_srgb_to_scene_linear(get_float3(c->color3())));
294
295                         if(nverts[i] == 4) {
296                                 cdata[3] = cdata[0];
297                                 cdata[4] = cdata[2];
298                                 cdata[5] = color_float_to_byte(color_srgb_to_scene_linear(get_float3(c->color4())));
299                                 cdata += 6;
300                         }
301                         else
302                                 cdata += 3;
303                 }
304         }
305 }
306
307 /* Create uv map attributes. */
308 static void attr_create_uv_map(Scene *scene,
309                                Mesh *mesh,
310                                BL::Mesh b_mesh,
311                                const vector<int>& nverts)
312 {
313         if(b_mesh.tessface_uv_textures.length() != 0) {
314                 BL::Mesh::tessface_uv_textures_iterator l;
315
316                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
317                         bool active_render = l->active_render();
318                         AttributeStandard std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
319                         ustring name = ustring(l->name().c_str());
320
321                         /* UV map */
322                         if(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)) {
323                                 Attribute *attr;
324
325                                 if(active_render)
326                                         attr = mesh->attributes.add(std, name);
327                                 else
328                                         attr = mesh->attributes.add(name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
329
330                                 BL::MeshTextureFaceLayer::data_iterator t;
331                                 float3 *fdata = attr->data_float3();
332                                 size_t i = 0;
333
334                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
335                                         fdata[0] = get_float3(t->uv1());
336                                         fdata[1] = get_float3(t->uv2());
337                                         fdata[2] = get_float3(t->uv3());
338                                         fdata += 3;
339
340                                         if(nverts[i] == 4) {
341                                                 fdata[0] = get_float3(t->uv1());
342                                                 fdata[1] = get_float3(t->uv3());
343                                                 fdata[2] = get_float3(t->uv4());
344                                                 fdata += 3;
345                                         }
346                                 }
347                         }
348
349                         /* UV tangent */
350                         std = (active_render)? ATTR_STD_UV_TANGENT: ATTR_STD_NONE;
351                         name = ustring((string(l->name().c_str()) + ".tangent").c_str());
352
353                         if(mesh->need_attribute(scene, name) || (active_render && mesh->need_attribute(scene, std))) {
354                                 std = (active_render)? ATTR_STD_UV_TANGENT_SIGN: ATTR_STD_NONE;
355                                 name = ustring((string(l->name().c_str()) + ".tangent_sign").c_str());
356                                 bool need_sign = (mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std));
357
358                                 mikk_compute_tangents(b_mesh, &(*l), mesh, nverts, need_sign, active_render);
359                         }
360                 }
361         }
362         else if(mesh->need_attribute(scene, ATTR_STD_UV_TANGENT)) {
363                 bool need_sign = mesh->need_attribute(scene, ATTR_STD_UV_TANGENT_SIGN);
364                 mikk_compute_tangents(b_mesh, NULL, mesh, nverts, need_sign, true);
365         }
366 }
367
368 /* Create vertex pointiness attributes. */
369 static void attr_create_pointiness(Scene *scene,
370                                    Mesh *mesh,
371                                    BL::Mesh b_mesh)
372 {
373         if(mesh->need_attribute(scene, ATTR_STD_POINTINESS)) {
374                 const int numverts = b_mesh.vertices.length();
375                 Attribute *attr = mesh->attributes.add(ATTR_STD_POINTINESS);
376                 float *data = attr->data_float();
377                 int *counter = new int[numverts];
378                 float *raw_data = new float[numverts];
379                 float3 *edge_accum = new float3[numverts];
380
381                 /* Calculate pointiness using single ring neighborhood. */
382                 memset(counter, 0, sizeof(int) * numverts);
383                 memset(raw_data, 0, sizeof(float) * numverts);
384                 memset(edge_accum, 0, sizeof(float3) * numverts);
385                 BL::Mesh::edges_iterator e;
386                 int i = 0;
387                 for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++i) {
388                         int v0 = b_mesh.edges[i].vertices()[0],
389                             v1 = b_mesh.edges[i].vertices()[1];
390                         float3 co0 = get_float3(b_mesh.vertices[v0].co()),
391                                co1 = get_float3(b_mesh.vertices[v1].co());
392                         float3 edge = normalize(co1 - co0);
393                         edge_accum[v0] += edge;
394                         edge_accum[v1] += -edge;
395                         ++counter[v0];
396                         ++counter[v1];
397                 }
398                 i = 0;
399                 BL::Mesh::vertices_iterator v;
400                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++i) {
401                         if(counter[i] > 0) {
402                                 float3 normal = get_float3(b_mesh.vertices[i].normal());
403                                 float angle = safe_acosf(dot(normal, edge_accum[i] / counter[i]));
404                                 raw_data[i] = angle * M_1_PI_F;
405                         }
406                         else {
407                                 raw_data[i] = 0.0f;
408                         }
409                 }
410
411                 /* Blur vertices to approximate 2 ring neighborhood. */
412                 memset(counter, 0, sizeof(int) * numverts);
413                 memcpy(data, raw_data, sizeof(float) * numverts);
414                 i = 0;
415                 for(b_mesh.edges.begin(e); e != b_mesh.edges.end(); ++e, ++i) {
416                         int v0 = b_mesh.edges[i].vertices()[0],
417                             v1 = b_mesh.edges[i].vertices()[1];
418                         data[v0] += raw_data[v1];
419                         data[v1] += raw_data[v0];
420                         ++counter[v0];
421                         ++counter[v1];
422                 }
423                 for(i = 0; i < numverts; ++i) {
424                         data[i] /= counter[i] + 1;
425                 }
426
427                 delete [] counter;
428                 delete [] raw_data;
429                 delete [] edge_accum;
430         }
431 }
432
433 /* Create Mesh */
434
435 static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<uint>& used_shaders)
436 {
437         /* count vertices and faces */
438         int numverts = b_mesh.vertices.length();
439         int numfaces = b_mesh.tessfaces.length();
440         int numtris = 0;
441         bool use_loop_normals = b_mesh.use_auto_smooth();
442
443         BL::Mesh::vertices_iterator v;
444         BL::Mesh::tessfaces_iterator f;
445
446         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
447                 int4 vi = get_int4(f->vertices_raw());
448                 numtris += (vi[3] == 0)? 1: 2;
449         }
450
451         /* reserve memory */
452         mesh->reserve(numverts, numtris, 0, 0);
453
454         /* create vertex coordinates and normals */
455         int i = 0;
456         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++i)
457                 mesh->verts[i] = get_float3(v->co());
458
459         Attribute *attr_N = mesh->attributes.add(ATTR_STD_VERTEX_NORMAL);
460         float3 *N = attr_N->data_float3();
461
462         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
463                 *N = get_float3(v->normal());
464         N = attr_N->data_float3();
465
466         /* create generated coordinates from undeformed coordinates */
467         if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
468                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
469
470                 float3 loc, size;
471                 mesh_texture_space(b_mesh, loc, size);
472
473                 float3 *generated = attr->data_float3();
474                 size_t i = 0;
475
476                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
477                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
478         }
479
480         /* Create needed vertex attributes. */
481         attr_create_pointiness(scene, mesh, b_mesh);
482
483         /* create faces */
484         vector<int> nverts(numfaces);
485         int fi = 0, ti = 0;
486
487         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f, ++fi) {
488                 int4 vi = get_int4(f->vertices_raw());
489                 int n = (vi[3] == 0)? 3: 4;
490                 int mi = clamp(f->material_index(), 0, used_shaders.size()-1);
491                 int shader = used_shaders[mi];
492                 bool smooth = f->use_smooth() || use_loop_normals;
493
494                 /* split vertices if normal is different
495                  *
496                  * note all vertex attributes must have been set here so we can split
497                  * and copy attributes in split_vertex without remapping later */
498                 if(use_loop_normals) {
499                         BL::Array<float, 12> loop_normals = f->split_normals();
500
501                         for(int i = 0; i < n; i++) {
502                                 float3 loop_N = make_float3(loop_normals[i * 3], loop_normals[i * 3 + 1], loop_normals[i * 3 + 2]);
503
504                                 if(N[vi[i]] != loop_N) {
505                                         int new_vi = mesh->split_vertex(vi[i]);
506
507                                         /* set new normal and vertex index */
508                                         N = attr_N->data_float3();
509                                         N[new_vi] = loop_N;
510                                         vi[i] = new_vi;
511                                 }
512                         }
513                 }
514
515                 /* create triangles */
516                 if(n == 4) {
517                         if(is_zero(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) ||
518                            is_zero(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])))
519                         {
520                                 mesh->set_triangle(ti++, vi[0], vi[1], vi[3], shader, smooth);
521                                 mesh->set_triangle(ti++, vi[2], vi[3], vi[1], shader, smooth);
522                         }
523                         else {
524                                 mesh->set_triangle(ti++, vi[0], vi[1], vi[2], shader, smooth);
525                                 mesh->set_triangle(ti++, vi[0], vi[2], vi[3], shader, smooth);
526                         }
527                 }
528                 else
529                         mesh->set_triangle(ti++, vi[0], vi[1], vi[2], shader, smooth);
530
531                 nverts[fi] = n;
532         }
533
534         /* Create all needed attributes.
535          * The calculate functions will check whether they're needed or not.
536          */
537         attr_create_vertex_color(scene, mesh, b_mesh, nverts);
538         attr_create_uv_map(scene, mesh, b_mesh, nverts);
539
540         /* for volume objects, create a matrix to transform from object space to
541          * mesh texture space. this does not work with deformations but that can
542          * probably only be done well with a volume grid mapping of coordinates */
543         if(mesh->need_attribute(scene, ATTR_STD_GENERATED_TRANSFORM)) {
544                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED_TRANSFORM);
545                 Transform *tfm = attr->data_transform();
546
547                 float3 loc, size;
548                 mesh_texture_space(b_mesh, loc, size);
549
550                 *tfm = transform_translate(-loc)*transform_scale(size);
551         }
552 }
553
554 static void create_subd_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, PointerRNA *cmesh, const vector<uint>& used_shaders)
555 {
556         /* create subd mesh */
557         SubdMesh sdmesh;
558
559         /* create vertices */
560         BL::Mesh::vertices_iterator v;
561
562         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
563                 sdmesh.add_vert(get_float3(v->co()));
564
565         /* create faces */
566         BL::Mesh::tessfaces_iterator f;
567
568         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
569                 int4 vi = get_int4(f->vertices_raw());
570                 int n = (vi[3] == 0) ? 3: 4;
571                 //int shader = used_shaders[f->material_index()];
572
573                 if(n == 4)
574                         sdmesh.add_face(vi[0], vi[1], vi[2], vi[3]);
575                 else
576                         sdmesh.add_face(vi[0], vi[1], vi[2]);
577         }
578
579         /* finalize subd mesh */
580         sdmesh.finish();
581
582         /* parameters */
583         bool need_ptex = mesh->need_attribute(scene, ATTR_STD_PTEX_FACE_ID) ||
584                          mesh->need_attribute(scene, ATTR_STD_PTEX_UV);
585
586         SubdParams sdparams(mesh, used_shaders[0], true, need_ptex);
587         sdparams.dicing_rate = RNA_float_get(cmesh, "dicing_rate");
588         //scene->camera->update();
589         //sdparams.camera = scene->camera;
590
591         /* tesselate */
592         DiagSplit dsplit(sdparams);
593         sdmesh.tessellate(&dsplit);
594 }
595
596 /* Sync */
597
598 Mesh *BlenderSync::sync_mesh(BL::Object b_ob, bool object_updated, bool hide_tris)
599 {
600         /* When viewport display is not needed during render we can force some
601          * caches to be releases from blender side in order to reduce peak memory
602          * footprint during synchronization process.
603          */
604         const bool is_interface_locked = b_engine.render() &&
605                                          b_engine.render().use_lock_interface();
606         const bool can_free_caches = BlenderSession::headless || is_interface_locked;
607
608         /* test if we can instance or if the object is modified */
609         BL::ID b_ob_data = b_ob.data();
610         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
611         BL::Material material_override = render_layer.material_override;
612
613         /* find shader indices */
614         vector<uint> used_shaders;
615
616         BL::Object::material_slots_iterator slot;
617         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
618                 if(material_override)
619                         find_shader(material_override, used_shaders, scene->default_surface);
620                 else
621                         find_shader(slot->material(), used_shaders, scene->default_surface);
622         }
623
624         if(used_shaders.size() == 0) {
625                 if(material_override)
626                         find_shader(material_override, used_shaders, scene->default_surface);
627                 else
628                         used_shaders.push_back(scene->default_surface);
629         }
630         
631         /* test if we need to sync */
632         int requested_geometry_flags = Mesh::GEOMETRY_NONE;
633         if(render_layer.use_surfaces) {
634                 requested_geometry_flags |= Mesh::GEOMETRY_TRIANGLES;
635         }
636         if(render_layer.use_hair) {
637                 requested_geometry_flags |= Mesh::GEOMETRY_CURVES;
638         }
639         Mesh *mesh;
640
641         if(!mesh_map.sync(&mesh, key)) {
642                 /* if transform was applied to mesh, need full update */
643                 if(object_updated && mesh->transform_applied);
644                 /* test if shaders changed, these can be object level so mesh
645                  * does not get tagged for recalc */
646                 else if(mesh->used_shaders != used_shaders);
647                 else if(requested_geometry_flags != mesh->geometry_flags);
648                 else {
649                         /* even if not tagged for recalc, we may need to sync anyway
650                          * because the shader needs different mesh attributes */
651                         bool attribute_recalc = false;
652
653                         foreach(uint shader, mesh->used_shaders)
654                                 if(scene->shaders[shader]->need_update_attributes)
655                                         attribute_recalc = true;
656
657                         if(!attribute_recalc)
658                                 return mesh;
659                 }
660         }
661
662         /* ensure we only sync instanced meshes once */
663         if(mesh_synced.find(mesh) != mesh_synced.end())
664                 return mesh;
665         
666         mesh_synced.insert(mesh);
667
668         /* create derived mesh */
669         PointerRNA cmesh = RNA_pointer_get(&b_ob_data.ptr, "cycles");
670
671         vector<Mesh::Triangle> oldtriangle = mesh->triangles;
672         
673         /* compares curve_keys rather than strands in order to handle quick hair
674          * adjustments in dynamic BVH - other methods could probably do this better*/
675         vector<float4> oldcurve_keys = mesh->curve_keys;
676
677         mesh->clear();
678         mesh->used_shaders = used_shaders;
679         mesh->name = ustring(b_ob_data.name().c_str());
680
681         if(requested_geometry_flags != Mesh::GEOMETRY_NONE) {
682                 /* mesh objects does have special handle in the dependency graph,
683                  * they're ensured to have properly updated.
684                  *
685                  * updating meshes here will end up having derived mesh referencing
686                  * freed data from the blender side.
687                  */
688                 if(preview && b_ob.type() != BL::Object::type_MESH)
689                         b_ob.update_from_editmode();
690
691                 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
692                 BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview, need_undeformed);
693
694                 if(b_mesh) {
695                         if(render_layer.use_surfaces && !hide_tris) {
696                                 if(cmesh.data && experimental && RNA_boolean_get(&cmesh, "use_subdivision"))
697                                         create_subd_mesh(scene, mesh, b_mesh, &cmesh, used_shaders);
698                                 else
699                                         create_mesh(scene, mesh, b_mesh, used_shaders);
700
701                                 create_mesh_volume_attributes(scene, b_ob, mesh, b_scene.frame_current());
702                         }
703
704                         if(render_layer.use_hair)
705                                 sync_curves(mesh, b_mesh, b_ob, false);
706
707                         if(can_free_caches) {
708                                 b_ob.cache_release();
709                         }
710
711                         /* free derived mesh */
712                         b_data.meshes.remove(b_mesh);
713                 }
714         }
715         mesh->geometry_flags = requested_geometry_flags;
716
717         /* displacement method */
718         if(cmesh.data) {
719                 const int method = RNA_enum_get(&cmesh, "displacement_method");
720
721                 if(method == 0 || !experimental)
722                         mesh->displacement_method = Mesh::DISPLACE_BUMP;
723                 else if(method == 1)
724                         mesh->displacement_method = Mesh::DISPLACE_TRUE;
725                 else
726                         mesh->displacement_method = Mesh::DISPLACE_BOTH;
727         }
728
729         /* tag update */
730         bool rebuild = false;
731
732         if(oldtriangle.size() != mesh->triangles.size())
733                 rebuild = true;
734         else if(oldtriangle.size()) {
735                 if(memcmp(&oldtriangle[0], &mesh->triangles[0], sizeof(Mesh::Triangle)*oldtriangle.size()) != 0)
736                         rebuild = true;
737         }
738
739         if(oldcurve_keys.size() != mesh->curve_keys.size())
740                 rebuild = true;
741         else if(oldcurve_keys.size()) {
742                 if(memcmp(&oldcurve_keys[0], &mesh->curve_keys[0], sizeof(float4)*oldcurve_keys.size()) != 0)
743                         rebuild = true;
744         }
745         
746         mesh->tag_update(scene, rebuild);
747
748         return mesh;
749 }
750
751 void BlenderSync::sync_mesh_motion(BL::Object b_ob, Object *object, float motion_time)
752 {
753         /* ensure we only sync instanced meshes once */
754         Mesh *mesh = object->mesh;
755
756         if(mesh_motion_synced.find(mesh) != mesh_motion_synced.end())
757                 return;
758
759         mesh_motion_synced.insert(mesh);
760
761         /* ensure we only motion sync meshes that also had mesh synced, to avoid
762          * unnecessary work and to ensure that its attributes were clear */
763         if(mesh_synced.find(mesh) == mesh_synced.end())
764                 return;
765
766         /* for motion pass always compute, for motion blur it can be disabled */
767         int time_index = 0;
768
769         if(scene->need_motion() == Scene::MOTION_BLUR) {
770                 if(!mesh->use_motion_blur)
771                         return;
772                 
773                 /* see if this mesh needs motion data at this time */
774                 vector<float> object_times = object->motion_times();
775                 bool found = false;
776
777                 foreach(float object_time, object_times) {
778                         if(motion_time == object_time) {
779                                 found = true;
780                                 break;
781                         }
782                         else
783                                 time_index++;
784                 }
785
786                 if(!found)
787                         return;
788         }
789         else {
790                 if(motion_time == -1.0f)
791                         time_index = 0;
792                 else if(motion_time == 1.0f)
793                         time_index = 1;
794                 else
795                         return;
796         }
797
798         /* skip empty meshes */
799         size_t numverts = mesh->verts.size();
800         size_t numkeys = mesh->curve_keys.size();
801
802         if(!numverts && !numkeys)
803                 return;
804         
805         /* skip objects without deforming modifiers. this is not totally reliable,
806          * would need a more extensive check to see which objects are animated */
807         BL::Mesh b_mesh(PointerRNA_NULL);
808
809         if(ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview)) {
810                 /* get derived mesh */
811                 b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview, false);
812         }
813
814         if(!b_mesh) {
815                 /* if we have no motion blur on this frame, but on other frames, copy */
816                 if(numverts) {
817                         /* triangles */
818                         Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
819
820                         if(attr_mP) {
821                                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
822                                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
823                                 float3 *P = &mesh->verts[0];
824                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
825
826                                 memcpy(attr_mP->data_float3() + time_index*numverts, P, sizeof(float3)*numverts);
827                                 if(attr_mN)
828                                         memcpy(attr_mN->data_float3() + time_index*numverts, N, sizeof(float3)*numverts);
829                         }
830                 }
831
832                 if(numkeys) {
833                         /* curves */
834                         Attribute *attr_mP = mesh->curve_attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
835
836                         if(attr_mP) {
837                                 float4 *keys = &mesh->curve_keys[0];
838                                 memcpy(attr_mP->data_float4() + time_index*numkeys, keys, sizeof(float4)*numkeys);
839                         }
840                 }
841
842                 return;
843         }
844
845         /* TODO(sergey): Perform preliminary check for number of verticies. */
846         if(numverts) {
847                 /* find attributes */
848                 Attribute *attr_mP = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_POSITION);
849                 Attribute *attr_mN = mesh->attributes.find(ATTR_STD_MOTION_VERTEX_NORMAL);
850                 Attribute *attr_N = mesh->attributes.find(ATTR_STD_VERTEX_NORMAL);
851                 bool new_attribute = false;
852
853                 /* add new attributes if they don't exist already */
854                 if(!attr_mP) {
855                         attr_mP = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_POSITION);
856                         if(attr_N)
857                                 attr_mN = mesh->attributes.add(ATTR_STD_MOTION_VERTEX_NORMAL);
858
859                         new_attribute = true;
860                 }
861
862                 /* load vertex data from mesh */
863                 float3 *mP = attr_mP->data_float3() + time_index*numverts;
864                 float3 *mN = (attr_mN)? attr_mN->data_float3() + time_index*numverts: NULL;
865
866                 BL::Mesh::vertices_iterator v;
867                 int i = 0;
868
869                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end() && i < numverts; ++v, ++i) {
870                         mP[i] = get_float3(v->co());
871                         if(mN)
872                                 mN[i] = get_float3(v->normal());
873                 }
874
875                 /* in case of new attribute, we verify if there really was any motion */
876                 if(new_attribute) {
877                         if(b_mesh.vertices.length() != numverts ||
878                            memcmp(mP, &mesh->verts[0], sizeof(float3)*numverts) == 0)
879                         {
880                                 /* no motion, remove attributes again */
881                                 VLOG(1) << "No actual deformation motion for object " << b_ob.name();
882                                 mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_POSITION);
883                                 if(attr_mN)
884                                         mesh->attributes.remove(ATTR_STD_MOTION_VERTEX_NORMAL);
885                         }
886                         else if(time_index > 0) {
887                                 VLOG(1) << "Filling deformation motion for object " << b_ob.name();
888                                 /* motion, fill up previous steps that we might have skipped because
889                                  * they had no motion, but we need them anyway now */
890                                 float3 *P = &mesh->verts[0];
891                                 float3 *N = (attr_N)? attr_N->data_float3(): NULL;
892
893                                 for(int step = 0; step < time_index; step++) {
894                                         memcpy(attr_mP->data_float3() + step*numverts, P, sizeof(float3)*numverts);
895                                         if(attr_mN)
896                                                 memcpy(attr_mN->data_float3() + step*numverts, N, sizeof(float3)*numverts);
897                                 }
898                         }
899                 }
900         }
901
902         /* hair motion */
903         if(numkeys)
904                 sync_curves(mesh, b_mesh, b_ob, true, time_index);
905
906         /* free derived mesh */
907         b_data.meshes.remove(b_mesh);
908 }
909
910 CCL_NAMESPACE_END
911