示例#1
0
Texture2D* TextureCache::addImage(Image *image, const std::string &key)
{
    CCASSERT(image != nullptr, "TextureCache: image MUST not be nil");

    Texture2D * texture = nullptr;

    do
    {
        auto it = _textures.find(key);
        if( it != _textures.end() ) {
            texture = it->second;
            break;
        }

        // prevents overloading the autorelease pool
        texture = new (std::nothrow) Texture2D();
        texture->initWithImage(image);

        if(texture)
        {
            _textures.insert( std::make_pair(key, texture) );
            texture->retain();

            texture->autorelease();
        }
        else
        {
            CCLOG("cocos2d: Couldn't add UIImage in TextureCache");
        }

    } while (0);

#if CC_ENABLE_CACHE_TEXTURE_DATA
    VolatileTextureMgr::addImage(texture, image);
#endif

    return texture;
}
// get CCSpriteFrame from cache or create with Bitmap's data
SpriteFrame* CacheGif::getGifSpriteFrame(Bitmap* bm, int index)
{
	std::string gifFrameName = getGifFrameName(index);
	SpriteFrame* spriteFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(gifFrameName.c_str());
	if(spriteFrame != NULL)
	{
		return spriteFrame;
	}
	
	do 
	{	
		Texture2D* texture = createTexture(bm,index,true);
		CC_BREAK_IF(! texture);

		spriteFrame = SpriteFrame::createWithTexture(texture, Rect(0,0,texture->getContentSize().width, texture->getContentSize().height));
		CC_BREAK_IF(! spriteFrame);

		SpriteFrameCache::getInstance()->addSpriteFrame(spriteFrame, gifFrameName.c_str());
	} while (0);


	return spriteFrame;
}
示例#3
0
bool Sprite::initWithFile(const std::string& filename)
{
    FKAssert(filename.size()>0, "Invalid filename for sprite");

    Texture2D *texture = new Texture2D();
		FKLOG("create image here");
	Image* image = dynamic_cast<Image*>(ResourceManager::thisManager()->createResource(filename.c_str(),ResourceManager::IMAGE_NAME));
	image->load(false);

	texture->initWithImage(image);
    if (texture)
    {
        Rect rect = RectZero;
        rect.size = texture->getContentSize();
        FKLOG("Sprite size:w %f,h %f",rect.size.width,rect.size.height);
        return initWithTexture(texture, rect);
    }

    // don't release here.
    // when load texture failed, it's better to get a "transparent" sprite then a crashed program
    // this->release();
    return false;
}
FrameBufferObject::FrameBufferObject(glm::uvec2 dim, const std::vector<Texture2D*>& textures, Texture2D* depthTexture) :
	dim(dim), textures(textures), depthTexture(depthTexture) {
	LOG_INFO << "create fbo: " << dim.x << " " << dim.y << std::endl;

	glGenFramebuffers(1, &fb);
	glBindFramebuffer(GL_FRAMEBUFFER, fb);

	LOG_GL_ERRORS();

	LOG_DEBUG << "attach textures" << std::endl;
	// attach
	assert(textures.size() <= 15);
	for (unsigned i = 0; i < textures.size(); ++i) {
		Texture2D* tex = textures[i];
		assert (dim.x == tex->getWidth() && dim.y == tex->getHeight());
		LOG_DEBUG << "attach color texture " << i << std::endl;
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+i, GL_TEXTURE_2D, tex->textureId, 0);
	}
	if(textures.size() <= 0) {
		// instruct openGL that we won't bind a color texture with the currently binded FBO
		glDrawBuffer(GL_NONE);
		glReadBuffer(GL_NONE);
	}

	if (depthTexture != NULL) {
		assert (dim.x == depthTexture->getWidth() && dim.y == depthTexture->getHeight());
		LOG_DEBUG << "attach depth texture" << std::endl;
		glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture->textureId, 0);
	}

	LOG_DEBUG << "check errors" << std::endl;
	checkError();
	LOG_DEBUG << "checked errors" << std::endl;

	glBindFramebuffer(GL_FRAMEBUFFER, GL_NONE);
	LOG_GL_ERRORS();
}
示例#5
0
bool GroundBuilding::init(Layer *gameScene_, b2World *gameWorld_, Point pos)
{
    gLayer = gameScene_;
    gWorld = gameWorld_;
    
    
    startPos = pos;
    
    cocos2d::Texture2D::TexParams params = {GL_NEAREST, GL_NEAREST, GL_REPEAT, GL_REPEAT};
    
    Texture2D* wallTexture = Director::getInstance()->getTextureCache()->addImage("testbuilding_wall.png");
    wallTexture->setTexParameters(params);
    wallTextureSize = Size(wallTexture->getPixelsWide(), wallTexture->getPixelsHigh());
    
    Texture2D* viewTexture = Director::getInstance()->getTextureCache()->addImage("testbuilding_view.png");
    viewTexture->setTexParameters(params);
    viewTextureSize = Size(viewTexture->getPixelsWide(), viewTexture->getPixelsHigh());
    
    Texture2D* terrainTexture = Director::getInstance()->getTextureCache()->addImage("terrain.png");
    terrainTexture->setTexParameters(params);

    
    Vector2dVector empty;
    
    
    wall = PRFilledPolygon::filledPolygonWithPointsAndTexture(empty, wallTexture);
    higherFrontView = PRFilledPolygon::filledPolygonWithPointsAndTexture(empty, viewTexture);
    terrain = PRFilledPolygon::filledPolygonWithPointsAndTexture(empty, terrainTexture);
    gLayer->addChild(wall, 2);
    gLayer->addChild(terrain,2);
    gLayer->addChild(higherFrontView, 60);
    
    setVertices(pos);

    
    return true;
}
Texture2D *ResourceManager::LoadTextureFromDDS (const std::string &filename)
{
	assertion(false, "current not do this.");

	return 0;

	FILE* inFile;
	inFile = fopen(filename.c_str(), "rb");

	if (!inFile)
	{
		assertion(false, "Failed to open file %s\n", filename.c_str());
		return 0;
	}

	DDSHeader header;
	int numRead = (int)fread(&header, sizeof(header), 1, inFile);
	PX2_UNUSED(numRead);

	int width = 0;
	int height = 0;
	int minmap = 1;
	Texture::Format format;
	GetDescInfo(header, width, height, minmap, format);

	Texture2D *texture = new Texture2D(format, width, height, minmap);
	fread(texture->GetData(0), texture->GetNumTotalBytes(), 1, inFile);

	if (fclose(inFile) != 0)
	{
		assertion(false, "Failed to read or close file %s\n",
			filename.c_str());
		return 0;
	}

	return texture;
}
示例#7
0
bool GridBase::initWithSize(const cocos2d::Size &gridSize, const cocos2d::Rect &rect)
{
    Director *director = Director::getInstance();
    Size s = director->getWinSizeInPixels();
    
    auto POTWide = ccNextPOT((unsigned int)s.width);
    auto POTHigh = ccNextPOT((unsigned int)s.height);
    
    // we only use rgba8888
    Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888;
    
    auto dataLen = POTWide * POTHigh * 4;
    void *data = calloc(dataLen, 1);
    if (! data)
    {
        CCLOG("cocos2d: Grid: not enough memory.");
        this->release();
        return false;
    }
    
    Texture2D *texture = new (std::nothrow) Texture2D();
    texture->initWithData(data, dataLen,  format, POTWide, POTHigh, s);
    
    free(data);
    
    if (! texture)
    {
        CCLOG("cocos2d: Grid: error creating texture");
        return false;
    }
    
    initWithSize(gridSize, texture, false, rect);
    
    texture->release();
    
    return true;
}
示例#8
0
Texture2D* makeDepthTexture(int width, int height, GLenum internalFormat)
{
    Texture2D *depthTex = new Texture2D;
    depthTex->setTextureSize(width, height);
    depthTex->setSourceFormat(GL_DEPTH_COMPONENT);
    depthTex->setSourceType(GL_FLOAT);
    depthTex->setInternalFormat(internalFormat);
    depthTex->setFilter(Texture2D::MIN_FILTER, Texture2D::NEAREST);
    depthTex->setFilter(Texture2D::MAG_FILTER, Texture2D::NEAREST);
    depthTex->setWrap(Texture::WRAP_S, Texture::CLAMP_TO_EDGE);
    depthTex->setWrap(Texture::WRAP_T, Texture::CLAMP_TO_EDGE);
    return depthTex;
}
示例#9
0
bool GridBase::initWithSize(const Size& gridSize)
{
    Director *pDirector = Director::getInstance();
    Size s = pDirector->getWinSizeInPixels();

    unsigned long POTWide = ccNextPOT((unsigned int)s.width);
    unsigned long POTHigh = ccNextPOT((unsigned int)s.height);

    // we only use rgba8888
    Texture2DPixelFormat format = kTexture2DPixelFormat_RGBA8888;

    void *data = calloc((int)(POTWide * POTHigh * 4), 1);
    if (! data)
    {
        CCLOG("cocos2d: Grid: not enough memory.");
        this->release();
        return false;
    }

    Texture2D *pTexture = new Texture2D();
    pTexture->initWithData(data, format, POTWide, POTHigh, s);

    free(data);

    if (! pTexture)
    {
        CCLOG("cocos2d: Grid: error creating texture");
        return false;
    }

    initWithSize(gridSize, pTexture, false);

    pTexture->release();

    return true;
}
void gfx::draw_rect_textured(float px, float py, float pw, float ph, const Color &pc, const Texture2D &pt)
{
  float x2 = px + pw,
        y2 = py + ph;
  pt.bind();
  draw_fill(0, px, py, 0.0f, 0.0f);
  draw_fill(1, x2, py, 1.0f, 0.0f);
  draw_fill(2, px, y2, 0.0f, 1.0f);
  draw_fill(3, x2, y2, 1.0f, 1.0f);
  draw_fill(0, pc);
  draw_fill(1, pc);
  draw_fill(2, pc);
  draw_fill(3, pc);
  glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}
