Ejemplo n.º 1
0
void AFK_3DEdgeShapeBase::initGL()
{
    bool needBufferPush = (bufs == nullptr);
    if (needBufferPush)
    {
        bufs = new GLuint[2];
        glGenBuffers(2, bufs);
    }

    glBindBuffer(GL_ARRAY_BUFFER, bufs[0]);
    if (needBufferPush)
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vec2<float>), &vertices[0], GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufs[1]);
    if (needBufferPush)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vec2<float>), 0);

    /* Overlap works based on squares of 2 triangles.  Since I
     * want to be able to cull in pairs, I'm going to use
     * triangle strips with primitive restart as my base
     * geometry type.
     */
    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(RESTART_INDEX);
}
Ejemplo n.º 2
0
void Geometry::construct()
{
	GLenum error = glGetError();
	constructed = true;
	glGenVertexArrays(1, &vaid);
	error = glGetError();
	glGenBuffers(1, &vbid);
	error = glGetError();
	glGenBuffers(1, &ibid);
	error = glGetError();

	glEnable(GL_PRIMITIVE_RESTART);
	glPrimitiveRestartIndex(-1);
	glBindVertexArray(vaid);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibid);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indexCount, indexValueBuffer, GL_STATIC_DRAW);
	error = glGetError();
	glBindBuffer(GL_ARRAY_BUFFER, vbid);
	glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertexCount, vertexValueBuffer, GL_STATIC_DRAW);
	error = glGetError();
	glEnableVertexAttribArray(ATTR_POS);
	glEnableVertexAttribArray(ATTR_COLOR);
	glEnableVertexAttribArray(ATTR_TEX_COORDS);
	error = glGetError();
	glVertexAttribPointer(ATTR_POS, 3, GL_FLOAT, false, 8*sizeof(GLfloat), 0);
	glVertexAttribPointer(ATTR_COLOR, 3, GL_FLOAT, false, 8*sizeof(GLfloat), (GLvoid*) (3*sizeof(GLfloat)));
	glVertexAttribPointer(ATTR_TEX_COORDS, 2, GL_FLOAT, false, 8*sizeof(GLfloat), (GLvoid*) (6*sizeof(GLfloat)));
	error = glGetError();
	glBindVertexArray(0);
}
    virtual void render(bool use_vbo) const
    {
      VL_CHECK(GLEW_VERSION_1_4);
      VL_CHECK(!use_vbo || (use_vbo && (GLEW_ARB_vertex_buffer_object||GLEW_VERSION_1_5||GLEW_VERSION_3_0)))
      use_vbo &= GLEW_ARB_vertex_buffer_object||GLEW_VERSION_1_5||GLEW_VERSION_3_0; // && indices()->gpuBuffer()->handle() && indices()->sizeGPU();
      if ( !use_vbo && !indices()->size() )
        return;

      // apply patch parameters if any and if using PT_PATCHES
      applyPatchParameters();

      // primitive restart enable
      if(primitiveRestartEnabled())
      {
        if(GLEW_VERSION_3_1)
        {
          glEnable(GL_PRIMITIVE_RESTART);
          glPrimitiveRestartIndex(primitiveRestartIndex());
        }
        else
        if(GLEW_NV_primitive_restart)
        {
          glEnable(GL_PRIMITIVE_RESTART_NV);
          glPrimitiveRestartIndexNV(primitiveRestartIndex());
        }
        else
        {
          vl::Log::error("MultiDrawElements error: primitive restart not supported by this OpenGL implementation!\n");
          VL_TRAP();
          return;
        }
      }

      GLvoid **indices_ptr = (GLvoid**)&mPointerVector[0];
      if (use_vbo && indices()->gpuBuffer()->handle())
      {
        VL_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices()->gpuBuffer()->handle());
        indices_ptr = (GLvoid**)&mNULLPointerVector[0];
      }
      else
        VL_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

      if (baseVertices().size())
      {
        VL_CHECK( baseVertices().size() == pointerVector().size() )
        VL_CHECK( baseVertices().size() == countVector().size() )
        if (GLEW_ARB_draw_elements_base_vertex || GLEW_VERSION_3_1)
          glMultiDrawElementsBaseVertex( 
            primitiveType(), (GLsizei*)&mCountVector[0], indices()->glType(), indices_ptr, (GLsizei)mCountVector.size(), (GLint*)&mBaseVertices[0] 
          );
        else
        {
          vl::Log::error("MultiDrawElements::render(): glMultiDrawElementsBaseVertex() not supported!\n"
            "OpenGL 3.1 or GL_ARB_draw_elements_base_vertex extension required.\n"
          );
        }
      }
void PCPUploadRenderer::renderParallelCoordinates() {
    std::shared_ptr<const ParallelCoordinatesPlotRawData> data = _inport.getData();
    int nDimensions = data->minMax.size();
    int nValues = data->data.size();

    utilgl::GlBoolState depthTest(GL_DEPTH_TEST, !_depthTesting);
    utilgl::BlendModeEquationState blendEquation(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_FUNC_ADD);

    utilgl::GlBoolState lineSmooth(GL_LINE_SMOOTH, _lineSmoothing);
    if (_lineSmoothing)
        glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);

    _shader.activate();

    _shader.setUniform("_nDimensions", nDimensions);
    _shader.setUniform("_nData", nValues / nDimensions);
    _shader.setUniform("_horizontalBorder", _horizontalBorder);
    _shader.setUniform("_verticalBorder", _verticalBorder);
    _shader.setUniform("_depthTesting", !_depthTesting);
    _shader.setUniform("_alphaFactor", _alphaFactor);

    TextureUnit tfUnit;
    utilgl::bindTexture(_transFunc, tfUnit);
    _shader.setUniform("_transFunc", tfUnit.getUnitNumber());

    glBindVertexArray(_vao);

    bool hasColoringData = _coloringData.hasData() && _coloringData.getData()->hasData;
    _shader.setUniform("_hasColoringData", hasColoringData);
    if (hasColoringData) {
        glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, _coloringData.getData()->ssboColor);
    }

    //glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, data->ssboData);
    glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 3, _dimensionOrderingBuffer);

    //for (int i = 0; i < nValues / nDimensions; ++i) {
    //    glDrawElements(GL_LINE_STRIP, nDimensions, )
    //}

    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(PRIM_RESTART);

    glDrawElements(GL_LINE_STRIP, nValues / nDimensions, GL_UNSIGNED_INT, _drawElements);


    glDisable(GL_PRIMITIVE_RESTART);
    //glDrawArrays(GL_LINE_STRIP, 0, nValues);

    //glMultiDrawArrays(GL_LINE_STRIP, _multiDrawIndices, _multiDrawCount, nValues / nDimensions);

    //glDrawArraysInstanced(GL_LINE_STRIP, 0, data->nDimensions, data->nValues / data->nDimensions);

    glBindVertexArray(0);

    _shader.deactivate();
}
Ejemplo n.º 5
0
void restart_strip( Mesh& m )
{
    m.indices.push_back(~0u);   // ~0u plus grand entier non signe representable
#if 1
    glPrimitiveRestartIndex(~0u);
    glEnable(GL_PRIMITIVE_RESTART);
#else
    glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX); // n'existe pas sur mac ?!
