Exemple #1
0
GLuint MGLTexture::GetTextureType(std::string name) {
	return m_textures->at(GetTexture(name, GL_TRUE));
}
already_AddRefed<gfx::SourceSurface>
D3D11ShareHandleImage::GetAsSourceSurface()
{
  RefPtr<ID3D11Texture2D> texture = GetTexture();
  if (!texture) {
    NS_WARNING("Cannot readback from shared texture because no texture is available.");
    return nullptr;
  }

  RefPtr<ID3D11Device> device;
  texture->GetDevice(getter_AddRefs(device));

  RefPtr<IDXGIKeyedMutex> keyedMutex;
  if (FAILED(texture->QueryInterface(static_cast<IDXGIKeyedMutex**>(getter_AddRefs(keyedMutex))))) {
    NS_WARNING("Failed to QueryInterface for IDXGIKeyedMutex, strange.");
    return nullptr;
  }

  if (FAILED(keyedMutex->AcquireSync(0, 0))) {
    NS_WARNING("Failed to acquire sync for keyedMutex, plugin failed to release?");
    return nullptr;
  }

  D3D11_TEXTURE2D_DESC desc;
  texture->GetDesc(&desc);

  CD3D11_TEXTURE2D_DESC softDesc(desc.Format, desc.Width, desc.Height);
  softDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
  softDesc.BindFlags = 0;
  softDesc.MiscFlags = 0;
  softDesc.MipLevels = 1;
  softDesc.Usage = D3D11_USAGE_STAGING;

  RefPtr<ID3D11Texture2D> softTexture;
  HRESULT hr = device->CreateTexture2D(&softDesc,
                                       NULL,
                                       static_cast<ID3D11Texture2D**>(getter_AddRefs(softTexture)));

  if (FAILED(hr)) {
    NS_WARNING("Failed to create 2D staging texture.");
    keyedMutex->ReleaseSync(0);
    return nullptr;
  }

  RefPtr<ID3D11DeviceContext> context;
  device->GetImmediateContext(getter_AddRefs(context));
  if (!context) {
    keyedMutex->ReleaseSync(0);
    return nullptr;
  }

  context->CopyResource(softTexture, texture);
  keyedMutex->ReleaseSync(0);

  RefPtr<gfx::DataSourceSurface> surface =
    gfx::Factory::CreateDataSourceSurface(mSize, gfx::SurfaceFormat::B8G8R8X8);
  if (NS_WARN_IF(!surface)) {
    return nullptr;
  }

  gfx::DataSourceSurface::MappedSurface mappedSurface;
  if (!surface->Map(gfx::DataSourceSurface::WRITE, &mappedSurface)) {
    return nullptr;
  }

  D3D11_MAPPED_SUBRESOURCE map;
  hr = context->Map(softTexture, 0, D3D11_MAP_READ, 0, &map);
  if (!SUCCEEDED(hr)) {
    surface->Unmap();
    return nullptr;
  }

  for (int y = 0; y < mSize.height; y++) {
    memcpy(mappedSurface.mData + mappedSurface.mStride * y,
           (unsigned char*)(map.pData) + map.RowPitch * y,
           mSize.width * 4);
  }

  context->Unmap(softTexture, 0);
  surface->Unmap();

  return surface.forget();
}
bool
PersistentBufferProviderShared::SetForwarder(KnowsCompositor* aFwd)
{
  MOZ_ASSERT(aFwd);
  if (!aFwd) {
    return false;
  }

  if (mFwd == aFwd) {
    // The forwarder should not change most of the time.
    return true;
  }

  if (IsActivityTracked()) {
    mFwd->GetActiveResourceTracker().RemoveObject(this);
  }

  if (mFwd->GetTextureForwarder() != aFwd->GetTextureForwarder() ||
      mFwd->GetCompositorBackendType() != aFwd->GetCompositorBackendType()) {
    // We are going to be used with an different and/or incompatible forwarder.
    // This should be extremely rare. We have to copy the front buffer into a
    // texture that is compatible with the new forwarder.

    // Grab the current front buffer.
    RefPtr<TextureClient> prevTexture = GetTexture(mFront);

    // Get rid of everything else
    Destroy();

    if (prevTexture) {
      RefPtr<TextureClient> newTexture = TextureClient::CreateForDrawing(
        aFwd, mFormat, mSize,
        BackendSelector::Canvas,
        TextureFlags::DEFAULT,
        TextureAllocationFlags::ALLOC_DEFAULT
      );

      MOZ_ASSERT(newTexture);
      if (!newTexture) {
        return false;
      }

      // If we early-return in one of the following branches, we will
      // leave the buffer provider in an empty state, since we called
      // Destroy. Not ideal but at least we won't try to use it with a
      // an incompatible ipc channel.

      if (!newTexture->Lock(OpenMode::OPEN_WRITE)) {
        return false;
      }

      if (!prevTexture->Lock(OpenMode::OPEN_READ)) {
        newTexture->Unlock();
        return false;
      }

      bool success = prevTexture->CopyToTextureClient(newTexture, nullptr, nullptr);

      prevTexture->Unlock();
      newTexture->Unlock();

      if (!success) {
        return false;
      }

      if (!mTextures.append(newTexture)) {
        return false;
      }
      mFront = Some<uint32_t>(mTextures.length() - 1);
      mBack = mFront;
    }
  }

  mFwd = aFwd;

  return true;
}
Exemple #4
0
Player::Player() : texture(GetTexture("man.png")) {}
Exemple #5
0
std::vector<Vertex> ModelLoader::load(int& numTriangles, int& numTextures)
{
	std::ifstream fileCheck(filename);
	Vertex tempVert;
	std::vector<Vertex> geometry;
	std::deque<aiVector3D> texCoord;
	numTriangles = 0;
	numTextures = 0;

	for(int i = 0; i < 3; i++)
		tempVert.color[i] = 1.0;

	if(!fileCheck) {
		std::cerr << "Error: Unable to open object file" << std::endl;
		exit(-1);
	}

	fileCheck.close();

	Assimp::Importer importer;

	auto scene = importer.ReadFile(filename, aiProcessPreset_TargetRealtime_Fast);

	if(!scene) {
		std::cerr << "Error: " << importer.GetErrorString() << std::endl;
		exit(-1);
	}

	std::cout << "Material Count: " << scene->mNumMaterials << std::endl;
	
	if(scene->HasMaterials()) {
		const auto& material = scene->mMaterials[0];
		aiColor3D color(0.0f,0.0f,0.0);
		material->Get(AI_MATKEY_COLOR_DIFFUSE, color);
		tempVert.color[0] = color.r;
		tempVert.color[1] = color.g;
		tempVert.color[2] = color.b;
	}

	for(unsigned int i = 0; i < scene->mNumMeshes; i++) {
		auto mesh = scene->mMeshes[i];

		if(scene->mNumMaterials > i+1) {
			auto material = scene->mMaterials[i+1];

			aiColor3D color(1.0f,1.0f,1.0f);
			material->Get(AI_MATKEY_COLOR_DIFFUSE, color);
			tempVert.color[0] = color.r;
			tempVert.color[1] = color.g;
			tempVert.color[2] = color.b;

			if(material->GetTextureCount(aiTextureType_DIFFUSE) > 0) {
				aiString path;

				if(material->GetTexture(aiTextureType_DIFFUSE, 0, &path, 
					NULL, NULL, NULL, NULL, NULL) == AI_SUCCESS) {
					
					std::cout << "Texture Path: " << path.C_Str() << std::endl;
					numTextures++;
					loadTexture(path.C_Str());
/*
					for(unsigned int j = 0; j < mesh->mNumVertices; j++) {
						const auto textureCoords = mesh->HasTextureCoords(0) ?
							 mesh->mTextureCoords[0][j] : aiVector3D(0.0f,0.0f,0.0f);

						//texCoord.emplace_back(textureCoords);
					}
					*/
				}

			}

		}

		numTriangles += mesh->mNumFaces;
		for(unsigned int j = 0; j < mesh->mNumFaces; j++) {
			const auto& face = mesh->mFaces[j];

			for(unsigned int k = 0; k < face.mNumIndices; k++) {
				const auto& vertex = mesh->mVertices[face.mIndices[k]];
				tempVert.position[0] = vertex.x;
				tempVert.position[1] = vertex.y;
				tempVert.position[2] = vertex.z;
				
				const auto& textureVertex = mesh->HasTextureCoords(0) ? mesh->mTextureCoords[0][face.mIndices[k]]
						: aiVector3D(0,0,0);
				tempVert.textCoord[0] = textureVertex[0];
				tempVert.textCoord[1] = textureVertex[1];
			
				geometry.push_back(tempVert);
			}
		}
	}

	//loadTexture("checkerboard.jpg");
	std::cout << "size: " << geometry.size() << std::endl
			  << "bytes: " << sizeof(tempVert) * geometry.size() << std::endl;
	return geometry;
}
Exemple #6
0
//
// ICWindowTitle::DrawSelf
//
void ICWindowTitle::DrawSelf(PaintInfo &pi)
{
    DrawCtrlBackground(pi, GetTexture());
    DrawCtrlFrame(pi);
    DrawCtrlText(pi);
}
Exemple #7
0
/** 
 * @brief ファイル名からテクスチャを取得
 * @param filename [IN] ファイル名
 * @return nxTexture
 */
