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