Esempio n. 1
0
void Model::handleNode(aiNode* ainode, const aiMatrix4x4& accumulatedTransformation, int level) {
//    std::cerr << "LVL " << level << " Node is: " << ainode->mName.C_Str() << " and has "
//              << ainode->mNumChildren << " children and " << ainode->mNumMeshes << " meshes." << "\n";

    aiMatrix4x4t<float> transformation =  accumulatedTransformation * ainode->mTransformation;

//    for (int i = 0 ; i < 4; ++i) {
//        for (int j = 0 ; j < 4; ++j) {
//            std::cerr << ainode->mTransformation[i][j] << " ";
//        }
//        std::cerr << '\n';
//    }

//    std::cerr << '\n';

    if (ainode->mNumMeshes > 0) {
        ModelNode current;

        for (unsigned int i = 0; i < ainode->mNumMeshes; ++i) {
            current.m_meshIndices.push_back(ainode->mMeshes[i]);
        }

        aiMat4ToDogeMat4(transformation, current.m_transformation);

        m_nodes.push_back(current);
    }


    for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
        handleNode(ainode->mChildren[i], transformation, level + 1);
    }

//    std::cerr << "END OF " << ainode->mName.C_Str() << "\n\n";

}
Esempio n. 2
0
void srs_env_model::CMarkerArrayPlugin::newMapDataCB(SMapWithParameters & par)
{
    // each array stores all cubes of a different size, one for each depth level:
    m_data->markers.resize(par.treeDepth + 1);

    m_ocFrameId = par.frameId;

    // Get octomap parameters
    par.map->octree.getMetricMin(m_minX, m_minY, m_minZ);
    par.map->octree.getMetricMax(m_maxX, m_maxY, m_maxZ);

    m_bTransform = m_ocFrameId != m_markerArrayFrameId;

    // Is transform needed?
    if( ! m_bTransform )
        return;

    ros::Time timestamp( par.currentTime );
    tf::StampedTransform ocToMarkerArrayTf;


    // Get transform
    try {
        // Transformation - to, from, time, waiting time
        m_tfListener.waitForTransform(m_markerArrayFrameId, m_ocFrameId,
                timestamp, ros::Duration(5));

        m_tfListener.lookupTransform(m_markerArrayFrameId, m_ocFrameId,
                timestamp, ocToMarkerArrayTf);

    } catch (tf::TransformException& ex) {
        ROS_ERROR_STREAM("MarkerArrayPlugin: Transform error - " << ex.what() << ", quitting callback");
        PERROR( "Transform error.");
        return;
    }


    Eigen::Matrix4f ocToMarkerArrayTM;

    // Get transformation matrix
    pcl_ros::transformAsMatrix(ocToMarkerArrayTf, ocToMarkerArrayTM);

    // Disassemble translation and rotation
    m_ocToMarkerArrayRot  = ocToMarkerArrayTM.block<3, 3> (0, 0);
    m_ocToMarkerArrayTrans = ocToMarkerArrayTM.block<3, 1> (0, 3);


    tButServerOcTree & tree( par.map->octree );
	srs_env_model::tButServerOcTree::leaf_iterator it, itEnd( tree.end_leafs() );

	// Crawl through nodes
	for ( it = tree.begin_leafs(m_crawlDepth); it != itEnd; ++it)
	{
		handleNode(it, par);
	} // Iterate through octree

	handlePostNodeTraversal( par );

}
Esempio n. 3
0
void DOMSerializer::iterate(const Node* pNode) const
{
	while (pNode)
	{
		handleNode(pNode);
		pNode = pNode->nextSibling();
	}
}
 bool handleBlock(BasicBlock* block)
 {
     HashSet<Node*> dontNeedBarriers;
     for (unsigned indexInBlock = 0; indexInBlock < block->size(); ++indexInBlock) {
         m_currentIndex = indexInBlock;
         Node* node = block->at(indexInBlock);
         handleNode(dontNeedBarriers, node);
     }
     return true;
 }