nxTexture*
nxTextureManager::GetTexture(const char *filename)
{
    nxTextureInfo *texInfo;
    return GetTexture(filename, &texInfo);
}
void Player::HandleControls(const jutil::GameTime& timespan)
{

	// Directional movement
	if (p_Window->GetKey(Mega::Keys::MOVE_LEFT) == JKEY_PRESS)
		MoveX(-0.05f);
	if (p_Window->GetKey(Mega::Keys::MOVE_LEFT) == JKEY_HOLD)
	{
		GetRigidBody()->ApplyForce(jmath::vec3(-0.5f, 0.f, 0.f));
		m_Direction = Mega::Direction::LEFT;
	}
	else if (p_Window->GetKey(Mega::Keys::MOVE_LEFT) == JKEY_RELEASE)
		GetRigidBody()->ClearForce();
	if (p_Window->GetKey(Mega::Keys::MOVE_RIGHT) == JKEY_HOLD)
	{
		GetRigidBody()->ApplyForce(jmath::vec3(0.5f, 0.f, 0.f));
		m_Direction = Mega::Direction::RIGHT;
	}
	
	/// Jumping

	// If space bar is just released, prevent jumping (to stop double jumping in the air)
	if (p_Window->GetKey(Mega::Keys::JUMP) == JKEY_RELEASE && m_TimerJump.ElapsedMilliseconds() > 0)
		m_TimerJump.SetTime(JTime::Milliseconds(JUMP_LIMIT));

	// If the player is standing on a block, allow jumping
	if (m_HasCollidedBelow && m_TimerJump.ElapsedMilliseconds() > 0 && m_TimerJump.ElapsedMilliseconds() >= JUMP_LIMIT && !(p_Window->GetKey(Mega::Keys::JUMP) == JKEY_PRESS || p_Window->GetKey(Mega::Keys::JUMP) == JKEY_HOLD))
		m_TimerJump.SetTime(JTime::Milliseconds(0));

	// If the player is mid-jump and can still hold the button for a longer jump, apply forces
	if (m_TimerJump.ElapsedMilliseconds() >= 0 && m_TimerJump.ElapsedMilliseconds() < JUMP_LIMIT && p_Window->GetKey(Mega::Keys::JUMP) == JKEY_HOLD)
	{
		m_TimerJump += timespan;
		if (m_TimerJump.ElapsedMilliseconds() < JUMP_LIMIT)
		{
			m_PlayerState = PlayerState::JUMPING;

			float t = std::max(m_TimerJump.ElapsedMilliseconds(), 250);
			GetRigidBody()->ApplyForce(jmath::vec3(0, -0.0095f*((t) / 12.f), 0.f));

			if (m_TimerJump.ElapsedMilliseconds() == timespan.ElapsedMilliseconds())
				GetRigidBody()->ApplyForce(jmath::vec3(0.f, -3.f, 0.f));

			if (m_TimerJump.ElapsedMilliseconds() != 0 && m_TimerJump.ElapsedMilliseconds() < 100)
			{
				jmath::vec3 v = GetRigidBody()->GetVelocity();
				v.x = 0.f;
				GetRigidBody()->SetVelocity(v);

				v = m_CollisionY.GetRigidBody()->GetVelocity();
				v.x = 0.f;
				m_CollisionY.GetRigidBody()->SetVelocity(v);

			}
		}
	}
	// Otherwise, we've ran out of jumping time 
	else if (m_TimerJump.ElapsedMilliseconds() < 0) 
	{
		m_TimerJump += timespan;
		if (m_TimerJump.ElapsedMilliseconds() > 0)
			m_TimerJump.SetTime(0);
	}

	// If the jump button has been released since jumping and we're on a tile, change state
	if (p_Window->GetKey(Mega::Keys::JUMP) != JKEY_HOLD && m_HasCollidedBelow)
		m_PlayerState = PlayerState::GROUNDED;


	m_TimerBulletAnimationDelay += timespan;

	//// Firing
	if (p_Window->GetKey(Mega::Keys::FIRE) == JKEY_PRESS)// && m_TimerBulletAnimationDelay.ElapsedMilliseconds() > FIRING_DELAY)
	{
		m_TimerBulletAnimationDelay.SetTime(0);
		jmath::vec2 pos = GetPositionXY();

		pos.x += static_cast<bool>(m_Direction) ? 12.f : -12.f;
		pos.y--;
		m_Bullets.push_back(Bullet(pos, m_Direction));
		m_Bullets.back().SetTexture(GetTexture());
		m_Bullets.back().SetRectangle(jmath::vec4(104, 72, 8, 8));
	}

	if (p_Window->GetKey(JKEY_KEY_C) == JKEY_PRESS)
		m_Health = 0;
}
	void ImageBasedLensFlare::LensBlur(const Ptr<Texture> & setupTex, const Ptr<Texture> & target)
	{
		int32_t tileSize = 9;

		//Extract Sprite Points
		int32_t extractWidth = (setupTex->GetDesc().width + tileSize - 1) / tileSize;
		int32_t extractHeight = (setupTex->GetDesc().height + tileSize - 1) / tileSize;

		RenderBufferDesc spPointsBufDesc;
		spPointsBufDesc.bindFlag = BUFFER_BIND_SHADER_RESOURCE | BUFFER_BIND_UNORDERED_ACCESS;
		spPointsBufDesc.elementSize = sizeof(float2) + sizeof(float3);
		spPointsBufDesc.numElements = extractWidth * extractHeight;
		spPointsBufDesc.cpuAccess = 0;
		spPointsBufDesc.bStructured = true;

		auto spPointsBufRef = BufferPool::Instance().FindFree(spPointsBufDesc);
		auto spPointsBuf = spPointsBufRef->Get()->Cast<RenderBuffer>();

		{
			auto ps = Shader::FindOrCreate<ExtractSpritePointsPS>();

			ps->SetScalar("spriteThreshold", _spriteThreshold);
			ps->SetSRV("setupTex", setupTex->GetShaderResourceView());
			ps->SetUAV("spPointsBuf", spPointsBuf->GetUnorderedAccessView(0, 0, RENDER_FORMAT_UNKNOWN, BUFFER_UAV_APPEND));
			ps->Flush();

			DrawQuad({}, 0.0f, 0.0f, (float)extractWidth, (float)extractHeight);
		}

		//Render Sprites
		if (!_indirectAgsBuf)
		{
			RenderBufferDesc indirectArgsBufDesc;
			indirectArgsBufDesc.bindFlag = BUFFER_BIND_INDIRECT_ARGS;
			indirectArgsBufDesc.elementSize = 16;
			indirectArgsBufDesc.numElements = 1;
			indirectArgsBufDesc.cpuAccess = 0;
			indirectArgsBufDesc.bStructured = false;

			uint32_t initData[] = { 0, 1, 0, 0 };

			_indirectAgsBuf = Global::GetRenderEngine()->GetRenderFactory()->CreateBuffer();
			_indirectAgsBuf->SetDesc(indirectArgsBufDesc);
			_indirectAgsBuf->Init(initData);
		}

		spPointsBuf->CopyStructureCountTo(_indirectAgsBuf, 0, 0, spPointsBuf->GetDesc().numElements, RENDER_FORMAT_UNKNOWN, BUFFER_UAV_APPEND);

		{
			auto vs = Shader::FindOrCreate<LensBlurVS>();
			auto gs = Shader::FindOrCreate<LensBlurGS>();
			auto ps = Shader::FindOrCreate<LensBlurPS>();

			vs->SetScalar("texSize", target->GetTexSize());
			gs->SetScalar("texSize", target->GetTexSize());

			gs->SetScalar("flareIntensity", _flareIntensity);

			vs->SetSRV("spPointsRenderBuf", spPointsBuf->GetShaderResourceView(0, 0, RENDER_FORMAT_UNKNOWN));

			auto lensTexAsset = Asset::Find<TextureAsset>("Textures/Bokeh_Circle.dds");
			if (!lensTexAsset->IsInit())
				lensTexAsset->Init();
			auto lensTex = lensTexAsset->GetTexture();
			ps->SetSRV("lensTex", lensTex->GetShaderResourceView());

			ps->SetSampler("linearSampler", SamplerTemplate<>::Get());

			vs->Flush();
			gs->Flush();
			ps->Flush();

			auto rc = Global::GetRenderEngine()->GetRenderContext();

			rc->SetVertexBuffer({});
			rc->SetIndexBuffer(nullptr);
			rc->SetPrimitiveTopology(PRIMITIVE_TOPOLOGY_POINTLIST);

			rc->SetViewport(GetTextureQuadViewport(target));

			rc->SetRenderTargets({ target->GetRenderTargetView(0, 0, 1) });
			rc->SetDepthStencil(nullptr);
			rc->SetDepthStencilState(DepthStencilStateTemplate<false>::Get());

			rc->SetBlendState(BlendStateTemplate<false, false, true, BLEND_PARAM_SRC_ALPHA, BLEND_PARAM_ONE, BLEND_OP_ADD>::Get());

			rc->DrawInstancedIndirect(_indirectAgsBuf, 0);

			rc->ResetShader(SHADER_GS);
			rc->SetBlendState(nullptr);
		}
	}