#endif
}
Ejemplo n.º 6
0
static void
enable_restart(GLuint restart_index)
{
   if (TestGL31) {
      glEnable(GL_PRIMITIVE_RESTART);
      glPrimitiveRestartIndex(restart_index);
   }
   else {
      glEnableClientState(GL_PRIMITIVE_RESTART_NV);
      glPrimitiveRestartIndexNV(restart_index);
   }
}
Ejemplo n.º 7
0
  void CRasterTerrainModel::Render() const 
  {
    //glColor3f(1.0f, 0.0f, 0.0f);
    if (glPrimitiveRestartIndex == nullptr)  {
      GLenum glew_err = glewInit();
      if (glew_err != GLEW_NO_ERROR) {
        std::cout << "failed to initialize opengl extension wrapper: " << (const char*)glewGetErrorString(glew_err) << std::endl;
        return;
      }
    }
    
    glEnable(GL_POLYGON_OFFSET_FILL);
    glEnable(GL_POLYGON_OFFSET_LINE);
    glPolygonOffset(1.0, 1.0);
    

    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(UINT_MAX);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);

    //reset number of rendered triangles
    mNumberOfRenderedTriangles = 0;

    std::vector<Patch*>::const_iterator itr, itre = mActivePatches.end();
    for (itr = mActivePatches.begin(); itr != itre; ++itr) {
      Patch* p = (*itr);

      //compute id
      uint hlv = p->neigbor[0] ? p->neigbor[0]->tessLevel : 0;
      uint vlv = p->neigbor[1] ? p->neigbor[1]->tessLevel : 0;
      uint cid = p->GetCIndex();
      uint tessID = vlv + hlv*mTessLevels + cid*(mTessLevels*mTessLevels);

      glBindBuffer(GL_ARRAY_BUFFER, p->glbuf);
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mTessellationIBOs[tessID]);
      glVertexPointer(3, GL_FLOAT, sizeof(CRasterTerrainModel::Vertex), 0);
      glNormalPointer(GL_FLOAT, sizeof(CRasterTerrainModel::Vertex), (void*)12);
      //glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>((*itr)->vbuf.size()));
      glDrawElements(GL_TRIANGLE_STRIP, static_cast<GLsizei>(mTessellationIBufs[tessID].size()), GL_UNSIGNED_INT, 0);

      //count number of rendered triangles
      mNumberOfRenderedTriangles += static_cast<unsigned int>(mTessellationIBufs[tessID].size());
    }

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisable(GL_PRIMITIVE_RESTART);
    glDisable(GL_POLYGON_OFFSET_LINE);
    glDisable(GL_POLYGON_OFFSET_FILL);
  }
///////////////////////////////////////////////////////////////////////////////
// Function Name: display
//
// Purpose: GLUT display callback.
// 
// INPUTS: None.
//
// OUTPUTS: None.
//
///////////////////////////////////////////////////////////////////////////////
void display()
{
    float t = float(GetTickCount() & 0x1FFF) / float(0x1FFF);
    const vmath::vec3 Y(0.0f, 1.0f, 0.0f);
    const vmath::vec3 Z(0.0f, 0.0f, 1.0f);

    // Setup
    glEnable(GL_CULL_FACE);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Activate simple shading program
    glUseProgram(shader_prog);

    // Set up the model and projection matrix
    vmath::mat4 model_matrix(vmath::translate(0.0f, 0.0f, -5.0f) * 
                             vmath::rotate(t * 360.0f, Y) *
                             vmath::rotate(t * 720.0f, Z));

    vmath::mat4 projection_matrix(vmath::frustum(-1.0f, 1.0f, -aspect, 
                                                 aspect, 1.0f, 20.0f));

    glUniformMatrix4fv(model_matrix_loc, 1, GL_FALSE, model_matrix);
    glUniformMatrix4fv(projection_matrix_loc, 1, GL_FALSE, projection_matrix);

    // Set up for a glDrawElements call
    glBindVertexArray(vao);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);

#ifdef USE_PRIMITIVE_RESTART
    // When primitive restart is on, we can call one draw command
    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(0xFFFF);
    glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
#else
    // Without primitive restart, we need to call two draw commands
    glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
    glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT,
                   BUFFER_OFFSET(9 * sizeof(GLushort)));
#endif

    glDisable(GL_CULL_FACE);
    glUseProgram(0);

    glutSwapBuffers();
}
Ejemplo n.º 9
0
void CHeightMap::Render()
{
	ProgramTerrain.Use();

	ProgramTerrain.SetUniform("fRenderHeight", RenderScale.y);
	ProgramTerrain.SetUniform("fMaxTextureU", float(cols)*0.1f);
	ProgramTerrain.SetUniform("fMaxTextureV", float(rows)*0.1f);

	ProgramTerrain.SetUniform("HeightmapScaleMatrix", RenderScaleMatrix);
	ProgramTerrain.SetUniform("NormalScaleMatrix", NormalScaleMatrix);

	glBindVertexArray(vao);
	glEnable(GL_PRIMITIVE_RESTART);
	glPrimitiveRestartIndex(rows*cols);

	int NumIndices = (rows - 1) * cols * 2 + rows - 1;
	glDrawElements(GL_TRIANGLE_STRIP, NumIndices, GL_UNSIGNED_INT, 0);
}
Ejemplo n.º 10
0
void C4ParticleList::Draw(C4TargetFacet cgo, C4Object *obj)
{
	if (particleChunks.empty()) return;

	pDraw->DeactivateBlitModulation();
	pDraw->ResetBlitMode();
	
	glPrimitiveRestartIndex(0xffffffff);
	glEnable(GL_PRIMITIVE_RESTART);

	// enable shader
	C4ShaderCall call(pGL->GetSpriteShader(true, false, false));
	// apply zoom and upload shader uniforms
	StdProjectionMatrix modelview = StdProjectionMatrix::Identity();
	pGL->SetupMultiBlt(call, NULL, 0, 0, 0, 0, &modelview);
	// go to correct output position (note the normal matrix is unaffected
	// by this)
	Translate(modelview, cgo.X-cgo.TargetX, cgo.Y-cgo.TargetY, 0.0f);
	// allocate texture unit for particle texture, and remember allocated
	// texture unit. Will be used for each particle chunk to bind
	// their texture to this unit.
	const GLint texUnit = call.AllocTexUnit(C4SSU_BaseTex);

	accessMutex.Enter();

	for (std::list<C4ParticleChunk*>::iterator iter = particleChunks.begin(); iter != particleChunks.end(); )
	{
		if ((*iter)->IsEmpty())
		{
			delete *iter;
			iter = particleChunks.erase(iter);
			lastAccessedChunk = 0;
		}
		else
		{
			(*iter)->Draw(cgo, obj, call, texUnit, modelview);
			++iter;
		}
	}

	accessMutex.Leave();

	glDisable(GL_PRIMITIVE_RESTART);
}
Ejemplo n.º 11
0
void Water::constructGrid() {
    const double STEP = (1.0 / GRID_SIZE) * 2.0;

    // construct vertices grid
    Point points [GRID_SIZE + 1][GRID_SIZE + 1];
    Point point;
    point.y = 1.0f;
    int currentIndice = 0;
    point.indice = currentIndice;
    for (int row = 0; row <= GRID_SIZE; ++row) {
        point.x = -1.0f;
        for (int col = 0; col <= GRID_SIZE; ++col) {
            points[row][col] = point;
            _vertices.push_back(point.x);
            _vertices.push_back(point.y);
            point.x = point.x + STEP;
            point.y = point.y;
            currentIndice = currentIndice + 1;
            point.indice = currentIndice;
        }
        point.y = point.y - STEP;
    }

    // bind triangles
    int primitive_restart_idx = 0xffffffff;
    glPrimitiveRestartIndex(primitive_restart_idx);
    glEnable(GL_PRIMITIVE_RESTART);

    for (int row = 0; row <= GRID_SIZE - 1  ; ++row ) {
        for (int col = 0; col <= GRID_SIZE; ++col) {
            Point point;
            point = points[row][col];
            _indices.push_back(point.indice);
            point = points[row + 1][col];
            _indices.push_back(point.indice);
            if (col == GRID_SIZE) {
                _indices.push_back(primitive_restart_idx);
                point = points[row + 1][0];
                _indices.push_back(point.indice);
            }
        }
    }
}
static void
draw_pattern(int restart_pos, bool use_primitive_restart)
{
	/* Draw test pattern in blue */
	glUniform4f(color_loc, 0.25, 0.25, 1.0, 1.0);
	if (use_primitive_restart) {
		GLubyte index_buffer[NUM_VERTICES + 1];
		int i;

		for (i = 0; i < restart_pos; i++) {
			index_buffer[i] = i;
		}
		index_buffer[restart_pos] = 0xff;
		for (i = restart_pos + 1; i < ARRAY_SIZE(index_buffer); i++) {
			index_buffer[i] = i - 1;
		}
		if (piglit_get_gl_version() >= 31) {
			glEnable(GL_PRIMITIVE_RESTART);
			glPrimitiveRestartIndex(0xff);
		} else {
			glEnableClientState(GL_PRIMITIVE_RESTART_NV);
			glPrimitiveRestartIndexNV(0xff);
		}
		glDrawElements(test->prim_type, ARRAY_SIZE(index_buffer),
			       GL_UNSIGNED_BYTE, index_buffer);
		if (piglit_get_gl_version() >= 31)
			glDisable(GL_PRIMITIVE_RESTART);
		else
			glDisableClientState(GL_PRIMITIVE_RESTART_NV);
	} else {
		glDrawArrays(test->prim_type, 0, restart_pos);
		glDrawArrays(test->prim_type, restart_pos,
			     NUM_VERTICES - restart_pos);
	}

	if (test->prim_type != GL_POINTS) {
		/* Draw vertices in white */
		glUniform4f(color_loc, 1.0, 1.0, 1.0, 1.0);
		glDrawArrays(GL_POINTS, 0, NUM_VERTICES);
	}
}
  void initGl() {
    RiftGlfwApp::initGl();
    glDisable(GL_BLEND);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(UINT_MAX);
    glClearColor(0.1f, 0.1f, 0.1f, 1.0f);

    program = GlUtils::getProgram(
        Resource::SHADERS_TEXTURED_VS,
        Resource::SHADERS_TEXTURED_FS);
    program->use();

    DistortionHelper distortionHelper(ovrHmdInfo);

    // Load scene textures and generate distortion meshes
    for_each_eye([&](StereoEye eye){
      GlUtils::getImageAsTexture(textures[eye], SCENE_IMAGES[eye]);
      distortionGeometry[eye] = distortionHelper.createDistortionMesh(glm::uvec2(64, 64), eye);
    });
  }