nsresult
txSyncCompileObserver::loadURI(const nsAString& aUri,
                               const nsAString& aReferrerUri,
                               txStylesheetCompiler* aCompiler)
{
    if (mProcessor->IsLoadDisabled()) {
        return NS_ERROR_XSLT_LOAD_BLOCKED_ERROR;
    }

    nsCOMPtr<nsIURI> uri;
    nsresult rv = NS_NewURI(getter_AddRefs(uri), aUri);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIURI> referrerUri;
    rv = NS_NewURI(getter_AddRefs(referrerUri), aReferrerUri);
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIPrincipal> referrerPrincipal;
    rv = nsContentUtils::GetSecurityManager()->
      GetCodebasePrincipal(referrerUri, getter_AddRefs(referrerPrincipal));
    NS_ENSURE_SUCCESS(rv, rv);

    // Content Policy
    PRInt16 shouldLoad = nsIContentPolicy::ACCEPT;
    rv = NS_CheckContentLoadPolicy(nsIContentPolicy::TYPE_STYLESHEET,
                                   uri,
                                   referrerPrincipal,
                                   nsnull,
                                   NS_LITERAL_CSTRING("application/xml"),
                                   nsnull,
                                   &shouldLoad);
    NS_ENSURE_SUCCESS(rv, rv);
    if (NS_CP_REJECTED(shouldLoad)) {
        return NS_ERROR_DOM_BAD_URI;
    }

    // This is probably called by js, a loadGroup for the channel doesn't
    // make sense.
    nsCOMPtr<nsIDOMDocument> document;
    rv = nsSyncLoadService::LoadDocument(uri, referrerPrincipal, nsnull,
                                         PR_FALSE, getter_AddRefs(document));
    NS_ENSURE_SUCCESS(rv, rv);

    nsCOMPtr<nsIDocument> doc = do_QueryInterface(document);
    rv = handleNode(doc, aCompiler);
    if (NS_FAILED(rv)) {
        nsCAutoString spec;
        uri->GetSpec(spec);
        aCompiler->cancel(rv, nsnull, NS_ConvertUTF8toUTF16(spec).get());
        return rv;
    }

    rv = aCompiler->doneLoading();
    return rv;
}
Esempio n. 6
0
   void Walker::walkQualifiedNode(libember::glow::GlowQualifiedNode const* glow)
   {
      auto glowPath = glow->path();
      m_path.clear();
      m_path.insert(m_path.end(), glowPath.begin(), glowPath.end());

      handleNode(glow, glowPath);

      auto children = glow->children();

      if(children != nullptr)
         walkElements(children->begin(), children->end());

      m_path.clear();
   }
    bool run()
    {
        RELEASE_ASSERT(m_graph.m_form == SSA);
        
        for (BlockIndex blockIndex = m_graph.numBlocks(); blockIndex--;) {
            m_block = m_graph.block(blockIndex);
            if (!m_block)
                continue;
            for (m_nodeIndex = 0; m_nodeIndex < m_block->size(); ++m_nodeIndex) {
                m_node = m_block->at(m_nodeIndex);
                handleNode();
            }
            m_insertionSet.execute(m_block);
        }

        return true;
    }
Esempio n. 8
0
int main() {
	omp_init_lock(&total_market_write_lock);
	omp_init_lock(&jobs_lock);

	srand(0);

	int tickNum = 0;

	nodes.resize(100);
	for(int i = 0; i < 10000; i++) {
		Job* job = new Job();
		//job->assumed_correctness_sum = getRand(0.0f, 0.1f);
		jobs.insert(job);
	}

	std::cout << "Init done." << std::endl;

	FILE* pipe = _popen("\"C:/Program Files (x86)/gnuplot/bin/pgnuplot.exe\" -persist", "w");
	//fprintf(pipe, "set terminal png crop size 640,480\n");
	fprintf(pipe, "set terminal wx\n");
	fprintf(pipe, "set output \"%s\"\n", "output/output.png");
	fprintf(pipe, "plot '-' using 1:2 with lines \n");

	while(tickNum < 1000) {
#pragma omp parallel for
		for(int i = 0; i < nodes.size(); i++) {
			handleNode(&nodes[i]);
		}

		if((tickNum % 10) == 0) {
			fprintf(pipe, "%d %g\n", tickNum, nodes[0].getCorrectnessScaled());
			printf("%d\n", tickNum);
		}
		++tickNum;
	}

	fprintf(pipe, "e\n");
	fflush(pipe);
	_pclose(pipe);

	omp_destroy_lock(&total_market_write_lock);
	omp_destroy_lock(&jobs_lock);
}
 bool run()
 {
     ASSERT(m_graph.m_fixpointState == FixpointNotConverged);
     
     m_changed = false;
     
     for (BlockIndex blockIndex = m_graph.numBlocks(); blockIndex--;) {
         m_block = m_graph.block(blockIndex);
         if (!m_block)
             continue;
         for (m_nodeIndex = 0; m_nodeIndex < m_block->size(); ++m_nodeIndex) {
             m_node = m_block->at(m_nodeIndex);
             handleNode();
         }
         m_insertionSet.execute(m_block);
     }
     
     return m_changed;
 }
void SceneSerializer::handleNode(const Value& entries, SceneNode* node) {
    handleNodeProperties(entries, node);
    
    // Then recursively handle scene objects and scenen nodes.
    for (Value::ConstMemberIterator entryIter = entries.MemberBegin();
         entryIter != entries.MemberEnd(); ++entryIter) {
        const Value& entryKey = entryIter->name;
        const Value& entryValue = entryIter->value;
        assert(entryKey.IsString());
        
        string key = entryKey.GetString();
        if (key == kEntityKey) {
            handleEntity(entryValue, createChildSceneNode(node, entryValue));
        } else if (key == kEntityGroupKey) {
            handleNode(entryValue, createChildSceneNode(node, entryValue));
        } else if (key == kIncludeKey) {
            assert(entryValue.IsString());
            handleInclude(entryValue.GetString(), kDefaultSceneNodeClass,
                          createChildSceneNodeWithNameSuffix(node, ""));
        } else if (key == kCameraKey) {
            if (entryValue.IsObject()) {
                handleCamera(entryValue, createChildSceneNode(node, entryValue));
            } else if (entryValue.IsString()) {
                // This is not a camera definition, but a referance to a camera.
                string cameraName = entryValue.GetString();
                node->addVisibleCamera(cameraName);
                Camera* camera = mSceneMgr->getCamera(cameraName);
                assert(camera != NULL && "Error: camera is null. "
                       "Please define camera before using to it.");
                getDefaultViewport()->addCamera(camera);
                
            }
        } else {
            // Assume it is a simple node property and it has been handled.
        }
    }
}
Esempio n. 11
0
bool Model::loadFromFile(const std::string& filename)
{
    Assimp::Importer importer;


	std::string strModelsResourcesFolder = "Data/Resources/Models/";

	std::string strModelFinalFilename = strModelsResourcesFolder + filename;

    // Component to be removed when importing file
    importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS,
                                aiComponent_COLORS
//                                | aiComponent_TANGENTS_AND_BITANGENTS
                                | aiComponent_BONEWEIGHTS
                                | aiComponent_ANIMATIONS
                                | aiComponent_LIGHTS
                                | aiComponent_CAMERAS);
    importer.SetPropertyInteger(AI_CONFIG_PP_PTV_NORMALIZE, 1);

    // And have it read the given file with some example postprocessing
    // Usually - if speed is not the most important aspect for you - you'll
    // propably to request more postprocessing than we do in this example.
	const aiScene* scene = importer.ReadFile(strModelFinalFilename,
        aiProcess_Triangulate
        | aiProcess_JoinIdenticalVertices
        | aiProcess_RemoveComponent
        | aiProcess_GenNormals
        | aiProcess_CalcTangentSpace
        | aiProcess_PreTransformVertices
        //| aiProcess_GenUVCoords
        //| aiProcess_MakeLeftHanded
    );