Exemple #10
0
BOOL Material::LoadFromFile(CTSTR lpFile)
{
    traceIn(Material::LoadFromFile);

    String path;

    ConfigFile materialFile;
    if(!materialFile.Open(lpFile))
    {
        AppWarning(TEXT("Couldn't load material file '%s'"), lpFile);
        return FALSE;
    }

    effect = ::GetEffect(materialFile.GetString(TEXT("Material"), TEXT("Effect")));

    if(!effect)
    {
        AppWarning(TEXT("Invalid effect in material file '%s'"), lpFile);
        return FALSE;
    }

    String soundName = materialFile.GetString(TEXT("Material"), TEXT("SoftSound"));
    if(soundName.IsValid()) SetSoftHitSound(soundName);
    soundName = materialFile.GetString(TEXT("Material"), TEXT("HardSound"));
    if(soundName.IsValid()) SetHardHitSound(soundName);

    restitution = materialFile.GetFloat(TEXT("Material"), TEXT("Restitution"));
    friction    = materialFile.GetFloat(TEXT("Material"), TEXT("Friction"), 0.5f);

    DWORD curParamID = 0;

    HANDLE hCurParam;
    while(hCurParam = effect->GetParameter(curParamID++))
    {
        EffectParameterInfo paramInfo;
        effect->GetEffectParameterInfo(hCurParam, paramInfo);

        if(paramInfo.propertyType != EffectProperty_None)
        {
            if(paramInfo.propertyType == EffectProperty_Texture)
            {
                MaterialParameter *param = Params.CreateNew();
                param->type = Parameter_Texture;
                param->handle = hCurParam;
                *(BaseTexture**)param->data = GetTexture(materialFile.GetString(TEXT("Parameters"), paramInfo.name));
            }
            else if(paramInfo.propertyType == EffectProperty_Color)
            {
                MaterialParameter *param = Params.CreateNew();
                param->type = Parameter_Vector3;
                param->handle = hCurParam;
                Vect chi = materialFile.GetColor3(TEXT("Parameters"), paramInfo.name);
                mcpy(param->data, &chi, sizeof(Vect));
            }
            else if(paramInfo.propertyType == EffectProperty_Float)
            {
                MaterialParameter *param = Params.CreateNew();
                param->type = Parameter_Float;
                param->handle = hCurParam;
                *(float*)param->data = materialFile.GetFloat(TEXT("Parameters"), paramInfo.name)*paramInfo.fMul;
            }
        }
    }

    return TRUE;

    traceOut;
}
Exemple #11
0
Menu::Menu(unique_ptr<Game> & game) :
	mGame(game),
	mCameraChangeTime(30 * 60),
	mDistBetweenButtons(68),
	mVisible(true),
	mPage(Page::Main),
	mLoadSaveGameName("") {
	// Load config
	mConfig.Load("config.cfg");
	mLocalization.Load(mGame->GetLocalizationPath() + "menu.loc");
	// load background scene
	mScene = mGame->GetEngine()->GetSceneFactory()->LoadScene("data/maps/menu.scene");
	// create gui scene
	mGUIScene = mGame->GetEngine()->CreateGUIScene();
	// create camera
	mpCamera = make_unique<GameCamera>(mGUIScene);
	mCameraPos1 = mScene->FindChild("Camera");
	mCameraPos2 = mScene->FindChild("Camera2");
	mpCamera->mCamera->Attach(mCameraPos1);
	mCameraFadeActionDone = false;
	mCameraInitialPosition = Vector3(0, 0, 0);
	mCameraAnimationNewOffset = Vector3(0.5, 0.5, 0.5);

	auto soundSystem = mGame->GetEngine()->GetSoundSystem();

	mPickSound = soundSystem->LoadSound2D("data/sounds/menupick.ogg");
	mMusic = soundSystem->LoadMusic3D("data/music/menu.ogg");
	mMusic->SetPosition(mScene->FindChild("Radio")->GetPosition());
	mMusic->SetRolloffFactor(0.1);
	mMusic->SetRoomRolloffFactor(0.1);

	const float buttonHeight = 30;
	const float buttonWidth = 128;
	const float buttonXOffset = 10;

	auto renderer = mGame->GetEngine()->GetRenderer();

	// load textures
	auto texTab = renderer->GetTexture("data/gui/menu/tab.tga");
	auto texButton = renderer->GetTexture("data/gui/menu/button.tga");
	auto texSmallButton = renderer->GetTexture("data/gui/menu/button.tga");

	// Setup
	mCanvas = mGUIScene->CreateRect(0, 0, 0, 0, nullptr);
	{
		// Main 
		mGUIMainButtonsCanvas = mGUIScene->CreateRect(20, ruVirtualScreenHeight - 4.0 * mDistBetweenButtons, buttonWidth + 2 * buttonXOffset, buttonHeight * 8.5, texTab, pGUIProp->mBackColor);
		mGUIMainButtonsCanvas->Attach(mCanvas);
		{
			mContinueGameButton = mGUIScene->CreateButton(buttonXOffset, 5, buttonWidth, buttonHeight, texButton, mLocalization.GetString("continueButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mContinueGameButton->Attach(mGUIMainButtonsCanvas);
			mContinueGameButton->AddAction(GUIAction::OnClick, [this] { OnContinueGameClick(); });

			mStartButton = mGUIScene->CreateButton(buttonXOffset, 5 + 0.5f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("startButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mStartButton->Attach(mGUIMainButtonsCanvas);
			mStartButton->AddAction(GUIAction::OnClick, [this] { OnStartNewGameClick(); });

			mSaveGameButton = mGUIScene->CreateButton(buttonXOffset, 5 + 1.0f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("saveButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mSaveGameButton->Attach(mGUIMainButtonsCanvas);
			mSaveGameButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::SaveGame); FillListOfSaveFiles(); });

			mLoadGameButton = mGUIScene->CreateButton(buttonXOffset, 5 + 1.5f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("loadButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mLoadGameButton->Attach(mGUIMainButtonsCanvas);
			mLoadGameButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::LoadGame); FillListOfSaveFiles(); });

			mOptionsButton = mGUIScene->CreateButton(buttonXOffset, 5 + 2.0f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("optionsButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mOptionsButton->Attach(mGUIMainButtonsCanvas);
			mOptionsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::Options); });

			mAuthorsButton = mGUIScene->CreateButton(buttonXOffset, 5 + 2.5f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("authorsButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mAuthorsButton->Attach(mGUIMainButtonsCanvas);
			mAuthorsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::Authors); });

			mExitButton = mGUIScene->CreateButton(buttonXOffset, 5 + 3.0f * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("exitButton"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mExitButton->Attach(mGUIMainButtonsCanvas);
			mExitButton->AddAction(GUIAction::OnClick, [this] { OnExitGameClick(); });
		}

		const int aTabX = 200;
		const int aTabY = ruVirtualScreenHeight - 4.0 * mDistBetweenButtons;
		const int aTabWidth = buttonWidth * 4;
		const int aTabHeight = buttonHeight * 8.5;

		// Modal window
		mModalWindow = make_unique<ModalWindow>(mGUIScene, aTabX, aTabY, aTabWidth, aTabHeight, texTab, texButton, pGUIProp->mBackColor);
		mModalWindow->AttachTo(mCanvas);

		// Page title
		mWindowText = mGUIScene->CreateText(" ", aTabX, aTabY - 21, aTabWidth, 32, pGUIProp->mFont, Vector3(255, 255, 255), TextAlignment::Left);
		mWindowText->Attach(mCanvas);

		// Product name
		mCaption = mGUIScene->CreateText("The Mine", 20, aTabY - 21, aTabWidth * 1.5f, 32, pGUIProp->mFont, Vector3(255, 255, 255), TextAlignment::Left);
		mCaption->Attach(mCanvas);

		// Options
		mGUIOptionsCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mGUIOptionsCanvas->Attach(mCanvas);
		{
			const int yOffset = (aTabHeight - 2 * mDistBetweenButtons) / 2;

			mGUIOptionsCommonButton = mGUIScene->CreateButton((aTabWidth - buttonWidth) / 2, yOffset, buttonWidth, buttonHeight, texButton, mLocalization.GetString("commonSettings"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mGUIOptionsCommonButton->Attach(mGUIOptionsCanvas);
			mGUIOptionsCommonButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::OptionsCommon); });

			mGUIOptionsControlsButton = mGUIScene->CreateButton((aTabWidth - buttonWidth) / 2, yOffset + 0.5 * mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("controls"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mGUIOptionsControlsButton->Attach(mGUIOptionsCanvas);
			mGUIOptionsControlsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::OptionsKeys); });

			mGUIOptionsGraphicsButton = mGUIScene->CreateButton((aTabWidth - buttonWidth) / 2, yOffset + mDistBetweenButtons, buttonWidth, buttonHeight, texButton, mLocalization.GetString("graphics"), pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
			mGUIOptionsGraphicsButton->Attach(mGUIOptionsCanvas);
			mGUIOptionsGraphicsButton->AddAction(GUIAction::OnClick, [this] { SetPage(Page::OptionsGraphics); });
		}

		// Options: Keys
		mOptionsKeysCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mGUIOptionsCanvas->Attach(mCanvas);
		mOptionsKeysCanvas->SetVisible(false);
		{
			// First column
			float x = 40, y = 10;

			mMoveForwardKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("forward"));
			mMoveForwardKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mMoveBackwardKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("backward"));
			mMoveBackwardKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mStrafeLeftKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("strafeLeft"));
			mStrafeLeftKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mStrafeRightKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("strafeRight"));
			mStrafeRightKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mJumpKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("jump"));
			mJumpKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mFlashLightKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("flashLight"));
			mFlashLightKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mRunKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("run"));
			mRunKey->AttachTo(mOptionsKeysCanvas);

			// Second column
			x += 150;
			y = 10;
			mInventoryKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("inventory"));
			mInventoryKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mUseKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("use"));
			mUseKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mQuickLoadKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("quickLoad"));
			mQuickLoadKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mQuickSaveKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("quickSave"));
			mQuickSaveKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mStealthKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("stealth"));
			mStealthKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mLookLeftKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("lookLeft"));
			mLookLeftKey->AttachTo(mOptionsKeysCanvas);
			y += 32 * 1.1f;
			mLookRightKey = make_unique<WaitKeyButton>(mGame, mGUIScene, x, y, texSmallButton, mLocalization.GetString("lookRight"));
			mLookRightKey->AttachTo(mOptionsKeysCanvas);
		}

		// Options: Graphics
		mOptionsGraphicsCanvas = mGUIScene->CreateRect(aTabX, aTabY, buttonWidth * 5.5, aTabHeight, texTab, pGUIProp->mBackColor);
		mOptionsGraphicsCanvas->Attach(mCanvas);
		mOptionsGraphicsCanvas->SetVisible(false);
		{
			float x = 30, y = 10;

			mFXAAButton = make_unique<RadioButton>(mGUIScene, x, y, texButton, mLocalization.GetString("fxaa"));
			mFXAAButton->AttachTo(mOptionsGraphicsCanvas);

			mFPSButton = make_unique<RadioButton>(mGUIScene, x, y + 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("showFPS"));
			mFPSButton->AttachTo(mOptionsGraphicsCanvas);

			mSpotShadowsButton = make_unique<RadioButton>(mGUIScene, x, y + mDistBetweenButtons, texButton, mLocalization.GetString("spotLightShadows"));
			mSpotShadowsButton->AttachTo(mOptionsGraphicsCanvas);

			mPointShadowsButton = make_unique<RadioButton>(mGUIScene, x, y + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("pointLightShadows"));
			mPointShadowsButton->AttachTo(mOptionsGraphicsCanvas);

			mHDRButton = make_unique<RadioButton>(mGUIScene, x, y + 2.0 * mDistBetweenButtons, texButton, mLocalization.GetString("hdr"));
			mHDRButton->AttachTo(mOptionsGraphicsCanvas);

			mParallaxButton = make_unique<RadioButton>(mGUIScene, x, y + 2.5 * mDistBetweenButtons, texButton, mLocalization.GetString("parallax"));
			mParallaxButton->AttachTo(mOptionsGraphicsCanvas);

			mVolumetricFogButton = make_unique<RadioButton>(mGUIScene, x, y + 3.0 * mDistBetweenButtons, texButton, mLocalization.GetString("volumetricFog"));
			mVolumetricFogButton->AttachTo(mOptionsGraphicsCanvas);

			// next column
			x += 170;

			mDynamicDirectionalLightShadows = make_unique<RadioButton>(mGUIScene, x, y, texButton, mLocalization.GetString("dynamicDirectionalLightShadows"));
			mDynamicDirectionalLightShadows->AttachTo(mOptionsGraphicsCanvas);

			mBloom = make_unique<RadioButton>(mGUIScene, x, y + 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("bloom"));
			mBloom->AttachTo(mOptionsGraphicsCanvas);

			mSoftParticles = make_unique<RadioButton>(mGUIScene, x, y + 1.0 * mDistBetweenButtons, texButton, mLocalization.GetString("softParticles"));
			mSoftParticles->AttachTo(mOptionsGraphicsCanvas);

			mVSync = make_unique<RadioButton>(mGUIScene, x, y + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("vsync"));
			mVSync->AttachTo(mOptionsGraphicsCanvas);
			//			mVSync->OnChange += [this] { mSettingsApplied->SetText(mLocalization.GetString("settingsNotApplied")); mSettingsApplied->SetColor(Vector3(255, 0, 0)); };

						// next column
			x += 170;

			mResolutionList = make_unique<ScrollList>(mGUIScene, x, y, texButton, mLocalization.GetString("resolution"));
			mResolutionList->AttachTo(mOptionsGraphicsCanvas);
			auto videoModes = mGame->GetEngine()->GetRenderer()->GetVideoModeList();
			for(auto videoMode : videoModes) {
				mResolutionList->AddValue(StringBuilder() << videoMode.mWidth << "x" << videoMode.mHeight << "@" << videoMode.mRefreshRate);
			}
			mResolutionList->OnChange += [this] { mSettingsApplied->SetText(mLocalization.GetString("settingsNotApplied")); mSettingsApplied->SetColor(Vector3(255, 0, 0)); };

			mWindowMode = make_unique<ScrollList>(mGUIScene, x, y + 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("windowMode"));
			mWindowMode->AttachTo(mOptionsGraphicsCanvas);
			mWindowMode->AddValue(mLocalization.GetString("windowed"));
			mWindowMode->AddValue(mLocalization.GetString("fullscreen"));
			mWindowMode->AddValue(mLocalization.GetString("borderless"));
			mWindowMode->OnChange += [this] { mSettingsApplied->SetText(mLocalization.GetString("settingsNotApplied")); mSettingsApplied->SetColor(Vector3(255, 0, 0)); };

			mTextureFiltering = make_unique<ScrollList>(mGUIScene, x, y + 1.0 * mDistBetweenButtons, texButton, mLocalization.GetString("filtering"));
			mTextureFiltering->AttachTo(mOptionsGraphicsCanvas);
			mTextureFiltering->AddValue(mLocalization.GetString("trilinear"));
			for(int i = 1; i <= mGame->GetEngine()->GetRenderer()->GetMaxIsotropyDegree(); ++i) {
				mTextureFiltering->AddValue(StringBuilder() << mLocalization.GetString("anisotropic") << " x" << i);
			}

			mSpotLightShadowMapSize = make_unique<ScrollList>(mGUIScene, x, y + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("spotLightShadowMap"));
			mSpotLightShadowMapSize->AttachTo(mOptionsGraphicsCanvas);
			for(int i = 256; i <= 2048; i *= 2) {
				mSpotLightShadowMapSize->AddValue(StringBuilder() << i << " x " << i);
			}

			mPointLightShadowMapSize = make_unique<ScrollList>(mGUIScene, x, y + 2.0 * mDistBetweenButtons, texButton, mLocalization.GetString("pointLightShadowMap"));
			mPointLightShadowMapSize->AttachTo(mOptionsGraphicsCanvas);
			for(int i = 128; i <= 1024; i *= 2) {
				mPointLightShadowMapSize->AddValue(StringBuilder() << i << " x " << i);
			}

			mDirectionalLightShadowMapSize = make_unique<ScrollList>(mGUIScene, x, y + 2.5 * mDistBetweenButtons, texButton, mLocalization.GetString("directionalLightShadowMap"));
			mDirectionalLightShadowMapSize->AttachTo(mOptionsGraphicsCanvas);
			for(int i = 1024; i <= 4096; i *= 2) {
				mDirectionalLightShadowMapSize->AddValue(StringBuilder() << i << " x " << i);
			}

			mSettingsApplied = mGUIScene->CreateText(mLocalization.GetString("settingsApplied"), x, y + 3.1 * mDistBetweenButtons, aTabWidth - 30, aTabHeight - 30, pGUIProp->mFont, Vector3(0, 255, 0), TextAlignment::Left);
			mSettingsApplied->Attach(mOptionsGraphicsCanvas);
		}

		// Authors
		mAuthorsBackground = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mAuthorsBackground->Attach(mCanvas);
		{
			mGUIAuthorsText = mGUIScene->CreateText(mLocalization.GetString("authorsText"), 15, 15, aTabWidth - 30, aTabHeight - 30, pGUIProp->mFont, Vector3(255, 255, 255), TextAlignment::Left);
			mGUIAuthorsText->Attach(mAuthorsBackground);
		}

		// Save Game
		mSaveGameCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mSaveGameCanvas->Attach(mCanvas);
		{
			float y = 10;
			for(int i = 0; i < mSaveLoadSlotCount; i++) {
				mSaveGameSlot[i] = mGUIScene->CreateButton(20, y, buttonWidth, buttonHeight, texButton, "Empty slot", pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
				mSaveGameSlot[i]->Attach(mSaveGameCanvas);
				mSaveGameSlot[i]->AddAction(GUIAction::OnClick, [this] { OnCreateSaveClick(); });

				mSaveGameFileTime[i] = mGUIScene->CreateText(" ", buttonWidth + 30, y, 160, buttonHeight, pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Left);
				mSaveGameFileTime[i]->Attach(mSaveGameCanvas);

				y += 1.1f * buttonHeight;
			}
		}

		// Load Game
		mLoadGameCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mLoadGameCanvas->Attach(mCanvas);
		{
			float y = 10;
			for(int i = 0; i < mSaveLoadSlotCount; i++) {
				mLoadGameSlot[i] = mGUIScene->CreateButton(20, y, buttonWidth, buttonHeight, texButton, "Empty slot", pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Center);
				mLoadGameSlot[i]->Attach(mLoadGameCanvas);
				mLoadGameSlot[i]->AddAction(GUIAction::OnClick, [this] { OnLoadSaveClick(); });

				mLoadGameFileTime[i] = mGUIScene->CreateText(" ", buttonWidth + 30, y, 160, buttonHeight, pGUIProp->mFont, pGUIProp->mForeColor, TextAlignment::Left);
				mLoadGameFileTime[i]->Attach(mLoadGameCanvas);
				y += 1.1f * buttonHeight;
			}
		}

		// Options: Common
		mOptionsCommonCanvas = mGUIScene->CreateRect(aTabX, aTabY, aTabWidth, aTabHeight, texTab, pGUIProp->mBackColor);
		mOptionsCommonCanvas->Attach(mCanvas);
		mOptionsCommonCanvas->SetVisible(false);
		{
			const int yOffset = (aTabHeight - 1.5 * mDistBetweenButtons) / 2;
			int xOffset = 20;

			mFOVSlider = make_unique<Slider>(mGUIScene, xOffset, yOffset - 0.5f * mDistBetweenButtons, 55, 90, 1.0f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("fov"));
			mFOVSlider->AttachTo(mOptionsCommonCanvas);

			mMasterVolume = make_unique<Slider>(mGUIScene, xOffset, yOffset, 0, 100, 2.5f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("masterVolume"));
			mMasterVolume->AttachTo(mOptionsCommonCanvas);
			mMasterVolume->SetChangeAction([this] { mGame->GetEngine()->GetSoundSystem()->SetMasterVolume(mMasterVolume->GetValue() / 100.0f); });

			mMusicVolume = make_unique<Slider>(mGUIScene, xOffset, yOffset + 0.5f * mDistBetweenButtons, 0, 100, 2.5f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("musicVolume"));
			mMusicVolume->AttachTo(mOptionsCommonCanvas);
			mMusicVolume->SetChangeAction([this] { OnMusicVolumeChange(); });

			mMouseSensivity = make_unique<Slider>(mGUIScene, xOffset, yOffset + 1.0f * mDistBetweenButtons, 0, 100, 2.5f, renderer->GetTexture("data/gui/menu/smallbutton.tga"), mLocalization.GetString("mouseSens"));
			mMouseSensivity->AttachTo(mOptionsCommonCanvas);
			mMouseSensivity->SetChangeAction([this] { mGame->SetMouseSensitivity(mMouseSensivity->GetValue() / 100.0f); });

			mLanguage = make_unique<ScrollList>(mGUIScene, xOffset, yOffset + 1.5 * mDistBetweenButtons, texButton, mLocalization.GetString("language"));
			mLanguage->AttachTo(mOptionsCommonCanvas);
			mLanguage->OnChange += [this] { mConfig.SetString("languagePath", StringBuilder("data/lang/") << mLanguage->GetValueString(mLanguage->GetCurrentValue()) << "/"); };


			mLangSettingsApplied = mGUIScene->CreateText(mLocalization.GetString("langChange"), 20, 3.3 * mDistBetweenButtons, aTabWidth - 30, aTabHeight - 30, pGUIProp->mFont, Vector3(255, 0, 0), TextAlignment::Left);
			mLangSettingsApplied->Attach(mOptionsCommonCanvas);

			xOffset += 300;
			mMouseInversionX = make_unique<RadioButton>(mGUIScene, xOffset, yOffset - 0.5 * mDistBetweenButtons, texButton, mLocalization.GetString("mouseInvX"));
			mMouseInversionX->AttachTo(mOptionsCommonCanvas);

			mMouseInversionY = make_unique<RadioButton>(mGUIScene, xOffset, yOffset, texButton, mLocalization.GetString("mouseInvY"));
			mMouseInversionY->AttachTo(mOptionsCommonCanvas);

			int current = 0, i = 0;
			WIN32_FIND_DATAA fi;
			HANDLE h = FindFirstFileExA("data/lang/*.*", FindExInfoStandard, &fi, FindExSearchLimitToDirectories, NULL, 0);
			if(h != INVALID_HANDLE_VALUE) {
				do {
					if(fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
						string v = fi.cFileName;
						if(v != "." && v != "..") {
							mLanguage->AddValue(v);
							if(mConfig.GetString("languagePath").rfind(v) != string::npos) {
								current = i;
							}
							++i;
						}
					}
				} while(FindNextFileA(h, &fi));
				FindClose(h);
			}

			mLanguage->SetCurrentValue(current);
		}
	}

	mGame->GetEngine()->GetSoundSystem()->SetReverbPreset(ReverbPreset::Auditorium);

	SetAuthorsPageVisible(false);
	SetPage(Page::Main);
	ReadConfig();
}
Exemple #12
0
//
// ICTicker::DrawSelf
//
// Draw the control
//
void ICTicker::DrawSelf(PaintInfo &pi)
{
  // Draw background
  DrawCtrlBackground(pi, GetTexture());

  // Draw frame
  DrawCtrlFrame(pi);

  // If there is a font then draw the control's text
  if (pi.font)
  {
    // Is there any text to be drawn
    if (currentMessage)
    {
      Color c = pi.colors->fg[ColorIndex()];
      c.a = U8(alpha);

      // Display the text
      pi.font->Draw
      (
        pi.client.p0.x + offsetX, 
        pi.client.p0.y + offsetY, 
        currentMessage->text, 
        currentMessage->length, 
        c,
        &pi.client
      );

      // Calcalate the width of the text
      //int width = pi.font->Width(currentMessage->text, currentMessage->length);
      
      switch (currentMessage->direction)
      {
        /*
        case DIR_LEFT:
          // Pause in the middle
          if (counter && offsetX <= ((pi.client.Width() - width) / 2))
          {
            counter--;
            break;
          }
           
          offsetX -= speed;
          if (offsetX < -width)
          {
            NextMessage();
          }
          break;

        case DIR_RIGHT:
          // Pause in the middle
          if (counter && offsetX >= ((pi.client.Width() - width) / 2))
          {
            counter--;
            break;
          }

          offsetX += speed;
          if (offsetX > pi.client.Width())
          {
            NextMessage();
          }
          break;

        case DIR_UP:
          // Pause in the middle
          if (counter && offsetY <= ((pi.client.Height() - S32(pi.font->Height())) / 2))
          {
            counter--;
            break;
          }

          offsetY -= speed;
          if (offsetY < -pi.font->Height())
          {
            NextMessage();
          }
          break;

        case DIR_DOWN:
          // Pause in the middle
          if (counter && offsetY >= ((pi.client.Height() - S32(pi.font->Height())) / 2))
          {
            counter--;
            break;
          }

          offsetY += speed;
          if (offsetY > pi.client.Height())
          {
            NextMessage();
          }
          break;
      */
        case DIR_ALPHA:
        default:
        {
          // Pause in the middle
          if (counter && alpha >= 255)
          {
            counter--;
            alphaDir = -S32(speed);
            break;
          }

          alpha += alphaDir;
          if (alpha > 255)
          {
            alpha = 255;
          }

          if (alpha <= 0)
          {
            NextMessage();
          }
          break;
        }
      }
    }
  }
}
Exemple #13
0
void Alien::set_texture()
{
	std::string a = "alien7.tga";
	malien = GetTexture(a);
}
Exemple #14
0
bool Sphere::Hit(Ray ray, real_t t0, real_t t1, HitRecord &rec)
{
	
	Vector3 localPos;
	Matrix4 inverseMatrix, transMatrix;
	Matrix3 temp, normalMatrix;
	Ray localRay;

	// calculate transform/ transform inverse/ normal matrix
	make_transformation_matrix(&transMatrix, position, orientation, scale);
	make_inverse_transformation_matrix(&inverseMatrix, position, orientation, scale);
	make_normal_matrix(&normalMatrix, transMatrix);
	
	// get the local ray
	localRay.origin = inverseMatrix.transform_point(ray.origin);
	localRay.dir = inverseMatrix.transform_vector(ray.dir);

	// do the intersection calculation
	real_t result, x1, x2, oriDotOri , dirDotDir, oriDotDir;
	oriDotDir = dot(localRay.dir , localRay.origin); 
	dirDotDir = dot(localRay.dir , localRay.dir); 
	oriDotOri = dot(localRay.origin , localRay.origin); 
	result = oriDotDir*oriDotDir-dirDotDir*(oriDotOri-radius*radius);

	// no intersection
	if(result < 0)
		return false;
	else 
	{
		x1=(-oriDotDir - sqrt(result)) / dirDotDir;
		x2=(-oriDotDir + sqrt(result)) / dirDotDir;
		// x1 is the place is the intersection
		if(x1>t0 && x1<t1)
		{
			localPos = localRay.origin + x1*localRay.dir;
			// set material 
			SetMaterialColors(rec.ambientColor, rec.diffuseColor,rec.specularColor);
			rec.refractiveIdx = material->refractive_index;

			// set normal
			rec.normal=(localPos)/radius;
			rec.normal=normalize(normalMatrix*rec.normal);
			
			// set texture color
			rec.textureColor = GetTexture(localPos);

			// set position
			rec.position = transMatrix.transform_point(localPos);

			// set t
			rec.t = x1;
			return true;
		}
		else
		{
			// x2 is the place is the intersection
			if(x2>t0 && x2<t1)
			{
				localPos = localRay.origin + x2*localRay.dir;
				//set material
				SetMaterialColors(rec.ambientColor, rec.diffuseColor,rec.specularColor);
				rec.refractiveIdx = material->refractive_index;

				// set normal
				rec.normal=(localPos)/radius;
				rec.normal=normalize(normalMatrix*rec.normal);

				// set texture
				rec.textureColor = GetTexture(localPos);
				
				// set position
				rec.position = transMatrix.transform_point(localPos);
				
				// set t
				rec.t = x2;
				return true;
			}
			return false;
	}

	}
}
Exemple #15
0
FbxModelData* FBXLoader::loadModel( const char* aFile )
{
	FBX_LOG("FBXLoader Creating ModelData...");
	myLoadingModel = new FbxModelData;
	FBX_LOG("Success!");
	FBX_LOG("FBXLoader Creating TextureData...");
	myLoadingModel->myTextureData = new TextureData();
	FBX_LOG("Success!");
	FBX_LOG("FBXLoader Loading Scene...");
	auto scene = LoadScene(aFile);
	FBX_LOG("Successfully loaded scene!");

	FBX_LOG("FBXLoader Loading Textures...");
	//TextureData
	const int lTextureCount = scene->GetTextureCount();
	for (int lTextureIndex = 0; lTextureIndex < lTextureCount; ++lTextureIndex)
	{
		FbxTexture * lTexture = scene->GetTexture(lTextureIndex);
		FbxFileTexture * lFileTexture = reinterpret_cast<FbxFileTexture*>(lTexture);
		if (lFileTexture && !lFileTexture->GetUserDataPtr())
		{
			const FbxString lFileName = lFileTexture->GetFileName();
			
			unsigned int lTextureObject = 0;
			lTextureObject;
			bool lStatus = false;
			lStatus;
			
			const FbxString lAbsFbxFileName = FbxPathUtils::Resolve(aFile);
			const FbxString lAbsFolderName = FbxPathUtils::GetFolderName(lAbsFbxFileName);
			
			const FbxString lTextureFileName = lAbsFolderName + "\\" + lFileTexture->GetRelativeFileName();// FbxPathUtils::GetFileName(lFileName);
				
			const FbxString lResolvedFileName = lAbsFolderName + "\\" + FbxPathUtils::GetFileName(lFileName);// lFileTexture->GetRelativeFileName();;// FbxPathUtils::Bind(lAbsFolderName, lTextureFileName);
			TextureInfo info;
			info.myFileName = lResolvedFileName;
			//info.myFileName += "\\";
			info.myFileName = lFileTexture->GetRelativeFileName();
			myLoadingModel->myTextureData->myTextures.push_back(info);
			lFileTexture->SetFileName(lResolvedFileName);
		}
	}
	FBX_LOG("Success!");
	FBX_LOG("FBXLoader Loading Animations...");

	FbxArray<FbxString*> animationNames;
	FbxArray<FbxPose*> poses;
	scene->FillAnimStackNameArray(animationNames);
	scene->FillPoseArray(poses);
	FbxAnimStack * lCurrentAnimationStack = nullptr;
	FbxAnimLayer* lCurrentAnimLayer = nullptr;
	if(animationNames.GetCount() > 0)
	{
		lCurrentAnimationStack = scene->FindMember<FbxAnimStack>(animationNames[0]->Buffer());
		if (lCurrentAnimationStack != NULL)
		{
			lCurrentAnimLayer = lCurrentAnimationStack->GetMember<FbxAnimLayer>();
		}
	}
	//lCurrentAnimLayer->IsR
	myLoadingModel->myAnimation = new AnimationData();
	FbxPose* pose = nullptr;
	if(poses.GetCount() > 0)
	{
		pose = poses[0];
	}

	LoadAnimation(*myLoadingModel->myAnimation,scene->GetRootNode(),FbxAMatrix(),pose, lCurrentAnimLayer,-1);
	LoadNodeRecursive(myLoadingModel, *myLoadingModel->myAnimation, scene->GetRootNode(), FbxAMatrix(), pose, lCurrentAnimLayer, -1);
	FBX_LOG("Success!");
		
	return myLoadingModel;
}
Exemple #16
0
 u32 getTexture() const { return GetTexture(); }
