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