04454f8232a47a81f113f97a5c4b6fdb3734c22c
[blender.git] / source / gameengine / Expressions / PyObjectPlus.cpp
1 /**
2  * $Id$
3  * ***** BEGIN GPL LICENSE BLOCK *****
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software Foundation,
17  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18  *
19  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
20  * All rights reserved.
21  *
22  * The Original Code is: all of this file.
23  *
24  * Contributor(s): none yet.
25  *
26  * ***** END GPL LICENSE BLOCK *****
27  */
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32
33 #ifndef NO_EXP_PYTHON_EMBEDDING
34
35 /*------------------------------
36  * PyObjectPlus cpp
37  *
38  * C++ library routines for Crawl 3.2
39  *
40  * Derived from work by
41  * David Redish
42  * graduate student
43  * Computer Science Department 
44  * Carnegie Mellon University (CMU)
45  * Center for the Neural Basis of Cognition (CNBC) 
46  * http://www.python.org/doc/PyCPP.html
47  *
48 ------------------------------*/
49 #include <MT_assert.h>
50 #include "stdlib.h"
51 #include "PyObjectPlus.h"
52 #include "STR_String.h"
53 #include "MT_Vector3.h"
54 /*------------------------------
55  * PyObjectPlus Type            -- Every class, even the abstract one should have a Type
56 ------------------------------*/
57
58
59 PyTypeObject PyObjectPlus::Type = {
60 #if (PY_VERSION_HEX >= 0x02060000)
61         PyVarObject_HEAD_INIT(NULL, 0)
62 #else
63         /* python 2.5 and below */
64         PyObject_HEAD_INIT( NULL )  /* required py macro */
65         0,                              /*ob_size*/
66 #endif
67         "PyObjectPlus",                 /*tp_name*/
68         sizeof(PyObjectPlus_Proxy),             /*tp_basicsize*/
69         0,                              /*tp_itemsize*/
70         /* methods */
71         py_base_dealloc,
72         0,
73         0,
74         0,
75         0,
76         py_base_repr,
77         0,0,0,0,0,0,0,0,0,
78         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
79         0,0,0,0,0,0,0,
80         Methods,
81         0,
82         0,
83         NULL // no subtype
84 };
85
86
87 PyObjectPlus::~PyObjectPlus()
88 {
89         if(m_proxy) {
90                 BGE_PROXY_REF(m_proxy)= NULL;
91                 Py_DECREF(m_proxy);                     /* Remove own reference, python may still have 1 */
92         }
93 //      assert(ob_refcnt==0);
94 }
95
96
97 PyObject *PyObjectPlus::py_base_repr(PyObject *self)                    // This should be the entry in Type.
98 {
99         PyObjectPlus *self_plus= BGE_PROXY_REF(self);
100         if(self_plus==NULL) {
101                 PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
102                 return NULL;
103         }
104         
105         return self_plus->py_repr();  
106 }
107
108
109 PyObject * PyObjectPlus::py_base_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
110 {
111         PyTypeObject *base_type;
112         PyObjectPlus_Proxy *base = NULL;
113
114         if (!PyArg_ParseTuple(args, "O:Base PyObjectPlus", &base))
115                 return NULL;
116
117         /* the 'base' PyObject may be subclassed (multiple times even)
118          * we need to find the first C++ defined class to check 'type'
119          * is a subclass of the base arguments type.
120          *
121          * This way we can share one tp_new function for every PyObjectPlus
122          *
123          * eg.
124          *
125          * # CustomOb is called 'type' in this C code
126          * class CustomOb(GameTypes.KX_GameObject):
127          *     pass
128          *
129          * # this calls py_base_new(...), the type of 'CustomOb' is checked to be a subclass of the 'cont.owner' type
130          * ob = CustomOb(cont.owner)
131          *
132          * */
133         base_type= Py_TYPE(base);
134         while(base_type && !BGE_PROXY_CHECK_TYPE(base_type))
135                 base_type= base_type->tp_base;
136
137         if(base_type==NULL || !BGE_PROXY_CHECK_TYPE(base_type)) {
138                 PyErr_SetString(PyExc_TypeError, "can't subclass from a blender game type because the argument given is not a game class or subclass");
139                 return NULL;
140         }
141
142         /* use base_type rather then Py_TYPE(base) because we could alredy be subtyped */
143         if(!PyType_IsSubtype(type, base_type)) {
144                 PyErr_Format(PyExc_TypeError, "can't subclass blender game type <%s> from <%s> because it is not a subclass", base_type->tp_name, type->tp_name);
145                 return NULL;
146         }
147
148         /* invalidate the existing base and return a new subclassed one,
149          * this is a bit dodgy in that it also attaches its self to the existing object
150          * which is not really 'correct' python OO but for our use its OK. */
151
152         PyObjectPlus_Proxy *ret = (PyObjectPlus_Proxy *) type->tp_alloc(type, 0); /* starts with 1 ref, used for the return ref' */
153         ret->ref= base->ref;
154         base->ref= NULL;                /* invalidate! disallow further access */
155
156         ret->py_owns= base->py_owns;
157
158         ret->ref->m_proxy= NULL;
159
160         /* 'base' may be free'd after this func finished but not necessarily
161          * there is no reference to the BGE data now so it will throw an error on access */
162         Py_DECREF(base);
163
164         ret->ref->m_proxy= (PyObject *)ret; /* no need to add a ref because one is added when creating. */
165         Py_INCREF(ret); /* we return a new ref but m_proxy holds a ref so we need to add one */
166
167
168         /* 'ret' will have 2 references.
169          * - One ref is needed because ret->ref->m_proxy holds a refcount to the current proxy.
170          * - Another is needed for returning the value.
171          *
172          * So we should be ok with 2 refs, but for some reason this crashes. so adding a new ref...
173          * */
174
175         return (PyObject *)ret;
176 }
177
178 void PyObjectPlus::py_base_dealloc(PyObject *self)                              // python wrapper
179 {
180         PyObjectPlus *self_plus= BGE_PROXY_REF(self);
181         if(self_plus) {
182                 if(BGE_PROXY_PYOWNS(self)) { /* Does python own this?, then delete it  */
183                         self_plus->m_proxy = NULL; /* Need this to stop ~PyObjectPlus from decrefing m_proxy otherwise its decref'd twice and py-debug crashes */
184                         delete self_plus;
185                 }
186
187                 BGE_PROXY_REF(self)= NULL; // not really needed
188         }
189
190 #if 0
191         /* is ok normally but not for subtyping, use tp_free instead. */
192         PyObject_DEL( self );
193 #else
194         Py_TYPE(self)->tp_free(self);
195 #endif
196 };
197
198 PyObjectPlus::PyObjectPlus() : SG_QList()                               // constructor
199 {
200         m_proxy= NULL;
201 };
202
203 /*------------------------------
204  * PyObjectPlus Methods         -- Every class, even the abstract one should have a Methods
205 ------------------------------*/
206 PyMethodDef PyObjectPlus::Methods[] = {
207   {NULL, NULL}          /* Sentinel */
208 };
209
210 #define attr_invalid (&(PyObjectPlus::Attributes[0]))
211 PyAttributeDef PyObjectPlus::Attributes[] = {
212         KX_PYATTRIBUTE_RO_FUNCTION("invalid",           PyObjectPlus, pyattr_get_invalid),
213         {NULL} //Sentinel
214 };
215
216
217
218 PyObject* PyObjectPlus::pyattr_get_invalid(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
219 {
220         return PyBool_FromLong(self_v ? 1:0);
221 }
222
223 /* note, this is called as a python 'getset, where the PyAttributeDef is the closure */
224 PyObject *PyObjectPlus::py_get_attrdef(PyObject *self_py, const PyAttributeDef *attrdef)
225 {
226         void *self= (void *)(BGE_PROXY_REF(self_py));
227         if(self==NULL) {
228                 if(attrdef == attr_invalid)
229                         Py_RETURN_TRUE; // dont bother running the function
230
231                 PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
232                 return NULL;
233         }
234
235
236         if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_DUMMY)
237         {
238                 // fake attribute, ignore
239                 return NULL;
240         }
241         if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
242         {
243                 // the attribute has no field correspondance, handover processing to function.
244                 if (attrdef->m_getFunction == NULL)
245                         return NULL;
246                 return (*attrdef->m_getFunction)(self, attrdef);
247         }
248         char *ptr = reinterpret_cast<char*>(self)+attrdef->m_offset;
249         if (attrdef->m_length > 1)
250         {
251                 PyObject* resultlist = PyList_New(attrdef->m_length);
252                 for (unsigned int i=0; i<attrdef->m_length; i++)
253                 {
254                         switch (attrdef->m_type) {
255                         case KX_PYATTRIBUTE_TYPE_BOOL:
256                                 {
257                                         bool *val = reinterpret_cast<bool*>(ptr);
258                                         ptr += sizeof(bool);
259                                         PyList_SET_ITEM(resultlist,i,PyLong_FromSsize_t(*val));
260                                         break;
261                                 }
262                         case KX_PYATTRIBUTE_TYPE_SHORT:
263                                 {
264                                         short int *val = reinterpret_cast<short int*>(ptr);
265                                         ptr += sizeof(short int);
266                                         PyList_SET_ITEM(resultlist,i,PyLong_FromSsize_t(*val));
267                                         break;
268                                 }
269                         case KX_PYATTRIBUTE_TYPE_ENUM:
270                                 // enum are like int, just make sure the field size is the same
271                                 if (sizeof(int) != attrdef->m_size)
272                                 {
273                                         Py_DECREF(resultlist);
274                                         return NULL;
275                                 }
276                                 // walkthrough
277                         case KX_PYATTRIBUTE_TYPE_INT:
278                                 {
279                                         int *val = reinterpret_cast<int*>(ptr);
280                                         ptr += sizeof(int);
281                                         PyList_SET_ITEM(resultlist,i,PyLong_FromSsize_t(*val));
282                                         break;
283                                 }
284                         case KX_PYATTRIBUTE_TYPE_FLOAT:
285                                 {
286                                         float *val = reinterpret_cast<float*>(ptr);
287                                         ptr += sizeof(float);
288                                         PyList_SET_ITEM(resultlist,i,PyFloat_FromDouble(*val));
289                                         break;
290                                 }
291                         default:
292                                 // no support for array of complex data
293                                 Py_DECREF(resultlist);
294                                 return NULL;
295                         }
296                 }
297                 return resultlist;
298         }
299         else
300         {
301                 switch (attrdef->m_type) {
302                 case KX_PYATTRIBUTE_TYPE_BOOL:
303                         {
304                                 bool *val = reinterpret_cast<bool*>(ptr);
305                                 return PyLong_FromSsize_t(*val);
306                         }
307                 case KX_PYATTRIBUTE_TYPE_SHORT:
308                         {
309                                 short int *val = reinterpret_cast<short int*>(ptr);
310                                 return PyLong_FromSsize_t(*val);
311                         }
312                 case KX_PYATTRIBUTE_TYPE_ENUM:
313                         // enum are like int, just make sure the field size is the same
314                         if (sizeof(int) != attrdef->m_size)
315                         {
316                                 return NULL;
317                         }
318                         // walkthrough
319                 case KX_PYATTRIBUTE_TYPE_INT:
320                         {
321                                 int *val = reinterpret_cast<int*>(ptr);
322                                 return PyLong_FromSsize_t(*val);
323                         }
324                 case KX_PYATTRIBUTE_TYPE_FLOAT:
325                         {
326                                 float *val = reinterpret_cast<float*>(ptr);
327                                 return PyFloat_FromDouble(*val);
328                         }
329                 case KX_PYATTRIBUTE_TYPE_VECTOR:
330                         {
331                                 MT_Vector3 *val = reinterpret_cast<MT_Vector3*>(ptr);
332 #ifdef USE_MATHUTILS
333                                 float fval[3]= {(*val)[0], (*val)[1], (*val)[2]};
334                                 return newVectorObject(fval, 3, Py_NEW, NULL);
335 #else
336                                 PyObject* resultlist = PyList_New(3);
337                                 for (unsigned int i=0; i<3; i++)
338                                 {
339                                         PyList_SET_ITEM(resultlist,i,PyFloat_FromDouble((*val)[i]));
340                                 }
341                                 return resultlist;
342 #endif
343                         }
344                 case KX_PYATTRIBUTE_TYPE_STRING:
345                         {
346                                 STR_String *val = reinterpret_cast<STR_String*>(ptr);
347                                 return PyUnicode_FromString(*val);
348                         }
349                 default:
350                         return NULL;
351                 }
352         }
353 }
354
355 /* note, this is called as a python getset */
356 int PyObjectPlus::py_set_attrdef(PyObject *self_py, PyObject *value, const PyAttributeDef *attrdef)
357 {
358         void *self= (void *)(BGE_PROXY_REF(self_py));
359         if(self==NULL) {
360                 PyErr_SetString(PyExc_SystemError, BGE_PROXY_ERROR_MSG);
361                 return PY_SET_ATTR_FAIL;
362         }
363
364         void *undoBuffer = NULL;
365         void *sourceBuffer = NULL;
366         size_t bufferSize = 0;
367         
368         char *ptr = reinterpret_cast<char*>(self)+attrdef->m_offset;
369         if (attrdef->m_length > 1)
370         {
371                 if (!PySequence_Check(value)) 
372                 {
373                         PyErr_Format(PyExc_TypeError, "expected a sequence for attribute \"%s\"", attrdef->m_name);
374                         return PY_SET_ATTR_FAIL;
375                 }
376                 if (PySequence_Size(value) != attrdef->m_length)
377                 {
378                         PyErr_Format(PyExc_TypeError, "incorrect number of elements in sequence for attribute \"%s\"", attrdef->m_name);
379                         return PY_SET_ATTR_FAIL;
380                 }
381                 switch (attrdef->m_type) 
382                 {
383                 case KX_PYATTRIBUTE_TYPE_FUNCTION:
384                         if (attrdef->m_setFunction == NULL) 
385                         {
386                                 PyErr_Format(PyExc_AttributeError, "function attribute without function for attribute \"%s\", report to blender.org", attrdef->m_name);
387                                 return PY_SET_ATTR_FAIL;
388                         }
389                         return (*attrdef->m_setFunction)(self, attrdef, value);
390                 case KX_PYATTRIBUTE_TYPE_BOOL:
391                         bufferSize = sizeof(bool);
392                         break;
393                 case KX_PYATTRIBUTE_TYPE_SHORT:
394                         bufferSize = sizeof(short int);
395                         break;
396                 case KX_PYATTRIBUTE_TYPE_ENUM:
397                 case KX_PYATTRIBUTE_TYPE_INT:
398                         bufferSize = sizeof(int);
399                         break;
400                 case KX_PYATTRIBUTE_TYPE_FLOAT:
401                         bufferSize = sizeof(float);
402                         break;
403                 default:
404                         // should not happen
405                         PyErr_Format(PyExc_AttributeError, "Unsupported attribute type for attribute \"%s\", report to blender.org", attrdef->m_name);
406                         return PY_SET_ATTR_FAIL;
407                 }
408                 // let's implement a smart undo method
409                 bufferSize *= attrdef->m_length;
410                 undoBuffer = malloc(bufferSize);
411                 sourceBuffer = ptr;
412                 if (undoBuffer)
413                 {
414                         memcpy(undoBuffer, sourceBuffer, bufferSize);
415                 }
416                 for (int i=0; i<attrdef->m_length; i++)
417                 {
418                         PyObject *item = PySequence_GetItem(value, i); /* new ref */
419                         // we can decrement the reference immediately, the reference count
420                         // is at least 1 because the item is part of an array
421                         Py_DECREF(item);
422                         switch (attrdef->m_type) 
423                         {
424                         case KX_PYATTRIBUTE_TYPE_BOOL:
425                                 {
426                                         bool *var = reinterpret_cast<bool*>(ptr);
427                                         ptr += sizeof(bool);
428                                         if (PyLong_Check(item)) 
429                                         {
430                                                 *var = (PyLong_AsSsize_t(item) != 0);
431                                         } 
432                                         else if (PyBool_Check(item))
433                                         {
434                                                 *var = (item == Py_True);
435                                         }
436                                         else
437                                         {
438                                                 PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
439                                                 goto UNDO_AND_ERROR;
440                                         }
441                                         break;
442                                 }
443                         case KX_PYATTRIBUTE_TYPE_SHORT:
444                                 {
445                                         short int *var = reinterpret_cast<short int*>(ptr);
446                                         ptr += sizeof(short int);
447                                         if (PyLong_Check(item)) 
448                                         {
449                                                 long val = PyLong_AsSsize_t(item);
450                                                 if (attrdef->m_clamp)
451                                                 {
452                                                         if (val < attrdef->m_imin)
453                                                                 val = attrdef->m_imin;
454                                                         else if (val > attrdef->m_imax)
455                                                                 val = attrdef->m_imax;
456                                                 }
457                                                 else if (val < attrdef->m_imin || val > attrdef->m_imax)
458                                                 {
459                                                         PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
460                                                         goto UNDO_AND_ERROR;
461                                                 }
462                                                 *var = (short int)val;
463                                         }
464                                         else
465                                         {
466                                                 PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
467                                                 goto UNDO_AND_ERROR;
468                                         }
469                                         break;
470                                 }
471                         case KX_PYATTRIBUTE_TYPE_ENUM:
472                                 // enum are equivalent to int, just make sure that the field size matches:
473                                 if (sizeof(int) != attrdef->m_size)
474                                 {
475                                         PyErr_Format(PyExc_AttributeError, "Size check error for attribute, \"%s\", report to blender.org", attrdef->m_name);
476                                         goto UNDO_AND_ERROR;
477                                 }
478                                 // walkthrough
479                         case KX_PYATTRIBUTE_TYPE_INT:
480                                 {
481                                         int *var = reinterpret_cast<int*>(ptr);
482                                         ptr += sizeof(int);
483                                         if (PyLong_Check(item)) 
484                                         {
485                                                 long val = PyLong_AsSsize_t(item);
486                                                 if (attrdef->m_clamp)
487                                                 {
488                                                         if (val < attrdef->m_imin)
489                                                                 val = attrdef->m_imin;
490                                                         else if (val > attrdef->m_imax)
491                                                                 val = attrdef->m_imax;
492                                                 }
493                                                 else if (val < attrdef->m_imin || val > attrdef->m_imax)
494                                                 {
495                                                         PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
496                                                         goto UNDO_AND_ERROR;
497                                                 }
498                                                 *var = (int)val;
499                                         }
500                                         else
501                                         {
502                                                 PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
503                                                 goto UNDO_AND_ERROR;
504                                         }
505                                         break;
506                                 }
507                         case KX_PYATTRIBUTE_TYPE_FLOAT:
508                                 {
509                                         float *var = reinterpret_cast<float*>(ptr);
510                                         ptr += sizeof(float);
511                                         double val = PyFloat_AsDouble(item);
512                                         if (val == -1.0 && PyErr_Occurred())
513                                         {
514                                                 PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name);
515                                                 goto UNDO_AND_ERROR;
516                                         }
517                                         else if (attrdef->m_clamp) 
518                                         {
519                                                 if (val < attrdef->m_fmin)
520                                                         val = attrdef->m_fmin;
521                                                 else if (val > attrdef->m_fmax)
522                                                         val = attrdef->m_fmax;
523                                         }
524                                         else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
525                                         {
526                                                 PyErr_Format(PyExc_ValueError, "item value out of range for attribute \"%s\"", attrdef->m_name);
527                                                 goto UNDO_AND_ERROR;
528                                         }
529                                         *var = (float)val;
530                                         break;
531                                 }
532                         default:
533                                 // should not happen
534                                 PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", report to blender.org", attrdef->m_name);
535                                 goto UNDO_AND_ERROR;
536                         }
537                 }
538                 // no error, call check function if any
539                 if (attrdef->m_checkFunction != NULL)
540                 {
541                         if ((*attrdef->m_checkFunction)(self, attrdef) != 0)
542                         {
543                                 // if the checing function didnt set an error then set a generic one here so we dont set an error with no exception
544                                 if (PyErr_Occurred()==0)
545                                         PyErr_Format(PyExc_AttributeError, "type check error for attribute \"%s\", reasion unknown", attrdef->m_name);
546                                 
547                                 // post check returned an error, restore values
548                         UNDO_AND_ERROR:
549                                 if (undoBuffer)
550                                 {
551                                         memcpy(sourceBuffer, undoBuffer, bufferSize);
552                                         free(undoBuffer);
553                                 }
554                                 return PY_SET_ATTR_FAIL;
555                         }
556                 }
557                 if (undoBuffer)
558                         free(undoBuffer);
559                 return PY_SET_ATTR_SUCCESS;
560         }
561         else    // simple attribute value
562         {
563                 if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_FUNCTION)
564                 {
565                         if (attrdef->m_setFunction == NULL)
566                         {
567                                 PyErr_Format(PyExc_AttributeError, "function attribute without function \"%s\", report to blender.org", attrdef->m_name);
568                                 return PY_SET_ATTR_FAIL;
569                         }
570                         return (*attrdef->m_setFunction)(self, attrdef, value);
571                 }
572                 if (attrdef->m_checkFunction != NULL || attrdef->m_type == KX_PYATTRIBUTE_TYPE_VECTOR)
573                 {
574                         // post check function is provided, prepare undo buffer
575                         sourceBuffer = ptr;
576                         switch (attrdef->m_type) 
577                         {
578                         case KX_PYATTRIBUTE_TYPE_BOOL:
579                                 bufferSize = sizeof(bool);
580                                 break;
581                         case KX_PYATTRIBUTE_TYPE_SHORT:
582                                 bufferSize = sizeof(short);
583                                 break;
584                         case KX_PYATTRIBUTE_TYPE_ENUM:
585                         case KX_PYATTRIBUTE_TYPE_INT:
586                                 bufferSize = sizeof(int);
587                                 break;
588                         case KX_PYATTRIBUTE_TYPE_FLOAT:
589                                 bufferSize = sizeof(float);
590                                 break;
591                         case KX_PYATTRIBUTE_TYPE_STRING:
592                                 sourceBuffer = reinterpret_cast<STR_String*>(ptr)->Ptr();
593                                 if (sourceBuffer)
594                                         bufferSize = strlen(reinterpret_cast<char*>(sourceBuffer))+1;
595                                 break;
596                         case KX_PYATTRIBUTE_TYPE_VECTOR:
597                                 bufferSize = sizeof(MT_Vector3);
598                                 break;
599                         default:
600                                 PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
601                                 return PY_SET_ATTR_FAIL;
602                         }
603                         if (bufferSize)
604                         {
605                                 undoBuffer = malloc(bufferSize);
606                                 if (undoBuffer)
607                                 {
608                                         memcpy(undoBuffer, sourceBuffer, bufferSize);
609                                 }
610                         }
611                 }
612                         
613                 switch (attrdef->m_type) 
614                 {
615                 case KX_PYATTRIBUTE_TYPE_BOOL:
616                         {
617                                 bool *var = reinterpret_cast<bool*>(ptr);
618                                 if (PyLong_Check(value)) 
619                                 {
620                                         *var = (PyLong_AsSsize_t(value) != 0);
621                                 } 
622                                 else if (PyBool_Check(value))
623                                 {
624                                         *var = (value == Py_True);
625                                 }
626                                 else
627                                 {
628                                         PyErr_Format(PyExc_TypeError, "expected an integer or a bool for attribute \"%s\"", attrdef->m_name);
629                                         goto FREE_AND_ERROR;
630                                 }
631                                 break;
632                         }
633                 case KX_PYATTRIBUTE_TYPE_SHORT:
634                         {
635                                 short int *var = reinterpret_cast<short int*>(ptr);
636                                 if (PyLong_Check(value)) 
637                                 {
638                                         long val = PyLong_AsSsize_t(value);
639                                         if (attrdef->m_clamp)
640                                         {
641                                                 if (val < attrdef->m_imin)
642                                                         val = attrdef->m_imin;
643                                                 else if (val > attrdef->m_imax)
644                                                         val = attrdef->m_imax;
645                                         }
646                                         else if (val < attrdef->m_imin || val > attrdef->m_imax)
647                                         {
648                                                 PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
649                                                 goto FREE_AND_ERROR;
650                                         }
651                                         *var = (short int)val;
652                                 }
653                                 else
654                                 {
655                                         PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
656                                         goto FREE_AND_ERROR;
657                                 }
658                                 break;
659                         }
660                 case KX_PYATTRIBUTE_TYPE_ENUM:
661                         // enum are equivalent to int, just make sure that the field size matches:
662                         if (sizeof(int) != attrdef->m_size)
663                         {
664                                 PyErr_Format(PyExc_AttributeError, "attribute size check error for attribute \"%s\", report to blender.org", attrdef->m_name);
665                                 goto FREE_AND_ERROR;
666                         }
667                         // walkthrough
668                 case KX_PYATTRIBUTE_TYPE_INT:
669                         {
670                                 int *var = reinterpret_cast<int*>(ptr);
671                                 if (PyLong_Check(value)) 
672                                 {
673                                         long val = PyLong_AsSsize_t(value);
674                                         if (attrdef->m_clamp)
675                                         {
676                                                 if (val < attrdef->m_imin)
677                                                         val = attrdef->m_imin;
678                                                 else if (val > attrdef->m_imax)
679                                                         val = attrdef->m_imax;
680                                         }
681                                         else if (val < attrdef->m_imin || val > attrdef->m_imax)
682                                         {
683                                                 PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
684                                                 goto FREE_AND_ERROR;
685                                         }
686                                         *var = (int)val;
687                                 }
688                                 else
689                                 {
690                                         PyErr_Format(PyExc_TypeError, "expected an integer for attribute \"%s\"", attrdef->m_name);
691                                         goto FREE_AND_ERROR;
692                                 }
693                                 break;
694                         }
695                 case KX_PYATTRIBUTE_TYPE_FLOAT:
696                         {
697                                 float *var = reinterpret_cast<float*>(ptr);
698                                 double val = PyFloat_AsDouble(value);
699                                 if (val == -1.0 && PyErr_Occurred())
700                                 {
701                                         PyErr_Format(PyExc_TypeError, "expected a float for attribute \"%s\"", attrdef->m_name);
702                                         goto FREE_AND_ERROR;
703                                 }
704                                 else if (attrdef->m_clamp)
705                                 {
706                                         if (val < attrdef->m_fmin)
707                                                 val = attrdef->m_fmin;
708                                         else if (val > attrdef->m_fmax)
709                                                 val = attrdef->m_fmax;
710                                 }
711                                 else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
712                                 {
713                                         PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
714                                         goto FREE_AND_ERROR;
715                                 }
716                                 *var = (float)val;
717                                 break;
718                         }
719                 case KX_PYATTRIBUTE_TYPE_VECTOR:
720                         {
721                                 if (!PySequence_Check(value) || PySequence_Size(value) != 3) 
722                                 {
723                                         PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name);
724                                         return PY_SET_ATTR_FAIL;
725                                 }
726                                 MT_Vector3 *var = reinterpret_cast<MT_Vector3*>(ptr);
727                                 for (int i=0; i<3; i++)
728                                 {
729                                         PyObject *item = PySequence_GetItem(value, i); /* new ref */
730                                         // we can decrement the reference immediately, the reference count
731                                         // is at least 1 because the item is part of an array
732                                         Py_DECREF(item);
733                                         double val = PyFloat_AsDouble(item);
734                                         if (val == -1.0 && PyErr_Occurred())
735                                         {
736                                                 PyErr_Format(PyExc_TypeError, "expected a sequence of 3 floats for attribute \"%s\"", attrdef->m_name);
737                                                 goto RESTORE_AND_ERROR;
738                                         }
739                                         else if (attrdef->m_clamp)
740                                         {
741                                                 if (val < attrdef->m_fmin)
742                                                         val = attrdef->m_fmin;
743                                                 else if (val > attrdef->m_fmax)
744                                                         val = attrdef->m_fmax;
745                                         }
746                                         else if (val < attrdef->m_fmin || val > attrdef->m_fmax)
747                                         {
748                                                 PyErr_Format(PyExc_ValueError, "value out of range for attribute \"%s\"", attrdef->m_name);
749                                                 goto RESTORE_AND_ERROR;
750                                         }
751                                         (*var)[i] = (MT_Scalar)val;
752                                 }
753                                 break;
754                         }
755                 case KX_PYATTRIBUTE_TYPE_STRING:
756                         {
757                                 STR_String *var = reinterpret_cast<STR_String*>(ptr);
758                                 if (PyUnicode_Check(value)) 
759                                 {
760                                         char *val = _PyUnicode_AsString(value);
761                                         if (attrdef->m_clamp)
762                                         {
763                                                 if (strlen(val) < attrdef->m_imin)
764                                                 {
765                                                         // can't increase the length of the string
766                                                         PyErr_Format(PyExc_ValueError, "string length too short for attribute \"%s\"", attrdef->m_name);
767                                                         goto FREE_AND_ERROR;
768                                                 }
769                                                 else if (strlen(val) > attrdef->m_imax)
770                                                 {
771                                                         // trim the string
772                                                         char c = val[attrdef->m_imax];
773                                                         val[attrdef->m_imax] = 0;
774                                                         *var = val;
775                                                         val[attrdef->m_imax] = c;
776                                                         break;
777                                                 }
778                                         } else if (strlen(val) < attrdef->m_imin || strlen(val) > attrdef->m_imax)
779                                         {
780                                                 PyErr_Format(PyExc_ValueError, "string length out of range for attribute \"%s\"", attrdef->m_name);
781                                                 goto FREE_AND_ERROR;
782                                         }
783                                         *var = val;
784                                 }
785                                 else
786                                 {
787                                         PyErr_Format(PyExc_TypeError, "expected a string for attribute \"%s\"", attrdef->m_name);
788                                         goto FREE_AND_ERROR;
789                                 }
790                                 break;
791                         }
792                 default:
793                         // should not happen
794                         PyErr_Format(PyExc_AttributeError, "unknown type for attribute \"%s\", report to blender.org", attrdef->m_name);
795                         goto FREE_AND_ERROR;
796                 }
797         }
798         // check if post processing is needed
799         if (attrdef->m_checkFunction != NULL)
800         {
801                 if ((*attrdef->m_checkFunction)(self, attrdef) != 0)
802                 {
803                         // restore value
804                 RESTORE_AND_ERROR:
805                         if (undoBuffer)
806                         {
807                                 if (attrdef->m_type == KX_PYATTRIBUTE_TYPE_STRING)
808                                 {
809                                         // special case for STR_String: restore the string
810                                         STR_String *var = reinterpret_cast<STR_String*>(ptr);
811                                         *var = reinterpret_cast<char*>(undoBuffer);
812                                 }
813                                 else
814                                 {
815                                         // other field type have direct values
816                                         memcpy(ptr, undoBuffer, bufferSize);
817                                 }
818                         }
819                 FREE_AND_ERROR:
820                         if (undoBuffer)
821                                 free(undoBuffer);
822                         return 1;
823                 }
824         }
825         if (undoBuffer)
826                 free(undoBuffer);
827         return 0;       
828 }
829
830
831
832 /*------------------------------
833  * PyObjectPlus repr            -- representations
834 ------------------------------*/
835 PyObject *PyObjectPlus::py_repr(void)
836 {
837         PyErr_SetString(PyExc_SystemError, "Representation not overridden by object.");  
838         return NULL;
839 }
840
841 void PyObjectPlus::ProcessReplica()
842 {
843         /* Clear the proxy, will be created again if needed with GetProxy()
844          * otherwise the PyObject will point to the wrong reference */
845         m_proxy= NULL;
846 }
847
848 /* Sometimes we might want to manually invalidate a BGE type even if
849  * it hasnt been released by the BGE, say for example when an object
850  * is removed from a scene, accessing it may cause problems.
851  * 
852  * In this case the current proxy is made invalid, disowned,
853  * and will raise an error on access. However if python can get access
854  * to this class again it will make a new proxy and work as expected.
855  */
856 void PyObjectPlus::InvalidateProxy()            // check typename of each parent
857 {
858         if(m_proxy) { 
859                 BGE_PROXY_REF(m_proxy)=NULL;
860                 Py_DECREF(m_proxy);
861                 m_proxy= NULL;
862         }
863 }
864
865 PyObject *PyObjectPlus::GetProxy_Ext(PyObjectPlus *self, PyTypeObject *tp)
866 {
867         if (self->m_proxy==NULL)
868         {
869                 self->m_proxy = reinterpret_cast<PyObject *>PyObject_NEW( PyObjectPlus_Proxy, tp);
870                 BGE_PROXY_PYOWNS(self->m_proxy) = false;
871         }
872         //PyObject_Print(self->m_proxy, stdout, 0);
873         //printf("ref %d\n", self->m_proxy->ob_refcnt);
874         
875         BGE_PROXY_REF(self->m_proxy) = self; /* Its possible this was set to NULL, so set it back here */
876         Py_INCREF(self->m_proxy); /* we own one, thos ones fore the return */
877         return self->m_proxy;
878 }
879
880 PyObject *PyObjectPlus::NewProxy_Ext(PyObjectPlus *self, PyTypeObject *tp, bool py_owns)
881 {
882         if (self->m_proxy)
883         {
884                 if(py_owns)
885                 {       /* Free */
886                         BGE_PROXY_REF(self->m_proxy) = NULL;
887                         Py_DECREF(self->m_proxy);
888                         self->m_proxy= NULL;
889                 }
890                 else {
891                         Py_INCREF(self->m_proxy);
892                         return self->m_proxy;
893                 }
894                 
895         }
896         
897         GetProxy_Ext(self, tp);
898         if(py_owns) {
899                 BGE_PROXY_PYOWNS(self->m_proxy) = py_owns;
900                 Py_DECREF(self->m_proxy); /* could avoid thrashing here but for now its ok */
901         }
902         return self->m_proxy;
903 }
904
905 ///////////////////////////////////////////////////////////////////////////////////////////////
906 ///////////////////////////////////////////////////////////////////////////////////////////////
907 /* deprecation warning management */
908
909 bool PyObjectPlus::m_ignore_deprecation_warnings(false);
910 void PyObjectPlus::SetDeprecationWarnings(bool ignoreDeprecationWarnings)
911 {
912         m_ignore_deprecation_warnings = ignoreDeprecationWarnings;
913 }
914
915 void PyObjectPlus::ShowDeprecationWarning_func(const char* old_way,const char* new_way)
916 {
917         {
918                 printf("Method %s is deprecated, please use %s instead.\n", old_way, new_way);
919                 
920                 // import sys; print '\t%s:%d' % (sys._getframe(0).f_code.co_filename, sys._getframe(0).f_lineno)
921                 
922                 PyObject *getframe, *frame;
923                 PyObject *f_lineno, *f_code, *co_filename;
924                 
925                 getframe = PySys_GetObject((char *)"_getframe"); // borrowed
926                 if (getframe) {
927                         frame = PyObject_CallObject(getframe, NULL);
928                         if (frame) {
929                                 f_lineno= PyObject_GetAttrString(frame, "f_lineno");
930                                 f_code= PyObject_GetAttrString(frame, "f_code");
931                                 if (f_lineno && f_code) {
932                                         co_filename= PyObject_GetAttrString(f_code, "co_filename");
933                                         if (co_filename) {
934                                                 
935                                                 printf("\t%s:%d\n", _PyUnicode_AsString(co_filename), (int)PyLong_AsSsize_t(f_lineno));
936                                                 
937                                                 Py_DECREF(f_lineno);
938                                                 Py_DECREF(f_code);
939                                                 Py_DECREF(co_filename);
940                                                 Py_DECREF(frame);
941                                                 return;
942                                         }
943                                 }
944                                 
945                                 Py_XDECREF(f_lineno);
946                                 Py_XDECREF(f_code);
947                                 Py_DECREF(frame);
948                         }
949                         
950                 }
951                 PyErr_Clear();
952                 printf("\tERROR - Could not access sys._getframe(0).f_lineno or sys._getframe().f_code.co_filename\n");
953         }
954 }
955
956 void PyObjectPlus::ClearDeprecationWarning()
957 {
958         WarnLink *wlink_next;
959         WarnLink *wlink = GetDeprecationWarningLinkFirst();
960         
961         while(wlink)
962         {
963                 wlink->warn_done= false; /* no need to NULL the link, its cleared before adding to the list next time round */
964                 wlink_next= reinterpret_cast<WarnLink *>(wlink->link);
965                 wlink->link= NULL;
966                 wlink= wlink_next;
967         }
968         NullDeprecationWarning();
969 }
970
971 WarnLink*               m_base_wlink_first= NULL;
972 WarnLink*               m_base_wlink_last= NULL;
973
974 WarnLink*               PyObjectPlus::GetDeprecationWarningLinkFirst(void) {return m_base_wlink_first;}
975 WarnLink*               PyObjectPlus::GetDeprecationWarningLinkLast(void) {return m_base_wlink_last;}
976 void                    PyObjectPlus::SetDeprecationWarningFirst(WarnLink* wlink) {m_base_wlink_first= wlink;}
977 void                    PyObjectPlus::SetDeprecationWarningLinkLast(WarnLink* wlink) {m_base_wlink_last= wlink;}
978 void                    PyObjectPlus::NullDeprecationWarning() {m_base_wlink_first= m_base_wlink_last= NULL;}
979
980 #endif //NO_EXP_PYTHON_EMBEDDING
981