style cleanup: follow style guide for formatting of if/for/while loops, and else...
[blender.git] / source / blender / editors / object / object_bake.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
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  * The Original Code is Copyright (C) 2004 by Blender Foundation
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Morten Mikkelsen,
24  *                 Sergey Sharybin
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 /** \file blender/editors/object/object_bake.c
30  *  \ingroup edobj
31  */
32
33 #include <string.h>
34
35 #include "MEM_guardedalloc.h"
36
37 #include "DNA_scene_types.h"
38 #include "DNA_screen_types.h"
39 #include "DNA_space_types.h"
40 #include "DNA_world_types.h"
41 #include "DNA_object_types.h"
42 #include "DNA_mesh_types.h"
43 #include "DNA_meshdata_types.h"
44
45 #include "BLI_blenlib.h"
46 #include "BLI_threads.h"
47 #include "BLI_utildefines.h"
48 #include "BLI_math.h"
49 #include "BLI_math_geom.h"
50
51 #include "BKE_blender.h"
52 #include "BKE_screen.h"
53 #include "BKE_context.h"
54 #include "BKE_global.h"
55 #include "BKE_image.h"
56 #include "BKE_main.h"
57 #include "BKE_multires.h"
58 #include "BKE_report.h"
59 #include "BKE_cdderivedmesh.h"
60 #include "BKE_modifier.h"
61 #include "BKE_DerivedMesh.h"
62 #include "BKE_subsurf.h"
63
64 #include "RE_pipeline.h"
65 #include "RE_shader_ext.h"
66
67 #include "PIL_time.h"
68
69 #include "IMB_imbuf_types.h"
70 #include "IMB_imbuf.h"
71
72 #include "GPU_draw.h" /* GPU_free_image */
73
74 #include "WM_api.h"
75 #include "WM_types.h"
76
77 #include "ED_object.h"
78
79 #include "object_intern.h"
80
81 /* ****************** multires BAKING ********************** */
82
83 /* holder of per-object data needed for bake job
84  * needed to make job totally thread-safe */
85 typedef struct MultiresBakerJobData {
86         struct MultiresBakerJobData *next, *prev;
87         DerivedMesh *lores_dm, *hires_dm;
88         int simple, lvl, tot_lvl;
89 } MultiresBakerJobData;
90
91 /* data passing to multires-baker job */
92 typedef struct {
93         ListBase data;
94         int bake_clear, bake_filter;
95         short mode, use_lores_mesh;
96 } MultiresBakeJob;
97
98 /* data passing to multires baker */
99 typedef struct {
100         DerivedMesh *lores_dm, *hires_dm;
101         int simple, lvl, tot_lvl, bake_filter;
102         short mode, use_lores_mesh;
103
104         int tot_obj, tot_image;
105         ListBase image;
106
107         int baked_objects, baked_faces;
108
109         short *stop;
110         short *do_update;
111         float *progress;
112 } MultiresBakeRender;
113
114 typedef void (*MPassKnownData)(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *bake_data,
115                                const int face_index, const int lvl, const float st[2],
116                                float tangmat[3][3], const int x, const int y);
117
118 typedef void* (*MInitBakeData)(MultiresBakeRender *bkr, Image* ima);
119 typedef void (*MApplyBakeData)(void *bake_data);
120 typedef void (*MFreeBakeData)(void *bake_data);
121
122 typedef struct {
123         MVert *mvert;
124         MFace *mface;
125         MTFace *mtface;
126         float *pvtangent;
127         float *precomputed_normals;
128         int w, h;
129         int face_index;
130         int i0, i1, i2;
131         DerivedMesh *lores_dm, *hires_dm;
132         int lvl;
133         void *bake_data;
134         MPassKnownData pass_data;
135 } MResolvePixelData;
136
137 typedef void (*MFlushPixel)(const MResolvePixelData *data, const int x, const int y);
138
139 typedef struct {
140         int w, h;
141         char *texels;
142         const MResolvePixelData *data;
143         MFlushPixel flush_pixel;
144 } MBakeRast;
145
146 typedef struct {
147         float *heights;
148         float height_min, height_max;
149         Image *ima;
150         DerivedMesh *ssdm;
151         const int *origindex;
152 } MHeightBakeData;
153
154 typedef struct {
155         const int *origindex;
156 } MNormalBakeData;
157
158 static void multiresbake_get_normal(const MResolvePixelData *data, float norm[], const int face_num, const int vert_index)
159 {
160         unsigned int indices[]= {data->mface[face_num].v1, data->mface[face_num].v2,
161                                  data->mface[face_num].v3, data->mface[face_num].v4};
162         const int smoothnormal= (data->mface[face_num].flag & ME_SMOOTH);
163
164         if (!smoothnormal) { /* flat */
165                 if (data->precomputed_normals) {
166                         copy_v3_v3(norm, &data->precomputed_normals[3*face_num]);
167                 }
168                 else {
169                         float nor[3];
170                         float *p0, *p1, *p2;
171                         const int iGetNrVerts= data->mface[face_num].v4!=0 ? 4 : 3;
172
173                         p0= data->mvert[indices[0]].co;
174                         p1= data->mvert[indices[1]].co;
175                         p2= data->mvert[indices[2]].co;
176
177                         if (iGetNrVerts==4) {
178                                 float *p3= data->mvert[indices[3]].co;
179                                 normal_quad_v3(nor, p0, p1, p2, p3);
180                         }
181                         else {
182                                 normal_tri_v3(nor, p0, p1, p2);
183                         }
184
185                         copy_v3_v3(norm, nor);
186                 }
187         }
188         else {
189                 short *no= data->mvert[indices[vert_index]].no;
190
191                 normal_short_to_float_v3(norm, no);
192                 normalize_v3(norm);
193         }
194 }
195
196 static void init_bake_rast(MBakeRast *bake_rast, const ImBuf *ibuf, const MResolvePixelData *data, MFlushPixel flush_pixel)
197 {
198         memset(bake_rast, 0, sizeof(MBakeRast));
199
200         bake_rast->texels = ibuf->userdata;
201         bake_rast->w= ibuf->x;
202         bake_rast->h= ibuf->y;
203         bake_rast->data= data;
204         bake_rast->flush_pixel= flush_pixel;
205 }
206
207 static void flush_pixel(const MResolvePixelData *data, const int x, const int y)
208 {
209         float st[2]= {(x+0.5f)/data->w, (y+0.5f)/data->h};
210         float *st0, *st1, *st2;
211         float *tang0, *tang1, *tang2;
212         float no0[3], no1[3], no2[3];
213         float fUV[2], from_tang[3][3], to_tang[3][3];
214         float u, v, w, sign;
215         int r;
216
217         const int i0= data->i0;
218         const int i1= data->i1;
219         const int i2= data->i2;
220
221         st0= data->mtface[data->face_index].uv[i0];
222         st1= data->mtface[data->face_index].uv[i1];
223         st2= data->mtface[data->face_index].uv[i2];
224
225         tang0= data->pvtangent + data->face_index*16 + i0*4;
226         tang1= data->pvtangent + data->face_index*16 + i1*4;
227         tang2= data->pvtangent + data->face_index*16 + i2*4;
228
229         multiresbake_get_normal(data, no0, data->face_index, i0);       /* can optimize these 3 into one call */
230         multiresbake_get_normal(data, no1, data->face_index, i1);
231         multiresbake_get_normal(data, no2, data->face_index, i2);
232
233         resolve_tri_uv(fUV, st, st0, st1, st2);
234
235         u= fUV[0];
236         v= fUV[1];
237         w= 1-u-v;
238
239         /* the sign is the same at all face vertices for any non degenerate face.
240          * Just in case we clamp the interpolated value though. */
241         sign= (tang0[3]*u + tang1[3]*v + tang2[3]*w)<0 ? (-1.0f) : 1.0f;
242
243         /* this sequence of math is designed specifically as is with great care
244          * to be compatible with our shader. Please don't change without good reason. */
245         for (r= 0; r<3; r++) {
246                 from_tang[0][r]= tang0[r]*u + tang1[r]*v + tang2[r]*w;
247                 from_tang[2][r]= no0[r]*u + no1[r]*v + no2[r]*w;
248         }
249
250         cross_v3_v3v3(from_tang[1], from_tang[2], from_tang[0]);  /* B = sign * cross(N, T)  */
251         mul_v3_fl(from_tang[1], sign);
252         invert_m3_m3(to_tang, from_tang);
253         /* sequence end */
254
255         data->pass_data(data->lores_dm, data->hires_dm, data->bake_data,
256                         data->face_index, data->lvl, st, to_tang, x, y);
257 }
258
259 static void set_rast_triangle(const MBakeRast *bake_rast, const int x, const int y)
260 {
261         const int w= bake_rast->w;
262         const int h= bake_rast->h;
263
264         if (x>=0 && x<w && y>=0 && y<h) {
265                 if ((bake_rast->texels[y*w+x])==0) {
266                         flush_pixel(bake_rast->data, x, y);
267                         bake_rast->texels[y*w+x]= FILTER_MASK_USED;
268                 }
269         }
270 }
271
272 static void rasterize_half(const MBakeRast *bake_rast,
273                            const float s0_s, const float t0_s, const float s1_s, const float t1_s,
274                            const float s0_l, const float t0_l, const float s1_l, const float t1_l,
275                            const int y0_in, const int y1_in, const int is_mid_right)
276 {
277         const int s_stable= fabsf(t1_s-t0_s)>FLT_EPSILON ? 1 : 0;
278         const int l_stable= fabsf(t1_l-t0_l)>FLT_EPSILON ? 1 : 0;
279         const int w= bake_rast->w;
280         const int h= bake_rast->h;
281         int y, y0, y1;
282
283         if (y1_in<=0 || y0_in>=h)
284                 return;
285
286         y0= y0_in<0 ? 0 : y0_in;
287         y1= y1_in>=h ? h : y1_in;
288
289         for (y= y0; y<y1; y++) {
290                 /*-b(x-x0) + a(y-y0) = 0 */
291                 int iXl, iXr, x;
292                 float x_l= s_stable!=0 ? (s0_s + (((s1_s-s0_s)*(y-t0_s))/(t1_s-t0_s))) : s0_s;
293                 float x_r= l_stable!=0 ? (s0_l + (((s1_l-s0_l)*(y-t0_l))/(t1_l-t0_l))) : s0_l;
294
295                 if (is_mid_right!=0)
296                         SWAP(float, x_l, x_r);
297
298                 iXl= (int)ceilf(x_l);
299                 iXr= (int)ceilf(x_r);
300
301                 if (iXr>0 && iXl<w) {
302                         iXl= iXl<0?0:iXl;
303                         iXr= iXr>=w?w:iXr;
304
305                         for (x= iXl; x<iXr; x++)
306                                 set_rast_triangle(bake_rast, x, y);
307                 }
308         }
309 }
310
311 static void bake_rasterize(const MBakeRast *bake_rast, const float st0_in[2], const float st1_in[2], const float st2_in[2])
312 {
313         const int w= bake_rast->w;
314         const int h= bake_rast->h;
315         float slo= st0_in[0]*w - 0.5f;
316         float tlo= st0_in[1]*h - 0.5f;
317         float smi= st1_in[0]*w - 0.5f;
318         float tmi= st1_in[1]*h - 0.5f;
319         float shi= st2_in[0]*w - 0.5f;
320         float thi= st2_in[1]*h - 0.5f;
321         int is_mid_right= 0, ylo, yhi, yhi_beg;
322
323         /* skip degenerates */
324         if ((slo==smi && tlo==tmi) || (slo==shi && tlo==thi) || (smi==shi && tmi==thi))
325                 return;
326
327         /* sort by T */
328         if (tlo>tmi && tlo>thi) {
329                 SWAP(float, shi, slo);
330                 SWAP(float, thi, tlo);
331         }
332         else if (tmi>thi) {
333                 SWAP(float, shi, smi);
334                 SWAP(float, thi, tmi);
335         }
336
337         if (tlo>tmi) {
338                 SWAP(float, slo, smi);
339                 SWAP(float, tlo, tmi);
340         }
341
342         /* check if mid point is to the left or to the right of the lo-hi edge */
343         is_mid_right= (-(shi-slo)*(tmi-thi) + (thi-tlo)*(smi-shi))>0 ? 1 : 0;
344         ylo= (int) ceilf(tlo);
345         yhi_beg= (int) ceilf(tmi);
346         yhi= (int) ceilf(thi);
347
348         /*if(fTmi>ceilf(fTlo))*/
349         rasterize_half(bake_rast, slo, tlo, smi, tmi, slo, tlo, shi, thi, ylo, yhi_beg, is_mid_right);
350         rasterize_half(bake_rast, smi, tmi, shi, thi, slo, tlo, shi, thi, yhi_beg, yhi, is_mid_right);
351 }
352
353 static int multiresbake_test_break(MultiresBakeRender *bkr)
354 {
355         if (!bkr->stop) {
356                 /* this means baker is executed outside from job system */
357                 return 0;
358         }
359
360         return G.afbreek;
361 }
362
363 static void do_multires_bake(MultiresBakeRender *bkr, Image* ima, MPassKnownData passKnownData,
364                              MInitBakeData initBakeData, MApplyBakeData applyBakeData, MFreeBakeData freeBakeData)
365 {
366         DerivedMesh *dm= bkr->lores_dm;
367         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
368         const int lvl= bkr->lvl;
369         const int tot_face= dm->getNumTessFaces(dm);
370         MVert *mvert= dm->getVertArray(dm);
371         MFace *mface= dm->getTessFaceArray(dm);
372         MTFace *mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
373         float *pvtangent= NULL;
374
375         if (CustomData_get_layer_index(&dm->faceData, CD_TANGENT) == -1)
376                 DM_add_tangent_layer(dm);
377
378         pvtangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
379
380         if (tot_face > 0) {  /* sanity check */
381                 int f= 0;
382                 MBakeRast bake_rast;
383                 MResolvePixelData data={NULL};
384
385                 data.mface= mface;
386                 data.mvert= mvert;
387                 data.mtface= mtface;
388                 data.pvtangent= pvtangent;
389                 data.precomputed_normals= dm->getTessFaceDataArray(dm, CD_NORMAL);      /* don't strictly need this */
390                 data.w= ibuf->x;
391                 data.h= ibuf->y;
392                 data.lores_dm= dm;
393                 data.hires_dm= bkr->hires_dm;
394                 data.lvl= lvl;
395                 data.pass_data= passKnownData;
396
397                 if (initBakeData)
398                         data.bake_data= initBakeData(bkr, ima);
399
400                 init_bake_rast(&bake_rast, ibuf, &data, flush_pixel);
401
402                 for (f= 0; f<tot_face; f++) {
403                         MTFace *mtfate= &mtface[f];
404                         int verts[3][2], nr_tris, t;
405
406                         if (multiresbake_test_break(bkr))
407                                 break;
408
409                         if (mtfate->tpage!=ima)
410                                 continue;
411
412                         data.face_index= f;
413
414                         /* might support other forms of diagonal splits later on such as
415                          * split by shortest diagonal.*/
416                         verts[0][0]=0;
417                         verts[1][0]=1;
418                         verts[2][0]=2;
419
420                         verts[0][1]=0;
421                         verts[1][1]=2;
422                         verts[2][1]=3;
423
424                         nr_tris= mface[f].v4!=0 ? 2 : 1;
425                         for (t= 0; t<nr_tris; t++) {
426                                 data.i0 = verts[0][t];
427                                 data.i1 = verts[1][t];
428                                 data.i2 = verts[2][t];
429
430                                 bake_rasterize(&bake_rast, mtfate->uv[data.i0], mtfate->uv[data.i1], mtfate->uv[data.i2]);
431                         }
432
433                         bkr->baked_faces++;
434
435                         if (bkr->do_update)
436                                 *bkr->do_update= 1;
437
438                         if (bkr->progress)
439                                 *bkr->progress= ((float)bkr->baked_objects + (float)bkr->baked_faces / tot_face) / bkr->tot_obj;
440                 }
441
442                 if (applyBakeData)
443                         applyBakeData(data.bake_data);
444
445                 if (freeBakeData)
446                         freeBakeData(data.bake_data);
447         }
448 }
449
450 static void interp_bilinear_quad_data(float data[4][3], float u, float v, float res[3])
451 {
452         float vec[3];
453
454         copy_v3_v3(res, data[0]);
455         mul_v3_fl(res, (1-u)*(1-v));
456         copy_v3_v3(vec, data[1]);
457         mul_v3_fl(vec, u*(1-v)); add_v3_v3(res, vec);
458         copy_v3_v3(vec, data[2]);
459         mul_v3_fl(vec, u*v); add_v3_v3(res, vec);
460         copy_v3_v3(vec, data[3]);
461         mul_v3_fl(vec, (1-u)*v); add_v3_v3(res, vec);
462 }
463
464 static void interp_barycentric_tri_data(float data[3][3], float u, float v, float res[3])
465 {
466         float vec[3];
467
468         copy_v3_v3(res, data[0]);
469         mul_v3_fl(res, u);
470         copy_v3_v3(vec, data[1]);
471         mul_v3_fl(vec, v); add_v3_v3(res, vec);
472         copy_v3_v3(vec, data[2]);
473         mul_v3_fl(vec, 1.0f-u-v); add_v3_v3(res, vec);
474 }
475
476 /* mode = 0: interpolate normals,
477  * mode = 1: interpolate coord */
478 static void interp_bilinear_grid(DMGridData *grid, int grid_size, float crn_x, float crn_y, int mode, float res[3])
479 {
480         int x0, x1, y0, y1;
481         float u, v;
482         float data[4][3];
483
484         x0= (int) crn_x;
485         x1= x0>=(grid_size-1) ? (grid_size-1) : (x0+1);
486
487         y0= (int) crn_y;
488         y1= y0>=(grid_size-1) ? (grid_size-1) : (y0+1);
489
490         u= crn_x-x0;
491         v= crn_y-y0;
492
493         if (mode == 0) {
494                 copy_v3_v3(data[0], grid[y0 * grid_size + x0].no);
495                 copy_v3_v3(data[1], grid[y0 * grid_size + x1].no);
496                 copy_v3_v3(data[2], grid[y1 * grid_size + x1].no);
497                 copy_v3_v3(data[3], grid[y1 * grid_size + x0].no);
498         }
499         else {
500                 copy_v3_v3(data[0], grid[y0 * grid_size + x0].co);
501                 copy_v3_v3(data[1], grid[y0 * grid_size + x1].co);
502                 copy_v3_v3(data[2], grid[y1 * grid_size + x1].co);
503                 copy_v3_v3(data[3], grid[y1 * grid_size + x0].co);
504         }
505
506         interp_bilinear_quad_data(data, u, v, res);
507 }
508
509 static void get_ccgdm_data(DerivedMesh *lodm, DerivedMesh *hidm, const int *origindex,  const int lvl, const int face_index, const float u, const float v, float co[3], float n[3])
510 {
511         MFace mface;
512         DMGridData **grid_data;
513         float crn_x, crn_y;
514         int grid_size, S, face_side;
515         int *grid_offset, g_index;
516
517         lodm->getTessFace(lodm, face_index, &mface);
518
519         grid_size= hidm->getGridSize(hidm);
520         grid_data= hidm->getGridData(hidm);
521         grid_offset= hidm->getGridOffset(hidm);
522
523         face_side= (grid_size<<1)-1;
524
525         if (lvl==0) {
526                 g_index= grid_offset[face_index];
527                 S= mdisp_rot_face_to_crn(mface.v4 ? 4 : 3, face_side, u*(face_side-1), v*(face_side-1), &crn_x, &crn_y);
528         }
529         else {
530                 int side= (1 << (lvl-1)) + 1;
531                 int grid_index= origindex[face_index];
532                 int loc_offs= face_index % (1<<(2*lvl));
533                 int cell_index= loc_offs % ((side-1)*(side-1));
534                 int cell_side= grid_size / (side-1);
535                 int row= cell_index / (side-1);
536                 int col= cell_index % (side-1);
537
538                 S= face_index / (1<<(2*(lvl-1))) - grid_offset[grid_index];
539                 g_index= grid_offset[grid_index];
540
541                 crn_y= (row * cell_side) + u * cell_side;
542                 crn_x= (col * cell_side) + v * cell_side;
543         }
544
545         CLAMP(crn_x, 0.0f, grid_size);
546         CLAMP(crn_y, 0.0f, grid_size);
547
548         if (n != NULL)
549                 interp_bilinear_grid(grid_data[g_index + S], grid_size, crn_x, crn_y, 0, n);
550
551         if (co != NULL)
552                 interp_bilinear_grid(grid_data[g_index + S], grid_size, crn_x, crn_y, 1, co);
553 }
554
555 /* mode = 0: interpolate normals,
556  * mode = 1: interpolate coord */
557 static void interp_bilinear_mface(DerivedMesh *dm, MFace *mface, const float u, const float v, const int mode, float res[3])
558 {
559         float data[4][3];
560
561         if (mode == 0) {
562                 dm->getVertNo(dm, mface->v1, data[0]);
563                 dm->getVertNo(dm, mface->v2, data[1]);
564                 dm->getVertNo(dm, mface->v3, data[2]);
565                 dm->getVertNo(dm, mface->v4, data[3]);
566         }
567         else {
568                 dm->getVertCo(dm, mface->v1, data[0]);
569                 dm->getVertCo(dm, mface->v2, data[1]);
570                 dm->getVertCo(dm, mface->v3, data[2]);
571                 dm->getVertCo(dm, mface->v4, data[3]);
572         }
573
574         interp_bilinear_quad_data(data, u, v, res);
575 }
576
577 /* mode = 0: interpolate normals,
578  * mode = 1: interpolate coord */
579 static void interp_barycentric_mface(DerivedMesh *dm, MFace *mface, const float u, const float v, const int mode, float res[3])
580 {
581         float data[3][3];
582
583         if (mode == 0) {
584                 dm->getVertNo(dm, mface->v1, data[0]);
585                 dm->getVertNo(dm, mface->v2, data[1]);
586                 dm->getVertNo(dm, mface->v3, data[2]);
587         }
588         else {
589                 dm->getVertCo(dm, mface->v1, data[0]);
590                 dm->getVertCo(dm, mface->v2, data[1]);
591                 dm->getVertCo(dm, mface->v3, data[2]);
592         }
593
594         interp_barycentric_tri_data(data, u, v, res);
595 }
596
597 static void *init_heights_data(MultiresBakeRender *bkr, Image *ima)
598 {
599         MHeightBakeData *height_data;
600         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
601         DerivedMesh *lodm= bkr->lores_dm;
602
603         height_data= MEM_callocN(sizeof(MHeightBakeData), "MultiresBake heightData");
604
605         height_data->ima= ima;
606         height_data->heights= MEM_callocN(sizeof(float)*ibuf->x*ibuf->y, "MultiresBake heights");
607         height_data->height_max= -FLT_MAX;
608         height_data->height_min= FLT_MAX;
609
610         if (!bkr->use_lores_mesh) {
611                 SubsurfModifierData smd= {{NULL}};
612                 int ss_lvl= bkr->tot_lvl - bkr->lvl;
613
614                 CLAMP(ss_lvl, 0, 6);
615
616                 smd.levels= smd.renderLevels= ss_lvl;
617                 smd.flags|= eSubsurfModifierFlag_SubsurfUv;
618
619                 if (bkr->simple)
620                         smd.subdivType= ME_SIMPLE_SUBSURF;
621
622                 height_data->ssdm= subsurf_make_derived_from_derived(bkr->lores_dm, &smd, 0, NULL, 0, 0, 0);
623         }
624
625         height_data->origindex= lodm->getTessFaceDataArray(lodm, CD_ORIGINDEX);
626
627         return (void*)height_data;
628 }
629
630 static void *init_normal_data(MultiresBakeRender *bkr, Image *UNUSED(ima))
631 {
632         MNormalBakeData *normal_data;
633         DerivedMesh *lodm= bkr->lores_dm;
634
635         normal_data= MEM_callocN(sizeof(MNormalBakeData), "MultiresBake normalData");
636
637         normal_data->origindex= lodm->getTessFaceDataArray(lodm, CD_ORIGINDEX);
638
639         return (void*)normal_data;
640 }
641
642 static void free_normal_data(void *bake_data)
643 {
644         MNormalBakeData *normal_data= (MNormalBakeData*)bake_data;
645
646         MEM_freeN(normal_data);
647 }
648
649 static void apply_heights_data(void *bake_data)
650 {
651         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
652         ImBuf *ibuf= BKE_image_get_ibuf(height_data->ima, NULL);
653         int x, y, i;
654         float height, *heights= height_data->heights;
655         float min= height_data->height_min, max= height_data->height_max;
656
657         for (x= 0; x<ibuf->x; x++) {
658                 for (y =0; y<ibuf->y; y++) {
659                         i= ibuf->x*y + x;
660
661                         if (((char*)ibuf->userdata)[i] != FILTER_MASK_USED)
662                                 continue;
663
664                         if (ibuf->rect_float) {
665                                 float *rrgbf= ibuf->rect_float + i*4;
666
667                                 if (max-min > 1e-5f) height= (heights[i]-min)/(max-min);
668                                 else height= 0;
669
670                                 rrgbf[0]=rrgbf[1]=rrgbf[2]= height;
671                         }
672                         else {
673                                 char *rrgb= (char*)ibuf->rect + i*4;
674
675                                 if (max-min > 1e-5f) height= (heights[i]-min)/(max-min);
676                                 else height= 0;
677
678                                 rrgb[0]=rrgb[1]=rrgb[2]= FTOCHAR(height);
679                         }
680                 }
681         }
682
683         ibuf->userflags= IB_RECT_INVALID;
684 }
685
686 static void free_heights_data(void *bake_data)
687 {
688         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
689
690         if (height_data->ssdm)
691                 height_data->ssdm->release(height_data->ssdm);
692
693         MEM_freeN(height_data->heights);
694         MEM_freeN(height_data);
695 }
696
697 /* MultiresBake callback for heights baking
698  * general idea:
699  *   - find coord of point with specified UV in hi-res mesh (let's call it p1)
700  *   - find coord of point and normal with specified UV in lo-res mesh (or subdivided lo-res
701  *     mesh to make texture smoother) let's call this point p0 and n.
702  *   - height wound be dot(n, p1-p0) */
703 static void apply_heights_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *bake_data,
704                                    const int face_index, const int lvl, const float st[2],
705                                    float UNUSED(tangmat[3][3]), const int x, const int y)
706 {
707         MTFace *mtface= CustomData_get_layer(&lores_dm->faceData, CD_MTFACE);
708         MFace mface;
709         Image *ima= mtface[face_index].tpage;
710         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
711         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
712         float uv[2], *st0, *st1, *st2, *st3;
713         int pixel= ibuf->x*y + x;
714         float vec[3], p0[3], p1[3], n[3], len;
715
716         lores_dm->getTessFace(lores_dm, face_index, &mface);
717
718         st0= mtface[face_index].uv[0];
719         st1= mtface[face_index].uv[1];
720         st2= mtface[face_index].uv[2];
721
722         if (mface.v4) {
723                 st3= mtface[face_index].uv[3];
724                 resolve_quad_uv(uv, st, st0, st1, st2, st3);
725         }
726         else
727                 resolve_tri_uv(uv, st, st0, st1, st2);
728
729         CLAMP(uv[0], 0.0f, 1.0f);
730         CLAMP(uv[1], 0.0f, 1.0f);
731
732         get_ccgdm_data(lores_dm, hires_dm, height_data->origindex, lvl, face_index, uv[0], uv[1], p1, 0);
733
734         if (height_data->ssdm) {
735                 get_ccgdm_data(lores_dm, height_data->ssdm, height_data->origindex, 0, face_index, uv[0], uv[1], p0, n);
736         }
737         else {
738                 lores_dm->getTessFace(lores_dm, face_index, &mface);
739
740                 if (mface.v4) {
741                         interp_bilinear_mface(lores_dm, &mface, uv[0], uv[1], 1, p0);
742                         interp_bilinear_mface(lores_dm, &mface, uv[0], uv[1], 0, n);
743                 }
744                 else {
745                         interp_barycentric_mface(lores_dm, &mface, uv[0], uv[1], 1, p0);
746                         interp_barycentric_mface(lores_dm, &mface, uv[0], uv[1], 0, n);
747                 }
748         }
749
750         sub_v3_v3v3(vec, p1, p0);
751         len= dot_v3v3(n, vec);
752
753         height_data->heights[pixel]= len;
754         if (len<height_data->height_min) height_data->height_min= len;
755         if (len>height_data->height_max) height_data->height_max= len;
756
757         if (ibuf->rect_float) {
758                 float *rrgbf= ibuf->rect_float + pixel*4;
759                 rrgbf[3]= 1.0f;
760
761                 ibuf->userflags= IB_RECT_INVALID;
762         }
763         else {
764                 char *rrgb= (char*)ibuf->rect + pixel*4;
765                 rrgb[3]= 255;
766         }
767 }
768
769 /* MultiresBake callback for normals' baking
770  * general idea:
771  *   - find coord and normal of point with specified UV in hi-res mesh
772  *   - multiply it by tangmat
773  *   - vector in color space would be norm(vec) /2 + (0.5, 0.5, 0.5) */
774 static void apply_tangmat_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *bake_data,
775                                    const int face_index, const int lvl, const float st[2],
776                                    float tangmat[3][3], const int x, const int y)
777 {
778         MTFace *mtface= CustomData_get_layer(&lores_dm->faceData, CD_MTFACE);
779         MFace mface;
780         Image *ima= mtface[face_index].tpage;
781         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
782         MNormalBakeData *normal_data= (MNormalBakeData*)bake_data;
783         float uv[2], *st0, *st1, *st2, *st3;
784         int pixel= ibuf->x*y + x;
785         float n[3], vec[3], tmp[3]= {0.5, 0.5, 0.5};
786
787         lores_dm->getTessFace(lores_dm, face_index, &mface);
788
789         st0= mtface[face_index].uv[0];
790         st1= mtface[face_index].uv[1];
791         st2= mtface[face_index].uv[2];
792
793         if (mface.v4) {
794                 st3= mtface[face_index].uv[3];
795                 resolve_quad_uv(uv, st, st0, st1, st2, st3);
796         }
797         else
798                 resolve_tri_uv(uv, st, st0, st1, st2);
799
800         CLAMP(uv[0], 0.0f, 1.0f);
801         CLAMP(uv[1], 0.0f, 1.0f);
802
803         get_ccgdm_data(lores_dm, hires_dm, normal_data->origindex, lvl, face_index, uv[0], uv[1], NULL, n);
804
805         mul_v3_m3v3(vec, tangmat, n);
806         normalize_v3(vec);
807         mul_v3_fl(vec, 0.5);
808         add_v3_v3(vec, tmp);
809
810         if (ibuf->rect_float) {
811                 float *rrgbf= ibuf->rect_float + pixel*4;
812                 rrgbf[0]= vec[0];
813                 rrgbf[1]= vec[1];
814                 rrgbf[2]= vec[2];
815                 rrgbf[3]= 1.0f;
816
817                 ibuf->userflags= IB_RECT_INVALID;
818         }
819         else {
820                 unsigned char *rrgb= (unsigned char *)ibuf->rect + pixel*4;
821                 rgb_float_to_uchar(rrgb, vec);
822                 rrgb[3]= 255;
823         }
824 }
825
826 static void count_images(MultiresBakeRender *bkr)
827 {
828         int a, totface;
829         DerivedMesh *dm= bkr->lores_dm;
830         MTFace *mtface= CustomData_get_layer(&dm->faceData, CD_MTFACE);
831
832         bkr->image.first= bkr->image.last= NULL;
833         bkr->tot_image= 0;
834
835         totface= dm->getNumTessFaces(dm);
836
837         for (a= 0; a<totface; a++)
838                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
839
840         for (a= 0; a<totface; a++) {
841                 Image *ima= mtface[a].tpage;
842                 if ((ima->id.flag&LIB_DOIT)==0) {
843                         LinkData *data= BLI_genericNodeN(ima);
844                         BLI_addtail(&bkr->image, data);
845                         bkr->tot_image++;
846                         ima->id.flag|= LIB_DOIT;
847                 }
848         }
849
850         for (a= 0; a<totface; a++)
851                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
852 }
853
854 static void bake_images(MultiresBakeRender *bkr)
855 {
856         LinkData *link;
857
858         for (link= bkr->image.first; link; link= link->next) {
859                 Image *ima= (Image*)link->data;
860                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
861
862                 if (ibuf->x>0 && ibuf->y>0) {
863                         ibuf->userdata= MEM_callocN(ibuf->y*ibuf->x, "MultiresBake imbuf mask");
864
865                         switch(bkr->mode) {
866                                 case RE_BAKE_NORMALS:
867                                         do_multires_bake(bkr, ima, apply_tangmat_callback, init_normal_data, NULL, free_normal_data);
868                                         break;
869                                 case RE_BAKE_DISPLACEMENT:
870                                         do_multires_bake(bkr, ima, apply_heights_callback, init_heights_data,
871                                                          apply_heights_data, free_heights_data);
872                                         break;
873                         }
874                 }
875
876                 ima->id.flag|= LIB_DOIT;
877         }
878 }
879
880 static void finish_images(MultiresBakeRender *bkr)
881 {
882         LinkData *link;
883
884         for (link= bkr->image.first; link; link= link->next) {
885                 Image *ima= (Image*)link->data;
886                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
887
888                 if (ibuf->x<=0 || ibuf->y<=0)
889                         continue;
890
891                 RE_bake_ibuf_filter(ibuf, (char *)ibuf->userdata, bkr->bake_filter);
892
893                 ibuf->userflags|= IB_BITMAPDIRTY;
894
895                 if (ibuf->rect_float)
896                         ibuf->userflags|= IB_RECT_INVALID;
897
898                 if (ibuf->mipmap[0]) {
899                         ibuf->userflags|= IB_MIPMAP_INVALID;
900                         imb_freemipmapImBuf(ibuf);
901                 }
902
903                 if (ibuf->userdata) {
904                         MEM_freeN(ibuf->userdata);
905                         ibuf->userdata= NULL;
906                 }
907         }
908 }
909
910 static void multiresbake_start(MultiresBakeRender *bkr)
911 {
912         count_images(bkr);
913         bake_images(bkr);
914         finish_images(bkr);
915 }
916
917 static int multiresbake_check(bContext *C, wmOperator *op)
918 {
919         Scene *scene= CTX_data_scene(C);
920         Object *ob;
921         Mesh *me;
922         MultiresModifierData *mmd;
923         int ok= 1, a;
924
925         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
926                 ob= base->object;
927
928                 if (ob->type != OB_MESH) {
929                         BKE_report(op->reports, RPT_ERROR, "Basking of multires data only works with active object which is a mesh");
930
931                         ok= 0;
932                         break;
933                 }
934
935                 me= (Mesh*)ob->data;
936                 mmd= get_multires_modifier(scene, ob, 0);
937
938                 /* Multi-resolution should be and be last in the stack */
939                 if (ok && mmd) {
940                         ModifierData *md;
941
942                         ok= mmd->totlvl>0;
943
944                         for (md = (ModifierData*)mmd->modifier.next; md && ok; md = md->next) {
945                                 if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
946                                         ok= 0;
947                                 }
948                         }
949                 }
950                 else ok= 0;
951
952                 if (!ok) {
953                         BKE_report(op->reports, RPT_ERROR, "Multires data baking requires multi-resolution object");
954
955                         break;
956                 }
957
958                 if (!me->mtpoly) {
959                         BKE_report(op->reports, RPT_ERROR, "Mesh should be unwrapped before multires data baking");
960
961                         ok= 0;
962                 }
963                 else {
964                         a = me->totpoly;
965                         while (ok && a--) {
966                                 Image *ima = me->mtpoly[a].tpage;
967
968                                 if (!ima) {
969                                         BKE_report(op->reports, RPT_ERROR, "You should have active texture to use multires baker");
970
971                                         ok= 0;
972                                 }
973                                 else {
974                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
975
976                                         if (!ibuf) {
977                                                 BKE_report(op->reports, RPT_ERROR, "Baking should happend to image with image buffer");
978
979                                                 ok= 0;
980                                         }
981                                         else {
982                                                 if (ibuf->rect==NULL && ibuf->rect_float==NULL)
983                                                         ok= 0;
984
985                                                 if (ibuf->rect_float && !(ibuf->channels==0 || ibuf->channels==4))
986                                                         ok= 0;
987
988                                                 if (!ok)
989                                                         BKE_report(op->reports, RPT_ERROR, "Baking to unsupported image type");
990                                         }
991                                 }
992                         }
993                 }
994
995                 if (!ok)
996                         break;
997         }
998         CTX_DATA_END;
999
1000         return ok;
1001 }
1002
1003 static DerivedMesh *multiresbake_create_loresdm(Scene *scene, Object *ob, int *lvl)
1004 {
1005         DerivedMesh *dm;
1006         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1007         Mesh *me= (Mesh*)ob->data;
1008
1009         *lvl= mmd->lvl;
1010
1011         if (*lvl==0) {
1012                 DerivedMesh *tmp_dm= CDDM_from_mesh(me, ob);
1013                 dm= CDDM_copy(tmp_dm);
1014                 tmp_dm->release(tmp_dm);
1015         }
1016         else {
1017                 MultiresModifierData tmp_mmd= *mmd;
1018                 DerivedMesh *cddm= CDDM_from_mesh(me, ob);
1019
1020                 tmp_mmd.lvl= *lvl;
1021                 tmp_mmd.sculptlvl= *lvl;
1022                 dm= multires_dm_create_from_derived(&tmp_mmd, 1, cddm, ob, 0);
1023                 cddm->release(cddm);
1024         }
1025
1026         return dm;
1027 }
1028
1029 static DerivedMesh *multiresbake_create_hiresdm(Scene *scene, Object *ob, int *lvl, int *simple)
1030 {
1031         Mesh *me= (Mesh*)ob->data;
1032         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1033         MultiresModifierData tmp_mmd= *mmd;
1034         DerivedMesh *cddm= CDDM_from_mesh(me, ob);
1035         DerivedMesh *dm;
1036
1037         *lvl= mmd->totlvl;
1038         *simple= mmd->simple;
1039
1040         tmp_mmd.lvl= mmd->totlvl;
1041         tmp_mmd.sculptlvl= mmd->totlvl;
1042         dm= multires_dm_create_from_derived(&tmp_mmd, 1, cddm, ob, 0);
1043         cddm->release(cddm);
1044
1045         return dm;
1046 }
1047
1048 static void clear_images(MTFace *mtface, int totface)
1049 {
1050         int a;
1051         const float vec_alpha[4]= {0.0f, 0.0f, 0.0f, 0.0f};
1052         const float vec_solid[4]= {0.0f, 0.0f, 0.0f, 1.0f};
1053
1054         for (a= 0; a<totface; a++)
1055                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
1056
1057         for (a= 0; a<totface; a++) {
1058                 Image *ima= mtface[a].tpage;
1059
1060                 if ((ima->id.flag&LIB_DOIT)==0) {
1061                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1062
1063                         IMB_rectfill(ibuf, (ibuf->planes == R_IMF_PLANES_RGBA) ? vec_alpha : vec_solid);
1064                         ima->id.flag|= LIB_DOIT;
1065                 }
1066         }
1067
1068         for (a= 0; a<totface; a++)
1069                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
1070 }
1071
1072 static int multiresbake_image_exec_locked(bContext *C, wmOperator *op)
1073 {
1074         Object *ob;
1075         Scene *scene= CTX_data_scene(C);
1076         int objects_baked= 0;
1077
1078         if (!multiresbake_check(C, op))
1079                 return OPERATOR_CANCELLED;
1080
1081         if (scene->r.bake_flag&R_BAKE_CLEAR) {  /* clear images */
1082                 CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
1083                         Mesh *me;
1084
1085                         ob= base->object;
1086                         me= (Mesh*)ob->data;
1087
1088                         clear_images(me->mtface, me->totface);
1089                 }
1090                 CTX_DATA_END;
1091         }
1092
1093         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
1094                 MultiresBakeRender bkr= {0};
1095
1096                 ob= base->object;
1097
1098                 multires_force_update(ob);
1099
1100                 /* copy data stored in job descriptor */
1101                 bkr.bake_filter= scene->r.bake_filter;
1102                 bkr.mode= scene->r.bake_mode;
1103                 bkr.use_lores_mesh= scene->r.bake_flag&R_BAKE_LORES_MESH;
1104
1105                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
1106                 bkr.lores_dm= multiresbake_create_loresdm(scene, ob, &bkr.lvl);
1107
1108                 if (!bkr.lores_dm)
1109                         continue;
1110
1111                 bkr.hires_dm= multiresbake_create_hiresdm(scene, ob, &bkr.tot_lvl, &bkr.simple);
1112
1113                 multiresbake_start(&bkr);
1114
1115                 BLI_freelistN(&bkr.image);
1116
1117                 bkr.lores_dm->release(bkr.lores_dm);
1118                 bkr.hires_dm->release(bkr.hires_dm);
1119
1120                 objects_baked++;
1121         }
1122         CTX_DATA_END;
1123
1124         if (!objects_baked)
1125                 BKE_report(op->reports, RPT_ERROR, "No objects found to bake from");
1126
1127         return OPERATOR_FINISHED;
1128 }
1129
1130 /* Multiresbake adopted for job-system executing */
1131 static void init_multiresbake_job(bContext *C, MultiresBakeJob *bkj)
1132 {
1133         Scene *scene= CTX_data_scene(C);
1134         Object *ob;
1135
1136         /* backup scene settings, so their changing in UI would take no effect on baker */
1137         bkj->bake_filter= scene->r.bake_filter;
1138         bkj->mode= scene->r.bake_mode;
1139         bkj->use_lores_mesh= scene->r.bake_flag&R_BAKE_LORES_MESH;
1140         bkj->bake_clear= scene->r.bake_flag&R_BAKE_CLEAR;
1141
1142         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
1143                 MultiresBakerJobData *data;
1144                 DerivedMesh *lores_dm;
1145                 int lvl;
1146                 ob= base->object;
1147
1148                 multires_force_update(ob);
1149
1150                 lores_dm = multiresbake_create_loresdm(scene, ob, &lvl);
1151                 if (!lores_dm)
1152                         continue;
1153
1154                 data= MEM_callocN(sizeof(MultiresBakerJobData), "multiresBaker derivedMesh_data");
1155                 data->lores_dm = lores_dm;
1156                 data->lvl = lvl;
1157                 data->hires_dm = multiresbake_create_hiresdm(scene, ob, &data->tot_lvl, &data->simple);
1158
1159                 BLI_addtail(&bkj->data, data);
1160         }
1161         CTX_DATA_END;
1162 }
1163
1164 static void multiresbake_startjob(void *bkv, short *stop, short *do_update, float *progress)
1165 {
1166         MultiresBakerJobData *data;
1167         MultiresBakeJob *bkj= bkv;
1168         int baked_objects= 0, tot_obj;
1169
1170         tot_obj= BLI_countlist(&bkj->data);
1171
1172         if (bkj->bake_clear) {  /* clear images */
1173                 for (data= bkj->data.first; data; data= data->next) {
1174                         DerivedMesh *dm= data->lores_dm;
1175                         MTFace *mtface= CustomData_get_layer(&dm->faceData, CD_MTFACE);
1176
1177                         clear_images(mtface, dm->getNumTessFaces(dm));
1178                 }
1179         }
1180
1181         for (data= bkj->data.first; data; data= data->next) {
1182                 MultiresBakeRender bkr= {0};
1183
1184                 /* copy data stored in job descriptor */
1185                 bkr.bake_filter= bkj->bake_filter;
1186                 bkr.mode= bkj->mode;
1187                 bkr.use_lores_mesh= bkj->use_lores_mesh;
1188
1189                 /* create low-resolution DM (to bake to) and hi-resolution DM (to bake from) */
1190                 bkr.lores_dm= data->lores_dm;
1191                 bkr.hires_dm= data->hires_dm;
1192                 bkr.tot_lvl= data->tot_lvl;
1193                 bkr.lvl= data->lvl;
1194                 bkr.simple= data->simple;
1195
1196                 /* needed for proper progress bar */
1197                 bkr.tot_obj= tot_obj;
1198                 bkr.baked_objects= baked_objects;
1199
1200                 bkr.stop= stop;
1201                 bkr.do_update= do_update;
1202                 bkr.progress= progress;
1203
1204                 multiresbake_start(&bkr);
1205
1206                 BLI_freelistN(&bkr.image);
1207
1208                 baked_objects++;
1209         }
1210 }
1211
1212 static void multiresbake_freejob(void *bkv)
1213 {
1214         MultiresBakeJob *bkj= bkv;
1215         MultiresBakerJobData *data, *next;
1216
1217         data= bkj->data.first;
1218         while (data) {
1219                 next= data->next;
1220                 data->lores_dm->release(data->lores_dm);
1221                 data->hires_dm->release(data->hires_dm);
1222                 MEM_freeN(data);
1223                 data= next;
1224         }
1225
1226         MEM_freeN(bkj);
1227 }
1228
1229 static int multiresbake_image_exec(bContext *C, wmOperator *op)
1230 {
1231         Scene *scene= CTX_data_scene(C);
1232         MultiresBakeJob *bkr;
1233         wmJob *steve;
1234
1235         if (!multiresbake_check(C, op))
1236                 return OPERATOR_CANCELLED;
1237
1238         bkr= MEM_callocN(sizeof(MultiresBakeJob), "MultiresBakeJob data");
1239         init_multiresbake_job(C, bkr);
1240
1241         if (!bkr->data.first) {
1242                 BKE_report(op->reports, RPT_ERROR, "No objects found to bake from");
1243                 return OPERATOR_CANCELLED;
1244         }
1245
1246         /* setup job */
1247         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Multires Bake", WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS);
1248         WM_jobs_customdata(steve, bkr, multiresbake_freejob);
1249         WM_jobs_timer(steve, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
1250         WM_jobs_callbacks(steve, multiresbake_startjob, NULL, NULL, NULL);
1251
1252         G.afbreek= 0;
1253
1254         WM_jobs_start(CTX_wm_manager(C), steve);
1255         WM_cursor_wait(0);
1256
1257         /* add modal handler for ESC */
1258         WM_event_add_modal_handler(C, op);
1259
1260         return OPERATOR_RUNNING_MODAL;
1261 }
1262
1263 /* ****************** render BAKING ********************** */
1264
1265 /* threaded break test */
1266 static int thread_break(void *UNUSED(arg))
1267 {
1268         return G.afbreek;
1269 }
1270
1271 typedef struct BakeRender {
1272         Render *re;
1273         Main *main;
1274         Scene *scene;
1275         struct Object *actob;
1276         int result, ready;
1277
1278         ReportList *reports;
1279
1280         short *stop;
1281         short *do_update;
1282         float *progress;
1283         
1284         ListBase threads;
1285
1286         /* backup */
1287         short prev_wo_amb_occ;
1288         short prev_r_raytrace;
1289
1290         /* for redrawing */
1291         ScrArea *sa;
1292 } BakeRender;
1293
1294 /* use by exec and invoke */
1295 static int test_bake_internal(bContext *C, ReportList *reports)
1296 {
1297         Scene *scene= CTX_data_scene(C);
1298
1299         if ((scene->r.bake_flag & R_BAKE_TO_ACTIVE) && CTX_data_active_object(C)==NULL) {
1300                 BKE_report(reports, RPT_ERROR, "No active object");
1301         }
1302         else if (scene->r.bake_mode==RE_BAKE_AO && scene->world==NULL) {
1303                 BKE_report(reports, RPT_ERROR, "No world set up");
1304         }
1305         else {
1306                 return 1;
1307         }
1308
1309         return 0;
1310 }
1311
1312 static void init_bake_internal(BakeRender *bkr, bContext *C)
1313 {
1314         Scene *scene= CTX_data_scene(C);
1315
1316         /* get editmode results */
1317         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
1318
1319         bkr->sa= BKE_screen_find_big_area(CTX_wm_screen(C), SPACE_IMAGE, 10); /* can be NULL */
1320         bkr->main= CTX_data_main(C);
1321         bkr->scene= scene;
1322         bkr->actob= (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL;
1323         bkr->re= RE_NewRender("_Bake View_");
1324
1325         if (scene->r.bake_mode==RE_BAKE_AO) {
1326                 /* If raytracing or AO is disabled, switch it on temporarily for baking. */
1327                 bkr->prev_wo_amb_occ = (scene->world->mode & WO_AMB_OCC) != 0;
1328                 scene->world->mode |= WO_AMB_OCC;
1329         }
1330         if (scene->r.bake_mode==RE_BAKE_AO || bkr->actob) {
1331                 bkr->prev_r_raytrace = (scene->r.mode & R_RAYTRACE) != 0;
1332                 scene->r.mode |= R_RAYTRACE;
1333         }
1334 }
1335
1336 static void finish_bake_internal(BakeRender *bkr)
1337 {
1338         RE_Database_Free(bkr->re);
1339
1340         /* restore raytrace and AO */
1341         if (bkr->scene->r.bake_mode==RE_BAKE_AO)
1342                 if (bkr->prev_wo_amb_occ == 0)
1343                         bkr->scene->world->mode &= ~WO_AMB_OCC;
1344
1345         if (bkr->scene->r.bake_mode==RE_BAKE_AO || bkr->actob)
1346                 if (bkr->prev_r_raytrace == 0)
1347                         bkr->scene->r.mode &= ~R_RAYTRACE;
1348
1349         if (bkr->result==BAKE_RESULT_OK) {
1350                 Image *ima;
1351                 /* force OpenGL reload and mipmap recalc */
1352                 for (ima= G.main->image.first; ima; ima= ima->id.next) {
1353                         if (ima->ok==IMA_OK_LOADED) {
1354                                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1355                                 if (ibuf) {
1356                                         if (ibuf->userflags & IB_BITMAPDIRTY) {
1357                                                 GPU_free_image(ima);
1358                                                 imb_freemipmapImBuf(ibuf);
1359                                         }
1360
1361                                         /* freed when baking is done, but if its canceled we need to free here */
1362                                         if (ibuf->userdata) {
1363                                                 MEM_freeN(ibuf->userdata);
1364                                                 ibuf->userdata= NULL;
1365                                         }
1366                                 }
1367                         }
1368                 }
1369         }
1370 }
1371
1372 static void *do_bake_render(void *bake_v)
1373 {
1374         BakeRender *bkr= bake_v;
1375
1376         bkr->result= RE_bake_shade_all_selected(bkr->re, bkr->scene->r.bake_mode, bkr->actob, NULL, bkr->progress);
1377         bkr->ready= 1;
1378
1379         return NULL;
1380 }
1381
1382 static void bake_startjob(void *bkv, short *stop, short *do_update, float *progress)
1383 {
1384         BakeRender *bkr= bkv;
1385         Scene *scene= bkr->scene;
1386         Main *bmain= bkr->main;
1387
1388         bkr->stop= stop;
1389         bkr->do_update= do_update;
1390         bkr->progress= progress;
1391
1392         RE_test_break_cb(bkr->re, NULL, thread_break);
1393         G.afbreek= 0;   /* blender_test_break uses this global */
1394
1395         RE_Database_Baking(bkr->re, bmain, scene, scene->lay, scene->r.bake_mode, bkr->actob);
1396
1397         /* baking itself is threaded, cannot use test_break in threads. we also update optional imagewindow */
1398         bkr->result= RE_bake_shade_all_selected(bkr->re, scene->r.bake_mode, bkr->actob, bkr->do_update, bkr->progress);
1399 }
1400
1401 static void bake_update(void *bkv)
1402 {
1403         BakeRender *bkr= bkv;
1404
1405         if (bkr->sa && bkr->sa->spacetype==SPACE_IMAGE) { /* in case the user changed while baking */
1406                 SpaceImage *sima= bkr->sa->spacedata.first;
1407                 if (sima)
1408                         sima->image= RE_bake_shade_get_image();
1409         }
1410 }
1411
1412 static void bake_freejob(void *bkv)
1413 {
1414         BakeRender *bkr= bkv;
1415         finish_bake_internal(bkr);
1416
1417         if (bkr->result==BAKE_RESULT_NO_OBJECTS)
1418                 BKE_report(bkr->reports, RPT_ERROR, "No objects or images found to bake to");
1419         else if (bkr->result==BAKE_RESULT_FEEDBACK_LOOP)
1420                 BKE_report(bkr->reports, RPT_WARNING, "Feedback loop detected");
1421
1422         MEM_freeN(bkr);
1423         G.rendering = 0;
1424 }
1425
1426 /* catch esc */
1427 static int objects_bake_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1428 {
1429         /* no running blender, remove handler and pass through */
1430         if (0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C)))
1431                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
1432
1433         /* running render */
1434         switch (event->type) {
1435                 case ESCKEY:
1436                         return OPERATOR_RUNNING_MODAL;
1437                         break;
1438         }
1439         return OPERATOR_PASS_THROUGH;
1440 }
1441
1442 static int is_multires_bake(Scene *scene)
1443 {
1444         if ( ELEM(scene->r.bake_mode, RE_BAKE_NORMALS, RE_BAKE_DISPLACEMENT))
1445                 return scene->r.bake_flag & R_BAKE_MULTIRES;
1446
1447         return 0;
1448 }
1449
1450 static int objects_bake_render_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(_event))
1451 {
1452         Scene *scene= CTX_data_scene(C);
1453         int result= OPERATOR_CANCELLED;
1454
1455         if (is_multires_bake(scene)) {
1456                 result= multiresbake_image_exec(C, op);
1457         }
1458         else {
1459                 /* only one render job at a time */
1460                 if (WM_jobs_test(CTX_wm_manager(C), scene))
1461                         return OPERATOR_CANCELLED;
1462
1463                 if (test_bake_internal(C, op->reports)==0) {
1464                         return OPERATOR_CANCELLED;
1465                 }
1466                 else {
1467                         BakeRender *bkr= MEM_callocN(sizeof(BakeRender), "render bake");
1468                         wmJob *steve;
1469
1470                         init_bake_internal(bkr, C);
1471                         bkr->reports= op->reports;
1472
1473                         /* setup job */
1474                         steve= WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Texture Bake", WM_JOB_EXCL_RENDER|WM_JOB_PRIORITY|WM_JOB_PROGRESS);
1475                         WM_jobs_customdata(steve, bkr, bake_freejob);
1476                         WM_jobs_timer(steve, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
1477                         WM_jobs_callbacks(steve, bake_startjob, NULL, bake_update, NULL);
1478
1479                         G.afbreek= 0;
1480                         G.rendering = 1;
1481
1482                         WM_jobs_start(CTX_wm_manager(C), steve);
1483
1484                         WM_cursor_wait(0);
1485
1486                         /* add modal handler for ESC */
1487                         WM_event_add_modal_handler(C, op);
1488                 }
1489
1490                 result= OPERATOR_RUNNING_MODAL;
1491         }
1492
1493         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
1494
1495         return result;
1496 }
1497
1498
1499 static int bake_image_exec(bContext *C, wmOperator *op)
1500 {
1501         Main *bmain= CTX_data_main(C);
1502         Scene *scene= CTX_data_scene(C);
1503         int result= OPERATOR_CANCELLED;
1504
1505         if (is_multires_bake(scene)) {
1506                 result= multiresbake_image_exec_locked(C, op);
1507         }
1508         else {
1509                 if (test_bake_internal(C, op->reports)==0) {
1510                         return OPERATOR_CANCELLED;
1511                 }
1512                 else {
1513                         ListBase threads;
1514                         BakeRender bkr= {NULL};
1515
1516                         init_bake_internal(&bkr, C);
1517                         bkr.reports= op->reports;
1518
1519                         RE_test_break_cb(bkr.re, NULL, thread_break);
1520                         G.afbreek= 0;   /* blender_test_break uses this global */
1521
1522                         RE_Database_Baking(bkr.re, bmain, scene, scene->lay, scene->r.bake_mode, (scene->r.bake_flag & R_BAKE_TO_ACTIVE)? OBACT: NULL);
1523
1524                         /* baking itself is threaded, cannot use test_break in threads  */
1525                         BLI_init_threads(&threads, do_bake_render, 1);
1526                         bkr.ready= 0;
1527                         BLI_insert_thread(&threads, &bkr);
1528
1529                         while (bkr.ready==0) {
1530                                 PIL_sleep_ms(50);
1531                                 if (bkr.ready)
1532                                         break;
1533
1534                                 /* used to redraw in 2.4x but this is just for exec in 2.5 */
1535                                 if (!G.background)
1536                                         blender_test_break();
1537                         }
1538                         BLI_end_threads(&threads);
1539
1540                         if (bkr.result==BAKE_RESULT_NO_OBJECTS)
1541                                 BKE_report(op->reports, RPT_ERROR, "No valid images found to bake to");
1542                         else if (bkr.result==BAKE_RESULT_FEEDBACK_LOOP)
1543                                 BKE_report(op->reports, RPT_ERROR, "Feedback loop detected");
1544
1545                         finish_bake_internal(&bkr);
1546
1547                         result= OPERATOR_FINISHED;
1548                 }
1549         }
1550
1551         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
1552
1553         return result;
1554 }
1555
1556 void OBJECT_OT_bake_image(wmOperatorType *ot)
1557 {
1558         /* identifiers */
1559         ot->name = "Bake";
1560         ot->description = "Bake image textures of selected objects";
1561         ot->idname = "OBJECT_OT_bake_image";
1562
1563         /* api callbacks */
1564         ot->exec = bake_image_exec;
1565         ot->invoke = objects_bake_render_invoke;
1566         ot->modal = objects_bake_render_modal;
1567 }