Ejemplo n.º 14
0
void render_room(glm::mat4 MVP)
{
	glm::mat4 P = camera.P;
	glm::mat4 V = camera.V;

	static float	angle = 0.0f;
	angle += 100.0f;
	if (angle > 360.0f)	angle -= 360.0f;

	glFrontFace(GL_CW);
	glUseProgram(h_prog_room);

	glActiveTexture(GL_TEXTURE0 + tex_unit);
	glBindTexture(GL_TEXTURE_CUBE_MAP, tex);

	glBindVertexArray(vao_room);
	glEnable(GL_PRIMITIVE_RESTART);

	glUniformMatrix4fv(glGetUniformLocation(h_prog_room, "MVP"), 1, GL_FALSE, glm::value_ptr(P*V));

	glPrimitiveRestartIndex(0xFFFF);
	glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
	glDisable(GL_PRIMITIVE_RESTART);

	glFrontFace(GL_CCW);


	//glUseProgram(h_prog_cubemap);
	//glActiveTexture(GL_TEXTURE0 + tex_unit);
	//glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
	//glm::mat4	M = glm::rotate(glm::mat4(1.0f), angle, glm::vec3(0.0f, 1.0f, 0.0f));
	////glUniformMatrix4fv(glGetUniformLocation(h_prog_cubemap, "MVP"), 1, GL_FALSE, glm::value_ptr(P*V*M));
	////glUniformMatrix4fv(glGetUniformLocation(h_prog_cubemap, "MV"), 1, GL_FALSE, glm::value_ptr(V*M));
	////glUniformMatrix3fv(glGetUniformLocation(h_prog_cubemap, "M_normal"), 1, GL_FALSE, glm::value_ptr(glm::mat3(V*M)));

	//glUniformMatrix4fv(glGetUniformLocation(h_prog_cubemap, "MVP"), 1, GL_FALSE, glm::value_ptr(MVP));


}
Ejemplo n.º 15
0
/**
 * Simulate the action of the 3 geometry shader invocations by making
 * 3 glDrawElements() calls.  Primitive restart is used to simulate
 * the action of EndPrimitive().
 */
