Example #1
0
	void run() {
	    RGBA c;

	    // test += 
	    c = RGBA(1.0,2.0,3.0,4.0);
	    c += RGBA(1.0,2.0,3.0,4.0);
	    assertTrue(c == RGBA(2.0,4.0,6.0,8.0));
	    assertTrue(c.a() == 8.0);

	    c = RGBA(1.0,2.0,3.0,0.0);
	    c += RGBA(1.0,2.0,3.0,1.0);
	    assertTrue(c == RGBA(2.0,4.0,6.0,1.0));
	    assertTrue(c.a() == 1.0);

	    // test / and *
	    c = RGBA(1.0,2.0,3.0,4.0);
	    c = c * 2.0;
	    assertTrue(c == RGBA(2.0,4.0,6.0,8.0));
	    c = c / 2.0;
	    assertTrue(c == RGBA(1.0,2.0,3.0,4.0));

	    c = RGB(1.0,2.0,3.0);
	    assertTrue(c.a() == 1);

	    assertTrue(RGB(1.0,2.0,3.0) == RGBA(1.0,2.0,3.0,1.0));
	    assertTrue(RGBA(1.0,2.0,3.0,1.0) == RGB(1.0,2.0,3.0));
	}
Example #2
0
void WidgetBase::RenderOutline(const Vec2& worldPos, const Vec2& widgetSize, float lineWidth)
{
	glPushAttrib(GL_LINE_BIT);
	glLineWidth(lineWidth);
	float opacity = GetOpacity();

	RGBA edgeColor;
	Vertex baseOutlineVertex;
	Vertex outlineVertices[4];
	GetPropertyForCurrentState("border color", edgeColor);

	edgeColor.a() = static_cast<unsigned char>(edgeColor.a() * opacity);

	baseOutlineVertex.m_color = edgeColor;

	Vertex bottomLeftOutlineVertex = baseOutlineVertex;
	Vertex topLeftOutlineVertex = baseOutlineVertex;
	Vertex topRightOutlineVertex = baseOutlineVertex;
	Vertex bottomRightOutlineVertex = baseOutlineVertex;

	bottomLeftOutlineVertex.m_position = worldPos;
	topLeftOutlineVertex.m_position = worldPos + Vec2(0.f, widgetSize.y());
	topRightOutlineVertex.m_position = worldPos + widgetSize;
	bottomRightOutlineVertex.m_position = worldPos + Vec2(widgetSize.x(), 0.f);

	outlineVertices[0] = bottomLeftOutlineVertex;
	outlineVertices[1] = topLeftOutlineVertex;
	outlineVertices[2] = topRightOutlineVertex;
	outlineVertices[3] = bottomRightOutlineVertex;

	Renderer& renderer = Renderer::GetInstance();
	renderer.RenderPrimitives(GL_LINE_LOOP, outlineVertices, 4);
	glPopAttrib();
}
void EditLineWidget::Render()
{
	WidgetBase::Render();
	LabelWidget::Render();

	Vec2 worldPos = GetWorldPosition();
	float textOpacity = GetTextOpacity();

	RGBA cursorColor;
	GetPropertyForCurrentState("text color", cursorColor);
	cursorColor.a() = static_cast<unsigned char>(cursorColor.a() * textOpacity);

	float textScale;
	GetPropertyForCurrentState("text scale", textScale);

	double time;
	GetPropertyForCurrentState("blink time", time);

	if ((m_currentBlinkTimeSeconds >= time) && m_canType) {
		Vec2 cursorSize = Vec2(1.f, textScale * 5.f);
		if (m_cursorIndex == 0) {
			RenderBackground(worldPos, cursorSize, cursorColor);
		}
		else {
			std::string leftOfCursor = m_fullText.substr(m_leftmostCharacterIndex, m_cursorIndex - m_leftmostCharacterIndex);
			float cursorOffset = m_fontRenderer->CalcTextWidth(leftOfCursor, cursorSize.y());
			RenderBackground(Vec2(worldPos.x() + cursorOffset, worldPos.y()), cursorSize, cursorColor);
		}
	}
	if (m_currentBlinkTimeSeconds >= (time * 2)) {
		m_currentBlinkTimeSeconds = 0.0;
	}
}
Example #4
0
RGBA ColorMatrix::operator*(const RGBA& color) const {
    double result[4] = {0,0,0,0};
    double c[4] = {color.r(), color.g(), color.b(), color.a()};

    for(int y = 0; y < 4; y++) {
	result[y] = matrix[y*4 + 0] * c[0] +
	            matrix[y*4 + 1] * c[1] +
	            matrix[y*4 + 2] * c[2] +
	            matrix[y*4 + 3] * c[3];
    }
    return RGBA(c[0],c[1],c[2],c[3]);
}
//Spawn a particle according to the particle system's vars
void ParticleSystem::spawnParticle() {

	//create a new particle
	Particle * newParticle = new Particle();
	_activeParticles.push_back(newParticle);

	_totalActiveParticles++;

	//set particle variables by applying a random variance to the related variance

	//working out position with variance
	Vector3 randomOffset;
	randomOffset.random(2);
	randomOffset.z = 0;
	newParticle->Position = (Origin - OriginVariance) + (OriginVariance * randomOffset);

	//working out the various properties with variance
	newParticle->Scale = (StartScale - StartScaleVariance) + StartScaleVariance * ((float)rand() / ((float)RAND_MAX / 2));
	newParticle->EndScale = (EndScale - EndScaleVariance) + EndScaleVariance * ((float)rand() / ((float)RAND_MAX / 2));
	newParticle->MaxAge = (ParticleLife - ParticleLifeVariance) + ParticleLifeVariance * ((float)rand() / ((float)RAND_MAX / 2));

	//working out the colour variances
	RGBA randomColourOffset;
	randomColourOffset.random();
	newParticle->Colour = (StartColour - StartColourVariance) + StartColourVariance * randomColourOffset * 2;

	//if the end colours are all -1, then programmer wants the end colour to be the same as the calculated start colour
	if (EndColour.r == -1 && EndColour.g == -1 && EndColour.b == -1) {

		newParticle->EndColour = newParticle->Colour;
		newParticle->EndColour.a = EndColour.a;
	}

	else
		newParticle->EndColour = (EndColour - EndColourVariance) + EndColourVariance * randomColourOffset;

	//if the alpha chanel is -1 then programmer wants end alpha to be same as calculated start alpha
	if (EndColour.a == -1)
		newParticle->EndColour.a = newParticle->Colour.a;

	//work out the direction for the particle by adjusting the starting angle
	float randomAngle = (Angle - AngleVariance) + AngleVariance * ((float)rand() / ((float)RAND_MAX / 2));
	//convert to radians
	float radians = (3.141592 * (randomAngle + 90)) / 180;
	//convert radian angle to direction vector
	newParticle->MoveVector = Vector3(-cosf(radians), sinf(radians), 0);
	float randMoveSpeed = (MoveSpeed - MoveVariance) + MoveVariance * ((float)rand() / ((float)RAND_MAX / 2));
	newParticle->MoveVector = newParticle->MoveVector * randMoveSpeed;
}
void SpawnFirework() {

	Firework * newFirework;

	//make 1 in 4 fireworks a dazzle firework
	if ((int)rand() % 4 == 1)
		newFirework = new DazzleFirework(_particleTexture);

	//and the rest just normal fireworks
	else
		newFirework = new Firework(_particleTexture);

	//place it at a random position around the point (-3, -3, -7)
	Vector3 pos = Vector3(-3, -3, -7);
	Vector3 randOffset;
	randOffset.random(5);
	//giving the variation in position added weight on the x axis so the fireworks spread out more
	randOffset.x *= 1.5f;
	pos = pos + randOffset;
	newFirework->Origin = pos;

	//make it a random colour
	RGBA randColour;
	randColour.random();
	randColour.a = 1;
	newFirework->ExplodeColour = randColour;

	//other poperties I like
	newFirework->ShouldEmitTrail = true;

	//make it a rare chance that some of the fireworks have different settings
	if ((int) rand() % 3 == 1) {

		newFirework->BlendFactor = GL_ONE_MINUS_SRC_COLOR;
		newFirework->TrailLifeModifier = 0.6;
		newFirework->ExplodeSpeed = 0.65f;
	}

	//make it launch for a random time
	float launchTime = (float)rand() / ((float)RAND_MAX / 1.5) + 1.7f;

	//add to list
	_fireworks.push_back(newFirework);

	//launch the firework
	newFirework->launchWithDuration(launchTime);

	_activeFireworks++;
}
Example #7
0
static bool readRGBA(const zeitgeist::ParameterList& in, RGBA& m)
{
    if (
        (in.GetSize() != 4) ||
        (! in.GetValue(in[0], m.r())) ||
        (! in.GetValue(in[1], m.g())) ||
        (! in.GetValue(in[2], m.b())) ||
        (! in.GetValue(in[3], m.a()))
        )
        {
            return false;
        }

    return true;
}
Example #8
0
	gh::Light Light::createAmbientLight( const RGBA& newColor )
	{
		Light toReturn;

		toReturn.m_Color = newColor.AsVector3();

		return toReturn;
	}
