int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); const bgfx::Caps* caps = bgfx::getCaps(); const bool computeSupported = !!(caps->supported & BGFX_CAPS_COMPUTE); const bool indirectSupported = !!(caps->supported & BGFX_CAPS_DRAW_INDIRECT); if (computeSupported) { // Imgui. imguiCreate(); bgfx::VertexDecl quadVertexDecl; quadVertexDecl.begin() .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float) .end(); // Create static vertex buffer. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_quadVertices, sizeof(s_quadVertices) ) , quadVertexDecl ); // Create static index buffer. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer( // Static data can be passed with bgfx::makeRef bgfx::makeRef(s_quadIndices, sizeof(s_quadIndices) ) ); // Create particle program from shaders. bgfx::ProgramHandle particleProgram = loadProgram("vs_particle", "fs_particle"); // Setup compute buffers bgfx::VertexDecl computeVertexDecl; computeVertexDecl.begin() .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float) .end(); const uint32_t threadGroupUpdateSize = 512; const uint32_t maxParticleCount = 32 * 1024; bgfx::DynamicVertexBufferHandle currPositionBuffer0 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE); bgfx::DynamicVertexBufferHandle currPositionBuffer1 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE); bgfx::DynamicVertexBufferHandle prevPositionBuffer0 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE); bgfx::DynamicVertexBufferHandle prevPositionBuffer1 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE); bgfx::UniformHandle u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, 3); bgfx::ProgramHandle initInstancesProgram = bgfx::createProgram(loadShader("cs_init_instances"), true); bgfx::ProgramHandle updateInstancesProgram = bgfx::createProgram(loadShader("cs_update_instances"), true); bgfx::ProgramHandle indirectProgram = BGFX_INVALID_HANDLE; bgfx::IndirectBufferHandle indirectBuffer = BGFX_INVALID_HANDLE; if (indirectSupported) { indirectProgram = bgfx::createProgram(loadShader("cs_indirect"), true); indirectBuffer = bgfx::createIndirectBuffer(2); } u_paramsDataStruct u_paramsData; InitializeParams(0, &u_paramsData); bgfx::setUniform(u_params, &u_paramsData, 3); bgfx::setBuffer(0, prevPositionBuffer0, bgfx::Access::Write); bgfx::setBuffer(1, currPositionBuffer0, bgfx::Access::Write); bgfx::dispatch(0, initInstancesProgram, maxParticleCount / threadGroupUpdateSize, 1, 1); float view[16]; float initialPos[3] = { 0.0f, 0.0f, -45.0f }; cameraCreate(); cameraSetPosition(initialPos); cameraSetVerticalAngle(0.0f); cameraGetViewMtx(view); int32_t scrollArea = 0; bool useIndirect = false; entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const float deltaTime = float(frameTime/freq); if (deltaTime > 1000.0) { abort(); } // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/24-nbody"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: N-body simulation with compute shaders using buffers."); imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) , mouseState.m_mz , width , height ); imguiBeginScrollArea("Settings", width - width / 4 - 10, 10, width / 4, 500, &scrollArea); imguiSlider("Random seed", u_paramsData.baseSeed, 0, 100); int32_t shape = imguiChoose(u_paramsData.initialShape, "Point", "Sphere", "Box", "Donut"); imguiSlider("Initial speed", u_paramsData.initialSpeed, 0.0f, 300.0f, 0.1f); bool defaults = imguiButton("Reset"); imguiSeparatorLine(); imguiSlider("Particle count (x512)", u_paramsData.dispatchSize, 1, 64); imguiSlider("Gravity", u_paramsData.gravity, 0.0f, 0.3f, 0.001f); imguiSlider("Damping", u_paramsData.damping, 0.0f, 1.0f, 0.01f); imguiSlider("Max acceleration", u_paramsData.maxAccel, 0.0f, 100.0f, 0.01f); imguiSlider("Time step", u_paramsData.timeStep, 0.0f, 0.02f, 0.0001f); imguiSeparatorLine(); imguiSlider("Particle intensity", u_paramsData.particleIntensity, 0.0f, 1.0f, 0.001f); imguiSlider("Particle size", u_paramsData.particleSize, 0.0f, 1.0f, 0.001f); imguiSlider("Particle power", u_paramsData.particlePower, 0.001f, 16.0f, 0.01f); imguiSeparatorLine(); if (imguiCheck("Use draw/dispatch indirect", useIndirect, indirectSupported) ) { useIndirect = !useIndirect; } imguiEndScrollArea(); imguiEndFrame(); // Modify parameters and reset if shape is changed if (shape != u_paramsData.initialShape) { defaults = true; InitializeParams(shape, &u_paramsData); } if (defaults) { bgfx::setBuffer(0, prevPositionBuffer0, bgfx::Access::Write); bgfx::setBuffer(1, currPositionBuffer0, bgfx::Access::Write); bgfx::setUniform(u_params, &u_paramsData, 3); bgfx::dispatch(0, initInstancesProgram, maxParticleCount / threadGroupUpdateSize, 1, 1); } if (useIndirect) { bgfx::setUniform(u_params, &u_paramsData, 3); bgfx::setBuffer(0, indirectBuffer, bgfx::Access::Write); bgfx::dispatch(0, indirectProgram); } bgfx::setBuffer(0, prevPositionBuffer0, bgfx::Access::Read); bgfx::setBuffer(1, currPositionBuffer0, bgfx::Access::Read); bgfx::setBuffer(2, prevPositionBuffer1, bgfx::Access::Write); bgfx::setBuffer(3, currPositionBuffer1, bgfx::Access::Write); bgfx::setUniform(u_params, &u_paramsData, 3); if (useIndirect) { bgfx::dispatch(0, updateInstancesProgram, indirectBuffer, 1); } else { bgfx::dispatch(0, updateInstancesProgram, u_paramsData.dispatchSize, 1, 1); } bx::xchg(currPositionBuffer0, currPositionBuffer1); bx::xchg(prevPositionBuffer0, prevPositionBuffer1); // Update camera. cameraUpdate(deltaTime, mouseState); cameraGetViewMtx(view); // Set view and projection matrix for view 0. const bgfx::HMD* hmd = bgfx::getHMD(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float viewHead[16]; float eye[3] = {}; bx::mtxQuatTranslationHMD(viewHead, hmd->eye[0].rotation, eye); float tmp[16]; bx::mtxMul(tmp, view, viewHead); float proj[16]; bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 10000.0f); bgfx::setViewTransform(0, tmp, proj); // Set view 0 default viewport. // // Use HMD's width/height since HMD's internal frame buffer size // might be much larger than window size. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float proj[16]; bx::mtxProj(proj, 90.0f, float(width)/float(height), 0.1f, 10000.0f); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); } // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); bgfx::setInstanceDataBuffer(currPositionBuffer0, 0, u_paramsData.dispatchSize * threadGroupUpdateSize); // Set render states. bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_BLEND_ADD | BGFX_STATE_DEPTH_TEST_ALWAYS ); // Submit primitive for rendering to view 0. if (useIndirect) { bgfx::submit(0, particleProgram, indirectBuffer, 0); } else { bgfx::submit(0, particleProgram); } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. cameraDestroy(); imguiDestroy(); if (indirectSupported) { bgfx::destroyProgram(indirectProgram); bgfx::destroyIndirectBuffer(indirectBuffer); } bgfx::destroyUniform(u_params); bgfx::destroyDynamicVertexBuffer(currPositionBuffer0); bgfx::destroyDynamicVertexBuffer(currPositionBuffer1); bgfx::destroyDynamicVertexBuffer(prevPositionBuffer0); bgfx::destroyDynamicVertexBuffer(prevPositionBuffer1); bgfx::destroyProgram(updateInstancesProgram); bgfx::destroyProgram(initInstancesProgram); bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(particleProgram); } else { int64_t timeOffset = bx::getHPCounter(); entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { int64_t now = bx::getHPCounter(); float time = (float)( (now - timeOffset)/double(bx::getHPFrequency() ) ); bgfx::setViewRect(0, 0, 0, width, height); bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/24-nbody"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: N-body simulation with compute shaders using buffers."); bool blink = uint32_t(time*3.0f)&1; bgfx::dbgTextPrintf(0, 5, blink ? 0x1f : 0x01, " Compute is not supported by GPU. "); bgfx::touch(0); bgfx::frame(); } } // Shutdown bgfx. bgfx::shutdown(); return 0; }
void GPUProgram::reload(const std::string& _code) { std::string code = _code; // If a syntax error occurs while loading the shader we want to break. // However, it makes no sense to break in this loading code when the // error is really in the shader code. To hack this under MSVC we print // out the error as if it were a MSVC error so double clicking will take // us there, then break in this code. To reload the shader we jump back // to the top of the loading routine and try again. bool reloadFromFile = (code == ""); bool ignore = false; LOADSHADER: if (reloadFromFile) { if (fileExists(filename)) { code = readFileAsString(filename); } else { error("Critical Error", std::string("Cannot locate file \"") + filename + "\" to reload it.", true); exit(-1); } } unit = getUnitFromCode(code, extension); glPushAttrib(GL_ALL_ATTRIB_BITS); glEnable(unit); genPrograms(1, &glProgram); bindProgram(unit, glProgram); // Clear the error flag. glGetError(); loadProgram(code); // Check for load errors if ((glGetError() == GL_INVALID_OPERATION) && (! ignore)) { int pos = 0; const unsigned char* msg = NULL; getProgramError(pos, msg); deletePrograms(1, &glProgram); int line = 1; int col = 1; // Find the line and column position. int x = 0; for (x = 0, col = 1; x < pos; ++x, ++col) { if (code[x] == '\n') { ++line; col = 1; } } if (col > 1) { --col; } // Count forward to the end of the line int endCol = col; while ((x < (int)code.size()) && (code[x] != '\n') && (code[x] != '\r')) { ++x; ++endCol; } // Extract the line std::string codeLine = code.substr(pos - col + 1, endCol - col); // Show the line std::string text = format("%s (%d:%d) : %s%s%s", filename.c_str(), line, col, msg, NEWLINE, NEWLINE); text += codeLine + NEWLINE; for (int i = 0; i < col - 1; ++i) { text += " "; } text += "^"; #ifdef G3D_WIN32 { // Print the error message in MSVC format std::string fullFilename = resolveFilename(filename); debugPrintf("%s%s(%d) : GPU Program Error : %s%s%s", NEWLINE, fullFilename.c_str(), line, msg, NEWLINE, NEWLINE); } #endif #ifndef _DEBUG Log::common()->print("\n******************************\n"); Log::common()->print(text); exit(-1); #endif const char* choice[] = {"Debug", "Ignore", "Ignore All", "Exit"}; switch (prompt("Error Loading Program", text.c_str(), choice, 4, true)) { case 0: // Debug { //////////////////////////////////////////////////////////////////////////// // // // PUSH F4 // // // // If your program breaks on this line in debug mode under Windows, // // go to the MSVC Debug window and click on the error message (or // // just press F4 be taken to the error line in your shader. // // // // When you change it and press continue, G3D will try to reload your // // shader (if it came from a file). // // // //////////////////////////////////////////////////////////////////////////// debugBreak(); reloadFromFile = true; goto LOADSHADER; break; } case 1: // Ignore break; case 2: // Ignore all ignore = true; break; case 3: // Exit exit(-1); } } bindingTable.parse(code); glPopAttrib(); }
int _main_(int _argc, char** _argv) { Args args(_argc, _argv); uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(width, height, reset); bgfx::RendererType::Enum renderer = bgfx::getRendererType(); bool flipV = false || renderer == bgfx::RendererType::OpenGL || renderer == bgfx::RendererType::OpenGLES ; // Enable debug text. bgfx::setDebug(debug); // Uniforms. bgfx::UniformHandle u_shadowMap = bgfx::createUniform("u_shadowMap", bgfx::UniformType::Int1); bgfx::UniformHandle u_lightPos = bgfx::createUniform("u_lightPos", bgfx::UniformType::Vec4); bgfx::UniformHandle u_lightMtx = bgfx::createUniform("u_lightMtx", bgfx::UniformType::Mat4); // Vertex declarations. bgfx::VertexDecl PosNormalDecl; PosNormalDecl.begin() .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float) .add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true) .end(); // Meshes. Mesh* bunny = meshLoad("meshes/bunny.bin"); Mesh* cube = meshLoad("meshes/cube.bin"); Mesh* hollowcube = meshLoad("meshes/hollowcube.bin"); bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer( bgfx::makeRef(s_hplaneVertices, sizeof(s_hplaneVertices) ) , PosNormalDecl ); bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer( bgfx::makeRef(s_planeIndices, sizeof(s_planeIndices) ) ); // Render targets. uint16_t shadowMapSize = 512; // Get renderer capabilities info. const bgfx::Caps* caps = bgfx::getCaps(); // Shadow samplers are supported at least partially supported if texture // compare less equal feature is supported. bool shadowSamplerSupported = 0 != (caps->supported & BGFX_CAPS_TEXTURE_COMPARE_LEQUAL); bgfx::ProgramHandle progShadow; bgfx::ProgramHandle progMesh; bgfx::TextureHandle shadowMapTexture; bgfx::FrameBufferHandle shadowMapFB; if (shadowSamplerSupported) { // Depth textures and shadow samplers are supported. progShadow = loadProgram("vs_sms_shadow", "fs_sms_shadow"); progMesh = loadProgram("vs_sms_mesh", "fs_sms_mesh"); shadowMapTexture = bgfx::createTexture2D(shadowMapSize, shadowMapSize, 1, bgfx::TextureFormat::D16, BGFX_TEXTURE_COMPARE_LEQUAL); bgfx::TextureHandle fbtextures[] = { shadowMapTexture }; shadowMapFB = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true); } else { // Depth textures and shadow samplers are not supported. Use float // depth packing into color buffer instead. progShadow = loadProgram("vs_sms_shadow_pd", "fs_sms_shadow_pd"); progMesh = loadProgram("vs_sms_mesh", "fs_sms_mesh_pd"); shadowMapTexture = bgfx::createTexture2D(shadowMapSize, shadowMapSize, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT); bgfx::TextureHandle fbtextures[] = { shadowMapTexture, bgfx::createTexture2D(shadowMapSize, shadowMapSize, 1, bgfx::TextureFormat::D16, BGFX_TEXTURE_RT_BUFFER_ONLY), }; shadowMapFB = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true); } MeshState* state[2]; state[0] = meshStateCreate(); state[0]->m_state = 0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_DEPTH_WRITE | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_CULL_CCW | BGFX_STATE_MSAA ; state[0]->m_program = progShadow; state[0]->m_viewId = RENDER_SHADOW_PASS_ID; state[0]->m_numTextures = 0; state[1] = meshStateCreate(); state[1]->m_state = 0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_DEPTH_WRITE | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_CULL_CCW | BGFX_STATE_MSAA ; state[1]->m_program = progMesh; state[1]->m_viewId = RENDER_SCENE_PASS_ID; state[1]->m_numTextures = 1; state[1]->m_textures[0].m_flags = UINT32_MAX; state[1]->m_textures[0].m_stage = 0; state[1]->m_textures[0].m_sampler = u_shadowMap; state[1]->m_textures[0].m_texture = shadowMapTexture; // Set view and projection matrices. float view[16]; float proj[16]; float eye[3] = { 0.0f, 30.0f, -60.0f }; float at[3] = { 0.0f, 5.0f, 0.0f }; bx::mtxLookAt(view, eye, at); const float aspect = float(int32_t(width) ) / float(int32_t(height) ); bx::mtxProj(proj, 60.0f, aspect, 0.1f, 1000.0f, flipV); // Time acumulators. float timeAccumulatorLight = 0.0f; float timeAccumulatorScene = 0.0f; entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { // Time. int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; const float deltaTime = float(frameTime/freq); // Update time accumulators. timeAccumulatorLight += deltaTime; timeAccumulatorScene += deltaTime; // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/15-shadowmaps-simple"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Shadow maps example (technique: %s).", shadowSamplerSupported ? "depth texture and shadow samplers" : "shadow depth packed into color texture"); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); // Setup lights. float lightPos[4]; lightPos[0] = -cosf(timeAccumulatorLight); lightPos[1] = -1.0f; lightPos[2] = -sinf(timeAccumulatorLight); lightPos[3] = 0.0f; bgfx::setUniform(u_lightPos, lightPos); // Setup instance matrices. float mtxFloor[16]; bx::mtxSRT(mtxFloor , 30.0f, 30.0f, 30.0f , 0.0f, 0.0f, 0.0f , 0.0f, 0.0f, 0.0f ); float mtxBunny[16]; bx::mtxSRT(mtxBunny , 5.0f, 5.0f, 5.0f , 0.0f, bx::pi - timeAccumulatorScene, 0.0f , 15.0f, 5.0f, 0.0f ); float mtxHollowcube[16]; bx::mtxSRT(mtxHollowcube , 2.5f, 2.5f, 2.5f , 0.0f, 1.56f - timeAccumulatorScene, 0.0f , 0.0f, 10.0f, 0.0f ); float mtxCube[16]; bx::mtxSRT(mtxCube , 2.5f, 2.5f, 2.5f , 0.0f, 1.56f - timeAccumulatorScene, 0.0f , -15.0f, 5.0f, 0.0f ); // Define matrices. float lightView[16]; float lightProj[16]; eye[0] = -lightPos[0]; eye[1] = -lightPos[1]; eye[2] = -lightPos[2]; at[0] = 0.0f; at[1] = 0.0f; at[2] = 0.0f; bx::mtxLookAt(lightView, eye, at); const float area = 30.0f; bx::mtxOrtho(lightProj, -area, area, -area, area, -100.0f, 100.0f); bgfx::setViewRect(RENDER_SHADOW_PASS_ID, 0, 0, shadowMapSize, shadowMapSize); bgfx::setViewFrameBuffer(RENDER_SHADOW_PASS_ID, shadowMapFB); bgfx::setViewTransform(RENDER_SHADOW_PASS_ID, lightView, lightProj); bgfx::setViewRect(RENDER_SCENE_PASS_ID, 0, 0, width, height); bgfx::setViewTransform(RENDER_SCENE_PASS_ID, view, proj); // Clear backbuffer and shadowmap framebuffer at beginning. bgfx::setViewClear(RENDER_SHADOW_PASS_ID , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x303030ff, 1.0f, 0 ); bgfx::setViewClear(RENDER_SCENE_PASS_ID , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x303030ff, 1.0f, 0 ); // Render. float mtxShadow[16]; float lightMtx[16]; const float sy = flipV ? 0.5f : -0.5f; const float mtxCrop[16] = { 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, sy, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, }; float mtxTmp[16]; bx::mtxMul(mtxTmp, lightProj, mtxCrop); bx::mtxMul(mtxShadow, lightView, mtxTmp); // Floor. bx::mtxMul(lightMtx, mtxFloor, mtxShadow); uint32_t cached = bgfx::setTransform(mtxFloor); for (uint32_t pass = 0; pass < 2; ++pass) { const MeshState& st = *state[pass]; bgfx::setTransform(cached); for (uint8_t tex = 0; tex < st.m_numTextures; ++tex) { const MeshState::Texture& texture = st.m_textures[tex]; bgfx::setTexture(texture.m_stage , texture.m_sampler , texture.m_texture , texture.m_flags ); } bgfx::setUniform(u_lightMtx, lightMtx); bgfx::setIndexBuffer(ibh); bgfx::setVertexBuffer(vbh); bgfx::setState(st.m_state); bgfx::submit(st.m_viewId, st.m_program); } // Bunny. bx::mtxMul(lightMtx, mtxBunny, mtxShadow); bgfx::setUniform(u_lightMtx, lightMtx); meshSubmit(bunny, &state[0], 1, mtxBunny); bgfx::setUniform(u_lightMtx, lightMtx); meshSubmit(bunny, &state[1], 1, mtxBunny); // Hollow cube. bx::mtxMul(lightMtx, mtxHollowcube, mtxShadow); bgfx::setUniform(u_lightMtx, lightMtx); meshSubmit(hollowcube, &state[0], 1, mtxHollowcube); bgfx::setUniform(u_lightMtx, lightMtx); meshSubmit(hollowcube, &state[1], 1, mtxHollowcube); // Cube. bx::mtxMul(lightMtx, mtxCube, mtxShadow); bgfx::setUniform(u_lightMtx, lightMtx); meshSubmit(cube, &state[0], 1, mtxCube); bgfx::setUniform(u_lightMtx, lightMtx); meshSubmit(cube, &state[1], 1, mtxCube); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } meshUnload(bunny); meshUnload(cube); meshUnload(hollowcube); meshStateDestroy(state[0]); meshStateDestroy(state[1]); bgfx::destroyVertexBuffer(vbh); bgfx::destroyIndexBuffer(ibh); bgfx::destroyProgram(progShadow); bgfx::destroyProgram(progMesh); bgfx::destroyFrameBuffer(shadowMapFB); bgfx::destroyUniform(u_shadowMap); bgfx::destroyUniform(u_lightPos); bgfx::destroyUniform(u_lightMtx); // Shutdown bgfx. bgfx::shutdown(); return 0; }
BOOL NextBarDlg::OCommand(ULONG msg, MPARAM mp1, MPARAM mp2) { switch(msg) { case WM_INITDLG: centerDlg(); Title.inherit(hwnd); Program.inherit(hwnd); Path.inherit(hwnd); Parms.inherit(hwnd); Icon.inherit(hwnd); Settings.inherit(hwnd); Settings.setFont("8.Helv"); setProgram2Dialog(); if (actualButton) WinSendMsg(WinWindowFromID(hwnd, NHX_ICONFIELD), SM_SETHANDLE, MPFROMP(actualButton->pIco->hptr), NULL); break; case WM_CONTROL: handleButtons(mp1); break; case DM_DRAGOVER: { PDRAGINFO pdinfo = (PDRAGINFO) mp1; PDRAGITEM pditem = NULL; DrgAccessDraginfo(pdinfo); pditem = DrgQueryDragitemPtr(pdinfo, 0); if (DrgVerifyRMF(pditem, "DRM_OS2FILE", NULL)) { DrgFreeDraginfo (pdinfo) ; return(TRUE); } else { DrgFreeDraginfo (pdinfo) ; return(FALSE); } } case DM_DROP: { PDRAGINFO pDragInfo; /* Pointer to DRAGINFO structure */ PDRAGITEM pDragItem; /* Pointer to DRAGITEM structure */ CHAR Buffer[CCHMAXPATH]; CHAR ObjectType[CCHMAXPATH]; PSZ pszBuffer; OString tmpBuf; pDragInfo = (PDRAGINFO)mp1; if(DrgAccessDraginfo(pDragInfo)==FALSE) break; pDragItem = DrgQueryDragitemPtr(pDragInfo, 0); DrgQueryStrName(pDragItem->hstrRMF, sizeof(ObjectType), ObjectType); if(!strstr(ObjectType, "<DRM_OBJECT, DRF_OBJECT>")) { // this is not a WPS object DrgQueryStrName(pDragItem->hstrContainerName, sizeof(Buffer), Buffer); pszBuffer = ((PSZ) Buffer)+strlen(Buffer); DrgQueryStrName(pDragItem->hstrSourceName, sizeof(Buffer)-strlen(pszBuffer), pszBuffer); tmpBuf << Buffer; strupr(tmpBuf); if (strstr(tmpBuf, ".ICO")) { hps = WinGetPS(WinWindowFromID(hwnd, NHX_ICONFIELD)); GpiCreateLogColorTable(hps, LCOL_RESET, LCOLF_RGB, 0L, 0L, NULL); WinQueryWindowRect(WinWindowFromID(hwnd, NHX_ICONFIELD), &rcl); GpiSetColor(hps, SYSCLR_DIALOGBACKGROUND); GpiBox(hps, DRO_FILL, (PPOINTL) &rcl.xRight, 0L, 0L); WinReleasePS(hps); if (actualButton->pIco) delete actualButton->pIco; try { actualButton->pIco = new OIcon(Buffer); } catch(...) { delete actualButton->pIco; actualButton->pIco = new OIcon(); } WinSendMsg(WinWindowFromID(hwnd, NHX_ICONFIELD), SM_SETHANDLE, MPFROMP(actualButton->pIco->hptr), NULL); WinSetDlgItemText(hwnd, NHX_ICON, Buffer); } else if ((!strstr(tmpBuf, ".EXE")) && (!strstr(tmpBuf, ".COM")) && (!strstr(tmpBuf, ".BAT")) && (!strstr(tmpBuf, ".CMD"))) install2Dialog(Buffer, TRUE); else install2Dialog(Buffer, FALSE); } else { DrgQueryStrName(pDragItem->hstrSourceName, sizeof(Buffer), Buffer); install2Dialog(Buffer, TRUE); } break; } case WM_COMMAND: switch(SHORT1FROMMP(mp1)) { case NHX_SAVE: setDialog2Program(); if (isCreation) WinPostMsg(nxh->toolbar->hwnd, WM_TOOLBAR_RESET, NULL, NULL); else WinPostMsg(nxh->toolbar->hwnd, WM_SAVE_BUTTONS, NULL, NULL); event = NULL; WinPostMsg(hwnd, WM_CLOSE, NULL, NULL); break; case NHX_CANCEL: WinSendMsg(hwnd, WM_CLOSE, NULL, NULL); break; case NHX_LOAD: loadProgram(); break; } break; case WM_HELP: nxh->toolbar->helpRequest(PANEL_CFGS); break; case WM_CLOSE: WinSendMsg(WinWindowFromID(hwnd, NHX_ICONFIELD), SM_SETHANDLE, MPFROMP(NULLHANDLE), NULL); if (isCreation) WinPostMsg(nxh->toolbar->hwnd, WM_CFG_CANCELED, MPFROMP(event), NULL); delete this; break; default: return(FALSE); } return(TRUE); #ifdef __BORLANDC__ #pragma warn -par #endif }
/* * Executes the Instruction based on the opcode. */ static inline void execute_instruction(Instruction instr){ switch(instr.op) { case MOVE:{ conditionalMove(registers, instr.reg1, instr.reg2, instr.reg3); programCounter++; break; } case SEGLOAD:{ UM_Word ID = registers[instr.reg2]; UM_Word offset = registers[instr.reg3]; UM_Word toStore = segmentedLoad(memorySegments, ID, offset); registers[instr.reg1] = toStore; programCounter++; break; } case SEGSTORE:{ UM_Word ID = registers[instr.reg1]; UM_Word offset = registers[instr.reg2]; UM_Word value = registers[instr.reg3]; segmentedStore(memorySegments, ID, offset, value); programCounter++; break; } case ADD:{ addition(registers, instr.reg1, instr.reg2, instr.reg3); programCounter++; break; } case MULTIPLY:{ multiplication(registers, instr.reg1, instr.reg2, instr.reg3); programCounter++; break; } case DIVIDE:{ division(registers, instr.reg1, instr.reg2, instr.reg3); programCounter++; break; } case NAND:{ bitwiseNAND(registers, instr.reg1, instr.reg2, instr.reg3); programCounter++; break; } case HALT: { programCounter = 0; break; } case MAP:{ UM_Word length = registers[instr.reg3]; registers[instr.reg2] = mapSegment(memorySegments, length); programCounter++; break; } case UNMAP:{ UM_Word ID = registers[instr.reg3]; unmapSegment(memorySegments, ID); programCounter++; break; } case OUTPUT:{ output(registers, instr.reg3); programCounter++; break; } case INPUT:{ input(registers, instr.reg3); programCounter++; break; } case LOADPROG:{ UM_Word ID = registers[instr.reg2]; if(ID != 0){ loadProgram(memorySegments, ID); numInstructions = instructionLength(memorySegments); //programPointer = getInstructions(memorySegments); } programCounter = registers[instr.reg3]; break; } case LOADVAL:{ registers[instr.reg1] = instr.value; programCounter++; break; } } }
int _main_(int /*_argc*/, char** /*_argv*/) { PosColorTexCoord0Vertex::init(); uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; s_texelHalf = 0.5f; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; s_flipV = true; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; s_flipV = true; break; } const bgfx::Memory* mem; mem = loadTexture("uffizi.dds"); bgfx::TextureHandle uffizi = bgfx::createTexture(mem, BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP|BGFX_TEXTURE_W_CLAMP); bgfx::UniformHandle u_time = bgfx::createUniform("u_time", bgfx::UniformType::Uniform1f); bgfx::UniformHandle u_texCube = bgfx::createUniform("u_texCube", bgfx::UniformType::Uniform1i); bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1i); bgfx::UniformHandle u_texLum = bgfx::createUniform("u_texLum", bgfx::UniformType::Uniform1i); bgfx::UniformHandle u_texBlur = bgfx::createUniform("u_texBlur", bgfx::UniformType::Uniform1i); bgfx::UniformHandle u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Uniform4x4fv); bgfx::UniformHandle u_tonemap = bgfx::createUniform("u_tonemap", bgfx::UniformType::Uniform4fv); bgfx::UniformHandle u_offset = bgfx::createUniform("u_offset", bgfx::UniformType::Uniform4fv, 16); bgfx::UniformHandle u_weight = bgfx::createUniform("u_weight", bgfx::UniformType::Uniform4fv, 16); bgfx::ProgramHandle skyProgram = loadProgram("vs_hdr_skybox", "fs_hdr_skybox"); bgfx::ProgramHandle lumProgram = loadProgram("vs_hdr_lum", "fs_hdr_lum"); bgfx::ProgramHandle lumAvgProgram = loadProgram("vs_hdr_lumavg", "fs_hdr_lumavg"); bgfx::ProgramHandle blurProgram = loadProgram("vs_hdr_blur", "fs_hdr_blur"); bgfx::ProgramHandle brightProgram = loadProgram("vs_hdr_bright", "fs_hdr_bright"); bgfx::ProgramHandle meshProgram = loadProgram("vs_hdr_mesh", "fs_hdr_mesh"); bgfx::ProgramHandle tonemapProgram = loadProgram("vs_hdr_tonemap", "fs_hdr_tonemap"); Mesh mesh; mesh.load("meshes/bunny.bin"); bgfx::RenderTargetHandle rt = bgfx::createRenderTarget(width, height, BGFX_RENDER_TARGET_COLOR_RGBA8|BGFX_RENDER_TARGET_DEPTH); bgfx::RenderTargetHandle lum[5]; lum[0] = bgfx::createRenderTarget(128, 128, BGFX_RENDER_TARGET_COLOR_RGBA8); lum[1] = bgfx::createRenderTarget( 64, 64, BGFX_RENDER_TARGET_COLOR_RGBA8); lum[2] = bgfx::createRenderTarget( 16, 16, BGFX_RENDER_TARGET_COLOR_RGBA8); lum[3] = bgfx::createRenderTarget( 4, 4, BGFX_RENDER_TARGET_COLOR_RGBA8); lum[4] = bgfx::createRenderTarget( 1, 1, BGFX_RENDER_TARGET_COLOR_RGBA8); bgfx::RenderTargetHandle bright; bright = bgfx::createRenderTarget(width/2, height/2, BGFX_RENDER_TARGET_COLOR_RGBA8); bgfx::RenderTargetHandle blur; blur = bgfx::createRenderTarget(width/8, height/8, BGFX_RENDER_TARGET_COLOR_RGBA8); FILE* file = fopen("font/droidsans.ttf", "rb"); uint32_t size = (uint32_t)fsize(file); void* data = malloc(size); size_t ignore = fread(data, 1, size, file); BX_UNUSED(ignore); fclose(file); imguiCreate(data, size); free(data); float speed = 0.37f; float middleGray = 0.18f; float white = 1.1f; float treshold = 1.5f; int32_t scrollArea = 0; uint32_t oldWidth = 0; uint32_t oldHeight = 0; entry::MouseState mouseState; float time = 0.0f; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { if (oldWidth != width || oldHeight != height) { // Recreate variable size render targets when resolution changes. oldWidth = width; oldHeight = height; bgfx::destroyRenderTarget(rt); bgfx::destroyRenderTarget(bright); bgfx::destroyRenderTarget(blur); rt = bgfx::createRenderTarget(width, height, BGFX_RENDER_TARGET_COLOR_RGBA8|BGFX_RENDER_TARGET_DEPTH); bright = bgfx::createRenderTarget(width/2, height/2, BGFX_RENDER_TARGET_COLOR_RGBA8); blur = bgfx::createRenderTarget(width/8, height/8, BGFX_RENDER_TARGET_COLOR_RGBA8); } imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) , 0 , width , height ); imguiBeginScrollArea("Settings", width - width / 5 - 10, 10, width / 5, height / 3, &scrollArea); imguiSeparatorLine(); imguiSlider("Speed", &speed, 0.0f, 1.0f, 0.01f); imguiSeparator(); imguiSlider("Middle gray", &middleGray, 0.1f, 1.0f, 0.01f); imguiSlider("White point", &white, 0.1f, 2.0f, 0.01f); imguiSlider("Treshold", &treshold, 0.1f, 2.0f, 0.01f); imguiEndScrollArea(); imguiEndFrame(); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; time += (float)(frameTime*speed/freq); bgfx::setUniform(u_time, &time); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/09-hdr"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Using multiple views and render targets."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); // Set views. bgfx::setViewRectMask(0x1f, 0, 0, width, height); bgfx::setViewRenderTargetMask(0x3, rt); bgfx::setViewRect(2, 0, 0, 128, 128); bgfx::setViewRenderTarget(2, lum[0]); bgfx::setViewRect(3, 0, 0, 64, 64); bgfx::setViewRenderTarget(3, lum[1]); bgfx::setViewRect(4, 0, 0, 16, 16); bgfx::setViewRenderTarget(4, lum[2]); bgfx::setViewRect(5, 0, 0, 4, 4); bgfx::setViewRenderTarget(5, lum[3]); bgfx::setViewRect(6, 0, 0, 1, 1); bgfx::setViewRenderTarget(6, lum[4]); bgfx::setViewRect(7, 0, 0, width/2, height/2); bgfx::setViewRenderTarget(7, bright); bgfx::setViewRect(8, 0, 0, width/8, height/8); bgfx::setViewRenderTarget(8, blur); bgfx::setViewRect(9, 0, 0, width, height); float view[16]; float proj[16]; mtxIdentity(view); mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransformMask(0 |(1<<0) |(1<<2) |(1<<3) |(1<<4) |(1<<5) |(1<<6) |(1<<7) |(1<<8) |(1<<9) , view , proj ); float at[3] = { 0.0f, 1.0f, 0.0f }; float eye[3] = { 0.0f, 1.0f, -2.5f }; float mtx[16]; mtxRotateXY(mtx , 0.0f , time ); float temp[4]; vec3MulMtx(temp, eye, mtx); mtxLookAt(view, temp, at); mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 1. bgfx::setViewTransformMask(1<<1, view, proj); bgfx::setUniform(u_mtx, mtx); // Render skybox into view 0. bgfx::setTexture(0, u_texCube, uffizi); bgfx::setProgram(skyProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad( (float)width, (float)height, true); bgfx::submit(0); // Render mesh into view 1 bgfx::setTexture(0, u_texCube, uffizi); mesh.submit(1, meshProgram, NULL); // Calculate luminance. setOffsets2x2Lum(u_offset, 128, 128); bgfx::setTexture(0, u_texColor, rt); bgfx::setProgram(lumProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad(128.0f, 128.0f, s_flipV); bgfx::submit(2); // Downscale luminance 0. setOffsets4x4Lum(u_offset, 128, 128); bgfx::setTexture(0, u_texColor, lum[0]); bgfx::setProgram(lumAvgProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad(64.0f, 64.0f, s_flipV); bgfx::submit(3); // Downscale luminance 1. setOffsets4x4Lum(u_offset, 64, 64); bgfx::setTexture(0, u_texColor, lum[1]); bgfx::setProgram(lumAvgProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad(16.0f, 16.0f, s_flipV); bgfx::submit(4); // Downscale luminance 2. setOffsets4x4Lum(u_offset, 16, 16); bgfx::setTexture(0, u_texColor, lum[2]); bgfx::setProgram(lumAvgProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad(4.0f, 4.0f, s_flipV); bgfx::submit(5); // Downscale luminance 3. setOffsets4x4Lum(u_offset, 4, 4); bgfx::setTexture(0, u_texColor, lum[3]); bgfx::setProgram(lumAvgProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad(1.0f, 1.0f, s_flipV); bgfx::submit(6); float tonemap[4] = { middleGray, square(white), treshold, 0.0f }; bgfx::setUniform(u_tonemap, tonemap); // Bright pass treshold is tonemap[3]. setOffsets4x4Lum(u_offset, width/2, height/2); bgfx::setTexture(0, u_texColor, rt); bgfx::setTexture(1, u_texLum, lum[4]); bgfx::setProgram(brightProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad( (float)width/2.0f, (float)height/2.0f, s_flipV); bgfx::submit(7); // Blur bright pass vertically. bgfx::setTexture(0, u_texColor, bright); bgfx::setProgram(blurProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad( (float)width/8.0f, (float)height/8.0f, s_flipV); bgfx::submit(8); // Blur bright pass horizontally, do tonemaping and combine. bgfx::setTexture(0, u_texColor, rt); bgfx::setTexture(1, u_texLum, lum[4]); bgfx::setTexture(2, u_texBlur, blur); bgfx::setProgram(tonemapProgram); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad( (float)width, (float)height, s_flipV); bgfx::submit(9); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } imguiDestroy(); // Cleanup. mesh.unload(); bgfx::destroyRenderTarget(lum[0]); bgfx::destroyRenderTarget(lum[1]); bgfx::destroyRenderTarget(lum[2]); bgfx::destroyRenderTarget(lum[3]); bgfx::destroyRenderTarget(lum[4]); bgfx::destroyRenderTarget(bright); bgfx::destroyRenderTarget(blur); bgfx::destroyRenderTarget(rt); bgfx::destroyProgram(meshProgram); bgfx::destroyProgram(skyProgram); bgfx::destroyProgram(tonemapProgram); bgfx::destroyProgram(lumProgram); bgfx::destroyProgram(lumAvgProgram); bgfx::destroyProgram(blurProgram); bgfx::destroyProgram(brightProgram); bgfx::destroyTexture(uffizi); bgfx::destroyUniform(u_time); bgfx::destroyUniform(u_texCube); bgfx::destroyUniform(u_texColor); bgfx::destroyUniform(u_texLum); bgfx::destroyUniform(u_texBlur); bgfx::destroyUniform(u_mtx); bgfx::destroyUniform(u_tonemap); bgfx::destroyUniform(u_offset); bgfx::destroyUniform(u_weight); // Shutdown bgfx. bgfx::shutdown(); return 0; }
// Entry point in the program int main(int argc, char **argv) { std::cout<<std::endl<<std::endl<<"________Template OpenGL3________"<<std::endl<<std::endl; //__________________________________________________________________________ // Application creation std::cout<<" Application creation"<<std::endl; Application * application=new Application(800, 600); //__________________________________________________________________________ // Scene creation std::cout<<" Scene creation"<<std::endl; Scene * scene=new Scene(800, 600); application->setScene(scene); GLfloat red[]= {1.0, 0.0, 0.0, 1.0}; scene->setDefaultColor(red); // Color for the objects drawn in the scene //__________________________________________________________________________ // Camera position and orientation std::cout<<" Camera settings"<<std::endl; scene->camera->c[2]=6.0; // Position of the camera scene->camera->c[1]=0.0; // Position of the camera scene->camera->c[0]=0.0; // Position of the camera scene->camera->updateView(); GLfloat c[]= {-0.2, 0.3, 0.1}; // Camera position GLfloat aim[]= {0.0, 0.0, 0.0}; // Where we look GLfloat up[]= {0.0, 1.0, 0.0}; // Vector pointing over the camera //scene->camera->lookAt(c, aim, up); //__________________________________________________________________________ // Creation of the shaders std::cout<<" Shaders reading, compiling and linking"<<std::endl; // Compilation and storage of the program std::vector<std::string> files; // The special shaders used for mac os are only necesary until Snow Leopard // From Leon on, mac os drivers version for Opengl is 3.2 // Therefore the shaders in folder oldGLSL become out-of-date // One very simple shader (one color everywhere on the object) files.push_back("../shaders/simpleShader.glsl"); GLuint simpleShaderID=loadProgram(files); files.pop_back(); scene->setDefaultShaderID(simpleShaderID); // One coloring shader (colors per vertex) files.push_back("../shaders/colorShader.glsl"); GLuint colorShaderID=loadProgram(files); files.pop_back(); // One lighting shader #ifdef APPLE files.push_back("../shaders/oldGLSL/shaderTools.glsl"); files.push_back("../shaders/oldGLSL/lightingShader.glsl"); #else files.push_back("../shaders/shaderTools.glsl"); files.push_back("../shaders/lightingShader.glsl"); #endif GLuint lightingShaderID=loadProgram(files); files.pop_back(); scene->setDefaultShaderID(lightingShaderID); // Uniforms filling glUseProgram(lightingShaderID); // Material creation and to shader GLfloat ambient[]= {1.0, 1.0, 1.0, 1.0}; GLfloat ka=0.01; GLfloat diffuse[]= {1.0, 1.0, 1.0, 1.0}; GLfloat kd=1.0; GLfloat specular[]= {1.0, 1.0, 1.0, 1.0}; GLfloat ks=2.0; GLfloat shininess=5.0; setMaterialInShader(lightingShaderID, ambient, diffuse, specular, ka, kd, ks, shininess); files.push_back("../shaders/persoShader.glsl"); GLuint persoShaderID=loadProgram(files); files.pop_back(); // Light creation GLfloat lightPosition[]= {1.0, 1.0, 1.0, 1.0}; GLfloat lightPower=2.0; scene->setLight(lightPosition, lightPower); // One texture and Phong shader #ifdef __APPLE__ files.push_back("../shaders/oldGLSL/lightingTexturingShader.glsl"); #else files.push_back("../shaders/lightingTexturingShader.glsl"); #endif GLuint lightingTextureShaderID=loadProgram(files); files.pop_back(); glUseProgram(lightingTextureShaderID); setMaterialInShader(lightingTextureShaderID, ambient, diffuse, specular, ka, kd, ks, shininess); setTextureUnitsInShader(lightingTextureShaderID); //__________________________________________________________________________ // Creation of the objects to store std::cout<<" Generic objects creation and storage :"<<std::endl; // Définition du repère Object * objectAxis=new Object(GL_LINES); GLuint storedObjectAxisID=scene->storeObject(objectAxis); // Définition boundingBox Object * objectBB=new Object(GL_TRIANGLES); GLuint storedObjectBBID=scene->storeObject(objectBB); // Définition de la cible Object * objectCible=new Object(GL_LINES); GLuint storedObjectCibleID=scene->storeObject(objectCible); // Environnement Object * objectLaby=new Object(GL_TRIANGLES); GLuint storedObjectLaby=scene->storeObject(objectLaby); bool smoothObjectFlag=true; GLuint houseTextureDiffuseID=loadTexture("../textures/mur_contour.ppm"); GLuint houseTextureSpecularID=loadTexture("../textures/mur_contour.ppm"); //portal Object * objectPortal = new Object(GL_TRIANGLES); GLuint storedObjectPortal=scene->storeObject(objectPortal); //std::cout<<"IIIIIDDDDDD"<<storedObjectPortal<<std::endl; GLuint portalTextureDiffuseID=loadTexture("../textures/mur_contour.ppm"); GLuint portalTextureSpecularID=loadTexture("../textures/mur_contour.ppm"); /*Object * objectTr=new Object(GL_TRIANGLES); GLuint storedObjectTrID=scene->storeObject(objectTr);*/ //__________________________________________________________________________ // Object building std::cout<<" Generic objects building :"<<std::endl; // Construction du repère buildAxis(objectAxis); //Construction boundingBox //buildCube(objectBB); // Construction de la cible buildCircle(objectCible, 0.3, 20); //environnement std::string fileName="../objs/contour.obj"; buildObjectGeometryFromOBJ(objectLaby, fileName, smoothObjectFlag, 10,10,10); /*std::cout << indicesObj[3] << " " << indicesObj[4] << indicesObj[5] << std::endl; std::cout << verticesObj[11*4] << " " << verticesObj[11*4+1] << " " << verticesObj[11*4+2] << " " << verticesObj[11*4+3] << std::endl; std::cout << verticesObj[10*4] << " " << verticesObj[10*4+1] << " " << verticesObj[10*4+2] << " " << verticesObj[10*4+3] << std::endl; std::cout << verticesObj[4] << " " << verticesObj[4+1] << " " << verticesObj[4+2] << " " << verticesObj[4+3] << std::endl << std::endl; std::cout << verticesObj[4] << " " << verticesObj[4+1] << " " << verticesObj[4+2] << " " << verticesObj[4+3] << std::endl; std::cout << verticesObj[0] << " " << verticesObj[1] << " " << verticesObj[2] << " " << verticesObj[3] << std::endl; std::cout << verticesObj[11*4] << " " << verticesObj[11*4+1] << " " << verticesObj[11*4+2] << " " << verticesObj[11*4+3] << std::endl << std::endl; for (int i=0; i<24; ++i) std::cout << application->objVertices[i] << " " ; std::cout << std::endl; std::string fileNamePortal="../objs/portail.obj"; std::vector<GLfloat> verticesObjPortal; std::vector<GLuint> indicesObjPortal; std::vector<GLfloat> normalsObjPortal; buildObjectGeometryFromOBJ(objectPortal, fileNamePortal, smoothObjectFlag, verticesObjPortal, indicesObjPortal, normalsObjPortal);*/ /*std::string fileNamePortal="../objs/portail.obj"; std::vector<GLfloat> verticesObjPortal; std::vector<GLuint> indicesObjPortal; std::vector<GLfloat> normalsObjPortal; buildObjectGeometryFromOBJ(objectPortal, fileNamePortal, smoothObjectFlag, verticesObjPortal, indicesObjPortal, normalsObjPortal);*/ //__________________________________________________________________________ // Objects we want to see std::cout<<" Objects to draw setting"<<std::endl; //axis GLuint axisID=scene->addObjectToDraw(storedObjectAxisID); scene->setDrawnObjectShaderID(axisID, lightingShaderID); //BoundingBox GLuint BBID=scene->addObjectToDraw(storedObjectBBID); //scene->setDrawnObjectShaderID(BBID, lightingShaderID); GLfloat yellow[4]= {0.0, 0.8, 0.4, 1.0}; scene->setDrawnObjectColor(BBID, yellow); //cible GLuint cibleID=scene->addObjectToDraw(storedObjectCibleID); scene->setDrawnObjectShaderID(cibleID, lightingShaderID); GLfloat blue[4]= {0.0, 0.3, 0.7, 1.0}; scene->setDrawnObjectColor(cibleID, blue); //environnement GLfloat S[16]; GLfloat s[3] = {3.0, 2.0, 3.0} ; setToScale(S, s); GLuint labyID=scene->addObjectToDraw(storedObjectLaby); //scene->setDrawnObjectModel(labyID, S); scene->setDrawnObjectColor(labyID, red); scene->setDrawnObjectShaderID(labyID, lightingShaderID); //std::cout<<"ID SHADER :"<<lightingShaderID<<std::endl; /*cible GLuint trID=scene->addObjectToDraw(storedObjectTrID); scene->setDrawnObjectShaderID(trID, lightingShaderID); GLfloat zarb[4]={0.4, 0.7, 0.2, 1.0}; scene->setDrawnObjectColor(trID, zarb);*/ std::cout<<scene->nbStoredObjects<<std::endl; //__________________________________________________________________________ // Other informations // Background color creation GLfloat black[]= {0.0, 0.0, 0.0, 1.0}; application->setBackgroundColor(black); //__________________________________________________________________________ // Errors checking std::cout<<" Errors cheking before the loop"<<std::endl; printGlErrors(); std::cout<<std::endl; //__________________________________________________________________________ // Loop start ! std::cout<<" Looping !! "<<std::endl; application->lastStartTime=getTime(); application->initTimers(); application->loop(); printGlErrors(); std::cout<<std::endl; //__________________________________________________________________________ // Cleaning and finishing std::cout<<" Cleaning before leaving"<<std::endl; delete application; return 0; }
// FIXME: Parallaction_br::parseLocation() is now a verbatim copy of the same routine from Parallaction_ns. void Parallaction_br::parseLocation(const char *filename) { debugC(1, kDebugParser, "parseLocation('%s')", filename); // find a new available slot allocateLocationSlot(filename); Script *script = _disk->loadLocation(filename); // parse the text file LocationParserOutput_br out; _locationParser->parse(script, &out); assert(out._info); delete script; bool visited = getLocationFlags() & kFlagsVisited; // load background, mask and path _disk->loadScenery(*out._info, out._backgroundName.empty() ? 0 : out._backgroundName.c_str(), out._maskName.empty() ? 0 : out._maskName.c_str(), out._pathName.empty() ? 0 : out._pathName.c_str()); // assign background _gfx->setBackground(kBackgroundLocation, out._info); // process zones ZoneList::iterator zit = _location._zones.begin(); for ( ; zit != _location._zones.end(); ++zit) { ZonePtr z = *zit; // restore the flags if the location has already been visited restoreOrSaveZoneFlags(z, visited); // (re)link the bounding animation if needed if (z->_flags & kFlagsAnimLinked) { z->_linkedAnim = _location.findAnimation(z->_linkedName.c_str()); } bool visible = (z->_flags & kFlagsRemove) == 0; if (visible) { showZone(z, visible); } } // load the character (must be done before animations are processed) if (!out._characterName.empty()) { changeCharacter(out._characterName.c_str()); } // process animations AnimationList::iterator ait = _location._animations.begin(); for ( ; ait != _location._animations.end(); ++ait) { // restore the flags if the location has already been visited restoreOrSaveZoneFlags(*ait, visited); // load the script if ((*ait)->_scriptName) { loadProgram(*ait, (*ait)->_scriptName); } } debugC(1, kDebugParser, "parseLocation('%s') done", filename); return; }
bool tf3Synth::loadProgram() { return loadProgram(curProgram); }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle u_stipple = bgfx::createUniform("u_stipple", bgfx::UniformType::Uniform3fv); bgfx::UniformHandle u_texStipple = bgfx::createUniform("u_texStipple", bgfx::UniformType::Uniform1iv); bgfx::ProgramHandle program = loadProgram("vs_tree", "fs_tree"); bgfx::TextureHandle textureLeafs = loadTexture("leafs1.dds"); bgfx::TextureHandle textureBark = loadTexture("bark1.dds"); bgfx::TextureHandle textureStipple; const bgfx::Memory* stipple = bgfx::alloc(8*4); memset(stipple->data, 0, stipple->size); for (uint32_t ii = 0; ii < 32; ++ii) { stipple->data[knightTour[ii].m_y * 8 + knightTour[ii].m_x] = ii*4; } textureStipple = bgfx::createTexture2D(8, 4, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIN_POINT, stipple); Mesh* meshTop[3] = { meshLoad("meshes/tree1b_lod0_1.bin"), meshLoad("meshes/tree1b_lod1_1.bin"), meshLoad("meshes/tree1b_lod2_1.bin"), }; Mesh* meshTrunk[3] = { meshLoad("meshes/tree1b_lod0_2.bin"), meshLoad("meshes/tree1b_lod1_2.bin"), meshLoad("meshes/tree1b_lod2_2.bin"), }; // Imgui. void* data = load("font/droidsans.ttf"); imguiCreate(data); free(data); const uint64_t stateCommon = 0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_CULL_CCW | BGFX_STATE_MSAA ; const uint64_t stateTransparent = stateCommon | BGFX_STATE_BLEND_ALPHA ; const uint64_t stateOpaque = stateCommon | BGFX_STATE_DEPTH_WRITE ; int32_t scrollArea = 0; bool transitions = true; int transitionFrame = 0; int currLOD = 0; int targetLOD = 0; float at[3] = { 0.0f, 1.0f, 0.0f }; float eye[3] = { 0.0f, 1.0f, -2.0f }; entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) , 0 , width , height ); imguiBeginScrollArea("Toggle transitions", width - width / 5 - 10, 10, width / 5, height / 6, &scrollArea); imguiSeparatorLine(); if (imguiButton(transitions ? "ON" : "OFF") ) { transitions = !transitions; } static float distance = 2.0f; imguiSlider("Distance", distance, 2.0f, 6.0f, .01f); imguiEndScrollArea(); imguiEndFrame(); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/12-lod"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Mesh LOD transitions."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); bgfx::dbgTextPrintf(0, 4, transitions ? 0x2f : 0x1f, transitions ? "Transitions on" : "Transitions off"); eye[2] = -distance; float view[16]; float proj[16]; bx::mtxLookAt(view, eye, at); bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); float mtx[16]; bx::mtxScale(mtx, 0.1f, 0.1f, 0.1f); float stipple[3]; float stippleInv[3]; const int currentLODframe = transitions ? 32-transitionFrame : 32; const int mainLOD = transitions ? currLOD : targetLOD; stipple[0] = 0.0f; stipple[1] = -1.0f; stipple[2] = (float(currentLODframe)*4.0f/255.0f) - (1.0f/255.0f); stippleInv[0] = (float(31)*4.0f/255.0f); stippleInv[1] = 1.0f; stippleInv[2] = (float(transitionFrame)*4.0f/255.0f) - (1.0f/255.0f); bgfx::setTexture(0, u_texColor, textureBark); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stipple); meshSubmit(meshTrunk[mainLOD], 0, program, mtx, stateOpaque); bgfx::setTexture(0, u_texColor, textureLeafs); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stipple); meshSubmit(meshTop[mainLOD], 0, program, mtx, stateTransparent); if (transitions && (transitionFrame != 0) ) { bgfx::setTexture(0, u_texColor, textureBark); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stippleInv); meshSubmit(meshTrunk[targetLOD], 0, program, mtx, stateOpaque); bgfx::setTexture(0, u_texColor, textureLeafs); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stippleInv); meshSubmit(meshTop[targetLOD], 0, program, mtx, stateTransparent); } int lod = 0; if (eye[2] < -2.5f) { lod = 1; } if (eye[2] < -5.0f) { lod = 2; } if (targetLOD!=lod) { if (targetLOD==currLOD) { targetLOD = lod; } } if (currLOD != targetLOD) { transitionFrame++; } if (transitionFrame>32) { currLOD = targetLOD; transitionFrame = 0; } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } imguiDestroy(); for (uint32_t ii = 0; ii < 3; ++ii) { meshUnload(meshTop[ii]); meshUnload(meshTrunk[ii]); } // Cleanup. bgfx::destroyProgram(program); bgfx::destroyUniform(u_texColor); bgfx::destroyUniform(u_stipple); bgfx::destroyUniform(u_texStipple); bgfx::destroyTexture(textureStipple); bgfx::destroyTexture(textureLeafs); bgfx::destroyTexture(textureBark); // Shutdown bgfx. bgfx::shutdown(); return 0; }
void openCLNR (unsigned char* bufIn, unsigned char* bufOut, int* info) { LOGI("\n\nStart openCLNR (i.e., OpenCL on the GPU)"); int width = info[0]; int height = info[1]; unsigned int imageSize = width * height * 4 * sizeof(cl_uchar); cl_int err = CL_SUCCESS; try { std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); if (platforms.size() == 0) { std::cout << "Platform size 0\n"; return; } cl_context_properties properties[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(), 0}; cl::Context context(CL_DEVICE_TYPE_GPU, properties); std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>(); cl::CommandQueue queue(context, devices[0], 0, &err); std::string kernelSource = loadProgram("/data/data/com.nkt.compute/app_execdir/bilateralKernel.cl"); cl::Program::Sources source(1, std::make_pair(kernelSource.c_str(), kernelSource.length()+1)); cl::Program program(context, source); const char *options = "-cl-fast-relaxed-math"; program.build(devices, options); cl::Kernel kernel(program, "bilateralFilterKernel", &err); cl::Buffer bufferIn = cl::Buffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, imageSize, (void *) &bufIn[0], &err); cl::Buffer bufferOut = cl::Buffer(context, CL_MEM_READ_WRITE | CL_MEM_USE_HOST_PTR, imageSize, (void *) &bufOut[0], &err); kernel.setArg(0,bufferIn); kernel.setArg(1,bufferOut); kernel.setArg(2,width); kernel.setArg(3,height); cl::Event event; clock_t startTimer1, stopTimer1; startTimer1=clock(); //one time queue.enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(width,height), cl::NullRange, NULL, &event); //swap in and out buffer pointers and run a 2nd time kernel.setArg(0,bufferOut); kernel.setArg(1,bufferIn); queue.enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(width,height), cl::NullRange, NULL, &event); //swap in and out buffer pointers and run a 3rd time kernel.setArg(0,bufferIn); kernel.setArg(1,bufferOut); queue.enqueueNDRangeKernel( kernel, cl::NullRange, cl::NDRange(width,height), cl::NullRange, NULL, &event); queue.finish(); stopTimer1 = clock(); double elapse = 1000.0* (double)(stopTimer1 - startTimer1)/(double)CLOCKS_PER_SEC; info[2] = (int)elapse; LOGI("OpenCL code on the GPU took %g ms\n\n", 1000.0* (double)(stopTimer1 - startTimer1)/(double)CLOCKS_PER_SEC) ; queue.enqueueReadBuffer(bufferOut, CL_TRUE, 0, imageSize, bufOut); } catch (cl::Error err) { LOGE("ERROR: %s\n", err.what()); } return; }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Create vertex stream declaration. PosTexcoordVertex::init(); bgfx::TextureHandle textures[] = { loadTexture("texture_compression_bc1.dds", BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP), loadTexture("texture_compression_bc2.dds", BGFX_TEXTURE_U_CLAMP), loadTexture("texture_compression_bc3.dds", BGFX_TEXTURE_V_CLAMP), loadTexture("texture_compression_etc1.ktx"), loadTexture("texture_compression_etc2.ktx"), loadTexture("texture_compression_ptc12.pvr"), loadTexture("texture_compression_ptc14.pvr"), loadTexture("texture_compression_ptc22.pvr"), loadTexture("texture_compression_ptc24.pvr"), }; const bgfx::Memory* mem8 = bgfx::alloc(32*32*32); const bgfx::Memory* mem16f = bgfx::alloc(32*32*32*2); const bgfx::Memory* mem32f = bgfx::alloc(32*32*32*4); for (uint8_t zz = 0; zz < 32; ++zz) { for (uint8_t yy = 0; yy < 32; ++yy) { for (uint8_t xx = 0; xx < 32; ++xx) { const uint32_t offset = ( (zz*32+yy)*32+xx); const uint32_t val = xx ^ yy ^ zz; mem8->data[offset] = val<<3; *(uint16_t*)&mem16f->data[offset*2] = bx::halfFromFloat( (float)val/32.0f); *(float*)&mem32f->data[offset*4] = (float)val/32.0f; } } } const bgfx::Caps* caps = bgfx::getCaps(); const bool texture3DSupported = !!(caps->supported & BGFX_CAPS_TEXTURE_3D); uint32_t numTextures3d = 0; bgfx::TextureHandle textures3d[3] = {}; if (texture3DSupported) { if (0 != (BGFX_CAPS_FORMAT_TEXTURE_COLOR & caps->formats[bgfx::TextureFormat::R8]) ) { textures3d[numTextures3d++] = bgfx::createTexture3D(32, 32, 32, 0, bgfx::TextureFormat::R8, BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP|BGFX_TEXTURE_W_CLAMP, mem8); } if (0 != (BGFX_CAPS_FORMAT_TEXTURE_COLOR & caps->formats[bgfx::TextureFormat::R16F]) ) { textures3d[numTextures3d++] = bgfx::createTexture3D(32, 32, 32, 0, bgfx::TextureFormat::R16F, BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP|BGFX_TEXTURE_W_CLAMP, mem16f); } if (0 != (BGFX_CAPS_FORMAT_TEXTURE_COLOR & caps->formats[bgfx::TextureFormat::R32F]) ) { textures3d[numTextures3d++] = bgfx::createTexture3D(32, 32, 32, 0, bgfx::TextureFormat::R32F, BGFX_TEXTURE_U_CLAMP|BGFX_TEXTURE_V_CLAMP|BGFX_TEXTURE_W_CLAMP, mem32f); } } // Create static vertex buffer. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ), PosTexcoordVertex::ms_decl); // Create static index buffer. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); // Create texture sampler uniforms. bgfx::UniformHandle u_texCube = bgfx::createUniform("u_texCube", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle u_time = bgfx::createUniform("u_time", bgfx::UniformType::Uniform1f); bgfx::ProgramHandle program = loadProgram("vs_update", "fs_update"); bgfx::ProgramHandle programCmp = loadProgram("vs_update", "fs_update_cmp"); bgfx::ProgramHandle program3d = BGFX_INVALID_HANDLE; if (texture3DSupported) { program3d = loadProgram("vs_update", "fs_update_3d"); } const uint32_t textureSide = 2048; bgfx::TextureHandle textureCube = bgfx::createTextureCube(textureSide, 1 , bgfx::TextureFormat::BGRA8 , BGFX_TEXTURE_MIN_POINT|BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIP_POINT ); const uint32_t texture2dSize = 256; bgfx::TextureHandle texture2d = bgfx::createTexture2D(texture2dSize, texture2dSize, 1 , bgfx::TextureFormat::BGRA8 , BGFX_TEXTURE_MIN_POINT|BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIP_POINT ); uint8_t* texture2dData = (uint8_t*)malloc(texture2dSize*texture2dSize*4); uint8_t rr = rand()%255; uint8_t gg = rand()%255; uint8_t bb = rand()%255; int64_t updateTime = 0; RectPackCubeT<256> cube(textureSide); uint32_t hit = 0; uint32_t miss = 0; std::list<PackCube> quads; int64_t timeOffset = bx::getHPCounter(); while (!entry::processEvents(width, height, debug, reset) ) { // Set view 0 and 1 viewport. bgfx::setViewRect(0, 0, 0, width, height); bgfx::setViewRect(1, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const int64_t freq = bx::getHPFrequency(); const double toMs = 1000.0/double(freq); float time = (float)( (now - timeOffset)/double(bx::getHPFrequency() ) ); bgfx::setUniform(u_time, &time); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/08-update"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Updating textures."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); if (now > updateTime) { PackCube face; uint32_t bw = bx::uint16_max(1, rand()%(textureSide/4) ); uint32_t bh = bx::uint16_max(1, rand()%(textureSide/4) ); if (cube.find(bw, bh, face) ) { quads.push_back(face); ++hit; const Pack2D& rect = face.m_rect; updateTextureCubeRectBgra8(textureCube, face.m_side, rect.m_x, rect.m_y, rect.m_width, rect.m_height, rr, gg, bb); rr = rand()%255; gg = rand()%255; bb = rand()%255; } else { ++miss; for (uint32_t ii = 0, num = bx::uint32_min(10, (uint32_t)quads.size() ); ii < num; ++ii) { cube.clear(quads.front() ); quads.pop_front(); } } { // Fill rect. const uint32_t pitch = texture2dSize*4; const uint16_t tw = rand()%texture2dSize; const uint16_t th = rand()%texture2dSize; const uint16_t tx = rand()%(texture2dSize-tw); const uint16_t ty = rand()%(texture2dSize-th); uint8_t* dst = &texture2dData[(ty*texture2dSize+tx)*4]; uint8_t* next = dst + pitch; // Using makeRef to pass texture memory without copying. const bgfx::Memory* mem = bgfx::makeRef(dst, tw*th*4); for (uint32_t yy = 0; yy < th; ++yy, dst = next, next += pitch) { for (uint32_t xx = 0; xx < tw; ++xx, dst += 4) { dst[0] = bb; dst[1] = gg; dst[2] = rr; dst[3] = 255; } } // Pitch here makes possible to pass data from source to destination // without need for textures and allocated memory to be the same size. bgfx::updateTexture2D(texture2d, 0, tx, ty, tw, th, mem, pitch); } } bgfx::dbgTextPrintf(0, 4, 0x0f, "hit: %d, miss %d", hit, miss); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -5.0f }; float view[16]; float proj[16]; bx::mtxLookAt(view, eye, at); bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); float mtx[16]; bx::mtxRotateXY(mtx, time, time*0.37f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(program); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Bind texture. bgfx::setTexture(0, u_texCube, textureCube); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 0. bgfx::submit(0); // Set view and projection matrix for view 1. const float aspectRatio = float(height)/float(width); const float size = 10.0f; bx::mtxOrtho(proj, -size, size, size*aspectRatio, -size*aspectRatio, 0.0f, 1000.0f); bgfx::setViewTransform(1, NULL, proj); bx::mtxTranslate(mtx, -8.0f - BX_COUNTOF(textures)*0.1f*0.5f, 1.9f, 0.0f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(programCmp); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Bind texture. bgfx::setTexture(0, u_texColor, texture2d); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 1. bgfx::submit(1); const float xpos = -8.0f - BX_COUNTOF(textures)*0.1f*0.5f; for (uint32_t ii = 0; ii < BX_COUNTOF(textures); ++ii) { bx::mtxTranslate(mtx, xpos + ii*2.1f, 4.0f, 0.0f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(programCmp); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh, 0, 6); // Bind texture. bgfx::setTexture(0, u_texColor, textures[ii]); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 1. bgfx::submit(1); } for (uint32_t ii = 0; ii < numTextures3d; ++ii) { bx::mtxTranslate(mtx, xpos + ii*2.1f, -4.0f, 0.0f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(program3d); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh, 0, 6); // Bind texture. bgfx::setTexture(0, u_texColor, textures3d[ii]); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 1. bgfx::submit(1); } for (uint32_t ii = 0; ii < 3; ++ii) { bx::mtxTranslate(mtx, xpos + 8*2.1f, -4.0f + ii*2.1f, 0.0f); // Set model matrix for rendering. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(programCmp); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh, 24, 4); bgfx::setIndexBuffer(ibh, 0, 6); // Bind texture. bgfx::setTexture(0, u_texColor, textures[ii]); // Set render states. bgfx::setState(BGFX_STATE_DEFAULT); // Submit primitive for rendering to view 1. bgfx::submit(1); } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // texture2dData is managed from main thread, and it's passed to renderer // just as MemoryRef. At this point render might be using it. We must wait // previous frame to finish before we can free it. bgfx::frame(); // Cleanup. free(texture2dData); for (uint32_t ii = 0; ii < BX_COUNTOF(textures); ++ii) { bgfx::destroyTexture(textures[ii]); } for (uint32_t ii = 0; ii < numTextures3d; ++ii) { bgfx::destroyTexture(textures3d[ii]); } bgfx::destroyTexture(texture2d); bgfx::destroyTexture(textureCube); bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); if (bgfx::isValid(program3d) ) { bgfx::destroyProgram(program3d); } bgfx::destroyProgram(programCmp); bgfx::destroyProgram(program); bgfx::destroyUniform(u_time); bgfx::destroyUniform(u_texColor); bgfx::destroyUniform(u_texCube); // Shutdown bgfx. bgfx::shutdown(); return 0; }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set clear color palette for index 0 bgfx::setClearColor(0, UINT32_C(0x00000000) ); // Set clear color palette for index 1 bgfx::setClearColor(1, UINT32_C(0x303030ff) ); // Set geometry pass view clear state. bgfx::setViewClear(RENDER_PASS_GEOMETRY_ID , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 1.0f , 0 , 1 ); // Set light pass view clear state. bgfx::setViewClear(RENDER_PASS_LIGHT_ID , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 1.0f , 0 , 0 ); // Create vertex stream declaration. PosNormalTangentTexcoordVertex::init(); PosTexCoord0Vertex::init(); DebugVertex::init(); calcTangents(s_cubeVertices , BX_COUNTOF(s_cubeVertices) , PosNormalTangentTexcoordVertex::ms_decl , s_cubeIndices , BX_COUNTOF(s_cubeIndices) ); // Create static vertex buffer. bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer( bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) ) , PosNormalTangentTexcoordVertex::ms_decl ); // Create static index buffer. bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) ); // Create texture sampler uniforms. bgfx::UniformHandle s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle s_texNormal = bgfx::createUniform("s_texNormal", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle s_light = bgfx::createUniform("s_light", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Uniform4x4fv); bgfx::UniformHandle u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Uniform4fv); bgfx::UniformHandle u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Uniform4fv); // Create program from shaders. bgfx::ProgramHandle geomProgram = loadProgram("vs_deferred_geom", "fs_deferred_geom"); bgfx::ProgramHandle lightProgram = loadProgram("vs_deferred_light", "fs_deferred_light"); bgfx::ProgramHandle combineProgram = loadProgram("vs_deferred_combine", "fs_deferred_combine"); bgfx::ProgramHandle debugProgram = loadProgram("vs_deferred_debug", "fs_deferred_debug"); bgfx::ProgramHandle lineProgram = loadProgram("vs_deferred_debug_line", "fs_deferred_debug_line"); // Load diffuse texture. bgfx::TextureHandle textureColor = loadTexture("fieldstone-rgba.dds"); // Load normal texture. bgfx::TextureHandle textureNormal = loadTexture("fieldstone-n.dds"); bgfx::TextureHandle gbufferTex[3] = { BGFX_INVALID_HANDLE, BGFX_INVALID_HANDLE, BGFX_INVALID_HANDLE }; bgfx::FrameBufferHandle gbuffer = BGFX_INVALID_HANDLE; bgfx::FrameBufferHandle lightBuffer = BGFX_INVALID_HANDLE; void* data = load("font/droidsans.ttf"); imguiCreate(data); free(data); const int64_t timeOffset = bx::getHPCounter(); const bgfx::RendererType::Enum renderer = bgfx::getRendererType(); const float texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f; const bool originBottomLeft = bgfx::RendererType::OpenGL == renderer || bgfx::RendererType::OpenGLES == renderer; // Get renderer capabilities info. const bgfx::Caps* caps = bgfx::getCaps(); uint32_t oldWidth = 0; uint32_t oldHeight = 0; uint32_t oldReset = reset; int32_t scrollArea = 0; int32_t numLights = 512; float lightAnimationSpeed = 0.3f; bool animateMesh = true; bool showScissorRects = false; bool showGBuffer = true; float view[16]; float initialPos[3] = { 0.0f, 0.0f, -15.0f }; cameraCreate(); cameraSetPosition(initialPos); cameraSetVerticalAngle(0.0f); cameraGetViewMtx(view); entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; const float deltaTime = float(frameTime/freq); float time = (float)( (now-timeOffset)/freq); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/21-deferred"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: MRT rendering and deferred shading."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); if (2 > caps->maxFBAttachments) { // When multiple render targets (MRT) is not supported by GPU, // implement alternative code path that doesn't use MRT. bool blink = uint32_t(time*3.0f)&1; bgfx::dbgTextPrintf(0, 5, blink ? 0x1f : 0x01, " MRT not supported by GPU. "); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); } else { if (oldWidth != width || oldHeight != height || oldReset != reset || !bgfx::isValid(gbuffer) ) { // Recreate variable size render targets when resolution changes. oldWidth = width; oldHeight = height; oldReset = reset; if (bgfx::isValid(gbuffer) ) { bgfx::destroyFrameBuffer(gbuffer); } const uint32_t samplerFlags = 0 | BGFX_TEXTURE_RT | BGFX_TEXTURE_MIN_POINT | BGFX_TEXTURE_MAG_POINT | BGFX_TEXTURE_MIP_POINT | BGFX_TEXTURE_U_CLAMP | BGFX_TEXTURE_V_CLAMP ; gbufferTex[0] = bgfx::createTexture2D(width, height, 1, bgfx::TextureFormat::BGRA8, samplerFlags); gbufferTex[1] = bgfx::createTexture2D(width, height, 1, bgfx::TextureFormat::BGRA8, samplerFlags); gbufferTex[2] = bgfx::createTexture2D(width, height, 1, bgfx::TextureFormat::D24, samplerFlags); gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(gbufferTex), gbufferTex, true); if (bgfx::isValid(lightBuffer) ) { bgfx::destroyFrameBuffer(lightBuffer); } lightBuffer = bgfx::createFrameBuffer(width, height, bgfx::TextureFormat::BGRA8, samplerFlags); } imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) , 0 , width , height ); imguiBeginScrollArea("Settings", width - width / 5 - 10, 10, width / 5, height / 3, &scrollArea); imguiSeparatorLine(); imguiSlider("Num lights", numLights, 1, 2048); if (imguiCheck("Show G-Buffer.", showGBuffer) ) { showGBuffer = !showGBuffer; } if (imguiCheck("Show light scissor.", showScissorRects) ) { showScissorRects = !showScissorRects; } if (imguiCheck("Animate mesh.", animateMesh) ) { animateMesh = !animateMesh; } imguiSlider("Lights animation speed", lightAnimationSpeed, 0.0f, 0.4f, 0.01f); imguiEndScrollArea(); imguiEndFrame(); // Update camera. cameraUpdate(deltaTime, mouseState.m_mx, mouseState.m_my, !!mouseState.m_buttons[entry::MouseButton::Right]); cameraGetViewMtx(view); // Setup views float vp[16]; float invMvp[16]; { bgfx::setViewRectMask(0 | RENDER_PASS_GEOMETRY_BIT | RENDER_PASS_LIGHT_BIT | RENDER_PASS_COMBINE_BIT | RENDER_PASS_DEBUG_LIGHTS_BIT | RENDER_PASS_DEBUG_GBUFFER_BIT , 0, 0, width, height ); bgfx::setViewFrameBuffer(RENDER_PASS_LIGHT_ID, lightBuffer); float proj[16]; bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); bgfx::setViewFrameBuffer(RENDER_PASS_GEOMETRY_ID, gbuffer); bgfx::setViewTransform(RENDER_PASS_GEOMETRY_ID, view, proj); bx::mtxMul(vp, view, proj); bx::mtxInverse(invMvp, vp); bx::mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f); bgfx::setViewTransformMask(0 | RENDER_PASS_LIGHT_BIT | RENDER_PASS_COMBINE_BIT , NULL, proj ); const float aspectRatio = float(height)/float(width); const float size = 10.0f; bx::mtxOrtho(proj, -size, size, size*aspectRatio, -size*aspectRatio, 0.0f, 1000.0f); bgfx::setViewTransform(RENDER_PASS_DEBUG_GBUFFER_ID, NULL, proj); bx::mtxOrtho(proj, 0.0f, (float)width, 0.0f, (float)height, 0.0f, 1000.0f); bgfx::setViewTransform(RENDER_PASS_DEBUG_LIGHTS_ID, NULL, proj); } const uint32_t dim = 11; const float offset = (float(dim-1) * 3.0f) * 0.5f; // Draw into geometry pass. for (uint32_t yy = 0; yy < dim; ++yy) { for (uint32_t xx = 0; xx < dim; ++xx) { float mtx[16]; if (animateMesh) { bx::mtxRotateXY(mtx, time*1.023f + xx*0.21f, time*0.03f + yy*0.37f); } else { bx::mtxIdentity(mtx); } mtx[12] = -offset + float(xx)*3.0f; mtx[13] = -offset + float(yy)*3.0f; mtx[14] = 0.0f; // Set transform for draw call. bgfx::setTransform(mtx); // Set vertex and fragment shaders. bgfx::setProgram(geomProgram); // Set vertex and index buffer. bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh); // Bind textures. bgfx::setTexture(0, s_texColor, textureColor); bgfx::setTexture(1, s_texNormal, textureNormal); // Set render states. bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_DEPTH_WRITE | BGFX_STATE_DEPTH_TEST_LESS | BGFX_STATE_MSAA ); // Submit primitive for rendering to view 0. bgfx::submit(RENDER_PASS_GEOMETRY_ID); } } // Draw lights into light buffer. for (int32_t light = 0; light < numLights; ++light) { Sphere lightPosRadius; float lightTime = time * lightAnimationSpeed * (sin(light/float(numLights) * float(M_PI_2) ) * 0.5f + 0.5f); lightPosRadius.m_center[0] = sin( ( (lightTime + light*0.47f) + float(M_PI_2)*1.37f ) )*offset; lightPosRadius.m_center[1] = cos( ( (lightTime + light*0.69f) + float(M_PI_2)*1.49f ) )*offset; lightPosRadius.m_center[2] = sin( ( (lightTime + light*0.37f) + float(M_PI_2)*1.57f ) )*2.0f; lightPosRadius.m_radius = 2.0f; Aabb aabb; sphereToAabb(aabb, lightPosRadius); float box[8][3] = { { aabb.m_min[0], aabb.m_min[1], aabb.m_min[2] }, { aabb.m_min[0], aabb.m_min[1], aabb.m_max[2] }, { aabb.m_min[0], aabb.m_max[1], aabb.m_min[2] }, { aabb.m_min[0], aabb.m_max[1], aabb.m_max[2] }, { aabb.m_max[0], aabb.m_min[1], aabb.m_min[2] }, { aabb.m_max[0], aabb.m_min[1], aabb.m_max[2] }, { aabb.m_max[0], aabb.m_max[1], aabb.m_min[2] }, { aabb.m_max[0], aabb.m_max[1], aabb.m_max[2] }, }; float xyz[3]; bx::vec3MulMtxH(xyz, box[0], vp); float minx = xyz[0]; float miny = xyz[1]; float maxx = xyz[0]; float maxy = xyz[1]; float maxz = xyz[2]; for (uint32_t ii = 1; ii < 8; ++ii) { bx::vec3MulMtxH(xyz, box[ii], vp); minx = bx::fmin(minx, xyz[0]); miny = bx::fmin(miny, xyz[1]); maxx = bx::fmax(maxx, xyz[0]); maxy = bx::fmax(maxy, xyz[1]); maxz = bx::fmax(maxz, xyz[2]); } // Cull light if it's fully behind camera. if (maxz >= 0.0f) { float x0 = bx::fclamp( (minx * 0.5f + 0.5f) * width, 0.0f, (float)width); float y0 = bx::fclamp( (miny * 0.5f + 0.5f) * height, 0.0f, (float)height); float x1 = bx::fclamp( (maxx * 0.5f + 0.5f) * width, 0.0f, (float)width); float y1 = bx::fclamp( (maxy * 0.5f + 0.5f) * height, 0.0f, (float)height); if (showScissorRects) { bgfx::TransientVertexBuffer tvb; bgfx::TransientIndexBuffer tib; if (bgfx::allocTransientBuffers(&tvb, DebugVertex::ms_decl, 4, &tib, 8) ) { uint32_t abgr = 0x8000ff00; DebugVertex* vertex = (DebugVertex*)tvb.data; vertex->m_x = x0; vertex->m_y = y0; vertex->m_z = 0.0f; vertex->m_abgr = abgr; ++vertex; vertex->m_x = x1; vertex->m_y = y0; vertex->m_z = 0.0f; vertex->m_abgr = abgr; ++vertex; vertex->m_x = x1; vertex->m_y = y1; vertex->m_z = 0.0f; vertex->m_abgr = abgr; ++vertex; vertex->m_x = x0; vertex->m_y = y1; vertex->m_z = 0.0f; vertex->m_abgr = abgr; uint16_t* indices = (uint16_t*)tib.data; *indices++ = 0; *indices++ = 1; *indices++ = 1; *indices++ = 2; *indices++ = 2; *indices++ = 3; *indices++ = 3; *indices++ = 0; bgfx::setProgram(lineProgram); bgfx::setVertexBuffer(&tvb); bgfx::setIndexBuffer(&tib); bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_PT_LINES | BGFX_STATE_BLEND_ALPHA ); bgfx::submit(RENDER_PASS_DEBUG_LIGHTS_ID); } } uint8_t val = light&7; float lightRgbInnerR[4] = { val & 0x1 ? 1.0f : 0.25f, val & 0x2 ? 1.0f : 0.25f, val & 0x4 ? 1.0f : 0.25f, 0.8f, }; // Draw light. bgfx::setUniform(u_lightPosRadius, &lightPosRadius); bgfx::setUniform(u_lightRgbInnerR, lightRgbInnerR); bgfx::setUniform(u_mtx, invMvp); const uint16_t scissorHeight = uint16_t(y1-y0); bgfx::setScissor(uint16_t(x0), height-scissorHeight-uint16_t(y0), uint16_t(x1-x0), scissorHeight); bgfx::setTexture(0, s_normal, gbuffer, 1); bgfx::setTexture(1, s_depth, gbuffer, 2); bgfx::setProgram(lightProgram); bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE | BGFX_STATE_BLEND_ADD ); screenSpaceQuad( (float)width, (float)height, texelHalf, originBottomLeft); bgfx::submit(RENDER_PASS_LIGHT_ID); } } // Combine color and light buffers. bgfx::setTexture(0, s_albedo, gbuffer, 0); bgfx::setTexture(1, s_light, lightBuffer, 0); bgfx::setProgram(combineProgram); bgfx::setState(0 | BGFX_STATE_RGB_WRITE | BGFX_STATE_ALPHA_WRITE ); screenSpaceQuad( (float)width, (float)height, texelHalf, originBottomLeft); bgfx::submit(RENDER_PASS_COMBINE_ID); if (showGBuffer) { const float aspectRatio = float(width)/float(height); // Draw debug GBuffer. for (uint32_t ii = 0; ii < BX_COUNTOF(gbufferTex); ++ii) { float mtx[16]; bx::mtxSRT(mtx , aspectRatio, 1.0f, 1.0f , 0.0f, 0.0f, 0.0f , -7.9f - BX_COUNTOF(gbufferTex)*0.1f*0.5f + ii*2.1f*aspectRatio, 4.0f, 0.0f ); bgfx::setTransform(mtx); bgfx::setProgram(debugProgram); bgfx::setVertexBuffer(vbh); bgfx::setIndexBuffer(ibh, 0, 6); bgfx::setTexture(0, s_texColor, gbufferTex[ii]); bgfx::setState(BGFX_STATE_RGB_WRITE); bgfx::submit(RENDER_PASS_DEBUG_GBUFFER_ID); } } } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. cameraDestroy(); imguiDestroy(); if (bgfx::isValid(gbuffer) ) { bgfx::destroyFrameBuffer(gbuffer); bgfx::destroyFrameBuffer(lightBuffer); } bgfx::destroyIndexBuffer(ibh); bgfx::destroyVertexBuffer(vbh); bgfx::destroyProgram(geomProgram); bgfx::destroyProgram(lightProgram); bgfx::destroyProgram(combineProgram); bgfx::destroyProgram(debugProgram); bgfx::destroyProgram(lineProgram); bgfx::destroyTexture(textureColor); bgfx::destroyTexture(textureNormal); bgfx::destroyUniform(s_texColor); bgfx::destroyUniform(s_texNormal); bgfx::destroyUniform(s_albedo); bgfx::destroyUniform(s_normal); bgfx::destroyUniform(s_depth); bgfx::destroyUniform(s_light); bgfx::destroyUniform(u_lightPosRadius); bgfx::destroyUniform(u_lightRgbInnerR); bgfx::destroyUniform(u_mtx); // Shutdown bgfx. bgfx::shutdown(); return 0; }
static int initScene(scene_t *scene) { // load mesh if (!loadSimpleObjFile("gazebo.obj", &scene->vertices, &scene->vertexCount, &scene->indices, &scene->indexCount)) { fprintf(stderr, "Error loading obj file\n"); return 0; } glGenVertexArrays(1, &scene->vao); glBindVertexArray(scene->vao); glGenBuffers(1, &scene->vbo); glBindBuffer(GL_ARRAY_BUFFER, scene->vbo); glBufferData(GL_ARRAY_BUFFER, scene->vertexCount * sizeof(vertex_t), scene->vertices, GL_STATIC_DRAW); glGenBuffers(1, &scene->ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, scene->ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, scene->indexCount * sizeof(unsigned short), scene->indices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(vertex_t), (void*)offsetof(vertex_t, p)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_t), (void*)offsetof(vertex_t, t)); // create lightmap texture scene->w = 654; scene->h = 654; glGenTextures(1, &scene->lightmap); glBindTexture(GL_TEXTURE_2D, scene->lightmap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); unsigned char emissive[] = { 0, 0, 0, 255 }; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, emissive); // load shader const char *vp = "#version 150 core\n" "in vec3 a_position;\n" "in vec2 a_texcoord;\n" "uniform mat4 u_view;\n" "uniform mat4 u_projection;\n" "out vec2 v_texcoord;\n" "void main()\n" "{\n" "gl_Position = u_projection * (u_view * vec4(a_position, 1.0));\n" "v_texcoord = a_texcoord;\n" "}\n"; const char *fp = "#version 150 core\n" "in vec2 v_texcoord;\n" "uniform sampler2D u_lightmap;\n" "out vec4 o_color;\n" "void main()\n" "{\n" "o_color = vec4(texture(u_lightmap, v_texcoord).rgb, gl_FrontFacing ? 1.0 : 0.0);\n" "}\n"; const char *attribs[] = { "a_position", "a_texcoord" }; scene->program = loadProgram(vp, fp, attribs, 2); if (!scene->program) { fprintf(stderr, "Error loading shader\n"); return 0; } scene->u_view = glGetUniformLocation(scene->program, "u_view"); scene->u_projection = glGetUniformLocation(scene->program, "u_projection"); scene->u_lightmap = glGetUniformLocation(scene->program, "u_lightmap"); return 1; }
int main(int argc, char *argv[]) { if(argc <= 3) { std::cout << "Wrong arguments, please provide config file, raw input file and number of packets." << std::endl; std::cout << argv[0] << " config.xml input.raw <npackets>" << std::endl; return 1; } const std::string configFilename(realpath(argv[1], NULL)); const std::string inputFilename(realpath(argv[2], NULL)); const unsigned long numevents = std::atol(argv[3]); // load events buffer PacketLib::PacketBufferV events(configFilename, inputFilename); events.load(); PacketLib::PacketStream ps(configFilename.c_str()); CTAConfig::CTAMDArray array_conf; std::cout << "Preloading.." << std::endl; array_conf.loadConfig("AARPROD2", "PROD2_telconfig.fits.gz", "Aar.conf", "conf/"); std::cout << "Load complete!" << std::endl; std::chrono::time_point<std::chrono::system_clock> start, end; unsigned long event_count = 0, event_size = 0; std::vector<cl::Platform> platforms; cl::Platform::get(&platforms); for(unsigned int i=0; i<platforms.size(); i++) { cl::Platform platform = platforms[i]; std::cout << "----------------------------" << std::endl; std::cout << "Platform " << i << " info:" << std::endl; std::string info; platform.getInfo(CL_PLATFORM_NAME, &info); std::cout << info << std::endl; platform.getInfo(CL_PLATFORM_VERSION, &info); std::cout << info << std::endl; platform.getInfo(CL_PLATFORM_VENDOR, &info); std::cout << info << std::endl; } std::vector<cl::Device> devices; platforms[0].getDevices(CL_DEVICE_TYPE_ALL, &devices); std::cout << "Using platform 0." << std::endl; for(unsigned int i=0; i<devices.size(); i++) { cl::Device device = devices[i]; std::cout << "----------------------------" << std::endl; std::cout << "Device " << i << " info:" << std::endl; std::string info; device.getInfo(CL_DEVICE_NAME, &info); std::cout << info << std::endl; device.getInfo(CL_DEVICE_VENDOR, &info); std::cout << info << std::endl; device.getInfo(CL_DEVICE_VERSION, &info); std::cout << info << std::endl; device.getInfo(CL_DRIVER_VERSION, &info); std::cout << info << std::endl; } std::cout << "Using device 0." << std::endl; cl::Context context(devices); cl::CommandQueue queue(context, devices[0], 0, NULL); std::string source = loadProgram("extract_wave.cl"); cl::Program::Sources sources(1, std::make_pair(source.c_str(), source.length())); cl::Program program(context, sources); program.build(devices); cl::Kernel koWaveextract(program, "waveextract"); ::size_t workgroupSize = koWaveextract.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(devices[0]); start = std::chrono::system_clock::now(); while(event_count++ < numevents) { PacketLib::ByteStreamPtr event = events.getNext(); event_size += event->size(); /// swap if the stream has a different endianity #ifdef ARCH_BIGENDIAN if(!event->isBigendian()) event->swapWord(); #else if(event->isBigendian()) event->swapWord(); #endif /// decoding packetlib packet PacketLib::Packet *packet = ps.getPacket(event); /// get telescope id PacketLib::DataFieldHeader* dfh = packet->getPacketDataFieldHeader(); const unsigned int telescopeID = dfh->getFieldValue_16ui("TelescopeID"); /// get the waveforms PacketLib::byte* buff = packet->getData()->getStream(); PacketLib::dword buffSize = packet->getData()->size(); /// get npixels and nsamples from ctaconfig using the telescopeID CTAConfig::CTAMDTelescopeType* teltype = array_conf.getTelescope(telescopeID)->getTelescopeType(); int telTypeSim = teltype->getID(); const unsigned int npixels = teltype->getCameraType()->getNpixels(); const unsigned int nsamples = teltype->getCameraType()->getPixel(0)->getPixelType()->getNSamples(); #ifdef DEBUG std::cout << workgroupSize << std::endl; std::cout << npixels << std::endl; #endif // compute waveform extraction cl::Buffer waveCLBuffer(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, buffSize, buff, NULL); std::vector<unsigned short> maxres(npixels); std::vector<unsigned short> timeres(npixels); cl::Buffer maxresCLBuffer(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, npixels*sizeof(unsigned short), maxres.data(), NULL); cl::Buffer timeresCLBuffer(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, npixels*sizeof(unsigned short), timeres.data(), NULL); koWaveextract.setArg(0, waveCLBuffer); koWaveextract.setArg(1, npixels); koWaveextract.setArg(2, nsamples); koWaveextract.setArg(3, 6); koWaveextract.setArg(4, maxresCLBuffer); koWaveextract.setArg(5, timeresCLBuffer); queue.enqueueMapBuffer(waveCLBuffer, CL_FALSE, CL_MAP_WRITE, 0, buffSize); queue.enqueueMapBuffer(maxresCLBuffer, CL_FALSE, CL_MAP_READ, 0, npixels); queue.enqueueMapBuffer(timeresCLBuffer, CL_FALSE, CL_MAP_READ, 0, npixels); cl::NDRange global(npixels); cl::NDRange local(1); queue.enqueueNDRangeKernel(koWaveextract, cl::NullRange, global, local); queue.finish(); #ifdef DEBUG std::cout << "npixels = " << npixels << std::endl; std::cout << "nsamples = " << nsamples << std::endl; for(int pixel = 0; pixel<npixels; pixel++) { PacketLib::word* s = (PacketLib::word*) buff + pixel * nsamples; std::cout << "pixel " << pixel << " samples "; for(int k=0; k<nsamples; k++) { std::cout << s[k] << " "; } std::cout << std::endl; std::cout << "result " << " " << maxres[pixel] << " " << timeres[pixel] << " " << std::endl; } #endif } end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed = end-start; double throughput = event_count / elapsed.count(); double mbytes = (event_size / 1000000) / elapsed.count(); std::cout << event_count << " events sent in " << elapsed.count() << " s" << std::endl; std::cout << "mean event size: " << event_size / event_count << " B" << std::endl; std::cout << "throughput: " << throughput << " event/s = " << mbytes << " MB/s" << std::endl; return 0; }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); bgfx::UniformHandle u_time = bgfx::createUniform("u_time", bgfx::UniformType::Vec4); // Create program from shaders. bgfx::ProgramHandle program = loadProgram("vs_mesh", "fs_mesh"); Mesh* mesh = meshLoad("meshes/bunny.bin"); int64_t timeOffset = bx::getHPCounter(); while (!entry::processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; float time = (float)( (bx::getHPCounter()-timeOffset)/double(bx::getHPFrequency() ) ); bgfx::setUniform(u_time, &time); // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/04-mesh"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Loading meshes."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); float at[3] = { 0.0f, 1.0f, 0.0f }; float eye[3] = { 0.0f, 1.0f, -2.5f }; // Set view and projection matrix for view 0. const bgfx::HMD* hmd = bgfx::getHMD(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float view[16]; bx::mtxQuatTranslationHMD(view, hmd->eye[0].rotation, eye); float proj[16]; bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. // // Use HMD's width/height since HMD's internal frame buffer size // might be much larger than window size. bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float view[16]; bx::mtxLookAt(view, eye, at); float proj[16]; bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); bgfx::setViewTransform(0, view, proj); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); } float mtx[16]; bx::mtxRotateXY(mtx , 0.0f , time*0.37f ); meshSubmit(mesh, 0, program, mtx); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } meshUnload(mesh); // Cleanup. bgfx::destroyProgram(program); bgfx::destroyUniform(u_time); // Shutdown bgfx. bgfx::shutdown(); return 0; }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set views clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Imgui. imguiCreate(); // Uniforms. s_uniforms.init(); // Vertex declarations. PosColorTexCoord0Vertex::init(); LightProbe lightProbes[LightProbe::Count]; lightProbes[LightProbe::Wells ].load("wells"); lightProbes[LightProbe::Uffizi].load("uffizi"); lightProbes[LightProbe::Pisa ].load("pisa"); lightProbes[LightProbe::Ennis ].load("ennis"); lightProbes[LightProbe::Grace ].load("grace"); LightProbe::Enum currentLightProbe = LightProbe::Wells; bgfx::UniformHandle u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Mat4); bgfx::UniformHandle u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4); bgfx::UniformHandle u_flags = bgfx::createUniform("u_flags", bgfx::UniformType::Vec4); bgfx::UniformHandle u_camPos = bgfx::createUniform("u_camPos", bgfx::UniformType::Vec4); bgfx::UniformHandle s_texCube = bgfx::createUniform("s_texCube", bgfx::UniformType::Int1); bgfx::UniformHandle s_texCubeIrr = bgfx::createUniform("s_texCubeIrr", bgfx::UniformType::Int1); bgfx::ProgramHandle programMesh = loadProgram("vs_ibl_mesh", "fs_ibl_mesh"); bgfx::ProgramHandle programSky = loadProgram("vs_ibl_skybox", "fs_ibl_skybox"); Mesh* meshBunny; meshBunny = meshLoad("meshes/bunny.bin"); struct Settings { float m_speed; float m_glossiness; float m_exposure; float m_diffspec; float m_rgbDiff[3]; float m_rgbSpec[3]; bool m_diffuse; bool m_specular; bool m_diffuseIbl; bool m_specularIbl; bool m_showDiffColorWheel; bool m_showSpecColorWheel; ImguiCubemap::Enum m_crossCubemapPreview; }; Settings settings; settings.m_speed = 0.37f; settings.m_glossiness = 1.0f; settings.m_exposure = 0.0f; settings.m_diffspec = 0.65f; settings.m_rgbDiff[0] = 0.2f; settings.m_rgbDiff[1] = 0.2f; settings.m_rgbDiff[2] = 0.2f; settings.m_rgbSpec[0] = 1.0f; settings.m_rgbSpec[1] = 1.0f; settings.m_rgbSpec[2] = 1.0f; settings.m_diffuse = true; settings.m_specular = true; settings.m_diffuseIbl = true; settings.m_specularIbl = true; settings.m_showDiffColorWheel = true; settings.m_showSpecColorWheel = false; settings.m_crossCubemapPreview = ImguiCubemap::Cross; float time = 0.0f; int32_t leftScrollArea = 0; entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) , mouseState.m_mz , width , height ); static int32_t rightScrollArea = 0; imguiBeginScrollArea("Settings", width - 256 - 10, 10, 256, 540, &rightScrollArea); imguiLabel("Shade:"); imguiSeparator(); imguiBool("Diffuse", settings.m_diffuse); imguiBool("Specular", settings.m_specular); imguiBool("IBL Diffuse", settings.m_diffuseIbl); imguiBool("IBL Specular", settings.m_specularIbl); imguiSeparatorLine(); imguiSlider("Speed", settings.m_speed, 0.0f, 1.0f, 0.01f); imguiSeparatorLine(); imguiSeparator(); imguiSlider("Exposure", settings.m_exposure, -8.0f, 8.0f, 0.01f); imguiSeparator(); imguiLabel("Environment:"); currentLightProbe = LightProbe::Enum(imguiChoose(currentLightProbe , "Wells" , "Uffizi" , "Pisa" , "Ennis" , "Grace" ) ); static float lod = 0.0f; if (imguiCube(lightProbes[currentLightProbe].m_tex, lod, settings.m_crossCubemapPreview, true) ) { settings.m_crossCubemapPreview = ImguiCubemap::Enum( (settings.m_crossCubemapPreview+1) % ImguiCubemap::Count); } imguiSlider("Texture LOD", lod, 0.0f, 10.1f, 0.1f); imguiEndScrollArea(); imguiBeginScrollArea("Settings", 10, 70, 256, 576, &leftScrollArea); imguiLabel("Material properties:"); imguiSeparator(); imguiSlider("Diffuse - Specular", settings.m_diffspec, 0.0f, 1.0f, 0.01f); imguiSlider("Glossiness" , settings.m_glossiness, 0.0f, 1.0f, 0.01f); imguiSeparator(); imguiColorWheel("Diffuse color:", &settings.m_rgbDiff[0], settings.m_showDiffColorWheel); imguiSeparator(); imguiColorWheel("Specular color:", &settings.m_rgbSpec[0], settings.m_showSpecColorWheel); imguiSeparator(); imguiLabel("Predefined materials:"); imguiSeparator(); if (imguiButton("Gold") ) { settings.m_glossiness = 0.8f; settings.m_diffspec = 1.0f; settings.m_rgbDiff[0] = 0.0f; settings.m_rgbDiff[1] = 0.0f; settings.m_rgbDiff[2] = 0.0f; settings.m_rgbSpec[0] = 1.0f; settings.m_rgbSpec[1] = 0.86f; settings.m_rgbSpec[2] = 0.58f; } if (imguiButton("Copper") ) { settings.m_glossiness = 0.67f; settings.m_diffspec = 1.0f; settings.m_rgbDiff[0] = 0.0f; settings.m_rgbDiff[1] = 0.0f; settings.m_rgbDiff[2] = 0.0f; settings.m_rgbSpec[0] = 0.98f; settings.m_rgbSpec[1] = 0.82f; settings.m_rgbSpec[2] = 0.76f; } if (imguiButton("Titanium") ) { settings.m_glossiness = 0.57f; settings.m_diffspec = 1.0f; settings.m_rgbDiff[0] = 0.0f; settings.m_rgbDiff[1] = 0.0f; settings.m_rgbDiff[2] = 0.0f; settings.m_rgbSpec[0] = 0.76f; settings.m_rgbSpec[1] = 0.73f; settings.m_rgbSpec[2] = 0.71f; } if (imguiButton("Steel") ) { settings.m_glossiness = 0.82f; settings.m_diffspec = 1.0f; settings.m_rgbDiff[0] = 0.0f; settings.m_rgbDiff[1] = 0.0f; settings.m_rgbDiff[2] = 0.0f; settings.m_rgbSpec[0] = 0.77f; settings.m_rgbSpec[1] = 0.78f; settings.m_rgbSpec[2] = 0.77f; } imguiEndScrollArea(); imguiEndFrame(); s_uniforms.m_glossiness = settings.m_glossiness; s_uniforms.m_exposure = settings.m_exposure; s_uniforms.m_diffspec = settings.m_diffspec; s_uniforms.m_flags[0] = float(settings.m_diffuse); s_uniforms.m_flags[1] = float(settings.m_specular); s_uniforms.m_flags[2] = float(settings.m_diffuseIbl); s_uniforms.m_flags[3] = float(settings.m_specularIbl); memcpy(s_uniforms.m_rgbDiff, settings.m_rgbDiff, 3*sizeof(float)); memcpy(s_uniforms.m_rgbSpec, settings.m_rgbSpec, 3*sizeof(float)); s_uniforms.submitPerFrameUniforms(); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; time += (float)(frameTime*settings.m_speed/freq); s_uniforms.m_camPosTime[3] = time; // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/18-ibl"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Image based lightning."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -3.0f }; bx::mtxRotateXY(s_uniforms.m_mtx , 0.0f , time ); float view[16]; float proj[16]; bx::mtxIdentity(view); bx::mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f); bgfx::setViewTransform(0, view, proj); bx::mtxLookAt(view, eye, at); memcpy(s_uniforms.m_camPosTime, eye, 3*sizeof(float) ); bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); bgfx::setViewTransform(1, view, proj); bgfx::setViewRect(0, 0, 0, width, height); bgfx::setViewRect(1, 0, 0, width, height); // View 0. bgfx::setTexture(0, s_texCube, lightProbes[currentLightProbe].m_tex); bgfx::setProgram(programSky); bgfx::setState(BGFX_STATE_RGB_WRITE|BGFX_STATE_ALPHA_WRITE); screenSpaceQuad( (float)width, (float)height, true); s_uniforms.submitPerDrawUniforms(); bgfx::submit(0); // View 1. float mtx[16]; bx::mtxSRT(mtx , 1.0f , 1.0f , 1.0f , 0.0f , bx::pi+time , 0.0f , 0.0f , -1.0f , 0.0f ); bgfx::setTexture(0, s_texCube, lightProbes[currentLightProbe].m_tex); bgfx::setTexture(1, s_texCubeIrr, lightProbes[currentLightProbe].m_texIrr); meshSubmit(meshBunny, 1, programMesh, mtx); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } meshUnload(meshBunny); // Cleanup. bgfx::destroyProgram(programMesh); bgfx::destroyProgram(programSky); bgfx::destroyUniform(u_camPos); bgfx::destroyUniform(u_flags); bgfx::destroyUniform(u_params); bgfx::destroyUniform(u_mtx); bgfx::destroyUniform(s_texCube); bgfx::destroyUniform(s_texCubeIrr); for (uint8_t ii = 0; ii < LightProbe::Count; ++ii) { lightProbes[ii].destroy(); } s_uniforms.destroy(); imguiDestroy(); // Shutdown bgfx. bgfx::shutdown(); return 0; }
InstancedColorizeShader() { loadProgram(OBJECT, GL_VERTEX_SHADER, "glow_object.vert", GL_FRAGMENT_SHADER, "glow_object.frag"); assignUniforms(); } // InstancedColorizeShader
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: break; case bgfx::RendererType::OpenGL: case bgfx::RendererType::OpenGLES: s_flipV = true; break; } // Create vertex stream declaration. PosColorTexCoord0Vertex::init(); bgfx::UniformHandle u_time = bgfx::createUniform("u_time", bgfx::UniformType::Uniform1f); bgfx::UniformHandle u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Uniform4x4fv); bgfx::UniformHandle u_lightDir = bgfx::createUniform("u_lightDir", bgfx::UniformType::Uniform3fv); // Create program from shaders. bgfx::ProgramHandle raymarching = loadProgram("vs_raymarching", "fs_raymarching"); int64_t timeOffset = bx::getHPCounter(); while (!entry::processEvents(width, height, debug, reset) ) { // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // Set view 1 default viewport. bgfx::setViewRect(1, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to viewZ 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/03-raymarch"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Updating shader uniforms."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); float at[3] = { 0.0f, 0.0f, 0.0f }; float eye[3] = { 0.0f, 0.0f, -15.0f }; float view[16]; float proj[16]; bx::mtxLookAt(view, eye, at); bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 1. bgfx::setViewTransform(0, view, proj); float ortho[16]; bx::mtxOrtho(ortho, 0.0f, 1280.0f, 720.0f, 0.0f, 0.0f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(1, NULL, ortho); float time = (float)( (bx::getHPCounter()-timeOffset)/double(bx::getHPFrequency() ) ); float vp[16]; bx::mtxMul(vp, view, proj); float mtx[16]; bx::mtxRotateXY(mtx , time , time*0.37f ); float mtxInv[16]; bx::mtxInverse(mtxInv, mtx); float lightDirModel[4] = { -0.4f, -0.5f, -1.0f, 0.0f }; float lightDirModelN[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; bx::vec3Norm(lightDirModelN, lightDirModel); float lightDir[4]; bx::vec4MulMtx(lightDir, lightDirModelN, mtxInv); bgfx::setUniform(u_lightDir, lightDir); float mvp[16]; bx::mtxMul(mvp, mtx, vp); float invMvp[16]; bx::mtxInverse(invMvp, mvp); bgfx::setUniform(u_mtx, invMvp); bgfx::setUniform(u_time, &time); renderScreenSpaceQuad(1, raymarching, 0.0f, 0.0f, 1280.0f, 720.0f); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } // Cleanup. bgfx::destroyProgram(raymarching); bgfx::destroyUniform(u_time); bgfx::destroyUniform(u_mtx); bgfx::destroyUniform(u_lightDir); // Shutdown bgfx. bgfx::shutdown(); return 0; }
ColoredRectShader() { loadProgram(OBJECT, GL_VERTEX_SHADER, "coloredquad.vert", GL_FRAGMENT_SHADER, "coloredquad.frag"); assignUniforms("center", "size", "color"); } // ColoredRectShader
bgfx::ProgramHandle loadProgram(const char* _vsName, const char* _fsName) { return loadProgram(s_fileReader, _vsName, _fsName); }
/* * Default: * argc = 1 * argv[0] = Nome do Programa */ int main(int argc, char** argv) { char * filename = NULL; int passoAPassoFlag = 0; int c; int maxMem = 256; int startIndex = 1; int startIndexPrint = 1; int endIndexPrint = 255; opterr = 0; while ((c = getopt(argc, argv, "i:f:m:n:ps:")) != -1) switch (c) { case 'i': startIndexPrint = atoi(optarg); break; case 'f': endIndexPrint = atoi(optarg); break; case 'm': maxMem = atoi(optarg); break; case 'n': filename = optarg; break; case 'p': passoAPassoFlag = 1; break; case 's': startIndex = atoi(optarg); break; case '?': switch (optopt) { case 'i': case 'f': case 'm': case 'n': case 's': fprintf(stderr, "Opção -%c necessita um argumento.\n", optopt); break; default: if (isprint(optopt)) fprintf(stderr, "Opção desconhecida `-%c'.\n", optopt); else fprintf(stderr, "Caractere de opção desconhecido `\\x%x'.\n", optopt); abort(); } } if (filename == NULL) { fprintf(stderr, "Erro nome do arquivo HEX não especificado!\n"); abort(); } FILE * hex = fopen(filename, "r"); if (!hex) { fprintf(stderr, "Erro ao abrir o arquivo %s!\n", filename); abort(); } inicializaMem(startIndexPrint, endIndexPrint, maxMem); if (loadProgram(hex, startIndex)) { fprintf(stderr, "Erro ao carregar o %s para a memória!\n", filename); abort(); } inicializaSimulador(); do { busca(); if (passoAPassoFlag) { printf("Precione 'r' para imprimir os registradores e seguir um passo na execução,\n" "'c' para continuar a execução sem o passo a passo,\n" "ou qualquer outra tecla para seguir um passo na execução: "); char * str = malloc(2); scanf("%s", str); if (strcmp(str, "r")==0) printRegs(); else if (strcmp(str, "c") == 0) passoAPassoFlag = 0; printf("\n"); } executa(); } while (1); return EXIT_SUCCESS; }
std::shared_ptr<OsgProgram> loadProgram(const SurgSim::Framework::ApplicationData& data, const std::string& name) { return loadProgram(data, name + ".vert", name + ".frag"); }
void Ibex::TextRenderer::precompileText(float x, float y, const std::vector<std::string> &lines, const std::vector<bool> &highlighted, int maxChars) { if(!initialized) { initialized = true; loadProgram(); initializeFont(); } checkForErrors(); vertices.clear(); indices.clear(); minX = minY = INT_MAX; maxX = maxY = INT_MIN; // assume orthographic projection with units = screen pixels, origin at top left int index = 0; int lineNum = (int)lines.size()-1; //for(std::string line : lines) { for(int i = 0; i < lines.size(); ++i) { std::string line = lines[i]; if(maxChars > 0 && line.length() > maxChars) { line.resize(maxChars); } const GLfloat *color = (highlighted.size() > i && highlighted[i]) ? highlightedTextColor : textColor; x = 0; y = -lineNum * (ascent-descent+lineGap)*scale; unsigned char *text = (unsigned char *)line.data(); while (*text) { if (*text >= 32 && *text < 128) { stbtt_aligned_quad q; stbtt_GetBakedQuad(cdata, 1024,256, *text-32, &x,&y,&q,1); // bottom right triangle vertices.push_back(q.x0); vertices.push_back((baseline-q.y0)); vertices.push_back(0); vertices.push_back(q.s0); vertices.push_back(q.t0); vertices.push_back(color[0]); vertices.push_back(color[1]); vertices.push_back(color[2]); vertices.push_back(color[3]); vertices.push_back(q.x1); vertices.push_back((baseline-q.y0)); vertices.push_back(0); vertices.push_back(q.s1); vertices.push_back(q.t0); vertices.push_back(color[0]); vertices.push_back(color[1]); vertices.push_back(color[2]); vertices.push_back(color[3]); vertices.push_back(q.x1); vertices.push_back((baseline-q.y1)); vertices.push_back(0); vertices.push_back(q.s1); vertices.push_back(q.t1); vertices.push_back(color[0]); vertices.push_back(color[1]); vertices.push_back(color[2]); vertices.push_back(color[3]); // top left triangle vertices.push_back(q.x0); vertices.push_back((baseline-q.y0)); vertices.push_back(0); vertices.push_back(q.s0); vertices.push_back(q.t0); vertices.push_back(color[0]); vertices.push_back(color[1]); vertices.push_back(color[2]); vertices.push_back(color[3]); vertices.push_back(q.x1); vertices.push_back((baseline-q.y1)); vertices.push_back(0); vertices.push_back(q.s1); vertices.push_back(q.t1); vertices.push_back(color[0]); vertices.push_back(color[1]); vertices.push_back(color[2]); vertices.push_back(color[3]); vertices.push_back(q.x0); vertices.push_back((baseline-q.y1)); vertices.push_back(0); vertices.push_back(q.s0); vertices.push_back(q.t1); vertices.push_back(color[0]); vertices.push_back(color[1]); vertices.push_back(color[2]); vertices.push_back(color[3]); minX = std::min(minX,std::min(q.x0,q.x1)); maxX = std::max(maxX,std::max(q.x0,q.x1)); minY = std::min(minY,std::min(baseline-q.y0,baseline-q.y1)+y); maxY = std::max(maxY,std::max(baseline-q.y0,baseline-q.y1)); for(int i = 0; i < 6; ++i) { indices.push_back(index++); } } ++text; } --lineNum; if(minX > maxX) std::swap(minX,maxX); if(minY > maxY) std::swap(minY,maxY); } if(vaoTextRenderer == 0) glGenVertexArrays(1,&vaoTextRenderer); if(!checkForErrors()) { exit(1); } glBindVertexArray(vaoTextRenderer); if(vboTextVertices == 0) glGenBuffers(1, &vboTextVertices); glBindBuffer(GL_ARRAY_BUFFER, vboTextVertices); glBufferData(GL_ARRAY_BUFFER, vertices.size()*sizeof(GLfloat), vertices.data(), GL_STATIC_DRAW); if(!checkForErrors()) { exit(1); } glEnableVertexAttribArray(IbexTextAttribLocations[0]); glVertexAttribPointer(IbexTextAttribLocations[0], 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*9, 0); glEnableVertexAttribArray(IbexTextAttribLocations[1]); glVertexAttribPointer(IbexTextAttribLocations[1], 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*9, (GLvoid*) (sizeof(GLfloat)*3)); glEnableVertexAttribArray(IbexTextAttribLocations[2]); glVertexAttribPointer(IbexTextAttribLocations[2], 4, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*9, (GLvoid*) (sizeof(GLfloat)*5)); if(!checkForErrors()) { exit(1); } if(vboTextIndices == 0) glGenBuffers(1, &vboTextIndices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboTextIndices); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size()*sizeof(GLuint), indices.data(), GL_STATIC_DRAW); if(!checkForErrors()) { exit(1); } glBindVertexArray(0); ////////////////////////////////////////////////////////////////////////////// static GLfloat IbexDisplayFlatVertices[] = { -1.0, -1.0, 0.0, 0, 1, 1.0, -1.0, 0.0, 1, 1, 1.0, 1.0, 0.0, 1, 0, -1.0, 1.0, 0.0, 0, 0 }; static GLushort IbexDisplayFlatIndices[] = { 0, 2, 1, 0, 3, 2 }; if(vaoTextTextureRenderer == 0) { if(vaoTextTextureRenderer == 0) glGenVertexArrays(1,&vaoTextTextureRenderer); if(!checkForErrors()) { exit(1); } glBindVertexArray(vaoTextTextureRenderer); if(vboTextTextureVertices == 0) glGenBuffers(1, &vboTextTextureVertices); glBindBuffer(GL_ARRAY_BUFFER, vboTextTextureVertices); glBufferData(GL_ARRAY_BUFFER, sizeof(IbexDisplayFlatVertices), IbexDisplayFlatVertices, GL_STATIC_DRAW); if(!checkForErrors()) { exit(1); } glEnableVertexAttribArray(IbexDisplayFlatAttribLocations[0]); glVertexAttribPointer(IbexDisplayFlatAttribLocations[0], 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, 0); glEnableVertexAttribArray(IbexDisplayFlatAttribLocations[2]); glVertexAttribPointer(IbexDisplayFlatAttribLocations[2], 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*5, (GLvoid*) (sizeof(GLfloat) * 3)); if(!checkForErrors()) { exit(1); } if(vboTextTextureIndices == 0) glGenBuffers(1, &vboTextTextureIndices); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboTextTextureIndices); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(IbexDisplayFlatIndices), IbexDisplayFlatIndices, GL_STATIC_DRAW); if(!checkForErrors()) { exit(1); } glBindVertexArray(0); } }
int go() { osg::setNotifyLevel(osg::NOTICE); // ====================================================================== // Create root group node osg::Group* root = new osg::Group(); // Create groups osg::Group* group01 = new osg::Group(); osg::Group* group02 = new osg::Group(); // Connect the two groups to the root root->addChild(group01); root->addChild(group02); // Create boxes and spheres osg::Box* box01 = new osg::Box(osg::Vec3f(0.0f,0.0f,0.0f),10.0f); osg::Box* box02 = new osg::Box(osg::Vec3f(0.0f,0.0f,0.0f),10.0f); osg::Sphere* sphere01 = new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),1.0f); osg::Sphere* sphere02 = new osg::Sphere(osg::Vec3(0.0f,0.0f,0.0f),1.0f); osg::ShapeDrawable* box01Drawable = new osg::ShapeDrawable(box01); osg::ShapeDrawable* box02Drawable = new osg::ShapeDrawable(box02); osg::ShapeDrawable* sphere01Drawable = new osg::ShapeDrawable(sphere01); osg::ShapeDrawable* sphere02Drawable = new osg::ShapeDrawable(sphere02); osg::Group* mainSceneRoot = new osg::Group(); osg::Geode* geode01 = new osg::Geode(); osg::Geode* geode02 = new osg::Geode(); geode01->addDrawable(sphere01Drawable); geode02->addDrawable(sphere02Drawable); // ====================================================================== osg::Node* model01 = osgDB::readNodeFile("data/models/cessna.osg"); { osg::Program* program = loadProgram("data/shaders/simpleShader01"); model01->getOrCreateStateSet()->setAttribute(program,osg::StateAttribute::ON); } // Create RT textures osg::Texture2D* rttDepthTexture = createDepthTexture (512,512); osg::Texture2D* rttColorTexture01 = createRenderTexture(512,512); osg::Texture2D* rttColorTexture02 = createRenderTexture(512,512); osg::Texture2D* rttColorTexture03 = createRenderTexture(512,512); // Create RTT camera osg::Camera* rttCamera = createRenderTargetCamera(rttDepthTexture,rttColorTexture01,rttColorTexture02,rttColorTexture03); osg::MatrixTransform* modelTransform = new osg::MatrixTransform(); modelTransform->addChild(model01); rttCamera->addChild(modelTransform); osg::NodeCallback* nc = new osg::AnimationPathCallback(modelTransform->getBound().center(),osg::Vec3(0.0f,0.0f,1.0f),osg::inDegrees(45.0f)); modelTransform->setUpdateCallback(nc); group01->addChild(rttCamera); // ====================================================================== osg::PositionAttitudeTransform* light01Transform = new osg::PositionAttitudeTransform(); osg::PositionAttitudeTransform* light02Transform = new osg::PositionAttitudeTransform(); light01Transform->setPosition(osg::Vec3(-20.0f, 0.0f, 0.0f)); light02Transform->setPosition(osg::Vec3( 20.0f, 0.0f, 0.0f)); light01Transform->addChild(geode01); light02Transform->addChild(geode02); rttCamera->addChild(light01Transform); rttCamera->addChild(light02Transform); osg::Uniform* light01Uniform = new osg::Uniform("uLight01Pos",osg::Vec4(-20.0f,0.0f,0.0f,1.0f)); osg::Uniform* light02Uniform = new osg::Uniform("uLight02Pos",osg::Vec4( 20.0f,0.0f,0.0f,1.0f)); rttCamera->getOrCreateStateSet()->addUniform(light01Uniform,osg::StateAttribute::ON); rttCamera->getOrCreateStateSet()->addUniform(light02Uniform,osg::StateAttribute::ON); // ====================================================================== // Add 4 x ortho quads to the screen/scene // Create 4 quads each one is a quarter of the screen. osg::Geode* fullScreenQuadGeode01 = createPlaneGeode( 0, 512, 512, 512); osg::Geode* fullScreenQuadGeode02 = createPlaneGeode( 512, 512, 512, 512); osg::Geode* fullScreenQuadGeode03 = createPlaneGeode( 0, 0, 512, 512); osg::Geode* fullScreenQuadGeode04 = createPlaneGeode( 512, 0, 512, 512); // Create an orthographic camera and attach the 4 quads to it. osg::Camera* normalCamera = createNormalCamera(); normalCamera->addChild(fullScreenQuadGeode01); normalCamera->addChild(fullScreenQuadGeode02); normalCamera->addChild(fullScreenQuadGeode03); normalCamera->addChild(fullScreenQuadGeode04); // quad 01 { osg::Program* program = loadProgram("data/shaders/colorTextureShader"); osg::Uniform* uniformTex01 = new osg::Uniform("uTexture01",0); osg::StateSet* ss = new osg::StateSet(); ss->setTextureAttributeAndModes(0,rttDepthTexture,osg::StateAttribute::ON); ss->setAttribute(program,osg::StateAttribute::ON); ss->addUniform(uniformTex01); fullScreenQuadGeode01->setStateSet(ss); } // quad 02 { osg::Program* program = loadProgram("data/shaders/colorTextureShader"); osg::Uniform* uniformTex01 = new osg::Uniform("uTexture01",0); osg::StateSet* ss = new osg::StateSet(); ss->setTextureAttributeAndModes(0,rttColorTexture01,osg::StateAttribute::ON); ss->setAttribute(program,osg::StateAttribute::ON); ss->addUniform(uniformTex01); fullScreenQuadGeode02->setStateSet(ss); } // quad 03 { osg::Program* program = loadProgram("data/shaders/colorTextureShader"); osg::Uniform* uniformTex01 = new osg::Uniform("uTexture01",0); osg::StateSet* ss = new osg::StateSet(); ss->setTextureAttributeAndModes(0,rttColorTexture02,osg::StateAttribute::ON); ss->setAttribute(program,osg::StateAttribute::ON); ss->addUniform(uniformTex01); fullScreenQuadGeode03->setStateSet(ss); } // quad 04 { osg::Program* program = loadProgram("data/shaders/lightingPass"); osg::Uniform* uniformTexDepth = new osg::Uniform("uDepthTex", 0); osg::Uniform* uniformTexColor = new osg::Uniform("uColorTex", 1); osg::Uniform* uniformTexNormal = new osg::Uniform("uNormalTex",2); osg::StateSet* ss = new osg::StateSet(); ss->setTextureAttributeAndModes(0,rttDepthTexture,osg::StateAttribute::ON); ss->setTextureAttributeAndModes(1,rttColorTexture01,osg::StateAttribute::ON); ss->setTextureAttributeAndModes(2,rttColorTexture02,osg::StateAttribute::ON); ss->setAttribute(program,osg::StateAttribute::ON); ss->addUniform(uniformTexDepth); ss->addUniform(uniformTexColor); ss->addUniform(uniformTexNormal); fullScreenQuadGeode04->setStateSet(ss); } group02->addChild(normalCamera); // ====================================================================== // :D // Create viewer osgViewer::Viewer viewer; // Attach scene root node viewer.setSceneData(root); // Setup window mode viewer.setUpViewInWindow( 50, 50, WINDOW_WIDTH, WINDOW_HEIGHT ); // Run! :) viewer.run(); // ====================================================================== return EXIT_SUCCESS; }
// ---------------------------------------------------------------------------- // parses the next command from m_instrStream // ---------------------------------------------------------------------------- void CRPNCalc::parse() { double number = 0; while (m_buffer.length() != 0) { bool delDecimal = false; //erase the spaces at the beginning of the string while(m_buffer[0] == ' ') m_buffer.erase(m_buffer.begin()); number = atof(m_buffer.c_str()); //if it is a number if((number != 0 && m_buffer[0] != '+') || m_buffer[0] == '0') { if(m_buffer[0] == '-') m_buffer.erase(m_buffer.begin()); while((m_buffer[0] >= '0' && m_buffer[0] <= '9') || m_buffer[0] == '.') { if(m_buffer[0] == '.') if(delDecimal == false) delDecimal = true; else break; m_buffer.erase(m_buffer.begin()); if(m_buffer.length() == 0) break; } m_stack.push_front(number); } else { string token; //if the beginning is a character if(m_buffer.length() >= 2) { //special situation with CE if(toupper(m_buffer[0]) == 'C' && toupper(m_buffer[1]) == 'E') { m_buffer.erase(m_buffer.begin(),m_buffer.begin() + 2); clearAll(); continue; } //special situation with -0 else if(m_buffer[0] == '-' && m_buffer[1] == '0') { m_buffer.erase(m_buffer.begin()); while(m_buffer[0] == '0') { m_buffer.erase(m_buffer.begin()); if(m_buffer.length() == 0) break; } m_stack.push_front(number); neg(); continue; } //special situation with S0-9 else if(toupper(m_buffer[0]) == 'S' && m_buffer[1] >= '0' && m_buffer[1] <= '9') { m_buffer.erase(m_buffer.begin()); // delete the 'S' to get the number char index = m_buffer[0]; setReg(static_cast<int>(index) - ZEROINASCII); m_buffer.erase(m_buffer.begin()); // delete the number continue; } //special situation with G0-9 else if(toupper(m_buffer[0]) == 'G' && m_buffer[1] >= '0' && m_buffer[1] <= '9') { m_buffer.erase(m_buffer.begin()); // delete the 'G' to get the number char index = m_buffer[0]; getReg(static_cast<int>(index) - ZEROINASCII); m_buffer.erase(m_buffer.begin()); // delete the number continue; } } if (m_buffer.length() != 0) { token = m_buffer[0]; if (0 == token.compare("+")) add(); else if (0 == token.compare("-")) subtract(); else if (0 == token.compare("*")) multiply(); else if (0 == token.compare("/")) divide(); else if (0 == token.compare("^")) exp(); else if (0 == token.compare("%")) mod(); else if (0 == token.compare("c") || 0 == token.compare("C")) clearEntry(); else if (0 == token.compare("d") || 0 == token.compare("D")) rotateDown(); else if (0 == token.compare("f") || 0 == token.compare("F")) saveToFile(); else if (0 == token.compare("h") || 0 == token.compare("H")) m_helpOn = !m_helpOn; else if (0 == token.compare("l") || 0 == token.compare("L")) loadProgram(); else if (0 == token.compare("m") || 0 == token.compare("M")) neg(); else if (0 == token.compare("p") || 0 == token.compare("P")) recordProgram(); else if (0 == token.compare("r") || 0 == token.compare("R")) { //the application only do this method and ignore other methods //if they are inputed at the same line runProgram(); return; } else if (0 == token.compare("u") || 0 == token.compare("U")) rotateUp(); else if (0 == token.compare("x") || 0 == token.compare("X")) m_on = false; else m_error = true; m_buffer.erase(m_buffer.begin()); } } } }
OpenGLShader::OpenGLShader(const std::string vertexPath, const std::string fragmentPath) { loadProgram(vertexPath, fragmentPath); }
int _main_(int /*_argc*/, char** /*_argv*/) { uint32_t width = 1280; uint32_t height = 720; uint32_t debug = BGFX_DEBUG_TEXT; uint32_t reset = BGFX_RESET_VSYNC; bgfx::init(); bgfx::reset(width, height, reset); // Enable debug text. bgfx::setDebug(debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT , 0x303030ff , 1.0f , 0 ); // Setup root path for binary shaders. Shader binaries are different // for each renderer. switch (bgfx::getRendererType() ) { default: case bgfx::RendererType::Direct3D9: s_shaderPath = "shaders/dx9/"; break; case bgfx::RendererType::Direct3D11: s_shaderPath = "shaders/dx11/"; break; case bgfx::RendererType::OpenGL: s_shaderPath = "shaders/glsl/"; s_flipV = true; break; case bgfx::RendererType::OpenGLES2: case bgfx::RendererType::OpenGLES3: s_shaderPath = "shaders/gles/"; s_flipV = true; break; } bgfx::UniformHandle u_texColor = bgfx::createUniform("u_texColor", bgfx::UniformType::Uniform1iv); bgfx::UniformHandle u_stipple = bgfx::createUniform("u_stipple", bgfx::UniformType::Uniform3fv); bgfx::UniformHandle u_texStipple = bgfx::createUniform("u_texStipple", bgfx::UniformType::Uniform1iv); bgfx::ProgramHandle program = loadProgram("vs_tree", "fs_tree"); const bgfx::Memory* mem; mem = loadTexture("leafs1.dds"); bgfx::TextureHandle textureLeafs = bgfx::createTexture(mem); mem = loadTexture("bark1.dds"); bgfx::TextureHandle textureBark = bgfx::createTexture(mem); bgfx::TextureHandle textureStipple; const bgfx::Memory* stipple = bgfx::alloc(8*4); memset(stipple->data, 0, stipple->size); for (uint32_t ii = 0; ii < 32; ++ii) { stipple->data[knightTour[ii].m_y * 8 + knightTour[ii].m_x] = ii*4; } textureStipple = bgfx::createTexture2D(8, 4, 1, bgfx::TextureFormat::L8, BGFX_TEXTURE_MAG_POINT|BGFX_TEXTURE_MIN_POINT, stipple); Mesh mesh_top[3]; mesh_top[0].load("meshes/tree1b_lod0_1.bin"); mesh_top[1].load("meshes/tree1b_lod1_1.bin"); mesh_top[2].load("meshes/tree1b_lod2_1.bin"); Mesh mesh_trunk[3]; mesh_trunk[0].load("meshes/tree1b_lod0_2.bin"); mesh_trunk[1].load("meshes/tree1b_lod1_2.bin"); mesh_trunk[2].load("meshes/tree1b_lod2_2.bin"); FILE* file = fopen("font/droidsans.ttf", "rb"); uint32_t size = (uint32_t)fsize(file); void* data = malloc(size); size_t ignore = fread(data, 1, size, file); BX_UNUSED(ignore); fclose(file); imguiCreate(data, size); free(data); int32_t scrollArea = 0; bool transitions = true; int transitionFrame = 0; int currLOD = 0; int targetLOD = 0; float at[3] = { 0.0f, 1.0f, 0.0f }; float eye[3] = { 0.0f, 1.0f, -2.0f }; entry::MouseState mouseState; while (!entry::processEvents(width, height, debug, reset, &mouseState) ) { imguiBeginFrame(mouseState.m_mx , mouseState.m_my , (mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) , 0 , width , height ); imguiBeginScrollArea("Toggle transitions", width - width / 5 - 10, 10, width / 5, height / 6, &scrollArea); imguiSeparatorLine(); if (imguiButton(transitions ? "ON" : "OFF") ) { transitions = !transitions; } static float distance = 2.0f; imguiSlider("Distance", &distance, 2.0f, 6.0f, .01f); imguiEndScrollArea(); imguiEndFrame(); // Set view 0 default viewport. bgfx::setViewRect(0, 0, 0, width, height); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::submit(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0/freq; // Use debug font to print information about this example. bgfx::dbgTextClear(); bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/12-lod"); bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Mesh LOD transitions."); bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs); bgfx::dbgTextPrintf(0, 4, transitions ? 0x2f : 0x1f, transitions ? "Transitions on" : "Transitions off"); eye[2] = -distance; float view[16]; float proj[16]; mtxLookAt(view, eye, at); mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 100.0f); // Set view and projection matrix for view 0. bgfx::setViewTransform(0, view, proj); float mtx[16]; mtxIdentity(mtx); float stipple[3]; float stippleInv[3]; const int currentLODframe = transitions ? 32-transitionFrame : 32; const int mainLOD = transitions ? currLOD : targetLOD; stipple[0] = 0.0f; stipple[1] = -1.0f; stipple[2] = (float(currentLODframe)*4.0f/255.0f) - (1.0f/255.0f); stippleInv[0] = (float(31)*4.0f/255.0f); stippleInv[1] = 1.0f; stippleInv[2] = (float(transitionFrame)*4.0f/255.0f) - (1.0f/255.0f); bgfx::setTexture(0, u_texColor, textureBark); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stipple); mesh_trunk[mainLOD].submit(program, mtx, false); bgfx::setTexture(0, u_texColor, textureLeafs); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stipple); mesh_top[mainLOD].submit(program, mtx, true); if (transitions && (transitionFrame != 0) ) { bgfx::setTexture(0, u_texColor, textureBark); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stippleInv); mesh_trunk[targetLOD].submit(program, mtx, false); bgfx::setTexture(0, u_texColor, textureLeafs); bgfx::setTexture(1, u_texStipple, textureStipple); bgfx::setUniform(u_stipple, stippleInv); mesh_top[targetLOD].submit(program, mtx, true); } int lod = 0; if (eye[2] < -2.5f) { lod = 1; } if (eye[2] < -5.0f) { lod = 2; } if (targetLOD!=lod) { if (targetLOD==currLOD) { targetLOD = lod; } } if (currLOD != targetLOD) { transitionFrame++; } if (transitionFrame>32) { currLOD = targetLOD; transitionFrame = 0; } // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); } for (uint32_t ii = 0; ii < 3; ++ii) { mesh_top[ii].unload(); mesh_trunk[ii].unload(); } // Cleanup. bgfx::destroyProgram(program); bgfx::destroyUniform(u_texColor); bgfx::destroyUniform(u_stipple); bgfx::destroyUniform(u_texStipple); bgfx::destroyTexture(textureStipple); bgfx::destroyTexture(textureLeafs); bgfx::destroyTexture(textureBark); // Shutdown bgfx. bgfx::shutdown(); return 0; }
bool Tunefish4AudioProcessor::loadProgram() { return loadProgram(currentProgramIndex); }
void DrawTexture::initialize() { program = loadProgram(vertexShaderResourceId, fragmentShaderResourceId); imageLocation = glGetUniformLocation(program, "image"); }