Exemplo n.º 1
0
//-------------------------------------------------------------------------------------------
void MagickWidget::loadMesh(Ogre::MeshPtr pMesh)
{
    QString directory(OgitorsRoot::getSingletonPtr()->GetProjectOptions()->ProjectDir.c_str());
    if(directory.isEmpty())
        directory = "./";

    QDir(directory).mkpath("entitycache");

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "MeshMagickTex", 
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, 
                   512, 512, 0, Ogre::PF_R8G8B8A8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "MeshMagickTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("MeshMagickCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0));

    Ogre::Entity *mEntity;

    mEntity = mSceneMgr->createEntity("scbDisplay", pMesh->getName());
    mSceneMgr->getRootSceneNode()->attachObject(mEntity);

    Ogre::Vector3 vSize = mEntity->getBoundingBox().getHalfSize();
    Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter(); 
    
    vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

    float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);
    
    vSize = Ogre::Vector3(0, 0, maxsize * 1.15f) + vCenter;
    
    RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
    RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

    rttTex->update();
    Ogre::String imagefile = OgitorsUtils::QualifyPath(directory.toStdString() + "/entitycache/meshmagick.png");
    rttTex->writeContentsToFile(imagefile);

    mEntity->detachFromParent();
    mSceneMgr->destroyEntity(mEntity);
    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    mDisplayWidget->setImage(QString(imagefile.c_str()));
}
void CSceneEditorView::OnEditsceneAddentity()
{
	CEntityCreatorDlg EntityCreatorDlg;

	if (IDOK == EntityCreatorDlg.DoModal())
	{
		HTREEITEM Selected = m_SceneManagerDlg->m_SceneTree.GetSelectedItem();
		m_SceneManagerDlg->m_SceneTree.InsertItem(EntityCreatorDlg.m_EntityName, Selected);
		
		Ogre::String SceneNodeName = m_SceneManagerDlg->m_SceneTree.GetItemText(Selected);
		Ogre::Entity *Entity = m_SceneManager->createEntity(Ogre::String(EntityCreatorDlg.m_EntityName), Ogre::String(EntityCreatorDlg.m_MeshName));
		Ogre::SceneNode *SceneNode = m_SceneManager->getSceneNode(SceneNodeName);
		SceneNode->attachObject(Entity);
	
		Ogre::AxisAlignedBox Box = Entity->getBoundingBox();
		Ogre::Vector3 Center = Box.getCenter();
		m_Camera->lookAt(Center);

		m_SceneManagerDlg->m_SceneTree.Expand(Selected, TVE_EXPAND);
		
		if (m_Root != NULL)
		{
			m_Root->renderOneFrame();
		}
	}
}
Exemplo n.º 3
0
void VLogicModel::_updateBoundingBox()
{
    if (VNULL == mFullBoundingBox)
    {
        mFullBoundingBox = new Ogre::AxisAlignedBox();
    }

    mFullBoundingBox->setNull();

    for (VEntityMap::iterator itr = mEntities.begin(); itr != mEntities.end(); ++itr)
    {
        Ogre::Entity *entity = itr->second.mEntity;
        if (entity != VNULL)
        {
            mFullBoundingBox->merge(entity->getBoundingBox());
        }
    }

    VAttachedModelOriginSceneNodes::const_iterator itr = mAttachedModelOriginSceneNodes.begin();
    while (itr != mAttachedModelOriginSceneNodes.end())
    {
        if (itr->first)
        {
            mFullBoundingBox->merge(itr->first->_getFullBoundingBox());
        }

        ++itr;
    }
}
void InputGeometry::_calculateExtents()
{
	Ogre::Entity* ent = _sourceMeshes[0];
	Ogre::AxisAlignedBox sourceMeshBB = ent->getBoundingBox();
	Ogre::Matrix4 transform;
	transform = _referenceNode->_getFullTransform().inverse() * ent->getParentSceneNode()->_getFullTransform();
	sourceMeshBB.transform(transform);
	Ogre::Vector3 min = sourceMeshBB.getMinimum();
	Ogre::Vector3 max = sourceMeshBB.getMaximum();

	for(auto itr = _sourceMeshes.begin(); itr != _sourceMeshes.end(); ++itr)
	{
		Ogre::Entity* tmpEnt = *itr;

		transform = _referenceNode->_getFullTransform().inverse() * tmpEnt->getParentSceneNode()->_getFullTransform();

		sourceMeshBB = ent->getBoundingBox();
		sourceMeshBB.transform(transform);
		Ogre::Vector3 min2 = sourceMeshBB.getMinimum();
		if(min2.x < min.x)
            min.x = min2.x;
        if(min2.y < min.y)
            min.y = min2.y;
        if(min2.z < min.z)
            min.z = min2.z;

		Ogre::Vector3 max2 = sourceMeshBB.getMaximum();
		if(max2.x > max.x)
            max.x = max2.x;
        if(max2.y > max.y)
            max.y = max2.y;
        if(max2.z > max.z)
            max.z = max2.z;
	}

	if(!_boundMin)
	{
		_boundMin = new float[3];
	}
	if(!_boundMax)
	{
		_boundMax = new float[3];
	}
	Utility::vector3_toFloatPtr(min,_boundMin);
	Utility::vector3_toFloatPtr(max,_boundMax);
}
/* ----------------------------------------------------------------------- 
 | build bullet box shape
 | 
 | : default create 125 (5x5x5) dynamic object
   ----------------------------------------------------------------------- */
