Esempio n. 1
0
void Renderer::renderColor(Mesh *mesh) {
    Eigen::Matrix4f MVP = ProjectionMatrix * ViewMatrix * mesh->ModelMatrix;

    glUseProgram(program["color"]);
    glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix(0, 0));
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP(0, 0));
    glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &mesh->ModelMatrix(0, 0));
    Vector3f lightPosition(0,-4,1);
//    lightPosition = ViewMatrix.topRightCorner(3,1);
//    printf("%.4f %.4f %.4f\n", lightPosition(0), lightPosition(1), lightPosition(2));
    glUniform3fv(LightPositionID, 1, &lightPosition(0));

    mesh->Render();
}
// engine-level shader parameters
void Context::SetCurrentTransformMatrix( const math::Matrix44& transform )
{
    sTransform = transform;

    math::Matrix44 lookAtMatrix, projectionMatrix;

    content::Ref< Camera > camera = GetCurrentCamera();
    camera->GetLookAtMatrix( lookAtMatrix );
    camera->GetProjectionMatrix( projectionMatrix );

    math::Matrix44 modelViewProjectionMatrix = projectionMatrix * lookAtMatrix * sTransform;

    // compute object space positions based on current object transform
    math::Matrix44 transformInverseTranspose = transform;
    transformInverseTranspose.InvertTranspose();
    
    math::Vector3 lightPosition( 0.0f, 1000.0f, 0.0f );

    if ( content::ParameterManager::Contains( "rendering", "debugLightWorldSpacePosition" ) )
    {
        lightPosition = content::ParameterManager::GetParameter< math::Vector3 >( "rendering", "debugLightWorldSpacePosition" );
    }

    math::Vector3 objectSpaceLightPosition  = transformInverseTranspose.Transform( lightPosition );
    math::Vector3 objectSpaceCameraPosition = transformInverseTranspose.Transform( camera->GetPosition() );

    rtgi::SetSharedShaderParameter( "modelViewProjectionMatrix", modelViewProjectionMatrix );
    rtgi::SetSharedShaderParameter( "objectSpaceLightPosition",  objectSpaceLightPosition );
    rtgi::SetSharedShaderParameter( "objectSpaceCameraPosition", objectSpaceCameraPosition );

    if ( sEffectParameters.Contains( "modelViewProjectionMatrix" ) )
    {
        SetEffectParameter( "modelViewProjectionMatrix", modelViewProjectionMatrix );
    }
}
Esempio n. 3
0
void Storm3D_Spotlight::renderStencilCone(Storm3D_Camera &camera)
{
	data->createStencilCone();

	D3DXVECTOR3 lightPosition(data->properties.position.x, data->properties.position.y, data->properties.position.z);
	D3DXVECTOR3 up(0, 1.f, 0);
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt += D3DXVECTOR3(data->properties.direction.x, data->properties.direction.y, data->properties.direction.z);

	D3DXMATRIX tm;
	D3DXMatrixLookAtLH(&tm, &lightPosition, &lookAt, &up);

	/*
	VC3 cameraDir = camera.GetDirection();
	cameraDir.Normalize();
	D3DXVECTOR3 direction(cameraDir.x, cameraDir.y, cameraDir.z);
	D3DXVec3TransformNormal(&direction, &direction, &tm);
	*/

	float det = D3DXMatrixDeterminant(&tm);
	D3DXMatrixInverse(&tm, &det, &tm);
	Storm3D_ShaderManager::GetSingleton()->SetWorldTransform(data->device, tm, true);

	data->coneStencilVertexShader->apply();
	data->coneStencilVertexBuffer.apply(data->device, 0);
	data->coneStencilIndexBuffer.render(data->device, CONE_FACES, CONE_VERTICES);
}
Esempio n. 4
0
void Render()
{
    RenderContext& rc = GlobalRenderContext;

    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glUseProgram(rc.ToonHandle);

    glUniform3f(rc.ToonUniforms.DiffuseMaterial, 0, 0.75, 0.75);
    glUniform3f(rc.ToonUniforms.AmbientMaterial, 0.04f, 0.04f, 0.04f);
    glUniform3f(rc.ToonUniforms.SpecularMaterial, 0.5, 0.5, 0.5);
    glUniform1f(rc.ToonUniforms.Shininess, 50);
    
    vec4 lightPosition(0.25, 0.25, 1, 0);
    glUniform3fv(rc.ToonUniforms.LightPosition, 1, lightPosition.Pointer());
    
    glUniformMatrix4fv(rc.ToonUniforms.Projection, 1, 0, rc.Projection.Pointer());
    glUniformMatrix4fv(rc.ToonUniforms.Modelview, 1, 0, rc.Modelview.Pointer());
    glUniformMatrix3fv(rc.ToonUniforms.NormalMatrix, 1, 0, rc.NormalMatrix.Pointer());
    
    glBindBuffer(GL_ARRAY_BUFFER, rc.VertexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rc.IndexBuffer);
    
    glEnableVertexAttribArray(VertexAttributes::Position);
    glEnableVertexAttribArray(VertexAttributes::Normal);
    
    glVertexAttribPointer(VertexAttributes::Position, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
    glVertexAttribPointer(VertexAttributes::Normal, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), VertexAttributes::NormalOffset);

    glDrawElements(GL_TRIANGLES, IndexCount, GL_UNSIGNED_INT, 0);
}
void RenderingEngine::Render(const vector<Visual>& visuals) const
{
    glClearColor(0.5f, 0.5f, 0.5f, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    vector<Visual>::const_iterator visual = visuals.begin();
    for (int visualIndex = 0; visual != visuals.end(); ++visual, ++visualIndex) {
        
        // Set the viewport transform.
        ivec2 size = visual->ViewportSize;
        ivec2 lowerLeft = visual->LowerLeft;
        glViewport(lowerLeft.x, lowerLeft.y, size.x, size.y);
        
        // Set the light position.
        glEnable(GL_LIGHTING);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        vec4 lightPosition(0.25, 0.25, 1, 0);
        glLightfv(GL_LIGHT0, GL_POSITION, lightPosition.Pointer());
        
        // Set the model-view transform.
        mat4 rotation = visual->Orientation.ToMatrix();
        mat4 modelview = rotation * m_translation;
        glLoadMatrixf(modelview.Pointer());
        
        // Set the projection transform.
        float h = 4.0f * size.y / size.x;
        mat4 projection = mat4::Frustum(-2, 2, -h / 2, h / 2, 5, 10);
        glMatrixMode(GL_PROJECTION);
        glLoadMatrixf(projection.Pointer());
        
        // Set the diffuse color.
        vec3 color = visual->Color * 0.75f;
        vec4 diffuse(color.x, color.y, color.z, 1);
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, &diffuse.x);

        // Set up the vertex buffer.
        int stride = 2 * sizeof(vec3);
        const GLvoid* normalOffset = (const GLvoid*) sizeof(vec3);
        const Drawable& drawable = m_drawables[visualIndex];
        glBindBuffer(GL_ARRAY_BUFFER, drawable.VertexBuffer);
        glVertexPointer(3, GL_FLOAT, stride, 0);

        // Draw the lit triangles.
        glPolygonOffset(4, 8);
        glEnable(GL_POLYGON_OFFSET_FILL);
        glEnableClientState(GL_NORMAL_ARRAY);
        glNormalPointer(GL_FLOAT, stride, normalOffset);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, drawable.TriangleIndexBuffer);
        glDrawElements(GL_TRIANGLES, drawable.TriangleIndexCount, GL_UNSIGNED_SHORT, 0);
        glDisable(GL_POLYGON_OFFSET_FILL);
        
        // Draw the black lines.
        glColor4f(0, 0, 0, 1);
        glDisable(GL_LIGHTING);
        glDisableClientState(GL_NORMAL_ARRAY);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, drawable.LineIndexBuffer);
        glDrawElements(GL_LINES, drawable.TriangleIndexCount, GL_UNSIGNED_SHORT, 0);
    }
}
/*************************************************************//**
 *
 *  @brief  描画処理を行う
 *  @param  なし
 *  @return なし
 *
 ****************************************************************/
void C_NormalMapTestScene::Draw()
{
    // テクスチャユニット0を有効にする
    glActiveTexture(GL_TEXTURE0);

    // テクスチャをバインド
    ::glBindTexture(GL_TEXTURE_2D, C_TextureManager::s_GetInstance()->GetTextureData("ogre").get()->textureHandle_);
    
    // テクスチャユニット1を有効にする
    glActiveTexture(GL_TEXTURE1);

    // テクスチャをバインド
    ::glBindTexture(GL_TEXTURE_2D, C_TextureManager::s_GetInstance()->GetTextureData("normal").get()->textureHandle_);

    // シェーダーの使用開始
    shader_.Begin();
    
    // 各行列を作成
    UtilityMath::S_Matrix4x4<> modelMatrix = UtilityMath::S_Matrix4x4<>::s_CreateTranslation(0.0f, 5.0f, 0.0f);
    UtilityMath::S_Matrix4x4<> modelViewMatrix = viewMatrix_ * modelMatrix;
    UtilityMath::S_Matrix3x3<> normalMatrix = UtilityMath::S_Matrix3x3<>::s_CreateNormal(modelViewMatrix);

    // ライトの座標
    UtilityMath::S_Vector3<> lightPosition(0.0f, 10.0f, 0.0f);

    shader_.SetUniformVector3("LightPosition", lightPosition);
    shader_.SetUniformVector3("EyePosition", camera_.GetEyePoint());
	shader_.SetUniformMatrix4("ModelMatrix", modelMatrix, 1);
    shader_.SetUniformMatrix4("MVP", projectionMatrix_ * modelViewMatrix, 1);

    // モデル1の描画
    objModel1_.Draw();

    modelMatrix = UtilityMath::S_Matrix4x4<>::s_CreateTranslation(0.0f, 0.5f, 0.0f) * UtilityMath::S_Matrix4x4<>::s_CreateScaling(50.0f, 0.1f, 50.0f) * UtilityMath::S_Matrix4x4<>::s_CreateTranslation(0.0f, 0.0f, -0.5f);
    modelViewMatrix = viewMatrix_ * modelMatrix;

    shader_.SetUniformMatrix4("ModelMatrix", modelMatrix, 1);
    shader_.SetUniformMatrix4("MVP", projectionMatrix_ * modelViewMatrix, 1);

    objModel2_.Draw();

    // シェーダーの使用終了
    shader_.End();

    // テクスチャをアンバインド
    ::glBindTexture(GL_TEXTURE_2D, 0);

    // グリッドの描画
    upGrid_->Draw(UtilityMath::S_Matrix4x4<>(projectionMatrix_ * viewMatrix_));

    // デバッグ文字列の描画
    C_DebugString::s_GetManagementInstance().Draw("  ノーマルマップテストシーン", UtilityMath::S_Vector3<>(0.0f, 0.0f, 0.0f), 0.8f, 0, 0, 0, C_DebugString::LEFT);
    C_DebugString::s_GetManagementInstance().Draw("方向キー・ホイールの回転とドラッグ : カメラの移動", UtilityMath::S_Vector3<>(0.0f, 30.0f, 0.0f), 0.5f, 0, 0, 0, C_DebugString::LEFT);
    C_DebugString::s_GetManagementInstance().Draw("                右クリックドラッグ : カメラの回転", UtilityMath::S_Vector3<>(0.0f, 49.0f, 0.0f), 0.5f, 0, 0, 0, C_DebugString::LEFT);
}
 void RenderingEngine::Render(const vector<Visual>& visuals) const
 {
     glClearColor(0.5f, 0.5f, 0.5f, 1);
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
     
     vector<Visual>::const_iterator visual = visuals.begin();
     for (int visualIndex = 0; visual != visuals.end(); ++visual, ++visualIndex) {
         
         // Set the viewport transform.
         ivec2 size = visual->ViewportSize;
         ivec2 lowerLeft = visual->LowerLeft;
         glViewport(lowerLeft.x, lowerLeft.y, size.x, size.y);
         
         // Set the light position.
         vec4 lightPosition(0.25, 0.25, 1, 0);
         glUniform3fv(m_uniforms.LightPosition, 1, lightPosition.Pointer());
         
         // Set the model-view transform.
         mat4 rotation = visual->Orientation.ToMatrix();
         mat4 modelview = rotation * m_translation;
         glUniformMatrix4fv(m_uniforms.Modelview, 1, 0, modelview.Pointer());
         
         // Set the normal matrix.
         // It's orthogonal, so its Inverse-Transpose is itself!
         mat3 normalMatrix = modelview.ToMat3();
         glUniformMatrix3fv(m_uniforms.NormalMatrix, 1, 0, normalMatrix.Pointer());
         
         // Set the projection transform.
         float h = 4.0f * size.y / size.x;
         mat4 projectionMatrix = mat4::Frustum(-2, 2, -h / 2, h / 2, 5, 10);
         glUniformMatrix4fv(m_uniforms.Projection, 1, 0, projectionMatrix.Pointer());
         
         // Set the diffuse color.
         vec3 color = visual->Color * 0.75f;
         glVertexAttrib4f(m_attributes.Diffuse, color.x, color.y, color.z, 1);
         
         // Draw the surface.
         int stride = sizeof(vec3) + sizeof(vec3) + sizeof(vec2);
         const GLvoid* normalOffset = (const GLvoid*) sizeof(vec3);
         const GLvoid* texCoordOffset = (const GLvoid*) (2 * sizeof(vec3));
         GLint position = m_attributes.Position;
         GLint normal = m_attributes.Normal;
         GLint texCoord = m_attributes.TextureCoord;
         const Drawable& drawable = m_drawables[visualIndex];
         glBindBuffer(GL_ARRAY_BUFFER, drawable.VertexBuffer);
         glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, stride, 0);
         glVertexAttribPointer(normal, 3, GL_FLOAT, GL_FALSE, stride, normalOffset);
         glVertexAttribPointer(texCoord, 2, GL_FLOAT, GL_FALSE, stride, texCoordOffset);
         glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, drawable.IndexBuffer);
         glDrawElements(GL_TRIANGLES, drawable.IndexCount, GL_UNSIGNED_SHORT, 0);
     }
 }