static void
draw_ref_pattern()
{
	int i, vertex_count, end_prim_offset;

	glUseProgram(prog_ref);
	glUniform1i(glGetUniformLocation(prog_ref, "num_vertices"),
		    num_vertices);
	glEnable(GL_PRIMITIVE_RESTART);
	glPrimitiveRestartIndex(0xffffffff);

	for (end_prim_offset = 0; end_prim_offset < 3; end_prim_offset++) {
		/* Note: this over-allocates the buffer somewhat.  The
		 * actual amount of buffer space we need is a complex
		 * formula involving num_vertices and end_prim_offset,
		 * and it's not worth computing precisely.
		 */
		GLuint *index_buffer =
			malloc(2 * sizeof(GLuint) * num_vertices);
		i = vertex_count = 0;
		while (true) {
			if (i % 3 == end_prim_offset)
				index_buffer[vertex_count++] = 0xffffffff;
			if (i == num_vertices)
				break;
			index_buffer[vertex_count++] = i++;
		}
		glUniform1i(glGetUniformLocation(prog_ref, "end_prim_offset"),
			    end_prim_offset);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER,
			     sizeof(GLuint) * vertex_count, index_buffer,
			     GL_STATIC_DRAW);
		free(index_buffer);
		glDrawElements(GL_TRIANGLE_STRIP, vertex_count,
			       GL_UNSIGNED_INT, NULL);
	}

	glDisable(GL_PRIMITIVE_RESTART);
}
Ejemplo n.º 16
0
ImageGL::ImageGL(unsigned int nDispWidth,
                 unsigned int nDispHeight,
                 unsigned int nTexWidth,
                 unsigned int nTexHeight,
                 bool bVsync, 
                 PixelFormat ePixelFormat)
    : nWidth_(nDispWidth)
    , nHeight_(nDispHeight)
    , nTexWidth_(nTexWidth)
    , nTexHeight_(nTexHeight)
    , e_PixFmt_(ePixelFormat)
    , bVsync_(bVsync) 
    , bIsCudaResource_(false)
{
    int nFrames = bVsync_ ? 3 : 1;

    glGenBuffersARB(nFrames, gl_pbo_);

    for (int n=0; n < nFrames; n++)
    {
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, gl_pbo_[n]);
        glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, nTexWidth*nTexHeight*4, NULL, GL_STREAM_DRAW_ARB);
        glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
        registerAsCudaResource(n);
    }

    // create texture for display
    glGenTextures(nFrames, gl_texid_);

    // setup the Texture filtering mode
    setTextureFilterMode(GL_NEAREST, GL_NEAREST);

    // load gl_shader_ program
    gl_shader_ = compile_glsl_shader(GL_FRAGMENT_PROGRAM_ARB, gl_shader_code);

	glPrimitiveRestartIndex(65535);
	glEnable(GL_PRIMITIVE_RESTART);

}
Ejemplo n.º 17
0
Tile::Tile(GLuint shader_id, int x, int z)
{
    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glGenBuffers(1, &ebo);

    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);

    GLuint posAttrib = glGetAttribLocation(shader_id, "position_model");
    GLuint norAttrib = glGetAttribLocation(shader_id, "normal_model");
    GLuint texAttrib = glGetAttribLocation(shader_id, "texcoord");
    GLuint colAttrib = glGetAttribLocation(shader_id, "color");
    glEnableVertexAttribArray(posAttrib);
    glEnableVertexAttribArray(norAttrib);
    glEnableVertexAttribArray(texAttrib);
    glEnableVertexAttribArray(colAttrib);
    glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 11*sizeof(float), 0 );
    glVertexAttribPointer(norAttrib, 3, GL_FLOAT, GL_FALSE, 11*sizeof(float), (void*)(3*sizeof(float)));
    glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 11*sizeof(float), (void*)(6*sizeof(float)));
    glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 11*sizeof(float), (void*)(8*sizeof(float)));

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex((TILE_SIZE+1)*(TILE_SIZE+1)+TILE_SIZE);

    reload_vbo = false;
    reload_ebo = false;
    needs_rebuild = false;
    needs_gen = true;
    show = false;

    lod(0);
    set_xz(x,z);
    update_vertices();
    update_indices();
}
Ejemplo n.º 18
0
void Renderer::init()
{
#ifdef OCULUSVR
    initOVR();
#endif

    SDL_GL_SetSwapInterval(1); // vsync
    glEnable(GL_DEPTH_TEST);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // the default is 4
    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(0xFFFF);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    skyRenderer_.reset(new SkyRenderer());
    landRenderer_.reset(new LandRenderer());
    structureRenderer_.reset(new StructureRenderer());
    modelRenderer_.reset(new ModelRenderer());

    landRenderer_->setLightPosition(skyRenderer_->sunVector() * fp_t(1000.0));
}
Ejemplo n.º 19
0
 Grid(int grid_width, int grid_height){
     ///--- So that we don't have to bother with connectivity data structure!!
     int primitive_restart_idx = 0xffffffff;
     glPrimitiveRestartIndex(primitive_restart_idx);
     glEnable(GL_PRIMITIVE_RESTART);
     
     int skip = 1;
     
     ///--- Vertices
     for (int row = 0; row < grid_height; row+=skip) {
         for (int col = 0; col < grid_width; col+=skip) {
             Scalar x = col;
             Scalar y = row;
             vertices.push_back(x); /// i [0...width]
             vertices.push_back(y); /// y [0...height]
         }
     }
     
     ///--- TexCoords
     for (int row = 0; row < grid_height; row+=skip) {
         for (int col = 0; col < grid_width; col+=skip) {
             Scalar x = col/((Scalar)grid_width);
             Scalar y = row/((Scalar)grid_height);
             texcoords.push_back(x); /// u [0,1]
             texcoords.push_back(y); /// v [0,1]
         }
     }
 
     ///--- Faces
     for (int row = 0; row < grid_height - 1; row+=skip) {
         for (int col = 0; col < grid_width; col+=skip) {
             indices.push_back((row + 1) * grid_width + col);
             indices.push_back(row * grid_width + col);
         }
         indices.push_back(primitive_restart_idx);
     }
 }
Ejemplo n.º 20
0
void display(void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glUseProgram(program);

	GLint model_matrix_loc = glGetUniformLocation(program, "model_matrix");
	GLint projection_matrix_loc = glGetUniformLocation(program, "projection_matrix");

	float t = float(GetTickCount() & 0x1FFF) / float(0x1FFF);
	static float q = 0.0f;
	float aspect = 1.0f;
	static const vmath::vec3 X(1.0f, 0.0f, 0.0f);
	static const vmath::vec3 Y(0.0f, 1.0f, 0.0f);
	static const vmath::vec3 Z(0.0f, 0.0f, 1.0f);

	vmath::mat4 model_matrix(vmath::translate(0.0f, 0.0f, -5.0f) * vmath::rotate(t * 360.0f, Y) * vmath::rotate(t * 720.0f, Z));
	vmath::mat4 projection_matrix(vmath::frustum(-1.0f, 1.0f, -aspect, aspect, 1.0f, 500.0f));

	glUniformMatrix4fv(model_matrix_loc, 1, GL_FALSE, model_matrix);
	glUniformMatrix4fv(projection_matrix_loc, 1, GL_FALSE, projection_matrix);

	glBindVertexArray(VAOs[Triangles]);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Buffers[ElementBuffer]);

#if USE_PRIMITIVE_RESTART
	glEnable(GL_PRIMITIVE_RESTART);
	glPrimitiveRestartIndex(0xFFFF);
	glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, NULL);

#else 
	glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT, NULL);
	glDrawElements(GL_TRIANGLE_STRIP, 8, GL_UNSIGNED_SHORT, BUFFER_OFFSET(9 * sizeof(GLushort)));
