opengl es 对bmp 文件贴图程序。

1.loadbmp.cpp

/*
 * This code was created by Jeff Molofee '99
 * (ported to Linux by Ti Leggett '01)
 * (ported to i.mx51, i.mx31 and x11 by Freescale '10)
 * If you've found this code useful, please let him know.
 *
 * Visit Jeff at http://nehe.gamedev.net/
 *
 */
 
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <EGL/egl.h>
#include "sageShader.h"
#include "loadBmp.h"
#include "sage.h"

GLuint       programHandle = 0 ;
GLuint       g_hModelViewMatrixLoc_RGB = 0;
GLuint       g_hProjMatrixLoc_RGB      = 0;
GLuint       g_hVertexLoc_RGB          = 0;
GLuint       g_hVertexTexLoc_RGB       = 2;
GLuint       g_hColorLoc_RGB           = 1;


//--------------------------------------------------------------------------------------
// Name: g_strVertexShader / g_strFragmentShader
// Desc: The vertex and fragment shader programs
//--------------------------------------------------------------------------------------
const char* g_strVertexShader =
"attribute vec4 g_vPosition;    \n"
"attribute vec3 g_vColor;     \n"
"attribute vec2 g_vTexCoord;    \n"
"        \n"
"varying   vec3 g_vVSColor;     \n"
"varying   vec2 g_vVSTexCoord;    \n"
"        \n"
"void main()      \n"
"{        \n"
"    gl_Position  = g_vPosition;  \n"
"    g_vVSColor = g_vColor;     \n"
"    g_vVSTexCoord = g_vTexCoord;    \n"
"}        \n";


const char* g_strFragmentShader =
"#ifdef GL_FRAGMENT_PRECISION_HIGH    \n"
"   precision highp float;     \n"
"#else       \n"
"   precision mediump float;    \n"
"#endif       \n"
"        \n"
"uniform sampler2D s_texture;    \n"
"varying   vec3      g_vVSColor;    \n"
"varying   vec2 g_vVSTexCoord;    \n"
"        \n"
"void main()      \n"
"{        \n"
"    gl_FragColor = texture2D(s_texture,g_vVSTexCoord); \n"
"}        \n";

GLuint texHandle = 0; /* Storage For One Texture ( NEW ) */

TAGImage texture={0};

void loadBmpFile(char *filename){
  BITMAPFILEHEADER bmpFileHeader;//bmp file header.
  BITMAPINFOHEADER bmpInfoHeader;//bmp info header.
  GLuint imageSize;
  GLuint temp;
  GLuint type = GL_RGB;


  sage::printLog("-----loadBmp.cpp,justclearbmp------\n");
  FILE  *file = fopen(filename,"rb");
  if(file == NULL){
      return ;
  }

 
  sage::printLog("-----loadBmp.cpp,openfile:%s,success.------\n",filename);
  int n =-1;
  n= fread(&bmpFileHeader,1,sizeof(BITMAPFILEHEADER),file);//read file head.
  if(bmpFileHeader.bfType != 0x4d42)
    return ;
 
  sage::printLog("-----loadBmp.cpp,readhead,success.------\n");
  n=fread(&bmpInfoHeader,1,sizeof(BITMAPINFOHEADER),file);//read file info.
  sage::printLog("-----loadBmp.cpp,readfileinfo,success.------\n");

  sage::printLog("-----loadBMp.cpp,sizeof head:%d\n",sizeof(BITMAPFILEHEADER));
  sage::printLog("-----loadBMp.cpp,sizeof info:%d\n",sizeof(BITMAPINFOHEADER));
  texture.width  = bmpInfoHeader.biWidth;// image width.
  texture.height = bmpInfoHeader.biHeight;//image height.
  texture.bpp    = bmpInfoHeader.biBitCount;//bit depth.
  imageSize       = bmpInfoHeader.biSizeImage;//image  size.

  sage::printLog("iwidth is:%d\n",texture.width);
  sage::printLog("iHeight is:%d\n",texture.height);
  sage::printLog("Count is:%d\n",texture.bpp);
  sage::printLog("SizeImage is:%d\n",imageSize);

  if(texture.width <=0 ||
     texture.height<=0 ||
     texture.bpp != 24)
  {
     fclose(file);
     return ;
  }

   sage::printLog("-----loadBmp.cpp done.------\n");

  //get true size.
  fseek(file,0,SEEK_END);
  int total_size = ftell(file);
  // jump to the real image data pos.
  fseek(file,bmpFileHeader.bfOffBits,SEEK_SET);
  int curr_size = ftell(file);
  imageSize = total_size - curr_size;

  sage::printLog("curr_size is:%d,total_size is:%d,imagesize:%d\n",
                  curr_size,total_size,imageSize);

  texture.imageData = (GLubyte *)malloc(imageSize);
  //check the memory exists or match filememory size.
  if(texture.imageData == NULL ||
     fread(texture.imageData,1,imageSize,file) != imageSize)
  {
     if(texture.imageData != NULL)
        free(texture.imageData);
     fclose(file);
     return ;
  }

  sage::printLog("-----loadBmp.cpp,filememory malloc success.------\n");
  //loop image data,swaps R B.
  for(GLuint i = 0 ; i < imageSize; i += 3){
    temp = texture.imageData[i];
    texture.imageData[i]   = texture.imageData[i+2];
    texture.imageData[i+2] = temp;
  }

  //finish read bmp file.
  fclose(file);

  sage::printLog("-----loadBmp.cpp,finish all the file read,begin draw image.------\n");
}