bool
buildBoxShapeArray(Ogre::SceneManager* sceneMgr, btDynamicsWorld* dynamicsWorld, btAlignedObjectArray<btCollisionShape*>& collisionShapes,
                   const btVector3& array_size, btScalar scale)
{
    btTransform startTransform;
    startTransform.setIdentity();

    btScalar mass(1.f);	
    btVector3 localInertia(0,0,0);	
    btBoxShape* colShape = new btBoxShape(btVector3(scale, scale, scale));
    btAssert(colShape);    
    colShape->calculateLocalInertia(mass,localInertia);
    collisionShapes.push_back(colShape);

    float start_x = - array_size.getX()/2;
    float start_y = array_size.getY();
    float start_z = - array_size.getZ()/2;

    int index = 0;
    for (int k=0;k<array_size.getY();k++)
    {
	    for (int i=0;i<array_size.getX();i++)
	    {
            for(int j=0;j<array_size.getZ();j++)
		    {
			    startTransform.setOrigin(scale * btVector3(
								    btScalar(2.0*i + start_x),
								    btScalar(20+2.0*k + start_y),
								    btScalar(2.0*j + start_z)));

			    //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
			    btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
			    btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);
			    btRigidBody* body = new btRigidBody(rbInfo);
                body->setContactProcessingThreshold(BT_LARGE_FLOAT);

                if (sceneMgr)
                {
                    Ogre::Entity* ent = sceneMgr->createEntity("ent_" + Ogre::StringConverter::toString(index++),"Barrel.mesh");

                    Ogre::SceneNode* node = sceneMgr->getRootSceneNode()->createChildSceneNode("node_box_" + Ogre::StringConverter::toString(index++));
                    node->attachObject(ent);
                    node->setPosition(startTransform.getOrigin().getX(), startTransform.getOrigin().getY(), startTransform.getOrigin().getZ());

                    const Ogre::AxisAlignedBox& aabb = ent->getBoundingBox();
                    const Ogre::Vector3& boxScale = (aabb.getMaximum() - aabb.getMinimum())/2.0f;
                    node->scale(scale/boxScale.x, scale/boxScale.y, scale/boxScale.z);

                    body->setUserPointer((void*)node);
                }

			    dynamicsWorld->addRigidBody(body);
		    }
	    }		
    }

    return true;
}
Exemplo n.º 6
0
Monster* MonsterFactory::createInstance(SceneManager* sceneMgr, Maze* maze, MonsterManager* monsterMgr)
{
	Ogre::SceneNode* monsterNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
	Ogre::Entity* entity = sceneMgr->createEntity(mParams["mesh"]);
	//entity->setCastShadows(true);
	monsterNode->attachObject(entity);
	Monster* mon;
	mon = new Monster(monsterNode, entity, maze, monsterMgr);
	if (mParams.find("radius") != mParams.end())
		mon->setRadius((float)atof(mParams["radius"].c_str()));

	if (mParams.find("blood") != mParams.end())
	{
		mon->setBlood((float)atof(mParams["blood"].c_str()));
		mon->setMaxBlood(mon->getBlood());
	}

	if (mParams.find("speed") != mParams.end())
		mon->setSpeed((float)atof(mParams["speed"].c_str()));

	if (mParams.find("spell") != mParams.end())
		mon->setType((mParams["spell"].c_str()));

	if (mParams.find("scale") != mParams.end())
	{
		float scale = (float)atof(mParams["scale"].c_str());
		mon->setScale(scale, scale, scale);
	}

	//mon->setScale(2, 2, 2);

	// 创建怪物头顶血条
	BillboardSet* healthHUD = sceneMgr->createBillboardSet();
	healthHUD->setMaterialName("Glass/Billboard");
	healthHUD->setDefaultWidth(100);
	healthHUD->setDefaultHeight(14);
	SceneNode* hudNode = monsterNode->createChildSceneNode();
	hudNode->attachObject(healthHUD);
	/*Billboard* b2 = healthHUD->createBillboard(0, entity->getBoundingBox().getSize().y, 0);
	b2->setColour(ColourValue::Black);*/
	Billboard* b = healthHUD->createBillboard(0, entity->getBoundingBox().getSize().y, 0);
	//b->setColour(ColourValue(0, 0.75f, 0));
	//b->setDimensions(96, 12);
	mon->setHealthHUD(healthHUD);

	// 测试粒子by kid
    Ogre::ParticleSystem* ps = sceneMgr->createParticleSystem(monsterNode->getName() + "frozen", "Glass/MonsterFrozen");
	monsterNode->attachObject(ps);
	ps->setVisible(false);
    ps = sceneMgr->createParticleSystem(monsterNode->getName() + "burn", "Glass/MonsterBurn");
	monsterNode->attachObject(ps);
	ps->setVisible(false);

	return mon;
}
Exemplo n.º 7
0
int Create_Static_Object::create(Ogre::SceneManager *mainSceneMgr) {
    if (meshName.empty() ) {
        std::cout << "Whoops, what do you think you're doing? You didn't give a mesh name!" << std::endl;
        return 0;
    }

    if (meshFile.empty() ) {
        std::cout << "Well what did you expect? There's no mesh file to load!" << std::endl;
        return 0;
    }

    Ogre::SceneNode *nodeStaticObject = mainSceneMgr->getRootSceneNode()->createChildSceneNode(meshName, location, rotation);
    Ogre::Entity *entityStaticObject = mainSceneMgr->createEntity(meshName, meshFile);

    if (!materialName.empty() ){
        entityStaticObject->setMaterialName(materialName);
    }

    entityStaticObject->setCastShadows(shadow);

    nodeStaticObject->attachObject(entityStaticObject);
    nodeStaticObject->showBoundingBox(showBBox);
    nodeStaticObject->scale(scale);

    //Create the ground shape.
    BtOgre::StaticMeshToShapeConverter ogreBulletShapeConverter(entityStaticObject);
    if (bulletCollision == "sphere"){
        shapeStaticObject = ogreBulletShapeConverter.createSphere();
    } else if (bulletCollision == "box"){
        shapeStaticObject = ogreBulletShapeConverter.createBox();
        offsetLocation = entityStaticObject->getBoundingBox().getHalfSize();
        location.y = location.y - offsetLocation.y;
    } else if (bulletCollision == "trimesh"){
        shapeStaticObject = ogreBulletShapeConverter.createTrimesh();
    } else if (bulletCollision == "cylinder"){
        shapeStaticObject = ogreBulletShapeConverter.createCylinder();
    } else if (bulletCollision == "convex"){
        shapeStaticObject = ogreBulletShapeConverter.createConvex();
    }else{
        return 0;
    }

    shapeStaticObject->setLocalScaling(BtOgre::Convert::toBullet(nodeStaticObject->getScale() ) );

    //Create MotionState (no need for BtOgre here, you can use it if you want to though).
    stateStaticObject = new btDefaultMotionState(btTransform( BtOgre::Convert::toBullet(rotation),  BtOgre::Convert::toBullet(location) ) );

    //Create the Body.
    bodyStaticObject = new btRigidBody(0, stateStaticObject, shapeStaticObject, btVector3(0,0,0));
    Globals::phyWorld->addRigidBody(bodyStaticObject);

    return 1;
}
Exemplo n.º 8
0
//-------------------------------------------------------
void Ground::LoadFromHeightMap(std::shared_ptr<Ogre::Image> hmap, Ogre::SceneNode* parentNode)
{
    mImage = hmap;
    Ogre::Box box = Ogre::Box(0, 0, mImage->getWidth(), mImage->getHeight());

    mRootNode = parentNode->createChildSceneNode();
    
    mGlobalBoundingBox.setNull();

    Ogre::Material* groundMaterial = CreateGroundMaterialTextured("Material/" + CLASS_NAME + "/Textured", mImage.get());
    
    static const float VERTEX_STEP = 1.0f;
    static const float HEIGHT_STEP = 8.0f;

    float offsetX = GROUND_SIZE * VERTEX_STEP / 2.0f;
    float offsetY = GROUND_SIZE * VERTEX_STEP / 2.0f;

    size_t width  = mImage->getWidth();
    size_t height = mImage->getHeight();

    float texStep = 1.0f / REGIONS_NUMBER;

    size_t texRegionWidth  = static_cast<size_t>(std::ceil(static_cast<float>(width) / REGIONS_NUMBER));
    size_t texRegionHeight = static_cast<size_t>(std::ceil(static_cast<float>(height) / REGIONS_NUMBER));
    for (size_t y = 0; y < REGIONS_NUMBER; ++y)
    {
        size_t top = y * texRegionHeight;
        for (size_t x = 0; x < REGIONS_NUMBER; ++x)
        {
            size_t left = x * texRegionWidth;
            Ogre::Box roi = Ogre::Box(left, height - std::min(top + texRegionHeight + 1, height), std::min(left + texRegionWidth + 1, width), height - top);
                
            Ogre::MeshPtr mesh = CreateRegion(y * REGIONS_NUMBER + x, groundMaterial->getName(), roi,
                Ogre::Vector3(x * VERTEX_STEP * REGION_SIZE - offsetX, y * VERTEX_STEP * REGION_SIZE - offsetY, 0.0f),
                Ogre::Vector3(VERTEX_STEP, VERTEX_STEP, HEIGHT_STEP),
                Ogre::Vector2(x * texStep, 1.0f - (y + 1) * texStep));

            Ogre::Entity* entity = mSceneManager->createEntity(mesh);
            
            auto node = mRootNode->createChildSceneNode();
            node->attachObject(entity);
            node->showBoundingBox(true);

            mGlobalBoundingBox.merge(entity->getBoundingBox());

            mEntities.push_back(entity);
        }
    }
}
Exemplo n.º 9
0
Ogre::SceneNode* createBox(Ogre::SceneManager* sceneMgr, Ogre::String name)
{
	// create an ordinary Ogre mesh with texture
	Ogre::Entity* boxEnt = sceneMgr->createEntity(name , "cube.mesh");
	
	// we need the bounding box of the cube.mesh to set the size of the Bullet box
	Ogre::AxisAlignedBox boxBb = boxEnt->getBoundingBox();
	//Ogre::Vector3 size = boxBb.getSize();
	boxEnt->setMaterialName("Examples/BumpyMetal");
	
	// create the node
	Ogre::SceneNode* boxNode = sceneMgr->getRootSceneNode()->createChildSceneNode();
	boxNode->attachObject( boxEnt );
	return boxNode;
}
	void OgreColladaContentImporter::sceneNodeCreated(Ogre::SceneNode* pNode, FCDSceneNode* pFColladaSceneNode)
	{
		NxOgre::ActorParams actorParams;
		NxOgre::ShapeParams shapeParams;
		Ogre::Vector3 boxSize;
		Ogre::Vector3 scale;
		Ogre::Entity *pEntity;
		std::list<Ogre::Entity*> entityList;
		std::list<Ogre::Entity*>::iterator entityListIter;
		NxVec3 row;

		pEntity = NULL;
		Ogre::SceneNode::ObjectIterator  iter = pNode->getAttachedObjectIterator();

		while (iter.hasMoreElements())
		{
			pEntity = dynamic_cast<Ogre::Entity*>(iter.getNext());

			if (pEntity != NULL)
			{
				entityList.push_back(pEntity);
			}
		}

		shapeParams.setToDefault();
		//scale = pNode->_getDerivedScale();
		//shapeParams.mMeshScale = NxVec3(scale.x, scale.y, scale.z);
		for (entityListIter = entityList.begin(); entityListIter != entityList.end(); ++entityListIter)
		{

			pEntity = *entityListIter;
			boxSize = pEntity->getBoundingBox().getSize();

			pNode->detachObject(pEntity);
			actorParams.setToDefault();
			actorParams.mMass = 0.0f;
			actorParams.mBodyFlags |= NX_BF_KINEMATIC;

			GameObjectFactory::getSingleton().makeBody(pEntity->getName(), pNode, pEntity, scene
				,new NxOgre::CubeShape(boxSize.x, boxSize.y, boxSize.z, shapeParams), actorParams);
		}

		sceneNodes.push_back(pNode);
	}
