BGE VideoTexture: fix bug with VideoTexture.materialID() since recent commit.
[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) 
116                         break;
117                 // name is a material name if it starts with MA and a UV texture name if it starts with IM
118                 if (name[0] == 'I' && name[1] == 'M')
119                 {
120                         // if texture name matches
121                         if (strcmp(mat->GetTextureName().ReadPtr(), name) == 0)
122                                 return matID;
123                 } else 
124                 {
125                         // if material name matches
126                         if (strcmp(mat->GetMaterialName().ReadPtr(), name) == 0)
127                                 return matID;
128                 }
129         }
130         // material was not found
131         return -1;
132 }
133
134
135 // Texture object allocation
136 PyObject * Texture_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
137 {
138         // allocate object
139         Texture * self = reinterpret_cast<Texture*>(type->tp_alloc(type, 0));
140         // initialize object structure
141         self->m_actTex = 0;
142         self->m_orgSaved = false;
143         self->m_imgTexture = NULL;
144         self->m_matTexture = NULL;
145         self->m_mipmap = false;
146         self->m_scaledImg = NULL;
147         self->m_scaledImgSize = 0;
148         self->m_source = NULL;
149         self->m_lastClock = 0.0;
150         // return allocated object
151         return reinterpret_cast<PyObject*>(self);
152 }
153
154
155 // forward declaration
156 PyObject * Texture_close(Texture * self);
157 int Texture_setSource (Texture * self, PyObject * value, void * closure);
158
159
160 // Texture object deallocation
161 void Texture_dealloc (Texture * self)
162 {
163         // release renderer
164         Py_XDECREF(self->m_source);
165         // close texture
166         PyObject* ret = Texture_close(self);
167         Py_DECREF(ret);
168         // release scaled image buffer
169         delete [] self->m_scaledImg;
170         // release object
171         self->ob_type->tp_free((PyObject*)self);
172 }
173
174
175 ExceptionID MaterialNotAvail;
176 ExpDesc MaterialNotAvailDesc (MaterialNotAvail, "Texture material is not available");
177
178 // Texture object initialization
179 int Texture_init (Texture *self, PyObject *args, PyObject *kwds)
180 {
181         // parameters - game object with video texture
182         PyObject * obj = NULL;
183         // material ID
184         short matID = 0;
185         // texture ID
186         short texID = 0;
187         // texture object with shared texture ID
188         Texture * texObj = NULL;
189
190         static char *kwlist[] = {"gameObj", "materialID", "textureID", "textureObj", NULL};
191
192         // get parameters
193         if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhO!", kwlist, &obj, &matID,
194                 &texID, &TextureType, &texObj))
195                 return -1; 
196
197         // if parameters are available
198         if (obj != NULL)
199         {
200                 // process polygon material or blender material
201                 try
202                 {
203                         // get pointer to texture image
204                         RAS_IPolyMaterial * mat = getMaterial(obj, matID);
205                         if (mat != NULL)
206                         {
207                                 // is it blender material or polygon material
208                                 if (mat->GetFlag() & RAS_BLENDERGLSL) 
209                                 {
210                                         self->m_imgTexture = static_cast<KX_BlenderMaterial*>(mat)->getImage(texID);
211                                         self->m_useMatTexture = false;
212                                 } else if (mat->GetFlag() & RAS_BLENDERMAT)
213                                 {
214                                         // get blender material texture
215                                         self->m_matTexture = static_cast<KX_BlenderMaterial*>(mat)->getTex(texID);
216                                         self->m_useMatTexture = true;
217                                 }
218                                 else
219                                 {
220                                         // get texture pointer from polygon material
221                                         MTFace * tface = static_cast<KX_PolygonMaterial*>(mat)->GetMTFace();
222                                         self->m_imgTexture = (Image*)tface->tpage;
223                                         self->m_useMatTexture = false;
224                                 }
225                         }
226                         // check if texture is available, if not, initialization failed
227                         if (self->m_imgTexture == NULL && self->m_matTexture == NULL)
228                                 // throw exception if initialization failed
229                                 THRWEXCP(MaterialNotAvail, S_OK);
230
231                         // if texture object is provided
232                         if (texObj != NULL)
233                         {
234                                 // copy texture code
235                                 self->m_actTex = texObj->m_actTex;
236                                 self->m_mipmap = texObj->m_mipmap;
237                                 if (texObj->m_source != NULL)
238                                         Texture_setSource(self, reinterpret_cast<PyObject*>(texObj->m_source), NULL);
239                         }
240                         else
241                                 // otherwise generate texture code
242                                 glGenTextures(1, (GLuint*)&self->m_actTex);
243                 }
244                 catch (Exception & exp)
245                 {
246                         exp.report();
247                         return -1;
248                 }
249         }
250         // initialization succeded
251         return 0;
252 }
253
254
255 // close added texture
256 PyObject * Texture_close(Texture * self)
257 {
258         // restore texture
259         if (self->m_orgSaved)
260         {
261                 self->m_orgSaved = false;
262                 // restore original texture code
263                 if (self->m_useMatTexture)
264                         self->m_matTexture->swapTexture(self->m_orgTex);
265                 else
266                         self->m_imgTexture->bindcode = self->m_orgTex;
267                 // drop actual texture
268                 if (self->m_actTex != 0)
269                 {
270                         glDeleteTextures(1, (GLuint *)&self->m_actTex);
271                         self->m_actTex = 0;
272                 }
273         }
274         Py_RETURN_NONE;
275 }
276
277
278 // refresh texture
279 PyObject * Texture_refresh (Texture * self, PyObject * args)
280 {
281         // get parameter - refresh source
282         PyObject * param;
283         if (!PyArg_ParseTuple(args, "O", &param) || !PyBool_Check(param))
284         {
285                 // report error
286                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
287                 return NULL;
288         }
289         // some trick here: we are in the business of loading a texture,
290         // no use to do it if we are still in the same rendering frame.
291         // We find this out by looking at the engine current clock time
292         KX_KetsjiEngine* engine = KX_GetActiveEngine();
293         if (engine->GetClockTime() != self->m_lastClock) 
294         {
295                 self->m_lastClock = engine->GetClockTime();
296                 // set source refresh
297                 bool refreshSource = (param == Py_True);
298                 // try to proces texture from source
299                 try
300                 {
301                         // if source is available
302                         if (self->m_source != NULL)
303                         {
304                                 // check texture code
305                                 if (!self->m_orgSaved)
306                                 {
307                                         self->m_orgSaved = true;
308                                         // save original image code
309                                         if (self->m_useMatTexture)
310                                                 self->m_orgTex = self->m_matTexture->swapTexture(self->m_actTex);
311                                         else
312                                         {
313                                                 self->m_orgTex = self->m_imgTexture->bindcode;
314                                                 self->m_imgTexture->bindcode = self->m_actTex;
315                                         }
316                                 }
317
318                                 // get texture
319                                 unsigned int * texture = self->m_source->m_image->getImage(self->m_actTex);
320                                 // if texture is available
321                                 if (texture != NULL)
322                                 {
323                                         // get texture size
324                                         short * orgSize = self->m_source->m_image->getSize();
325                                         // calc scaled sizes
326                                         short size[] = {ImageBase::calcSize(orgSize[0]), ImageBase::calcSize(orgSize[1])};
327                                         // scale texture if needed
328                                         if (size[0] != orgSize[0] || size[1] != orgSize[1])
329                                         {
330                                                 // if scaled image buffer is smaller than needed
331                                                 if (self->m_scaledImgSize < (unsigned int)(size[0] * size[1]))
332                                                 {
333                                                         // new size
334                                                         self->m_scaledImgSize = size[0] * size[1];
335                                                         // allocate scaling image
336                                                         delete [] self->m_scaledImg;
337                                                         self->m_scaledImg = new unsigned int[self->m_scaledImgSize];
338                                                 }
339                                                 // scale texture
340                                                 gluScaleImage(GL_RGBA, orgSize[0], orgSize[1], GL_UNSIGNED_BYTE, texture,
341                                                         size[0], size[1], GL_UNSIGNED_BYTE, self->m_scaledImg);
342                                                 // use scaled image instead original
343                                                 texture = self->m_scaledImg;
344                                         }
345                                         // load texture for rendering
346                                         loadTexture (self->m_actTex, texture, size, self->m_mipmap);
347
348                                         // refresh texture source, if required
349                                         if (refreshSource) self->m_source->m_image->refresh();
350                                 }
351                         }
352                 }
353                 CATCH_EXCP;
354         }
355         Py_RETURN_NONE;
356 }
357
358
359 // get mipmap value
360 PyObject * Texture_getMipmap (Texture * self, void * closure)
361 {
362         // return true if flag is set, otherwise false
363         if (self->m_mipmap) Py_RETURN_TRUE;
364         else Py_RETURN_FALSE;
365 }
366
367 // set mipmap value
368 int Texture_setMipmap (Texture * self, PyObject * value, void * closure)
369 {
370         // check parameter, report failure
371         if (value == NULL || !PyBool_Check(value))
372         {
373                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
374                 return -1;
375         }
376         // set mipmap
377         self->m_mipmap = value == Py_True;
378         // success
379         return 0;
380 }
381
382
383 // get source object
384 PyObject * Texture_getSource (Texture * self, PyObject * value, void * closure)
385 {
386         // if source exists
387         if (self->m_source != NULL)
388         {
389                 Py_INCREF(self->m_source);
390                 return reinterpret_cast<PyObject*>(self->m_source);
391         }
392         // otherwise return None
393         Py_RETURN_NONE;
394 }
395
396
397 // set source object
398 int Texture_setSource (Texture * self, PyObject * value, void * closure)
399 {
400         // check new value
401         if (value == NULL || !pyImageTypes.in(value->ob_type))
402         {
403                 // report value error
404                 PyErr_SetString(PyExc_TypeError, "Invalid type of value");
405                 return -1;
406         }
407         // increase ref count for new value
408         Py_INCREF(value);
409         // release previous
410         Py_XDECREF(self->m_source);
411         // set new value
412         self->m_source = reinterpret_cast<PyImage*>(value);
413         // return success
414         return 0;
415 }
416
417
418 // class Texture methods
419 static PyMethodDef textureMethods[] =
420 {
421         { "close", (PyCFunction)Texture_close, METH_NOARGS, "Close dynamic texture and restore original"},
422         { "refresh", (PyCFunction)Texture_refresh, METH_VARARGS, "Refresh texture from source"},
423         {NULL}  /* Sentinel */
424 };
425
426 // class Texture attributes
427 static PyGetSetDef textureGetSets[] =
428
429         {(char*)"source", (getter)Texture_getSource, (setter)Texture_setSource, (char*)"source of texture", NULL},
430         {(char*)"mipmap", (getter)Texture_getMipmap, (setter)Texture_setMipmap, (char*)"mipmap texture", NULL},
431         {NULL}
432 };
433
434
435 // class Texture declaration
436 PyTypeObject TextureType =
437 {
438         PyObject_HEAD_INIT(NULL)
439         0,                         /*ob_size*/
440         "VideoTexture.Texture",   /*tp_name*/
441         sizeof(Texture),           /*tp_basicsize*/
442         0,                         /*tp_itemsize*/
443         (destructor)Texture_dealloc,/*tp_dealloc*/
444         0,                         /*tp_print*/
445         0,                         /*tp_getattr*/
446         0,                         /*tp_setattr*/
447         0,                         /*tp_compare*/
448         0,                         /*tp_repr*/
449         0,                         /*tp_as_number*/
450         0,                         /*tp_as_sequence*/
451         0,                         /*tp_as_mapping*/
452         0,                         /*tp_hash */
453         0,                         /*tp_call*/
454         0,                         /*tp_str*/
455         0,                         /*tp_getattro*/
456         0,                         /*tp_setattro*/
457         0,                         /*tp_as_buffer*/
458         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
459         "Texture objects",       /* tp_doc */
460         0,                             /* tp_traverse */
461         0,                             /* tp_clear */
462         0,                             /* tp_richcompare */
463         0,                             /* tp_weaklistoffset */
464         0,                             /* tp_iter */
465         0,                             /* tp_iternext */
466         textureMethods,      /* tp_methods */
467         0,                   /* tp_members */
468         textureGetSets,            /* tp_getset */
469         0,                         /* tp_base */
470         0,                         /* tp_dict */
471         0,                         /* tp_descr_get */
472         0,                         /* tp_descr_set */
473         0,                         /* tp_dictoffset */
474         (initproc)Texture_init,    /* tp_init */
475         0,                         /* tp_alloc */
476         Texture_new,               /* tp_new */
477 };