예제 #1
0
	//---------------------------------------------------------------------
	bool BillboardSetElement::_createBillboardSet(void)
	{
		Ogre::SceneNode* parent = mBasicNode;

		if (parent)
		{
			mBillboardSet = mSystem->getSceneManager()->createBillboardSet( parent->getName() );
			mBillboardSet->setMaterialName(mBillboardMaterial);

            if ( (mStacks > 1) || (mSlices > 1) )
                mBillboardSet->setTextureStacksAndSlices(mStacks, mSlices);

            mBillboardSet->setCastShadows(false);

            mBillboardSet->setVisible(mVisible);

			parent->attachObject(mBillboardSet);

			for ( int i=0; i<mBillboardCount; ++i )
			{
				Ogre::Billboard *billboard = mBillboardSet->createBillboard(0, i*mBillboardInterval, 0, mBillboardColour * mAlphaValue);
				assert (billboard);
				billboard->setDimensions(mBillboardWidth, mBillboardHeight);
			}

            _resetBillboardStartTexIndex();
            _resetBillboardStartScaleTime();

			return true;
		}

		return false;
	}
예제 #2
0
	void Billboard::build(){
			mBillboardSet = Level::getSingleton()->getSceneManager()->createBillboardSet(mFilename+ts(GameElement::getNextIdCounter()));
			mBillboardSet->setMaterialName(mFilename);
			mBillboardSet->setCullIndividually(true);
			
			//mBillboardSet->setPointRenderingEnabled(true);
			//mBillboardSet->setBillboardsInWorldSpace(true);
			//mBillboardSet->setBillboardType(Ogre::BillboardType::BBT_PERPENDICULAR_COMMON);
			if (mParentConnector.mGameObject == NULL){
				mSceneNode->attachObject(mBillboardSet);
			}else{
				//Ogre::Vector3 scale = mSceneNode->getScale();
				if (mParentConnector.mBone != ""){
					mParentConnector.mGameObject->getEntity()->attachObjectToBone(mParentConnector.mBone, mBillboardSet);
					getNode()->setPosition(mSceneNode->getPosition());
					getNode()->setOrientation(mSceneNode->getOrientation());
				}else{
					throw("Billboard object requires to be attached to a parent's bone.  No bone, no go");
				}


				//mEntity->getParentNode()->setScale(scale);
				//mBoneNodeMode =true;
			}


			
			//attachObject(mBillboardSet);
			
			Ogre::AxisAlignedBox box(Ogre::Vector3(0,0,0), Ogre::Vector3(0,0,0));
			for (list<BILLBOARD_ELEMENT>::iterator it = mBillboardElement.begin();it!=mBillboardElement.end();it++){
				Ogre::Billboard* bb = mBillboardSet->createBillboard((*it).mPos, (*it).mColour);
				bb->setDimensions((*it).mSize.x,(*it).mSize.y);

				Ogre::Vector3 np1 = (*it).mPos + Ogre::Vector3((*it).mSize.x, (*it).mSize.y, (*it).mSize.x);
				Ogre::Vector3 np2 = (*it).mPos - Ogre::Vector3((*it).mSize.x, (*it).mSize.y, (*it).mSize.x);
				Ogre::AxisAlignedBox box2(np2, np1);
				box.merge(box2);
			}
			mBillboardSet->setBounds(box, (*mBillboardElement.begin()).mSize.x);
		


		/*mHaloSet = mSceneMgr->createBillboardSet("halo");
	mHaloSet->setMaterialName("lensflare/halo");
	mHaloSet->setCullIndividually(true);
	mHaloSet->setQueryFlags(VOIDOBJECT);	// They should not be detected by rays.*/
		Parent::build();
		//attachObject(mCamera);
		mBillboardSet->setQueryFlags(SceneQueryFlag::IMMATERIAL);
		mBillboardSet->setRenderQueueGroup(mLevelSegment->getSceneManager()->getRenderQueue()->getDefaultQueueGroup()+getRenderQueueDelta());
		
	}
예제 #3
0
/**
 * @inheritDoc
 */
