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