VideoTexture: Add support for GLSL. FIx small printout bug in Exception printout
[blender.git] / source / gameengine / VideoTexture / Texture.cpp
1 /* $Id$
2 -----------------------------------------------------------------------------
3 This source file is part of VideoTexture library
4
5 Copyright (c) 2007 The Zdeno Ash Miklas
6
7 This program is free software; you can redistribute it and/or modify it under
8 the terms of the GNU Lesser General Public License as published by the Free Software
9 Foundation; either version 2 of the License, or (at your option) any later
10 version.
11
12 This program is distributed in the hope that it will be useful, but WITHOUT
13 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along with
17 this program; if not, write to the Free Software Foundation, Inc., 59 Temple
18 Place - Suite 330, Boston, MA 02111-1307, USA, or go to
19 http://www.gnu.org/copyleft/lesser.txt.
20 -----------------------------------------------------------------------------
21 */
22
23 // implementation
24
25 #include <PyObjectPlus.h>
26 #include <structmember.h>
27
28 #include <KX_GameObject.h>
29 #include <RAS_MeshObject.h>
30 #include <DNA_mesh_types.h>
31 #include <DNA_meshdata_types.h>
32 #include <DNA_image_types.h>
33 #include <IMB_imbuf_types.h>
34 #include <BDR_drawmesh.h>
35 #include <KX_PolygonMaterial.h>
36
37 #include <MEM_guardedalloc.h>
38
39 #include <KX_BlenderMaterial.h>
40 #include <BL_Texture.h>
41
42 #include "KX_KetsjiEngine.h"
43 #include "KX_PythonInit.h"
44 #include "Texture.h"
45 #include "ImageBase.h"
46 #include "Exception.h"
47
48 #include <memory.h>
49 #include <BIF_gl.h>
50
51
52 // macro for exception handling and logging
53 #define CATCH_EXCP catch (Exception & exp) \
54 { exp.report(); }
55
56
57 // Blender GameObject type
58 BlendType<KX_GameObject> gameObjectType ("KX_GameObject");
59
60
61 // load texture
62 void loadTexture (unsigned int texId, unsigned int * texture, short * size,
63                                   bool mipmap)
64 {
65         // load texture for rendering
66         glBindTexture(GL_TEXTURE_2D, texId);
67         if (mipmap)
68         {
69                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
70                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
71                 gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, size[0], size[1], GL_RGBA, GL_UNSIGNED_BYTE, texture);
72         } 
73         else
74         {
75                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
76                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
77                 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, size[0], size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
78         }
79         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
80 }
81
82
83 // get pointer to material
84 RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID)
85 {
86         // if object is available
87         if (obj != NULL)
88         {
89                 // get pointer to texture image
90                 KX_GameObject * gameObj = gameObjectType.checkType(obj);
91                 if (gameObj != NULL && gameObj->GetMeshCount() > 0)
92                 {
93                         // get material from mesh
94                         RAS_MeshObject * mesh = gameObj->GetMesh(0);
95                         RAS_MeshMaterial *meshMat = mesh->GetMeshMaterial(matID);
96                         if (meshMat != NULL && meshMat->m_bucket != NULL)
97                                 // return pointer to polygon or blender material
98                                 return meshMat->m_bucket->GetPolyMaterial();
99                 }
100         }
101         // otherwise material was not found
102         return NULL;
103 }
104
105
106 // get material ID
107 short getMaterialID (PyObject * obj, char * name)
108 {
109         // search for material
110         for (short matID = 0;; ++matID)
111         {
112                 // get material
113                 RAS_IPolyMaterial * mat = getMaterial(obj, matID);
114                 // if material is not available, report that no material was found
115                 if (mat == NULL) break;
116                 // if material name matches
117                 if (strcmp(mat->GetMaterialName().ReadPtr(), name) == 0)
118                         // matID is found
119                         return matID;
120         }
121         // material was not found
122         return -1;
123 }
124
125
126 // Texture object allocation
127 PyObject * Texture_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
128 {
129         // allocate object
130         Texture * self = reinterpret_cast<Texture*>(type->tp_alloc(type, 0));
131         // initialize object structure
132         self->m_actTex = 0;
133         self->m_orgSaved = false;
134         self->m_imgTexture = NULL;
135         self->m_matTexture = NULL;
136         self->m_mipmap = false;
137         self->m_scaledImg = NULL;
138         self->m_scaledImgSize = 0;
139         self->m_source = NULL;
140         self->m_lastClock = 0.0;
141         // return allocated object
142         return reinterpret_cast<PyObject*>(self);
143 }
144
145
146 // forward declaration
147 PyObject * Texture_close(Texture * self);
148 int Texture_setSource (Texture * self, PyObject * value, void * closure);
149
150
151 // Texture object deallocation
152 void Texture_dealloc (Texture * self)
153 {
154         // release renderer
155         Py_XDECREF(self->m_source);
156         // close texture
157         Texture_close(self);
158         // release scaled image buffer
159         delete [] self->m_scaledImg;
160         // release object
161         self->ob_type->tp_free((PyObject*)self);
162 }
163
164
165 ExceptionID MaterialNotAvail;
166 ExpDesc MaterialNotAvailDesc (MaterialNotAvail, "Texture material is not available");
167
168 // Texture object initialization
169 int Texture_init (Texture *self, PyObject *args, PyObject *kwds)
170 {
171         // parameters - game object with video texture
172         PyObject * obj = NULL;
173         // material ID
174         short matID = 0;
175         // texture ID
176         short texID = 0;
177         // texture object with shared texture ID
178         Texture * texObj = NULL;
179
180         static char *kwlist[] = {"gameObj", "materialID", "textureID", "textureObj", NULL};
181
182         // get parameters
183         if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhO!", kwlist, &obj, &matID,
184                 &texID, &TextureType, &texObj))
185                 return -1; 
186
187         // if parameters are available
188         if (obj != NULL)
189         {
190                 // process polygon material or blender material
191                 try
192                 {
193                         // get pointer to texture image
194                         RAS_IPolyMaterial * mat = getMaterial(obj, matID);
195                         if (mat != NULL)
196                         {
197                                 // is it blender material or polygon material
198                                 if (mat->GetFlag() & RAS_BLENDERGLSL) 
199                                 {
200                                         self->m_imgTexture = static_cast<KX_BlenderMaterial*>(mat)->getImage(texID);
201                                         self->m_useMatTexture = false;
202                                 } else if (mat->GetFlag() & RAS_BLENDERMAT)
203                                 {
204                                         // get blender material texture
205                                         self->m_matTexture = static_cast<KX_BlenderMaterial*>(mat)->getTex(texID);
206                                         self->m_useMatTexture = true;
207                                 }
208                                 else
209                                 {
210                                         // get texture pointer from polygon material
211                                         MTFace * tface = static_cast<KX_PolygonMaterial*>(mat)->GetMTFace();
212                                         self->m_imgTexture = (Image*)tface->tpage;
213                                         self->m_useMatTexture = false;
214                                 }
215                         }
216                         // check if texture is available, if not, initialization failed
217                         if (self->m_imgTexture == NULL && self->m_matTexture == NULL)
218                                 // throw exception if initialization failed
219                                 THRWEXCP(MaterialNotAvail, S_OK);
220
221                         // if texture object is provided
222                         if (texObj != NULL)
223                         {
224                                 // copy texture code
225                                 self->m_actTex = texObj->m_actTex;
226                                 self->m_mipmap = texObj->m_mipmap;
227                                 if (texObj->m_source != NULL)
228                                         Texture_setSource(self, reinterpret_cast<PyObject*>(texObj->m_source), NULL);
229                         }
230                         else
231                                 // otherwise generate texture code
232                                 glGenTextures(1, (GLuint*)&self->m_actTex);
233                 }
234                 catch (Exception & exp)
235                 {
236                         exp.report();
237                         return -1;
238                 }
239         }
240         // initialization succeded
241         return 0;
242 }
243
244
245 // close added texture
246 PyObject * Texture_close(Texture * self)
247 {
248         // restore texture
249         if (self->m_orgSaved)
250         {
251                 self->m_orgSaved = false;
252                 // restore original texture code
253                 if (self->m_useMatTexture)
254                         self->m_matTexture->swapTexture(self->m_orgTex);
255                 else
256                         self->m_imgTexture->bindcode = self->m_orgTex;
257                 // drop actual texture
258                 if (self->m_actTex != 0)
259                 {
260                         glDeleteTextures(1, (GLuint *)&self->m_actTex);
261                         self->m_actTex = 0;
262                 }
263         }
264         Py_RETURN_NONE;
265 }
266
267
268 // refresh texture
269 PyObject * Texture_refresh (Texture * self, PyObject * args)
270 {
271         // get parameter - refresh source
272         PyObject * param;
273         if (!PyArg_ParseTuple(args, "O", &param) || !PyBool_Check(param))
274         {
275                 // report error
276                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
277                 return NULL;
278         }
279         // some trick here: we are in the business of loading a texture,
280         // no use to do it if we are still in the same rendering frame.
281         // We find this out by looking at the engine current clock time
282         KX_KetsjiEngine* engine = KX_GetActiveEngine();
283         if (engine->GetClockTime() != self->m_lastClock) 
284         {
285                 self->m_lastClock = engine->GetClockTime();
286                 // set source refresh
287                 bool refreshSource = (param == Py_True);
288                 // try to proces texture from source
289                 try
290                 {
291                         // if source is available
292                         if (self->m_source != NULL)
293                         {
294                                 // check texture code
295                                 if (!self->m_orgSaved)
296                                 {
297                                         self->m_orgSaved = true;
298                                         // save original image code
299                                         if (self->m_useMatTexture)
300                                                 self->m_orgTex = self->m_matTexture->swapTexture(self->m_actTex);
301                                         else
302                                         {
303                                                 self->m_orgTex = self->m_imgTexture->bindcode;
304                                                 self->m_imgTexture->bindcode = self->m_actTex;
305                                         }
306                                 }
307
308                                 // get texture
309                                 unsigned int * texture = self->m_source->m_image->getImage(self->m_actTex);
310                                 // if texture is available
311                                 if (texture != NULL)
312                                 {
313                                         // get texture size
314                                         short * orgSize = self->m_source->m_image->getSize();
315                                         // calc scaled sizes
316                                         short size[] = {ImageBase::calcSize(orgSize[0]), ImageBase::calcSize(orgSize[1])};
317                                         // scale texture if needed
318                                         if (size[0] != orgSize[0] || size[1] != orgSize[1])
319                                         {
320                                                 // if scaled image buffer is smaller than needed
321                                                 if (self->m_scaledImgSize < (unsigned int)(size[0] * size[1]))
322                                                 {
323                                                         // new size
324                                                         self->m_scaledImgSize = size[0] * size[1];
325                                                         // allocate scaling image
326                                                         delete [] self->m_scaledImg;
327                                                         self->m_scaledImg = new unsigned int[self->m_scaledImgSize];
328                                                 }
329                                                 // scale texture
330                                                 gluScaleImage(GL_RGBA, orgSize[0], orgSize[1], GL_UNSIGNED_BYTE, texture,
331                                                         size[0], size[1], GL_UNSIGNED_BYTE, self->m_scaledImg);
332                                                 // use scaled image instead original
333                                                 texture = self->m_scaledImg;
334                                         }
335                                         // load texture for rendering
336                                         loadTexture (self->m_actTex, texture, size, self->m_mipmap);
337
338                                         // refresh texture source, if required
339                                         if (refreshSource) self->m_source->m_image->refresh();
340                                 }
341                         }
342                 }
343                 CATCH_EXCP;
344         }
345         Py_RETURN_NONE;
346 }
347
348
349 // get mipmap value
350 PyObject * Texture_getMipmap (Texture * self, void * closure)
351 {
352         // return true if flag is set, otherwise false
353         if (self->m_mipmap) Py_RETURN_TRUE;
354         else Py_RETURN_FALSE;
355 }
356
357 // set mipmap value
358 int Texture_setMipmap (Texture * self, PyObject * value, void * closure)
359 {
360         // check parameter, report failure
361         if (value == NULL || !PyBool_Check(value))
362         {
363                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
364                 return -1;
365         }
366         // set mipmap
367         self->m_mipmap = value == Py_True;
368         // success
369         return 0;
370 }
371
372
373 // get source object
374 PyObject * Texture_getSource (Texture * self, PyObject * value, void * closure)
375 {
376         // if source exists
377         if (self->m_source != NULL)
378         {
379                 Py_INCREF(self->m_source);
380                 return reinterpret_cast<PyObject*>(self->m_source);
381         }
382         // otherwise return None
383         Py_RETURN_NONE;
384 }
385
386
387 // set source object
388 int Texture_setSource (Texture * self, PyObject * value, void * closure)
389 {
390         // check new value
391         if (value == NULL || !pyImageTypes.in(value->ob_type))
392         {
393                 // report value error
394                 PyErr_SetString(PyExc_TypeError, "Invalid type of value");
395                 return -1;
396         }
397         // increase ref count for new value
398         Py_INCREF(value);
399         // release previous
400         Py_XDECREF(self->m_source);
401         // set new value
402         self->m_source = reinterpret_cast<PyImage*>(value);
403         // return success
404         return 0;
405 }
406
407
408 // class Texture methods
409 static PyMethodDef textureMethods[] =
410 {
411         { "close", (PyCFunction)Texture_close, METH_NOARGS, "Close dynamic texture and restore original"},
412         { "refresh", (PyCFunction)Texture_refresh, METH_VARARGS, "Refresh texture from source"},
413         {NULL}  /* Sentinel */
414 };
415
416 // class Texture attributes
417 static PyGetSetDef textureGetSets[] =
418
419         {(char*)"source", (getter)Texture_getSource, (setter)Texture_setSource, (char*)"source of texture", NULL},
420         {(char*)"mipmap", (getter)Texture_getMipmap, (setter)Texture_setMipmap, (char*)"mipmap texture", NULL},
421         {NULL}
422 };
423
424
425 // class Texture declaration
426 PyTypeObject TextureType =
427 {
428         PyObject_HEAD_INIT(NULL)
429         0,                         /*ob_size*/
430         "VideoTexture.Texture",   /*tp_name*/
431         sizeof(Texture),           /*tp_basicsize*/
432         0,                         /*tp_itemsize*/
433         (destructor)Texture_dealloc,/*tp_dealloc*/
434         0,                         /*tp_print*/
435         0,                         /*tp_getattr*/
436         0,                         /*tp_setattr*/
437         0,                         /*tp_compare*/
438         0,                         /*tp_repr*/
439         0,                         /*tp_as_number*/
440         0,                         /*tp_as_sequence*/
441         0,                         /*tp_as_mapping*/
442         0,                         /*tp_hash */
443         0,                         /*tp_call*/
444         0,                         /*tp_str*/
445         0,                         /*tp_getattro*/
446         0,                         /*tp_setattro*/
447         0,                         /*tp_as_buffer*/
448         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
449         "Texture objects",       /* tp_doc */
450         0,                             /* tp_traverse */
451         0,                             /* tp_clear */
452         0,                             /* tp_richcompare */
453         0,                             /* tp_weaklistoffset */
454         0,                             /* tp_iter */
455         0,                             /* tp_iternext */
456         textureMethods,      /* tp_methods */
457         0,                   /* tp_members */
458         textureGetSets,            /* tp_getset */
459         0,                         /* tp_base */
460         0,                         /* tp_dict */
461         0,                         /* tp_descr_get */
462         0,                         /* tp_descr_set */
463         0,                         /* tp_dictoffset */
464         (initproc)Texture_init,    /* tp_init */
465         0,                         /* tp_alloc */
466         Texture_new,               /* tp_new */
467 };