void cleanup()
{
  if(texHandle){
    glDeleteTextures(1,&texHandle);
    if(texture.imageData != 0){
      free(texture.imageData);
      texture.imageData = NULL;
    }
 }
}

 

void init(void)
{
    // Load the shader
    programHandle = GLSLinstallShaders(g_strVertexShader, g_strFragmentShader);
    // Finally, use the program
    glUseProgram(programHandle);
    // Switch back to no shader
    glUseProgram(0);
    //glUseProgram(0);
    GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors

    // Create GL texture object
    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &texHandle);
    glBindTexture(GL_TEXTURE_2D, texHandle);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,texture.width,texture.height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture.imageData);

    
   GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors
}

void render(void)
{
       //add by liucong.----------------
       GLfloat vtx[] = {
          -1.0f,1.0f,0.0f,
           1.0f, 1.0f,0.0f,
          -1.0f,-1.0f,0.0f,
          1.0f,-1.0f,0.0f
       };
       GLfloat tex[] = {
          0.0f,0.0f,
          1.0f,0.0f,
          0.0f,1.0f,
          1.0f,1.0f
      };
      GLfloat color[] = {
         1.0f,0.0f,0.0f,
         0.0f,1.0f,0.0f,
         0.0f,0.0f,1.0f,
         1.0f,1.0f,0.0f
      };
       

        glUseProgram(programHandle);
        glEnable(GL_TEXTURE_2D);
 // Set the shader program
        glBindAttribLocation(programHandle, g_hVertexLoc_RGB, "g_vPosition");
        glBindAttribLocation(programHandle, g_hColorLoc_RGB, "g_vColor");
        glBindAttribLocation(programHandle, g_hVertexTexLoc_RGB, "g_vTexCoord");


        glVertexAttribPointer( g_hVertexLoc_RGB, 3, GL_FLOAT, 0, 0, vtx );
 glEnableVertexAttribArray( g_hVertexLoc_RGB );

 glVertexAttribPointer( g_hVertexTexLoc_RGB, 2, GL_FLOAT, 0, 0, tex );
 glEnableVertexAttribArray( g_hVertexTexLoc_RGB );

 glVertexAttribPointer( g_hColorLoc_RGB, 3, GL_FLOAT, 0, 0, color );
 glEnableVertexAttribArray( g_hColorLoc_RGB );


        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texHandle);
        int h=glGetUniformLocation(programHandle, "s_texture");
        glUniform1i(h,0);  /* Bind yuvtex to texture unit 0 */
 /* Drawing Using Triangle strips, draw triangle strips using 4 vertices */
 glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        glDisableVertexAttribArray(g_hVertexLoc_RGB);
        glDisableVertexAttribArray(g_hColorLoc_RGB);
        glDisableVertexAttribArray(g_hVertexTexLoc_RGB);
        glUseProgram(0);
}


