예제 #1
0
GLuint esLoadShader(GLenum shader_type, std::string src)
{
  GLint succeeded;
  GLuint sid;

  sid = glCreateShader(shader_type);
  // glShaderSource(sid, 1, (const GLchar **) &src, NULL);
  char const * shaderCodePointer = src.c_str();
  glShaderSource(sid, 1, &shaderCodePointer, NULL);
  glCompileShader(sid);
  glGetShaderiv(sid, GL_COMPILE_STATUS, &succeeded);

  GLint log_length;
  glGetShaderiv(sid, GL_INFO_LOG_LENGTH, &log_length);

  if (log_length > 1) {
    char *log =  (char *) malloc(sizeof(char) * log_length);
    GLint chars_written;
    glGetShaderInfoLog(sid, log_length, &chars_written, log);
    checkGLError(" *********    Error esLoadShader: Loading and compiling a shader.");
    printf("%s\n", log);
    free(log);
  }
  checkGLError(" *********** Error esLoadShader: Something went wrong with the shader.");
  return sid;
}
예제 #2
0
void CVertexBuffer::allocate(U32 size, eUsageType usage, bool system, void *data) {
    mSize = size;
    mUsage = usage;
    mLocked = false;
    //GLEW_ARB_vertex_buffer_object = false;
    if(GLEW_ARB_vertex_buffer_object && !system){
        mSystemMemory = false;
        checkGLError();
        glGenBuffersARB(1, &mBufferId);
        checkGLError();
        GLenum use;
        switch (usage) {
            case STATIC:
                use = GL_STATIC_DRAW_ARB;
                break;
            case DYNAMIC:
                use = GL_STREAM_DRAW_ARB;
                break;
        }
        activate();
        glBufferDataARB(GL_ARRAY_BUFFER_ARB, mSize, data, use);
        checkGLError();
        deactivate();
    } else {
        mSystemMemory = true;
        mSysAddr = malloc(mSize);
        if(data){
            memcpy(mSysAddr, data, mSize);
        }
    }
}
예제 #3
0
//Creates the Vertex Array Object, and Vertex Buffer Objects for the mesh
void Mesh::createBuffers() {
	
	//Generate and fill vertex buffer object
	glGenBuffers(1, &this->vertexBufferID);
	glBindBuffer(GL_ARRAY_BUFFER, this->vertexBufferID);
	checkGLError("Could not generate the VertexBuffer");
	glBufferData(GL_ARRAY_BUFFER, (sizeof(this->vertices[0])*this->vertices.size()), (GLvoid*)&this->vertices[0], GL_STATIC_DRAW);
	checkGLError("Could not fill VertexBuffer");

	//Generate and fill the vertex index buffer
	glGenBuffers(1, &this->vertexIndexID);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->vertexIndexID);
	checkGLError("Could not generate the VertexIndexBuffer");
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, (sizeof(GLuint)*this->vertexIndices.size()), (GLvoid*)&this->vertexIndices[0], GL_STATIC_DRAW);
	checkGLError("Could not fill the VertexIndexBuffer");

	//Generate Vertex Array Object
	glGenVertexArrays(1, &this->vertexArrayID);
	glBindVertexArray(this->vertexArrayID);
	checkGLError("Could not generate and bind VertexArray");

	glBindBuffer(GL_ARRAY_BUFFER, this->vertexBufferID);
	this->shader->linkVertexAttributes();
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->vertexIndexID);

	//Unbind the buffers
	glBindBuffer(GL_ARRAY_BUFFER,0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0);
	glBindVertexArray(0);
}
예제 #4
0
	void MenuRenderer::render() {
		checkGLError("MenuRenderer Start");
		// set the menu projection
		glDisable(GL_CULL_FACE);
		glDisable(GL_DEPTH_TEST);
		glEnable(GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glViewport(0, 0, context->gConfig->viewportWidth, context->gConfig->viewportHeight);
		if (context->gConfig->useShaders) {
			context->renderContext->projMatrix.identity();
			context->renderContext->projMatrix.ortho(0, context->gConfig->width, context->gConfig->height, 0, -1, 1);
			context->renderContext->mvMatrix.identity();
		} else {
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
			// top left is 0,0, so scissor will be inverted y
			glOrthof(0, context->gConfig->width, context->gConfig->height, 0, -1, 1);
			glMatrixMode(GL_MODELVIEW);
			glColor4f(1, 1, 1, 1);
		}
		S32 i = 0;
		for (i = 0; i < context->uiManager->activeMenuStack->getSize(); i++) {
			Menu *menu = context->uiManager->activeMenuStack->array[i];
			UIComponent *root = menu->getRootComponent();
			activeResourceId = -1;
			render(root);
		}
		glDisable(GL_BLEND);
		checkGLError("MenuRenderer End");
	}
예제 #5
0
		void swapDisplayBuffers()
		{
#if OXYGINE_SDL
			if (!_context)
				return;
#endif

            checkGLError();
#if __S3E__
			IwGLSwapBuffers();
#elif USE_EGL || EMSCRIPTEN
			SDL_GL_SwapBuffers();
			//eglSwapBuffers(eglDisplay, eglSurface);
#elif OXYGINE_SDL
			//if (isActive())
			if (_context)
			{
				int status = SDL_GL_MakeCurrent(_window, _context);
				if (status)
				{
					log::error("SDL_GL_MakeCurrent(): %s", SDL_GetError());
				}
				SDL_GL_SwapWindow(_window);
			}
#endif

			IVideoDriver::instance->getStats(_videoStats);
			IVideoDriver::instance->swapped();

			checkGLError();

			//sleep(1000/50);
		}
예제 #6
0
파일: Font.cpp 프로젝트: Df458/DFEngine
Glyph Font::renderGlyph(char glyph, float font_size)
{
    if(m_rendered_symbols[(int)glyph].find(font_size) != m_rendered_symbols[(int)glyph].end()) {
        return m_rendered_symbols[(int)glyph].at(font_size);
    }
    Glyph new_glyph;

    FT_UInt char_index = FT_Get_Char_Index(m_font_face, glyph);

    if(FT_Load_Glyph(m_font_face, char_index, FT_LOAD_DEFAULT) || FT_Render_Glyph(m_font_face->glyph, FT_RENDER_MODE_NORMAL))
        return new_glyph;

    FT_Bitmap& bitmap   = m_font_face->glyph->bitmap;
    new_glyph.bearing.x = m_font_face->glyph->metrics.horiBearingX / 64;
    new_glyph.bearing.y = m_font_face->glyph->metrics.horiBearingY / 128;
    new_glyph.advance   = m_font_face->glyph->metrics.horiAdvance / 64;

    glGenTextures(1, &new_glyph.texture);
    glBindTexture(GL_TEXTURE_2D, new_glyph.texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    checkGLError();

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bitmap.width, bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, bitmap.buffer);
    checkGLError();
    new_glyph.id = glyph;
    new_glyph.dimensions = glm::vec2(bitmap.width, bitmap.rows);
    m_rendered_symbols[(int)glyph][font_size] = new_glyph;

    return new_glyph;
}
bool HeightMap::appMain() {
    if (!running) {
        return false;
    }
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(program.programID());
    running &= checkGLError("Error encountered enabling Shader Program\n", Logger::LOG_ERROR);

    _xform = Matrix4::translate(0.0f, -1.0f, _zPlane) 
           * Matrix4::rotate(40.0f, 0.0f, 0.0f)
           * Matrix4::rotate(0.0f, _angle, 0.0f);

    glUniformMatrix4fv(_xformLoc, 1, false, _xform.buffer());
    running &= checkGLError("Error encountered enabling loading Transform matrix: %s\n", Logger::LOG_ERROR);

    glDrawArrays(_drawMode, 0, _totalVerts);
    running &= checkGLError("Error encountered calling glDrawArrays: %s\n", Logger::LOG_ERROR);

    display->swapBuffers();
    display->mainLoop(*this);

    _angle += 0.5f;
    if (_angle >= 360.0f) {
        _angle -= 360.0f;
    };

    return true;
}
예제 #8
0
// private
void CGLvbo::Init(const int nElements, const void *pVertexBuf, const void *pNormalBuf, const void *pUVBuf, GLenum nUsage)
{
	assert(nullptr!=pVertexBuf);
	assert(0<nElements);
	assert( nUsage>=0x88E0 && nUsage<=0x88EA );

	Cleanup();
	checkGLError();

	glGenVertexArrays(1, &mVAO);
	glBindVertexArray(mVAO);

	// the vertex buffer is NOT optional
	glGenBuffers(1, &mVertObjId);
	glBindBuffer(GL_ARRAY_BUFFER, mVertObjId);
	glBufferData(GL_ARRAY_BUFFER, nElements * sizeof(glm::vec3), pVertexBuf, nUsage);
	checkGLError();

	if(pNormalBuf) {
		glGenBuffers(1, &mNormObjId);
		glBindBuffer(GL_ARRAY_BUFFER, mNormObjId);
		glBufferData(GL_ARRAY_BUFFER, nElements * sizeof(glm::vec3), pNormalBuf, nUsage);
		checkGLError();
	}

	if(pUVBuf) {
		glGenBuffers(1, &mUVObjId);
		glBindBuffer(GL_ARRAY_BUFFER, mUVObjId);
		glBufferData(GL_ARRAY_BUFFER, nElements * sizeof(glm::vec2), pUVBuf, nUsage);
		checkGLError();
	}

	// LOG_GLERROR();
}
예제 #9
0
void SDLFontGL::updateDimensions() {
	if (!m_openglActive || 0 == nWidth || 0 == nHeight) return;

	unsigned int oldCols = m_cols, oldRows = m_rows;

	m_cols = m_dimW / nWidth;
	m_rows = m_dimH / nHeight;

	m_curdimW = m_cols * nWidth;
	m_curdimH = m_rows * nHeight;
	m_curdimX = m_dimX + (m_dimW - m_curdimW) / 2;
	m_curdimY = m_dimY + (m_dimH - m_curdimH) / 2;

	if (oldCols != m_cols || oldRows != m_rows || !m_cellsTex) {
		updateCells();
	}

	if (m_charShader.program) {
		glUseProgram(m_charShader.program);
		checkGLError();

		glUniform2f(m_charShader.aDim, m_cols, m_rows);
		checkGLError();
	}

	if (m_cursorShader.program) {
		glUseProgram(m_cursorShader.program);
		checkGLError();

		glUniform2f(m_cursorShader.aDim, m_cols, m_rows);
		checkGLError();
	}
}
예제 #10
0
파일: sdlfontgl.cpp 프로젝트: minego/wTerm
void SDLFontGL::createTexture() {
	// Create Big GL texture:
	glGenTextures(1,&GlyphCache);
	glBindTexture(GL_TEXTURE_2D, GlyphCache);

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

	// Set size of the texture, but no data.
	// We want 1 extra row of pixel data
	// so we can draw solid colors as part
	// of the same operations.
	texW = nextPowerOfTwo(nChars*nWidth);
	texH = nextPowerOfTwo(nFonts*MAX_CHARSETS*nHeight + 1);
	int nMode = getGLFormat();
	glTexImage2D(GL_TEXTURE_2D,
			0, nMode,
			texW, texH,
			0, nMode,
			GL_UNSIGNED_BYTE, NULL);
	checkGLError();


	// Put a single white pixel at bottom of texture.
	// We use this as the 'texture' data for blitting
	// solid backgrounds.
	char whitepixel[] = { 255, 255, 255, 255 };
	assert(nFonts && nHeight);
	glTexSubImage2D(GL_TEXTURE_2D, 0,
			0,nFonts*MAX_CHARSETS*nHeight,
			1, 1,
			GL_RGBA, GL_UNSIGNED_BYTE, whitepixel);
	checkGLError();
}
예제 #11
0
파일: Font.cpp 프로젝트: Df458/DFEngine
void Font::draw(IScene* scene, const char* text, glm::mat4 transform, float font_size, glm::vec3 color)
{
	FT_Set_Pixel_Sizes(m_font_face, font_size, font_size);
    glUseProgram(TEXT_PROGRAM);
    checkGLError();

    glm::vec3 pen(0, 0, 0);
    char prev = 0;
    bool kern = FT_HAS_KERNING(m_font_face);
    for(const char* i = text; i[0]; ++i) {
        FT_UInt index = FT_Get_Char_Index(m_font_face, i[0]);
        Glyph glyph = renderGlyph(i[0], font_size);

        if(prev && kern && i) {
            FT_Vector delta;
            FT_Get_Kerning(m_font_face, prev, index, FT_KERNING_DEFAULT, &delta);
            pen.x += delta.x * scene->getDPU();
            //fprintf(stderr, "%ld\n", delta.x);
        }

        if(i[0] == '\n') {
            pen.x = 0;
            pen.y += font_size;
            prev = 0;
            continue;
        } else if(i[0] == ' ' || glyph.id == 0) {
            pen.x += font_size;
            prev = 0;
            continue;
        }

        glUniform3f(m_color_uniform, color.x, color.y, color.z);
        glm::vec3 offset(glyph.bearing.x, -glyph.bearing.y, 0.0f);

        glm::mat4 mvp = scene->getActiveProjectionMatrix() *
                        scene->getActiveViewMatrix() *
                        transform *
                        glm::translate(glm::mat4(1), -(pen + offset) * scene->getDPU()) *
                        glm::scale(glm::mat4(1), glm::vec3(glyph.dimensions.x * scene->getDPU(), glyph.dimensions.y * scene->getDPU(), 1.0f));
        //fprintf(stderr, "Result: %f, %f, %f, %f\n", glyph.dimensions.x, glyph.dimensions.y, glyph.dimensions.x * scene->getDPU(), glyph.dimensions.y * scene->getDPU());
        glUniformMatrix4fv(m_transform_uniform, 1, GL_FALSE, &mvp[0][0]);
        glEnableVertexAttribArray(m_vertex_position);
        glBindBuffer(GL_ARRAY_BUFFER, QUAD_BUFFER);
        glVertexAttribPointer(m_vertex_position, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, glyph.texture);
        glUniform1i(m_texture_uniform, 0);
        checkGLError();

        glDrawArrays(GL_TRIANGLES, 0, 6);
        checkGLError();

        glDisableVertexAttribArray(m_vertex_position);
        pen.x += glyph.advance;
        //fprintf(stderr, "(%d)\n", (int)glyph.advance);
        prev = index;
    }
}
예제 #12
0
    void
    PhysicsDebugDrawer::drawAll
    ()
    {
        #ifdef DREAM_LOG
        auto log = getLog();
        log->debug( "Drawing {} lines" , mVertexBuffer.size()/2 );
        #endif
        preRender();

        // Enable shader program
        glUseProgram(mShaderProgram);

        glBindVertexArray(mVAO);
        ShaderRuntime::CurrentShaderProgram = mShaderProgram;

        // Set the projection matrix
        GLint projUniform = glGetUniformLocation(mShaderProgram, "projection");
        if (projUniform == -1)
        {
            #ifdef DREAM_LOG
            log->error( "Unable to find Uniform Location for projection" );
            checkGLError();
            #endif
            return;
        }
        else
        {
            mat4 projectionMatrix = mCamera->getProjectionMatrix();
            glUniformMatrix4fv(projUniform, 1, GL_FALSE, glm::value_ptr(projectionMatrix));
        }

        // Set the view matrix
        GLint viewUniform = glGetUniformLocation(mShaderProgram, "view");
        if (viewUniform == -1)
        {
            #ifdef DREAM_LOG
            log->error( "Unable to find Uniform Location for view" );
            checkGLError();
            #endif
            return;
        }
        else
        {
            mat4 viewMatrix = mCamera->getViewMatrix();
            glUniformMatrix4fv(viewUniform, 1, GL_FALSE, glm::value_ptr(viewMatrix));
        }

        glBindBuffer(GL_ARRAY_BUFFER, mVBO);
        glBufferData(GL_ARRAY_BUFFER, static_cast<GLint>(mVertexBuffer.size() * sizeof(PhysicsDebugVertex)), &mVertexBuffer[0], GL_STATIC_DRAW);

        // Draw
        glDrawArrays(GL_LINES, 0, static_cast<GLsizei>(mVertexBuffer.size()));
        // Unbind
        postRender();
        // Clear old buffer
        mVertexBuffer.clear();
    }
예제 #13
0
void CGLfbo::CopyTexture(const uint32_t target) const
{
	glBindTexture(GL_TEXTURE_2D, target);
	checkGLError();
	glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 0, 0, mWidth, mHeight, 0);
	checkGLError();
	glBindTexture(GL_TEXTURE_2D, 0);
	checkGLError();
}
예제 #14
0
파일: font.cpp 프로젝트: harkal/sylphis3d
void CBitmapFont::generateGlyph(U32 ch){
	S32 pad = 3;
	FT_GlyphSlot  slot = mFace->glyph;
	FT_Glyph glyph;
    FT_UInt glyph_index;

	glyph_index = FT_Get_Char_Index( mFace, (FT_ULong)ch );

	FT_Load_Glyph( mFace, glyph_index, FT_LOAD_DEFAULT);
	FT_Get_Glyph( slot, &glyph);

	FT_Glyph_To_Bitmap(&glyph, ft_render_mode_normal, 0 ,1);

	FT_BitmapGlyph bitmap = (FT_BitmapGlyph)glyph;
	FT_Bitmap* source = &bitmap->bitmap;


	S32 srcWidth = source->width;
	S32 srcHeight = source->rows;
	S32 srcPitch = source->pitch;

	S32 dstWidth = srcWidth;
	S32 dstHeight = srcHeight;
	S32 dstPitch = srcPitch;

	FT_BBox bbox;
	FT_Glyph_Get_CBox( glyph, ft_glyph_bbox_pixels, &bbox);

	unsigned char *src = source->buffer;

	if(pen.x + srcWidth >= mTextureSize){
		pen.x = 0;
		pen.y += (getFontSize() * 64.0f / dpi) + pad;
	}

	glBindTexture(GL_TEXTURE_2D, curTex);checkGLError();
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);checkGLError();
	glTexSubImage2D(GL_TEXTURE_2D, 0, 
		pen.x, pen.y,
		srcWidth, srcHeight,
		GL_ALPHA, GL_UNSIGNED_BYTE, src); checkGLError();

	CTexCoord start(pen);
	start /= mTextureSize;
	CTexCoord end(pen.x + srcWidth, pen.y + srcHeight);
	end /= mTextureSize;
	//CVector2 pos(slot->bitmap_left, slot->bitmap_top);
	CVector2 pos(bitmap->left, srcHeight - bitmap->top);
	CVector2 size(srcWidth, srcHeight);
	CVector2 advance(slot->advance.x >> 6, slot->advance.y >> 6);
	
	mGlyphs[glyph_index] = new CBitmapGlyph(curTex, start, end, pos, size, advance);

	pen.x += srcWidth + pad;

	FT_Done_Glyph(glyph);
}
예제 #15
0
  void Render::drawVertices(const std::vector<inputData> &vertices)
{
   assert(initialized);
   glBufferSubData(GL_ARRAY_BUFFER,0, vertices.size() * sizeof(inputData),&vertices[0]);
   checkGLError();

   glDrawElements(GL_TRIANGLES,6 * vertices.size()/4,GL_UNSIGNED_SHORT,0);
   checkGLError();
}
예제 #16
0
CGLfbo::~CGLfbo() {
	if(glIsTexture(mTexture)==GL_TRUE) {
		glDeleteTextures(1, &mTexture);
		checkGLError();
	}
	if(glIsFramebuffer(mFBO)==GL_TRUE) {
		glDeleteFramebuffers(1, &mFBO);
		checkGLError();
	}
}
예제 #17
0
		void init2()
		{
#ifdef OXYGINE_SDL
			initGLExtensions(SDL_GL_GetProcAddress);
#endif

			Point size = getDisplaySize();
			log::messageln("display size: %d %d", size.x, size.y);


#if __S3E__
			int glversion = s3eGLGetInt(S3E_GL_VERSION);
			int major_gl = glversion >> 8;

			if (major_gl == 2)
				IVideoDriver::instance = new VideoDriverGLES20();
			else
			{
				OX_ASSERT(!"gl version should be 2");
				//IVideoDriver::instance = new VideoDriverGLES11();			
			}

#elif __FLASHPLAYER__
			{
				VideoDriverStage3D *vd = new VideoDriverStage3D();
				vd->init();
				IVideoDriver::instance = vd;
			}

			//IVideoDriver::instance = new VideoDriverNull();
#else
			IVideoDriver::instance = new VideoDriverGLES20();			
#endif


			checkGLError();

			IVideoDriver::instance->setDefaultSettings();

			checkGLError();

			Renderer::initialize();

			Resources::registerResourceType(ResAtlas::create, "atlas");
			Resources::registerResourceType(ResBuffer::create, "buffer");
			Resources::registerResourceType(ResFontBM::create, "font");
			Resources::registerResourceType(ResFontBM::createBM, "bmfc_font");
			Resources::registerResourceType(ResFontBM::createSD, "sdfont");
			Resources::registerResourceType(ResStarlingAtlas::create, "starling");

			checkGLError();
			log::messageln("oxygine initialized");


		}