void RenderingEngine::Render(const vector<Visual>& visuals) const
{
    glClearColor(0.5f, 0.5f, 0.5f, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

    vector<Visual>::const_iterator visual = visuals.begin();
    for (int visualIndex = 0;
         visual != visuals.end();
         ++visual, ++visualIndex)
    {
        // 뷰포트 변환을 설정한다.
        ivec2 size = visual->ViewportSize;
        ivec2 lowerLeft = visual->LowerLeft;
        glViewport(lowerLeft.x, lowerLeft.y, size.x, size.y);

        // 조명 위치를 설정한다.
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        vec4 lightPosition(0.25, 0.25, 1, 0);
        glLightfv(GL_LIGHT0, GL_POSITION, lightPosition.Pointer());

        // 모델-뷰 변환을 설정한다.
        mat4 rotation = visual->Orientation.ToMatrix();
        mat4 modelview = rotation * m_traslation;
        glLoadMatrixf(modelview.Pointer());

        // 투상 행렬을 설정한다.
        float h = 4.0f * size.y / size.x;
        mat4 projection = mat4::Frustum(-2, 2, -h/2, h/2, 5, 10);
        glMatrixMode(GL_PROJECTION);
        glLoadMatrixf(projection.Pointer());

        // 확산 색상을 설정한다.
        vec3 color = visual->Color * 0.75f;
        vec4 diffuse(color.x, color.y, color.z, 1);
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse.Pointer());

        // 표면을 그린다.
        int stride = 2 * sizeof(vec3);
        const Drawable& drawalbe = m_drawables[visualIndex];
        glBindBuffer(GL_ARRAY_BUFFER, drawable.VertexBuffer);
        glVertexPointer(3, GL_FLOAT, stride, 0);
        const GLvoid* normalOffset = (const GLvoid*) sizeof(vec3);
        glNormalPointer(GL_FLOAT, stride, normalOffset);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, drawable.IndexBuffer);
        glDrawElements(GL_LINES, drawable.IndexCount, GL_UNSIGNED_SHORT, 0);
    }
}
Esempio n. 9
0
QUAT Storm3D_Spotlight::getOrientation() const
{
	D3DXVECTOR3 lightPosition(data->properties.position.x, data->properties.position.y, data->properties.position.z);
	D3DXVECTOR3 up(0, 1.f, 0);
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt += D3DXVECTOR3(data->properties.direction.x, data->properties.direction.y, data->properties.direction.z);

	D3DXMATRIX tm;
	D3DXMatrixLookAtLH(&tm, &lightPosition, &lookAt, &up);

	float det = D3DXMatrixDeterminant(&tm);
	D3DXMatrixInverse(&tm, &det, &tm);

	MAT m;

	for(int j = 0; j < 4; ++j)
	for(int i = 0; i < 4; ++i)
		m.Set(j*4 + i, tm[j*4 + i]);

	return m.GetRotation();
}
bool Storm3D_SpotlightShared::setScissorRect(Storm3D_Camera &camera, const VC2I &screenSize)
{
	D3DXMATRIX light;
	D3DXVECTOR3 lightPosition(position.x, position.y, position.z);
	D3DXVECTOR3 up(0, 1.f, 0);
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt += D3DXVECTOR3(direction.x, direction.y, direction.z);
	D3DXMatrixLookAtLH(&light, &lightPosition, &lookAt, &up);

	D3DXVECTOR3 v[5];
	v[0] = D3DXVECTOR3(0, 0, 0);
	v[1] = D3DXVECTOR3(0, 0, 1.f);
	v[2] = D3DXVECTOR3(0, 0, 1.f);
	v[3] = D3DXVECTOR3(0, 0, 1.f);
	v[4] = D3DXVECTOR3(0, 0, 1.f);

	int minX = screenSize.x;
	int minY = screenSize.y;
	int maxX = 0;
	int maxY = 0;

	float det = D3DXMatrixDeterminant(&light);
	D3DXMatrixInverse(&light, &det, &light);

	float angle = D3DXToRadian(fov) * .5f;
	for(int i = 0; i <= 4; ++i)
	{
		if(i > 0)
		{
			float z = v[i].z;
			if(i == 1 || i == 2)
			{
				v[i].x = z * sinf(angle);
				v[i].z = z * cosf(angle);
			}
			else
			{
				v[i].x = z * sinf(-angle);
				v[i].z = z * cosf(-angle);
			}

			if(i == 1 || i == 3)
				v[i].y = z * sinf(angle);
			else
				v[i].y = z * sinf(-angle);

			float scale = range / cosf(angle);
			v[i] *= scale;
		}

		D3DXVec3TransformCoord(&v[i], &v[i], &light);
	}

	const Frustum &frustum = camera.getFrustum();
	calculateLineToScissor(toVC3(v[0]), toVC3(v[1]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[0]), toVC3(v[2]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[0]), toVC3(v[3]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[0]), toVC3(v[4]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[1]), toVC3(v[2]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[2]), toVC3(v[3]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[3]), toVC3(v[4]), frustum, camera, screenSize, minX, minY, maxX, maxY);
	calculateLineToScissor(toVC3(v[4]), toVC3(v[1]), frustum, camera, screenSize, minX, minY, maxX, maxY);

	/*
	VC3 cameraPos = camera.GetPosition();
	VC3 cameraPosResult;
	float cameraRhw = 0, cameraRealZ = 0;
	bool cameraVisible = camera.GetTransformedToScreen(cameraPos, cameraPosResult, cameraRhw, cameraRealZ);

	for(i = 0; i <= 4; ++i)
	{
		VC3 source(v[i].x, v[i].y, v[i].z);
		VC3 result;
		float rhw = 0, realZ = 0;
		bool inFront = camera.GetTransformedToScreen(source, result, rhw, realZ);

		// HAX HAX!

		result.x = std::max(0.f, result.x);
		result.y = std::max(0.f, result.y);
		result.x = std::min(1.f, result.x);
		result.y = std::min(1.f, result.y);

		//if(fabsf(rhw) < 0.0001f)
		//	continue;

		bool flip = false;
		if(realZ < cameraRealZ)
			flip = true;

		if(flip)
		{
			result.x = 1.f - result.x;
			result.y = 1.f - result.y;

			//minX = 0;
			//minY = 0;
			//maxX = screenSize.x;
			//maxY = screenSize.y;
		}

		int x = int(result.x * screenSize.x);
		int y = int(result.y * screenSize.y);

		maxX = std::max(x, maxX);
		maxY = std::max(y, maxY);
		minX = std::min(x, minX);
		minY = std::min(y, minY);
	}
	*/

	if(maxX > screenSize.x)
		maxX = screenSize.x;
	if(maxY > screenSize.y)
		maxY = screenSize.y;
	if(minX < 0)
		minX = 0;
	if(minY < 0)
		minY = 0;

	RECT rc;
	rc.left = minX;
	rc.top = minY;
	rc.right = maxX;
	rc.bottom = maxY;

	if(rc.left < rc.right && rc.top < rc.bottom)
	{
		device.SetScissorRect(&rc);
		device.SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
	}
	else
	{
		RECT rc;
		rc.left = 0;
		rc.top = 0;
		rc.right = 1;
		rc.bottom = 1;

		device.SetScissorRect(&rc);
		device.SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);

		return false;
	}

	return true;
}
Esempio n. 11
0
void RenderingEngine::Render(const vector<Visual>& visuals) const
{
    glClearColor(0.5f, 0.5f, 0.5f, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    vector<Visual>::const_iterator visual = visuals.begin();
    for (int visualIndex = 0; visual != visuals.end(); ++visual, ++visualIndex) {
        
        if (visualIndex == 1) {
            glBindTexture(GL_TEXTURE_2D, m_gridTexture);
            switch (m_filter) {
                case TextureFilterNearest:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 
                    break;
                case TextureFilterBilinear:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 
                    break;
                case TextureFilterTrilinear:
                    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); 
                    break;
            }
        } else {
            glBindTexture(GL_TEXTURE_2D, m_backgroundTexture);
        }
        
        // Set the viewport transform.
        ivec2 size = visual->ViewportSize;
        ivec2 lowerLeft = visual->LowerLeft;
        glViewport(lowerLeft.x, lowerLeft.y, size.x, size.y);
        
        // Set the light position.
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        vec4 lightPosition(0.25, 0.25, 1, 0);
        glLightfv(GL_LIGHT0, GL_POSITION, lightPosition.Pointer());
        
        // Set the model-view transform.
        mat4 rotation = visual->Orientation.ToMatrix();
        mat4 modelview = rotation * m_translation;
        glLoadMatrixf(modelview.Pointer());
        
        // Set the projection transform.
        float h = 4.0f * size.y / size.x;
        mat4 projection = mat4::Frustum(-2, 2, -h / 2, h / 2, 5, 10);
        glMatrixMode(GL_PROJECTION);
        glLoadMatrixf(projection.Pointer());
        
        // Set the diffuse color.
        vec3 color = visual->Color * 0.75f;
        vec4 diffuse(color.x, color.y, color.z, 1);
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse.Pointer());

        // Draw the surface.
        int stride = sizeof(vec3) + sizeof(vec3) + sizeof(vec2);
        const GLvoid* normalOffset = (const GLvoid*) sizeof(vec3);
        const GLvoid* texCoordOffset = (const GLvoid*) (2 * sizeof(vec3));
        const Drawable& drawable = m_drawables[visualIndex];
        glBindBuffer(GL_ARRAY_BUFFER, drawable.VertexBuffer);
        glVertexPointer(3, GL_FLOAT, stride, 0);
        glNormalPointer(GL_FLOAT, stride, normalOffset);
        glTexCoordPointer(2, GL_FLOAT, stride, texCoordOffset);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, drawable.IndexBuffer);
        glDrawElements(GL_TRIANGLES, drawable.IndexCount, GL_UNSIGNED_SHORT, 0);
    }
}
Esempio n. 12
0
int main(void) {
	//Only one Window is allowed in the application, singleton pattern
	//Create a window of: width, height, title
	Window& window = Window::getInstance();
	window.createWindow(1024, 768,
			std::string("Inverse kinematics course work"), 60.0);

	//All objects to be drawn have to be created with their pointers
	//Create 3D axis object
	AxisPtr axis(new Axis());

	//Once an object is added to the window, it will be rendered
	window.addDrawable(axis);

	Point3DMarkerPtr goalMarker(new Point3DMarker());
	goalMarker->setUniformColor(glm::vec3(0, 1, 1));

	// Add the marker to inputHandler before adding the Chain to Window
	// If not, the marker wont get initialised to chain initial position
	window.getInputHandler().setGoalMarker(goalMarker);
	window.addDrawable(goalMarker);

	//Create a chain object
	ChainPtr chain(new Chain());

	//Add several bones with different lengths and joints rotations
	//Bone of length 1
	chain->addBone(1);
	//Change the angle of joint 0 to 45 degrees
	chain->setJointAngles(0, 45, 45);

	chain->addBone(0.5);
	chain->setJointAngles(1, 0, 0);

	chain->addBone(2);
	chain->setJointAngles(2, 0, 0);

	chain->addBone(1);
	chain->setJointAngles(3, 0, 0);

	//Draw chain
	window.addDrawable(chain);

	// This only changes the light marker, to change the position go to
	//the renderer class
	glm::vec3 lightPosition(3, 3, -1);

	Point3DMarkerPtr lightMarker(new Point3DMarker());
	lightMarker->setUniformColor(glm::vec3(0.9, 0.9, 0.9));
	lightMarker->translate(lightPosition);

	window.addDrawable(lightMarker);

	CubePtr cube(new Cube());
	cube->setUniformColor(glm::vec3(0, 1, 1));

	//Start the input handling and rendering loop
	window.executeMainLoop();

	return 0;
//
//	TrianglePtr triangle2(
//			new Triangle(glm::vec3(-2.0f, -2.0f, 0.0f),
//					glm::vec3(0.0f, -2.0f, 0.0f),
//					glm::vec3(-1.0f, 0.0f, 0.0f)));
//
//
//	triangle2->setUniformColor(glm::vec3(0, 1, 1));
//
//	triangle->translate(glm::vec3(1, 0.8, 0));
//
//	LinePtr line(new Line(glm::vec3(-2, 0, 0), glm::vec3(2, 0, 0)));
//	line->setUniformColor(glm::vec3(0, 1, 0));
//
//	//Indices should be provided as
//	// 3 - 4
//	// 1 - 2
//	SquarePtr square(
//			new Square(glm::vec3(-1.0f, -1.0f, 0.0f),
//					glm::vec3(1.0f, -1.0f, 0.0f), glm::vec3(-1.0f, 1.0f, 0.0f),
//					glm::vec3(1.0f, 1.0f, 0.0f)));
//
//	square->setUniformColor(glm::vec3(0, 0, 1));
//

//	window.addDrawable(line);
//
//	window.addDrawable(square);
//	window.addDrawable(triangle2);
}
Esempio n. 13
0
int main(int , char**)
{
	int width = 1280, height = 760;
	Display mainWindow(width, height, "DEngine");
	//mainWindow.ShowCursor(false);
	mainWindow.WrapMouse(false);

	glm::vec3 lightPosition(-4.0f, 8.0f, -6.0f);
	Light sun(lightPosition, glm::vec3(1.0f, 1.0f, 1.0f), DIRECTIONAL_LIGHT);

	Camera camera(glm::vec3(0.0f, 2.0f, 1.0f));
	camera.SetCameraMode(FLY);
	

	Shader simpleProgram;
	simpleProgram.LoadShaders("./SHADERS/SOURCE/NoNormal_vs.glsl",
		"./SHADERS/SOURCE/NoNormal_fs.glsl");

	Shader skyBoxShaders;
	skyBoxShaders.LoadShaders("./SHADERS/SOURCE/skyBox_vs.glsl",
		"./SHADERS/SOURCE/skyBox_fs.glsl");
	Shader shadowShaders;
	shadowShaders.LoadShaders("./SHADERS/SOURCE/ShadowDepth_vs.glsl",
		"./SHADERS/SOURCE/ShadowDepth_fs.glsl");

	EventListener eventListener(&mainWindow, &camera, &simpleProgram);

	SkyBox sky;
	sky.LoadCubeMap("./Models/skybox");
	
	Model box;
	box.LoadModelFromFile(".\\Models\\Box.obj");
	box.TranslateModel(glm::vec3(0.0f, 2.0f, 0.0f));
	box.meshes[0].AddTexture("./Models/textures/154.png", textureType::DIFFUSE_MAP);
	box.meshes[0].AddTexture("./Models/textures/154_norm.png", textureType::NORMAL_MAP);
	box.meshes[0].AddTexture("./Models/textures/154s.png", textureType::SPECULAR_MAP);
	box.TranslateModel(glm::vec3(0.0f, -0.5f, -2.0f));

	Model floor;
	floor.LoadModelFromFile("./Models/Plane/plane.obj");
	floor.meshes[0].AddTexture("./Models/textures/196.png", textureType::DIFFUSE_MAP);
	floor.meshes[0].AddTexture("./Models/textures/196_norm.png", textureType::NORMAL_MAP);
	floor.meshes[0].AddTexture("./Models/textures/196s.png", textureType::SPECULAR_MAP);
	floor.TranslateModel(glm::vec3(0.0f, -2.0f, 0.0f));
	Clock clock;
	
	while (!mainWindow.isClosed)
	{
		eventListener.Listen();
		clock.NewFrame();

//DRAWING SCENE TO SHADOWMAP		
		//sun.StartDrawingShadows(shadowShaders.programID);
		//
		//glCullFace(GL_FRONT);
		////nanosuit.Draw(&mainWindow, camera, &sun, shadowShaders);
		//box.Draw(&mainWindow, camera, &sun, shadowShaders);
		//floor.Draw(&mainWindow, camera, &sun, shadowShaders);
		//
		//sun.StopDrawingShadows();
		//
		//glCullFace(GL_BACK);
		//glViewport(0, 0, width, height);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//NORMAL DRAWING SCENE		
		simpleProgram.UseProgram();
		glUniformMatrix4fv(glGetUniformLocation(simpleProgram.programID, "lightSpaceMatrix"), 1, GL_FALSE, glm::value_ptr(sun.shadowMatrix));
		glUniform1f(glGetUniformLocation(simpleProgram.programID, "time"), clock.time);
		
		//glActiveTexture(GL_TEXTURE15);
		//glBindTexture(GL_TEXTURE_2D, sun.shadowTexture.textureID);
		//glUniform1i(glGetUniformLocation(simpleProgram.programID, "depth_map"), 15);
		
		
		floor.Draw(&mainWindow, camera, &sun, simpleProgram);
		box.Draw(&mainWindow, camera, &sun, simpleProgram);
		//sky.Draw(&mainWindow, camera, skyBoxShaders);

		camera.Update(clock.deltaTime);
		mainWindow.Update();
	}

	return 0;
}
void render(GLFWwindow* window)
{
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);

    inputHandling(window);

    /********** Section camera view **********/

    glm::vec3 cameraPosition(0,2,7);

    glm::vec4 cameraPositionTransformed =
            glm::rotate(glm::mat4(1.0f), angleX, glm::vec3(0,1,0)) *
            glm::rotate(glm::mat4(1.0f), angleY, glm::vec3(1,0,0))* glm::vec4(cameraPosition, 1.0f);

    cameraPosition = glm::vec3(XYZ(cameraPositionTransformed));

    // come from http://www.opengl-tutorial.org/fr/beginners-tutorials/tutorial-3-matrices/

	glm::mat4 Projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 50.0f);

     // Camera matrix
     glm::mat4 ViewCamera = glm::lookAt(
                    cameraPosition, // Camera is at (4,3,3), in World Space
                    glm::vec3(0,0,0), // and looks at the origin
                    glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                    );


     glm::mat4 Model = glm::mat4(1.0f);


     glm::mat4 mvpCamera = Projection * ViewCamera * Model; // Remember, matrix multiplication is the other way around

     //glProgramUniformMatrix4fv(gs.programView, 23, 1, GL_FALSE, &mvpCamera[0][0]);



    /********** Section lumière **********/

    glm::vec3 lightPosition(0, 5.f, 15.f);

    glm::vec4 lightPositionTransformed =
            glm::rotate(glm::mat4(1.0f), anglePhiLight, glm::vec3(0,1,0)) *
            glm::rotate(glm::mat4(1.0f), angleTetaLight, glm::vec3(1,0,0)) * glm::vec4(lightPosition,1.0f);

    /*** calcul du mvp de la caméra lumière (déplacement de la lumière donc calcule ici) ***/

    lightPosition = glm::vec3(XYZ(lightPositionTransformed));

	Projection = glm::perspective(glm::radians(45.0f), (float)width / (float)height, 0.1f, 50.0f);

    // Light Camera matrix
    glm::mat4 ViewLightCamera = glm::lookAt(
                   lightPosition, // Camera is at (4,3,3), in World Space
                   glm::vec3(0,0,0), // and looks at the origin
                   glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                   );

    // Our ModelViewProjection : multiplication of our 3 matrices
    glm::mat4 mvpLightCamera = Projection * ViewLightCamera * Model; // Remember, matrix multiplication is the other way around

    //glProgramUniformMatrix4fv(gs.programView, 22, 1, GL_FALSE, &mvpLightCamera[0][0]);



	float color[3] = { 0, 1, 0 };

	glProgramUniform3fv(gs.programView, 3, 1, color);
	glProgramUniform3fv(gs.programView, 4, 1, glm::value_ptr(lightPosition));


    
    glBindFramebuffer(GL_FRAMEBUFFER, gs.fbo);
	glViewport(0, 0, width, height);

	glClear(GL_COLOR_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

	glUseProgram(gs.programView);
	glBindVertexArray(gs.vao);

    {
		glProgramUniformMatrix4fv(gs.programView, 22, 1, GL_FALSE, &mvpLightCamera[0][0]);
		glProgramUniformMatrix4fv(gs.programView, 23, 1, GL_FALSE, &mvpLightCamera[0][0]);

		glProgramUniform3fv(gs.programView, 3, 1, color);
		glProgramUniform3fv(gs.programView, 4, 1, glm::value_ptr(lightPosition));

        glDrawArrays(GL_TRIANGLES, 0, nbVertex*4);
    }
	//glBindFramebuffer(GL_FRAMEBUFFER, 0);
    //glBindVertexArray(0);
    //glUseProgram(0);




    
	
    
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glViewport(0, 0, width, height);

	glClear(GL_COLOR_BUFFER_BIT);
	glClear(GL_DEPTH_BUFFER_BIT);

    //glUseProgram(gs.programView);
    //glBindVertexArray(gs.vao);
    {
		glProgramUniformMatrix4fv(gs.programView, 23, 1, GL_FALSE, &mvpCamera[0][0]);
		glProgramUniformMatrix4fv(gs.programView, 22, 1, GL_FALSE, &mvpLightCamera[0][0]);

		glProgramUniform3fv(gs.programView, 3, 1, color);
		glProgramUniform3fv(gs.programView, 4, 1, glm::value_ptr(lightPosition));

        glDrawArrays(GL_TRIANGLES, 0, nbVertex*4);
    }

    glBindVertexArray(0);
    glUseProgram(0);

}
Esempio n. 15
0
int main( int argc, char **argv )
{
    int width = 1024, height=768;
    float widthf = (float) width, heightf = (float) height;
    double t;
    float fps = 0.f;

    // Initialise GLFW
    if( !glfwInit() )
    {
        fprintf( stderr, "Failed to initialize GLFW\n" );
        exit( EXIT_FAILURE );
    }

    // Force core profile on Mac OSX
#ifdef __APPLE__
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
    // Open a window and create its OpenGL context
    if( !glfwOpenWindow( width, height, 0,0,0,0, 24, 0, GLFW_WINDOW ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );

        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwSetWindowTitle( "002_forward_a" );


    // Core profile is flagged as experimental in glew
#ifdef __APPLE__
    glewExperimental = GL_TRUE;
#endif
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
          /* Problem: glewInit failed, something is seriously wrong. */
          fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
          exit( EXIT_FAILURE );
    }

    // Ensure we can capture the escape key being pressed below
    glfwEnable( GLFW_STICKY_KEYS );

    // Enable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );
    GLenum glerr = GL_NO_ERROR;
    glerr = glGetError();

    if (!imguiRenderGLInit(DroidSans_ttf, DroidSans_ttf_len))
    {
        fprintf(stderr, "Could not init GUI renderer.\n");
        exit(EXIT_FAILURE);
    }

    // Init viewer structures
    Camera camera;
    camera_defaults(camera);
    GUIStates guiStates;
    init_gui_states(guiStates);

    // GUI
    float intensity = 1.0;

    // Load images and upload textures
    GLuint textures[3];
    glGenTextures(3, textures);
    int x;
    int y;
    int comp; 
    unsigned char * diffuse = stbi_load("textures/spnza_bricks_a_diff.tga", &x, &y, &comp, 3);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, textures[0]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, x, y, 0, GL_RGB, GL_UNSIGNED_BYTE, diffuse);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    fprintf(stderr, "Diffuse %dx%d:%d\n", x, y, comp);
    unsigned char * spec = stbi_load("textures/spnza_bricks_a_spec.tga", &x, &y, &comp, 1);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, textures[1]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, x, y, 0, GL_RED, GL_UNSIGNED_BYTE, spec);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    fprintf(stderr, "Spec %dx%d:%d\n", x, y, comp);

    // Try to load and compile shader
    ShaderGLSL shader;
    const char * shaderFile = "002/1.glsl";
    //int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER | ShaderGLSL::GEOMETRY_SHADER);
    int status = load_shader_from_file(shader, shaderFile, ShaderGLSL::VERTEX_SHADER | ShaderGLSL::FRAGMENT_SHADER);
    if ( status == -1 )
    {
        fprintf(stderr, "Error on loading  %s\n", shaderFile);
        exit( EXIT_FAILURE );
    }    

    // Apply shader
    GLuint program = shader.program;
    glUseProgram(program);
    GLuint projectionLocation = glGetUniformLocation(program, "Projection");
    GLuint viewLocation = glGetUniformLocation(program, "View");
    GLuint objectLocation = glGetUniformLocation(program, "Object");
    GLuint timeLocation = glGetUniformLocation(program, "Time");
    GLuint diffuseLocation = glGetUniformLocation(program, "Diffuse");
    GLuint specLocation = glGetUniformLocation(program, "Spec");
    GLuint intensityLocation = glGetUniformLocation(program, "Intensity");
    GLuint cameraPositionLocation = glGetUniformLocation(program, "CameraPosition");

    GLuint lightPositionLocation = glGetUniformLocation(program, "LightPosition");
    GLuint lightIntensityLocation = glGetUniformLocation(program, "LightIntensity");
    GLuint diffuseColorLocation = glGetUniformLocation(program, "DiffuseColor");
    GLuint specularColorLocation = glGetUniformLocation(program, "SpecularColor");
    GLuint specularFactorLocation = glGetUniformLocation(program, "SpecularFactor");

    GLuint lightPositionLocation2 = glGetUniformLocation(program, "LightPosition2");
    GLuint lightIntensityLocation2 = glGetUniformLocation(program, "LightIntensity2");
    GLuint diffuseColorLocation2 = glGetUniformLocation(program, "DiffuseColor2");
    GLuint specularColorLocation2 = glGetUniformLocation(program, "SpecularColor2");
    GLuint specularFactorLocation2 = glGetUniformLocation(program, "SpecularFactor2");

    GLuint spotLightExternalAngleLocation = glGetUniformLocation(program, "SpotLightExternalAngle");
    GLuint spotLightInternalAngleLocation = glGetUniformLocation(program, "SpotLightInternalAngle");


    // Load geometry
    int cube_triangleCount = 12;
    int cube_triangleList[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, };
    float cube_uvs[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f,  1.f, 0.f,  1.f, 1.f,  0.f, 1.f,  1.f, 1.f,  0.f, 0.f, 0.f, 0.f, 1.f, 1.f,  1.f, 0.f,  };
    float cube_vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 };
    float cube_normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, };
    int plane_triangleCount = 2;
    int plane_triangleList[] = {0, 1, 2, 2, 1, 3}; 
    float plane_uvs[] = {0.f, 0.f, 0.f, 10.f, 10.f, 0.f, 10.f, 10.f};
    float plane_vertices[] = {-50.0, -1.0, 50.0, 50.0, -1.0, 50.0, -50.0, -1.0, -50.0, 50.0, -1.0, -50.0};
    float plane_normals[] = {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0};

    // Vertex Array Object
    GLuint vao[2];
    glGenVertexArrays(2, vao);

    // Vertex Buffer Objects
    GLuint vbo[8];
    glGenBuffers(8, vbo);

    // Cube
    glBindVertexArray(vao[0]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[0]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_triangleList), cube_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
    // Bind normals and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_normals), cube_normals, GL_STATIC_DRAW);
    // Bind uv coords and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[3]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_uvs), cube_uvs, GL_STATIC_DRAW);

    // Plane
    glBindVertexArray(vao[1]);
    // Bind indices and upload data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo[4]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(plane_triangleList), plane_triangleList, GL_STATIC_DRAW);
    // Bind vertices and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[5]);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_vertices), plane_vertices, GL_STATIC_DRAW);
    // Bind normals and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[6]);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*3, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_normals), plane_normals, GL_STATIC_DRAW);
    // Bind uv coords and upload data
    glBindBuffer(GL_ARRAY_BUFFER, vbo[7]);
    glEnableVertexAttribArray(2);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GL_FLOAT)*2, (void*)0);
    glBufferData(GL_ARRAY_BUFFER, sizeof(plane_uvs), plane_uvs, GL_STATIC_DRAW);

    // Unbind everything. Potentially illegal on some implementations
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    // Viewport 
    glViewport( 0, 0, width, height  );

    // Default states

    glm::vec3 lightPosition(0.0, 1.0, 10);
    float lightIntensity = 1.0f;
    glm::vec3 diffuseColor(1.0, 1.0, 1.0);
    glm::vec3 specularColor(1.0, 1.0, 1.0);
    float specularFactor = 100.f;

    glm::vec3 lightPosition2(1.0, 0.0, 10);
    float lightIntensity2 = 1.0f;
    glm::vec3 diffuseColor2(1.0, 0.0, 0.0);
    glm::vec3 specularColor2(1.0, 1.0, 1.0);
    float specularFactor2 = 100.f;

    float spotLightInternal = M_PI/32;
    float spotLightExternal = M_PI/16;

    bool checkedLight1 = true;
    bool checkedLight2 = false;
    bool checkedLight3 = false;

    do
    {
        t = glfwGetTime();
        glEnable(GL_DEPTH_TEST);

        // Mouse states
        int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT );
        int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT );
        int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE );

        if( leftButton == GLFW_PRESS )
            guiStates.turnLock = true;
        else
            guiStates.turnLock = false;

        if( rightButton == GLFW_PRESS )
            guiStates.zoomLock = true;
        else
            guiStates.zoomLock = false;

        if( middleButton == GLFW_PRESS )
            guiStates.panLock = true;
        else
            guiStates.panLock = false;

        // Camera movements
        int altPressed = glfwGetKey(GLFW_KEY_LSHIFT);
        if (!altPressed && (leftButton == GLFW_PRESS || rightButton == GLFW_PRESS || middleButton == GLFW_PRESS))
        {
            int x; int y;
            glfwGetMousePos(&x, &y);
            guiStates.lockPositionX = x;
            guiStates.lockPositionY = y;
        }
        if (altPressed == GLFW_PRESS)
        {
            int mousex; int mousey;
            glfwGetMousePos(&mousex, &mousey);
            int diffLockPositionX = mousex - guiStates.lockPositionX;
            int diffLockPositionY = mousey - guiStates.lockPositionY;
            if (guiStates.zoomLock)
            {
                float zoomDir = 0.0;
                if (diffLockPositionX > 0)
                    zoomDir = -1.f;
                else if (diffLockPositionX < 0 )
                    zoomDir = 1.f;
                camera_zoom(camera, zoomDir * GUIStates::MOUSE_ZOOM_SPEED);
            }
            else if (guiStates.turnLock)
            {
                camera_turn(camera, diffLockPositionY * GUIStates::MOUSE_TURN_SPEED,
                            diffLockPositionX * GUIStates::MOUSE_TURN_SPEED);

            }
            else if (guiStates.panLock)
            {
                camera_pan(camera, diffLockPositionX * GUIStates::MOUSE_PAN_SPEED,
                            diffLockPositionY * GUIStates::MOUSE_PAN_SPEED);
            }
            guiStates.lockPositionX = mousex;
            guiStates.lockPositionY = mousey;
        }
  
        // Get camera matrices
        glm::mat4 projection = glm::perspective(45.0f, widthf / heightf, 0.1f, 100.f); 
        glm::mat4 worldToView = glm::lookAt(camera.eye, camera.o, camera.up);
        glm::mat4 objectToWorld;

        // Clear the front buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Bind textures
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, textures[0]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, textures[1]);

        // Bind shader
        glUseProgram(program);

        // Upload uniforms
        glUniformMatrix4fv(projectionLocation, 1, 0, glm::value_ptr(projection));
        glUniformMatrix4fv(viewLocation, 1, 0, glm::value_ptr(worldToView));
        glUniformMatrix4fv(objectLocation, 1, 0, glm::value_ptr(objectToWorld));
        glUniform1f(timeLocation, t);
        glUniform3fv(cameraPositionLocation, 1, glm::value_ptr(camera.eye));
        glUniform1f(intensityLocation, intensity);
        glUniform1i(diffuseLocation, 0);
        glUniform1i(specLocation, 1);
        
        glUniform3fv(lightPositionLocation, 1, glm::value_ptr(lightPosition));
        glUniform1f(lightIntensityLocation, lightIntensity);
        glUniform3fv(diffuseColorLocation, 1, glm::value_ptr(diffuseColor));
        glUniform3fv(specularColorLocation, 1, glm::value_ptr(specularColor));
        glUniform1f(specularFactorLocation, specularFactor);

        glUniform3fv(lightPositionLocation2, 1, glm::value_ptr(lightPosition2));
        glUniform1f(lightIntensityLocation2, lightIntensity2);
        glUniform3fv(diffuseColorLocation2, 1, glm::value_ptr(diffuseColor2));
        glUniform3fv(specularColorLocation2, 1, glm::value_ptr(specularColor2));
        glUniform1f(specularFactorLocation2, specularFactor2);

        glUniform1f(spotLightInternalAngleLocation, spotLightInternal);
        glUniform1f(spotLightExternalAngleLocation, spotLightExternal);

        // Render vaos
        glBindVertexArray(vao[0]);
        glDrawElementsInstanced(GL_TRIANGLES, cube_triangleCount * 3, GL_UNSIGNED_INT, (void*)0, 4);
        glBindVertexArray(vao[1]);
        glDrawElements(GL_TRIANGLES, plane_triangleCount * 3, GL_UNSIGNED_INT, (void*)0);