#endif

	glFlush();
}
void
piglit_init(int argc, char **argv)
{
	static const float pos[] = {
		-1, -1,
		-1,  1,
		 1, -1,
		 1,  1,
		 1, -1,
		-1,  1,
	};
	static const short indices[] = {0, 1, 2, 0xFFFF, 3, 4, 5};
	GLuint vao, buf, elem;

	piglit_require_gl_version(33);
	piglit_require_extension("GL_ARB_ES3_compatibility");
	prog = piglit_build_simple_program(vstext, fstext);
	glUseProgram(prog);

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

	glGenBuffers(1, &buf);
	glBindBuffer(GL_ARRAY_BUFFER, buf);
	glBufferData(GL_ARRAY_BUFFER, sizeof(pos), pos, GL_STATIC_DRAW);

	glGenBuffers(1, &elem);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elem);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,
		     GL_STATIC_DRAW);

	glEnableVertexAttribArray(PIGLIT_ATTRIB_POS);
	glVertexAttribPointer(PIGLIT_ATTRIB_POS, 2, GL_FLOAT, 0, 0, NULL);

	glEnable(GL_PRIMITIVE_RESTART_FIXED_INDEX);
	glPrimitiveRestartIndex(2);
}
Ejemplo n.º 22
0
      void RenderEngineGLIndirect::render( RenderGroupGLHandle groupHandle, const dp::rix::core::RenderOptions& /*renderOptions*/ )
      {
        // if dirty, update sorted list
        RenderGroupGL::ProgramPipelineCaches::iterator glIt;
        RenderGroupGL::ProgramPipelineCaches::iterator glIt_end = groupHandle->m_programPipelineCaches.end();
        for ( glIt = groupHandle->m_programPipelineCaches.begin(); glIt != glIt_end; ++glIt )
        {
          ProgramPipelineGLHandle programPipeline = glIt->first;
          RenderGroupGLCache* cache = glIt->second.get<RenderGroupGLCache>();

#if RIX_GL_SEPARATE_SHADER_OBJECTS_SUPPORT == 1
          glBindProgramPipeline( programPipeline->m_pipelineId );
#else
          glUseProgram( programPipeline->m_programs[0]->getProgram()->getGLId() );
#endif

          //if ( giList->m_indirectEntries.size() != giList->m_geometryInstances.size())
          if ( !cache->m_initialized ) // TODO support changes
          {
            cache->m_initialized = true;

            RenderGroupGLCache::DrawArrayListEntry triangles;
            RenderGroupGLCache::DrawArrayListEntry lines;
            RenderGroupGLCache::DrawArrayListEntry linesStrips;

            //cache->m_indirectEntries.clear();
            //cache->m_indirectCommands.clear();
            for (size_t index = 0; index < cache->getGeometryInstances().size(); ++index )
            {
              GeometryInstanceGLHandle gi = cache->getGeometryInstances()[index];

              if ( !gi->getGeometry()->getIndices() )
              {
                switch ( gi->getGeometry()->getGeometryDescription()->getPrimitiveType() )
                {
                case GeometryPrimitiveType::TRIANGLES:
                  //drawEntry = &triangles;
                  addArrayIndirectCommand(gi, triangles);
                  break;
                case GeometryPrimitiveType::LINES:
                  addArrayIndirectCommand(gi, lines);
                  break;
                case GeometryPrimitiveType::LINE_STRIP:
                  addArrayIndirectCommand(gi, linesStrips);
                  break;
                default:
                  assert( 0 && "unsupported primitve types");
                }
              }
              else
              {
                //addElementIndirectCommand(cache, gi );
              }

            }

            addDrawArrayList( cache, triangles, GL_TRIANGLES);
            addDrawArrayList( cache, lines, GL_LINES );
            addDrawArrayList( cache, linesStrips, GL_LINE_STRIP );
            for ( size_t idx = 0;idx < cache->m_drawElementsList.size(); ++idx )
            {
              prepareDrawElementsEntry( &cache->m_drawElementsList[idx] );
            }

          }

          // prepare fixed containers
#if 0
          GeometryInstanceGLHandle gi = cache->getGeometryInstances()[0];
          for ( size_t containerIdx = 0; containerIdx < gi->m_containers.size(); ++containerIdx )
          {
            // debug info
            auto infos = gi->m_containers[containerIdx].container->m_descriptor->m_parameterInfos;
            for ( size_t infoIdx = 0; infoIdx < infos.size(); ++infoIdx )
            {
              std::cout << "c: " << containerIdx << ", infoIdX:" << infoIdx << ", name: " << infos[infoIdx].m_name << std::endl;
            }
          }
#endif
          assert( !"No implementation available atm");
          // TODO update to new interface
          //gi->m_containers[0].parameters[0]->update( gi->m_containers[0].container->m_data ); // sys_View
          //gi->m_containers[1].parameters[0]->update( gi->m_containers[1].container->m_data ); // lights


          for ( size_t idx = 0;idx < cache->m_drawArrayList.size(); ++idx )
          {
            RenderGroupGLCache::DrawArrayListEntry &entry = cache->m_drawArrayList[idx];

            glEnableVertexAttribArray( 12 );
            dp::gl::bind( GL_ARRAY_BUFFER, entry.m_indirectPointersBuffer->getBuffer() );
            glVertexAttribLPointerEXT( 12, 1, GL_UNSIGNED_INT64_NV, 0, 0 );
            glVertexAttribDivisor( 12, 1);
            // TODO update vertex attrib pointer to 64-bit values


            #define USE_DRAW_INDIRECT_BUFFER

#if 0

#if defined(USE_DRAW_INDIRECT_BUFFER) 
            dp::gl::bind( GL_DRAW_INDIRECT_BUFFER, entry.m_indirectCommandsBuffer->getBuffer() );
            size_t offset = 0;
            for (size_t index = 0; index < entry.m_indirectCommands.size(); ++index )
            {
              glDrawArraysIndirect( entry.m_primitiveType, (const void*)(offset) );
              offset += sizeof( RenderGroupGLCache::DrawArraysIndirectCommand );

            }
#else
            RenderGroupGLCache::DrawArraysIndirectCommand *command = &entry.m_indirectCommands[0];
            for (size_t index = 0; index < entry.m_indirectCommands.size(); ++index )
            {
              //glDrawArraysIndirect( entry.m_primitiveType, command );
              glDrawArraysInstancedBaseInstance( entry.m_primitiveType, command->first, command->count, command->primCount, command->baseInstance );
              //glDrawementsBaseVertex( entry.m_primitiveType, command->count, GL_UN)
              ++command;
            }
#endif

#else

#if defined(USE_DRAW_INDIRECT_BUFFER)
            dp::gl::bind( GL_DRAW_INDIRECT_BUFFER, entry.m_indirectCommandsBuffer->getBuffer() );
            glMultiDrawArraysIndirectAMD( entry.m_primitiveType, 0, static_cast<GLsizei>(entry.m_indirectCommands.size()), sizeof( RenderGroupGLCache::DrawArraysIndirectCommand ) );
#else
            RenderGroupGLCache::DrawArraysIndirectCommand *commands = &entry.m_indirectCommands[0];
            glMultiDrawArraysIndirectAMD( entry.m_primitiveType, commands, static_cast<GLuint>(entry.m_indirectCommands.size()), 0 );
#endif

#endif

          }


#if 0
          unsigned int indirectCommands = 0;

          glEnable( GL_PRIMITIVE_RESTART );
          //glDisable( GL_PRIMITIVE_RESTART );
          glPrimitiveRestartIndex( ~0 );

          glEnableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV );
          glEnableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);
          glEnableVertexAttribArray( 12 );
          glVertexAttribDivisor( 12, 1);
          glVertexAttribLFormatNV( 12, 1, GL_UNSIGNED_INT64_NV, 0 );

          for ( size_t idx = 0;idx < cache->m_drawElementsList.size(); ++idx )
          {
            const RenderGroupGLCache::DrawElementsListEntry& entry = cache->m_drawElementsList[idx];

            //dp::gl::bind( GL_ARRAY_BUFFER, entry.m_indirectPointersBuffer );
            //glVertexAttribLPointerEXT( 12, 1, GL_UNSIGNED_INT64_NV, 0, 0 );
            glBufferAddressRangeNV( GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV, 12, entry.m_indirectPointersBufferAddress, entry.m_indirectPointersBufferRange );

            //dp::gl::bind( GL_ELEMENT_ARRAY_BUFFER, entry.m_indexBuffer );
            glBufferAddressRangeNV( GL_ELEMENT_ARRAY_ADDRESS_NV, 0, entry.m_indexBufferAddress, entry.m_indexBufferRange );
            //glMultiDrawElementsIndirectAMD( entry.m_primitiveType, GL_UNSIGNED_INT, &entry.m_indirectCommands[0], static_cast<GLuint>(entry.m_indirectCommands.size()), 0);
            //glDrawElementsIndirect( entry.m_primitiveType, GL_UNSIGNED_INT, &entry.m_indirectCommands[0] );
            glDrawElementsInstancedBaseVertexBaseInstance( entry.m_primitiveType, entry.m_indirectCommands[0].count, GL_UNSIGNED_INT, 0, 1, entry.m_indirectCommands[0].baseVertex, entry.m_indirectCommands[0].baseInstance );

            indirectCommands += static_cast<unsigned int>(entry.m_indirectCommands.size());
          }
          glDisableClientState(GL_ELEMENT_ARRAY_UNIFIED_NV );
          glDisableClientState(GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV);

#endif

          //std::cout << "indirect commands " << indirectCommands << ", " << cache->m_drawElementsList.size() << std::endl;
        }
      }
