1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  */
16 
17 /** \file
18  * \ingroup render
19  *
20  * \brief The API itself is simple.
21  * Blender sends a populated array of BakePixels to the renderer,
22  * and gets back an array of floats with the result.
23  *
24  * \section bake_api Development Notes for External Engines
25  *
26  * The Bake API is fully implemented with Python rna functions.
27  * The operator expects/call a function:
28  *
29  * ``def bake(scene, object, pass_type, object_id, pixel_array, num_pixels, depth, result)``
30  * - scene: current scene (Python object)
31  * - object: object to render (Python object)
32  * - pass_type: pass to render (string, e.g., "COMBINED", "AO", "NORMAL", ...)
33  * - object_id: index of object to bake (to use with the pixel_array)
34  * - pixel_array: list of primitive ids and barycentric coordinates to
35  *   `bake(Python object, see bake_pixel)`.
36  * - num_pixels: size of pixel_array, number of pixels to bake (int)
37  * - depth: depth of pixels to return (int, assuming always 4 now)
38  * - result: array to be populated by the engine (float array, PyLong_AsVoidPtr)
39  *
40  * \note Normals are expected to be in World Space and in the +X, +Y, +Z orientation.
41  *
42  * \subsection bake_pixel BakePixel data structure
43  *
44  * pixel_array is a Python object storing BakePixel elements:
45  *
46  * \code{.c}
47  * struct BakePixel {
48  *     int primitive_id, object_id;
49  *     float uv[2];
50  *     float du_dx, du_dy;
51  *     float dv_dx, dv_dy;
52  * };
53  * \endcode
54  *
55  * In python you have access to:
56  * - ``primitive_id``, ``object_id``,  ``uv``, ``du_dx``, ``du_dy``, ``next``
57  * - ``next()`` is a function that returns the next #BakePixel in the array.
58  *
59  * \note Pixels that should not be baked have ``primitive_id == -1``
60  *
61  * For a complete implementation example look at the Cycles Bake commit.
62  */
63 
64 #include <limits.h>
65 
66 #include "MEM_guardedalloc.h"
67 
68 #include "BLI_math.h"
69 
70 #include "DNA_mesh_types.h"
71 #include "DNA_meshdata_types.h"
72 
73 #include "BKE_bvhutils.h"
74 #include "BKE_customdata.h"
75 #include "BKE_image.h"
76 #include "BKE_lib_id.h"
77 #include "BKE_mesh.h"
78 #include "BKE_mesh_runtime.h"
79 #include "BKE_mesh_tangent.h"
80 #include "BKE_node.h"
81 
82 #include "IMB_imbuf.h"
83 #include "IMB_imbuf_types.h"
84 
85 #include "RE_bake.h"
86 
87 /* local include */
88 #include "render_types.h"
89 #include "zbuf.h"
90 
91 typedef struct BakeDataZSpan {
92   BakePixel *pixel_array;
93   int primitive_id;
94   BakeImage *bk_image;
95   ZSpan *zspan;
96   float du_dx, du_dy;
97   float dv_dx, dv_dy;
98 } BakeDataZSpan;
99 
100 /**
101  * struct wrapping up tangent space data
102  */
103 typedef struct TSpace {
104   float tangent[3];
105   float sign;
106 } TSpace;
107 
108 typedef struct TriTessFace {
109   const MVert *mverts[3];
110   const TSpace *tspace[3];
111   float *loop_normal[3];
112   float normal[3]; /* for flat faces */
113   bool is_smooth;
114 } TriTessFace;
115 
store_bake_pixel(void * handle,int x,int y,float u,float v)116 static void store_bake_pixel(void *handle, int x, int y, float u, float v)
117 {
118   BakeDataZSpan *bd = (BakeDataZSpan *)handle;
119   BakePixel *pixel;
120 
121   const int width = bd->bk_image->width;
122   const size_t offset = bd->bk_image->offset;
123   const int i = offset + y * width + x;
124 
125   pixel = &bd->pixel_array[i];
126   pixel->primitive_id = bd->primitive_id;
127 
128   /* At this point object_id is always 0, since this function runs for the
129    * low-poly mesh only. The object_id lookup indices are set afterwards. */
130 
131   copy_v2_fl2(pixel->uv, u, v);
132 
133   pixel->du_dx = bd->du_dx;
134   pixel->du_dy = bd->du_dy;
135   pixel->dv_dx = bd->dv_dx;
136   pixel->dv_dy = bd->dv_dy;
137   pixel->object_id = 0;
138 }
139 
RE_bake_mask_fill(const BakePixel pixel_array[],const size_t num_pixels,char * mask)140 void RE_bake_mask_fill(const BakePixel pixel_array[], const size_t num_pixels, char *mask)
141 {
142   size_t i;
143   if (!mask) {
144     return;
145   }
146 
147   /* only extend to pixels outside the mask area */
148   for (i = 0; i < num_pixels; i++) {
149     if (pixel_array[i].primitive_id != -1) {
150       mask[i] = FILTER_MASK_USED;
151     }
152   }
153 }
154 
RE_bake_margin(ImBuf * ibuf,char * mask,const int margin)155 void RE_bake_margin(ImBuf *ibuf, char *mask, const int margin)
156 {
157   /* margin */
158   IMB_filter_extend(ibuf, mask, margin);
159 
160   if (ibuf->planes != R_IMF_PLANES_RGBA) {
161     /* clear alpha added by filtering */
162     IMB_rectfill_alpha(ibuf, 1.0f);
163   }
164 }
165 
166 /**
167  * This function returns the coordinate and normal of a barycentric u,v
168  * for a face defined by the primitive_id index.
169  * The returned normal is actually the direction from the same barycentric coordinate
170  * in the cage to the base mesh
171  * The returned coordinate is the point in the cage mesh
172  */
calc_point_from_barycentric_cage(TriTessFace * triangles_low,TriTessFace * triangles_cage,const float mat_low[4][4],const float mat_cage[4][4],int primitive_id,float u,float v,float r_co[3],float r_dir[3])173 static void calc_point_from_barycentric_cage(TriTessFace *triangles_low,
174                                              TriTessFace *triangles_cage,
175                                              const float mat_low[4][4],
176                                              const float mat_cage[4][4],
177                                              int primitive_id,
178                                              float u,
179                                              float v,
180                                              float r_co[3],
181                                              float r_dir[3])
182 {
183   float data[2][3][3];
184   float coord[2][3];
185   float dir[3];
186   int i;
187 
188   TriTessFace *triangle[2];
189 
190   triangle[0] = &triangles_low[primitive_id];
191   triangle[1] = &triangles_cage[primitive_id];
192 
193   for (i = 0; i < 2; i++) {
194     copy_v3_v3(data[i][0], triangle[i]->mverts[0]->co);
195     copy_v3_v3(data[i][1], triangle[i]->mverts[1]->co);
196     copy_v3_v3(data[i][2], triangle[i]->mverts[2]->co);
197     interp_barycentric_tri_v3(data[i], u, v, coord[i]);
198   }
199 
200   /* convert from local to world space */
201   mul_m4_v3(mat_low, coord[0]);
202   mul_m4_v3(mat_cage, coord[1]);
203 
204   sub_v3_v3v3(dir, coord[0], coord[1]);
205   normalize_v3(dir);
206 
207   copy_v3_v3(r_co, coord[1]);
208   copy_v3_v3(r_dir, dir);
209 }
210 
211 /**
212  * This function returns the coordinate and normal of a barycentric u,v
213  * for a face defined by the primitive_id index.
214  * The returned coordinate is extruded along the normal by cage_extrusion
215  */
calc_point_from_barycentric_extrusion(TriTessFace * triangles,const float mat[4][4],const float imat[4][4],int primitive_id,float u,float v,float cage_extrusion,float r_co[3],float r_dir[3],const bool is_cage)216 static void calc_point_from_barycentric_extrusion(TriTessFace *triangles,
217                                                   const float mat[4][4],
218                                                   const float imat[4][4],
219                                                   int primitive_id,
220                                                   float u,
221                                                   float v,
222                                                   float cage_extrusion,
223                                                   float r_co[3],
224                                                   float r_dir[3],
225                                                   const bool is_cage)
226 {
227   float data[3][3];
228   float coord[3];
229   float dir[3];
230   float cage[3];
231   bool is_smooth;
232 
233   TriTessFace *triangle = &triangles[primitive_id];
234   is_smooth = triangle->is_smooth || is_cage;
235 
236   copy_v3_v3(data[0], triangle->mverts[0]->co);
237   copy_v3_v3(data[1], triangle->mverts[1]->co);
238   copy_v3_v3(data[2], triangle->mverts[2]->co);
239 
240   interp_barycentric_tri_v3(data, u, v, coord);
241 
242   if (is_smooth) {
243     normal_short_to_float_v3(data[0], triangle->mverts[0]->no);
244     normal_short_to_float_v3(data[1], triangle->mverts[1]->no);
245     normal_short_to_float_v3(data[2], triangle->mverts[2]->no);
246 
247     interp_barycentric_tri_v3(data, u, v, dir);
248     normalize_v3(dir);
249   }
250   else {
251     copy_v3_v3(dir, triangle->normal);
252   }
253 
254   mul_v3_v3fl(cage, dir, cage_extrusion);
255   add_v3_v3(coord, cage);
256 
257   normalize_v3(dir);
258   negate_v3(dir);
259 
260   /* convert from local to world space */
261   mul_m4_v3(mat, coord);
262   mul_transposed_mat3_m4_v3(imat, dir);
263   normalize_v3(dir);
264 
265   copy_v3_v3(r_co, coord);
266   copy_v3_v3(r_dir, dir);
267 }
268 
barycentric_differentials_from_position(const float co[3],const float v1[3],const float v2[3],const float v3[3],const float dxco[3],const float dyco[3],const float facenor[3],const bool differentials,float * u,float * v,float * dx_u,float * dx_v,float * dy_u,float * dy_v)269 static void barycentric_differentials_from_position(const float co[3],
270                                                     const float v1[3],
271                                                     const float v2[3],
272                                                     const float v3[3],
273                                                     const float dxco[3],
274                                                     const float dyco[3],
275                                                     const float facenor[3],
276                                                     const bool differentials,
277                                                     float *u,
278                                                     float *v,
279                                                     float *dx_u,
280                                                     float *dx_v,
281                                                     float *dy_u,
282                                                     float *dy_v)
283 {
284   /* find most stable axis to project */
285   int axis1, axis2;
286   axis_dominant_v3(&axis1, &axis2, facenor);
287 
288   /* compute u,v and derivatives */
289   float t00 = v3[axis1] - v1[axis1];
290   float t01 = v3[axis2] - v1[axis2];
291   float t10 = v3[axis1] - v2[axis1];
292   float t11 = v3[axis2] - v2[axis2];
293 
294   float detsh = (t00 * t11 - t10 * t01);
295   detsh = (detsh != 0.0f) ? 1.0f / detsh : 0.0f;
296   t00 *= detsh;
297   t01 *= detsh;
298   t10 *= detsh;
299   t11 *= detsh;
300 
301   *u = (v3[axis1] - co[axis1]) * t11 - (v3[axis2] - co[axis2]) * t10;
302   *v = (v3[axis2] - co[axis2]) * t00 - (v3[axis1] - co[axis1]) * t01;
303   if (differentials) {
304     *dx_u = dxco[axis1] * t11 - dxco[axis2] * t10;
305     *dx_v = dxco[axis2] * t00 - dxco[axis1] * t01;
306     *dy_u = dyco[axis1] * t11 - dyco[axis2] * t10;
307     *dy_v = dyco[axis2] * t00 - dyco[axis1] * t01;
308   }
309 }
310 
311 /**
312  * This function populates pixel_array and returns TRUE if things are correct
313  */
cast_ray_highpoly(BVHTreeFromMesh * treeData,TriTessFace * triangle_low,TriTessFace * triangles[],BakePixel * pixel_array_low,BakePixel * pixel_array,const float mat_low[4][4],BakeHighPolyData * highpoly,const float co[3],const float dir[3],const int pixel_id,const int tot_highpoly,const float max_ray_distance)314 static bool cast_ray_highpoly(BVHTreeFromMesh *treeData,
315                               TriTessFace *triangle_low,
316                               TriTessFace *triangles[],
317                               BakePixel *pixel_array_low,
318                               BakePixel *pixel_array,
319                               const float mat_low[4][4],
320                               BakeHighPolyData *highpoly,
321                               const float co[3],
322                               const float dir[3],
323                               const int pixel_id,
324                               const int tot_highpoly,
325                               const float max_ray_distance)
326 {
327   int i;
328   int hit_mesh = -1;
329   float hit_distance = max_ray_distance;
330   if (hit_distance == 0.0f) {
331     /* No ray distance set, use maximum. */
332     hit_distance = FLT_MAX;
333   }
334 
335   BVHTreeRayHit *hits;
336   hits = MEM_mallocN(sizeof(BVHTreeRayHit) * tot_highpoly, "Bake Highpoly to Lowpoly: BVH Rays");
337 
338   for (i = 0; i < tot_highpoly; i++) {
339     float co_high[3], dir_high[3];
340 
341     hits[i].index = -1;
342     /* TODO: we should use FLT_MAX here, but sweepsphere code isn't prepared for that */
343     hits[i].dist = BVH_RAYCAST_DIST_MAX;
344 
345     /* transform the ray from the world space to the highpoly space */
346     mul_v3_m4v3(co_high, highpoly[i].imat, co);
347 
348     /* rotates */
349     mul_v3_mat3_m4v3(dir_high, highpoly[i].imat, dir);
350     normalize_v3(dir_high);
351 
352     /* cast ray */
353     if (treeData[i].tree) {
354       BLI_bvhtree_ray_cast(treeData[i].tree,
355                            co_high,
356                            dir_high,
357                            0.0f,
358                            &hits[i],
359                            treeData[i].raycast_callback,
360                            &treeData[i]);
361     }
362 
363     if (hits[i].index != -1) {
364       float distance;
365       float hit_world[3];
366 
367       /* distance comparison in world space */
368       mul_v3_m4v3(hit_world, highpoly[i].obmat, hits[i].co);
369       distance = len_squared_v3v3(hit_world, co);
370 
371       if (distance < hit_distance) {
372         hit_mesh = i;
373         hit_distance = distance;
374       }
375     }
376   }
377 
378   if (hit_mesh != -1) {
379     int primitive_id_high = hits[hit_mesh].index;
380     TriTessFace *triangle_high = &triangles[hit_mesh][primitive_id_high];
381     BakePixel *pixel_low = &pixel_array_low[pixel_id];
382     BakePixel *pixel_high = &pixel_array[pixel_id];
383 
384     pixel_high->primitive_id = primitive_id_high;
385     pixel_high->object_id = hit_mesh;
386 
387     /* ray direction in high poly object space */
388     float dir_high[3];
389     mul_v3_mat3_m4v3(dir_high, highpoly[hit_mesh].imat, dir);
390     normalize_v3(dir_high);
391 
392     /* compute position differentials on low poly object */
393     float duco_low[3], dvco_low[3], dxco[3], dyco[3];
394     sub_v3_v3v3(duco_low, triangle_low->mverts[0]->co, triangle_low->mverts[2]->co);
395     sub_v3_v3v3(dvco_low, triangle_low->mverts[1]->co, triangle_low->mverts[2]->co);
396 
397     mul_v3_v3fl(dxco, duco_low, pixel_low->du_dx);
398     madd_v3_v3fl(dxco, dvco_low, pixel_low->dv_dx);
399     mul_v3_v3fl(dyco, duco_low, pixel_low->du_dy);
400     madd_v3_v3fl(dyco, dvco_low, pixel_low->dv_dy);
401 
402     /* transform from low poly to high poly object space */
403     mul_mat3_m4_v3(mat_low, dxco);
404     mul_mat3_m4_v3(mat_low, dyco);
405     mul_mat3_m4_v3(highpoly[hit_mesh].imat, dxco);
406     mul_mat3_m4_v3(highpoly[hit_mesh].imat, dyco);
407 
408     /* transfer position differentials */
409     float tmp[3];
410     mul_v3_v3fl(tmp, dir_high, 1.0f / dot_v3v3(dir_high, triangle_high->normal));
411     madd_v3_v3fl(dxco, tmp, -dot_v3v3(dxco, triangle_high->normal));
412     madd_v3_v3fl(dyco, tmp, -dot_v3v3(dyco, triangle_high->normal));
413 
414     /* compute barycentric differentials from position differentials */
415     barycentric_differentials_from_position(hits[hit_mesh].co,
416                                             triangle_high->mverts[0]->co,
417                                             triangle_high->mverts[1]->co,
418                                             triangle_high->mverts[2]->co,
419                                             dxco,
420                                             dyco,
421                                             triangle_high->normal,
422                                             true,
423                                             &pixel_high->uv[0],
424                                             &pixel_high->uv[1],
425                                             &pixel_high->du_dx,
426                                             &pixel_high->dv_dx,
427                                             &pixel_high->du_dy,
428                                             &pixel_high->dv_dy);
429 
430     /* verify we have valid uvs */
431     BLI_assert(pixel_high->uv[0] >= -1e-3f && pixel_high->uv[1] >= -1e-3f &&
432                pixel_high->uv[0] + pixel_high->uv[1] <= 1.0f + 1e-3f);
433   }
434   else {
435     pixel_array[pixel_id].primitive_id = -1;
436     pixel_array[pixel_id].object_id = -1;
437   }
438 
439   MEM_freeN(hits);
440   return hit_mesh != -1;
441 }
442 
443 /**
444  * This function populates an array of verts for the triangles of a mesh
445  * Tangent and Normals are also stored
446  */
mesh_calc_tri_tessface(Mesh * me,bool tangent,Mesh * me_eval)447 static TriTessFace *mesh_calc_tri_tessface(Mesh *me, bool tangent, Mesh *me_eval)
448 {
449   int i;
450   MVert *mvert;
451   TSpace *tspace = NULL;
452   float(*loop_normals)[3] = NULL;
453 
454   const int tottri = poly_to_tri_count(me->totpoly, me->totloop);
455   MLoopTri *looptri;
456   TriTessFace *triangles;
457 
458   /* calculate normal for each polygon only once */
459   unsigned int mpoly_prev = UINT_MAX;
460   float no[3];
461 
462   mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
463   looptri = MEM_mallocN(sizeof(*looptri) * tottri, __func__);
464   triangles = MEM_callocN(sizeof(TriTessFace) * tottri, __func__);
465 
466   BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, looptri);
467 
468   if (tangent) {
469     BKE_mesh_ensure_normals_for_display(me_eval);
470     BKE_mesh_calc_normals_split(me_eval);
471     BKE_mesh_calc_loop_tangents(me_eval, true, NULL, 0);
472 
473     tspace = CustomData_get_layer(&me_eval->ldata, CD_TANGENT);
474     BLI_assert(tspace);
475 
476     loop_normals = CustomData_get_layer(&me_eval->ldata, CD_NORMAL);
477   }
478 
479   const float *precomputed_normals = CustomData_get_layer(&me->pdata, CD_NORMAL);
480   const bool calculate_normal = precomputed_normals ? false : true;
481 
482   for (i = 0; i < tottri; i++) {
483     const MLoopTri *lt = &looptri[i];
484     const MPoly *mp = &me->mpoly[lt->poly];
485 
486     triangles[i].mverts[0] = &mvert[me->mloop[lt->tri[0]].v];
487     triangles[i].mverts[1] = &mvert[me->mloop[lt->tri[1]].v];
488     triangles[i].mverts[2] = &mvert[me->mloop[lt->tri[2]].v];
489     triangles[i].is_smooth = (mp->flag & ME_SMOOTH) != 0;
490 
491     if (tangent) {
492       triangles[i].tspace[0] = &tspace[lt->tri[0]];
493       triangles[i].tspace[1] = &tspace[lt->tri[1]];
494       triangles[i].tspace[2] = &tspace[lt->tri[2]];
495     }
496 
497     if (loop_normals) {
498       triangles[i].loop_normal[0] = loop_normals[lt->tri[0]];
499       triangles[i].loop_normal[1] = loop_normals[lt->tri[1]];
500       triangles[i].loop_normal[2] = loop_normals[lt->tri[2]];
501     }
502 
503     if (calculate_normal) {
504       if (lt->poly != mpoly_prev) {
505         BKE_mesh_calc_poly_normal(mp, &me->mloop[mp->loopstart], me->mvert, no);
506         mpoly_prev = lt->poly;
507       }
508       copy_v3_v3(triangles[i].normal, no);
509     }
510     else {
511       copy_v3_v3(triangles[i].normal, &precomputed_normals[lt->poly]);
512     }
513   }
514 
515   MEM_freeN(looptri);
516 
517   return triangles;
518 }
519 
RE_bake_pixels_populate_from_objects(struct Mesh * me_low,BakePixel pixel_array_from[],BakePixel pixel_array_to[],BakeHighPolyData highpoly[],const int tot_highpoly,const size_t num_pixels,const bool is_custom_cage,const float cage_extrusion,const float max_ray_distance,float mat_low[4][4],float mat_cage[4][4],struct Mesh * me_cage)520 bool RE_bake_pixels_populate_from_objects(struct Mesh *me_low,
521                                           BakePixel pixel_array_from[],
522                                           BakePixel pixel_array_to[],
523                                           BakeHighPolyData highpoly[],
524                                           const int tot_highpoly,
525                                           const size_t num_pixels,
526                                           const bool is_custom_cage,
527                                           const float cage_extrusion,
528                                           const float max_ray_distance,
529                                           float mat_low[4][4],
530                                           float mat_cage[4][4],
531                                           struct Mesh *me_cage)
532 {
533   size_t i;
534   int primitive_id;
535   float u, v;
536   float imat_low[4][4];
537   bool is_cage = me_cage != NULL;
538   bool result = true;
539 
540   Mesh *me_eval_low = NULL;
541   Mesh **me_highpoly;
542   BVHTreeFromMesh *treeData;
543 
544   /* Note: all coordinates are in local space */
545   TriTessFace *tris_low = NULL;
546   TriTessFace *tris_cage = NULL;
547   TriTessFace **tris_high;
548 
549   /* assume all lowpoly tessfaces can be quads */
550   tris_high = MEM_callocN(sizeof(TriTessFace *) * tot_highpoly, "MVerts Highpoly Mesh Array");
551 
552   /* assume all highpoly tessfaces are triangles */
553   me_highpoly = MEM_mallocN(sizeof(Mesh *) * tot_highpoly, "Highpoly Derived Meshes");
554   treeData = MEM_callocN(sizeof(BVHTreeFromMesh) * tot_highpoly, "Highpoly BVH Trees");
555 
556   if (!is_cage) {
557     me_eval_low = BKE_mesh_copy_for_eval(me_low, false);
558     tris_low = mesh_calc_tri_tessface(me_low, true, me_eval_low);
559   }
560   else if (is_custom_cage) {
561     tris_low = mesh_calc_tri_tessface(me_low, false, NULL);
562     tris_cage = mesh_calc_tri_tessface(me_cage, false, NULL);
563   }
564   else {
565     tris_cage = mesh_calc_tri_tessface(me_cage, false, NULL);
566   }
567 
568   invert_m4_m4(imat_low, mat_low);
569 
570   for (i = 0; i < tot_highpoly; i++) {
571     tris_high[i] = mesh_calc_tri_tessface(highpoly[i].me, false, NULL);
572 
573     me_highpoly[i] = highpoly[i].me;
574     BKE_mesh_runtime_looptri_ensure(me_highpoly[i]);
575 
576     if (me_highpoly[i]->runtime.looptris.len != 0) {
577       /* Create a bvh-tree for each highpoly object */
578       BKE_bvhtree_from_mesh_get(&treeData[i], me_highpoly[i], BVHTREE_FROM_LOOPTRI, 2);
579 
580       if (treeData[i].tree == NULL) {
581         printf("Baking: out of memory while creating BHVTree for object \"%s\"\n",
582                highpoly[i].ob->id.name + 2);
583         result = false;
584         goto cleanup;
585       }
586     }
587   }
588 
589   for (i = 0; i < num_pixels; i++) {
590     float co[3];
591     float dir[3];
592     TriTessFace *tri_low;
593 
594     primitive_id = pixel_array_from[i].primitive_id;
595 
596     if (primitive_id == -1) {
597       pixel_array_to[i].primitive_id = -1;
598       continue;
599     }
600 
601     u = pixel_array_from[i].uv[0];
602     v = pixel_array_from[i].uv[1];
603 
604     /* calculate from low poly mesh cage */
605     if (is_custom_cage) {
606       calc_point_from_barycentric_cage(
607           tris_low, tris_cage, mat_low, mat_cage, primitive_id, u, v, co, dir);
608       tri_low = &tris_cage[primitive_id];
609     }
610     else if (is_cage) {
611       calc_point_from_barycentric_extrusion(
612           tris_cage, mat_low, imat_low, primitive_id, u, v, cage_extrusion, co, dir, true);
613       tri_low = &tris_cage[primitive_id];
614     }
615     else {
616       calc_point_from_barycentric_extrusion(
617           tris_low, mat_low, imat_low, primitive_id, u, v, cage_extrusion, co, dir, false);
618       tri_low = &tris_low[primitive_id];
619     }
620 
621     /* cast ray */
622     if (!cast_ray_highpoly(treeData,
623                            tri_low,
624                            tris_high,
625                            pixel_array_from,
626                            pixel_array_to,
627                            mat_low,
628                            highpoly,
629                            co,
630                            dir,
631                            i,
632                            tot_highpoly,
633                            max_ray_distance)) {
634       /* if it fails mask out the original pixel array */
635       pixel_array_from[i].primitive_id = -1;
636     }
637   }
638 
639   /* garbage collection */
640 cleanup:
641   for (i = 0; i < tot_highpoly; i++) {
642     free_bvhtree_from_mesh(&treeData[i]);
643 
644     if (tris_high[i]) {
645       MEM_freeN(tris_high[i]);
646     }
647   }
648 
649   MEM_freeN(tris_high);
650   MEM_freeN(treeData);
651   MEM_freeN(me_highpoly);
652 
653   if (me_eval_low) {
654     BKE_id_free(NULL, me_eval_low);
655   }
656   if (tris_low) {
657     MEM_freeN(tris_low);
658   }
659   if (tris_cage) {
660     MEM_freeN(tris_cage);
661   }
662 
663   return result;
664 }
665 
bake_differentials(BakeDataZSpan * bd,const float * uv1,const float * uv2,const float * uv3)666 static void bake_differentials(BakeDataZSpan *bd,
667                                const float *uv1,
668                                const float *uv2,
669                                const float *uv3)
670 {
671   float A;
672 
673   /* assumes dPdu = P1 - P3 and dPdv = P2 - P3 */
674   A = (uv2[0] - uv1[0]) * (uv3[1] - uv1[1]) - (uv3[0] - uv1[0]) * (uv2[1] - uv1[1]);
675 
676   if (fabsf(A) > FLT_EPSILON) {
677     A = 0.5f / A;
678 
679     bd->du_dx = (uv2[1] - uv3[1]) * A;
680     bd->dv_dx = (uv3[1] - uv1[1]) * A;
681 
682     bd->du_dy = (uv3[0] - uv2[0]) * A;
683     bd->dv_dy = (uv1[0] - uv3[0]) * A;
684   }
685   else {
686     bd->du_dx = bd->du_dy = 0.0f;
687     bd->dv_dx = bd->dv_dy = 0.0f;
688   }
689 }
690 
RE_bake_pixels_populate(Mesh * me,BakePixel pixel_array[],const size_t num_pixels,const BakeImages * bake_images,const char * uv_layer)691 void RE_bake_pixels_populate(Mesh *me,
692                              BakePixel pixel_array[],
693                              const size_t num_pixels,
694                              const BakeImages *bake_images,
695                              const char *uv_layer)
696 {
697   const MLoopUV *mloopuv;
698   if ((uv_layer == NULL) || (uv_layer[0] == '\0')) {
699     mloopuv = CustomData_get_layer(&me->ldata, CD_MLOOPUV);
700   }
701   else {
702     int uv_id = CustomData_get_named_layer(&me->ldata, CD_MLOOPUV, uv_layer);
703     mloopuv = CustomData_get_layer_n(&me->ldata, CD_MLOOPUV, uv_id);
704   }
705 
706   if (mloopuv == NULL) {
707     return;
708   }
709 
710   BakeDataZSpan bd;
711   bd.pixel_array = pixel_array;
712   bd.zspan = MEM_callocN(sizeof(ZSpan) * bake_images->size, "bake zspan");
713 
714   /* initialize all pixel arrays so we know which ones are 'blank' */
715   for (int i = 0; i < num_pixels; i++) {
716     pixel_array[i].primitive_id = -1;
717     pixel_array[i].object_id = 0;
718   }
719 
720   for (int i = 0; i < bake_images->size; i++) {
721     zbuf_alloc_span(&bd.zspan[i], bake_images->data[i].width, bake_images->data[i].height);
722   }
723 
724   const int tottri = poly_to_tri_count(me->totpoly, me->totloop);
725   MLoopTri *looptri = MEM_mallocN(sizeof(*looptri) * tottri, __func__);
726 
727   BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, looptri);
728 
729   for (int i = 0; i < tottri; i++) {
730     const MLoopTri *lt = &looptri[i];
731     const MPoly *mp = &me->mpoly[lt->poly];
732     float vec[3][2];
733     int mat_nr = mp->mat_nr;
734     int image_id = bake_images->lookup[mat_nr];
735 
736     if (image_id < 0) {
737       continue;
738     }
739 
740     bd.bk_image = &bake_images->data[image_id];
741     bd.primitive_id = i;
742 
743     for (int a = 0; a < 3; a++) {
744       const float *uv = mloopuv[lt->tri[a]].uv;
745 
746       /* Note, workaround for pixel aligned UVs which are common and can screw up our
747        * intersection tests where a pixel gets in between 2 faces or the middle of a quad,
748        * camera aligned quads also have this problem but they are less common.
749        * Add a small offset to the UVs, fixes bug T18685 - Campbell */
750       vec[a][0] = uv[0] * (float)bd.bk_image->width - (0.5f + 0.001f);
751       vec[a][1] = uv[1] * (float)bd.bk_image->height - (0.5f + 0.002f);
752     }
753 
754     bake_differentials(&bd, vec[0], vec[1], vec[2]);
755     zspan_scanconvert(&bd.zspan[image_id], (void *)&bd, vec[0], vec[1], vec[2], store_bake_pixel);
756   }
757 
758   for (int i = 0; i < bake_images->size; i++) {
759     zbuf_free_span(&bd.zspan[i]);
760   }
761 
762   MEM_freeN(looptri);
763   MEM_freeN(bd.zspan);
764 }
765 
766 /* ******************** NORMALS ************************ */
767 
768 /**
769  * convert a normalized normal to the -1.0 1.0 range
770  * the input is expected to be POS_X, POS_Y, POS_Z
771  */
normal_uncompress(float out[3],const float in[3])772 static void normal_uncompress(float out[3], const float in[3])
773 {
774   int i;
775   for (i = 0; i < 3; i++) {
776     out[i] = 2.0f * in[i] - 1.0f;
777   }
778 }
779 
normal_compress(float out[3],const float in[3],const eBakeNormalSwizzle normal_swizzle[3])780 static void normal_compress(float out[3],
781                             const float in[3],
782                             const eBakeNormalSwizzle normal_swizzle[3])
783 {
784   const int swizzle_index[6] = {
785       0, /* R_BAKE_POSX */
786       1, /* R_BAKE_POSY */
787       2, /* R_BAKE_POSZ */
788       0, /* R_BAKE_NEGX */
789       1, /* R_BAKE_NEGY */
790       2, /* R_BAKE_NEGZ */
791   };
792   const float swizzle_sign[6] = {
793       +1.0f, /* R_BAKE_POSX */
794       +1.0f, /* R_BAKE_POSY */
795       +1.0f, /* R_BAKE_POSZ */
796       -1.0f, /* R_BAKE_NEGX */
797       -1.0f, /* R_BAKE_NEGY */
798       -1.0f, /* R_BAKE_NEGZ */
799   };
800 
801   int i;
802 
803   for (i = 0; i < 3; i++) {
804     int index;
805     float sign;
806 
807     sign = swizzle_sign[normal_swizzle[i]];
808     index = swizzle_index[normal_swizzle[i]];
809 
810     /*
811      * There is a small 1e-5f bias for precision issues. otherwise
812      * we randomly get 127 or 128 for neutral colors in tangent maps.
813      * we choose 128 because it is the convention flat color. *
814      */
815 
816     out[i] = sign * in[index] / 2.0f + 0.5f + 1e-5f;
817   }
818 }
819 
820 /**
821  * This function converts an object space normal map
822  * to a tangent space normal map for a given low poly mesh.
823  */
RE_bake_normal_world_to_tangent(const BakePixel pixel_array[],const size_t num_pixels,const int depth,float result[],Mesh * me,const eBakeNormalSwizzle normal_swizzle[3],float mat[4][4])824 void RE_bake_normal_world_to_tangent(const BakePixel pixel_array[],
825                                      const size_t num_pixels,
826                                      const int depth,
827                                      float result[],
828                                      Mesh *me,
829                                      const eBakeNormalSwizzle normal_swizzle[3],
830                                      float mat[4][4])
831 {
832   size_t i;
833 
834   TriTessFace *triangles;
835 
836   Mesh *me_eval = BKE_mesh_copy_for_eval(me, false);
837 
838   triangles = mesh_calc_tri_tessface(me, true, me_eval);
839 
840   BLI_assert(num_pixels >= 3);
841 
842   for (i = 0; i < num_pixels; i++) {
843     TriTessFace *triangle;
844     float tangents[3][3];
845     float normals[3][3];
846     float signs[3];
847     int j;
848 
849     float tangent[3];
850     float normal[3];
851     float binormal[3];
852     float sign;
853     float u, v, w;
854 
855     float tsm[3][3]; /* tangent space matrix */
856     float itsm[3][3];
857 
858     size_t offset;
859     float nor[3]; /* texture normal */
860 
861     bool is_smooth;
862 
863     int primitive_id = pixel_array[i].primitive_id;
864 
865     offset = i * depth;
866 
867     if (primitive_id == -1) {
868       if (depth == 4) {
869         copy_v4_fl4(&result[offset], 0.5f, 0.5f, 1.0f, 1.0f);
870       }
871       else {
872         copy_v3_fl3(&result[offset], 0.5f, 0.5f, 1.0f);
873       }
874       continue;
875     }
876 
877     triangle = &triangles[primitive_id];
878     is_smooth = triangle->is_smooth;
879 
880     for (j = 0; j < 3; j++) {
881       const TSpace *ts;
882 
883       if (is_smooth) {
884         if (triangle->loop_normal[j]) {
885           copy_v3_v3(normals[j], triangle->loop_normal[j]);
886         }
887         else {
888           normal_short_to_float_v3(normals[j], triangle->mverts[j]->no);
889         }
890       }
891 
892       ts = triangle->tspace[j];
893       copy_v3_v3(tangents[j], ts->tangent);
894       signs[j] = ts->sign;
895     }
896 
897     u = pixel_array[i].uv[0];
898     v = pixel_array[i].uv[1];
899     w = 1.0f - u - v;
900 
901     /* normal */
902     if (is_smooth) {
903       interp_barycentric_tri_v3(normals, u, v, normal);
904     }
905     else {
906       copy_v3_v3(normal, triangle->normal);
907     }
908 
909     /* tangent */
910     interp_barycentric_tri_v3(tangents, u, v, tangent);
911 
912     /* sign */
913     /* The sign is the same at all face vertices for any non degenerate face.
914      * Just in case we clamp the interpolated value though. */
915     sign = (signs[0] * u + signs[1] * v + signs[2] * w) < 0 ? (-1.0f) : 1.0f;
916 
917     /* binormal */
918     /* B = sign * cross(N, T)  */
919     cross_v3_v3v3(binormal, normal, tangent);
920     mul_v3_fl(binormal, sign);
921 
922     /* populate tangent space matrix */
923     copy_v3_v3(tsm[0], tangent);
924     copy_v3_v3(tsm[1], binormal);
925     copy_v3_v3(tsm[2], normal);
926 
927     /* texture values */
928     normal_uncompress(nor, &result[offset]);
929 
930     /* converts from world space to local space */
931     mul_transposed_mat3_m4_v3(mat, nor);
932 
933     invert_m3_m3(itsm, tsm);
934     mul_m3_v3(itsm, nor);
935     normalize_v3(nor);
936 
937     /* save back the values */
938     normal_compress(&result[offset], nor, normal_swizzle);
939   }
940 
941   /* garbage collection */
942   MEM_freeN(triangles);
943 
944   if (me_eval) {
945     BKE_id_free(NULL, me_eval);
946   }
947 }
948 
RE_bake_normal_world_to_object(const BakePixel pixel_array[],const size_t num_pixels,const int depth,float result[],struct Object * ob,const eBakeNormalSwizzle normal_swizzle[3])949 void RE_bake_normal_world_to_object(const BakePixel pixel_array[],
950                                     const size_t num_pixels,
951                                     const int depth,
952                                     float result[],
953                                     struct Object *ob,
954                                     const eBakeNormalSwizzle normal_swizzle[3])
955 {
956   size_t i;
957   float iobmat[4][4];
958 
959   invert_m4_m4(iobmat, ob->obmat);
960 
961   for (i = 0; i < num_pixels; i++) {
962     size_t offset;
963     float nor[3];
964 
965     if (pixel_array[i].primitive_id == -1) {
966       continue;
967     }
968 
969     offset = i * depth;
970     normal_uncompress(nor, &result[offset]);
971 
972     /* rotates only without translation */
973     mul_mat3_m4_v3(iobmat, nor);
974     normalize_v3(nor);
975 
976     /* save back the values */
977     normal_compress(&result[offset], nor, normal_swizzle);
978   }
979 }
980 
RE_bake_normal_world_to_world(const BakePixel pixel_array[],const size_t num_pixels,const int depth,float result[],const eBakeNormalSwizzle normal_swizzle[3])981 void RE_bake_normal_world_to_world(const BakePixel pixel_array[],
982                                    const size_t num_pixels,
983                                    const int depth,
984                                    float result[],
985                                    const eBakeNormalSwizzle normal_swizzle[3])
986 {
987   size_t i;
988 
989   for (i = 0; i < num_pixels; i++) {
990     size_t offset;
991     float nor[3];
992 
993     if (pixel_array[i].primitive_id == -1) {
994       continue;
995     }
996 
997     offset = i * depth;
998     normal_uncompress(nor, &result[offset]);
999 
1000     /* save back the values */
1001     normal_compress(&result[offset], nor, normal_swizzle);
1002   }
1003 }
1004 
RE_bake_ibuf_clear(Image * image,const bool is_tangent)1005 void RE_bake_ibuf_clear(Image *image, const bool is_tangent)
1006 {
1007   ImBuf *ibuf;
1008   void *lock;
1009 
1010   const float vec_alpha[4] = {0.0f, 0.0f, 0.0f, 0.0f};
1011   const float vec_solid[4] = {0.0f, 0.0f, 0.0f, 1.0f};
1012   const float nor_alpha[4] = {0.5f, 0.5f, 1.0f, 0.0f};
1013   const float nor_solid[4] = {0.5f, 0.5f, 1.0f, 1.0f};
1014 
1015   ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
1016   BLI_assert(ibuf);
1017 
1018   if (is_tangent) {
1019     IMB_rectfill(ibuf, (ibuf->planes == R_IMF_PLANES_RGBA) ? nor_alpha : nor_solid);
1020   }
1021   else {
1022     IMB_rectfill(ibuf, (ibuf->planes == R_IMF_PLANES_RGBA) ? vec_alpha : vec_solid);
1023   }
1024 
1025   BKE_image_release_ibuf(image, ibuf, lock);
1026 }
1027 
1028 /* ************************************************************* */
1029 
RE_pass_depth(const eScenePassType pass_type)1030 int RE_pass_depth(const eScenePassType pass_type)
1031 {
1032   /* IMB_buffer_byte_from_float assumes 4 channels
1033    * making it work for now - XXX */
1034   return 4;
1035 
1036   switch (pass_type) {
1037     case SCE_PASS_Z:
1038     case SCE_PASS_AO:
1039     case SCE_PASS_MIST: {
1040       return 1;
1041     }
1042     case SCE_PASS_UV: {
1043       return 2;
1044     }
1045     case SCE_PASS_COMBINED:
1046     case SCE_PASS_SHADOW:
1047     case SCE_PASS_NORMAL:
1048     case SCE_PASS_VECTOR:
1049     case SCE_PASS_INDEXOB: /* XXX double check */
1050     case SCE_PASS_RAYHITS: /* XXX double check */
1051     case SCE_PASS_EMIT:
1052     case SCE_PASS_ENVIRONMENT:
1053     case SCE_PASS_INDEXMA:
1054     case SCE_PASS_DIFFUSE_DIRECT:
1055     case SCE_PASS_DIFFUSE_INDIRECT:
1056     case SCE_PASS_DIFFUSE_COLOR:
1057     case SCE_PASS_GLOSSY_DIRECT:
1058     case SCE_PASS_GLOSSY_INDIRECT:
1059     case SCE_PASS_GLOSSY_COLOR:
1060     case SCE_PASS_TRANSM_DIRECT:
1061     case SCE_PASS_TRANSM_INDIRECT:
1062     case SCE_PASS_TRANSM_COLOR:
1063     case SCE_PASS_SUBSURFACE_DIRECT:
1064     case SCE_PASS_SUBSURFACE_INDIRECT:
1065     case SCE_PASS_SUBSURFACE_COLOR:
1066     default: {
1067       return 3;
1068     }
1069   }
1070 }
1071