Exemple #17
0
void CEditPoly::SetTextureSpace(uint32 nTex, const LTVector& newO, const LTVector& newP, const LTVector& newQ)
{
	GetTexture(nTex).SetTextureSpace(GetTextureNormal(), newO, newP, newQ);
}
   void ShaderParamTextureCubeMap::LoadImage()
   {
      if(
         GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_X ||
         GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_X ||
         GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Y ||
         GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Y ||
         GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Z ||
         GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Z

         )
      {
         //Timer statsTickClock;
         //Timer_t frameTickStart = statsTickClock.Tick();

         RefPtr<osgDB::ReaderWriter::Options> options = new osgDB::ReaderWriter::Options;
         options->setObjectCacheHint(osgDB::ReaderWriter::Options::CACHE_ALL);

         std::string filePath = dtCore::FindFileInPathList(GetTexture());
         osg::Image *image = osgDB::readImageFile(filePath, options.get());

         if (image == NULL)
         {
            // we don't want to crash just because a shader couldnt find an image, but we need to let
            // the user know.
            image = new osg::Image(); // gotta have some sort of image placeholder
            LOG_ALWAYS("Could not find image for shader parameter [" + GetName() + "] at location [" +
               GetTexture() + "].");
            //throw dtUtil::Exception(ShaderParameterException::INVALID_ATTRIBUTE,"Could not find image for texture at location: " + GetTexture());
         }

         osg::TextureCubeMap *texCube = static_cast<osg::TextureCubeMap*>(GetTextureObject());

         if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_X)
         {
            texCube->setImage(osg::TextureCubeMap::POSITIVE_X, image);
         }
         else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_X)
         {
            texCube->setImage(osg::TextureCubeMap::NEGATIVE_X, image);
         }
         else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Y)
         {
            texCube->setImage(osg::TextureCubeMap::POSITIVE_Y, image);
         }
         else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Y)
         {
            texCube->setImage(osg::TextureCubeMap::NEGATIVE_Y, image);
         }
         else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_POSITIVE_Z)
         {
            texCube->setImage(osg::TextureCubeMap::POSITIVE_Z, image);
         }
         else if(GetTextureSourceType() == ShaderParamTexture::TextureSourceType::CUBEMAP_IMAGE_NEGATIVE_Z)
         {
            texCube->setImage(osg::TextureCubeMap::NEGATIVE_Z, image);
         }

         // we aren't dirty anymore

         //Timer_t frameTickStop = statsTickClock.Tick();
         //double processTime = statsTickClock.DeltaSec(frameTickStart, frameTickStop);
         //printf("Load Image time [%f]", processTime);
      }

      SetImageSourceDirty(false);
   }
