144ff4ac8834a06407ffda7d5ff574952006fdb2
[blender.git] / source / gameengine / Ketsji / KX_Camera.cpp
1 /*
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * Camera in the gameengine. Cameras are also used for views.
29  */
30  
31 #include "GL/glew.h"
32 #include "KX_Camera.h"
33 #include "KX_Scene.h"
34 #include "KX_PythonInit.h"
35 #include "KX_Python.h"
36 #include "KX_PyMath.h"
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 KX_Camera::KX_Camera(void* sgReplicationInfo,
42                                          SG_Callbacks callbacks,
43                                          const RAS_CameraData& camdata,
44                                          bool frustum_culling,
45                                          bool delete_node,
46                                          PyTypeObject *T)
47                                         :
48                                         KX_GameObject(sgReplicationInfo,callbacks,T),
49                                         m_camdata(camdata),
50                                         m_dirty(true),
51                                         m_normalized(false),
52                                         m_frustum_culling(frustum_culling),
53                                         m_set_projection_matrix(false),
54                                         m_set_frustum_center(false),
55                                         m_delete_node(delete_node)
56 {
57         // setting a name would be nice...
58         m_name = "cam";
59         m_projection_matrix.setIdentity();
60         m_modelview_matrix.setIdentity();
61         CValue* val = new CIntValue(1);
62         SetProperty("camera",val);
63         val->Release();
64 }
65
66
67 KX_Camera::~KX_Camera()
68 {
69         if (m_delete_node && m_pSGNode)
70         {
71                 // for shadow camera, avoids memleak
72                 delete m_pSGNode;
73                 m_pSGNode = NULL;
74         }
75 }       
76
77
78 CValue* KX_Camera::GetReplica()
79 {
80         KX_Camera* replica = new KX_Camera(*this);
81         
82         // this will copy properties and so on...
83         replica->ProcessReplica();
84         
85         return replica;
86 }
87
88 void KX_Camera::ProcessReplica()
89 {
90         KX_GameObject::ProcessReplica();
91         // replicated camera are always registered in the scene
92         m_delete_node = false;
93 }
94
95 MT_Transform KX_Camera::GetWorldToCamera() const
96
97         MT_Transform camtrans;
98         camtrans.invert(MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation()));
99         
100         return camtrans;
101 }
102
103
104          
105 MT_Transform KX_Camera::GetCameraToWorld() const
106 {
107         return MT_Transform(NodeGetWorldPosition(), NodeGetWorldOrientation());
108 }
109
110
111
112 void KX_Camera::CorrectLookUp(MT_Scalar speed)
113 {
114 }
115
116
117
118 const MT_Point3 KX_Camera::GetCameraLocation() const
119 {
120         /* this is the camera locatio in cam coords... */
121         //return m_trans1.getOrigin();
122         //return MT_Point3(0,0,0);   <-----
123         /* .... I want it in world coords */
124         //MT_Transform trans;
125         //trans.setBasis(NodeGetWorldOrientation());
126         
127         return NodeGetWorldPosition();          
128 }
129
130
131
132 /* I want the camera orientation as well. */
133 const MT_Quaternion KX_Camera::GetCameraOrientation() const
134 {
135         return NodeGetWorldOrientation().getRotation();
136 }
137
138
139
140 /**
141 * Sets the projection matrix that is used by the rasterizer.
142 */
143 void KX_Camera::SetProjectionMatrix(const MT_Matrix4x4 & mat)
144 {
145         m_projection_matrix = mat;
146         m_dirty = true;
147         m_set_projection_matrix = true;
148         m_set_frustum_center = false;
149 }
150
151
152
153 /**
154 * Sets the modelview matrix that is used by the rasterizer.
155 */
156 void KX_Camera::SetModelviewMatrix(const MT_Matrix4x4 & mat)
157 {
158         m_modelview_matrix = mat;
159         m_dirty = true;
160         m_set_frustum_center = false;
161 }
162
163
164
165 /**
166 * Gets the projection matrix that is used by the rasterizer.
167 */
168 const MT_Matrix4x4& KX_Camera::GetProjectionMatrix() const
169 {
170         return m_projection_matrix;
171 }
172
173
174
175 /**
176 * Gets the modelview matrix that is used by the rasterizer.
177 */
178 const MT_Matrix4x4& KX_Camera::GetModelviewMatrix() const
179 {
180         return m_modelview_matrix;
181 }
182
183
184 bool KX_Camera::hasValidProjectionMatrix() const
185 {
186         return m_set_projection_matrix;
187 }
188
189 void KX_Camera::InvalidateProjectionMatrix(bool valid)
190 {
191         m_set_projection_matrix = valid;
192 }
193
194
195 /*
196 * These getters retrieve the clip data and the focal length
197 */
198 float KX_Camera::GetLens() const
199 {
200         return m_camdata.m_lens;
201 }
202
203 float KX_Camera::GetScale() const
204 {
205         return m_camdata.m_scale;
206 }
207
208
209
210 float KX_Camera::GetCameraNear() const
211 {
212         return m_camdata.m_clipstart;
213 }
214
215
216
217 float KX_Camera::GetCameraFar() const
218 {
219         return m_camdata.m_clipend;
220 }
221
222 float KX_Camera::GetFocalLength() const
223 {
224         return m_camdata.m_focallength;
225 }
226
227
228
229 RAS_CameraData* KX_Camera::GetCameraData()
230 {
231         return &m_camdata; 
232 }
233
234 void KX_Camera::ExtractClipPlanes()
235 {
236         if (!m_dirty)
237                 return;
238
239         MT_Matrix4x4 m = m_projection_matrix * m_modelview_matrix;
240         // Left clip plane
241         m_planes[0] = m[3] + m[0];
242         // Right clip plane
243         m_planes[1] = m[3] - m[0];
244         // Top clip plane
245         m_planes[2] = m[3] - m[1];
246         // Bottom clip plane
247         m_planes[3] = m[3] + m[1];
248         // Near clip plane
249         m_planes[4] = m[3] + m[2];
250         // Far clip plane
251         m_planes[5] = m[3] - m[2];
252         
253         m_dirty = false;
254         m_normalized = false;
255 }
256
257 void KX_Camera::NormalizeClipPlanes()
258 {
259         if (m_normalized)
260                 return;
261         
262         for (unsigned int p = 0; p < 6; p++)
263         {
264                 MT_Scalar factor = sqrt(m_planes[p][0]*m_planes[p][0] + m_planes[p][1]*m_planes[p][1] + m_planes[p][2]*m_planes[p][2]);
265                 if (!MT_fuzzyZero(factor))
266                         m_planes[p] /= factor;
267         }
268         
269         m_normalized = true;
270 }
271
272 void KX_Camera::ExtractFrustumSphere()
273 {
274         if (m_set_frustum_center)
275                 return;
276
277     // compute sphere for the general case and not only symmetric frustum:
278     // the mirror code in ImageRender can use very asymmetric frustum.
279     // We will put the sphere center on the line that goes from origin to the center of the far clipping plane
280     // This is the optimal position if the frustum is symmetric or very asymmetric and probably close
281     // to optimal for the general case. The sphere center position is computed so that the distance to 
282     // the near and far extreme frustum points are equal.
283
284     // get the transformation matrix from device coordinate to camera coordinate
285         MT_Matrix4x4 clip_camcs_matrix = m_projection_matrix;
286         clip_camcs_matrix.invert();
287
288         if (m_projection_matrix[3][3] == MT_Scalar(0.0)) 
289         {
290                 // frustrum projection
291                 // detect which of the corner of the far clipping plane is the farthest to the origin
292                 MT_Vector4 nfar;    // far point in device normalized coordinate
293                 MT_Point3 farpoint; // most extreme far point in camera coordinate
294                 MT_Point3 nearpoint;// most extreme near point in camera coordinate
295                 MT_Point3 farcenter(0.,0.,0.);// center of far cliping plane in camera coordinate
296                 MT_Scalar F=-1.0, N; // square distance of far and near point to origin
297                 MT_Scalar f, n;     // distance of far and near point to z axis. f is always > 0 but n can be < 0
298                 MT_Scalar e, s;     // far and near clipping distance (<0)
299                 MT_Scalar c;        // slope of center line = distance of far clipping center to z axis / far clipping distance
300                 MT_Scalar z;        // projection of sphere center on z axis (<0)
301                 // tmp value
302                 MT_Vector4 npoint(1., 1., 1., 1.);
303                 MT_Vector4 hpoint;
304                 MT_Point3 point;
305                 MT_Scalar len;
306                 for (int i=0; i<4; i++)
307                 {
308                 hpoint = clip_camcs_matrix*npoint;
309                         point.setValue(hpoint[0]/hpoint[3], hpoint[1]/hpoint[3], hpoint[2]/hpoint[3]);
310                         len = point.dot(point);
311                         if (len > F)
312                         {
313                                 nfar = npoint;
314                                 farpoint = point;
315                                 F = len;
316                         }
317                         // rotate by 90 degree along the z axis to walk through the 4 extreme points of the far clipping plane
318                         len = npoint[0];
319                         npoint[0] = -npoint[1];
320                         npoint[1] = len;
321                         farcenter += point;
322                 }
323                 // the far center is the average of the far clipping points
324                 farcenter *= 0.25;
325                 // the extreme near point is the opposite point on the near clipping plane
326                 nfar.setValue(-nfar[0], -nfar[1], -1., 1.);
327                 nfar = clip_camcs_matrix*nfar;
328                 nearpoint.setValue(nfar[0]/nfar[3], nfar[1]/nfar[3], nfar[2]/nfar[3]);
329                 // this is a frustrum projection
330                 N = nearpoint.dot(nearpoint);
331                 e = farpoint[2];
332                 s = nearpoint[2];
333                 // projection on XY plane for distance to axis computation
334                 MT_Point2 farxy(farpoint[0], farpoint[1]);
335                 // f is forced positive by construction
336                 f = farxy.length();
337                 // get corresponding point on the near plane
338                 farxy *= s/e;
339                 // this formula preserve the sign of n
340                 n = f*s/e - MT_Point2(nearpoint[0]-farxy[0], nearpoint[1]-farxy[1]).length();
341                 c = MT_Point2(farcenter[0], farcenter[1]).length()/e;
342                 // the big formula, it simplifies to (F-N)/(2(e-s)) for the symmetric case
343                 z = (F-N)/(2.0*(e-s+c*(f-n)));
344                 m_frustum_center = MT_Point3(farcenter[0]*z/e, farcenter[1]*z/e, z);
345                 m_frustum_radius = m_frustum_center.distance(farpoint);
346         } 
347         else
348         {
349                 // orthographic projection
350                 // The most extreme points on the near and far plane. (normalized device coords)
351                 MT_Vector4 hnear(1., 1., 1., 1.), hfar(-1., -1., -1., 1.);
352                 
353                 // Transform to hom camera local space
354                 hnear = clip_camcs_matrix*hnear;
355                 hfar = clip_camcs_matrix*hfar;
356                 
357                 // Tranform to 3d camera local space.
358                 MT_Point3 nearpoint(hnear[0]/hnear[3], hnear[1]/hnear[3], hnear[2]/hnear[3]);
359                 MT_Point3 farpoint(hfar[0]/hfar[3], hfar[1]/hfar[3], hfar[2]/hfar[3]);
360                 
361                 // just use mediant point
362                 m_frustum_center = (farpoint + nearpoint)*0.5;
363                 m_frustum_radius = m_frustum_center.distance(farpoint);
364         }
365         // Transform to world space.
366         m_frustum_center = GetCameraToWorld()(m_frustum_center);
367         m_frustum_radius /= fabs(NodeGetWorldScaling()[NodeGetWorldScaling().closestAxis()]);
368         
369         m_set_frustum_center = true;
370 }
371
372 bool KX_Camera::PointInsideFrustum(const MT_Point3& x)
373 {
374         ExtractClipPlanes();
375         
376         for( unsigned int i = 0; i < 6 ; i++ )
377         {
378                 if (m_planes[i][0]*x[0] + m_planes[i][1]*x[1] + m_planes[i][2]*x[2] + m_planes[i][3] < 0.)
379                         return false;
380         }
381         return true;
382 }
383
384 int KX_Camera::BoxInsideFrustum(const MT_Point3 *box)
385 {
386         ExtractClipPlanes();
387         
388         unsigned int insideCount = 0;
389         // 6 view frustum planes
390         for( unsigned int p = 0; p < 6 ; p++ )
391         {
392                 unsigned int behindCount = 0;
393                 // 8 box verticies.
394                 for (unsigned int v = 0; v < 8 ; v++)
395                 {
396                         if (m_planes[p][0]*box[v][0] + m_planes[p][1]*box[v][1] + m_planes[p][2]*box[v][2] + m_planes[p][3] < 0.)
397                                 behindCount++;
398                 }
399                 
400                 // 8 points behind this plane
401                 if (behindCount == 8)
402                         return OUTSIDE;
403
404                 // Every box vertex is on the front side of this plane
405                 if (!behindCount)
406                         insideCount++;
407         }
408         
409         // All box verticies are on the front side of all frustum planes.
410         if (insideCount == 6)
411                 return INSIDE;
412         
413         return INTERSECT;
414 }
415
416 int KX_Camera::SphereInsideFrustum(const MT_Point3& center, const MT_Scalar &radius)
417 {
418         ExtractFrustumSphere();
419         if (center.distance2(m_frustum_center) > (radius + m_frustum_radius)*(radius + m_frustum_radius))
420                 return OUTSIDE;
421
422         unsigned int p;
423         ExtractClipPlanes();
424         NormalizeClipPlanes();
425                 
426         MT_Scalar distance;
427         int intersect = INSIDE;
428         // distance:  <-------- OUTSIDE -----|----- INTERSECT -----0----- INTERSECT -----|----- INSIDE -------->
429         //                                -radius                                      radius
430         for (p = 0; p < 6; p++)
431         {
432                 distance = m_planes[p][0]*center[0] + m_planes[p][1]*center[1] + m_planes[p][2]*center[2] + m_planes[p][3];
433                 if (fabs(distance) <= radius)
434                         intersect = INTERSECT;
435                 else if (distance < -radius)
436                         return OUTSIDE;
437         }
438         
439         return intersect;
440 }
441
442 bool KX_Camera::GetFrustumCulling() const
443 {
444         return m_frustum_culling;
445 }
446  
447 void KX_Camera::EnableViewport(bool viewport)
448 {
449         m_camdata.m_viewport = viewport;
450 }
451
452 void KX_Camera::SetViewport(int left, int bottom, int right, int top)
453 {
454         m_camdata.m_viewportleft = left;
455         m_camdata.m_viewportbottom = bottom;
456         m_camdata.m_viewportright = right;
457         m_camdata.m_viewporttop = top;
458 }
459
460 bool KX_Camera::GetViewport() const
461 {
462         return m_camdata.m_viewport;
463 }
464
465 int KX_Camera::GetViewportLeft() const
466 {
467         return m_camdata.m_viewportleft;
468 }
469
470 int KX_Camera::GetViewportBottom() const
471 {
472         return m_camdata.m_viewportbottom;
473 }
474
475 int KX_Camera::GetViewportRight() const
476 {
477         return m_camdata.m_viewportright;
478 }
479
480 int KX_Camera::GetViewportTop() const
481 {
482         return m_camdata.m_viewporttop;
483 }
484
485 //----------------------------------------------------------------------------
486 //Python
487
488
489 PyMethodDef KX_Camera::Methods[] = {
490         KX_PYMETHODTABLE(KX_Camera, sphereInsideFrustum),
491         KX_PYMETHODTABLE_O(KX_Camera, boxInsideFrustum),
492         KX_PYMETHODTABLE_O(KX_Camera, pointInsideFrustum),
493         KX_PYMETHODTABLE_NOARGS(KX_Camera, getCameraToWorld),
494         KX_PYMETHODTABLE_NOARGS(KX_Camera, getWorldToCamera),
495         KX_PYMETHODTABLE(KX_Camera, setViewport),
496         KX_PYMETHODTABLE_NOARGS(KX_Camera, setOnTop),
497         KX_PYMETHODTABLE_O(KX_Camera, getScreenPosition),
498         KX_PYMETHODTABLE(KX_Camera, getScreenVect),
499         KX_PYMETHODTABLE(KX_Camera, getScreenRay),
500
501         // DEPRECATED
502         KX_PYMETHODTABLE_O(KX_Camera, enableViewport),
503         KX_PYMETHODTABLE_NOARGS(KX_Camera, getProjectionMatrix),
504         KX_PYMETHODTABLE_O(KX_Camera, setProjectionMatrix),
505         
506         {NULL,NULL} //Sentinel
507 };
508
509 PyAttributeDef KX_Camera::Attributes[] = {
510         
511         KX_PYATTRIBUTE_BOOL_RW("frustum_culling", KX_Camera, m_frustum_culling),
512         KX_PYATTRIBUTE_RW_FUNCTION("perspective", KX_Camera, pyattr_get_perspective, pyattr_set_perspective),
513         
514         KX_PYATTRIBUTE_RW_FUNCTION("lens",      KX_Camera,      pyattr_get_lens, pyattr_set_lens),
515         KX_PYATTRIBUTE_RW_FUNCTION("near",      KX_Camera,      pyattr_get_near, pyattr_set_near),
516         KX_PYATTRIBUTE_RW_FUNCTION("far",       KX_Camera,      pyattr_get_far,  pyattr_set_far),
517         
518         KX_PYATTRIBUTE_RW_FUNCTION("useViewport",       KX_Camera,      pyattr_get_use_viewport,  pyattr_set_use_viewport),
519         
520         KX_PYATTRIBUTE_RW_FUNCTION("projection_matrix", KX_Camera,      pyattr_get_projection_matrix, pyattr_set_projection_matrix),
521         KX_PYATTRIBUTE_RO_FUNCTION("modelview_matrix",  KX_Camera,      pyattr_get_modelview_matrix),
522         KX_PYATTRIBUTE_RO_FUNCTION("camera_to_world",   KX_Camera,      pyattr_get_camera_to_world),
523         KX_PYATTRIBUTE_RO_FUNCTION("world_to_camera",   KX_Camera,      pyattr_get_world_to_camera),
524         
525         /* Grrr, functions for constants? */
526         KX_PYATTRIBUTE_RO_FUNCTION("INSIDE",    KX_Camera, pyattr_get_INSIDE),
527         KX_PYATTRIBUTE_RO_FUNCTION("OUTSIDE",   KX_Camera, pyattr_get_OUTSIDE),
528         KX_PYATTRIBUTE_RO_FUNCTION("INTERSECT", KX_Camera, pyattr_get_INTERSECT),
529         
530         { NULL }        //Sentinel
531 };
532
533 PyTypeObject KX_Camera::Type = {
534 #if (PY_VERSION_HEX >= 0x02060000)
535         PyVarObject_HEAD_INIT(NULL, 0)
536 #else
537         /* python 2.5 and below */
538         PyObject_HEAD_INIT( NULL )  /* required py macro */
539         0,                          /* ob_size */
540 #endif
541                 "KX_Camera",
542                 sizeof(PyObjectPlus_Proxy),
543                 0,
544                 py_base_dealloc,
545                 0,
546                 0,
547                 0,
548                 0,
549                 py_base_repr,
550                 0,0,
551                 &KX_GameObject::Mapping,
552                 0,0,0,
553                 py_base_getattro,
554                 py_base_setattro,
555                 0,0,0,0,0,0,0,0,0,
556                 Methods
557 };
558
559
560
561
562
563
564 PyParentObject KX_Camera::Parents[] = {
565         &KX_Camera::Type,
566         &KX_GameObject::Type,
567                 &SCA_IObject::Type,
568                 &CValue::Type,
569                 NULL
570 };
571
572 PyObject* KX_Camera::py_getattro(PyObject *attr)
573 {
574         py_getattro_up(KX_GameObject);
575 }
576
577 PyObject* KX_Camera::py_getattro_dict() {
578         py_getattro_dict_up(KX_GameObject);
579 }
580
581 int KX_Camera::py_setattro(PyObject *attr, PyObject *value)
582 {       
583         py_setattro_up(KX_GameObject);
584 }
585
586 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, sphereInsideFrustum,
587 "sphereInsideFrustum(center, radius) -> Integer\n"
588 "\treturns INSIDE, OUTSIDE or INTERSECT if the given sphere is\n"
589 "\tinside/outside/intersects this camera's viewing frustum.\n\n"
590 "\tcenter = the center of the sphere (in world coordinates.)\n"
591 "\tradius = the radius of the sphere\n\n"
592 "\tExample:\n"
593 "\timport GameLogic\n\n"
594 "\tco = GameLogic.getCurrentController()\n"
595 "\tcam = co.GetOwner()\n\n"
596 "\t# A sphere of radius 4.0 located at [x, y, z] = [1.0, 1.0, 1.0]\n"
597 "\tif (cam.sphereInsideFrustum([1.0, 1.0, 1.0], 4) != cam.OUTSIDE):\n"
598 "\t\t# Sphere is inside frustum !\n"
599 "\t\t# Do something useful !\n"
600 "\telse:\n"
601 "\t\t# Sphere is outside frustum\n"
602 )
603 {
604         PyObject *pycenter;
605         float radius;
606         if (PyArg_ParseTuple(args, "Of:sphereInsideFrustum", &pycenter, &radius))
607         {
608                 MT_Point3 center;
609                 if (PyVecTo(pycenter, center))
610                 {
611                         return PyInt_FromLong(SphereInsideFrustum(center, radius)); /* new ref */
612                 }
613         }
614
615         PyErr_SetString(PyExc_TypeError, "camera.sphereInsideFrustum(center, radius): KX_Camera, expected arguments: (center, radius)");
616         
617         return NULL;
618 }
619
620 KX_PYMETHODDEF_DOC_O(KX_Camera, boxInsideFrustum,
621 "boxInsideFrustum(box) -> Integer\n"
622 "\treturns INSIDE, OUTSIDE or INTERSECT if the given box is\n"
623 "\tinside/outside/intersects this camera's viewing frustum.\n\n"
624 "\tbox = a list of the eight (8) corners of the box (in world coordinates.)\n\n"
625 "\tExample:\n"
626 "\timport GameLogic\n\n"
627 "\tco = GameLogic.getCurrentController()\n"
628 "\tcam = co.GetOwner()\n\n"
629 "\tbox = []\n"
630 "\tbox.append([-1.0, -1.0, -1.0])\n"
631 "\tbox.append([-1.0, -1.0,  1.0])\n"
632 "\tbox.append([-1.0,  1.0, -1.0])\n"
633 "\tbox.append([-1.0,  1.0,  1.0])\n"
634 "\tbox.append([ 1.0, -1.0, -1.0])\n"
635 "\tbox.append([ 1.0, -1.0,  1.0])\n"
636 "\tbox.append([ 1.0,  1.0, -1.0])\n"
637 "\tbox.append([ 1.0,  1.0,  1.0])\n\n"
638 "\tif (cam.boxInsideFrustum(box) != cam.OUTSIDE):\n"
639 "\t\t# Box is inside/intersects frustum !\n"
640 "\t\t# Do something useful !\n"
641 "\telse:\n"
642 "\t\t# Box is outside the frustum !\n"
643 )
644 {
645         unsigned int num_points = PySequence_Size(value);
646         if (num_points != 8)
647         {
648                 PyErr_Format(PyExc_TypeError, "camera.boxInsideFrustum(box): KX_Camera, expected eight (8) points, got %d", num_points);
649                 return NULL;
650         }
651         
652         MT_Point3 box[8];
653         for (unsigned int p = 0; p < 8 ; p++)
654         {
655                 PyObject *item = PySequence_GetItem(value, p); /* new ref */
656                 bool error = !PyVecTo(item, box[p]);
657                 Py_DECREF(item);
658                 if (error)
659                         return NULL;
660         }
661         
662         return PyInt_FromLong(BoxInsideFrustum(box)); /* new ref */
663 }
664
665 KX_PYMETHODDEF_DOC_O(KX_Camera, pointInsideFrustum,
666 "pointInsideFrustum(point) -> Bool\n"
667 "\treturns 1 if the given point is inside this camera's viewing frustum.\n\n"
668 "\tpoint = The point to test (in world coordinates.)\n\n"
669 "\tExample:\n"
670 "\timport GameLogic\n\n"
671 "\tco = GameLogic.getCurrentController()\n"
672 "\tcam = co.GetOwner()\n\n"
673 "\t# Test point [0.0, 0.0, 0.0]"
674 "\tif (cam.pointInsideFrustum([0.0, 0.0, 0.0])):\n"
675 "\t\t# Point is inside frustum !\n"
676 "\t\t# Do something useful !\n"
677 "\telse:\n"
678 "\t\t# Box is outside the frustum !\n"
679 )
680 {
681         MT_Point3 point;
682         if (PyVecTo(value, point))
683         {
684                 return PyInt_FromLong(PointInsideFrustum(point)); /* new ref */
685         }
686         
687         PyErr_SetString(PyExc_TypeError, "camera.pointInsideFrustum(point): KX_Camera, expected point argument.");
688         return NULL;
689 }
690
691 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getCameraToWorld,
692 "getCameraToWorld() -> Matrix4x4\n"
693 "\treturns the camera to world transformation matrix, as a list of four lists of four values.\n\n"
694 "\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
695 )
696 {
697         return PyObjectFrom(GetCameraToWorld()); /* new ref */
698 }
699
700 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getWorldToCamera,
701 "getWorldToCamera() -> Matrix4x4\n"
702 "\treturns the world to camera transformation matrix, as a list of four lists of four values.\n\n"
703 "\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
704 )
705 {
706         return PyObjectFrom(GetWorldToCamera()); /* new ref */
707 }
708
709 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, getProjectionMatrix,
710 "getProjectionMatrix() -> Matrix4x4\n"
711 "\treturns this camera's projection matrix, as a list of four lists of four values.\n\n"
712 "\tie: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]])\n"
713 )
714 {
715         ShowDeprecationWarning("getProjectionMatrix()", "the projection_matrix property");
716         return PyObjectFrom(GetProjectionMatrix()); /* new ref */
717 }
718
719 KX_PYMETHODDEF_DOC_O(KX_Camera, setProjectionMatrix,
720 "setProjectionMatrix(MT_Matrix4x4 m) -> None\n"
721 "\tSets this camera's projection matrix\n"
722 "\n"
723 "\tExample:\n"
724 "\timport GameLogic\n"
725 "\t# Set a perspective projection matrix\n"
726 "\tdef Perspective(left, right, bottom, top, near, far):\n"
727 "\t\tm = MT_Matrix4x4()\n"
728 "\t\tm[0][0] = m[0][2] = right - left\n"
729 "\t\tm[1][1] = m[1][2] = top - bottom\n"
730 "\t\tm[2][2] = m[2][3] = -far - near\n"
731 "\t\tm[3][2] = -1\n"
732 "\t\tm[3][3] = 0\n"
733 "\t\treturn m\n"
734 "\n"
735 "\t# Set an orthographic projection matrix\n"
736 "\tdef Orthographic(left, right, bottom, top, near, far):\n"
737 "\t\tm = MT_Matrix4x4()\n"
738 "\t\tm[0][0] = right - left\n"
739 "\t\tm[0][3] = -right - left\n"
740 "\t\tm[1][1] = top - bottom\n"
741 "\t\tm[1][3] = -top - bottom\n"
742 "\t\tm[2][2] = far - near\n"
743 "\t\tm[2][3] = -far - near\n"
744 "\t\tm[3][3] = 1\n"
745 "\t\treturn m\n"
746 "\n"
747 "\t# Set an isometric projection matrix\n"
748 "\tdef Isometric(left, right, bottom, top, near, far):\n"
749 "\t\tm = MT_Matrix4x4()\n"
750 "\t\tm[0][0] = m[0][2] = m[1][1] = 0.8660254037844386\n"
751 "\t\tm[1][0] = 0.25\n"
752 "\t\tm[1][2] = -0.25\n"
753 "\t\tm[3][3] = 1\n"
754 "\t\treturn m\n"
755 "\n"
756 "\t"
757 "\tco = GameLogic.getCurrentController()\n"
758 "\tcam = co.getOwner()\n"
759 "\tcam.setProjectionMatrix(Perspective(-1.0, 1.0, -1.0, 1.0, 0.1, 1))\n")
760 {
761         ShowDeprecationWarning("setProjectionMatrix(mat)", "the projection_matrix property");
762         
763         MT_Matrix4x4 mat;
764         if (!PyMatTo(value, mat))
765         {
766                 PyErr_SetString(PyExc_TypeError, "camera.setProjectionMatrix(matrix): KX_Camera, expected 4x4 list as matrix argument.");
767                 return NULL;
768         }
769         
770         SetProjectionMatrix(mat);
771         Py_RETURN_NONE;
772 }
773
774 KX_PYMETHODDEF_DOC_O(KX_Camera, enableViewport,
775 "enableViewport(viewport)\n"
776 "Sets this camera's viewport status\n"
777 )
778 {
779         ShowDeprecationWarning("enableViewport(bool)", "the useViewport property");
780         
781         int viewport = PyObject_IsTrue(value);
782         if (viewport == -1) {
783                 PyErr_SetString(PyExc_ValueError, "camera.enableViewport(bool): KX_Camera, expected True/False or 0/1");
784                 return NULL;
785         }
786         
787         if(viewport)
788                 EnableViewport(true);
789         else
790                 EnableViewport(false);
791         
792         Py_RETURN_NONE;
793 }
794
795 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, setViewport,
796 "setViewport(left, bottom, right, top)\n"
797 "Sets this camera's viewport\n")
798 {
799         int left, bottom, right, top;
800         if (!PyArg_ParseTuple(args,"iiii:setViewport",&left, &bottom, &right, &top))
801                 return NULL;
802         
803         SetViewport(left, bottom, right, top);
804         Py_RETURN_NONE;
805 }
806
807 KX_PYMETHODDEF_DOC_NOARGS(KX_Camera, setOnTop,
808 "setOnTop()\n"
809 "Sets this camera's viewport on top\n")
810 {
811         class KX_Scene* scene = KX_GetActiveScene();
812         scene->SetCameraOnTop(this);
813         Py_RETURN_NONE;
814 }
815
816 PyObject* KX_Camera::pyattr_get_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
817 {
818         KX_Camera* self= static_cast<KX_Camera*>(self_v);
819         return PyBool_FromLong(self->m_camdata.m_perspective);
820 }
821
822 int KX_Camera::pyattr_set_perspective(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
823 {
824         KX_Camera* self= static_cast<KX_Camera*>(self_v);
825         int param = PyObject_IsTrue( value );
826         if (param == -1) {
827                 PyErr_SetString(PyExc_AttributeError, "camera.perspective = bool: KX_Camera, expected True/False or 0/1");
828                 return PY_SET_ATTR_FAIL;
829         }
830         
831         self->m_camdata.m_perspective= param;
832         return PY_SET_ATTR_SUCCESS;
833 }
834
835 PyObject* KX_Camera::pyattr_get_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
836 {
837         KX_Camera* self= static_cast<KX_Camera*>(self_v);
838         return PyFloat_FromDouble(self->m_camdata.m_lens);
839 }
840
841 int KX_Camera::pyattr_set_lens(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
842 {
843         KX_Camera* self= static_cast<KX_Camera*>(self_v);
844         float param = PyFloat_AsDouble(value);
845         if (param == -1) {
846                 PyErr_SetString(PyExc_AttributeError, "camera.lens = float: KX_Camera, expected a float greater then zero");
847                 return PY_SET_ATTR_FAIL;
848         }
849         
850         self->m_camdata.m_lens= param;
851         self->m_set_projection_matrix = false;
852         return PY_SET_ATTR_SUCCESS;
853 }
854
855 PyObject* KX_Camera::pyattr_get_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
856 {
857         KX_Camera* self= static_cast<KX_Camera*>(self_v);
858         return PyFloat_FromDouble(self->m_camdata.m_clipstart);
859 }
860
861 int KX_Camera::pyattr_set_near(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
862 {
863         KX_Camera* self= static_cast<KX_Camera*>(self_v);
864         float param = PyFloat_AsDouble(value);
865         if (param == -1) {
866                 PyErr_SetString(PyExc_AttributeError, "camera.near = float: KX_Camera, expected a float greater then zero");
867                 return PY_SET_ATTR_FAIL;
868         }
869         
870         self->m_camdata.m_clipstart= param;
871         self->m_set_projection_matrix = false;
872         return PY_SET_ATTR_SUCCESS;
873 }
874
875 PyObject* KX_Camera::pyattr_get_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
876 {
877         KX_Camera* self= static_cast<KX_Camera*>(self_v);
878         return PyFloat_FromDouble(self->m_camdata.m_clipend);
879 }
880
881 int KX_Camera::pyattr_set_far(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
882 {
883         KX_Camera* self= static_cast<KX_Camera*>(self_v);
884         float param = PyFloat_AsDouble(value);
885         if (param == -1) {
886                 PyErr_SetString(PyExc_AttributeError, "camera.far = float: KX_Camera, expected a float greater then zero");
887                 return PY_SET_ATTR_FAIL;
888         }
889         
890         self->m_camdata.m_clipend= param;
891         self->m_set_projection_matrix = false;
892         return PY_SET_ATTR_SUCCESS;
893 }
894
895
896 PyObject* KX_Camera::pyattr_get_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
897 {
898         KX_Camera* self= static_cast<KX_Camera*>(self_v);
899         return PyBool_FromLong(self->GetViewport());
900 }
901
902 int KX_Camera::pyattr_set_use_viewport(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
903 {
904         KX_Camera* self= static_cast<KX_Camera*>(self_v);
905         int param = PyObject_IsTrue( value );
906         if (param == -1) {
907                 PyErr_SetString(PyExc_AttributeError, "camera.useViewport = bool: KX_Camera, expected True or False");
908                 return PY_SET_ATTR_FAIL;
909         }
910         self->EnableViewport((bool)param);
911         return PY_SET_ATTR_SUCCESS;
912 }
913
914
915 PyObject* KX_Camera::pyattr_get_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
916 {
917         KX_Camera* self= static_cast<KX_Camera*>(self_v);
918         return PyObjectFrom(self->GetProjectionMatrix()); 
919 }
920
921 int KX_Camera::pyattr_set_projection_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
922 {
923         KX_Camera* self= static_cast<KX_Camera*>(self_v);
924         MT_Matrix4x4 mat;
925         if (!PyMatTo(value, mat)) 
926                 return PY_SET_ATTR_FAIL;
927         
928         self->SetProjectionMatrix(mat);
929         return PY_SET_ATTR_SUCCESS;
930 }
931
932 PyObject* KX_Camera::pyattr_get_modelview_matrix(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
933 {
934         KX_Camera* self= static_cast<KX_Camera*>(self_v);
935         return PyObjectFrom(self->GetModelviewMatrix()); 
936 }
937
938 PyObject* KX_Camera::pyattr_get_camera_to_world(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
939 {
940         KX_Camera* self= static_cast<KX_Camera*>(self_v);
941         return PyObjectFrom(self->GetCameraToWorld());
942 }
943
944 PyObject* KX_Camera::pyattr_get_world_to_camera(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
945 {
946         KX_Camera* self= static_cast<KX_Camera*>(self_v);
947         return PyObjectFrom(self->GetWorldToCamera()); 
948 }
949
950
951 PyObject* KX_Camera::pyattr_get_INSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
952 {       return PyInt_FromLong(INSIDE); }
953 PyObject* KX_Camera::pyattr_get_OUTSIDE(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
954 {       return PyInt_FromLong(OUTSIDE); }
955 PyObject* KX_Camera::pyattr_get_INTERSECT(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
956 {       return PyInt_FromLong(INTERSECT); }
957
958
959 bool ConvertPythonToCamera(PyObject * value, KX_Camera **object, bool py_none_ok, const char *error_prefix)
960 {
961         if (value==NULL) {
962                 PyErr_Format(PyExc_TypeError, "%s, python pointer NULL, should never happen", error_prefix);
963                 *object = NULL;
964                 return false;
965         }
966                 
967         if (value==Py_None) {
968                 *object = NULL;
969                 
970                 if (py_none_ok) {
971                         return true;
972                 } else {
973                         PyErr_Format(PyExc_TypeError, "%s, expected KX_Camera or a KX_Camera name, None is invalid", error_prefix);
974                         return false;
975                 }
976         }
977         
978         if (PyString_Check(value)) {
979                 STR_String value_str = PyString_AsString(value);
980                 *object = KX_GetActiveScene()->FindCamera(value_str);
981                 
982                 if (*object) {
983                         return true;
984                 } else {
985                         PyErr_Format(PyExc_ValueError, "%s, requested name \"%s\" did not match any KX_Camera in this scene", error_prefix, PyString_AsString(value));
986                         return false;
987                 }
988         }
989         
990         if (PyObject_TypeCheck(value, &KX_Camera::Type)) {
991                 *object = static_cast<KX_Camera*>BGE_PROXY_REF(value);
992                 
993                 /* sets the error */
994                 if (*object==NULL) {
995                         PyErr_Format(PyExc_SystemError, "%s, " BGE_PROXY_ERROR_MSG, error_prefix);
996                         return false;
997                 }
998                 
999                 return true;
1000         }
1001         
1002         *object = NULL;
1003         
1004         if (py_none_ok) {
1005                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera, a string or None", error_prefix);
1006         } else {
1007                 PyErr_Format(PyExc_TypeError, "%s, expect a KX_Camera or a string", error_prefix);
1008         }
1009         
1010         return false;
1011 }
1012
1013 KX_PYMETHODDEF_DOC_O(KX_Camera, getScreenPosition,
1014 "getScreenPosition()\n"
1015 )
1016
1017 {
1018         MT_Vector3 vect;
1019         KX_GameObject *obj = NULL;
1020
1021         if (!PyVecTo(value, vect))
1022         {
1023                 if(ConvertPythonToGameObject(value, &obj, true, ""))
1024                 {
1025                         PyErr_Clear();
1026                         vect = MT_Vector3(obj->NodeGetWorldPosition());
1027                 }
1028                 else
1029                 {
1030                         PyErr_SetString(PyExc_TypeError, "Error in getScreenPosition. Expected a Vector3 or a KX_GameObject or a string for a name of a KX_GameObject");
1031                         return NULL;
1032                 }
1033         }
1034
1035         GLint viewport[4];
1036         GLdouble win[3];
1037         GLdouble modelmatrix[16];
1038         GLdouble projmatrix[16];
1039
1040         MT_Matrix4x4 m_modelmatrix = this->GetModelviewMatrix();
1041         MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();
1042
1043         m_modelmatrix.getValue(modelmatrix);
1044         m_projmatrix.getValue(projmatrix);
1045
1046         glGetIntegerv(GL_VIEWPORT, viewport);
1047
1048         gluProject(vect[0], vect[1], vect[2], modelmatrix, projmatrix, viewport, &win[0], &win[1], &win[2]);
1049
1050         vect[0] =  win[0] / (viewport[0] + viewport[2]);
1051         vect[1] =  win[1] / (viewport[1] + viewport[3]);
1052
1053         PyObject* ret = PyTuple_New(2);
1054         if(ret){
1055                 PyTuple_SET_ITEM(ret, 0, PyFloat_FromDouble(vect[0]));
1056                 PyTuple_SET_ITEM(ret, 1, PyFloat_FromDouble(vect[1]));
1057                 return ret;
1058         }
1059
1060         return NULL;
1061 }
1062
1063 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenVect,
1064 "getScreenVect()\n"
1065 )
1066 {
1067         double x,y;
1068         if (!PyArg_ParseTuple(args,"dd:getScreenVect",&x,&y))
1069                 return NULL;
1070
1071         MT_Vector3 vect;
1072         MT_Point3 campos, screenpos;
1073
1074         GLint viewport[4];
1075         GLdouble win[3];
1076         GLdouble modelmatrix[16];
1077         GLdouble projmatrix[16];
1078
1079         MT_Matrix4x4 m_modelmatrix = this->GetModelviewMatrix();
1080         MT_Matrix4x4 m_projmatrix = this->GetProjectionMatrix();
1081
1082         m_modelmatrix.getValue(modelmatrix);
1083         m_projmatrix.getValue(projmatrix);
1084
1085         glGetIntegerv(GL_VIEWPORT, viewport);
1086
1087         vect[0] = x * viewport[2];
1088         vect[1] = y * viewport[3];
1089
1090         vect[0] += viewport[0];
1091         vect[1] += viewport[1];
1092
1093         glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &vect[2]);
1094         gluUnProject(vect[0], vect[1], vect[2], modelmatrix, projmatrix, viewport, &win[0], &win[1], &win[2]);
1095
1096         campos = this->GetCameraLocation();
1097         screenpos = MT_Point3(win[0], win[1], win[2]);
1098         vect = campos-screenpos;
1099
1100         vect.normalize();
1101         return PyObjectFrom(vect);
1102 }
1103
1104 KX_PYMETHODDEF_DOC_VARARGS(KX_Camera, getScreenRay,
1105 "getScreenRay()\n"
1106 )
1107 {
1108         KX_Camera* cam;
1109         MT_Vector3 vect;
1110         double x,y,dist;
1111         char *propName = NULL;
1112
1113         if (!PyArg_ParseTuple(args,"ddd|s:getScreenRay",&x,&y,&dist,&propName))
1114                 return NULL;
1115
1116         PyObject* argValue = PyTuple_New(2);
1117         if (argValue) {
1118                 PyTuple_SET_ITEM(argValue, 0, PyFloat_FromDouble(x));
1119                 PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(y));
1120         }
1121
1122         if(!PyVecTo(PygetScreenVect(argValue), vect))
1123         {
1124                 Py_DECREF(argValue);
1125                 PyErr_SetString(PyExc_TypeError,
1126                         "Error in getScreenRay. Invalid 2D coordinate. Expected a normalized 2D screen coordinate, a distance and an optional property argument");
1127                 return NULL;
1128         }
1129         Py_DECREF(argValue);
1130
1131         dist *= -1.0;
1132
1133         argValue = (propName?PyTuple_New(3):PyTuple_New(2));
1134         if (argValue) {
1135                 PyTuple_SET_ITEM(argValue, 0, PyObjectFrom(vect));
1136                 PyTuple_SET_ITEM(argValue, 1, PyFloat_FromDouble(dist));
1137                 if (propName)
1138                         PyTuple_SET_ITEM(argValue, 2, PyString_FromString(propName));
1139
1140                 PyObject* ret= this->PyrayCastTo(argValue,NULL);
1141                 Py_DECREF(argValue);
1142                 return ret;
1143         }
1144
1145         return NULL;
1146 }
1147