Example #9
0
void ImageDrawing::pixel(Image* image, float xf, float yf, const RGBA& color, ImageDrawing::AlphaCombineMode am) {
    int x = int(xf);
    int y = int(yf);
    if (x >= 0 && x < image->getWidth() && y >= 0 && y < image->getHeight()) {
        RGBA c = color;
        double a = c.a();
        if (a < 1.0) {
            RGB existing = image->getRGBA(x,y);    
            if (am == ImageDrawing::ADD) {
                c = existing + c * a;
            } else if (am == ImageDrawing::DECAL) {
                c = (c * a) + (existing * (1.0 - a));
            } 
        }        
        image->setRGBA(x,y,c); 
    }    
}
Example #10
0
bool BMP::read8bits()
{
    std::ifstream imageFile(_pathname.c_str(),std::ios::binary);

    //Palette recuperation
    imageFile.seekg(_offsetImage-1024,std::ios::beg);
    unsigned char red,green,blue,alpha,color;
    RGBA* rgba;
    for(int i=0;i<256;i++)
    {
        rgba = new RGBA();
        imageFile.read((char*)&red,sizeof(char));
        imageFile.read((char*)&green,sizeof(char));
        imageFile.read((char*)&blue,sizeof(char));
        imageFile.read((char*)&alpha,sizeof(char));
        rgba->setRed(red);
        rgba->setGreen(green);
        rgba->setBlue(blue);
        rgba->setAlpha(alpha);
        this->palette.push_back(rgba);
        _correspondancepixelPalette[red][green][blue][alpha]=i;

    }
    imageFile.seekg(_offsetImage,std::ios::beg);
    //pixel recuperation

    //Initialisation array first to reverse to order : 0,0 means top left
    this->pixel.resize(this->getHeightImage());
    for(int i=0;i<this->getHeightImage();i++)
    {
        this->pixel[i].resize(this->getWidthImage());
    }


    for(int i=this->getHeightImage()-1;i>=0;i--)
    {
        for(int j=0;j<this->getWidthImage();j++)
        {
        imageFile.read((char*)&color,sizeof(char));
        this->pixel[i][j]=new RGBA(this->palette[color]);
        }
    }

    imageFile.close();
    return false;
}
Example #11
0
void Buffer::change_color(uint32_t vertex_offset, uint32_t vertex_count, const RGBA& color)
{
	ColorStruct clr;
	clr.color[0] = color.r();
	clr.color[1] = color.g();
	clr.color[2] = color.b();
	clr.color[3] = color.a();
	
	std::vector<ColorStruct> colors;
	for (uint32_t i=0; i < vertex_count; i++)
		colors.push_back(clr);

	glBindBuffer(GL_ARRAY_BUFFER, color_buffer_id);
	glBufferSubData(GL_ARRAY_BUFFER, vertex_offset * sizeof(ColorStruct), 
		vertex_count * sizeof(ColorStruct), &colors[0]);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}
