5922e97aaf44d9cc908cf39209424162ae4bb860
[blender.git] / source / gameengine / Ketsji / KX_Light.cpp
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 gameengine/Ketsji/KX_Light.cpp
29  *  \ingroup ketsji
30  */
31
32
33 #if defined(WIN32) && !defined(FREE_WINDOWS)
34 #pragma warning (disable : 4786)
35 #endif
36
37 #include "GL/glew.h"
38
39 #include "KX_Light.h"
40 #include "KX_Camera.h"
41 #include "RAS_IRasterizer.h"
42 #include "RAS_IRenderTools.h"
43
44 #include "KX_PyMath.h"
45
46 #include "DNA_object_types.h"
47 #include "DNA_scene_types.h"
48 #include "DNA_lamp_types.h"
49 #include "GPU_material.h"
50  
51 KX_LightObject::KX_LightObject(void* sgReplicationInfo,SG_Callbacks callbacks,
52                                                            class RAS_IRenderTools* rendertools,
53                                                            const RAS_LightObject&       lightobj,
54                                                            bool glsl)
55         : KX_GameObject(sgReplicationInfo,callbacks),
56           m_rendertools(rendertools)
57 {
58         m_lightobj = lightobj;
59         m_lightobj.m_scene = sgReplicationInfo;
60         m_lightobj.m_light = this;
61         m_rendertools->AddLight(&m_lightobj);
62         m_glsl = glsl;
63         m_blenderscene = ((KX_Scene*)sgReplicationInfo)->GetBlenderScene();
64 };
65
66
67 KX_LightObject::~KX_LightObject()
68 {
69         GPULamp *lamp;
70
71         if ((lamp = GetGPULamp())) {
72                 float obmat[4][4] = {{0}};
73                 GPU_lamp_update(lamp, 0, 0, obmat);
74         }
75
76         m_rendertools->RemoveLight(&m_lightobj);
77 }
78
79
80 CValue*         KX_LightObject::GetReplica()
81 {
82
83         KX_LightObject* replica = new KX_LightObject(*this);
84
85         replica->ProcessReplica();
86         
87         replica->m_lightobj.m_light = replica;
88         m_rendertools->AddLight(&replica->m_lightobj);
89
90         return replica;
91 }
92
93 bool KX_LightObject::ApplyLight(KX_Scene *kxscene, int oblayer, int slot)
94 {
95         KX_Scene* lightscene = (KX_Scene*)m_lightobj.m_scene;
96         float vec[4];
97         int scenelayer = ~0;
98
99         if (kxscene && kxscene->GetBlenderScene())
100                 scenelayer = kxscene->GetBlenderScene()->lay;
101         
102         /* only use lights in the same layer as the object */
103         if (!(m_lightobj.m_layer & oblayer))
104                 return false;
105         /* only use lights in the same scene, and in a visible layer */
106         if (kxscene != lightscene || !(m_lightobj.m_layer & scenelayer))
107                 return false;
108
109         // lights don't get their openGL matrix updated, do it now
110         if (GetSGNode()->IsDirty())
111                 GetOpenGLMatrix();
112
113         MT_CmMatrix4x4& worldmatrix= *GetOpenGLMatrixPtr();
114
115         vec[0] = worldmatrix(0,3);
116         vec[1] = worldmatrix(1,3);
117         vec[2] = worldmatrix(2,3);
118         vec[3] = 1.0f;
119
120         if (m_lightobj.m_type==RAS_LightObject::LIGHT_SUN) {
121                 
122                 vec[0] = worldmatrix(0,2);
123                 vec[1] = worldmatrix(1,2);
124                 vec[2] = worldmatrix(2,2);
125                 //vec[0]= base->object->obmat[2][0];
126                 //vec[1]= base->object->obmat[2][1];
127                 //vec[2]= base->object->obmat[2][2];
128                 vec[3]= 0.0;
129                 glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec); 
130         }
131         else {
132                 //vec[3]= 1.0;
133                 glLightfv((GLenum)(GL_LIGHT0+slot), GL_POSITION, vec); 
134                 glLightf((GLenum)(GL_LIGHT0+slot), GL_CONSTANT_ATTENUATION, 1.0);
135                 glLightf((GLenum)(GL_LIGHT0+slot), GL_LINEAR_ATTENUATION, m_lightobj.m_att1/m_lightobj.m_distance);
136                 // without this next line it looks backward compatible.
137                 //attennuation still is acceptable 
138                 glLightf((GLenum)(GL_LIGHT0+slot), GL_QUADRATIC_ATTENUATION, m_lightobj.m_att2/(m_lightobj.m_distance*m_lightobj.m_distance)); 
139                 
140                 if (m_lightobj.m_type==RAS_LightObject::LIGHT_SPOT) {
141                         vec[0] = -worldmatrix(0,2);
142                         vec[1] = -worldmatrix(1,2);
143                         vec[2] = -worldmatrix(2,2);
144                         //vec[0]= -base->object->obmat[2][0];
145                         //vec[1]= -base->object->obmat[2][1];
146                         //vec[2]= -base->object->obmat[2][2];
147                         glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPOT_DIRECTION, vec);
148                         glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, m_lightobj.m_spotsize/2.0);
149                         glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_EXPONENT, 128.0*m_lightobj.m_spotblend);
150                 }
151                 else
152                         glLightf((GLenum)(GL_LIGHT0+slot), GL_SPOT_CUTOFF, 180.0);
153         }
154         
155         if (m_lightobj.m_nodiffuse) {
156                 vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
157         }
158         else {
159                 vec[0]= m_lightobj.m_energy*m_lightobj.m_red;
160                 vec[1]= m_lightobj.m_energy*m_lightobj.m_green;
161                 vec[2]= m_lightobj.m_energy*m_lightobj.m_blue;
162                 vec[3]= 1.0;
163         }
164
165         glLightfv((GLenum)(GL_LIGHT0+slot), GL_DIFFUSE, vec);
166         if (m_lightobj.m_nospecular)
167         {
168                 vec[0] = vec[1] = vec[2] = vec[3] = 0.0;
169         }
170         else if (m_lightobj.m_nodiffuse) {
171                 vec[0]= m_lightobj.m_energy*m_lightobj.m_red;
172                 vec[1]= m_lightobj.m_energy*m_lightobj.m_green;
173                 vec[2]= m_lightobj.m_energy*m_lightobj.m_blue;
174                 vec[3]= 1.0;
175         }
176
177         glLightfv((GLenum)(GL_LIGHT0+slot), GL_SPECULAR, vec);
178         glEnable((GLenum)(GL_LIGHT0+slot));
179
180         return true;
181 }
182
183 GPULamp *KX_LightObject::GetGPULamp()
184 {
185         if (m_glsl)
186                 return GPU_lamp_from_blender(m_blenderscene, GetBlenderObject(), GetBlenderGroupObject());
187         else
188                 return NULL;
189 }
190
191 void KX_LightObject::Update()
192 {
193         GPULamp *lamp;
194
195         if ((lamp = GetGPULamp()) != NULL && GetSGNode()) {
196                 float obmat[4][4];
197                 // lights don't get their openGL matrix updated, do it now
198                 if (GetSGNode()->IsDirty())
199                         GetOpenGLMatrix();
200                 double *dobmat = GetOpenGLMatrixPtr()->getPointer();
201
202                 for (int i=0; i<4; i++)
203                         for (int j=0; j<4; j++, dobmat++)
204                                 obmat[i][j] = (float)*dobmat;
205
206                 GPU_lamp_update(lamp, m_lightobj.m_layer, 0, obmat);
207                 GPU_lamp_update_colors(lamp, m_lightobj.m_red, m_lightobj.m_green, 
208                         m_lightobj.m_blue, m_lightobj.m_energy);
209         }
210 }
211
212 bool KX_LightObject::HasShadowBuffer()
213 {
214         GPULamp *lamp;
215
216         if ((lamp = GetGPULamp()))
217                 return GPU_lamp_has_shadow_buffer(lamp);
218         else
219                 return false;
220 }
221
222 int KX_LightObject::GetShadowLayer()
223 {
224         GPULamp *lamp;
225
226         if ((lamp = GetGPULamp()))
227                 return GPU_lamp_shadow_layer(lamp);
228         else
229                 return 0;
230 }
231
232 void KX_LightObject::BindShadowBuffer(RAS_IRasterizer *ras, KX_Camera *cam, MT_Transform& camtrans)
233 {
234         GPULamp *lamp;
235         float viewmat[4][4], winmat[4][4];
236         int winsize;
237
238         /* bind framebuffer */
239         lamp = GetGPULamp();
240         GPU_lamp_shadow_buffer_bind(lamp, viewmat, &winsize, winmat);
241
242         /* setup camera transformation */
243         MT_Matrix4x4 modelviewmat((float*)viewmat);
244         MT_Matrix4x4 projectionmat((float*)winmat);
245
246         MT_Transform trans = MT_Transform((float*)viewmat);
247         camtrans.invert(trans);
248
249         cam->SetModelviewMatrix(modelviewmat);
250         cam->SetProjectionMatrix(projectionmat);
251         
252         cam->NodeSetLocalPosition(camtrans.getOrigin());
253         cam->NodeSetLocalOrientation(camtrans.getBasis());
254         cam->NodeUpdateGS(0);
255
256         /* setup rasterizer transformations */
257         /* SetViewMatrix may use stereomode which we temporarily disable here */
258         RAS_IRasterizer::StereoMode stereomode = ras->GetStereoMode();
259         ras->SetStereoMode(RAS_IRasterizer::RAS_STEREO_NOSTEREO);
260         ras->SetProjectionMatrix(projectionmat);
261         ras->SetViewMatrix(modelviewmat, cam->NodeGetWorldOrientation(), cam->NodeGetWorldPosition(), cam->GetCameraData()->m_perspective);
262         ras->SetStereoMode(stereomode);
263 }
264
265 void KX_LightObject::UnbindShadowBuffer(RAS_IRasterizer *ras)
266 {
267         GPULamp *lamp = GetGPULamp();
268         GPU_lamp_shadow_buffer_unbind(lamp);
269 }
270
271 struct Image *KX_LightObject::GetTextureImage(short texslot)
272 {
273         Lamp *la = (Lamp*)GetBlenderObject()->data;
274
275         if (texslot >= MAX_MTEX || texslot < 0)
276         {
277                 printf("KX_LightObject::GetTextureImage(): texslot exceeds slot bounds (0-%d)\n", MAX_MTEX-1);
278                 return NULL;
279         }
280         
281         if (la->mtex[texslot])
282                 return la->mtex[texslot]->tex->ima;
283
284         return NULL;
285 }
286
287 #ifdef WITH_PYTHON
288 /* ------------------------------------------------------------------------- */
289 /* Python Integration Hooks                                                                      */
290 /* ------------------------------------------------------------------------- */
291
292 PyTypeObject KX_LightObject::Type = {
293         PyVarObject_HEAD_INIT(NULL, 0)
294         "KX_LightObject",
295         sizeof(PyObjectPlus_Proxy),
296         0,
297         py_base_dealloc,
298         0,
299         0,
300         0,
301         0,
302         py_base_repr,
303         0,
304         &KX_GameObject::Sequence,
305         &KX_GameObject::Mapping,
306         0,0,0,
307         NULL,
308         NULL,
309         0,
310         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
311         0,0,0,0,0,0,0,
312         Methods,
313         0,
314         0,
315         &KX_GameObject::Type,
316         0,0,0,0,0,0,
317         py_base_new
318 };
319
320 PyMethodDef KX_LightObject::Methods[] = {
321         {NULL,NULL} //Sentinel
322 };
323
324 PyAttributeDef KX_LightObject::Attributes[] = {
325         KX_PYATTRIBUTE_INT_RW("layer", 1, 20, true, KX_LightObject, m_lightobj.m_layer),
326         KX_PYATTRIBUTE_FLOAT_RW("energy", 0, 10, KX_LightObject, m_lightobj.m_energy),
327         KX_PYATTRIBUTE_FLOAT_RW("distance", 0.01, 5000, KX_LightObject, m_lightobj.m_distance),
328         KX_PYATTRIBUTE_RW_FUNCTION("color", KX_LightObject, pyattr_get_color, pyattr_set_color),
329         KX_PYATTRIBUTE_FLOAT_RW("lin_attenuation", 0, 1, KX_LightObject, m_lightobj.m_att1),
330         KX_PYATTRIBUTE_FLOAT_RW("quad_attenuation", 0, 1, KX_LightObject, m_lightobj.m_att2),
331         KX_PYATTRIBUTE_FLOAT_RW("spotsize", 1, 180, KX_LightObject, m_lightobj.m_spotsize),
332         KX_PYATTRIBUTE_FLOAT_RW("spotblend", 0, 1, KX_LightObject, m_lightobj.m_spotblend),
333         KX_PYATTRIBUTE_RO_FUNCTION("SPOT", KX_LightObject, pyattr_get_typeconst),
334         KX_PYATTRIBUTE_RO_FUNCTION("SUN", KX_LightObject, pyattr_get_typeconst),
335         KX_PYATTRIBUTE_RO_FUNCTION("NORMAL", KX_LightObject, pyattr_get_typeconst),
336         KX_PYATTRIBUTE_RW_FUNCTION("type", KX_LightObject, pyattr_get_type, pyattr_set_type),
337         { NULL }        //Sentinel
338 };
339
340 PyObject* KX_LightObject::pyattr_get_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
341 {
342         KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
343         return Py_BuildValue("[fff]", self->m_lightobj.m_red, self->m_lightobj.m_green, self->m_lightobj.m_blue);
344 }
345
346 int KX_LightObject::pyattr_set_color(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
347 {
348         KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
349
350         MT_Vector3 color;
351         if (PyVecTo(value, color))
352         {
353                 self->m_lightobj.m_red = color[0];
354                 self->m_lightobj.m_green = color[1];
355                 self->m_lightobj.m_blue = color[2];
356                 return PY_SET_ATTR_SUCCESS;
357         }
358         return PY_SET_ATTR_FAIL;
359 }
360
361 PyObject* KX_LightObject::pyattr_get_typeconst(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
362 {
363         PyObject* retvalue;
364
365         const char* type = attrdef->m_name;
366
367         if (!strcmp(type, "SPOT")) {
368                 retvalue = PyLong_FromSsize_t(RAS_LightObject::LIGHT_SPOT);
369         } else if (!strcmp(type, "SUN")) {
370                 retvalue = PyLong_FromSsize_t(RAS_LightObject::LIGHT_SUN);
371         } else if (!strcmp(type, "NORMAL")) {
372                 retvalue = PyLong_FromSsize_t(RAS_LightObject::LIGHT_NORMAL);
373         }
374         else {
375                 /* should never happen */
376                 PyErr_SetString(PyExc_TypeError, "light.type: internal error, invalid light type");
377                 retvalue = NULL;
378         }
379
380         return retvalue;
381 }
382
383 PyObject* KX_LightObject::pyattr_get_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef)
384 {
385         KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
386         return PyLong_FromSsize_t(self->m_lightobj.m_type);
387 }
388
389 int KX_LightObject::pyattr_set_type(void* self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject* value)
390 {
391         KX_LightObject* self = static_cast<KX_LightObject*>(self_v);
392         int val = PyLong_AsSsize_t(value);
393         if ((val==-1 && PyErr_Occurred()) || val<0 || val>2) {
394                 PyErr_SetString(PyExc_ValueError, "light.type= val: KX_LightObject, expected an int between 0 and 2");
395                 return PY_SET_ATTR_FAIL;
396         }
397         
398         switch(val) {
399                 case 0:
400                         self->m_lightobj.m_type = self->m_lightobj.LIGHT_SPOT;
401                         break;
402                 case 1:
403                         self->m_lightobj.m_type = self->m_lightobj.LIGHT_SUN;
404                         break;
405                 case 2:
406                         self->m_lightobj.m_type = self->m_lightobj.LIGHT_NORMAL;
407                         break;
408         }
409
410         return PY_SET_ATTR_SUCCESS;
411 }
412 #endif // WITH_PYTHON