Ejemplo n.º 23
0
void StateSystem::PrimitiveState::applyGL() const
{
  glPrimitiveRestartIndex(restartIndex);
  glProvokingVertex(provokingVertex);
  glPatchParameteri(GL_PATCH_VERTICES,patchVertices);
}
Ejemplo n.º 24
0
bool OGLIndexedDraw::Init(int windowWidth, int windowHeight)
{
    bool res = gs::Stage::Init(windowWidth, windowHeight);
    
    if (res) {
        res &= InitGUI();
        
		/******************************* Shaders ********************************/
		
        auto vertexShader = std::make_unique<gs::Shader>(GL_VERTEX_SHADER);
        auto fragmentShader = std::make_unique<gs::Shader>(GL_FRAGMENT_SHADER);
        auto program = std::make_shared<gs::Program>();
        
        vertexShader->SetSource("heightmap.vert");
        res &= vertexShader->Compile();
        fragmentShader->SetSource("heightmap.frag");
        res &= fragmentShader->Compile();
        
        program->Attach(vertexShader->get());
        program->Attach(fragmentShader->get());
		res &= program->Link();
        program->Use();
        
        programs.push_back(program);
        
        glm::mat4 MVP = projection * glm::lookAt(glm::vec3(0, 40, -30), glm::vec3(0), glm::vec3(0, 1, 0));
        GLint mvpLocation = glGetUniformLocation(program->get(), "MVP");
		glUniformMatrix4fv(mvpLocation, 1, GL_FALSE, glm::value_ptr(MVP));	

		hDivLocation = glGetUniformLocation(program->get(), "heightDivider");
        
		/******************************* Geometry ********************************/
        auto vao = std::make_unique<gs::VertexArray>();
        vao->BindVAO();
        vaos.push_back(std::move(vao));

		auto vbo = std::make_unique<gs::VertexBuffer>(GL_ARRAY_BUFFER);
		vbo->BindVBO();
		vbos.push_back(std::move(vbo));

		heights = { 4.0f, 2.0f, 3.0f, 1.0f,
					3.0f, 5.0f, 8.0f, 2.0f,
					7.0f, 10.0f, 12.0f, 6.0f,
					4.0f, 6.0f, 8.0f, 3.0f };

		const float halfX = WORLD_SIZE_X * 0.5f;
		const float halfZ = WORLD_SIZE_Z * 0.5f;

		for (size_t i = 0; i < HM_SIZE_Z; i++) {
			for (size_t j = 0; j < HM_SIZE_X; j++)
			{
				short currentLineOffset = (short)j * HM_SIZE_Z;

				float xPos = j / (float)(HM_SIZE_X - 1) * WORLD_SIZE_X - halfX;
				float yPos = heights[i + currentLineOffset];
				float zPos = i / (float)(HM_SIZE_Z - 1) * WORLD_SIZE_Z - halfZ;
				vertices[i + currentLineOffset] = glm::vec3(xPos, yPos, zPos);
			}
		}
		glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertices.size(), vertices.data(), GL_STATIC_DRAW);

		/******************************* Indices ********************************/
		auto ibo = std::make_unique<gs::VertexBuffer>(GL_ELEMENT_ARRAY_BUFFER);
		ibo->BindVBO();
		vbos.push_back(std::move(ibo));

		const GLushort restartIndex = HM_SIZE_X * HM_SIZE_Z;
		indices = { 0, 4, 1, 5, 2, 6, 3, 7, restartIndex,
					4, 8, 5, 9, 6, 10, 7, 11, restartIndex,
					8, 12, 9, 13, 10, 14, 11, 15};
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * indices.size(), indices.data(), GL_STATIC_DRAW);

		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

		glEnable(GL_PRIMITIVE_RESTART);
		glEnable(GL_DEPTH_TEST);
		glPrimitiveRestartIndex(restartIndex);
    }
    return res;
}
Ejemplo n.º 25
0
void init() {
    GLuint vbo = 0;
    GLuint ebo = 0;
    GLfloat* vertices = NULL;
    GLushort* indices = NULL;

    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, 6 * NumPoints * sizeof(GLfloat), NULL, GL_STATIC_DRAW);
    vertices = (GLfloat*)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);

    if (vertices == NULL) {
        exit(EXIT_FAILURE);
    }
    else {
        int i;
        int j;
        GLfloat dx = (GLfloat)(XEnd - XStart) / (NumXPoints - 1);
        GLfloat dy = (GLfloat)(YEnd - YStart) / (NumYPoints - 1);
        GLfloat* tmp = vertices;
        int n = 0;

        for (j = 0; j < NumYPoints; ++j) {
            GLfloat y = (GLfloat)(YStart + j * dy);
            for (i = 0; i < NumXPoints; ++i) {
                GLfloat x = (GLfloat)(XStart + i * dx);
                *tmp++ = color[(i + j) % 6][0];
                *tmp++ = color[(i + j) % 6][1];
                *tmp++ = color[(i + j) % 6][2];
                *tmp++ = x;
                *tmp++ = y;
                *tmp++ = 0;
            }
        }
        glUnmapBuffer(GL_ARRAY_BUFFER);
        glVertexPointer(3, GL_FLOAT, 6 * sizeof(GLfloat), BUFFER_OFFSET(3 * sizeof(GLfloat)));
        glColorPointer(3, GL_FLOAT, 6 * sizeof(GLfloat), BUFFER_OFFSET(0));
        glEnableClientState(GL_VERTEX_ARRAY);
        glEnableClientState(GL_COLOR_ARRAY);
        //glInterleavedArrays(GL_C3F_V3F, 0, 0);
    }

    glGenBuffers(1, &ebo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, NumStrips * (NumPointsPerStrip + 1) * sizeof(GLushort), NULL, GL_STATIC_DRAW);
    indices = (GLushort*)glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_WRITE_ONLY);
    if (indices == NULL) {
        exit(EXIT_FAILURE);
    }
    else {
        int i;
        int j;
        GLushort* index = indices;
        for (j = 0; j < NumStrips; ++j) {
            GLushort bottomRow = j * NumYPoints;
            GLushort topRow = bottomRow + NumYPoints;
            for (i = 0; i < NumXPoints; ++i) {
                *index++ = topRow + i;
                *index++ = bottomRow + i;
            }
            *index++ = RestartIndex;
        }
        glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER);
    }
    glPrimitiveRestartIndex(RestartIndex);
    glEnable(GL_PRIMITIVE_RESTART);

}
Ejemplo n.º 26
0
Archivo: glew_stub.c Proyecto: mjard/gl
void go_glPrimitiveRestartIndex(GLuint index) {
    glPrimitiveRestartIndex(index);
}
Ejemplo n.º 27
0
void GLGSRender::ExecCMD()
{
	//return;
	if(!LoadProgram())
	{
		ConLog.Error("LoadProgram failed.");
		Emu.Pause();
		return;
	}

	if(!m_fbo.IsCreated() || RSXThread::m_width != last_width || RSXThread::m_height != last_height || last_depth_format != m_surface_depth_format)
	{
		ConLog.Warning("New FBO (%dx%d)", RSXThread::m_width, RSXThread::m_height);
		last_width = RSXThread::m_width;
		last_height = RSXThread::m_height;
		last_depth_format = m_surface_depth_format;

		m_fbo.Create();
		checkForGlError("m_fbo.Create");
		m_fbo.Bind();

		m_rbo.Create(4 + 1);
		checkForGlError("m_rbo.Create");

		for(int i=0; i<4; ++i)
		{
			m_rbo.Bind(i);
			m_rbo.Storage(GL_RGBA, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_RGBA)");
		}

		m_rbo.Bind(4);

		switch(m_surface_depth_format)
		{
		// case 0 found in BLJM60410-[Suzukaze no Melt - Days in the Sanctuary]  
		// [E : RSXThread]: Bad depth format! (0)
		// [E : RSXThread]: glEnable: opengl error 0x0506
		// [E : RSXThread]: glDrawArrays: opengl error 0x0506
		case 0:
			m_rbo.Storage(GL_DEPTH_COMPONENT, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH_COMPONENT)");
		break;
		
		case CELL_GCM_SURFACE_Z16:
			m_rbo.Storage(GL_DEPTH_COMPONENT16, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH_COMPONENT16)");
		break;

		case CELL_GCM_SURFACE_Z24S8:
			m_rbo.Storage(GL_DEPTH24_STENCIL8, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH24_STENCIL8)");
		break;

		default:
			ConLog.Error("Bad depth format! (%d)", m_surface_depth_format);
			assert(0);
		break;
		}

		for(int i=0; i<4; ++i)
		{
			m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0 + i, m_rbo.GetId(i));
			checkForGlError(fmt::Format("m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT%d)", i));
		}

		m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT, m_rbo.GetId(4));
		checkForGlError("m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT)");

		if(m_surface_depth_format == 2)
		{
			m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT, m_rbo.GetId(4));
			checkForGlError("m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT)");
		}
	}

	if(!m_set_surface_clip_horizontal)
	{
		m_surface_clip_x = 0;
		m_surface_clip_w = RSXThread::m_width;
	}

	if(!m_set_surface_clip_vertical)
	{
		m_surface_clip_y = 0;
		m_surface_clip_h = RSXThread::m_height;
	}
		
	m_fbo.Bind();

	if(Ini.GSDumpDepthBuffer.GetValue())
		WriteDepthBuffer();

	static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };

	switch(m_surface_colour_target)
	{
	case CELL_GCM_SURFACE_TARGET_NONE:
		break;

	case CELL_GCM_SURFACE_TARGET_0:
		glDrawBuffer(draw_buffers[0]);
	break;

	case CELL_GCM_SURFACE_TARGET_1:
		glDrawBuffer(draw_buffers[1]);
	break;

	case CELL_GCM_SURFACE_TARGET_MRT1:
		glDrawBuffers(2, draw_buffers);
	break;

	case CELL_GCM_SURFACE_TARGET_MRT2:
		glDrawBuffers(3, draw_buffers);
	break;

	case CELL_GCM_SURFACE_TARGET_MRT3:
		glDrawBuffers(4, draw_buffers);
	break;

	default:
		ConLog.Error("Bad surface colour target: %d", m_surface_colour_target);
	break;
	}

	if(m_set_color_mask)
	{
		glColorMask(m_color_mask_r, m_color_mask_g, m_color_mask_b, m_color_mask_a);
		checkForGlError("glColorMask");
	}

	if(m_set_viewport_horizontal && m_set_viewport_vertical)
	{
		//glViewport(m_viewport_x, m_viewport_y, m_viewport_w, m_viewport_h);
		//checkForGlError("glViewport");
	}
	
	if (m_set_scissor_horizontal && m_set_scissor_vertical)
	{
		glScissor(m_scissor_x, m_scissor_y, m_scissor_w, m_scissor_h);
		checkForGlError("glScissor");
	}
	
	if(m_clear_surface_mask)
	{
		GLbitfield f = 0;

		if (m_clear_surface_mask & 0x1)
		{
			glClearDepth(m_clear_surface_z / (float)0xffffff);

			f |= GL_DEPTH_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0x2)
		{
			glClearStencil(m_clear_surface_s);

			f |= GL_STENCIL_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0xF0)
		{
			glClearColor(
				m_clear_surface_color_r / 255.0f,
				m_clear_surface_color_g / 255.0f,
				m_clear_surface_color_b / 255.0f,
				m_clear_surface_color_a / 255.0f);

			f |= GL_COLOR_BUFFER_BIT;
		}

		glClear(f);
	}

	Enable(m_set_depth_test, GL_DEPTH_TEST);
	Enable(m_set_alpha_test, GL_ALPHA_TEST);
	Enable(m_set_depth_bounds_test, GL_DEPTH_BOUNDS_TEST_EXT);
	Enable(m_set_blend, GL_BLEND);
	Enable(m_set_logic_op, GL_LOGIC_OP);
	Enable(m_set_cull_face, GL_CULL_FACE);
	Enable(m_set_dither, GL_DITHER);
	Enable(m_set_stencil_test, GL_STENCIL_TEST);
	Enable(m_set_line_smooth, GL_LINE_SMOOTH);
	Enable(m_set_poly_smooth, GL_POLYGON_SMOOTH);
	Enable(m_set_point_sprite_control, GL_POINT_SPRITE);
	Enable(m_set_specular, GL_LIGHTING);
	Enable(m_set_poly_offset_fill, GL_POLYGON_OFFSET_FILL);
	Enable(m_set_poly_offset_line, GL_POLYGON_OFFSET_LINE);
	Enable(m_set_poly_offset_point, GL_POLYGON_OFFSET_POINT);
	Enable(m_set_restart_index, GL_PRIMITIVE_RESTART);
	Enable(m_set_line_stipple, GL_LINE_STIPPLE);

	if(m_set_clip_plane)
	{
		Enable(m_clip_plane_0, GL_CLIP_PLANE0);
		Enable(m_clip_plane_1, GL_CLIP_PLANE1);
		Enable(m_clip_plane_2, GL_CLIP_PLANE2);
		Enable(m_clip_plane_3, GL_CLIP_PLANE3);
		Enable(m_clip_plane_4, GL_CLIP_PLANE4);
		Enable(m_clip_plane_5, GL_CLIP_PLANE5);

		checkForGlError("m_set_clip_plane");
	}

	checkForGlError("glEnable");

	if (m_set_front_polygon_mode)
	{
		glPolygonMode(GL_FRONT, m_front_polygon_mode);
		checkForGlError("glPolygonMode(Front)");
	}

	if (m_set_back_polygon_mode)
	{
		glPolygonMode(GL_BACK, m_back_polygon_mode);
		checkForGlError("glPolygonMode(Back)");
	}

	if (m_set_point_size)
	{
		glPointSize(m_point_size);
		checkForGlError("glPointSize");
	}

	if (m_set_poly_offset_mode)
	{
		glPolygonOffset(m_poly_offset_scale_factor, m_poly_offset_bias);
		checkForGlError("glPolygonOffset");
	}

	if (m_set_logic_op)
	{
		glLogicOp(m_logic_op);
		checkForGlError("glLogicOp");
	}

	if(m_set_two_sided_stencil_test_enable)
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOpSeparate(GL_FRONT, m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOpSeparate");
		}

		if(m_set_stencil_mask)
		{
			glStencilMaskSeparate(GL_FRONT, m_stencil_mask);
			checkForGlError("glStencilMaskSeparate");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_FRONT, m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate");
		}

		if(m_set_back_stencil_fail && m_set_back_stencil_zfail && m_set_back_stencil_zpass)
		{
			glStencilOpSeparate(GL_BACK, m_back_stencil_fail, m_back_stencil_zfail, m_back_stencil_zpass);
			checkForGlError("glStencilOpSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_mask)
		{
			glStencilMaskSeparate(GL_BACK, m_back_stencil_mask);
			checkForGlError("glStencilMaskSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_func && m_set_back_stencil_func_ref && m_set_back_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_BACK, m_back_stencil_func, m_back_stencil_func_ref, m_back_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate(GL_BACK)");
		}
	}
	else
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOp(m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOp");
		}

		if(m_set_stencil_mask)
		{
			glStencilMask(m_stencil_mask);
			checkForGlError("glStencilMask");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFunc(m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFunc");
		}
	}

	if(m_set_shade_mode)
	{
		glShadeModel(m_shade_mode);
		checkForGlError("glShadeModel");
	}

	if(m_set_depth_mask)
	{
		glDepthMask(m_depth_mask);
		checkForGlError("glDepthMask");
	}

	if(m_set_depth_func)
	{
		//ConLog.Warning("glDepthFunc(0x%x)", m_depth_func);
		glDepthFunc(m_depth_func);
		checkForGlError("glDepthFunc");
	}

	if(m_set_depth_bounds)
	{
		//ConLog.Warning("glDepthBounds(%f, %f)", m_depth_bounds_min, m_depth_bounds_max);
		glDepthBoundsEXT(m_depth_bounds_min, m_depth_bounds_max);
		checkForGlError("glDepthBounds");
	}

	if(m_set_clip)
	{
		//ConLog.Warning("glDepthRangef(%f, %f)", m_clip_min, m_clip_max);
		glDepthRangef(m_clip_min, m_clip_max);
		checkForGlError("glDepthRangef");
	}

	if(m_set_line_width)
	{
		glLineWidth(m_line_width);
		checkForGlError("glLineWidth");
	}

	if (m_set_line_stipple)
	{
		glLineStipple(m_line_stipple_factor, m_line_stipple_pattern);
		checkForGlError("glLineStipple");
	}

	if(m_set_blend_equation)
	{
		glBlendEquationSeparate(m_blend_equation_rgb, m_blend_equation_alpha);
		checkForGlError("glBlendEquationSeparate");
	}

	if(m_set_blend_sfactor && m_set_blend_dfactor)
	{
		glBlendFuncSeparate(m_blend_sfactor_rgb, m_blend_dfactor_rgb, m_blend_sfactor_alpha, m_blend_dfactor_alpha);
		checkForGlError("glBlendFuncSeparate");
	}

	if(m_set_blend_color)
	{
		glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a);
		checkForGlError("glBlendColor");
	}

	if(m_set_cull_face)
	{
		glCullFace(m_cull_face);
		checkForGlError("glCullFace");
	}

	if (m_set_front_face)
	{
		glFrontFace(m_front_face);
		checkForGlError("glFrontFace");
	}

	if(m_set_alpha_func && m_set_alpha_ref)
	{
		glAlphaFunc(m_alpha_func, m_alpha_ref);
		checkForGlError("glAlphaFunc");
	}

	if(m_set_fog_mode)
	{
		glFogi(GL_FOG_MODE, m_fog_mode);
		checkForGlError("glFogi(GL_FOG_MODE)");
	}

	if(m_set_fog_params)
	{
		glFogf(GL_FOG_START, m_fog_param0);
		checkForGlError("glFogf(GL_FOG_START)");
		glFogf(GL_FOG_END, m_fog_param1);
		checkForGlError("glFogf(GL_FOG_END)");
	}

	if(m_set_restart_index)
	{
		glPrimitiveRestartIndex(m_restart_index);
		checkForGlError("glPrimitiveRestartIndex");
	}

	if(m_indexed_array.m_count && m_draw_array_count)
	{
		ConLog.Warning("m_indexed_array.m_count && draw_array_count");
	}

	for(u32 i=0; i<m_textures_count; ++i)
	{
		if(!m_textures[i].IsEnabled()) continue;

		glActiveTexture(GL_TEXTURE0 + i);
		checkForGlError("glActiveTexture");
		m_gl_textures[i].Create();
		m_gl_textures[i].Bind();
		checkForGlError(fmt::Format("m_gl_textures[%d].Bind", i));
		m_program.SetTex(i);
		m_gl_textures[i].Init(m_textures[i]);
		checkForGlError(fmt::Format("m_gl_textures[%d].Init", i));
	}

	m_vao.Bind();
	if(m_indexed_array.m_count)
	{
		LoadVertexData(m_indexed_array.index_min, m_indexed_array.index_max - m_indexed_array.index_min + 1);
	}

	EnableVertexData(m_indexed_array.m_count ? true : false);

	InitVertexData();
	InitFragmentData();

	if(m_indexed_array.m_count)
	{
		switch(m_indexed_array.m_type)
		{
		case CELL_GCM_DRAW_INDEX_ARRAY_TYPE_32:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_INT, nullptr);
			checkForGlError("glDrawElements #4");
		break;

		case CELL_GCM_DRAW_INDEX_ARRAY_TYPE_16:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_SHORT, nullptr);
			checkForGlError("glDrawElements #2");
		break;

		default:
			ConLog.Error("Bad indexed array type (%d)", m_indexed_array.m_type);
		break;
		}

		DisableVertexData();
		m_indexed_array.Reset();
	}

	if(m_draw_array_count)
	{
		//ConLog.Warning("glDrawArrays(%d,%d,%d)", m_draw_mode - 1, m_draw_array_first, m_draw_array_count);
		glDrawArrays(m_draw_mode - 1, 0, m_draw_array_count);
		checkForGlError("glDrawArrays");
		DisableVertexData();
	}

	if (Ini.GSDumpColorBuffers.GetValue())
	{
		WriteColorBuffers();
	}
}
Ejemplo n.º 28
-1
void AFK_TerrainBaseTile::initGL()
{
    bool needBufferPush = (bufs == nullptr);
    if (needBufferPush)
    {
        bufs = new GLuint[2];
        glGenBuffers(2, bufs);
    }

    glBindBuffer(GL_ARRAY_BUFFER, bufs[0]);
    if (needBufferPush)
        glBufferData(GL_ARRAY_BUFFER, vertices.size() * AFK_TER_BASE_VERTEX_SIZE, &vertices[0], GL_STATIC_DRAW);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufs[1]);
    if (needBufferPush)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, AFK_TER_BASE_VERTEX_SIZE, 0);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, AFK_TER_BASE_VERTEX_SIZE, (GLvoid *)sizeof(Vec3<float>));

    glEnable(GL_PRIMITIVE_RESTART);
    glPrimitiveRestartIndex(RESTART_INDEX);
}
Ejemplo n.º 29
-1
/* Draws the ground according to the height map provided
 * @param void
 * @return void
 */
