50afac6992ec61230a3144fd14a1aa29ac8e043d
[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 bUseContinue = false;
143         KX_GameObject *obj = (KX_GameObject*)GetParent();
144         short playtype = BL_Action::ACT_MODE_PLAY;
145         float start = m_startframe;
146         float end = m_endframe;
147
148         // If we don't have an action, we can't do anything
149         if (!m_action)
150                 return false;
151
152         // Convert our playtype to one that BL_Action likes
153         switch(m_playtype)
154         {
155                 case ACT_ACTION_LOOP_END:
156                 case ACT_ACTION_LOOP_STOP:
157                         playtype = BL_Action::ACT_MODE_LOOP;
158                         break;
159
160                 case ACT_ACTION_PINGPONG:
161                         // We handle ping pong ourselves to increase compabitility
162                         // with files made prior to animation changes from GSoC 2011.
163                         playtype = BL_Action::ACT_MODE_PLAY;
164                 
165                         if (m_flag & ACT_FLAG_REVERSE)
166                         {
167                                 m_localtime = start;
168                                 start = end;
169                                 end = m_localtime;
170                         }
171
172                         break;
173                 case ACT_ACTION_FROM_PROP:
174                         CValue* prop = GetParent()->GetProperty(m_propname);
175
176                         playtype = BL_Action::ACT_MODE_PLAY;
177                         start = end = prop->GetNumber();
178
179                         break;
180         }
181
182         // Continue only really makes sense for play stop and flipper. All other modes go until they are complete.
183         if (m_flag & ACT_FLAG_CONTINUE &&
184                 (m_playtype == ACT_ACTION_LOOP_STOP ||
185                 m_playtype == ACT_ACTION_FLIPPER))
186                 bUseContinue = true;
187         
188         
189         // Handle events
190         if (frame)
191         {
192                 bNegativeEvent = m_negevent;
193                 bPositiveEvent = m_posevent;
194                 RemoveAllEvents();
195         }
196
197         if (bUseContinue && (m_flag & ACT_FLAG_ACTIVE))
198                 m_localtime = obj->GetActionFrame(m_layer);
199         
200         if (bPositiveEvent)
201         {
202                 if (obj->PlayAction(m_action->id.name+2, start, end, m_layer, m_priority, m_blendin, playtype, m_layer_weight, m_ipo_flags))
203                 {
204                         m_flag |= ACT_FLAG_ACTIVE;
205                         if (bUseContinue)
206                                 obj->SetActionFrame(m_layer, m_localtime);
207
208                         if (m_playtype == ACT_ACTION_PLAY)
209                                 m_flag |= ACT_FLAG_PLAY_END;
210                         else
211                                 m_flag &= ~ACT_FLAG_PLAY_END;
212                 }
213                 else
214                         return false;
215         }
216         else if ((m_flag & ACT_FLAG_ACTIVE) && bNegativeEvent)
217         {       
218                 bAction *curr_action = obj->GetCurrentAction(m_layer);
219                 if (curr_action && curr_action != m_action)
220                 {
221                         // Someone changed the action on us, so we wont mess with it
222                         // Hopefully there wont be too many problems with two actuators using
223                         // the same action...
224                         m_flag &= ~ACT_FLAG_ACTIVE;
225                         return false;
226                 }
227
228                 
229                 m_localtime = obj->GetActionFrame(m_layer);
230                 if (m_localtime < min(m_startframe, m_endframe) || m_localtime > max(m_startframe, m_endframe))
231                         m_localtime = m_startframe;
232
233                 switch(m_playtype)
234                 {
235                         case ACT_ACTION_LOOP_STOP:
236                                 obj->StopAction(m_layer); // Stop the action after getting the frame
237
238                                 // We're done
239                                 m_flag &= ~ACT_FLAG_ACTIVE;
240                                 return false;
241                         case ACT_ACTION_PINGPONG:
242                                 m_flag ^= ACT_FLAG_REVERSE;
243                                 // Now fallthrough to LOOP_END code
244                         case ACT_ACTION_LOOP_END:
245                                 // Convert into a play and let it finish
246                                 obj->SetPlayMode(m_layer, BL_Action::ACT_MODE_PLAY);
247
248                                 m_flag |= ACT_FLAG_PLAY_END;
249                                 break;
250         
251                         case ACT_ACTION_FLIPPER:
252                                 // Convert into a play action and play back to the beginning
253                                 end = start;
254                                 start = obj->GetActionFrame(m_layer);
255                                 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);
256
257                                 m_flag |= ACT_FLAG_PLAY_END;
258                                 break;
259                 }
260         }
261
262         // Handle a frame property if it's defined
263         if ((m_flag & ACT_FLAG_ACTIVE) && m_framepropname[0] != 0)
264         {
265                 CValue* oldprop = obj->GetProperty(m_framepropname);
266                 CValue* newval = new CFloatValue(obj->GetActionFrame(m_layer));
267                 if (oldprop)
268                         oldprop->SetValue(newval);
269                 else
270                         obj->SetProperty(m_framepropname, newval);
271
272                 newval->Release();
273         }
274
275         // Handle a finished animation
276         if ((m_flag & ACT_FLAG_PLAY_END) && obj->IsActionDone(m_layer))
277         {
278                 m_flag &= ~ACT_FLAG_ACTIVE;
279                 obj->StopAction(m_layer);
280                 return false;
281         }
282
283         return true;
284 }
285
286 #ifdef WITH_PYTHON
287
288 /* ------------------------------------------------------------------------- */
289 /* Python functions                                                          */
290 /* ------------------------------------------------------------------------- */
291
292 PyObject* BL_ActionActuator::PyGetChannel(PyObject* value) {
293         char *string= _PyUnicode_AsString(value);
294         
295         if (!string) {
296                 PyErr_SetString(PyExc_TypeError, "expected a single string");
297                 return NULL;
298         }
299         
300         bPoseChannel *pchan;
301         
302         if(m_userpose==NULL && m_pose==NULL) {
303                 BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
304                 obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
305         }
306         
307         // get_pose_channel accounts for NULL pose, run on both incase one exists but
308         // the channel doesnt
309         if(             !(pchan=get_pose_channel(m_userpose, string)) &&
310                         !(pchan=get_pose_channel(m_pose, string))  )
311         {
312                 PyErr_SetString(PyExc_ValueError, "channel doesnt exist");
313                 return NULL;
314         }
315
316         PyObject *ret = PyTuple_New(3);
317         
318         PyObject *list = PyList_New(3); 
319         PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->loc[0]));
320         PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->loc[1]));
321         PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->loc[2]));
322         PyTuple_SET_ITEM(ret, 0, list);
323         
324         list = PyList_New(3);
325         PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->size[0]));
326         PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->size[1]));
327         PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->size[2]));
328         PyTuple_SET_ITEM(ret, 1, list);
329         
330         list = PyList_New(4);
331         PyList_SET_ITEM(list, 0, PyFloat_FromDouble(pchan->quat[0]));
332         PyList_SET_ITEM(list, 1, PyFloat_FromDouble(pchan->quat[1]));
333         PyList_SET_ITEM(list, 2, PyFloat_FromDouble(pchan->quat[2]));
334         PyList_SET_ITEM(list, 3, PyFloat_FromDouble(pchan->quat[3]));
335         PyTuple_SET_ITEM(ret, 2, list);
336
337         return ret;
338 /*
339         return Py_BuildValue("([fff][fff][ffff])",
340                 pchan->loc[0], pchan->loc[1], pchan->loc[2],
341                 pchan->size[0], pchan->size[1], pchan->size[2],
342                 pchan->quat[0], pchan->quat[1], pchan->quat[2], pchan->quat[3] );
343 */
344 }
345
346 /*     setChannel                                                         */
347 KX_PYMETHODDEF_DOC(BL_ActionActuator, setChannel,
348 "setChannel(channel, matrix)\n"
349 "\t - channel   : A string specifying the name of the bone channel.\n"
350 "\t - matrix    : A 4x4 matrix specifying the overriding transformation\n"
351 "\t               as an offset from the bone's rest position.\n")
352 {
353         BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
354         char *string;
355         PyObject *pymat= NULL;
356         PyObject *pyloc= NULL, *pysize= NULL, *pyquat= NULL;
357         bPoseChannel *pchan;
358         
359         if(PyTuple_Size(args)==2) {
360                 if (!PyArg_ParseTuple(args,"sO:setChannel", &string, &pymat)) // matrix
361                         return NULL;
362         }
363         else if(PyTuple_Size(args)==4) {
364                 if (!PyArg_ParseTuple(args,"sOOO:setChannel", &string, &pyloc, &pysize, &pyquat)) // loc/size/quat
365                         return NULL;
366         }
367         else {
368                 PyErr_SetString(PyExc_ValueError, "Expected a string and a 4x4 matrix (2 args) or a string and loc/size/quat sequences (4 args)");
369                 return NULL;
370         }
371         
372         if(pymat) {
373                 float matrix[4][4];
374                 MT_Matrix4x4 mat;
375                 
376                 if(!PyMatTo(pymat, mat))
377                         return NULL;
378                 
379                 mat.getValue((float*)matrix);
380                 
381                 BL_ArmatureObject *obj = (BL_ArmatureObject*)GetParent();
382                 
383                 if (!m_userpose) {
384                         if(!m_pose)
385                                 obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
386                         game_copy_pose(&m_userpose, m_pose, 0);
387                 }
388                 // pchan= verify_pose_channel(m_userpose, string); // adds the channel if its not there.
389                 pchan= get_pose_channel(m_userpose, string); // adds the channel if its not there.
390                 
391                 if(pchan) {
392                         VECCOPY (pchan->loc, matrix[3]);
393                         mat4_to_size( pchan->size,matrix);
394                         mat4_to_quat( pchan->quat,matrix);
395                 }
396         }
397         else {
398                 MT_Vector3 loc;
399                 MT_Vector3 size;
400                 MT_Quaternion quat;
401                 
402                 if (!PyVecTo(pyloc, loc) || !PyVecTo(pysize, size) || !PyQuatTo(pyquat, quat))
403                         return NULL;
404                 
405                 // same as above
406                 if (!m_userpose) {
407                         if(!m_pose)
408                                 obj->GetPose(&m_pose); /* Get the underlying pose from the armature */
409                         game_copy_pose(&m_userpose, m_pose, 0);
410                 }
411                 // pchan= verify_pose_channel(m_userpose, string);
412                 pchan= get_pose_channel(m_userpose, string); // adds the channel if its not there.
413                 
414                 // for some reason loc.setValue(pchan->loc) fails
415                 if(pchan) {
416                         pchan->loc[0]= loc[0]; pchan->loc[1]= loc[1]; pchan->loc[2]= loc[2];
417                         pchan->size[0]= size[0]; pchan->size[1]= size[1]; pchan->size[2]= size[2];
418                         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 */
419                 }
420         }
421         
422         if(pchan==NULL) {
423                 PyErr_SetString(PyExc_ValueError, "Channel could not be found, use the 'channelNames' attribute to get a list of valid channels");
424                 return NULL;
425         }
426         
427         Py_RETURN_NONE;
428 }
429
430 /* ------------------------------------------------------------------------- */
431 /* Python Integration Hooks                                                                      */
432 /* ------------------------------------------------------------------------- */
433
434 PyTypeObject BL_ActionActuator::Type = {
435         PyVarObject_HEAD_INIT(NULL, 0)
436         "BL_ActionActuator",
437         sizeof(PyObjectPlus_Proxy),
438         0,
439         py_base_dealloc,
440         0,
441         0,
442         0,
443         0,
444         py_base_repr,
445         0,0,0,0,0,0,0,0,0,
446         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
447         0,0,0,0,0,0,0,
448         Methods,
449         0,
450         0,
451         &SCA_IActuator::Type,
452         0,0,0,0,0,0,
453         py_base_new
454 };
455
456 PyMethodDef BL_ActionActuator::Methods[] = {
457         {"getChannel", (PyCFunction) BL_ActionActuator::sPyGetChannel, METH_O},
458         KX_PYMETHODTABLE(BL_ActionActuator, setChannel),
459         {NULL,NULL} //Sentinel
460 };
461
462 PyAttributeDef BL_ActionActuator::Attributes[] = {
463         KX_PYATTRIBUTE_FLOAT_RW("frameStart", 0, MAXFRAMEF, BL_ActionActuator, m_startframe),
464         KX_PYATTRIBUTE_FLOAT_RW("frameEnd", 0, MAXFRAMEF, BL_ActionActuator, m_endframe),
465         KX_PYATTRIBUTE_FLOAT_RW("blendIn", 0, MAXFRAMEF, BL_ActionActuator, m_blendin),
466         KX_PYATTRIBUTE_RW_FUNCTION("action", BL_ActionActuator, pyattr_get_action, pyattr_set_action),
467         KX_PYATTRIBUTE_RO_FUNCTION("channelNames", BL_ActionActuator, pyattr_get_channel_names),
468         KX_PYATTRIBUTE_SHORT_RW("priority", 0, 100, false, BL_ActionActuator, m_priority),
469         KX_PYATTRIBUTE_RW_FUNCTION("frame", BL_ActionActuator, pyattr_get_frame, pyattr_set_frame),
470         KX_PYATTRIBUTE_STRING_RW("propName", 0, 31, false, BL_ActionActuator, m_propname),
471         KX_PYATTRIBUTE_STRING_RW("framePropName", 0, 31, false, BL_ActionActuator, m_framepropname),
472         KX_PYATTRIBUTE_RW_FUNCTION("useContinue", BL_ActionActuator, pyattr_get_use_continue, pyattr_set_use_continue),
473         KX_PYATTRIBUTE_FLOAT_RW_CHECK("blendTime", 0, MAXFRAMEF, BL_ActionActuator, m_blendframe, CheckBlendTime),
474         KX_PYATTRIBUTE_SHORT_RW_CHECK("mode",0,100,false,BL_ActionActuator,m_playtype,CheckType),
475         { NULL }        //Sentinel
476 };
477
478 PyObject* BL_ActionActuator::pyattr_get_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
479 {
480         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
481         return PyUnicode_FromString(self->GetAction() ? self->GetAction()->id.name+2 : "");
482 }
483
484 int BL_ActionActuator::pyattr_set_action(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
485 {
486         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
487         
488         if (!PyUnicode_Check(value))
489         {
490                 PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, expected the string name of the action");
491                 return PY_SET_ATTR_FAIL;
492         }
493
494         bAction *action= NULL;
495         STR_String val = _PyUnicode_AsString(value);
496         
497         if (val != "")
498         {
499                 action= (bAction*)SCA_ILogicBrick::m_sCurrentLogicManager->GetActionByName(val);
500                 if (!action)
501                 {
502                         PyErr_SetString(PyExc_ValueError, "actuator.action = val: Action Actuator, action not found!");
503                         return PY_SET_ATTR_FAIL;
504                 }
505         }
506         
507         self->SetAction(action);
508         return PY_SET_ATTR_SUCCESS;
509
510 }
511
512 PyObject* BL_ActionActuator::pyattr_get_channel_names(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
513 {
514         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
515         PyObject *ret= PyList_New(0);
516         PyObject *item;
517         
518         bPose *pose= ((BL_ArmatureObject*)self->GetParent())->GetOrigPose();
519         
520         if(pose) {
521                 bPoseChannel *pchan;
522                 for(pchan= (bPoseChannel *)pose->chanbase.first; pchan; pchan= (bPoseChannel *)pchan->next) {
523                         item= PyUnicode_FromString(pchan->name);
524                         PyList_Append(ret, item);
525                         Py_DECREF(item);
526                 }
527         }
528         
529         return ret;
530 }
531
532 PyObject* BL_ActionActuator::pyattr_get_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
533 {
534         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
535         return PyBool_FromLong(self->m_flag & ACT_FLAG_CONTINUE);
536 }
537
538 int BL_ActionActuator::pyattr_set_use_continue(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
539 {
540         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
541         
542         if (PyObject_IsTrue(value))
543                 self->m_flag |= ACT_FLAG_CONTINUE;
544         else
545                 self->m_flag &= ~ACT_FLAG_CONTINUE;
546         
547         return PY_SET_ATTR_SUCCESS;
548 }
549
550 PyObject* BL_ActionActuator::pyattr_get_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef)
551 {
552         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
553         return PyFloat_FromDouble(((KX_GameObject*)self->m_gameobj)->GetActionFrame(self->m_layer));
554 }
555
556 int BL_ActionActuator::pyattr_set_frame(void *self_v, const KX_PYATTRIBUTE_DEF *attrdef, PyObject *value)
557 {
558         BL_ActionActuator* self= static_cast<BL_ActionActuator*>(self_v);
559         
560         ((KX_GameObject*)self->m_gameobj)->SetActionFrame(self->m_layer, PyFloat_AsDouble(value));
561         
562         return PY_SET_ATTR_SUCCESS;
563 }
564
565 #endif // WITH_PYTHON