Error ImageGraphicObject::initialize(void) {
    ASSERT(!m_bInitialized);
    
    std::string image = IMAGE_BASE_PATH + m_image;
    /*m_sourceImage = IMG_Load(image.c_str());
    m_displayImage = SDL_ConvertSurface(m_sourceImage, m_sourceImage->format, m_sourceImage->flags);*/
    
    Ogre::SceneNode* rootNode = static_cast<GraphicScene*>(m_pSystemScene)->getRootNode();
    Ogre::SceneManager* sceneManager = static_cast<GraphicScene*>(m_pSystemScene)->getSceneManager();
    Ogre::SceneNode* myNode = static_cast<Ogre::SceneNode*>(rootNode->createChild());
    Ogre::BillboardSet* mySet = sceneManager->createBillboardSet("mySet");
    Ogre::Billboard* myBillboard = mySet->createBillboard(Ogre::Vector3(0, 0, 0));
    myBillboard->setDimensions(100, 100);
    myNode->attachObject(mySet);
    
    m_bInitialized = true;
    return Errors::Success;
}
예제 #4
0
	//---------------------------------------------------------------------
	void BillboardSetElement::setBillboardCount(int count)
	{
		mBillboardCount = count;

		if (mBillboardSet)
		{
			mBillboardSet->clear();

			for ( int i=0; i<mBillboardCount; ++i )
			{
				Ogre::Billboard *billboard = mBillboardSet->createBillboard(0, i*mBillboardInterval, 0, mBillboardColour * mAlphaValue);
				assert (billboard);
				billboard->setDimensions(mBillboardWidth, mBillboardHeight);
			}

            _resetBillboardStartTexIndex();
            _resetBillboardStartScaleTime();
		}
	}
예제 #5
0
//-----------------------------------------------------------------------------------------
bool CBillboardSetEditor::load(bool async)
{
    if(mLoaded->get())
        return true;
    
    if(CNodeEditor::load())
    {
        mBillboardSetHandle = mOgitorsRoot->GetSceneManager()->createBillboardSet(mName->get());
        mHandle->attachObject(mBillboardSetHandle);
        
        mBillboardSetHandle->setBillboardType((Ogre::BillboardType)mBillboardType->get());
        mBillboardSetHandle->setSortingEnabled(mSorting->get());
        mBillboardSetHandle->setBillboardOrigin((Ogre::BillboardOrigin)mOrigin->get());
        mBillboardSetHandle->setBillboardRotationType((Ogre::BillboardRotationType)mRotation->get());
        mBillboardSetHandle->setDefaultWidth(mDefaultWidth->get());
        mBillboardSetHandle->setDefaultHeight(mDefaultHeight->get());
        mBillboardSetHandle->setVisibilityFlags(1 << mLayer->get());
        if(mMaterial->get() != "")
            mBillboardSetHandle->setMaterialName(mMaterial->get());
        
        mBillboardSetHandle->setPointRenderingEnabled(mPointRendering->get());
        mBillboardSetHandle->setRenderingDistance(mRenderDistance->get());

        Ogre::Vector2 v2val;
        Ogre::Vector3 v3val;
        Ogre::Vector4 v4val;
        Ogre::ColourValue cval;
        Ogre::Real rval;
        int ival;
        Ogre::String propname;

        int count = mBillboardCount->get();
        for(int ix = 0;ix < count;ix++)
        {
            propname = "billboard" + Ogre::StringConverter::toString(ix);

            Ogre::Billboard *pBillboard = mBillboardSetHandle->createBillboard(Ogre::Vector3::ZERO);
            mProperties.getValue(propname + "::position", v3val);
            pBillboard->setPosition(v3val);
            mProperties.getValue(propname + "::colour", cval);
            pBillboard->setColour(cval);
            mProperties.getValue(propname + "::dimensions", v2val);
             pBillboard->setDimensions(v2val.x, v2val.y);
            mProperties.getValue(propname + "::rotation", rval);
            pBillboard->setRotation(Ogre::Degree(rval));
            mProperties.getValue(propname + "::texcoordindex", ival);
            pBillboard->setTexcoordIndex(ival);
            mProperties.getValue(propname + "::texrect", v4val);
            pBillboard->setTexcoordRect(v4val.x, v4val.y, v4val.z, v4val.w);
        }

    }
    else
        return false;

    return true;
}
int OgreBillboardInterface::createBillboard(const std::string& name, const vec2& size, const vec3& displacement, Transformable* link) {
	if(billboard_sets.count(name) == 0) {
		char buf[256];
		sprintf(buf, "Invalid billboard set '%s'", name.c_str());
		LOG(buf);
		return -1;
	}

	int id = icount;
	icount++;
	billboards[id].displacement = displacement;
	billboards[id].link = link;
	billboards[id].link_id = link->getId();
	billboards[id].size = size;
	Ogre::Billboard* b = billboard_sets[name]->createBillboard(Ogre::Vector3(0, 0, 0));
	billboards[id].billboard = b;
	billboards[id].set = billboard_sets[name];
	b->setDimensions(size[0], size[1]);
	billboards[id].set->notifyBillboardDataChanged();
	
	return id;
}
예제 #7
0
/**
 * Get a new Billboard. If have no more billboard then 0 is returned
 */