Exemplo n.º 11
0
void Player::setupNodes (Ogre::SceneManager* sceneManager)
{
    // Create the nodes
    mPlayerNode         = sceneManager->getRootSceneNode()->createChildSceneNode("PlayerNode");
    mPlayerCameraNode   = mPlayerNode->createChildSceneNode("PlayerCameraNode");
    mCharacterNode      = mPlayerNode->createChildSceneNode("PlayerCharacterNode");
    mTargettingPathNode = mPlayerNode->createChildSceneNode("PlayerPathNode");
    mTargettingEndNode  = sceneManager->getRootSceneNode()->createChildSceneNode("TargettingEndNode");
    mTargettingPathNode->setVisible(false);
    mPlayerCameraNode->setPosition(0, 100, 200);


    // Add the entities
    // Add player
    Ogre::Entity* playerEntity = sceneManager->createEntity("PlayerCharacter", "potato.mesh");
    Ogre::AxisAlignedBox bb = playerEntity->getBoundingBox();
    mPlayerHeight = (bb.getMaximum().y - bb.getMinimum().y) * 0.1f * 0.5f;
    mCharacterNode->attachObject(playerEntity);
    mCharacterNode->setScale(0.1f, 0.1f, 0.1f);
    mCharacterNode->setPosition(0, 0, 0);

    // Add target marker
    mTargettingEndNode = sceneManager->getRootSceneNode()->createChildSceneNode("TargetNode");
    Ogre::Entity* targetEntity = sceneManager->createEntity("TargetEntity", "sphere.mesh");
    mTargettingEndNode->attachObject(targetEntity);
    targetEntity = sceneManager->createEntity("TargetEntity2", "column.mesh");
    mTargettingEndNode->attachObject(targetEntity);
    mTargettingEndNode->setScale(0.1f, 0.1f, 0.1f);
    mTargettingEndNode->setPosition(0, 0, 0);


    // Billboard set
    /*mTargettingEndBBS = sceneManager->createBillboardSet("TargetBillboardSet", 2);
    sceneManager->getRootSceneNode()->attachObject(mTargettingEndBBS);
    mTargettingEndBBS->setMaterialName("Examples/Flare");
    mTargettingEndBBS->setVisible(true);
    mTargettingEndBBS->createBillboard(0, 300, 0, Ogre::ColourValue(0.5f, 0.6f, 1.0f));
    mTargettingEndBBS->setDefaultDimensions(100, 100);
    mTargettingEndBBS->setBillboardType(Ogre::BBT_ORIENTED_COMMON);
    mTargettingEndBBS->setCommonUpVector(Ogre::Vector3(0, 1, 0));*/
}
bool TutorialApplication::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
    if (m_mode == TrollMode) {
        const Vector3 p = m_cursorNode->getPosition();
        m_ogres.push_back(p);

        Ogre::Entity *troll = m_SceneMgr->createEntity("ogrehead.mesh");
        Vector3 bounds = troll->getBoundingBox().getSize();
        Real dim = std::max({bounds.x, bounds.y, bounds.z});
        Real scale = GRID_SPACING / dim;
        bounds = bounds * scale * 0.5f;

        Ogre::SceneNode *node = m_SceneMgr->getRootSceneNode()->createChildSceneNode();
        node->setPosition(p.x + bounds.x, p.y + bounds.y, p.z + bounds.z);
//        node->showBoundingBox(true);
        node->scale(scale, scale, scale);
        node->attachObject(troll);
    }

    return BaseApplication::mouseReleased(arg, id);
}
Exemplo n.º 13
0
void MapManager::AddObstacle(MapArea* area, Objects* input)
{
	if(input->mLoaded)
		return;

	char areaString[30];
	sprintf(areaString, "map_area_%d", area->getIndex());

	//get the area node from map node.
	Ogre::SceneNode* areaNode = (Ogre::SceneNode*)mMapNode->getChild(Ogre::String(areaString));

	char cubeString[30];
	sprintf(cubeString, "cube_%d", input->index);
	
	Ogre::Entity* cubeEntity = mSceneMgr->createEntity(Ogre::String(cubeString),"cube.mesh");
			
	cubeEntity->setMaterialName("Cube");

	//cubeEntity->getMesh()->setAutoBuildEdgeLists(true);
	//cubeEntity->getMesh()->buildEdgeList();
	
	cubeEntity->setCastShadows(false);

	//create a node for the cube
	Ogre::SceneNode* cubeNode = areaNode->createChildSceneNode(Ogre::String(cubeString));

	//attach the cube to the node
	cubeNode->attachObject(cubeEntity);

	//move the cube to it's position
	cubeNode->setPosition(input->mPosition);
	
	//cube entity actual size = 100 by 100 by 100

	Ogre::Vector3 scale;
	scale.x = Ogre::Real(0.01f)*input->sizeWidth;
	scale.y = 0.1f;
	scale.z = Ogre::Real(0.01f)*input->sizeHeight;
	cubeNode->setScale(scale);

	input->mLoaded = true;

	Ogre::Vector3 size = cubeEntity->getBoundingBox().getSize();
	size /= 2.f;
	size *= 0.96f;
	//size rescale. refer to prac07 for full calculation
	size.x *= Ogre::Real(0.01f)*input->sizeWidth;
	size.y *= Ogre::Real(0.1f);
	size.z *= Ogre::Real(0.01f)*input->sizeHeight;

	OgreBulletCollisions::BoxCollisionShape *sceneBoxShape = new OgreBulletCollisions::BoxCollisionShape(size);
	OgreBulletDynamics::RigidBody *boxBody = new OgreBulletDynamics::RigidBody("BoxRigid" + Ogre::StringConverter::toString(input->index), 
		PhysicManager::getSingletonPtr()->getPhysicWorld(),
		PhysicManager::COL_OBSTACLE,
		PhysicManager::mObstacleCollideWith);

	boxBody->setStaticShape(cubeNode, sceneBoxShape,
		1.f,
		1.f,
		input->mPosition,
		Ogre::Quaternion(0,0,0,1));

	mRigidBodyList.push_back(boxBody);
	
	mNumEntitiesInstanced++;
}
void CResourceManagementView::EngineSetup(void)
{
	CEngine* Engine = ((CResourceManagementApp*)AfxGetApp())->m_Engine;
	Ogre::Root *Root = Engine->GetRoot();

	Ogre::SceneManager *SceneManager = NULL;

	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "ResourceManagement");

    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);

	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Resource Management");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Resource Management", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
	
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(200.0, 50.0, 100.0));
	m_Camera->lookAt(0.0, 0.0, 0.0);
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 1.0f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
	Ogre::StringVector Groups = Ogre::ResourceGroupManager::getSingleton().getResourceGroups();

	Ogre::Entity *MobiusEntity = Engine->m_StlFileManager->createEntity("Mobius", "1_4.stl");
	Ogre::SceneNode *MobiusNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	MobiusNode->attachObject(MobiusEntity);
	Ogre::AxisAlignedBox MobiusBox = MobiusEntity->getBoundingBox();
	Ogre::Vector3 MobiusCenter = MobiusBox.getCenter();
	m_Camera->lookAt(MobiusCenter);

	Ogre::Real Radius = MobiusEntity->getBoundingRadius();
	m_Camera->setPosition(300, 100, 200);
	m_Camera->setPolygonMode(Ogre::PM_WIREFRAME);
}
Exemplo n.º 15
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
#else
int main (int argc, char *argv[]) {
#endif

	Ogre::Root *ogre;
	Ogre::RenderWindow *window;
	Ogre::SceneManager *sceneMgr;
	Ogre::SceneManager *guiSceneMgr;
	Ogre::Camera *camera;
	Ogre::Camera *guiCamera;

	// fire up an Ogre rendering window. Clearing the first two (of three) params will let us 
	// specify plugins and resources in code instead of via text file
	ogre = new Ogre::Root("", "");

#if defined(_DEBUG)
	ogre->loadPlugin("RenderSystem_GL_d");
#else
	ogre->loadPlugin("RenderSystem_GL");
#endif

	Ogre::RenderSystemList *renderSystems = NULL;
	Ogre::RenderSystemList::iterator r_it;

	renderSystems = ogre->getAvailableRenderers();
	r_it = renderSystems->begin();
	ogre->setRenderSystem(*r_it);
	ogre->initialise(false);

	// load common plugins
#if defined(_DEBUG)
	//ogre->loadPlugin("Plugin_CgProgramManager_d");		
	ogre->loadPlugin("Plugin_OctreeSceneManager_d");
#else
	//ogre->loadPlugin("Plugin_CgProgramManager");		
	ogre->loadPlugin("Plugin_OctreeSceneManager");
#endif
	// load the basic resource location(s)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource", "FileSystem", "General");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("resource/gui.zip", "Zip", "GUI");
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("meshes", "FileSystem", "Meshes");
#if defined(WIN32)
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation("c:\\windows\\fonts", "FileSystem", "GUI");
#endif

	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("General");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("GUI");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Meshes");

	// setup main window; hardcode some defaults for the sake of presentation
	Ogre::NameValuePairList opts;
	opts["resolution"] = "1024x768";
	opts["fullscreen"] = "false";
	opts["vsync"] = "false";

	// create a rendering window with the title "CDK"
	window = ogre->createRenderWindow("Bouwgame Client v0.1", 1024, 768, false, &opts);

	// since this is basically a CEGUI app, we can use the ST_GENERIC scene manager for now; in a later article 
	// we'll see how to change this
	sceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);
	guiSceneMgr = ogre->createSceneManager(Ogre::ST_GENERIC);

	guiCamera = guiSceneMgr->createCamera("GUICamera");
	guiCamera->setNearClipDistance(5);
	camera = sceneMgr->createCamera("camera");
	camera->setNearClipDistance(5);
    Ogre::Viewport* vp = window->addViewport(guiCamera);
    vp->setBackgroundColour(Ogre::ColourValue(0.2f,0.2f,0.8f));

	/* ambient light */
	sceneMgr->setAmbientLight(Ogre::ColourValue(0.8, 0.8, 0.8));
	sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	/* meshes */
	Ogre::Entity* ent = sceneMgr->createEntity( "BouwPlaatsEntity", "world.mesh" );
	Ogre::SceneNode* node = sceneMgr->getRootSceneNode()->createChildSceneNode("BouwNode", Ogre::Vector3(0, 0, 0));
    node->attachObject(ent);
	//node->setScale(Ogre::Vector3(0.7,0.7,0.7));

	ent = sceneMgr->createEntity("plaats", "bouwplaats_step_00.mesh");
	Ogre::Vector3 size = ent->getBoundingBox().getSize();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats size: ") + Ogre::StringConverter::toString(size));
	size = ent->getBoundingBox().getMaximum();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats max: ") + Ogre::StringConverter::toString(size));
	size = ent->getBoundingBox().getMinimum();
	Ogre::LogManager::getSingletonPtr()->getDefaultLog()->logMessage(Ogre::String("Bouwplaats min: ") + Ogre::StringConverter::toString(size));

    Ogre::Entity* ent1 = sceneMgr->createEntity( "KeetEntity", "keet.mesh" );
	Ogre::SceneNode* scenenode = sceneMgr->getRootSceneNode()->createChildSceneNode("KeetNode", Ogre::Vector3(0, 0, 0));
    scenenode->attachObject(ent1);

	
	Ogre::Entity* ent2 = sceneMgr->createEntity( "HekjeEntity", "hekje.mesh" );
	Ogre::SceneNode* scenenode2 = sceneMgr->getRootSceneNode()->createChildSceneNode("HekjeNode", Ogre::Vector3(0, -100, 0));
    scenenode2->attachObject(ent2);
	scenenode2->setScale(Ogre::Vector3(400,0,100));

	// most examples get the viewport size to calculate this; for now, we'll just 
	// set it to 4:3 the easy way
	camera->setAspectRatio((Ogre::Real)1.333333);
	camera->setPosition(Ogre::Vector3(40,100,10));
	guiCamera->setPosition(0, 0, 300);
	guiCamera->lookAt(node->getPosition());

	// this next bit is for the sake of the input handler
	unsigned long hWnd;
	window->getCustomAttribute("WINDOW", &hWnd);

	
	// set up the input handlers
	Simulation *sim = new Simulation();
	InputHandler *handler = new InputHandler(sim, hWnd, camera);
	DataManager *dataManager = new DataManager();
	GameAI* gameAI = new GameAI(dataManager);

	//Create Network
	Network * net = new Network(dataManager);
	//net->start();

	sim->requestStateChange(GUI);
	gui = new GuiManager();

	// networkshit
	while(!net->isConnected())
	{
		Sleep(1000);
	}
	net->Send(GETGROUPS, "", "", NULL);
	net->Send(LOGIN, "gast", "gast", 1);

	gui->setSimulation(sim);
	gui->init("", ogre, guiSceneMgr, window);
	gui->activate("main");
	handler->setWindowExtents(1024,768);
	
	SimulationState cState;
	Ogre::WindowEventUtilities::addWindowEventListener(window, handler);

	DWORD tFrameStart = 0x0; //in miliseconds
	signed long tFrameX = 0x0;
	float tDelta2 = 0.0f; //in seconds
	float m_fps = 60.0f;
	tFrameStart = GetTickCount();

	float tDelta;

	//testAI->calculateNextPath(40,10);

	while ((cState = sim->getCurrentState()) != SHUTDOWN) {

		tFrameX = GetTickCount() - tFrameStart;
		tDelta2 = (float)tFrameX / 1000.0f;
		if (tDelta2 > 3600) // tDelta > 1 hour
			tDelta2 = 1.0f / m_fps; //< System tick count has highly likely overflowed, so get approximation
		tFrameStart = GetTickCount();
		m_fps = (int)(1.0f / tDelta2);

		tDelta = tDelta2;

		handler->capture();
		handler->update(tDelta);
		gui->update(tDelta);

		//if (sim->getCurrentState() == SIMULATION || sim->getCurrentState() == SIMULATION_MOUSELOOK)
//			testAI->update(tDelta);

		// run the message pump (Eihort)
		Ogre::WindowEventUtilities::messagePump();

		ogre->renderOneFrame();

		if (sim->getCurrentState() != cState) {
			handler->StateSwitched(cState, sim->getCurrentState());
			switch (sim->getCurrentState()) {
				case GUI:
					window->getViewport(0)->setCamera(guiCamera);
					break;
				case SIMULATION:
					window->getViewport(0)->setCamera(camera);
					break;
			}
		}

	}

	// clean up after ourselves
	//delete testAI;
	delete sim;
	delete ogre;
	delete handler;
	delete gameAI;
	delete dataManager;

	return 0;
}
void CTerrainWalkingView::EngineSetup(void)
{
	Ogre::Root *Root = ((CTerrainWalkingApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Walking");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Walking");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Walking", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(10);
	m_Camera->setFarClipDistance(10000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);

	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::SceneNode *TopographyNode = SceneManager->getRootSceneNode()->createChildSceneNode("Topography");
	Ogre::Entity *TopographyEntity = SceneManager->createEntity("Topography", "Topography.mesh");
	TopographyNode->attachObject(TopographyEntity);
	
	Ogre::AxisAlignedBox TopographyBox = TopographyEntity->getBoundingBox();
	
	Ogre::Vector3 Minimum = TopographyBox.getMinimum();
	Ogre::Vector3 Center = TopographyBox.getCenter();

	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode("Robot");
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	RobotNode->attachObject(RobotEntity);
	RobotEntity->getParentNode()->scale(10,10,10);
	Ogre::AxisAlignedBox RobotBox = RobotEntity->getBoundingBox();

	RobotNode->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + RobotBox.getSize()[1], Minimum[2]));

	m_Camera->setPosition(Ogre::Vector3(Minimum[0], Minimum[1] + 5000, Minimum[2]));
	m_Camera->lookAt(Center);
	
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);

	m_Animation = RobotEntity->getAnimationState("Walk");
	m_Animation->setEnabled(true);
	
	m_CollisionTools = new MOC::CollisionTools(SceneManager);

	Root->renderOneFrame();
}
Exemplo n.º 17
0
void Objects::insertMesh (const MWWorld::Ptr& ptr, const std::string& mesh)
{
    Ogre::SceneNode* insert = ptr.getRefData().getBaseNode();
    assert(insert);

    NifOgre::NIFLoader::load(mesh);
    Ogre::Entity *ent = mRenderer.getScene()->createEntity(mesh);


    Ogre::Vector3 extents = ent->getBoundingBox().getSize();
    extents *= insert->getScale();
    float size = std::max(std::max(extents.x, extents.y), extents.z);

    bool small = (size < Settings::Manager::getInt("small object size", "Viewing distance")) && Settings::Manager::getBool("limit small object distance", "Objects");

    // do not fade out doors. that will cause holes and look stupid
    if (ptr.getTypeName().find("Door") != std::string::npos)
        small = false;

    if (mBounds.find(ptr.getCell()) == mBounds.end())
        mBounds[ptr.getCell()] = Ogre::AxisAlignedBox::BOX_NULL;

    Ogre::AxisAlignedBox bounds = ent->getBoundingBox();
    bounds = Ogre::AxisAlignedBox(
        insert->_getDerivedPosition() + bounds.getMinimum(),
        insert->_getDerivedPosition() + bounds.getMaximum()
    );

    bounds.scale(insert->getScale());
    mBounds[ptr.getCell()].merge(bounds);

    bool transparent = false;
    for (unsigned int i=0; i<ent->getNumSubEntities(); ++i)
    {
        Ogre::MaterialPtr mat = ent->getSubEntity(i)->getMaterial();
        Ogre::Material::TechniqueIterator techIt = mat->getTechniqueIterator();
        while (techIt.hasMoreElements())
        {
            Ogre::Technique* tech = techIt.getNext();
            Ogre::Technique::PassIterator passIt = tech->getPassIterator();
            while (passIt.hasMoreElements())
            {
                Ogre::Pass* pass = passIt.getNext();

                if (pass->getDepthWriteEnabled() == false)
                    transparent = true;
            }
        }
    }

    if(!mIsStatic || !Settings::Manager::getBool("use static geometry", "Objects") || transparent)
    {
        insert->attachObject(ent);

        ent->setRenderingDistance(small ? Settings::Manager::getInt("small object distance", "Viewing distance") : 0);
        ent->setVisibilityFlags(mIsStatic ? (small ? RV_StaticsSmall : RV_Statics) : RV_Misc);
        ent->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);
    }
    else
    {
        Ogre::StaticGeometry* sg = 0;

        if (small)
        {
            if( mStaticGeometrySmall.find(ptr.getCell()) == mStaticGeometrySmall.end())
            {
                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometrySmall[ptr.getCell()] = sg;

                sg->setRenderingDistance(Settings::Manager::getInt("small object distance", "Viewing distance"));
            }
            else
                sg = mStaticGeometrySmall[ptr.getCell()];
        }
        else
        {
            if( mStaticGeometry.find(ptr.getCell()) == mStaticGeometry.end())
            {

                uniqueID = uniqueID +1;
                sg = mRenderer.getScene()->createStaticGeometry( "sg" + Ogre::StringConverter::toString(uniqueID));
                mStaticGeometry[ptr.getCell()] = sg;
            }
            else
                sg = mStaticGeometry[ptr.getCell()];
        }

        // This specifies the size of a single batch region.
        // If it is set too high:
        //  - there will be problems choosing the correct lights
        //  - the culling will be more inefficient
        // If it is set too low:
        //  - there will be too many batches.
        sg->setRegionDimensions(Ogre::Vector3(2500,2500,2500));

        sg->addEntity(ent,insert->_getDerivedPosition(),insert->_getDerivedOrientation(),insert->_getDerivedScale());

        sg->setVisibilityFlags(small ? RV_StaticsSmall : RV_Statics);

        sg->setCastShadows(true);

        sg->setRenderQueueGroup(transparent ? RQG_Alpha : RQG_Main);

        mRenderer.getScene()->destroyEntity(ent);
    }
}
Exemplo n.º 18
0
Ogre::Vector3 Cube::getEntityCenter(Ogre::Entity& _entity)
{
    Ogre::AxisAlignedBox boundingBox = _entity.getBoundingBox();
    Ogre::Vector3 point = ( boundingBox.getMaximum() - boundingBox.getMinimum() ) /2;
    return point;
}
Exemplo n.º 19
0
int initOgreAR(aruco::CameraParameters camParams, unsigned char* buffer, std::string resourcePath)
{
	/// INIT OGRE FUNCTIONS
#ifdef _WIN32
  	root = new Ogre::Root(resourcePath + "plugins_win.cfg", resourcePath + "ogre_win.cfg");
#elif __x86_64__ || __ppc64__
	root = new Ogre::Root(resourcePath + "plugins_x64.cfg", resourcePath + "ogre.cfg");
#else
	root = new Ogre::Root(resourcePath + "plugins.cfg", resourcePath + "ogre.cfg");
#endif
  	if (!root->showConfigDialog()) return -1;
	Ogre::SceneManager* smgr = root->createSceneManager(Ogre::ST_GENERIC);


	/// CREATE WINDOW, CAMERA AND VIEWPORT
    Ogre::RenderWindow* window = root->initialise(true);
	Ogre::Camera *camera;
	Ogre::SceneNode* cameraNode;
	camera = smgr->createCamera("camera");
	camera->setNearClipDistance(0.01f);
	camera->setFarClipDistance(10.0f);
	camera->setProjectionType(Ogre::PT_ORTHOGRAPHIC);
	camera->setPosition(0, 0, 0);
	camera->lookAt(0, 0, 1);
	double pMatrix[16];
	camParams.OgreGetProjectionMatrix(camParams.CamSize,camParams.CamSize, pMatrix, 0.05,10, false);
	Ogre::Matrix4 PM(pMatrix[0], pMatrix[1], pMatrix[2] , pMatrix[3],
			pMatrix[4], pMatrix[5], pMatrix[6] , pMatrix[7],
			pMatrix[8], pMatrix[9], pMatrix[10], pMatrix[11],
			pMatrix[12], pMatrix[13], pMatrix[14], pMatrix[15]);
	camera->setCustomProjectionMatrix(true, PM);
	camera->setCustomViewMatrix(true, Ogre::Matrix4::IDENTITY);
	window->addViewport(camera);
	cameraNode = smgr->getRootSceneNode()->createChildSceneNode("cameraNode");
	cameraNode->attachObject(camera);


	/// CREATE BACKGROUND FROM CAMERA IMAGE
	int width = camParams.CamSize.width;
	int height = camParams.CamSize.height;
	// create background camera image
	mPixelBox = Ogre::PixelBox(width, height, 1, Ogre::PF_R8G8B8, buffer);
	// Create Texture
	mTexture = Ogre::TextureManager::getSingleton().createManual("CameraTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		      Ogre::TEX_TYPE_2D,width,height,0,Ogre::PF_R8G8B8,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

	//Create Camera Material
	Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("CameraMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	Ogre::Technique *technique = material->createTechnique();
	technique->createPass();
	material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
	material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
	material->getTechnique(0)->getPass(0)->createTextureUnitState("CameraTexture");

	Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true);
	rect->setCorners(-1.0, 1.0, 1.0, -1.0);
	rect->setMaterial("CameraMaterial");

	// Render the background before everything else
	rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND);

	// Hacky, but we need to set the bounding box to something big, use infinite AAB to always stay visible
	Ogre::AxisAlignedBox aabInf;
	aabInf.setInfinite();
	rect->setBoundingBox(aabInf);

	// Attach background to the scene
	Ogre::SceneNode* node = smgr->getRootSceneNode()->createChildSceneNode("Background");
	node->attachObject(rect);


	/// CREATE SIMPLE OGRE SCENE
	// add sinbad.mesh
	Ogre::ResourceGroupManager::getSingleton().addResourceLocation(resourcePath + "Sinbad.zip", "Zip", "Popular");
 	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	for(int i=0; i<MAX_MARKERS; i++) {
	  Ogre::String entityName = "Marker_" + Ogre::StringConverter::toString(i);
	  Ogre::Entity* ogreEntity = smgr->createEntity(entityName, "Sinbad.mesh");
	  Ogre::Real offset = ogreEntity->getBoundingBox().getHalfSize().y;
	  ogreNode[i] = smgr->getRootSceneNode()->createChildSceneNode();
	  // add entity to a child node to correct position (this way, entity axis is on feet of sinbad)
	  Ogre::SceneNode *ogreNodeChild = ogreNode[i]->createChildSceneNode();
	  ogreNodeChild->attachObject(ogreEntity);
	  // Sinbad is placed along Y axis, we need to rotate to put it along Z axis so it stands up over the marker
	  // first rotate along X axis, then add offset in Z dir so it is over the marker and not in the middle of it
	  ogreNodeChild->rotate(Ogre::Vector3(1,0,0), Ogre::Radian(Ogre::Degree(90)));
	  ogreNodeChild->translate(0,0,offset,Ogre::Node::TS_PARENT);
	  // mesh is too big, rescale!
	  const float scale = 0.006675f;
	  ogreNode[i]->setScale(scale, scale, scale);

	    // Init animation
	  ogreEntity->getSkeleton()->setBlendMode(Ogre::ANIMBLEND_CUMULATIVE);
	  if(i==0)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("HandsClosed");
        topAnim[i] = ogreEntity->getAnimationState("HandsRelaxed");
	  }
	  else if(i==1)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("Dance");
        topAnim[i] = ogreEntity->getAnimationState("Dance");
	  }
	  else if(i==2)
	  {
        baseAnim[i] = ogreEntity->getAnimationState("RunBase");
        topAnim[i] = ogreEntity->getAnimationState("RunTop");
	  }
	  else
	  {
        baseAnim[i] = ogreEntity->getAnimationState("IdleBase");
        topAnim[i] = ogreEntity->getAnimationState("IdleTop");
	  }
	  baseAnim[i]->setLoop(true);
	  topAnim[i]->setLoop(true);
	  baseAnim[i]->setEnabled(true);
	  topAnim[i]->setEnabled(true);
	}


 	/// KEYBOARD INPUT READING
 	size_t windowHnd = 0;
 	window->getCustomAttribute("WINDOW", &windowHnd);
 	im = OIS::InputManager::createInputSystem(windowHnd);
 	keyboard = static_cast<OIS::Keyboard*>(im->createInputObject(OIS::OISKeyboard, true));

	return 1;
}
void CSaveSceneView::EngineSetup(void)
{
	Ogre::Root *Root = ((CSaveSceneApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "SaveScene");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("SaveScene");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("SaveScene", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(200.0, 50.0, 100.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");
	CameraNode->attachObject(m_Camera);

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	RobotNode->attachObject(RobotEntity);


	Ogre::AxisAlignedBox Box = RobotEntity->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();
	m_Camera->lookAt(Center);

	int rc;

    xmlDocPtr doc;
   // Create a new Xmlm_XmlWriter for DOM, with no compression.
    m_XmlWriter = xmlNewTextWriterDoc(&doc, 0);
   // Start the document with the xml default for the version,
   // encoding ISO 8859-1 and the default for the standalone
   // declaration.
    xmlTextWriterStartDocument(m_XmlWriter, NULL, MY_ENCODING, NULL);
	
	SceneExplore(SceneManager);
   
	xmlTextWriterEndDocument(m_XmlWriter);
	xmlFreeTextWriter(m_XmlWriter);
    xmlSaveFileEnc("1.scene", doc, MY_ENCODING);
    xmlFreeDoc(doc);
}
Exemplo n.º 21
0
void ZoneListWidget::_createImages(ImageMap& retlist)
{
    retlist.clear();

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( "EntityTex",
                   Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,
                   256, 256, 0, Ogre::PF_A8R8G8B8 , Ogre::TU_RENDERTARGET );

    Ogre::RenderTexture *rttTex = texture->getBuffer()->getRenderTarget();
    Ogre::SceneManager *mSceneMgr = Ogre::Root::getSingletonPtr()->createSceneManager("OctreeSceneManager", "EntityTexMgr");

    Ogre::Light *dirl = mSceneMgr->createLight("DisplayLight");
    dirl->setDirection(-1,-1,-1);
    dirl->setDiffuseColour(1,1,1);
    dirl->setType(Ogre::Light::LT_DIRECTIONAL);

    Ogre::Camera* RTTCam = mSceneMgr->createCamera("EntityCam");
    RTTCam->setNearClipDistance(0.01F);
    RTTCam->setFarClipDistance(0);
    RTTCam->setAspectRatio(1);
    RTTCam->setFOVy(Ogre::Degree(90));
    RTTCam->setPosition(0,0,1);
    RTTCam->lookAt(0,0,0);

    Ogre::Viewport *v = rttTex->addViewport( RTTCam );
    v->setClearEveryFrame( true );
    v->setBackgroundColour(Ogre::ColourValue(0,0,0,0));

    ModularZoneFactory* factory = dynamic_cast<ModularZoneFactory*>(OgitorsRoot::getSingletonPtr()->GetEditorObjectFactory("Modular Zone Object"));
    if(!factory)return;
    factory->loadZoneTemplates();
    ZoneInfoMap zoneTemplates = factory->getZoneTemplateMap();

    Ogre::Entity *mEntity;

    unsigned char dataptr[300 * 300 * 6];
    unsigned char *dataptr2;
    Ogre::PixelBox pb(256,256,1,Ogre::PF_A8R8G8B8, dataptr);

    EntityMap entities;
    ZoneInfoMap::iterator zi;
    for(zi=zoneTemplates.begin();zi!=zoneTemplates.end();++zi)
    {
        Ogre::String addstr = (*zi).second.mMesh;
        if(entities.find((*zi).first) == entities.end())
            entities.insert(EntityMap::value_type((*zi).first,addstr));
    }

    EntityMap::const_iterator ite = entities.begin();

    while(ite != entities.end())
    {
        Ogre::String addstr = ite->second;

        mEntity = mSceneMgr->createEntity("MZP_Preview", addstr);

        mSceneMgr->getRootSceneNode()->attachObject(mEntity);

        //TODO: It would be nice to retrieve a Preview Camera Position from
        //the .zone file
        //TODO: also render portal outlines clearly so that the user can see
        //how the zone is laid out
        Ogre::Vector3 vSize = mEntity->getBoundingBox().getCorner(Ogre::AxisAlignedBox::NEAR_RIGHT_TOP);//.getHalfSize();//============
        Ogre::Vector3 vCenter = mEntity->getBoundingBox().getCenter();

//FIXME ------ NICE PREVIEWS NEEDED - bigger

        vSize += Ogre::Vector3(vSize.z, vSize.z, vSize.z);

        float maxsize = std::max(std::max(vSize.x,vSize.y),vSize.z);

        //vSize = Ogre::Vector3(0, 0, maxsize * 1.1f) + vCenter;
        vSize = Ogre::Vector3(maxsize * 0.5f, vSize.y, maxsize * 0.5f) + vCenter;
        //vSize.x +=vSize.x/2;//Maybe test to see which is larger x/2 or z/2 and use that?
        //vSize.z +=vSize.x/2;
        //RTTCam->setProjectionType(Ogre::PT_ORTHOGRAPHIC);

        RTTCam->setPosition(vSize.x,vSize.y,vSize.z);
        RTTCam->lookAt(vCenter.x,vCenter.y,vCenter.z);

        rttTex->update();
        rttTex->copyContentsToMemory(pb, Ogre::RenderTarget::FB_FRONT);


        dataptr2 = new unsigned char[96 * 96 * 4];
        Ogre::PixelBox pb2(96,96,1,Ogre::PF_A8R8G8B8, dataptr2);
        Ogre::Image::scale(pb,pb2);

        addstr.erase(addstr.length() - 5, 5);
        retlist.insert(ImageMap::value_type((*ite).first, dataptr2));

        mEntity->detachFromParent();
        mSceneMgr->destroyEntity(mEntity);

        ite++;
    }

    rttTex->removeAllViewports();
    Ogre::Root::getSingletonPtr()->destroySceneManager(mSceneMgr);
    Ogre::TextureManager::getSingletonPtr()->unload(texture->getName());
    Ogre::TextureManager::getSingletonPtr()->remove(texture->getName());
}
void COrbitViewView::EngineSetup(void)
{
	Ogre::Root *Root = ((COrbitViewApp*)AfxGetApp())->m_Engine->GetRoot();

	m_SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "OrbitViewt");

    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);

	try
	{
		m_RenderWindow = Root->createRenderWindow("OrbitViewt", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = m_SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = m_SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode", Ogre::Vector3::ZERO);
	CameraNode->attachObject(m_Camera);

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 1.0f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
		
	Ogre::Entity *RobotEntity = m_SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::SceneNode *RobotNode = m_SceneManager->getRootSceneNode()->createChildSceneNode("Robot");
	RobotNode->attachObject(RobotEntity);

	Ogre::AxisAlignedBox Box = RobotEntity->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();
	m_Camera->setPosition(Ogre::Vector3(Center[0], Center[1], Center[2] + 500.0));
	m_Camera->lookAt(Center);

	Root->renderOneFrame();
}
void CTerrainWalkingView::OnTimer(UINT_PTR nIDEvent)
{
	Ogre::Quaternion Quaternion;
	CEngine *Engine = ((CTerrainWalkingApp*)AfxGetApp())->m_Engine;		
	Ogre::Root *Root = Engine->GetRoot();
	Ogre::SceneNode *RobotNode = Root->getSceneManager("Walking")->getSceneNode("Robot");
	Ogre::Entity *RobotEntity = Root->getSceneManager("Walking")->getEntity("Robot");
	Ogre::AxisAlignedBox RobotBox = RobotEntity->getBoundingBox();

	Ogre::Entity *TopographyEntity = Root->getSceneManager("Walking")->getEntity("Topography");

	Ogre::AxisAlignedBox TopographyBox = TopographyEntity->getBoundingBox();
		
	Ogre::Vector3 Start = TopographyBox.getMinimum();
	Ogre::Vector3 Finish = TopographyBox.getMaximum();

	double x = Start[0] + (Finish[0] - Start[0]) * m_RelativeDistance;
	double y = Start[1] + (Finish[1] - Start[1]) * m_RelativeDistance;
	double z = Start[2] + (Finish[2] - Start[2]) * m_RelativeDistance;
	
	Ogre::Vector3 Elevation(x, y, z);
	Ogre::Vector3 CameraMove;

	switch (nIDEvent)
	{
		case 1:

			m_Animation->addTime(0.01);
			m_RelativeDistance += 0.01;

			if (m_CollisionTools->collidesWithEntity(Elevation, Ogre::Vector3(x,y - 1,z), Ogre::Vector3(x,y + 1,z), 100.0f, 0.0f, 4294967295))
			{
				x = Elevation[0];
				y = Elevation[1] + RobotBox.getSize()[1];
				z = Elevation[2];
			}

			RobotNode->setPosition(x, y, z);
			m_Camera->lookAt(x, y, z);
			
			if (m_RelativeDistance > 1.0)
			  KillTimer(1);

		break;

		case 2:

			CameraMove[0] = -100;
			CameraMove[1] = 0;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

		break;

		case 3:

			CameraMove[0] = 0;
			CameraMove[1] = 100;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

			break;

		case 4:

			CameraMove[0] = 100;
			CameraMove[1] = 0;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

			break;

		case 5:

			CameraMove[0] = 0;
			CameraMove[1] = -100;
			CameraMove[2] = 0;
			m_Camera->moveRelative(CameraMove);

			break;
	}

	Root->renderOneFrame();
	CView::OnTimer(nIDEvent);
}
//-------------------------------------------------------------------------------------
void TutorialApplication::createScene(void)
{
    // Set the scene's ambient light
    mSceneMgr->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
 
    // Create an Entity
    Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "templeTest111.mesh");
	b= ogreHead->getBoundingBox();
	Ogre::Vector3 t= b.getCenter();
	Ogre::Vector3 dim = b.getSize();
    // Create a SceneNode and attach the Entity to it
	Ogre::SceneNode* headNode1 = mSceneMgr->getRootSceneNode()->createChildSceneNode("HeadNode1");
    Ogre::SceneNode* headNode2 = headNode1->createChildSceneNode("HeadNode2",Ogre::Vector3(-1*t.x,-1*t.y,-1*t.z));
    headNode2->attachObject(ogreHead);
	//headNode1->scale(0.15,0.15,0.15);

    //Create a Light and set its position
    Ogre::Light* light = mSceneMgr->createLight("MainLight");
    light->setPosition(0.0f, 10000.0f, 0.0f);

	//create skybox.
	mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);

	//create arrow
	/*
	Ogre::Entity* arrow = mSceneMgr->createEntity("arrow", "arrow.mesh");
	Ogre::SceneNode* arrowNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("arrowNode");
    arrowNode->attachObject(arrow);
	arrowNode->translate(4000,4000,0);
	arrowNode->scale(50,1,100);
	*/

	// Assuming scene_mgr is your SceneManager.
    Ogre::ManualObject * circle = mSceneMgr->createManualObject("circle");
	float const radius = 7;
    float const accuracy = 35;
    circle->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_STRIP);
    unsigned point_index = 0;
    for(float theta = 0; theta <= 2 * Ogre::Math::PI; theta += Ogre::Math::PI / accuracy) {
        circle->position(radius * cos(theta), 0, radius * sin(theta));
        circle->index(point_index++);
    }
    circle->index(0);// Rejoins the last point to the first.
    circle->end();
	circleNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("circleNode");
    circleNode->attachObject(circle);
	circleNode->scale(100,1,100);
	//circleNode->translate(4000,-4000,0);

	mCamera->setOrthoWindow(dim.x,dim.z);

	mWindow->resize(500+700,500*dim.z/dim.x);
	winsize.x = 500;
	winsize.y = mWindow->getHeight();
	mCamera->setAspectRatio(dim.x/dim.z);
	
	mCamera2->setAspectRatio(700.0/mWindow->getHeight());
	mCamera2->setPosition(4000,(-dim.y/2)+1000,0);
	mCamera2->lookAt(4000,(-dim.y/2)+1000,-1);
	
}
Exemplo n.º 25
0
void Animation::addExtraLight(Ogre::SceneManager *sceneMgr, NifOgre::ObjectScenePtr objlist, const ESM::Light *light)
{
    const MWWorld::Fallback *fallback = MWBase::Environment::get().getWorld()->getFallback();

    const int clr = light->mData.mColor;
    Ogre::ColourValue color(((clr >> 0) & 0xFF) / 255.0f,
                            ((clr >> 8) & 0xFF) / 255.0f,
                            ((clr >> 16) & 0xFF) / 255.0f);
    const float radius = float(light->mData.mRadius);

    if((light->mData.mFlags&ESM::Light::Negative))
        color *= -1;

    objlist->mLights.push_back(sceneMgr->createLight());
    Ogre::Light *olight = objlist->mLights.back();
    olight->setDiffuseColour(color);

    Ogre::ControllerValueRealPtr src(Ogre::ControllerManager::getSingleton().getFrameTimeSource());
    Ogre::ControllerValueRealPtr dest(OGRE_NEW OEngine::Render::LightValue(olight, color));
    Ogre::ControllerFunctionRealPtr func(OGRE_NEW OEngine::Render::LightFunction(
        (light->mData.mFlags&ESM::Light::Flicker) ? OEngine::Render::LT_Flicker :
        (light->mData.mFlags&ESM::Light::FlickerSlow) ? OEngine::Render::LT_FlickerSlow :
        (light->mData.mFlags&ESM::Light::Pulse) ? OEngine::Render::LT_Pulse :
        (light->mData.mFlags&ESM::Light::PulseSlow) ? OEngine::Render::LT_PulseSlow :
        OEngine::Render::LT_Normal
    ));
    objlist->mControllers.push_back(Ogre::Controller<Ogre::Real>(src, dest, func));

    bool interior = !(mPtr.isInCell() && mPtr.getCell()->getCell()->isExterior());
    bool quadratic = fallback->getFallbackBool("LightAttenuation_OutQuadInLin") ?
                     !interior : fallback->getFallbackBool("LightAttenuation_UseQuadratic");

    // with the standard 1 / (c + d*l + d*d*q) equation the attenuation factor never becomes zero,
    // so we ignore lights if their attenuation falls below this factor.
    const float threshold = 0.03;

    if (!quadratic)
    {
        float r = radius * fallback->getFallbackFloat("LightAttenuation_LinearRadiusMult");
        float attenuation = fallback->getFallbackFloat("LightAttenuation_LinearValue") / r;
        float activationRange = 1.0f / (threshold * attenuation);
        olight->setAttenuation(activationRange, 0, attenuation, 0);
    }
    else
    {
        float r = radius * fallback->getFallbackFloat("LightAttenuation_QuadraticRadiusMult");
        float attenuation = fallback->getFallbackFloat("LightAttenuation_QuadraticValue") / std::pow(r, 2);
        float activationRange = std::sqrt(1.0f / (threshold * attenuation));
        olight->setAttenuation(activationRange, 0, 0, attenuation);
    }

    // If there's an AttachLight bone, attach the light to that, otherwise put it in the center,
    if(objlist->mSkelBase && objlist->mSkelBase->getSkeleton()->hasBone("AttachLight"))
        objlist->mSkelBase->attachObjectToBone("AttachLight", olight);
    else
    {
        Ogre::AxisAlignedBox bounds = Ogre::AxisAlignedBox::BOX_NULL;
        for(size_t i = 0;i < objlist->mEntities.size();i++)
        {
            Ogre::Entity *ent = objlist->mEntities[i];
            bounds.merge(ent->getBoundingBox());
        }

        Ogre::SceneNode *node = bounds.isFinite() ? mInsert->createChildSceneNode(bounds.getCenter())
                                                  : mInsert->createChildSceneNode();
        node->attachObject(olight);
    }
}