summaryrefslogtreecommitdiff
path: root/public/python/valvePython/valvePython.h
blob: 5a0a9e0ffa4b018e7a6970a3945b0ce5413ff252 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//======= Copyright � 1996-2007, Valve Corporation, All rights reserved. ======
//
// Purpose:
//
//=============================================================================

#ifndef VALVEPYTHON_H
#define VALVEPYTHON_H


#if defined( _WIN32 )
#pragma once
#endif


// Python includes
#include <Python.h>


// Valve includes
#include "interface.h"
#include "tier1/utlvector.h"
#include "tier1/utlstring.h"

//-----------------------------------------------------------------------------
// Finds the GetAppFactory function in the specified python module and returns
// the app factory handle or NULL on error
//-----------------------------------------------------------------------------
CreateInterfaceFn ValvePythonAppFactory( const char *pGetAppFactory = "GetAppFactory" );


//=============================================================================
//
// Should be called by each module's init function
//
//=============================================================================
bool ValvePythonInit( CreateInterfaceFn pInFactory = NULL );


//=============================================================================
//
// Python command factory class
//
//=============================================================================
class CValvePythonCommand
{
public:
	// Constructor
	CValvePythonCommand( const char *pName, PyCFunction pMeth, int nFlags, const char *pDoc )
	: m_name( pName )
	, m_pMeth( pMeth )
	, m_nFlags( nFlags )
	, m_doc( pDoc )
	{
		m_pNextFactory = s_pFirstFactory;
		s_pFirstFactory = this;
	}

	static void Register( char *pModuleName );

protected:

	void Register( CUtlVector< PyMethodDef > &pyMethodDefs );

private:
	// The next factory
	CValvePythonCommand *m_pNextFactory;
	static CValvePythonCommand *s_pFirstFactory;
	// Has to stay in same place in memory for duration of python
	static CUtlVector< PyMethodDef > s_pyMethodDefs;

	CUtlString m_name;
	PyCFunction m_pMeth;
	const int m_nFlags;
	CUtlString m_doc;
};


//-----------------------------------------------------------------------------
// Macro to install a valve python command
//
// Use it like this:
//
// PYTHON_COMMAND( foo, METH_VARARGS, "The documentation for foo" )
//-----------------------------------------------------------------------------
#define PYTHON_COMMAND( _name, _flags, _doc ) \
	extern "C" static PyObject *_name##_pythonFunc( PyObject *pSelf, PyObject *pArgs ); \
	static CValvePythonCommand _name##_command( #_name, _name##_pythonFunc, _flags, _doc ); \
	extern "C" static PyObject *_name##_pythonFunc( PyObject *pSelf, PyObject *pArgs )

//-----------------------------------------------------------------------------
// Macro to install a valve python command which uses keywords in the interface
//
// Use it like this:
//
// PYTHON_COMMAND( foo, METH_VARARGS, "The documentation for foo" )
//-----------------------------------------------------------------------------
#define PYTHON_COMMAND_KEYWORDS( _name, _flags, _doc ) \
	extern "C" static PyObject *_name##_pythonFunc( PyObject *pSelf, PyObject *pArgs, PyObject *pKeywords ); \
	static CValvePythonCommand _name##_command( #_name, reinterpret_cast< PyCFunction >( _name##_pythonFunc ), _flags, _doc ); \
	extern "C" static PyObject *_name##_pythonFunc( PyObject *pSelf, PyObject *pArgs, PyObject *pKeywords )


//=============================================================================
//
// Python sub module factory class
//
//=============================================================================
class CValvePythonSubModule
{
public:
	typedef void ( *PythonInitFunc_t )( void );

	// Constructor
	CValvePythonSubModule( const char *pName, PythonInitFunc_t pInitFunc )
	: m_name( "_" )
	, m_pInitFunc( pInitFunc )
	{
		m_name += pName;
		m_pNextFactory = s_pFirstFactory;
		s_pFirstFactory = this;
	}

	static void Register( PyObject *pPackage );

private:
	// The next factory
	CValvePythonSubModule *m_pNextFactory;
	static CValvePythonSubModule *s_pFirstFactory;

	CUtlString m_name;
	PythonInitFunc_t m_pInitFunc;
};


//-----------------------------------------------------------------------------
// Macro to install a valve python command
//
// Use it like this:
//
// PYTHON_COMMAND( foo, METH_VARARGS, "The documentation for foo" )
//-----------------------------------------------------------------------------
#define PYTHON_SUBMODULE( _name ) \
	extern "C" void init_##_name( void ); \
	static CValvePythonSubModule _name##_submodule( #_name, init_##_name );