void justclearbmp (int pic_new)
{
    if (pic_new == 1){
     if(texture.imageData == NULL)
       loadBmpFile("background.bmp");
     cleanup();
     init();
  }
  render();
}

 

2.loadbmp.h

#ifndef LOAD_BMP_INCLUDE
#define LOAD_BMP_INCLUDE
typedef struct tagImage{
  GLubyte *imageData;
  GLuint  bpp;
  GLuint  width;
  GLuint  height;
  GLuint  textID;
}TAGImage;


// bmp file headerdefine.
typedef struct tagBITMAPFILEHEADER{
  unsigned short bfType;
  unsigned int   bfSize;
  unsigned short bfReserved1;
  unsigned short bfReserved2;
  unsigned int   bfOffBits;
}__attribute__((packed)) BITMAPFILEHEADER;

// bmp info header define.
typedef struct tagBITMAPINFOHEADER{
  unsigned int biSize;
  int biWidth;
  int biHeight;
  unsigned short biPlanes;
  unsigned short biBitCount;
  unsigned int   biCompression;
  unsigned int   biSizeImage;
  int  biXPelsPerMeter;
  int  biYpelsPerMeter;
  unsigned int biClrUsed;
  unsigned int biClrImportant;
}__attribute__((packed)) BITMAPINFOHEADER;


void init(void);
void render(void);
void cleanup(void);
void justclearbmp(int pic_new);

#endif

3.eglContex.cpp

/******************************************************************************
 * SAGE - Scalable Adaptive Graphics Environment
 *
 * Module: sdlSingleContext.cpp
 * Author : Byungil Jeong
 *
 * Copyright (C) 2004 Electronic Visualization Laboratory,
 * University of Illinois at Chicago
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following disclaimer
 *    in the documentation and/or other materials provided with the distribution.
 *  * Neither the name of the University of Illinois at Chicago nor
 *    the names of its contributors may be used to endorse or promote
 *    products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Direct questions, comments etc about SAGE to bijeong@evl.uic.edu or
 * http://www.evl.uic.edu/cavern/forum/
 *
 *****************************************************************************/

#if defined(GLSL_YUV) || defined(SAGE_S3D)
#if !defined(WIN32)
#define GLEW_STATIC 1
#endif
//#include <GL/glew.h>
#if defined(__APPLE__)
#include <OpenGL/glu.h>
#else
//#include <GL/glu.h>
#endif
#include <fcntl.h>
#endif

#include "eglContext.h"
#include "sageShader.h"
#include "loadBmp.h"


static EGLint const attribute_list[] = {
 EGL_RED_SIZE, 1,
 EGL_GREEN_SIZE, 1,
 EGL_BLUE_SIZE, 1,
 EGL_ALPHA_SIZE, 0,
 EGL_NONE
};