//    const aiScene* scene = importer.ReadFile( filename,
//                                              aiProcessPreset_TargetRealtime_MaxQuality
//    );

    // If the import failed, report it
    if( !scene)
    {
        std::cerr << importer.GetErrorString() << '\n';
        return false;
    }    

    m_nodes.clear();

    aiNode* rootNode = scene->mRootNode;

    handleNode(rootNode, aiMatrix4x4());

    m_meshes.clear();
    m_meshes.resize(scene->mNumMeshes);

    m_materials.clear();
    //m_materials.resize(scene->mNumMaterials);

    //std::string dir = filename;

    //size_t lastSeparator = dir.find_last_of('/');

    //if (lastSeparator != std::string::npos) {
    //    dir.erase(lastSeparator, dir.size());
    //}
    //else {
    //    dir = std::string(".");
    //}

    for (unsigned int i = 0; i < scene->mNumMeshes; ++i) {
        m_meshes[i].loadFromAssimpMesh(scene->mMeshes[i]);
    }

    //for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
    //    m_materials[i].loadFromAssimpMaterial(scene->mMaterials[i], dir);
    //}

//    const aiMesh* mesh = scene->mMeshes[0];

//    std::cerr << "Mesh HasFaces ? " << mesh->HasFaces() << '\n';
//    std::cerr << "Mesh HasNormals ? " << mesh->HasNormals() << '\n';
//    std::cerr << "Mesh HasPositions ? " << mesh->HasPositions() << '\n';
//    std::cerr << "Mesh HasTangentsAndBitangents ? " << mesh->HasTangentsAndBitangents() << '\n';
//    std::cerr << "Mesh HasBones ? " << mesh->HasBones() << '\n';
//    std::cerr << "Mesh HasTextureCoords ? " << mesh->HasTextureCoords(0) << '\n';
//    std::cerr << "mesh->mTextureCoords[0] != NULL ? " << (mesh->mTextureCoords[0] != NULL) << '\n';
//    std::cerr << "Mesh GetNumUVChannels ? " << mesh->GetNumUVChannels() << '\n';
//    std::cerr << "Mesh GetNumColorChannels ? " << mesh->GetNumColorChannels() << '\n';
//    std::cerr << "Mesh mNumFaces ? " << mesh->mNumFaces << '\n';
//    std::cerr << "Mesh mNumVertices ? " << mesh->mNumVertices << '\n';
//    std::cerr << "Mesh mPrimitiveTypes ? " << mesh->mPrimitiveTypes << " and should be " << aiPrimitiveType_TRIANGLE << '\n';

    return true;
}
Node *
ColladaNode::createInstanceJoint(ColladaInstInfo *colInstInfo, domNode *node)
{
    NodeUnrecPtr retVal    = NULL;
    bool         startSkel = false;

    // if there is a ColladaInstanceElement someone tried to use <instance_node>
    // with this joint as target - this is currently not supported
    if(colInstInfo->getColInst() != NULL)
    {
        SWARNING << "ColladaNode::createInstanceJoint: <instance_node> with "
                 << "target <node> of type JOINT not supported." << std::endl;
        return retVal;
    }

    NodeLoaderState *state =
        getGlobal()->getLoaderStateAs<NodeLoaderState>(_loaderStateName);
    OSG_ASSERT(state != NULL);

    state->pushNodePath(node->getId() != NULL ? node->getId() : "");
    state->dumpNodePath();

    InstData instData;
    instData._nodePath = state->getNodePath();
    instData._skel     = state->getSkeleton();

    if(instData._skel == NULL)
    {
        startSkel      = true;
        instData._skel = Skeleton::create();

        state->setSkeleton(instData._skel);
        state->setJointId (0             );

        OSG_COLLADA_LOG(("ColladaNode::createInstanceJoint: id [%s] "
                         "root joint\n", node->getId()));
    }
    else
    {
        state->setJointId(state->getJointId() + 1);

        OSG_COLLADA_LOG(("ColladaNode::createInstanceJoint: id [%s] "
                         "joint [%d]\n", node->getId(), state->getJointId()));
    }

    const daeElementRefArray &contents = node->getContents();

    for(UInt32 i = 0; i < contents.getCount(); ++i)
    {
        switch(contents[i]->getElementType())
        {
        case COLLADA_TYPE::LOOKAT:
            handleLookAt(daeSafeCast<domLookat>(contents[i]), instData);
            break;

        case COLLADA_TYPE::MATRIX:
            handleMatrix(daeSafeCast<domMatrix>(contents[i]), instData);
            break;

        case COLLADA_TYPE::ROTATE:
            handleRotate(daeSafeCast<domRotate>(contents[i]), instData);
            break;

        case COLLADA_TYPE::SCALE:
            handleScale(daeSafeCast<domScale>(contents[i]), instData);
            break;

        case COLLADA_TYPE::SKEW:
            handleSkew(daeSafeCast<domSkew>(contents[i]), instData);
            break;

        case COLLADA_TYPE::TRANSLATE:
            handleTranslate(daeSafeCast<domTranslate>(contents[i]), instData);
            break;
        }
    }

    // assert top and bottom are both set or both unset
    OSG_ASSERT((instData._topN != NULL && instData._bottomN != NULL) ||
               (instData._topN == NULL && instData._bottomN == NULL)   );

    if(instData._topN == NULL && instData._bottomN == NULL)
    {
        // no xforms were created, make a SkeletonJoint for this <node>

        SkeletonJointUnrecPtr joint = SkeletonJoint::create();

        joint->setJointId(state->getJointId());

        instData._topN    = makeNodeFor(joint);
        instData._bottomN = instData._topN;

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(instData._topN, node->getName());
        }
    }
    else if(getGlobal()->getOptions()->getMergeTransforms() == false)
    {
        // when not merging transforms add SkeletonJoint core now

        SkeletonJointUnrecPtr joint  = SkeletonJoint::create();
        NodeUnrecPtr          jointN = makeNodeFor(joint);

        joint->setJointId(state->getJointId());

        instData._bottomN->addChild(jointN);
        instData._bottomN = jointN;
    }

    if(startSkel == true)
    {
        // add a transform for the world matrix up to this node to put
        // the Skeleton in the correct coordinate system

        TransformUnrecPtr xform  = Transform::create();
        NodeUnrecPtr      xformN = makeNodeFor(xform);

        xform->setMatrix(state->getWorldMatrix());

        xformN->addChild(instData._topN);
        instData._topN = xformN;

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true)
            setName(xformN, "SkeletonWorldMatrix");
    }

    // update world matrix before we instantiate child nodes, etc.
    state->pushMatrix(instData._localMatrix);

    // add <node> child elements
    const domNode_Array &nodes = node->getNode_array();

    for(UInt32 i = 0; i < nodes.getCount(); ++i)
        handleNode(nodes[i], instData);

    // add <instance_node> child elements
    const domInstance_node_Array &instNodes =
        node->getInstance_node_array();

    for(UInt32 i = 0; i < instNodes.getCount(); ++i)
        handleInstanceNode(instNodes[i], instData);

    // we don't handle other <instance_*> tags here, it does not
    // make sense to have them inside a skeleton

    editInstStore().push_back(instData._topN);
    _instDataStore .push_back(instData      );
    retVal = instData._topN;

    if(startSkel == true)
    {
        instData._skel->pushToRoots(instData._topN);

        state->setSkeleton(NULL);
        state->setJointId (SkeletonJoint::INVALID_JOINT_ID);
    }

    state->popMatrix  ();
    state->popNodePath();

    return retVal;
}
Node *
ColladaNode::createInstanceNode(ColladaInstInfo *colInstInfo, domNode *node)
{
    OSG_COLLADA_LOG(("ColladaNode::createInstanceNode id [%s]\n",
                     node->getId()));

    NodeLoaderState *state =
        getGlobal()->getLoaderStateAs<NodeLoaderState>(_loaderStateName);
    OSG_ASSERT(state != NULL);

    state->pushNodePath(node->getId() != NULL ? node->getId() : "");
    state->dumpNodePath();

    NodeUnrecPtr retVal = NULL;
    InstData     instData;

    instData._nodePath = state->getNodePath();
    const daeElementRefArray &contents = node->getContents();

    // read "transform" child elements in the order
    // they occur in the document
    for(UInt32 i = 0; i < contents.getCount(); ++i)
    {
        switch(contents[i]->getElementType())
        {
        case COLLADA_TYPE::LOOKAT:
            handleLookAt(daeSafeCast<domLookat>(contents[i]), instData);
            break;

        case COLLADA_TYPE::MATRIX:
            handleMatrix(daeSafeCast<domMatrix>(contents[i]), instData);
            break;

        case COLLADA_TYPE::ROTATE:
            handleRotate(daeSafeCast<domRotate>(contents[i]), instData);
            break;

        case COLLADA_TYPE::SCALE:
            handleScale(daeSafeCast<domScale>(contents[i]), instData);
            break;

        case COLLADA_TYPE::SKEW:
            handleSkew(daeSafeCast<domSkew>(contents[i]), instData);
            break;

        case COLLADA_TYPE::TRANSLATE:
            handleTranslate(daeSafeCast<domTranslate>(contents[i]), instData);
            break;
        }
    }

    // assert top and bottom are both set or both unset
    OSG_ASSERT((instData._topN != NULL && instData._bottomN != NULL) ||
               (instData._topN == NULL && instData._bottomN == NULL)   );

    // if no xforms were created make a group for this <node>
    if(instData._topN == NULL && instData._bottomN == NULL)
    {
        instData._topN    = makeCoredNode<Group>();
        instData._bottomN = instData._topN;

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(instData._topN, node->getName());
        }
    }

    // update world matrix before we instantiate child nodes, etc.
    state->pushMatrix(instData._localMatrix);

    // add <node> child elements
    const domNode_Array &nodes = node->getNode_array();

    for(UInt32 i = 0; i < nodes.getCount(); ++i)
        handleNode(nodes[i], instData);

    // add <instance_node> child elements
    const domInstance_node_Array &instNodes =
        node->getInstance_node_array();

    for(UInt32 i = 0; i < instNodes.getCount(); ++i)
        handleInstanceNode(instNodes[i], instData);

    // add <instance_light> child elements
    const domInstance_light_Array &instLights =
        node->getInstance_light_array();

    for(UInt32 i = 0; i < instLights.getCount(); ++i)
        handleInstanceLight(instLights[i], instData);

    // add <instance_geometry> child elements
    const domInstance_geometry_Array &instGeos =
        node->getInstance_geometry_array();

    for(UInt32 i = 0; i < instGeos.getCount(); ++i)
        handleInstanceGeometry(instGeos[i], instData);

    // add <instance_controller> child elemnts
    const domInstance_controller_Array &instControllers =
        node->getInstance_controller_array();

    for(UInt32 i = 0; i < instControllers.getCount(); ++i)
        handleInstanceController(instControllers[i], instData);

    editInstStore().push_back(instData._topN);
    _instDataStore .push_back(instData      );
    retVal = instData._topN;

    state->popMatrix  ();
    state->popNodePath();

    return retVal;
}
Esempio n. 14
0
osg::ref_ptr<Resource::BulletShape> BulletNifLoader::load(const Nif::File& nif)
{
    mShape = new Resource::BulletShape;

    mCompoundShape.reset();
    mStaticMesh.reset();
    mAvoidStaticMesh.reset();

    if (nif.numRoots() < 1)
    {
        warn("Found no root nodes in NIF.");
        return mShape;
    }

    Nif::Record *r = nif.getRoot(0);
    assert(r != nullptr);

    Nif::Node *node = dynamic_cast<Nif::Node*>(r);
    if (node == nullptr)
    {
        warn("First root in file was not a node, but a " +
             r->recName + ". Skipping file.");
        return mShape;
    }

    if (findBoundingBox(node))
    {
        std::unique_ptr<btCompoundShape> compound (new btCompoundShape);

        std::unique_ptr<btBoxShape> boxShape(new btBoxShape(getbtVector(mShape->mCollisionBoxHalfExtents)));
        btTransform transform = btTransform::getIdentity();
        transform.setOrigin(getbtVector(mShape->mCollisionBoxTranslate));
        compound->addChildShape(transform, boxShape.get());
        boxShape.release();

        mShape->mCollisionShape = compound.release();
        return mShape;
    }
    else
    {
        bool autogenerated = hasAutoGeneratedCollision(node);

        // files with the name convention xmodel.nif usually have keyframes stored in a separate file xmodel.kf (see Animation::addAnimSource).
        // assume all nodes in the file will be animated
        const auto filename = nif.getFilename();
        const bool isAnimated = pathFileNameStartsWithX(filename);

        handleNode(filename, node, 0, autogenerated, isAnimated, autogenerated);

        if (mCompoundShape)
        {
            if (mStaticMesh)
            {
                btTransform trans;
                trans.setIdentity();
                std::unique_ptr<btCollisionShape> child(new Resource::TriangleMeshShape(mStaticMesh.get(), true));
                mCompoundShape->addChildShape(trans, child.get());
                child.release();
                mStaticMesh.release();
            }
            mShape->mCollisionShape = mCompoundShape.release();
        }
        else if (mStaticMesh)
        {
            mShape->mCollisionShape = new Resource::TriangleMeshShape(mStaticMesh.get(), true);
            mStaticMesh.release();
        }

        if (mAvoidStaticMesh)
        {
            mShape->mAvoidCollisionShape = new Resource::TriangleMeshShape(mAvoidStaticMesh.get(), false);
            mAvoidStaticMesh.release();
        }

        return mShape;
    }
}
Esempio n. 15
0
void BulletNifLoader::handleNode(const std::string& fileName, const Nif::Node *node, int flags,
        bool isCollisionNode, bool isAnimated, bool autogenerated, bool avoid)
{
    // Accumulate the flags from all the child nodes. This works for all
    // the flags we currently use, at least.
    flags |= node->flags;

    if (!node->controller.empty() && node->controller->recType == Nif::RC_NiKeyframeController
            && (node->controller->flags & Nif::NiNode::ControllerFlag_Active))
        isAnimated = true;

    isCollisionNode = isCollisionNode || (node->recType == Nif::RC_RootCollisionNode);

    // Don't collide with AvoidNode shapes
    avoid = avoid || (node->recType == Nif::RC_AvoidNode);

    // We encountered a RootCollisionNode inside autogenerated mesh. It is not right.
    if (node->recType == Nif::RC_RootCollisionNode && autogenerated)
        Log(Debug::Info) << "Found RootCollisionNode attached to non-root node in " << fileName << ". Treat it as a common NiTriShape.";

    // Check for extra data
    Nif::Extra const *e = node;
    while (!e->extra.empty())
    {
        // Get the next extra data in the list
        e = e->extra.getPtr();
        assert(e != nullptr);

        if (e->recType == Nif::RC_NiStringExtraData)
        {
            // String markers may contain important information
            // affecting the entire subtree of this node
            Nif::NiStringExtraData *sd = (Nif::NiStringExtraData*)e;

            if (Misc::StringUtils::ciCompareLen(sd->string, "NC", 2) == 0)
            {
                // No collision. Use an internal flag setting to mark this.
                flags |= 0x800;
            }
            else if (sd->string == "MRK" && autogenerated)
            {
                // Marker can still have collision if the model explicitely specifies it via a RootCollisionNode.
                return;
            }

        }
    }

    if (isCollisionNode)
    {
        // NOTE: a trishape with hasBounds=true, but no BBoxCollision flag should NOT go through handleNiTriShape!
        // It must be ignored completely.
        // (occurs in tr_ex_imp_wall_arch_04.nif)
        if(!node->hasBounds && node->recType == Nif::RC_NiTriShape)
        {
            handleNiTriShape(static_cast<const Nif::NiTriShape*>(node), flags, getWorldTransform(node), isAnimated, avoid);
        }
    }

    // For NiNodes, loop through children
    const Nif::NiNode *ninode = dynamic_cast<const Nif::NiNode*>(node);
    if(ninode)
    {
        const Nif::NodeList &list = ninode->children;
        for(size_t i = 0;i < list.length();i++)
        {
            if(!list[i].empty())
                handleNode(fileName, list[i].getPtr(), flags, isCollisionNode, isAnimated, autogenerated, avoid);
        }
    }
}
Esempio n. 16
0
void ManualBulletShapeLoader::loadResource(Ogre::Resource *resource)
{
    cShape = static_cast<OEngine::Physic::BulletShape *>(resource);
    resourceName = cShape->getName();
    cShape->mCollide = false;
    mBoundingBox = NULL;
    cShape->boxTranslation = Ogre::Vector3(0,0,0);
    cShape->boxRotation = Ogre::Quaternion::IDENTITY;

    mTriMesh = new btTriangleMesh();

    // Load the NIF. TODO: Wrap this in a try-catch block once we're out
    // of the early stages of development. Right now we WANT to catch
    // every error as early and intrusively as possible, as it's most
    // likely a sign of incomplete code rather than faulty input.
    Nif::NIFFile::ptr pnif (Nif::NIFFile::create (resourceName.substr(0, resourceName.length()-7)));
    Nif::NIFFile & nif = *pnif.get ();
    if (nif.numRecords() < 1)
    {
        warn("Found no records in NIF.");
        return;
    }

    // The first record is assumed to be the root node
    Nif::Record *r = nif.getRecord(0);
    assert(r != NULL);

    Nif::Node *node = dynamic_cast<Nif::Node*>(r);
    if (node == NULL)
    {
        warn("First record in file was not a node, but a " +
                r->recName + ". Skipping file.");
        return;
    }

    bool hasCollisionNode = hasRootCollisionNode(node);

    //do a first pass
    handleNode(node,0,hasCollisionNode,false,false);

    //if collide = false, then it does a second pass which create a shape for raycasting.
    if(cShape->mCollide == false)
        handleNode(node,0,hasCollisionNode,false,true);

    //cShape->collide = hasCollisionNode&&cShape->collide;

    struct TriangleMeshShape : public btBvhTriangleMeshShape
    {
        TriangleMeshShape(btStridingMeshInterface* meshInterface, bool useQuantizedAabbCompression)
            : btBvhTriangleMeshShape(meshInterface, useQuantizedAabbCompression)
        {
        }

        virtual ~TriangleMeshShape()
        {
            delete getTriangleInfoMap();
            delete m_meshInterface;
        }
    };

    if(mBoundingBox != NULL)
       cShape->Shape = mBoundingBox;
    else
    {
        currentShape = new TriangleMeshShape(mTriMesh,true);
        cShape->Shape = currentShape;
    }
}
/**
 * handling DOM->txStylesheet
 * Observer needs to do synchronous loads.
 */