int GdImageRenderer::createColor(const RGBA& color)
{
    if (color.hasAlpha()) {
        return gdImageColorAllocateAlpha(image_, color.red, color.green, color.blue, 127 - (color.alpha / 2));
    }
    else {
        return gdImageColorAllocate(image_, color.red, color.green, color.blue);
    }
}
Example #13
0
void WidgetBase::Render()
{
	Vec2 worldPos = GetWorldPosition();

	float opacity = GetOpacity();

	RGBA backgroundColor;
	GetPropertyForCurrentState("color", backgroundColor);
	backgroundColor.a() = static_cast<unsigned char>(backgroundColor.a() * opacity);

	Vec2 size;
	GetPropertyForCurrentState("size", size);

	float borderSize;
	GetPropertyForCurrentState("border size", borderSize);

	RenderBackground(worldPos, size, backgroundColor);
	RenderOutline(worldPos, size, borderSize);
}
static bool
readRGBAVal(const zeitgeist::ParameterList& in, RGBA& m)
{
    int r,g,b;

    if (
        (in.GetSize() != 4) ||
        (! in.GetValue(in[0], r)) ||
        (! in.GetValue(in[1], g)) ||
        (! in.GetValue(in[2], b)) ||
        (! in.GetValue(in[3], m.a()))
        )
    {
        return false;
    }
    m.r() = r / 255.0;
    m.g() = g / 255.0;
    m.b() = b / 255.0;
    return true;
}
Example #15
0
	gh::Light Light::createDirectionalLight( const RGBA& newColor, const Vector3& newDirection )
	{
		Light toReturn;

		toReturn.m_Color		= newColor.AsVector3();
		toReturn.m_Direction	= newDirection;
		toReturn.m_Direction.normalize();
		toReturn.isDirectional	= 1.f;

		return toReturn;
	}
