doxygen: add newline after \file
[blender.git] / source / blender / blenkernel / intern / studiolight.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2006-2007 Blender Foundation.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24 #include "BKE_studiolight.h"
25
26 #include "BKE_appdir.h"
27 #include "BKE_icons.h"
28
29 #include "BLI_dynstr.h"
30 #include "BLI_fileops.h"
31 #include "BLI_fileops_types.h"
32 #include "BLI_listbase.h"
33 #include "BLI_linklist.h"
34 #include "BLI_math.h"
35 #include "BLI_math_color.h"
36 #include "BLI_path_util.h"
37 #include "BLI_string.h"
38 #include "BLI_string_utils.h"
39
40 #include "DNA_listBase.h"
41
42 #include "IMB_imbuf.h"
43 #include "IMB_imbuf_types.h"
44
45 #include "GPU_texture.h"
46
47 #include "MEM_guardedalloc.h"
48
49
50 /* Statics */
51 static ListBase studiolights;
52 static int last_studiolight_id = 0;
53 #define STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE 96
54 #define STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT 32
55 #define STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH (STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT * 2)
56
57 /*
58  * The method to calculate the irradiance buffers
59  * The irradiance buffer is only shown in the background when in LookDev.
60  *
61  * STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE is very slow, but very accurate
62  * STUDIOLIGHT_IRRADIANCE_METHOD_SPHERICAL_HARMONICS is faster but has artifacts
63  * Cannot have both enabled at the same time!!!
64  */
65 // #define STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
66 #define STUDIOLIGHT_IRRADIANCE_METHOD_SPHERICAL_HARMONICS
67
68 /* Temporarily disabled due to the creation of textures with -nan(ind)s */
69 #define STUDIOLIGHT_SH_WINDOWING 0.0f /* 0.0 is disabled */
70
71 /*
72  * Disable this option so caches are not loaded from disk
73  * Do not checkin with this commented out
74  */
75 #define STUDIOLIGHT_LOAD_CACHED_FILES
76
77 static const char *STUDIOLIGHT_LIGHTS_FOLDER = "studiolights/studio/";
78 static const char *STUDIOLIGHT_WORLD_FOLDER = "studiolights/world/";
79 static const char *STUDIOLIGHT_MATCAP_FOLDER = "studiolights/matcap/";
80
81 static const char *STUDIOLIGHT_WORLD_DEFAULT = "forest.exr";
82 static const char *STUDIOLIGHT_MATCAP_DEFAULT = "basic_1.exr";
83
84 /* ITER MACRO */
85
86 /** Iter on all pixel giving texel center position and pixel pointer.
87  * Arguments
88  *   type : type of src.
89  *   src : source buffer.
90  *   channels : number of channels per pixel.
91  *
92  * Others
93  *   x, y : normalized UV coordinate [0..1] of the current pixel center.
94  *   texel_size[2] : UV size of a pixel in this texture.
95  *   pixel[] : pointer to the current pixel.
96  */
97 #define ITER_PIXELS(type, src, channels, width, height)                                \
98 {                                                                                      \
99         float texel_size[2];                                                               \
100         texel_size[0] = 1.0f / width;                                                      \
101         texel_size[1] = 1.0f / height;                                                     \
102         type (*pixel_)[channels] = (type (*)[channels])src;                                \
103         for (float y = 0.5 * texel_size[1]; y < 1.0; y += texel_size[1]) {                 \
104                 for (float x = 0.5 * texel_size[0]; x < 1.0; x += texel_size[0], pixel_++) {   \
105                         type *pixel = *pixel_;
106
107 #define ITER_PIXELS_END                                                              \
108                 }                                                                            \
109         }                                                                                \
110 } ((void)0)
111
112 /* FUNCTIONS */
113 #define IMB_SAFE_FREE(p) do { \
114 if (p) {                      \
115         IMB_freeImBuf(p);         \
116         p = NULL;                 \
117 }                             \
118 } while (0)
119
120 #define GPU_TEXTURE_SAFE_FREE(p) do { \
121 if (p) {                              \
122         GPU_texture_free(p);              \
123         p = NULL;                         \
124 }                                     \
125 } while (0)
126
127 static void studiolight_free(struct StudioLight *sl)
128 {
129 #define STUDIOLIGHT_DELETE_ICON(s) {  \
130         if (s != 0) {                          \
131                 BKE_icon_delete(s);           \
132                 s = 0;                        \
133         }                                 \
134 }
135         if (sl->free_function) {
136                 sl->free_function(sl, sl->free_function_data);
137         }
138         STUDIOLIGHT_DELETE_ICON(sl->icon_id_radiance);
139         STUDIOLIGHT_DELETE_ICON(sl->icon_id_irradiance);
140         STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap);
141         STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap_flipped);
142 #undef STUDIOLIGHT_DELETE_ICON
143
144         for (int index = 0; index < 6; index++) {
145                 IMB_SAFE_FREE(sl->radiance_cubemap_buffers[index]);
146         }
147         GPU_TEXTURE_SAFE_FREE(sl->equirect_radiance_gputexture);
148         GPU_TEXTURE_SAFE_FREE(sl->equirect_irradiance_gputexture);
149         IMB_SAFE_FREE(sl->equirect_radiance_buffer);
150         IMB_SAFE_FREE(sl->equirect_irradiance_buffer);
151         MEM_SAFE_FREE(sl->path_irr_cache);
152         MEM_SAFE_FREE(sl->path_sh_cache);
153         MEM_SAFE_FREE(sl);
154 }
155
156 static struct StudioLight *studiolight_create(int flag)
157 {
158         struct StudioLight *sl = MEM_callocN(sizeof(*sl), __func__);
159         sl->path[0] = 0x00;
160         sl->name[0] = 0x00;
161         sl->path_irr_cache = NULL;
162         sl->path_sh_cache = NULL;
163         sl->free_function = NULL;
164         sl->flag = flag;
165         sl->index = ++last_studiolight_id;
166         if (flag & STUDIOLIGHT_TYPE_STUDIO) {
167                 sl->icon_id_irradiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE);
168         }
169         else if (flag & STUDIOLIGHT_TYPE_MATCAP) {
170                 sl->icon_id_matcap = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP);
171                 sl->icon_id_matcap_flipped = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED);
172         }
173         else {
174                 sl->icon_id_radiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_RADIANCE);
175         }
176
177         for (int index = 0; index < 6; index++) {
178                 sl->radiance_cubemap_buffers[index] = NULL;
179         }
180
181         return sl;
182 }
183
184 #define STUDIOLIGHT_FILE_VERSION 1
185
186 #define READ_VAL(type, parser, id, val, lines) do { \
187         for (LinkNode *line = lines; line; line = line->next) { \
188                 char *val_str, *str = line->link; \
189                 if ((val_str = strstr(str, id " "))) { \
190                         val_str += sizeof(id); /* Skip id + spacer. */ \
191                         val = parser(val_str); \
192                 } \
193         } \
194 } while (0)
195
196 #define READ_FVAL(id, val, lines) READ_VAL(float, atof, id, val, lines)
197 #define READ_IVAL(id, val, lines) READ_VAL(int, atoi, id, val, lines)
198
199 #define READ_VEC3(id, val, lines) do { \
200         READ_FVAL(id ".x", val[0], lines); \
201         READ_FVAL(id ".y", val[1], lines); \
202         READ_FVAL(id ".z", val[2], lines); \
203 } while (0)
204
205 #define READ_SOLIDLIGHT(sl, i, lines) do { \
206         READ_IVAL("light[" STRINGIFY(i) "].flag", sl[i].flag, lines); \
207         READ_FVAL("light[" STRINGIFY(i) "].smooth", sl[i].smooth, lines); \
208         READ_VEC3("light[" STRINGIFY(i) "].col", sl[i].col, lines); \
209         READ_VEC3("light[" STRINGIFY(i) "].spec", sl[i].spec, lines); \
210         READ_VEC3("light[" STRINGIFY(i) "].vec", sl[i].vec, lines); \
211 } while (0)
212
213 static void studiolight_load_solid_light(StudioLight *sl)
214 {
215         LinkNode *lines = BLI_file_read_as_lines(sl->path);
216         if (lines) {
217                 READ_VEC3("light_ambient", sl->light_ambient, lines);
218                 READ_SOLIDLIGHT(sl->light, 0, lines);
219                 READ_SOLIDLIGHT(sl->light, 1, lines);
220                 READ_SOLIDLIGHT(sl->light, 2, lines);
221                 READ_SOLIDLIGHT(sl->light, 3, lines);
222         }
223         BLI_file_free_lines(lines);
224 }
225
226 #undef READ_SOLIDLIGHT
227 #undef READ_VEC3
228 #undef READ_IVAL
229 #undef READ_FVAL
230
231 #define WRITE_FVAL(str, id, val) (BLI_dynstr_appendf(str, id " %f\n", val))
232 #define WRITE_IVAL(str, id, val) (BLI_dynstr_appendf(str, id " %d\n", val))
233
234 #define WRITE_VEC3(str, id, val) do { \
235         WRITE_FVAL(str, id ".x", val[0]); \
236         WRITE_FVAL(str, id ".y", val[1]); \
237         WRITE_FVAL(str, id ".z", val[2]); \
238 } while (0)
239
240 #define WRITE_SOLIDLIGHT(str, sl, i) do { \
241         WRITE_IVAL(str, "light[" STRINGIFY(i) "].flag", sl[i].flag); \
242         WRITE_FVAL(str, "light[" STRINGIFY(i) "].smooth", sl[i].smooth); \
243         WRITE_VEC3(str, "light[" STRINGIFY(i) "].col", sl[i].col); \
244         WRITE_VEC3(str, "light[" STRINGIFY(i) "].spec", sl[i].spec); \
245         WRITE_VEC3(str, "light[" STRINGIFY(i) "].vec", sl[i].vec); \
246 } while (0)
247
248 static void studiolight_write_solid_light(StudioLight *sl)
249 {
250         FILE *fp = BLI_fopen(sl->path, "wb");
251         if (fp) {
252                 DynStr *str = BLI_dynstr_new();
253
254                 /* Very dumb ascii format. One value per line separated by a space. */
255                 WRITE_IVAL(str, "version", STUDIOLIGHT_FILE_VERSION);
256                 WRITE_VEC3(str, "light_ambient", sl->light_ambient);
257                 WRITE_SOLIDLIGHT(str, sl->light, 0);
258                 WRITE_SOLIDLIGHT(str, sl->light, 1);
259                 WRITE_SOLIDLIGHT(str, sl->light, 2);
260                 WRITE_SOLIDLIGHT(str, sl->light, 3);
261
262                 char *cstr = BLI_dynstr_get_cstring(str);
263
264                 fwrite(cstr, BLI_dynstr_get_len(str), 1, fp);
265                 fclose(fp);
266
267                 MEM_freeN(cstr);
268                 BLI_dynstr_free(str);
269         }
270 }
271
272 #undef WRITE_SOLIDLIGHT
273 #undef WRITE_VEC3
274 #undef WRITE_IVAL
275 #undef WRITE_FVAL
276
277 static void direction_to_equirect(float r[2], const float dir[3])
278 {
279         r[0] = (atan2f(dir[1], dir[0]) - M_PI) / -(M_PI * 2);
280         r[1] = (acosf(dir[2] / 1.0) - M_PI) / -M_PI;
281 }
282
283 static void equirect_to_direction(float r[3], float u, float v)
284 {
285         float phi = (-(M_PI * 2)) * u + M_PI;
286         float theta = -M_PI * v + M_PI;
287         float sin_theta = sinf(theta);
288         r[0] = sin_theta * cosf(phi);
289         r[1] = sin_theta * sinf(phi);
290         r[2] = cosf(theta);
291 }
292
293 static void UNUSED_FUNCTION(direction_to_cube_face_uv)(float r_uv[2], int *r_face, const float dir[3])
294 {
295         if (fabsf(dir[0]) > fabsf(dir[1]) && fabsf(dir[0]) > fabsf(dir[2])) {
296                 bool is_pos = (dir[0] > 0.0f);
297                 *r_face = is_pos ? STUDIOLIGHT_X_POS : STUDIOLIGHT_X_NEG;
298                 r_uv[0] = dir[2] / fabsf(dir[0]) * (is_pos ?  1 : -1);
299                 r_uv[1] = dir[1] / fabsf(dir[0]) * (is_pos ? -1 : -1);
300         }
301         else if (fabsf(dir[1]) > fabsf(dir[0]) && fabsf(dir[1]) > fabsf(dir[2])) {
302                 bool is_pos = (dir[1] > 0.0f);
303                 *r_face = is_pos ? STUDIOLIGHT_Y_POS : STUDIOLIGHT_Y_NEG;
304                 r_uv[0] = dir[0] / fabsf(dir[1]) * (is_pos ?  1 :  1);
305                 r_uv[1] = dir[2] / fabsf(dir[1]) * (is_pos ? -1 :  1);
306         }
307         else {
308                 bool is_pos = (dir[2] > 0.0f);
309                 *r_face = is_pos ? STUDIOLIGHT_Z_NEG : STUDIOLIGHT_Z_POS;
310                 r_uv[0] = dir[0] / fabsf(dir[2]) * (is_pos ? -1 :  1);
311                 r_uv[1] = dir[1] / fabsf(dir[2]) * (is_pos ? -1 : -1);
312         }
313         r_uv[0] = r_uv[0] * 0.5f + 0.5f;
314         r_uv[1] = r_uv[1] * 0.5f + 0.5f;
315 }
316
317 static void cube_face_uv_to_direction(float r_dir[3], float x, float y, int face)
318 {
319         const float conversion_matrices[6][3][3] = {
320                 {{ 0.0f, 0.0f,  1.0f}, {0.0f, -1.0f,  0.0f}, { 1.0f,  0.0f,  0.0f}},
321                 {{ 0.0f, 0.0f, -1.0f}, {0.0f, -1.0f,  0.0f}, {-1.0f,  0.0f,  0.0f}},
322                 {{ 1.0f, 0.0f,  0.0f}, {0.0f,  0.0f, -1.0f}, { 0.0f,  1.0f,  0.0f}},
323                 {{ 1.0f, 0.0f,  0.0f}, {0.0f,  0.0f,  1.0f}, { 0.0f, -1.0f,  0.0f}},
324                 {{ 1.0f, 0.0f,  0.0f}, {0.0f, -1.0f,  0.0f}, { 0.0f,  0.0f, -1.0f}},
325                 {{-1.0f, 0.0f,  0.0f}, {0.0f, -1.0f,  0.0f}, { 0.0f,  0.0f,  1.0f}},
326         };
327
328         copy_v3_fl3(r_dir, x * 2.0f - 1.0f, y * 2.0f - 1.0f, 1.0f);
329         mul_m3_v3(conversion_matrices[face], r_dir);
330         normalize_v3(r_dir);
331 }
332
333 static void studiolight_load_equirect_image(StudioLight *sl)
334 {
335         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
336                 ImBuf *ibuf = NULL;
337                 ibuf = IMB_loadiffname(sl->path, 0, NULL);
338                 if (ibuf == NULL) {
339                         float *colbuf = MEM_mallocN(sizeof(float[4]), __func__);
340                         copy_v4_fl4(colbuf, 1.0f, 0.0f, 1.0f, 1.0f);
341                         ibuf = IMB_allocFromBuffer(NULL, colbuf, 1, 1);
342                 }
343                 IMB_float_from_rect(ibuf);
344                 sl->equirect_radiance_buffer = ibuf;
345         }
346         sl->flag |= STUDIOLIGHT_EXTERNAL_IMAGE_LOADED;
347 }
348
349 static void studiolight_create_equirect_radiance_gputexture(StudioLight *sl)
350 {
351         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
352                 char error[256];
353                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
354                 ImBuf *ibuf = sl->equirect_radiance_buffer;
355
356                 if (sl->flag & STUDIOLIGHT_TYPE_MATCAP) {
357                         float *gpu_matcap_3components = MEM_callocN(sizeof(float[3]) * ibuf->x * ibuf->y, __func__);
358
359                         float (*offset4)[4] = (float (*)[4])ibuf->rect_float;
360                         float (*offset3)[3] = (float (*)[3])gpu_matcap_3components;
361                         for (int i = 0; i < ibuf->x * ibuf->y; i++, offset4++, offset3++) {
362                                 copy_v3_v3(*offset3, *offset4);
363                         }
364
365                         sl->equirect_radiance_gputexture = GPU_texture_create_nD(
366                                 ibuf->x, ibuf->y, 0, 2, gpu_matcap_3components, GPU_R11F_G11F_B10F, GPU_DATA_FLOAT, 0, false, error);
367
368                         MEM_SAFE_FREE(gpu_matcap_3components);
369                 }
370                 else {
371                         sl->equirect_radiance_gputexture = GPU_texture_create_2D(
372                                 ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error);
373                         GPUTexture *tex = sl->equirect_radiance_gputexture;
374                         GPU_texture_bind(tex, 0);
375                         GPU_texture_filter_mode(tex, true);
376                         GPU_texture_wrap_mode(tex, true);
377                         GPU_texture_unbind(tex);
378                 }
379         }
380         sl->flag |= STUDIOLIGHT_EQUIRECT_RADIANCE_GPUTEXTURE;
381 }
382
383 static void studiolight_create_equirect_irradiance_gputexture(StudioLight *sl)
384 {
385         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
386                 char error[256];
387                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED);
388                 ImBuf *ibuf = sl->equirect_irradiance_buffer;
389                 sl->equirect_irradiance_gputexture = GPU_texture_create_2D(
390                         ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error);
391                 GPUTexture *tex = sl->equirect_irradiance_gputexture;
392                 GPU_texture_bind(tex, 0);
393                 GPU_texture_filter_mode(tex, true);
394                 GPU_texture_wrap_mode(tex, true);
395                 GPU_texture_unbind(tex);
396         }
397         sl->flag |= STUDIOLIGHT_EQUIRECT_IRRADIANCE_GPUTEXTURE;
398 }
399
400 static void studiolight_calculate_radiance(ImBuf *ibuf, float color[4], const float direction[3])
401 {
402         float uv[2];
403         direction_to_equirect(uv, direction);
404         nearest_interpolation_color_wrap(ibuf, NULL, color, uv[0] * ibuf->x, uv[1] * ibuf->y);
405 }
406
407 static void studiolight_calculate_radiance_buffer(
408         ImBuf *ibuf, float *colbuf,
409         const int index_x, const int index_y, const int index_z,
410         const float xsign, const float ysign, const float zsign)
411 {
412         ITER_PIXELS(float, colbuf, 4,
413                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE,
414                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE)
415         {
416                 float direction[3];
417                 direction[index_x] = xsign * (x - 0.5f);
418                 direction[index_y] = ysign * (y - 0.5f);
419                 direction[index_z] = zsign * 0.5f;
420                 normalize_v3(direction);
421                 studiolight_calculate_radiance(ibuf, pixel, direction);
422         }
423         ITER_PIXELS_END;
424 }
425
426 static void studiolight_calculate_radiance_cubemap_buffers(StudioLight *sl)
427 {
428         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
429                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
430                 ImBuf *ibuf = sl->equirect_radiance_buffer;
431                 if (ibuf) {
432                         float *colbuf = MEM_mallocN(SQUARE(STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) * sizeof(float[4]), __func__);
433
434                         /* front */
435                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 2, 1,  1, -1,  1);
436                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS] = IMB_allocFromBuffer(
437                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
438
439                         /* back */
440                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 2, 1,  1,  1, -1);
441                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG] = IMB_allocFromBuffer(
442                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
443
444                         /* left */
445                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 2, 1, 0,  1, -1,  1);
446                         sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS] = IMB_allocFromBuffer(
447                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
448
449                         /* right */
450                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 2, 1, 0, -1, -1, -1);
451                         sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG] = IMB_allocFromBuffer(
452                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
453
454                         /* top */
455                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 1, 2, -1, -1,  1);
456                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG] = IMB_allocFromBuffer(
457                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
458
459                         /* bottom */
460                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 1, 2,  1, -1, -1);
461                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS] = IMB_allocFromBuffer(
462                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
463
464 #if 0
465                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], "/tmp/studiolight_radiance_left.png", IB_rectfloat);
466                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], "/tmp/studiolight_radiance_right.png", IB_rectfloat);
467                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], "/tmp/studiolight_radiance_front.png", IB_rectfloat);
468                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], "/tmp/studiolight_radiance_back.png", IB_rectfloat);
469                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], "/tmp/studiolight_radiance_bottom.png", IB_rectfloat);
470                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], "/tmp/studiolight_radiance_top.png", IB_rectfloat);
471 #endif
472                         MEM_freeN(colbuf);
473                 }
474         }
475         sl->flag |= STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED;
476 }
477
478 /*
479  * Spherical Harmonics
480  */
481 BLI_INLINE float area_element(float x, float y)
482 {
483         return atan2(x * y, sqrtf(x * x + y * y + 1));
484 }
485
486 BLI_INLINE float texel_solid_angle(float x, float y, float halfpix)
487 {
488         float v1x = (x - halfpix) * 2.0f - 1.0f;
489         float v1y = (y - halfpix) * 2.0f - 1.0f;
490         float v2x = (x + halfpix) * 2.0f - 1.0f;
491         float v2y = (y + halfpix) * 2.0f - 1.0f;
492
493         return area_element(v1x, v1y) - area_element(v1x, v2y) - area_element(v2x, v1y) + area_element(v2x, v2y);
494 }
495
496 static void studiolight_calculate_cubemap_vector_weight(float normal[3], float *weight, int face, float x, float y)
497 {
498         const float halfpix = 0.5f / STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE;
499         cube_face_uv_to_direction(normal, x, y, face);
500         *weight = texel_solid_angle(x, y, halfpix);
501 }
502
503 static void studiolight_spherical_harmonics_calculate_coefficients(StudioLight *sl, float (*sh)[3])
504 {
505         float weight_accum = 0.0f;
506         memset(sh, 0, sizeof(float) * 3 * STUDIOLIGHT_SH_COEFS_LEN);
507
508         for (int face = 0; face < 6; face++) {
509                 ITER_PIXELS(float, sl->radiance_cubemap_buffers[face]->rect_float, 4,
510                             STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE,
511                             STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE)
512                 {
513                         float color[3], cubevec[3], weight;
514                         studiolight_calculate_cubemap_vector_weight(cubevec, &weight, face, x, y);
515                         mul_v3_v3fl(color, pixel, weight);
516                         weight_accum += weight;
517
518                         int i = 0;
519                         /* L0 */
520                         madd_v3_v3fl(sh[i++], color, 0.2822095f);
521 #if STUDIOLIGHT_SH_BANDS > 1 /* L1 */
522                         const float nx = cubevec[0];
523                         const float ny = cubevec[1];
524                         const float nz = cubevec[2];
525                         madd_v3_v3fl(sh[i++], color, -0.488603f * nz);
526                         madd_v3_v3fl(sh[i++], color, 0.488603f * ny);
527                         madd_v3_v3fl(sh[i++], color, -0.488603f * nx);
528 #endif
529 #if STUDIOLIGHT_SH_BANDS > 2 /* L2 */
530                         const float nx2 = SQUARE(nx);
531                         const float ny2 = SQUARE(ny);
532                         const float nz2 = SQUARE(nz);
533                         madd_v3_v3fl(sh[i++], color, 1.092548f * nx * nz);
534                         madd_v3_v3fl(sh[i++], color, -1.092548f * nz * ny);
535                         madd_v3_v3fl(sh[i++], color, 0.315392f * (3.0f * ny2 - 1.0f));
536                         madd_v3_v3fl(sh[i++], color, 1.092548f * nx * ny);
537                         madd_v3_v3fl(sh[i++], color, 0.546274f * (nx2 - nz2));
538 #endif
539                         /* Bypass L3 Because final irradiance does not need it. */
540 #if STUDIOLIGHT_SH_BANDS > 4 /* L4 */
541                         const float nx4 = SQUARE(nx2);
542                         const float ny4 = SQUARE(ny2);
543                         const float nz4 = SQUARE(nz2);
544                         madd_v3_v3fl(sh[i++], color, 2.5033429417967046f * nx * nz * (nx2 - nz2));
545                         madd_v3_v3fl(sh[i++], color, -1.7701307697799304f * nz * ny * (3.0f * nx2 - nz2));
546                         madd_v3_v3fl(sh[i++], color, 0.9461746957575601f * nz * nx * (-1.0f + 7.0f * ny2));
547                         madd_v3_v3fl(sh[i++], color, -0.6690465435572892f * nz * ny * (-3.0f + 7.0f * ny2));
548                         madd_v3_v3fl(sh[i++], color, (105.0f * ny4 - 90.0f * ny2 + 9.0f) / 28.359261614f);
549                         madd_v3_v3fl(sh[i++], color, -0.6690465435572892f * nx * ny * (-3.0f + 7.0f * ny2));
550                         madd_v3_v3fl(sh[i++], color, 0.9461746957575601f * (nx2 - nz2) * (-1.0f + 7.0f * ny2));
551                         madd_v3_v3fl(sh[i++], color, -1.7701307697799304f * nx * ny * (nx2 - 3.0f * nz2));
552                         madd_v3_v3fl(sh[i++], color, 0.6258357354491761f * (nx4 - 6.0f * nz2 * nx2 + nz4));
553 #endif
554                 }
555                 ITER_PIXELS_END;
556         }
557
558         /* The sum of solid angle should be equal to the solid angle of the sphere (4 PI),
559          * so normalize in order to make our weightAccum exactly match 4 PI. */
560         for (int i = 0; i < STUDIOLIGHT_SH_COEFS_LEN; ++i) {
561                 mul_v3_fl(sh[i], M_PI * 4.0f / weight_accum);
562         }
563 }
564
565 /* Take monochrome SH as input */
566 static float studiolight_spherical_harmonics_lambda_get(float *sh, float max_laplacian)
567 {
568         /* From Peter-Pike Sloan's Stupid SH Tricks http://www.ppsloan.org/publications/StupidSH36.pdf */
569         float table_l[STUDIOLIGHT_SH_BANDS];
570         float table_b[STUDIOLIGHT_SH_BANDS];
571
572         float lambda = 0.0f;
573
574         table_l[0] = 0.0f;
575         table_b[0] = 0.0f;
576         int index = 1;
577         for (int level = 1; level < STUDIOLIGHT_SH_BANDS; level++) {
578                 table_l[level] = (float)(SQUARE(level) * SQUARE(level + 1));
579
580                 float b = 0.0f;
581                 for (int m = -1; m <= level; m++) {
582                         b += SQUARE(sh[index++]);
583                 }
584                 table_b[level] = b;
585         }
586
587         float squared_lamplacian = 0.0f;
588         for (int level = 1; level < STUDIOLIGHT_SH_BANDS; level++) {
589                 squared_lamplacian += table_l[level] * table_b[level];
590         }
591
592         const float target_squared_laplacian = max_laplacian * max_laplacian;
593         if (squared_lamplacian <= target_squared_laplacian) {
594                 return lambda;
595         }
596
597         const int no_iterations = 10000000;
598         for (int i = 0; i < no_iterations; ++i) {
599                 float f = 0.0f;
600                 float fd = 0.0f;
601
602                 for (int level = 1; level < STUDIOLIGHT_SH_BANDS; ++level) {
603                         f += table_l[level] * table_b[level] / SQUARE(1.0f + lambda * table_l[level]);
604                         fd += (2.0f * SQUARE(table_l[level]) * table_b[level]) / CUBE(1.0f + lambda * table_l[level]);
605                 }
606
607                 f = target_squared_laplacian - f;
608
609                 float delta = -f / fd;
610                 lambda += delta;
611
612                 if (ABS(delta) < 1e-6f) {
613                         break;
614                 }
615         }
616
617         return lambda;
618 }
619
620 static void studiolight_spherical_harmonics_apply_windowing(float (*sh)[3], float max_laplacian)
621 {
622         if (max_laplacian <= 0.0f)
623                 return;
624
625         float sh_r[STUDIOLIGHT_SH_COEFS_LEN];
626         float sh_g[STUDIOLIGHT_SH_COEFS_LEN];
627         float sh_b[STUDIOLIGHT_SH_COEFS_LEN];
628         for (int i = 0; i < STUDIOLIGHT_SH_COEFS_LEN; i++) {
629                 sh_r[i] = sh[i][0];
630                 sh_g[i] = sh[i][1];
631                 sh_b[i] = sh[i][2];
632         }
633         float lambda_r = studiolight_spherical_harmonics_lambda_get(sh_r, max_laplacian);
634         float lambda_g = studiolight_spherical_harmonics_lambda_get(sh_g, max_laplacian);
635         float lambda_b = studiolight_spherical_harmonics_lambda_get(sh_b, max_laplacian);
636
637         /* Apply windowing lambda */
638         int index = 0;
639         for (int level = 0; level < STUDIOLIGHT_SH_BANDS; level++) {
640                 float s[3];
641                 s[0] = 1.0f / (1.0f + lambda_r * SQUARE(level) * SQUARE(level + 1.0f));
642                 s[1] = 1.0f / (1.0f + lambda_g * SQUARE(level) * SQUARE(level + 1.0f));
643                 s[2] = 1.0f / (1.0f + lambda_b * SQUARE(level) * SQUARE(level + 1.0f));
644
645                 for (int m = -1; m <= level; m++) {
646                         mul_v3_v3(sh[index++], s);
647                 }
648         }
649 }
650
651 static float studiolight_spherical_harmonics_geomerics_eval(const float normal[3], float sh0, float sh1, float sh2, float sh3)
652 {
653         /* Use Geomerics non-linear SH. */
654         /* http://www.geomerics.com/wp-content/uploads/2015/08/CEDEC_Geomerics_ReconstructingDiffuseLighting1.pdf */
655         float R0 = sh0 * M_1_PI;
656
657         float R1[3] = {-sh3, sh2, -sh1};
658         mul_v3_fl(R1, 0.5f * M_1_PI * 1.5f); /* 1.5f is to improve the contrast a bit. */
659         float lenR1 = len_v3(R1);
660         mul_v3_fl(R1, 1.0f / lenR1);
661         float q = 0.5f * (1.0f + dot_v3v3(R1, normal));
662
663         float p = 1.0f + 2.0f * lenR1 / R0;
664         float a = (1.0f - lenR1 / R0) / (1.0f + lenR1 / R0);
665
666         return R0 * (a + (1.0f - a) * (p + 1.0f) * powf(q, p));
667 }
668
669 BLI_INLINE void studiolight_spherical_harmonics_eval(StudioLight *sl, float color[3], const float normal[3])
670 {
671 #if STUDIOLIGHT_SH_BANDS == 2
672         float (*sh)[3] = (float (*)[3])sl->spherical_harmonics_coefs;
673         for (int i = 0; i < 3; ++i) {
674                 color[i] = studiolight_spherical_harmonics_geomerics_eval(normal, sh[0][i], sh[1][i], sh[2][i], sh[3][i]);
675         }
676         return;
677 #else
678
679         /* L0 */
680         mul_v3_v3fl(color, sl->spherical_harmonics_coefs[0], 0.282095f);
681 #  if STUDIOLIGHT_SH_BANDS > 1 /* L1 */
682         const float nx = normal[0];
683         const float ny = normal[1];
684         const float nz = normal[2];
685         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[1], -0.488603f * nz);
686         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[2],  0.488603f * ny);
687         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[3], -0.488603f * nx);
688 #  endif
689 #  if STUDIOLIGHT_SH_BANDS > 2 /* L2 */
690         const float nx2 = SQUARE(nx);
691         const float ny2 = SQUARE(ny);
692         const float nz2 = SQUARE(nz);
693         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[4], 1.092548f * nx * nz);
694         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[5], -1.092548f * nz * ny);
695         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[6], 0.315392f * (3.0f * ny2 - 1.0f));
696         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[7], -1.092548 * nx * ny);
697         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[8], 0.546274 * (nx2 - nz2));
698 #  endif
699         /* L3 coefs are 0 */
700 #  if STUDIOLIGHT_SH_BANDS > 4 /* L4 */
701         const float nx4 = SQUARE(nx2);
702         const float ny4 = SQUARE(ny2);
703         const float nz4 = SQUARE(nz2);
704         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[9],   2.5033429417967046f * nx * nz * (nx2 - nz2));
705         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[10], -1.7701307697799304f * nz * ny * (3.0f * nx2 - nz2));
706         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[11],  0.9461746957575601f * nz * nx * (-1.0f + 7.0f * ny2));
707         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[12], -0.6690465435572892f * nz * ny * (-3.0f + 7.0f * ny2));
708         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[13],  (105.0f * ny4 - 90.0f * ny2 + 9.0f) / 28.359261614f);
709         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[14], -0.6690465435572892f * nx * ny * (-3.0f + 7.0f * ny2));
710         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[15],  0.9461746957575601f * (nx2 - nz2) * (-1.0f + 7.0f * ny2));
711         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[16], -1.7701307697799304f * nx * ny * (nx2 - 3.0f * nz2));
712         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[17],  0.6258357354491761f * (nx4 - 6.0f * nz2 * nx2 + nz4));
713 #  endif
714 #endif
715 }
716
717 /* This modify the radiance into irradiance. */
718 static void studiolight_spherical_harmonics_apply_band_factors(StudioLight *sl, float (*sh)[3])
719 {
720         static float sl_sh_band_factors[5] = {
721                 1.0f,
722                 2.0f / 3.0f,
723                 1.0f / 4.0f,
724                 0.0f,
725                 -1.0f / 24.0f,
726         };
727
728         int index = 0, dst_idx = 0;
729         for (int band = 0; band < STUDIOLIGHT_SH_BANDS; band++) {
730                 for (int m = 0; m < SQUARE(band + 1) - SQUARE(band); m++) {
731                         /* Skip L3 */
732                         if (band != 3) {
733                                 mul_v3_v3fl(sl->spherical_harmonics_coefs[dst_idx++], sh[index], sl_sh_band_factors[band]);
734                         }
735                         index++;
736                 }
737         }
738 }
739
740 static void studiolight_calculate_diffuse_light(StudioLight *sl)
741 {
742         /* init light to black */
743         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
744                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED);
745
746                 float sh_coefs[STUDIOLIGHT_SH_COEFS_LEN][3];
747                 studiolight_spherical_harmonics_calculate_coefficients(sl, sh_coefs);
748                 studiolight_spherical_harmonics_apply_windowing(sh_coefs, STUDIOLIGHT_SH_WINDOWING);
749                 studiolight_spherical_harmonics_apply_band_factors(sl, sh_coefs);
750
751                 if (sl->flag & STUDIOLIGHT_USER_DEFINED) {
752                         FILE *fp = BLI_fopen(sl->path_sh_cache, "wb");
753                         if (fp) {
754                                 fwrite(sl->spherical_harmonics_coefs, sizeof(sl->spherical_harmonics_coefs), 1, fp);
755                                 fclose(fp);
756                         }
757                 }
758         }
759         sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED;
760 }
761
762 BLI_INLINE void studiolight_evaluate_specular_radiance_buffer(
763         ImBuf *radiance_buffer, const float normal[3], float color[3],
764         int xoffset, int yoffset, int zoffset, float zsign)
765 {
766         if (radiance_buffer == NULL) {
767                 return;
768         }
769
770         float accum[3] = {0.0f, 0.0f, 0.0f};
771         float accum_weight = 0.00001f;
772         ITER_PIXELS(float, radiance_buffer->rect_float, 4,
773                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE,
774                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE)
775         {
776                 float direction[3];
777                 direction[zoffset] = zsign * 0.5f;
778                 direction[xoffset] = x - 0.5f;
779                 direction[yoffset] = y - 0.5f;
780                 normalize_v3(direction);
781                 float weight = dot_v3v3(direction, normal) > 0.95f ? 1.0f : 0.0f;
782                 // float solid_angle = texel_solid_angle(x, y, texel_size[0] * 0.5f);
783                 madd_v3_v3fl(accum, pixel, weight);
784                 accum_weight += weight;
785         }
786         ITER_PIXELS_END;
787
788         madd_v3_v3fl(color, accum, 1.0f / accum_weight);
789 }
790
791 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
792 static void studiolight_irradiance_eval(StudioLight *sl, float color[3], const float normal[3])
793 {
794         copy_v3_fl(color, 0.0f);
795
796         /* XXX: This is madness, iterating over all cubemap pixels for each destination pixels
797          * even if their weight is 0.0f.
798          * It should use hemisphere, cosine sampling at least. */
799
800         /* back */
801         studiolight_evaluate_specular_radiance_buffer(
802                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], normal, color, 0, 2, 1, 1);
803         /* front */
804         studiolight_evaluate_specular_radiance_buffer(
805                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], normal, color, 0, 2, 1, -1);
806
807         /* left */
808         studiolight_evaluate_specular_radiance_buffer(
809                 sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], normal, color, 1, 2, 0, 1);
810         /* right */
811         studiolight_evaluate_specular_radiance_buffer(
812                 sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], normal, color, 1, 2, 0, -1);
813
814         /* top */
815         studiolight_evaluate_specular_radiance_buffer(
816                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], normal, color, 0, 1, 2, 1);
817         /* bottom */
818         studiolight_evaluate_specular_radiance_buffer(
819                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], normal, color, 0, 1, 2, -1);
820
821         mul_v3_fl(color, 1.0 / M_PI);
822 }
823 #endif
824
825 static float brdf_approx(float spec_color, float roughness, float NV)
826 {
827         /* Very rough own approx. We don't need it to be correct, just fast.
828          * Just simulate fresnel effect with roughness attenuation. */
829         float fresnel = exp2(-8.35f * NV) * (1.0f - roughness);
830         return spec_color * (1.0f - fresnel) + fresnel;
831 }
832
833 /* NL need to be unclamped. w in [0..1] range. */
834 static float wrapped_lighting(float NL, float w)
835 {
836         float w_1 = w + 1.0f;
837         return max_ff((NL + w) / (w_1 * w_1), 0.0f);
838 }
839
840 static float blinn_specular(
841         const float L[3], const float I[3], const float N[3], float R[3], float NL, float roughness, float wrap)
842 {
843         float half_dir[3];
844         float wrapped_NL = dot_v3v3(L, R);
845         add_v3_v3v3(half_dir, L, I);
846         normalize_v3(half_dir);
847         float spec_angle = max_ff(dot_v3v3(half_dir, N), 0.0f);
848
849         float gloss = 1.0f - roughness;
850         /* Reduce gloss for smooth light. (simulate bigger light) */
851         gloss *= 1.0f - wrap;
852         float shininess = exp2(10.0f * gloss + 1.0f);
853
854         /* Pi is already divided in the lamp power.
855          * normalization_factor = (shininess + 8.0) / (8.0 * M_PI) */
856         float normalization_factor = shininess * 0.125f + 1.0f;
857         float spec_light = powf(spec_angle, shininess) * max_ff(NL, 0.0f) * normalization_factor;
858
859         /* Simulate Env. light. */
860         float w = wrap * (1.0 - roughness) + roughness;
861         float spec_env = wrapped_lighting(wrapped_NL, w);
862
863         float w2 = wrap * wrap;
864
865         return spec_light * (1.0 - w2) + spec_env * w2;
866 }
867
868 /* Keep in sync with the glsl shader function get_world_lighting() */
869 static void studiolight_lights_eval(StudioLight *sl, float color[3], const float normal[3])
870 {
871         float R[3], I[3] = {0.0f, 0.0f, 1.0f}, N[3] = {normal[0], normal[2], -normal[1]};
872         const float roughness = 0.5f;
873         const float diffuse_color = 0.8f;
874         const float specular_color = brdf_approx(0.05f, roughness, N[2]);
875         float diff_light[3], spec_light[3];
876
877         /* Ambient lighting */
878         copy_v3_v3(diff_light, sl->light_ambient);
879         copy_v3_v3(spec_light, sl->light_ambient);
880
881         reflect_v3_v3v3(R, I, N);
882         for (int i = 0; i < 3; ++i) {
883                 SolidLight *light = &sl->light[i];
884                 if (light->flag) {
885                         /* Diffuse lighting */
886                         float NL = dot_v3v3(light->vec, N);
887                         float diff = wrapped_lighting(NL, light->smooth);
888                         madd_v3_v3fl(diff_light, light->col, diff);
889                         /* Specular lighting */
890                         float spec = blinn_specular(light->vec, I, N, R, NL, roughness, light->smooth);
891                         madd_v3_v3fl(spec_light, light->spec, spec);
892                 }
893         }
894
895         /* Multiply result by surface colors. */
896         mul_v3_fl(diff_light, diffuse_color * (1.0 - specular_color));
897         mul_v3_fl(spec_light, specular_color);
898
899         add_v3_v3v3(color, diff_light, spec_light);
900 }
901
902 static bool studiolight_load_irradiance_equirect_image(StudioLight *sl)
903 {
904 #ifdef STUDIOLIGHT_LOAD_CACHED_FILES
905         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
906                 ImBuf *ibuf = NULL;
907                 ibuf = IMB_loadiffname(sl->path_irr_cache, 0, NULL);
908                 if (ibuf) {
909                         IMB_float_from_rect(ibuf);
910                         sl->equirect_irradiance_buffer = ibuf;
911                         sl->flag |= STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED;
912                         return true;
913                 }
914         }
915 #else
916         UNUSED_VARS(sl);
917 #endif
918         return false;
919 }
920
921 static bool studiolight_load_spherical_harmonics_coefficients(StudioLight *sl)
922 {
923 #ifdef STUDIOLIGHT_LOAD_CACHED_FILES
924         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
925                 FILE *fp = BLI_fopen(sl->path_sh_cache, "rb");
926                 if (fp) {
927                         if (fread((void *)(sl->spherical_harmonics_coefs), sizeof(sl->spherical_harmonics_coefs), 1, fp)) {
928                                 sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED;
929                                 fclose(fp);
930                                 return true;
931                         }
932                         fclose(fp);
933                 }
934         }
935 #else
936         UNUSED_VARS(sl);
937 #endif
938         return false;
939 }
940
941 static void studiolight_calculate_irradiance_equirect_image(StudioLight *sl)
942 {
943         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
944 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
945                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED);
946 #else
947                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED);
948 #endif
949
950                 float *colbuf = MEM_mallocN(STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH * STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT * sizeof(float[4]), __func__);
951
952                 ITER_PIXELS(float, colbuf, 4,
953                             STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH,
954                             STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT)
955                 {
956                         float dir[3];
957                         equirect_to_direction(dir, x, y);
958 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
959                         studiolight_irradiance_eval(sl, pixel, dir);
960 #else
961                         studiolight_spherical_harmonics_eval(sl, pixel, dir);
962 #endif
963                         pixel[3] = 1.0f;
964                 }
965                 ITER_PIXELS_END;
966
967                 sl->equirect_irradiance_buffer = IMB_allocFromBuffer(
968                         NULL, colbuf,
969                         STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH,
970                         STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT);
971                 MEM_freeN(colbuf);
972
973 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
974                 /*
975                  * Only store cached files when using STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
976                  */
977                 if (sl->flag & STUDIOLIGHT_USER_DEFINED) {
978                         IMB_saveiff(sl->equirect_irradiance_buffer, sl->path_irr_cache, IB_rectfloat);
979                 }
980 #endif
981         }
982         sl->flag |= STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED;
983 }
984
985 static StudioLight *studiolight_add_file(const char *path, int flag)
986 {
987         char filename[FILE_MAXFILE];
988         BLI_split_file_part(path, filename, FILE_MAXFILE);
989
990         if ((((flag & STUDIOLIGHT_TYPE_STUDIO) != 0) && BLI_path_extension_check(filename, ".sl")) ||
991             BLI_path_extension_check_array(filename, imb_ext_image))
992         {
993                 StudioLight *sl = studiolight_create(STUDIOLIGHT_EXTERNAL_FILE | flag);
994                 BLI_strncpy(sl->name, filename, FILE_MAXFILE);
995                 BLI_strncpy(sl->path, path, FILE_MAXFILE);
996
997                 if ((flag & STUDIOLIGHT_TYPE_STUDIO) != 0) {
998                         studiolight_load_solid_light(sl);
999                 }
1000                 else {
1001                         sl->path_irr_cache = BLI_string_joinN(path, ".irr");
1002                         sl->path_sh_cache = BLI_string_joinN(path, ".sh2");
1003                 }
1004                 BLI_addtail(&studiolights, sl);
1005                 return sl;
1006         }
1007         return NULL;
1008 }
1009
1010 static void studiolight_add_files_from_datafolder(const int folder_id, const char *subfolder, int flag)
1011 {
1012         struct direntry *dir;
1013         const char *folder = BKE_appdir_folder_id(folder_id, subfolder);
1014         if (folder) {
1015                 uint totfile = BLI_filelist_dir_contents(folder, &dir);
1016                 int i;
1017                 for (i = 0; i < totfile; i++) {
1018                         if ((dir[i].type & S_IFREG)) {
1019                                 studiolight_add_file(dir[i].path, flag);
1020                         }
1021                 }
1022                 BLI_filelist_free(dir, totfile);
1023                 dir = NULL;
1024         }
1025 }
1026
1027 static int studiolight_flag_cmp_order(const StudioLight *sl)
1028 {
1029         /* Internal studiolights before external studio lights */
1030         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
1031                 return 1;
1032         }
1033         return 0;
1034 }
1035
1036 static int studiolight_cmp(const void *a, const void *b)
1037 {
1038         const StudioLight *sl1 = a;
1039         const StudioLight *sl2 = b;
1040
1041         const int flagorder1 = studiolight_flag_cmp_order(sl1);
1042         const int flagorder2 = studiolight_flag_cmp_order(sl2);
1043
1044         if (flagorder1 < flagorder2) {
1045                 return -1;
1046         }
1047         else if (flagorder1 > flagorder2) {
1048                 return 1;
1049         }
1050         else {
1051                 return BLI_strcasecmp(sl1->name, sl2->name);
1052         }
1053 }
1054
1055 /* icons */
1056
1057 /* Takes normalized uvs as parameter (range from 0 to 1).
1058  * inner_edge and outer_edge are distances (from the center)
1059  * in uv space for the alpha mask falloff. */
1060 static uint alpha_circle_mask(float u, float v, float inner_edge, float outer_edge)
1061 {
1062         /* Coords from center. */
1063         float co[2] = {u - 0.5f, v - 0.5f};
1064         float dist = len_v2(co);
1065         float alpha = 1.0f + (inner_edge - dist) / (outer_edge - inner_edge);
1066         uint mask = (uint)floorf(255.0f * min_ff(max_ff(alpha, 0.0f), 1.0f));
1067         return mask << 24;
1068 }
1069
1070 /* Percentage of the icon that the preview sphere covers. */
1071 #define STUDIOLIGHT_DIAMETER 0.95f
1072 /* Rescale coord around (0.5, 0.5) by STUDIOLIGHT_DIAMETER. */
1073 #define RESCALE_COORD(x) (x / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f)
1074
1075 /* Remaps normalized UV [0..1] to a sphere normal around (0.5, 0.5) */
1076 static void sphere_normal_from_uv(float normal[3], float u, float v)
1077 {
1078         normal[0] = u * 2.0f - 1.0f;
1079         normal[1] = v * 2.0f - 1.0f;
1080         float dist = len_v2(normal);
1081         normal[2] = sqrtf(1.0f - SQUARE(dist));
1082 }
1083
1084 static void studiolight_radiance_preview(uint *icon_buffer, StudioLight *sl)
1085 {
1086         BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
1087
1088         ITER_PIXELS(uint, icon_buffer, 1,
1089                     STUDIOLIGHT_ICON_SIZE,
1090                     STUDIOLIGHT_ICON_SIZE)
1091         {
1092                 float dy = RESCALE_COORD(y);
1093                 float dx = RESCALE_COORD(x);
1094
1095                 uint alphamask = alpha_circle_mask(dx, dy, 0.5f - texel_size[0], 0.5f);
1096                 if (alphamask != 0) {
1097                         float normal[3], direction[3], color[4];
1098                         float incoming[3] = {0.0f, 0.0f, -1.0f};
1099                         sphere_normal_from_uv(normal, dx, dy);
1100                         reflect_v3_v3v3(direction, incoming, normal);
1101                         /* We want to see horizon not poles. */
1102                         SWAP(float, direction[1], direction[2]);
1103                         direction[1] = -direction[1];
1104
1105                         studiolight_calculate_radiance(sl->equirect_radiance_buffer, color, direction);
1106
1107                         *pixel = rgb_to_cpack(
1108                                 linearrgb_to_srgb(color[0]),
1109                                 linearrgb_to_srgb(color[1]),
1110                                 linearrgb_to_srgb(color[2])) | alphamask;
1111                 }
1112                 else {
1113                         *pixel = 0x0;
1114                 }
1115         }
1116         ITER_PIXELS_END;
1117 }
1118
1119 static void studiolight_matcap_preview(uint *icon_buffer, StudioLight *sl, bool flipped)
1120 {
1121         BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
1122
1123         ImBuf *ibuf = sl->equirect_radiance_buffer;
1124
1125         ITER_PIXELS(uint, icon_buffer, 1,
1126                     STUDIOLIGHT_ICON_SIZE,
1127                     STUDIOLIGHT_ICON_SIZE)
1128         {
1129                 float dy = RESCALE_COORD(y);
1130                 float dx = RESCALE_COORD(x);
1131                 if (flipped) {
1132                         dx = 1.0f - dx;
1133                 }
1134
1135                 float color[4];
1136                 nearest_interpolation_color(ibuf, NULL, color, dx * ibuf->x - 1.0f, dy * ibuf->y - 1.0f);
1137
1138                 uint alphamask = alpha_circle_mask(dx, dy, 0.5f - texel_size[0], 0.5f);
1139
1140                 *pixel = rgb_to_cpack(
1141                         linearrgb_to_srgb(color[0]),
1142                         linearrgb_to_srgb(color[1]),
1143                         linearrgb_to_srgb(color[2])) | alphamask;
1144         }
1145         ITER_PIXELS_END;
1146 }
1147
1148 static void studiolight_irradiance_preview(uint *icon_buffer, StudioLight *sl)
1149 {
1150         ITER_PIXELS(uint, icon_buffer, 1,
1151                     STUDIOLIGHT_ICON_SIZE,
1152                     STUDIOLIGHT_ICON_SIZE)
1153         {
1154                 float dy = RESCALE_COORD(y);
1155                 float dx = RESCALE_COORD(x);
1156
1157                 uint alphamask = alpha_circle_mask(dx, dy, 0.5f - texel_size[0], 0.5f);
1158                 if (alphamask != 0) {
1159                         float normal[3], color[3];
1160                         sphere_normal_from_uv(normal, dx, dy);
1161                         /* We want to see horizon not poles. */
1162                         SWAP(float, normal[1], normal[2]);
1163                         normal[1] = -normal[1];
1164
1165                         studiolight_lights_eval(sl, color, normal);
1166
1167                         *pixel = rgb_to_cpack(
1168                                 linearrgb_to_srgb(color[0]),
1169                                 linearrgb_to_srgb(color[1]),
1170                                 linearrgb_to_srgb(color[2])) | alphamask;
1171                 }
1172                 else {
1173                         *pixel = 0x0;
1174                 }
1175         }
1176         ITER_PIXELS_END;
1177 }
1178
1179 /* API */
1180 void BKE_studiolight_init(void)
1181 {
1182         /* Add default studio light */
1183         StudioLight *sl = studiolight_create(
1184                 STUDIOLIGHT_INTERNAL | STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED | STUDIOLIGHT_TYPE_STUDIO);
1185         BLI_strncpy(sl->name, "Default", FILE_MAXFILE);
1186
1187         copy_v4_fl4(sl->light_ambient, 0.025000, 0.025000, 0.025000, 1.000000);
1188
1189         copy_v4_fl4(sl->light[0].vec, -0.580952, 0.228571, 0.781185, 0.0);
1190         copy_v4_fl4(sl->light[0].col, 0.900000, 0.900000, 0.900000, 1.000000);
1191         copy_v4_fl4(sl->light[0].spec, 0.318547, 0.318547, 0.318547, 1.000000);
1192         sl->light[0].flag = 1;
1193         sl->light[0].smooth = 0.1;
1194
1195         copy_v4_fl4(sl->light[1].vec, 0.788218, 0.593482, -0.162765, 0.0);
1196         copy_v4_fl4(sl->light[1].col, 0.267115, 0.269928, 0.358840, 1.000000);
1197         copy_v4_fl4(sl->light[1].spec, 0.090838, 0.090838, 0.090838, 1.000000);
1198         sl->light[1].flag = 1;
1199         sl->light[1].smooth = 0.25;
1200
1201         copy_v4_fl4(sl->light[2].vec, 0.696472, -0.696472, -0.172785, 0.0);
1202         copy_v4_fl4(sl->light[2].col, 0.293216, 0.304662, 0.401968, 1.000000);
1203         copy_v4_fl4(sl->light[2].spec, 0.069399, 0.020331, 0.020331, 1.000000);
1204         sl->light[2].flag = 1;
1205         sl->light[2].smooth = 0.5;
1206
1207         copy_v4_fl4(sl->light[3].vec, 0.021053, -0.989474, 0.143173, 0.0);
1208         copy_v4_fl4(sl->light[3].col, 0.0, 0.0, 0.0, 1.0);
1209         copy_v4_fl4(sl->light[3].spec, 0.072234, 0.082253, 0.162642, 1.000000);
1210         sl->light[3].flag = 1;
1211         sl->light[3].smooth = 0.7;
1212
1213         BLI_addtail(&studiolights, sl);
1214
1215         /* go over the preset folder and add a studiolight for every image with its path */
1216         /* for portable installs (where USER and SYSTEM paths are the same), only go over LOCAL datafiles once */
1217         /* Also reserve icon space for it. */
1218         if (!BKE_appdir_app_is_portable_install()) {
1219                 studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES,
1220                                                       STUDIOLIGHT_LIGHTS_FOLDER,
1221                                                       STUDIOLIGHT_TYPE_STUDIO | STUDIOLIGHT_USER_DEFINED);
1222                 studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES,
1223                                                       STUDIOLIGHT_WORLD_FOLDER,
1224                                                       STUDIOLIGHT_TYPE_WORLD | STUDIOLIGHT_USER_DEFINED);
1225                 studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES,
1226                                                       STUDIOLIGHT_MATCAP_FOLDER,
1227                                                       STUDIOLIGHT_TYPE_MATCAP | STUDIOLIGHT_USER_DEFINED);
1228         }
1229         studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_LIGHTS_FOLDER, STUDIOLIGHT_TYPE_STUDIO);
1230         studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_WORLD_FOLDER,  STUDIOLIGHT_TYPE_WORLD);
1231         studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_MATCAP_FOLDER, STUDIOLIGHT_TYPE_MATCAP);
1232
1233         /* sort studio lights on filename. */
1234         BLI_listbase_sort(&studiolights, studiolight_cmp);
1235 }
1236
1237 void BKE_studiolight_free(void)
1238 {
1239         struct StudioLight *sl;
1240         while ((sl = BLI_pophead(&studiolights))) {
1241                 studiolight_free(sl);
1242         }
1243 }
1244
1245 struct StudioLight *BKE_studiolight_find_default(int flag)
1246 {
1247         const char *default_name = "";
1248
1249         if (flag & STUDIOLIGHT_TYPE_WORLD) {
1250                 default_name = STUDIOLIGHT_WORLD_DEFAULT;
1251         }
1252         else if (flag & STUDIOLIGHT_TYPE_MATCAP) {
1253                 default_name = STUDIOLIGHT_MATCAP_DEFAULT;
1254         }
1255
1256         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1257                 if ((sl->flag & flag) && STREQ(sl->name, default_name)) {
1258                         return sl;
1259                 }
1260         }
1261
1262         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1263                 if ((sl->flag & flag)) {
1264                         return sl;
1265                 }
1266         }
1267         return NULL;
1268 }
1269
1270 struct StudioLight *BKE_studiolight_find(const char *name, int flag)
1271 {
1272         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1273                 if (STREQLEN(sl->name, name, FILE_MAXFILE)) {
1274                         if ((sl->flag & flag)) {
1275                                 return sl;
1276                         }
1277                         else {
1278                                 /* flags do not match, so use default */
1279                                 return BKE_studiolight_find_default(flag);
1280                         }
1281                 }
1282         }
1283         /* When not found, use the default studio light */
1284         return BKE_studiolight_find_default(flag);
1285 }
1286
1287 struct StudioLight *BKE_studiolight_findindex(int index, int flag)
1288 {
1289         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1290                 if (sl->index == index) {
1291                         return sl;
1292                 }
1293         }
1294         /* When not found, use the default studio light */
1295         return BKE_studiolight_find_default(flag);
1296 }
1297
1298 struct ListBase *BKE_studiolight_listbase(void)
1299 {
1300         return &studiolights;
1301 }
1302
1303 void BKE_studiolight_preview(uint *icon_buffer, StudioLight *sl, int icon_id_type)
1304 {
1305         switch (icon_id_type) {
1306                 case STUDIOLIGHT_ICON_ID_TYPE_RADIANCE:
1307                 default:
1308                 {
1309                         studiolight_radiance_preview(icon_buffer, sl);
1310                         break;
1311                 }
1312                 case STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE:
1313                 {
1314                         studiolight_irradiance_preview(icon_buffer, sl);
1315                         break;
1316                 }
1317                 case STUDIOLIGHT_ICON_ID_TYPE_MATCAP:
1318                 {
1319                         studiolight_matcap_preview(icon_buffer, sl, false);
1320                         break;
1321                 }
1322                 case STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED:
1323                 {
1324                         studiolight_matcap_preview(icon_buffer, sl, true);
1325                         break;
1326                 }
1327         }
1328 }
1329
1330 /* Ensure state of Studiolights */
1331 void BKE_studiolight_ensure_flag(StudioLight *sl, int flag)
1332 {
1333         if ((sl->flag & flag) == flag) {
1334                 return;
1335         }
1336
1337         if ((flag & STUDIOLIGHT_EXTERNAL_IMAGE_LOADED)) {
1338                 studiolight_load_equirect_image(sl);
1339         }
1340         if ((flag & STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED)) {
1341                 studiolight_calculate_radiance_cubemap_buffers(sl);
1342         }
1343         if ((flag & STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED)) {
1344                 if (!studiolight_load_spherical_harmonics_coefficients(sl)) {
1345                         studiolight_calculate_diffuse_light(sl);
1346                 }
1347         }
1348         if ((flag & STUDIOLIGHT_EQUIRECT_RADIANCE_GPUTEXTURE)) {
1349                 studiolight_create_equirect_radiance_gputexture(sl);
1350         }
1351         if ((flag & STUDIOLIGHT_EQUIRECT_IRRADIANCE_GPUTEXTURE)) {
1352                 studiolight_create_equirect_irradiance_gputexture(sl);
1353         }
1354         if ((flag & STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED)) {
1355                 if (!studiolight_load_irradiance_equirect_image(sl)) {
1356                         studiolight_calculate_irradiance_equirect_image(sl);
1357                 }
1358         }
1359 }
1360
1361 /*
1362  * Python API Functions
1363  */
1364 void BKE_studiolight_remove(StudioLight *sl)
1365 {
1366         if (sl->flag & STUDIOLIGHT_USER_DEFINED) {
1367                 BLI_remlink(&studiolights, sl);
1368                 studiolight_free(sl);
1369         }
1370 }
1371
1372 StudioLight *BKE_studiolight_load(const char *path, int type)
1373 {
1374         StudioLight *sl = studiolight_add_file(path, type | STUDIOLIGHT_USER_DEFINED);
1375         return sl;
1376 }
1377
1378 StudioLight *BKE_studiolight_create(const char *path, const SolidLight light[4], const float light_ambient[3])
1379 {
1380         StudioLight *sl = studiolight_create(STUDIOLIGHT_EXTERNAL_FILE | STUDIOLIGHT_USER_DEFINED | STUDIOLIGHT_TYPE_STUDIO);
1381
1382         char filename[FILE_MAXFILE];
1383         BLI_split_file_part(path, filename, FILE_MAXFILE);
1384         STRNCPY(sl->path, path);
1385         STRNCPY(sl->name, filename);
1386
1387         memcpy(sl->light, light, sizeof(*light) * 4);
1388         memcpy(sl->light_ambient, light_ambient, sizeof(*light_ambient) * 3);
1389
1390         studiolight_write_solid_light(sl);
1391
1392         BLI_addtail(&studiolights, sl);
1393         return sl;
1394 }
1395
1396 /* Only useful for workbench while editing the userprefs. */
1397 StudioLight *BKE_studiolight_studio_edit_get(void)
1398 {
1399         static StudioLight sl = {0};
1400         sl.flag = STUDIOLIGHT_TYPE_STUDIO;
1401
1402         memcpy(sl.light, U.light_param, sizeof(*sl.light) * 4);
1403         memcpy(sl.light_ambient, U.light_ambient, sizeof(*sl.light_ambient) * 3);
1404
1405         return &sl;
1406 }
1407
1408 void BKE_studiolight_refresh(void)
1409 {
1410         BKE_studiolight_free();
1411         BKE_studiolight_init();
1412 }
1413
1414 void BKE_studiolight_set_free_function(StudioLight *sl, StudioLightFreeFunction *free_function, void *data)
1415 {
1416         sl->free_function = free_function;
1417         sl->free_function_data = data;
1418 }
1419
1420 void BKE_studiolight_unset_icon_id(StudioLight *sl, int icon_id)
1421 {
1422         BLI_assert(sl != NULL);
1423         if (sl->icon_id_radiance == icon_id) {
1424                 sl->icon_id_radiance = 0;
1425         }
1426         if (sl->icon_id_irradiance == icon_id) {
1427                 sl->icon_id_irradiance = 0;
1428         }
1429         if (sl->icon_id_matcap == icon_id) {
1430                 sl->icon_id_matcap = 0;
1431         }
1432         if (sl->icon_id_matcap_flipped == icon_id) {
1433                 sl->icon_id_matcap_flipped = 0;
1434         }
1435 }