예제 #18
0
void drawGuiLogo() {
  float pos[] = { 512 - 10 - 256, 384 - 64 };
  float size[] = { 256, 64 };
  float glpos = 64;
  float glsize = 32;
  float font_shift[] = { 0.5, 0.00 };

  checkGLError("gui logo start");
  
  rasonly(game->screen);

  pos[0] *= game->screen->vp_w / 512.0;
  pos[1] *= game->screen->vp_h / 384.0;
  size[0] *= game->screen->vp_w / 512.0;
  size[1] *= game->screen->vp_h / 384.0;
  glpos *= game->screen->vp_w / 512.0;
  glsize *= game->screen->vp_w / 512.0;
  
  glEnable(GL_TEXTURE_2D);
  if(game->settings->show_gl_logo == 1) {
    glPushMatrix();
    glTranslatef(pos[0] - glpos + glsize * font_shift[0], 
		 pos[1] + glsize * font_shift[1], 0);
    glScalef(glsize, glsize, glsize);
    glColor3f(0.2, 0.4, 0.8);
    ftxRenderString(gameFtx, "gl", 2);
    glPopMatrix();
  }
  glBindTexture(GL_TEXTURE_2D, game->screen->textures[TEX_LOGO]);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glColor3f(1.0, 1.0, 1.0);
  glBegin(GL_QUADS);

  glTexCoord2f(0.0, 0.0);
  glVertex2f(pos[0], pos[1]);

  glTexCoord2f(1.0, 0.0);
  glVertex2f(pos[0] + size[0], pos[1]);

  glTexCoord2f(1.0, 1.0);
  glVertex2f(pos[0] + size[0], pos[1] + size[1]);

  glTexCoord2f(0.0, 1.0);
  glVertex2f(pos[0], pos[1] + size[1]);

  glEnd();

  glDisable(GL_BLEND);

  checkGLError("gui background end");
}
void HeightMap::keyEvent(SDL_Keysym &key, bool press) {
    if (!press) {
        return;
    }

    switch(key.sym) {
    case SDLK_a:
        if (_vertsPerSide < 1024) {
            _vertsPerSide *= 2;
            _totalVerts = _vertsPerSide * 2 * (_vertsPerSide - 1);
            glUniform1i(_vpsLoc, _vertsPerSide);
            checkGLError("Error encountered updating Vertices Per Side count: %s\n", Logger::LOG_WARN);
        }
        break;
    case SDLK_z:
        if (_vertsPerSide > 4) {
             _vertsPerSide /= 2;
             _totalVerts = _vertsPerSide * 2 * (_vertsPerSide - 1);
             glUniform1i(_vpsLoc, _vertsPerSide);
             checkGLError("Error encountered updating Vertices Per Side count: %s\n", Logger::LOG_WARN);
        }
        break;
    case SDLK_d:
        _drawMode = GL_TRIANGLE_STRIP;
        running &= buildShaderProgram(VERTEX_SHADER, "heightmap-debugfrag.sdr");
        loadUniforms();
        break;
    case SDLK_c:
        _drawMode = GL_TRIANGLE_STRIP;
        running &= buildShaderProgram(VERTEX_SHADER, FRAGMENT_SHADER);
        loadUniforms();
        break;
    case SDLK_p:
        glPointSize(2.0);
        _drawMode = GL_POINTS;
        running &= buildShaderProgram(VERTEX_SHADER, "heightmap-pointdebug.sdr");
        loadUniforms();
        break;
    case SDLK_f:
        _flatten = !_flatten;
        glUniform1i(_flattenLoc, _flatten);
        break;
    case SDLK_s:
        if (_zPlane < 4.0f) {
            _zPlane += 0.1f;
        }
        break;
    case SDLK_x:
        if (_zPlane > 0.0f) {
            _zPlane -= 0.1f;
        }
        break;
    }
}
예제 #20
0
void Render::perspectiveOrtho(double left,double right,double bottom, double top, double near, double far)
{
   assert(initialized);
   int perspectivePosition = glGetUniformLocation(program,"in_ProjectionMatrix");
   checkGLError();

   float matrix[16] = {};
   makeOrtho(left,right,bottom,top,near,far,matrix);

   glUniformMatrix4fv(perspectivePosition,1,false,matrix);
   checkGLError();
}
void ColorShaderProgram::updateUniforms(void){
	glm::mat4 modelMatrix = *this->owner->getTransform()->getTransformMatrix();
	glm::mat4 viewMatrix = *EngineData::getActiveCamera()->transform.getTransformMatrix();
	glm::mat4 projectionMatrix = EngineData::getActiveCamera()->ProjectionMatrix;

	glUniformMatrix4fv(this->modelMatrixUniform, 1, GL_FALSE, glm::value_ptr(modelMatrix));
	checkGLError("Could not update uniforms1");
	glUniformMatrix4fv(this->viewMatrixUniform, 1, GL_FALSE, glm::value_ptr(viewMatrix));
	checkGLError("Could not update uniforms2");
	glUniformMatrix4fv(this->projectionMatrixUniform, 1, GL_FALSE, glm::value_ptr(projectionMatrix));
	checkGLError("Could not update uniforms3");
}
예제 #22
0
// Orphan GL buffer
int modelEngine::orphanArrayBuffer(GLuint buffer, int size)
{
	// Bind buffer
	glBindBuffer(GL_ARRAY_BUFFER, buffer);
	checkGLError();
	// Orphan
	glBufferData(GL_ARRAY_BUFFER, size, NULL, GL_STATIC_DRAW);
	checkGLError();
	// Unbind
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	return checkGLError();
}
예제 #23
0
void guiProjection(int x, int y) {
  checkGLError("gui.c guiProj - start");
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  /*glOrtho(0, 0, x, y, -1, 1); */
  checkGLError("gui.c guiProj - proj");
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();
  glViewport(game->screen->vp_x, game->screen->vp_y,
	     x, y);
  checkGLError("gui.c guiProj - end");
}
예제 #24
0
	/**
	 * \brief AxisMgr::draw,	render axis Axis lines,
	 */
	void AxisMgr::draw()
	{
		const float tick = mScene->getElapsedTime();
		LineShader &shader 	= getShader();
		glDisable(GL_CULL_FACE);
		glUseProgram(shader.mShader);
		checkGLError("glUseProgram");

		glm::vec3 sv(1.0f,1.0f,1.0f);

		// Update variables to the shader, that is only updated commonly for all bars once per frame such as ParojactionMatrix, ViewMatrix, should be World Matrix aswell
		// projectionMatrix and viewMatrix tick time, resolution constants for pixel shader that are identical trough out the obj calls. hence update only once.
		glUniform1f(shader.mTimeLoc, tick);
		checkGLError("glUniform1f");
		glUniform2f(shader.mResolutionLoc, 1.0f/(float)mScene->getWidth(), 1.0f/(float)mScene->getHeight());
		checkGLError("glUniform2f");
		glUniformMatrix4fv(shader.mMatrixPVW, 1, GL_FALSE, &mScene->getPVWMat()[0][0]);
		checkGLError("glUniformMatrix4fv");
		glUniform3fv(shader.mScaleV,1, (float *)&sv.x);				// mScale location => variable "ScaleV" in vertex shader
		checkGLError("glUniform3fv");

		glEnableVertexAttribArray(shader.mAttribVtxLoc);

		for(size_t i = 0; i<mLineArray.size(); i++)
		{
			Line &ln = mLineArray[i];
			glBindBuffer(GL_ARRAY_BUFFER, shader.mVertexbuffer[ln.mAxisAlign]);
			glVertexAttribPointer(
				shader.mAttribVtxLoc,      // attribute
				3,                  // size
				GL_FLOAT,           // type
				GL_FALSE,           // normalized?
				0,                  // stride
				(void*)0            // array buffer offset
			);
//			checkGLError("glEnableVertexAttribArray");
			glLineWidth(ln.mWidth);

			glm::vec4 tpos = glm::vec4(ln.mPos.x, ln.mPos.y, ln.mPos.z, 1.0f);
			glUniform4fv(shader.mTPos,1, (float *)&tpos.x);
			glUniform4fv(shader.mColor,1, (float *)&ln.mColor.x);
			glUniform3fv(shader.mLength,1, (float *)&ln.mScale.x);				// mScale location => variable "ScaleV" in vertex shader
			glDrawArrays(GL_LINES, 0, 2);
		}

		glDisableVertexAttribArray(shader.mAttribVtxLoc);
		glBindBuffer(GL_ARRAY_BUFFER,0);

		// Clean-up

		glUseProgram(0);
	}
