void EdvsRiftApp::drawSphereBackground(int camera_id) { static ProgramPtr program = oria::loadProgram("./resources/sphere_background.vs", "./resources/sphere_background.fs"); static ShapeWrapperPtr geometry = ShapeWrapperPtr(new shapes::ShapeWrapper({ "Position" }, shapes::ObjMesh(mesh_input.stream), *program)); // Reset before application exit Platform::addShutdownHook([] { program.reset(); geometry.reset(); }); MatrixStack & mv = Stacks::modelview(); mv.withPush([&] { // Binds the program program->Use(); // Matrices as uniforms Mat4Uniform(*program, "ModelView").Set(Stacks::modelview().top()); Mat4Uniform(*program, "Projection").Set(Stacks::projection().top()); // Draw this geometry->Use(); geometry->Draw(); }); // Unbind oglplus::NoProgram().Bind(); oglplus::NoVertexArray().Bind(); }
void GlUtils::draw3dGrid() { using namespace gl; GL_CHECK_ERROR; static GeometryPtr g; if (!g) { Mesh m; for (int i = 0; i < 5; ++i) { float offset = ((float) i * 0.2f) + 0.2f; glm::vec3 zOffset(0, 0, offset); glm::vec3 xOffset(offset, 0, 0); m.addVertex(-X_AXIS + zOffset); m.addVertex(X_AXIS + zOffset); m.addVertex(-X_AXIS - zOffset); m.addVertex(X_AXIS - zOffset); m.addVertex(-Z_AXIS + xOffset); m.addVertex(Z_AXIS + xOffset); m.addVertex(-Z_AXIS - xOffset); m.addVertex(Z_AXIS - xOffset); } m.addVertex(X_AXIS); m.addVertex(-X_AXIS); m.addVertex(Z_AXIS); m.addVertex(-Z_AXIS); g = m.getGeometry(GL_LINES); } ProgramPtr program = getProgram(Resource::SHADERS_SIMPLE_VS, Resource::SHADERS_COLORED_FS); GL_CHECK_ERROR; program->use(); GL_CHECK_ERROR; program->setUniform("Color", glm::vec4(Colors::gray,1)); GL_CHECK_ERROR; renderGeometry(g, program); GL_CHECK_ERROR; }
Shader::~Shader() { if (m_shader) { ProgramPtr prog = program(); if (prog) prog->removeShader(shared_from_this()); glDeleteShader(m_shader); } }
int main(int argc, char **argv) { if (argc == 1) { curr_filename = "<stdin>"; yyin = stdin; yyparse(); } else { for (int i = 1; i < argc; ++i) { curr_filename = argv[i]; yyin = std::fopen(argv[i], "r"); if (yyin) { yyparse(); std::fclose(yyin); } else { utility::print_error(argv[i], "cannot be opened"); } } } if (yynerrs > 0) { std::cerr << "Compilation halted due to lexical or syntax errors.\n"; exit(1); } SemanticAnalyzer semant; semant.install_basic(ast_root); if (!semant.validate_inheritance(ast_root->classes)) { std::cerr << "Compilation halted due to inheritance errors.\n"; exit(1); } if (!semant.type_check(ast_root)) { std::cerr << "Compilation halted due to type errors.\n"; exit(1); } AstNodeDisplayer print(std::cout, AstNodeDisplayer::DISPLAYNONBASIC); ast_root->accept(print); std::ofstream out("output.s"); AstNodeCodeGenerator codegen(semant.get_inherit_graph(), out); ast_root->accept(codegen); return 0; }
void GlUtils::renderBunny() { static GeometryPtr bunnyGeometry = getMesh(Resource::MESHES_BUNNY2_CTM).getGeometry(); ProgramPtr program = GlUtils::getProgram( Resource::SHADERS_LITCOLORED_VS, Resource::SHADERS_LITCOLORED_FS); program->use(); program->setUniform("Color", glm::vec4(1)); renderGeometry(bunnyGeometry, program); }
bool Shader::loadSrc(const QString& data) { if (m_src != data) { m_src = data; m_needCompile = true; // Tell the program object, that it needs to recompile stuff ProgramPtr p = m_prog.lock(); if (p) p->setIsCompiled(false); return true; } return false; }
void GlUtils::draw3dVector(glm::vec3 vec, const glm::vec3 & col) { Mesh m; m.color = Colors::gray; m.addVertex(glm::vec3()); m.addVertex(glm::vec3(vec.x, 0, vec.z)); m.addVertex(glm::vec3(vec.x, 0, vec.z)); m.addVertex(vec); m.fillColors(true); m.color = col; m.addVertex(vec); m.addVertex(glm::vec3()); m.fillColors(); static GeometryPtr g = m.getGeometry(GL_LINES); g->updateVertices(m.buildVertices()); ProgramPtr program = getProgram( Resource::SHADERS_COLORED_VS, Resource::SHADERS_COLORED_FS); program->use(); renderGeometry(g, program); gl::Program::clear(); // lineWidth(1.0f); // float len = glm::length(vec); // if (len > 1.0f) { // vec /= len; // } // gl::Program::clear(); // // glLineWidth(2.0f + len); // glBegin(GL_LINES); // gl::color(col); // gl::vertex(); // gl::vertex(); // glEnd(); // // glLineWidth(1.0f); // glBegin(GL_LINE_STRIP); // gl::color(Colors::gray); // gl::vertex(glm::vec3()); // gl::vertex(glm::vec3(vec.x, 0, vec.z)); // gl::vertex(vec); // glEnd(); }
ProgramPtr Program::remEntryPoints(NodeManager& manager, const ProgramPtr& program, const ExpressionList& entryPoints) { ExpressionList list; for_each(program->getEntryPoints(), [&list, &entryPoints](const ExpressionPtr& cur) { if(!contains(entryPoints, cur, equal_target<ExpressionPtr>())) { list.push_back(cur); } }); return manager.get(Program(list)); }
void State::useProgram(ProgramPtr prog) { if (prog) glRun(glUseProgram(prog->id())); else glRun(glUseProgram(0)); m_data.back().m_prog = prog; }
ShaderPtr Shader::clone(ProgramPtr prog) const { ShaderPtr s(new Shader(prog, m_type)); s->setFilename(rawFilename()); s->m_src = m_src; s->m_needCompile = true; if (prog) prog->setIsCompiled(false); return s; }
bool dumpTo(const ProgramPtr& program, const std::string& dir) { // first of all, we want to dump the callgraph auto callgraph = analysis::callgraph::getCallGraph(program); if (!dumpTo(dir + "/callgraph.dot", toString(callgraph))) return false; // finally, generate a file for each function for (const auto& fun : program->getFunctions()) { if (!dumpTo(dir + "/" + analysis::callgraph::getFunctionName(fun) + ".dot", toString(*fun))) return false; } return true; }
void GlUtils::drawAngleTicks() { using namespace gl; static GeometryPtr g; if (!g) { float offsets[] = { // (float) tan( PI / 6.0f), // 30 degrees (float) tan( PI / 4.0f), // 45 degrees (float) tan( PI / 3.0f) // 60 degrees }; Mesh m; // 43.9 degrees puts tick on the inner edge of the screen // 42.6 degrees is the effective fov for wide screen // 43.9 degrees puts tick on the inner edge of the screen m.addVertex(glm::vec3(-2, 0, 0)); m.addVertex(glm::vec3(2, 0, 0)); m.addVertex(glm::vec3(0, -2, 0)); m.addVertex(glm::vec3(0, 2, 0)); // By keeping the camera locked at 1 unit away from the origin, all our // distances can be computed as tan(angle) for (float offset : offsets) { m.addVertex(glm::vec3(offset, -0.05, 0)); m.addVertex(glm::vec3(offset, 0.05, 0)); m.addVertex(glm::vec3(-offset, -0.05, 0)); m.addVertex(glm::vec3(-offset, 0.05, 0)); } for (float offset : offsets) { m.addVertex(glm::vec3(-0.05, offset, 0)); m.addVertex(glm::vec3(0.05, offset, 0)); m.addVertex(glm::vec3(-0.05, -offset, 0)); m.addVertex(glm::vec3(0.05, -offset, 0)); } g = m.getGeometry(GL_LINES); } // Fix the modelview at exactly 1 unit away from the origin, no rotation gl::Stacks::modelview().push(glm::mat4(1)).translate(glm::vec3(0, 0, -1)); ProgramPtr program = getProgram(Resource::SHADERS_SIMPLE_VS, Resource::SHADERS_COLORED_FS); program->use(); renderGeometry(g, program); gl::Stacks::modelview().pop(); }
void UniformGroup::apply_subroutines(ProgramPtr prog, GLenum shadertype, const std::unordered_map<std::string, std::string>& subroutines) { assert_gl("apply_subroutines:enter"); GLint num_uniform_locations; glGetProgramStageiv(prog->get_id(), shadertype, GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS, &num_uniform_locations); std::vector<GLuint> subroutine_mappings; for(int i = 0; i < num_uniform_locations; ++i) { char name[256]; GLsizei length; glGetActiveSubroutineUniformName(prog->get_id(), shadertype, i, sizeof(name), &length, name); const auto& it = subroutines.find(name); if (it == subroutines.end()) { log_error("unmapped subroutine: %s", name); } else { GLuint loc = glGetSubroutineIndex(prog->get_id(), shadertype, it->second.c_str()); if (loc == GL_INVALID_INDEX) { log_error("unknown subroutine: %s", it->second); } else { subroutine_mappings.emplace_back(loc); } } } glUniformSubroutinesuiv(shadertype, subroutine_mappings.size(), subroutine_mappings.data()); assert_gl("apply_subroutines:exit"); }
bool Parser::parse(const wchar_t* code, const ProgramPtr& program) { tokenizer->set(code); try { Token token; while(peek(token)) { StatementPtr statement = parseStatement(); if(!statement) break; program->addStatement(statement); match(L";"); } } catch(...) { return false; } return true; }
void Uniform<UniformSymbol>::apply(ProgramPtr prog, const RenderContext& ctx) { assert_gl("Uniform<UniformSymbol>::apply:enter"); switch(m_value) { case UniformSymbol::NormalMatrix: prog->set_uniform(m_name, glm::mat3(ctx.get_view_matrix() * ctx.get_model_matrix())); break; case UniformSymbol::ViewMatrix: prog->set_uniform(m_name, ctx.get_view_matrix()); break; case UniformSymbol::ModelMatrix: prog->set_uniform(m_name, ctx.get_model_matrix()); break; case UniformSymbol::ModelViewMatrix: prog->set_uniform(m_name, ctx.get_view_matrix() * ctx.get_model_matrix()); break; case UniformSymbol::ProjectionMatrix: prog->set_uniform(m_name, ctx.get_projection_matrix()); break; case UniformSymbol::ModelViewProjectionMatrix: prog->set_uniform(m_name, ctx.get_projection_matrix() * ctx.get_view_matrix() * ctx.get_model_matrix()); break; default: log_error("unknown UniformSymbol %d", static_cast<int>(m_value)); break; } assert_gl("Uniform<UniformSymbol>::apply:exit"); }
/** Bind a program Program have bindings globalVar->parameter */ void GLEngine::setProgram(ProgramPtr program) { if(mCurrentProgram.get() == program.get()) return; mCurrentProgram = program; }
void apply(ProgramPtr prog, const RenderContext& ctx) { prog->set_uniform(m_name, m_value); }
void GlUtils::renderArtificialHorizon(float alpha) { static GeometryPtr geometry; if (!geometry) { Mesh mesh; MatrixStack & m = mesh.getModel(); m.push(); { m.top() = glm::translate(glm::mat4(), glm::vec3(0, 0, 1.01)); mesh.getColor() = Colors::yellow; mesh.addQuad(0.5, 0.05f); mesh.fillColors(true); mesh.getColor() = Colors::lightGray; glm::vec2 bar(0.5, 0.025); glm::vec2 smallBar(0.3, 0.015); for (int i = 1; i <= 4; ++i) { float angle = i * (TAU / 18.0f); m.identity().rotate(angle, GlUtils::X_AXIS).translate( GlUtils::Z_AXIS); mesh.addQuad(bar); m.identity().rotate(HALF_TAU, GlUtils::Y_AXIS).rotate(angle, GlUtils::X_AXIS).translate(GlUtils::Z_AXIS); mesh.addQuad(bar); m.identity().rotate(HALF_TAU, GlUtils::Z_AXIS).rotate(angle, GlUtils::X_AXIS).translate(GlUtils::Z_AXIS); mesh.addQuad(bar); m.identity().rotate(HALF_TAU, GlUtils::Z_AXIS).rotate(HALF_TAU, GlUtils::Y_AXIS).rotate(angle, GlUtils::X_AXIS).translate( GlUtils::Z_AXIS); mesh.addQuad(bar); angle -= (TAU / 36.0f); m.identity().rotate(angle, GlUtils::X_AXIS).translate( GlUtils::Z_AXIS); mesh.addQuad(smallBar); m.identity().rotate(HALF_TAU, GlUtils::Y_AXIS).rotate(angle, GlUtils::X_AXIS).translate(GlUtils::Z_AXIS); mesh.addQuad(smallBar); m.identity().rotate(HALF_TAU, GlUtils::Z_AXIS).rotate(angle, GlUtils::X_AXIS).translate(GlUtils::Z_AXIS); mesh.addQuad(smallBar); m.identity().rotate(HALF_TAU, GlUtils::Z_AXIS).rotate(HALF_TAU, GlUtils::Y_AXIS).rotate(angle, GlUtils::X_AXIS).translate( GlUtils::Z_AXIS); mesh.addQuad(smallBar); } } m.pop(); mesh.fillNormals(true); const Mesh & hemi = getMesh(Resource::MESHES_HEMI_CTM); m.top() = glm::rotate(glm::mat4(), -QUARTER_TAU, GlUtils::X_AXIS); mesh.getColor() = Colors::cyan; mesh.addMesh(hemi, true); m.top() = glm::rotate(glm::mat4(), QUARTER_TAU, GlUtils::X_AXIS); mesh.getColor() = Colors::orange; mesh.addMesh(hemi); { set<int> poleIndices; for (size_t i = 0; i < mesh.positions.size(); ++i) { const glm::vec4 & v = mesh.positions[i]; if (abs(v.x) < EPSILON && abs(v.z) < EPSILON) { poleIndices.insert(i); } } for (size_t i = 0; i < mesh.indices.size(); i += 3) { bool black = false; for (size_t j = i; j < i + 3; ++j) { if (poleIndices.count(mesh.indices[j])) { black = true; break; } } if (black) { for (size_t j = i; j < i + 3; ++j) { mesh.colors[mesh.indices[j]] = Colors::grey; } } } } geometry = mesh.getGeometry(); } ProgramPtr program = getProgram( Resource::SHADERS_LITCOLORED_VS, Resource::SHADERS_LITCOLORED_FS); program->use(); program->setUniform("ForceAlpha", alpha); renderGeometry(geometry, program); }
bool Compiler::CompileShaderPrimary( const ShaderInput& inputDesc, const ShaderOutput& outputDesc, Reflection::ReflectionData* reflectionData) { /* Validate arguments */ ValidateArguments(inputDesc, outputDesc); /* ----- Pre-processing ----- */ timePoints_.preprocessor = Time::now(); std::unique_ptr<IncludeHandler> stdIncludeHandler; if (!inputDesc.includeHandler) stdIncludeHandler = std::unique_ptr<IncludeHandler>(new IncludeHandler()); auto includeHandler = (inputDesc.includeHandler != nullptr ? inputDesc.includeHandler : stdIncludeHandler.get()); std::unique_ptr<PreProcessor> preProcessor; if (IsLanguageHLSL(inputDesc.shaderVersion)) preProcessor = MakeUnique<PreProcessor>(*includeHandler, log_); else if (IsLanguageGLSL(inputDesc.shaderVersion)) preProcessor = MakeUnique<GLSLPreProcessor>(*includeHandler, log_); const bool writeLineMarksInPP = (!outputDesc.options.preprocessOnly || outputDesc.formatting.lineMarks); const bool writeLineMarkFilenamesInPP = (!outputDesc.options.preprocessOnly || IsLanguageHLSL(inputDesc.shaderVersion)); auto processedInput = preProcessor->Process( std::make_shared<SourceCode>(inputDesc.sourceCode), inputDesc.filename, writeLineMarksInPP, writeLineMarkFilenamesInPP, ((inputDesc.warnings & Warnings::PreProcessor) != 0) ); if (reflectionData) reflectionData->macros = preProcessor->ListDefinedMacroIdents(); if (!processedInput) return ReturnWithError(R_PreProcessingSourceFailed); if (outputDesc.options.preprocessOnly) { (*outputDesc.sourceCode) << processedInput->rdbuf(); return true; } /* ----- Parsing ----- */ timePoints_.parser = Time::now(); std::unique_ptr<IntrinsicAdept> intrinsicAdpet; ProgramPtr program; if (IsLanguageHLSL(inputDesc.shaderVersion)) { /* Establish intrinsic adept */ intrinsicAdpet = MakeUnique<HLSLIntrinsicAdept>(); /* Parse HLSL input code */ HLSLParser parser(log_); program = parser.ParseSource( std::make_shared<SourceCode>(std::move(processedInput)), outputDesc.nameMangling, inputDesc.shaderVersion, outputDesc.options.rowMajorAlignment, ((inputDesc.warnings & Warnings::Syntax) != 0) ); } else if (IsLanguageGLSL(inputDesc.shaderVersion)) { /* Establish intrinsic adept */ #if 0 intrinsicAdpet = MakeUnique<GLSLIntrinsicAdept>(); #else //!!! intrinsicAdpet = MakeUnique<HLSLIntrinsicAdept>(); #endif /* Parse GLSL input code */ GLSLParser parser(log_); program = parser.ParseSource( std::make_shared<SourceCode>(std::move(processedInput)), outputDesc.nameMangling, inputDesc.shaderVersion, ((inputDesc.warnings & Warnings::Syntax) != 0) ); } if (!program) return ReturnWithError(R_ParsingSourceFailed); /* ----- Context analysis ----- */ timePoints_.analyzer = Time::now(); bool analyzerResult = false; if (IsLanguageHLSL(inputDesc.shaderVersion)) { /* Analyse HLSL program */ HLSLAnalyzer analyzer(log_); analyzerResult = analyzer.DecorateAST(*program, inputDesc, outputDesc); } /* Print AST */ if (outputDesc.options.showAST) { ASTPrinter printer; printer.PrintAST(program.get()); } if (!analyzerResult) return ReturnWithError(R_AnalyzingSourceFailed); /* Optimize AST */ timePoints_.optimizer = Time::now(); if (outputDesc.options.optimize) { Optimizer optimizer; optimizer.Optimize(*program); } /* ----- Code generation ----- */ timePoints_.generation = Time::now(); bool generatorResult = false; if (IsLanguageGLSL(outputDesc.shaderVersion) || IsLanguageESSL(outputDesc.shaderVersion) || IsLanguageVKSL(outputDesc.shaderVersion)) { /* Generate GLSL output code */ GLSLGenerator generator(log_); generatorResult = generator.GenerateCode(*program, inputDesc, outputDesc, log_); } if (!generatorResult) return ReturnWithError(R_GeneratingOutputCodeFailed); /* ----- Code reflection ----- */ timePoints_.reflection = Time::now(); if (reflectionData) { ReflectionAnalyzer reflectAnalyzer(log_); reflectAnalyzer.Reflect( *program, inputDesc.shaderTarget, *reflectionData, ((inputDesc.warnings & Warnings::CodeReflection) != 0) ); } return true; }
void EdvsRiftApp::drawEvents() { static ProgramPtr program = oria::loadProgram("./resources/event_pixel.vs", "./resources/event_pixel.fs"); // Reset before application exit Platform::addShutdownHook([] { program.reset(); }); MatrixStack & mv = Stacks::modelview(); mv.withPush([&] { // Binds the program program->Use(); // Matrices as uniforms Mat4Uniform(*program, "ModelView").Set(Stacks::modelview().top()); Mat4Uniform(*program, "Projection").Set(Stacks::projection().top()); // Manual set for azimuth and elevation oglplus::Uniform<float>(*program, "ManAzimuth").Set(azimuth); oglplus::Uniform<float>(*program, "ManElevation").Set(elevation); // Manual set for field of view oglplus::Uniform<float>(*program, "FovX").Set(60.0 * DEGREES_TO_RADIANS); oglplus::Uniform<float>(*program, "FovY").Set(60.0 * DEGREES_TO_RADIANS); // Bind VAO vao->Bind(); // Bind VBO "Positions" vbo_position->Bind(Buffer::Target::Array); { Buffer::Data(Buffer::Target::Array, position_); VertexArrayAttrib vao_attr(*program, "Position"); vao_attr.Setup<Vec2f>(); vao_attr.Enable(); } // Bind VBO "CameraId" vbo_camera_id->Bind(Buffer::Target::Array); { Buffer::Data(Buffer::Target::Array, camera_id_); VertexArrayAttrib vao_attr(*program, "CameraId"); vao_attr.Setup<Vec1f>(); vao_attr.Enable(); } // Bind VBO "Color" vbo_color->Bind(Buffer::Target::Array); { Buffer::Data(Buffer::Target::Array, parity_); //, BufferUsage::StreamDraw); VertexArrayAttrib vao_attr(*program, "Color"); vao_attr.Setup<Vec1f>(); vao_attr.Enable(); } // Draw all elements Context::DrawArrays(PrimitiveType::Points, 0, camera_id_.size()); }); // Unbind oglplus::NoProgram().Bind(); oglplus::NoVertexArray().Bind(); }
inline GLhandleARB handleOf(const ProgramPtr& p) { return (p ? p->getHandle() : 0); }