Пример #1
0
void DeferredRenderer::DrawAmbientLight(const glm::vec3 &color) {
  //화면 전체를 단색으로 그리기
  Device *device = Device::GetInstance();
  RenderState &render_state = device->render_state();
  Shader &shader = ambient_shader();
  render_state.UseShader(shader);

  mat4 mvp(1.0f);
  shader.SetUniformMatrix(kMVPHandleName, mvp);

  vec4 ambient_color(color, 1.0f);
  shader.SetUniformVector(kAmbientColorHandleName, ambient_color);

  Texture diffuse_tex = DiffuseTex();
  render_state.UseTexture(diffuse_tex, 0);
  
  vector<Vertex2D> vert_list;
  vert_list.push_back(CreateVertex2D(-1, -1, 0, 0));
  vert_list.push_back(CreateVertex2D(1, -1, 1, 0));
  vert_list.push_back(CreateVertex2D(1, 1, 1, 1));
  vert_list.push_back(CreateVertex2D(-1, 1, 0, 1));
  shader.DrawArrays(kDrawTriangleFan, vert_list);
}
Пример #2
0
/*!
onPaint does all the rendering for one frame from scratch with OpenGL (in core
profile).
*/
bool onPaint()
{  
    // Clear the color & depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // View transform: move the coordinate system away from the camera
    _viewMatrix.identity();
    _viewMatrix.translate(0, 0, _camZ);

    // View transform: rotate the coordinate system increasingly by the mouse
    _viewMatrix.rotate(_rotX + _deltaX, 1,0,0);
    _viewMatrix.rotate(_rotY + _deltaY, 0,1,0);

    // Transform light position & direction into view space
    SLVec3f lightPosVS = _viewMatrix * _lightPos;

    // The light dir is not a position. We only take the rotation of the mv matrix.
    SLMat3f viewRot    = _viewMatrix.mat3();
    SLVec3f lightDirVS = viewRot * _lightDir;

    // Rotate the model so that we see the square from the front side
    // or the earth from the equator.
    _modelMatrix.identity();
    _modelMatrix.rotate(90, -1,0,0);

    // Build the combined model-view and model-view-projection matrix
    SLMat4f mvp(_projectionMatrix);
    SLMat4f mv(_viewMatrix * _modelMatrix);
    mvp.multiply(mv);

    // Build normal matrix
    SLMat3f nm(mv.inverseTransposed());

    // Pass the matrix uniform variables
    glUniformMatrix4fv(_mvMatrixLoc,  1, 0, (float*)&mv);
    glUniformMatrix3fv(_nMatrixLoc,   1, 0, (float*)&nm);
    glUniformMatrix4fv(_mvpMatrixLoc, 1, 0, (float*)&mvp);

    // Pass lighting uniforms variables
    glUniform4fv(_globalAmbiLoc,     1, (float*)&_globalAmbi);
    glUniform3fv(_lightPosVSLoc,     1, (float*)&lightPosVS);
    glUniform3fv(_lightDirVSLoc,     1, (float*)&lightDirVS);
    glUniform4fv(_lightAmbientLoc,   1, (float*)&_lightAmbient);
    glUniform4fv(_lightDiffuseLoc,   1, (float*)&_lightDiffuse);
    glUniform4fv(_lightSpecularLoc,  1, (float*)&_lightSpecular);
    glUniform4fv(_matAmbientLoc,     1, (float*)&_matAmbient);
    glUniform4fv(_matDiffuseLoc,     1, (float*)&_matDiffuse);
    glUniform4fv(_matSpecularLoc,    1, (float*)&_matSpecular);
    glUniform4fv(_matEmissiveLoc,    1, (float*)&_matEmissive);
    glUniform1f (_matShininessLoc,   _matShininess);
    glUniform1i (_texture0Loc,       0);
     
    //////////////////////
    // Draw with 2 VBOs //
    //////////////////////

    // Enable all of the vertex attribute arrays
    glEnableVertexAttribArray(_pLoc);
    glEnableVertexAttribArray(_nLoc);
    glEnableVertexAttribArray(_tLoc);

    // Activate VBOs
    glBindBuffer(GL_ARRAY_BUFFER, _vboV);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vboI);

    // Activate Texture
    glBindTexture(GL_TEXTURE_2D, _textureID);

    // For VBO only offset instead of data pointer
    GLsizei stride  = sizeof(VertexPNT);
    GLsizei offsetN = sizeof(SLVec3f);
    GLsizei offsetT = sizeof(SLVec3f) + sizeof(SLVec3f);
    glVertexAttribPointer(_pLoc, 3, GL_FLOAT, GL_FALSE, stride, 0);
    glVertexAttribPointer(_nLoc, 3, GL_FLOAT, GL_FALSE, stride, (void*)offsetN);
    glVertexAttribPointer(_tLoc, 2, GL_FLOAT, GL_FALSE, stride, (void*)offsetT);
   
    ////////////////////////////////////////////////////////
    // Draw cube model triangles by indexes
    glDrawElements(GL_TRIANGLES, _numI, GL_UNSIGNED_INT, 0);
    ////////////////////////////////////////////////////////

    // Deactivate buffers
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    // Disable the vertex arrays
    glDisableVertexAttribArray(_pLoc);
    glDisableVertexAttribArray(_nLoc);
    glDisableVertexAttribArray(_tLoc);

    // Check for errors from time to time
    GETGLERROR;

    // Fast copy the back buffer to the front buffer. This is OS dependent.
    glfwSwapBuffers(window);

    // Calculate frames per second
    char title[255];
    static float lastTimeSec = 0;
    float timeNowSec = (float)glfwGetTime();
    float fps = calcFPS(timeNowSec-lastTimeSec);
    sprintf(title, "Sphere, %d x %d, fps: %4.0f", _resolution, _resolution, fps);
    glfwSetWindowTitle(window, title);
    lastTimeSec = timeNowSec;

    // Return true to get an immediate refresh
    return true;
}
Пример #3
0
void test()
{
	unsigned int s = 3;
	double* a = (double*)malloc(sizeof(double)*s);
	double* b = (double*)malloc(sizeof(double)*s);

	// Vector - Vector
	register unsigned int i, j;
	for (i = 0; i < s; i++)
	{
		a[i] = i;
		b[i] = i * i;
	}

	double dc = dvp(a, b, s);

	if (equal(9, dc))
		printf("Vector - Vector dot product ok\n");


	//openMp
	double oc = odvp(a, b, s);
	if (equal(oc, dc))
		printf("OpenMp: Vector - Vector dot product ok\n");

	free(a);
	free(b);

	// Matrix - Vector
	a = (double*)malloc(sizeof(double)*s);
	b = (double*)malloc(sizeof(double)*s*s);

	for (i = 0; i < s; i++){
		a[i] = 1.0;
		for (j = 0; j < s; j++){
			b[i + j*s] = 1.0;
		}
	}

	double* c = (double*)malloc(sizeof(double)*s);
	c = (double*)mvp(b, a, s, s);

	double* d = (double*)malloc(sizeof(double)*s);
	d[0] = 3.0;
	d[1] = 3.0;
	d[2] = 3.0;

	if (assert((void*)c, (void*)d, s))
		printf("Matrix - Vector product ok\n");

	//openMp
	double* cc = (double*)malloc(sizeof(double)*s);
	cc = omvp(b, a, s, s);

	if (assert(cc, d, s))
		printf("OpenMp: Matrix - Vector product ok\n");

	free(a);
	free(b);
	free(c);
	free(cc);
	free(d);

	// Matrix - Matrix
	a = (double*)malloc(sizeof(double)*s*s);
	b = (double*)malloc(sizeof(double)*s*s);
	d = (double*)malloc(sizeof(double)*s*s);
	d[0] = 30.0; d[3] = 66.0; d[6] = 102.0;
	d[1] = 36.0; d[4] = 81.0; d[7] = 126.0;
	d[2] = 42.0; d[5] = 96.0; d[8] = 150.0;

	for (i = 1; i < (s*s) + 1; i++)
	{
		a[i - 1] = i;
		b[i - 1] = i;
	}
	c = mmp(a, b, s);

	if (assert(c, d, s*s))
		printf("Matrix - Matrix product ok\n");

	//openMp
	cc = ommp(a, b, s);
	
	if (assert(cc, d, s*s))
		printf("OpenMp: Matrix - Matrix product ok\n");

	free(a);
	free(b);
	free(c);
	free(cc);
	free(d);
}
Пример #4
0
/*! Draws the background as a flat 2D rectangle with a height and a width on two
triangles with zero in the bottom left corner: <br>
          w
       +-----+
       |    /|
       |   / |
    h  |  /  |
       | /   |
       |/    |
     0 +-----+
       0

We render the quad as a triangle strip: <br>
     0         2
       +-----+
       |    /|
       |   / |
       |  /  |
       | /   |
       |/    |
       +-----+
     1         3
*/
void SLBackground::render(SLint widthPX, SLint heightPX)
{
    SLGLState* stateGL = SLGLState::getInstance();
    SLScene* s = SLScene::current;

    // Set orthographic projection
    stateGL->projectionMatrix.ortho(0.0f, (SLfloat)widthPX, 0.0f, (SLfloat)heightPX, 0.0f, 1.0f);
    stateGL->modelViewMatrix.identity();

    // Combine modelview-projection matrix
    SLMat4f mvp(stateGL->projectionMatrix * stateGL->modelViewMatrix);
    
    stateGL->depthTest(false);
    stateGL->multiSample(false);

    // Get shader program
    SLGLProgram* sp = _texture ? s->programs(SP_TextureOnly) : s->programs(SP_colorAttribute);
    sp->useProgram();
    sp->uniformMatrix4fv("u_mvpMatrix", 1, (SLfloat*)&mvp);

    // Create or update buffer for vertex position and indices
    if (_resX != widthPX || _resY != heightPX || !_vao.id())
    {
        _resX = widthPX;
        _resY = heightPX;
        _vao.clearAttribs();

        // Float array with vertex X & Y of corners
        SLVVec2f P = {{0.0f, (SLfloat)_resY}, {0.0f, 0.0f},
                      {(SLfloat)_resX, (SLfloat)_resY}, {(SLfloat)_resX, 0.0f}}; 
        _vao.setAttrib(AT_position, sp->getAttribLocation("a_position"), &P);
        
        // Indexes for a triangle strip
        SLVushort I = {0,1,2,3};
        _vao.setIndices(&I);

        if(_texture)
        {   // Float array of texture coordinates
            SLVVec2f T = {{0.0f, 1.0f}, {0.0f, 0.0f}, {1.0f, 1.0f}, {1.0f, 0.0f}};
            _vao.setAttrib(AT_texCoord, sp->getAttribLocation("a_texCoord"), &T);
            _vao.generate(4);
        } else
        {   // Float array of colors of corners
            SLVVec3f C = {{_colors[0].r, _colors[0].g, _colors[0].b},
                          {_colors[1].r, _colors[1].g, _colors[1].b},
                          {_colors[2].r, _colors[2].g, _colors[2].b},
                          {_colors[3].r, _colors[3].g, _colors[3].b}};            
            _vao.setAttrib(AT_color, sp->getAttribLocation("a_color"), &C);
            _vao.generate(4);
        }
    }

    // draw a textured or colored quad
    if(_texture)
    {   _texture->bindActive(0);
        sp->uniform1i("u_texture0", 0);
    }

    ///////////////////////////////////////
    _vao.drawElementsAs(PT_triangleStrip);
    ///////////////////////////////////////
}
Пример #5
0
  void draw_frame(Device *device) {
    SR_CHECK_ERROR("Begin RenderFrame");
    RenderState &render_state = device->render_state();
    vec4ub color(77, 77, 77, 255);
    render_state.ClearBuffer(true, true, false, color);

    //3d
    device->render_state().Set3D();

    depth_fbo.Bind();  //fbo로 그리기. deferred같은거 구현하기 위해서 임시로 시도함
    device->render_state().Set3D();
    render_state.ClearBuffer(true, true, false, color);

    VertexList vert_list;
    vert_list.push_back(CreateVertex(vec3(-0.5, -0.5, 0), vec2(0, 0)));
    vert_list.push_back(CreateVertex(vec3(0.5, -0.5, 0), vec2(1, 0)));
    vert_list.push_back(CreateVertex(vec3(0, 0.5, 0), vec2(0.5, 1)));

    //vbo, ibo 적절히 만들기
    if(vbo.Loaded() == false) {
      vbo.Init(vert_list);
    }
    if(wire_ibo.Loaded() == false) {
      IndexList index_list;
      index_list.push_back(0);
      index_list.push_back(1);
      index_list.push_back(1);
      index_list.push_back(2);
      index_list.push_back(2);
      index_list.push_back(0);
      wire_ibo.Init(index_list);
    }

    {
      //shader사용 선언이 가장 먼저
      device->render_state().UseShader(color_shader);
      SR_CHECK_ERROR("UseShader");

      mat4 mvp(1.0f);
      ShaderVariable mvp_var = color_shader.uniform_var(kMVPHandleName);
      SetUniformMatrix(mvp_var, mvp);

      vec4 color(1.0f);
      ShaderVariable const_color_var = color_shader.uniform_var(kConstColorHandleName);
      SetUniformVector(const_color_var, color);
      SR_CHECK_ERROR("SetVector");

      color_shader.SetVertexList(vert_list);
      color_shader.DrawArrays(kDrawTriangles, vert_list.size());

      color_shader.DrawArrays(kDrawTriangles, vbo);

      color_shader.DrawElements(kDrawLines, vbo, wire_ibo);
    }

    {
      //shader사용 선언이 가장 먼저
      device->render_state().UseShader(simple_shader);
      TexturePtr tex = device->tex_mgr()->Get("sora");
      device->render_state().UseTexture(*tex, 0);
      SR_CHECK_ERROR("UseShader");
      mat4 mvp(1.0f);
      mvp = glm::rotate(mvp, 10.0f, vec3(0, 0, 1));
      ShaderVariable mvp_var = simple_shader.uniform_var(kMVPHandleName);
      SetUniformMatrix(mvp_var, mvp);
      SR_CHECK_ERROR("SetMatrix");
      simple_shader.SetVertexList(vert_list);
      simple_shader.DrawArrays(kDrawTriangles, vert_list.size());
    }

    //일반 3d객체 그리기+카메라 회전 장착
    {
      //set camera + projection
      float win_width = (float)device->render_state().win_width();
      float win_height = (float)device->render_state().win_height();
      glm::mat4 projection = glm::perspective(45.0f, win_width / win_height, 0.1f, 100.0f);
      float radius = 4;
      float cam_x = radius * cos(SR_DEG_2_RAD(aptitude)) * sin(SR_DEG_2_RAD(latitude));
      float cam_y = radius * sin(SR_DEG_2_RAD(aptitude));
      float cam_z = radius * cos(SR_DEG_2_RAD(aptitude)) * cos(SR_DEG_2_RAD(latitude));
      vec3 eye(cam_x, cam_y, cam_z);
      vec3 center(0);
      vec3 up(0, 1, 0);
      glm::mat4 view = glm::lookAt(eye, center, up);

      glm::mat4 mvp(1.0f);
      mvp = projection * view;
      ShaderVariable mvp_var = simple_shader.uniform_var(kMVPHandleName);
      SetUniformMatrix(mvp_var, mvp);
      SR_CHECK_ERROR("SetMatrix");

      GeometricObject<Vertex> mesh;
      //mesh.PointTeapot(0.05f);
      //mesh.WireTeapot(0.05f);
      //mesh.SolidTeapot(0.05f);
      //mesh.WireShpere(1, 16, 16);
      //mesh.PointShpere(1, 16, 16);
      //mesh.SolidSphere(1, 16, 16);
      //mesh.SolidCube(1, 1, 1);
      //mesh.WireCube(1, 1, 1);
      mesh.PointCube(1, 1, 1);
      //mesh.PointCylinder(1, 1, 2, 8, 8);
      //mesh.WireCylinder(1, 1, 2, 8, 8);
      mesh.SolidCylinder(1, 1, 2, 8, 8);
      //mesh.WireAxis(5);
      //mesh.SolidPlane(3);
      //mesh.WirePlane(3, 0.1f);
      //mesh.SolidTorus(1, 0.1);
      //mesh.SolidCone(2, 2);
      auto it = mesh.Begin();
      auto endit = mesh.End();
      for( ; it != endit ; ++it) {
        const DrawCmdData<Vertex> &cmd = *it;
        //앞면 뒷면 그리기를 허용/불가능 정보까지 내장해야
        //뚜껑없는 원통 그리기가 편하다
        if(cmd.disable_cull_face == true) {
          glDisable(GL_CULL_FACE);
        }
        simple_shader.SetVertexList(cmd.vertex_list);
        if(cmd.index_list.empty()) {
          simple_shader.DrawArrays(cmd.draw_mode, cmd.vertex_list.size());
        } else {
          simple_shader.DrawElements(cmd.draw_mode, cmd.index_list);
        }
        if(cmd.disable_cull_face == true) {
          glEnable(GL_CULL_FACE);
        }
      }
    }
    depth_fbo.Unbind();

    /*
    //fbo에 있는 내용을 적절히 그리기
    {
    device->render_state().Set2D();
    device->render_state().UseShader(simple_shader);
    ShaderVariable mvp_var = simple_shader.uniform_var(kMVPHandleName);
    mat4 world_mat(1.0f);
    SetUniformMatrix(mvp_var, world_mat);

    //device->render_state().UseTexture(depth_fbo.color_tex());
    device->render_state().UseTexture(depth_fbo.depth_tex());

    Vertex2DList vert_list;
    vert_list.push_back(CreateVertex2D(-1, -1, 0, 0));
    vert_list.push_back(CreateVertex2D(1, -1, 1, 0));
    vert_list.push_back(CreateVertex2D(1, 1, 1, 1));
    vert_list.push_back(CreateVertex2D(-1, 1, 0, 1));
    simple_shader.SetVertexList(vert_list);
    simple_shader.DrawArrays(kDrawTriangleFan, vert_list.size());
    }
    */
    null_post_effect.DrawScissor(depth_fbo.color_tex(), 0, 0, 320, 480);
    grayscale_post_effect.DrawScissor(depth_fbo.color_tex(), 320, 0, 320, 480);
    grayscale_post_effect.Draw(depth_fbo.color_tex(), 100, 100, 100, 100);

    SR_CHECK_ERROR("End RenderFrame");
  }
