本文整理汇总了C++中Bone类的典型用法代码示例。如果您正苦于以下问题:C++ Bone类的具体用法?C++ Bone怎么用?C++ Bone使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Bone类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: memcpy
bool
PMDHandler::doLoad(Model& model, istream& stream) noexcept
{
PMD _pmd;
if (!stream.read((char*)&_pmd.Header, sizeof(_pmd.Header))) return false;
// vertex
if (!stream.read((char*)&_pmd.VertexCount, sizeof(_pmd.VertexCount))) return false;
if (_pmd.VertexCount > 0)
{
_pmd.VertexList.resize(_pmd.VertexCount);
if (!stream.read((char*)&_pmd.VertexList[0], (std::streamsize)(sizeof(PMD_Vertex)* _pmd.VertexCount))) return false;
}
// index
if (!stream.read((char*)&_pmd.IndexCount, sizeof(_pmd.IndexCount))) return false;
if (_pmd.IndexCount > 0)
{
_pmd.IndexList.resize(_pmd.IndexCount);
if (!stream.read((char*)&_pmd.IndexList[0], (std::streamsize)(sizeof(PMD_Index)* _pmd.IndexCount))) return false;
}
// materal
if (!stream.read((char*)&_pmd.MaterialCount, sizeof(_pmd.MaterialCount))) return false;
if (_pmd.MaterialCount > 0)
{
_pmd.MaterialList.resize(_pmd.MaterialCount);
if (!stream.read((char*)&_pmd.MaterialList[0], (std::streamsize)(sizeof(PMD_Material)* _pmd.MaterialCount))) return false;
}
// bone
if (!stream.read((char*)&_pmd.BoneCount, sizeof(_pmd.BoneCount))) return false;
if (_pmd.BoneCount > 0)
{
_pmd.BoneList.resize(_pmd.BoneCount);
if (!stream.read((char*)&_pmd.BoneList[0], (std::streamsize)(sizeof(PMD_Bone)* _pmd.BoneCount))) return false;
}
// IK
if (!stream.read((char*)&_pmd.IkCount, sizeof(_pmd.IkCount))) return false;
if (_pmd.IkCount > 0)
{
_pmd.IkList.resize(_pmd.IkCount);
for (std::size_t i = 0; i < (std::size_t)_pmd.IkCount; i++)
{
if (!stream.read((char*)&_pmd.IkList[i].IK, sizeof(_pmd.IkList[i].IK))) return false;
if (!stream.read((char*)&_pmd.IkList[i].Target, sizeof(_pmd.IkList[i].Target))) return false;
if (!stream.read((char*)&_pmd.IkList[i].LinkCount, sizeof(_pmd.IkList[i].LinkCount))) return false;
if (!stream.read((char*)&_pmd.IkList[i].LoopCount, sizeof(_pmd.IkList[i].LoopCount))) return false;
if (!stream.read((char*)&_pmd.IkList[i].LimitOnce, sizeof(_pmd.IkList[i].LimitOnce))) return false;
_pmd.IkList[i].LinkList.resize(_pmd.IkList[i].LinkCount);
if (!stream.read((char*)&_pmd.IkList[i].LinkList[0], (std::streamsize)(sizeof(PMD_Link)* _pmd.IkList[i].LinkCount))) return false;
}
}
// Morph
if (!stream.read((char*)&_pmd.MorphCount, sizeof(_pmd.MorphCount))) return false;
if (_pmd.MorphCount > 0)
{
_pmd.MorphList.resize(_pmd.MorphCount);
for (std::size_t i = 0; i < (std::size_t)_pmd.MorphCount; i++)
{
if (!stream.read((char*)&_pmd.MorphList[i].Name, sizeof(_pmd.MorphList[i].Name))) return false;
if (!stream.read((char*)&_pmd.MorphList[i].VertexCount, sizeof(_pmd.MorphList[i].VertexCount))) return false;
if (!stream.read((char*)&_pmd.MorphList[i].Category, sizeof(_pmd.MorphList[i].Category))) return false;
if (_pmd.MorphList[i].VertexCount > 0)
{
_pmd.MorphList[i].VertexList.resize(_pmd.MorphList[i].VertexCount);
if (!stream.read((char*)&_pmd.MorphList[i].VertexList[0], (std::streamsize)(sizeof(PMD_MorphVertex)* _pmd.MorphList[i].VertexCount))) return false;
}
}
}
// frame window
if (!stream.read((char*)&_pmd.FrameWindow.ExpressionListCount, sizeof(_pmd.FrameWindow.ExpressionListCount))) return false;
if (_pmd.FrameWindow.ExpressionListCount > 0)
{
_pmd.FrameWindow.ExpressionList.resize(_pmd.FrameWindow.ExpressionListCount);
if (!stream.read((char*)&_pmd.FrameWindow.ExpressionList[0], (std::streamsize)(sizeof(PMD_Expression)* _pmd.FrameWindow.ExpressionListCount))) return false;
}
if (!stream.read((char*)&_pmd.FrameWindow.NodeNameCount, sizeof(_pmd.FrameWindow.NodeNameCount))) return false;
//.........这里部分代码省略.........
示例2: if
/**
* Draws the skeleton.
* \param mode bitmask of RENDER_WIREFRAME, RENDER_FEEDBACK or RENDER_OUTPUT,
* determines how the primitives are drawn.
* \param active active state
**/
void Skeleton::draw(int mode, int active)
{
unsigned hit = 0;
SelectItem *selected = NULL;
if (selector->getPickLayer()
&& selector->getPickLayer()->getSkeleton() == this) {
hit = selector->getHitCount();
selected = selector->getSelected();
}
// select objects from the selection buffer
pJoint = NULL;
pBone = NULL;
for (unsigned int i = 0; i < hit; i++) {
if (selected->type == Selection::SELECT_JOINT &&
((ui->settings.mode == ANIMATA_MODE_CREATE_JOINT) ||
(ui->settings.mode == ANIMATA_MODE_SKELETON_SELECT) ||
(ui->settings.mode == ANIMATA_MODE_SKELETON_DELETE) ||
(ui->settings.mode == ANIMATA_MODE_CREATE_BONE))) {
/* joints are prefered to bones if they overlap */
pJoint = (*joints)[selected->name];
pBone = NULL;
break;
}
else if (selected->type == Selection::SELECT_BONE &&
(ui->settings.mode != ANIMATA_MODE_CREATE_BONE)) {
pBone = (*bones)[selected->name];
}
selected++;
}
if ((mode & RENDER_WIREFRAME)
&& ((!(mode & RENDER_OUTPUT)
&& ui->settings.display_elements & DISPLAY_EDITOR_BONE)
|| ((mode & RENDER_OUTPUT)
&& ui->settings.display_elements & DISPLAY_OUTPUT_BONE)))
{
glLoadName(Selection::SELECT_BONE); /* type of primitive */
glPushName(0); /* id of primitive */
for (unsigned i = 0; i < bones->size(); i++) {
Bone *bone = (*bones)[i];
glLoadName(i);
if (mode & RENDER_OUTPUT)
bone->draw(false);
else
bone->draw(bone == pBone, active);
}
glPopName();
}
if (mode & RENDER_FEEDBACK) {
for (unsigned i = 0; i < joints->size(); i++) {
Joint *joint = (*joints)[i];
glPassThrough(i);
glBegin(GL_POINTS);
glVertex2f(joint->position.x, joint->position.y);
glEnd();
}
}
else if ((mode & RENDER_WIREFRAME) &&
((!(mode & RENDER_OUTPUT)
&& ui->settings.display_elements & DISPLAY_EDITOR_JOINT) ||
((mode & RENDER_OUTPUT)
&& ui->settings.display_elements & DISPLAY_OUTPUT_JOINT)))
{
glLoadName(Selection::SELECT_JOINT); /* type of primitive */
glPushName(0); /* id of primitive */
for (unsigned i = 0; i < joints->size(); i++) {
Joint *joint = (*joints)[i];
glLoadName(i);
if (mode & RENDER_OUTPUT)
joint->draw(false);
else
joint->draw(joint == pJoint, active);
}
glPopName();
}
}
示例3: renderMeshLocally
void SceneMesh::renderMeshLocally() {
Renderer *renderer = CoreServices::getInstance()->getRenderer();
if(skeleton) {
for(int i=0; i < mesh->getPolygonCount(); i++) {
Polygon *polygon = mesh->getPolygon(i);
unsigned int vCount = polygon->getVertexCount();
for(int j=0; j < vCount; j++) {
Vertex *vert = polygon->getVertex(j);
Vector3 norm;
Vector3 aPos = vert->restPosition;
Vector3 tPos;
Number mult = 0;
for(int b =0; b < vert->getNumBoneAssignments(); b++) {
BoneAssignment *bas = vert->getBoneAssignment(b);
mult += bas->weight;
}
mult = 1.0f/mult;
for(int b =0; b < vert->getNumBoneAssignments(); b++) {
BoneAssignment *bas = vert->getBoneAssignment(b);
Bone *bone = bas->bone;
if(bone) {
Matrix4 restMatrix = bone->getRestMatrix();
Matrix4 finalMatrix = bone->getFinalMatrix();
Vector3 vec = restMatrix * aPos;
tPos += finalMatrix * vec * (bas->weight*mult);
Vector3 nvec = vert->restNormal;
nvec = restMatrix.rotateVector(nvec);
nvec = finalMatrix.rotateVector(nvec);
norm += nvec * (bas->weight*mult);
}
}
vert->x = tPos.x;
vert->y = tPos.y;
vert->z = tPos.z;
norm.Normalize();
vert->setNormal(norm.x, norm.y, norm.z);
}
}
mesh->arrayDirtyMap[RenderDataArray::VERTEX_DATA_ARRAY] = true;
mesh->arrayDirtyMap[RenderDataArray::NORMAL_DATA_ARRAY] = true;
}
if(mesh->useVertexColors) {
renderer->pushDataArrayForMesh(mesh, RenderDataArray::COLOR_DATA_ARRAY);
}
renderer->pushDataArrayForMesh(mesh, RenderDataArray::VERTEX_DATA_ARRAY);
renderer->pushDataArrayForMesh(mesh, RenderDataArray::NORMAL_DATA_ARRAY);
renderer->pushDataArrayForMesh(mesh, RenderDataArray::TEXCOORD_DATA_ARRAY);
renderer->drawArrays(mesh->getMeshType());
}
示例4: getRow
bool Board::display() //Displays the board
{
if (!hasSpinner() && rightRow.size() == 0)
return false;
if (!hasSpinner()) //if no spinner is in the board
{
vector<Bone> vecRow = getRow('e');
int numChars = vecRow.size()*4;
numChars = 60 - numChars/2;
int x = numChars;
int y = 27;
for (unsigned int i = 0; i < vecRow.size(); i++)
{
Bone tempBone = vecRow[i];
if (i == 0)
tempBone.swap();
tempBone.display(x,y,'e');
}
}
else //if there is a spinner on the board
{
int tempX = 60;
int tempY = 27;
spinner.display(tempX,tempY,'e');
if (rightRow.size() != 0)
{
int x = 62;
int y = 27;
bool up = false;
bool left = false;
bool lastDouble = false;
for (unsigned int i = 0; i < rightRow.size(); i++) //the following code accounts for the possibility of the bones coming out of the board's limits
{
if (x >= 114 && !up)
{
up = true;
if (lastDouble)
{
y = y - 3;
x = x - 2;
}
else
{
x = x - 2;
y = y - 2;
}
}
if (y <= 8 && !left)
{
left = true;
if (lastDouble)
{
y = y + 2;
x = x - 3;
}
else
{
y = y + 2;
x = x - 2;
}
}
if (up)
if (left)
rightRow[i].display(x,y,'w');
else
rightRow[i].display(x,y,'n');
else
rightRow[i].display(x,y,'e');
if (rightRow[i].isDouble())
lastDouble = true;
else
lastDouble = false;
}
}
if (leftRow.size() != 0)
{
int x = 58;
int y = 27;
bool down = false;
bool right = false;
bool lastDouble = false;
for (unsigned int i = 0; i < leftRow.size(); i++)
{
if (x <= 4 && !down)
{
down = true;
if (lastDouble)
{
x = x + 2;
y = y + 3;
}
else
{
x = x + 2;
y = y + 2;
//.........这里部分代码省略.........
示例5: CreateEmptyTransformNodeTree
void CreateEmptyTransformNodeTree( TransformNode& root_transform_node ) { m_RootBone.CreateEmptyTransformNodeTree( root_transform_node ); }
示例6: setB2bodyPosition
void NormalEnemy::headDropDie()
{
if (footBody != NULL) {
gameWorld->DestroyBody(footBody);
footBody = NULL;
}
setB2bodyPosition();
if (!dead) {
for (auto o : deadSpriteArray) {
if (armature->getScaleX() < 0) {
o->setScaleX(-o->getScaleX());
}
}
armature->setVisible(false);
b2Filter filter;
filter.categoryBits = DEAD_ZOMBIE;
filter.maskBits = UPPER_GROUND | BASE_GROUND;
const Map<std::string, Bone*>& dic = armature->getBoneDic();
for(auto& element : dic)
{
//Ref *o = dickeyarr->objectAtIndex(i);
// CCString *key = dynamic_cast<CCString*>(o);
Bone *bone = element.second;
Skin *skin = (Skin*)element.second->getDisplayRenderNode();
string name = element.first;
if (skin) {
b2Body *body = skin->body;
body->GetFixtureList()->SetFixtureType(f_bodydead);
body->GetFixtureList()->SetFilterData(filter);
body->SetType(b2_dynamicBody);
Bone *parentBone = bone->getParentBone();
string selfName = bone->getName();
string parentName;
if (parentBone) {
parentName = parentBone->getName();
}
if (parentBone && selfName.compare("headbone") != 0 && parentName.compare("headbone") != 0) {
Skin *parentSkin = (Skin*)parentBone->getDisplayRenderNode();
b2Body *parentBody = parentSkin->body;
b2RevoluteJointDef jdef;
Mat4 tran = bone->_getNodeToParentTransform();
Point p = Point(tran.m[12], tran.m[13]);
// Point p = skin->getWorldPosition();
//printf("p x = %f y = %f\n", p.x, p.y);
jdef.Initialize(parentBody, body, b2Vec2(p.x/PTM_RATIO, p.y/PTM_RATIO));
jdef.lowerAngle = -0.35f * b2_pi;
jdef.upperAngle = 0.35f * b2_pi;
jdef.enableLimit = true;
gameWorld->CreateJoint(&jdef);
}
}
}
// update(0);
setBodySprites();
dead = true;
for (auto o : deadSpriteArray) {
o->setVisible(true);
}
}
}
示例7: lock
AEResult Skeleton::Load()
{
std::lock_guard<std::mutex> lock(m_GameResourceMutex);
AEAssert(!m_FileName.empty());
if(m_FileName.empty())
{
return AEResult::EmptyFilename;
}
/////////////////////////////////////////////
//Clean Up memory before loading File
CleanUp();
AEResult ret = AEResult::Ok;
/////////////////////////////////////////////
//Start reading file
std::ifstream skeletonFile;
skeletonFile.open(m_FileName, std::ios::binary | std::ios::in);
if(!skeletonFile.is_open())
{
AETODO("add log");
return AEResult::OpenFileFail;
}
char* tempPtr = nullptr;
uint32_t sizeToRead = 0;
/////////////////////////////////////////////
//Verify Header
bool verifyHeader = AEGameContentHelpers::ReadFileHeaderAndVerify(skeletonFile, AE_CT_AE3DS_FILE_HEADER, AE_CT_AE3DS_FILE_VERSION_MAYOR, AE_CT_AE3DS_FILE_VERSION_MINOR, AE_CT_AE3DS_FILE_VERSION_REVISON);
if(!verifyHeader)
{
AETODO("Add log");
return AEResult::InvalidFileHeader;
}
/////////////////////////////////////////////
//Read Number of Bones
uint32_t numBones = 0;
tempPtr = reinterpret_cast<char*>(&numBones);
sizeToRead = sizeof(uint32_t);
skeletonFile.read(tempPtr, sizeToRead);
/////////////////////////////////////////////
//Read Bones
for(uint32_t i = 0; i < numBones; ++i)
{
Bone* bone = new Bone();
glm::mat4 tempMat = AEMathHelpers::Mat4Identity;
int32_t tempInt32 = 0;
/////////////////////////////////////////////
//Write name of Bone and size of Name
bone->SetName(AEGameContentHelpers::ReadString(skeletonFile));
/////////////////////////////////////////////
//Read Bone Matrices
sizeToRead = sizeof(glm::mat4);
tempPtr = reinterpret_cast<char*>(&tempMat);
//Local Matrix
skeletonFile.read(tempPtr, sizeToRead);
bone->SetLocalMatrix(tempMat);
//World Matrix
skeletonFile.read(tempPtr, sizeToRead);
bone->SetWorldMatrix(tempMat);
//Off Set Matrix
skeletonFile.read(tempPtr, sizeToRead);
bone->SetOffSetMatrix(tempMat);
/////////////////////////////////////////////
//Read Bone Indices
tempPtr = reinterpret_cast<char*>(&tempInt32);
sizeToRead = sizeof(int32_t);
//Parent Index
skeletonFile.read(tempPtr, sizeToRead);
bone->SetParentIndex(tempInt32);
//Bone Index
skeletonFile.read(tempPtr, sizeToRead);
bone->SetIndex(tempInt32);
/////////////////////////////////////////////
//Add Bone to Skeleton
m_BoneHierarchy.push_back(bone);
}
/////////////////////////////////////////////
//Read Footer
bool verifyFooter = AEGameContentHelpers::ReadFileFooterAndVerify(skeletonFile, AE_CT_AE3DS_FILE_FOOTER);
//.........这里部分代码省略.........
示例8: CC_CALLBACK_2
void TestParticleDisplay::onEnter()
{
ArmatureTestLayer::onEnter();
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesEnded = CC_CALLBACK_2(TestParticleDisplay::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
animationID = 0;
armature = Armature::create("robot");
armature->getAnimation()->playWithIndex(0);
armature->setPosition(VisibleRect::center());
armature->setScale(0.48f);
armature->getAnimation()->setSpeedScale(0.5f);
addChild(armature);
ParticleSystem *p1 = CCParticleSystemQuad::create("Particles/SmallSun.plist");
ParticleSystem *p2 = CCParticleSystemQuad::create("Particles/SmallSun.plist");
Bone *bone = Bone::create("p1");
bone->addDisplay(p1, 0);
bone->changeDisplayWithIndex(0, true);
bone->setIgnoreMovementBoneData(true);
bone->setLocalZOrder(100);
bone->setScale(1.2f);
armature->addBone(bone, "bady-a3");
bone = Bone::create("p2");
bone->addDisplay(p2, 0);
bone->changeDisplayWithIndex(0, true);
bone->setIgnoreMovementBoneData(true);
bone->setLocalZOrder(100);
bone->setScale(1.2f);
armature->addBone(bone, "bady-a30");
}
示例9: while
SkeletonPtr MergeSkeleton::bake()
{
MeshCombiner::getSingleton().log(
"Baking: New Skeleton started" );
SkeletonPtr sp = SkeletonManager::getSingleton().create( "mergeSkeleton",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, true );
for( std::vector< Ogre::SkeletonPtr >::iterator it = m_Skeletons.begin();
it != m_Skeletons.end(); ++it )
{
if( it == m_Skeletons.begin() )
{
MeshCombiner::getSingleton().log(
"Baking: using " + (*it)->getName() + " as the base skeleton" );
MeshCombiner::getSingleton().log(
"Baking: adding bones" );
Skeleton::BoneIterator bit = (*it)->getBoneIterator();
while( bit.hasMoreElements() )
{
Bone* bone = bit.getNext();
Bone* newbone = sp->createBone( bone->getName(), bone->getHandle() );
newbone->setScale( bone->getScale() );
newbone->setOrientation( bone->getOrientation() );
newbone->setPosition( bone->getPosition() );
}
MeshCombiner::getSingleton().log(
"Baking: building bone hierarchy" );
// bone hierarchy
bit = (*it)->getBoneIterator();
while( bit.hasMoreElements() )
{
Bone* bone = bit.getNext();
Node* pnode = bone->getParent();
if( pnode != NULL )
{
Bone* pbone = static_cast<Bone*>( pnode );
sp->getBone( pbone->getHandle() )->addChild( sp->getBone( bone->getHandle() ) );
}
}
}
MeshCombiner::getSingleton().log(
"Baking: adding animations for " + (*it)->getName() );
// insert all animations
for (unsigned short a=0; a < (*it)->getNumAnimations(); ++a )
{
Animation* anim = (*it)->getAnimation( a );
Animation* newanim = sp->createAnimation( anim->getName(), anim->getLength() );
if( anim->getNumNodeTracks() > 0 )
MeshCombiner::getSingleton().log(
"Baking: adding node tracks" );
for( unsigned short na=0; na < anim->getNumNodeTracks(); ++na )
{
if( anim->hasNodeTrack( na ) )
{
NodeAnimationTrack* nat = anim->getNodeTrack( na );
NodeAnimationTrack* newnat = newanim->createNodeTrack( na );
// all key frames
for( unsigned short nf=0; nf < nat->getNumKeyFrames(); ++nf )
{
TransformKeyFrame* tkf = nat->getNodeKeyFrame( nf );
TransformKeyFrame* newtkf = newnat->createNodeKeyFrame( tkf->getTime() );
newtkf->setRotation( tkf->getRotation() );
newtkf->setTranslate( tkf->getTranslate() );
newtkf->setScale( tkf->getScale() );
}
newnat->setAssociatedNode( sp->getBone( nat->getHandle() ) );
}
}
if( anim->getNumNumericTracks() > 0 )
MeshCombiner::getSingleton().log(
"Baking: adding numeric tracks" );
for( unsigned short na=0; na < anim->getNumNumericTracks(); ++na )
{
if( anim->hasNumericTrack( na ) )
{
NumericAnimationTrack* nat = anim->getNumericTrack( na );
NumericAnimationTrack* newnat = newanim->createNumericTrack( na );
// all key frames
for( unsigned short nf=0; nf < nat->getNumKeyFrames(); ++nf )
{
NumericKeyFrame* nkf = nat->getNumericKeyFrame( nf );
NumericKeyFrame* newnkf = newnat->createNumericKeyFrame( nkf->getTime() );
newnkf->setValue( nkf->getValue() );
}
}
}
if( anim->getNumVertexTracks() > 0 )
MeshCombiner::getSingleton().log(
"Baking: adding vertex tracks" );
for( unsigned short va=0; va < anim->getNumVertexTracks(); ++va )
{
//.........这里部分代码省略.........
示例10: Radian
// ---------------------------------------------------------
// set positions and orientations.
void XMLSkeletonSerializer::readBones2(Skeleton* skel, TiXmlElement* mBonesNode)
{
LogManager::getSingleton().logMessage("XMLSkeletonSerializer: Reading Bones data...");
Bone* btmp;
Quaternion quat;
for (TiXmlElement* bonElem = mBonesNode->FirstChildElement();
bonElem != 0; bonElem = bonElem->NextSiblingElement())
{
String name = bonElem->Attribute("name");
// int id = StringConverter::parseInt(bonElem->Attribute("id"));
TiXmlElement* posElem = bonElem->FirstChildElement("position");
TiXmlElement* rotElem = bonElem->FirstChildElement("rotation");
TiXmlElement* axisElem = rotElem->FirstChildElement("axis");
TiXmlElement* scaleElem = bonElem->FirstChildElement("scale");
Vector3 pos;
Vector3 axis;
Radian angle;
Vector3 scale;
pos.x = StringConverter::parseReal(posElem->Attribute("x"));
pos.y = StringConverter::parseReal(posElem->Attribute("y"));
pos.z = StringConverter::parseReal(posElem->Attribute("z"));
angle = Radian(StringConverter::parseReal(rotElem->Attribute("angle")));
axis.x = StringConverter::parseReal(axisElem->Attribute("x"));
axis.y = StringConverter::parseReal(axisElem->Attribute("y"));
axis.z = StringConverter::parseReal(axisElem->Attribute("z"));
// Optional scale
if (scaleElem)
{
// Uniform scale or per axis?
const char* factorAttrib = scaleElem->Attribute("factor");
if (factorAttrib)
{
// Uniform scale
Real factor = StringConverter::parseReal(factorAttrib);
scale = Vector3(factor, factor, factor);
}
else
{
// axis scale
scale = Vector3::UNIT_SCALE;
const char* factorString = scaleElem->Attribute("x");
if (factorString)
{
scale.x = StringConverter::parseReal(factorString);
}
factorString = scaleElem->Attribute("y");
if (factorString)
{
scale.y = StringConverter::parseReal(factorString);
}
factorString = scaleElem->Attribute("z");
if (factorString)
{
scale.z = StringConverter::parseReal(factorString);
}
}
}
else
{
scale = Vector3::UNIT_SCALE;
}
/*LogManager::getSingleton().logMessage("bone " + name + " : position("
+ StringConverter::toString(pos.x) + "," + StringConverter::toString(pos.y) + "," + StringConverter::toString(pos.z) + ")"
+ " - angle: " + StringConverter::toString(angle) +" - axe: "
+ StringConverter::toString(axis.x) + "," + StringConverter::toString(axis.y) + "," + StringConverter::toString(axis.z) );
*/
btmp = skel->getBone(name);
btmp->setPosition(pos);
quat.FromAngleAxis(angle, axis);
btmp->setOrientation(quat);
btmp->setScale(scale);
} // bones
}
示例11: CalcIK_CCD
///***************************************************************************************
/// CalcIK_2D_CCD
/// Given a bone chain located at the origin, this function will perform a single cyclic
/// coordinate descent (CCD) iteration. This finds a solution of bone angles that places
/// the final bone in the given chain at a target position. The supplied bone angles are
/// used to prime the CCD iteration. If a valid solution does not exist, the angles will
/// move as close to the target as possible. The user should resupply the updated angles
/// until a valid solution is found (or until an iteration limit is met).
///
/// returns: CCD_Result.Success when a valid solution was found.
/// CCD_Result.Processing when still searching for a valid solution.
/// CCD_Result.Failure when it can get no closer to the target.
///***************************************************************************************
CCD_Result CalcIK_CCD(Bone *startBone, Bone *endBone, CCPoint &targetPoint, float arrivalDist)
{
double arrivalDistSqr = arrivalDist * arrivalDist;
//===
// Track the end effector position (the final bone)
CCPoint endPoint = ccp(startBone->m_tWorldTransform.tx, startBone->m_tWorldTransform.ty);
CCPoint currentPoint = ccp(0, 0);
//===
// Perform CCD on the bones by optimizing each bone in a loop
// from the final bone to the root bone
bool modifiedBones = false;
Bone *currentBone = startBone->getParentBone();
Bone *lastCurrentBone = startBone;
while(!currentBone->getParentBone() == NULL)
{
currentPoint = ccp(currentBone->m_tWorldTransform.tx, currentBone->m_tWorldTransform.ty);
// Get the vector from the current bone to the end effector position.
double curToEndX = endPoint.x - currentPoint.x;
double curToEndY = endPoint.y - currentPoint.y;
double curToEndMag = ccpDistance(endPoint, currentPoint);
// Get the vector from the current bone to the target position.
double curToTargetX = targetPoint.x - currentPoint.x;
double curToTargetY = targetPoint.y - currentPoint.y;
double curToTargetMag = ccpDistance(targetPoint, currentPoint);
// Get rotation to place the end effector on the line from the current
// joint position to the target postion.
double cosRotAng;
double sinRotAng;
double endTargetMag = (curToEndMag*curToTargetMag);
if( endTargetMag <= epsilon )
{
cosRotAng = 1;
sinRotAng = 0;
}
else
{
cosRotAng = (curToEndX*curToTargetX + curToEndY*curToTargetY) / endTargetMag;
sinRotAng = (curToEndX*curToTargetY - curToEndY*curToTargetX) / endTargetMag;
}
// Clamp the cosine into range when computing the angle (might be out of range
// due to floating point error).
double rotAng = acos( MAX(-1, MIN(1, cosRotAng) ) );
if( sinRotAng < 0.0 )
rotAng = -rotAng;
// Rotate the end effector position.
endPoint.x = currentPoint.x + cosRotAng*curToEndX - sinRotAng*curToEndY;
endPoint.y = currentPoint.y + sinRotAng*curToEndX + cosRotAng*curToEndY;
#if CS_DEBUG_FOR_EDIT
// Rotate the current bone in local space (this value is output to the user)
if (dynamic_cast<EditorTween*>(currentBone->getTween()) != 0)
{
EditorTween *tween = ((EditorTween*)currentBone->getTween());
if(currentBone == endBone || currentBone->getChildren()->count() > 1)
{
CCPoint p = ccpRotateByAngle(ccp(lastCurrentBone->m_tWorldTransform.tx, lastCurrentBone->m_tWorldTransform.ty), currentPoint, rotAng);
((EditorDisplayManager*)currentBone->getDisplayManager())->convertPointToSpace(p);
((EditorTween*)lastCurrentBone->getTween())->editPosition(p.x, p.y);
}
else
{
rotAng = tween->getRotation() - rotAng;
rotAng = simplifyAngle(rotAng);
((EditorTween*)currentBone->getTween())->editRotation(rotAng);
}
}
//.........这里部分代码省略.........
示例12: CC_SAFE_DELETE
bool Armature::init(const char *name)
{
bool bRet = false;
do
{
//cocos2d::CCLog("Armature (%s) create.", name);
CC_SAFE_DELETE(m_pAnimation);
m_pAnimation = Animation::create(this);
CCAssert(m_pAnimation, "create Armature::m_pAnimation fail!");
m_pAnimation->retain();
CC_SAFE_DELETE(m_pBoneDic);
m_pBoneDic = CCDictionary::create();
CCAssert(m_pBoneDic, "create Armature::m_pBoneDic fail!");
m_pBoneDic->retain();
m_sBlendFunc.src = CC_BLEND_SRC;
m_sBlendFunc.dst = CC_BLEND_DST;
m_strName = name == NULL ? "" : name;
ArmatureDataManager *armatureDataManager = ArmatureDataManager::sharedArmatureDataManager();
if(m_strName.compare("") != 0)
{
m_strName = name;
AnimationData* animationData = armatureDataManager->getAnimationData(name);
CCAssert(animationData, "AnimationData not exist! ");
m_pAnimation->setAnimationData(animationData);
ArmatureData *armatureData = armatureDataManager->getArmatureData(name);
CCAssert(armatureData, "");
m_pArmatureData = armatureData;
CCDictElement *_element = NULL;
CCDictionary *boneDataDic = &armatureData->boneDataDic;
CCDICT_FOREACH(boneDataDic, _element)
{
Bone *bone = createBone(_element->getStrKey());
//! init bone's Tween to 1st movement's 1st frame
do {
MovementData *movData = animationData->getMovement(animationData->movementNames.at(0).c_str());
CC_BREAK_IF(!movData);
MovementBoneData *movBoneData = movData->getMovementBoneData(bone->getName().c_str());
CC_BREAK_IF(!movBoneData || movBoneData->frameList.count() <= 0);
FrameData *_frameData = movBoneData->getFrameData(0);
CC_BREAK_IF(!_frameData);
bone->getTweenData()->copy(_frameData);
} while (0);
}
}
示例13: Spawned
void Spawned()
{
physics = corpse->game_state->physics_world;
// get bone pos/ori info
vector<Mat4> mats = vector<Mat4>();
unsigned int count = character->skeleton->bones.size();
for(unsigned int i = 0; i < count; ++i)
{
Bone* bone = character->skeleton->bones[i];
bone_offsets.push_back(bone->rest_pos);
mats.push_back(whole_xform * bone->GetTransformationMatrix());
}
UberModel::BonePhysics** bone_physes = new UberModel::BonePhysics* [count];
// create rigid bodies
for(unsigned int i = 0; i < count; ++i)
{
Bone* bone = character->skeleton->bones[i];
Mat4 mat = mats[i];
float ori_values[] = {mat[0], mat[1], mat[2], mat[4], mat[5], mat[6], mat[8], mat[9], mat[10]};
bone->ori = Quaternion::FromRotationMatrix(Mat3(ori_values));
Vec3 bone_pos = mat.TransformVec3(bone_offsets[i], 1);
UberModel::BonePhysics* phys = NULL;
for(unsigned int j = 0; j < model->bone_physics.size(); ++j)
if(Bone::string_table[model->bone_physics[j].bone_name] == bone->name)
phys = &model->bone_physics[j];
bone_physes[i] = phys;
if(phys != NULL)
{
btCollisionShape* shape = phys->shape;
if(shape != NULL)
{
RigidBodyInfo* rigid_body = new RigidBodyInfo(shape, MassInfo::FromCollisionShape(shape, phys->mass), bone_pos, bone->ori);
rigid_body->SetLinearVelocity(initial_vel);
// these constants taken from the ragdoll demo
rigid_body->SetDamping(0.05f, 0.85f);
rigid_body->SetDeactivationTime(0.8f);
rigid_body->SetSleepingThresholds(1.6f, 2.5f);
rigid_body->SetFriction(1.0f);
rigid_body->SetRestitution(0.01f);
physics->AddRigidBody(rigid_body);
rigid_bodies.push_back(rigid_body);
CorpseBoneShootable* shootable = new CorpseBoneShootable(corpse->game_state, corpse, rigid_body, blood_material);
shootables.push_back(shootable);
rigid_body->SetCustomCollisionEnabled(shootable);
bone_indices.push_back(i);
}
}
}
// create constraints between bones
for(unsigned int i = 0; i < rigid_bodies.size(); ++i)
{
unsigned int bone_index = bone_indices[i];
UberModel::BonePhysics* phys = bone_physes[bone_index];
if(phys != NULL)
{
Bone* bone = character->skeleton->bones[bone_index];
Bone* parent = bone->parent;
if(parent != NULL)
{
// find index of parent (bone's index is the same as rigid body info's index)
for(unsigned int j = 0; j < rigid_bodies.size(); ++j)
{
unsigned int j_index = bone_indices[j];
if(character->skeleton->bones[j_index] == parent)
{
if(bone_physes[j_index] != NULL)
{
RigidBodyInfo* my_body = rigid_bodies[i];
RigidBodyInfo* parent_body = rigid_bodies[j];
ConeTwistConstraint* c = new ConeTwistConstraint(my_body, parent_body, Quaternion::Identity(), Vec3(), phys->ori, phys->pos);
c->SetLimit(phys->span);
c->SetDamping(0.1f); // default is 0.01
constraints.push_back(c);
physics->AddConstraint(c, true); // true = prevent them from colliding normally
break;
}
}
}
//.........这里部分代码省略.........
示例14: TiXmlDocument
bool Skeleton::loadSkeletonFromXML(const std::string &skeletonFileName)
{
TiXmlDocument* skelDoc = new TiXmlDocument();
if(!skelDoc->LoadFile(skeletonFileName))
throw std::logic_error("Load Skeleton File Failed !!");
TiXmlElement *rootEle = skelDoc->FirstChildElement();
TiXmlElement *bonesElement = static_cast<TiXmlElement*>(rootEle->FirstChild("bones"));
if(!bonesElement)
throw std::invalid_argument("Invalid Skeleton File !!!");
TiXmlElement *boneElement = bonesElement->FirstChildElement();
while(boneElement)
{
TiXmlAttribute *attributes = boneElement->FirstAttribute();
int parentID, boneID;
std::string boneName;
float length = 0.0;
boneElement->QueryIntAttribute( "id", &boneID);
boneElement->QueryIntAttribute("parent", &parentID);
boneElement->QueryFloatAttribute( "length", &length);
boneElement->QueryStringAttribute( "name", &boneName);
Bone *bone = NULL;
if(parentID == boneID)
bone = createBone();
else
{
Bone *parent = getBone(parentID);
bone = createBone(parent);
}
bone->name() = boneName;
mBoneNameToID[boneName] = bone->id();
bone->boneLength() = length;
//transition
TiXmlElement *sibElement = boneElement->FirstChildElement();
sibElement->QueryFloatAttribute("x", &bone->initPose().T.x);
sibElement->QueryFloatAttribute("y", &bone->initPose().T.y);
sibElement->QueryFloatAttribute("z", &bone->initPose().T.z);
//orientation
sibElement = sibElement->NextSiblingElement();
sibElement->QueryFloatAttribute("w", &bone->initPose().Q.w);
sibElement->QueryFloatAttribute("x", &bone->initPose().Q.x);
sibElement->QueryFloatAttribute("y", &bone->initPose().Q.y);
sibElement->QueryFloatAttribute("z", &bone->initPose().Q.z);
//mesh ori
sibElement = sibElement->NextSiblingElement();
sibElement->QueryStringAttribute("name", &bone->meshName());
sibElement->QueryFloatAttribute("w", &bone->meshOrientation().w);
sibElement->QueryFloatAttribute("x", &bone->meshOrientation().x);
sibElement->QueryFloatAttribute("y", &bone->meshOrientation().y);
sibElement->QueryFloatAttribute("z", &bone->meshOrientation().z);
sibElement = sibElement->NextSiblingElement();
int jointtype;
sibElement->QueryIntAttribute("jointtype",&jointtype);
bone->type() = static_cast<Bone::JointType>(jointtype);
TiXmlElement *limitsElement = NULL;
if(jointtype &0x01)
{
limitsElement = sibElement->FirstChildElement();
limitsElement->QueryFloatAttribute("low", &bone->limitsBox(0).x);
limitsElement->QueryFloatAttribute("up", &bone->limitsBox(0).y);
/*bone->limitsBox(0).x = -bone->limitsBox(0).x;
bone->limitsBox(0).y = -bone->limitsBox(0).y;*/
}
if(jointtype &0x02)
{
if(!limitsElement)
limitsElement = sibElement->FirstChildElement();
else
limitsElement = limitsElement->NextSiblingElement();
limitsElement->QueryFloatAttribute("low", &bone->limitsBox(1).x);
limitsElement->QueryFloatAttribute( "up", &bone->limitsBox(1).y);
/* bone->limitsBox(1).x = -bone->limitsBox(1).x;
bone->limitsBox(1).y = -bone->limitsBox(1).y;*/
}
if(jointtype &0x04)
{
if(!limitsElement)
limitsElement = sibElement->FirstChildElement();
else
limitsElement = limitsElement->NextSiblingElement();
limitsElement->QueryFloatAttribute("low", &bone->limitsBox(2).x);
//.........这里部分代码省略.........
示例15: onFrame
void LeapListener::onFrame(const Controller &controller){
const Frame frame = controller.frame();
HandList hands = frame.hands();
std::vector<HandModel> myhands;
BoneModel mybone;
HandModel myhand;
//printf("frame: %d\n", frame.id());
float scale = 0.025;
float disp = 3.5f;
bool record = true;
for (int i = 0; i < hands.count(); i++){
FingerList fingers = hands[i].fingers();
myhand.bones.clear();
myhand.references.clear();
Vector handPosition = hands[i].palmPosition();
handPosition *= scale;
handPosition.y -= disp;
Vector wrist = hands[i].wristPosition();
wrist *= scale;
wrist.y -= disp;
myhand.palmPosition = handPosition;
myhand.palmNormal = hands[i].palmNormal();
myhand.direction = hands[i].direction();
for (int j = 0; j < fingers.count(); j++){
Bone bone;
Bone::Type boneType;
Vector currentPosition = fingers[j].tipPosition();
currentPosition *= scale;
currentPosition.y -= disp;
Vector lastPosition = m_lastFrame.finger(fingers[j].id()).tipPosition();
lastPosition *= scale;
lastPosition.y -= disp;
Vector diff = currentPosition - lastPosition;
//printf("%f, %f, %f\n", abs(diff.x), abs(diff.y), abs(diff.z));
//if (abs(diff.x) > 0.2 || abs(diff.y) > 0.2 || abs(diff.z) > 0.2) record = false;
if (abs(diff.x) < 0.0001 || abs(diff.y) < 0.0001 || abs(diff.z) < 0.0001) record = false;
for (int k = 0; k < 4; k++){
boneType = static_cast<Bone::Type>(k);
bone = fingers[j].bone(boneType);
if (fingers[j].type() == Finger::Type::TYPE_THUMB && k == 0) continue;
Vector prevPos = bone.prevJoint();
prevPos *= scale;
prevPos.y -= disp;
Vector nextPos = bone.nextJoint();
nextPos *= scale;
nextPos.y -= disp;
mybone.direction = nextPos - prevPos;
mybone.position = (prevPos + nextPos) / 2;
mybone.prevJoint = prevPos;
mybone.nextJoint = nextPos;
mybone.length = bone.length() * scale;
if (boneType == Bone::Type::TYPE_PROXIMAL){
if (fingers[j].type() == Finger::Type::TYPE_THUMB){
myhand.thumb = prevPos;
//myhand.references.push_back(nextPos);
}
else{
myhand.references.push_back(prevPos);
}
}
myhand.bones.push_back(mybone);
}
}
myhand.base = myhand.references[3] - myhand.references[0];
Vector disp = myhand.base.normalized() * 0.3f;
myhand.references[3] += disp;
myhand.references[0] -= disp;
//for (int i = 1; i < 5; i++){
// printf("%f\n", myhand.references[i - 1].distanceTo(myhand.references[i]));
//}
myhands.push_back(myhand);
}
if (record){
m_hands.clear();
for (int i = 0; i < myhands.size(); i++){
m_hands.push_back(myhands[i]);
}
}
//.........这里部分代码省略.........