Exemple #19
0
	Model* MeshManager::load_model(const std::string& name, Owner loc, Shader& shader)
	{
		static const std::string middle_path = "Resources/Models/";

		const std::string& obj_path = BASE_PATHS[loc] + middle_path + name + ".obj";
		const std::string& mtl_path = BASE_PATHS[loc] + middle_path;



		std::string err;
		Assimp::Importer importer;
		const aiScene* scene = importer.ReadFile(obj_path, aiProcess_Triangulate | aiProcess_FlipUVs);


		if (!err.empty()) {
			std::cerr << err << std::endl;
			exit(1);
		}

		Model* model = new Model();

		//std::cout << "Meshes: " << scene->mNumMeshes << std::endl;
		//std::cout << "Meshes: " << scene->mNumMaterials << std::endl;

		TextureManager* text_man = TextureManager::get_instance();
		for (int i = 0; i < scene->mNumMeshes; i++) {
			
			
			auto* assimp_mesh = scene->mMeshes[i];
			auto mat = scene->mMaterials[assimp_mesh->mMaterialIndex];
			

			//Aboid rendering of invisible objects
			float transp;
			mat->Get(AI_MATKEY_OPACITY, transp);
			if (transp < .9f)
				continue;

			aiColor3D diffuse;
			mat->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse);
			aiColor3D specular;
			mat->Get(AI_MATKEY_COLOR_SPECULAR, specular);
			F32 shininess;
			mat->Get(AI_MATKEY_SHININESS, shininess);
			ColorRGBA diffuse_final(diffuse.r*255, diffuse.g*255, diffuse.b*255,0);
		
			ColorRGBA specular_final(specular.r*255, specular.g*255, specular.b*255,shininess*255);

			SubModel& sm = model->add_sub_model();
			sm.cast_shadows = true;
			sm.material.set_shader(&shader);
			//Set colors
			sm.material.set_attribute("diffuse_color", diffuse_final);
			sm.material.set_attribute("specular_color", specular_final);

			//Set textures
			aiString tex_name;
			aiReturn r = mat->GetTexture(aiTextureType_DIFFUSE, 0, &tex_name);	
			
			sm.material.set_uniform("diffuse_texture", r == aiReturn_SUCCESS ? text_man->load_png(name + "/" + tex_name.C_Str(), GAME).id : -1);

			r = mat->GetTexture(aiTextureType_SPECULAR, 0, &tex_name);
			sm.material.set_uniform("specular_texture", r == aiReturn_SUCCESS ? text_man->load_png(name + "/" + tex_name.C_Str(), GAME).id : -1);
			
			r = mat->GetTexture(aiTextureType_NORMALS, 0, &tex_name);
			sm.material.set_uniform("normal_texture", r == aiReturn_SUCCESS ? text_man->load_png(name + "/" + tex_name.C_Str(), GAME).id : -1);
		
			Mesh* mesh = new Mesh();

			//Set vertices
			for (U32 i = 0; i < assimp_mesh->mNumVertices; i++)
			{
				Vertex3D v;
				v.position = glm::vec3(assimp_mesh->mVertices[i].x, assimp_mesh->mVertices[i].y, assimp_mesh->mVertices[i].z);
				if (assimp_mesh->mNormals)
					v.normal = glm::vec3(assimp_mesh->mNormals[i].x, assimp_mesh->mNormals[i].y, assimp_mesh->mNormals[i].z);
				if (assimp_mesh->mTangents)
					v.tangent = glm::vec3(assimp_mesh->mTangents[i].x, assimp_mesh->mTangents[i].y, assimp_mesh->mTangents[i].z);
				
				if (assimp_mesh->mTextureCoords[0]) // Does the mesh contain texture coordinates?
				{
					v.uv.x = assimp_mesh->mTextureCoords[0][i].x;
					v.uv.y = assimp_mesh->mTextureCoords[0][i].y;
				}
				else {

					v.uv.x = 0;
					v.uv.y = 0;
				}

				mesh->vertices.push_back(v);

			}
			//Set indices
			for (GLuint i = 0; i < assimp_mesh->mNumFaces; i++)
			{
				aiFace face = assimp_mesh->mFaces[i];
				for (GLuint j = 0; j < face.mNumIndices; j++)
					mesh->indices.push_back(face.mIndices[j]);
			}

			mesh->indices_number = assimp_mesh->mNumFaces*3;
			mesh->vertices_number = assimp_mesh->mNumVertices;

			if (!assimp_mesh->mNormals) {
				MeshBuilder::calculate_normals(mesh);
			}
			if (!assimp_mesh->mTangents) {
	
				MeshBuilder::calculate_tangents(mesh);
			}


			if (loc == Owner::ENGINE)
				lifetime_meshes.push_back(mesh);
			else
				temporary_meshes.push_back(mesh);


			if (loc == Owner::ENGINE)
				sm.mesh = ++last_lifetime_mesh;
			else
				sm.mesh = ++last_temporary_mesh;

		}

		return model;
	}