Пример #6
0
void
TouchableComponent::Process()
{
    glm::mat4 hitbox(mCurrentHitbox);
    glm::mat4 mvp(mCurrentPMat * mCurrentMVMat);

    //TouchEvent* e  = (TouchEvent*)mCurrentEvent;
    auto t = mCurrentEvent.GetData();


    // TODO:  We need to do a raycast hit test rather than this current hit test in order to work properly with 3D.
    // Unproject touch pos and cast ray from zNear to zFar, test intersection with hit boxes.
    {
        auto touches = t.touches;

        glm::vec4 low(hitbox * glm::vec4(-0.5f,-0.5f,-0.5f,1.f)), high(hitbox * glm::vec4(0.5f,0.5f,0.5f,1.f));

        // Translate based on model-view * projection
        low = mvp * low;
        high = mvp * high;

        // homogenous divide to get normalized device coordinates
        low.x /= low.w;
        low.y /= low.w;
        low.z /= low.w;
        high.x /= high.w;
        high.y /= high.w;
        high.z /= high.w;

        int screenX, screenY, screenW, screenH;
        mOwner.GetOwner()->GetViewport(screenX,screenY,screenW,screenH);


        // convert the normalized device coordinates from [-1,1] back to screen-space coordinates
        short hw = screenW>>1;
        short hh = screenH>>1;
        low.x = low.x * hw + hw;
        low.y = low.y * hh + hh;
        low.z = low.z * 0.5 + 0.5;
        high.x = high.x * hw + hw;
        high.y = high.y * hh + hh;
        high.z = high.z * 0.5 + 0.5;

        //
        // Hit-test
        for (auto it = touches.begin() ; it != touches.end() ; ++it)
        {

            //          D_PRINT("Touch: (%d, %d) Low: (%lf, %lf, %lf) High: (%lf, %lf, %lf)", (*it).x, (*it).y, low.x, low.y, low.z, high.x, high.y, high.z);

            (*it).flags |= 0x10 * ((*it).x > low.x && (*it).x < high.x && (*it).y > low.y && (*it).y < high.y); // hit

            if( (*it).flags & 0x10 ) {

                mCurrentEvent.SetTarget(e::kEventTargetTouchHit);
            }

        }

    }

}