Example #16
0
	gh::Light Light::createPointLight( const RGBA& newColor, const Vector3& newLocation, float newInnerRadius, float newOuterRadius )
	{
		Light toReturn;

		toReturn.m_Color		= newColor.AsVector3();
		toReturn.m_Location		= newLocation;
		toReturn.innerRadius	= newInnerRadius;
		toReturn.outerRadius	= newOuterRadius;
		toReturn.isPoint		= 1.f;

		return toReturn;
	}
Example #17
0
void SpecularBloom::apply(Image* image) {
    // TODO: Wouldn't a more lightweight <double,1> do the job too?
    Image* glow = new ImageImpl<double,4>(*image);

    RGBA black = RGBA(0,0,0,0);

    int w = image->getWidth();
    int h = image->getHeight();

    for(int x = 0; x < w; x++) {
	for(int y = 0; y < h; y++) {
	    RGBA col = glow->getRGBA(x,y);
	    if (col.brightness() > cutoff) {
		col = col.toGrayscale();
	    } else {
		col = black;
	    }
	    glow->setRGBA(x,y,col);
	}
    }

    // Clip colors
    glow->clipColors();

    GaussianBlur blur_filter = GaussianBlur(radius);
    blur_filter.apply(glow);

    //image->copy(glow);
    
    for(int x = 0; x < w; x++) {
	for(int y = 0; y < h; y++) {
	    RGBA col = image->getRGBA(x,y);
	    col += alpha * glow->getRGBA(x,y);
	    image->setRGBA(x,y,col);
	}
    }

    delete glow;
}
Example #18
0
void UnitViewController::updateBars() {
    GLfloat ratioAp, ratioHp, lengthAp, lengthHp;
    RGBA color;
    
    ratioHp = (GLfloat)_state.hp / (GLfloat)_state.maxHp;
    lengthHp = ratioHp * 32.0f;
    
    ratioAp = (GLfloat)_state.ap / (GLfloat)_state.maxAp;
    lengthAp = ratioAp * 32.0f;
    
    if (ratioHp > 0.75f) {
        color.makeGreen(); 
    } else if (ratioHp > 0.25f) {
        color.makeYellow(); 
    } else {
        color.makeRed(); 
    }
    
    _hpBar->setSize(lengthHp, 4.0f);
    _hpBar->setColor(color);
    
    _apBar->setSize(lengthAp, 6.0f);
}
void ProgressBarWidget::Render()
{
	Vec2 worldPos = GetWorldPosition();
	float progress;

	Vec2 size;
	GetPropertyForCurrentState("size", size);

	float borderSize;
	GetPropertyForCurrentState("border size", borderSize);

	float opacity = GetOpacity();

	RGBA backgroundColor;
	RGBA innerColor;
	GetPropertyForCurrentState("color", backgroundColor);
	GetPropertyForCurrentState("inner color", innerColor);

	backgroundColor.a() *= static_cast<unsigned char>(backgroundColor.a() * opacity);
	innerColor.a() = static_cast<unsigned char>(innerColor.a() * opacity);


	RenderBackground(worldPos, size, backgroundColor);
	GetPropertyForCurrentState("progress", progress);

	CardinalDir dir;
	GetPropertyForCurrentState("direction", dir);
	switch (dir) {
	case C_DIRECTION_EAST:
		RenderBackground(worldPos, Vec2(size.x() * progress, size.y()), innerColor);
		break;
	case C_DIRECTION_WEST: {
		Vec2 fillSize = Vec2(size.x() * progress, size.y());
		Vec2 leftEnd = Vec2(worldPos.x() + size.x() - fillSize.x(), worldPos.y());
		RenderBackground(leftEnd, fillSize, innerColor);
		break;
	}
	case C_DIRECTION_SOUTH: {
		Vec2 fillSize = Vec2(size.x(), size.y()  * progress);
		Vec2 top = Vec2(worldPos.x(), worldPos.y() + size.y() - fillSize.y());
		RenderBackground(top, fillSize, innerColor);
		break;
	}
	case C_DIRECTION_NORTH:
		RenderBackground(worldPos, Vec2(size.x(), size.y()  * progress), innerColor);
		break;
	}

	RenderOutline(worldPos, size, borderSize);

	WidgetBase::ProcessRenderEvent();
	/*
	RenderBackground(worldPos + (size * 0.25f), size * 0.5f, innerColor);
	RenderOutline(worldPos, size, borderSize);
	*/
}
Example #20
0
	gh::Light Light::createSpotlight( const RGBA& newColor, const Vector3& newLocation, const Vector3& newDirection, float newInnerRadius, float newOuterRadius, float newInnerDot, float newOuterDot )
	{
		Light toReturn;

		toReturn.m_Color		= newColor.AsVector3();
		toReturn.m_Location		= newLocation;
		toReturn.m_Direction	= newDirection;
		toReturn.m_Direction.normalize();
		toReturn.innerRadius	= newInnerRadius;
		toReturn.outerRadius	= newOuterRadius;
		toReturn.innerDot		= newInnerDot;
		toReturn.outerDot		= newOuterDot;

		return toReturn;
	}
