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