#if 1
        // Draw UI
        glDisable(GL_DEPTH_TEST);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glViewport(0, 0, width, height);

        unsigned char mbut = 0;
        int mscroll = 0;
        int mousex; int mousey;
        glfwGetMousePos(&mousex, &mousey);
        mousey = height - mousey;

        if( leftButton == GLFW_PRESS )
            mbut |= IMGUI_MBUT_LEFT;

        imguiBeginFrame(mousex, mousey, mbut, mscroll);
        int logScroll = 0;
        char lineBuffer[512];
        imguiBeginScrollArea("001", 0, 0, 200, height, &logScroll);
        sprintf(lineBuffer, "FPS %f", fps);
        imguiLabel(lineBuffer);
        
        int toggle = 0;
        toggle = imguiCollapse("Light1", "", checkedLight1);
            
        if(checkedLight1)
        { 
            imguiIndent();
            imguiIndent();
                imguiLabel("Light Position");
                imguiIndent();
                    imguiSlider("x", &lightPosition.x, -10, 10, 0.01);
                    imguiSlider("y", &lightPosition.y, -10, 10, 0.01);
                    imguiSlider("z", &lightPosition.z, -10, 10, 0.01);
                imguiUnindent();
                imguiSlider("Light Intensity", &lightIntensity, 0, 3, 0.01);
                imguiLabel("Diffuse Color");
                imguiIndent();
                    imguiSlider("r", &diffuseColor.x, 0, 1, 0.001);
                    imguiSlider("g", &diffuseColor.y, 0, 1, 0.001);
                    imguiSlider("b", &diffuseColor.z, 0, 1, 0.001);
                imguiUnindent();
                imguiLabel("Specular Color");
                imguiIndent();
                    imguiSlider("r", &specularColor.x, 0, 1, 0.001);
                    imguiSlider("g", &specularColor.y, 0, 1, 0.001);
                    imguiSlider("b", &specularColor.z, 0, 1, 0.001);
                imguiUnindent();
                imguiSlider("Specular Intensity", &specularFactor, 0, 100, 1);
            imguiUnindent();
            imguiUnindent();
        }
        if (toggle)
        {
            checkedLight1 = !checkedLight1;
        }

        toggle = imguiCollapse("Light2", "", checkedLight2);
        if(checkedLight2)
        { 
            imguiIndent();
            imguiIndent();
                imguiLabel("Light Position");
                imguiIndent();
                    imguiSlider("x", &lightPosition2.x, -10, 10, 0.01);
                    imguiSlider("y", &lightPosition2.y, -10, 10, 0.01);
                    imguiSlider("z", &lightPosition2.z, -10, 10, 0.01);
                imguiUnindent();
                imguiSlider("Light Intensity", &lightIntensity2, 0, 3, 0.01);
                imguiLabel("Diffuse Color");
                imguiIndent();
                    imguiSlider("r", &diffuseColor2.x, 0, 1, 0.001);
                    imguiSlider("g", &diffuseColor2.y, 0, 1, 0.001);
                    imguiSlider("b", &diffuseColor2.z, 0, 1, 0.001);
                imguiUnindent();
                imguiLabel("Specular Color");
                imguiIndent();
                    imguiSlider("r", &specularColor2.x, 0, 1, 0.001);
                    imguiSlider("g", &specularColor2.y, 0, 1, 0.001);
                    imguiSlider("b", &specularColor2.z, 0, 1, 0.001);
                imguiUnindent();
                imguiSlider("Specular Intensity", &specularFactor2, 0, 100, 1);
            imguiUnindent();
            imguiUnindent();
        }
        if (toggle)
        {
            checkedLight2 = !checkedLight2;
        }

        toggle = imguiCollapse("SpotLight", "", checkedLight3);
        if(checkedLight3)
        { 
            imguiIndent();
            imguiIndent();
                imguiSlider("External Angle", &spotLightExternal, 0, 2, 0.01);
                imguiSlider("Internal Angle", &spotLightInternal, 0, 2, 0.01);
            imguiUnindent();
            imguiUnindent();
        }
        if (toggle)
        {
            checkedLight3 = !checkedLight3;
        }

        imguiEndScrollArea();
        imguiEndFrame();
        imguiRenderGLDraw(width, height); 

        glDisable(GL_BLEND);
