f949fcaea07fd3242d05cf88ece953db4f943469
[blender.git] / source / blender / blenkernel / intern / studiolight.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) 2006-2007 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  */
28
29 /** \file blender/blenkernel/intern/studiolight.c
30  *  \ingroup bke
31  */
32
33 #include "BKE_studiolight.h"
34
35 #include "BKE_appdir.h"
36 #include "BKE_icons.h"
37
38 #include "BLI_fileops.h"
39 #include "BLI_fileops_types.h"
40 #include "BLI_listbase.h"
41 #include "BLI_math.h"
42 #include "BLI_math_color.h"
43 #include "BLI_path_util.h"
44 #include "BLI_rand.h"
45 #include "BLI_string.h"
46 #include "BLI_string_utils.h"
47
48 #include "DNA_listBase.h"
49
50 #include "IMB_imbuf.h"
51 #include "IMB_imbuf_types.h"
52
53 #include "GPU_texture.h"
54
55 #include "MEM_guardedalloc.h"
56
57
58 /* Statics */
59 static ListBase studiolights;
60 static int last_studiolight_id = 0;
61 #define STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE 96
62 #define STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT 32
63 #define STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH (STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT * 2)
64
65 /*
66  * The method to calculate the irradiance buffers
67  * The irradiance buffer is only shown in the background when in LookDev.
68  *
69  * STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE is very slow, but very accurate
70  * STUDIOLIGHT_IRRADIANCE_METHOD_SPHERICAL_HARMONICS is faster but has artifacts
71  * Cannot have both enabled at the same time!!!
72  */
73 // #define STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
74 #define STUDIOLIGHT_IRRADIANCE_METHOD_SPHERICAL_HARMONICS
75
76 /* Temporarily disabled due to the creation of textures with -nan(ind)s */
77 #define STUDIOLIGHT_SH_WINDOWING 0.0f /* 0.0 is disabled */
78
79 /*
80  * Disable this option so caches are not loaded from disk
81  * Do not checkin with this commented out
82  */
83 #define STUDIOLIGHT_LOAD_CACHED_FILES
84
85 static const char *STUDIOLIGHT_CAMERA_FOLDER = "studiolights/camera/";
86 static const char *STUDIOLIGHT_WORLD_FOLDER = "studiolights/world/";
87 static const char *STUDIOLIGHT_MATCAP_FOLDER = "studiolights/matcap/";
88
89 /* ITER MACRO */
90
91 /** Iter on all pixel giving texel center position and pixel pointer.
92  * Arguments
93  *   type : type of src.
94  *   src : source buffer.
95  *   channels : number of channels per pixel.
96  *
97  * Others
98  *   x, y : normalized UV coordinate [0..1] of the current pixel center.
99  *   texel_size[2] : UV size of a pixel in this texture.
100  *   pixel[] : pointer to the current pixel.
101  */
102 #define ITER_PIXELS(type, src, channels, width, height)                                \
103 {                                                                                      \
104         float texel_size[2];                                                               \
105         texel_size[0] = 1.0f / width;                                                      \
106         texel_size[1] = 1.0f / height;                                                     \
107         type (*pixel_)[channels] = (type (*)[channels])src;                                \
108         for (float y = 0.5 * texel_size[1]; y < 1.0; y += texel_size[1]) {                 \
109                 for (float x = 0.5 * texel_size[0]; x < 1.0; x += texel_size[0], pixel_++) {   \
110                         type *pixel = *pixel_;
111
112 #define ITER_PIXELS_END                                                              \
113                 }                                                                            \
114         }                                                                                \
115 } ((void)0)
116
117 /* FUNCTIONS */
118 #define IMB_SAFE_FREE(p) do { \
119 if (p) {                      \
120         IMB_freeImBuf(p);         \
121         p = NULL;                 \
122 }                             \
123 } while (0)
124
125 #define GPU_TEXTURE_SAFE_FREE(p) do { \
126 if (p) {                              \
127         GPU_texture_free(p);              \
128         p = NULL;                         \
129 }                                     \
130 } while (0)
131
132 static void studiolight_free(struct StudioLight *sl)
133 {
134 #define STUDIOLIGHT_DELETE_ICON(s) {  \
135         if (s != 0) {                          \
136                 BKE_icon_delete(s);           \
137                 s = 0;                        \
138         }                                 \
139 }
140         if (sl->free_function) {
141                 sl->free_function(sl, sl->free_function_data);
142         }
143         STUDIOLIGHT_DELETE_ICON(sl->icon_id_radiance);
144         STUDIOLIGHT_DELETE_ICON(sl->icon_id_irradiance);
145         STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap);
146         STUDIOLIGHT_DELETE_ICON(sl->icon_id_matcap_flipped);
147 #undef STUDIOLIGHT_DELETE_ICON
148
149         for (int index = 0; index < 6; index++) {
150                 IMB_SAFE_FREE(sl->radiance_cubemap_buffers[index]);
151         }
152         GPU_TEXTURE_SAFE_FREE(sl->equirect_radiance_gputexture);
153         GPU_TEXTURE_SAFE_FREE(sl->equirect_irradiance_gputexture);
154         IMB_SAFE_FREE(sl->equirect_radiance_buffer);
155         IMB_SAFE_FREE(sl->equirect_irradiance_buffer);
156         MEM_SAFE_FREE(sl->path_irr_cache);
157         MEM_SAFE_FREE(sl->path_sh_cache);
158         MEM_SAFE_FREE(sl);
159 }
160
161 static struct StudioLight *studiolight_create(int flag)
162 {
163         struct StudioLight *sl = MEM_callocN(sizeof(*sl), __func__);
164         sl->path[0] = 0x00;
165         sl->name[0] = 0x00;
166         sl->path_irr_cache = NULL;
167         sl->path_sh_cache = NULL;
168         sl->free_function = NULL;
169         sl->flag = flag;
170         sl->index = ++last_studiolight_id;
171         if (flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) {
172                 sl->icon_id_matcap = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP);
173                 sl->icon_id_matcap_flipped = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED);
174         }
175         else {
176                 sl->icon_id_radiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_RADIANCE);
177                 sl->icon_id_irradiance = BKE_icon_ensure_studio_light(sl, STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE);
178         }
179
180         for (int index = 0; index < 6; index++) {
181                 sl->radiance_cubemap_buffers[index] = NULL;
182         }
183
184         return sl;
185 }
186
187 static void direction_to_equirect(float r[2], const float dir[3])
188 {
189         r[0] = (atan2f(dir[1], dir[0]) - M_PI) / -(M_PI * 2);
190         r[1] = (acosf(dir[2] / 1.0) - M_PI) / -M_PI;
191 }
192
193 static void equirect_to_direction(float r[3], float u, float v)
194 {
195         float phi = (-(M_PI * 2)) * u + M_PI;
196         float theta = -M_PI * v + M_PI;
197         float sin_theta = sinf(theta);
198         r[0] = sin_theta * cosf(phi);
199         r[1] = sin_theta * sinf(phi);
200         r[2] = cosf(theta);
201 }
202
203 static void UNUSED_FUNCTION(direction_to_cube_face_uv)(float r_uv[2], int *r_face, const float dir[3])
204 {
205         if (fabsf(dir[0]) > fabsf(dir[1]) && fabsf(dir[0]) > fabsf(dir[2])) {
206                 bool is_pos = (dir[0] > 0.0f);
207                 *r_face = is_pos ? STUDIOLIGHT_X_POS : STUDIOLIGHT_X_NEG;
208                 r_uv[0] = dir[2] / fabsf(dir[0]) * (is_pos ?  1 : -1);
209                 r_uv[1] = dir[1] / fabsf(dir[0]) * (is_pos ? -1 : -1);
210         }
211         else if (fabsf(dir[1]) > fabsf(dir[0]) && fabsf(dir[1]) > fabsf(dir[2])) {
212                 bool is_pos = (dir[1] > 0.0f);
213                 *r_face = is_pos ? STUDIOLIGHT_Y_POS : STUDIOLIGHT_Y_NEG;
214                 r_uv[0] = dir[0] / fabsf(dir[1]) * (is_pos ?  1 :  1);
215                 r_uv[1] = dir[2] / fabsf(dir[1]) * (is_pos ? -1 :  1);
216         }
217         else {
218                 bool is_pos = (dir[2] > 0.0f);
219                 *r_face = is_pos ? STUDIOLIGHT_Z_NEG : STUDIOLIGHT_Z_POS;
220                 r_uv[0] = dir[0] / fabsf(dir[2]) * (is_pos ? -1 :  1);
221                 r_uv[1] = dir[1] / fabsf(dir[2]) * (is_pos ? -1 : -1);
222         }
223         r_uv[0] = r_uv[0] * 0.5f + 0.5f;
224         r_uv[1] = r_uv[1] * 0.5f + 0.5f;
225 }
226
227 static void cube_face_uv_to_direction(float r_dir[3], float x, float y, int face)
228 {
229         const float conversion_matrices[6][3][3] = {
230                 {{ 0.0f, 0.0f,  1.0f}, {0.0f, -1.0f,  0.0f}, { 1.0f,  0.0f,  0.0f}},
231                 {{ 0.0f, 0.0f, -1.0f}, {0.0f, -1.0f,  0.0f}, {-1.0f,  0.0f,  0.0f}},
232                 {{ 1.0f, 0.0f,  0.0f}, {0.0f,  0.0f, -1.0f}, { 0.0f,  1.0f,  0.0f}},
233                 {{ 1.0f, 0.0f,  0.0f}, {0.0f,  0.0f,  1.0f}, { 0.0f, -1.0f,  0.0f}},
234                 {{ 1.0f, 0.0f,  0.0f}, {0.0f, -1.0f,  0.0f}, { 0.0f,  0.0f, -1.0f}},
235                 {{-1.0f, 0.0f,  0.0f}, {0.0f, -1.0f,  0.0f}, { 0.0f,  0.0f,  1.0f}}
236         };
237
238         copy_v3_fl3(r_dir, x * 2.0f - 1.0f, y * 2.0f - 1.0f, 1.0f);
239         mul_m3_v3(conversion_matrices[face], r_dir);
240         normalize_v3(r_dir);
241 }
242
243 static void studiolight_load_equirect_image(StudioLight *sl)
244 {
245         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
246                 ImBuf *ibuf = NULL;
247                 ibuf = IMB_loadiffname(sl->path, 0, NULL);
248                 if (ibuf == NULL) {
249                         float *colbuf = MEM_mallocN(sizeof(float[4]), __func__);
250                         copy_v4_fl4(colbuf, 1.0f, 0.0f, 1.0f, 1.0f);
251                         ibuf = IMB_allocFromBuffer(NULL, colbuf, 1, 1);
252                 }
253                 IMB_float_from_rect(ibuf);
254                 sl->equirect_radiance_buffer = ibuf;
255         }
256         sl->flag |= STUDIOLIGHT_EXTERNAL_IMAGE_LOADED;
257 }
258
259 static void studiolight_create_equirect_radiance_gputexture(StudioLight *sl)
260 {
261         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
262                 char error[256];
263                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
264                 ImBuf *ibuf = sl->equirect_radiance_buffer;
265
266                 if (sl->flag & STUDIOLIGHT_ORIENTATION_VIEWNORMAL) {
267                         float *gpu_matcap_3components = MEM_callocN(sizeof(float[3]) * ibuf->x * ibuf->y, __func__);
268
269                         float (*offset4)[4] = (float (*)[4])ibuf->rect_float;
270                         float (*offset3)[3] = (float (*)[3])gpu_matcap_3components;
271                         for (int i = 0; i < ibuf->x * ibuf->y; i++, offset4++, offset3++) {
272                                 copy_v3_v3(*offset3, *offset4);
273                         }
274
275                         sl->equirect_radiance_gputexture = GPU_texture_create_nD(
276                                 ibuf->x, ibuf->y, 0, 2, gpu_matcap_3components, GPU_R11F_G11F_B10F, GPU_DATA_FLOAT, 0, false, error);
277
278                         MEM_SAFE_FREE(gpu_matcap_3components);
279                 }
280                 else {
281                         sl->equirect_radiance_gputexture = GPU_texture_create_2D(
282                                 ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error);
283                         GPUTexture *tex = sl->equirect_radiance_gputexture;
284                         GPU_texture_bind(tex, 0);
285                         GPU_texture_filter_mode(tex, true);
286                         GPU_texture_wrap_mode(tex, true);
287                         GPU_texture_unbind(tex);
288                 }
289         }
290         sl->flag |= STUDIOLIGHT_EQUIRECT_RADIANCE_GPUTEXTURE;
291 }
292
293 static void studiolight_create_equirect_irradiance_gputexture(StudioLight *sl)
294 {
295         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
296                 char error[256];
297                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED);
298                 ImBuf *ibuf = sl->equirect_irradiance_buffer;
299                 sl->equirect_irradiance_gputexture = GPU_texture_create_2D(
300                         ibuf->x, ibuf->y, GPU_RGBA16F, ibuf->rect_float, error);
301                 GPUTexture *tex = sl->equirect_irradiance_gputexture;
302                 GPU_texture_bind(tex, 0);
303                 GPU_texture_filter_mode(tex, true);
304                 GPU_texture_wrap_mode(tex, true);
305                 GPU_texture_unbind(tex);
306         }
307         sl->flag |= STUDIOLIGHT_EQUIRECT_IRRADIANCE_GPUTEXTURE;
308 }
309
310 static void studiolight_calculate_radiance(ImBuf *ibuf, float color[4], const float direction[3])
311 {
312         float uv[2];
313         direction_to_equirect(uv, direction);
314         nearest_interpolation_color_wrap(ibuf, NULL, color, uv[0] * ibuf->x, uv[1] * ibuf->y);
315 }
316
317 static void studiolight_calculate_radiance_buffer(
318         ImBuf *ibuf, float *colbuf,
319         const int index_x, const int index_y, const int index_z,
320         const float xsign, const float ysign, const float zsign)
321 {
322         ITER_PIXELS(float, colbuf, 4,
323                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE,
324                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE)
325         {
326                 float direction[3];
327                 direction[index_x] = xsign * (x - 0.5f);
328                 direction[index_y] = ysign * (y - 0.5f);
329                 direction[index_z] = zsign * 0.5f;
330                 normalize_v3(direction);
331                 studiolight_calculate_radiance(ibuf, pixel, direction);
332         }
333         ITER_PIXELS_END;
334 }
335
336 static void studiolight_calculate_radiance_cubemap_buffers(StudioLight *sl)
337 {
338         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
339                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
340                 ImBuf *ibuf = sl->equirect_radiance_buffer;
341                 if (ibuf) {
342                         float *colbuf = MEM_mallocN(SQUARE(STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE) * sizeof(float[4]), __func__);
343
344                         /* front */
345                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 2, 1,  1, -1,  1);
346                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS] = IMB_allocFromBuffer(
347                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
348
349                         /* back */
350                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 2, 1,  1,  1, -1);
351                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG] = IMB_allocFromBuffer(
352                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
353
354                         /* left */
355                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 2, 1, 0,  1, -1,  1);
356                         sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS] = IMB_allocFromBuffer(
357                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
358
359                         /* right */
360                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 2, 1, 0, -1, -1, -1);
361                         sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG] = IMB_allocFromBuffer(
362                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
363
364                         /* top */
365                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 1, 2, -1, -1,  1);
366                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG] = IMB_allocFromBuffer(
367                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
368
369                         /* bottom */
370                         studiolight_calculate_radiance_buffer(ibuf, colbuf, 0, 1, 2,  1, -1, -1);
371                         sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS] = IMB_allocFromBuffer(
372                                 NULL, colbuf, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE, STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE);
373
374 #if 0
375                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], "/tmp/studiolight_radiance_left.png", IB_rectfloat);
376                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], "/tmp/studiolight_radiance_right.png", IB_rectfloat);
377                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], "/tmp/studiolight_radiance_front.png", IB_rectfloat);
378                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], "/tmp/studiolight_radiance_back.png", IB_rectfloat);
379                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], "/tmp/studiolight_radiance_bottom.png", IB_rectfloat);
380                         IMB_saveiff(sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], "/tmp/studiolight_radiance_top.png", IB_rectfloat);
381 #endif
382                         MEM_freeN(colbuf);
383                 }
384         }
385         sl->flag |= STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED;
386 }
387
388 /*
389  * Spherical Harmonics
390  */
391 BLI_INLINE float area_element(float x, float y)
392 {
393         return atan2(x * y, sqrtf(x * x + y * y + 1));
394 }
395
396 BLI_INLINE float texel_solid_angle(float x, float y, float halfpix)
397 {
398         float v1x = (x - halfpix) * 2.0f - 1.0f;
399         float v1y = (y - halfpix) * 2.0f - 1.0f;
400         float v2x = (x + halfpix) * 2.0f - 1.0f;
401         float v2y = (y + halfpix) * 2.0f - 1.0f;
402
403         return area_element(v1x, v1y) - area_element(v1x, v2y) - area_element(v2x, v1y) + area_element(v2x, v2y);
404 }
405
406 static void studiolight_calculate_cubemap_vector_weight(float normal[3], float *weight, int face, float x, float y)
407 {
408         const float halfpix = 0.5f / STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE;
409         cube_face_uv_to_direction(normal, x, y, face);
410         *weight = texel_solid_angle(x, y, halfpix);
411 }
412
413 static void studiolight_spherical_harmonics_calculate_coefficients(StudioLight *sl, float (*sh)[3])
414 {
415         float weight_accum = 0.0f;
416         memset(sh, 0, sizeof(float) * 3 * STUDIOLIGHT_SH_COEFS_LEN);
417
418         for (int face = 0; face < 6; face++) {
419                 ITER_PIXELS(float, sl->radiance_cubemap_buffers[face]->rect_float, 4,
420                             STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE,
421                             STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE)
422                 {
423                         float color[3], cubevec[3], weight;
424                         studiolight_calculate_cubemap_vector_weight(cubevec, &weight, face, x, y);
425                         mul_v3_v3fl(color, pixel, weight);
426                         weight_accum += weight;
427
428                         int i = 0;
429                         /* L0 */
430                         madd_v3_v3fl(sh[i++], color, 0.2822095f);
431 #if STUDIOLIGHT_SH_BANDS > 1 /* L1 */
432                         const float nx = cubevec[0];
433                         const float ny = cubevec[1];
434                         const float nz = cubevec[2];
435                         madd_v3_v3fl(sh[i++], color, -0.488603f * nz);
436                         madd_v3_v3fl(sh[i++], color, 0.488603f * ny);
437                         madd_v3_v3fl(sh[i++], color, -0.488603f * nx);
438 #endif
439 #if STUDIOLIGHT_SH_BANDS > 2 /* L2 */
440                         const float nx2 = SQUARE(nx);
441                         const float ny2 = SQUARE(ny);
442                         const float nz2 = SQUARE(nz);
443                         madd_v3_v3fl(sh[i++], color, 1.092548f * nx * nz);
444                         madd_v3_v3fl(sh[i++], color, -1.092548f * nz * ny);
445                         madd_v3_v3fl(sh[i++], color, 0.315392f * (3.0f * ny2 - 1.0f));
446                         madd_v3_v3fl(sh[i++], color, 1.092548f * nx * ny);
447                         madd_v3_v3fl(sh[i++], color, 0.546274f * (nx2 - nz2));
448 #endif
449                         /* Bypass L3 Because final irradiance does not need it. */
450 #if STUDIOLIGHT_SH_BANDS > 4 /* L4 */
451                         const float nx4 = SQUARE(nx2);
452                         const float ny4 = SQUARE(ny2);
453                         const float nz4 = SQUARE(nz2);
454                         madd_v3_v3fl(sh[i++], color, 2.5033429417967046f * nx * nz * (nx2 - nz2));
455                         madd_v3_v3fl(sh[i++], color, -1.7701307697799304f * nz * ny * (3.0f * nx2 - nz2));
456                         madd_v3_v3fl(sh[i++], color, 0.9461746957575601f * nz * nx * (-1.0f + 7.0f * ny2));
457                         madd_v3_v3fl(sh[i++], color, -0.6690465435572892f * nz * ny * (-3.0f + 7.0f * ny2));
458                         madd_v3_v3fl(sh[i++], color, (105.0f * ny4 - 90.0f * ny2 + 9.0f) / 28.359261614f);
459                         madd_v3_v3fl(sh[i++], color, -0.6690465435572892f * nx * ny * (-3.0f + 7.0f * ny2));
460                         madd_v3_v3fl(sh[i++], color, 0.9461746957575601f * (nx2 - nz2) * (-1.0f + 7.0f * ny2));
461                         madd_v3_v3fl(sh[i++], color, -1.7701307697799304f * nx * ny * (nx2 - 3.0f * nz2));
462                         madd_v3_v3fl(sh[i++], color, 0.6258357354491761f * (nx4 - 6.0f * nz2 * nx2 + nz4));
463 #endif
464                 }
465                 ITER_PIXELS_END;
466         }
467
468         /* The sum of solid angle should be equal to the solid angle of the sphere (4 PI),
469          * so normalize in order to make our weightAccum exactly match 4 PI. */
470         for (int i = 0; i < STUDIOLIGHT_SH_COEFS_LEN; ++i) {
471                 mul_v3_fl(sh[i], M_PI * 4.0f / weight_accum);
472         }
473 }
474
475 /* Take monochrome SH as input */
476 static float studiolight_spherical_harmonics_lambda_get(float *sh, float max_laplacian)
477 {
478         /* From Peter-Pike Sloan's Stupid SH Tricks http://www.ppsloan.org/publications/StupidSH36.pdf */
479         float table_l[STUDIOLIGHT_SH_BANDS];
480         float table_b[STUDIOLIGHT_SH_BANDS];
481
482         float lambda = 0.0f;
483
484         table_l[0] = 0.0f;
485         table_b[0] = 0.0f;
486         int index = 1;
487         for (int level = 1; level < STUDIOLIGHT_SH_BANDS; level++) {
488                 table_l[level] = (float)(SQUARE(level) * SQUARE(level + 1));
489
490                 float b = 0.0f;
491                 for (int m = -1; m <= level; m++) {
492                         b += SQUARE(sh[index++]);
493                 }
494                 table_b[level] = b;
495         }
496
497         float squared_lamplacian = 0.0f;
498         for (int level = 1; level < STUDIOLIGHT_SH_BANDS; level++) {
499                 squared_lamplacian += table_l[level] * table_b[level];
500         }
501
502         const float target_squared_laplacian = max_laplacian * max_laplacian;
503         if (squared_lamplacian <= target_squared_laplacian) {
504                 return lambda;
505         }
506
507         const int no_iterations = 10000000;
508         for (int i = 0; i < no_iterations; ++i) {
509                 float f = 0.0f;
510                 float fd = 0.0f;
511
512                 for (int level = 1; level < STUDIOLIGHT_SH_BANDS; ++level) {
513                         f += table_l[level] * table_b[level] / SQUARE(1.0f + lambda * table_l[level]);
514                         fd += (2.0f * SQUARE(table_l[level]) * table_b[level]) / CUBE(1.0f + lambda * table_l[level]);
515                 }
516
517                 f = target_squared_laplacian - f;
518
519                 float delta = -f / fd;
520                 lambda += delta;
521
522                 if (ABS(delta) < 1e-6f) {
523                         break;
524                 }
525         }
526
527         return lambda;
528 }
529
530 static void studiolight_spherical_harmonics_apply_windowing(float (*sh)[3], float max_laplacian)
531 {
532         if (max_laplacian <= 0.0f)
533                 return;
534
535         float sh_r[STUDIOLIGHT_SH_COEFS_LEN];
536         float sh_g[STUDIOLIGHT_SH_COEFS_LEN];
537         float sh_b[STUDIOLIGHT_SH_COEFS_LEN];
538         for (int i = 0; i < STUDIOLIGHT_SH_COEFS_LEN; i++) {
539                 sh_r[i] = sh[i][0];
540                 sh_g[i] = sh[i][1];
541                 sh_b[i] = sh[i][2];
542         }
543         float lambda_r = studiolight_spherical_harmonics_lambda_get(sh_r, max_laplacian);
544         float lambda_g = studiolight_spherical_harmonics_lambda_get(sh_g, max_laplacian);
545         float lambda_b = studiolight_spherical_harmonics_lambda_get(sh_b, max_laplacian);
546
547         /* Apply windowing lambda */
548         int index = 0;
549         for (int level = 0; level < STUDIOLIGHT_SH_BANDS; level++) {
550                 float s[3];
551                 s[0] = 1.0f / (1.0f + lambda_r * SQUARE(level) * SQUARE(level + 1.0f));
552                 s[1] = 1.0f / (1.0f + lambda_g * SQUARE(level) * SQUARE(level + 1.0f));
553                 s[2] = 1.0f / (1.0f + lambda_b * SQUARE(level) * SQUARE(level + 1.0f));
554
555                 for (int m = -1; m <= level; m++) {
556                         mul_v3_v3(sh[index++], s);
557                 }
558         }
559 }
560
561 static float studiolight_spherical_harmonics_geomerics_eval(const float normal[3], float sh0, float sh1, float sh2, float sh3)
562 {
563         /* Use Geomerics non-linear SH. */
564         /* http://www.geomerics.com/wp-content/uploads/2015/08/CEDEC_Geomerics_ReconstructingDiffuseLighting1.pdf */
565         float R0 = sh0 * M_1_PI;
566
567         float R1[3] = {-sh3, sh2, -sh1};
568         mul_v3_fl(R1, 0.5f * M_1_PI * 1.5f); /* 1.5f is to improve the contrast a bit. */
569         float lenR1 = len_v3(R1);
570         mul_v3_fl(R1, 1.0f / lenR1);
571         float q = 0.5f * (1.0f + dot_v3v3(R1, normal));
572
573         float p = 1.0f + 2.0f * lenR1 / R0;
574         float a = (1.0f - lenR1 / R0) / (1.0f + lenR1 / R0);
575
576         return R0 * (a + (1.0f - a) * (p + 1.0f) * powf(q, p));
577 }
578
579 BLI_INLINE void studiolight_spherical_harmonics_eval(StudioLight *sl, float color[3], const float normal[3])
580 {
581 #if STUDIOLIGHT_SH_BANDS == 2
582         float (*sh)[3] = (float (*)[3])sl->spherical_harmonics_coefs;
583         for (int i = 0; i < 3; ++i) {
584                 color[i] = studiolight_spherical_harmonics_geomerics_eval(normal, sh[0][i], sh[1][i], sh[2][i], sh[3][i]);
585         }
586         return;
587 #else
588
589         /* L0 */
590         mul_v3_v3fl(color, sl->spherical_harmonics_coefs[0], 0.282095f);
591 #  if STUDIOLIGHT_SH_BANDS > 1 /* L1 */
592         const float nx = normal[0];
593         const float ny = normal[1];
594         const float nz = normal[2];
595         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[1], -0.488603f * nz);
596         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[2],  0.488603f * ny);
597         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[3], -0.488603f * nx);
598 #  endif
599 #  if STUDIOLIGHT_SH_BANDS > 2 /* L2 */
600         const float nx2 = SQUARE(nx);
601         const float ny2 = SQUARE(ny);
602         const float nz2 = SQUARE(nz);
603         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[4], 1.092548f * nx * nz);
604         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[5], -1.092548f * nz * ny);
605         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[6], 0.315392f * (3.0f * ny2 - 1.0f));
606         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[7], -1.092548 * nx * ny);
607         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[8], 0.546274 * (nx2 - nz2));
608 #  endif
609         /* L3 coefs are 0 */
610 #  if STUDIOLIGHT_SH_BANDS > 4 /* L4 */
611         const float nx4 = SQUARE(nx2);
612         const float ny4 = SQUARE(ny2);
613         const float nz4 = SQUARE(nz2);
614         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[9],   2.5033429417967046f * nx * nz * (nx2 - nz2));
615         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[10], -1.7701307697799304f * nz * ny * (3.0f * nx2 - nz2));
616         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[11],  0.9461746957575601f * nz * nx * (-1.0f + 7.0f * ny2));
617         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[12], -0.6690465435572892f * nz * ny * (-3.0f + 7.0f * ny2));
618         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[13],  (105.0f * ny4 - 90.0f * ny2 + 9.0f) / 28.359261614f);
619         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[14], -0.6690465435572892f * nx * ny * (-3.0f + 7.0f * ny2));
620         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[15],  0.9461746957575601f * (nx2 - nz2) * (-1.0f + 7.0f * ny2));
621         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[16], -1.7701307697799304f * nx * ny * (nx2 - 3.0f * nz2));
622         madd_v3_v3fl(color, sl->spherical_harmonics_coefs[17],  0.6258357354491761f * (nx4 - 6.0f * nz2 * nx2 + nz4));
623 #  endif
624 #endif
625 }
626
627 /* This modify the radiance into irradiance. */
628 static void studiolight_spherical_harmonics_apply_band_factors(StudioLight *sl, float (*sh)[3])
629 {
630         static float sl_sh_band_factors[5] = {
631                 1.0f,
632                 2.0f / 3.0f,
633                 1.0f / 4.0f,
634                 0.0f,
635                 -1.0f / 24.0f
636         };
637
638         int index = 0, dst_idx = 0;
639         for (int band = 0; band < STUDIOLIGHT_SH_BANDS; band++) {
640                 for (int m = 0; m < SQUARE(band + 1) - SQUARE(band); m++) {
641                         /* Skip L3 */
642                         if (band != 3) {
643                                 mul_v3_v3fl(sl->spherical_harmonics_coefs[dst_idx++], sh[index], sl_sh_band_factors[band]);
644                         }
645                         index++;
646                 }
647         }
648 }
649
650 static void studiolight_calculate_diffuse_light(StudioLight *sl)
651 {
652         /* init light to black */
653         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
654                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED);
655
656                 float sh_coefs[STUDIOLIGHT_SH_COEFS_LEN][3];
657                 studiolight_spherical_harmonics_calculate_coefficients(sl, sh_coefs);
658                 studiolight_spherical_harmonics_apply_windowing(sh_coefs, STUDIOLIGHT_SH_WINDOWING);
659                 studiolight_spherical_harmonics_apply_band_factors(sl, sh_coefs);
660
661                 if (sl->flag & STUDIOLIGHT_USER_DEFINED) {
662                         FILE *fp = BLI_fopen(sl->path_sh_cache, "wb");
663                         if (fp) {
664                                 fwrite(sl->spherical_harmonics_coefs, sizeof(sl->spherical_harmonics_coefs), 1, fp);
665                                 fclose(fp);
666                         }
667                 }
668         }
669         sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED;
670 }
671
672 BLI_INLINE void studiolight_evaluate_specular_radiance_buffer(
673         ImBuf *radiance_buffer, const float normal[3], float color[3],
674         int xoffset, int yoffset, int zoffset, float zsign)
675 {
676         if (radiance_buffer == NULL) {
677                 return;
678         }
679
680         float accum[3] = {0.0f, 0.0f, 0.0f};
681         float accum_weight = 0.00001f;
682         ITER_PIXELS(float, radiance_buffer->rect_float, 4,
683                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE,
684                     STUDIOLIGHT_RADIANCE_CUBEMAP_SIZE)
685         {
686                 float direction[3];
687                 direction[zoffset] = zsign * 0.5f;
688                 direction[xoffset] = x - 0.5f;
689                 direction[yoffset] = y - 0.5f;
690                 normalize_v3(direction);
691                 float weight = dot_v3v3(direction, normal) > 0.95f ? 1.0f : 0.0f;
692                 // float solid_angle = texel_solid_angle(x, y, texel_size[0] * 0.5f);
693                 madd_v3_v3fl(accum, pixel, weight);
694                 accum_weight += weight;
695         }
696         ITER_PIXELS_END;
697
698         madd_v3_v3fl(color, accum, 1.0f / accum_weight);
699 }
700
701 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
702 static void studiolight_irradiance_eval(StudioLight *sl, float color[3], const float normal[3])
703 {
704         copy_v3_fl(color, 0.0f);
705
706         /* XXX: This is madness, iterating over all cubemap pixels for each destination pixels
707          * even if their weight is 0.0f.
708          * It should use hemisphere, cosine sampling at least. */
709
710         /* back */
711         studiolight_evaluate_specular_radiance_buffer(
712                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_POS], normal, color, 0, 2, 1, 1);
713         /* front */
714         studiolight_evaluate_specular_radiance_buffer(
715                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Y_NEG], normal, color, 0, 2, 1, -1);
716
717         /* left */
718         studiolight_evaluate_specular_radiance_buffer(
719                 sl->radiance_cubemap_buffers[STUDIOLIGHT_X_POS], normal, color, 1, 2, 0, 1);
720         /* right */
721         studiolight_evaluate_specular_radiance_buffer(
722                 sl->radiance_cubemap_buffers[STUDIOLIGHT_X_NEG], normal, color, 1, 2, 0, -1);
723
724         /* top */
725         studiolight_evaluate_specular_radiance_buffer(
726                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_POS], normal, color, 0, 1, 2, 1);
727         /* bottom */
728         studiolight_evaluate_specular_radiance_buffer(
729                 sl->radiance_cubemap_buffers[STUDIOLIGHT_Z_NEG], normal, color, 0, 1, 2, -1);
730
731         mul_v3_fl(color, 1.0 / M_PI);
732 }
733 #endif
734
735 static bool studiolight_load_irradiance_equirect_image(StudioLight *sl)
736 {
737 #ifdef STUDIOLIGHT_LOAD_CACHED_FILES
738         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
739                 ImBuf *ibuf = NULL;
740                 ibuf = IMB_loadiffname(sl->path_irr_cache, 0, NULL);
741                 if (ibuf) {
742                         IMB_float_from_rect(ibuf);
743                         sl->equirect_irradiance_buffer = ibuf;
744                         sl->flag |= STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED;
745                         return true;
746                 }
747         }
748 #else
749         UNUSED_VARS(sl);
750 #endif
751         return false;
752 }
753
754 static bool studiolight_load_spherical_harmonics_coefficients(StudioLight *sl)
755 {
756 #ifdef STUDIOLIGHT_LOAD_CACHED_FILES
757         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
758                 FILE *fp = BLI_fopen(sl->path_sh_cache, "rb");
759                 if (fp) {
760                         if (fread((void *)(sl->spherical_harmonics_coefs), sizeof(sl->spherical_harmonics_coefs), 1, fp)) {
761                                 sl->flag |= STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED;
762                                 fclose(fp);
763                                 return true;
764                         }
765                         fclose(fp);
766                 }
767         }
768 #else
769         UNUSED_VARS(sl);
770 #endif
771         return false;
772 }
773
774 static void studiolight_calculate_irradiance_equirect_image(StudioLight *sl)
775 {
776         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
777 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
778                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED);
779 #else
780                 BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED);
781 #endif
782
783                 float *colbuf = MEM_mallocN(STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH * STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT * sizeof(float[4]), __func__);
784
785                 ITER_PIXELS(float, colbuf, 4,
786                             STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH,
787                             STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT)
788                 {
789                         float dir[3];
790                         equirect_to_direction(dir, x, y);
791 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
792                         studiolight_irradiance_eval(sl, pixel, dir);
793 #else
794                         studiolight_spherical_harmonics_eval(sl, pixel, dir);
795 #endif
796                         pixel[3] = 1.0f;
797                 }
798                 ITER_PIXELS_END;
799
800                 sl->equirect_irradiance_buffer = IMB_allocFromBuffer(
801                         NULL, colbuf,
802                         STUDIOLIGHT_IRRADIANCE_EQUIRECT_WIDTH,
803                         STUDIOLIGHT_IRRADIANCE_EQUIRECT_HEIGHT);
804                 MEM_freeN(colbuf);
805
806 #ifdef STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
807                 /*
808                  * Only store cached files when using STUDIOLIGHT_IRRADIANCE_METHOD_RADIANCE
809                  */
810                 if (sl->flag & STUDIOLIGHT_USER_DEFINED) {
811                         IMB_saveiff(sl->equirect_irradiance_buffer, sl->path_irr_cache, IB_rectfloat);
812                 }
813 #endif
814         }
815         sl->flag |= STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED;
816 }
817
818 static StudioLight *studiolight_add_file(const char *path, int flag)
819 {
820         char filename[FILE_MAXFILE];
821         BLI_split_file_part(path, filename, FILE_MAXFILE);
822         if (BLI_path_extension_check_array(filename, imb_ext_image)) {
823                 StudioLight *sl = studiolight_create(STUDIOLIGHT_EXTERNAL_FILE | flag);
824                 BLI_strncpy(sl->name, filename, FILE_MAXFILE);
825                 BLI_strncpy(sl->path, path, FILE_MAXFILE);
826                 sl->path_irr_cache = BLI_string_joinN(path, ".irr");
827                 sl->path_sh_cache = BLI_string_joinN(path, ".sh2");
828                 BLI_addtail(&studiolights, sl);
829                 return sl;
830         }
831         return NULL;
832 }
833
834 static void studiolight_add_files_from_datafolder(const int folder_id, const char *subfolder, int flag)
835 {
836         struct direntry *dir;
837         const char *folder = BKE_appdir_folder_id(folder_id, subfolder);
838         if (folder) {
839                 uint totfile = BLI_filelist_dir_contents(folder, &dir);
840                 int i;
841                 for (i = 0; i < totfile; i++) {
842                         if ((dir[i].type & S_IFREG)) {
843                                 studiolight_add_file(dir[i].path, flag);
844                         }
845                 }
846                 BLI_filelist_free(dir, totfile);
847                 dir = NULL;
848         }
849 }
850
851 static int studiolight_flag_cmp_order(const StudioLight *sl)
852 {
853         /* Internal studiolights before external studio lights */
854         if (sl->flag & STUDIOLIGHT_EXTERNAL_FILE) {
855                 return 1;
856         }
857         return 0;
858 }
859
860 static int studiolight_cmp(const void *a, const void *b)
861 {
862         const StudioLight *sl1 = a;
863         const StudioLight *sl2 = b;
864
865         const int flagorder1 = studiolight_flag_cmp_order(sl1);
866         const int flagorder2 = studiolight_flag_cmp_order(sl2);
867
868         if (flagorder1 < flagorder2) {
869                 return -1;
870         }
871         else if (flagorder1 > flagorder2) {
872                 return 1;
873         }
874         else {
875                 return BLI_strcasecmp(sl1->name, sl2->name);
876         }
877 }
878
879 /* icons */
880
881 /* Takes normalized uvs as parameter (range from 0 to 1).
882  * inner_edge and outer_edge are distances (from the center)
883  * in uv space for the alpha mask falloff. */
884 static uint alpha_circle_mask(float u, float v, float inner_edge, float outer_edge)
885 {
886         /* Coords from center. */
887         float co[2] = {u - 0.5f, v - 0.5f};
888         float dist = len_v2(co);
889         float alpha = 1.0f + (inner_edge - dist) / (outer_edge - inner_edge);
890         uint mask = (uint)floorf(255.0f * min_ff(max_ff(alpha, 0.0f), 1.0f));
891         return mask << 24;
892 }
893
894 /* Percentage of the icon that the preview sphere covers. */
895 #define STUDIOLIGHT_DIAMETER 0.95f
896 /* Rescale coord around (0.5, 0.5) by STUDIOLIGHT_DIAMETER. */
897 #define RESCALE_COORD(x) (x / STUDIOLIGHT_DIAMETER - (1.0f - STUDIOLIGHT_DIAMETER) / 2.0f)
898
899 /* Remaps normalized UV [0..1] to a sphere normal around (0.5, 0.5) */
900 static void sphere_normal_from_uv(float normal[3], float u, float v)
901 {
902         normal[0] = u * 2.0f - 1.0f;
903         normal[1] = v * 2.0f - 1.0f;
904         float dist = len_v2(normal);
905         normal[2] = sqrtf(1.0f - SQUARE(dist));
906 }
907
908 static void studiolight_radiance_preview(uint *icon_buffer, StudioLight *sl)
909 {
910         BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
911
912         ITER_PIXELS(uint, icon_buffer, 1,
913                     STUDIOLIGHT_ICON_SIZE,
914                     STUDIOLIGHT_ICON_SIZE)
915         {
916                 float dy = RESCALE_COORD(y);
917                 float dx = RESCALE_COORD(x);
918
919                 uint alphamask = alpha_circle_mask(dx, dy, 0.5f - texel_size[0], 0.5f);
920                 if (alphamask != 0) {
921                         float normal[3], direction[3], color[4];
922                         float incoming[3] = {0.0f, 0.0f, -1.0f};
923                         sphere_normal_from_uv(normal, dx, dy);
924                         reflect_v3_v3v3(direction, incoming, normal);
925                         /* We want to see horizon not poles. */
926                         SWAP(float, direction[1], direction[2]);
927                         direction[1] = -direction[1];
928
929                         studiolight_calculate_radiance(sl->equirect_radiance_buffer, color, direction);
930
931                         *pixel = rgb_to_cpack(
932                                 linearrgb_to_srgb(color[0]),
933                                 linearrgb_to_srgb(color[1]),
934                                 linearrgb_to_srgb(color[2])) | alphamask;
935                 }
936                 else {
937                         *pixel = 0x0;
938                 }
939         }
940         ITER_PIXELS_END;
941 }
942
943 static void studiolight_matcap_preview(uint *icon_buffer, StudioLight *sl, bool flipped)
944 {
945         BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_EXTERNAL_IMAGE_LOADED);
946
947         ImBuf *ibuf = sl->equirect_radiance_buffer;
948
949         ITER_PIXELS(uint, icon_buffer, 1,
950                     STUDIOLIGHT_ICON_SIZE,
951                     STUDIOLIGHT_ICON_SIZE)
952         {
953                 float dy = RESCALE_COORD(y);
954                 float dx = RESCALE_COORD(x);
955                 if (flipped) {
956                         dx = 1.0f - dx;
957                 }
958
959                 float color[4];
960                 nearest_interpolation_color(ibuf, NULL, color, dx * ibuf->x - 1.0f, dy * ibuf->y - 1.0f);
961
962                 uint alphamask = alpha_circle_mask(dx, dy, 0.5f - texel_size[0], 0.5f);
963
964                 *pixel = rgb_to_cpack(
965                         linearrgb_to_srgb(color[0]),
966                         linearrgb_to_srgb(color[1]),
967                         linearrgb_to_srgb(color[2])) | alphamask;
968         }
969         ITER_PIXELS_END;
970 }
971
972 static void studiolight_irradiance_preview(uint *icon_buffer, StudioLight *sl)
973 {
974         BKE_studiolight_ensure_flag(sl, STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED);
975
976         ITER_PIXELS(uint, icon_buffer, 1,
977                     STUDIOLIGHT_ICON_SIZE,
978                     STUDIOLIGHT_ICON_SIZE)
979         {
980                 float dy = RESCALE_COORD(y);
981                 float dx = RESCALE_COORD(x);
982
983                 uint alphamask = alpha_circle_mask(dx, dy, 0.5f - texel_size[0], 0.5f);
984                 if (alphamask != 0) {
985                         float normal[3], color[3];
986                         sphere_normal_from_uv(normal, dx, dy);
987                         /* We want to see horizon not poles. */
988                         SWAP(float, normal[1], normal[2]);
989                         normal[1] = -normal[1];
990
991                         studiolight_spherical_harmonics_eval(sl, color, normal);
992
993                         *pixel = rgb_to_cpack(
994                                 linearrgb_to_srgb(color[0]),
995                                 linearrgb_to_srgb(color[1]),
996                                 linearrgb_to_srgb(color[2])) | alphamask;
997                 }
998                 else {
999                         *pixel = 0x0;
1000                 }
1001         }
1002         ITER_PIXELS_END;
1003 }
1004
1005 /* API */
1006 void BKE_studiolight_init(void)
1007 {
1008         StudioLight *sl;
1009         /* go over the preset folder and add a studiolight for every image with its path */
1010         /* order studio lights by name */
1011         /* Also reserve icon space for it. */
1012         /* Add default studio light */
1013         sl = studiolight_create(STUDIOLIGHT_INTERNAL | STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED | STUDIOLIGHT_ORIENTATION_CAMERA);
1014         BLI_strncpy(sl->name, "Default", FILE_MAXFILE);
1015
1016         int i = 0;
1017         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], 1.03271556f, 1.07163882f, 1.11193657f);
1018 #if STUDIOLIGHT_SH_BANDS > 1
1019         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], -0.00480952f, 0.05290511f, 0.16394117f);
1020         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], -0.29686999f, -0.27378261f, -0.24797194f);
1021         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], 0.47932500f, 0.48242140f, 0.47190312f);
1022 #endif
1023 #if STUDIOLIGHT_SH_BANDS > 2
1024         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], -0.00576984f, 0.00504886f, 0.01640534f);
1025         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], 0.15500379f, 0.15415503f, 0.16244425f);
1026         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], -0.02483751f, -0.02245096f, -0.00536885f);
1027         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], 0.11155496f, 0.11005443f, 0.10839636f);
1028         copy_v3_fl3(sl->spherical_harmonics_coefs[i++], 0.01363425f, 0.01278363f, -0.00159006f);
1029 #endif
1030
1031         BLI_addtail(&studiolights, sl);
1032
1033         studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_CAMERA_FOLDER, STUDIOLIGHT_ORIENTATION_CAMERA);
1034         studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES,   STUDIOLIGHT_CAMERA_FOLDER, STUDIOLIGHT_ORIENTATION_CAMERA | STUDIOLIGHT_USER_DEFINED);
1035         studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_WORLD_FOLDER,  STUDIOLIGHT_ORIENTATION_WORLD);
1036         studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES,   STUDIOLIGHT_WORLD_FOLDER,  STUDIOLIGHT_ORIENTATION_WORLD | STUDIOLIGHT_USER_DEFINED);
1037         studiolight_add_files_from_datafolder(BLENDER_SYSTEM_DATAFILES, STUDIOLIGHT_MATCAP_FOLDER, STUDIOLIGHT_ORIENTATION_VIEWNORMAL);
1038         studiolight_add_files_from_datafolder(BLENDER_USER_DATAFILES,   STUDIOLIGHT_MATCAP_FOLDER, STUDIOLIGHT_ORIENTATION_VIEWNORMAL | STUDIOLIGHT_USER_DEFINED);
1039
1040         /* sort studio lights on filename. */
1041         BLI_listbase_sort(&studiolights, studiolight_cmp);
1042 }
1043
1044 void BKE_studiolight_free(void)
1045 {
1046         struct StudioLight *sl;
1047         while ((sl = BLI_pophead(&studiolights))) {
1048                 studiolight_free(sl);
1049         }
1050 }
1051
1052 struct StudioLight *BKE_studiolight_find_first(int flag)
1053 {
1054         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1055                 if ((sl->flag & flag)) {
1056                         return sl;
1057                 }
1058         }
1059         return NULL;
1060 }
1061
1062 struct StudioLight *BKE_studiolight_find(const char *name, int flag)
1063 {
1064         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1065                 if (STREQLEN(sl->name, name, FILE_MAXFILE)) {
1066                         if ((sl->flag & flag)) {
1067                                 return sl;
1068                         }
1069                         else {
1070                                 /* flags do not match, so use default */
1071                                 return BKE_studiolight_find_first(flag);
1072                         }
1073                 }
1074         }
1075         /* When not found, use the default studio light */
1076         return BKE_studiolight_find_first(flag);
1077 }
1078
1079 struct StudioLight *BKE_studiolight_findindex(int index, int flag)
1080 {
1081         LISTBASE_FOREACH(StudioLight *, sl, &studiolights) {
1082                 if (sl->index == index) {
1083                         return sl;
1084                 }
1085         }
1086         /* When not found, use the default studio light */
1087         return BKE_studiolight_find_first(flag);
1088 }
1089
1090 struct ListBase *BKE_studiolight_listbase(void)
1091 {
1092         return &studiolights;
1093 }
1094
1095 void BKE_studiolight_preview(uint *icon_buffer, StudioLight *sl, int icon_id_type)
1096 {
1097         switch (icon_id_type) {
1098                 case STUDIOLIGHT_ICON_ID_TYPE_RADIANCE:
1099                 default:
1100                 {
1101                         studiolight_radiance_preview(icon_buffer, sl);
1102                         break;
1103                 }
1104                 case STUDIOLIGHT_ICON_ID_TYPE_IRRADIANCE:
1105                 {
1106                         studiolight_irradiance_preview(icon_buffer, sl);
1107                         break;
1108                 }
1109                 case STUDIOLIGHT_ICON_ID_TYPE_MATCAP:
1110                 {
1111                         studiolight_matcap_preview(icon_buffer, sl, false);
1112                         break;
1113                 }
1114                 case STUDIOLIGHT_ICON_ID_TYPE_MATCAP_FLIPPED:
1115                 {
1116                         studiolight_matcap_preview(icon_buffer, sl, true);
1117                         break;
1118                 }
1119         }
1120 }
1121
1122 /* Ensure state of Studiolights */
1123 void BKE_studiolight_ensure_flag(StudioLight *sl, int flag)
1124 {
1125         if ((sl->flag & flag) == flag) {
1126                 return;
1127         }
1128
1129         if ((flag & STUDIOLIGHT_EXTERNAL_IMAGE_LOADED)) {
1130                 studiolight_load_equirect_image(sl);
1131         }
1132         if ((flag & STUDIOLIGHT_RADIANCE_BUFFERS_CALCULATED)) {
1133                 studiolight_calculate_radiance_cubemap_buffers(sl);
1134         }
1135         if ((flag & STUDIOLIGHT_SPHERICAL_HARMONICS_COEFFICIENTS_CALCULATED)) {
1136                 if (!studiolight_load_spherical_harmonics_coefficients(sl)) {
1137                         studiolight_calculate_diffuse_light(sl);
1138                 }
1139         }
1140         if ((flag & STUDIOLIGHT_EQUIRECT_RADIANCE_GPUTEXTURE)) {
1141                 studiolight_create_equirect_radiance_gputexture(sl);
1142         }
1143         if ((flag & STUDIOLIGHT_EQUIRECT_IRRADIANCE_GPUTEXTURE)) {
1144                 studiolight_create_equirect_irradiance_gputexture(sl);
1145         }
1146         if ((flag & STUDIOLIGHT_EQUIRECT_IRRADIANCE_IMAGE_CALCULATED)) {
1147                 if (!studiolight_load_irradiance_equirect_image(sl)) {
1148                         studiolight_calculate_irradiance_equirect_image(sl);
1149                 }
1150         }
1151 }
1152
1153 /*
1154  * Python API Functions
1155  */
1156 void BKE_studiolight_remove(StudioLight *sl)
1157 {
1158         if (sl->flag & STUDIOLIGHT_USER_DEFINED) {
1159                 BLI_remlink(&studiolights, sl);
1160                 studiolight_free(sl);
1161         }
1162 }
1163
1164 StudioLight *BKE_studiolight_new(const char *path, int orientation)
1165 {
1166         StudioLight *sl = studiolight_add_file(path, orientation | STUDIOLIGHT_USER_DEFINED);
1167         return sl;
1168 }
1169
1170 void BKE_studiolight_refresh(void)
1171 {
1172         BKE_studiolight_free();
1173         BKE_studiolight_init();
1174 }
1175
1176 void BKE_studiolight_set_free_function(StudioLight *sl, StudioLightFreeFunction *free_function, void *data)
1177 {
1178         sl->free_function = free_function;
1179         sl->free_function_data = data;
1180 }
1181
1182 void BKE_studiolight_unset_icon_id(StudioLight *sl, int icon_id)
1183 {
1184         BLI_assert(sl != NULL);
1185         if (sl->icon_id_radiance == icon_id) {
1186                 sl->icon_id_radiance = 0;
1187         }
1188         if (sl->icon_id_irradiance == icon_id) {
1189                 sl->icon_id_irradiance = 0;
1190         }
1191         if (sl->icon_id_matcap == icon_id) {
1192                 sl->icon_id_matcap = 0;
1193         }
1194         if (sl->icon_id_matcap_flipped == icon_id) {
1195                 sl->icon_id_matcap_flipped = 0;
1196         }
1197 }