KisOpenGLHDRExposureProgram::KisOpenGLHDRExposureProgram() { m_exposure = 0; createProgram(); }
float sgemmMain(int rowa,int cola,int colb) { cl_context context = 0; cl_command_queue commandQueue = 0; cl_program program = 0; cl_device_id device = 0; cl_kernel kernel = 0; const unsigned int numberOfMemoryObjects = 3; cl_mem memoryObjectsa = 0; cl_mem memoryObjectsb = 0; cl_mem memoryObjectsc = 0; cl_int errorNumber; cl_uint clrowa = rowa; cl_uint clcola = cola; cl_uint clcolb = colb; int err; err = createContext(&context); LOGD("create context"); err = createCommandQueue(context, &commandQueue, &device); err = createProgram(context, device, "/mnt/sdcard/kernel/sgemm.cl", &program); kernel = clCreateKernel(program, "sgemm", &errorNumber); LOGD("createKernel code %d",errorNumber); LOGD("start computing"); float alpha = 1; float beta = 0.1; /* Create the matrices. */ size_t matrixSizea = rowa * cola; size_t matrixSizeb = cola * colb; size_t matrixSizec = rowa * colb; /* As all the matrices have the same size, the buffer size is common. */ size_t bufferSizea = matrixSizea * sizeof(float); size_t bufferSizeb = matrixSizeb * sizeof(float); size_t bufferSizec = matrixSizec * sizeof(float); /* Create buffers for the matrices used in the kernel. */ int createMemoryObjectsSuccess = 0; memoryObjectsa = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, bufferSizea, NULL, &errorNumber); createMemoryObjectsSuccess &= errorNumber; memoryObjectsb = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_ALLOC_HOST_PTR, bufferSizeb, NULL, &errorNumber); createMemoryObjectsSuccess &= errorNumber; memoryObjectsc = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, bufferSizec, NULL, &errorNumber); createMemoryObjectsSuccess &= errorNumber; LOGD("create memory err %d",createMemoryObjectsSuccess); int mapMemoryObjectsSuccess = 0; cl_float* matrixA = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjectsa, CL_TRUE, CL_MAP_WRITE, 0, bufferSizea, 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= errorNumber; cl_float* matrixB = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjectsb, CL_TRUE, CL_MAP_WRITE, 0, bufferSizeb, 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= errorNumber; cl_float* matrixC = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjectsc, CL_TRUE, CL_MAP_WRITE, 0, bufferSizec, 0, NULL, NULL, &errorNumber); mapMemoryObjectsSuccess &= errorNumber; LOGD("map memory err %d",mapMemoryObjectsSuccess); sgemmInitialize(rowa,cola,colb, matrixA, matrixB, matrixC); LOGD("data initial finish"); int unmapMemoryObjectsSuccess = 0; errorNumber = clEnqueueUnmapMemObject(commandQueue, memoryObjectsa, matrixA, 0, NULL, NULL); LOGD("memory code %d",errorNumber); unmapMemoryObjectsSuccess &= errorNumber; errorNumber = clEnqueueUnmapMemObject(commandQueue, memoryObjectsb, matrixB, 0, NULL, NULL); LOGD("memory code %d",errorNumber); unmapMemoryObjectsSuccess &= errorNumber; errorNumber = clEnqueueUnmapMemObject(commandQueue, memoryObjectsc, matrixC, 0, NULL, NULL); LOGD("memory code %d",errorNumber); unmapMemoryObjectsSuccess &= errorNumber; LOGD("unmap memory err %d",unmapMemoryObjectsSuccess); int setKernelArgumentsSuccess = 0; errorNumber = clSetKernelArg(kernel, 0, sizeof(cl_mem), &memoryObjectsa); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 1, sizeof(cl_mem), &memoryObjectsb); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 2, sizeof(cl_mem), &memoryObjectsc); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 3, sizeof(cl_uint), &clrowa); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 4, sizeof(cl_uint), &clcola); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 5, sizeof(cl_uint), &clcolb); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 6, sizeof(cl_float), &alpha); setKernelArgumentsSuccess &= errorNumber; errorNumber = clSetKernelArg(kernel, 7, sizeof(cl_float), &beta); setKernelArgumentsSuccess &= errorNumber; LOGD("setKernel err %d",setKernelArgumentsSuccess); LOGD("start running kernel"); clock_t start_t,end_t; float cost_time; start_t = clock(); cl_event event = 0; size_t globalWorksize[2] = {rowa, colb}; errorNumber = clEnqueueNDRangeKernel(commandQueue, kernel, 2, NULL, globalWorksize, NULL, 0, NULL, &event); //LOGD("Enqueue err code %d",errorNumber); errorNumber = clFinish(commandQueue); end_t = clock(); cost_time = (float)(end_t-start_t)/CLOCKS_PER_SEC*1000; LOGD("Finish err code %d",errorNumber); float time; time = printProfilingInfo(event); LOGT("using CPU clock: %f ms",cost_time); LOGT("using GPU clock: %f ms",time); clReleaseEvent(event); matrixC = (cl_float*)clEnqueueMapBuffer(commandQueue, memoryObjectsc, CL_TRUE, CL_MAP_READ, 0, bufferSizec, 0, NULL, NULL, &errorNumber); clEnqueueUnmapMemObject(commandQueue, memoryObjectsc, matrixC, 0, NULL, NULL); LOGD("read out matrixC finish"); LOGD("matrixC value C(0,0): %f",matrixC[0]); cleanUpOpenCL(context, commandQueue, program, kernel, memoryObjectsa, memoryObjectsb,memoryObjectsc,numberOfMemoryObjects); LOGD("RUNNING finsh"); return time; }
void COpenGLSLMaterialRenderer::init(s32& outMaterialTypeNr, const c8* vertexShaderProgram, const c8* pixelShaderProgram, const c8* geometryShaderProgram, scene::E_PRIMITIVE_TYPE inType, scene::E_PRIMITIVE_TYPE outType, u32 verticesOut) { outMaterialTypeNr = -1; if (!createProgram()) return; #if defined(GL_ARB_vertex_shader) && defined (GL_ARB_fragment_shader) if (vertexShaderProgram) if (!createShader(GL_VERTEX_SHADER_ARB, vertexShaderProgram)) return; if (pixelShaderProgram) if (!createShader(GL_FRAGMENT_SHADER_ARB, pixelShaderProgram)) return; #endif #if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_program4) || defined(GL_NV_geometry_shader4) if (geometryShaderProgram && Driver->queryFeature(EVDF_GEOMETRY_SHADER)) { if (!createShader(GL_GEOMETRY_SHADER_EXT, geometryShaderProgram)) return; #if defined(GL_ARB_geometry_shader4) || defined(GL_EXT_geometry_shader4) || defined(GL_NV_geometry_shader4) if (Program2) { Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_INPUT_TYPE_EXT, Driver->primitiveTypeToGL(inType)); Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_OUTPUT_TYPE_EXT, Driver->primitiveTypeToGL(outType)); if (verticesOut==0) Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_VERTICES_OUT_EXT, Driver->MaxGeometryVerticesOut); else Driver->extGlProgramParameteri(Program2, GL_GEOMETRY_VERTICES_OUT_EXT, core::min_(verticesOut, Driver->MaxGeometryVerticesOut)); } else { Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_INPUT_TYPE_EXT, Driver->primitiveTypeToGL(inType)); Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_OUTPUT_TYPE_EXT, Driver->primitiveTypeToGL(outType)); if (verticesOut==0) Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_VERTICES_OUT_EXT, Driver->MaxGeometryVerticesOut); else Driver->extGlProgramParameteri((GLuint)Program, GL_GEOMETRY_VERTICES_OUT_EXT, core::min_(verticesOut, Driver->MaxGeometryVerticesOut)); } #elif defined(GL_NV_geometry_program4) if (verticesOut==0) Driver->extGlProgramVertexLimit(GL_GEOMETRY_PROGRAM_NV, Driver->MaxGeometryVerticesOut); else Driver->extGlProgramVertexLimit(GL_GEOMETRY_PROGRAM_NV, core::min_(verticesOut, Driver->MaxGeometryVerticesOut)); #endif } #endif if (!linkProgram()) return; // register myself as new material outMaterialTypeNr = Driver->addMaterialRenderer(this); }
void Program::setFragmentSource(const std::string &source) { fSource = source; createProgram(); }
bool Simulation::setup(const GLuint windowWidth, const GLuint windowHeight, const GLuint viewportWidth, const GLuint viewportHeight, AssetLoader& assetLoader) { setup_rand(); this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->viewportWidth = viewportWidth; this->viewportHeight = viewportHeight; const char VertexShaderCode[] = "attribute vec4 a_position; \n" "attribute lowp vec4 a_color; \n" "varying lowp vec4 v_color; \n" " \n" "void main() { \n" " gl_Position = a_position; \n" " v_color = a_color; \n" "} \n"; const char FragmentShaderCode[] = "precision mediump float; \n" "varying lowp vec4 v_color; \n" "void main() { \n" " gl_FragColor = v_color; \n" "} \n"; program = createProgram(VertexShaderCode, FragmentShaderCode); if(!program) { LOGE("Could not create program."); return false; } // Load shader attribute locations positionAttribute = glGetAttribLocation(program, "a_position"); checkGlError("glGetAttribLocation"); LOGI("glGetAttribLocation(\"a_position\") = %d\n", positionAttribute); colorAttribute = glGetAttribLocation(program, "a_color"); checkGlError("glGetAttribLocation"); LOGI("glGetAttribLocation(\"a_color\") = %d\n", colorAttribute); // Load triangle currentBuffer glGenBuffers(1, &vboId); checkGlError("glGenBuffers"); glBindBuffer(GL_ARRAY_BUFFER, vboId); checkGlError("glBindBuffer"); // Set the currentBuffer's data glBufferData(GL_ARRAY_BUFFER, Constants::MaximumVertexCount * sizeof(ColorVertex), ¤tVertices[0], GL_DYNAMIC_DRAW); checkGlError("glBufferData"); // Create image buffers const int BufferSize = viewportWidth*viewportHeight*4; /* RGBA format*/ currentBuffer = new unsigned char[BufferSize]; std::fill_n(currentBuffer, BufferSize, 0); targetBuffer = new unsigned char[BufferSize]; std::fill_n(targetBuffer, BufferSize, 0); if(!create_render_target()) { LOGE("Could not create render target!"); return false; } LOGW("Integer Sizes: %d %d", sizeof(unsigned long), sizeof(unsigned long)); LOGI("Success engine_init_display"); if(!load_content(assetLoader)) { LOGE("Could not load content!"); return false; } create_random_triangles(); copy_current_to_best_triangles(); LOGI("Simulation is ready to go."); return true; }
/// // Initialize the shader and program object // int Init ( void* assetManager, char* fileName, int width, int height ) { context = malloc(sizeof(Context)); context->width = width; context->height = height; context->data = malloc ( sizeof ( UserData ) ); if (assetManager == NULL) { context->platformData = NULL; } else{ context->platformData = assetManager; } UserData *userData = context->data; int i; char vShaderStr[] = "#version 300 es \n" "uniform float u_time; \n" "uniform vec3 u_centerPosition; \n" "layout(location = 0) in float a_lifetime; \n" "layout(location = 1) in vec3 a_startPosition; \n" "layout(location = 2) in vec3 a_endPosition; \n" "out float v_lifetime; \n" "void main() \n" "{ \n" " if ( u_time <= a_lifetime ) \n" " { \n" " gl_Position.xyz = a_startPosition + \n" " (u_time * a_endPosition); \n" " gl_Position.xyz += u_centerPosition; \n" " gl_Position.w = 1.0; \n" " } \n" " else \n" " { \n" " gl_Position = vec4( -1000, -1000, 0, 0 ); \n" " } \n" " v_lifetime = 1.0 - ( u_time / a_lifetime ); \n" " v_lifetime = clamp ( v_lifetime, 0.0, 1.0 ); \n" " gl_PointSize = ( v_lifetime * v_lifetime ) * 40.0; \n" "}"; char fShaderStr[] = "#version 300 es \n" "precision mediump float; \n" "uniform vec4 u_color; \n" "in float v_lifetime; \n" "layout(location = 0) out vec4 fragColor; \n" "uniform sampler2D s_texture; \n" "void main() \n" "{ \n" " vec4 texColor; \n" " texColor = texture( s_texture, gl_PointCoord ); \n" " fragColor = vec4( u_color ) * texColor; \n" " fragColor.a *= v_lifetime; \n" "} \n"; // Load the shaders and get a linked program object userData->programObject = createProgram ( vShaderStr, fShaderStr ); // Get the uniform locations userData->timeLoc = glGetUniformLocation ( userData->programObject, "u_time" ); userData->centerPositionLoc = glGetUniformLocation ( userData->programObject, "u_centerPosition" ); userData->colorLoc = glGetUniformLocation ( userData->programObject, "u_color" ); userData->samplerLoc = glGetUniformLocation ( userData->programObject, "s_texture" ); glClearColor ( 0.0f, 0.0f, 0.0f, 0.0f ); // Fill in particle data array srand ( 0 ); for ( i = 0; i < NUM_PARTICLES; i++ ) { float *particleData = &userData->particleData[i * PARTICLE_SIZE]; // Lifetime of particle ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 10000.0f ); // End position of particle ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 5000.0f ) - 1.0f; ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 5000.0f ) - 1.0f; ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 5000.0f ) - 1.0f; // Start position of particle ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 40000.0f ) - 0.125f; ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 40000.0f ) - 0.125f; ( *particleData++ ) = ( ( float ) ( rand() % 10000 ) / 40000.0f ) - 0.125f; } // Initialize time to cause reset on first update userData->time = 1.0f; userData->textureId = LoadTexture ( context->platformData, fileName ); if ( userData->textureId <= 0 ) { LOGE ( "init fail" ); return GL_FALSE; } LOGE ( "init success" ); return GL_TRUE; }
void ShaderProgram::initGLResources() { // To detect whether or not resources for ShaderProgram allocated // successfully, we clean up pre-existing errors here and will check for // new errors at the end of this function. GLUtils::checkGlError("before initGLResources"); GLint tex2DProgram = createProgram(gVertexShader, gFragmentShader); GLint pureColorProgram = createProgram(gPureColorVertexShader, gPureColorFragmentShader); GLint tex2DInvProgram = createProgram(gVertexShader, gFragmentShaderInverted); GLint videoProgram = createProgram(gVideoVertexShader, gVideoFragmentShader); GLint texOESProgram = createProgram(gVertexShader, gSurfaceTextureOESFragmentShader); GLint texOESInvProgram = createProgram(gVertexShader, gSurfaceTextureOESFragmentShaderInverted); GLint repeatTexProgram = createProgram(gVertexShader, gRepeatTexFragmentShader); GLint repeatTexInvProgram = createProgram(gVertexShader, gRepeatTexFragmentShaderInverted); if (tex2DProgram == -1 || pureColorProgram == -1 || tex2DInvProgram == -1 || videoProgram == -1 || texOESProgram == -1 || texOESInvProgram == -1 || repeatTexProgram == -1 || repeatTexInvProgram == -1) { m_needsInit = true; return; } GLint pureColorPosition = glGetAttribLocation(pureColorProgram, "vPosition"); GLint pureColorProjMtx = glGetUniformLocation(pureColorProgram, "projectionMatrix"); GLint pureColorValue = glGetUniformLocation(pureColorProgram, "inputColor"); m_handleArray[PureColor].init(-1, -1, pureColorPosition, pureColorProgram, pureColorProjMtx, pureColorValue, -1, -1, -1, -1); GLint tex2DAlpha = glGetUniformLocation(tex2DProgram, "alpha"); GLint tex2DPosition = glGetAttribLocation(tex2DProgram, "vPosition"); GLint tex2DProjMtx = glGetUniformLocation(tex2DProgram, "projectionMatrix"); GLint tex2DTexSampler = glGetUniformLocation(tex2DProgram, "s_texture"); GLint tex2DFillPortion = glGetUniformLocation(tex2DProgram, "fillPortion"); m_handleArray[Tex2D].init(tex2DAlpha, -1, tex2DPosition, tex2DProgram, tex2DProjMtx, -1, tex2DTexSampler, -1, tex2DFillPortion, -1); GLint tex2DInvAlpha = glGetUniformLocation(tex2DInvProgram, "alpha"); GLint tex2DInvContrast = glGetUniformLocation(tex2DInvProgram, "contrast"); GLint tex2DInvPosition = glGetAttribLocation(tex2DInvProgram, "vPosition"); GLint tex2DInvProjMtx = glGetUniformLocation(tex2DInvProgram, "projectionMatrix"); GLint tex2DInvTexSampler = glGetUniformLocation(tex2DInvProgram, "s_texture"); GLint tex2DInvFillPortion = glGetUniformLocation(tex2DInvProgram, "fillPortion"); m_handleArray[Tex2DInv].init(tex2DInvAlpha, tex2DInvContrast, tex2DInvPosition, tex2DInvProgram, tex2DInvProjMtx, -1, tex2DInvTexSampler, -1, tex2DInvFillPortion, -1); GLint repeatTexAlpha = glGetUniformLocation(repeatTexProgram, "alpha"); GLint repeatTexPosition = glGetAttribLocation(repeatTexProgram, "vPosition"); GLint repeatTexProjMtx = glGetUniformLocation(repeatTexProgram, "projectionMatrix"); GLint repeatTexTexSampler = glGetUniformLocation(repeatTexProgram, "s_texture"); GLint repeatTexFillPortion = glGetUniformLocation(repeatTexProgram, "fillPortion"); GLint repeatTexScale = glGetUniformLocation(repeatTexProgram, "repeatScale"); m_handleArray[RepeatTex].init(repeatTexAlpha, -1, repeatTexPosition, repeatTexProgram,repeatTexProjMtx, -1, repeatTexTexSampler, -1, repeatTexFillPortion, repeatTexScale); GLint repeatTexInvAlpha = glGetUniformLocation(repeatTexInvProgram, "alpha"); GLint repeatTexInvContrast = glGetUniformLocation(tex2DInvProgram, "contrast"); GLint repeatTexInvPosition = glGetAttribLocation(repeatTexInvProgram, "vPosition"); GLint repeatTexInvProjMtx = glGetUniformLocation(repeatTexInvProgram, "projectionMatrix"); GLint repeatTexInvTexSampler = glGetUniformLocation(repeatTexInvProgram, "s_texture"); GLint repeatTexInvFillPortion = glGetUniformLocation(repeatTexInvProgram, "fillPortion"); GLint repeatTexInvScale = glGetUniformLocation(repeatTexInvProgram, "repeatScale"); m_handleArray[RepeatTexInv].init(repeatTexInvAlpha, repeatTexInvContrast, repeatTexInvPosition, repeatTexInvProgram, repeatTexInvProjMtx, -1, repeatTexInvTexSampler, -1, repeatTexInvFillPortion, repeatTexInvScale); GLint texOESAlpha = glGetUniformLocation(texOESProgram, "alpha"); GLint texOESPosition = glGetAttribLocation(texOESProgram, "vPosition"); GLint texOESProjMtx = glGetUniformLocation(texOESProgram, "projectionMatrix"); GLint texOESTexSampler = glGetUniformLocation(texOESProgram, "s_texture"); GLint texOESFillPortion = glGetUniformLocation(texOESProgram, "fillPortion"); m_handleArray[TexOES].init(texOESAlpha, -1, texOESPosition, texOESProgram, texOESProjMtx, -1, texOESTexSampler, -1, texOESFillPortion, -1); GLint texOESInvAlpha = glGetUniformLocation(texOESInvProgram, "alpha"); GLint texOESInvContrast = glGetUniformLocation(texOESInvProgram, "contrast"); GLint texOESInvPosition = glGetAttribLocation(texOESInvProgram, "vPosition"); GLint texOESInvProjMtx = glGetUniformLocation(texOESInvProgram, "projectionMatrix"); GLint texOESInvTexSampler = glGetUniformLocation(texOESInvProgram, "s_texture"); GLint texOESInvFillPortion = glGetUniformLocation(texOESInvProgram, "fillPortion"); m_handleArray[TexOESInv].init(texOESInvAlpha, texOESInvContrast, texOESInvPosition, texOESInvProgram, texOESInvProjMtx, -1, texOESInvTexSampler, -1, texOESInvFillPortion, -1); GLint videoPosition = glGetAttribLocation(videoProgram, "vPosition"); GLint videoProjMtx = glGetUniformLocation(videoProgram, "projectionMatrix"); GLint videoTexSampler = glGetUniformLocation(videoProgram, "s_yuvTexture"); GLint videoTexMtx = glGetUniformLocation(videoProgram, "textureMatrix"); m_handleArray[Video].init(-1, -1, videoPosition, videoProgram, videoProjMtx, -1, videoTexSampler, videoTexMtx, -1, -1); const GLfloat coord[] = { 0.0f, 0.0f, // C 1.0f, 0.0f, // D 0.0f, 1.0f, // A 1.0f, 1.0f // B }; glGenBuffers(1, m_textureBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_textureBuffer[0]); glBufferData(GL_ARRAY_BUFFER, 2 * 4 * sizeof(GLfloat), coord, GL_STATIC_DRAW); TransformationMatrix matrix; // Map x,y from (0,1) to (-1, 1) matrix.scale3d(2, 2, 1); matrix.translate3d(-0.5, -0.5, 0); GLUtils::toGLMatrix(m_transferProjMtx, matrix); m_needsInit = GLUtils::checkGlError("initGLResources"); return; }
int main(int argc, char** argv) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName()); arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is a simple example which show draw order of pixel."); arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ..."); osgViewer::Viewer viewer(arguments); unsigned int helpType = 0; if ((helpType = arguments.readHelpType())) { arguments.getApplicationUsage()->write(std::cout, helpType); return 1; } // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } // set up the camera manipulators. viewer.setCameraManipulator( new osgGA::TrackballManipulator() ); // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); // add the thread model handler viewer.addEventHandler(new osgViewer::ThreadingHandler); // add the window size toggle handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); // add the stats handler viewer.addEventHandler(new osgViewer::StatsHandler); // add the help handler viewer.addEventHandler(new osgViewer::HelpHandler(arguments.getApplicationUsage())); // add the screen capture handler viewer.addEventHandler(new osgViewer::ScreenCaptureHandler); // load the data osg::ref_ptr<osg::Node> loadedModel = osgDB::readRefNodeFiles(arguments); if (!loadedModel) { osg::Geometry * quad = osg::createTexturedQuadGeometry(osg::Vec3f(-2.0f, 0.0f, -2.0f), osg::Vec3f(2.0f, 0.0f, 0.0f), osg::Vec3f(0.0f, 0.0f, 2.0f) ); osg::Geode * geode = new osg::Geode; geode->addDrawable(quad); loadedModel = geode; } // any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized(); // report any errors if they have occurred when parsing the program arguments. if (arguments.errors()) { arguments.writeErrorMessages(std::cout); return 1; } osg::StateSet * ss = loadedModel->asGeode()->getDrawable(0)->getOrCreateStateSet(); ss->setAttributeAndModes( createProgram(), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE | osg::StateAttribute::PROTECTED ); ss = loadedModel->getOrCreateStateSet(); osg::ref_ptr<osg::UIntArray> atomicCounterArrayRedAndGreen = new osg::UIntArray; atomicCounterArrayRedAndGreen->push_back(0); atomicCounterArrayRedAndGreen->push_back(0); osg::ref_ptr<osg::UIntArray> atomicCounterArrayBlue = new osg::UIntArray; atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); atomicCounterArrayBlue->push_back(0); osg::ref_ptr<osg::AtomicCounterBufferObject> acboRedAndGreen = new osg::AtomicCounterBufferObject; acboRedAndGreen->setUsage(GL_STREAM_COPY); atomicCounterArrayRedAndGreen->setBufferObject(acboRedAndGreen.get()); osg::ref_ptr<osg::AtomicCounterBufferObject> acboBlue = new osg::AtomicCounterBufferObject; acboBlue->setUsage(GL_STREAM_COPY); atomicCounterArrayBlue->setBufferObject(acboBlue.get()); osg::ref_ptr<osg::AtomicCounterBufferBinding> acbbRedAndGreen = new osg::AtomicCounterBufferBinding(0, atomicCounterArrayRedAndGreen.get(), 0, sizeof(GLuint)*3); ss->setAttributeAndModes(acbbRedAndGreen.get()); osg::ref_ptr<osg::AtomicCounterBufferBinding> acbbBlue = new osg::AtomicCounterBufferBinding(2, atomicCounterArrayBlue.get(), 0, sizeof(GLuint)); ss->setAttributeAndModes(acbbBlue.get()); osg::ref_ptr<osg::Uniform> invNumPixelUniform = new osg::Uniform("invNumPixel", 1.0f/(800.0f*600.0f)); ss->addUniform( invNumPixelUniform.get() ); acbbRedAndGreen->setUpdateCallback(new ResetAtomicCounter); #ifndef OSGREADBACK acbbBlue->setUpdateCallback(new ResetAtomicCounter); AdaptNumPixelUniform * drawCallback = new AdaptNumPixelUniform(acbbBlue); drawCallback->_invNumPixelUniform = invNumPixelUniform; //drawCallback->_acbb = acbbBlue; viewer.getCamera()->setFinalDrawCallback(drawCallback); #else ReadBackAndResetCallback *readbackandreset=new ReadBackAndResetCallback(atomicCounterArrayBlue); loadedModel->addUpdateCallback( readbackandreset); #endif // optimize the scene graph, remove redundant nodes and state etc. osgUtil::Optimizer optimizer; optimizer.optimize(loadedModel.get()); viewer.setSceneData( loadedModel.get() ); viewer.realize(); return viewer.run(); }
//------------------------------------------------------------------------------ void UI::Init(const std::string &font, unsigned int fontSize) { createAtlasData(font, fontSize); createProgram(); }
int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); GLFWwindow *window = glfwCreateWindow(800, 600, "flappy girl", NULL, NULL); glfwMakeContextCurrent(window); glfwSwapInterval(1); // set callback glfwSetKeyCallback(window, key_callback); gladLoadGL(); // init opengl glClearColor(0.3f, 0.4f, 0.5f, 1.0f); GLuint vao, vbo; glGenVertexArrays(1, &vao); glGenBuffers(1, &vbo); GLfloat vertices[] = { 0.0f, 0.5f, 0.0f, -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f }; glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(0); // init program GLint program = createProgram(vert::shader, frag::shader); glUseProgram(program); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); glfwPollEvents(); glfwSwapBuffers(window); } glfwDestroyWindow(window); glfwTerminate(); return 0; }
bool setupGraphics(int w, int h) { printGLString("Version", GL_VERSION); printGLString("Vendor", GL_VENDOR); printGLString("Renderer", GL_RENDERER); printGLString("Extensions", GL_EXTENSIONS); LOGI("setupGraphics(%d, %d)", w, h); gProgram = createProgram(gVertexShader, gFragmentShader); if (!gProgram) { LOGE("Could not create program."); return false; } gvPositionHandle = glGetAttribLocation(gProgram, "vPosition"); gShaderTexCoord = glGetAttribLocation ( gProgram, "a_texCoord" ); gvpMatrix = glGetUniformLocation( gProgram, "u_TransMatrix" ); gShaderImgTexture = glGetUniformLocation( gProgram, "s_ImgTexture" ); makeCheckImages(); glGenTextures( 1, &texName ); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); glUseProgram(gProgram); glEnableVertexAttribArray(gvPositionHandle); glEnableVertexAttribArray( gShaderTexCoord ); glUniform1i ( gShaderImgTexture, 0 ); gWidthd2 = w / 2; gHeightd2 = h / 2; esMatrixLoadIdentity( &gOrthographic ); //esOrtho(&gOrthographic, 0, mWidth, -mHeight, 0, 5.0f, -5.0f ); esOrtho(&gOrthographic, -gWidthd2, gWidthd2, -gHeightd2, gHeightd2, 5.0f, -5.0f ); ESMatrix modelview; esMatrixLoadIdentity( &gMatrix ); esMatrixLoadIdentity( &modelview ); esMatrixMultiply( &gMatrix, &modelview, &gOrthographic ); glViewport(0, 0, w, h); glUniformMatrix4fv( gvpMatrix, 1, GL_FALSE, (GLfloat *)&gMatrix ); //glGenBuffers( 1, &guVbo ); //glBindBuffer( GL_ARRAY_BUFFER, guVbo ); //glBufferData( GL_ARRAY_BUFFER, 5 * 6 * sizeof( GLfloat), gTriangleVertices, GL_STREAM_DRAW ); glActiveTexture ( GL_TEXTURE0 ); glBindTexture ( GL_TEXTURE_2D, texName ); createRenderBuffer(); //ESMatrix matrixTrans; //ESMatrix modelview; //esMatrixLoadIdentity( &modelview ); //esTranslate( &modelview, -fx, fy, 0.0 ); //esMatrixMultiply( &matrixTrans, &modelview, &gOrthographic ); glUniformMatrix4fv( gvpMatrix, 1, GL_FALSE, (GLfloat *)&gOrthographic ); return true; }
void InitLivin(int width, int height){ int i; char letterpath[] = "data/x.obj"; /* character mesh mask */ char letterlist[LETTERNUM] = "bceginrsty"; /* Cybernetic genetics characters */ char greetingspath[21]; /* OpenGL related initialization */ glClearColor(0.0, 0.0, 0.0, 0.0); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); perspectiveMatrix(pmatrix, 35.0, (float)width/(float)height, 0.1, 1500.0); /* Demo related initialization */ head = openDepthVideo("data/head.dv"); matat = openDepthVideo("data/matat.dv"); face = initFace("shaders/face.vs", "shaders/face.fs"); armface = initFace("shaders/face.vs", "shaders/face.fs"); knock = openOutline("data/knock.pyd", "shaders/knock.vs", "shaders/knock.fs"); jump = openOutline("data/jump.pyd", "shaders/jump.vs", "shaders/outline.fs"); hang = openOutline("data/hanging.pyd", "shaders/hang.vs", "shaders/outline.fs"); run = openOutline("data/run.pyd", "shaders/run.vs", "shaders/outline.fs"); falling = openOutline("data/falling_letters.pyd", "shaders/run.vs", "shaders/outline.fs"); door = openOutline("data/door.pyd", "shaders/door.vs", "shaders/door.fs"); trap = openOutline("data/trap.pyd", "shaders/trap.vs", "shaders/outline.fs"); fractalme = openOutline("data/fractalme.pyd", "shaders/frme.vs", "shaders/frme.fs"); /* Acrobatic outlines */ tiger = openOutline("data/tiger.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); hop = openOutline("data/hop.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); katf = openOutline("data/kezenatfordulas.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); flip = openOutline("data/flip.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); run2 = openOutline("data/run2.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); catwheel = openOutline("data/catwheel.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); tbill = openOutline("data/tarkobillenes.pyd", "shaders/acrobat.vs", "shaders/outline.fs"); createBox(); createBackground(); initGreetings(); createDistBack(); bigcube = createBigCube(600); titletex = loadPNGTexture("data/title.png"); greentex = loadPNGTexture("data/green.png"); creditstex = loadPNGTexture("data/credits.png"); bgalphatex = loadPNGTexture("data/bg_alpha.png"); whitetex = loadPNGTexture("data/white.png"); icubetex = loadPNGTexture("data/innercube.png"); headouttex = loadPNGTexture("data/headout.png"); chesstex = loadPNGTexture("data/chessboard.png"); atpartytex = loadPNGTexture("data/at_party.png"); for(i = 0; i < 12; i++){ sprintf(greetingspath, "data/greetings%d.png", i+1); greetingstex[i] = loadPNGTexture(greetingspath); } for(i = 0; i < MAXKNOCKINGMAN; i++){ knockingmans[i * 3 + 0] = drand48() * 4.0 + 8.0; knockingmans[i * 3 + 1] = drand48() * 6.0 + 1.0; knockingmans[i * 3 + 2] = drand48(); } /* Shaders */ background_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/background.vs"); background_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/background.fs"); background_src[2] = loadShader(GL_TESS_EVALUATION_SHADER, "shaders/background.te"); background_src[3] = loadShader(GL_TESS_CONTROL_SHADER, "shaders/background.tc"); background_src[4] = loadShader(GL_GEOMETRY_SHADER, "shaders/background.gs"); background_shader = createProgram(5, background_src); title_src[0] = background_src[0]; title_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/title.fs"); title_src[2] = background_src[2]; title_src[3] = background_src[3]; title_src[4] = background_src[4]; title_shader = createProgram(5, title_src); scroll_src[0] = background_src[0]; scroll_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/scroll.fs"); scroll_src[2] = background_src[2]; scroll_src[3] = background_src[3]; scroll_src[4] = background_src[4]; scroll_shader = createProgram(5, scroll_src); credits_src[0] = background_src[0]; credits_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/credits.fs"); credits_src[2] = background_src[2]; credits_src[3] = background_src[3]; credits_src[4] = loadShader(GL_GEOMETRY_SHADER, "shaders/credits.gs"); credits_shader = createProgram(5, credits_src); letter_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/letter.vs"); letter_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/letter.fs"); letter_shader = createProgram(2, letter_src); cube_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/cube.vs"); cube_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/cube.fs"); cube_src[2] = loadShader(GL_GEOMETRY_SHADER, "shaders/cube.gs"); cube_shader = createProgram(3, cube_src); gr_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/greetings.vs"); gr_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/greetings.fs"); gr_shader = createProgram(2, gr_src); dbgr_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/dbgr.vs"); dbgr_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/dbgr.fs"); dbgr_shader = createProgram(2, dbgr_src); bigcube_src[0] = loadShader(GL_VERTEX_SHADER, "shaders/bigcube.vs"); bigcube_src[1] = loadShader(GL_FRAGMENT_SHADER, "shaders/bigcube.fs"); bigcube_shader = createProgram(2, bigcube_src); /* Letters */ for(i = 0; i < LETTERNUM; i++){ letterpath[5] = letterlist[i]; letters[i] = loadOBJ(letterpath); glBindVertexArray(letters[i]->vao); bindVarToBuff(letter_shader, "vertex", letters[i]->vbo[MESHVERTEXINDEX], 3); bindVarToBuff(letter_shader, "normal", letters[i]->vbo[MESHNORMALINDEX], 3); bindVarToBuff(letter_shader, "tcoord", letters[i]->vbo[MESHTEXINDEX], 2); } cube = loadOBJ("data/cube.obj"); glBindVertexArray(cube->vao); bindVarToBuff(cube_shader, "vertex", cube->vbo[MESHVERTEXINDEX], 3); bindVarToBuff(cube_shader, "normal", cube->vbo[MESHNORMALINDEX], 3); bindVarToBuff(cube_shader, "tcoord", cube->vbo[MESHTEXINDEX], 2); initExplosion(); startTime(); }
void Program::setVertexSource(const std::string &source) { vSource = source; createProgram(); }
ShaderProgram::ShaderProgram(const char *vertex, const char *fragment) { m_program = createProgram(vertex, fragment); }
void StreamplotInit(int numPlots, StreamplotType* plotTypes, int screenWidth, int screenHeight, int showPlayPauseButton, int* resHandles) { int i, j; // Init global vars freeze = 0; lastEvent = 0; doubleTapCountDown = 0; gridEnabled = 1; initPinchEventDx = 0; initPinchEventX = 0; lastTranX = 0.0f; lastScaleX = 0.0f; startPtr = STREAMPLOT_N_MAX_POINTS/2 - 600; endPtr = STREAMPLOT_N_MAX_POINTS/2 + 600; showPlayPause = 0; for(i = 0; i < 16; i++) { gMVPMatrix[i] = 0.0f; } gMVPMatrix[0] = 1.0f; gMVPMatrix[5] = 1.0f; gMVPMatrix[10] = 1.0f; gMVPMatrix[15] = 1.0f; // Start usual init now int w = screenWidth; int h = screenHeight; freeze = 0; lastFreeze = 0; showPlayPause = showPlayPauseButton; gPlayButtonHandle = resHandles[0]; gPauseButtonHandle = resHandles[1]; gFontHandle = resHandles[2]; width = w; height = h; nPlots = numPlots; ptr = startPtr; float scaleX = (float)STREAMPLOT_N_MAX_POINTS * 1.0f / (endPtr - startPtr); gMVPMatrix[0] = scaleX; float aspectRatio = w * 1.0f / h; playPauseVertices[7] = -1.0f + (1.0f + playPauseVertices[2]) * aspectRatio; playPauseVertices[5] = -1.0f + (1.0f + playPauseVertices[2]) * aspectRatio; for(i = 0;i < nPlots; i++) { for(j = 0; j < 4; j++) { plots[i].color[j] = plotTypes[i].color[j]; } plots[i].thickness = plotTypes[i].thickness; plots[i].style = plotTypes[i].style; for(j = 0;j < STREAMPLOT_N_MAX_POINTS;j++) { plots[i].data[4*j] = -1.0f + (j * 2.0f) / STREAMPLOT_N_MAX_POINTS; plots[i].data[4*j + 1] = 0.0f; plots[i].data[4*j + 2] = -1.0f + ((j+1) * 2.0f) / STREAMPLOT_N_MAX_POINTS; plots[i].data[4*j + 3] = 0.0f; } } for(i = 0; i < STREAMPLOT_N_H_GRID_LINES; i++) { float yLevel = STREAMPLOT_GRID_MIN + ((STREAMPLOT_GRID_MAX-STREAMPLOT_GRID_MIN)/STREAMPLOT_N_H_GRID_LINES) * i; gridLinesH[4*i] = -1.0f; gridLinesH[4*i + 1] = yLevel; gridLinesH[4*i + 2] = 1.0f; gridLinesH[4*i + 3] = yLevel; } for(i = 0; i < STREAMPLOT_N_HT_GRID_LINES; i++) { float yLevel = STREAMPLOT_GRID_MIN + ((STREAMPLOT_GRID_MAX-STREAMPLOT_GRID_MIN)/STREAMPLOT_N_HT_GRID_LINES) * i; gridLinesHT[4*i] = -1.0f; gridLinesHT[4*i + 1] = yLevel; gridLinesHT[4*i + 2] = 1.0f; gridLinesHT[4*i + 3] = yLevel; } for(i = 0; i < STREAMPLOT_N_V_GRID_LINES; i++) { float xLevel = -1.0f + (2.0f/STREAMPLOT_N_V_GRID_LINES) * i; gridLinesV[4*i] = xLevel; gridLinesV[4*i + 1] = STREAMPLOT_GRID_MIN; gridLinesV[4*i + 2] = xLevel; gridLinesV[4*i + 3] = STREAMPLOT_GRID_MAX; } for(i = 0; i < STREAMPLOT_N_VT_GRID_LINES; i++) { float xLevel = -1.0f + (2.0f/STREAMPLOT_N_VT_GRID_LINES) * i; gridLinesVT[4*i] = xLevel; gridLinesVT[4*i + 1] = STREAMPLOT_GRID_MIN; gridLinesVT[4*i + 2] = xLevel; gridLinesVT[4*i + 3] = STREAMPLOT_GRID_MAX; } LOGI("StreamplotInit(%d, %d)", w, h); gProgramTexture = createProgram(tVertexShader, tFragmentShader); if (!gProgramTexture) { LOGE("Could not create program."); return; } gProgram = createProgram(gVertexShader, gFragmentShader); if (!gProgram) { LOGE("Could not create program."); return; } gLineHandle = glGetAttribLocation(gProgram, "vPosition"); checkGlError("glGetAttribLocation"); gMVPHandle = glGetUniformLocation(gProgram, "u_MVPMatrix"); checkGlError("glGetUniformLocation"); gColorHandle = glGetUniformLocation(gProgram, "u_Color"); checkGlError("glGetUniformLocation"); gPointSizeHandle = glGetUniformLocation(gProgram, "u_PointSize"); checkGlError("glGetUniformLocation"); gTexturePositionHandle = glGetAttribLocation(gProgramTexture, "vPosition"); checkGlError("glGetAttribLocation"); gTextureCoordinateHandle = glGetAttribLocation(gProgramTexture, "vCoordinate"); checkGlError("glGetAttribLocation"); gTextureUniformSamplerHandle = glGetUniformLocation(gProgramTexture, "u_Texture"); checkGlError("glGetUniformLocation"); glViewport(0, 0, w, h); checkGlError("glViewport"); }
void SSAO::setupShaders() { depth_prog = createProgram(SSAO_IMAGE_VS, SSAO_DEPTH_FS); // debug: draw depth texture with gamma correction image_prog = createProgram(SSAO_IMAGE_VS, SSAO_IMAGE_FS); // debug: draw an image quad, just draw a texture scene_prog = createProgram(SSAO_SCENE_VS, SSAO_SCENE_FS); // dof step 0: renders the scene + writes linear depth ssao_prog = createProgram(SSAO_VS, SSAO_FS); // dof: applies box blur using 2 render passes }
ShaderProgram *ShadersManager::getSimpleProgram() { const std::string dir = paths.getStringValue("shaders"); return createProgram(dir + paths.getStringValue("simpleVertexShader"), dir + paths.getStringValue("simpleFragmentShader")); }
unsigned int ShaderManager::createProgram(const std::string &vertexShaderFilename, const std::string &geometryShaderFilename, const std::string &fragmentShaderFilename) { std::map<std::string, std::string> emptyTokens; return createProgram(vertexShaderFilename, geometryShaderFilename, fragmentShaderFilename, emptyTokens); }
int main(void) { if(!glfwInit()) { printf("Could not init GLFW"); getchar(); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); //Opengl 2.1 //glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); //glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); //Opengl 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // MacOS fix glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); if(window_init(&window, 640, 480, "Test")) { fprintf( stderr, "Failed to open window.\n" ); getchar(); glfwTerminate(); }; window_set_size_callback(&window, window_size_callback); glewExperimental = GL_TRUE; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } //#clear errors GLEW may trigger printError(); glClearColor(0.0f, 0.0f, 0.4f, 0.0f); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); //Load model //---------- Model cube; model_init(&cube); model_set_data_length(&cube, sizeof(cube_vertex_data)); model_set_vertices(&cube, cube_vertex_data); model_set_colors(&cube, cube_color_data); model_set_uv_map(&cube, cube_uv_data); model_set_texture(&cube, "./textures/bricks.dds"); model_bind(&cube); //Create shaders //-------------- GLuint vertexShader, fragmentShader; loadShader(&vertexShader, GL_VERTEX_SHADER, mvpVertexShaderSource); loadShader(&fragmentShader, GL_FRAGMENT_SHADER, fragmentShaderSource); //Create program //-------------- GLuint program; createProgram(&program, vertexShader, fragmentShader); // Enable z-buffer // --------------- glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Enable culling // -------------- glEnable(GL_CULL_FACE); // Get MVP uniform // --------------- GLuint mvp_ul = glGetUniformLocation(program, "MVP"); // Model Matrix // ------------ Mat4 s; scale_m4(&s, 0.1f, 0.1f, 0.1f); printf("Scale:\n"); print_m4(&s); Mat4 r; rotate_m4(&r, 0.0f, 1.0f, 0.0f, 0.0f); printf("Rotate:\n"); print_m4(&r); Mat4 t; translate_m4(&t, 0.0f, 0.0f, 0.0f); printf("Translate:\n"); print_m4(&t); Mat4 rs; printf("Rotated*Scaled:\n"); mul_m4(&rs, &r, &s); print_m4(&rs); Mat4 model; printf("Model:\n"); mul_m4(&model, &t, &rs); print_m4(&model); // Camera // ------ Vec3 pos; Vec3 center; Vec3 up; Vec3 direction; Vec3 right; camera_init(&camera); camera_set_fov(&camera, 1.0f); camera_set_aspect(&camera, (float)window.width/(float)window.height); Input input; input_init(&input, &window, 0.5f, 0.5f, 0.8f, -5.7f, -2.7f); do { glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glUseProgram(program); input_get_data(&input, &pos, &direction, &right); add_v3(¢er, &pos, &direction); cross_v3(&up, &direction, &right); camera_set_position(&camera, &pos); camera_set_center(&camera, ¢er); camera_set_up(&camera, &up); // Mvp Matrix // ---------- Mat4 vp; camera_get_matrix(&camera, &vp); Mat4 mvp; mul_m4(&mvp, &vp, &model); printf("Perspective:\n"); print_m4(&mvp); // Set MVP transform glUniformMatrix4fv(mvp_ul, 1, GL_TRUE, &mvp[0][0]); model_render(&cube); window_swap_buffers(&window); glfwPollEvents(); } while( glfwGetKey(window.handle, GLFW_KEY_ESCAPE ) != GLFW_PRESS && glfwWindowShouldClose(window.handle) == 0 ); // Dispose // ------- model_dispose(&cube); glDeleteVertexArrays(1, &VertexArrayID); glDetachShader(program, fragmentShader); glDetachShader(program, vertexShader); glDeleteShader(fragmentShader); glDeleteShader(vertexShader); glDeleteProgram(program); glfwTerminate(); return 0; }
SSAOScene::SSAOScene(Context * ctx): CameraScene(ctx), cryModel("assets/models/nanosuit/nanosuit.obj") { FramebufferConfiguration cfg(ctx->getWindowWidth(),ctx->getWindowHeight()); TextureConfig posBfrConfig("positionDepth",GL_RGBA16F,GL_RGBA,GL_FLOAT); posBfrConfig.setTextureFilter(GL_NEAREST); posBfrConfig.setWrapMode(GL_CLAMP_TO_EDGE); TextureAttachment posBfr(posBfrConfig,GL_COLOR_ATTACHMENT0); TextureConfig norBfrConfig("normal",GL_RGB16F,GL_RGB,GL_FLOAT); posBfrConfig.setTextureFilter(GL_NEAREST); TextureAttachment norBfr(norBfrConfig,GL_COLOR_ATTACHMENT1); TextureConfig spec_albedoConfig("color",GL_RGBA,GL_RGBA,GL_FLOAT); posBfrConfig.setTextureFilter(GL_NEAREST); TextureAttachment spec_albedoBfr(spec_albedoConfig,GL_COLOR_ATTACHMENT2); cfg.addTexturebuffer(posBfr); cfg.addTexturebuffer(norBfr); cfg.addTexturebuffer(spec_albedoBfr); cfg.addRenderbuffer(RenderbufferAttachment(GL_DEPTH24_STENCIL8,GL_DEPTH_STENCIL_ATTACHMENT)); gBuffer.init(cfg); FramebufferConfiguration aoConfig(ctx->getWindowWidth(),ctx->getWindowHeight()); TextureConfig aoTexture("occlusion",GL_RED,GL_RGB,GL_FLOAT); aoTexture.setTextureFilter(GL_NEAREST); TextureAttachment ssaoBufferAttachment(aoTexture,GL_COLOR_ATTACHMENT0); aoConfig.addTexturebuffer(ssaoBufferAttachment); ssaoBuffer.init(aoConfig); GL_Logger::LogError("Could not configure ssaoBuffer"); //Blur buffer has same properties as ao buffer. FramebufferConfiguration blurConfiguration(ctx->getWindowWidth(),ctx->getWindowHeight()); TextureConfig blurTexture("occlusion",GL_RED,GL_RGB,GL_FLOAT); blurTexture.setTextureFilter(GL_NEAREST); TextureAttachment blurBufferAttachment(blurTexture,GL_COLOR_ATTACHMENT0); blurConfiguration.addTexturebuffer(blurBufferAttachment); ssaoBlurBuffer.init(blurConfiguration); std::uniform_real_distribution<GLfloat> randomFloats(0.0, 1.0); // random floats between 0.0 - 1.0 std::default_random_engine generator; //Set up a noise texture std::vector<glm::vec3> ssaoNoiseVec; for (GLuint i = 0; i < 16; i++) { glm::vec3 noise( randomFloats(generator) * 2.0 - 1.0, randomFloats(generator) * 2.0 - 1.0, 0.0f); ssaoNoiseVec.push_back(noise); } TextureConfig ssaoConfig("ssaoNoise",GL_RGB16F,GL_RGB,GL_FLOAT); ssaoConfig.setWrapMode(GL_REPEAT); ssaoConfig.setTextureFilter(GL_NEAREST); ssaoNoise.init(ssaoConfig,&ssaoNoiseVec[0],4,4); GL_Logger::LogError("Could not configure ssaoNoise"); deferredGBufferProg = createProgram("SSAO GBuffer fill program"); ssaoProgram = createProgram("SSAO creation program"); postProcessProg = createProgram("Display AO map program"); ssaoBlurProgram = createProgram("SSAO blur program"); finalPassProgram = createProgram("Final Pass Program"); geomPlane.transform.setScale(glm::vec3(20.0)); geomPlane.transform.setPosition(glm::vec3(0,-1,0)); cryModel.transform.setScale(glm::vec3(0.5)); cryModel.transform.setPosition(glm::vec3(0,0,3.5)); cryModel.transform.rotate(-M_PI/2, glm::vec3(1.0,0,0)); }
ShaderProgramGL::ShaderProgramGL(GLuint vs, GLuint ps, const VertexDeclarationGL* decl) { _program = createProgram(vs, ps, decl); }
GLuint loadShaders(std::string const& vs, std::string const& fs) { std::string v = readFile(vs); std::string f = readFile(fs); return createProgram(v,f); }
int main(int /*argc*/, char ** /*argv*/) { BaseApp app; ProgramObject programEnv, program; auto mainWindow = app.getMainWindow(); PerspectiveCamera cam; OrbitManipulator manipulator(&cam); manipulator.setupCallbacks(app); manipulator.setZoom(3); GLuint diffuseTexture; GLuint specularTexture; GLuint vao; GLuint vaoEmpty; GLuint vbo; int32_t sphereSizeX = 20; int32_t sphereSizeY = 20; app.addInitCallback([&]() { std::string prefix = app.getResourceDir() + "Shaders/Tutorial/"; auto vs = compileShader(GL_VERTEX_SHADER, "#version 450\n", Loader::text(prefix + "uv.vp")); auto fs = compileShader(GL_FRAGMENT_SHADER, "#version 450\n", Loader::text(prefix + "lighting.vp"), Loader::text(prefix + "uv.fp")); program = createProgram(vs, fs); std::string texPrefix = app.getResourceDir() + "Textures/Tutorial/"; diffuseTexture = Loader::texture(texPrefix + "earth.png"); specularTexture = Loader::texture(texPrefix + "earth_s.png"); glCreateBuffers(1, &vbo); const uint32_t floatsPerVertex = 6; const uint32_t vertiesPerFace = 6; float*vertices = new float[sphereSizeX*sphereSizeY*vertiesPerFace*floatsPerVertex]; for (int32_t y = 0; y<sphereSizeY; ++y) { for (int32_t x = 0; x<sphereSizeX; ++x) { for (uint32_t k = 0; k<vertiesPerFace; ++k) { const int32_t xOffset[] = { 0,1,0,0,1,1 }; const int32_t yOffset[] = { 0,0,1,1,0,1 }; float u = (float)(x + xOffset[k]) / sphereSizeX; float v = (float)(y + yOffset[k]) / sphereSizeY; float xAngle = -u*glm::two_pi<float>(); float yAngle = v*glm::pi<float>(); uint32_t faceId = y*sphereSizeX + x; uint32_t faceVertex = faceId*vertiesPerFace + k; vertices[faceVertex*floatsPerVertex + 0] = glm::cos(xAngle)*glm::sin(yAngle); vertices[faceVertex*floatsPerVertex + 1] = -glm::cos(yAngle); vertices[faceVertex*floatsPerVertex + 2] = glm::sin(xAngle)*glm::sin(yAngle); vertices[faceVertex*floatsPerVertex + 3] = 1; vertices[faceVertex*floatsPerVertex + 4] = u; vertices[faceVertex*floatsPerVertex + 5] = v; } } } glNamedBufferData(vbo, sizeof(float)*sphereSizeX*sphereSizeY*vertiesPerFace*floatsPerVertex, vertices, GL_STATIC_DRAW); delete[]vertices; glCreateVertexArrays(1, &vao); glEnableVertexArrayAttrib(vao, 0); glVertexArrayAttribFormat(vao, 0, 4, GL_FLOAT, 0, 0); glVertexArrayVertexBuffer(vao, 0, vbo, 0, sizeof(float)*floatsPerVertex); glEnableVertexArrayAttrib(vao, 1); glVertexArrayAttribFormat(vao, 1, 2, GL_FLOAT, 0, 0); glVertexArrayVertexBuffer(vao, 1, vbo, sizeof(float) * 4, sizeof(float)*floatsPerVertex); glClearColor(0, 0, 0, 1); glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); }); app.addResizeCallback([&](int w, int h) { glViewport(0, 0, w, h); cam.setAspect(float(w) / float(h)); }); app.addDrawCallback([&]() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); program.use(); glBindTextureUnit(0, diffuseTexture); glBindTextureUnit(1, specularTexture); program.setMatrix4fv("p", value_ptr(cam.getProjection())); program.setMatrix4fv("v", value_ptr(cam.getView())); glBindVertexArray(vao); glDrawArrays(GL_TRIANGLES, 0, sphereSizeX*sphereSizeY * 6); glBindVertexArray(0); }); return app.run(); }
bool GLWidgetRendererPrivate::prepareShaderProgram(const VideoFormat &fmt, ColorTransform::ColorSpace cs) { // isSupported(pixfmt) if (!fmt.isValid()) return false; releaseShaderProgram(); video_format.setPixelFormatFFmpeg(fmt.pixelFormatFFmpeg()); colorTransform.setInputColorSpace(cs); // TODO: only to kinds, packed.glsl, planar.glsl QString frag; if (fmt.isPlanar()) { frag = getShaderFromFile("shaders/planar.f.glsl"); } else { frag = getShaderFromFile("shaders/rgb.f.glsl"); } if (frag.isEmpty()) return false; if (fmt.isRGB()) { frag.prepend("#define INPUT_RGB\n"); } else { frag.prepend(QString("#define YUV%1P\n").arg(fmt.bitsPerPixel(0))); } if (fmt.isPlanar() && fmt.bytesPerPixel(0) == 2) { if (fmt.isBigEndian()) frag.prepend("#define LA_16BITS_BE\n"); else frag.prepend("#define LA_16BITS_LE\n"); } if (cs == ColorTransform::BT601) { frag.prepend("#define CS_BT601\n"); } else if (cs == ColorTransform::BT709) { frag.prepend("#define CS_BT709\n"); } #if NO_QGL_SHADER program = createProgram(kVertexShader, frag.toUtf8().constData()); if (!program) { qWarning("Could not create shader program."); return false; } // vertex shader. we can set attribute locations calling glBindAttribLocation a_Position = glGetAttribLocation(program, "a_Position"); a_TexCoords = glGetAttribLocation(program, "a_TexCoords"); u_matrix = glGetUniformLocation(program, "u_MVP_matrix"); u_bpp = glGetUniformLocation(program, "u_bpp"); // fragment shader u_colorMatrix = glGetUniformLocation(program, "u_colorMatrix"); #else if (!shader_program->addShaderFromSourceCode(QGLShader::Vertex, kVertexShader)) { qWarning("Failed to add vertex shader: %s", shader_program->log().toUtf8().constData()); return false; } if (!shader_program->addShaderFromSourceCode(QGLShader::Fragment, frag)) { qWarning("Failed to add fragment shader: %s", shader_program->log().toUtf8().constData()); return false; } if (!shader_program->link()) { qWarning("Failed to link shader program...%s", shader_program->log().toUtf8().constData()); return false; } // vertex shader a_Position = shader_program->attributeLocation("a_Position"); a_TexCoords = shader_program->attributeLocation("a_TexCoords"); u_matrix = shader_program->uniformLocation("u_MVP_matrix"); u_bpp = shader_program->uniformLocation("u_bpp"); // fragment shader u_colorMatrix = shader_program->uniformLocation("u_colorMatrix"); #endif //NO_QGL_SHADER qDebug("glGetAttribLocation(\"a_Position\") = %d\n", a_Position); qDebug("glGetAttribLocation(\"a_TexCoords\") = %d\n", a_TexCoords); qDebug("glGetUniformLocation(\"u_MVP_matrix\") = %d\n", u_matrix); qDebug("glGetUniformLocation(\"u_bpp\") = %d\n", u_bpp); qDebug("glGetUniformLocation(\"u_colorMatrix\") = %d\n", u_colorMatrix); if (fmt.isRGB()) u_Texture.resize(1); else u_Texture.resize(fmt.channels()); for (int i = 0; i < u_Texture.size(); ++i) { QString tex_var = QString("u_Texture%1").arg(i); #if NO_QGL_SHADER u_Texture[i] = glGetUniformLocation(program, tex_var.toUtf8().constData()); #else u_Texture[i] = shader_program->uniformLocation(tex_var); #endif qDebug("glGetUniformLocation(\"%s\") = %d\n", tex_var.toUtf8().constData(), u_Texture[i]); } return true; }
void ShaderProgram::initProgram(std::string vertexCode, std::string fragmentCode) { _program = createProgram(vertexCode, fragmentCode); }