Ogre::Billboard *BillboardManager::getNewBillboard(int atlasNumber)
{
	ASSERT(mBillboardSet);
	if(mBillboards.empty()){
		return 0;
	}
	// check if we have to attach to the scene node
	if(mBillboards.size() == mBillboardSet->getPoolSize()){
		// this is the first that we will remove
		mNode->attachObject(mBillboardSet);
	}

	Ogre::Billboard *result = mBillboards.front();
	mBillboards.pop_front();

	// configure the atlas if needed
	if(atlasNumber >= 0){
		Ogre::Real x1 = (mAtlasSize * atlasNumber);
		ASSERT(x1 + mAtlasSize <= 1.0f);
		result->setTexcoordRect(x1, 0.0f, x1+mAtlasSize, 1.0f);
	}

	return result;
}
예제 #8
0
	void Lightning::create()
	{
		remove();

		Ogre::Vector3 end = mOrigin + mDirection*mLength;
		Ogre::Vector3 current, last = mOrigin;

		// Create ray segments
		for(Ogre::uint32 k = 1; k < mDivisions+1; k++)
		{
			Ogre::Vector3 current = mOrigin + mDirection*mLength*(static_cast<Ogre::Real>(k)/mDivisions);

			current += (mLength/(mDivisions*3))*Ogre::Vector3(
				Ogre::Math::RangeRandom(-1, 1), Ogre::Math::RangeRandom(-1, 1), Ogre::Math::RangeRandom(-1, 1));

			mSegments.push_back(Segment(last, current));

			mRealLength += (current-last).length();

			last = current;
		}

		// Create the associated billboard set
		mBillboardSet = mSceneManager->createBillboardSet();
		mBillboardSet->setMaterialName("SkyX_Lightning");
		mBillboardSet->setBillboardType(Ogre::BBT_ORIENTED_SELF);

		Ogre::Real width = mWidthMultiplier*3*(static_cast<Ogre::Real>(mRecursivity)/4+1)*Ogre::Math::RangeRandom(0.5f, 2.5f-mRecursivity/3);

		// Create the associated billboard for each segment
		Ogre::Real delta;
		Ogre::Vector2 bounds;
		Ogre::Billboard* bb;
		for(Ogre::uint32 k = 0; k < mSegments.size(); k++)
		{
			delta = 1.0f / mSegments.size();
			bounds = Ogre::Vector2(k*delta,(k+1)*delta);

			bounds = Ogre::Vector2(mBounds.x, mBounds.x) + bounds*(mBounds.y-mBounds.x);

			bb = mBillboardSet->createBillboard((mSegments.at(k).a+mSegments.at(k).b)/2);
			bb->setDimensions(width, (mSegments.at(k).a-mSegments.at(k).b).length());
			bb->setColour(Ogre::ColourValue(0,bounds.x,bounds.y));
			bb->mDirection = (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy();

			bb = mBillboardSet->createBillboard(mSegments.at(k).a + (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy()*width/2);
			bb->setDimensions(width, width);
			bb->setColour(Ogre::ColourValue(1,bounds.x,bounds.x));
			bb->mDirection = (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy();
			
			bb = mBillboardSet->createBillboard(mSegments.at(k).b - (mSegments.at(k).a-mSegments.at(k).b).normalisedCopy()*width/2);
			bb->setDimensions(width, width);
			bb->setColour(Ogre::ColourValue(1,bounds.y,bounds.y));
			bb->mDirection = -(mSegments.at(k).a-mSegments.at(k).b).normalisedCopy();
		
			width *= 1-(1.0f/(mRecursivity*mRecursivity))*(1.0f/mSegments.size());
		}

		mBillboardSet->_updateBounds();

		mSceneNode->attachObject(mBillboardSet);

		mBillboardSet->setCustomParameter(0, Ogre::Vector4(1,0,0,0));

		// Ramifications
		if (mRecursivity > 0)
		{
			Ogre::Real angle;
			Ogre::Vector3 dir;
			Ogre::Real lengthMult;
			for (Ogre::uint32 k = 0; k < mDivisions-1; k++)
			{
				angle = (mSegments.at(k).b-mSegments.at(k).a).normalisedCopy().dotProduct(
					((mSegments.at(k+1).b-mSegments.at(k+1).a).normalisedCopy()));

				if (angle < Ogre::Math::RangeRandom(mAngleRange.x, mAngleRange.y))
				{
					dir = (mSegments.at(k).b-mSegments.at(k).a).normalisedCopy();
					dir.x *= Ogre::Math::RangeRandom(0.8f, 1.2f);
					dir.y *= Ogre::Math::RangeRandom(0.8f, 1.2f);
					dir.z *= Ogre::Math::RangeRandom(0.8f, 1.2f);
					dir.normalise();

					delta = 1.0f / mSegments.size();
					bounds = Ogre::Vector2(mBounds.x+(mBounds.y-mBounds.x)*(k+1)*delta,1);

					lengthMult = Ogre::Math::RangeRandom(0.1f, 0.7f);

					Lightning* lightning = new Lightning(mSceneManager, mSceneNode, mSegments.at(k).b, dir, lengthMult*mLength, 2+mDivisions*lengthMult, mRecursivity-1, mTimeMultiplier, mWidthMultiplier, bounds);
					lightning->create();
					
					mChildren.push_back(lightning);
				}
			}
		}

		mCreated = true;
	}
예제 #9
0
    //---------------------------------------------------------------------
    void BillboardSetElement::updateRenderInstance( Real time, TransformInfo &info )
    {
        if (mBillboardSet)
        {
            bool updateTexIndex = false;

            if (mSlices > 1 || mStacks > 1)
            {
                mCurrentTexIntervalTime += time;

                if (mCurrentTexIntervalTime >= mTexIntervalTime)
                {
                    updateTexIndex = true;
                    mCurrentTexIntervalTime = 0.0f;
                }            
            }

            for ( int i = 0; i < mBillboardSet->getNumBillboards(); ++i )
            {
                Ogre::Billboard* billboard = mBillboardSet->getBillboard(i);

                if (updateTexIndex)
                {
                    uint16 texIndex = billboard->getTexcoordIndex();
                    ++texIndex;

                    if (texIndex == mStacks * mSlices)
                        texIndex = 0;

                    billboard->setTexcoordIndex(texIndex);
                }
                
                if (mColourChanged)
                    billboard->setColour(mBillboardColour * mAlphaValue);

                if (mSizeChanged)
                {
                    _CurrentScaleInfo& info = mCurrentScaleInfos[i];
                    info.mCurrentScaleIntervalTime += time;

                    float colourPersent = fmod( info.mCurrentScaleIntervalTime, mScaleIntervalTime );

                    if (info.mCurrentScaleIntervalTime > mScaleIntervalTime)
                    {
                        info.mCurrentScaleIntervalTime  = colourPersent;

                        ++(info.mCurrentIndex);

                        if (info.mCurrentIndex == MAX_STAGES)
                            info.mCurrentIndex = 0;
                    }

                    Ogre::Vector3 resultColour;

                    Real rate = colourPersent / mScaleIntervalTime;

                    int incIndex = info.mCurrentIndex + 1;
                    if (incIndex == MAX_STAGES)
                        incIndex = 0;

                    resultColour = mBillboardScale[info.mCurrentIndex] * (1-rate) + mBillboardScale[incIndex] * rate;

                    billboard->setDimensions(mBillboardWidth * resultColour.x,
                        mBillboardHeight * resultColour.y);
                }
            }

            if (mColourChanged)
                mColourChanged = false;
        }
    }
예제 #10
0
void CellDrawActor< C >::allDraw(
    const AllDrawMessage< C >& m
) {
    // Рисуем только если ещё не было нарисовано
    // или по просьбе "обновлять постоянно"
    const std::string sceneName = "CellDrawActor::allDraw::Scene";
    const std::string bsName = "CellDrawActor::allDraw::BillboardSet";

    // @test
    /*
    try {
        m.sm->getRootSceneNode()->removeAndDestroyChild( sceneName );
    } catch ( ... ) {
    }
    try {
        m.sm->destroyBillboardSet( bsName );
    } catch ( ... ) {
    }
    */

    if ( m.update || !m.sm->hasSceneNode( sceneName ) ) {

        // Каждому образу - свой холст (общая сцена)
        auto scene = m.sm->hasSceneNode( sceneName ) ?
            m.sm->getSceneNode( sceneName ) :
            m.sm->getRootSceneNode()->createChildSceneNode( sceneName );

        // Определяем общее кол-во элементов
        const size_t NM = m.N * m.M;

        // Готовим биллборды

        // Обращаются за отрисовкой первый раз?
        const bool virgin = m.sm->hasBillboardSet( bsName );
        Ogre::BillboardSet* bs = nullptr;
        if ( virgin ) {
            bs = m.sm->getBillboardSet( bsName );

        } else {
            // Один образ для всех ячеек
            // @todo Расширить кол-во образов.
            bs = m.sm->createBillboardSet( bsName, NM );
            bs->setAutoextend( true );
            const std::string nameMaterial = m.prefixMaterial + "0";
            bs->setMaterialName( nameMaterial );
            bs->setBillboardType( Ogre::BBT_PERPENDICULAR_COMMON );
            bs->setCommonUpVector( Ogre::Vector3::UNIT_Z );
            bs->setCommonDirection( -Ogre::Vector3::UNIT_Y );
            bs->setBillboardsInWorldSpace( true );
            bs->setBillboardOrigin( Ogre::BBO_CENTER );
            bs->setDefaultDimensions( m.scale, m.scale );
            bs->setUseAccurateFacing( false );
            scene->attachObject( bs );
        }

        // Визуализируем каждую ячейку

        /* - @todo Можно ускорить отрисовку > http://www.ogre3d.org/forums/viewtopic.php?f=2&t=11134&start=0
        Ogre::Billboard b = Ogre::Billboard( Ogre::Vector3::ZERO, bs );
        b.setColour( Ogre::ColourValue::White );
        b.setRotation( Ogre::Degree( (float)rand() ) );
        */

        //bs->beginBillboards();
        for (size_t z = 0; z < m.M; ++z) {
            for (size_t x = 0; x < m.N; ++x) {
                const coordInt2d_t coord( (int)x, (int)z );

                // Создадим образ ячейки с указанной координатой

                const int i = helper::ic( coord.get<0>(), coord.get<1>(), m.N, m.M );
                assert( (i != -1) && "Получена координата за пределами матрицы порта." );
                const C c = m.content[i];

                // Биллборд уже мог быть создан ранее
                const auto bi = helper::index( *bs, coord, m.scale );
                if (bi != -1) {
                    bs->removeBillboard( bi );
                }

                if (c.uid == 0) {
                    // Вакуум - отсутствие образа
                    continue;
                }
    
#if 0
                // - Медленно. Переписано через биллборды.
                /*
                const std::string name =
                    "smoke-pressure-"
                  + Ogre::StringConverter::toString( (int)c.pressure );
                */
                const std::string meshName = "sphere.mesh";
                /* - @todo Так ли каждый раз нужна новая сущность?
                const std::string entityName = meshName + ".entity";
                const bool has = sm->hasEntity( entityName );
                Ogre::Entity* image = has ?
                    sm->getEntity( entityName ) :
                    sm->createEntity( entityName, meshName );
                */
                Ogre::Entity* image = sm->createEntity( meshName );
                auto childScene = sn->createChildSceneNode();
                childScene->attachObject( image );
                // Координаты образа кратны масштабу
                childScene->setPosition(
                    (float)coord.get<0>() * scale,
                    0.0f,
                    (float)coord.get<1>() * scale
                );
                // Образ заполняет ячейку целиком
                //const Ogre::Vector3 fillScale( scale / image->getBoundingRadius() );
                //childScene->setScale( fillScale );
#endif

                // Работаем через биллборды
                // @source http://89.151.96.106/forums/viewtopic.php?f=10&t=60455

                // @todo Визаулизировать в зависимости от характеристики ячейки и соседей.

                // Позиционируем биллборд

                Ogre::Billboard* b = bs->createBillboard(
                    (float)coord.get<0>() * m.scale,
                    0.0f,
                    (float)coord.get<1>() * m.scale
                );
                b->setRotation( Ogre::Degree( (float)rand() ) );
                /*
                b.setPosition(
                    (float)coord.get<0>() * m.scale,
                    0.0f,
                    (float)coord.get<1>() * m.scale
                );
                bs->injectBillboard( b );
                */
                
                // @test
                //break;

            } // for (size_t x = 0; x < m.N; ++x)

        } // for (size_t z = 0; z < m.M; ++z)

        //bs->endBillboards();

    } // if ( m.update || !m.sm->hasSceneNode( sceneName ) )

}
예제 #11
0
void JumpTape::updateStateFrame(double simulation_frame_time) {
    mRuntime += simulation_frame_time;
    mKeyboard = dt::InputManager::get()->getKeyboard();
    double field_speed = mRuntime/1000; 
    
    // Move each tile. 
    for(uint8_t i=0; i<TILES; ++i) {
        Ogre::Billboard* tile = mTiles->getBillboard(i);
        tile->setPosition(tile->getPosition() - Ogre::Vector3(field_speed, 0, 0));
    }
    
    // Wheater the next tile should be blank or present.
    bool blank = _GetTileType();
    
    // Move the first tile at the end of the group if it went beyond left margin.
    static uint8_t i = 0; //  index for selecting the right tile.
    Ogre::Billboard* tile = mTiles->getBillboard(i);
    if(tile->getPosition().x < (-GAME_WITDH/2)-4) {
        // Get position of the last (precedent) tile.
        double last_tile_x = mTiles->getBillboard((i+TILES-1) % TILES)->getPosition().x;
        // Append billboard to end.
        tile->setPosition(last_tile_x+TILE_X, dt::Random::get(-3, 3), 0);
        tile->setTexcoordIndex(blank);
        i++; // Switch to next tile...
        i %= TILES; // ...in a cicle.
    }
    
    // Move player.
    // Player and tile variables.
    tile = mTiles->getBillboard((i+2) % TILES); // The tile on which the player is.
    static float jump_height = 0; // The height of each jump.
    static bool jump_allowed = false; // Jump is not allowed when the player is already on air.
    bool blank_tile = tile->getTexcoordIndex(); // Wheater the tile under the player is blank.
    Ogre::Vector3 player_pos = mPlayer->getPosition();
    Ogre::Vector3 tile_pos = tile->getPosition(); // Position of the tile under the player.
    
    // Jump.
    if(mKeyboard->isKeyDown(OIS::KC_SPACE) 
        && (jump_height < MAX_JUMP_HEIGHT) && jump_allowed) {
        player_pos += Ogre::Vector3(0, JUMP_POWER, 0);
        mPlayer->setPosition(player_pos);
        jump_height += JUMP_POWER;
    }
    else {
        jump_allowed = false; // Once the player release space he can't go up anymore.
    }
    
    
    float tile_top = tile_pos.y + TILE_Y * 2; // Top of the tile.
    // Wheater the player is running on the tile.
    bool on_tile = (player_pos.y <= tile_top+0.1) && (player_pos.y >= tile_top-0.1); 
    
    // Gravity.
    if((blank_tile || !on_tile) && !jump_allowed) {
        player_pos -= Ogre::Vector3(0, G_POWER, 0);
        mPlayer->setPosition(player_pos);
    }
    
    // Evaluate if jump is allowed.
    if(on_tile && !blank_tile) {
        jump_height = 0;
        jump_allowed = true;
        // The player is running, change animation.
        mPlayer->setTexcoordIndex(static_cast<uint8_t>(mRuntime*10) % PLAYER_FRAME);
    }
    
    // Reset game.
    if(mKeyboard->isKeyDown(OIS::KC_N)) {
        mRuntime=0;
        mPlayer->setPosition(mPlayer->getPosition().x, tile_pos.y+4, 0);
        tile->setTexcoordIndex(0);
    }
    
    // Show reset game info.
    static QString time;
    if(player_pos.y < -4) {
        mGameInfo->setText("You ran for " + time + " seconds, press N for a new game");
    }
    else {
        time = dt::Utils::toString(static_cast<uint32_t>(mRuntime));
        mGameInfo->setText("You ran for " + time + " seconds");
    }
}
예제 #12
0
void JumpTape::onInitialize() {
        auto scene = addScene(new dt::Scene("JumpTape_scene"));
        OgreProcedural::Root::getInstance()->sceneManager = scene->getSceneManager();

        dt::ResourceManager::get()->addResourceLocation("", "FileSystem", true);
        Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
        Ogre::FontManager::getSingleton().load("DejaVuSans", "General");

        auto camnode = scene->addChildNode(new dt::Node("camnode"));
        camnode->setPosition(Ogre::Vector3(0, 0, 40));
        camnode->addComponent(new dt::CameraComponent("cam"))->lookAt(Ogre::Vector3(0, 0, 0));
        
        auto background = scene->addChildNode(new dt::Node("background"));
        background->setPosition(Ogre::Vector3(0, 0, -1));
        auto background_billboard = background->addComponent( new dt::BillboardSetComponent(
                "background_billboard", 1, "jumptape-background.jpg"));
        background_billboard->getOgreBillboardSet()->setDefaultDimensions(50, 34);

        mField = scene->addChildNode(new dt::Node("field_node"));
        mField->setPosition(Ogre::Vector3(0, 0, 0));
        
        auto billboard = mField->addComponent(new dt::BillboardSetComponent("tiles", TILES));
        billboard->setTextureFromFile("jumptape-tiles.png");
        mTiles = billboard->getOgreBillboardSet();
        mTiles->setTextureStacksAndSlices(1, 2);
        mTiles->setDefaultDimensions(TILE_X, TILE_Y);
        mTiles->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY); // Always visible
        
        for(uint8_t i=0; i<TILES; ++i) {    
            // Consecutive blank tiles, must be under MAX_BLANK_TILE,
            // otherwise the player can't reach the other tile.
            bool blank; 
            
            if(i<5) { // Plain start.
               blank = false;
            }
            else {
               blank = _GetTileType();
            }
            
            mTiles->setBillboardOrigin(Ogre::BBO_CENTER);
            Ogre::Billboard* tile = mTiles->createBillboard((-GAME_WITDH/2)+(TILE_X*i), 0, 0);
            tile->setTexcoordIndex(blank);
        }

        auto player = scene->addChildNode(new dt::Node("player"));
        player->setPosition(Ogre::Vector3(0, 0, 0));
        auto billboard_component = 
            player->addComponent(new dt::BillboardSetComponent("player",
                                                               1, "jumptape-jumper.png"));
        Ogre::BillboardSet* player_billboard = billboard_component->getOgreBillboardSet();
        player_billboard->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY);
        player_billboard->setTextureStacksAndSlices(1, 12);
        player_billboard->setDefaultDimensions(2, 2);
        mPlayer = player_billboard->getBillboard(0);
        mPlayer->setPosition(mTiles->getBillboard(2)->getPosition().x-1.6, // Match edges of image.
                             mTiles->getBillboard(2)->getPosition().y+9, 0);
        
        auto info_node = scene->addChildNode(new dt::Node("info"));
        info_node->setPosition(Ogre::Vector3(0, (-GAME_HEIGHT/2)+5, 2));
        mGameInfo = info_node->addComponent(new dt::TextComponent(""));
        mGameInfo->setFont("DejaVuSans");
        mGameInfo->setFontSize(20);
        mGameInfo->setColor(Ogre::ColourValue::White);
}
예제 #13
0
int main(int argc, char* argv[])
{
	std::unique_ptr<ExecutionArgs> exArgs(new ExecutionArgs());
	if (!processCommandLineArgs(argc, argv, *exArgs)) {
		return -1;
	} else if (exArgs->helpPrompt) {
		std::cout << "Usage: sts [--help] || [--config]" << std::endl;
		std::cout << "Options:" << std::endl;
		std::cout << "\t --help - print this message;" << std::endl;
		std::cout << "\t --config - show config dialog." << std::endl;
		std::cout << std::endl;
		return 0;
	}

	try {
		Ogre::String lConfigFileName = "ogre.cfg";
		Ogre::String lPluginsFileName = "plugins.cfg";
		Ogre::String lLogFileName = "Ogre_STS.log";

		std::unique_ptr<Ogre::Root> lRoot(new Ogre::Root(lPluginsFileName, lConfigFileName, lLogFileName));

		if (exArgs->showConfigDialog) {
			if (!lRoot->showConfigDialog()) {
				return 0;
			}
		}

		Ogre::String lWindowTitle = "STS";
		Ogre::String lCustomCapacities = "";

		/* Check for the valid ogre.cfg */
		bool lCreateAWindowAutomatically = lRoot->restoreConfig();
		if (!lCreateAWindowAutomatically) {
			initSomeRenderSystem(lRoot);
		}
		Ogre::RenderWindow* lWindow = lRoot->initialise(lCreateAWindowAutomatically, lWindowTitle, lCustomCapacities);

		if (!lWindow) {
			/* ogre.cfg is not available - start with hardcoded parameters */
			unsigned int lSizeX = 800;
			unsigned int lSizeY = 600;
			bool lFullscreen = false;

			Ogre::NameValuePairList lParams;
			lParams["FSAA"] = "0";
			lParams["vsync"] = "true";
			lWindow = lRoot->createRenderWindow(lWindowTitle, lSizeX, lSizeY, lFullscreen, &lParams);
		}

		/* Create a scene manager */
		Ogre::SceneManager* lScene = lRoot->createSceneManager(Ogre::ST_GENERIC, "SceneManager");

		Ogre::SceneNode* lRootSceneNode = lScene->getRootSceneNode();

		/* Create camera */
		Ogre::Camera* lCamera = lScene->createCamera("MyCamera");

		/* Create viewport (camera <-> window) */
		Ogre::Viewport* vp = lWindow->addViewport(lCamera);

		vp->setAutoUpdated(true);
		vp->setBackgroundColour(Ogre::ColourValue(1, 0, 1));

		lCamera->setAspectRatio(float(vp->getActualWidth()) / vp->getActualHeight());
		lCamera->setPosition(Ogre::Vector3(0, 100, -1));
		lCamera->lookAt(Ogre::Vector3(0, 0, 0));

		/* Set clipping*/
		lCamera->setNearClipDistance(1.5f);
		lCamera->setFarClipDistance(3000.0f);

		/* Lighting */
		Ogre::Light* lLight = lScene->createLight("MainLight");
		lLight->setPosition(Ogre::Vector3(0, 100, 0));

		/* Resource manager */
		Ogre::String lRcGroupName = "Main group";
		initResourceMainGroup(lRcGroupName);

		/* Load model */
		Ogre::Entity* lShipEntity = lScene->createEntity("airship.mesh");
		lShipEntity->setCastShadows(false);

		Ogre::SceneNode* lShipNode = lRootSceneNode->createChildSceneNode();
		lShipNode->attachObject(lShipEntity);
		lShipNode->setScale(Ogre::Vector3(3.15f, 3.15f, 3.15f));

		/* Starship start point */
		Ogre::Vector3 razorSP(0, -200, -100);
		lShipNode->setPosition(razorSP);

		/* Sprite billboard */
		Ogre::SceneNode* lSpriteNode = lRootSceneNode->createChildSceneNode();
		Ogre::BillboardSet* lBillboardSet = lScene->createBillboardSet();
		lBillboardSet->setMaterialName("enemy_01", lRcGroupName);
		lBillboardSet->setTextureStacksAndSlices(1, 4);
		Ogre::Billboard* lSpriteBillboard = lBillboardSet->createBillboard(Ogre::Vector3(0, 0, 0));
		lSpriteBillboard->setDimensions(48.0f / 2.0f, 58.0f / 2.0f);
		lSpriteBillboard->setTexcoordIndex(1);
		lSpriteNode->attachObject(lBillboardSet);
		lSpriteNode->setPosition(Ogre::Vector3(0, -200, 100));

		/* Obtain the timer pointer */
		Ogre::Timer* lTimer = lRoot->getTimer();

		/* Skip all the messages */
		lWindow->setAutoUpdated(false);
		lRoot->clearEventTimes();

		while (!lWindow->isClosed()) {
			float angle = Ogre::Math::Sin(float(lTimer->getMilliseconds()) * Ogre::Math::PI / 2000.0f) * Ogre::Math::PI / 4.0f;
			float diplacement = Ogre::Math::Cos(float(lTimer->getMilliseconds()) * Ogre::Math::PI / 2000.0f) * 100.0f;
			lShipNode->setOrientation(Ogre::Quaternion(Ogre::Radian(angle), Ogre::Vector3(0, 0, 1)));
			lShipNode->setPosition(razorSP + Ogre::Vector3(diplacement, 0.0f, 0.0f));

			unsigned int spriteFrame = (lTimer->getMilliseconds() / 125) % 2;
			lSpriteBillboard->setTexcoordIndex(spriteFrame);

			lWindow->update(false);
			lWindow->swapBuffers();
			lRoot->renderOneFrame();

			Ogre::WindowEventUtilities::messagePump();
		}
		Ogre::LogManager::getSingleton().logMessage("Render window closed.");
	}
	catch (Ogre::Exception &e) {
		std::cerr << "Ogre::Exception: " << e.what() << std::endl;
	}
	catch (std::exception &e) {
		std::cerr << "std::exception: " << e.what() << std::endl;
	}

	return 0;
}