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