doxygen: add newline after \file
[blender.git] / source / blender / blenkernel / intern / camera.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License
4  * as published by the Free Software Foundation; either version 2
5  * of the License, or (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software Foundation,
14  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
15  *
16  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
17  * All rights reserved.
18  */
19
20 /** \file
21  * \ingroup bke
22  */
23
24 #include <stdlib.h>
25 #include <stddef.h>
26
27 #include "DNA_camera_types.h"
28 #include "DNA_lamp_types.h"
29 #include "DNA_object_types.h"
30 #include "DNA_scene_types.h"
31 #include "DNA_view3d_types.h"
32 #include "DNA_ID.h"
33
34 #include "BLI_math.h"
35 #include "BLI_listbase.h"
36 #include "BLI_rect.h"
37 #include "BLI_string.h"
38 #include "BLI_utildefines.h"
39
40 #include "BKE_animsys.h"
41 #include "BKE_camera.h"
42 #include "BKE_object.h"
43 #include "BKE_layer.h"
44 #include "BKE_library.h"
45 #include "BKE_main.h"
46 #include "BKE_scene.h"
47 #include "BKE_screen.h"
48
49 #include "DEG_depsgraph_query.h"
50
51 #include "MEM_guardedalloc.h"
52
53 /****************************** Camera Datablock *****************************/
54
55 void BKE_camera_init(Camera *cam)
56 {
57         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(cam, id));
58
59         cam->lens = 50.0f;
60         cam->sensor_x = DEFAULT_SENSOR_WIDTH;
61         cam->sensor_y = DEFAULT_SENSOR_HEIGHT;
62         cam->clip_start = 0.1f;
63         cam->clip_end = 1000.0f;
64         cam->drawsize = 1.0f;
65         cam->ortho_scale = 6.0;
66         cam->flag |= CAM_SHOWPASSEPARTOUT;
67         cam->passepartalpha = 0.5f;
68
69         cam->gpu_dof.fstop = 128.0f;
70         cam->gpu_dof.ratio = 1.0f;
71
72         /* stereoscopy 3d */
73         cam->stereo.interocular_distance = 0.065f;
74         cam->stereo.convergence_distance = 30.f * 0.065f;
75         cam->stereo.pole_merge_angle_from = DEG2RADF(60.0f);
76         cam->stereo.pole_merge_angle_to = DEG2RADF(75.0f);
77 }
78
79 void *BKE_camera_add(Main *bmain, const char *name)
80 {
81         Camera *cam;
82
83         cam =  BKE_libblock_alloc(bmain, ID_CA, name, 0);
84
85         BKE_camera_init(cam);
86
87         return cam;
88 }
89
90 /**
91  * Only copy internal data of Camera ID from source to already allocated/initialized destination.
92  * You probably never want to use that directly, use BKE_id_copy or BKE_id_copy_ex for typical needs.
93  *
94  * WARNING! This function will not handle ID user count!
95  *
96  * \param flag: Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
97  */
98 void BKE_camera_copy_data(Main *UNUSED(bmain), Camera *cam_dst, const Camera *cam_src, const int UNUSED(flag))
99 {
100         BLI_duplicatelist(&cam_dst->bg_images, &cam_src->bg_images);
101 }
102
103 Camera *BKE_camera_copy(Main *bmain, const Camera *cam)
104 {
105         Camera *cam_copy;
106         BKE_id_copy(bmain, &cam->id, (ID **)&cam_copy);
107         return cam_copy;
108 }
109
110 void BKE_camera_make_local(Main *bmain, Camera *cam, const bool lib_local)
111 {
112         BKE_id_make_local_generic(bmain, &cam->id, true, lib_local);
113 }
114
115 /** Free (or release) any data used by this camera (does not free the camera itself). */
116 void BKE_camera_free(Camera *ca)
117 {
118         BLI_freelistN(&ca->bg_images);
119
120         BKE_animdata_free((ID *)ca, false);
121 }
122
123 /******************************** Camera Usage *******************************/
124
125 /* get the camera's dof value, takes the dof object into account */
126 float BKE_camera_object_dof_distance(Object *ob)
127 {
128         Camera *cam = (Camera *)ob->data;
129         if (ob->type != OB_CAMERA)
130                 return 0.0f;
131         if (cam->dof_ob) {
132                 float view_dir[3], dof_dir[3];
133                 normalize_v3_v3(view_dir, ob->obmat[2]);
134                 sub_v3_v3v3(dof_dir, ob->obmat[3], cam->dof_ob->obmat[3]);
135                 return fabsf(dot_v3v3(view_dir, dof_dir));
136         }
137         return cam->dof_distance;
138 }
139
140 float BKE_camera_sensor_size(int sensor_fit, float sensor_x, float sensor_y)
141 {
142         /* sensor size used to fit to. for auto, sensor_x is both x and y. */
143         if (sensor_fit == CAMERA_SENSOR_FIT_VERT)
144                 return sensor_y;
145
146         return sensor_x;
147 }
148
149 int BKE_camera_sensor_fit(int sensor_fit, float sizex, float sizey)
150 {
151         if (sensor_fit == CAMERA_SENSOR_FIT_AUTO) {
152                 if (sizex >= sizey)
153                         return CAMERA_SENSOR_FIT_HOR;
154                 else
155                         return CAMERA_SENSOR_FIT_VERT;
156         }
157
158         return sensor_fit;
159 }
160
161 /******************************** Camera Params *******************************/
162
163 void BKE_camera_params_init(CameraParams *params)
164 {
165         memset(params, 0, sizeof(CameraParams));
166
167         /* defaults */
168         params->sensor_x = DEFAULT_SENSOR_WIDTH;
169         params->sensor_y = DEFAULT_SENSOR_HEIGHT;
170         params->sensor_fit = CAMERA_SENSOR_FIT_AUTO;
171
172         params->zoom = 1.0f;
173
174         /* fallback for non camera objects */
175         params->clip_start = 0.1f;
176         params->clip_end = 100.0f;
177 }
178
179 void BKE_camera_params_from_object(CameraParams *params, const Object *ob)
180 {
181         if (!ob)
182                 return;
183
184         if (ob->type == OB_CAMERA) {
185                 /* camera object */
186                 Camera *cam = ob->data;
187
188                 if (cam->type == CAM_ORTHO)
189                         params->is_ortho = true;
190                 params->lens = cam->lens;
191                 params->ortho_scale = cam->ortho_scale;
192
193                 params->shiftx = cam->shiftx;
194                 params->shifty = cam->shifty;
195
196                 params->sensor_x = cam->sensor_x;
197                 params->sensor_y = cam->sensor_y;
198                 params->sensor_fit = cam->sensor_fit;
199
200                 params->clip_start = cam->clip_start;
201                 params->clip_end = cam->clip_end;
202         }
203         else if (ob->type == OB_LAMP) {
204                 /* lamp object */
205                 Lamp *la = ob->data;
206                 params->lens = 16.0f / tanf(la->spotsize * 0.5f);
207                 if (params->lens == 0.0f)
208                         params->lens = 35.0f;
209
210                 params->clip_start = la->clipsta;
211                 params->clip_end = la->clipend;
212         }
213         else {
214                 params->lens = 35.0f;
215         }
216 }
217
218 void BKE_camera_params_from_view3d(CameraParams *params, Depsgraph *depsgraph, const View3D *v3d, const RegionView3D *rv3d)
219 {
220         /* common */
221         params->lens = v3d->lens;
222         params->clip_start = v3d->clip_start;
223         params->clip_end = v3d->clip_end;
224
225         if (rv3d->persp == RV3D_CAMOB) {
226                 /* camera view */
227                 const Object *ob_camera_eval = DEG_get_evaluated_object(depsgraph, v3d->camera);
228                 BKE_camera_params_from_object(params, ob_camera_eval);
229
230                 params->zoom = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
231
232                 params->offsetx = 2.0f * rv3d->camdx * params->zoom;
233                 params->offsety = 2.0f * rv3d->camdy * params->zoom;
234
235                 params->shiftx *= params->zoom;
236                 params->shifty *= params->zoom;
237
238                 params->zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB / params->zoom;
239         }
240         else if (rv3d->persp == RV3D_ORTHO) {
241                 /* orthographic view */
242                 float sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
243                 params->clip_end *= 0.5f;    // otherwise too extreme low zbuffer quality
244                 params->clip_start = -params->clip_start;
245
246                 params->is_ortho = true;
247                 /* make sure any changes to this match ED_view3d_radius_to_dist_ortho() */
248                 params->ortho_scale = rv3d->dist * sensor_size / v3d->lens;
249                 params->zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
250         }
251         else {
252                 /* perspective view */
253                 params->zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
254         }
255 }
256
257 void BKE_camera_params_compute_viewplane(CameraParams *params, int winx, int winy, float xasp, float yasp)
258 {
259         rctf viewplane;
260         float pixsize, viewfac, sensor_size, dx, dy;
261         int sensor_fit;
262
263         params->ycor = yasp / xasp;
264
265         if (params->is_ortho) {
266                 /* orthographic camera */
267                 /* scale == 1.0 means exact 1 to 1 mapping */
268                 pixsize = params->ortho_scale;
269         }
270         else {
271                 /* perspective camera */
272                 sensor_size = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y);
273                 pixsize = (sensor_size * params->clip_start) / params->lens;
274         }
275
276         /* determine sensor fit */
277         sensor_fit = BKE_camera_sensor_fit(params->sensor_fit, xasp * winx, yasp * winy);
278
279         if (sensor_fit == CAMERA_SENSOR_FIT_HOR)
280                 viewfac = winx;
281         else
282                 viewfac = params->ycor * winy;
283
284         pixsize /= viewfac;
285
286         /* extra zoom factor */
287         pixsize *= params->zoom;
288
289         /* compute view plane:
290          * fully centered, zbuffer fills in jittered between -.5 and +.5 */
291         viewplane.xmin = -0.5f * (float)winx;
292         viewplane.ymin = -0.5f * params->ycor * (float)winy;
293         viewplane.xmax =  0.5f * (float)winx;
294         viewplane.ymax =  0.5f * params->ycor * (float)winy;
295
296         /* lens shift and offset */
297         dx = params->shiftx * viewfac + winx * params->offsetx;
298         dy = params->shifty * viewfac + winy * params->offsety;
299
300         viewplane.xmin += dx;
301         viewplane.ymin += dy;
302         viewplane.xmax += dx;
303         viewplane.ymax += dy;
304
305         /* the window matrix is used for clipping, and not changed during OSA steps */
306         /* using an offset of +0.5 here would give clip errors on edges */
307         viewplane.xmin *= pixsize;
308         viewplane.xmax *= pixsize;
309         viewplane.ymin *= pixsize;
310         viewplane.ymax *= pixsize;
311
312         /* Used for rendering (offset by near-clip with perspective views), passed to RE_SetPixelSize.
313          * For viewport drawing 'RegionView3D.pixsize'. */
314         params->viewdx = pixsize;
315         params->viewdy = params->ycor * pixsize;
316         params->viewplane = viewplane;
317 }
318
319 /* viewplane is assumed to be already computed */
320 void BKE_camera_params_compute_matrix(CameraParams *params)
321 {
322         rctf viewplane = params->viewplane;
323
324         /* compute projection matrix */
325         if (params->is_ortho)
326                 orthographic_m4(params->winmat, viewplane.xmin, viewplane.xmax,
327                                 viewplane.ymin, viewplane.ymax, params->clip_start, params->clip_end);
328         else
329                 perspective_m4(params->winmat, viewplane.xmin, viewplane.xmax,
330                                viewplane.ymin, viewplane.ymax, params->clip_start, params->clip_end);
331 }
332
333 /***************************** Camera View Frame *****************************/
334
335 void BKE_camera_view_frame_ex(
336         const Scene *scene, const Camera *camera,
337         const float drawsize, const bool do_clip, const float scale[3],
338         float r_asp[2], float r_shift[2], float *r_drawsize, float r_vec[4][3])
339 {
340         float facx, facy;
341         float depth;
342
343         /* aspect correcton */
344         if (scene) {
345                 float aspx = (float) scene->r.xsch * scene->r.xasp;
346                 float aspy = (float) scene->r.ysch * scene->r.yasp;
347                 int sensor_fit = BKE_camera_sensor_fit(camera->sensor_fit, aspx, aspy);
348
349                 if (sensor_fit == CAMERA_SENSOR_FIT_HOR) {
350                         r_asp[0] = 1.0;
351                         r_asp[1] = aspy / aspx;
352                 }
353                 else {
354                         r_asp[0] = aspx / aspy;
355                         r_asp[1] = 1.0;
356                 }
357         }
358         else {
359                 r_asp[0] = 1.0f;
360                 r_asp[1] = 1.0f;
361         }
362
363         if (camera->type == CAM_ORTHO) {
364                 facx = 0.5f * camera->ortho_scale * r_asp[0] * scale[0];
365                 facy = 0.5f * camera->ortho_scale * r_asp[1] * scale[1];
366                 r_shift[0] = camera->shiftx * camera->ortho_scale * scale[0];
367                 r_shift[1] = camera->shifty * camera->ortho_scale * scale[1];
368                 depth = do_clip ? -((camera->clip_start * scale[2]) + 0.1f) : -drawsize * scale[2];
369
370                 *r_drawsize = 0.5f * camera->ortho_scale;
371         }
372         else {
373                 /* that way it's always visible - clip_start+0.1 */
374                 float fac, scale_x, scale_y;
375                 float half_sensor = 0.5f * ((camera->sensor_fit == CAMERA_SENSOR_FIT_VERT) ?
376                                             (camera->sensor_y) : (camera->sensor_x));
377
378
379                 if (do_clip) {
380                         /* fixed depth, variable size (avoids exceeding clipping range) */
381                         /* r_drawsize shouldn't be used in this case, set to dummy value */
382                         *r_drawsize = 1.0f;
383                         depth = -(camera->clip_start + 0.1f) * scale[2];
384                         fac = depth / (camera->lens / (-half_sensor));
385                         scale_x = scale[0] / scale[2];
386                         scale_y = scale[1] / scale[2];
387                 }
388                 else {
389                         /* fixed size, variable depth (stays a reasonable size in the 3D view) */
390                         *r_drawsize = (drawsize / 2.0f) / ((scale[0] + scale[1] + scale[2]) / 3.0f);
391                         depth = *r_drawsize * camera->lens / (-half_sensor) * scale[2];
392                         fac = *r_drawsize;
393                         scale_x = scale[0];
394                         scale_y = scale[1];
395                 }
396
397                 facx = fac * r_asp[0] * scale_x;
398                 facy = fac * r_asp[1] * scale_y;
399                 r_shift[0] = camera->shiftx * fac * 2.0f * scale_x;
400                 r_shift[1] = camera->shifty * fac * 2.0f * scale_y;
401         }
402
403         r_vec[0][0] = r_shift[0] + facx; r_vec[0][1] = r_shift[1] + facy; r_vec[0][2] = depth;
404         r_vec[1][0] = r_shift[0] + facx; r_vec[1][1] = r_shift[1] - facy; r_vec[1][2] = depth;
405         r_vec[2][0] = r_shift[0] - facx; r_vec[2][1] = r_shift[1] - facy; r_vec[2][2] = depth;
406         r_vec[3][0] = r_shift[0] - facx; r_vec[3][1] = r_shift[1] + facy; r_vec[3][2] = depth;
407 }
408
409 void BKE_camera_view_frame(const Scene *scene, const Camera *camera, float r_vec[4][3])
410 {
411         float dummy_asp[2];
412         float dummy_shift[2];
413         float dummy_drawsize;
414         const float dummy_scale[3] = {1.0f, 1.0f, 1.0f};
415
416         BKE_camera_view_frame_ex(scene, camera, 0.0, true, dummy_scale,
417                                  dummy_asp, dummy_shift, &dummy_drawsize, r_vec);
418 }
419
420 #define CAMERA_VIEWFRAME_NUM_PLANES 4
421
422 typedef struct CameraViewFrameData {
423         float plane_tx[CAMERA_VIEWFRAME_NUM_PLANES][4];  /* 4 planes */
424         float normal_tx[CAMERA_VIEWFRAME_NUM_PLANES][3];
425         float dist_vals_sq[CAMERA_VIEWFRAME_NUM_PLANES];  /* distance squared (signed) */
426         unsigned int tot;
427
428         /* Ortho camera only. */
429         bool is_ortho;
430         float camera_no[3];
431         float dist_to_cam;
432
433         /* Not used by callbacks... */
434         float camera_rotmat[3][3];
435 } CameraViewFrameData;
436
437 static void camera_to_frame_view_cb(const float co[3], void *user_data)
438 {
439         CameraViewFrameData *data = (CameraViewFrameData *)user_data;
440         unsigned int i;
441
442         for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
443                 const float nd = dist_signed_squared_to_plane_v3(co, data->plane_tx[i]);
444                 CLAMP_MAX(data->dist_vals_sq[i], nd);
445         }
446
447         if (data->is_ortho) {
448                 const float d = dot_v3v3(data->camera_no, co);
449                 CLAMP_MAX(data->dist_to_cam, d);
450         }
451
452         data->tot++;
453 }
454
455 static void camera_frame_fit_data_init(
456         const Scene *scene, const Object *ob,
457         CameraParams *params, CameraViewFrameData *data)
458 {
459         float camera_rotmat_transposed_inversed[4][4];
460         unsigned int i;
461
462         /* setup parameters */
463         BKE_camera_params_init(params);
464         BKE_camera_params_from_object(params, ob);
465
466         /* compute matrix, viewplane, .. */
467         if (scene) {
468                 BKE_camera_params_compute_viewplane(params, scene->r.xsch, scene->r.ysch, scene->r.xasp, scene->r.yasp);
469         }
470         else {
471                 BKE_camera_params_compute_viewplane(params, 1, 1, 1.0f, 1.0f);
472         }
473         BKE_camera_params_compute_matrix(params);
474
475         /* initialize callback data */
476         copy_m3_m4(data->camera_rotmat, (float (*)[4])ob->obmat);
477         normalize_m3(data->camera_rotmat);
478         /* To transform a plane which is in its homogeneous representation (4d vector),
479          * we need the inverse of the transpose of the transform matrix... */
480         copy_m4_m3(camera_rotmat_transposed_inversed, data->camera_rotmat);
481         transpose_m4(camera_rotmat_transposed_inversed);
482         invert_m4(camera_rotmat_transposed_inversed);
483
484         /* Extract frustum planes from projection matrix. */
485         planes_from_projmat(params->winmat,
486                             /*   left              right                 top              bottom        near  far */
487                             data->plane_tx[2], data->plane_tx[0], data->plane_tx[3], data->plane_tx[1], NULL, NULL);
488
489         /* Rotate planes and get normals from them */
490         for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
491                 mul_m4_v4(camera_rotmat_transposed_inversed, data->plane_tx[i]);
492                 normalize_v3_v3(data->normal_tx[i], data->plane_tx[i]);
493         }
494
495         copy_v4_fl(data->dist_vals_sq, FLT_MAX);
496         data->tot = 0;
497         data->is_ortho = params->is_ortho;
498         if (params->is_ortho) {
499                 /* we want (0, 0, -1) transformed by camera_rotmat, this is a quicker shortcut. */
500                 negate_v3_v3(data->camera_no, data->camera_rotmat[2]);
501                 data->dist_to_cam = FLT_MAX;
502         }
503 }
504
505 static bool camera_frame_fit_calc_from_data(
506         CameraParams *params, CameraViewFrameData *data, float r_co[3], float *r_scale)
507 {
508         float plane_tx[CAMERA_VIEWFRAME_NUM_PLANES][4];
509         unsigned int i;
510
511         if (data->tot <= 1) {
512                 return false;
513         }
514
515         if (params->is_ortho) {
516                 const float *cam_axis_x = data->camera_rotmat[0];
517                 const float *cam_axis_y = data->camera_rotmat[1];
518                 const float *cam_axis_z = data->camera_rotmat[2];
519                 float dists[CAMERA_VIEWFRAME_NUM_PLANES];
520                 float scale_diff;
521
522                 /* apply the dist-from-plane's to the transformed plane points */
523                 for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
524                         dists[i] = sqrtf_signed(data->dist_vals_sq[i]);
525                 }
526
527                 if ((dists[0] + dists[2]) > (dists[1] + dists[3])) {
528                         scale_diff = (dists[1] + dists[3]) *
529                                      (BLI_rctf_size_x(&params->viewplane) / BLI_rctf_size_y(&params->viewplane));
530                 }
531                 else {
532                         scale_diff = (dists[0] + dists[2]) *
533                                      (BLI_rctf_size_y(&params->viewplane) / BLI_rctf_size_x(&params->viewplane));
534                 }
535                 *r_scale = params->ortho_scale - scale_diff;
536
537                 zero_v3(r_co);
538                 madd_v3_v3fl(r_co, cam_axis_x, (dists[2] - dists[0]) * 0.5f + params->shiftx * scale_diff);
539                 madd_v3_v3fl(r_co, cam_axis_y, (dists[1] - dists[3]) * 0.5f + params->shifty * scale_diff);
540                 madd_v3_v3fl(r_co, cam_axis_z, -(data->dist_to_cam - 1.0f - params->clip_start));
541
542                 return true;
543         }
544         else {
545                 float plane_isect_1[3], plane_isect_1_no[3], plane_isect_1_other[3];
546                 float plane_isect_2[3], plane_isect_2_no[3], plane_isect_2_other[3];
547
548                 float plane_isect_pt_1[3], plane_isect_pt_2[3];
549
550                 /* apply the dist-from-plane's to the transformed plane points */
551                 for (i = 0; i < CAMERA_VIEWFRAME_NUM_PLANES; i++) {
552                         float co[3];
553                         mul_v3_v3fl(co, data->normal_tx[i], sqrtf_signed(data->dist_vals_sq[i]));
554                         plane_from_point_normal_v3(plane_tx[i], co, data->normal_tx[i]);
555                 }
556
557                 if ((!isect_plane_plane_v3(plane_tx[0], plane_tx[2], plane_isect_1, plane_isect_1_no)) ||
558                     (!isect_plane_plane_v3(plane_tx[1], plane_tx[3], plane_isect_2, plane_isect_2_no)))
559                 {
560                         return false;
561                 }
562
563                 add_v3_v3v3(plane_isect_1_other, plane_isect_1, plane_isect_1_no);
564                 add_v3_v3v3(plane_isect_2_other, plane_isect_2, plane_isect_2_no);
565
566                 if (isect_line_line_v3(plane_isect_1, plane_isect_1_other,
567                                        plane_isect_2, plane_isect_2_other,
568                                        plane_isect_pt_1, plane_isect_pt_2) != 0)
569                 {
570                         float cam_plane_no[3];
571                         float plane_isect_delta[3];
572                         float plane_isect_delta_len;
573
574                         float shift_fac = BKE_camera_sensor_size(params->sensor_fit, params->sensor_x, params->sensor_y) /
575                                           params->lens;
576
577                         /* we want (0, 0, -1) transformed by camera_rotmat, this is a quicker shortcut. */
578                         negate_v3_v3(cam_plane_no, data->camera_rotmat[2]);
579
580                         sub_v3_v3v3(plane_isect_delta, plane_isect_pt_2, plane_isect_pt_1);
581                         plane_isect_delta_len = len_v3(plane_isect_delta);
582
583                         if (dot_v3v3(plane_isect_delta, cam_plane_no) > 0.0f) {
584                                 copy_v3_v3(r_co, plane_isect_pt_1);
585
586                                 /* offset shift */
587                                 normalize_v3(plane_isect_1_no);
588                                 madd_v3_v3fl(r_co, plane_isect_1_no, params->shifty * plane_isect_delta_len * shift_fac);
589                         }
590                         else {
591                                 copy_v3_v3(r_co, plane_isect_pt_2);
592
593                                 /* offset shift */
594                                 normalize_v3(plane_isect_2_no);
595                                 madd_v3_v3fl(r_co, plane_isect_2_no, params->shiftx * plane_isect_delta_len * shift_fac);
596                         }
597
598                         return true;
599                 }
600         }
601
602         return false;
603 }
604
605 /* don't move the camera, just yield the fit location */
606 /* r_scale only valid/useful for ortho cameras */
607 bool BKE_camera_view_frame_fit_to_scene(
608         Depsgraph *depsgraph, Scene *scene, Object *camera_ob, float r_co[3], float *r_scale)
609 {
610         CameraParams params;
611         CameraViewFrameData data_cb;
612
613         /* just in case */
614         *r_scale = 1.0f;
615
616         camera_frame_fit_data_init(scene, camera_ob, &params, &data_cb);
617
618         /* run callback on all visible points */
619         BKE_scene_foreach_display_point(depsgraph, camera_to_frame_view_cb, &data_cb);
620
621         return camera_frame_fit_calc_from_data(&params, &data_cb, r_co, r_scale);
622 }
623
624 bool BKE_camera_view_frame_fit_to_coords(
625         const Depsgraph *depsgraph, const float (*cos)[3], int num_cos, Object *camera_ob,
626         float r_co[3], float *r_scale)
627 {
628         Scene *scene_eval = DEG_get_evaluated_scene(depsgraph);
629         Object *camera_ob_eval = DEG_get_evaluated_object(depsgraph, camera_ob);
630         CameraParams params;
631         CameraViewFrameData data_cb;
632
633         /* just in case */
634         *r_scale = 1.0f;
635
636         camera_frame_fit_data_init(scene_eval, camera_ob_eval, &params, &data_cb);
637
638         /* run callback on all given coordinates */
639         while (num_cos--) {
640                 camera_to_frame_view_cb(cos[num_cos], &data_cb);
641         }
642
643         return camera_frame_fit_calc_from_data(&params, &data_cb, r_co, r_scale);
644 }
645
646 /******************* multiview matrix functions ***********************/
647
648 static void camera_model_matrix(const Object *camera, float r_modelmat[4][4])
649 {
650         copy_m4_m4(r_modelmat, camera->obmat);
651 }
652
653 static void camera_stereo3d_model_matrix(const Object *camera, const bool is_left, float r_modelmat[4][4])
654 {
655         Camera *data = (Camera *)camera->data;
656         float interocular_distance, convergence_distance;
657         short convergence_mode, pivot;
658         float sizemat[4][4];
659
660         float fac = 1.0f;
661         float fac_signed;
662
663         interocular_distance = data->stereo.interocular_distance;
664         convergence_distance = data->stereo.convergence_distance;
665         convergence_mode = data->stereo.convergence_mode;
666         pivot = data->stereo.pivot;
667
668         if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) ||
669             ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left))
670         {
671                 camera_model_matrix(camera, r_modelmat);
672                 return;
673         }
674         else {
675                 float size[3];
676                 mat4_to_size(size, camera->obmat);
677                 size_to_mat4(sizemat, size);
678         }
679
680         if (pivot == CAM_S3D_PIVOT_CENTER)
681                 fac = 0.5f;
682
683         fac_signed = is_left ? fac : -fac;
684
685         /* rotation */
686         if (convergence_mode == CAM_S3D_TOE) {
687                 float angle;
688                 float angle_sin, angle_cos;
689                 float toeinmat[4][4];
690                 float rotmat[4][4];
691
692                 unit_m4(rotmat);
693
694                 if (pivot == CAM_S3D_PIVOT_CENTER) {
695                         fac = -fac;
696                         fac_signed = -fac_signed;
697                 }
698
699                 angle = atanf((interocular_distance * 0.5f) / convergence_distance) / fac;
700
701                 angle_cos = cosf(angle * fac_signed);
702                 angle_sin = sinf(angle * fac_signed);
703
704                 rotmat[0][0] =  angle_cos;
705                 rotmat[2][0] = -angle_sin;
706                 rotmat[0][2] =  angle_sin;
707                 rotmat[2][2] =  angle_cos;
708
709                 if (pivot == CAM_S3D_PIVOT_CENTER) {
710                         /* set the rotation */
711                         copy_m4_m4(toeinmat, rotmat);
712                         /* set the translation */
713                         toeinmat[3][0] = interocular_distance * fac_signed;
714
715                         /* transform */
716                         normalize_m4_m4(r_modelmat, camera->obmat);
717                         mul_m4_m4m4(r_modelmat, r_modelmat, toeinmat);
718
719                         /* scale back to the original size */
720                         mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
721                 }
722                 else { /* CAM_S3D_PIVOT_LEFT, CAM_S3D_PIVOT_RIGHT */
723                         /* rotate perpendicular to the interocular line */
724                         normalize_m4_m4(r_modelmat, camera->obmat);
725                         mul_m4_m4m4(r_modelmat, r_modelmat, rotmat);
726
727                         /* translate along the interocular line */
728                         unit_m4(toeinmat);
729                         toeinmat[3][0] = -interocular_distance * fac_signed;
730                         mul_m4_m4m4(r_modelmat, r_modelmat, toeinmat);
731
732                         /* rotate to toe-in angle */
733                         mul_m4_m4m4(r_modelmat, r_modelmat, rotmat);
734
735                         /* scale back to the original size */
736                         mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
737                 }
738         }
739         else {
740                 normalize_m4_m4(r_modelmat, camera->obmat);
741
742                 /* translate - no rotation in CAM_S3D_OFFAXIS, CAM_S3D_PARALLEL */
743                 translate_m4(r_modelmat, -interocular_distance * fac_signed, 0.0f, 0.0f);
744
745                 /* scale back to the original size */
746                 mul_m4_m4m4(r_modelmat, r_modelmat, sizemat);
747         }
748 }
749
750 /* the view matrix is used by the viewport drawing, it is basically the inverted model matrix */
751 void BKE_camera_multiview_view_matrix(RenderData *rd, const Object *camera, const bool is_left, float r_viewmat[4][4])
752 {
753         BKE_camera_multiview_model_matrix(rd, camera, is_left ? STEREO_LEFT_NAME : STEREO_RIGHT_NAME, r_viewmat);
754         invert_m4(r_viewmat);
755 }
756
757 /* left is the default */
758 static bool camera_is_left(const char *viewname)
759 {
760         if (viewname && viewname[0] != '\0') {
761                 return !STREQ(viewname, STEREO_RIGHT_NAME);
762         }
763         return true;
764 }
765
766 void BKE_camera_multiview_model_matrix(RenderData *rd, const Object *camera, const char *viewname, float r_modelmat[4][4])
767 {
768         BKE_camera_multiview_model_matrix_scaled(rd, camera, viewname, r_modelmat);
769         normalize_m4(r_modelmat);
770 }
771
772 void BKE_camera_multiview_model_matrix_scaled(RenderData *rd, const Object *camera, const char *viewname, float r_modelmat[4][4])
773 {
774         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
775
776         if (!is_multiview) {
777                 camera_model_matrix(camera, r_modelmat);
778         }
779         else if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
780                 camera_model_matrix(camera, r_modelmat);
781         }
782         else { /* SCE_VIEWS_SETUP_BASIC */
783                 const bool is_left = camera_is_left(viewname);
784                 camera_stereo3d_model_matrix(camera, is_left, r_modelmat);
785         }
786 }
787
788 void BKE_camera_multiview_window_matrix(RenderData *rd, const Object *camera, const char *viewname, float r_winmat[4][4])
789 {
790         CameraParams params;
791
792         /* Setup parameters */
793         BKE_camera_params_init(&params);
794         BKE_camera_params_from_object(&params, camera);
795         BKE_camera_multiview_params(rd, &params, camera, viewname);
796
797         /* Compute matrix, viewplane, .. */
798         BKE_camera_params_compute_viewplane(&params, rd->xsch, rd->ysch, rd->xasp, rd->yasp);
799         BKE_camera_params_compute_matrix(&params);
800
801         copy_m4_m4(r_winmat, params.winmat);
802 }
803
804 bool BKE_camera_multiview_spherical_stereo(RenderData *rd, const Object *camera)
805 {
806         Camera *cam;
807         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
808
809         if (!is_multiview)
810                 return false;
811
812         if (camera->type != OB_CAMERA)
813                 return false;
814         else
815                 cam = camera->data;
816
817         if ((rd->views_format == SCE_VIEWS_FORMAT_STEREO_3D) &&
818             ELEM(cam->type, CAM_PANO, CAM_PERSP) &&
819             ((cam->stereo.flag & CAM_S3D_SPHERICAL) != 0))
820         {
821                 return true;
822         }
823
824         return false;
825 }
826
827 static Object *camera_multiview_advanced(Scene *scene, Object *camera, const char *suffix)
828 {
829         SceneRenderView *srv;
830         char name[MAX_NAME];
831         const char *camera_name = camera->id.name + 2;
832         const int len_name = strlen(camera_name);
833         int len_suffix_max = -1;
834
835         name[0] = '\0';
836
837         /* we need to take the better match, thus the len_suffix_max test */
838         for (srv = scene->r.views.first; srv; srv = srv->next) {
839                 const int len_suffix = strlen(srv->suffix);
840
841                 if ((len_suffix < len_suffix_max) || (len_name < len_suffix))
842                         continue;
843
844                 if (STREQ(camera_name + (len_name - len_suffix), srv->suffix)) {
845                         BLI_snprintf(name, sizeof(name), "%.*s%s", (len_name - len_suffix), camera_name, suffix);
846                         len_suffix_max = len_suffix;
847                 }
848         }
849
850         if (name[0] != '\0') {
851                 Object *ob = BKE_scene_object_find_by_name(scene, name);
852                 if (ob != NULL) {
853                         return ob;
854                 }
855         }
856
857         return camera;
858 }
859
860 /* returns the camera to be used for render */
861 Object *BKE_camera_multiview_render(Scene *scene, Object *camera, const char *viewname)
862 {
863         const bool is_multiview = (camera != NULL) &&  (scene->r.scemode & R_MULTIVIEW) != 0;
864
865         if (!is_multiview) {
866                 return camera;
867         }
868         else if (scene->r.views_format == SCE_VIEWS_FORMAT_STEREO_3D) {
869                 return camera;
870         }
871         else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
872                 const char *suffix = BKE_scene_multiview_view_suffix_get(&scene->r, viewname);
873                 return camera_multiview_advanced(scene, camera, suffix);
874         }
875 }
876
877 static float camera_stereo3d_shift_x(const Object *camera, const char *viewname)
878 {
879         Camera *data = camera->data;
880         float shift = data->shiftx;
881         float interocular_distance, convergence_distance;
882         short convergence_mode, pivot;
883         bool is_left = true;
884
885         float fac = 1.0f;
886         float fac_signed;
887
888         if (viewname && viewname[0]) {
889                 is_left = STREQ(viewname, STEREO_LEFT_NAME);
890         }
891
892         interocular_distance = data->stereo.interocular_distance;
893         convergence_distance = data->stereo.convergence_distance;
894         convergence_mode = data->stereo.convergence_mode;
895         pivot = data->stereo.pivot;
896
897         if (convergence_mode != CAM_S3D_OFFAXIS)
898                 return shift;
899
900         if (((pivot == CAM_S3D_PIVOT_LEFT) && is_left) ||
901             ((pivot == CAM_S3D_PIVOT_RIGHT) && !is_left))
902         {
903                 return shift;
904         }
905
906         if (pivot == CAM_S3D_PIVOT_CENTER)
907                 fac = 0.5f;
908
909         fac_signed = is_left ? fac : -fac;
910         shift += ((interocular_distance / data->sensor_x) * (data->lens / convergence_distance)) * fac_signed;
911
912         return shift;
913 }
914
915 float BKE_camera_multiview_shift_x(RenderData *rd, const Object *camera, const char *viewname)
916 {
917         const bool is_multiview = (rd && rd->scemode & R_MULTIVIEW) != 0;
918         Camera *data = camera->data;
919
920         BLI_assert(camera->type == OB_CAMERA);
921
922         if (!is_multiview) {
923                 return data->shiftx;
924         }
925         else if (rd->views_format == SCE_VIEWS_FORMAT_MULTIVIEW) {
926                 return data->shiftx;
927         }
928         else { /* SCE_VIEWS_SETUP_BASIC */
929                 return camera_stereo3d_shift_x(camera, viewname);
930         }
931 }
932
933 void BKE_camera_multiview_params(RenderData *rd, CameraParams *params, const Object *camera, const char *viewname)
934 {
935         if (camera->type == OB_CAMERA) {
936                 params->shiftx = BKE_camera_multiview_shift_x(rd, camera, viewname);
937         }
938 }
939
940 void BKE_camera_to_gpu_dof(struct Object *camera, struct GPUFXSettings *r_fx_settings)
941 {
942         if (camera->type == OB_CAMERA) {
943                 Camera *cam = camera->data;
944                 r_fx_settings->dof = &cam->gpu_dof;
945                 r_fx_settings->dof->focal_length = cam->lens;
946                 r_fx_settings->dof->sensor = BKE_camera_sensor_size(cam->sensor_fit, cam->sensor_x, cam->sensor_y);
947                 r_fx_settings->dof->focus_distance = BKE_camera_object_dof_distance(camera);
948         }
949 }
950
951 CameraBGImage *BKE_camera_background_image_new(Camera *cam)
952 {
953         CameraBGImage *bgpic = MEM_callocN(sizeof(CameraBGImage), "Background Image");
954
955         bgpic->scale = 1.0f;
956         bgpic->alpha = 0.5f;
957         bgpic->iuser.ok = 1;
958         bgpic->iuser.flag |= IMA_ANIM_ALWAYS;
959         bgpic->flag |= CAM_BGIMG_FLAG_EXPANDED;
960
961         BLI_addtail(&cam->bg_images, bgpic);
962
963         return bgpic;
964 }
965
966 void BKE_camera_background_image_remove(Camera *cam, CameraBGImage *bgpic)
967 {
968         BLI_remlink(&cam->bg_images, bgpic);
969
970         MEM_freeN(bgpic);
971 }
972
973 void BKE_camera_background_image_clear(Camera *cam)
974 {
975         CameraBGImage *bgpic = cam->bg_images.first;
976
977         while (bgpic) {
978                 CameraBGImage *next_bgpic = bgpic->next;
979
980                 BKE_camera_background_image_remove(cam, bgpic);
981
982                 bgpic = next_bgpic;
983         }
984 }