#endif
        
        // Check for errors
        GLenum err = glGetError();
        if(err != GL_NO_ERROR)
        {
            fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err));
            
        }

        // Swap buffers
        glfwSwapBuffers();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS &&
           glfwGetWindowParam( GLFW_OPENED ) );

    // Clean UI
    imguiRenderGLDestroy();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    exit( EXIT_SUCCESS );
}
Esempio n. 16
0
void Graphic::Update( unsigned int diffTime )
{
	Messages();

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glLoadIdentity();

	glUseProgram( shaderProgram );

	float angle = 90; // degres
	glm::mat4 modelMatrix( glm::mat4( 1.0f ) );
	modelMatrix = glm::rotate( modelMatrix, angle, glm::vec3( 0.0f, 1.0f, 0.0f ) );

	glm::mat4 modelViewMatrix = viewMatrix * modelMatrix;
	glUniformMatrix4fv( glGetUniformLocation( shaderProgram, "modelViewMatrix" ), 1, GL_FALSE, &modelViewMatrix[0][0] );

	glm::mat3 tempMatrix = glm::inverseTranspose( (glm::mat3)modelViewMatrix );
	glUniformMatrix3fv( glGetUniformLocation( shaderProgram, "normalInverseTranspose"), 1, GL_FALSE, &tempMatrix[0][0] );

	/// handle the light position
	glm::vec4 lightPosition( -1.0f, 1.0f, 0.0f, 1.0f );
	lightPosition = viewMatrix * lightPosition;
	glUniform1fv( glGetUniformLocation( shaderProgram, "lightPosition"), 1, &lightPosition[0] );

	// TEXTURE
	GLuint texture;
	glGenTextures( 1, &texture );
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
	glBindTexture( GL_TEXTURE_2D, texture );

	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

	glTexImage2D( GL_TEXTURE_2D, 0, 3, textures[0].width, textures[0].height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, textures[0].t );

	glBindTexture( GL_TEXTURE_2D, texture );
	// END TEXTURE

	// MODEL
	GLuint Vbo[2];
	glGenBuffers(2, Vbo);

	int size = models[0].num * sizeof( float );

	// Vertex, normal, texture
	glBindBuffer(GL_ARRAY_BUFFER, Vbo[0]); 
	glBufferData(GL_ARRAY_BUFFER, size * 3, models[0].vertexs, GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[1]);
	glBufferData(GL_ARRAY_BUFFER, size * 3, models[0].normals, GL_STATIC_DRAW);
	
	glBindBuffer(GL_ARRAY_BUFFER, Vbo[2]);
	glBufferData(GL_ARRAY_BUFFER, size * 2, models[0].textureCoordinates, GL_STATIC_DRAW);

	// create 1 VAO
	GLuint Vao;
	glGenVertexArrays(1, &Vao);
	glBindVertexArray(Vao);

	// Vertex, normal, texture
	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);

	GLubyte* null = 0;

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[0]);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, null);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[1]);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, null);

	glBindBuffer(GL_ARRAY_BUFFER, Vbo[2]);
	glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, null);

	glBindVertexArray(Vao);
	glDrawArrays( GL_TRIANGLES, 0, models[0].num );
	// END MODEL

	glUseProgram(0);
	glBindVertexArray(0);

	SDL_GL_SwapBuffers();
}
Esempio n. 17
0
void
renderSceneToImage(::osg::Node* node, const ::std::string& sFileName_,double position[3],double target[3],double up[3])
{
  

  osg::Group* root = new osg::Group();

  // Declare transform, initialize with defaults.

  osg::PositionAttitudeTransform* nodeXform =
     new osg::PositionAttitudeTransform();

  // Use the 'addChild' method of the osg::Group class to
  // add the transform as a child of the root node and the
  // node node as a child of the transform.

  root->addChild(nodeXform);
    
  {
  Moby::CcolorVisitor  newColor;
    newColor.setColor(0,0,0,0);
    node->accept( newColor );
  } 
    nodeXform->addChild(node);

  

  if(!sceneFile.empty()){
    ::osg::Node* sceneNode = osgDB::readNodeFile(sceneFile);
    nodeXform->addChild(sceneNode);
  }

  // Declare and initialize a Vec3 instance to change the
  // position of the node model in the scene
  osg::Vec3 nodePosit(0,0,0);
  nodeXform->setPosition( nodePosit );

  // Declare a 'viewer'
  osgViewer::Viewer viewer;

  // Next we will need to assign the scene graph we created
  // above to this viewer:
  viewer.setSceneData( root );

  viewer.setCameraManipulator(new osgGA::TrackballManipulator());
  viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));

  osg::Vec3d position_osg(position[0], position[1], position[2]);
  osg::Vec3d target_osg(target[0], target[1], target[2]);
  osg::Vec3d up_osg(up[0], up[1], up[2]);

  osg::Vec3d view = target_osg - position_osg;

  // compute the up and normal vectors 
  //osg::Quat rot;
  // compute the rotation from the view vector to the world up
  //rot.makeRotate( up_osg, view );    // #unused
  // find the normal vector by crossing the view and world up vectors
  osg::Vec3d n = view^up_osg;
  // find desired up vector by crossing the normal vector with the view vector
  osg::Vec3d up_desired = n^view;

  //osg::Vec3d up_new = rot * up_osg;  // #unused

  // replace the up vector with the desired up
  up_osg = up_desired;

  // set the camera view

  osg::Camera* camera = viewer.getCamera();
  camera->setViewMatrixAsLookAt(position_osg, target_osg, up_osg);

  // setup the manipulator using the camera, if necessary
  viewer.getCameraManipulator()->setHomePosition(position_osg, target_osg, up_osg);

  ::osg::ref_ptr<SnapImageDrawCallback> snapImageDrawCallback = new SnapImageDrawCallback();
  camera->setPostDrawCallback (snapImageDrawCallback.get());

  snapImageDrawCallback->setFileName(sFileName_);
  snapImageDrawCallback->setSnapImageOnNextFrame(true);

  // Add a Light to the scene
  osg::ref_ptr<osg::Group> lightGroup (new osg::Group);
  osg::ref_ptr<osg::StateSet> lightSS (root->getOrCreateStateSet());
  osg::ref_ptr<osg::LightSource> lightSource1 = new osg::LightSource;

  double xCenter = 10, yCenter=10;
  osg::Vec4f lightPosition (osg::Vec4f(xCenter, yCenter,75,1.0f));
  osg::ref_ptr<osg::Light> light = new osg::Light;
  light->setLightNum(1);
  light->setPosition(lightPosition);
  light->setAmbient(osg::Vec4(0.3f,0.3f,0.3f,0.4f));
  light->setDiffuse(osg::Vec4(0.2f,0.2f,0.2f,0.5f));
