Recreating my GSoC branch.
[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 <KX_PolygonMaterial.h>
35
36 #include <MEM_guardedalloc.h>
37
38 #include <KX_BlenderMaterial.h>
39 #include <BL_Texture.h>
40
41 #include "KX_KetsjiEngine.h"
42 #include "KX_PythonInit.h"
43 #include "Texture.h"
44 #include "ImageBase.h"
45 #include "Exception.h"
46
47 #include <memory.h>
48 #include "GL/glew.h"
49
50
51 // macro for exception handling and logging
52 #define CATCH_EXCP catch (Exception & exp) \
53 { exp.report(); return NULL; }
54
55
56 // Blender GameObject type
57 BlendType<KX_GameObject> gameObjectType ("KX_GameObject");
58
59
60 // load texture
61 void loadTexture (unsigned int texId, unsigned int * texture, short * size,
62                                   bool mipmap)
63 {
64         // load texture for rendering
65         glBindTexture(GL_TEXTURE_2D, texId);
66         if (mipmap)
67         {
68                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
69                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
70                 gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, size[0], size[1], GL_RGBA, GL_UNSIGNED_BYTE, texture);
71         } 
72         else
73         {
74                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
75                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
76                 glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, size[0], size[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
77         }
78         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
79 }
80
81
82 // get pointer to material
83 RAS_IPolyMaterial * getMaterial (PyObject *obj, short matID)
84 {
85         // if object is available
86         if (obj != NULL)
87         {
88                 // get pointer to texture image
89                 KX_GameObject * gameObj = gameObjectType.checkType(obj);
90                 if (gameObj != NULL && gameObj->GetMeshCount() > 0)
91                 {
92                         // get material from mesh
93                         RAS_MeshObject * mesh = gameObj->GetMesh(0);
94                         RAS_MeshMaterial *meshMat = mesh->GetMeshMaterial(matID);
95                         if (meshMat != NULL && meshMat->m_bucket != NULL)
96                                 // return pointer to polygon or blender material
97                                 return meshMat->m_bucket->GetPolyMaterial();
98                 }
99         }
100         // otherwise material was not found
101         return NULL;
102 }
103
104
105 // get material ID
106 short getMaterialID (PyObject * obj, char * name)
107 {
108         // search for material
109         for (short matID = 0;; ++matID)
110         {
111                 // get material
112                 RAS_IPolyMaterial * mat = getMaterial(obj, matID);
113                 // if material is not available, report that no material was found
114                 if (mat == NULL) 
115                         break;
116                 // name is a material name if it starts with MA and a UV texture name if it starts with IM
117                 if (name[0] == 'I' && name[1] == 'M')
118                 {
119                         // if texture name matches
120                         if (strcmp(mat->GetTextureName().ReadPtr(), name) == 0)
121                                 return matID;
122                 } else 
123                 {
124                         // if material name matches
125                         if (strcmp(mat->GetMaterialName().ReadPtr(), name) == 0)
126                                 return matID;
127                 }
128         }
129         // material was not found
130         return -1;
131 }
132
133
134 // Texture object allocation
135 PyObject * Texture_new (PyTypeObject *type, PyObject *args, PyObject *kwds)
136 {
137         // allocate object
138         Texture * self = reinterpret_cast<Texture*>(type->tp_alloc(type, 0));
139         // initialize object structure
140         self->m_actTex = 0;
141         self->m_orgSaved = false;
142         self->m_imgTexture = NULL;
143         self->m_matTexture = NULL;
144         self->m_mipmap = false;
145         self->m_scaledImg = NULL;
146         self->m_scaledImgSize = 0;
147         self->m_source = NULL;
148         self->m_lastClock = 0.0;
149         // return allocated object
150         return reinterpret_cast<PyObject*>(self);
151 }
152
153
154 // forward declaration
155 PyObject * Texture_close(Texture * self);
156 int Texture_setSource (Texture * self, PyObject * value, void * closure);
157
158
159 // Texture object deallocation
160 void Texture_dealloc (Texture * self)
161 {
162         // release renderer
163         Py_XDECREF(self->m_source);
164         // close texture
165         PyObject* ret = Texture_close(self);
166         Py_DECREF(ret);
167         // release scaled image buffer
168         delete [] self->m_scaledImg;
169         // release object
170         ((PyObject *)self)->ob_type->tp_free((PyObject*)self);
171 }
172
173
174 ExceptionID MaterialNotAvail;
175 ExpDesc MaterialNotAvailDesc (MaterialNotAvail, "Texture material is not available");
176
177 // Texture object initialization
178 int Texture_init (Texture *self, PyObject *args, PyObject *kwds)
179 {
180         // parameters - game object with video texture
181         PyObject * obj = NULL;
182         // material ID
183         short matID = 0;
184         // texture ID
185         short texID = 0;
186         // texture object with shared texture ID
187         Texture * texObj = NULL;
188
189         static const char *kwlist[] = {"gameObj", "materialID", "textureID", "textureObj", NULL};
190
191         // get parameters
192         if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|hhO!",
193                 const_cast<char**>(kwlist), &obj, &matID, &texID, &TextureType,
194                 &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         double ts = -1.0;
284
285         if (!PyArg_ParseTuple(args, "O|d:refresh", &param, &ts) || !PyBool_Check(param))
286         {
287                 // report error
288                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
289                 return NULL;
290         }
291         // some trick here: we are in the business of loading a texture,
292         // no use to do it if we are still in the same rendering frame.
293         // We find this out by looking at the engine current clock time
294         KX_KetsjiEngine* engine = KX_GetActiveEngine();
295         if (engine->GetClockTime() != self->m_lastClock) 
296         {
297                 self->m_lastClock = engine->GetClockTime();
298                 // set source refresh
299                 bool refreshSource = (param == Py_True);
300                 // try to proces texture from source
301                 try
302                 {
303                         // if source is available
304                         if (self->m_source != NULL)
305                         {
306                                 // check texture code
307                                 if (!self->m_orgSaved)
308                                 {
309                                         self->m_orgSaved = true;
310                                         // save original image code
311                                         if (self->m_useMatTexture)
312                                                 self->m_orgTex = self->m_matTexture->swapTexture(self->m_actTex);
313                                         else
314                                         {
315                                                 self->m_orgTex = self->m_imgTexture->bindcode;
316                                                 self->m_imgTexture->bindcode = self->m_actTex;
317                                         }
318                                 }
319
320                                 // get texture
321                                 unsigned int * texture = self->m_source->m_image->getImage(self->m_actTex, ts);
322                                 // if texture is available
323                                 if (texture != NULL)
324                                 {
325                                         // get texture size
326                                         short * orgSize = self->m_source->m_image->getSize();
327                                         // calc scaled sizes
328                                         short size[] = {ImageBase::calcSize(orgSize[0]), ImageBase::calcSize(orgSize[1])};
329                                         // scale texture if needed
330                                         if (size[0] != orgSize[0] || size[1] != orgSize[1])
331                                         {
332                                                 // if scaled image buffer is smaller than needed
333                                                 if (self->m_scaledImgSize < (unsigned int)(size[0] * size[1]))
334                                                 {
335                                                         // new size
336                                                         self->m_scaledImgSize = size[0] * size[1];
337                                                         // allocate scaling image
338                                                         delete [] self->m_scaledImg;
339                                                         self->m_scaledImg = new unsigned int[self->m_scaledImgSize];
340                                                 }
341                                                 // scale texture
342                                                 gluScaleImage(GL_RGBA, orgSize[0], orgSize[1], GL_UNSIGNED_BYTE, texture,
343                                                         size[0], size[1], GL_UNSIGNED_BYTE, self->m_scaledImg);
344                                                 // use scaled image instead original
345                                                 texture = self->m_scaledImg;
346                                         }
347                                         // load texture for rendering
348                                         loadTexture (self->m_actTex, texture, size, self->m_mipmap);
349
350                                         // refresh texture source, if required
351                                         if (refreshSource) self->m_source->m_image->refresh();
352                                 }
353                         }
354                 }
355                 CATCH_EXCP;
356         }
357         Py_RETURN_NONE;
358 }
359
360 // get OpenGL Bind Id
361 PyObject * Texture_getBindId (Texture * self, void * closure)
362 {
363         unsigned int id = self->m_actTex;
364         return Py_BuildValue("h", id);
365 }
366
367 // get mipmap value
368 PyObject * Texture_getMipmap (Texture * self, void * closure)
369 {
370         // return true if flag is set, otherwise false
371         if (self->m_mipmap) Py_RETURN_TRUE;
372         else Py_RETURN_FALSE;
373 }
374
375 // set mipmap value
376 int Texture_setMipmap (Texture * self, PyObject * value, void * closure)
377 {
378         // check parameter, report failure
379         if (value == NULL || !PyBool_Check(value))
380         {
381                 PyErr_SetString(PyExc_TypeError, "The value must be a bool");
382                 return -1;
383         }
384         // set mipmap
385         self->m_mipmap = value == Py_True;
386         // success
387         return 0;
388 }
389
390
391 // get source object
392 PyObject * Texture_getSource (Texture * self, PyObject * value, void * closure)
393 {
394         // if source exists
395         if (self->m_source != NULL)
396         {
397                 Py_INCREF(self->m_source);
398                 return reinterpret_cast<PyObject*>(self->m_source);
399         }
400         // otherwise return None
401         Py_RETURN_NONE;
402 }
403
404
405 // set source object
406 int Texture_setSource (Texture * self, PyObject * value, void * closure)
407 {
408         // check new value
409         if (value == NULL || !pyImageTypes.in(value->ob_type))
410         {
411                 // report value error
412                 PyErr_SetString(PyExc_TypeError, "Invalid type of value");
413                 return -1;
414         }
415         // increase ref count for new value
416         Py_INCREF(value);
417         // release previous
418         Py_XDECREF(self->m_source);
419         // set new value
420         self->m_source = reinterpret_cast<PyImage*>(value);
421         // return success
422         return 0;
423 }
424
425
426 // class Texture methods
427 static PyMethodDef textureMethods[] =
428 {
429         { "close", (PyCFunction)Texture_close, METH_NOARGS, "Close dynamic texture and restore original"},
430         { "refresh", (PyCFunction)Texture_refresh, METH_VARARGS, "Refresh texture from source"},
431         {NULL}  /* Sentinel */
432 };
433
434 // class Texture attributes
435 static PyGetSetDef textureGetSets[] =
436
437         {(char*)"source", (getter)Texture_getSource, (setter)Texture_setSource, (char*)"source of texture", NULL},
438         {(char*)"mipmap", (getter)Texture_getMipmap, (setter)Texture_setMipmap, (char*)"mipmap texture", NULL},
439         {(char*)"bindId", (getter)Texture_getBindId, NULL, (char*)"OpenGL Bind Name", NULL},
440         {NULL}
441 };
442
443
444 // class Texture declaration
445 PyTypeObject TextureType =
446 {
447         PyVarObject_HEAD_INIT(NULL, 0)
448         "VideoTexture.Texture",   /*tp_name*/
449         sizeof(Texture),           /*tp_basicsize*/
450         0,                         /*tp_itemsize*/
451         (destructor)Texture_dealloc,/*tp_dealloc*/
452         0,                         /*tp_print*/
453         0,                         /*tp_getattr*/
454         0,                         /*tp_setattr*/
455         0,                         /*tp_compare*/
456         0,                         /*tp_repr*/
457         0,                         /*tp_as_number*/
458         0,                         /*tp_as_sequence*/
459         0,                         /*tp_as_mapping*/
460         0,                         /*tp_hash */
461         0,                         /*tp_call*/
462         0,                         /*tp_str*/
463         0,                         /*tp_getattro*/
464         0,                         /*tp_setattro*/
465         &imageBufferProcs,         /*tp_as_buffer*/
466         Py_TPFLAGS_DEFAULT,        /*tp_flags*/
467         "Texture objects",       /* tp_doc */
468         0,                             /* tp_traverse */
469         0,                             /* tp_clear */
470         0,                             /* tp_richcompare */
471         0,                             /* tp_weaklistoffset */
472         0,                             /* tp_iter */
473         0,                             /* tp_iternext */
474         textureMethods,      /* tp_methods */
475         0,                   /* tp_members */
476         textureGetSets,            /* tp_getset */
477         0,                         /* tp_base */
478         0,                         /* tp_dict */
479         0,                         /* tp_descr_get */
480         0,                         /* tp_descr_set */
481         0,                         /* tp_dictoffset */
482         (initproc)Texture_init,    /* tp_init */
483         0,                         /* tp_alloc */
484         Texture_new,               /* tp_new */
485 };