void Urho3DQtApplication::CreateLogo()
{
    // Get logo texture
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    Texture2D* logoTexture = cache->GetResource<Texture2D>("Textures/LogoLarge.png");
    if (!logoTexture)
        return;

    // Create logo sprite and add to the UI layout
    UI* ui = GetSubsystem<UI>();
    logoSprite_ = ui->GetRoot()->CreateChild<Sprite>();

    // Set logo sprite texture
    logoSprite_->SetTexture(logoTexture);

    int textureWidth = logoTexture->GetWidth();
    int textureHeight = logoTexture->GetHeight();

    // Set logo sprite scale
    logoSprite_->SetScale(256.0f / textureWidth);

    // Set logo sprite size
    logoSprite_->SetSize(textureWidth, textureHeight);

    // Set logo sprite hot spot
    logoSprite_->SetHotSpot(0, textureHeight);

    // Set logo sprite alignment
    logoSprite_->SetAlignment(HA_LEFT, VA_BOTTOM);

    // Make logo not fully opaque to show the scene underneath
    logoSprite_->SetOpacity(0.75f);

    // Set a low priority for the logo so that other UI elements can be drawn on top
    logoSprite_->SetPriority(-100);
}
示例#12
0
bool Sprite::initWithFile(const std::string& filename)
{
    if (filename.empty())
    {
        CCLOG("Call Sprite::initWithFile with blank resource filename.");
        return false;
    }

    _fileName = filename;
    _fileType = 0;

    Texture2D *texture = _director->getTextureCache()->addImage(filename);
    if (texture)
    {
        Rect rect = Rect::ZERO;
        rect.size = texture->getContentSize();
        return initWithTexture(texture, rect);
    }

    // don't release here.
    // when load texture failed, it's better to get a "transparent" sprite then a crashed program
    // this->release();
    return false;
}
/*-----------------------------------------------------------*/
static void ReajustUV(CinematicBitmap* cb) {

	C_UV* uvs = cb->grid.uvs;

	for(std::vector<C_INDEXED>::iterator mat = cb->grid.mats.begin(); mat != cb->grid.mats.end(); ++mat)
	{
		Texture2D* tex = mat->tex;

		if (!tex)
			return;

		int w, h;

		w = tex->getStoredSize().x;
		h = tex->getStoredSize().y;

		if ((w != (int)mat->bitmapw) || (h != (int)mat->bitmaph))
		{
			float dx = (.999999f * (float)mat->bitmapw) / ((float)w);
			float dy = (.999999f * (float)mat->bitmaph) / ((float)h);

			int nb2 = mat->nbvertexs;

			while (nb2--)
			{
				uvs->uv.x *= dx;
				uvs->uv.y *= dy;
				uvs++;
			}
		}
		else
		{
			uvs += mat->nbvertexs;
		}
	}
}
示例#14
0
Texture2D* VideoTextureCache::addImageWidthData(const char *filename, int frame, const void *data, ssize_t dataLen, Texture2D::PixelFormat pixelFormat, unsigned int pixelsWide, unsigned int pixelsHigh, const Size& contentSize)
{
    ostringstream keystream;
    keystream << filename << "_" << frame;
    string key = keystream.str();
    
    Texture2D * texture = NULL;
    texture = (Texture2D*)m_pTextures->at(key);
	if(!texture) {
        texture = new Texture2D();
        if( texture && 
        	texture->initWithData(data, dataLen, pixelFormat, pixelsWide, pixelsHigh, contentSize) ) {
            
            m_pTextures->insert(key, texture);
            texture->release();
		} else {
            CCLOG("cocos2d: Couldn't create texture for file:%s in CCVideoTextureCache", key.c_str());
        }
	} else {
        CCLOG("追加画像データ - %s", key.c_str());
    }

	return texture;
}
示例#15
0
void PhysXTerrain::Init()
{
    Model<VertexPosNormTanTex>* pModel = Content->LoadTerrain(m_Path);
    Texture2D* pTexTemp = Content->LoadTexture2D(m_Path, true);
    
    vector<NxHeightFieldSample> samples;
    samples.reserve(pTexTemp->GetWidth() * pTexTemp->GetHeight());
    for_each(pModel->GetModelMeshes()[0]->GetVertices().cbegin(), pModel->GetModelMeshes()[0]->GetVertices().cend(),
        [&](const VertexPosNormTanTex& vpnt)
    {
        NxHeightFieldSample s;
        s.height = static_cast<NxI16>(vpnt.position.Y * NX_MAX_I16);
        s.tessFlag = 0;
        //s.materialIndex0 = 0;
        //s.materialIndex1 = 0;
        //s.unused = 0;
        samples.push_back(s);
    });

    NxHeightFieldDesc desc;
    desc.convexEdgeThreshold = 0;
    desc.nbColumns = pTexTemp->GetWidth();
    desc.nbRows = pTexTemp->GetHeight();
    desc.samples = &samples[0];
    desc.sampleStride = sizeof(NxHeightFieldSample);
    desc.thickness = -1.0f;

    NxHeightField* pHeightField = m_pPhysX->GetSDK()->createHeightField(desc);
    ASSERT(pHeightField != 0, "heightfield creation failed");


    delete m_pHeightShapeDesc;
    m_pHeightShapeDesc = new NxHeightFieldShapeDesc();

    m_pHeightShapeDesc->heightField = pHeightField;    
    m_pHeightShapeDesc->heightScale = m_HeightScale / NX_MAX_I16;    
    m_pHeightShapeDesc->rowScale = m_PlanarScale / max(pTexTemp->GetWidth(), pTexTemp->GetHeight());    
    m_pHeightShapeDesc->columnScale = m_PlanarScale / max(pTexTemp->GetWidth(), pTexTemp->GetHeight());    
    m_pHeightShapeDesc->materialIndexHighBits = 0;    
    m_pHeightShapeDesc->holeMaterial = 0;
}
示例#16
0
static void drawDebugMaterialTexture(Vec2f & textpos, const std::string & type,
                                     const Texture2D & t, Color color) {
	
	const std::string & name = t.getFileName().string();
	
	std::ostringstream oss;
	oss << "(" << t.GetFormat() << ", " << t.getSize().x << "×" << t.getSize().y;
	if(t.getStoredSize() != t.getSize()) {
		oss << " [" << t.getStoredSize().x << "×" << t.getStoredSize().y << "]";
	}
	if(t.hasMipmaps()) {
		oss << " + mip";
	}
	oss << ")";
	std::string format = oss.str();
	
	float type_s = hFontDebug->getTextSize(type).x + 10;
	float name_s = hFontDebug->getTextSize(name).x + 10;
	float format_s = hFontDebug->getTextSize(format).x;
	
	Vec2i pos = Vec2i(textpos);
	pos.x -= (type_s + name_s + format_s) * 0.5f;
	if(pos.x < g_size.left + 5) {
		pos.x = g_size.left + 5;
	} else if(pos.x + type_s + name_s + format_s > g_size.right - 5) {
		pos.x = g_size.right - 5 - (type_s + name_s + format_s);
	}
	
	hFontDebug->draw(pos + Vec2i_ONE, type, Color::black);
	hFontDebug->draw(pos, type, color);
	pos.x += type_s;
	
	hFontDebug->draw(pos + Vec2i_ONE, name, Color::black);
	hFontDebug->draw(pos, name, Color::white);
	pos.x += name_s;
	
	hFontDebug->draw(pos + Vec2i_ONE, format, Color::black);
	hFontDebug->draw(pos, format, Color::gray(0.7f));
	
	textpos.y += hFontDebug->getLineHeight();
}
Resource* ResourceManager::LoadTexture2D(std::string filepath)
{
	Image image;
	int width, height, components;
	image.data = stbi_load(filepath.c_str(), &width, &height, &components, 0);
	image.width = width;
	image.height = height;
	image.components = components;

	// This may not work as intended
	if (image.data == NULL)
	{
#ifdef DEBUG
		Debug::LogError("[ResourceManager] Texture2D could not be loaded.");
#endif
		return 0;
	}

	Texture2D* texture = new Texture2D(image);

	texture->IncreaseReferenceCount();
	resourceCollection[filepath] = texture;
	return dynamic_cast<Resource*>(texture);
}
示例#18
0
	int FrameBuffer::addTexture( Texture2D& target , bool beManaged )
	{
		int idx = mTextures.size();

		Info info;
		info.handle   = target.mHandle;
		info.idx      = 0;
		info.bManaged = ( beManaged ) ? target.mbManaged : false;
		if ( info.bManaged )
			target.release();

		mTextures.push_back( info );
		setTextureInternal( idx , info , GL_TEXTURE_2D );
		
		return idx;
	}
