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