예제 #25
0
void initTexture(gDisplay *d) {
    GLint min_filter;
    char texname[120];

    int i, j;

    if(getSettingi("use_mipmaps")) {
        if(getSettingi("mipmap_filter") == TRILINEAR)
            min_filter = GL_LINEAR_MIPMAP_LINEAR;
        else
            min_filter = GL_LINEAR_MIPMAP_NEAREST;
    } else
        min_filter = GL_LINEAR;

    checkGLError("texture.c initTexture - start");
    /* todo: move that somewhere else */
    glGenTextures(game_textures, d->textures);
    checkGLError("texture.c initTexture - creating textures");
    for(i = 0; i < n_textures; i++) {
        for( j = 0; j < textures[i].count; j++) {
            glBindTexture(GL_TEXTURE_2D, d->textures[ textures[i].id + j ]);
            /* todo: snprintf would be safer, but win32 doesn't have it */
            if(textures[i].count == 1) {
                sprintf(texname, "%s%s", textures[i].name, TEX_SUFFIX);
            } else {
                sprintf(texname, "%s%d%s", textures[i].name, j, TEX_SUFFIX);
            }
            loadTexture(texname, textures[i].type);

            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, textures[i].wrap_s);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, textures[i].wrap_t);

            if(getSettingi("softwareRendering")) {

                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            } else {
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
                glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);

#define GL_TEXTURE_MAX_ANISOTROPY_EXT     0x84FE

                if(renderer.ext_filter_anisotropic) {
                    /* fprintf(stderr, "enabling anisotropic filtering\n"); */
                    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT,
                                    textures[i].anisotropy);
                }
            }
            checkGLError("texture.c initTextures");
        }
    }
}
예제 #26
0
bool init_grid()
{
    grid_program = create_program(GRID_VERTEX_SHADER, GRID_FRAGMENT_SHADER);
    /* grid_position_attrib = glGetAttribLocation(grid_program, "position"); */
    /* grid_horizontal_attrib = glGetAttribLocation(grid_program, "horizontal"); */
    /* grid_vertex_attrib = glGetAttribLocation(grid_program, "vertex_pos"); */
    /* grid_transform_uniform = glGetUniformLocation(grid_program, "transform"); */
    /* grid_texture_uniform = glGetUniformLocation(grid_program, "texture"); */
    /* grid_color_uniform = glGetUniformLocation(grid_program, "color"); */
    /* if(checkGLError()) */
    /*     return false; */

    glGenBuffers(1, &grid_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, grid_buffer);
	glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(float), GRID_BUFFER_DATA, GL_STATIC_DRAW);
    if(checkGLError())
        return false;

    float position_buffer_data[TILEMAP_DIMS * 6];
    GLuint horiz_buffer_data[TILEMAP_DIMS * 2];

    for(int i = 0; i < TILEMAP_DIMS; ++i) {
        position_buffer_data[i*3] = i * 32;
        position_buffer_data[i*3 + 1] = 0;
        position_buffer_data[i*3 + 2] = -1;
        horiz_buffer_data[i] = 0;
    }

    for(int i = 0; i < TILEMAP_DIMS; ++i) {
        position_buffer_data[(TILEMAP_DIMS * 3) + (i*3)] = 0;
        position_buffer_data[(TILEMAP_DIMS * 3) + (i*3 + 1)] = i * 32;
        position_buffer_data[(TILEMAP_DIMS * 3) + (i*3 + 2)] = -1;
        horiz_buffer_data[(TILEMAP_DIMS) + i] = 1;
    }

    glGenBuffers(1, &grid_position_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, grid_position_buffer);
	glBufferData(GL_ARRAY_BUFFER, 6 * TILEMAP_DIMS * sizeof(float), position_buffer_data, GL_STATIC_DRAW);
    if(checkGLError())
        return false;


    glGenBuffers(1, &grid_horiz_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, grid_horiz_buffer);
	glBufferData(GL_ARRAY_BUFFER, 2 * TILEMAP_DIMS * sizeof(GLuint), horiz_buffer_data, GL_STATIC_DRAW);
    if(checkGLError())
        return false;

    grid_dash_texture = create_texture_data(1, 5, GRID_TEXTURE_BUFFER_DATA);

    return true;
}
Texture::Texture(SDL_Surface &surface, GLenum texUnit) {
    GLint intFormat;
    GLenum format, type;
    bool recognised;

    _refCount = 0;

    glGenTextures(1, &_GLtexture);
    Logger::logprintf(Logger::LOG_VERBOSEINFO, Logger::LOG_TEXTURES, "Loading SDL Surface 0x%X (Pixel Format %s) to OpenGL name %i and Texture Unit GL_TEXTURE%i\n", &surface,SDL_GetPixelFormatName(surface.format->format), _GLtexture, texUnit - GL_TEXTURE0);

    switch(surface.format->format) {
    case SDL_PIXELFORMAT_ABGR8888:
        intFormat = GL_RGBA8;
        format = GL_RGBA;
        type = GL_UNSIGNED_BYTE;
        recognised = true;
        break;
    case SDL_PIXELFORMAT_ARGB8888:
        intFormat = GL_RGBA8;
        format = GL_BGRA;
        type = GL_UNSIGNED_BYTE;
        recognised = true;
        break;
    default:
        Logger::logprintf(Logger::LOG_WARN, Logger::LOG_TEXTURES, "No mapped GL format for SDL pixel format %s, will be reformatted internally\n", SDL_GetPixelFormatName(surface.format->format));
        recognised = false;
        break;
    }

    glActiveTexture(texUnit);
    glBindTexture( GL_TEXTURE_2D, _GLtexture);
    _loaded = checkGLError("glBindTexture failed: %s\n", Logger::LOG_ERROR );

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        
    if ( recognised ) {
        glTexImage2D( GL_TEXTURE_2D, 0, intFormat, surface.w, surface.h
                    , 0, format, type, surface.pixels );
    } else {
        SDL_Surface *surface_bgra;

        Logger::logprintf(Logger::LOG_INFO, Logger::LOG_TEXTURES, "Converting source SDL pixel format %s to SDL_PIXELFORMAT_ABGR8888\n", SDL_GetPixelFormatName(surface.format->format));
        surface_bgra = SDL_ConvertSurfaceFormat(&surface, SDL_PIXELFORMAT_ABGR8888, 0);
        
        glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, surface_bgra->w, surface_bgra->h
                    , 0, GL_RGBA, GL_UNSIGNED_BYTE, surface_bgra->pixels );
        SDL_FreeSurface(surface_bgra);
    }
    _loaded &= checkGLError("Failed to load texture from SDL Surface: %s\n", Logger::LOG_ERROR);
}
예제 #28
0
void drawGuiLogo(void) {
  float pos[] = { 512 - 10 - 320, 384 - 80 };
  float size[] = { 320, 80 };
  float glpos = 64;
  float glsize = 32;

  checkGLError("gui logo start");
  
  rasonly(gScreen);

  pos[0] *= gScreen->vp_w / 512.0f;
  pos[1] *= gScreen->vp_h / 384.0f;
  size[0] *= gScreen->vp_w / 512.0f;
  size[1] *= gScreen->vp_h / 384.0f;
  glpos *= gScreen->vp_w / 512.0f;
  glsize *= gScreen->vp_w / 512.0f;
  
  glEnable(GL_TEXTURE_2D);

  glBindTexture(GL_TEXTURE_2D, gScreen->textures[TEX_LOGO]);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

  glEnable(GL_BLEND);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glColor3f(1.0, 1.0, 1.0);
  glBegin(GL_QUADS);

	{ 
		// float texy = 1.0f - 256.0f / 320.0f;
		float texy = 0.0f;
		glTexCoord2f(0.0, texy);
		glVertex2f(pos[0], pos[1]);

		glTexCoord2f(1.0, texy);
		glVertex2f(pos[0] + size[0], pos[1]);

		glTexCoord2f(1.0, 1.0);
		glVertex2f(pos[0] + size[0], pos[1] + size[1]);

		glTexCoord2f(0.0, 1.0);
		glVertex2f(pos[0], pos[1] + size[1]);
	}
	
  glEnd();

  glDisable(GL_BLEND);

  checkGLError("gui background end");
}
예제 #29
0
파일: Font.cpp 프로젝트: Df458/DFEngine
void Font::draw2D(IScene* scene, const char* text, glm::mat4 transform, float font_size, glm::vec3 color)
{
	FT_Set_Pixel_Sizes(m_font_face, 0, font_size);

    glUseProgram(TEXT_PROGRAM);

    glm::vec3 pen(font_size, font_size, 0);
    glm::vec2 view = scene->getViewportSize();
    for(const char* i = text; i[0]; ++i) {
        Glyph glyph = renderGlyph(i[0], font_size);
        //FT_UInt char_index = FT_Get_Char_Index(m_font_face, i[0]);

        //if(FT_Load_Glyph(m_font_face, char_index, FT_LOAD_DEFAULT) || FT_Render_Glyph(m_font_face->glyph, FT_RENDER_MODE_NORMAL))
            //continue; // TODO: Handle FreeType errors

        if(i[0] == '\n') {
            pen.x = font_size;
            pen.y += font_size;
            continue;
        } else if(i[0] == ' ' || glyph.id == 0) {
            pen.x += font_size;
            continue;
        }

        //FT_Bitmap& bitmap = m_font_face->glyph->bitmap;

        glUniform3f(m_color_uniform, color.x, color.y, color.z);
        glm::vec3 offset(glyph.bearing.x * scene->getDPU(), -glyph.bearing.y * scene->getDPU(), 0.0f);
        glm::mat4 mvp = glm::ortho(0.0f, view.x, view.y, 0.0f, -10.0f, 10.0f) *
                        transform *
                        glm::rotate(glm::mat4(1), (float)M_PI, glm::vec3(0, 0, 1)) *
                        glm::translate(glm::mat4(1), -(pen + offset)) *
                        glm::scale(glm::mat4(1), glm::vec3(glyph.dimensions.x * scene->getDPU(), glyph.dimensions.y * scene->getDPU(), 1.0f));
        glUniformMatrix4fv(m_transform_uniform, 1, GL_FALSE, &mvp[0][0]);
        glEnableVertexAttribArray(m_vertex_position);
        glBindBuffer(GL_ARRAY_BUFFER, QUAD_BUFFER);
        glVertexAttribPointer(m_vertex_position, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, glyph.texture);
        glUniform1i(m_texture_uniform, 0);
        checkGLError();

        glDrawArrays(GL_TRIANGLES, 0, 6);
        checkGLError();

        glDisableVertexAttribArray(m_vertex_position);
        pen.x += glyph.advance;
    }
}
예제 #30
0
파일: main.cpp 프로젝트: mimaun/Rose
/*
 Initialize the graphics state
 */