static nsresult
handleNode(nsINode* aNode, txStylesheetCompiler* aCompiler)
{
    nsresult rv = NS_OK;
    
    if (aNode->IsNodeOfType(nsINode::eELEMENT)) {
        nsIContent* element = static_cast<nsIContent*>(aNode);

        PRUint32 attsCount = element->GetAttrCount();
        nsAutoArrayPtr<txStylesheetAttr> atts;
        if (attsCount > 0) {
            atts = new txStylesheetAttr[attsCount];
            NS_ENSURE_TRUE(atts, NS_ERROR_OUT_OF_MEMORY);

            PRUint32 counter;
            for (counter = 0; counter < attsCount; ++counter) {
                txStylesheetAttr& att = atts[counter];
                const nsAttrName* name = element->GetAttrNameAt(counter);
                att.mNamespaceID = name->NamespaceID();
                att.mLocalName = name->LocalName();
                att.mPrefix = name->GetPrefix();
                element->GetAttr(att.mNamespaceID, att.mLocalName, att.mValue);
            }
        }

        nsINodeInfo *ni = element->NodeInfo();

        rv = aCompiler->startElement(ni->NamespaceID(),
                                     ni->NameAtom(),
                                     ni->GetPrefixAtom(), atts,
                                     attsCount);
        NS_ENSURE_SUCCESS(rv, rv);

        // explicitly destroy the attrs here since we no longer need it
        atts = nsnull;

        PRUint32 childCount = element->GetChildCount();
        if (childCount > 0) {
            PRUint32 counter = 0;
            nsIContent *child;
            while ((child = element->GetChildAt(counter++))) {
                rv = handleNode(child, aCompiler);
                NS_ENSURE_SUCCESS(rv, rv);
            }
        }

        rv = aCompiler->endElement();
        NS_ENSURE_SUCCESS(rv, rv);
    }
    else if (aNode->IsNodeOfType(nsINode::eTEXT)) {
        nsAutoString chars;
        static_cast<nsIContent*>(aNode)->AppendTextTo(chars);
        rv = aCompiler->characters(chars);
        NS_ENSURE_SUCCESS(rv, rv);
    }
    else if (aNode->IsNodeOfType(nsINode::eDOCUMENT)) {
        nsIDocument* document = static_cast<nsIDocument*>(aNode);

        PRUint32 counter = 0;
        nsIContent *child;
        while ((child = document->GetChildAt(counter++))) {
            rv = handleNode(child, aCompiler);
            NS_ENSURE_SUCCESS(rv, rv);
        }
    }

    return NS_OK;
}
Esempio n. 18
0
void DOMSerializer::serialize(const Node* pNode)
{
	poco_check_ptr (pNode);

	handleNode(pNode);
}
osg::ref_ptr<Resource::BulletShape> BulletNifLoader::load(const Nif::NIFFilePtr& nif)
{
    mShape = new Resource::BulletShape;

    mCompoundShape = NULL;
    mStaticMesh = NULL;

    if (nif->numRoots() < 1)
    {
        warn("Found no root nodes in NIF.");
        return mShape;
    }

    Nif::Record *r = nif->getRoot(0);
    assert(r != NULL);

    Nif::Node *node = dynamic_cast<Nif::Node*>(r);
    if (node == NULL)
    {
        warn("First root in file was not a node, but a " +
             r->recName + ". Skipping file.");
        return mShape;
    }

    if (findBoundingBox(node))
    {
        std::unique_ptr<btCompoundShape> compound (new btCompoundShape);

        btBoxShape* boxShape = new btBoxShape(getbtVector(mShape->mCollisionBoxHalfExtents));
        btTransform transform = btTransform::getIdentity();
        transform.setOrigin(getbtVector(mShape->mCollisionBoxTranslate));
        compound->addChildShape(transform, boxShape);

        mShape->mCollisionShape = compound.release();
        return mShape;
    }
    else
    {
        bool autogenerated = hasAutoGeneratedCollision(node);
        bool isAnimated = false;

        // files with the name convention xmodel.nif usually have keyframes stored in a separate file xmodel.kf (see Animation::addAnimSource).
        // assume all nodes in the file will be animated
        std::string filename = nif->getFilename();
        size_t slashpos = filename.find_last_of("/\\");
        if (slashpos == std::string::npos)
            slashpos = 0;
        if (slashpos+1 < filename.size() && (filename[slashpos+1] == 'x' || filename[slashpos+1] == 'X'))
        {
            isAnimated = true;
        }

        handleNode(node, 0, autogenerated, isAnimated, autogenerated);

        if (mCompoundShape)
        {
            mShape->mCollisionShape = mCompoundShape;
            if (mStaticMesh)
            {
                btTransform trans;
                trans.setIdentity();
                mCompoundShape->addChildShape(trans, new Resource::TriangleMeshShape(mStaticMesh,true));
            }
        }
        else if (mStaticMesh)
            mShape->mCollisionShape = new Resource::TriangleMeshShape(mStaticMesh,true);

        return mShape;
    }
}
void SceneSerializer::importSceneDOM(DataStream & stream, SceneNode* node) {
    Document doc;
    doc.Parse<0>(stream.getData());
    assert(doc.IsObject() && "Error: Invalid scene description file found. Please check the correctness of the syntax.\n");
    handleNode(doc, node);
}
void
ColladaNode::read(void)
{
    OSG_COLLADA_LOG(("ColladaNode::read\n"));

    domNodeRef                node     = getDOMElementAs<domNode>();
    const daeElementRefArray &contents = node->getContents();

    // handle "transform" child elements in the order
    // they occur in the document

    for(UInt32 i = 0; i < contents.getCount(); ++i)
    {
        switch(contents[i]->getElementType())
        {
        case COLLADA_TYPE::LOOKAT:
            handleLookAt(daeSafeCast<domLookat>(contents[i]));
            break;
            
        case COLLADA_TYPE::MATRIX:
            handleMatrix(daeSafeCast<domMatrix>(contents[i]));
        break;
        
        case COLLADA_TYPE::ROTATE:
            handleRotate(daeSafeCast<domRotate>(contents[i]));
        break;
        
        case COLLADA_TYPE::SCALE:
            handleScale(daeSafeCast<domScale>(contents[i]));
        break;
        
        case COLLADA_TYPE::SKEW:
            handleSkew(daeSafeCast<domSkew>(contents[i]));
        break;
        
        case COLLADA_TYPE::TRANSLATE:
            handleTranslate(daeSafeCast<domTranslate>(contents[i]));
        break;
        }
    }

    // handle <node> child elements
    const domNode_Array &nodes = node->getNode_array();
    
    for(UInt32 i = 0; i < nodes.getCount(); ++i)
    {
        handleNode(nodes[i]);
    }

    // handle <instance_node> child elements
    const domInstance_node_Array &instNodes = node->getInstance_node_array();
    
    for(UInt32 i = 0; i < instNodes.getCount(); ++i)
    {
        handleInstanceNode(instNodes[i]);
    }

    // handle <instance_light> child elements
    const domInstance_light_Array &instLights = node->getInstance_light_array();
    for(UInt32 i = 0; i < instLights.getCount(); ++i)
    {
        handleInstanceLight(instLights[i]);
    }

    // handle <instance_geometry> child elements
    const domInstance_geometry_Array &instGeos =
        node->getInstance_geometry_array();

    for(UInt32 i = 0; i < instGeos.getCount(); ++i)
    {
        handleInstanceGeometry(instGeos[i]);
    }

    // handle <instance_controller> child elemnts
    const domInstance_controller_Array &instControllers =
        node->getInstance_controller_array();

    for(UInt32 i = 0; i < instControllers.getCount(); ++i)
    {
        handleInstanceController(instControllers[i]);
    }

    // nothing created? build a dummy node
    if(_topN == NULL)
    {
        _topN = makeCoredNode<Group>();

        if(getGlobal()->getOptions()->getCreateNameAttachments() == true &&
           node->getName()                                       != NULL   )
        {
            setName(_topN, node->getName());
        }
    }

    if(_bottomN == NULL)
    {
        _bottomN = _topN;
    }
}
Esempio n. 22
0
void ManualBulletShapeLoader::handleNode(const Nif::Node *node, int flags,
                                         bool hasCollisionNode, bool isCollisionNode,
                                         bool raycastingOnly)
{
    // Accumulate the flags from all the child nodes. This works for all
    // the flags we currently use, at least.
    flags |= node->flags;

    isCollisionNode = isCollisionNode || (node->recType == Nif::RC_RootCollisionNode);

    // Marker objects: no collision
    /// \todo don't do this in the editor
    if (node->name.find("marker") != std::string::npos)
    {
        flags |= 0x800;
        cShape->mIgnore = true;
    }

    // Check for extra data
    Nif::Extra const *e = node;
    while (!e->extra.empty())
    {
        // Get the next extra data in the list
        e = e->extra.getPtr();
        assert(e != NULL);

        if (e->recType == Nif::RC_NiStringExtraData)
        {
            // String markers may contain important information
            // affecting the entire subtree of this node
            Nif::NiStringExtraData *sd = (Nif::NiStringExtraData*)e;

            // not sure what the difference between NCO and NCC is, or if there even is one
            if (sd->string == "NCO" || sd->string == "NCC")
            {
                // No collision. Use an internal flag setting to mark this.
                flags |= 0x800;
            }
            else if (sd->string == "MRK" && !raycastingOnly)
                // Marker objects. These are only visible in the
                // editor. Until and unless we add an editor component to
                // the engine, just skip this entire node.
                return;
        }
    }

    if(!hasCollisionNode || isCollisionNode)
    {
        if(node->hasBounds)
        {
            cShape->boxTranslation = node->boundPos;
            cShape->boxRotation = node->boundRot;
            mBoundingBox = new btBoxShape(getbtVector(node->boundXYZ));
        }

        if(node->recType == Nif::RC_NiTriShape)
        {
            cShape->mCollide = !(flags&0x800);
            handleNiTriShape(static_cast<const Nif::NiTriShape*>(node), flags, node->getWorldTransform(), raycastingOnly);
        }
    }

    // For NiNodes, loop through children
    const Nif::NiNode *ninode = dynamic_cast<const Nif::NiNode*>(node);
    if(ninode)
    {
        const Nif::NodeList &list = ninode->children;
        for(size_t i = 0;i < list.length();i++)
        {
            if(!list[i].empty())
                handleNode(list[i].getPtr(), flags, hasCollisionNode, isCollisionNode, raycastingOnly);
        }
    }
}
nsresult
TX_CompileStylesheet(nsINode* aNode, txMozillaXSLTProcessor* aProcessor,
                     nsIPrincipal* aCallerPrincipal,
                     txStylesheet** aStylesheet)
{
    // If we move GetBaseURI to nsINode this can be simplified.
    nsCOMPtr<nsIDocument> doc = aNode->GetOwnerDoc();
    NS_ENSURE_TRUE(doc, NS_ERROR_FAILURE);

    nsCOMPtr<nsIURI> uri;
    if (aNode->IsNodeOfType(nsINode::eCONTENT)) {
      uri = static_cast<nsIContent*>(aNode)->GetBaseURI();
    }
    else { 
      NS_ASSERTION(aNode->IsNodeOfType(nsINode::eDOCUMENT), "not a doc");
      uri = static_cast<nsIDocument*>(aNode)->GetBaseURI();
    }
    NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);
    
    nsCAutoString spec;
    uri->GetSpec(spec);
    NS_ConvertUTF8toUTF16 baseURI(spec);

    nsIURI* docUri = doc->GetDocumentURI();
    NS_ENSURE_TRUE(docUri, NS_ERROR_FAILURE);

    docUri->Clone(getter_AddRefs(uri));
    NS_ENSURE_TRUE(uri, NS_ERROR_FAILURE);

    // We need to remove the ref, a URL with a ref would mean that we have an
    // embedded stylesheet.
    nsCOMPtr<nsIURL> url = do_QueryInterface(uri);
    if (url) {
        url->SetRef(EmptyCString());
    }

    uri->GetSpec(spec);
    NS_ConvertUTF8toUTF16 stylesheetURI(spec);

    nsRefPtr<txSyncCompileObserver> obs =
        new txSyncCompileObserver(aProcessor);
    NS_ENSURE_TRUE(obs, NS_ERROR_OUT_OF_MEMORY);

    nsRefPtr<txStylesheetCompiler> compiler =
        new txStylesheetCompiler(stylesheetURI, obs);
    NS_ENSURE_TRUE(compiler, NS_ERROR_OUT_OF_MEMORY);

    compiler->setBaseURI(baseURI);

    nsresult rv = handleNode(aNode, compiler);
    if (NS_FAILED(rv)) {
        compiler->cancel(rv);
        return rv;
    }

    rv = compiler->doneLoading();
    NS_ENSURE_SUCCESS(rv, rv);
    
    *aStylesheet = compiler->getStylesheet();
    NS_ADDREF(*aStylesheet);

    return NS_OK;
}