Eevee: SSR: Making ray count a define rather than an uniform.
[blender.git] / source / blender / editors / object / object_bake_api.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):
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/editors/object/object_bake_api.c
29  *  \ingroup edobj
30  */
31
32
33 #include "MEM_guardedalloc.h"
34
35 #include "DNA_object_types.h"
36 #include "DNA_mesh_types.h"
37 #include "DNA_material_types.h"
38
39 #include "RNA_access.h"
40 #include "RNA_define.h"
41 #include "RNA_enum_types.h"
42
43 #include "BLI_listbase.h"
44 #include "BLI_string.h"
45 #include "BLI_fileops.h"
46 #include "BLI_math_geom.h"
47 #include "BLI_path_util.h"
48
49 #include "BKE_context.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_library.h"
53 #include "BKE_main.h"
54 #include "BKE_material.h"
55 #include "BKE_node.h"
56 #include "BKE_report.h"
57 #include "BKE_modifier.h"
58 #include "BKE_mesh.h"
59 #include "BKE_screen.h"
60
61 #include "DEG_depsgraph.h"
62
63 #include "RE_engine.h"
64 #include "RE_pipeline.h"
65
66 #include "IMB_imbuf_types.h"
67 #include "IMB_imbuf.h"
68 #include "IMB_colormanagement.h"
69
70 #include "WM_api.h"
71 #include "WM_types.h"
72
73 #include "ED_object.h"
74 #include "ED_screen.h"
75 #include "ED_uvedit.h"
76
77 #include "GPU_draw.h"
78
79 #include "object_intern.h"
80
81 /* prototypes */
82 static void bake_set_props(wmOperator *op, Scene *scene);
83
84 typedef struct BakeAPIRender {
85         Object *ob;
86         Main *main;
87         Depsgraph *depsgraph;
88         Scene *scene;
89         ReportList *reports;
90         ListBase selected_objects;
91
92         ScenePassType pass_type;
93         int pass_filter;
94         int margin;
95
96         int save_mode;
97
98         bool is_clear;
99         bool is_split_materials;
100         bool is_automatic_name;
101         bool is_selected_to_active;
102         bool is_cage;
103
104         float cage_extrusion;
105         int normal_space;
106         BakeNormalSwizzle normal_swizzle[3];
107
108         char uv_layer[MAX_CUSTOMDATA_LAYER_NAME];
109         char custom_cage[MAX_NAME];
110         char filepath[FILE_MAX];
111
112         int width;
113         int height;
114         const char *identifier;
115
116         int result;
117         bool ready;
118
119         /* callbacks */
120         Render *render;
121         float *progress;
122         short *do_update;
123
124         /* for redrawing */
125         ScrArea *sa;
126 } BakeAPIRender;
127
128 /* callbacks */
129
130 static void bake_progress_update(void *bjv, float progress)
131 {
132         BakeAPIRender *bj = bjv;
133
134         if (bj->progress && *bj->progress != progress) {
135                 *bj->progress = progress;
136
137                 /* make jobs timer to send notifier */
138                 *(bj->do_update) = true;
139         }
140 }
141
142 /* catch esc */
143 static int bake_modal(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
144 {
145         /* no running blender, remove handler and pass through */
146         if (0 == WM_jobs_test(CTX_wm_manager(C), CTX_data_scene(C), WM_JOB_TYPE_OBJECT_BAKE))
147                 return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
148
149         /* running render */
150         switch (event->type) {
151                 case ESCKEY:
152                 {
153                         G.is_break = true;
154                         return OPERATOR_RUNNING_MODAL;
155                 }
156         }
157         return OPERATOR_PASS_THROUGH;
158 }
159
160 /* for exec() when there is no render job
161  * note: this wont check for the escape key being pressed, but doing so isnt threadsafe */
162 static int bake_break(void *UNUSED(rjv))
163 {
164         if (G.is_break)
165                 return 1;
166         return 0;
167 }
168
169
170 static void bake_update_image(ScrArea *sa, Image *image)
171 {
172         if (sa && sa->spacetype == SPACE_IMAGE) { /* in case the user changed while baking */
173                 SpaceImage *sima = sa->spacedata.first;
174                 if (sima)
175                         sima->image = image;
176         }
177 }
178
179 static bool write_internal_bake_pixels(
180         Image *image, BakePixel pixel_array[], float *buffer,
181         const int width, const int height, const int margin,
182         const bool is_clear, const bool is_noncolor)
183 {
184         ImBuf *ibuf;
185         void *lock;
186         bool is_float;
187         char *mask_buffer = NULL;
188         const size_t num_pixels = (size_t)width * (size_t)height;
189
190         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
191
192         if (!ibuf)
193                 return false;
194
195         if (margin > 0 || !is_clear) {
196                 mask_buffer = MEM_callocN(sizeof(char) * num_pixels, "Bake Mask");
197                 RE_bake_mask_fill(pixel_array, num_pixels, mask_buffer);
198         }
199
200         is_float = (ibuf->flags & IB_rectfloat);
201
202         /* colormanagement conversions */
203         if (!is_noncolor) {
204                 const char *from_colorspace;
205                 const char *to_colorspace;
206
207                 from_colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_SCENE_LINEAR);
208
209                 if (is_float)
210                         to_colorspace = IMB_colormanagement_get_float_colorspace(ibuf);
211                 else
212                         to_colorspace = IMB_colormanagement_get_rect_colorspace(ibuf);
213
214                 if (from_colorspace != to_colorspace)
215                         IMB_colormanagement_transform(buffer, ibuf->x, ibuf->y, ibuf->channels, from_colorspace, to_colorspace, false);
216         }
217
218         /* populates the ImBuf */
219         if (is_clear) {
220                 if (is_float) {
221                         IMB_buffer_float_from_float(
222                                 ibuf->rect_float, buffer, ibuf->channels,
223                                 IB_PROFILE_LINEAR_RGB, IB_PROFILE_LINEAR_RGB, false,
224                                 ibuf->x, ibuf->y, ibuf->x, ibuf->x);
225                 }
226                 else {
227                         IMB_buffer_byte_from_float(
228                                 (unsigned char *) ibuf->rect, buffer, ibuf->channels, ibuf->dither,
229                                 IB_PROFILE_SRGB, IB_PROFILE_SRGB,
230                                 false, ibuf->x, ibuf->y, ibuf->x, ibuf->x);
231                 }
232         }
233         else {
234                 if (is_float) {
235                         IMB_buffer_float_from_float_mask(
236                                 ibuf->rect_float, buffer, ibuf->channels,
237                                 ibuf->x, ibuf->y, ibuf->x, ibuf->x, mask_buffer);
238                 }
239                 else {
240                         IMB_buffer_byte_from_float_mask(
241                                 (unsigned char *) ibuf->rect, buffer, ibuf->channels, ibuf->dither,
242                                 false, ibuf->x, ibuf->y, ibuf->x, ibuf->x, mask_buffer);
243                 }
244         }
245
246         /* margins */
247         if (margin > 0)
248                 RE_bake_margin(ibuf, mask_buffer, margin);
249
250         ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID | IB_BITMAPDIRTY;
251
252         if (ibuf->rect_float)
253                 ibuf->userflags |= IB_RECT_INVALID;
254
255         /* force mipmap recalc */
256         if (ibuf->mipmap[0]) {
257                 ibuf->userflags |= IB_MIPMAP_INVALID;
258                 imb_freemipmapImBuf(ibuf);
259         }
260
261         BKE_image_release_ibuf(image, ibuf, NULL);
262
263         if (mask_buffer)
264                 MEM_freeN(mask_buffer);
265
266         return true;
267 }
268
269 /* force OpenGL reload */
270 static void refresh_images(BakeImages *bake_images)
271 {
272         int i;
273         for (i = 0; i < bake_images->size; i++) {
274                 Image *ima = bake_images->data[i].image;
275                 if (ima->ok == IMA_OK_LOADED) {
276                         GPU_free_image(ima);
277                         DEG_id_tag_update(&ima->id, 0);         
278                 }
279         }
280 }
281
282 static bool write_external_bake_pixels(
283         const char *filepath, BakePixel pixel_array[], float *buffer,
284         const int width, const int height, const int margin,
285         ImageFormatData *im_format, const bool is_noncolor)
286 {
287         ImBuf *ibuf = NULL;
288         bool ok = false;
289         bool is_float;
290
291         is_float = im_format->depth > 8;
292
293         /* create a new ImBuf */
294         ibuf = IMB_allocImBuf(width, height, im_format->planes, (is_float ? IB_rectfloat : IB_rect));
295
296         if (!ibuf)
297                 return false;
298
299         /* populates the ImBuf */
300         if (is_float) {
301                 IMB_buffer_float_from_float(
302                         ibuf->rect_float, buffer, ibuf->channels,
303                         IB_PROFILE_LINEAR_RGB, IB_PROFILE_LINEAR_RGB, false,
304                         ibuf->x, ibuf->y, ibuf->x, ibuf->x);
305         }
306         else {
307                 if (!is_noncolor) {
308                         const char *from_colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_SCENE_LINEAR);
309                         const char *to_colorspace = IMB_colormanagement_get_rect_colorspace(ibuf);
310                         IMB_colormanagement_transform(buffer, ibuf->x, ibuf->y, ibuf->channels, from_colorspace, to_colorspace, false);
311                 }
312
313                 IMB_buffer_byte_from_float(
314                         (unsigned char *) ibuf->rect, buffer, ibuf->channels, ibuf->dither,
315                         IB_PROFILE_SRGB, IB_PROFILE_SRGB,
316                         false, ibuf->x, ibuf->y, ibuf->x, ibuf->x);
317         }
318
319         /* margins */
320         if (margin > 0) {
321                 char *mask_buffer = NULL;
322                 const size_t num_pixels = (size_t)width * (size_t)height;
323
324                 mask_buffer = MEM_callocN(sizeof(char) * num_pixels, "Bake Mask");
325                 RE_bake_mask_fill(pixel_array, num_pixels, mask_buffer);
326                 RE_bake_margin(ibuf, mask_buffer, margin);
327
328                 if (mask_buffer)
329                         MEM_freeN(mask_buffer);
330         }
331
332         if ((ok = BKE_imbuf_write(ibuf, filepath, im_format))) {
333 #ifndef WIN32
334                 chmod(filepath, S_IRUSR | S_IWUSR);
335 #endif
336                 //printf("%s saving bake map: '%s'\n", __func__, filepath);
337         }
338
339         /* garbage collection */
340         IMB_freeImBuf(ibuf);
341
342         return ok;
343 }
344
345 static bool is_noncolor_pass(ScenePassType pass_type)
346 {
347         return ELEM(pass_type,
348                     SCE_PASS_Z,
349                     SCE_PASS_NORMAL,
350                     SCE_PASS_VECTOR,
351                     SCE_PASS_INDEXOB,
352                     SCE_PASS_UV,
353                     SCE_PASS_RAYHITS,
354                     SCE_PASS_INDEXMA);
355 }
356
357 /* if all is good tag image and return true */
358 static bool bake_object_check(Scene *scene, Object *ob, ReportList *reports)
359 {
360         Image *image;
361         void *lock;
362         int i;
363
364         if ((ob->lay & scene->lay) == 0) {
365                 BKE_reportf(reports, RPT_ERROR, "Object \"%s\" is not on a scene layer", ob->id.name + 2);
366                 return false;
367         }
368
369         if (ob->type != OB_MESH) {
370                 BKE_reportf(reports, RPT_ERROR, "Object \"%s\" is not a mesh", ob->id.name + 2);
371                 return false;
372         }
373         else {
374                 Mesh *me = (Mesh *)ob->data;
375
376                 if (CustomData_get_active_layer_index(&me->ldata, CD_MLOOPUV) == -1) {
377                         BKE_reportf(reports, RPT_ERROR,
378                                     "No active UV layer found in the object \"%s\"", ob->id.name + 2);
379                         return false;
380                 }
381         }
382
383         for (i = 0; i < ob->totcol; i++) {
384                 bNodeTree *ntree = NULL;
385                 bNode *node = NULL;
386                 ED_object_get_active_image(ob, i + 1, &image, NULL, &node, &ntree);
387
388                 if (image) {
389                         ImBuf *ibuf;
390
391                         if (node) {
392                                 if (BKE_node_is_connected_to_output(ntree, node)) {
393                                         /* we don't return false since this may be a false positive
394                                          * this can't be RPT_ERROR though, otherwise it prevents
395                                          * multiple highpoly objects to be baked at once */
396                                         BKE_reportf(reports, RPT_INFO,
397                                                     "Circular dependency for image \"%s\" from object \"%s\"",
398                                                     image->id.name + 2, ob->id.name + 2);
399                                 }
400                         }
401
402                         ibuf = BKE_image_acquire_ibuf(image, NULL, &lock);
403
404                         if (ibuf) {
405                                 BKE_image_release_ibuf(image, ibuf, lock);
406                         }
407                         else {
408                                 BKE_reportf(reports, RPT_ERROR,
409                                             "Uninitialized image \"%s\" from object \"%s\"",
410                                             image->id.name + 2, ob->id.name + 2);
411
412                                 BKE_image_release_ibuf(image, ibuf, lock);
413                                 return false;
414                         }
415                 }
416                 else {
417                         Material *mat = give_current_material(ob, i);
418                         if (mat != NULL) {
419                                 BKE_reportf(reports, RPT_INFO,
420                                             "No active image found in material \"%s\" (%d) for object \"%s\"",
421                                             mat->id.name + 2, i, ob->id.name + 2);
422                         }
423                         else {
424                                 BKE_reportf(reports, RPT_INFO,
425                                             "No active image found in material slot (%d) for object \"%s\"",
426                                             i, ob->id.name + 2);
427                         }
428                         continue;
429                 }
430
431                 image->id.tag |= LIB_TAG_DOIT;
432         }
433         return true;
434 }
435
436 static bool bake_pass_filter_check(ScenePassType pass_type, const int pass_filter, ReportList *reports)
437 {
438         switch (pass_type) {
439                 case SCE_PASS_COMBINED:
440                         if ((pass_filter & R_BAKE_PASS_FILTER_EMIT) != 0) {
441                                 return true;
442                         }
443
444                         if (((pass_filter & R_BAKE_PASS_FILTER_DIRECT) != 0) ||
445                             ((pass_filter & R_BAKE_PASS_FILTER_INDIRECT) != 0))
446                         {
447                                 if (((pass_filter & R_BAKE_PASS_FILTER_DIFFUSE) != 0) ||
448                                     ((pass_filter & R_BAKE_PASS_FILTER_GLOSSY) != 0) ||
449                                     ((pass_filter & R_BAKE_PASS_FILTER_TRANSM) != 0) ||
450                                     ((pass_filter & R_BAKE_PASS_FILTER_SUBSURFACE) != 0))
451                                 {
452                                         return true;
453                                 }
454
455                                 if ((pass_filter & R_BAKE_PASS_FILTER_AO) != 0) {
456                                         BKE_report(reports, RPT_ERROR,
457                                                    "Combined bake pass Ambient Occlusion contribution requires an enabled light pass "
458                                                    "(bake the Ambient Occlusion pass type instead)");
459                                 }
460                                 else {
461                                         BKE_report(reports, RPT_ERROR,
462                                                    "Combined bake pass requires Emit, or a light pass with "
463                                                    "Direct or Indirect contributions enabled");
464                                 }
465
466                                 return false;
467                         }
468                         else {
469                                 BKE_report(reports, RPT_ERROR,
470                                            "Combined bake pass requires Emit, or a light pass with "
471                                            "Direct or Indirect contributions enabled");
472                                 return false;
473                         }
474                         break;
475                 case SCE_PASS_DIFFUSE_COLOR:
476                 case SCE_PASS_GLOSSY_COLOR:
477                 case SCE_PASS_TRANSM_COLOR:
478                 case SCE_PASS_SUBSURFACE_COLOR:
479                         if (((pass_filter & R_BAKE_PASS_FILTER_COLOR) != 0) ||
480                             ((pass_filter & R_BAKE_PASS_FILTER_DIRECT) != 0) ||
481                             ((pass_filter & R_BAKE_PASS_FILTER_INDIRECT) != 0))
482                         {
483                                 return true;
484                         }
485                         else {
486                                 BKE_report(reports, RPT_ERROR,
487                                            "Bake pass requires Direct, Indirect, or Color contributions to be enabled");
488                                 return false;
489                         }
490                         break;
491                 default:
492                         return true;
493                         break;
494         }
495 }
496
497 /* before even getting in the bake function we check for some basic errors */
498 static bool bake_objects_check(Main *bmain, Scene *scene, Object *ob, ListBase *selected_objects,
499                                ReportList *reports, const bool is_selected_to_active)
500 {
501         CollectionPointerLink *link;
502
503         /* error handling and tag (in case multiple materials share the same image) */
504         BKE_main_id_tag_idcode(bmain, ID_IM, LIB_TAG_DOIT, false);
505
506         if (is_selected_to_active) {
507                 int tot_objects = 0;
508
509                 if (!bake_object_check(scene, ob, reports))
510                         return false;
511
512                 for (link = selected_objects->first; link; link = link->next) {
513                         Object *ob_iter = (Object *)link->ptr.data;
514
515                         if (ob_iter == ob)
516                                 continue;
517
518                         if (ELEM(ob_iter->type, OB_MESH, OB_FONT, OB_CURVE, OB_SURF, OB_MBALL) == false) {
519                                 BKE_reportf(reports, RPT_ERROR, "Object \"%s\" is not a mesh or can't be converted to a mesh (Curve, Text, Surface or Metaball)", ob_iter->id.name + 2);
520                                 return false;
521                         }
522                         tot_objects += 1;
523                 }
524
525                 if (tot_objects == 0) {
526                         BKE_report(reports, RPT_ERROR, "No valid selected objects");
527                         return false;
528                 }
529         }
530         else {
531                 if (BLI_listbase_is_empty(selected_objects)) {
532                         BKE_report(reports, RPT_ERROR, "No valid selected objects");
533                         return false;
534                 }
535
536                 for (link = selected_objects->first; link; link = link->next) {
537                         if (!bake_object_check(scene, link->ptr.data, reports))
538                                 return false;
539                 }
540         }
541         return true;
542 }
543
544 /* it needs to be called after bake_objects_check since the image tagging happens there */
545 static void bake_images_clear(Main *bmain, const bool is_tangent)
546 {
547         Image *image;
548         for (image = bmain->image.first; image; image = image->id.next) {
549                 if ((image->id.tag & LIB_TAG_DOIT) != 0) {
550                         RE_bake_ibuf_clear(image, is_tangent);
551                 }
552         }
553 }
554
555 static void build_image_lookup(Main *bmain, Object *ob, BakeImages *bake_images)
556 {
557         const int tot_mat = ob->totcol;
558         int i, j;
559         int tot_images = 0;
560
561         /* error handling and tag (in case multiple materials share the same image) */
562         BKE_main_id_tag_idcode(bmain, ID_IM, LIB_TAG_DOIT, false);
563
564         for (i = 0; i < tot_mat; i++) {
565                 Image *image;
566                 ED_object_get_active_image(ob, i + 1, &image, NULL, NULL, NULL);
567
568                 /* Some materials have no image, we just ignore those cases. */
569                 if (image == NULL) {
570                         bake_images->lookup[i] = -1;
571                 }
572                 else if (image->id.tag & LIB_TAG_DOIT) {
573                         for (j = 0; j < i; j++) {
574                                 if (bake_images->data[j].image == image) {
575                                         bake_images->lookup[i] = j;
576                                         break;
577                                 }
578                         }
579                 }
580                 else {
581                         bake_images->lookup[i] = tot_images;
582                         bake_images->data[tot_images].image = image;
583                         image->id.tag |= LIB_TAG_DOIT;
584                         tot_images++;
585                 }
586         }
587
588         bake_images->size = tot_images;
589 }
590
591 /*
592  * returns the total number of pixels
593  */
594 static size_t initialize_internal_images(BakeImages *bake_images, ReportList *reports)
595 {
596         int i;
597         size_t tot_size = 0;
598
599         for (i = 0; i < bake_images->size; i++) {
600                 ImBuf *ibuf;
601                 void *lock;
602
603                 BakeImage *bk_image = &bake_images->data[i];
604                 ibuf = BKE_image_acquire_ibuf(bk_image->image, NULL, &lock);
605
606                 if (ibuf) {
607                         bk_image->width = ibuf->x;
608                         bk_image->height = ibuf->y;
609                         bk_image->offset = tot_size;
610
611                         tot_size += (size_t)ibuf->x * (size_t)ibuf->y;
612                 }
613                 else {
614                         BKE_image_release_ibuf(bk_image->image, ibuf, lock);
615                         BKE_reportf(reports, RPT_ERROR, "Uninitialized image %s", bk_image->image->id.name + 2);
616                         return 0;
617                 }
618                 BKE_image_release_ibuf(bk_image->image, ibuf, lock);
619         }
620         return tot_size;
621 }
622
623 /* create new mesh with edit mode changes and modifiers applied */
624 static Mesh *bake_mesh_new_from_object(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Object *ob)
625 {
626         if (ob->mode & OB_MODE_EDIT)
627                 ED_object_editmode_load(ob);
628
629         Mesh *me = BKE_mesh_new_from_object(eval_ctx, bmain, scene, ob, 1, 2, 0, 0);
630         BKE_mesh_split_faces(me, true);
631
632         return me;
633 }
634
635 static int bake(
636         Render *re, Main *bmain, Depsgraph *graph, Scene *scene, Object *ob_low, ListBase *selected_objects, ReportList *reports,
637         const ScenePassType pass_type, const int pass_filter, const int margin,
638         const BakeSaveMode save_mode, const bool is_clear, const bool is_split_materials,
639         const bool is_automatic_name, const bool is_selected_to_active, const bool is_cage,
640         const float cage_extrusion, const int normal_space, const BakeNormalSwizzle normal_swizzle[],
641         const char *custom_cage, const char *filepath, const int width, const int height,
642         const char *identifier, ScrArea *sa, const char *uv_layer)
643 {
644         int op_result = OPERATOR_CANCELLED;
645         bool ok = false;
646
647         Object *ob_cage = NULL;
648
649         BakeHighPolyData *highpoly = NULL;
650         int tot_highpoly = 0;
651
652         char restrict_flag_low = ob_low->restrictflag;
653         char restrict_flag_cage = 0;
654
655         Mesh *me_low = NULL;
656         Mesh *me_cage = NULL;
657
658         MultiresModifierData *mmd_low = NULL;
659         int mmd_flags_low = 0;
660
661         float *result = NULL;
662
663         BakePixel *pixel_array_low = NULL;
664         BakePixel *pixel_array_high = NULL;
665
666         const bool is_save_internal = (save_mode == R_BAKE_SAVE_INTERNAL);
667         const bool is_noncolor = is_noncolor_pass(pass_type);
668         const int depth = RE_pass_depth(pass_type);
669
670         BakeImages bake_images = {NULL};
671
672         size_t num_pixels;
673         int tot_materials;
674
675         RE_bake_engine_set_engine_parameters(re, bmain, graph, scene);
676
677         if (!RE_bake_has_engine(re)) {
678                 BKE_report(reports, RPT_ERROR, "Current render engine does not support baking");
679                 goto cleanup;
680         }
681
682         tot_materials = ob_low->totcol;
683
684         if (uv_layer && uv_layer[0] != '\0') {
685                 Mesh *me = (Mesh *)ob_low->data;
686                 if (CustomData_get_named_layer(&me->ldata, CD_MLOOPUV, uv_layer) == -1) {
687                         BKE_reportf(reports, RPT_ERROR,
688                                     "No UV layer named \"%s\" found in the object \"%s\"", uv_layer, ob_low->id.name + 2);
689                         goto cleanup;
690                 }
691         }
692
693         if (tot_materials == 0) {
694                 if (is_save_internal) {
695                         BKE_report(reports, RPT_ERROR,
696                                    "No active image found, add a material or bake to an external file");
697
698                         goto cleanup;
699                 }
700                 else if (is_split_materials) {
701                         BKE_report(reports, RPT_ERROR,
702                                    "No active image found, add a material or bake without the Split Materials option");
703
704                         goto cleanup;
705                 }
706                 else {
707                         /* baking externally without splitting materials */
708                         tot_materials = 1;
709                 }
710         }
711
712         /* we overallocate in case there is more materials than images */
713         bake_images.data = MEM_mallocN(sizeof(BakeImage) * tot_materials, "bake images dimensions (width, height, offset)");
714         bake_images.lookup = MEM_mallocN(sizeof(int) * tot_materials, "bake images lookup (from material to BakeImage)");
715
716         build_image_lookup(bmain, ob_low, &bake_images);
717
718         if (is_save_internal) {
719                 num_pixels = initialize_internal_images(&bake_images, reports);
720
721                 if (num_pixels == 0) {
722                         goto cleanup;
723                 }
724         }
725         else {
726                 /* when saving extenally always use the size specified in the UI */
727
728                 num_pixels = (size_t)width * (size_t)height * bake_images.size;
729
730                 for (int i = 0; i < bake_images.size; i++) {
731                         bake_images.data[i].width = width;
732                         bake_images.data[i].height = height;
733                         bake_images.data[i].offset = (is_split_materials ? num_pixels : 0);
734                         bake_images.data[i].image = NULL;
735                 }
736
737                 if (!is_split_materials) {
738                         /* saving a single image */
739                         for (int i = 0; i < tot_materials; i++) {
740                                 bake_images.lookup[i] = 0;
741                         }
742                 }
743         }
744
745         if (is_selected_to_active) {
746                 CollectionPointerLink *link;
747                 tot_highpoly = 0;
748
749                 for (link = selected_objects->first; link; link = link->next) {
750                         Object *ob_iter = link->ptr.data;
751
752                         if (ob_iter == ob_low)
753                                 continue;
754
755                         tot_highpoly ++;
756                 }
757
758                 if (is_cage && custom_cage[0] != '\0') {
759                         ob_cage = BLI_findstring(&bmain->object, custom_cage, offsetof(ID, name) + 2);
760
761                         if (ob_cage == NULL || ob_cage->type != OB_MESH) {
762                                 BKE_report(reports, RPT_ERROR, "No valid cage object");
763                                 goto cleanup;
764                         }
765                         else {
766                                 restrict_flag_cage = ob_cage->restrictflag;
767                                 ob_cage->restrictflag |= OB_RESTRICT_RENDER;
768                         }
769                 }
770         }
771
772         pixel_array_low = MEM_mallocN(sizeof(BakePixel) * num_pixels, "bake pixels low poly");
773         pixel_array_high = MEM_mallocN(sizeof(BakePixel) * num_pixels, "bake pixels high poly");
774         result = MEM_callocN(sizeof(float) * depth * num_pixels, "bake return pixels");
775
776         /* for multires bake, use linear UV subdivision to match low res UVs */
777         if (pass_type == SCE_PASS_NORMAL && normal_space == R_BAKE_SPACE_TANGENT && !is_selected_to_active) {
778                 mmd_low = (MultiresModifierData *) modifiers_findByType(ob_low, eModifierType_Multires);
779                 if (mmd_low) {
780                         mmd_flags_low = mmd_low->flags;
781                         mmd_low->flags |= eMultiresModifierFlag_PlainUv;
782                 }
783         }
784
785         /* get the mesh as it arrives in the renderer */
786         me_low = bake_mesh_new_from_object(RE_GetEvalCtx(re), bmain, scene, ob_low);
787
788         /* populate the pixel array with the face data */
789         if ((is_selected_to_active && (ob_cage == NULL) && is_cage) == false)
790                 RE_bake_pixels_populate(me_low, pixel_array_low, num_pixels, &bake_images, uv_layer);
791         /* else populate the pixel array with the 'cage' mesh (the smooth version of the mesh)  */
792
793         if (is_selected_to_active) {
794                 CollectionPointerLink *link;
795                 ModifierData *md, *nmd;
796                 ListBase modifiers_tmp, modifiers_original;
797                 int i = 0;
798
799                 /* prepare cage mesh */
800                 if (ob_cage) {
801                         me_cage = bake_mesh_new_from_object(RE_GetEvalCtx(re), bmain, scene, ob_cage);
802                         if ((me_low->totpoly != me_cage->totpoly) || (me_low->totloop != me_cage->totloop)) {
803                                 BKE_report(reports, RPT_ERROR,
804                                            "Invalid cage object, the cage mesh must have the same number "
805                                            "of faces as the active object");
806                                 goto cleanup;
807                         }
808                 }
809                 else if (is_cage) {
810                         modifiers_original = ob_low->modifiers;
811                         BLI_listbase_clear(&modifiers_tmp);
812
813                         for (md = ob_low->modifiers.first; md; md = md->next) {
814                                 /* Edge Split cannot be applied in the cage,
815                                  * the cage is supposed to have interpolated normals
816                                  * between the faces unless the geometry is physically
817                                  * split. So we create a copy of the low poly mesh without
818                                  * the eventual edge split.*/
819
820                                 if (md->type == eModifierType_EdgeSplit)
821                                         continue;
822
823                                 nmd = modifier_new(md->type);
824                                 BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
825                                 modifier_copyData(md, nmd);
826                                 BLI_addtail(&modifiers_tmp, nmd);
827                         }
828
829                         /* temporarily replace the modifiers */
830                         ob_low->modifiers = modifiers_tmp;
831
832                         /* get the cage mesh as it arrives in the renderer */
833                         me_cage = bake_mesh_new_from_object(RE_GetEvalCtx(re), bmain, scene, ob_low);
834                         RE_bake_pixels_populate(me_cage, pixel_array_low, num_pixels, &bake_images, uv_layer);
835                 }
836
837                 highpoly = MEM_callocN(sizeof(BakeHighPolyData) * tot_highpoly, "bake high poly objects");
838
839                 /* populate highpoly array */
840                 for (link = selected_objects->first; link; link = link->next) {
841                         TriangulateModifierData *tmd;
842                         Object *ob_iter = link->ptr.data;
843
844                         if (ob_iter == ob_low)
845                                 continue;
846
847                         /* initialize highpoly_data */
848                         highpoly[i].ob = ob_iter;
849                         highpoly[i].restrict_flag = ob_iter->restrictflag;
850
851                         /* triangulating so BVH returns the primitive_id that will be used for rendering */
852                         highpoly[i].tri_mod = ED_object_modifier_add(
853                                 reports, bmain, scene, highpoly[i].ob,
854                                 "TmpTriangulate", eModifierType_Triangulate);
855                         tmd = (TriangulateModifierData *)highpoly[i].tri_mod;
856                         tmd->quad_method = MOD_TRIANGULATE_QUAD_FIXED;
857                         tmd->ngon_method = MOD_TRIANGULATE_NGON_EARCLIP;
858
859                         highpoly[i].me = bake_mesh_new_from_object(RE_GetEvalCtx(re), bmain, scene, highpoly[i].ob);
860                         highpoly[i].ob->restrictflag &= ~OB_RESTRICT_RENDER;
861
862                         /* lowpoly to highpoly transformation matrix */
863                         copy_m4_m4(highpoly[i].obmat, highpoly[i].ob->obmat);
864                         invert_m4_m4(highpoly[i].imat, highpoly[i].obmat);
865
866                         highpoly[i].is_flip_object = is_negative_m4(highpoly[i].ob->obmat);
867
868                         i++;
869                 }
870
871                 BLI_assert(i == tot_highpoly);
872
873                 ob_low->restrictflag |= OB_RESTRICT_RENDER;
874
875                 /* populate the pixel arrays with the corresponding face data for each high poly object */
876                 if (!RE_bake_pixels_populate_from_objects(
877                             me_low, pixel_array_low, pixel_array_high, highpoly, tot_highpoly, num_pixels, ob_cage != NULL,
878                             cage_extrusion, ob_low->obmat, (ob_cage ? ob_cage->obmat : ob_low->obmat), me_cage))
879                 {
880                         BKE_report(reports, RPT_ERROR, "Error handling selected objects");
881                         goto cage_cleanup;
882                 }
883
884                 /* the baking itself */
885                 for (i = 0; i < tot_highpoly; i++) {
886                         ok = RE_bake_engine(re, highpoly[i].ob, i, pixel_array_high,
887                                             num_pixels, depth, pass_type, pass_filter, result);
888                         if (!ok) {
889                                 BKE_reportf(reports, RPT_ERROR, "Error baking from object \"%s\"", highpoly[i].ob->id.name + 2);
890                                 goto cage_cleanup;
891                         }
892                 }
893
894 cage_cleanup:
895                 /* reverting data back */
896                 if ((ob_cage == NULL) && is_cage) {
897                         ob_low->modifiers = modifiers_original;
898
899                         while ((md = BLI_pophead(&modifiers_tmp))) {
900                                 modifier_free(md);
901                         }
902                 }
903
904                 if (!ok) {
905                         goto cleanup;
906                 }
907         }
908         else {
909                 /* make sure low poly renders */
910                 ob_low->restrictflag &= ~OB_RESTRICT_RENDER;
911
912                 if (RE_bake_has_engine(re)) {
913                         ok = RE_bake_engine(re, ob_low, 0, pixel_array_low, num_pixels, depth, pass_type, pass_filter, result);
914                 }
915                 else {
916                         BKE_report(reports, RPT_ERROR, "Current render engine does not support baking");
917                         goto cleanup;
918                 }
919         }
920
921         /* normal space conversion
922          * the normals are expected to be in world space, +X +Y +Z */
923         if (ok && pass_type == SCE_PASS_NORMAL) {
924                 switch (normal_space) {
925                         case R_BAKE_SPACE_WORLD:
926                         {
927                                 /* Cycles internal format */
928                                 if ((normal_swizzle[0] == R_BAKE_POSX) &&
929                                     (normal_swizzle[1] == R_BAKE_POSY) &&
930                                     (normal_swizzle[2] == R_BAKE_POSZ))
931                                 {
932                                         break;
933                                 }
934                                 else {
935                                         RE_bake_normal_world_to_world(pixel_array_low, num_pixels,  depth, result, normal_swizzle);
936                                 }
937                                 break;
938                         }
939                         case R_BAKE_SPACE_OBJECT:
940                         {
941                                 RE_bake_normal_world_to_object(pixel_array_low, num_pixels, depth, result, ob_low, normal_swizzle);
942                                 break;
943                         }
944                         case R_BAKE_SPACE_TANGENT:
945                         {
946                                 if (is_selected_to_active) {
947                                         RE_bake_normal_world_to_tangent(pixel_array_low, num_pixels, depth, result, me_low, normal_swizzle, ob_low->obmat);
948                                 }
949                                 else {
950                                         /* from multiresolution */
951                                         Mesh *me_nores = NULL;
952                                         ModifierData *md = NULL;
953                                         int mode;
954
955                                         md = modifiers_findByType(ob_low, eModifierType_Multires);
956
957                                         if (md) {
958                                                 mode = md->mode;
959                                                 md->mode &= ~eModifierMode_Render;
960                                         }
961
962                                         me_nores = bake_mesh_new_from_object(RE_GetEvalCtx(re), bmain, scene, ob_low);
963                                         RE_bake_pixels_populate(me_nores, pixel_array_low, num_pixels, &bake_images, uv_layer);
964
965                                         RE_bake_normal_world_to_tangent(pixel_array_low, num_pixels, depth, result, me_nores, normal_swizzle, ob_low->obmat);
966                                         BKE_libblock_free(bmain, me_nores);
967
968                                         if (md)
969                                                 md->mode = mode;
970                                 }
971                                 break;
972                         }
973                         default:
974                                 break;
975                 }
976         }
977
978         if (!ok) {
979                 BKE_reportf(reports, RPT_ERROR, "Problem baking object \"%s\"", ob_low->id.name + 2);
980                 op_result = OPERATOR_CANCELLED;
981         }
982         else {
983                 /* save the results */
984                 for (int i = 0; i < bake_images.size; i++) {
985                         BakeImage *bk_image = &bake_images.data[i];
986
987                         if (is_save_internal) {
988                                 ok = write_internal_bake_pixels(
989                                          bk_image->image,
990                                          pixel_array_low + bk_image->offset,
991                                          result + bk_image->offset * depth,
992                                          bk_image->width, bk_image->height,
993                                          margin, is_clear, is_noncolor);
994
995                                 /* might be read by UI to set active image for display */
996                                 bake_update_image(sa, bk_image->image);
997
998                                 if (!ok) {
999                                         BKE_reportf(reports, RPT_ERROR,
1000                                                    "Problem saving the bake map internally for object \"%s\"", ob_low->id.name + 2);
1001                                         op_result = OPERATOR_CANCELLED;
1002                                 }
1003                                 else {
1004                                         BKE_report(reports, RPT_INFO,
1005                                                    "Baking map saved to internal image, save it externally or pack it");
1006                                         op_result = OPERATOR_FINISHED;
1007                                 }
1008                         }
1009                         /* save externally */
1010                         else {
1011                                 BakeData *bake = &scene->r.bake;
1012                                 char name[FILE_MAX];
1013
1014                                 BKE_image_path_from_imtype(name, filepath, bmain->name, 0, bake->im_format.imtype, true, false, NULL);
1015
1016                                 if (is_automatic_name) {
1017                                         BLI_path_suffix(name, FILE_MAX, ob_low->id.name + 2, "_");
1018                                         BLI_path_suffix(name, FILE_MAX, identifier, "_");
1019                                 }
1020
1021                                 if (is_split_materials) {
1022                                         if (bk_image->image) {
1023                                                 BLI_path_suffix(name, FILE_MAX, bk_image->image->id.name + 2, "_");
1024                                         }
1025                                         else {
1026                                                 if (ob_low->mat[i]) {
1027                                                         BLI_path_suffix(name, FILE_MAX, ob_low->mat[i]->id.name + 2, "_");
1028                                                 }
1029                                                 else if (me_low->mat[i]) {
1030                                                         BLI_path_suffix(name, FILE_MAX, me_low->mat[i]->id.name + 2, "_");
1031                                                 }
1032                                                 else {
1033                                                         /* if everything else fails, use the material index */
1034                                                         char tmp[5];
1035                                                         sprintf(tmp, "%d", i % 1000);
1036                                                         BLI_path_suffix(name, FILE_MAX, tmp, "_");
1037                                                 }
1038                                         }
1039                                 }
1040
1041                                 /* save it externally */
1042                                 ok = write_external_bake_pixels(
1043                                         name,
1044                                         pixel_array_low + bk_image->offset,
1045                                         result + bk_image->offset * depth,
1046                                         bk_image->width, bk_image->height,
1047                                         margin, &bake->im_format, is_noncolor);
1048
1049                                 if (!ok) {
1050                                         BKE_reportf(reports, RPT_ERROR, "Problem saving baked map in \"%s\"", name);
1051                                         op_result = OPERATOR_CANCELLED;
1052                                 }
1053                                 else {
1054                                         BKE_reportf(reports, RPT_INFO, "Baking map written to \"%s\"", name);
1055                                         op_result = OPERATOR_FINISHED;
1056                                 }
1057
1058                                 if (!is_split_materials) {
1059                                         break;
1060                                 }
1061                         }
1062                 }
1063         }
1064
1065         if (is_save_internal)
1066                 refresh_images(&bake_images);
1067
1068 cleanup:
1069
1070         if (highpoly) {
1071                 int i;
1072                 for (i = 0; i < tot_highpoly; i++) {
1073                         highpoly[i].ob->restrictflag = highpoly[i].restrict_flag;
1074
1075                         if (highpoly[i].tri_mod)
1076                                 ED_object_modifier_remove(reports, bmain, highpoly[i].ob, highpoly[i].tri_mod);
1077
1078                         if (highpoly[i].me)
1079                                 BKE_libblock_free(bmain, highpoly[i].me);
1080                 }
1081                 MEM_freeN(highpoly);
1082         }
1083
1084         ob_low->restrictflag = restrict_flag_low;
1085
1086         if (mmd_low)
1087                 mmd_low->flags = mmd_flags_low;
1088
1089         if (ob_cage)
1090                 ob_cage->restrictflag = restrict_flag_cage;
1091
1092         if (pixel_array_low)
1093                 MEM_freeN(pixel_array_low);
1094
1095         if (pixel_array_high)
1096                 MEM_freeN(pixel_array_high);
1097
1098         if (bake_images.data)
1099                 MEM_freeN(bake_images.data);
1100
1101         if (bake_images.lookup)
1102                 MEM_freeN(bake_images.lookup);
1103
1104         if (result)
1105                 MEM_freeN(result);
1106
1107         if (me_low)
1108                 BKE_libblock_free(bmain, me_low);
1109
1110         if (me_cage)
1111                 BKE_libblock_free(bmain, me_cage);
1112
1113         return op_result;
1114 }
1115
1116 static void bake_init_api_data(wmOperator *op, bContext *C, BakeAPIRender *bkr)
1117 {
1118         bool is_save_internal;
1119         bScreen *sc = CTX_wm_screen(C);
1120
1121         bkr->ob = CTX_data_active_object(C);
1122         bkr->main = CTX_data_main(C);
1123         bkr->depsgraph = CTX_data_depsgraph(C);
1124         bkr->scene = CTX_data_scene(C);
1125         bkr->sa = sc ? BKE_screen_find_big_area(sc, SPACE_IMAGE, 10) : NULL;
1126
1127         bkr->pass_type = RNA_enum_get(op->ptr, "type");
1128         bkr->pass_filter = RNA_enum_get(op->ptr, "pass_filter");
1129         bkr->margin = RNA_int_get(op->ptr, "margin");
1130
1131         bkr->save_mode = RNA_enum_get(op->ptr, "save_mode");
1132         is_save_internal = (bkr->save_mode == R_BAKE_SAVE_INTERNAL);
1133
1134         bkr->is_clear = RNA_boolean_get(op->ptr, "use_clear");
1135         bkr->is_split_materials = (!is_save_internal) && RNA_boolean_get(op->ptr, "use_split_materials");
1136         bkr->is_automatic_name = RNA_boolean_get(op->ptr, "use_automatic_name");
1137         bkr->is_selected_to_active = RNA_boolean_get(op->ptr, "use_selected_to_active");
1138         bkr->is_cage = RNA_boolean_get(op->ptr, "use_cage");
1139         bkr->cage_extrusion = RNA_float_get(op->ptr, "cage_extrusion");
1140
1141         bkr->normal_space = RNA_enum_get(op->ptr, "normal_space");
1142         bkr->normal_swizzle[0] = RNA_enum_get(op->ptr, "normal_r");
1143         bkr->normal_swizzle[1] = RNA_enum_get(op->ptr, "normal_g");
1144         bkr->normal_swizzle[2] = RNA_enum_get(op->ptr, "normal_b");
1145
1146         bkr->width = RNA_int_get(op->ptr, "width");
1147         bkr->height = RNA_int_get(op->ptr, "height");
1148         bkr->identifier = "";
1149
1150         RNA_string_get(op->ptr, "uv_layer", bkr->uv_layer);
1151
1152         RNA_string_get(op->ptr, "cage_object", bkr->custom_cage);
1153
1154         if ((!is_save_internal) && bkr->is_automatic_name) {
1155                 PropertyRNA *prop = RNA_struct_find_property(op->ptr, "type");
1156                 RNA_property_enum_identifier(C, op->ptr, prop, bkr->pass_type, &bkr->identifier);
1157         }
1158
1159         CTX_data_selected_objects(C, &bkr->selected_objects);
1160
1161         bkr->reports = op->reports;
1162
1163         bkr->result = OPERATOR_CANCELLED;
1164
1165         bkr->render = RE_NewRender(bkr->scene->id.name);
1166
1167         /* XXX hack to force saving to always be internal. Whether (and how) to support
1168          * external saving will be addressed later */
1169         bkr->save_mode = R_BAKE_SAVE_INTERNAL;
1170 }
1171
1172 static int bake_exec(bContext *C, wmOperator *op)
1173 {
1174         Render *re;
1175         int result = OPERATOR_CANCELLED;
1176         BakeAPIRender bkr = {NULL};
1177         Scene *scene = CTX_data_scene(C);
1178
1179         G.is_break = false;
1180         G.is_rendering = true;
1181
1182         bake_set_props(op, scene);
1183
1184         bake_init_api_data(op, C, &bkr);
1185         re = bkr.render;
1186
1187         /* setup new render */
1188         RE_test_break_cb(re, NULL, bake_break);
1189
1190         if (!bake_pass_filter_check(bkr.pass_type, bkr.pass_filter, bkr.reports)) {
1191                 goto finally;
1192         }
1193
1194         if (!bake_objects_check(bkr.main, bkr.scene, bkr.ob, &bkr.selected_objects, bkr.reports, bkr.is_selected_to_active)) {
1195                 goto finally;
1196         }
1197
1198         if (bkr.is_clear) {
1199                 const bool is_tangent = ((bkr.pass_type == SCE_PASS_NORMAL) && (bkr.normal_space == R_BAKE_SPACE_TANGENT));
1200                 bake_images_clear(bkr.main, is_tangent);
1201         }
1202
1203         RE_SetReports(re, bkr.reports);
1204
1205         if (bkr.is_selected_to_active) {
1206                 result = bake(
1207                         bkr.render, bkr.main, bkr.depsgraph, bkr.scene, bkr.ob, &bkr.selected_objects, bkr.reports,
1208                         bkr.pass_type, bkr.pass_filter, bkr.margin, bkr.save_mode,
1209                         bkr.is_clear, bkr.is_split_materials, bkr.is_automatic_name, true, bkr.is_cage,
1210                         bkr.cage_extrusion, bkr.normal_space, bkr.normal_swizzle,
1211                         bkr.custom_cage, bkr.filepath, bkr.width, bkr.height, bkr.identifier, bkr.sa,
1212                         bkr.uv_layer);
1213         }
1214         else {
1215                 CollectionPointerLink *link;
1216                 const bool is_clear = bkr.is_clear && BLI_listbase_is_single(&bkr.selected_objects);
1217                 for (link = bkr.selected_objects.first; link; link = link->next) {
1218                         Object *ob_iter = link->ptr.data;
1219                         result = bake(
1220                                 bkr.render, bkr.main, bkr.depsgraph, bkr.scene, ob_iter, NULL, bkr.reports,
1221                                 bkr.pass_type, bkr.pass_filter, bkr.margin, bkr.save_mode,
1222                                 is_clear, bkr.is_split_materials, bkr.is_automatic_name, false, bkr.is_cage,
1223                                 bkr.cage_extrusion, bkr.normal_space, bkr.normal_swizzle,
1224                                 bkr.custom_cage, bkr.filepath, bkr.width, bkr.height, bkr.identifier, bkr.sa,
1225                                 bkr.uv_layer);
1226                 }
1227         }
1228
1229         RE_SetReports(re, NULL);
1230
1231
1232 finally:
1233         G.is_rendering = false;
1234         BLI_freelistN(&bkr.selected_objects);
1235         return result;
1236 }
1237
1238 static void bake_startjob(void *bkv, short *UNUSED(stop), short *do_update, float *progress)
1239 {
1240         BakeAPIRender *bkr = (BakeAPIRender *)bkv;
1241
1242         /* setup new render */
1243         bkr->do_update = do_update;
1244         bkr->progress = progress;
1245
1246         RE_SetReports(bkr->render, bkr->reports);
1247
1248         if (!bake_pass_filter_check(bkr->pass_type, bkr->pass_filter, bkr->reports)) {
1249                 bkr->result = OPERATOR_CANCELLED;
1250                 return;
1251         }
1252
1253         if (!bake_objects_check(bkr->main, bkr->scene, bkr->ob, &bkr->selected_objects, bkr->reports, bkr->is_selected_to_active)) {
1254                 bkr->result = OPERATOR_CANCELLED;
1255                 return;
1256         }
1257
1258         if (bkr->is_clear) {
1259                 const bool is_tangent = ((bkr->pass_type == SCE_PASS_NORMAL) && (bkr->normal_space == R_BAKE_SPACE_TANGENT));
1260                 bake_images_clear(bkr->main, is_tangent);
1261         }
1262
1263         if (bkr->is_selected_to_active) {
1264                 bkr->result = bake(
1265                         bkr->render, bkr->main, bkr->depsgraph, bkr->scene, bkr->ob, &bkr->selected_objects, bkr->reports,
1266                         bkr->pass_type, bkr->pass_filter, bkr->margin, bkr->save_mode,
1267                         bkr->is_clear, bkr->is_split_materials, bkr->is_automatic_name, true, bkr->is_cage,
1268                         bkr->cage_extrusion, bkr->normal_space, bkr->normal_swizzle,
1269                         bkr->custom_cage, bkr->filepath, bkr->width, bkr->height, bkr->identifier, bkr->sa,
1270                         bkr->uv_layer);
1271         }
1272         else {
1273                 CollectionPointerLink *link;
1274                 const bool is_clear = bkr->is_clear && BLI_listbase_is_single(&bkr->selected_objects);
1275                 for (link = bkr->selected_objects.first; link; link = link->next) {
1276                         Object *ob_iter = link->ptr.data;
1277                         bkr->result = bake(
1278                                 bkr->render, bkr->main, bkr->depsgraph, bkr->scene, ob_iter, NULL, bkr->reports,
1279                                 bkr->pass_type, bkr->pass_filter, bkr->margin, bkr->save_mode,
1280                                 is_clear, bkr->is_split_materials, bkr->is_automatic_name, false, bkr->is_cage,
1281                                 bkr->cage_extrusion, bkr->normal_space, bkr->normal_swizzle,
1282                                 bkr->custom_cage, bkr->filepath, bkr->width, bkr->height, bkr->identifier, bkr->sa,
1283                                 bkr->uv_layer);
1284
1285                         if (bkr->result == OPERATOR_CANCELLED)
1286                                 return;
1287                 }
1288         }
1289
1290         RE_SetReports(bkr->render, NULL);
1291 }
1292
1293 static void bake_freejob(void *bkv)
1294 {
1295         BakeAPIRender *bkr = (BakeAPIRender *)bkv;
1296
1297         BLI_freelistN(&bkr->selected_objects);
1298         MEM_freeN(bkr);
1299
1300         G.is_rendering = false;
1301 }
1302
1303 static void bake_set_props(wmOperator *op, Scene *scene)
1304 {
1305         PropertyRNA *prop;
1306         BakeData *bake = &scene->r.bake;
1307
1308         prop = RNA_struct_find_property(op->ptr, "filepath");
1309         if (!RNA_property_is_set(op->ptr, prop)) {
1310                 RNA_property_string_set(op->ptr, prop, bake->filepath);
1311         }
1312
1313         prop =  RNA_struct_find_property(op->ptr, "width");
1314         if (!RNA_property_is_set(op->ptr, prop)) {
1315                 RNA_property_int_set(op->ptr, prop, bake->width);
1316         }
1317
1318         prop =  RNA_struct_find_property(op->ptr, "height");
1319         if (!RNA_property_is_set(op->ptr, prop)) {
1320                 RNA_property_int_set(op->ptr, prop, bake->width);
1321         }
1322
1323         prop = RNA_struct_find_property(op->ptr, "margin");
1324         if (!RNA_property_is_set(op->ptr, prop)) {
1325                 RNA_property_int_set(op->ptr, prop, bake->margin);
1326         }
1327
1328         prop = RNA_struct_find_property(op->ptr, "use_selected_to_active");
1329         if (!RNA_property_is_set(op->ptr, prop)) {
1330                 RNA_property_boolean_set(op->ptr, prop, (bake->flag & R_BAKE_TO_ACTIVE) != 0);
1331         }
1332
1333         prop = RNA_struct_find_property(op->ptr, "cage_extrusion");
1334         if (!RNA_property_is_set(op->ptr, prop)) {
1335                 RNA_property_float_set(op->ptr, prop, bake->cage_extrusion);
1336         }
1337
1338         prop = RNA_struct_find_property(op->ptr, "cage_object");
1339         if (!RNA_property_is_set(op->ptr, prop)) {
1340                 RNA_property_string_set(op->ptr, prop, bake->cage);
1341         }
1342
1343         prop = RNA_struct_find_property(op->ptr, "normal_space");
1344         if (!RNA_property_is_set(op->ptr, prop)) {
1345                 RNA_property_enum_set(op->ptr, prop, bake->normal_space);
1346         }
1347
1348         prop = RNA_struct_find_property(op->ptr, "normal_r");
1349         if (!RNA_property_is_set(op->ptr, prop)) {
1350                 RNA_property_enum_set(op->ptr, prop, bake->normal_swizzle[0]);
1351         }
1352
1353         prop = RNA_struct_find_property(op->ptr, "normal_g");
1354         if (!RNA_property_is_set(op->ptr, prop)) {
1355                 RNA_property_enum_set(op->ptr, prop, bake->normal_swizzle[1]);
1356         }
1357
1358         prop = RNA_struct_find_property(op->ptr, "normal_b");
1359         if (!RNA_property_is_set(op->ptr, prop)) {
1360                 RNA_property_enum_set(op->ptr, prop, bake->normal_swizzle[2]);
1361         }
1362
1363         prop = RNA_struct_find_property(op->ptr, "save_mode");
1364         if (!RNA_property_is_set(op->ptr, prop)) {
1365                 RNA_property_enum_set(op->ptr, prop, bake->save_mode);
1366         }
1367
1368         prop = RNA_struct_find_property(op->ptr, "use_clear");
1369         if (!RNA_property_is_set(op->ptr, prop)) {
1370                 RNA_property_boolean_set(op->ptr, prop, (bake->flag & R_BAKE_CLEAR) != 0);
1371         }
1372
1373         prop = RNA_struct_find_property(op->ptr, "use_cage");
1374         if (!RNA_property_is_set(op->ptr, prop)) {
1375                 RNA_property_boolean_set(op->ptr, prop, (bake->flag & R_BAKE_CAGE) != 0);
1376         }
1377
1378         prop = RNA_struct_find_property(op->ptr, "use_split_materials");
1379         if (!RNA_property_is_set(op->ptr, prop)) {
1380                 RNA_property_boolean_set(op->ptr, prop, (bake->flag & R_BAKE_SPLIT_MAT) != 0);
1381         }
1382
1383         prop = RNA_struct_find_property(op->ptr, "use_automatic_name");
1384         if (!RNA_property_is_set(op->ptr, prop)) {
1385                 RNA_property_boolean_set(op->ptr, prop, (bake->flag & R_BAKE_AUTO_NAME) != 0);
1386         }
1387
1388         prop = RNA_struct_find_property(op->ptr, "pass_filter");
1389         if (!RNA_property_is_set(op->ptr, prop)) {
1390                 RNA_property_enum_set(op->ptr, prop, bake->pass_filter);
1391         }
1392 }
1393
1394 static int bake_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
1395 {
1396         wmJob *wm_job;
1397         BakeAPIRender *bkr;
1398         Render *re;
1399         Scene *scene = CTX_data_scene(C);
1400
1401         bake_set_props(op, scene);
1402
1403         /* only one render job at a time */
1404         if (WM_jobs_test(CTX_wm_manager(C), scene, WM_JOB_TYPE_OBJECT_BAKE))
1405                 return OPERATOR_CANCELLED;
1406
1407         bkr = MEM_mallocN(sizeof(BakeAPIRender), "render bake");
1408
1409         /* init bake render */
1410         bake_init_api_data(op, C, bkr);
1411         re = bkr->render;
1412
1413         /* setup new render */
1414         RE_test_break_cb(re, NULL, bake_break);
1415         RE_progress_cb(re, bkr, bake_progress_update);
1416
1417         /* setup job */
1418         wm_job = WM_jobs_get(CTX_wm_manager(C), CTX_wm_window(C), scene, "Texture Bake",
1419                              WM_JOB_EXCL_RENDER | WM_JOB_PRIORITY | WM_JOB_PROGRESS, WM_JOB_TYPE_OBJECT_BAKE);
1420         WM_jobs_customdata_set(wm_job, bkr, bake_freejob);
1421         WM_jobs_timer(wm_job, 0.5, NC_IMAGE, 0); /* TODO - only draw bake image, can we enforce this */
1422         WM_jobs_callbacks(wm_job, bake_startjob, NULL, NULL, NULL);
1423
1424         G.is_break = false;
1425         G.is_rendering = true;
1426
1427         WM_jobs_start(CTX_wm_manager(C), wm_job);
1428
1429         WM_cursor_wait(0);
1430
1431         /* add modal handler for ESC */
1432         WM_event_add_modal_handler(C, op);
1433
1434         WM_event_add_notifier(C, NC_SCENE | ND_RENDER_RESULT, scene);
1435         return OPERATOR_RUNNING_MODAL;
1436 }
1437
1438 void OBJECT_OT_bake(wmOperatorType *ot)
1439 {
1440         PropertyRNA *prop;
1441
1442         /* identifiers */
1443         ot->name = "Bake";
1444         ot->description = "Bake image textures of selected objects";
1445         ot->idname = "OBJECT_OT_bake";
1446
1447         /* api callbacks */
1448         ot->exec = bake_exec;
1449         ot->modal = bake_modal;
1450         ot->invoke = bake_invoke;
1451         ot->poll = ED_operator_object_active_editable_mesh;
1452
1453         RNA_def_enum(ot->srna, "type", rna_enum_bake_pass_type_items, SCE_PASS_COMBINED, "Type",
1454                      "Type of pass to bake, some of them may not be supported by the current render engine");
1455         prop = RNA_def_enum(ot->srna, "pass_filter", rna_enum_bake_pass_filter_type_items, R_BAKE_PASS_FILTER_NONE, "Pass Filter",
1456                      "Filter to combined, diffuse, glossy, transmission and subsurface passes");
1457         RNA_def_property_flag(prop, PROP_ENUM_FLAG);
1458         RNA_def_string_file_path(ot->srna, "filepath", NULL, FILE_MAX, "File Path",
1459                                  "Image filepath to use when saving externally");
1460         RNA_def_int(ot->srna, "width", 512, 1, INT_MAX, "Width",
1461                     "Horizontal dimension of the baking map (external only)", 64, 4096);
1462         RNA_def_int(ot->srna, "height", 512, 1, INT_MAX, "Height",
1463                     "Vertical dimension of the baking map (external only)", 64, 4096);
1464         RNA_def_int(ot->srna, "margin", 16, 0, INT_MAX, "Margin",
1465                     "Extends the baked result as a post process filter", 0, 64);
1466         RNA_def_boolean(ot->srna, "use_selected_to_active", false, "Selected to Active",
1467                         "Bake shading on the surface of selected objects to the active object");
1468         RNA_def_float(ot->srna, "cage_extrusion", 0.0f, 0.0f, FLT_MAX, "Cage Extrusion",
1469                       "Distance to use for the inward ray cast when using selected to active", 0.0f, 1.0f);
1470         RNA_def_string(ot->srna, "cage_object", NULL, MAX_NAME, "Cage Object",
1471                        "Object to use as cage, instead of calculating the cage from the active object with cage extrusion");
1472         RNA_def_enum(ot->srna, "normal_space", rna_enum_normal_space_items, R_BAKE_SPACE_TANGENT, "Normal Space",
1473                      "Choose normal space for baking");
1474         RNA_def_enum(ot->srna, "normal_r", rna_enum_normal_swizzle_items, R_BAKE_POSX, "R", "Axis to bake in red channel");
1475         RNA_def_enum(ot->srna, "normal_g", rna_enum_normal_swizzle_items, R_BAKE_POSY, "G", "Axis to bake in green channel");
1476         RNA_def_enum(ot->srna, "normal_b", rna_enum_normal_swizzle_items, R_BAKE_POSZ, "B", "Axis to bake in blue channel");
1477         RNA_def_enum(ot->srna, "save_mode", rna_enum_bake_save_mode_items, R_BAKE_SAVE_INTERNAL, "Save Mode",
1478                      "Choose how to save the baking map");
1479         RNA_def_boolean(ot->srna, "use_clear", false, "Clear",
1480                         "Clear Images before baking (only for internal saving)");
1481         RNA_def_boolean(ot->srna, "use_cage", false, "Cage",
1482                         "Cast rays to active object from a cage");
1483         RNA_def_boolean(ot->srna, "use_split_materials", false, "Split Materials",
1484                         "Split baked maps per material, using material name in output file (external only)");
1485         RNA_def_boolean(ot->srna, "use_automatic_name", false, "Automatic Name",
1486                         "Automatically name the output file with the pass type");
1487         RNA_def_string(ot->srna, "uv_layer", NULL, MAX_CUSTOMDATA_LAYER_NAME, "UV Layer", "UV layer to override active");
1488 }