8efcdd8c551e89c6610f130bd0707cdb0ac51ffa
[blender.git] / source / gameengine / Converter / BL_ActionActuator.cpp
1 /*
2 * $Id$
3 *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28 */
29
30 /** \file gameengine/Converter/BL_ActionActuator.cpp
31  *  \ingroup bgeconv
32  */
33
34
35 #include "SCA_LogicManager.h"
36 #include "BL_ActionActuator.h"
37 #include "BL_ArmatureObject.h"
38 #include "BL_SkinDeformer.h"
39 #include "BL_Action.h"
40 #include "KX_GameObject.h"
41 #include "STR_HashedString.h"
42 #include "MEM_guardedalloc.h"
43 #include "DNA_nla_types.h"
44 #include "DNA_action_types.h"
45 #include "DNA_armature_types.h"
46 #include "DNA_scene_types.h"
47 #include "BLI_blenlib.h"
48 #include "BLI_math.h"
49 #include "BLI_utildefines.h"
50 #include "MT_Matrix4x4.h"
51
52 #include "BKE_action.h"
53 #include "FloatValue.h"
54 #include "PyObjectPlus.h"
55 #include "KX_PyMath.h"
56
57 extern "C" {
58 #include "BKE_animsys.h"
59 #include "BKE_action.h"
60 #include "RNA_access.h"
61 #include "RNA_define.h"
62 }
63
64 BL_ActionActuator::BL_ActionActuator(SCA_IObject* gameobj,
65                                         const STR_String& propname,
66                                         const STR_String& framepropname,
67                                         float starttime,
68                                         float endtime,
69                                         struct bAction *action,
70                                         short   playtype,
71                                         short   blendin,
72                                         short   priority,
73                                         short   layer,
74                                         float   layer_weight,
75                                         short   ipo_flags,
76                                         short   end_reset,
77                                         float   stride) 
78         : SCA_IActuator(gameobj, KX_ACT_ACTION),
79                 
80         m_lastpos(0, 0, 0),
81         m_blendframe(0),
82         m_flag(0),
83         m_startframe (starttime),
84         m_endframe(endtime) ,
85         m_starttime(0),
86         m_localtime(starttime),
87         m_lastUpdate(-1),
88         m_blendin(blendin),
89         m_blendstart(0),
90         m_stridelength(stride),
91         m_playtype(playtype),
92         m_priority(priority),
93         m_layer(layer),
94         m_layer_weight(layer_weight),
95         m_ipo_flags(ipo_flags),
96         m_pose(NULL),
97         m_blendpose(NULL),
98         m_userpose(NULL),
99         m_action(action),
100         m_propname(propname),
101         m_framepropname(framepropname)          
102 {
103         if (!end_reset)
104                 m_flag |= ACT_FLAG_CONTINUE;
105 };
106
107 BL_ActionActuator::~BL_ActionActuator()
108 {
109         if (m_pose)
110                 game_free_pose(m_pose);
111         if (m_userpose)
112                 game_free_pose(m_userpose);
113         if (m_blendpose)
114                 game_free_pose(m_blendpose);
115 }
116
117 void BL_ActionActuator::ProcessReplica()
118 {
119         SCA_IActuator::ProcessReplica();
120         
121         m_pose = NULL;
122         m_blendpose = NULL;
123         m_localtime=m_startframe;
124         m_lastUpdate=-1;
125         
126 }
127
128 void BL_ActionActuator::SetBlendTime (float newtime){
129         m_blendframe = newtime;
130 }
131
132 CValue* BL_ActionActuator::GetReplica() {
133         BL_ActionActuator* replica = new BL_ActionActuator(*this);//m_float,GetName());
134         replica->ProcessReplica();
135         return replica;
136 }
137
138 bool BL_ActionActuator::Update(double curtime, bool frame)
139 {
140         bool bNegativeEvent = false;
141         bool bPositiveEvent = false;
142         bool use_continue = false;
143         KX_GameObject *obj = (KX_GameObject*)GetParent();
144         short play_mode = BL_Action::ACT_MODE_PLAY;
145         float start = m_startframe, end = m_endframe;
146
147         // If we don't have an action, we can't do anything
148         if (!m_action)
149                 return false;
150
151         // Convert playmode
152         if (m_playtype == ACT_ACTION_LOOP_END)
153                 play_mode = BL_Action::ACT_MODE_LOOP;
154         else if (m_playtype == ACT_ACTION_LOOP_STOP)
155                 play_mode = BL_Action::ACT_MODE_LOOP;
156         else if (m_playtype == ACT_ACTION_PINGPONG)
157         {
158                 // We handle ping pong ourselves to increase compabitility with the pre-Pepper actuator
159                 play_mode = BL_Action::ACT_MODE_PLAY;
160                 
161                 if (m_flag & ACT_FLAG_REVERSE)
162                 {
163                         float tmp = start;
164                         start = end;
165                         end = tmp;
166                         m_localtime = end;
167                 }
168         }
169         else if (m_playtype == ACT_ACTION_FROM_PROP)
170         {
171                 CValue* prop = GetParent()->GetProperty(m_propname);
172
173                 play_mode = BL_Action::ACT_MODE_PLAY;
174                 start = end = prop->GetNumber();
175         }
176
177         // Continue only really makes sense for play stop. All other modes go until they are complete.
178         if (m_flag & ACT_FLAG_CONTINUE && m_playtype == ACT_ACTION_LOOP_STOP)
179                 use_continue = true;
180         
181         
182         // Handle events
183         if (frame)
184         {
185                 bNegativeEvent = m_negevent;
186                 bPositiveEvent = m_posevent;
187                 RemoveAllEvents();
188         }
189         
190         if (bPositiveEvent)
191         {
192                 if (obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, m_blendin, play_mode, m_layer_weight, m_ipo_flags))
193                 {
194                         m_flag |= ACT_FLAG_ACTIVE;
195                         if (use_continue)
196                                 obj->SetActionFrame(m_layer, m_localtime);
197
198                         if (m_playtype == ACT_ACTION_PLAY)
199                                 m_flag |= ACT_FLAG_PLAY_END;
200                         else
201                                 m_flag &= ~ACT_FLAG_PLAY_END;
202                 }
203                 else
204                         return false;
205         }
206         else if ((m_flag & ACT_FLAG_ACTIVE) && bNegativeEvent)
207         {       
208                 bAction *curr_action = obj->GetCurrentAction(m_layer);
209                 if (curr_action && curr_action != m_action)
210                 {
211                         // Someone changed the action on us, so we wont mess with it
212                         // Hopefully there wont be too many problems with two actuators using
213                         // the same action...
214                         m_flag &= ~ACT_FLAG_ACTIVE;
215                         return false;
216                 }
217
218                 if (m_playtype == ACT_ACTION_LOOP_STOP)
219                 {
220                         m_localtime = obj->GetActionFrame(m_layer);
221                         if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe))
222                                 m_localtime = m_startframe;
223                         obj->StopAction(m_layer); // Stop the action after getting the frame
224
225                         // We're done
226                         m_flag &= ~ACT_FLAG_ACTIVE;
227                         return false;
228                 }
229                 else if (m_playtype == ACT_ACTION_LOOP_END || m_playtype == ACT_ACTION_PINGPONG)
230                 {
231                         // Convert into a play and let it finish
232                         obj->SetPlayMode(m_layer, BL_Action::ACT_MODE_PLAY);
233
234                         m_flag |= ACT_FLAG_PLAY_END;
235
236                         if (m_playtype == ACT_ACTION_PINGPONG)
237                                 m_flag ^= ACT_FLAG_REVERSE;
238                 }
239                 else if (m_playtype == ACT_ACTION_FLIPPER)
240                 {
241                         // Convert into a play action and play back to the beginning
242                         end = start;
243                         start = obj->GetActionFrame(m_layer);
244                         obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, 0, BL_Action::ACT_MODE_PLAY, m_layer_weight, m_ipo_flags);
245
246                         m_flag |= ACT_FLAG_PLAY_END;
247                 }
248         }
249
250         // Handle a frame property if it's defined
251         if ((m_flag & ACT_FLAG_ACTIVE) && m_framepropname[0] != 0)
252         {
253                 CValue* oldprop = obj->GetProperty(m_framepropname);
254                 CValue* newval = new CFloatValue(obj->GetActionFrame(m_layer));
255                 if (oldprop)
256                         oldprop->SetValue(newval);
257                 else
258                         obj->SetProperty(m_framepropname, newval);
259
260                 newval->Release();
261         }
262
263         // Handle a finished animation
264         if ((m_flag & ACT_FLAG_PLAY_END) && obj->IsActionDone(m_layer))
265         {
266                 m_flag &= ~ACT_FLAG_ACTIVE;
267                 obj->StopAction(m_layer);
268                 return false;
269         }
270
271         return true;
272 }
273
274 #ifdef WITH_PYTHON
275
276 /* ------------------------------------------------------------------------- */
277 /* Python functions                                                          */
278 /* ------------------------------------------------------------------------- */
279
280 PyObject* BL_ActionActuator::PyGetChannel(PyObject* value) {
281         char *string= _PyUnicode_AsString(value);
282         
283         if (!string) {
284                 PyErr_SetString(PyExc_TypeError, "expected a single string");
285                 return NULL;
286         }
287         
288         bPoseChannel *pchan;
289         
290         if(m_userpose==NULL && m_pose==NULL) {
291                 BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
292                 obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
293         }
294         
295         // get_pose_channel accounts for NULL pose, run on both incase one exists but
296         // the channel doesnt
297         if(             !(pchan=get_pose_channel(m_userpose, string)) &&
298                         !(pchan=get_pose_channel(m_pose, string))  )
299         {
300                 PyErr_SetString(PyExc_ValueError, "channel doesnt exist");
301                 return NULL;
302         }
303
304         PyObject *ret = PyTuple_New(3);
305         
306         PyObject *list = PyList_New(3); 
307         PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->loc[0]));
308         PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->loc[1]));
309         PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->loc[2]));
310         PyTuple_SET_ITEM(ret, 0, list);
311         
312         list = PyList_New(3);
313         PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->size[0]));
314         PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->size[1]));
315         PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->size[2]));
316         PyTuple_SET_ITEM(ret, 1, list);
317         
318         list = PyList_New(4);
319         PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->quat[0]));
320         PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->quat[1]));
321         PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->quat[2]));
322         PyList_SET_ITEM(list, 3, PyFloat_FromDouble(pchan->quat[3]));
323         PyTuple_SET_ITEM(ret, 2, list);
324
325         return ret;
326 /*
327         return Py_BuildValue("([fff][fff][ffff])",
328                 pchan->loc[0], pchan->loc[1], pchan->loc[2],
329                 pchan->size[0], pchan->size[1], pchan->size[2],
330                 pchan->quat[0], pchan->quat[1], pchan->quat[2], pchan->quat[3] );
331 */
332 }
333
334 /*     setChannel                                                         */
335 KX_PYMETHODDEF_DOC(BL_ActionActuator, setChannel,
336 "setChannel(channel, matrix)\n"
337 "\t - channel   : A string specifying the name of the bone channel.\n"
338 "\t - matrix    : A 4x4 matrix specifying the overriding transformation\n"
339 "\t               as an offset from the bone's rest position.\n")
340 {
341         BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
342         char *string;
343         PyObject *pymat= NULL;
344         PyObject *pyloc= NULL, *pysize= NULL, *pyquat= NULL;
345         bPoseChannel *pchan;
346         
347         if(PyTuple_Size(args)==2) {
348                 if (!PyArg_ParseTuple(args,"sO:setChannel", &string, &pymat)) // matrix
349                         return NULL;
350         }
351         else if(PyTuple_Size(args)==4) {
352                 if (!PyArg_ParseTuple(args,"sOOO:setChannel", &string, &pyloc, &pysize, &pyquat)) // loc/size/quat
353                         return NULL;
354         }
355         else {
356                 PyErr_SetString(PyExc_ValueError, "Expected a string and a 4x4 matrix (2 args) or a string and loc/size/quat sequences (4 args)");
357                 return NULL;
358         }
359         
360         if(pymat) {
361                 float matrix[4][4];
362                 MT_Matrix4x4 mat;
363                 
364                 if(!PyMatTo(pymat, mat))
365                         return NULL;
366                 
367                 mat.getValue((float*)matrix);
368                 
369                 BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
370                 
371                 if (!m_userpose) {
372                         if(!m_pose)
373                                 obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
374                         game_copy_pose(&m_userpose, m_pose, 0);
375                 }
376                 // pchan= verify_pose_channel(m_userpose, string); // adds the channel if its not there.
377                 pchan= get_pose_channel(m_userpose, string); // adds the channel if its not there.
378                 
379                 if(pchan) {
380                         VECCOPY (pchan->loc, matrix[3]);
381                         mat4_to_size( pchan->size,matrix);
382                         mat4_to_quat( pchan->quat,matrix);
383                 }
384         }
385         else {
386                 MT_Vector3 loc;
387                 MT_Vector3 size;
388                 MT_Quaternion quat;
389                 
390                 if (!PyVecTo(pyloc, loc) || !PyVecTo(pysize, size) || !PyQuatTo(pyquat, quat))
391                         return NULL;
392                 
393                 // same as above
394                 if (!m_userpose) {
395                         if(!m_pose)
396                                 obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
397                         game_copy_pose(&m_userpose, m_pose, 0);
398                 }
399                 // pchan= verify_pose_channel(m_userpose, string);
400                 pchan= get_pose_channel(m_userpose, string); // adds the channel if its not there.
401                 
402                 // for some reason loc.setValue(pchan->loc) fails
403                 if(pchan) {
404                         pchan->loc[0]= loc[0]; pchan->loc[1]= loc[1]; pchan->loc[2]= loc[2];
405                         pchan->size[0]= size[0]; pchan->size[1]= size[1]; pchan->size[2]= size[2];
406                         pchan->quat[0]= quat[3]; pchan->quat[1]= quat[0]; pchan->quat[2]= quat[1]; pchan->quat[3]= quat[2]; /* notice xyzw -> wxyz is intentional */
407                 }
408         }
409         
410         if(pchan==NULL) {
411                 PyErr_SetString(PyExc_ValueError, "Channel could not be found, use the 'channelNames' attribute to get a list of valid channels");
412                 return NULL;
413         }
414         
415         Py_RETURN_NONE;
416 }
417
418 /* ------------------------------------------------------------------------- */
419 /* Python Integration Hooks                                                                      */
420 /* ------------------------------------------------------------------------- */
421
422 PyTypeObject BL_ActionActuator::Type = {
423         PyVarObject_HEAD_INIT(NULL, 0)
424         "BL_ActionActuator",
425         sizeof(PyObjectPlus_Proxy),
426         0,
427         py_base_dealloc,
428         0,
429         0,
430         0,
431         0,
432         py_base_repr,
433         0,0,0,0,0,0,0,0,0,
434         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
435         0,0,0,0,0,0,0,
436         Methods,
437         0,
438         0,
439         &SCA_IActuator::Type,
440         0,0,0,0,0,0,
441         py_base_new
442 };
443
444 PyMethodDef BL_ActionActuator::Methods[] = {
445         {"getChannel", (PyCFunction) BL_ActionActuator::sPyGetChannel, METH_O},
446         KX_PYMETHODTABLE(BL_ActionActuator, setChannel),
447         {NULL,NULL} //Sentinel
448 };
449
450 PyAttributeDef BL_ActionActuator::Attributes[] = {
451         KX_PYATTRIBUTE_FLOAT_RW("frameStart", 0, MAXFRAMEF, BL_ActionActuator, m_startframe),
452         KX_PYATTRIBUTE_FLOAT_RW("frameEnd", 0, MAXFRAMEF, BL_ActionActuator, m_endframe),
453         KX_PYATTRIBUTE_FLOAT_RW("blendIn", 0, MAXFRAMEF, BL_ActionActuator, m_blendin),
454         KX_PYATTRIBUTE_RW_FUNCTION("action", BL_ActionActuator, pyattr_get_action, pyattr_set_action),
455         KX_PYATTRIBUTE_RO_FUNCTION("channelNames", BL_ActionActuator, pyattr_get_channel_names),
456         KX_PYATTRIBUTE_SHORT_RW("priority", 0, 100, false, BL_ActionActuator, m_priority),
457         KX_PYATTRIBUTE_FLOAT_RW_CHECK("frame", 0, MAXFRAMEF, BL_ActionActuator, m_localtime, CheckFrame),
458         KX_PYATTRIBUTE_STRING_RW("propName", 0, 31, false, BL_ActionActuator, m_propname),
459         KX_PYATTRIBUTE_STRING_RW("framePropName", 0, 31, false, BL_ActionActuator, m_framepropname),
460         KX_PYATTRIBUTE_RW_FUNCTION("useContinue", BL_ActionActuator, pyattr_get_use_continue, pyattr_set_use_continue),
461         KX_PYATTRIBUTE_FLOAT_RW_CHECK("blendTime", 0, MAXFRAMEF, BL_ActionActuator, m_blendframe, CheckBlendTime),
462         KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",0,100,false,BL_ActionActuator,m_playtype,CheckType),
463         { NULL }        //Sentinel
464 };
465
466 PyObject* BL_ActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
467 {
468         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
469         return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : "");
470 }
471
472 int BL_ActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
473 {
474         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
475         
476         if (!PyUnicode_Check(value))
477         {
478                 PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, expected the string name of the action");
479                 return PY_SET_ATTR_FAIL;
480         }
481
482         bAction *action= NULL;
483         STR_String val = _PyUnicode_AsString(value);
484         
485         if (val != "")
486         {
487                 action= (bAction*)SCA_ILogicBrick::m_sCurrentLogicManager->GetActionByName(val);
488                 if (!action)
489                 {
490                         PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, action not found!");
491                         return PY_SET_ATTR_FAIL;
492                 }
493         }
494         
495         self->SetAction(action);
496         return PY_SET_ATTR_SUCCESS;
497
498 }
499
500 PyObject* BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
501 {
502         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
503         PyObject *ret= PyList_New(0);
504         PyObject *item;
505         
506         bPose *pose= ((BL_ArmatureObject*)self->GetParent())->GetOrigPose();
507         
508         if(pose) {
509                 bPoseChannel *pchan;
510                 for(pchan= (bPoseChannel *)pose->chanbase.first; pchan; pchan= (bPoseChannel *)pchan->next) {
511                         item= PyUnicode_FromString(pchan->name);
512                         PyList_Append(ret, item);
513                         Py_DECREF(item);
514                 }
515         }
516         
517         return ret;
518 }
519
520 PyObject* BL_ActionActuator::pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
521 {
522         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
523         return PyBool_FromLong(self->m_flag & ACT_FLAG_CONTINUE);
524 }
525
526 int BL_ActionActuator::pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
527 {
528         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
529         
530         if (PyObject_IsTrue(value))
531                 self->m_flag |= ACT_FLAG_CONTINUE;
532         else
533                 self->m_flag &= ~ACT_FLAG_CONTINUE;
534         
535         return PY_SET_ATTR_SUCCESS;
536 }
537
538 #endif // WITH_PYTHON