Exemple #20
0
int plLayerMovie::GetHeight() const
{
    plMipmap    *mip = plMipmap::ConvertNoRef( GetTexture() );
    return mip ? mip->GetHeight() : 0;
}
// Called on a decorator to generate any required per-element data for a newly decorated element.
DecoratorDataHandle DecoratorTiledImage::GenerateElementData(Element* element)
{
	// Calculate the tile's dimensions for this element.
	tile.CalculateDimensions(element, *GetTexture(tile.texture_index));

	Geometry* data = new Geometry(element);
	data->SetTexture(GetTexture());

	Vector2f dest = element->GetBox().GetSize(Box::PADDING);
	Vector2f source = tile.GetDimensions(element);

	// Generate the geometry for the tile.
	switch(tile.scaling_mode) {
	case IGNORE /* default */: tile.GenerateGeometry(data->GetVertices(), data->GetIndices(), element, Vector2f(0, 0), dest, source, color_multiplier); break;
	case FILL:
	case FIT: {
	  Vector2f offset(0, 0); float f; 
	  switch(tile.scaling_mode) {
	  case FILL: {
	    RenderInterface* render_interface = element->GetRenderInterface();
	    Vector2i texture_dimensions = GetTexture(tile.texture_index)->GetDimensions(render_interface);
	    f = max(dest.y / source.y, dest.x / source.x); 
	  }; break;
	  case FIT: 
	    f = min(dest.y / source.y, dest.x / source.x); 
	    source *= f;
	    offset.x = (dest.x - source.x)/2;
	    offset.y = (dest.y - source.y)/2;
	    dest = source;
	    break;
	  }
	  tile.GenerateGeometry(data->GetVertices(), data->GetIndices(), element, offset, dest, source, color_multiplier); 
	}; break;
	case CENTER: 
	  Vector2f offset(0, 0);
	  Vector2i texture_dimension;
	  if (!tile.texcoords_absolute[0][0] || !tile.texcoords_absolute[1][0] || !tile.texcoords_absolute[0][1] || !tile.texcoords_absolute[1][1]) {
	    RenderInterface* render_interface = element->GetRenderInterface();
	    texture_dimension = GetTexture(tile.texture_index)->GetDimensions(render_interface);
	  }
	  if (source.x > dest.x) { // crop width of image
	    float diff_begin = (source.x - dest.x)/2, diff_end = diff_begin;
	    if (!tile.texcoords_absolute[0][0] || !tile.texcoords_absolute[1][0]) {
	      if (!tile.texcoords_absolute[0][0]) diff_begin /= texture_dimension.x;
	      if (!tile.texcoords_absolute[1][0]) diff_end /= texture_dimension.x;
	    }
	    tile.texcoords[0].x += diff_begin; // -s-begin
	    tile.texcoords[1].x -= diff_end; // -s-end
	    source.x = dest.x;
	  } else {                 // center image
	    offset.x = (dest.x - source.x)/2;
	    dest.x = source.x;
	  }
	  if (source.y > dest.y) { // crop height of image
	    float diff_begin = (source.y - dest.y)/2, diff_end = diff_begin;
	    if (!tile.texcoords_absolute[0][1] || !tile.texcoords_absolute[1][1]) {
	      if (!tile.texcoords_absolute[0][1]) diff_begin /= texture_dimension.y;
	      if (!tile.texcoords_absolute[1][1]) diff_end /= texture_dimension.y;
	    }
	    tile.texcoords[0].y += diff_begin; // -s-begin
	    tile.texcoords[1].y -= diff_end; // -s-end
	    source.y = dest.y;
	  } else {                 // center image
	    offset.y = (dest.y - source.y)/2;
	    dest.y = source.y;
	  }
	  tile.GenerateGeometry(data->GetVertices(), data->GetIndices(), element, offset, dest, source, color_multiplier); 
	  break;
	}

	return reinterpret_cast<DecoratorDataHandle>(data);
}
Exemple #22
0
Texture* TextureContainer::GetDiffuse( std::string aFilename )
{
	return GetTexture(aFilename, true);
}
//
// Draw this control
//
void Power::DrawSelf(PaintInfo &pi)
{
    DrawCtrlBackground(pi, GetTexture());
    DrawCtrlFrame(pi);

    // Get the display team
    Team *team = Team::GetDisplayTeam();

    if (team)
    {
        // Get this teams power
        const ::Power::Team &power = team->GetPower();

        U32 available = power.GetAvailable();
        U32 availableDay = power.GetAvailableDay();
        U32 availableNight = power.GetAvailableNight();
        U32 consumed = power.GetConsumed();

        // Get the maximum
        U32 max = 0;
        max = Max(max, available);
        max = Max(max, availableDay);
        max = Max(max, availableNight);
        max = Max(max, consumed);

        // What the available height
        U32 height = pi.client.Height();
        ASSERT(height > 0)

        // How many notches are required to display this max (round up)
        div_t d = div(max, notchValue);
        U32 numNotches = d.quot + (d.rem ? 1 : 0);

        // How many pixels can we assign to each notch
        U32 notchPixels = numNotches ? Min(notchPixelMax, height / numNotches) : notchPixelMax;

        // Reduce notch pixels to the nearest power of two
        U32 mask = 0x10000000;
        do
        {
            if (mask & notchPixels)
            {
                notchPixels = mask;
                break;
            }
        }
        while (mask >>= 1);

        // We now have the number of pixels per notch, which also gives the ratio of pixels/units

        // Draw background
        IFace::RenderRectangle(
            pi.client,
            Color(0.0f, 0.0f, 0.0f),
            NULL,
            pi.alphaScale);

        // Display the available power
        IFace::RenderRectangle(
            ClipRect(
                pi.client.p0.x, pi.client.p1.y - notchPixels * available / notchValue,
                pi.client.p1.x, pi.client.p1.y),
            power.GetColor(),
            NULL,
            pi.alphaScale);

        // Display the day night difference
        IFace::RenderRectangle(
            ClipRect(
                pi.client.p0.x, pi.client.p1.y - notchPixels * availableDay / notchValue,
                pi.client.p1.x, pi.client.p1.y - notchPixels * availableNight / notchValue),
            Color(1.0f, 1.0f, 1.0f, 0.4f),
            NULL,
            pi.alphaScale);

        // Display the current power
        IFace::RenderRectangle(
            ClipRect(
                pi.client.p0.x, pi.client.p1.y - notchPixels * consumed / notchValue,
                pi.client.p1.x, pi.client.p1.y - notchPixels * consumed / notchValue + 1),
            Color(1.0f, 1.0f, 1.0f),
            NULL,
            pi.alphaScale);


        if (notchPixels > notchPixelMin)
        {
            // Draw the notches
            S32 y = pi.client.p1.y;
            while (y >= pi.client.p0.y)
            {
                IFace::RenderRectangle(
                    ClipRect(
                        pi.client.p0.x, y,
                        pi.client.p0.x + notchWidth, y + 1),
                    Color(1.0f, 1.0f, 1.0f),
                    NULL,
                    pi.alphaScale);

                IFace::RenderRectangle(
                    ClipRect(
                        pi.client.p1.x - notchWidth, y,
                        pi.client.p1.x, y + 1),
                    Color(1.0f, 1.0f, 1.0f),
                    NULL,
                    pi.alphaScale);

                y -= notchPixels;
            }

        }

    }

}
Exemple #24
0
Texture* TextureContainer::GetNormal( std::string aFilename )
{
	return GetTexture(aFilename, false);
}
    //
    // TransferList::Item::DrawSelf
    //
    // DrawSelf
    //
    void TransferList::Item::DrawSelf(PaintInfo &pi)
    {
      // Fill the background
      DrawCtrlBackground(pi, GetTexture());

      // Draw the frame
      DrawCtrlFrame(pi);

      if (!pi.font)
      {
        return;
      }

      CH buff[128];
      const CH *ch;

      // Draw the name of the file
      ch = Utils::Ansi2Unicode(offer->path.str);
      pi.font->Draw
      (
        pi.client.p0.x + transferList.offsetFile.x,
        pi.client.p0.y + transferList.offsetFile.y, 
        ch, 
        Utils::Strlen(ch),
        pi.colors->fg[ColorIndex()],
        &pi.client
      );

      Network::Player *player = Network::GetPlayers().Find(offer->who);
      if (player)
      {
        Utils::Sprintf(buff, 128, L"%s %s", offer->from ? L"From" : L"To", Utils::Ansi2Unicode(player->GetName()));
        ch = buff;
        pi.font->Draw
        (
          pi.client.p0.x + transferList.offsetPlayer.x,
          pi.client.p0.y + transferList.offsetPlayer.y, 
          ch, 
          Utils::Strlen(ch),
          pi.colors->fg[ColorIndex()],
          &pi.client
        );
      }

      ch = Utils::Ansi2Unicode(offer->path.str);
      pi.font->Draw
      (
        pi.client.p0.x + transferList.offsetFile.x,
        pi.client.p0.y + transferList.offsetFile.y, 
        ch, 
        Utils::Strlen(ch),
        pi.colors->fg[ColorIndex()],
        &pi.client
      );

      U32 state;
      U32 remaining;
      U32 rate;

      offer->transfer.Progress(state, remaining, rate);

      switch (state)
      {
        case StyxNet::TransferState::Transferring:
          break;

        default:
          remaining = offer->size;
          rate = 0;
          break;
      }

      U32 transferred = offer->size - remaining;

      // Draw the amount transferred
      if (transferred < 1000)
      {
        Utils::Sprintf(buff, 128, L"%.1fB", F32(transferred));
      }
      else if (transferred < 1000000)
      {
        Utils::Sprintf(buff, 128, L"%.1fkB", F32(transferred) / 1000.0f);
      }
      else
      {
        Utils::Sprintf(buff, 128, L"%.1fMB", F32(transferred) / 1000000.0f);
      }
      ch = buff;
      pi.font->Draw
      (
        pi.client.p0.x + transferList.offsetTransferred.x,
        pi.client.p0.y + transferList.offsetTransferred.y, 
        ch, 
        Utils::Strlen(ch),
        pi.colors->fg[ColorIndex()],
        &pi.client
      );

      // Draw the rate
      if (rate < 1000)
      {
        Utils::Sprintf(buff, 128, L"%.1fB/s", F32(rate));
      }
      else if (rate < 1000000)
      {
        Utils::Sprintf(buff, 128, L"%.1fkB/s", F32(rate) / 1000.0f);
      }
      else
      {
        Utils::Sprintf(buff, 128, L"%.1fMB/s", F32(rate) / 1000000.0f);
      }
      pi.font->Draw
      (
        pi.client.p0.x + transferList.offsetRate.x,
        pi.client.p0.y + transferList.offsetRate.y, 
        ch, 
        Utils::Strlen(ch),
        pi.colors->fg[ColorIndex()],
        &pi.client
      );

      // Draw the ETA
      if (rate)
      {
        S32 eta = remaining / rate;
        Utils::Sprintf(buff, 128, L"%d:%02d", eta / 60, eta % 60);
      }
      else
      {
        ch = L"?:??";
      }
      pi.font->Draw
      (
        pi.client.p0.x + transferList.offsetETA.x,
        pi.client.p0.y + transferList.offsetETA.y, 
        ch, 
        Utils::Strlen(ch),
        pi.colors->fg[ColorIndex()],
        &pi.client
      );

      // Draw a progress bar
      ClipRect c
      (
        pi.client.p0.x + transferList.offsetProgress.x, pi.client.p0.y + transferList.offsetProgress.y,
        pi.client.p1.x - transferList.offsetProgress.x, pi.client.p0.y + transferList.offsetProgress.y + transferList.heightProgress
      );

      IFace::RenderRectangle
      (
        c,
        Color(0.0f, 0.0f, 0.0f, pi.alphaScale), 
        NULL, 
        pi.alphaScale
      );

      IFace::RenderGradient
      (
        ClipRect
        (
          c.p0.x, c.p0.y,
          c.p1.x - (c.Width() * remaining / offer->size), c.p1.y
        ), 
        Color(0.2f, 1.0f, 1.0f, pi.alphaScale), 
        Color(0.1f, 0.5f, 0.5f, pi.alphaScale)
      );

    }