int eglContext::init(struct sageDisplayConfig &cfg)
{
   m_bbackmode = RGB_MODE;
   pic_new = 1 ;
   singleContext = true;
   configStruct = cfg;

#if defined(WIN32)
   // Weird position with windows
   _putenv("SDL_VIDEO_CENTERED=1");
#endif

   if ( configStruct.fullScreenFlag ) {
      char posStr[SAGE_NAME_LEN];
      sprintf(posStr, "SDL_VIDEO_WINDOW_POS=%d,%d",configStruct.winX, configStruct.winY);
      putenv(posStr);
   }  
 
   tileNum = cfg.dimX * cfg.dimY;
   if (tileNum > MAX_TILES_PER_NODE) {
      sage::printLog("sdlSingleContext::init() : The tile number exceeds the maximum");
      return -1;
   }

   if (!winCreatFlag) {
      window_width  = cfg.width*cfg.dimX;
      window_height = cfg.height*cfg.dimY;

      EGLint numconfigs;

      //get egl display
      native_display_type = fsl_getNativeDisplay();
      display = eglGetDisplay(native_display_type);
 
      //Initialize egl
      eglInitialize(display, NULL, NULL);
      assert(eglGetError() == EGL_SUCCESS);
 
      //tell the driver we are using OpenGL ES
      eglBindAPI(EGL_OPENGL_ES_API);

      //pass our egl configuration to egl
      eglChooseConfig(display, attribute_list, &config, 1, &num_config);
      printf("chooseconfig, \n");
      assert(eglGetError() == EGL_SUCCESS);
      assert(num_config == 1);

      //glShadeModel(GL_SMOOTH);
 
      native_window = fsl_createwindow(display, native_display_type, window_width, window_height, configStruct.fullScreenFlag); 
      assert(native_window); 

      surface = eglCreateWindowSurface(display, config, (EGLNativeWindowType)native_window, NULL);

      printf("createwindow, \n");
      assert(eglGetError() == EGL_SUCCESS);

      // for opengles2.x
      EGLint ContextAttribList[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE };

      //create the egl graphics context
      context = eglCreateContext(display, config, NULL, ContextAttribList);
//    context = eglCreateContext(display, config, NULL, NULL);

      printf("creatcontext, \n");
      assert(eglGetError() == EGL_SUCCESS);

      //make the context current
      eglMakeCurrent(display, surface, surface, context);
      printf("makecurrent, \n");
      assert(eglGetError() == EGL_SUCCESS);

      glEnable(GL_TEXTURE_2D);
      glEnable(GL_DEPTH_TEST);
      glDepthFunc(GL_LEQUAL);
      glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
      glClearDepthf(1.0f);
  
      winCreatFlag = true;
      sage::printLog("eglContext:init(): Window created");
   }

   GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors

  // dark gray background
  //changeBackground(20,20,20);

   return 0;
} // End of sdlSingleContext::init()

int  eglContext::changeBackBMP(){
  sage::printLog("----eglContext.cpp,changeBackBMP---\n");
  m_bbackmode = BMP_MODE;
  pic_new = 1 ;
  return 0 ;
}

void eglContext::clearScreen()
{
  
   //GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors

   sage::printLog("------in file eglContext,clearScreen!----\n");
   sage::printLog("------m_bbackmode is:%d----\n",m_bbackmode);
   sage::printLog("------pic_new is:%d----\n",pic_new);
   if(m_bbackmode == RGB_MODE){
     sage::printLog("----eglContext.cpp,clearScreen,RGB_MODE---\n");
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   }else{
     sage::printLog("----eglContext.cpp,clearScreen,BMP_MODE---\n");
     justclearbmp(pic_new);
     pic_new = 0 ;
   }
}

void eglContext::setupViewport(int i, sageRect &tileRect)
{
   GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors
   glViewport(tileRect.x, tileRect.y, tileRect.width, tileRect.height);
}

void eglContext::refreshScreen()
{
  GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors
  eglSwapBuffers(display, surface);
}

void eglContext::changeBackground(int red, int green, int blue)
{
  //GLprintError(__FILE__, __LINE__);  // Check for OpenGL errors
  // modify by liucong,2014.7.30,from r to b,and b to r
  //glClearColor((float)red/255.0f, (float)green/255.0f, (float)blue/255.0f, 0.0f);
  glClearColor((float)blue/255.0f, (float)green/255.0f, (float)red/255.0f, 0.0f);
  m_bbackmode = RGB_MODE;
}

eglContext::~eglContext()
{
    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    eglDestroyContext(display, context);
    eglDestroySurface(display, surface); 
    fsl_destroywindow(native_window, native_display_type);
    eglTerminate(display);
    eglReleaseThread(); 
 
} //End of sageDisplay::~sageDisplay()


void eglContext::checkEvent()
{
   //refreshScreen();
}

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值