565c5810cff82c284d7d1cc3e084f90b31914d97
[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         DerivedMesh *dm= bkr->lores_dm;
364         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
365         const int lvl= bkr->lvl;
366         const int tot_face= dm->getNumFaces(dm);
367         MVert *mvert= dm->getVertArray(dm);
368         MFace *mface= dm->getFaceArray(dm);
369         MTFace *mtface= dm->getFaceDataArray(dm, CD_MTFACE);
370         float *pvtangent= NULL;
371
372         if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) == -1)
373                 DM_add_tangent_layer(dm);
374
375         pvtangent= DM_get_face_data_layer(dm, CD_TANGENT);
376
377         if(tot_face > 0) {  /* sanity check */
378                 int f= 0;
379                 MBakeRast bake_rast;
380                 MResolvePixelData data={NULL};
381
382                 data.mface= mface;
383                 data.mvert= mvert;
384                 data.mtface= mtface;
385                 data.pvtangent= pvtangent;
386                 data.precomputed_normals= dm->getFaceDataArray(dm, CD_NORMAL);  /* don't strictly need this */
387                 data.w= ibuf->x;
388                 data.h= ibuf->y;
389                 data.lores_dm= dm;
390                 data.hires_dm= bkr->hires_dm;
391                 data.lvl= lvl;
392                 data.pass_data= passKnownData;
393
394                 if(initBakeData)
395                         data.bake_data= initBakeData(bkr, ima);
396
397                 init_bake_rast(&bake_rast, ibuf, &data, flush_pixel);
398
399                 for(f= 0; f<tot_face; f++) {
400                         MTFace *mtfate= &mtface[f];
401                         int verts[3][2], nr_tris, t;
402
403                         if(multiresbake_test_break(bkr))
404                                 break;
405
406                         if(mtfate->tpage!=ima)
407                                 continue;
408
409                         data.face_index= f;
410
411                         /* might support other forms of diagonal splits later on such as
412                            split by shortest diagonal.*/
413                         verts[0][0]=0;
414                         verts[1][0]=1;
415                         verts[2][0]=2;
416
417                         verts[0][1]=0;
418                         verts[1][1]=2;
419                         verts[2][1]=3;
420
421                         nr_tris= mface[f].v4!=0 ? 2 : 1;
422                         for(t= 0; t<nr_tris; t++) {
423                                 data.i0= verts[0][t];
424                                 data.i1= verts[1][t];
425                                 data.i2 =verts[2][t];
426
427                                 bake_rasterize(&bake_rast, mtfate->uv[data.i0], mtfate->uv[data.i1], mtfate->uv[data.i2]);
428                         }
429
430                         bkr->baked_faces++;
431
432                         if(bkr->do_update)
433                                 *bkr->do_update= 1;
434
435                         if(bkr->progress)
436                                 *bkr->progress= ((float)bkr->baked_objects + (float)bkr->baked_faces / tot_face) / bkr->tot_obj;
437                 }
438
439                 if(applyBakeData)
440                         applyBakeData(data.bake_data);
441
442                 if(freeBakeData)
443                         freeBakeData(data.bake_data);
444         }
445 }
446
447 static void interp_bilinear_quad_data(float data[4][3], float u, float v, float res[3])
448 {
449         float vec[3];
450
451         copy_v3_v3(res, data[0]);
452         mul_v3_fl(res, (1-u)*(1-v));
453         copy_v3_v3(vec, data[1]);
454         mul_v3_fl(vec, u*(1-v)); add_v3_v3(res, vec);
455         copy_v3_v3(vec, data[2]);
456         mul_v3_fl(vec, u*v); add_v3_v3(res, vec);
457         copy_v3_v3(vec, data[3]);
458         mul_v3_fl(vec, (1-u)*v); add_v3_v3(res, vec);
459 }
460
461 static void interp_barycentric_tri_data(float data[3][3], float u, float v, float res[3])
462 {
463         float vec[3];
464
465         copy_v3_v3(res, data[0]);
466         mul_v3_fl(res, u);
467         copy_v3_v3(vec, data[1]);
468         mul_v3_fl(vec, v); add_v3_v3(res, vec);
469         copy_v3_v3(vec, data[2]);
470         mul_v3_fl(vec, 1.0f-u-v); add_v3_v3(res, vec);
471 }
472
473 /* mode = 0: interpolate normals,
474    mode = 1: interpolate coord */
475 static void interp_bilinear_grid(DMGridData *grid, int grid_size, float crn_x, float crn_y, int mode, float res[3])
476 {
477         int x0, x1, y0, y1;
478         float u, v;
479         float data[4][3];
480
481         x0= (int) crn_x;
482         x1= x0>=(grid_size-1) ? (grid_size-1) : (x0+1);
483
484         y0= (int) crn_y;
485         y1= y0>=(grid_size-1) ? (grid_size-1) : (y0+1);
486
487         u= crn_x-x0;
488         v= crn_y-y0;
489
490         if(mode == 0) {
491                 copy_v3_v3(data[0], grid[y0 * grid_size + x0].no);
492                 copy_v3_v3(data[1], grid[y0 * grid_size + x1].no);
493                 copy_v3_v3(data[2], grid[y1 * grid_size + x1].no);
494                 copy_v3_v3(data[3], grid[y1 * grid_size + x0].no);
495         } else {
496                 copy_v3_v3(data[0], grid[y0 * grid_size + x0].co);
497                 copy_v3_v3(data[1], grid[y0 * grid_size + x1].co);
498                 copy_v3_v3(data[2], grid[y1 * grid_size + x1].co);
499                 copy_v3_v3(data[3], grid[y1 * grid_size + x0].co);
500         }
501
502         interp_bilinear_quad_data(data, u, v, res);
503 }
504
505 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])
506 {
507         MFace mface;
508         DMGridData **grid_data;
509         float crn_x, crn_y;
510         int grid_size, S, face_side;
511         int *grid_offset, g_index;
512
513         lodm->getFace(lodm, face_index, &mface);
514
515         grid_size= hidm->getGridSize(hidm);
516         grid_data= hidm->getGridData(hidm);
517         grid_offset= hidm->getGridOffset(hidm);
518
519         face_side= (grid_size<<1)-1;
520
521         if(lvl==0) {
522                 g_index= grid_offset[face_index];
523                 S= mdisp_rot_face_to_crn(mface.v4 ? 4 : 3, face_side, u*(face_side-1), v*(face_side-1), &crn_x, &crn_y);
524         } else {
525                 const int *index= lodm->getFaceDataArray(lodm, CD_ORIGINDEX);
526                 int side= (1 << (lvl-1)) + 1;
527                 int grid_index= index[face_index];
528                 int loc_offs= face_index % (1<<(2*lvl));
529                 int cell_index= loc_offs % ((side-1)*(side-1));
530                 int cell_side= grid_size / (side-1);
531                 int row= cell_index / (side-1);
532                 int col= cell_index % (side-1);
533
534                 S= face_index / (1<<(2*(lvl-1))) - grid_offset[grid_index];
535                 g_index= grid_offset[grid_index];
536
537                 crn_y= (row * cell_side) + u * cell_side;
538                 crn_x= (col * cell_side) + v * cell_side;
539         }
540
541         CLAMP(crn_x, 0.0f, grid_size);
542         CLAMP(crn_y, 0.0f, grid_size);
543
544         if(n != NULL)
545                 interp_bilinear_grid(grid_data[g_index + S], grid_size, crn_x, crn_y, 0, n);
546
547         if(co != NULL)
548                 interp_bilinear_grid(grid_data[g_index + S], grid_size, crn_x, crn_y, 1, co);
549 }
550
551 /* mode = 0: interpolate normals,
552    mode = 1: interpolate coord */
553 static void interp_bilinear_mface(DerivedMesh *dm, MFace *mface, const float u, const float v, const int mode, float res[3])
554 {
555         float data[4][3];
556
557         if(mode == 0) {
558                 dm->getVertNo(dm, mface->v1, data[0]);
559                 dm->getVertNo(dm, mface->v2, data[1]);
560                 dm->getVertNo(dm, mface->v3, data[2]);
561                 dm->getVertNo(dm, mface->v4, data[3]);
562         } else {
563                 dm->getVertCo(dm, mface->v1, data[0]);
564                 dm->getVertCo(dm, mface->v2, data[1]);
565                 dm->getVertCo(dm, mface->v3, data[2]);
566                 dm->getVertCo(dm, mface->v4, data[3]);
567         }
568
569         interp_bilinear_quad_data(data, u, v, res);
570 }
571
572 /* mode = 0: interpolate normals,
573    mode = 1: interpolate coord */
574 static void interp_barycentric_mface(DerivedMesh *dm, MFace *mface, const float u, const float v, const int mode, float res[3])
575 {
576         float data[3][3];
577
578         if(mode == 0) {
579                 dm->getVertNo(dm, mface->v1, data[0]);
580                 dm->getVertNo(dm, mface->v2, data[1]);
581                 dm->getVertNo(dm, mface->v3, data[2]);
582         } else {
583                 dm->getVertCo(dm, mface->v1, data[0]);
584                 dm->getVertCo(dm, mface->v2, data[1]);
585                 dm->getVertCo(dm, mface->v3, data[2]);
586         }
587
588         interp_barycentric_tri_data(data, u, v, res);
589 }
590
591 static void *init_heights_data(MultiresBakeRender *bkr, Image* ima)
592 {
593         MHeightBakeData *height_data;
594         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
595
596         height_data= MEM_callocN(sizeof(MHeightBakeData), "MultiresBake heightData");
597
598         height_data->ima= ima;
599         height_data->heights= MEM_callocN(sizeof(float)*ibuf->x*ibuf->y, "MultiresBake heights");
600         height_data->height_max= -FLT_MAX;
601         height_data->height_min= FLT_MAX;
602
603         if(!bkr->use_lores_mesh) {
604                 SubsurfModifierData smd= {{NULL}};
605                 int ss_lvl= bkr->tot_lvl - bkr->lvl;
606
607                 CLAMP(ss_lvl, 0, 6);
608
609                 smd.levels= smd.renderLevels= ss_lvl;
610                 smd.flags|= eSubsurfModifierFlag_SubsurfUv;
611
612                 if(bkr->simple)
613                         smd.subdivType= ME_SIMPLE_SUBSURF;
614
615                 height_data->ssdm= subsurf_make_derived_from_derived(bkr->lores_dm, &smd, 0, NULL, 0, 0, 0);
616         }
617
618         return (void*)height_data;
619 }
620
621 static void apply_heights_data(void *bake_data)
622 {
623         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
624         ImBuf *ibuf= BKE_image_get_ibuf(height_data->ima, NULL);
625         int x, y, i;
626         float height, *heights= height_data->heights;
627         float min= height_data->height_min, max= height_data->height_max;
628
629         for(x= 0; x<ibuf->x; x++) {
630                 for(y =0; y<ibuf->y; y++) {
631                         i= ibuf->x*y + x;
632
633                         if(((char*)ibuf->userdata)[i] != FILTER_MASK_USED)
634                                 continue;
635
636                         if(ibuf->rect_float) {
637                                 float *rrgbf= ibuf->rect_float + i*4;
638
639                                 if(max-min > 1e-5) height= (heights[i]-min)/(max-min);
640                                 else height= 0;
641
642                                 rrgbf[0]=rrgbf[1]=rrgbf[2]= height;
643                         } else {
644                                 char *rrgb= (char*)ibuf->rect + i*4;
645
646                                 if(max-min > 1e-5) height= (heights[i]-min)/(max-min);
647                                 else height= 0;
648
649                                 rrgb[0]=rrgb[1]=rrgb[2]= FTOCHAR(height);
650                         }
651                 }
652         }
653
654         ibuf->userflags= IB_RECT_INVALID;
655 }
656
657 static void free_heights_data(void *bake_data)
658 {
659         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
660
661         if(height_data->ssdm)
662                 height_data->ssdm->release(height_data->ssdm);
663
664         MEM_freeN(height_data->heights);
665         MEM_freeN(height_data);
666 }
667
668 /* MultiresBake callback for heights baking
669    general idea:
670      - find coord of point with specified UV in hi-res mesh (let's call it p1)
671      - find coord of point and normal with specified UV in lo-res mesh (or subdivided lo-res
672        mesh to make texture smoother) let's call this point p0 and n.
673      - height wound be dot(n, p1-p0) */
674 static void apply_heights_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *bake_data,
675                                    const int face_index, const int lvl, const float st[2],
676                                    float UNUSED(tangmat[3][3]), const int x, const int y)
677 {
678         MTFace *mtface= CustomData_get_layer(&lores_dm->faceData, CD_MTFACE);
679         MFace mface;
680         Image *ima= mtface[face_index].tpage;
681         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
682         MHeightBakeData *height_data= (MHeightBakeData*)bake_data;
683         float uv[2], *st0, *st1, *st2, *st3;
684         int pixel= ibuf->x*y + x;
685         float vec[3], p0[3], p1[3], n[3], len;
686
687         lores_dm->getFace(lores_dm, face_index, &mface);
688
689         st0= mtface[face_index].uv[0];
690         st1= mtface[face_index].uv[1];
691         st2= mtface[face_index].uv[2];
692
693         if(mface.v4) {
694                 st3= mtface[face_index].uv[3];
695                 resolve_quad_uv(uv, st, st0, st1, st2, st3);
696         } else
697                 resolve_tri_uv(uv, st, st0, st1, st2);
698
699         CLAMP(uv[0], 0.0f, 1.0f);
700         CLAMP(uv[1], 0.0f, 1.0f);
701
702         get_ccgdm_data(lores_dm, hires_dm, lvl, face_index, uv[0], uv[1], p1, 0);
703
704         if(height_data->ssdm) {
705                 //get_ccgdm_data_ss(lores_dm, height_data->ssdm, lvl, face_index, uv[0], uv[1], p0, n);
706                 get_ccgdm_data(lores_dm, height_data->ssdm, 0, face_index, uv[0], uv[1], p0, n);
707         } else {
708                 MFace mface;
709                 lores_dm->getFace(lores_dm, face_index, &mface);
710
711                 if(mface.v4) {
712                         interp_bilinear_mface(lores_dm, &mface, uv[0], uv[1], 1, p0);
713                         interp_bilinear_mface(lores_dm, &mface, uv[0], uv[1], 0, n);
714                 } else {
715                         interp_barycentric_mface(lores_dm, &mface, uv[0], uv[1], 1, p0);
716                         interp_barycentric_mface(lores_dm, &mface, uv[0], uv[1], 0, n);
717                 }
718         }
719
720         sub_v3_v3v3(vec, p1, p0);
721         //len= len_v3(vec);
722         len= dot_v3v3(n, vec);
723
724         height_data->heights[pixel]= len;
725         if(len<height_data->height_min) height_data->height_min= len;
726         if(len>height_data->height_max) height_data->height_max= len;
727
728         if(ibuf->rect_float) {
729                 float *rrgbf= ibuf->rect_float + pixel*4;
730                 rrgbf[3]= 1.0f;
731
732                 ibuf->userflags= IB_RECT_INVALID;
733         } else {
734                 char *rrgb= (char*)ibuf->rect + pixel*4;
735                 rrgb[3]= 255;
736         }
737 }
738
739 /* MultiresBake callback for normals' baking
740    general idea:
741      - find coord and normal of point with specified UV in hi-res mesh
742      - multiply it by tangmat
743      - vector in color space would be norm(vec) /2 + (0.5, 0.5, 0.5) */
744 static void apply_tangmat_callback(DerivedMesh *lores_dm, DerivedMesh *hires_dm, const void *UNUSED(bake_data),
745                                    const int face_index, const int lvl, const float st[2],
746                                    float tangmat[3][3], const int x, const int y)
747 {
748         MTFace *mtface= CustomData_get_layer(&lores_dm->faceData, CD_MTFACE);
749         MFace mface;
750         Image *ima= mtface[face_index].tpage;
751         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
752         float uv[2], *st0, *st1, *st2, *st3;
753         int pixel= ibuf->x*y + x;
754         float n[3], vec[3], tmp[3]= {0.5, 0.5, 0.5};
755
756         lores_dm->getFace(lores_dm, face_index, &mface);
757
758         st0= mtface[face_index].uv[0];
759         st1= mtface[face_index].uv[1];
760         st2= mtface[face_index].uv[2];
761
762         if(mface.v4) {
763                 st3= mtface[face_index].uv[3];
764                 resolve_quad_uv(uv, st, st0, st1, st2, st3);
765         } else
766                 resolve_tri_uv(uv, st, st0, st1, st2);
767
768         CLAMP(uv[0], 0.0f, 1.0f);
769         CLAMP(uv[1], 0.0f, 1.0f);
770
771         get_ccgdm_data(lores_dm, hires_dm, lvl, face_index, uv[0], uv[1], NULL, n);
772
773         mul_v3_m3v3(vec, tangmat, n);
774         normalize_v3(vec);
775         mul_v3_fl(vec, 0.5);
776         add_v3_v3(vec, tmp);
777
778         if(ibuf->rect_float) {
779                 float *rrgbf= ibuf->rect_float + pixel*4;
780                 rrgbf[0]= vec[0];
781                 rrgbf[1]= vec[1];
782                 rrgbf[2]= vec[2];
783                 rrgbf[3]= 1.0f;
784
785                 ibuf->userflags= IB_RECT_INVALID;
786         } else {
787                 char *rrgb= (char*)ibuf->rect + pixel*4;
788                 rrgb[0]= FTOCHAR(vec[0]);
789                 rrgb[1]= FTOCHAR(vec[1]);
790                 rrgb[2]= FTOCHAR(vec[2]);
791                 rrgb[3]= 255;
792         }
793 }
794
795 static void count_images(MultiresBakeRender *bkr)
796 {
797         int a, totface;
798         DerivedMesh *dm= bkr->lores_dm;
799         MTFace *mtface= CustomData_get_layer(&dm->faceData, CD_MTFACE);
800
801         bkr->image.first= bkr->image.last= NULL;
802         bkr->tot_image= 0;
803
804         totface= dm->getNumFaces(dm);
805
806         for(a= 0; a<totface; a++)
807                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
808
809         for(a= 0; a<totface; a++) {
810                 Image *ima= mtface[a].tpage;
811                 if((ima->id.flag&LIB_DOIT)==0) {
812                         LinkData *data= BLI_genericNodeN(ima);
813                         BLI_addtail(&bkr->image, data);
814                         bkr->tot_image++;
815                         ima->id.flag|= LIB_DOIT;
816                 }
817         }
818
819         for(a= 0; a<totface; a++)
820                 mtface[a].tpage->id.flag&= ~LIB_DOIT;
821 }
822
823 static void bake_images(MultiresBakeRender *bkr)
824 {
825         LinkData *link;
826
827         for(link= bkr->image.first; link; link= link->next) {
828                 Image *ima= (Image*)link->data;
829                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
830
831                 if(ibuf->x>0 && ibuf->y>0) {
832                         ibuf->userdata= MEM_callocN(ibuf->y*ibuf->x, "MultiresBake imbuf mask");
833
834                         switch(bkr->mode) {
835                                 case RE_BAKE_NORMALS:
836                                         do_multires_bake(bkr, ima, apply_tangmat_callback, NULL, NULL, NULL);
837                                         break;
838                                 case RE_BAKE_DISPLACEMENT:
839                                         do_multires_bake(bkr, ima, apply_heights_callback, init_heights_data,
840                                                          apply_heights_data, free_heights_data);
841                                         break;
842                         }
843                 }
844
845                 ima->id.flag|= LIB_DOIT;
846         }
847 }
848
849 static void finish_images(MultiresBakeRender *bkr)
850 {
851         LinkData *link;
852
853         for(link= bkr->image.first; link; link= link->next) {
854                 Image *ima= (Image*)link->data;
855                 int i;
856                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
857
858                 if(ibuf->x<=0 || ibuf->y<=0)
859                         continue;
860
861                 /* Margin */
862                 if(bkr->bake_filter) {
863                         char *temprect;
864
865                         /* extend the mask +2 pixels from the image,
866                          * this is so colors dont blend in from outside */
867
868                         for(i=0; i<bkr->bake_filter; i++)
869                                 IMB_mask_filter_extend((char *)ibuf->userdata, ibuf->x, ibuf->y);
870
871                         temprect = MEM_dupallocN(ibuf->userdata);
872
873                         /* expand twice to clear this many pixels, so they blend back in */
874                         IMB_mask_filter_extend(temprect, ibuf->x, ibuf->y);
875                         IMB_mask_filter_extend(temprect, ibuf->x, ibuf->y);
876
877                         /* clear all pixels in the margin */
878                         IMB_mask_clear(ibuf, temprect, FILTER_MASK_MARGIN);
879                         MEM_freeN(temprect);
880
881                         for(i= 0; i<bkr->bake_filter; i++)
882                                 IMB_filter_extend(ibuf, (char *)ibuf->userdata);
883                 }
884
885                 ibuf->userflags|= IB_BITMAPDIRTY;
886                 if(ibuf->mipmap[0]) {
887                         ibuf->userflags|= IB_MIPMAP_INVALID;
888                         imb_freemipmapImBuf(ibuf);
889                 }
890
891                 if(ibuf->userdata) {
892                         MEM_freeN(ibuf->userdata);
893                         ibuf->userdata= NULL;
894                 }
895         }
896 }
897
898 static void multiresbake_start(MultiresBakeRender *bkr)
899 {
900         count_images(bkr);
901         bake_images(bkr);
902         finish_images(bkr);
903 }
904
905 static int multiresbake_check(bContext *C, wmOperator *op) {
906         Scene *scene= CTX_data_scene(C);
907         Object *ob;
908         Mesh *me;
909         MultiresModifierData *mmd;
910         int ok= 1, a;
911
912         CTX_DATA_BEGIN(C, Base*, base, selected_editable_bases) {
913                 ob= base->object;
914
915                 if(ob->type != OB_MESH) {
916                         BKE_report(op->reports, RPT_ERROR, "Basking of multires data only works with active object which is a mesh");
917
918                         ok= 0;
919                         break;
920                 }
921
922                 me= (Mesh*)ob->data;
923                 mmd= get_multires_modifier(scene, ob, 0);
924
925                 /* Multi-resolution should be and be last in the stack */
926                 if(ok && mmd) {
927                         ModifierData *md;
928
929                         ok= mmd->totlvl>0;
930
931                         for(md = (ModifierData*)mmd->modifier.next; md && ok; md = md->next) {
932                                 if (modifier_isEnabled(scene, md, eModifierMode_Realtime)) {
933                                         ok= 0;
934                                 }
935                         }
936                 } else ok= 0;
937
938                 if(!ok) {
939                         BKE_report(op->reports, RPT_ERROR, "Multires data baking requires multi-resolution object");
940
941                         break;
942                 }
943
944                 if(!me->mtface) {
945                         BKE_report(op->reports, RPT_ERROR, "Mesh should be unwrapped before multires data baking");
946
947                         ok= 0;
948                 } else {
949                         a= me->totface;
950                         while (ok && a--) {
951                                 Image *ima= me->mtface[a].tpage;
952
953                                 if(!ima) {
954                                         BKE_report(op->reports, RPT_ERROR, "You should have active texture to use multires baker");
955
956                                         ok= 0;
957                                 } else {
958                                         ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
959
960                                         if(!ibuf) {
961                                                 BKE_report(op->reports, RPT_ERROR, "Baking should happend to image with image buffer");
962
963                                                 ok= 0;
964                                         } else {
965                                                 if(ibuf->rect==NULL && ibuf->rect_float==NULL)
966                                                         ok= 0;
967
968                                                 if(ibuf->rect_float && !(ibuf->channels==0 || ibuf->channels==4))
969                                                         ok= 0;
970
971                                                 if(!ok)
972                                                         BKE_report(op->reports, RPT_ERROR, "Baking to unsupported image type");
973                                         }
974                                 }
975                         }
976                 }
977
978                 if(!ok)
979                         break;
980         }
981         CTX_DATA_END;
982
983         return ok;
984 }
985
986 static DerivedMesh *multiresbake_create_loresdm(Scene *scene, Object *ob, int *lvl)
987 {
988         DerivedMesh *dm;
989         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
990         Mesh *me= (Mesh*)ob->data;
991
992         *lvl= mmd->lvl;
993
994         if(mmd->lvl==0) {
995                 DerivedMesh *tmp_dm= CDDM_from_mesh(me, ob);
996                 dm= CDDM_copy(tmp_dm);
997                 tmp_dm->release(tmp_dm);
998         } else {
999                 MultiresModifierData tmp_mmd= *mmd;
1000                 DerivedMesh *cddm= CDDM_from_mesh(me, ob);
1001
1002                 tmp_mmd.lvl= mmd->lvl;
1003                 dm= multires_dm_create_from_derived(&tmp_mmd, 1, cddm, ob, 0, 0);
1004                 cddm->release(cddm);
1005         }
1006
1007         return dm;
1008 }
1009
1010 static DerivedMesh *multiresbake_create_hiresdm(Scene *scene, Object *ob, int *lvl, int *simple)
1011 {
1012         Mesh *me= (Mesh*)ob->data;
1013         MultiresModifierData *mmd= get_multires_modifier(scene, ob, 0);
1014         MultiresModifierData tmp_mmd= *mmd;
1015         DerivedMesh *cddm= CDDM_from_mesh(me, ob);
1016         DerivedMesh *dm;
1017
1018         *lvl= mmd->totlvl;
1019         *simple= mmd->simple;
1020
1021         tmp_mmd.lvl= mmd->totlvl;
1022         dm= multires_dm_create_from_derived(&tmp_mmd, 1, cddm, ob, 0, 0);
1023         cddm->release(cddm);
1024
1025         return dm;
1026 }
1027
1028 static void clear_images(MTFace *mtface, int totface)
1029 {
1030         int a;
1031         float vec[4]= {0.0f, 0.0f, 0.0f, 0.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, vec);
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 static ScrArea *biggest_image_area(bScreen *screen)
1224 {
1225         ScrArea *sa, *big= NULL;
1226         int size, maxsize= 0;
1227
1228         for(sa= screen->areabase.first; sa; sa= sa->next) {
1229                 if(sa->spacetype==SPACE_IMAGE) {
1230                         size= sa->winx*sa->winy;
1231                         if(sa->winx > 10 && sa->winy > 10 && size > maxsize) {
1232                                 maxsize= size;
1233                                 big= sa;
1234                         }
1235                 }
1236         }
1237         return big;
1238 }
1239
1240
1241 typedef struct BakeRender {
1242         Render *re;
1243         Main *main;
1244         Scene *scene;
1245         struct Object *actob;
1246         int tot, ready;
1247
1248         ReportList *reports;
1249
1250         short *stop;
1251         short *do_update;
1252         float *progress;
1253         
1254         ListBase threads;
1255
1256         /* backup */
1257         short prev_wo_amb_occ;
1258         short prev_r_raytrace;
1259
1260         /* for redrawing */
1261         ScrArea *sa;
1262 } BakeRender;
1263
1264 /* use by exec and invoke */
1265 static int test_bake_internal(bContext *C, ReportList *reports)
1266 {
1267         Scene *scene= CTX_data_scene(C);
1268
1269         if(scene->r.renderer!=R_INTERN) {
1270                 BKE_report(reports, RPT_ERROR, "Bake only supported for Internal Renderer");
1271         } else if((scene->r.bake_flag & R_BAKE_TO_ACTIVE) && CTX_data_active_object(C)==NULL) {
1272                 BKE_report(reports, RPT_ERROR, "No active object");
1273         }
1274         else if(scene->r.bake_mode==RE_BAKE_AO && scene->world==NULL) {
1275                 BKE_report(reports, RPT_ERROR, "No world set up");
1276         }
1277         else {
1278                 return 1;
1279         }
1280
1281         return 0;
1282 }
1283
1284 static void init_bake_internal(BakeRender *bkr, bContext *C)
1285 {
1286         Scene *scene= CTX_data_scene(C);
1287
1288         /* get editmode results */
1289         ED_object_exit_editmode(C, 0);  /* 0 = does not exit editmode */
1290
1291         bkr->sa= biggest_image_area(CTX_wm_screen(C)); /* can be NULL */
1292         bkr->main= CTX_data_main(C);
1293         bkr->scene= scene;
1294         bkr->actob= (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL;
1295         bkr->re= RE_NewRender("_Bake View_");
1296
1297         if(scene->r.bake_mode==RE_BAKE_AO) {
1298                 /* If raytracing or AO is disabled, switch it on temporarily for baking. */
1299                 bkr->prev_wo_amb_occ = (scene->world->mode & WO_AMB_OCC) != 0;
1300                 scene->world->mode |= WO_AMB_OCC;
1301         }
1302         if(scene->r.bake_mode==RE_BAKE_AO || bkr->actob) {
1303                 bkr->prev_r_raytrace = (scene->r.mode & R_RAYTRACE) != 0;
1304                 scene->r.mode |= R_RAYTRACE;
1305         }
1306 }
1307
1308 static void finish_bake_internal(BakeRender *bkr)
1309 {
1310         RE_Database_Free(bkr->re);
1311
1312         /* restore raytrace and AO */
1313         if(bkr->scene->r.bake_mode==RE_BAKE_AO)
1314                 if(bkr->prev_wo_amb_occ == 0)
1315                         bkr->scene->world->mode &= ~WO_AMB_OCC;
1316
1317         if(bkr->scene->r.bake_mode==RE_BAKE_AO || bkr->actob)
1318                 if(bkr->prev_r_raytrace == 0)
1319                         bkr->scene->r.mode &= ~R_RAYTRACE;
1320
1321         if(bkr->tot) {
1322                 Image *ima;
1323                 /* force OpenGL reload and mipmap recalc */
1324                 for(ima= G.main->image.first; ima; ima= ima->id.next) {
1325                         if(ima->ok==IMA_OK_LOADED) {
1326                                 ImBuf *ibuf= BKE_image_get_ibuf(ima, NULL);
1327                                 if(ibuf) {
1328                                         if(ibuf->userflags & IB_BITMAPDIRTY) {
1329                                                 GPU_free_image(ima);
1330                                                 imb_freemipmapImBuf(ibuf);
1331                                         }
1332
1333                                         /* freed when baking is done, but if its canceled we need to free here */
1334                                         if (ibuf->userdata) {
1335                                                 printf("freed\n");
1336                                                 MEM_freeN(ibuf->userdata);
1337                                                 ibuf->userdata= NULL;
1338                                         }
1339                                 }
1340                         }
1341                 }
1342         }
1343 }
1344
1345 static void *do_bake_render(void *bake_v)
1346 {
1347         BakeRender *bkr= bake_v;
1348
1349         bkr->tot= RE_bake_shade_all_selected(bkr->re, bkr->scene->r.bake_mode, bkr->actob, NULL, bkr->progress);
1350         bkr->ready= 1;
1351
1352         return NULL;
1353 }
1354
1355 static void bake_startjob(void *bkv, short *stop, short *do_update, float *progress)
1356 {
1357         BakeRender *bkr= bkv;
1358         Scene *scene= bkr->scene;
1359         Main *bmain= bkr->main;
1360
1361         bkr->stop= stop;
1362         bkr->do_update= do_update;
1363         bkr->progress= progress;
1364
1365         RE_test_break_cb(bkr->re, NULL, thread_break);
1366         G.afbreek= 0;   /* blender_test_break uses this global */
1367
1368         RE_Database_Baking(bkr->re, bmain, scene, scene->lay, scene->r.bake_mode, bkr->actob);
1369
1370         /* baking itself is threaded, cannot use test_break in threads. we also update optional imagewindow */
1371         bkr->tot= RE_bake_shade_all_selected(bkr->re, scene->r.bake_mode, bkr->actob, bkr->do_update, bkr->progress);
1372 }
1373
1374 static void bake_update(void *bkv)
1375 {
1376         BakeRender *bkr= bkv;
1377
1378         if(bkr->sa && bkr->sa->spacetype==SPACE_IMAGE) { /* incase the user changed while baking */
1379                 SpaceImage *sima= bkr->sa->spacedata.first;
1380                 if(sima)
1381                         sima->image= RE_bake_shade_get_image();
1382         }
1383 }
1384
1385 static void bake_freejob(void *bkv)
1386 {
1387         BakeRender *bkr= bkv;
1388         finish_bake_internal(bkr);
1389
1390         if(bkr->tot==0) BKE_report(bkr->reports, RPT_ERROR, "No objects or images found to bake to");
1391         MEM_freeN(bkr);
1392         G.rendering = 0;
1393 }
1394
1395 /* catch esc */
1396 static int objects_bake_render_modal(bContext *C, wmOperator *UNUSED(op), wmEvent *event)
1397 {
1398         /* no running blender, remove handler and pass through */
1399         if(0==WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C)))
1400                 return OPERATOR_FINISHED|OPERATOR_PASS_THROUGH;
1401
1402         /* running render */
1403         switch (event->type) {
1404                 case ESCKEY:
1405                         return OPERATOR_RUNNING_MODAL;
1406                         break;
1407         }
1408         return OPERATOR_PASS_THROUGH;
1409 }
1410
1411 static int is_multires_bake(Scene *scene)
1412 {
1413         if ( ELEM(scene->r.bake_mode, RE_BAKE_NORMALS, RE_BAKE_DISPLACEMENT))
1414                 return scene->r.bake_flag & R_BAKE_MULTIRES;
1415
1416         return 0;
1417 }
1418
1419 static int objects_bake_render_invoke(bContext *C, wmOperator *op, wmEvent *UNUSED(_event))
1420 {
1421         Scene *scene= CTX_data_scene(C);
1422         int result= OPERATOR_CANCELLED;
1423
1424         if(is_multires_bake(scene)) {
1425                 result= multiresbake_image_exec(C, op);
1426         } else {
1427                 /* only one render job at a time */
1428                 if(WM_jobs_test(CTX_wm_manager(C), scene))
1429                         return OPERATOR_CANCELLED;
1430
1431                 if(test_bake_internal(C, op->reports)==0) {
1432                         return OPERATOR_CANCELLED;
1433                 }
1434                 else {
1435                         BakeRender *bkr= MEM_callocN(sizeof(BakeRender), "render bake");
1436                         wmJob *steve;
1437
1438                         init_bake_internal(bkr, C);
1439                         bkr->reports= op->reports;
1440
1441                         /* setup job */
1442                         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);
1443                         WM_jobs_customdata(steve, bkr, bake_freejob);
1444                         WM_jobs_timer(steve, 0.2, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
1445                         WM_jobs_callbacks(steve, bake_startjob, NULL, bake_update, NULL);
1446
1447                         G.afbreek= 0;
1448                         G.rendering = 1;
1449
1450                         WM_jobs_start(CTX_wm_manager(C), steve);
1451
1452                         WM_cursor_wait(0);
1453
1454                         /* add modal handler for ESC */
1455                         WM_event_add_modal_handler(C, op);
1456                 }
1457
1458                 result= OPERATOR_RUNNING_MODAL;
1459         }
1460
1461         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
1462
1463         return result;
1464 }
1465
1466
1467 static int bake_image_exec(bContext *C, wmOperator *op)
1468 {
1469         Main *bmain= CTX_data_main(C);
1470         Scene *scene= CTX_data_scene(C);
1471         int result= OPERATOR_CANCELLED;
1472
1473         if(is_multires_bake(scene)) {
1474                 result= multiresbake_image_exec_locked(C, op);
1475         } else  {
1476                 if(test_bake_internal(C, op->reports)==0) {
1477                         return OPERATOR_CANCELLED;
1478                 }
1479                 else {
1480                         ListBase threads;
1481                         BakeRender bkr= {NULL};
1482
1483                         init_bake_internal(&bkr, C);
1484                         bkr.reports= op->reports;
1485
1486                         RE_test_break_cb(bkr.re, NULL, thread_break);
1487                         G.afbreek= 0;   /* blender_test_break uses this global */
1488
1489                         RE_Database_Baking(bkr.re, bmain, scene, scene->lay, scene->r.bake_mode, (scene->r.bake_flag & R_BAKE_TO_ACTIVE)? OBACT: NULL);
1490
1491                         /* baking itself is threaded, cannot use test_break in threads  */
1492                         BLI_init_threads(&threads, do_bake_render, 1);
1493                         bkr.ready= 0;
1494                         BLI_insert_thread(&threads, &bkr);
1495
1496                         while(bkr.ready==0) {
1497                                 PIL_sleep_ms(50);
1498                                 if(bkr.ready)
1499                                         break;
1500
1501                                 /* used to redraw in 2.4x but this is just for exec in 2.5 */
1502                                 if (!G.background)
1503                                         blender_test_break();
1504                         }
1505                         BLI_end_threads(&threads);
1506
1507                         if(bkr.tot==0) BKE_report(op->reports, RPT_ERROR, "No valid images found to bake to");
1508
1509                         finish_bake_internal(&bkr);
1510
1511                         result= OPERATOR_FINISHED;
1512                 }
1513         }
1514
1515         WM_event_add_notifier(C, NC_SCENE|ND_RENDER_RESULT, scene);
1516
1517         return result;
1518 }
1519
1520 void OBJECT_OT_bake_image(wmOperatorType *ot)
1521 {
1522         /* identifiers */
1523         ot->name= "Bake";
1524         ot->description= "Bake image textures of selected objects";
1525         ot->idname= "OBJECT_OT_bake_image";
1526
1527         /* api callbacks */
1528         ot->exec= bake_image_exec;
1529         ot->invoke= objects_bake_render_invoke;
1530         ot->modal= objects_bake_render_modal;
1531 }