void graphicsInit()
{
    //Use ShaderManager to prepare shader
    //char const * vertSource = "attribute vec2 pos; attribute vec3 color; varying vec4 smoothColor; void main() { gl_Position=vec4(pos.xy, 0, 1); smoothColor=vec4(color.xyz, 1); }";
    //char const * fragSource = "varying vec4 smoothColor; void main() { gl_FragColor = smoothColor; }";
    //shaderProg = ShaderManager::shaderFromString(&vertSource, &fragSource, 1, 1);
    glEnable(GL_PROGRAM_POINT_SIZE);
    glPointSize(10);
    
    char const * vertPath = "shaders/simple.vert";
    char const * fragPath = "shaders/simple.frag";
    shaderProg = ShaderManager::shaderFromFile(&vertPath, &fragPath, 1, 1);
    
    // The data we will render needs to be on the GPU
    // These commands upload the data
    
    // Find out where the shader expects the data
    positionSlot = glGetAttribLocation(shaderProg, "pos");
    colorSlot = glGetAttribLocation(shaderProg, "color");
    sizeSlot = glGetAttribLocation(shaderProg, "size");
    if(positionSlot < 0 || colorSlot < 0 || sizeSlot < 0)  {
        fprintf(stderr, "Could not get input location\n");
    }
    
    glGenBuffers(1, &positionBuffer); //make the position buffer
    glGenBuffers(1, &colorBuffer);
    glGenBuffers(1, &sizeBuffer);
    if(positionBuffer == 0) fprintf(stderr, "GenBuffer failed\n");
    if(colorBuffer == 0) fprintf(stderr, "GenBuffer failed\n");
    if(sizeBuffer == 0) fprintf(stderr, "GenBuffer failed\n");
    
    
    glGenVertexArrays(1, &vertexArray);
    glBindBuffer(GL_ARRAY_BUFFER, positionBuffer); //activate the position buffer
    glBufferData(GL_ARRAY_BUFFER, sizeof(positions), positions, GL_STATIC_DRAW); //alloc and upload
    glBindBuffer(GL_ARRAY_BUFFER, 0); //deactivate the position buffer
    checkGLError("pos buffer");
    
    // Do the same thing for the color data
    glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    checkGLError("color buffer");
    
    glBindBuffer(GL_ARRAY_BUFFER, sizeBuffer); //activate the size buffer
    glBufferData(GL_ARRAY_BUFFER, sizeof(sizes), sizes, GL_STATIC_DRAW); //alloc and upload
    glBindBuffer(GL_ARRAY_BUFFER, 0); //deactivate the size buffer
    checkGLError("size buffer");
}