// Support for implemented extended python commands which can take multiple position arguments and specified keyword arguments
//
typedef enum _pytypes
{
	PY_FIELD_VOID = 0,			// No type or value
	PY_FIELD_BOOLEAN,			// boolean, implemented as an int, I may use this as a hint for compression
	PY_FIELD_CHARACTER,			// a byte
	PY_FIELD_UTLSTRING,			// CUtlString
	PY_FIELD_SHORT,				// 2 byte integer
	PY_FIELD_INTEGER,			// Any integer or enum
	PY_FIELD_FLOAT,				// Any floating point value
	PY_FIELD_VECTOR,			// Any vector, QAngle, or AngularImpulse
	PY_FIELD_QUATERNION,		// A quaternion
	PY_FIELD_VMATRIX,			// a Vmatrix (output coords are NOT worldspace)
	PY_FIELD_MATRIX3X4,			// matrix3x4_t

	PY_FIELD_TYPECOUNT,			// MUST BE LAST
} pytype_t;

#define _PY_PARAMETER(var_name,type,parameter_name,help)		{ type, #var_name, offsetof(classNameTypedef, var_name), -1, parameter_name, help, NULL, sizeof( ((classNameTypedef *)0)->var_name ) }
#define _PY_ARGUMENT(var_name,type,argument_index,help)			{ type, #var_name, offsetof(classNameTypedef, var_name), argument_index, "", help, NULL, sizeof( ((classNameTypedef *)0)->var_name ) }

#define DEFINE_PY_PARAMETER(var_name,type,parameter_name,help)				_PY_PARAMETER(var_name, type, parameter_name, help )
#define DEFINE_PY_ARGUMENT(var_name,type,argument_index,help)				_PY_ARGUMENT(var_name, type, argument_index, help )

struct pydatamap_t;
struct pytypedescription_t;

#define SIZE_OF_ARRAY(p)	_ARRAYSIZE(p)

#define DECLARE_PY_PARAMETER_DESC() \
	static pydatamap_t m_ParameterMap; \
	static pydatamap_t *GetBaseParameterMap(); \
	template <typename T> friend void ParameterMapAccess(T *, pydatamap_t **p); \
	template <typename T> friend pydatamap_t *ParameterMapInit(T *); \
	virtual pydatamap_t *GetParameterMap( void );