//  light->setSpecular(osg::Vec4(0.1,0.1,0.1,0.3));
//  light->setConstantAttenuation(0.5f);
  light->setDirection(osg::Vec3(0.1f, 0.1f, -1.0f));

  lightSource1->setLight(light.get());

  lightSource1->setLocalStateSetModes(osg::StateAttribute::ON);
  lightSource1->setStateSetModes(*lightSS,osg::StateAttribute::ON);
  //osg::StateSet* lightSS (lightGroup->getOrCreateStateSet());

  lightGroup->addChild(lightSource1.get());

  //Light markers: small spheres
  osg::ref_ptr<osg::Geode> lightMarkerGeode (new osg::Geode);
  lightMarkerGeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3f(xCenter,yCenter,75),10.0f)));


  //Tuto 9: lighting code
//  root->addChild(lightGroup.get());
  //Tuto 9: Adding the light marker geode
//  root->addChild(lightMarkerGeode.get());

  viewer.realize();

  int x,y,width,height;
  x = camera->getViewport()->x();
  y = camera->getViewport()->y();
         width = (WIDTH != 0)? WIDTH : camera->getViewport()->width();
         height = (HEIGHT != 0)? HEIGHT : camera->getViewport()->height();
//    ::osg::notify(::osg::NOTICE) << "Capturing image from: (" << x << ", " << y<< ")    " <<width<< " x "<< height << std::endl;

  // Prevent this from opening a window by making pbuffer context
//  osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
//  traits->x = 0;
//  traits->y = 0;
//  traits->width = width;
//  traits->height = height;
//  traits->red = 8;
//  traits->green = 8;
//  traits->blue = 8;
//  traits->alpha = 8;
//  traits->windowDecoration = false;
//  traits->pbuffer = true;
//  traits->doubleBuffer = true;
//  traits->sharedContext = 0;

//  osg::ref_ptr<osg::GraphicsContext> pbuffer;
//  pbuffer = ::osg::GraphicsContext::createGraphicsContext(traits.get());
//  if (pbuffer.valid())
//  {
//      ::osg::notify(osg::NOTICE)<<"Pixel buffer has been created successfully."<<std::endl;
//  }
//  else
//  {
//      ::osg::notify(osg::NOTICE)<<"Pixel buffer has not been created successfully."<<std::endl;
//  }

//  if (pbuffer.valid())
//  {
//      osg::ref_ptr<osg::Camera> camera = new osg::Camera;
//      camera->setGraphicsContext(pbuffer.get());
//      camera->setViewport(new osg::Viewport(0,0,width,height));
//      GLenum buffer = pbuffer->getTraits()->doubleBuffer ? GL_BACK : GL_FRONT;
//      camera->setDrawBuffer(buffer);
//      camera->setReadBuffer(buffer);
////      camera->setFinalDrawCallback(new WindowCaptureCallback(mode, position, readBuffer));
//      camera->setFinalDrawCallback(snapImageDrawCallback.get());

//      viewer.addSlave(camera.get(), osg::Matrixd(), osg::Matrixd());

      viewer.realize();

      viewer.frame();