Exemple #26
0
Texture* TextureContainer::GetSpecular( std::string aFilename )
{
	return GetTexture(aFilename, true);
}
Exemple #27
0
static errcode GetTPolyFile(FILE * dfile) {
  void * tex;
  vector ctr, rot, scale;
  vector v1, v2, v0;
  char ifname[255];
  FILE *ifp;
  int v, totalpolys;
  RotMat RotA;
  errcode rc;

  totalpolys=0;

  rc = GetString(dfile, "SCALE");
  rc |= GetVector(dfile, &scale);

  rc |= GetString(dfile, "ROT");
  rc |= GetVector(dfile, &rot);

  degvectoradvec(&rot);
  InitRot3d(&RotA, rot.x, rot.y, rot.z);

  rc |= GetString(dfile, "CENTER");
  rc |= GetVector(dfile, &ctr);

  rc |= GetString(dfile, "FILE");
  fscanf(dfile, "%s", ifname);

  rc |= GetTexture(dfile, &tex);

  if ((ifp=fopen(ifname, "r")) == NULL) {
    fprintf(stderr, "Can't open data file %s for input!! Aborting...\n", ifname);
    return PARSEBADSUBFILE;
  }

  while (!feof(ifp)) {
    fscanf(ifp, "%d", &v);
    if (v != 3) { break; }

    totalpolys++;
    v=0;

    rc |= GetVector(ifp, &v0);
    rc |= GetVector(ifp, &v1);
    rc |= GetVector(ifp, &v2);

    Scale3d(&scale, &v0);
    Scale3d(&scale, &v1);
    Scale3d(&scale, &v2);

    Rotate3d(&RotA, &v0);
    Rotate3d(&RotA, &v1);
    Rotate3d(&RotA, &v2);

    Trans3d(&ctr, &v0);
    Trans3d(&ctr, &v1);
    Trans3d(&ctr, &v2);

    rt_tri(tex, v1, v0, v2);
  }

  fclose(ifp);

  return rc;
}
Exemple #28
0
Texture* TextureContainer::GetAmbientOcclusion( std::string aFilename )
{
	return GetTexture(aFilename, true);
}
already_AddRefed<gfx::DrawTarget>
PersistentBufferProviderShared::BorrowDrawTarget(const gfx::IntRect& aPersistedRect)
{
  if (!mFwd->GetTextureForwarder()->IPCOpen()) {
    return nullptr;
  }

  MOZ_ASSERT(!mSnapshot);

  if (IsActivityTracked()) {
    mFwd->GetActiveResourceTracker().MarkUsed(this);
  } else {
    mFwd->GetActiveResourceTracker().AddObject(this);
  }

  if (mDrawTarget) {
    RefPtr<gfx::DrawTarget> dt(mDrawTarget);
    return dt.forget();
  }

  mFront = Nothing();

  auto previousBackBuffer = mBack;

  TextureClient* tex = GetTexture(mBack);

  // First try to reuse the current back buffer. If we can do that it means
  // we can skip copying its content to the new back buffer.
  if (tex && tex->IsReadLocked()) {
    // The back buffer is currently used by the compositor, we can't draw
    // into it.
    tex = nullptr;
  }

  if (!tex) {
    // Try to grab an already allocated texture if any is available.
    for (uint32_t i = 0; i < mTextures.length(); ++i) {
      if (!mTextures[i]->IsReadLocked()) {
        mBack = Some(i);
        tex = mTextures[i];
        break;
      }
    }
  }

  if (!tex) {
    // We have to allocate a new texture.
    if (mTextures.length() >= 4) {
      // We should never need to buffer that many textures, something's wrong.
      MOZ_ASSERT(false);
      // In theory we throttle the main thread when the compositor can't keep up,
      // so we shoud never get in a situation where we sent 4 textures to the
      // compositor and the latter as not released any of them.
      // This seems to happen, however, in some edge cases such as just after a
      // device reset (cf. Bug 1291163).
      // It would be pretty bad to keep piling textures up at this point so we
      // call NotifyInactive to remove some of our textures.
      NotifyInactive();
      // Give up now. The caller can fall-back to a non-shared buffer provider.
      return nullptr;
    }

    RefPtr<TextureClient> newTexture = TextureClient::CreateForDrawing(
      mFwd, mFormat, mSize,
      BackendSelector::Canvas,
      TextureFlags::DEFAULT,
      TextureAllocationFlags::ALLOC_DEFAULT
    );

    MOZ_ASSERT(newTexture);
    if (newTexture) {
      if (mTextures.append(newTexture)) {
        tex = newTexture;
        mBack = Some<uint32_t>(mTextures.length() - 1);
      }
    }
  }

  if (!tex || !tex->Lock(OpenMode::OPEN_READ_WRITE)) {
    return nullptr;
  }

  if (mBack != previousBackBuffer && !aPersistedRect.IsEmpty()) {
    TextureClient* previous = GetTexture(previousBackBuffer);
    if (previous && previous->Lock(OpenMode::OPEN_READ)) {
      DebugOnly<bool> success = previous->CopyToTextureClient(tex, &aPersistedRect, nullptr);
      MOZ_ASSERT(success);

      previous->Unlock();
    }
  }

  mDrawTarget = tex->BorrowDrawTarget();

  RefPtr<gfx::DrawTarget> dt(mDrawTarget);
  return dt.forget();
}
Exemple #30
0
//===========================================================================
// DoTexture
//	Called after the name of the texture has been read (in 'token').
//===========================================================================
int DoTexture(void)
{
	def_t *def;
	int i;
	mappatch_t *pat = NULL;

	// Check that it's a valid texture name (and convert to upper case).
	strupr(token);
	if(strlen(token) > 8)
	{
		Message("Too long texture name '%s'.", token);
		return false;
	}
	else if(strlen(token) <= 2)
	{
		Message("Warning: Short texture name '%s'.", token);
	}
	// Get the definition and let's start filling up those infos!
	def = GetTexture(token);
	while(!endOfSource)
	{
		ReadToken();
		if(ISTOKEN(";")) break; // End of definition.
		// Flags.
		if(ISTOKEN("masked")) 
		{
			// Masked flag (ever needed?).
			def->tex.flags |= 1;
		}
		else if(ISTOKEN("flags"))
		{
			// Custom flags.
			ReadToken();
			def->tex.flags = strtol(token, 0, 0);
		}
		else if(ISTOKEN("misc"))
		{
			// Custom integer.
			ReadToken();
			def->tex.reserved = strtol(token, 0, 0);
		}
		else if(pat && ISTOKEN("arg1"))
		{
			// Custom data for stepdir.
			ReadToken();
			pat->reserved1 = (short) strtol(token, 0, 0);
		}
		else if(pat && ISTOKEN("arg2"))
		{
			// Custom data for 'colormap'.
			ReadToken();
			pat->reserved2 = (short) strtol(token, 0, 0);
		}
		else if(isdigit(token[0]) || (pat && token[0] == '-'))
		{
			i = strtol(token, 0, 0);
			if(pat) 
				pat->originX = i; 
			else 
				def->tex.width = i;
			ReadToken(); 
			if(!ISTOKEN(","))
			{
				Message("Expected a comma after %s.",
					pat? "patch origin X" : "texture width");
				return false;
			}
			ReadToken();
			i = strtol(token, 0, 0);
			if(pat)
				pat->originY = i;
			else
				def->tex.height = i;
		}
		else if(ISTOKEN("@"))
		{
			// A patch definition follows. 
			// Allocate a new patch entry from the def.
			i = def->tex.patchCount++;
			if(i == MAX_PATCHES)
			{
				Message("Too many patches (maximum is %i).", MAX_PATCHES);
				return false;
			}
			pat = def->tex.patches + i;
			// Initialize.
			memset(pat, 0, sizeof(*pat));
			pat->reserved1 = 1; // stepdir defaults to one.
			// The name of the patch comes first.
			ReadToken(); 
			strupr(token);
			if(strlen(token) > 8)
			{
				Message("Too long patch name '%s'.", token);
				return false;
			}
			pat->patch = PatchNumber(token);
		}
		else
		{
			Message("Bad token '%s'.", token);
			return false;
		}
	}
	return true;
}