#define BEGIN_PY_PARAMETERS( className ) \
	pydatamap_t className::m_ParameterMap = { 0, 0, #className, NULL }; \
	pydatamap_t *className::GetParameterMap( void ) { return &m_ParameterMap; } \
	pydatamap_t *className::GetBaseParameterMap() { pydatamap_t *pResult; ParameterMapAccess((BaseClass *)NULL, &pResult); return pResult; } \
	BEGIN_PY_PARAMETERS_GUTS( className )

#define BEGIN_PY_PARAMETERS_NO_BASE( className ) \
	pydatamap_t className::m_ParameterMap = { 0, 0, #className, NULL }; \
	pydatamap_t *className::GetParameterMap( void ) { return &m_ParameterMap; } \
	pydatamap_t *className::GetBaseParameterMap() { return NULL; } \
	BEGIN_PY_PARAMETERS_GUTS( className )

#define BEGIN_PY_PARAMETERS_GUTS( className ) \
	template <typename T> pydatamap_t *ParameterMapInit(T *); \
	template <> pydatamap_t *ParameterMapInit<className>( className * ); \
	namespace className##_ParameterMapInit \
	{ \
		pydatamap_t *g_DataMapHolder = ParameterMapInit( (className *)NULL ); /* This can/will be used for some clean up duties later */ \
	} \
	\
	template <> pydatamap_t *ParameterMapInit<className>( className * ) \
	{ \
		typedef className classNameTypedef; \
		static CParameterGeneratedNameHolder nameHolder(#className); \
		className::m_ParameterMap.baseMap = className::GetBaseParameterMap(); \
		static pytypedescription_t dataDesc[] = \
		{ \
		{ PY_FIELD_VOID,0,0,0,0,0,0 }, /* so you can define "empty" tables */

#define END_PY_PARAMETERS() \
		}; \
		\
		if ( sizeof( dataDesc ) > sizeof( dataDesc[0] ) ) \
		{ \
			classNameTypedef::m_ParameterMap.dataNumFields = SIZE_OF_ARRAY( dataDesc ) - 1; \
			classNameTypedef::m_ParameterMap.dataDesc 	  = &dataDesc[1]; \
		} \
		else \
		{ \
			classNameTypedef::m_ParameterMap.dataNumFields = 1; \
			classNameTypedef::m_ParameterMap.dataDesc 	  = dataDesc; \
		} \
		return &classNameTypedef::m_ParameterMap; \
	}

#define IMPLEMENT_NULL_PY_PARAMETERS( derivedClass ) \
	BEGIN_PY_PARAMETERS_GUTS( derivedClass ) \
	END_PY_PARAMETERS()

struct pytypedescription_t
{
	pytype_t			type;
	const char			*var_name;
	int					offset;
	// index of the argument in the script file function call
	int					argument_index;
	// the name of the parameter in script files
	const char			*parameter_name;	
	const char			*help;
	// For embedding additional datatables inside this one
	pydatamap_t			*td;  // NOT HOOKED UP YET!!!

	// Stores the actual member variable size in bytes
	int					fieldSizeInBytes;
};

struct pydatamap_t
{
	pytypedescription_t	*dataDesc;
	int					dataNumFields;
	char const			*dataClassName;
	pydatamap_t			*baseMap;
};

template <typename T> 
inline void ParameterMapAccess(T *ignored, pydatamap_t **p)
{
	*p = &T::m_ParameterMap;
}


//-----------------------------------------------------------------------------

class CParameterGeneratedNameHolder
{
public:
	CParameterGeneratedNameHolder( const char *pszBase )
		: m_pszBase(pszBase)
	{
		m_nLenBase = strlen( m_pszBase );
	}

	~CParameterGeneratedNameHolder()
	{
		for ( int i = 0; i < m_Names.Count(); i++ )
		{
			delete m_Names[i];
		}
	}

	const char *GenerateName( const char *pszIdentifier )
	{
		char *pBuf = new char[m_nLenBase + strlen(pszIdentifier) + 1];
		strcpy( pBuf, m_pszBase );
		strcat( pBuf, pszIdentifier );
		m_Names.AddToTail( pBuf );
		return pBuf;
	}

private:
	const char *m_pszBase;
	size_t m_nLenBase;
	CUtlVector<char *> m_Names;
};

#define PYTHON_COMMAND_EXTENDED( _className ) \
	static _className g_##_className##Instance;\
	extern "C" static PyObject *g_##_className##Dispatch( PyObject *pSelf, PyObject *pArgs, PyObject *pKeywords ) \
{ \
	return g_##_className##Instance.DispatchRaw( pSelf, pArgs, pKeywords ); \
} \
	static CValvePythonCommand _className##_command( g_##_className##Instance.GetName(), reinterpret_cast< PyCFunction >( g_##_className##Dispatch ), g_##_className##Instance.GetFlags(), g_##_className##Instance.GetDoc() ); \

class CBasePythonCommand
{
	DECLARE_PY_PARAMETER_DESC();

public:
	CBasePythonCommand( const char *pchCommandName, int nFlags, char const *pchHelpText, pydatamap_t *pDataMap );

	PyObject *DispatchRaw( PyObject *pSelf, PyObject *pArgs, PyObject *pKeywords );

	char const *GetName() const;
	char const *GetDoc() const;
	int GetFlags() const;
	
	virtual PyObject *Dispatch( CUtlVector< CUtlString > &args, CUtlVector< int > &typedArgs ) = 0;
	virtual void SetDefaults() = 0;

private:

	void InitParameters();
	void ProcessArguments( PyObject *pArgs, PyObject *pKeywords, CUtlVector< CUtlString > &args, CUtlVector< int > &typedArgs );
	pytypedescription_t *FindParameter( char const *pchName );
	pytypedescription_t *FindArgument( int index );
	void ExtractParameter( char const *pchName, pytypedescription_t *pTypeDescription, PyObject *pValue );
	template <class T>
	inline bool IsParameterTypeValid( pytype_t, T * ) const;

protected:

	CUtlString BuildAutoGeneratedField( char const *pchParameterName, char const *pchPrefix, int *pCounter );

	template < class T >
	inline bool GetParameter( char const *pchParameterName, T *value );

protected:

	char const					*m_pchCommandName;
	int							m_nFlags;
	char const					*m_pchBaseHelpText;
	CUtlString					m_HelpText;
	pydatamap_t					*m_pDataMap;
};

#endif // VALVEPYTHON_H