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