示例#19
0
void Batch2D::SetTexture(Texture2D& tex, glm::vec4* sourceRect){
	if (texture){
		//if texture is different from previous
		if (texture->GetHandle() != tex.GetHandle()){
			//draw all stored sprites
			Flush();
			//set texture handle
			texture = &tex;

			//bind texture to texture unit 0
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, texture->GetHandle());
		}
		
		//else: if texture is same as previous, do not bind

	}
	//no previous texture
	else{
		//set texture handle
		texture = &tex;

		//bind texture to texture unit 0
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texture->GetHandle());
	}

	//set sourceDim and sourceTexCoords(normalized) based on sourceRect and texture
	if (sourceRect == nullptr){
		sourceDim = glm::vec2(texture->GetWidth(), texture->GetHeight());
		sourceTexCoords[0] = glm::vec2(0.f, 0.f);
		sourceTexCoords[1] = glm::vec2(1.f, 0.f);
		sourceTexCoords[2] = glm::vec2(0.f, 1.f);
		sourceTexCoords[3] = glm::vec2(1.f, 1.f);
	}
	else{
		sourceDim = glm::vec2(sourceRect->z, sourceRect->w);

		glm::float32 w = 1.f / texture->GetWidth();
		glm::float32 h = 1.f / texture->GetHeight();

		sourceTexCoords[0] = glm::vec2(sourceRect->x * w, sourceRect->y * h);
		sourceTexCoords[1] = glm::vec2(sourceRect->z * w, sourceRect->y * h);
		sourceTexCoords[2] = glm::vec2(sourceRect->x * w, sourceRect->w * h);
		sourceTexCoords[3] = glm::vec2(sourceRect->z * w, sourceRect->w * h);
	}
}
void FilteredSpriteWithMulti::update(float delta) {
    if (_filterIdxCompound < 0) {
        return;
    }

    if (_filterIdxCompound >= _pFilters.size()) {
        //finish
        _filterIdxCompound = -1;
        
        Texture2D *texture = nullptr;
        texture = new Texture2D();
        texture->autorelease();
        Image *pNewImage = _pRenderTextureCompound->newImage(true);
        texture->initWithImage(pNewImage);
        delete pNewImage;
        initWithTexture(texture);

        _pFilterSpiteCompound->release();
        _pFilterSpiteCompound = nullptr;
        return;
    }

    _pRenderTextureCompound->begin();
    Filter* __filter = static_cast<Filter*>(_pFilters.at(_filterIdxCompound));
    if (nullptr != _pFilterSpiteCompound) {
        _pFilterSpiteCompound->release();
        _pFilterSpiteCompound = nullptr;
    }
    if (_filterIdxCompound == 0)
    {
        _pFilterSpiteCompound = _pTexture ?
        FilteredSpriteWithOne::createWithTexture(_pTexture) :
        FilteredSpriteWithOne::createWithSpriteFrame(_pFrame);
    }
    else
    {
        Texture2D *texture = nullptr;
        texture = new Texture2D();
        texture->autorelease();
        Image * pNewImage = _pRenderTextureCompound->newImage(true);
        texture->initWithImage(pNewImage);
        delete pNewImage;
        
        _pFilterSpiteCompound = FilteredSpriteWithOne::createWithTexture(texture);
    }
    _pFilterSpiteCompound->retain();
    _pFilterSpiteCompound->setFilter(__filter);
    _pFilterSpiteCompound->setAnchorPoint(Vec2(0, 0));
    _pFilterSpiteCompound->visit();
    _pRenderTextureCompound->end();

    _filterIdxCompound++;
}
示例#21
0
		void initialize( )
		{
			if ( initialized )
			{
				std::cerr << "Texture was already initialized." << std::endl;
				exit( -1 );
			}

			if ( texData == NULL )
			{
				std::cerr << "Attempted to initialize sprite with null data. " << std::endl;
				exit( -1 );
			}

			tex.initialize( w, h, texData );

			initialized = true;
		}
