Python BGE API
[blender.git] / source / gameengine / Expressions / Value.h
1 /*
2  * Value.h: interface for the CValue class.
3  * $Id$
4  * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
5  *
6  * Permission to use, copy, modify, distribute and sell this software
7  * and its documentation for any purpose is hereby granted without fee,
8  * provided that the above copyright notice appear in all copies and
9  * that both that copyright notice and this permission notice appear
10  * in supporting documentation.  Erwin Coumans makes no
11  * representations about the suitability of this software for any
12  * purpose.  It is provided "as is" without express or implied warranty.
13  *
14  */
15
16 #ifdef WIN32
17 #pragma warning (disable:4786)
18 #endif //WIN32
19
20 /////////////////////////////////////////////////////////////////////////////////////
21 //// Baseclass CValue
22 //// Together with CExpression, CValue and it's derived classes can be used to
23 //// parse expressions into a parsetree with error detecting/correcting capabilities
24 //// also expandible by a CFactory pluginsystem 
25 //// 
26 //// Features:
27 //// Reference Counting (AddRef() / Release())
28 //// Calculations (Calc() / CalcFinal())
29 //// Configuration (Configure())
30 //// Serialization (EdSerialize() / EdIdSerialize() / EdPtrSerialize() and macro PLUGIN_DECLARE_SERIAL
31 //// Property system (SetProperty() / GetProperty() / FindIdentifier())
32 //// Replication (GetReplica())
33 //// Flags (IsSelected() / IsModified() / SetSelected()...)
34 //// 
35 //// Some small editor-specific things added
36 //// A helperclass CompressorArchive handles the serialization
37 //// 
38 /////////////////////////////////////////////////////////////////////////////////////
39 #ifndef __VALUE_H__
40 #define __VALUE_H__
41
42 #include <map>          // array functionality for the propertylist
43 #include "STR_String.h" // STR_String class
44
45 #ifndef GEN_NO_ASSERT
46 #undef  assert
47 #define assert(exp)                     ((void)NULL)
48 #endif
49
50
51 #ifndef GEN_NO_TRACE
52 #undef  trace
53 #define trace(exp)                      ((void)NULL)
54 #endif
55
56 #ifndef GEN_NO_DEBUG
57 #undef  debug
58 #define debug(exp)                      ((void)NULL)
59 #endif
60
61 #ifndef GEN_NO_ASSERTD
62 #undef  assertd
63 #define assertd(exp)                    ((void)NULL)
64 #endif
65
66
67 #ifndef USE_PRAGMA_ONCE
68 #ifdef WIN32
69         #pragma once
70
71 #endif //WIN32
72 #endif
73
74 #define EDITOR_LEVEL_VERSION 0x06
75
76 enum VALUE_OPERATOR {
77         
78         VALUE_MOD_OPERATOR,                     // %
79         VALUE_ADD_OPERATOR,                     // +
80         VALUE_SUB_OPERATOR,                     // -
81         VALUE_MUL_OPERATOR,                     // *
82         VALUE_DIV_OPERATOR,                     // /
83         VALUE_NEG_OPERATOR,                     // -
84         VALUE_POS_OPERATOR,                     // +
85         VALUE_AND_OPERATOR,                     // &&
86         VALUE_OR_OPERATOR,                      // ||
87         VALUE_EQL_OPERATOR,                     // ==
88         VALUE_NEQ_OPERATOR,                     // !=
89         VALUE_GRE_OPERATOR,                     // >
90         VALUE_LES_OPERATOR,                     // <
91         VALUE_GEQ_OPERATOR,                     // >=
92         VALUE_LEQ_OPERATOR,                     // <=
93         VALUE_NOT_OPERATOR,                     // !
94         VALUE_NO_OPERATOR                       // no operation at all
95 };
96
97 enum VALUE_DATA_TYPE {
98         VALUE_NO_TYPE,                          // abstract baseclass
99         VALUE_INT_TYPE,
100         VALUE_FLOAT_TYPE,
101         VALUE_STRING_TYPE,
102         VALUE_BOOL_TYPE,
103         VALUE_ERROR_TYPE,
104         VALUE_EMPTY_TYPE,
105         VALUE_SOLID_TYPE,
106         VALUE_COMBISOLID_TYPE,
107         VALUE_VECTOR_TYPE,
108         VALUE_MENU_TYPE,
109         VALUE_ACTOR_TYPE,
110         VALUE_MAX_TYPE                          //only here to provide number of types
111 };
112
113
114
115 #ifdef _DEBUG
116 //extern int gRefCountValue;            // debugonly variable to check if all CValue Refences are Dereferenced at programexit
117 #endif
118
119 struct HashableInt 
120 {
121         HashableInt(int id)                                                                                                                     : mData(id) { }
122
123         unsigned long                           Hash() const                                                                                    { return 0;} ////}gHash(&mData, sizeof(int));}
124         
125         bool                            operator==(HashableInt rhs)                                                             { return mData == rhs.mData; }
126         
127         int                                     mData;
128 };
129
130
131 //
132 // Bitfield that stores the flags for each CValue derived class
133 //
134 struct ValueFlags {
135         ValueFlags() :
136                 Modified(true),
137                 Selected(false),
138                 Affected(false),
139                 ReleaseRequested(false),
140                 Error(false),
141                 RefCountDisabled(false),
142                 HasProperties(false),
143                 HasName(false),
144                 Visible(true),
145                 CustomFlag1(false),
146                 CustomFlag2(false)
147         {
148         }
149
150         unsigned short Modified : 1;
151         unsigned short Selected : 1;
152         unsigned short Affected : 1;
153         unsigned short ReleaseRequested : 1;
154         unsigned short Error : 1;
155         unsigned short RefCountDisabled : 1;
156         unsigned short HasProperties : 1;
157         unsigned short HasName : 1;
158         unsigned short Visible : 1;
159         unsigned short CustomFlag1 : 1;
160         unsigned short CustomFlag2 : 1;
161
162         
163 };
164
165 /**
166  *      Base Class for all Actions performed on CValue's. Can be extended for undo/redo system in future.
167 */
168 class CAction
169 {
170 public:
171         CAction() {
172         };
173         virtual ~CAction(){
174         };
175         virtual void Execute() const =0;
176 };
177
178 //
179 // CValue
180 //
181 // Base class for all editor functionality, flexible object type that allows
182 // calculations and uses reference counting for memory management.
183 // 
184 //
185
186
187
188
189 #ifndef NO_EXP_PYTHON_EMBEDDING
190 #include "PyObjectPlus.h"
191 #include "object.h"
192 class CValue  : public PyObjectPlus
193 #else
194 class CValue  
195 #endif //NO_EXP_PYTHON_EMBEDDING
196
197
198 {
199 #ifndef NO_EXP_PYTHON_EMBEDDING
200 Py_Header;
201 #endif //NO_EXP_PYTHON_EMBEDDING
202 public:
203         enum AllocationTYPE {
204                 STACKVALUE              = 0,
205                 HEAPVALUE               = 1
206         };
207         
208         enum DrawTYPE {
209                 STARTFRAME              = 0,
210                 ENDFRAME                = 1,
211                 INTERFRAME              = 2
212         };
213
214
215         // Construction / Destruction
216 #ifndef NO_EXP_PYTHON_EMBEDDING
217
218         CValue(PyTypeObject *T = &Type);
219         //static PyObject*      PyMake(PyObject*,PyObject*);
220         virtual PyObject *py_repr(void)
221         {
222                 return Py_BuildValue("s",(const char*)GetText());
223         }
224
225
226
227         virtual PyObject*                       py_getattro(PyObject *attr);
228
229         void    SpecialRelease()
230         {
231                 int i=0;
232                 if (ob_refcnt == 0)
233                 {
234                         _Py_NewReference(this);
235                         
236                 } else
237                 {
238                         i++;
239                 }
240                 Release();
241         }
242         static void PyDestructor(PyObject *P)                           // python wrapper
243         {
244           ((CValue*)P)->SpecialRelease();
245         };
246
247         virtual PyObject*       ConvertValueToPython() {
248                 return NULL;
249         }
250
251         virtual CValue* ConvertPythonToValue(PyObject* pyobj);
252
253
254         virtual int                             py_delattro(PyObject *attr);
255         virtual int                             py_setattro(PyObject *attr, PyObject* value);
256         
257         virtual PyObject* ConvertKeysToPython( void );
258         
259         KX_PYMETHOD_NOARGS(CValue,GetName);
260
261 #else
262         CValue();
263 #endif //NO_EXP_PYTHON_EMBEDDING
264
265         
266         
267         // Expression Calculation
268         virtual CValue*         Calc(VALUE_OPERATOR op, CValue *val) = 0;
269         virtual CValue*         CalcFinal(VALUE_DATA_TYPE dtype, VALUE_OPERATOR op, CValue *val) = 0;
270         virtual void            SetOwnerExpression(class CExpression* expr);
271
272         
273
274         void                            Execute(const CAction& a)
275         {
276                 a.Execute();
277         };
278
279         /// Reference Counting
280         int                                     GetRefCount()                                                                                   { return m_refcount; }
281         virtual CValue*         AddRef();                                                                                               // Add a reference to this value
282         virtual int                     Release();                                                                                              // Release a reference to this value (when reference count reaches 0, the value is removed from the heap)
283
284         /// Property Management
285         virtual void            SetProperty(const STR_String& name,CValue* ioProperty);                                         // Set property <ioProperty>, overwrites and releases a previous property with the same name if needed
286         virtual void            SetProperty(const char* name,CValue* ioProperty);
287         virtual CValue*         GetProperty(const char* inName);                                                        // Get pointer to a property with name <inName>, returns NULL if there is no property named <inName>
288         virtual CValue*         GetProperty(const STR_String & inName);
289         STR_String                      GetPropertyText(const STR_String & inName,const STR_String& deftext="");                                                // Get text description of property with name <inName>, returns an empty string if there is no property named <inName>
290         float                           GetPropertyNumber(const STR_String& inName,float defnumber);
291         virtual bool            RemoveProperty(const char *inName);                                             // Remove the property named <inName>, returns true if the property was succesfully removed, false if property was not found or could not be removed
292         virtual vector<STR_String>      GetPropertyNames();
293         virtual void            ClearProperties();                                                                              // Clear all properties
294
295         virtual void            SetPropertiesModified(bool inModified);                                 // Set all properties' modified flag to <inModified>
296         virtual bool            IsAnyPropertyModified();                                                                // Check if any of the properties in this value have been modified
297
298         virtual CValue*         GetProperty(int inIndex);                                                               // Get property number <inIndex>
299         virtual int                     GetPropertyCount();                                                                             // Get the amount of properties assiocated with this value
300
301         virtual void            CloneProperties(CValue* replica);
302         virtual CValue*         FindIdentifier(const STR_String& identifiername);
303         /** Set the wireframe color of this value depending on the CSG
304          * operator type <op>
305          * @attention: not implemented */
306         virtual void            SetColorOperator(VALUE_OPERATOR op);
307
308         virtual const STR_String &      GetText() = 0;
309         virtual float           GetNumber() = 0;
310         double*                         ZeroVector() { return m_sZeroVec; };
311         virtual double*         GetVector3(bool bGetTransformedVec = false);
312
313         virtual STR_String      GetName() = 0;                                                                                  // Retrieve the name of the value
314         virtual void            SetName(STR_String name) = 0;                                                           // Set the name of the value
315         virtual void            ReplicaSetName(STR_String name) = 0;
316         /** Sets the value to this cvalue.
317          * @attention this particular function should never be called. Why not abstract? */
318         virtual void            SetValue(CValue* newval);
319         virtual CValue*         GetReplica() =0;
320         //virtual CValue*               Copy() = 0;
321         
322         
323         STR_String                              op2str(VALUE_OPERATOR op);
324         /** enable/disable display of deprecation warnings */
325         static void                     SetDeprecationWarnings(bool ignoreDeprecationWarnings);
326         /** Shows a deprecation warning */
327         static void                     ShowDeprecationWarning(const char* method,const char* prop);
328                 
329         // setting / getting flags
330         inline void                     SetSelected(bool bSelected)                                                             { m_ValFlags.Selected = bSelected; }
331         virtual void            SetModified(bool bModified)                                                             { m_ValFlags.Modified = bModified; }
332         virtual void            SetAffected(bool bAffected=true)                                                { m_ValFlags.Affected = bAffected; }
333         inline void                     SetReleaseRequested(bool bReleaseRequested)                             { m_ValFlags.ReleaseRequested=bReleaseRequested; }
334         inline void                     SetError(bool err)                                                                              { m_ValFlags.Error=err; }
335         inline void                     SetVisible (bool vis)                                                                   { m_ValFlags.Visible=vis; }
336                                                                                                                                                                 
337         virtual bool            IsModified()                                                                                    { return m_ValFlags.Modified; }
338         inline bool                     IsError()                                                                                               { return m_ValFlags.Error; }
339         virtual bool            IsAffected()                                                                                    { return m_ValFlags.Affected || m_ValFlags.Modified; }
340         virtual bool            IsSelected()                                                                                    { return m_ValFlags.Selected; }
341         inline bool                     IsReleaseRequested()                                                                    { return m_ValFlags.ReleaseRequested; }
342         virtual bool            IsVisible()                                                                                             { return m_ValFlags.Visible;}
343         virtual void            SetCustomFlag1(bool bCustomFlag)                                                { m_ValFlags.CustomFlag1 = bCustomFlag;};
344         virtual bool            IsCustomFlag1()                                                                                 { return m_ValFlags.CustomFlag1;};
345
346         virtual void            SetCustomFlag2(bool bCustomFlag)                                                { m_ValFlags.CustomFlag2 = bCustomFlag;};
347         virtual bool            IsCustomFlag2()                                                                                 { return m_ValFlags.CustomFlag2;};
348                                                                                                                                                                 
349 protected:                                                                                                                                              
350         virtual void            DisableRefCount();                                                                              // Disable reference counting for this value
351         virtual void            AddDataToReplica(CValue* replica);                                              
352         virtual                         ~CValue();
353 private:
354         // Member variables                                                                                                                     
355         std::map<STR_String,CValue*>*           m_pNamedPropertyArray;                                                                  // Properties for user/game etc
356         ValueFlags                      m_ValFlags;                                                                                             // Frequently used flags in a bitfield (low memoryusage)
357         int                                     m_refcount;                                                                                             // Reference Counter    
358         static  double m_sZeroVec[3];   
359         static bool                     m_ignore_deprecation_warnings;
360
361 };
362
363
364
365 //
366 // Declare a CValue or CExpression or CWhatever to be serialized by the editor.
367 //
368 // This macro introduces the EdSerialize() function (which must be implemented by
369 // the client) and the EdIdSerialize() function (which is implemented by this macro).
370 //
371 // The generated Copy() function returns a pointer to <root_base_class_name> type
372 // of object. So, for *any* CValue-derived object this should be set to CValue,
373 // for *any* CExpression-derived object this should be set to CExpression.
374 //
375 #define PLUGIN_DECLARE_SERIAL(class_name, root_base_class_name)                                                                                 \
376 public:                                                                                                                                                                                                 \
377         virtual root_base_class_name *  Copy()                                  { return new class_name; }                                      \
378         virtual bool EdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring);    \
379         virtual bool EdIdSerialize(CompressorArchive& arch,class CFactoryManager* facmgr,bool bIsStoring)       \
380 {                                                                                                                                                                                                               \
381         if (bIsStoring)                                                                                                                                                                         \
382                 arch.StoreString(#class_name);                                                                                                                                  \
383                                                                                                                                                                                                                 \
384         return false;                                                                                                                                                                           \
385 }                                                                                                                                                                                                               \
386         
387
388 ////////////////////////////////////////////////////////////////////////////////
389 ////////////////////////////////////////////////////////////////////////////////
390 ////////////////////////////////////////////////////////////////////////////////
391
392 // CPropValue is a CValue derived class, that implements the identification (String name)
393 // SetName() / GetName(), 
394 // normal classes should derive from CPropValue, real lightweight classes straight from CValue
395
396
397 class CPropValue : public CValue
398 {
399 public:
400
401 #ifndef NO_EXP_PYTHON_EMBEDDING 
402         CPropValue(PyTypeObject* T=&Type) :
403           CValue(T),
404 #else
405         CPropValue() :
406 #endif //NO_EXP_PYTHON_EMBEDDING
407                 m_pstrNewName(NULL)
408
409         {
410         }
411         
412         virtual ~CPropValue()
413         {
414                 if (m_pstrNewName)
415                 {
416                         delete m_pstrNewName;
417                         m_pstrNewName = NULL;
418                 }
419         }
420         
421         virtual void                    SetName(STR_String name) {
422                 if (m_pstrNewName)
423                 {
424                         delete m_pstrNewName;
425                         m_pstrNewName = NULL;   
426                 }
427                 if (name.Length())
428                         m_pstrNewName = new STR_String(name);
429         }
430         virtual void                    ReplicaSetName(STR_String name) {
431                 m_pstrNewName=NULL;
432                 if (name.Length())
433                         m_pstrNewName = new STR_String(name);
434         }
435         
436         virtual STR_String                      GetName() {
437                 //STR_String namefromprop = GetPropertyText("Name");
438                 //if (namefromprop.Length() > 0)
439                 //      return namefromprop;
440                 
441                 if (m_pstrNewName)
442                 {
443                         return *m_pstrNewName;
444                 }
445                 return STR_String("");
446         };                                              // name of Value
447         
448 protected:
449         STR_String*                                     m_pstrNewName;                              // Identification
450 };
451
452 #endif // !defined _VALUEBASECLASS_H
453