//  }

}
Esempio n. 18
0
void Storm3D_SpotlightShared::updateMatrices(const D3DXMATRIX &cameraView, float bias)
{
	D3DXVECTOR3 lightPosition(position.x, position.y, position.z);
	D3DXVECTOR3 up(0, 1.f, 0);
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt += D3DXVECTOR3(direction.x, direction.y, direction.z);

	D3DXMatrixPerspectiveFovLH(&lightProjection, D3DXToRadian(fov), 1.f, .2f, range);
	D3DXMATRIX cameraMatrix(cameraView);
	float det = D3DXMatrixDeterminant(&cameraMatrix);
	D3DXMatrixInverse(&cameraMatrix, &det, &cameraMatrix);

	float currentBias = bias;
	for(int i = 0; i < 2; ++i)
	{	
		D3DXMatrixLookAtLH(&lightView[i], &lightPosition, &lookAt, &up);
		//if(i == 1)
		//	currentBias = 0;
		if(i == 1)
			currentBias = 1.f;

		// Tweak matrix
		float soffsetX = 0.5f;
		float soffsetY = 0.5f;
		float scale = 0.5f;

		/*
		D3DXMATRIX shadowTweak( scale,    0.0f,     0.0f,				0.0f,
								0.0f,     -scale,   0.0f,				0.0f,
								0.0f,      0.0f,     float(tweakRange),	0.0f,
								soffsetX,  soffsetY, currentBias,		1.0f );
		*/
		D3DXMATRIX shadowTweak( scale,    0.0f,      0.0f,				0.0f,
								0.0f,     -scale,    0.0f,				0.0f,
								0.0f,      0.0f,	 currentBias,		0.0f,
								soffsetX,  soffsetY, 0.f,				1.0f );

		D3DXMatrixMultiply(&shadowProjection[i], &lightProjection, &shadowTweak);
		D3DXMatrixMultiply(&shadowProjection[i], &lightView[i], &shadowProjection[i]);
		D3DXMatrixMultiply(&lightViewProjection[i], &lightView[i], &lightProjection);

		shaderProjection[i] = shadowProjection[i];
		D3DXMatrixMultiply(&shadowProjection[i], &cameraMatrix, &shadowProjection[i]);
	}

	{
		float xf = (1.f / resolutionX * .5f);
		float yf = (1.f / resolutionY * .5f);
		float sX = soffsetX + (2 * targetPos.x * soffsetX) - xf;
		float sY = soffsetY + (2 * targetPos.y * soffsetY) - yf;

		/*
		D3DXMATRIX shadowTweak( scaleX,    0.0f,	0.0f,				0.0f,
								0.0f,    -scaleY,	0.0f,				0.0f,
								0.0f,     0.0f,     float(tweakRange),	0.0f,
								sX,       sY,		bias,				1.0f );
		*/

		D3DXMATRIX shadowTweak( scaleX,    0.0f,	0.0f,				0.0f,
								0.0f,    -scaleY,	0.0f,				0.0f,
								0.0f,     0.0f,     bias,				0.0f,
								sX,       sY,		0.f,				1.0f );

		D3DXMatrixMultiply(&targetProjection, &lightProjection, &shadowTweak);
		D3DXMatrixMultiply(&targetProjection, &lightView[0], &targetProjection);
	}
}
Esempio n. 19
0
void Storm3D_Spotlight::renderCone(Storm3D_Camera &camera, float timeFactor, bool renderGlows)
{
	if(!data->hasCone || !data->hasShadows || !data->shadowMap)
		return;

	bool normalPass = !data->coneUpdated;
	if(data->hasCone && data->updateCone && !data->coneUpdated)
	{
		data->createCone();
		data->coneUpdated = true;
	}

	D3DXVECTOR3 lightPosition(data->properties.position.x, data->properties.position.y, data->properties.position.z);
	D3DXVECTOR3 up(0, 1.f, 0);
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt += D3DXVECTOR3(data->properties.direction.x, data->properties.direction.y, data->properties.direction.z);

	D3DXMATRIX tm;
	D3DXMatrixLookAtLH(&tm, &lightPosition, &lookAt, &up);

	VC3 cameraDir = camera.GetDirection();
	cameraDir.Normalize();
	D3DXVECTOR3 direction(cameraDir.x, cameraDir.y, cameraDir.z);
	D3DXVec3TransformNormal(&direction, &direction, &tm);

	Storm3D_ShaderManager::GetSingleton()->setSpot(data->properties.color, data->properties.position, data->properties.direction, data->properties.range, .1f);
	Storm3D_ShaderManager::GetSingleton()->setTextureTm(data->properties.shaderProjection[0]);
	Storm3D_ShaderManager::GetSingleton()->setSpotTarget(data->properties.targetProjection);

	float det = D3DXMatrixDeterminant(&tm);
	D3DXMatrixInverse(&tm, &det, &tm);
	Storm3D_ShaderManager::GetSingleton()->SetWorldTransform(data->device, tm, true);

	if(data->shadowMap && data->shadowMap->hasInitialized())
		data->shadowMap->apply(0);
	if(data->coneTexture)
	{
		data->coneTexture->AnimateVideo();
		data->coneTexture->Apply(3);

		if(type == AtiBuffer || type == AtiFloatBuffer)
			data->coneTexture->Apply(4);
		else
			data->coneTexture->Apply(1);
	}

	if(type == AtiBuffer)
	{
		if(data->coneTexture)
			data->coneAtiPixelShader_Texture->apply();
		else
			data->coneAtiPixelShader_NoTexture->apply();

	}
	else if(type == AtiFloatBuffer)
	{
		if(data->coneTexture)
			data->coneAtiFloatPixelShader_Texture->apply();
		else
			data->coneAtiFloatPixelShader_NoTexture->apply();
	}
	else
	{
		if(data->coneTexture)
			data->coneNvPixelShader_Texture->apply();
		else
			data->coneNvPixelShader_NoTexture->apply();
	}

	float colorMul = data->coneColorMultiplier;
	float colorData[4] = { data->properties.color.r * colorMul, data->properties.color.g * colorMul, data->properties.color.b * colorMul, 1.f };
	if(renderGlows)
	{
		if(normalPass)
		{
			colorData[0] *= 0.2f;
			colorData[1] *= 0.2f;
			colorData[2] *= 0.2f;
			colorData[3] *= 0.2f;
		}
		else
		{
			colorData[0] *= 0.4f;
			colorData[1] *= 0.4f;
			colorData[2] *= 0.4f;
			colorData[3] *= 0.4f;
		}
	}

	data->device.SetVertexShaderConstantF(9, colorData, 1);

	float bias = 0.005f;
	float directionData[4] = { -direction.x, -direction.y, -direction.z, bias };
	data->device.SetVertexShaderConstantF(10, directionData, 1);

	for(int i = 0; i < 2; ++i)
	{
		data->angle[i] += data->speed[i] * timeFactor;
		D3DXVECTOR3 center(0.5f, 0.5f, 0.f);
		D3DXQUATERNION quat1;
		D3DXQuaternionRotationYawPitchRoll(&quat1, 0, 0, data->angle[i]);
		D3DXMATRIX rot1;
		D3DXMatrixAffineTransformation(&rot1, 1.f, &center, &quat1, 0);
		D3DXMatrixTranspose(&rot1, &rot1);
		
		if(i == 0)
			data->device.SetVertexShaderConstantF(16, rot1, 3);
		else
			data->device.SetVertexShaderConstantF(19, rot1, 3);
	}

	frozenbyte::storm::enableMipFiltering(data->device, 0, 0, false);
	data->coneVertexBuffer.apply(data->device, 0);
	data->coneIndexBuffer.render(data->device, CONE_FACES, CONE_VERTICES);
	frozenbyte::storm::enableMipFiltering(data->device, 0, 0, true);
}
Esempio n. 20
0
int main()
{
    	osgViewer::Viewer viewer;
	osg::ref_ptr<osg::Group> root (new osg::Group);

	osg::ref_ptr<osg::PositionAttitudeTransform> objectPat (new osg::PositionAttitudeTransform);
	osg::ref_ptr<osg::PositionAttitudeTransform> quadPat (new osg::PositionAttitudeTransform);
	osg::ref_ptr<osg::MatrixTransform> terrainScaleMAT (new osg::MatrixTransform);
	osg::Matrix terrainScaleMatrix;
 	terrainScaleMatrix.makeScale(0.05f,0.05f,0.03f);

	osg::Vec3f objectPosTrans = osg::Vec3f(-1,3,5);
	osg::Vec3f quadPos = osg::Vec3f(5,0,0.5f);
	osg::Vec3f quadPos2 = osg::Vec3f(-5,0,0);
	//osg::Vec3f terrainScale = osg::Vec3f(0.5f,0.5f,0.5f);

	
	//Tuto9: Lighting code
	osg::ref_ptr<osg::Group> lightGroup (new osg::Group);
	osg::ref_ptr<osg::StateSet> lightSS (root->getOrCreateStateSet());
	osg::ref_ptr<osg::LightSource> lightSource1 = new osg::LightSource;
	osg::ref_ptr<osg::LightSource> lightSource2 = new osg::LightSource;
	
	// create a local light.
	osg::Vec4f lightPosition (osg::Vec4f(-5.0,-2.0,3.0,1.0f));
  	osg::ref_ptr<osg::Light> myLight = new osg::Light;
	myLight->setLightNum(1);
	myLight->setPosition(lightPosition);
        myLight->setAmbient(osg::Vec4(0.2f,0.2f,0.2f,1.0f));
        myLight->setDiffuse(osg::Vec4(0.8f,0.8f,0.8f,1.0f));
        myLight->setConstantAttenuation(1.0f);
	lightSource1->setLight(myLight.get());

	lightSource1->setLocalStateSetModes(osg::StateAttribute::ON); 
	lightSource1->setStateSetModes(*lightSS,osg::StateAttribute::ON);
	//osg::StateSet* lightSS (lightGroup->getOrCreateStateSet());
       
	// create a local light.
	osg::Vec4f lightPosition2 (osg::Vec4f(2.0,-1.0,3.0,1.0f));
  	osg::ref_ptr<osg::Light> myLight2 = new osg::Light;
	myLight2->setLightNum(0);
	myLight2->setPosition(lightPosition2);
        myLight2->setAmbient(osg::Vec4(0.2f,0.2f,0.2f,1.0f));
        myLight2->setDiffuse(osg::Vec4(0.8f,0.1f,0.1f,1.0f));
        myLight2->setConstantAttenuation(1.0f);
	            
        lightSource2->setLight(myLight2.get());
	lightSource2->setLocalStateSetModes(osg::StateAttribute::ON); 
	lightSource2->setStateSetModes(*lightSS,osg::StateAttribute::ON);
        

	
    	lightGroup->addChild(lightSource1.get());
	lightGroup->addChild(lightSource2.get());
	//Light markers: small spheres
	osg::ref_ptr<osg::Geode> lightMarkerGeode (new osg::Geode);
	lightMarkerGeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3f(-5.0f,-2.0f,3.0f),0.5f)));
	//lightMarkerGeode->getOrCreateStateSet()->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
	
	//Second light marker
	lightMarkerGeode->addDrawable(new osg::ShapeDrawable(new osg::Sphere(osg::Vec3f(2.0f,-1.0f,3.0f),0.5f)));
	
	


	//The geode of the capsule
	osg::ref_ptr<osg::Geode> myshapegeode (new osg::Geode);

	

	objectPat->addChild(myshapegeode.get());
	objectPat->setPosition(objectPosTrans);
	
	//quadPat->addChild(myQuad().get());
	quadPat->setPosition(quadPos);
	myshapegeode->addDrawable(new osg::ShapeDrawable(new osg::Capsule(osg::Vec3f(),1,2)));
	
	
	
	//Getting the state set of the geode
	osg::ref_ptr<osg::StateSet> nodess (myshapegeode->getOrCreateStateSet());
	
	//loading texture image object
	osg::ref_ptr<osg::Image> image (osgDB::readImageFile("Fieldstone.png"));

	//Bind the image to a 2D texture object
	osg::ref_ptr<osg::Texture2D> tex (new osg::Texture2D);
	tex->setImage(image.get());

	//Release the image memory on the GPU after using it!
	//tex->setUnRefImageDataAfterApply(true);	

	//Applying texture on the object
	
	nodess->setTextureAttributeAndModes(0,tex.get(),osg::StateAttribute::ON);
	
	
	//Loading the terrain node
	osg::ref_ptr<osg::Node> terrainnode (osgDB::readNodeFile("JoeDirt.flt"));
	//osg::ref_ptr<osg::Node> terrainnode (osgDB::readNodeFile("Terrain2.3ds"));
	terrainScaleMAT->addChild(terrainnode.get());
	terrainScaleMAT->setMatrix(terrainScaleMatrix);


	//Tutorial 11: Billboarding stuff
	osg::ref_ptr<osg::Billboard> quadBillBoard = new osg::Billboard();
	osg::ref_ptr<osg::StateSet> billSS (quadBillBoard->getOrCreateStateSet());

	//Adding texture to the billboards
	osg::ref_ptr<osg::Image> image1 (osgDB::readImageFile("foo.png"));
  	 if (image1.get() == 0)
  	 {
   	   std::cerr << "Error loading 'foo.png'.\n";
    	  exit (EXIT_FAILURE);
  	 }

 	osg::ref_ptr<osg::Texture2D> texture (new osg::Texture2D);
  	texture->setImage (image1.get());
	billSS->setTextureAttributeAndModes (0,   // unit
                                         texture.get(),
                                          osg::StateAttribute::ON);

  	root->addChild(quadBillBoard.get());
	
	quadBillBoard->setMode(osg::Billboard::AXIAL_ROT);
  	quadBillBoard->setAxis(osg::Vec3(0.0f,0.0f,1.0f));
  	quadBillBoard->setNormal(osg::Vec3(0.0f,-1.0f,0.0f));	
	
	quadBillBoard->addDrawable(myQuad().get(),quadPos);
	quadBillBoard->addDrawable(myQuad().get(),quadPos2);

	//adding the terrain node to the root node
	//root->addChild(myQuad().get());
	//root->addChild(quadPat.get());
	
	root->addChild(objectPat.get());
	root->addChild(terrainScaleMAT.get());
	
	//Tuto 9: lighting code
	root->addChild(lightGroup.get());
	//Tuto 9: Adding the light marker geode
	root->addChild(lightMarkerGeode.get());

	//Adding the fog to the root node
	//root->setStateSet(setFogState().get());

	// add the state manipulator
    	viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
	
	//Stats Event Handler s key
	viewer.addEventHandler(new osgViewer::StatsHandler);

	//Windows size handler
	viewer.addEventHandler(new osgViewer::WindowSizeHandler);

	//Threading Handler activate with the 'm' key
	viewer.addEventHandler(new osgViewer::ThreadingHandler);

	 // run optimization over the scene graph
   	osgUtil::Optimizer optimzer;
  	optimzer.optimize(root.get());
	
	viewer.setSceneData( root.get() );

	return (viewer.run());
	}
