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