CKERROR LogEntryCB(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKBeObject *beo = (CKBeObject *)beh->GetTarget(); if (behcontext.CallbackMessage==CKM_BEHAVIOREDITED) { /* CKParameterIn* pin = beh->GetInputParameter(0); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve first input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (pin->GetGUID()!=CKPGUID_MESSAGE) { pin->SetGUID(CKPGUID_MESSAGE,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : first input parameter type must be \"Message\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); } pin = beh->GetInputParameter(1); if (!pin) { CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : failed to retrieve second input parameter"; behcontext.Context->OutputToConsole(str.Str(),TRUE); return CKBR_PARAMETERERROR; } if (!behcontext.ParameterManager->IsDerivedFrom(pin->GetGUID(),CKPGUID_OBJECT)) { pin->SetGUID(CKPGUID_BEOBJECT,FALSE); CKBehavior* pbeh = beh; XString name; while ((pbeh=pbeh->GetParent())) { name << pbeh->GetName() << "->"; } name << beh->GetName(); XString str; str << '[' << name << "] : second input parameter type must derived from \"BeObject\"!"; behcontext.Context->OutputToConsole(str.Str(),TRUE); }*/ } return CKBR_OK; }
int TextureSinus(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; // we get the amount value float xamp=0.1f; beh->GetInputParameterValue(0, &xamp); // we get the amount value float yamp=0.1f; beh->GetInputParameterValue(1, &yamp); float l= 1.0f; beh->GetInputParameterValue(2, &l); // we get the saved uv's VxUV* savedUV = (VxUV*) beh->GetLocalParameterReadDataPtr(0); // we get the interpolated mesh CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); int channel = -1; beh->GetInputParameterValue(3, &channel); int channelcount = mesh->GetChannelCount(); if (channel < -1 || channel >= channelcount) { beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_PARAMETERERROR; } CKDWORD Stride; VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride,channel); int pointsNumber = mesh->GetModifierUVCount(channel); float time; beh->GetLocalParameterValue(1, &time); float t; for( int i=0 ; i<pointsNumber ; i++, uvarray =(VxUV *)((BYTE *)uvarray + Stride)) { t = ((float)i/pointsNumber-0.5f)*4.0f+time*l; uvarray->u = savedUV[i].u + ( 0.5f - savedUV[i].u ) * xamp * cosf(t); uvarray->v = savedUV[i].v + ( 0.5f - savedUV[i].v ) * yamp * sinf(t); } mesh->ModifierUVMove(channel); float pi = 3.1415926535f; time += behcontext.DeltaTime * 0.001f; if(l*time > 2*pi) time -= (2*pi / l); beh->SetLocalParameterValue(1, &time); beh->ActivateInput(0, FALSE); beh->ActivateOutput(0); return CKBR_OK; }
int GBLCOBGWrapper::BehaviourFunction( const CKBehaviorContext& behContext ) { CKBehavior *behaviour = behContext.Behavior; CKContext *context = behContext.Context; int iPin, nbPin; CKBehavior* script = (CKBehavior*)behaviour->GetLocalParameterObject(EGBLCOBGWRAPPERPARAM_PARAMETER_SCRIPT); if (script == NULL) return CKBR_GENERICERROR; // Activate the right inputs nbPin = behaviour->GetInputCount(); for (iPin = 0; iPin < nbPin; iPin++) { if (behaviour->IsInputActive(iPin)) { script->ActivateInput(iPin, TRUE); behaviour->ActivateInput(iPin, FALSE); } } // Deactivate all the outputs nbPin = script->GetOutputCount(); for (iPin = 0; iPin < nbPin; iPin++) { behaviour->ActivateOutput(iPin, FALSE); } // Parameter In: Set Source int nbPinBB = behaviour->GetInputParameterCount(); int nbPinBG = script->GetInputParameterCount(); if (nbPinBB != nbPinBG) return CKBR_GENERICERROR; for (iPin = 0; iPin < nbPinBB; iPin++) { CKParameterIn *pBin = behaviour->GetInputParameter(iPin); CKParameter* pSource = pBin->GetDirectSource(); CKParameterIn *pSin = script->GetInputParameter(iPin); pSin->SetDirectSource(pSource); } // Execute the contained script CKERROR result = script->Execute(behContext.DeltaTime); // The script loop on itself too much times if (result == CKBR_INFINITELOOP) { context->OutputToConsoleExBeep("Execute Script : Script %s Executed too much times",script->GetName()); script->Activate(FALSE,FALSE); return CKBR_OK; } // Activate the right outputs nbPin = script->GetOutputCount(); for (iPin = 0; iPin < nbPin; iPin++) { if (script->IsOutputActive(iPin)) { behaviour->ActivateOutput(iPin); script->ActivateOutput(iPin, FALSE); } } // Update Parameters Out nbPin = behaviour->GetOutputParameterCount(); for (iPin = 0; iPin < nbPin; iPin++) { CKParameterOut *pBout = behaviour->GetOutputParameter(iPin); CKParameterOut *pSout = script->GetOutputParameter(iPin); pBout->CopyValue(pSout, TRUE); } // Test if there are any active sub-behaviors, restart the next frame if any BOOL bActivateNextFrame = FALSE; ActivateNextFrameSubBB(script,bActivateNextFrame); if (bActivateNextFrame) return CKBR_ACTIVATENEXTFRAME; // return the execute value return result; }
//************************************ // Method: PBPhysicalize // FullName: PBPhysicalize // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBPhysicalize(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; ////////////////////////////////////////////////////////////////////////// //basic parameters CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); ////////////////////////////////////////////////////////////////////////// //settings int useDWorld; beh->GetLocalParameterValue(bbS_USE_DEFAULT_WORLD,&useDWorld); // int useWorldSS; beh->GetLocalParameterValue(bbS_USE_WORLD_SLEEP_SETTINGS,&useWorldSS); // int useWorldDS; beh->GetLocalParameterValue(bbS_USE_WORLD_DAMPING_SETTINGS,&useWorldDS); int useWorldM; beh->GetLocalParameterValue(bbS_USE_WORLD_MATERIAL,&useWorldM); int addAttributes; beh->GetLocalParameterValue(bbS_ADD_ATTRIBUTES,&addAttributes); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *referenceObject = (CK3dEntity *) beh->GetTarget(); if( !referenceObject ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// //the world : CK3dEntity*worldRef = NULL; if (!useDWorld) { worldRef = (CK3dEntity *) beh->GetInputParameterObject(bbI_TargetWorld); } // the world : pWorld *world=GetPMan()->getWorld(worldRef,referenceObject); if (!world) { beh->ActivateOutput(0); return 0; } pRigidBody*result = world->getBody(referenceObject); if (result) { beh->ActivateOutput(0); return 0; } ////////////////////////////////////////////////////////////////////////// //pick up some parameters : int flags = GetInputParameterValue<int>(beh,bbI_Flags); int hType = GetInputParameterValue<int>(beh,bbI_HullType); float density = GetInputParameterValue<float>(beh,bbI_Density); float skinWidth = GetInputParameterValue<float>(beh,bbI_SkinWidth); int hierarchy = GetInputParameterValue<int>(beh,bbI_Hierachy); float newDensity = GetInputParameterValue<float>(beh,bbI_NewDensity); float totalMass = GetInputParameterValue<float>(beh,bbI_TotalMass); VxVector massOffset = GetInputParameterValue<VxVector>(beh,bbI_MassShift); VxVector shapeOffset = GetInputParameterValue<VxVector>(beh,bbI_ShapeShift); ////////////////////////////////////////////////////////////////////////// // we remove the old physic attribute : if (referenceObject->HasAttribute(GetPMan()->GetPAttribute())) { referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); } referenceObject->SetAttribute(GetPMan()->GetPAttribute()); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HIRARCHY,&hierarchy); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_HULLTYPE,&hType); SetAttributeValue<int>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_BODY_FLAGS,&flags); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_DENSITY,&density); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_NEW_DENSITY,&newDensity); SetAttributeValue<float>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_TOTAL_MASS,&totalMass); SetAttributeValue<VxVector>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&massOffset); //SetAttributeValue<VxVector>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_MASS_OFFSET,&massOffset); CK_ID wID = world->getReference()->GetID(); AttributeTools::SetAttributeValue<CK_ID>(referenceObject,GetPMan()->GetPAttribute(),E_PPS_WORLD,&wID); ////////////////////////////////////////////////////////////////////////// //Material : if (!useWorldM) { if (referenceObject->HasAttribute(GetPMan()->att_surface_props)) { referenceObject->RemoveAttribute(GetPMan()->att_surface_props); } referenceObject->SetAttribute(GetPMan()->att_surface_props); CKParameterIn *pMatIn = beh->GetInputParameter(bbI_Material); CKParameter *pMat = pMatIn->GetRealSource(); CKParameterOut* pout = referenceObject->GetAttributeParameter(GetPMan()->att_surface_props); int error = pout->CopyValue(pMat); pout->Update(); } pRigidBody *body = pFactory::Instance()->createRigidBodyFull(referenceObject,worldRef); if (body) { body->translateLocalShapePosition(shapeOffset); } //GetPMan()->checkWorlds(); if (!addAttributes) { referenceObject->RemoveAttribute(GetPMan()->GetPAttribute()); referenceObject->RemoveAttribute(GetPMan()->att_surface_props); } beh->ActivateOutput(0); return 0; }
int GBLCOCreateError::BehaviourFunction( const CKBehaviorContext& behContext ) { CKBehavior *behaviour = behContext.Behavior; CKContext *context = behContext.Context; if ( behaviour == NULL || context == NULL ) return CKBR_GENERICERROR; behaviour->ActivateInput(ECGBLCOCreateErrorBehInputs::In, FALSE); CGBLCOErrorManager *errorManager = (CGBLCOErrorManager *)context->GetManagerByGuid(CGBLCOErrorManagerGUID); if ( errorManager == NULL ) return CKBR_GENERICERROR; // Get Parameters Inputs Source. CKParameterOut *poutError = behaviour->GetOutputParameter(ECGBLCOCreateErrorParamOutputs::GetError); if ( poutError == NULL ) return CKBR_GENERICERROR; CKParameterIn*pinCode = behaviour->GetInputParameter(ECGBLCOCreateErrorParamInputs::SetErrorCode); CKParameterIn*pinDesc = behaviour->GetInputParameter(ECGBLCOCreateErrorParamInputs::SetErrorDescription); CKParameterIn*pinType = behaviour->GetInputParameter(ECGBLCOCreateErrorParamInputs::SetErrorType); if ( pinCode == NULL || pinDesc == NULL || pinType == NULL ) return CKBR_GENERICERROR; CKParameter*paraCode = pinCode->GetRealSource(); CKParameter*paraDesc = pinDesc->GetRealSource(); CKParameter*paraType = pinType->GetRealSource(); if ( paraCode == NULL || paraDesc == NULL || paraType == NULL ) return CKBR_GENERICERROR; // Get Parameters Inputs Values (code,desc,type). int code = 0; paraCode->GetValue(&code); XString desc; int paramsize = paraDesc->GetStringValue(NULL); if (paramsize) { XAP<char> paramstring(new char[paramsize]); paraDesc->GetStringValue(paramstring,TRUE); desc << (char*)paramstring; } CGBLCOError::EGBLCOErrorType type; paraType->GetValue(&type); // Create the TGBLError parameter output. TGBLError::SetTGBLError(poutError,type,code,(CKSTRING)desc.CStr()); CK_CLASSID cid = poutError->GetClassID(); // if ( type != CGBLCOError::EGBLCOErrorType::GBLCO_FATAL ) { behaviour->ActivateOutput(ECGBLCOCreateErrorBehOutputs::OutHandled, FALSE); behaviour->ActivateOutput(ECGBLCOCreateErrorBehOutputs::OutUnhandled, TRUE); return CKBR_OK; } errorManager->NotifyError(type,code,(CKSTRING)desc.CStr()); behaviour->ActivateOutput(ECGBLCOCreateErrorBehOutputs::OutHandled, TRUE); behaviour->ActivateOutput(ECGBLCOCreateErrorBehOutputs::OutUnhandled, FALSE); return CKBR_OK; }
/* ******************************************************************* * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Parameters : * behaviourContext r Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int RetrieveCI(const CKBehaviorContext& behcontext) { /************************************************************************/ /* collecting data : */ /* */ CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CGBLCIConfigurationController* cman=(CGBLCIConfigurationController*)ctx->GetManagerByGuid(CONFIGURATION_MAN_GUID); IGBLCIManageInterface *cisFac = cman->GetCISFactoryInterface(); IGBLCIAccessInterface * accessInterface = cman->GetCISAccessInterface(); BOOL getAsString,outputAttriubtes = false; beh->GetLocalParameterValue(BEH_SETTINGS_GET_AS_STRING,&getAsString); beh->GetLocalParameterValue(BEH_SETTINGS_GET_CUSTOM_ATTRIBUTES,&outputAttriubtes); using namespace GBLCommon::BehaviorTools; using namespace GBLCommon::ParameterTools; using namespace Customisation::typedefs; int idCI = GetInputParameterValue<int>(beh,BEH_PAR_INDEX_CI); CGBLCI *currentCI = NULL; CGBLSMStorageManager *storageManager = static_cast<CGBLSMStorageManager *>(ctx->GetManagerByGuid(GBLSMStorageManagerGUID)); IGBLSMConfigurationAccess* smCIS = storageManager->GetConfigurationInterface(); currentCI = new CGBLCI("temp",CKPGUID_INT); CGBLCOError returnValue = accessInterface->GetCI(currentCI,idCI); //get error parameter CKParameterOut *parameterOutError = beh->GetOutputParameter(BEH_PIN_OUT_INDEX_ERROR); // check results and output error if (returnValue == CGBLCOError::EGBLCOErrorType::GBLCO_OK) { ////////////////////////////////////////////////////////////////////////// // output values : CKParameterOut *pout = beh->GetOutputParameter(1); if(getAsString) { //output the value VxScratch sbuffer(currentCI->realValue->GetDataSize()); CKSTRING buffer = (CKSTRING)sbuffer.Mem(); currentCI->realValue->GetStringValue(buffer); pout->SetStringValue(buffer); }else { CKParameterManager *pm = static_cast<CKParameterManager*>(ctx->GetParameterManager()); if ( beh->GetOutputParameter(0)->GetType() == currentCI->realValue->GetType() ) { pout->CopyValue(currentCI->realValue); }else { pout->SetType(currentCI->realValue->GetType()); return CKBR_PARAMETERERROR; } } ////////////////////////////////////////////////////////////////////////// // output custom attributes : if(outputAttriubtes) { //output unique name : CKParameterOut *poutName = beh->GetOutputParameter(BEH_OUT_INDEX_UNAME); poutName->SetStringValue(currentCI->name.Str()); //output description : CKParameterOut *poutDescription = beh->GetOutputParameter(BEH_OUT_INDEX_DESCRIPTION); poutDescription->SetStringValue(currentCI->description.Str()); //output default value : CKParameterOut *poutDefaultValue = beh->GetOutputParameter(BEH_OUT_INDEX_DEFAULTVALUE); TypeCheckedParameterCopy(poutDefaultValue,currentCI->defaultValue); if(getAsString) { XString outDefValue = GBLCommon::ParameterTools::GetParameterAsString(currentCI->defaultValue); poutDefaultValue->SetStringValue( outDefValue.Str() ); }else{ poutDefaultValue->CopyValue(currentCI->defaultValue,TRUE); } //output flags : int flags = 0 ; beh->SetOutputParameterValue(BEH_OUT_INDEX_FLAGS,¤tCI->flags); //output type int type = ctx->GetParameterManager()->ParameterGuidToType(currentCI->type); beh->SetOutputParameterValue(BEH_OUT_INDEX_TYPE,&type); } TGBLError::SetTGBLError(parameterOutError,returnValue.GetType(),returnValue.GetCode(),(CKSTRING)returnValue.GetDescription()); beh->ActivateOutput(BEH_PIN_OUT_INDEX_SUCCESS, true); } else { CGBLCOError::EGBLCOErrorType tType = CGBLCOError::EGBLCOErrorType::GBLCO_OK; switch((CGBLCOError::EGBLCOErrorType)returnValue) { case 0: tType = CGBLCOError::EGBLCOErrorType::GBLCO_OK; break; case 1: tType = CGBLCOError::EGBLCOErrorType::GBLCO_FATAL; break; case 2: tType = CGBLCOError::EGBLCOErrorType::GBLCO_LOCAL; break; case 3: tType = CGBLCOError::EGBLCOErrorType::GBLCO_LOCAL; break; } TGBLError::SetTGBLError(parameterOutError,tType,returnValue.GetCode(),(CKSTRING)returnValue.GetDescription()); beh->ActivateOutput(BEH_PIN_OUT_INDEX_ERROR, true); } return CKBR_OK; }
int GeneralCameraOrbit(const CKBehaviorContext& behcontext,INPUTPROCESSFUNCTION InputFunction) { // Get the behavior CKBehavior* beh = behcontext.Behavior; float delta = behcontext.DeltaTime; // Current state of the behavior CKBOOL stopping; // Indicates the behavior we are stopping if returns, stop otherwise CKBOOL Returns = TRUE; beh->GetLocalParameterValue(LOCAL_RETURN,&Returns); // Stop Entrance, we stop if (beh->IsInputActive(1)) { // Set IO State beh->ActivateInput(1,FALSE); // A protection in case we stop the behavior before having started it VxVector InitialAngles; beh->GetLocalParameterValue(LOCAL_INIT,&InitialAngles); // Get current position VxVector RotationAngles; beh->GetLocalParameterValue(LOCAL_ROT,&RotationAngles); // Stopping Now stopping = TRUE; beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); if ( !Returns || ((RotationAngles.x == 0) && (RotationAngles.y == 0)) ) { beh->ActivateOutput(1,TRUE); return CKBR_OK; } } // Gets the current camera CKCamera *Camera = (CKCamera *) beh->GetTarget(); if( !Camera ) return CKBR_OWNERERROR; // Gets the target informations VxVector TargetPosition; beh->GetInputParameterValue(IN_TARGET_POS,&TargetPosition); CK3dEntity* TargetRef = (CK3dEntity*)beh->GetInputParameterObject(IN_TARGET_REF); ////////////////////////////////////////////// // Gets the input parameters of the behavior ////////////////////////////////////////////// VxVector InitialAngles(0,0,0), RotationAngles(0,0,0); // First entrance, sets the initial values here only if (beh->IsInputActive(0)) { // Sets IO State beh->ActivateInput(0,FALSE); beh->ActivateOutput(0,TRUE); // Not Stopping stopping = FALSE; beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); // Compute the Initial Angles, the radius VxVector InitialPosition; Camera->GetPosition(&InitialPosition, TargetRef); InitialPosition -= TargetPosition; InitialAngles.z = Magnitude(InitialPosition); if ( InitialAngles.z == 0.0f ) { InitialAngles.x = 0.0f; InitialAngles.y = 0.0f; } else { // Vertical Polar Angle float d; InitialPosition.Normalize(); d = DotProduct(InitialPosition,VxVector::axisY()); // bound the value of d to avoid errors due to precision. if (d < -1) d = -1; else if (d > 1) d = 1; InitialAngles.y = acosf(d); // Horizontal Polar Angle InitialPosition.y = 0; if ( (InitialPosition.x == 0.0f) && (InitialPosition.y == 0.0f) && (InitialPosition.z == 0.0f) ) InitialAngles.x = PI/2; else { InitialPosition.Normalize(); d = DotProduct(InitialPosition,VxVector::axisX()); // bound the value of d to avoid eroors due to precision. if (d < -1) d = -1; else if (d > 1) d = 1; InitialAngles.x = acosf(d); d = DotProduct(InitialPosition,VxVector::axisZ()); if (d < 0) InitialAngles.x *= -1; } // In case the camera has the head down, we need to inverse the commands when we go // Up otherwise, the user will have the feeling to turn on the wrong direction. VxVector CamUp; Camera->GetOrientation(NULL,&CamUp,NULL,NULL); if ( CamUp.y < 0 ) { InitialAngles.x += PI; InitialAngles.y *= -1; InitialAngles.x = (float)fmod(InitialAngles.x,2*PI); } } // Reset stopping stopping = FALSE; // Sets the values in memory beh->SetLocalParameterValue(LOCAL_INIT,&InitialAngles); beh->SetLocalParameterValue(LOCAL_ROT,&RotationAngles); beh->SetLocalParameterValue(LOCAL_STOPPING,&stopping); // Only initialization on "On" entrance return CKBR_ACTIVATENEXTFRAME; } // Auto-activation of the behavior beh->GetLocalParameterValue(LOCAL_INIT,&InitialAngles); beh->GetLocalParameterValue(LOCAL_ROT,&RotationAngles); beh->GetLocalParameterValue(LOCAL_STOPPING,&stopping); // Get the input manager CKInputManager *input = (CKInputManager*)behcontext.Context->GetManagerByGuid(INPUT_MANAGER_GUID); // Call the input processing function InputFunction (&RotationAngles,beh,input,delta,Returns,stopping); // Do nothing when initial angle were not initialized. // Simply stop the BB. No output activated. if ( (InitialAngles.x == INF) || (RotationAngles.x == INF) ) return CKBR_OK; // When we are exactly on the top or the bottom of the target, +/-90°, // The LookAt BB won't rotate the camera when we turn right or left as // it already looks at the target. Therefore, when we are at +/-90°, we // add or remove a little something. if ( (RotationAngles.y==PI/2) || (RotationAngles.y == -PI/2) ) { // Get Min, Max // If equals, nothing to change, it is the given value. float MinH = -PI/2; float MaxH = PI/2; beh->GetInputParameterValue(IN_MIN_H, &MinH); beh->GetInputParameterValue(IN_MAX_H, &MaxH); if ( MaxH - MinH > 2 * STEP ) { float sign = (RotationAngles.y > 0) ? 1.0f : -1.0f; if ( MaxH >= sign * PI/2 + STEP ) RotationAngles.y += STEP; else RotationAngles.y -= STEP; } } // We memorize the new state with modulos RotationAngles.x = (float)fmod(RotationAngles.x,2*PI); RotationAngles.y = (float)fmod(RotationAngles.y,2*PI); beh->SetLocalParameterValue(LOCAL_ROT,&RotationAngles); // Computes the coordinates of the camera in the target referential thanks to the // current polar angles and radius informations. And moves the camera VxVector Position; Position = InitialAngles + RotationAngles; Position = Position.z * (cosf(Position.x) * sinf(Position.y) * VxVector::axisX() + sinf(Position.x) * sinf(Position.y) * VxVector::axisZ() + cosf(Position.y) * VxVector::axisY()); Position += TargetPosition; Camera->SetPosition(&Position, TargetRef, FALSE); // Does the camera has a Target ? CK3dEntity *CameraTarget; CKBOOL CameraHasTarget = CKIsChildClassOf(Camera,CKCID_TARGETCAMERA) && (CameraTarget=((CKTargetCamera*)Camera)->GetTarget()); // Orients the Camera. The LookAt implies that when the camera reach // the 90°, it may be flipped and suddently have the head up and down. // Therefore we use the target for target cameras as we have to use the // target. But for free cameras, we do our own look at using our rotation // angle to avoid this problem. if (CameraHasTarget) CameraTarget->SetPosition(&TargetPosition, TargetRef, TRUE); else { // New direction VxVector Dir; Dir = TargetPosition - Position; // Temp Right Value VxMatrix mat; VxVector R(0,0,-1); // Up for (0,0) angle Vx3DMatrixFromRotationAndOrigin(mat,VxVector::axisY(),VxVector(0,0,0),InitialAngles.x + RotationAngles.x); R.Rotate(mat); // Get Up VxVector Up; Up = CrossProduct(R,Dir); Camera->SetOrientation(&Dir,&Up,NULL,TargetRef); //Camera->LookAt(&TargetPosition,TargetRef); } // Stop is finished, reset values. if ( stopping && ((RotationAngles.x == 0) && (RotationAngles.y == 0)) ) { beh->ActivateOutput(1,TRUE); return CKBR_OK; } else // Come back next frame return CKBR_ACTIVATENEXTFRAME; }
//************************************ // Method: PJRevolute // FullName: PJRevolute // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PJRevolute(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(bI_ObjectB); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_Revolute)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA && ! worldB ) { return 0; } if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); //anchor : VxVector anchor = GetInputParameterValue<VxVector>(beh,bI_Anchor); VxVector anchorOut = anchor; CK3dEntity*anchorReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AnchorRef); if (anchorReference) { anchorReference->Transform(&anchorOut,&anchor); } //swing axis VxVector Axis = GetInputParameterValue<VxVector>(beh,bI_Axis); VxVector axisOut = Axis; CK3dEntity*axisReference = (CK3dEntity *) beh->GetInputParameterObject(bI_AxisRef); if (axisReference) { VxVector dir,up,right; axisReference->GetOrientation(&dir,&up,&right); axisReference->TransformVector(&axisOut,&up); } ////////////////////////////////////////////////////////////////////////// //limit high : pJointLimit limitH; pJointLimit limitL; DWORD limit; beh->GetLocalParameterValue(1,&limit); if (limit) { CKParameterIn *par = beh->GetInputParameter(bbI_HighLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { limitH = pFactory::Instance()->createLimitFromParameter(rPar); } } } if (limit) { CKParameterIn *par = beh->GetInputParameter(bbI_LowLimit); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { limitL = pFactory::Instance()->createLimitFromParameter(rPar); } } } ////////////////////////////////////////////////////////////////////////// DWORD spring; pSpring sSpring; beh->GetLocalParameterValue(0,&spring); if (spring) { CKParameterIn *par = beh->GetInputParameter(bbI_Spring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { sSpring = pFactory::Instance()->createSpringFromParameter(rPar); } } } pMotor motor; DWORD hasMotor; beh->GetLocalParameterValue(2,&hasMotor); if (hasMotor) { CKParameterIn *par = beh->GetInputParameter(bbI_Motor); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { motor = pFactory::Instance()->createMotorFromParameter(rPar); } } } int col = GetInputParameterValue<int>(beh,bbI_Collision); ProjectionMode mode =GetInputParameterValue<ProjectionMode>(beh,bbI_PMode); float distance = GetInputParameterValue<float>(beh,bbI_PDistance); float angle= GetInputParameterValue<float>(beh,bbI_PAngle); ////////////////////////////////////////////////////////////////////////// // pJointRevolute *joint = static_cast<pJointRevolute*>(worldA->getJoint(target,targetB,JT_Revolute)); if(bodyA || bodyB) { ////////////////////////////////////////////////////////////////////////// //joint create ? if (!joint) { joint = static_cast<pJointRevolute*>(pFactory::Instance()->createRevoluteJoint(target,targetB,anchorOut,axisOut)); } ////////////////////////////////////////////////////////////////////////// Modification : if (joint) { joint->setGlobalAxis(axisOut); joint->setGlobalAnchor(anchorOut); if (mode!=0) { joint->setProjectionMode(mode); joint->setProjectionDistance(distance); joint->setProjectionAngle(angle); } ////////////////////////////////////////////////////////////////////////// if(limit) { joint->setHighLimit(limitH); joint->setLowLimit(limitL); } ////////////////////////////////////////////////////////////////////////// if (spring) { joint->setSpring(sSpring); } if (hasMotor) { joint->setMotor(motor); } joint->enableCollision(col); } } beh->ActivateOutput(0); } return 0; }
//************************************ // Method: JD6SetParameters // FullName: JD6SetParameters // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int JD6SetParameters(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object A: CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); CK3dEntity *targetB = (CK3dEntity *) beh->GetInputParameterObject(0); if (!pFactory::Instance()->jointCheckPreRequisites(target,targetB,JT_D6)) { return CK_OK; } // the world : pWorld *worldA=GetPMan()->getWorldByBody(target); pWorld *worldB=GetPMan()->getWorldByBody(targetB); if (!worldA) { worldA = worldB; } if (!worldA) { beh->ActivateOutput(0); return 0; } // the physic object A : pRigidBody*bodyA= worldA->getBody(target); pRigidBody*bodyB= worldA->getBody(targetB); if(bodyA || bodyB) { pJointD6 *joint =static_cast<pJointD6*>(worldA->getJoint(target,targetB,JT_D6)); VxVector linVel = GetInputParameterValue<VxVector>(beh,1); VxVector aVel = GetInputParameterValue<VxVector>(beh,2); VxVector pos = GetInputParameterValue<VxVector>(beh,3); VxQuaternion rot = GetInputParameterValue<VxQuaternion>(beh,4); float ratio = GetInputParameterValue<float>(beh,5); joint->setDriveLinearVelocity(linVel); joint->setDriveAngularVelocity(aVel); joint->setRatio(ratio); joint->setDrivePosition(pos); joint->setDriveRotation(rot); } beh->ActivateOutput(0); } return 0; }
/* ******************************************************************* * Function: int CISIteratorBB( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Parameters : * behaviourContext r Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int CISIteratorBB(const CKBehaviorContext& behcontext) { /************************************************************************/ /* collecting data : */ /* */ CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; CGBLCIConfigurationController* cman=(CGBLCIConfigurationController*)ctx->GetManagerByGuid(CONFIGURATION_MAN_GUID); /*get the last index */ int index = 0; beh->GetLocalParameterValue(BEH_LOCAL_PAR_INDEX_INDEX, &index); BOOL getFromDB = false; beh->GetLocalParameterValue(BEH_LOCAL_PAR_INDEX_DB_MODE,&getFromDB); using namespace GBLCommon::BehaviorTools; using namespace GBLCommon::ParameterTools; using namespace Customisation::typedefs; /************************************************************************/ /* behavior trigger event processing : */ /* */ /* */ /* Reset/On : sets the index to zero and save it */ if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); if (getFromDB) { CKDataArray * resultArray = NULL; beh->GetLocalParameterValue(BEH_LOCAL_PAR_INDEX_CIID_LIST,&resultArray); if (resultArray) { resultArray->Clear(); while ( resultArray->GetColumnCount() ) resultArray->RemoveColumn(0); } else { resultArray = static_cast<CKDataArray*>(ctx->CreateObject( CKCID_DATAARRAY, "IGBLSMConfigurationAccess::CIS_IDLIST", CK_OBJECTCREATION_DYNAMIC )); } ctx->GetCurrentLevel()->AddObject( resultArray ); ////////////////////////////////////////////////////////////////////////// retrieve list of CI ID's : CGBLSMStorageManager *storageManager = static_cast<CGBLSMStorageManager *>(ctx->GetManagerByGuid(GBLSMStorageManagerGUID)); IGBLSMConfigurationAccess* smCIS = storageManager->GetConfigurationInterface(); int idCIS = GetInputParameterValue<int>(beh,BEH_IN_PAR_CIS_ID); smCIS->RetrieveCIList(resultArray,CGBLCISID(idCIS)); beh->SetLocalParameterValue(BEH_LOCAL_PAR_INDEX_CIID_LIST,&resultArray,sizeof(CKDataArray*)); int cis_size = resultArray->GetRowCount(); beh->SetLocalParameterValue(BEH_LOCAL_PAR_INDEX_CIS_SIZE,&cis_size); }else { Customisation::typedefs::CIS* currentCIS = cman->GetCIS(); if(!currentCIS) Logger::ShowDebugMessage(ctx,Logger::ELOGERROR,"CISIterator : couldn't find CIS"); } //reset counter : index = 0 ; beh->SetLocalParameterValue(BEH_LOCAL_PAR_INDEX_INDEX,&index); beh->ActivateInput(1,TRUE); } //get LA_ID : int cisSize; beh->GetLocalParameterValue(BEH_LOCAL_PAR_INDEX_CIS_SIZE,&cisSize); /* bounding check for the index: if out of range, set to zero and save it.*/ if(index > cisSize -1 ) { index = 0; beh->SetLocalParameterValue(BEH_LOCAL_PAR_INDEX_INDEX,&index); beh->ActivateOutput(0); return CKBR_OK; } /* Loop In : */ if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); CGBLCI *currentCI = NULL; //ctx->OutputToConsole("asfasdf"); if (getFromDB) { CKDataArray * resultArray = NULL; beh->GetLocalParameterValue(BEH_LOCAL_PAR_INDEX_CIID_LIST,&resultArray); if (resultArray) { CGBLSMStorageManager *storageManager = static_cast<CGBLSMStorageManager *>(ctx->GetManagerByGuid(GBLSMStorageManagerGUID)); IGBLSMConfigurationAccess* smCIS = storageManager->GetConfigurationInterface(); CGBLCIConfigurationController* cman=static_cast<CGBLCIConfigurationController*>(ctx->GetManagerByGuid(CONFIGURATION_MAN_GUID)); IGBLCIAccessInterface * accessInterface = cman->GetCISAccessInterface(); currentCI = new CGBLCI("temp",CKPGUID_INT); int idCI; resultArray->GetElementValue(index,0,&idCI); accessInterface->GetCI(currentCI,idCI); beh->SetOutputParameterValue(BEH_OUT_PAR_INDEX_DB_INDEX,&idCI); }else { ctx->OutputToConsole("wrong array"); } }else { Customisation::typedefs::CISIterator it = cman->GetCIS()->GetIteratorByIndex(index); currentCI = (CGBLCI *)*it; } if (currentCI) { //output name : CKParameterOut *outName = beh->GetOutputParameter(BEH_OUT_PAR_INDEX_UNAME); outName->SetStringValue(currentCI->name.Str()); //output description: CKParameterOut *outDescr = beh->GetOutputParameter(BEH_OUT_PAR_INDEX_DESCRIPTION); outDescr->SetStringValue(currentCI->description.Str()); //output type int type = ctx->GetParameterManager()->ParameterGuidToType(currentCI->type); beh->SetOutputParameterValue(BEH_OUT_PAR_INDEX_TYPE,&type); //output value: CKParameterOut *outStrValue = beh->GetOutputParameter(BEH_OUT_PAR_INDEX_VALUE); outStrValue->SetStringValue(GetParameterAsString(currentCI->realValue)); //output default value: CKParameterOut *outDefaultStrValue = beh->GetOutputParameter(BEH_OUT_PAR_INDEX_DEFAULTVALUE); outDefaultStrValue->SetStringValue(GetParameterAsString(currentCI->defaultValue)); //output flags : beh->SetOutputParameterValue(BEH_OUT_PAR_INDEX_FLAGS,¤tCI->flags); }else { Logger::ShowDebugMessage(ctx,Logger::ELOGERROR,"CISIterator : couldn't find CI Parameter"); } //increase counter : index++; beh->SetLocalParameterValue(BEH_LOCAL_PAR_INDEX_INDEX,&index); beh->ActivateOutput(1); } return CKBR_OK; }
//************************************ // Method: PVWSet // FullName: PVWSet // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PVWSet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbErrorME("No Reference Object specified"); pWheel *wheel = body->getWheel(target); if (!wheel)bbErrorME("pWheel object doesnt exist!"); pWheel2 *wheel2 = wheel->castWheel2(); if (!wheel2)bbErrorME("Couldnt cast a pWheel2 object"); BB_DECLARE_PIMAP; /************************************************************************/ /* engel kuehne un partner */ /************************************************************************/ /************************************************************************/ /* retrieve settings state */ /************************************************************************/ BBSParameter(bbI_XML); BBSParameter(bbI_AxleSpeed); BBSParameter(bbI_Steer); BBSParameter(bbI_MotorTorque); BBSParameter(bbI_BrakeTorque); BBSParameter(bbI_SuspensionSpring); BBSParameter(bbI_SuspensionTravel); BBSParameter(bbI_Radius); BBSParameter(bbI_WFlags); BBSParameter(bbI_WSFlags); BBSParameter(bbI_LatFunc); BBSParameter(bbI_LongFunc); /************************************************************************/ /* retrieve values */ /************************************************************************/ int xmlValue = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_XML)); float axleVel = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_AxleSpeed)); float steer = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_Steer)); float mTorque = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_MotorTorque)); float bTorque = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_BrakeTorque)); float suspensionTravel = GetInputParameterValue<float>(beh,BB_IP_INDEX(bbI_SuspensionTravel)); int wFlags = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_WFlags)); int wSFlags = GetInputParameterValue<int>(beh,BB_IP_INDEX(bbI_WSFlags)); pSpring sSpring; if (sbbI_SuspensionSpring) { CKParameterIn *par = beh->GetInputParameter(bbI_SuspensionSpring); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { sSpring = pFactory::Instance()->createSpringFromParameter(rPar); NxSpringDesc xsp; xsp.damper = sSpring.damper; xsp.spring = sSpring.spring; xsp.targetValue = sSpring.targetValue; if (xsp.isValid()) { wheel2->setSuspensionSpring(sSpring); }else bbErrorME("Invalid Spring Setings!"); } } } /************************************************************************/ /* Update Object ! */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// // load some settings from XML if(sbbI_XML) { } if (sbbI_Steer)wheel2->setAngle(steer); if (sbbI_AxleSpeed)wheel2->setAxleSpeed(axleVel); if (sbbI_MotorTorque)wheel2->setMotorTorque(mTorque); if (sbbI_BrakeTorque)wheel2->setBreakTorque(bTorque); if (sbbI_SuspensionSpring)wheel2->setSuspensionSpring(sSpring); if (sbbI_SuspensionTravel)wheel2->setSuspensionTravel(suspensionTravel); if (sbbI_WFlags) { ////////////////////////////////////////////////////////////////////////// // // wheel2->setFlags(wFlags); } if (sbbI_WSFlags) { wheel2->getWheelShape()->setWheelFlags(wSFlags); } if (sbbI_LatFunc) { CKParameterIn *par = beh->GetInputParameter(BB_IP_INDEX(bbI_LatFunc)); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { pTireFunction func = pFactory::Instance()->createTireFuncFromParameter(rPar); if (func.isValid()) { NxTireFunctionDesc xFn; xFn.asymptoteSlip = func.asymptoteSlip; xFn.asymptoteValue = func.asymptoteValue; xFn.extremumSlip= func.extremumSlip; xFn.extremumValue= func.extremumValue; xFn.stiffnessFactor= func.stiffnessFactor; wheel2->getWheelShape()->setLongitudalTireForceFunction(xFn); }else bbErrorME("Invalid Tire Function Settings!"); } } } if (sbbI_LongFunc) { CKParameterIn *par = beh->GetInputParameter(BB_IP_INDEX(bbI_LongFunc)); if (par) { CKParameter *rPar = par->GetRealSource(); if (rPar) { pTireFunction func = pFactory::Instance()->createTireFuncFromParameter(rPar); if (func.isValid()) { NxTireFunctionDesc xFn; xFn.asymptoteSlip = func.asymptoteSlip; xFn.asymptoteValue = func.asymptoteValue; xFn.extremumSlip= func.extremumSlip; xFn.extremumValue= func.extremumValue; xFn.stiffnessFactor= func.stiffnessFactor; wheel2->getWheelShape()->setLongitudalTireForceFunction(xFn); }else bbErrorME("Invalid Tire Function Settings!"); } } } } beh->ActivateOutput(0); return 0; }
//************************************ // Method: vt_GetInVal // FullName: vt_GetInVal // Access: public static // Returns: PyObject * // Qualifier: // Parameter: PyObject * self // Parameter: PyObject * args //************************************ static PyObject *vt_GetInVal( PyObject * self, PyObject * args ) { int size = PyTuple_Size(args); int bid, index; PyArg_ParseTuple(args, "ii", &bid, &index); CK_ID cid = bid; CKBehavior *beh = static_cast<CKBehavior*>(pym->m_Context->GetObject(cid)); if (size!=2) { pym->m_Context->OutputToConsole("PyError : This function needs 2 arguments : \n\t bid,index"); Py_RETURN_NONE; } using namespace vtTools; using namespace vtTools::Enums; CKParameterManager *pam = static_cast<CKParameterManager *>(pym->m_Context->GetParameterManager()); if (index < beh->GetInputParameterCount() ) { CKParameterIn *ciIn = beh->GetInputParameter(index); CKParameterType pType = ciIn->GetType(); vtTools::Enums::SuperType sType = ParameterTools::GetVirtoolsSuperType(pym->m_Context,pam->ParameterTypeToGuid(pType)); PyObject *val; switch (sType) { case vtSTRING: { val = PyString_FromString( vtTools::BehaviorTools::GetInputParameterValue<CKSTRING>(beh,index )); break; } case vtFLOAT: { val = PyFloat_FromDouble(static_cast<float>(vtTools::BehaviorTools::GetInputParameterValue<float>(beh,index ))); break; } case vtINTEGER: { val = PyInt_FromLong( static_cast<long>(vtTools::BehaviorTools::GetInputParameterValue<int>(beh,index ))); break; } default : XString err("wrong input parameter type: "); err << ciIn->GetName() << "Only Types derivated from Interger,Float or String are acceptable"; pym->m_Context->OutputToConsole(err.Str(),FALSE ); Py_RETURN_NONE; } if (!val) { Py_DECREF(val); } return val; } Py_RETURN_NONE; }
//************************************ // Method: PWOverlapSphere // FullName: PWOverlapSphere // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PWOverlapSphere(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) return CKBR_OWNERERROR; ////////////////////////////////////////////////////////////////////////// // the world : pWorld *world=GetPMan()->getWorld(target->GetID()); if (!world) { beh->ActivateOutput(bbOT_No); return 0; } NxScene *scene = world->getScene(); if (!scene) { beh->ActivateOutput(bbOT_No); return 0; } if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); if (carray) { //carray->clear(); carray->Clear(); }else { CK_OBJECTCREATION_OPTIONS creaoptions = (CK_OBJECTCREATION_OPTIONS)(CK_OBJECTCREATION_NONAMECHECK|CK_OBJECTCREATION_DYNAMIC); carray = (CKGroup*)ctx()->CreateObject(CKCID_GROUP,"asdasd",creaoptions); } beh->SetLocalParameterObject(0,carray); int hitIndex = 0; beh->SetLocalParameterValue(bbS_Index,&hitIndex); int hitSize = 0; beh->SetLocalParameterValue(bbS_Size,&hitSize); ////////////////////////////////////////////////////////////////////////// int types = GetInputParameterValue<int>(beh,bbI_ShapesType); int accurate = GetInputParameterValue<int>(beh,bbI_Accurate); DWORD groupsEnabled; DWORD groups = 0xffffffff; beh->GetLocalParameterValue(bbS_Groups,&groupsEnabled); if (groupsEnabled) { groups = GetInputParameterValue<int>(beh,bbI_Groups); } pGroupsMask *gmask = NULL; DWORD mask; beh->GetLocalParameterValue(bbS_Mask,&mask); if (mask) { CKParameter *maskP = beh->GetInputParameter(bbI_Mask)->GetRealSource(); gmask->bits0 = GetValueFromParameterStruct<int>(maskP,0); gmask->bits1 = GetValueFromParameterStruct<int>(maskP,1); gmask->bits2 = GetValueFromParameterStruct<int>(maskP,2); gmask->bits3 = GetValueFromParameterStruct<int>(maskP,3); } float radius = GetInputParameterValue<float>(beh,bbI_Radius); VxVector center = GetInputParameterValue<VxVector>(beh,bbI_Center); VxSphere sphere(center,radius); CK3dEntity *shape = (CK3dEntity*)beh->GetInputParameterObject(bbI_Ref); int nbShapes = world->overlapSphereShapes(sphere,shape,(pShapesType)types,carray,groups,gmask,accurate); if (nbShapes) { beh->ActivateOutput(bbOT_Yes); beh->ActivateInput(1,TRUE); }else{ beh->ActivateOutput(bbOT_No); } } if( beh->IsInputActive(1) ) { beh->ActivateInput(1,FALSE); CKGroup *carray = (CKGroup*)beh->GetLocalParameterObject(bbS_Result); ////////////////////////////////////////////////////////////////////////// if (carray) { if (carray->GetObjectCount()) { CKBeObject *hit = carray->GetObject(carray->GetObjectCount()-1); if (hit) { beh->SetOutputParameterObject(0,hit); carray->RemoveObject(hit); if (carray->GetObjectCount()) { beh->ActivateOutput(bbOT_Next); }else { beh->ActivateOutput(bbOT_Finish); CKDestroyObject(carray); } } }else{ beh->ActivateOutput(bbOT_Finish); CKDestroyObject(carray); } }else { beh->ActivateOutput(bbOT_Finish); CKDestroyObject(carray); } } return 0; }
int LogEntry(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; CKParameterManager *pam = static_cast<CKParameterManager *>(ctx->GetParameterManager()); XString File((CKSTRING) beh->GetInputParameterReadDataPtr(0)); if (GetPMan()->GetLastLogEntry().Length()) { CKParameterOut *pout = beh->GetOutputParameter(0); pout->SetStringValue(GetPMan()->GetLastLogEntry().Str()); GetPMan()->SetLastLogEntry(""); vtTools::BehaviorTools::SetOutputParameterValue<int>(beh,1,xLogger::GetInstance()->lastTyp); int descriptionS = xLogger::GetInstance()->getItemDescriptions().size(); int compo = xLogger::GetInstance()->lastComponent; XString compoStr; /*if(compo<= xLogger::GetInstance()->getItemDescriptions().size() ) compoStr.Format("%s",xLogger::GetInstance()->getItemDescriptions().at(compo));*/ beh->ActivateOutput(0,TRUE); switch (xLogger::GetInstance()->lastTyp) { case ELOGERROR: beh->ActivateOutput(1,TRUE); case ELOGWARNING: beh->ActivateOutput(2,TRUE); case ELOGINFO: beh->ActivateOutput(3,TRUE); case ELOGTRACE: beh->ActivateOutput(4,TRUE); case ELOGDEBUG: beh->ActivateOutput(5,TRUE); default: beh->ActivateOutput(0,TRUE); } } // Steering if( beh->IsInputActive(1) ) { beh->ActivateOutput(0,FALSE); return 1; } return CKBR_ACTIVATENEXTFRAME; }
/* ******************************************************************* * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Parameters : * behaviourContext r Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int CGBLCHPopulateAvailableRecipients::BehaviourFunction( const CKBehaviorContext& behaviorContext ) { enum { GETACTIVEPLAYERSARRAY_COLUMN_VIRTOOLSUSERID, GETACTIVEPLAYERSARRAY_COLUMN_USERNAME, GETACTIVEPLAYERSARRAY_COLUMN_GBLTEAMID }; enum { AVAILABLERECIPIENTSARRAY_COLUMN_USERNAME, AVAILABLERECIPIENTSARRAY_COLUMN_VIRTOOLSUSERID, AVAILABLERECIPIENTSARRAY_COLUMN_GBLTEAMID }; CKBehavior *beh = behaviorContext.Behavior; CGBLCOError localError(CGBLCOError::EGBLCOErrorType::GBLCO_OK); if (!beh) { assert(NULL); return CKBR_BEHAVIORERROR; } // Get profile controller CGBLProfileManager* profileManager = static_cast<CGBLProfileManager*>(beh->GetCKContext()->GetManagerByGuid(GBLProfileManagerGUID)); if (!profileManager) { assert(NULL); return CKBR_BEHAVIORERROR; } // Get GBL Loader manager GBLLDManager* loaderManager = static_cast<GBLLDManager*>(beh->GetCKContext()->GetManagerByGuid(GBLLDManagerGUID)); if (!profileManager) { assert(NULL); return CKBR_BEHAVIORERROR; } // Check we have been passed an array CKDataArray* availableRecipientsArray = static_cast<CKDataArray*>(beh->GetInputParameterObject(eParamInputAvailableRecipientsArray)); if (!availableRecipientsArray) { return CKBR_BEHAVIORERROR; } // Clear array and set up structure availableRecipientsArray->Clear(); while (availableRecipientsArray->GetColumnCount()) availableRecipientsArray->RemoveColumn(0); availableRecipientsArray->InsertColumn(-1, CKARRAYTYPE_STRING, "Name"); availableRecipientsArray->InsertColumn(-1, CKARRAYTYPE_INT, "VirtoolsUserID"); availableRecipientsArray->InsertColumn(-1, CKARRAYTYPE_PARAMETER, "GBLTeamID", GUID_TEAM_ID); // Create a temporary array of active players to be filled in by the Profile Controller CKDataArray* tmpActivePlayersArray = (CKDataArray*)beh->GetCKContext()->CreateObject(CKCID_DATAARRAY, "CGBLCHPopulateAvailableRecipients temp array", CK_OBJECTCREATION_DYNAMIC); if (!tmpActivePlayersArray) { assert(NULL); return CKBR_BEHAVIORERROR; } // Create temporary array for team names to be filled in by the Profile Controller CKDataArray* tmpTeamNameArray = (CKDataArray*)beh->GetCKContext()->CreateObject(CKCID_DATAARRAY, "CGBLCHPopulateAvailableRecipients temp array 2", CK_OBJECTCREATION_DYNAMIC); if (!tmpTeamNameArray) { assert(NULL); return CKBR_BEHAVIORERROR; } // Get active players localError = profileManager->GetActivePlayers(tmpActivePlayersArray); if (localError != CGBLCOError::EGBLCOErrorType::GBLCO_OK) { localError.SetCode(GBLCH_ERRORCODE_UNABLETOGETPROFILEINFORMATION); localError.SetDescription((XString)"An error occurred while attempting to retrieve profile information: " + (const char*)localError); } else { // Collate Team IDs into local array CGBLTeamID teamID; XArray<CGBLTeamID> arrayOfTeamIDs; XArray<XString> arrayOfTeamNames; char* stringBuffer = NULL; for (int row = 0;row < tmpActivePlayersArray->GetRowCount();row++) { // Get Team ID teamID = 0; if (tmpActivePlayersArray->GetElementValue(row, GETACTIVEPLAYERSARRAY_COLUMN_GBLTEAMID, &teamID)) { if ((int)teamID) { // Have we already got this team ID in the array? if (arrayOfTeamIDs.End() == arrayOfTeamIDs.Find(teamID)) { // No, add it to the array arrayOfTeamIDs.PushBack(teamID); } } } } // Copy team IDs and names into AvailableRecipients array for (int team = 0;team < arrayOfTeamIDs.Size();team++) { availableRecipientsArray->AddRow(); int row = availableRecipientsArray->GetRowCount() - 1; assert(row == team); // Get team name teamID = arrayOfTeamIDs[team]; localError = profileManager->GetProfileField((const)teamID, "Name", tmpTeamNameArray); if (localError != CGBLCOError::EGBLCOErrorType::GBLCO_OK) { localError.SetCode(GBLCH_ERRORCODE_UNABLETOGETPROFILEINFORMATION); localError.SetDescription((XString)"An error occurred while attempting to retrieve profile information: " + (const char*)localError); break; } // Place team name into destination array stringBuffer = new char[tmpTeamNameArray->GetElementStringValue(0, 0, NULL) + 1]; tmpTeamNameArray->GetElementStringValue(0, 0, stringBuffer); availableRecipientsArray->SetElementStringValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_USERNAME, stringBuffer); delete stringBuffer; stringBuffer = NULL; // Set user ID as 0 int virtoolsUserID = 0; availableRecipientsArray->SetElementValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_VIRTOOLSUSERID, &virtoolsUserID); // Set team ID availableRecipientsArray->SetElementValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_GBLTEAMID, &arrayOfTeamIDs[team]); } } if (localError == CGBLCOError::EGBLCOErrorType::GBLCO_OK) { CGBLTeamID teamID; char* stringBuffer = NULL; int virtoolsUserID; // Now copy players (which includes facilitators) into the destination array for (int row = 0;row < tmpActivePlayersArray->GetRowCount();row++) { // Get User ID virtoolsUserID = 0; if (tmpActivePlayersArray->GetElementValue(row, GETACTIVEPLAYERSARRAY_COLUMN_VIRTOOLSUSERID, &virtoolsUserID)) { // Check this user ID valid if (virtoolsUserID) { // Add new row to destination array availableRecipientsArray->AddRow(); int row = availableRecipientsArray->GetRowCount() - 1; // Set Virtools user ID availableRecipientsArray->SetElementValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_VIRTOOLSUSERID, &virtoolsUserID); // Get name and put into dest array stringBuffer = new char[tmpActivePlayersArray->GetElementStringValue(row, GETACTIVEPLAYERSARRAY_COLUMN_USERNAME, NULL) + 1]; tmpActivePlayersArray->GetElementStringValue(row, GETACTIVEPLAYERSARRAY_COLUMN_USERNAME, stringBuffer); availableRecipientsArray->SetElementStringValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_USERNAME, stringBuffer); delete stringBuffer; stringBuffer = NULL; // Set team ID to 0 teamID = 0; availableRecipientsArray->SetElementValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_GBLTEAMID, &teamID); } } } } if (localError == CGBLCOError::EGBLCOErrorType::GBLCO_OK) { // Remove the current user from the array // Get current Virtools User ID from GBL Loader int currentVirtoolsUserID = loaderManager->GetVirtoolsUserID(); for (int row = availableRecipientsArray->GetRowCount() - 1;row >= 0;row--) { int virtoolsUserId = 0; availableRecipientsArray->GetElementValue(row, AVAILABLERECIPIENTSARRAY_COLUMN_VIRTOOLSUSERID, &virtoolsUserId); if (virtoolsUserId == currentVirtoolsUserID) { // This row is the current user. Remove it availableRecipientsArray->RemoveRow(row); } } } // Free temporary arrays beh->GetCKContext()->DestroyObject(tmpActivePlayersArray); beh->GetCKContext()->DestroyObject(tmpTeamNameArray); // Did an error occur? if (localError == CGBLCOError::EGBLCOErrorType::GBLCO_OK) { // Output success beh->ActivateOutput(eBehOutputDone); } else { // Output the error TGBLError::SetTGBLError(beh->GetOutputParameter(eParamOutputError), localError, localError, (CKSTRING)(const char*)localError); beh->ActivateOutput(eBehOutputError); } // All done return CKBR_OK; }
/* ******************************************************************* * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Paramters : * behaviourContext r Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int CGBLCHChatMoveHomogeneous::BehaviourFunction( const CKBehaviorContext& behaviorContext ) { CKBehavior *beh = behaviorContext.Behavior; CKContext *ctx = behaviorContext.Context; CK2dEntity *chatFrame = (CK2dEntity *)beh->GetInputParameterObject(0); if (chatFrame) { float left, top, right, bottom; beh->GetInputParameterValue(3, &left); beh->GetInputParameterValue(3, &top); beh->GetInputParameterValue(2, &right); right += left; beh->GetInputParameterValue(1, &bottom); bottom += top; VxRect rect(left, top, right, bottom); chatFrame->SetHomogeneousCoordinates ( 1 ); int res = chatFrame->SetHomogeneousRect ( rect ); if (res == 0) { beh->ActivateInput (0, 0); beh->ActivateOutput (0); } else { beh->ActivateInput (0, 0); beh->ActivateOutput (1); } } else { beh->ActivateInput (0, 0); beh->ActivateOutput (1); } return CKBR_OK; }
/* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int NSUnlockObject(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; bbNoError(E_NWE_OK); //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { bbError(E_NWE_NO_CONNECTION); return 0; } if (!cin->getMyClient()) { bbError(E_NWE_INTERN); return 0; } ISession *sInterface = cin->getSessionInterface(); int connectionID = GetInputParameterValue<int>(beh,BB_IP_CONNECTION_ID); ////////////////////////////////////////////////////////////////////////// // // Check states : // xDistributedClient *myClient = cin->getMyClient(); if (!myClient) { bbError(E_NWE_INTERN); return 0; } if (!myClient->getClientFlags().test(1 << E_CF_SESSION_JOINED)) { bbError(E_NWE_NO_SESSION); return 0; } xDistributedSession *session = cin->getCurrentSession(); if (!session) { bbError(E_NWE_NO_SUCH_SESSION); return 0; } if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); if (myClient->getUserID() != session->getUserID()) { bbError(E_NWE_NOT_SESSION_MASTER); return 0; } beh->ActivateInput(0,FALSE); sInterface->unlockSession(myClient->getUserID(),session->getSessionID()); } if (session->isLocked()) { beh->ActivateOutput(BB_O_UNLOCKED); return 0; }else { beh->ActivateOutput(BB_O_WAITING); } return CKBR_ACTIVATENEXTFRAME; }
//************************************ // Method: PBPhysicalizeEx // FullName: PBPhysicalizeEx // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PBPhysicalizeEx(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; using namespace vtTools; using namespace vtTools::AttributeTools; using namespace vtTools::ParameterTools; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // objects // CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); //the object : CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); //the world reference, optional used CK3dEntity*worldRef = NULL; //the world object, only used when reference has been specified pWorld *world = NULL; //final object description pObjectDescr *oDesc = new pObjectDescr(); pRigidBody *body = NULL; XString errMesg; //---------------------------------------------------------------- // // sanity checks // // rigid body GetPMan()->getBody(target); if( body){ errMesg.Format("Object %s already registered.",target->GetName()); bbErrorME(errMesg.Str()); } //---------------------------------------------------------------- // // // if (!GetPMan()->isValid()) GetPMan()->performInitialization(); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // Collecting data. Stores all settings in a pObjectDescr. // //get the parameter array BB_DECLARE_PIMAP; //---------------------------------------------------------------- // // generic settings // oDesc->hullType = (HullType)GetInputParameterValue<int>(beh,bbI_HullType); oDesc->flags = (BodyFlags)GetInputParameterValue<int>(beh,bbI_Flags); oDesc->density = GetInputParameterValue<float>(beh,bbI_Density); //---------------------------------------------------------------- // optional // world // BBSParameterM(bbI_World,BB_SSTART); if (sbbI_World) { worldRef = (CK3dEntity *) beh->GetInputParameterObject(BB_IP_INDEX(bbI_World)); if (worldRef) { world = GetPMan()->getWorld(worldRef,target); if (!world) { xLogger::xLog(ELOGERROR,E_LI_MANAGER,"World reference has been specified but no valid world object found. Switching to default world"); goto errorFound; } } } //---------------------------------------------------------------- // optional // Pivot // BBSParameterM(bbI_Pivot,BB_SSTART); if (sbbI_Pivot) { CKParameter*pivotParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Pivot))->GetRealSource(); if (pivotParameter) { IParameter::Instance()->copyTo(oDesc->pivot,pivotParameter); oDesc->mask |= OD_Pivot; } } //---------------------------------------------------------------- // optional // mass // BBSParameterM(bbI_Mass,BB_SSTART); if (sbbI_Mass) { CKParameter*massParameter = beh->GetInputParameter(BB_IP_INDEX(bbI_Mass))->GetRealSource(); if (massParameter) { IParameter::Instance()->copyTo(oDesc->mass,massParameter); oDesc->mask |= OD_Mass; } } //---------------------------------------------------------------- // optional // collision // BBSParameterM(bbI_Collision , BB_SSTART); if (sbbI_Collision) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Collision))->GetRealSource(); if (par) { oDesc->collisionGroup = GetValueFromParameterStruct<int>(par,PS_BC_GROUP,false); CKParameterOut* maskPar = GetParameterFromStruct(par,PS_BC_GROUPSMASK); if (maskPar) { oDesc->groupsMask.bits0 = GetValueFromParameterStruct<int>(maskPar,0); oDesc->groupsMask.bits1 = GetValueFromParameterStruct<int>(maskPar,1); oDesc->groupsMask.bits2 = GetValueFromParameterStruct<int>(maskPar,2); oDesc->groupsMask.bits3 = GetValueFromParameterStruct<int>(maskPar,3); } oDesc->skinWidth = GetValueFromParameterStruct<float>(par,PS_BC_SKINWITDH,false); IParameter::Instance()->copyTo(oDesc->collision,par); oDesc->mask |= OD_Collision; } } //---------------------------------------------------------------- // optional // collision : CCD // BBSParameterM(bbI_CCD, BB_SSTART); if (sbbI_CCD) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCD))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc->ccd,par); oDesc->mask |= OD_CCD; } } //---------------------------------------------------------------- // optional // optimization // BBSParameterM(bbI_Optimization, BB_SSTART); if (sbbI_Optimization) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Optimization))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc->optimization,par); oDesc->mask |= OD_Optimization; } } //---------------------------------------------------------------- // optional // Material // BBSParameterM(bbI_Material, BB_SSTART); if (sbbI_Material) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(oDesc->material,par); oDesc->mask |= OD_Material; } } //---------------------------------------------------------------- // optional // capsule // BBSParameterM(bbI_Capsule, BB_SSTART); if (sbbI_Capsule) { if (oDesc->hullType == HT_Capsule) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_Capsule))->GetRealSource(); if (par) { IParameter::Instance()->copyTo(oDesc->capsule,par); oDesc->mask |= OD_Capsule; } }else{ errMesg.Format("You attached a capsule parameter but the hull type is not capsule"); bbWarning(errMesg.Str()); } } //---------------------------------------------------------------- // optional // convex cylinder // BBSParameterM(bbI_CCylinder, BB_SSTART); if (sbbI_CCylinder) { if (oDesc->hullType == HT_ConvexCylinder) { CKParameter*par = beh->GetInputParameter(BB_IP_INDEX(bbI_CCylinder))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(oDesc->convexCylinder,par,true); oDesc->mask |= OD_ConvexCylinder; } }else{ errMesg.Format("You attached a convex cylinder parameter but the hull type is not a convex cylinder"); bbWarning(errMesg.Str()); } } oDesc->version = pObjectDescr::E_OD_VERSION::OD_DECR_V1; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // body creation // if (!body) { if(! (oDesc->flags & BF_SubShape) ) { body = pFactory::Instance()->createRigidBody(target,*oDesc); } } if (!body) { SAFE_DELETE(oDesc); bbErrorME("No Reference Object specified"); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // attribute creation, attach settings // if (oDesc->flags & BF_AddAttributes ) { //body->saveToAttributes(oDesc); GetPMan()->copyToAttributes(*oDesc,target); } //---------------------------------------------------------------- // // update input parameters // if (sbbI_Material) { CKParameterOut *par = (CKParameterOut*)beh->GetInputParameter(BB_IP_INDEX(bbI_Material))->GetRealSource(); if (par) { pFactory::Instance()->copyTo(par,oDesc->material); } } //---------------------------------------------------------------- // // cleanup // //SAFE_DELETE(oDesc); //---------------------------------------------------------------- // // error out // errorFound: { beh->ActivateOutput(0); return CKBR_GENERICERROR; } //---------------------------------------------------------------- // // All ok // allOk: { beh->ActivateOutput(0); return CKBR_OK; } return 0; }
/* ******************************************************************* * Function: int RetrieveCICB( const CKBehaviorContext& behaviorContext ) * * Description : The Behavior Callback function is called by Virtools when various events happen * in the life of a BuildingBlock. Exactly which events trigger a call to the * Behavior Callback function is defined in the Behavior Prototype, along with the * declaration of the function pointer * * Parameters : * behaviourContext r Behavior context reference, which gives * access to frequently used global objects * ( context, level, manager, etc... ) * * Returns : int, The return value of the callback function should be one of the CK_BEHAVIOR_RETURN values. * ******************************************************************* */ CKERROR RetrieveCICB(const CKBehaviorContext& behcontext) { /************************************************************************/ /* collecting data : */ /* */ CKBehavior *beh = behcontext.Behavior; CKContext* ctx = beh->GetCKContext(); CKParameterManager *pm = static_cast<CKParameterManager*>(ctx->GetParameterManager()); /************************************************************************/ /* process virtools callbacks : */ /* */ switch(behcontext.CallbackMessage) { case CKM_BEHAVIOREDITED: case CKM_BEHAVIORSETTINGSEDITED: { assert(beh && ctx); BOOL getAsString,outputAttriubtes = false; beh->GetLocalParameterValue(BEH_SETTINGS_GET_AS_STRING,&getAsString); beh->GetLocalParameterValue(BEH_SETTINGS_GET_CUSTOM_ATTRIBUTES,&outputAttriubtes); ////////////////////////////////////////////////////////////////////////// // get ci by string if(getAsString) { CKParameterOut* ciValue = beh->GetOutputParameter(0); ciValue->SetType(pm->ParameterGuidToType(CKPGUID_STRING)); } if(outputAttriubtes) { beh->CreateOutputParameter("Default Value",CKPGUID_STRING); beh->CreateOutputParameter("Unique name",CKPGUID_STRING); beh->CreateOutputParameter("Description",CKPGUID_STRING); beh->CreateOutputParameter("Runtime flags",CIPRTFLAGSGUID); beh->CreateOutputParameter("Type",CKPGUID_PARAMETERTYPE); } int p_count = beh->GetOutputParameterCount(); while( (outputAttriubtes ? BEH_OUT_MAX_COUNT : BEH_OUT_MIN_COUNT ) < p_count ) { CKDestroyObject( beh->RemoveOutputParameter( --p_count) ); } } } return CKBR_OK; }
/* ******************************************************************* * Function: int BehaviourFunction() * * Description : Returns the number of plugins in this DLL * * Paramters : * CKBehaviorContext& r The virtools behaviour context * * Returns : One of the many virtools return values * ******************************************************************* */ int CGBLLOGetMOStatus::BehaviourFunction(const CKBehaviorContext& behContext) { CKBehavior* beh = behContext.Behavior; CKBOOL localError = false; CGBLCOError retVal(CGBLCOError::EGBLCOErrorType::GBLCO_OK); MeasuredObjectiveControllerMgr* MOMngr = static_cast<MeasuredObjectiveControllerMgr*>(behContext.Context->GetManagerByGuid(MeasuredObjectiveControllerMgrGUID)); // Check to see if we got the manager ok if (!MOMngr) { assert(NULL); return CKBR_OK; } if (beh->IsInputActive(eBehInputStart)) { // Get the details of the MO P-In CKParameterIn *pIn = beh->GetInputParameter(eParamInputMO); CKParameter *moParam = pIn->GetRealSource(); // Ensure we read the P-In ok if (!moParam) { // Report the error CKParameterOut *pOut = beh->GetOutputParameter(eParamOutputGetError); TGBLError::SetTGBLError(pOut, CGBLCOError::EGBLCOErrorType::GBLCO_LOCAL, GBLLO_ERROR_NO_PARAM_FROM_BB,GBLLO_ERROR_NO_DATA_FROM_BB_DESC); beh->ActivateOutput(eBehOutputError, TRUE); localError = true; } if (!localError) { // Get the data from the P-In CGBLMOData *moData = static_cast<CGBLMOData*>(moParam->GetAppData()); if (moData) { // Get the name from the MO and use this to get the // runtime MO from the controller XString moName = moData->GetName(); CGBLLOMeasuredObjective *mo=NULL; retVal=MOMngr->GetRunTimeMO(moName,mo); // See if the controller gave us the MO if((retVal==CGBLCOError::EGBLCOErrorType::GBLCO_OK)&&(mo)) { // Get the status of the MO bool moStatus=mo->GetMOStatus(); // return the status of the MO back to Virtools Dev beh->SetOutputParameterValue(eParamOutputGetStatus, &moStatus); } } else { // Report the fact that we couldnt create a runtime MO from the param CKParameterOut *pOut = beh->GetOutputParameter(eParamOutputGetError); TGBLError::SetTGBLError(pOut, CGBLCOError::EGBLCOErrorType::GBLCO_LOCAL, GBLLO_ERROR_NO_DATA_FROM_BB,GBLLO_ERROR_NO_DATA_FROM_BB_DESC); beh->ActivateOutput(eBehOutputError, TRUE); localError = true; } } } if (localError) { // error allready dealt with } else if (retVal!=CGBLCOError::EGBLCOErrorType::GBLCO_OK) { // Report the error back to Virtools dev CKParameterOut *pOut = beh->GetOutputParameter(eParamOutputGetError); const char* errorString = retVal; TGBLError::SetTGBLError(pOut, retVal,retVal,(CKSTRING)errorString); beh->ActivateOutput(eBehOutputError, TRUE); } else { // We are ok beh->ActivateOutput(eBehOutputDone, TRUE); } return CKBR_OK; }
/* ******************************************************************* * Function: * * Description: * * Parameters: * * Returns: * ******************************************************************* */ int NSRemoveUser(const CKBehaviorContext& behcontext) { using namespace vtTools::BehaviorTools; CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { Error(beh,"No connection at the moment",BB_OP_SESSION_ERROR,TRUE,BB_O_ERROR); return 0; } IDistributedObjects *oInterface = cin->getDistObjectInterface(); ISession *sInterface = cin->getSessionInterface(); int connectionID = GetInputParameterValue<int>(beh,BB_IP_CONNECTION_ID); int userID = GetInputParameterValue<int>(beh,BB_IP_USER_ID); ////////////////////////////////////////////////////////////////////////// // // Check states : // xDistributedClient *myClient = cin->getMyClient(); xDistributedClient *client = (xDistributedClient*)oInterface->getByUserID(userID,E_DC_BTYPE_CLIENT); xDistributedSession *session = cin->getCurrentSession(); if (!session) { Error(beh,"There doesn't exist such session",BB_OP_SESSION_ERROR,TRUE,BB_O_ERROR); xLogger::xLog(ELOGERROR,E_LI_SESSION,"There doesn't exist such session!"); XL_BB_SIGNATURE; return 0; } if (!client) { Error(beh,"There doesn't exist such client object",BB_OP_SESSION_ERROR,TRUE,BB_O_ERROR); xLogger::xLog(ELOGERROR,E_LI_SESSION,"There doesn't exist such client object :%d",userID); XL_BB_SIGNATURE; return 0; } if (!session->isClientJoined(userID)) { Error(beh,"Client not joint on this session!",BB_OP_SESSION_ERROR,TRUE,BB_O_ERROR); xLogger::xLog(ELOGERROR,E_LI_SESSION,"Client not joint on this session! %d",userID); XL_BB_SIGNATURE; return 0; } if (beh->IsInputActive(0)) { beh->ActivateInput(0,FALSE); sInterface->removeClient(client,session->getSessionID(),false); beh->ActivateOutput(0); } return 0; }
/* ******************************************************************* * Function: int BehaviourFunction( const CKBehaviorContext& behaviorContext ) * * Description : The execution function is the function that will be called * during the process loop of the behavior engine, if the behavior * is defined as using an execution function. This function is not * called if the behavior is defined as a graph. This function is the * heart of the behavior: it should compute the essence of the behavior, * in an incremental way. The minimum amount of computing should be * done at each call, to leave time for the other behaviors to run. * The function receives the delay in milliseconds that has elapsed * since the last behavioral process, and should rely on this value to * manage the amount of effect it has on its computation, if the effect * of this computation relies on time. * * Paramters : * behaviourContext r Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : int, If it is done, it should return CKBR_OK. If it returns * CKBR_ACTIVATENEXTFRAME, the behavior will again be called * during the next process loop. * ******************************************************************* */ int CGBLLAEGetLAE::BehaviourFunction( const CKBehaviorContext& behaviorContext ) { CKBehavior* beh = behaviorContext.Behavior; CKContext* ctx = behaviorContext.Context; IGBLSMProfileAccess* pin = NULL; CGBLSMStorageManager *storageManager = (CGBLSMStorageManager *)ctx->GetManagerByGuid(GBLSMStorageManagerGUID); IGBLSMLAAccess *laInterface = storageManager->GetLAInterface(); IGBLSMLAEAccess *laeInterface = storageManager->GetLAEInterface(); char *laListArrayName = "laList"; CKDataArray* laListArray; laListArray = (CKDataArray *)ctx->CreateObject(CKCID_DATAARRAY,laListArrayName, CK_OBJECTCREATION_DYNAMIC); behaviorContext.CurrentLevel->AddObject( laListArray ); laListArray->InsertColumn( -1, CKARRAYTYPE_INT, "LAID" ); char *laeArrayName = "laeidList"; CKDataArray* laeArray; laeArray = (CKDataArray *)ctx->CreateObject(CKCID_DATAARRAY,laeArrayName, CK_OBJECTCREATION_DYNAMIC); behaviorContext.CurrentLevel->AddObject( laeArray ); laeArray->InsertColumn( -1, CKARRAYTYPE_INT, "LAEID" ); char *laelaArrayName = "laelaIDList"; CKDataArray* laelaArray; laelaArray = (CKDataArray *)ctx->GetObjectByNameAndClass(laelaArrayName,CKCID_DATAARRAY,NULL); if ( !laelaArray ) { laelaArray = (CKDataArray *)ctx->CreateObject(CKCID_DATAARRAY,laelaArrayName, CK_OBJECTCREATION_DYNAMIC); behaviorContext.CurrentLevel->AddObject( laelaArray ); laelaArray->InsertColumn( -1, CKARRAYTYPE_INT, "LAEID" ); laelaArray->InsertColumn( -1, CKARRAYTYPE_STRING, "LAID" ); } else { laelaArray->Clear(); } CGBLCOError res = laInterface->RetrieveLAList(laListArray); if ( res == CGBLCOError::EGBLCOErrorType::GBLCO_OK) { int count = laListArray->GetRowCount(); for (int i=0; i < count; i++) { //get list of laes for given la and add it to results list XString xLAID; CKSTRING valueField = NULL; int labelLength = laListArray->GetElementStringValue(i, 0, NULL); valueField = new CKCHAR[labelLength]; labelLength = laListArray->GetElementStringValue(i, 0, valueField); xLAID = valueField; delete valueField; CGBLLAID laid; laid.FromString(xLAID); CGBLCOError res = laeInterface->RetrieveLAEList(laeArray,laid); if ( res == CGBLCOError::EGBLCOErrorType::GBLCO_OK) { int count = laeArray->GetRowCount(); for (int j=0; j < count; j++) { CKSTRING valueField = NULL; int labelLength = laeArray->GetElementStringValue(j, 0, NULL); valueField = new CKCHAR[labelLength]; labelLength = laeArray->GetElementStringValue(j, 0, valueField); laelaArray->AddRow(); laelaArray->SetElementStringValue(laelaArray->GetRowCount()-1, 0, valueField); laelaArray->SetElementStringValue(laelaArray->GetRowCount()-1, 1, xLAID.Str()); delete valueField; } } } beh->ActivateInput(0, FALSE); beh->SetOutputParameterObject(0, laelaArray); beh->ActivateOutput(0); } else { beh->ActivateInput(0, FALSE); CKParameterOut *parameterOutError = beh->GetOutputParameter(1); TGBLError::SetTGBLError(parameterOutError,CGBLCOError::EGBLCOErrorType::GBLCO_LOCAL,GBLLAE_ERROR_GETLISTOFLAIDS,GBLLAE_ERROR_GETLISTOFLAIDS_DESC); beh->ActivateOutput(1); } behaviorContext.CurrentLevel->RemoveObject(laListArray); ctx->DestroyObject(laListArray); behaviorContext.CurrentLevel->RemoveObject(laeArray); ctx->DestroyObject(laeArray); return CKBR_OK; }
//************************************ // Method: PVGet // FullName: PVGet // Access: public // Returns: int // Qualifier: // Parameter: const CKBehaviorContext& behcontext //************************************ int PVGet(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); using namespace vtTools::BehaviorTools; if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbErrorME("No Reference Object specified"); pRigidBody *body = NULL; body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); pVehicle *v = body->getVehicle(); if (!v) { bbSErrorME(E_PE_NoVeh); } BB_DECLARE_PMAP; /************************************************************************/ /* retrieve settings state */ /***** *******************************************************************/ BBSParameter(O_StateFlags); BBSParameter(O_Acceleration); BBSParameter(O_Steering); BBSParameter(O_MTorque); BBSParameter(O_MPH); BBSParameter(O_RPM); BBSParameter(O_MRPM); BBSParameter(O_WRPM); BBSParameter(O_Gear); /************************************************************************/ /* */ /************************************************************************/ BB_O_SET_VALUE_IF(int,O_StateFlags,v->getStateFlags()); BB_O_SET_VALUE_IF(float,O_Acceleration,v->_cAcceleration); BB_O_SET_VALUE_IF(float,O_Steering,v->_cSteering); BB_O_SET_VALUE_IF(float,O_MPH,v->getMPH()); float wRPM = v->_computeRpmFromWheels(); BB_O_SET_VALUE_IF(float,O_WRPM,wRPM); //---------------------------------------------------------------- // // output new engine values // if (v->isValidEngine()) { BB_O_SET_VALUE_IF(float,O_MTorque,v->getEngine()->GetEngineTorque()); BB_O_SET_VALUE_IF(float,O_RPM,v->getRPM()); BB_O_SET_VALUE_IF(int,O_Gear,v->getGear()); }
int MidiEvent(const CKBehaviorContext& behcontext) { CKBehavior *beh = behcontext.Behavior; if( beh->IsInputActive(1) ){ // OFF beh->ActivateInput(1, FALSE); return CKBR_OK; } CKBOOL combiWasOK = FALSE; if( beh->IsInputActive(0) ){ // ON beh->ActivateInput(0, FALSE); beh->SetLocalParameterValue(0, &combiWasOK); } else { beh->GetLocalParameterValue(0, &combiWasOK); } MidiManager *mm = (MidiManager *) behcontext.Context->GetManagerByGuid( MIDI_MANAGER_GUID ); // Channel int channel=0; beh->GetInputParameterValue(0, &channel); int note, count = beh->GetInputParameterCount(); //--- test if all input notes are activated or not for( int a=1 ; a<count ; a++ ){ beh->GetInputParameterValue(a, ¬e); if( !mm->IsNoteActive(note, channel) ) break; } if( a==count ){ // All notes are pressed if( !combiWasOK ){ beh->ActivateOutput(0); combiWasOK = TRUE; beh->SetLocalParameterValue(0, &combiWasOK); return CKBR_ACTIVATENEXTFRAME; } } else { // Not all notes are pressed if( combiWasOK ){ beh->ActivateOutput(1); combiWasOK = FALSE; beh->SetLocalParameterValue(0, &combiWasOK); return CKBR_ACTIVATENEXTFRAME; } } return CKBR_ACTIVATENEXTFRAME; }
CKERROR TextureSinusCallBackObject(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; switch(behcontext.CallbackMessage) { #ifdef macintosh case CKM_BEHAVIORLOAD: { CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); if(!mesh) return 0; int nbvert = mesh->GetModifierUVCount(); // we get the saved uv's DWORD *savedUV = (DWORD *) beh->GetLocalParameterWriteDataPtr(0); for(int i=0; i<nbvert*2; i++) { savedUV[i] = ENDIANSWAP32(savedUV[i]); } } break; #endif case CKM_BEHAVIORATTACH: { // we get the mesh vertices CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); if(!mesh) return 0; CKDWORD Stride; VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride); int nbvert = mesh->GetModifierUVCount(); VxUV *savedUV; savedUV = new VxUV[nbvert]; for(int i=0 ; i<nbvert ; i++, uvarray = (VxUV*)((BYTE*)uvarray + Stride) ) { savedUV[i] = *uvarray; } beh->SetLocalParameterValue(0, savedUV, nbvert * sizeof(VxUV) ); delete[] savedUV; } break; case CKM_BEHAVIORDETACH: { // we get the mesh vertices if(!beh) return 0; CKMesh *mesh = (CKMesh*) beh->GetInputParameterObject(4); if(!mesh) return 0; CKDWORD Stride; VxUV *uvarray = (VxUV*) mesh->GetModifierUVs(&Stride); int nbvert = mesh->GetModifierUVCount(); VxUV *savePos = (VxUV*) beh->GetLocalParameterWriteDataPtr(0); if(!savePos) return 0; for(int i=0 ; i<nbvert ; i++, uvarray = (VxUV*)((BYTE*)uvarray + Stride) ) { *uvarray = savePos[i]; } mesh->ModifierUVMove(); } } return CKBR_OK; }
int PVSetMotorValues(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; PhysicManager *pm = GetPMan(); pFactory *pf = pFactory::Instance(); if( beh->IsInputActive(0) ) { beh->ActivateInput(0,FALSE); CK3dEntity *target = (CK3dEntity *) beh->GetTarget(); if( !target ) bbSErrorME(E_PE_REF); pRigidBody *body = GetPMan()->getBody(target); if (!body) bbSErrorME(E_PE_NoBody); pVehicle *v = body->getVehicle(); if (!v) bbSErrorME(E_PE_NoVeh); if (!v->isValidEngine()) bbErrorME("Vehicle is not complete"); pEngine *engine = v->getEngine(); if (!engine) bbErrorME("No valid engine"); CK2dCurve* pOCurve = NULL; //optional BB_DECLARE_PIMAP;//retrieves the parameter input configuration array BBSParameter(I_XML);//our bb settings concated as s##I_XML BBSParameter(I_Flags); BBSParameter(I_Clutch); BBSParameter(I_tList); BBSParameter(I_maxRPM); BBSParameter(I_minRPM); BBSParameter(I_maxTorque); BBSParameter(I_intertia); BBSParameter(I_engineFriction); BBSParameter(I_breakCoeff); BBSParameter(I_GroundForceFeedBackScale); if (sI_XML){ int xmlLink = GetInputParameterValue<int>(beh,BB_IP_INDEX(I_XML)); } if (sI_GroundForceFeedBackScale) engine->setForceFeedbackScale(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_GroundForceFeedBackScale))); if (sI_Flags) engine->setFlags(GetInputParameterValue<int>(beh,BB_IP_INDEX(I_Flags))); if (sI_Clutch) engine->setClutch(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_Clutch))); if (sI_maxTorque) engine->setMaxTorque(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_maxTorque))); if (sI_maxTorque) engine->setMaxTorque(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_maxTorque))); if (sI_maxRPM) engine->setMaxRPM(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_maxRPM))); if (sI_minRPM) engine->setIdleRPM(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_minRPM))); if (sI_engineFriction) engine->setFriction(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_engineFriction))); if (sI_intertia) engine->SetInertia(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_intertia))); if (sI_breakCoeff) engine->setBrakingCoeff(GetInputParameterValue<float>(beh,BB_IP_INDEX(I_breakCoeff))); if (sI_tList){ CKParameterIn *inP = beh->GetInputParameter(BB_IP_INDEX(I_tList)); CKParameter *pout= inP->GetDirectSource(); if (pout) { if (engine->getTorqueCurve()) { pLinearInterpolation &curve = *engine->getTorqueCurve(); curve.clear(); IParameter::Instance()->copyTo(curve,pout); engine->preStep(); } } //engine->setTorqueCurve(); } ////////////////////////////////////////////////////////////////////////// //a optinal curve to display ratio between horse power and rpm /* DWORD outputCurve; beh->GetLocalParameterValue(BB_PMAP_SIZE(gPIMAP),&outputCurve);//special settings ! if (outputCurve) beh->GetOutputParameterValue(0,&pOCurve); */ ////////////////////////////////////////////////////////////////////////// // // Checking we have to replace of the entire motor object ! // if (sI_tList) { float maxInputRPM =0.0f; float maxInputNM =0.0f; ////////////////////////////////////////////////////////////////////////// // // this is only a test run ! pLinearInterpolation nTable; //getNewTorqueTable(beh,nTable,maxInputRPM,maxInputNM,NULL); if (nTable.getSize() ) { /* if (pOCurve) { while (pOCurve->GetControlPointCount()) { pOCurve->DeleteControlPoint(pOCurve->GetControlPoint(0)); pOCurve->Update(); } } */ ////////////////////////////////////////////////////////////////////////// // we just copy into the motor we can get ! ////////////////////////////////////////////////////////////////////////// // we make a new torque ratios //getNewTorqueTable(beh,mDesc->torqueCurve,maxInputRPM,maxInputNM,pOCurve); /* if (!mDesc->isValid()) bbErrorME("motor description was invalid, aborting update "); if (!motor) { motor = pFactory::Instance()->createVehicleMotor(*mDesc); v->setMotor(motor); }else { if (mDesc->torqueCurve.getSize()) { motor->loadNewTorqueCurve(mDesc->torqueCurve); } }*/ } } ////////////////////////////////////////////////////////////////////////// // // Flexibility : // /* if (sI_minRDown && motor )motor->setMinRpmToGearDown(mDDown); if (sI_maxRUp && motor )motor->setMaxRpmToGearUp(mDUp); if (sI_maxR && motor )motor->setMaxRpm(maxR); if (sI_minR && motor )motor->setMinRpm(minR); */ if ( pOCurve ) { /* #ifdef _DEBUG XString error; error << "t curve created with " << pOCurve->GetControlPointCount() << " with l : " << pOCurve->GetLength(); bbErrorME(error.CStr()); #endif */ /* for (int i = 0 ; i < pOCurve->GetControlPointCount() ; i++) { CK2dCurvePoint* point = pOCurve->GetControlPoint(i); point->SetLinear(true); } pOCurve->Update(); beh->SetOutputParameterValue(0,&pOCurve); */ } //delete mDesc; //mDesc = NULL; } beh->ActivateOutput(0); return 0; }
int DirToArray(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; XString filename((CKSTRING) beh->GetInputParameterReadDataPtr(0)); XString Mask((CKSTRING) beh->GetInputParameterReadDataPtr(1)); int rec; beh->GetInputParameterValue(2,&rec); if( beh->IsInputActive(0) ){ beh->ActivateInput(0,FALSE); flist.erase(flist.begin(),flist.end()); CKDirectoryParser MyParser(filename.Str(),Mask.Str(),rec); char* str = NULL; while(str = MyParser.GetNextFile()) flist.push_back(XString(str)); counter = 0; beh->ActivateInput(1,TRUE); } if( beh->IsInputActive(1) ){ beh->ActivateInput(1,FALSE); if ( counter < flist.size() ){ XString entry = flist.at(counter); CKParameterOut * pout = beh->GetOutputParameter(0); pout->SetStringValue(entry.Str() ); counter++; beh->SetOutputParameterValue(1,&counter); beh->ActivateOutput(1); }else{ beh->SetOutputParameterValue(1,&counter); counter = 0 ; beh->ActivateOutput(0); } } return 0; }
int DOOwnerChanged(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKMessageManager* mm = behcontext.MessageManager; CKContext* ctx = behcontext.Context; ////////////////////////////////////////////////////////////////////////// //connection id : int connectionID = vtTools::BehaviorTools::GetInputParameterValue<int>(beh,0); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : if (beh->IsInputActive(0)) { beh->ActivateOutput(0); beh->ActivateInput(0,FALSE); } if (beh->IsInputActive(1)) { beh->ActivateOutput(1); beh->ActivateInput(1,FALSE); return 0; } ////////////////////////////////////////////////////////////////////////// //the object : CK3dEntity *obj= (CK3dEntity*)beh->GetInputParameterObject(1); if (!obj) { beh->ActivateOutput(4); return CKBR_ACTIVATENEXTFRAME; } ////////////////////////////////////////////////////////////////////////// //network ok ? xNetInterface *cin = GetNM()->GetClientNetInterface(); if (!cin) { CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("distributed object creation failed,no network connection !"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(4); return CKBR_ACTIVATENEXTFRAME; } IDistributedObjects*doInterface = cin->getDistObjectInterface(); ////////////////////////////////////////////////////////////////////////// //we come in by input 0 : xDistributedObject *dobj = doInterface->getByEntityID(obj->GetID()); if (!dobj) { CKParameterOut *pout = beh->GetOutputParameter(1); XString errorMesg("There is no such an object"); pout->SetStringValue(errorMesg.Str()); beh->ActivateOutput(4); } else { if (dobj->getOwnershipState().test(1 << E_DO_OS_RELEASED) && dobj->getOwnershipState().test( 1 << E_DO_OS_OWNERCHANGED) ) { beh->ActivateOutput(3); } if (dobj->getOwnershipState().testStrict(1 << E_DO_OS_OWNERCHANGED)) { dobj->getOwnershipState().set( 1<<E_DO_OS_OWNERCHANGED ,false ); int newCLientID = dobj->getUserID(); beh->SetOutputParameterValue(0,&newCLientID); beh->ActivateOutput(2); } } return CKBR_ACTIVATENEXTFRAME; }
/* ******************************************************************* * Function: CKERROR BGWrapperCB(const CKBehaviorContext& behContext) * * Description : The Behavior Callback function is called by Virtools * when various events happen in the life of a BuildingBlock. * * Parameters : * behaviourContext Behavior context reference, which gives access to * frequently used global objects ( context, level, manager, etc... ) * * Returns : CKERROR * ******************************************************************* */ CKERROR GBLCOBGWrapper::BGWrapperCB(const CKBehaviorContext& behContext) { CKERROR result = CKBR_GENERICERROR; // Initialize common pointers. CKBehavior *behaviour = behContext.Behavior; CKContext *context = behContext.Context; CKLevel *level = behContext.CurrentLevel; CKBeObject *owner = behContext.Behavior->GetOwner(); char*name = behaviour->GetName(); if ( behaviour == NULL || context == NULL || level == NULL /*|| owner == NULL*/ ) return CKBR_OK; //Get The BG Script Object if exists CKBehavior* newBG = NULL; CKBehavior* curBG = (CKBehavior*)behaviour->GetLocalParameterObject(EGBLCOBGWRAPPERPARAM_PARAMETER_SCRIPT); // Get the BG nms file path. GetStringValue doesn't work with setting... char fileName[_MAX_PATH+1]; memset(fileName,0,_MAX_PATH+1); CKParameter* scriptPath = behaviour->GetLocalParameter(EGBLCOBGWRAPPERPARAM_PARAMETER_NAME); if ( scriptPath == NULL ) return CKBR_OK; int lenPath = scriptPath->GetDataSize(); if ( lenPath >= _MAX_PATH ) return CKBR_OK; void*ptrPath = scriptPath->GetReadDataPtr(TRUE); if ( ptrPath == NULL ) return CKBR_OK; memcpy(fileName,ptrPath,lenPath); CKDWORD message = behContext.CallbackMessage; switch (message) { case CKM_BEHAVIORLOAD : // when the behavior is loaded case CKM_BEHAVIORRESET: // when the behavior is reseted case CKM_BEHAVIORSETTINGSEDITED : // when the settings are edited { if ( curBG != NULL ) { DestroyCurrentBG(level,behaviour,curBG); curBG = NULL; } newBG = BGLoader( fileName, behContext ); if ( newBG == NULL ) return CKBR_OK; if ( message == CKM_BEHAVIORLOAD || message == CKM_BEHAVIORRESET ) { //context->OutputToConsoleExBeep("%s : LOADED %s",behaviour->GetName(), fileName); if ( CheckIO(behaviour, newBG) == TRUE ) result = CKBR_OK; else context->OutputToConsoleExBeep("%s : Too many inputs/outputs changes in %s\r\nPlease reconstruct the wrapper.",behaviour->GetName(), fileName); } else if ( message == CKM_BEHAVIORSETTINGSEDITED ) { if ( CheckIO(behaviour, newBG) == TRUE ) { result = CKBR_OK; } else if (DeleteIO(behaviour) == TRUE) { if ( CreateIO(behaviour, newBG ) == TRUE ) result = CKBR_OK; else context->OutputToConsoleExBeep("%s : Cannot Create Inputs/Outputs %s",behaviour->GetName(), fileName); } else context->OutputToConsoleExBeep("%s : Cannot Delete Inputs/Outputs %s",behaviour->GetName(), fileName); } if ( result == CKBR_OK && newBG != NULL ) SetNewBG(behaviour,newBG); } break; case CKM_BEHAVIORDEACTIVATESCRIPT: { if ( curBG != NULL ) DesactivateSubBB(curBG); result = CKBR_OK; } break; case CKM_BEHAVIORDETACH : // when the behavior is deleted { if (curBG != NULL) { DestroyCurrentBG(level,behaviour,curBG); curBG = NULL; } result = CKBR_OK; } break; default: { result = CKBR_OK; } break; } if (result != CKBR_OK) context->OutputToConsoleExBeep("%s : Problem while manipulating",behaviour->GetName()); return result; }
int GetNextBBId(const CKBehaviorContext& behcontext) { CKBehavior* beh = behcontext.Behavior; CKContext* ctx = behcontext.Context; beh->ActivateInput(0,FALSE); int count = beh->GetParent()->GetSubBehaviorLinkCount(); int result = -1; for (int i=0; i<count; i++) { CKBehaviorLink *link = beh->GetParent()->GetSubBehaviorLink(i); if (link->GetInBehaviorIO() == beh->GetOutput(0)) { result = link->GetOutBehaviorIO()->GetOwner()->GetID(); beh->SetOutputParameterValue(0,&result); break; } } CKBehavior *script = static_cast<CKBehavior*>(ctx->GetObject(result)); if (script) { int bc = script->GetOutputCount(); int bc2 = script->GetInputCount(); } beh->ActivateOutput(0); beh->SetOutputParameterValue(0,&result); return CKBR_OK; }