Example #21
0
void ImageDrawing::filledcircle(Image* image, float x, float y, float r, const RGBA& c, AlphaCombineMode am) {
    for(float yi = y-r; yi < y+r; yi++) {
        float phi = ::asin(::abs(yi-y)/r);
        float xr = abs(::cos(phi)*r);
        // Antialiased begin point
        float a = 1 - ((x-xr) - int(x-xr));
        RGBA d = RGBA(c.r(), c.g(), c.b(), c.a() * a);
        pixel(image, int(x-xr), yi, d, ImageDrawing::DECAL);
        // Middle 
        for(float xi = x-xr+1; xi <= int(x+xr); xi++) {
            pixel(image, xi, yi, c);
        }
        // Antialiased end point
        a = ((x+xr) - int(x+xr));
        d = RGBA(c.r(), c.g(), c.b(), c.a() * a);
        pixel(image, int(x+xr), yi, d, ImageDrawing::DECAL);
    }
}
static bool SetRGBFromArray(ArrayID arr, RGBA& outRGB)
{
	ArrayVar* var = g_ArrayMap.Get(arr);
	if (var && var->IsPacked() && var->Size() == 3) {
		double rgb[3];
		for (UInt32 i=0; i < 3; i++) {
			if (g_ArrayMap.GetElementNumber(arr, i, &rgb[i])) {
				rgb[i] = min(max(0.0, rgb[i]), 255.0);
			}
			else {
				return false;
			}
		}
		outRGB.Set(rgb[0], rgb[1], rgb[2]);
		outRGB.a = 0;
		return true;
	}

	return false;
}
Example #23
0
inline RGBA Interpolate(const RGBA& start, const RGBA& end, float fractionComplete) {
	RGBA interpRGBA;
	interpRGBA.r() = Interpolate(start.r(), end.r(), fractionComplete);
	interpRGBA.g() = Interpolate(start.g(), end.g(), fractionComplete);
	interpRGBA.b() = Interpolate(start.b(), end.b(), fractionComplete);
	interpRGBA.a() = Interpolate(start.a(), end.a(), fractionComplete);
	return interpRGBA;
}
Example #24
0
void FontRendererImpl::DrawText(const std::string& text, const Rect& rect, const RGBA& color, float fontSize, float fontScale, const std::string& fontRef)
{
	// wait for a swap to complete
	FrpSeqAllocatorWaitForSwap();

	m_mutex.lock();

	// create or find a text format
	ComPtr<IDWriteTextFormat> textFormat;

	auto formatKey = std::make_pair(fontRef, fontSize);
	auto formatIter = m_textFormatCache.find(formatKey);

	if (formatIter != m_textFormatCache.end())
	{
		textFormat = formatIter->second;
	}
	else
	{
		m_dwFactory->CreateTextFormat(ToWide(fontRef).c_str(), nullptr, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL, fontSize, L"en-us", textFormat.GetAddressOf());

		m_textFormatCache[formatKey] = textFormat;
	}

	// create or find a cached text layout
	ComPtr<IDWriteTextLayout> textLayout;

	auto layoutKey = std::make_pair(textFormat.Get(), std::make_pair(color.AsARGB(), text));
	auto layoutIter = m_textLayoutCache.find(layoutKey);

	if (layoutIter != m_textLayoutCache.end())
	{
		textLayout = layoutIter->second;
	}
	else
	{
		std::wstring wideText = ToWide(text);
		
		// parse colors and the lot
		std::wstring noColorTextString;

		std::vector<DWRITE_TEXT_RANGE> textRanges;
		std::vector<RGBA> textColors;

		{
			std::wstringstream noColorText;
			int count = 0;

			static const RGBA colors[] = {
				RGBA(0, 0, 0),
				RGBA(255, 0, 0),
				RGBA(0, 255, 0),
				RGBA(255, 255, 0),
				RGBA(0, 0, 255),
				RGBA(0, 255, 255),
				RGBA(255, 0, 255),
				RGBA(255, 255, 255),
				RGBA(100, 0, 0),
				RGBA(0, 0, 100)
			};

			textRanges.reserve(50);
			textColors.reserve(50);

			textRanges.push_back({ 0, UINT32_MAX });
			textColors.push_back(color);

			for (int i = 0; i < wideText.length(); i++)
			{
				if (wideText[i] == '^' && (i + 1) < wideText.length() && isdigit(wideText[i + 1]))
				{
					textRanges.back().length = count - textRanges.back().startPosition;
					textRanges.push_back({ (UINT32)count, UINT32_MAX });

					textColors.push_back(colors[wideText[i + 1] - '0']);

					++i;
					continue;
				}

				noColorText << wideText[i];
				++count;
			}

			textRanges.back().length = count - textRanges.back().startPosition;

			noColorTextString = noColorText.str();
		}

		m_dwFactory->CreateTextLayout(noColorTextString.c_str(), static_cast<UINT32>(noColorTextString.length()), textFormat.Get(), rect.Width(), rect.Height(), textLayout.GetAddressOf());

		m_textLayoutCache[layoutKey] = textLayout;

		// set effect
		for (size_t i : irange(textRanges.size()))
		{
			DWRITE_TEXT_RANGE effectRange = textRanges[i];
			RGBA color = textColors[i];

			static thread_local std::map<uint32_t, ComPtr<FrDrawingEffect>> effects;
			auto it = effects.find(color.AsARGB());

			if (it == effects.end())
			{
				ComPtr<FrDrawingEffect> effect = Make<FrDrawingEffect>();

				effect->SetColor(textColors[i]);

				it = effects.insert({ color.AsARGB(), effect }).first;
			}

			check(SUCCEEDED(textLayout->SetDrawingEffect((IUnknown*)it->second.Get(), effectRange)));
		}
	}

	// draw
	auto drawingContext = new FrDrawingContext();
	textLayout->Draw(drawingContext, m_textRenderer.Get(), rect.Left(), rect.Top());

	auto numRuns = drawingContext->glyphRuns.size();

	if (numRuns)
	{
		for (auto& run : drawingContext->glyphRuns)
		{
			m_queuedRenderables.push_back(std::make_unique<FrGlyphRunRenderable>(run));
			//m_queuedGlyphRuns.push_back(run);
		}
	}

	delete drawingContext;

	m_mutex.unlock();
}
Example #25
0
u32 Surface::MapRGB(const RGBA & color) const
{
    return amask() ? SDL_MapRGBA(surface->format, color.r(), color.g(), color.b(), color.a()) : SDL_MapRGB(surface->format, color.r(), color.g(), color.b());
}
Example #26
0
void Window::clear(RGBA colour) {
    colour.check(); // Check if the RGB values are in the 0.0 <= x <= 1.0 range

    glClearColor(colour.r, colour.g, colour.b, colour.a);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
Example #27
0
void PngIO::save(const Image* const image, FILE* fp) const {

    png_structp png_ptr;
    png_infop info_ptr;

    int width = image->getWidth();
    int height = image->getHeight();

    /* Create and initialize the png_struct with the desired error handler
     * functions.  If you want to use the default stderr and longjump method,
     * you can supply NULL for the last three parameters.  We also check that
     * the library version is compatible with the one used at compile time,
     * in case we are using dynamically linked libraries.  REQUIRED.
     */
    png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
	    NULL, NULL, NULL);

    if (png_ptr == NULL)
    {
	::fclose(fp);
	throw_exception("Error saving PNG");
    }

    /* Allocate/initialize the image information data.  REQUIRED */
    info_ptr = png_create_info_struct(png_ptr);
    if (info_ptr == NULL)
    {
	::fclose(fp);
	png_destroy_write_struct(&png_ptr,  NULL);
	throw_exception("Error saving PNG");
    }

    /* Set error handling.  REQUIRED if you aren't supplying your own
     * error handling functions in the png_create_write_struct() call.
     */
    if (setjmp(png_jmpbuf(png_ptr)))
    {
	/* If we get here, we had a problem reading the file */
	::fclose(fp);
	png_destroy_write_struct(&png_ptr, &info_ptr);
	throw_exception("Error saving ");
    }

    png_init_io(png_ptr, fp);

    png_set_IHDR(png_ptr, info_ptr, width, height, 8, 
	    PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, 
	    PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);

    /*
       text_ptr[0].key = "Title";
       text_ptr[0].text = "RayGay Image";
       text_ptr[0].compression = PNG_TEXT_COMPRESSION_NONE;
       text_ptr[1].key = "Author";
       text_ptr[1].text = "RayGay";
       text_ptr[1].compression = PNG_TEXT_COMPRESSION_NONE;
       text_ptr[2].key = "Description";
       text_ptr[2].text = "An image rendered with RayGay";
       text_ptr[2].compression = PNG_TEXT_COMPRESSION_zTXt;
#ifdef PNG_iTXt_SUPPORTED
text_ptr[0].lang = NULL;
text_ptr[1].lang = NULL;
text_ptr[2].lang = NULL;
#endif

png_set_text(png_ptr, info_ptr, text_ptr, 3);
*/
    png_write_info(png_ptr, info_ptr);

    /* If you are only writing one row at a time, this works */
    png_byte row[width*4];
    png_bytep rowp = row;

    for (int y = 0; y < height; y++)
    {
	for(int x = 0; x < width; x++) {
	    RGBA pixel = image->getRGBA(x,y);
	    row[x*4 + 0] = int(pixel.r() * 255);
	    row[x*4 + 1] = int(pixel.g() * 255);
	    row[x*4 + 2] = int(pixel.b() * 255);
	    row[x*4 + 3] = int(pixel.a() * 255);
	}
	png_write_rows(png_ptr, &rowp, 1);
    }

    png_write_end(png_ptr, info_ptr);

    /* clean up after the write, and free any memory allocated */
    png_destroy_write_struct(&png_ptr, &info_ptr);
}
Example #28
0
RGBA applyAlpha(double a, const RGBA& c) {
    return RGBA(c.r(), c.g(), c.b(), c.a()*a);         
}
Example #29
0
bool Buffer::add_ctm_data(CTMDecoder& ctm, const glm::mat4& matrix, const RGBA& color, Box& bbox, BufferOffset& offset)
{
	auto vertCnt = ctm.get_vertex_count();
	auto triCnt = ctm.get_tri_count();
	auto indexCnt = triCnt * 3;

	update_buffer_count();

	if ((buf_vertex_count + vertCnt) > MAX_VERTEX_COUNT || (buf_index_count + indexCnt) > MAX_INDEX_COUNT)
		return false;

	vertex_buffer.reserve(buf_vertex_count + vertCnt);
	index_buffer.reserve(buf_index_count + indexCnt);

	transparent = color.is_transparent();

	const float* ctm_vertices = ctm.get_vertices();
	const unsigned int* ctm_indices = ctm.get_indices();

	offset.vertex_offset = buf_vertex_count;
	offset.vertex_count = vertCnt;
	offset.index_offset = buf_index_count;
	offset.index_count = indexCnt;

	for (unsigned int i=0; i < vertCnt; i++)
	{
		glm::vec4 pos(ctm_vertices[i * 3], ctm_vertices[i * 3 + 1], ctm_vertices[i * 3 + 2], 1);
		pos = matrix * pos;
		bbox.add_point(glm::vec3(pos));

		VertexStruct vertex;
		vertex.position[0] = pos.x;
		vertex.position[1] = pos.y;
		vertex.position[2] = pos.z;

		vertex.normal[0] = 0;
		vertex.normal[1] = 0;
		vertex.normal[2] = 0;

		ColorStruct clr;
		clr.color[0] = color.r();
		clr.color[1] = color.g();
		clr.color[2] = color.b();
		clr.color[3] = color.a();

		vertex_buffer.push_back(vertex);
		color_buffer.push_back(clr);
	}

	for (unsigned int i=0; i < indexCnt; i += 3)
	{
		auto i0 = ctm_indices[i] + buf_vertex_count;
		auto i1 = ctm_indices[i + 1] + buf_vertex_count;
		auto i2 = ctm_indices[i + 2] + buf_vertex_count;

		index_buffer.push_back(i0);
		index_buffer.push_back(i1);
		index_buffer.push_back(i2);

		glm::vec3 p0(vertex_buffer[i0].position[0], vertex_buffer[i0].position[1], vertex_buffer[i0].position[2]);
		glm::vec3 p1(vertex_buffer[i1].position[0], vertex_buffer[i1].position[1], vertex_buffer[i1].position[2]);
		glm::vec3 p2(vertex_buffer[i2].position[0], vertex_buffer[i2].position[1], vertex_buffer[i2].position[2]);
		glm::vec3 norm = glm::cross((p1 - p0), (p2 - p0));
		
		vertex_buffer[i0].normal[0] += norm.x;
		vertex_buffer[i0].normal[1] += norm.y;
		vertex_buffer[i0].normal[2] += norm.z;

		vertex_buffer[i1].normal[0] += norm.x;
		vertex_buffer[i1].normal[1] += norm.y;
		vertex_buffer[i1].normal[2] += norm.z;

		vertex_buffer[i2].normal[0] += norm.x;
		vertex_buffer[i2].normal[1] += norm.y;
		vertex_buffer[i2].normal[2] += norm.z;
	}

	for (unsigned int i=0; i < vertCnt; i++)
	{
		glm::vec3 norm(vertex_buffer[buf_vertex_count + i].normal[0], 
					vertex_buffer[buf_vertex_count + i].normal[1], 
					vertex_buffer[buf_vertex_count + i].normal[2]);
		norm = glm::normalize(norm);
		vertex_buffer[buf_vertex_count + i].normal[0] = norm.x;
		vertex_buffer[buf_vertex_count + i].normal[1] = norm.y;
		vertex_buffer[buf_vertex_count + i].normal[2] = norm.z;
	}

	return true;
}