void Ground::draw() {
	Renderer::setShader(2);//set current shader to the ground shader
	glUseProgram(Renderer::getShader());

	glm::mat4 view = glm::lookAt(glm::vec3(0, 250, 1000), glm::vec3(0, 0, 0), glm::vec3(0.0f, 1.0f, 0.0f));
	glm::mat4 projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 1000.0f);

	GLuint viewID = glGetUniformLocation(Renderer::getShader(), "viewMatrix");
	GLuint projID = glGetUniformLocation(Renderer::getShader(), "projectionMatrix");
	GLuint worldID = glGetUniformLocation(Renderer::getShader(), "worldMatrix");
	GLuint TextureID  = glGetUniformLocation(Renderer::getShader(), "myTextureSampler");
	GLuint hmScaleID = glGetUniformLocation(Renderer::getShader(), "scaleMatrix");

	glm::mat4 scaleMat = glm::scale(glm::mat4(1.f), hmScale);

	glUniformMatrix4fv(viewID, 1, GL_FALSE, &view[0][0]);
	glUniformMatrix4fv(projID, 1, GL_FALSE, &projection[0][0]);
	glUniformMatrix4fv(worldID, 1, GL_FALSE, &getWorldMatrix()[0][0]);
	glUniformMatrix4fv(hmScaleID, 1, GL_FALSE, &scaleMat[0][0]);
	
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, textureID);
	glUniform1i(TextureID, 0);

	glBindVertexArray(vertexArrayID);
	glEnable(GL_PRIMITIVE_RESTART);
	glPrimitiveRestartIndex(hmRows * hmCols);
	
	int iNumIndices = (hmRows-1)*hmCols*2 + hmRows-1;
	glDrawElements(GL_TRIANGLE_STRIP, iNumIndices, GL_UNSIGNED_INT, 0);
	//glDrawElements(GL_TRIANGLE_STRIP, HM_SIZE_X*(HM_SIZE_Y-1)*2+HM_SIZE_Y-2, GL_UNSIGNED_INT, 0);
}
Ejemplo n.º 30
-1
	void StateManager::set_restart_index(const Uint32 restart_index)
		noexcept
	{
		m_state_set.set_restart_index(restart_index);

		if (get_global_vars()->get_opengl_3_1())
		{
			glPrimitiveRestartIndex(restart_index);
		}
	}