Fix #36962, "Render emitter" option for hair is ignored in Cycles. Hair particles...
[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_util.h"
24
25 #include "subd_mesh.h"
26 #include "subd_patch.h"
27 #include "subd_split.h"
28
29 #include "util_foreach.h"
30
31 #include "mikktspace.h"
32
33 CCL_NAMESPACE_BEGIN
34
35 /* Tangent Space */
36
37 struct MikkUserData {
38         MikkUserData(const BL::Mesh mesh_, const BL::MeshTextureFaceLayer layer_, int num_faces_)
39         : mesh(mesh_), layer(layer_), num_faces(num_faces_)
40         {
41                 tangent.resize(num_faces*4);
42         }
43
44         BL::Mesh mesh;
45         BL::MeshTextureFaceLayer layer;
46         int num_faces;
47         vector<float4> tangent;
48 };
49
50 static int mikk_get_num_faces(const SMikkTSpaceContext *context)
51 {
52         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
53         return userdata->num_faces;
54 }
55
56 static int mikk_get_num_verts_of_face(const SMikkTSpaceContext *context, const int face_num)
57 {
58         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
59         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
60         int4 vi = get_int4(f.vertices_raw());
61
62         return (vi[3] == 0)? 3: 4;
63 }
64
65 static void mikk_get_position(const SMikkTSpaceContext *context, float P[3], const int face_num, const int vert_num)
66 {
67         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
68         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
69         int4 vi = get_int4(f.vertices_raw());
70         BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
71         float3 vP = get_float3(v.co());
72
73         P[0] = vP.x;
74         P[1] = vP.y;
75         P[2] = vP.z;
76 }
77
78 static void mikk_get_texture_coordinate(const SMikkTSpaceContext *context, float uv[2], const int face_num, const int vert_num)
79 {
80         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
81         BL::MeshTextureFace tf = userdata->layer.data[face_num];
82         float3 tfuv;
83         
84         switch (vert_num) {
85                 case 0:
86                         tfuv = get_float3(tf.uv1());
87                         break;
88                 case 1:
89                         tfuv = get_float3(tf.uv2());
90                         break;
91                 case 2:
92                         tfuv = get_float3(tf.uv3());
93                         break;
94                 default:
95                         tfuv = get_float3(tf.uv4());
96                         break;
97         }
98         
99         uv[0] = tfuv.x;
100         uv[1] = tfuv.y;
101 }
102
103 static void mikk_get_normal(const SMikkTSpaceContext *context, float N[3], const int face_num, const int vert_num)
104 {
105         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
106         BL::MeshTessFace f = userdata->mesh.tessfaces[face_num];
107         float3 vN;
108
109         if(f.use_smooth()) {
110                 int4 vi = get_int4(f.vertices_raw());
111                 BL::MeshVertex v = userdata->mesh.vertices[vi[vert_num]];
112                 vN = get_float3(v.normal());
113         }
114         else {
115                 vN = get_float3(f.normal());
116         }
117
118         N[0] = vN.x;
119         N[1] = vN.y;
120         N[2] = vN.z;
121 }
122
123 static void mikk_set_tangent_space(const SMikkTSpaceContext *context, const float T[], const float sign, const int face, const int vert)
124 {
125         MikkUserData *userdata = (MikkUserData*)context->m_pUserData;
126
127         userdata->tangent[face*4 + vert] = make_float4(T[0], T[1], T[2], sign);
128 }
129
130 static void mikk_compute_tangents(BL::Mesh b_mesh, BL::MeshTextureFaceLayer b_layer, Mesh *mesh, vector<int>& nverts, bool need_sign, bool active_render)
131 {
132         /* setup userdata */
133         MikkUserData userdata(b_mesh, b_layer, nverts.size());
134
135         /* setup interface */
136         SMikkTSpaceInterface sm_interface;
137         memset(&sm_interface, 0, sizeof(sm_interface));
138         sm_interface.m_getNumFaces = mikk_get_num_faces;
139         sm_interface.m_getNumVerticesOfFace = mikk_get_num_verts_of_face;
140         sm_interface.m_getPosition = mikk_get_position;
141         sm_interface.m_getTexCoord = mikk_get_texture_coordinate;
142         sm_interface.m_getNormal = mikk_get_normal;
143         sm_interface.m_setTSpaceBasic = mikk_set_tangent_space;
144
145         /* setup context */
146         SMikkTSpaceContext context;
147         memset(&context, 0, sizeof(context));
148         context.m_pUserData = &userdata;
149         context.m_pInterface = &sm_interface;
150
151         /* compute tangents */
152         genTangSpaceDefault(&context);
153
154         /* create tangent attributes */
155         Attribute *attr;
156         ustring name = ustring((string(b_layer.name().c_str()) + ".tangent").c_str());
157
158         if(active_render)
159                 attr = mesh->attributes.add(ATTR_STD_UV_TANGENT, name);
160         else
161                 attr = mesh->attributes.add(name, TypeDesc::TypeVector, ATTR_ELEMENT_CORNER);
162
163         float3 *tangent = attr->data_float3();
164
165         /* create bitangent sign attribute */
166         float *tangent_sign = NULL;
167
168         if(need_sign) {
169                 Attribute *attr_sign;
170                 ustring name_sign = ustring((string(b_layer.name().c_str()) + ".tangent_sign").c_str());
171
172                 if(active_render)
173                         attr_sign = mesh->attributes.add(ATTR_STD_UV_TANGENT_SIGN, name_sign);
174                 else
175                         attr_sign = mesh->attributes.add(name_sign, TypeDesc::TypeFloat, ATTR_ELEMENT_CORNER);
176
177                 tangent_sign = attr_sign->data_float();
178         }
179
180         for(int i = 0; i < nverts.size(); i++) {
181                 tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
182                 tangent[1] = float4_to_float3(userdata.tangent[i*4 + 1]);
183                 tangent[2] = float4_to_float3(userdata.tangent[i*4 + 2]);
184                 tangent += 3;
185
186                 if(tangent_sign) {
187                         tangent_sign[0] = userdata.tangent[i*4 + 0].w;
188                         tangent_sign[1] = userdata.tangent[i*4 + 1].w;
189                         tangent_sign[2] = userdata.tangent[i*4 + 2].w;
190                         tangent_sign += 3;
191                 }
192
193                 if(nverts[i] == 4) {
194                         tangent[0] = float4_to_float3(userdata.tangent[i*4 + 0]);
195                         tangent[1] = float4_to_float3(userdata.tangent[i*4 + 2]);
196                         tangent[2] = float4_to_float3(userdata.tangent[i*4 + 3]);
197                         tangent += 3;
198
199                         if(tangent_sign) {
200                                 tangent_sign[0] = userdata.tangent[i*4 + 0].w;
201                                 tangent_sign[1] = userdata.tangent[i*4 + 2].w;
202                                 tangent_sign[2] = userdata.tangent[i*4 + 3].w;
203                                 tangent_sign += 3;
204                         }
205                 }
206         }
207 }
208
209 /* Create Mesh */
210
211 static void create_mesh(Scene *scene, Mesh *mesh, BL::Mesh b_mesh, const vector<uint>& used_shaders)
212 {
213         /* count vertices and faces */
214         int numverts = b_mesh.vertices.length();
215         int numfaces = b_mesh.tessfaces.length();
216         int numtris = 0;
217
218         BL::Mesh::vertices_iterator v;
219         BL::Mesh::tessfaces_iterator f;
220
221         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
222                 int4 vi = get_int4(f->vertices_raw());
223                 numtris += (vi[3] == 0)? 1: 2;
224         }
225
226         /* reserve memory */
227         mesh->reserve(numverts, numtris, 0, 0);
228
229         /* create vertex coordinates and normals */
230         int i = 0;
231         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++i)
232                 mesh->verts[i] = get_float3(v->co());
233
234         Attribute *attr_N = mesh->attributes.add(ATTR_STD_VERTEX_NORMAL);
235         float3 *N = attr_N->data_float3();
236
237         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v, ++N)
238                 *N = get_float3(v->normal());
239
240         /* create faces */
241         vector<int> nverts(numfaces);
242         int fi = 0, ti = 0;
243
244         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f, ++fi) {
245                 int4 vi = get_int4(f->vertices_raw());
246                 int n = (vi[3] == 0)? 3: 4;
247                 int mi = clamp(f->material_index(), 0, used_shaders.size()-1);
248                 int shader = used_shaders[mi];
249                 bool smooth = f->use_smooth();
250
251                 if(n == 4) {
252                         if(len_squared(cross(mesh->verts[vi[1]] - mesh->verts[vi[0]], mesh->verts[vi[2]] - mesh->verts[vi[0]])) == 0.0f ||
253                                 len_squared(cross(mesh->verts[vi[2]] - mesh->verts[vi[0]], mesh->verts[vi[3]] - mesh->verts[vi[0]])) == 0.0f) {
254                                 mesh->set_triangle(ti++, vi[0], vi[1], vi[3], shader, smooth);
255                                 mesh->set_triangle(ti++, vi[2], vi[3], vi[1], shader, smooth);
256                         }
257                         else {
258                                 mesh->set_triangle(ti++, vi[0], vi[1], vi[2], shader, smooth);
259                                 mesh->set_triangle(ti++, vi[0], vi[2], vi[3], shader, smooth);
260                         }
261                 }
262                 else
263                         mesh->set_triangle(ti++, vi[0], vi[1], vi[2], shader, smooth);
264
265                 nverts[fi] = n;
266         }
267
268         /* create vertex color attributes */
269         {
270                 BL::Mesh::tessface_vertex_colors_iterator l;
271
272                 for(b_mesh.tessface_vertex_colors.begin(l); l != b_mesh.tessface_vertex_colors.end(); ++l) {
273                         if(!mesh->need_attribute(scene, ustring(l->name().c_str())))
274                                 continue;
275
276                         Attribute *attr = mesh->attributes.add(
277                                 ustring(l->name().c_str()), TypeDesc::TypeColor, ATTR_ELEMENT_CORNER);
278
279                         BL::MeshColorLayer::data_iterator c;
280                         float3 *fdata = attr->data_float3();
281                         size_t i = 0;
282
283                         for(l->data.begin(c); c != l->data.end(); ++c, ++i) {
284                                 fdata[0] = color_srgb_to_scene_linear(get_float3(c->color1()));
285                                 fdata[1] = color_srgb_to_scene_linear(get_float3(c->color2()));
286                                 fdata[2] = color_srgb_to_scene_linear(get_float3(c->color3()));
287
288                                 if(nverts[i] == 4) {
289                                         fdata[3] = fdata[0];
290                                         fdata[4] = fdata[2];
291                                         fdata[5] = color_srgb_to_scene_linear(get_float3(c->color4()));
292                                         fdata += 6;
293                                 }
294                                 else
295                                         fdata += 3;
296                         }
297                 }
298         }
299
300         /* create uv map attributes */
301         {
302                 BL::Mesh::tessface_uv_textures_iterator l;
303
304                 for(b_mesh.tessface_uv_textures.begin(l); l != b_mesh.tessface_uv_textures.end(); ++l) {
305                         bool active_render = l->active_render();
306                         AttributeStandard std = (active_render)? ATTR_STD_UV: ATTR_STD_NONE;
307                         ustring name = ustring(l->name().c_str());
308
309                         /* UV map */
310                         if(mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std)) {
311                                 Attribute *attr;
312
313                                 if(active_render)
314                                         attr = mesh->attributes.add(std, name);
315                                 else
316                                         attr = mesh->attributes.add(name, TypeDesc::TypePoint, ATTR_ELEMENT_CORNER);
317
318                                 BL::MeshTextureFaceLayer::data_iterator t;
319                                 float3 *fdata = attr->data_float3();
320                                 size_t i = 0;
321
322                                 for(l->data.begin(t); t != l->data.end(); ++t, ++i) {
323                                         fdata[0] =  get_float3(t->uv1());
324                                         fdata[1] =  get_float3(t->uv2());
325                                         fdata[2] =  get_float3(t->uv3());
326                                         fdata += 3;
327
328                                         if(nverts[i] == 4) {
329                                                 fdata[0] =  get_float3(t->uv1());
330                                                 fdata[1] =  get_float3(t->uv3());
331                                                 fdata[2] =  get_float3(t->uv4());
332                                                 fdata += 3;
333                                         }
334                                 }
335                         }
336
337                         /* UV tangent */
338                         std = (active_render)? ATTR_STD_UV_TANGENT: ATTR_STD_NONE;
339                         name = ustring((string(l->name().c_str()) + ".tangent").c_str());
340
341                         if(mesh->need_attribute(scene, name) || (active_render && mesh->need_attribute(scene, std))) {
342                                 std = (active_render)? ATTR_STD_UV_TANGENT_SIGN: ATTR_STD_NONE;
343                                 name = ustring((string(l->name().c_str()) + ".tangent_sign").c_str());
344                                 bool need_sign = (mesh->need_attribute(scene, name) || mesh->need_attribute(scene, std));
345
346                                 mikk_compute_tangents(b_mesh, *l, mesh, nverts, need_sign, active_render);
347                         }
348                 }
349         }
350
351         /* create generated coordinates. todo: we should actually get the orco
352          * coordinates from modifiers, for now we use texspace loc/size which
353          * is available in the api. */
354         if(mesh->need_attribute(scene, ATTR_STD_GENERATED)) {
355                 Attribute *attr = mesh->attributes.add(ATTR_STD_GENERATED);
356
357                 float3 loc, size;
358                 mesh_texture_space(b_mesh, loc, size);
359
360                 float3 *generated = attr->data_float3();
361                 size_t i = 0;
362
363                 for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
364                         generated[i++] = get_float3(v->undeformed_co())*size - loc;
365         }
366 }
367
368 static void create_subd_mesh(Mesh *mesh, BL::Mesh b_mesh, PointerRNA *cmesh, const vector<uint>& used_shaders)
369 {
370         /* create subd mesh */
371         SubdMesh sdmesh;
372
373         /* create vertices */
374         BL::Mesh::vertices_iterator v;
375
376         for(b_mesh.vertices.begin(v); v != b_mesh.vertices.end(); ++v)
377                 sdmesh.add_vert(get_float3(v->co()));
378
379         /* create faces */
380         BL::Mesh::tessfaces_iterator f;
381
382         for(b_mesh.tessfaces.begin(f); f != b_mesh.tessfaces.end(); ++f) {
383                 int4 vi = get_int4(f->vertices_raw());
384                 int n = (vi[3] == 0) ? 3: 4;
385                 //int shader = used_shaders[f->material_index()];
386
387                 if(n == 4)
388                         sdmesh.add_face(vi[0], vi[1], vi[2], vi[3]);
389 #if 0
390                 else
391                         sdmesh.add_face(vi[0], vi[1], vi[2]);
392 #endif
393         }
394
395         /* finalize subd mesh */
396         sdmesh.link_boundary();
397
398         /* subdivide */
399         DiagSplit dsplit;
400         dsplit.camera = NULL;
401         dsplit.dicing_rate = RNA_float_get(cmesh, "dicing_rate");
402
403         sdmesh.tessellate(&dsplit, false, mesh, used_shaders[0], true);
404 }
405
406 /* Sync */
407
408 Mesh *BlenderSync::sync_mesh(BL::Object b_ob, bool object_updated, bool hide_tris)
409 {
410         /* test if we can instance or if the object is modified */
411         BL::ID b_ob_data = b_ob.data();
412         BL::ID key = (BKE_object_is_modified(b_ob))? b_ob: b_ob_data;
413         BL::Material material_override = render_layer.material_override;
414
415         /* find shader indices */
416         vector<uint> used_shaders;
417
418         BL::Object::material_slots_iterator slot;
419         for(b_ob.material_slots.begin(slot); slot != b_ob.material_slots.end(); ++slot) {
420                 if(material_override)
421                         find_shader(material_override, used_shaders, scene->default_surface);
422                 else
423                         find_shader(slot->material(), used_shaders, scene->default_surface);
424         }
425
426         if(used_shaders.size() == 0) {
427                 if(material_override)
428                         find_shader(material_override, used_shaders, scene->default_surface);
429                 else
430                         used_shaders.push_back(scene->default_surface);
431         }
432         
433         /* test if we need to sync */
434         Mesh *mesh;
435
436         if(!mesh_map.sync(&mesh, key)) {
437                 /* if transform was applied to mesh, need full update */
438                 if(object_updated && mesh->transform_applied);
439                 /* test if shaders changed, these can be object level so mesh
440                  * does not get tagged for recalc */
441                 else if(mesh->used_shaders != used_shaders);
442                 else {
443                         /* even if not tagged for recalc, we may need to sync anyway
444                          * because the shader needs different mesh attributes */
445                         bool attribute_recalc = false;
446
447                         foreach(uint shader, mesh->used_shaders)
448                                 if(scene->shaders[shader]->need_update_attributes)
449                                         attribute_recalc = true;
450
451                         if(!attribute_recalc)
452                                 return mesh;
453                 }
454         }
455
456         /* ensure we only sync instanced meshes once */
457         if(mesh_synced.find(mesh) != mesh_synced.end())
458                 return mesh;
459         
460         mesh_synced.insert(mesh);
461
462         /* create derived mesh */
463         PointerRNA cmesh = RNA_pointer_get(&b_ob_data.ptr, "cycles");
464
465         vector<Mesh::Triangle> oldtriangle = mesh->triangles;
466         
467         /* compares curve_keys rather than strands in order to handle quick hair
468          * adjustsments in dynamic BVH - other methods could probably do this better*/
469         vector<Mesh::CurveKey> oldcurve_keys = mesh->curve_keys;
470
471         mesh->clear();
472         mesh->used_shaders = used_shaders;
473         mesh->name = ustring(b_ob_data.name().c_str());
474
475         if(render_layer.use_surfaces || render_layer.use_hair) {
476                 if(preview)
477                         b_ob.update_from_editmode();
478
479                 bool need_undeformed = mesh->need_attribute(scene, ATTR_STD_GENERATED);
480                 BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview, need_undeformed);
481
482                 if(b_mesh) {
483                         if(render_layer.use_surfaces && !hide_tris) {
484                                 if(cmesh.data && experimental && RNA_boolean_get(&cmesh, "use_subdivision"))
485                                         create_subd_mesh(mesh, b_mesh, &cmesh, used_shaders);
486                                 else
487                                         create_mesh(scene, mesh, b_mesh, used_shaders);
488                         }
489
490                         if(render_layer.use_hair)
491                                 sync_curves(mesh, b_mesh, b_ob, object_updated);
492
493                         /* free derived mesh */
494                         b_data.meshes.remove(b_mesh);
495                 }
496         }
497
498         /* displacement method */
499         if(cmesh.data) {
500                 const int method = RNA_enum_get(&cmesh, "displacement_method");
501
502                 if(method == 0 || !experimental)
503                         mesh->displacement_method = Mesh::DISPLACE_BUMP;
504                 else if(method == 1)
505                         mesh->displacement_method = Mesh::DISPLACE_TRUE;
506                 else
507                         mesh->displacement_method = Mesh::DISPLACE_BOTH;
508         }
509
510         /* tag update */
511         bool rebuild = false;
512
513         if(oldtriangle.size() != mesh->triangles.size())
514                 rebuild = true;
515         else if(oldtriangle.size()) {
516                 if(memcmp(&oldtriangle[0], &mesh->triangles[0], sizeof(Mesh::Triangle)*oldtriangle.size()) != 0)
517                         rebuild = true;
518         }
519
520         if(oldcurve_keys.size() != mesh->curve_keys.size())
521                 rebuild = true;
522         else if(oldcurve_keys.size()) {
523                 if(memcmp(&oldcurve_keys[0], &mesh->curve_keys[0], sizeof(Mesh::CurveKey)*oldcurve_keys.size()) != 0)
524                         rebuild = true;
525         }
526         
527         mesh->tag_update(scene, rebuild);
528
529         return mesh;
530 }
531
532 void BlenderSync::sync_mesh_motion(BL::Object b_ob, Mesh *mesh, int motion)
533 {
534         /* todo: displacement, subdivision */
535         size_t size = mesh->verts.size();
536
537         /* skip objects without deforming modifiers. this is not a totally reliable,
538          * would need a more extensive check to see which objects are animated */
539         if(!size || !ccl::BKE_object_is_deform_modified(b_ob, b_scene, preview))
540                 return;
541
542         /* get derived mesh */
543         BL::Mesh b_mesh = object_to_mesh(b_data, b_ob, b_scene, true, !preview, false);
544
545         if(b_mesh) {
546                 BL::Mesh::vertices_iterator v;
547                 AttributeStandard std = (motion == -1)? ATTR_STD_MOTION_PRE: ATTR_STD_MOTION_POST;
548                 Attribute *attr_M = mesh->attributes.add(std);
549                 float3 *M = attr_M->data_float3(), *cur_M;
550                 size_t i = 0;
551
552                 for(b_mesh.vertices.begin(v), cur_M = M; v != b_mesh.vertices.end() && i < size; ++v, cur_M++, i++)
553                         *cur_M = get_float3(v->co());
554
555                 /* if number of vertices changed, or if coordinates stayed the same, drop it */
556                 if(i != size || memcmp(M, &mesh->verts[0], sizeof(float3)*size) == 0)
557                         mesh->attributes.remove(std);
558
559                 /* free derived mesh */
560                 b_data.meshes.remove(b_mesh);
561         }
562 }
563
564 CCL_NAMESPACE_END
565