Esempio n. 21
0
void Storm3D_SpotlightShared::updateMatricesOffCenter(const D3DXMATRIX &cameraView, const VC2 &min, const VC2 &max, float height, Storm3D_Camera &camera)
{
	// Position of the light in global coordinates
	// Y-axis is height
	D3DXVECTOR3 lightPosition(position.x, position.y, position.z);
	// Up vector (z-axis)
	D3DXVECTOR3 up(0.f, 0.f, 1.f);
	// Look direction
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt.y -= 1.f;

	{
		// max and min define the extents of light area in local coordinates
		// Z-axis is height
		float zmin = 0.2f;
		//float zmax = std::max(range, height) * 1.4f;
		// height is light height from light properties
		float zmax = height;
		float factor = 1.5f * zmin / height;
		float xmin = min.x * factor;
		float xmax = max.x * factor;
		float ymin = min.y * factor;
		float ymax = max.y * factor;
		D3DXMatrixPerspectiveOffCenterLH(&lightProjection, xmin, xmax, ymin, ymax, zmin, zmax);

		// Calculate the extents of light area in global coordinates
		VC2 worldMin = min;
		worldMin.x += position.x;
		worldMin.y += position.z;
		VC2 worldMax = max;
		worldMax.x += position.x;
		worldMax.y += position.z;

		// Generate approximate camera for culling.

		// Calculate range of the camera.
		// Y-axis is height
		float planeY = position.y - height;
		// Calculate distances from light position to light plane edges
		VC3 p1 = VC3( worldMin.x, planeY, worldMin.y ) - position;
		VC3 p2 = VC3( worldMax.x, planeY, worldMin.y ) - position;
		VC3 p3 = VC3( worldMax.x, planeY, worldMax.y ) - position;
		VC3 p4 = VC3( worldMin.x, planeY, worldMax.y ) - position;
		float d1 = p1.GetLength();
		float d2 = p2.GetLength();
		float d3 = p3.GetLength();
		float d4 = p4.GetLength();
		float maxRange = 0.0f;
		maxRange = MAX( maxRange, d1 );
		maxRange = MAX( maxRange, d2 );
		maxRange = MAX( maxRange, d3 );
		maxRange = MAX( maxRange, d4 );
		//maxRange = sqrtf(maxRange);

		// Calculate FOV of the camera.
		VC3 planeCenter = VC3( (worldMin.x + worldMax.x) * 0.5f, planeY, (worldMin.y + worldMax.y) * 0.5f );
		VC3 camVec = planeCenter - position;
		camVec.Normalize();
		float minDot = 10000.0f;
		float t1 = camVec.GetDotWith( p1 ) / d1;
		float t2 = camVec.GetDotWith( p2 ) / d2;
		float t3 = camVec.GetDotWith( p3 ) / d3;
		float t4 = camVec.GetDotWith( p4 ) / d4;
		minDot = MIN( minDot, t1 );
		minDot = MIN( minDot, t2 );
		minDot = MIN( minDot, t3 );
		minDot = MIN( minDot, t4 );
		float maxAngle = acosf( minDot );

		// Place camera to light position
		camera.SetPosition(position);
		camera.SetUpVec(VC3(0.f, 0.f, 1.f));
		// Point camera at light plane center
		camera.SetTarget(planeCenter);
		camera.SetFieldOfView( maxAngle );
		camera.SetVisibilityRange( maxRange );
	}
	
	D3DXMATRIX cameraMatrix(cameraView);
	float det = D3DXMatrixDeterminant(&cameraMatrix);
	D3DXMatrixInverse(&cameraMatrix, &det, &cameraMatrix);

	unsigned int tweakRange = 1;
	float bias = 0.f;
	float currentBias = 0.f;
	for(int i = 0; i < 2; ++i)
	{	
		D3DXMatrixLookAtLH(&lightView[i], &lightPosition, &lookAt, &up);
		if(i == 1)
			currentBias = 0;

		// Tweak matrix
		float soffsetX = 0.5f;
		float soffsetY = 0.5f;
		float scale = 0.5f;

		D3DXMATRIX shadowTweak( scale,    0.0f,     0.0f,				0.0f,
								0.0f,     -scale,   0.0f,				0.0f,
								0.0f,      0.0f,     float(tweakRange),	0.0f,
								soffsetX,  soffsetY, currentBias,		1.0f );

		D3DXMatrixMultiply(&shadowProjection[i], &lightProjection, &shadowTweak);
		D3DXMatrixMultiply(&shadowProjection[i], &lightView[i], &shadowProjection[i]);
		D3DXMatrixMultiply(&lightViewProjection[i], &lightView[i], &lightProjection);

		shaderProjection[i] = shadowProjection[i];
		D3DXMatrixMultiply(&shadowProjection[i], &cameraMatrix, &shadowProjection[i]);
	}

	{
		float xf = (1.f / resolutionX * .5f);
		float yf = (1.f / resolutionY * .5f);
		float sX = soffsetX + (2 * targetPos.x * soffsetX) - xf;
		float sY = soffsetY + (2 * targetPos.y * soffsetY) - yf;

		D3DXMATRIX shadowTweak( scaleX,    0.0f,	0.0f,				0.0f,
								0.0f,    -scaleY,	0.0f,				0.0f,
								0.0f,     0.0f,     float(tweakRange),	0.0f,
								sX,       sY,		bias,				1.0f );

		D3DXMatrixMultiply(&targetProjection, &lightProjection, &shadowTweak);
		D3DXMatrixMultiply(&targetProjection, &lightView[0], &targetProjection);
	}
}
Esempio n. 22
0
File: utils.cpp Progetto: JT-a/USD
/* static */
GlfSimpleLightingContextRefPtr
px_vp20Utils::GetLightingContextFromDrawContext(
        const MHWRender::MDrawContext& context)
{
    const GfVec4f blackColor(0.0f, 0.0f, 0.0f, 1.0f);
    const GfVec4f whiteColor(1.0f, 1.0f, 1.0f, 1.0f);

    GlfSimpleLightingContextRefPtr lightingContext =
        GlfSimpleLightingContext::New();

    MStatus status;

    unsigned int numMayaLights =
        context.numberOfActiveLights(MHWRender::MDrawContext::kFilteredToLightLimit,
                                     &status);
    if (status != MS::kSuccess || numMayaLights < 1) {
        return lightingContext;
    }

    bool viewDirectionAlongNegZ = context.viewDirectionAlongNegZ(&status);
    if (status != MS::kSuccess) {
        // If we fail to find out the view direction for some reason, assume
        // that it's along the negative Z axis (OpenGL).
        viewDirectionAlongNegZ = true;
    }

    GlfSimpleLightVector lights;

    for (unsigned int i = 0; i < numMayaLights; ++i) {
        MHWRender::MLightParameterInformation* mayaLightParamInfo =
            context.getLightParameterInformation(i);

        if (!mayaLightParamInfo) {
            continue;
        }

        // Setup some default values before we read the light parameters.
        bool lightEnabled = true;

        bool    lightHasPosition = false;
        GfVec4f lightPosition(0.0f, 0.0f, 0.0f, 1.0f);
        bool    lightHasDirection = false;
        GfVec3f lightDirection(0.0f, 0.0f, -1.0f);
        if (!viewDirectionAlongNegZ) {
            // The convention for DirectX is positive Z.
            lightDirection[2] = 1.0f;
        }

        float   lightIntensity = 1.0f;
        GfVec4f lightColor = blackColor;
        bool    lightEmitsDiffuse = true;
        bool    lightEmitsSpecular = false;
        float   lightDecayRate = 0.0f;
        float   lightDropoff = 0.0f;
        // The cone angle is 180 degrees by default.
        GfVec2f lightCosineConeAngle(-1.0f);
        float   lightShadowBias = 0.0f;
        bool    lightShadowOn = false;

        bool globalShadowOn = false;

        MStringArray paramNames;
        mayaLightParamInfo->parameterList(paramNames);

        for (unsigned int paramIndex = 0; paramIndex < paramNames.length(); ++paramIndex) {
            const MString paramName = paramNames[paramIndex];
            const MHWRender::MLightParameterInformation::ParameterType paramType =
                mayaLightParamInfo->parameterType(paramName);
            const MHWRender::MLightParameterInformation::StockParameterSemantic paramSemantic =
                mayaLightParamInfo->parameterSemantic(paramName);

            MIntArray intValues;
            MFloatArray floatValues;

            switch (paramType) {
                case MHWRender::MLightParameterInformation::kBoolean:
                case MHWRender::MLightParameterInformation::kInteger:
                    mayaLightParamInfo->getParameter(paramName, intValues);
                    break;
                case MHWRender::MLightParameterInformation::kFloat:
                case MHWRender::MLightParameterInformation::kFloat2:
                case MHWRender::MLightParameterInformation::kFloat3:
                case MHWRender::MLightParameterInformation::kFloat4:
                    mayaLightParamInfo->getParameter(paramName, floatValues);
                    break;
                default:
                    // Unsupported paramType.
                    continue;
                    break;
            }

            switch (paramSemantic) {
                case MHWRender::MLightParameterInformation::kLightEnabled:
                    _GetLightingParam(intValues, floatValues, lightEnabled);
                    break;
                case MHWRender::MLightParameterInformation::kWorldPosition:
                    if (_GetLightingParam(intValues, floatValues, lightPosition)) {
                        lightHasPosition = true;
                    }
                    break;
                case MHWRender::MLightParameterInformation::kWorldDirection:
                    if (_GetLightingParam(intValues, floatValues, lightDirection)) {
                        lightHasDirection = true;
                    }
                    break;
                case MHWRender::MLightParameterInformation::kIntensity:
                    _GetLightingParam(intValues, floatValues, lightIntensity);
                    break;
                case MHWRender::MLightParameterInformation::kColor:
                    _GetLightingParam(intValues, floatValues, lightColor);
                    break;
                case MHWRender::MLightParameterInformation::kEmitsDiffuse:
                    _GetLightingParam(intValues, floatValues, lightEmitsDiffuse);
                    break;
                case MHWRender::MLightParameterInformation::kEmitsSpecular:
                    _GetLightingParam(intValues, floatValues, lightEmitsSpecular);
                    break;
                case MHWRender::MLightParameterInformation::kDecayRate:
                    _GetLightingParam(intValues, floatValues, lightDecayRate);
                    break;
                case MHWRender::MLightParameterInformation::kDropoff:
                    _GetLightingParam(intValues, floatValues, lightDropoff);
                    break;
                case MHWRender::MLightParameterInformation::kCosConeAngle:
                    _GetLightingParam(intValues, floatValues, lightCosineConeAngle);
                    break;
                case MHWRender::MLightParameterInformation::kShadowBias:
                    _GetLightingParam(intValues, floatValues, lightShadowBias);
                    break;
                case MHWRender::MLightParameterInformation::kShadowOn:
                    _GetLightingParam(intValues, floatValues, lightShadowOn);
                    break;
                case MHWRender::MLightParameterInformation::kGlobalShadowOn:
                    _GetLightingParam(intValues, floatValues, globalShadowOn);
                    break;
                default:
                    // Unsupported paramSemantic.
                    continue;
                    break;
            }

            if (!lightEnabled) {
                // Stop reading light parameters if the light is disabled.
                break;
            }
        }

        if (!lightEnabled) {
            // Skip to the next light if this light is disabled.
            continue;
        }

        lightColor[0] *= lightIntensity;
        lightColor[1] *= lightIntensity;
        lightColor[2] *= lightIntensity;

        // Populate a GlfSimpleLight from the light information from Maya.
        GlfSimpleLight light;

        GfVec4f lightAmbient = blackColor;
        GfVec4f lightDiffuse = blackColor;
        GfVec4f lightSpecular = blackColor;

        // We receive the cone angle from Maya as a pair of floats which
        // includes the penumbra, but GlfSimpleLights don't currently support
        // that, so we only use the primary cone angle value.
        float lightCutoff = GfRadiansToDegrees(std::acos(lightCosineConeAngle[0]));
        float lightFalloff = lightDropoff;

        // decayRate is actually an enum in Maya that we receive as a float:
        // - 0.0 = no attenuation
        // - 1.0 = linear attenuation
        // - 2.0 = quadratic attenuation
        // - 3.0 = cubic attenuation (not supported by GlfSimpleLight)
        GfVec3f lightAttenuation(0.0f);
        if (lightDecayRate > 1.5) {
            // Quadratic attenuation.
            lightAttenuation[2] = 1.0f;
        } else if (lightDecayRate > 0.5f) {
            // Linear attenuation.
            lightAttenuation[1] = 1.0f;
        } else {
            // No/constant attenuation.
            lightAttenuation[0] = 1.0f;
        }

        if (lightHasDirection && !lightHasPosition) {
            // This is a directional light. Set the direction as its position.
            lightPosition[0] = -lightDirection[0];
            lightPosition[1] = -lightDirection[1];
            lightPosition[2] = -lightDirection[2];
            lightPosition[3] = 0.0f;

            // Revert direction to the default value.
            lightDirection = GfVec3f(0.0f, 0.0f, -1.0f);
            if (!viewDirectionAlongNegZ) {
                lightDirection[2] = 1.0f;
            }
        }

        if (!lightHasPosition && !lightHasDirection) {
            // This is an ambient light.
            lightAmbient = lightColor;
        } else {
            if (lightEmitsDiffuse) {
                lightDiffuse = lightColor;
            }
            if (lightEmitsSpecular) {
                // XXX: It seems that the specular color cannot be specified
                // separately from the diffuse color on Maya lights.
                lightSpecular = lightColor;
            }
        }

        light.SetAmbient(lightAmbient);
        light.SetDiffuse(lightDiffuse);
        light.SetSpecular(lightSpecular);
        light.SetPosition(lightPosition);
        light.SetSpotDirection(lightDirection);
        light.SetSpotCutoff(lightCutoff);
        light.SetSpotFalloff(lightFalloff);
        light.SetAttenuation(lightAttenuation);
        light.SetShadowBias(lightShadowBias);
        light.SetHasShadow(lightShadowOn && globalShadowOn);

        lights.push_back(light);
    }

    lightingContext->SetLights(lights);

    // XXX: These material settings match what we used to get when we read the
    // material from OpenGL. This should probably eventually be something more
    // sophisticated.
    GlfSimpleMaterial material;
    material.SetAmbient(whiteColor);
    material.SetDiffuse(whiteColor);
    material.SetSpecular(blackColor);
    material.SetEmission(blackColor);
    material.SetShininess(0.0001f);

    lightingContext->SetMaterial(material);

    lightingContext->SetSceneAmbient(blackColor);

    return lightingContext;
}
Esempio n. 23
0
bool Storm3D_SpotlightShared::setScissorRect(Storm3D_Camera &camera, const VC2I &screenSize, Storm3D_Scene *scene)
{
	D3DXMATRIX light;
	D3DXVECTOR3 lightPosition(position.x, position.y, position.z);
	D3DXVECTOR3 up(0, 1.f, 0);
	D3DXVECTOR3 lookAt = lightPosition;
	lookAt += D3DXVECTOR3(direction.x, direction.y, direction.z);
	D3DXMatrixLookAtLH(&light, &lightPosition, &lookAt, &up);

	// Create frustum vertices

	D3DXVECTOR3 v[5];
	v[0] = D3DXVECTOR3(0, 0, 0);
	v[1] = D3DXVECTOR3(0, 0, 1.f);
	v[2] = D3DXVECTOR3(0, 0, 1.f);
	v[3] = D3DXVECTOR3(0, 0, 1.f);
	v[4] = D3DXVECTOR3(0, 0, 1.f);

	float det = D3DXMatrixDeterminant(&light);
	D3DXMatrixInverse(&light, &det, &light);
	float angle = D3DXToRadian(fov) * .5f;
	for(int i = 0; i <= 4; ++i)
	{
		if(i > 0)
		{
			float z = v[i].z;
			if(i == 1 || i == 2)
			{
				v[i].x = z * sinf(angle);
				v[i].z = z * cosf(angle);
			}
			else
			{
				v[i].x = z * sinf(-angle);
				v[i].z = z * cosf(-angle);
			}

			if(i == 1 || i == 3)
				v[i].y = z * sinf(angle);
			else
				v[i].y = z * sinf(-angle);

			float scale = range / cosf(angle);
			v[i] *= scale;
		}

		D3DXVec3TransformCoord(&v[i], &v[i], &light);
	}

	// Create area

	const Frustum &frustum = camera.getFrustum();
	int minX = screenSize.x;
	int minY = screenSize.y;
	int maxX = 0;
	int maxY = 0;

	for(int i = 0; i < 6; ++i)
	{
		VC3 v1;
		VC3 v2;
		VC3 v3;

		if(i == 0)
		{
			v1 = toVC3(v[0]);
			v2 = toVC3(v[1]);
			v3 = toVC3(v[2]);
		}
		else if(i == 1)
		{
			v1 = toVC3(v[0]);
			v2 = toVC3(v[2]);
			v3 = toVC3(v[4]);
		}
		else if(i == 2)
		{
			v1 = toVC3(v[0]);
			v2 = toVC3(v[3]);
			v3 = toVC3(v[4]);
		}
		else if(i == 3)
		{
			v1 = toVC3(v[0]);
			v2 = toVC3(v[1]);
			v3 = toVC3(v[3]);
		}
		else if(i == 4)
		{
			v1 = toVC3(v[1]);
			v2 = toVC3(v[2]);
			v3 = toVC3(v[3]);
		}
		else if(i == 5)
		{
			v1 = toVC3(v[4]);
			v2 = toVC3(v[2]);
			v3 = toVC3(v[3]);
		}

		const ClipPolygon &clipPolygon = clipTriangleToFrustum(v1, v2, v3, frustum);
		for(int j = 0; j < clipPolygon.vertexAmount; ++j)
		{
			VC3 result;
			float rhw = 0.f;
			float real_z = 0.f;
			camera.GetTransformedToScreen(clipPolygon.vertices[j], result, rhw, real_z);

			int x = int(result.x * screenSize.x);
			int y = int(result.y * screenSize.y);
			//if(x < -1 || x > screenSize.x)
			//	continue;
			//if(y < -1 || x > screenSize.y)
			//	continue;

			x = max(x, 0);
			y = max(y, 0);
			x = min(x, screenSize.x - 1);
			y = min(y, screenSize.y - 1);

			maxX = max(x, maxX);
			maxY = max(y, maxY);
			minX = min(x, minX);
			minY = min(y, minY);

			/*
			// Visualize clipped polygons
			if(scene)
			{
				VC3 p1 = clipPolygon.vertices[j];
				VC3 p2 = clipPolygon.vertices[(j + 1) % clipPolygon.vertexAmount];


				for(int k = 0; k < 5; ++k)
				{
					const VC3 &planeNormal = frustum.planeNormals[k];
					PLANE plane;

					if(k == 0)
						plane.MakeFromNormalAndPosition(planeNormal, frustum.position + planeNormal);
					else
						plane.MakeFromNormalAndPosition(planeNormal, frustum.position);
	
					float d1 = plane.GetPointRange(p1);
					float d2 = plane.GetPointRange(p2);

					if(d1 < .25f)
						p1 += planeNormal * (.25f - d1);
					if(d2 < .25f)
						p2 += planeNormal * (.25f - d2);
				}

				scene->AddLine(p1, p2, COL(1.f, 1.f, 1.f));
			}
			*/
		}
	}

	RECT rc;
	bool visible = false;

	if(maxX > minX && maxY > minY)
	{
		visible = true;
		rc.left = minX;
		rc.top = minY;
		rc.right = maxX;
		rc.bottom = maxY;
	}
	else
	{
		visible = false;
		rc.left = 0;
		rc.top = 0;
		rc.right = 1;
		rc.bottom = 1;
	}
/*
	// Visualize scissor area
	if(scene && visible)
	{
		static DWORD foo = GetTickCount();
		int dif = (GetTickCount() - foo) % 2000;
		if(dif < 1000)
			scene->Render2D_Picture(0, VC2(float(minX), float(minY)), VC2(float(maxX - minX), float(maxY - minY)), 0.5f, 0.f, 0, 0, 0, 0, false);
	}
*/
	device.SetScissorRect(&rc);
	device.SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);

	return visible;
}
Esempio n. 24
0
void TessMeshApp::initMesh(){
    
    if (mesh) {
        delete mesh;
    }
    mesh = new Mesh();
    
    vector<vec3> vertices;
    vector<vec3> colors;
    vector<GLuint> indices;
    
    
    
    //    createTetraedron(vertices, indices);
    createIcosphere(vertices, indices);
    
    
    unsigned int num_of_colors = (unsigned int)vertices.size();
    
    colors.reserve(num_of_colors);
    //    generateColors(num_of_colors, colors);
    generateSingleColor(num_of_colors, colors, vec3(1.0f, 1.0f, 1.0f));
    

    // position:
    {
        Attribute positionAttrib;
        positionAttrib.name = "position";
        positionAttrib.num_of_components = 3;
        positionAttrib.data_type = GL_FLOAT;
        positionAttrib.buffer_type = GL_ARRAY_BUFFER;
        
        
        
        mesh->addVBO(vertices, positionAttrib);
        meshShaderProgram->use();
        positionAttrib.id = meshShaderProgram->addAttribute(positionAttrib.name);
        glEnableVertexAttribArray(positionAttrib.id);
        glVertexAttribPointer(positionAttrib.id, positionAttrib.num_of_components, GL_FLOAT, GL_FALSE, 0, 0);
        meshShaderProgram->disable();
        mesh->attributes.push_back(positionAttrib);
    }
    
    // color:
    {
        Attribute colorAttrib;
        colorAttrib.name = "color";
        colorAttrib.num_of_components = 3;
        colorAttrib.data_type = GL_FLOAT;
        colorAttrib.buffer_type = GL_ARRAY_BUFFER;
        
        
        
        mesh->addVBO(colors, colorAttrib);
        meshShaderProgram->use();
        colorAttrib.id = meshShaderProgram->addAttribute(colorAttrib.name);
        glEnableVertexAttribArray(colorAttrib.id);
        glVertexAttribPointer(colorAttrib.id, colorAttrib.num_of_components, GL_FLOAT, GL_FALSE, 0, 0);
        meshShaderProgram->disable();
        mesh->attributes.push_back(colorAttrib);
    }
    
    
    
    // indices:
    {
        mesh->addIndices(indices);
    }
    
    
    
    // uniforms:
    {
        meshShaderProgram->use();
        GLuint model = meshShaderProgram->addUniform("model");
        glUniformMatrix4fv(model, 1, GL_FALSE, glm::value_ptr(mesh->modelMatrix));
        GLuint view = meshShaderProgram->addUniform("view");
        glUniformMatrix4fv(view, 1, GL_FALSE, glm::value_ptr(camera.view));
        GLuint projection = meshShaderProgram->addUniform("projection");
        glUniformMatrix4fv(projection, 1, GL_FALSE, glm::value_ptr(camera.projection));
        
        
        GLuint light0 = meshShaderProgram->addUniform("lightPosition");
        vec3 lightPosition(0.25f, 0.25f, 1.0f);
        glUniform3fv(light0, 1, glm::value_ptr(lightPosition));
        
        
        GLuint ambient = meshShaderProgram->addUniform("ambientMaterial");
        vec3 ambientMaterial(0.04f, 0.04f, 0.04f);
        glUniform3fv(ambient, 1, glm::value_ptr(ambientMaterial));
        
        
        GLuint diffuse = meshShaderProgram->addUniform("diffuseMaterial");
        vec3 diffuseMaterial(0.0f, 0.75f, 0.75f);
        glUniform3fv(diffuse, 1, glm::value_ptr(diffuseMaterial));
        
        meshShaderProgram->disable();
        
    }
    
}