示例#22
0
void PhotoLayer::changeOk(Ref* pSender, TouchEventType type)
{
    if (type == TOUCH_EVENT_ENDED){
        Sprite* sprite = this->mask();
        
        ImageView* face = ImageView::create();
        Texture2D* texture = sprite->getTexture();
        SpriteFrame* spriteFrame = SpriteFrame::createWithTexture(texture, Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height));
        ((Sprite*)face->getVirtualRenderer())->setSpriteFrame(spriteFrame);
        ((Sprite*)face->getVirtualRenderer())->setFlippedY(true);
        
        MainLayer* layer = (MainLayer*)this->getParent()->getParent();
        layer->changeFace(face);

        Layer* parent = (Layer*)this->getParent();
        this->removeFromParentAndCleanup(true);
        parent->removeFromParentAndCleanup(true);
    }
}
示例#23
0
void SpriteRenderer::DrawSprite(Texture2D& texture, glm::vec2 position, glm::vec2 size /*= glm::vec2(10, 10)*/, GLfloat rotate /*= 0.0f*/, glm::vec3 color /*= glm::vec3(1.0f)*/)
{
	this->shader.Use();
	glm::mat4 model;
	
	model = glm::translate(model, glm::vec3(position, 0.0f));
	model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f));
	model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f));
	model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f));
	model = glm::scale(model, glm::vec3(size, 1.0f));

	this->shader.SetMatrix4("model", model);
	this->shader.SetVector3f("spriteColor", color);

	glActiveTexture(GL_TEXTURE0);
	texture.Bind();

	glBindVertexArray(this->quadVAO);
	glDrawArrays(GL_TRIANGLES, 0, 6);
	glBindVertexArray(0);
}
示例#24
0
void GenerateSkyboxTexture(Texture2D& texture, uint length)
{
    const size_t textureSize = static_cast<size_t>(length*length);

    Color::rgb * textureData = new Color::rgb[textureSize];

    const Color::rgb black = {0, 0, 0};
    const Color::rgb white = {(char)255, (char)255, (char)255};

    int r = 0;
    for(size_t i=0; i< textureSize; ++i)
    {
        r = rand()%1000;
        if(r<5)
            textureData[i] = white;
        else
            textureData[i] = black;
    }

    texture.setTexture(textureData, length, length);
}
示例#25
0
VOID ResourceDatabase::CreateDefaultResources()
{
    if( m_pBlackTexture2D == NULL )
        CreateBlackTexture();
    if( m_pBlueTexture2D == NULL )
        CreateBlueTexture();
    if( m_pWhiteTexture2D == NULL )
        CreateWhiteTexture();

    Texture2D* pDefaultNormalMap = new Texture2D();
    pDefaultNormalMap->SetName( L"default-normalmap.dds" );
    pDefaultNormalMap->SetD3DTexture( m_pBlueTexture2D->GetD3DTexture() );
    AddResource( pDefaultNormalMap );

    Texture2D* pDefaultDiffuse = CreateColorTexture( 0xFF808080 );
    pDefaultDiffuse->SetName( L"default.dds" );
    AddResource( pDefaultDiffuse );

    Texture2D* pDefaultSpecMap = new Texture2D();
    pDefaultSpecMap->SetName( L"default-specularmap.dds" );
    pDefaultSpecMap->SetD3DTexture( m_pWhiteTexture2D->GetD3DTexture() );
    AddResource( pDefaultSpecMap );
}
std::string TextureCache::getCachedTextureInfo() const
{
    char buffer[16386];
    char buftmp[4096];

    memset(buffer,0,sizeof(buffer));

    unsigned int count = 0;
    unsigned int totalBytes = 0;

    for( auto it = _textures.begin(); it != _textures.end(); ++it ) {

        memset(buftmp,0,sizeof(buftmp));


        Texture2D* tex = it->second;
        unsigned int bpp = tex->getBitsPerPixelForFormat();
        // Each texture takes up width * height * bytesPerPixel bytes.
        auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8;
        totalBytes += bytes;
        count++;
        snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n",
               it->first.c_str(),
               (long)tex->getReferenceCount(),
               (long)tex->getName(),
               (long)tex->getPixelsWide(),
               (long)tex->getPixelsHigh(),
               (long)bpp,
               (long)bytes / 1024);
        strcat(buffer, buftmp);
    }

    snprintf(buftmp, sizeof(buftmp)-1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f));
    strcat(buffer, buftmp);

    return std::string(buffer);
}
示例#27
0
void MenuStateRoot::render() {
	Renderer &renderer= Renderer::getInstance();
	CoreData &coreData= CoreData::getInstance();
	const Metrics &metrics= Metrics::getInstance();

	int w= 300;
	int h= 150;
	int yPos=495;

	renderer.renderTextureQuad(
		(metrics.getVirtualW()-w)/2, yPos-h/2, w, h,
		coreData.getLogoTexture(), GraphicComponent::getFade());

	int maxLogoWidth=0;
	for(int idx = 0; idx < coreData.getLogoTextureExtraCount(); ++idx) {
		Texture2D *extraLogo = coreData.getLogoTextureExtra(idx);
		maxLogoWidth += extraLogo->getPixmap()->getW();
	}

	int currentX = (metrics.getVirtualW()-maxLogoWidth)/2;
	int currentY = 50;
	for(int idx = 0; idx < coreData.getLogoTextureExtraCount(); ++idx) {
		Texture2D *extraLogo = coreData.getLogoTextureExtra(idx);

		renderer.renderTextureQuad(
				currentX, currentY,
				extraLogo->getPixmap()->getW(), extraLogo->getPixmap()->getH(),
				extraLogo, GraphicComponent::getFade());

		currentX += extraLogo->getPixmap()->getW();
	}
	renderer.renderButton(&buttonNewGame);
	renderer.renderButton(&buttonJoinGame);
	renderer.renderButton(&buttonMasterserverGame);
	renderer.renderButton(&buttonOptions);
	renderer.renderButton(&buttonAbout);
	renderer.renderButton(&buttonExit);
	renderer.renderLabel(&labelVersion);

	//exit message box
	if(mainMessageBox.getEnabled()){
		renderer.renderMessageBox(&mainMessageBox);
	}
	if(program != NULL) program->renderProgramMsgBox();
}
示例#28
0
void SpriteRenderer::draw(
    glm::vec2 position,
    glm::vec2 size,
    const Texture2D& texture,
    const Camera& camera
    ) const
{
    ResourceManager::GetShader("sprite_texture")->use();
    glm::mat4 model;
    // При расстановке объектов сдвигаем начало координат в центр экрана. Чтоб герой всегда был по центру.
    model = glm::translate(model, glm::vec3(position.x + screenWidth_ / 2, position.y + screenHeight_ / 2, 0.0f));
    model = glm::scale(model, glm::vec3(size, 1.0f));

    glm::mat4 view;
    camera.getView(view);

    ResourceManager::GetShader("sprite_texture")->setUniform("view", view);
    ResourceManager::GetShader("sprite_texture")->setUniform("model", model);

    glBindVertexArray(VAO_);
    texture.Bind();
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindVertexArray(0);
}
示例#29
0
bool load()
{
	GLenum types[] = { GL_COMPUTE_SHADER };
	string paths[] = { "./demo/29compute/blurcompute.cs" };
	if (!shader_display.loadFromFile("./demo/29compute/texturems") ||
		!shader_compute.loadFromFile(paths, types, 1))
		return false;

	if (!shader_display.linkAndCheckStatus() ||
		!shader_compute.linkAndCheckStatus())
		return false;

	if (!tex.loadFromFile("./data/textures/dungeon2.png", GL_RGBA16F))
		return false;

	tex.setTexParameteri(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);
	tex_blurred.create(0, GL_RGBA16F, tex.getWidth(), tex.getHeight(), GL_RGB, GL_FLOAT, NULL);
	tex_blurred.setTexParameteri(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE);

	return true;
}
void AbstractTextureGLTest::constructMove() {
    Texture2D a;
    const Int id = a.id();

    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_VERIFY(id > 0);

    Texture2D b(std::move(a));

    CORRADE_COMPARE(a.id(), 0);
    CORRADE_COMPARE(b.id(), id);

    Texture2D c;
    const Int cId = c.id();
    c = std::move(b);

    MAGNUM_VERIFY_NO_ERROR();
    CORRADE_VERIFY(cId > 0);
    CORRADE_COMPARE(b.id(), cId);
    CORRADE_COMPARE(c.id(), id);
}