void doArcball( double * _viewMatrix, double const * _rotationCenter, double const * _projectionMatrix, double const * _initialViewMatrix, //double const * _currentViewMatrix, double const * _initialMouse, double const * _currentMouse, bool screenSpaceRadius, double radius) { Eigen::Map<Eigen::Vector3d const> rotationCenter(_rotationCenter); Eigen::Map<Eigen::Matrix4d const> initialViewMatrix(_initialViewMatrix); //Eigen::Map<Eigen::Matrix4d const> currentViewMatrix(_currentViewMatrix); Eigen::Map<Eigen::Matrix4d const> projectionMatrix(_projectionMatrix); Eigen::Map<Eigen::Matrix4d> viewMatrix(_viewMatrix); Eigen::Vector2d initialMouse(_initialMouse); Eigen::Vector2d currentMouse(_currentMouse); Eigen::Quaterniond q; Eigen::Vector3d Pa, Pc; if (screenSpaceRadius) { double aspectRatio = projectionMatrix(1, 1) / projectionMatrix(0, 0); initialMouse(0) *= aspectRatio; currentMouse(0) *= aspectRatio; Pa = mapToSphere(initialMouse, radius); Pc = mapToSphere(currentMouse, radius); q.setFromTwoVectors(Pa - rotationCenter, Pc - rotationCenter); } else { Pa = mapToSphere(projectionMatrix.inverse(), initialMouse, rotationCenter, radius); Pc = mapToSphere(projectionMatrix.inverse(), currentMouse, rotationCenter, radius); Eigen::Vector3d a = Pa - rotationCenter, b = Pc - rotationCenter; #if 0 std::cout << "Mouse Initial Radius = " << sqrt(a.dot(a)) << " Current Radius = " << sqrt(b.dot(b)) << std::endl; #endif q.setFromTwoVectors(a, b); } Eigen::Matrix4d qMat4; qMat4.setIdentity(); qMat4.topLeftCorner<3, 3>() = q.toRotationMatrix(); Eigen::Matrix4d translate; translate.setIdentity(); translate.topRightCorner<3, 1>() = -rotationCenter; Eigen::Matrix4d invTranslate; invTranslate.setIdentity(); invTranslate.topRightCorner<3, 1>() = rotationCenter; viewMatrix = invTranslate * qMat4 * translate * initialViewMatrix; }
RAY MOUSE::GetRay() { try { D3DXMATRIX projectionMatrix, viewMatrix, worldViewInverse, worldMatrix; m_pDevice->GetTransform(D3DTS_PROJECTION, &projectionMatrix); m_pDevice->GetTransform(D3DTS_VIEW, &viewMatrix); m_pDevice->GetTransform(D3DTS_WORLD, &worldMatrix); float width = (float)(m_viewport.right - m_viewport.left); float height = (float)(m_viewport.bottom - m_viewport.top); float angle_x = (((2.0f * x) / width) - 1.0f) / projectionMatrix(0,0); float angle_y = (((-2.0f * y) / height) + 1.0f) / projectionMatrix(1,1); RAY ray; ray.org = D3DXVECTOR3(0.0f, 0.0f, 0.0f); ray.dir = D3DXVECTOR3(angle_x, angle_y, 1.0f); D3DXMATRIX m = worldMatrix * viewMatrix; D3DXMatrixInverse(&worldViewInverse, 0, &m); D3DXVec3TransformCoord(&ray.org, &ray.org, &worldViewInverse); D3DXVec3TransformNormal(&ray.dir, &ray.dir, &worldViewInverse); D3DXVec3Normalize(&ray.dir, &ray.dir); return ray; } catch(...) { debug.Print("Error in MOUSE::GetRay()"); } return RAY(); }
float AbstractViewer::ProjectDepth(float depth) { const Matrix4f& projectionMatrix = GetProjectionMatrix(); float a = projectionMatrix(2, 2); float b = projectionMatrix(2, 3); return (0.5f * (-a * depth + b) / depth + 0.5f); }
void SceneGraph::setupView() { auto use_cam = camera_; auto use_projector = projector_; if (render_mode_ == RenderInfo::SHADOW) { use_cam = shadow_camera_; use_projector = shadow_projector_; } T3_NULL_ASSERT(use_cam); const Mtx44& view_mtx = use_cam->viewMatrix(); const Mtx44& proj_mtx = use_projector->projectionMatrix(); auto view_projection = proj_mtx * view_mtx; pushAndSetMatrix(view_projection); cross::RenderSystem::setViewport( 0, 0, static_cast<int>(use_projector->screenSize().x_), static_cast<int>(use_projector->screenSize().y_) ); }
void Camera::perspective (float fovy, float aspectRatio, float zNear, float zFar) { _perspective.isPerpective = true; _perspective.fovy = fovy; _perspective.aspectRatio = aspectRatio; _perspective.zNear = zNear; _perspective.zFar = zFar; projectionMatrix = Matrix4::Zero(); double angle = degreeToRadian(fovy/2); double f = 1 / (tan(angle)); projectionMatrix (0, 0) = f/aspectRatio; projectionMatrix (1, 1) = f; projectionMatrix (2, 2) = (zFar + zNear) / (zNear - zFar); projectionMatrix (3, 2) = -1; projectionMatrix (2, 3) = 2 * zFar * zNear / (zNear - zFar); }
PMatrix4x4 PRenderTransform::mvp() const { pfloat32 mv[16]; m_drawable->calculateModelCameraMatrix(cameraMatrix(), mv); PMatrix4x4 ret; pMatrix4x4Multiply(projectionMatrix().m_m, mv, ret.m_m); return ret; }
/* Inits the shader program for this object */ void GLColoredBox::initShader(void) { // Vertex shader source code. This draws the vertices in our window. We have 3 vertices since we're drawing an triangle. // Each vertex is represented by a vector of size 4 (x, y, z, w) coordinates. // static const string vertex_code = vs_string_CoordSystem; static const char * vs_source = vs_string_ColoredBox_410.c_str(); // Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader. // static const string fragment_code = fs_string_CoordSystem; static const char * fs_source = fs_string_ColoredBox_410.c_str(); // This next section we'll generate the OpenGL program and attach the shaders to it so that we can render our triangle. _program = glCreateProgram(); // We create a shader with our fragment shader source code and compile it. GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fs_source, NULL); glCompileShader(fs); // We create a shader with our vertex shader source code and compile it. GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vs_source, NULL); glCompileShader(vs); // We'll attach our two compiled shaders to the OpenGL program. glAttachShader(_program, vs); glAttachShader(_program, fs); glLinkProgram(_program); glUseProgram(_program); _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model int projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader glBindAttribLocation(_program, 0, "in_Position"); glBindAttribLocation(_program, 1, "in_Color"); }
/*! Add the model view matrix, especially the three shader program objects to the shader program "program" */ bool GLObject::addModelViewMatrixToProgram(GLuint program) { _projectionMatrixLocation = glGetUniformLocation(program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader _viewMatrixLocation = glGetUniformLocation(program, "viewMatrixBox"); // Get the location of our view matrix in the shader _modelMatrixLocation = glGetUniformLocation(program, "modelMatrixBox"); // Get the location of our model matrix in the shader _inverseViewMatrixLocation = glGetUniformLocation(program, "inverseViewMatrix"); glUniformMatrix4fv(_projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &g_invViewMatrix[0][0]); return true; }
void Camera::passPerFrameUniforms(Shader *_shader) { glm::vec2 size = services.get<WindowManager>()->getSize(); (*_shader)["viewPosition"] = position; // Pass the view and projection matrices to the shader (*_shader)["view"] = viewMatrix(); (*_shader)["projection"] = projectionMatrix(size.x / size.y); (*_shader)["camera.FOV"] = FOV; (*_shader)["camera.nearPlane"] = 0.01f; (*_shader)["camera.farPlane"] = 100.0f; }
void ShadowManager::loadShadowMaps(const Matrix4<float> &viewMatrix) { int i = 0; std::vector<Light *> visibleLights = lightManager->getVisibleLights(); for(std::vector<Light *>::const_iterator itLights = visibleLights.begin(); itLights!=visibleLights.end(); ++itLights) { if((*itLights)->isProduceShadow()) { std::map<const Light *, ShadowData *>::const_iterator it = shadowDatas.find(*itLights); const ShadowData *shadowData = it->second; glActiveTexture(GL_TEXTURE0 + lightsLocation[i].shadowMapTextureUnits); unsigned int shadowMapTextureID = (blurShadow==BlurShadow::NO_BLUR) ? shadowData->getShadowMapTextureID() : shadowData->getHorizontalBlurFilter()->getTextureID(); glBindTexture(GL_TEXTURE_2D_ARRAY, shadowMapTextureID); glUniform1i(lightsLocation[i].shadowMapTexLoc, lightsLocation[i].shadowMapTextureUnits); for(unsigned int j=0; j<nbShadowMaps; ++j) { glUniformMatrix4fv(lightsLocation[i].mLightProjectionViewLoc[j], 1, false, (float *)(shadowData->getFrustumShadowData(j)->getLightProjectionMatrix() * shadowData->getLightViewMatrix())); } } ++i; } float depthSplitDistance[nbShadowMaps]; for(unsigned int i=0; i<nbShadowMaps; ++i) { float currSplitDistance = splittedDistance[i]; depthSplitDistance[i] = (projectionMatrix(2, 2)*-currSplitDistance + projectionMatrix(2, 3)) / (currSplitDistance); } glUniform1fv(depthSplitDistanceLoc, nbShadowMaps, depthSplitDistance); }
/*! Maps \a point from viewport co-ordinates to eye co-ordinates. The size of the viewport is given by \a viewportSize, and its aspect ratio by \a aspectRatio. The returned vector will have its x and y components set to the position of the point on the near plane, and the z component set to -nearPlane(). This function is used for converting a mouse event's position into eye co-ordinates within the current camera view. */ QVector3D QGLCamera::mapPoint (const QPoint& point, float aspectRatio, const QSize& viewportSize) const { Q_D(const QGLCamera); // Rotate the co-ordinate system to account for the screen rotation. int x = point.x(); int y = point.y(); int width = viewportSize.width(); int height = viewportSize.height(); if (!d->adjustForAspectRatio) aspectRatio = 1.0f; if (d->screenRotation == 90) { if (aspectRatio != 0.0f) aspectRatio = 1.0f / aspectRatio; qSwap(x, y); qSwap(width, height); y = height - 1 - y; } else if (d->screenRotation == 180) { x = width - 1 - x; y = height - 1 - y; } else if (d->screenRotation == 270) { if (aspectRatio != 0.0f) aspectRatio = 1.0f / aspectRatio; qSwap(x, y); qSwap(width, height); } // Determine the relative distance from the middle of the screen. // After this xrel and yrel are typically between -1.0 and +1.0 // (unless the point was outside the viewport). The yrel is // flipped upside down to account for the incoming co-ordinate // being left-handed, but the world being right-handed. float xrel, yrel; if (width) xrel = ((float(x * 2)) - float(width)) / float(width); else xrel = 0.0f; if (height) yrel = -((float(y * 2)) - float(height)) / float(height); else yrel = 0.0f; // Reverse the projection and return the point in world co-ordinates. QMatrix4x4 m = projectionMatrix(aspectRatio); QMatrix4x4 invm = m.inverted(); return invm.map(QVector3D(xrel, yrel, -1.0f)); }
Game::Game() : ground_plane_(shaders_), projection_( projectionMatrix(), shaders_.getUniforms(Uniform::PROJECTION)), cube_mesh_(Mesh::fromAssimpMesh(shaders_, loadMesh("../models/cube.obj"))) { glClearColor(0, 0, 0, 1); // Clear to solid blue. glClearDepth(1.0f); glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST);// Enable Depth Testing glDisable(GL_LIGHTING); glShadeModel(GL_SMOOTH); glDisable(GL_LINE_SMOOTH); glEnable(GL_CULL_FACE); free_type_engine_.loadFont("/usr/share/fonts/TTF/DejaVuSans.ttf"); }
void Camera::drawCurve(QMatrix4x4 modelMatrix) { Q_D(Camera); QMatrix4x4 modelViewProject = projectionMatrix() * viewMatrix() * modelMatrix; d->curveShader->bind(); d->curveShader->setUniformValue("mvp", modelViewProject); foreach(BezierCurve* curve, d->curves) curve->drawCurve(d->curveShader); d->curvePointsShader->bind(); d->curvePointsShader->setUniformValue("mvp", modelViewProject); foreach(BezierCurve* curve, d->curves) curve->drawControlPoints(d->curvePointsShader); }
void Camera::projectionMatrixFromCameraInfo (float fx, float fy, int w, int h, float cx, float cy) { _perspective.isPerpective = false; projectionMatrix = Eigen::Matrix4f::Zero(); double far_plane = 100, near_plane = 0.01; // double zoom_x = (float)imageWidth / (float)w, // zoom_y = (float)imageHeight / (float)h; double zoom_x = 1.0, zoom_y = 1.0; projectionMatrix(0, 0) = 2.0 * fx/w * zoom_x; projectionMatrix(1, 1) = 2.0 * fy/h * zoom_y; projectionMatrix(0, 2) = 2.0 * (0.5 - cx/w) * zoom_x; projectionMatrix(1, 2) = 2.0 * (cy/h - 0.5) * zoom_y; projectionMatrix(2, 2) = -(far_plane+near_plane) / (far_plane-near_plane); projectionMatrix(2, 3) = -2.0*far_plane*near_plane / (far_plane-near_plane); projectionMatrix(3, 2) = -1; }
/*! Shader for the normal vector renderer */ void GLSphereRed::initShaderNormal(void) { _program_normals = CreateShaderProgram(vs_string_simple_shader_410, fs_string_simple_shader_410); glUseProgram(_program_normals); unsigned int projectionMatrixLocation = glGetUniformLocation(_program_normals, "projectionMatrix"); // Get the location of our projection matrix in the shader _viewMatrixLocationN = glGetUniformLocation(_program_normals, "viewMatrix"); // Get the location of our view matrix in the shader _modelMatrixLocationN = glGetUniformLocation(_program_normals, "modelMatrix"); // Get the location of our model matrix in the shader glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocationN, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocationN, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader glBindAttribLocation(_program_normals, 0, "in_Position"); glBindAttribLocation(_program_normals, 1, "in_Color"); glUseProgram(0); }
void SimpleGMap3::cb_keyPress(int code) { switch(code) { case 'e': { time_t rawtime; struct tm * timeinfo; char buffer[80]; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer,80,".%F.%H:%M:%S",timeinfo); std::string filename = std::string("topo_screenshot") + std::string(buffer) + std::string(".svg"); m_render_topo->svgout2D(filename, modelViewMatrix(), projectionMatrix()); break; } } }
//protected: virtual void Render() const override { //Debug::Log("Rendere %s", m_gameObject->name().c_str()); auto meshFilter = m_gameObject->GetComponent<MeshFilter>(); if (meshFilter == nullptr) { Debug::LogWarning("This GameObject has no MeshFilter"); return; } auto model = transform()->localToWorldMatrix(); auto camera = Scene::mainCamera(); auto view = camera->worldToCameraMatrix(); auto proj = camera->projectionMatrix(); auto mv = view * model; auto mvp = proj * mv; ShaderUniforms uniforms; //std::map<std::string, Matrix4x4> matrices; uniforms.mat4s["_Object2World"] = model; uniforms.mat4s["MATRIX_V"] = view; uniforms.mat4s["MATRIX_P"] = proj; uniforms.mat4s["MATRIX_VP"] = proj * view; uniforms.mat4s["MATRIX_MVP"] = mvp; uniforms.mat4s["MATRIX_MV"] = mv; uniforms.mat4s["MATRIX_IT_M"] = glm::inverse(glm::transpose(model)); uniforms.mat4s["MATRIX_IT_MV"] = glm::inverse(glm::transpose(mv)); //auto camera = Scene::getMainCamera(); uniforms.vec3s["_WorldSpaceCameraPos"] = camera->transform()->position(); for (auto& m : m_materials) { auto shader = m->shader(); shader->Use(); shader->PreRender(); shader->BindUniforms(uniforms); m->Update(); shader->CheckStatus(); meshFilter->mesh()->Render(); shader->PostRender(); } }
/* Inits the shader program for this object */ void GLSphere::initShader(void) { // Vertex shader source code. This draws the vertices in our window. We have 3 vertices since we're drawing an triangle. // Each vertex is represented by a vector of size 4 (x, y, z, w) coordinates. // static const string vertex_code = vs_string_CoordSystem; static const char * vs_source = vs_string_GLSphere_410.c_str(); // Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader. // static const string fragment_code = fs_string_CoordSystem; static const char * fs_source = fs_string_GLSphere_410.c_str(); // This next section we'll generate the OpenGL program and attach the shaders to it so that we can render our triangle. _program = glCreateProgram(); // We create a shader with our fragment shader source code and compile it. GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &fs_source, NULL); glCompileShader(fs); CheckShader(fs, GL_FRAGMENT_SHADER); // We create a shader with our vertex shader source code and compile it. GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &vs_source, NULL); glCompileShader(vs); CheckShader(vs, GL_VERTEX_SHADER); // We'll attach our two compiled shaders to the OpenGL program. glAttachShader(_program, vs); glAttachShader(_program, fs); glLinkProgram(_program); glUseProgram(_program); _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model int projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader _inverseViewMatrixLocation = glGetUniformLocation(_program, "inverseViewMatrix"); _light_source0._lightPosIdx = glGetUniformLocation(_program, "light_position"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]); /////////////////////////////////////////////////////////////////////////////////////////////// // Material _material._diffuse_material = glm::vec3(1.0, 0.5, 0.0); _material._ambient_material = glm::vec3(1.0, 0.5, 0.0); _material._specular_material = glm::vec3(1.0, 1.0, 1.0); _material._shininess = 12.0; _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color"); _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color"); _material._specularColorPos = glGetUniformLocation(_program, "specular_color"); _material._shininessIdx = glGetUniformLocation(_program, "shininess"); // Send the material to your shader program glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] ); glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]); glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]); glUniform1f(_material._shininessIdx, _material._shininess); /////////////////////////////////////////////////////////////////////////////////////////////// // Light // define the position of the light and send the light position to your shader program _light_source0._lightPos = glm::vec4(50.0,50.0,0.0,1.0); _light_source0._ambient_intensity = 0.5; _light_source0._specular_intensity = 1.0; _light_source0._diffuse_intensity = 1.0; _light_source0._ambientIdx = glGetUniformLocation(_program, "ambient_intensity"); _light_source0._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity"); _light_source0._specularIdx = glGetUniformLocation(_program, "specular_intensity"); // Send the light information to your shader program glUniform1f(_light_source0._ambientIdx, _light_source0._ambient_intensity ); glUniform1f(_light_source0._diffuseIdx, _light_source0._diffuse_intensity); glUniform1f(_light_source0._specularIdx, _light_source0._specular_intensity); glUniform4fv(_light_source0._lightPosIdx, 1, &_light_source0._lightPos[0]); /////////////////////////////////////////////////////////////////////////////////////////////// // Vertex information / names // bind the to the shader program glBindAttribLocation(_program, 0, "in_Position"); glBindAttribLocation(_program, 1, "in_Normal"); glBindAttribLocation(_program, 2, "in_Color"); glUseProgram(0); }
/* Inits the shader program for this object */ void GLSphereRed::initShader(void) { #ifdef _WIN32 // This loads the shader program from a file _program = LoadAndCreateShaderProgram("../data/shaders/redsphere1.vs", "../data/shaders/redsphere1.fs"); #else // This loads the shader program from a file _program = LoadAndCreateShaderProgram("/Users/geethanjalijeevanatham/Desktop/Helloworld/myopenGL/model/testing/assignment2/Problem2/Problem2/data/shaders/redsphere1.vs", "/Users/geethanjalijeevanatham/Desktop/Helloworld/myopenGL/model/testing/assignment2/Problem2/Problem2/data/shaders/redsphere1.fs"); #endif glUseProgram(_program); /////////////////////////////////////////////////////////////////////////////////////////////// // Vertex information / names glBindAttribLocation(_program, 0, "in_Position"); glBindAttribLocation(_program, 1, "in_Normal"); glBindAttribLocation(_program, 2, "in_Color"); /////////////////////////////////////////////////////////////////////////////////////////////// // Define the model view matrix. _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model _projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader _inverseViewMatrixLocation = glGetUniformLocation(_program, "inverseViewMatrix"); glUniformMatrix4fv(_projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]); /////////////////////////////////////////////////////////////////////////////////////////////// // Material _material._diffuse_material = glm::vec3(1.0, 0.0, 0.0); _material._ambient_material = glm::vec3(1.0, 0.0, 0.0); _material._specular_material = glm::vec3(1.0, 1.0, 1.0); _material._shininess = 150.0; _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color"); _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color"); _material._specularColorPos = glGetUniformLocation(_program, "specular_color"); _material._shininessIdx = glGetUniformLocation(_program, "shininess"); // Send the material to your shader program glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] ); glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]); glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]); glUniform1f(_material._shininessIdx, _material._shininess); /////////////////////////////////////////////////////////////////////////////////////////////// // Light // define the position of the light and send the light position to your shader program _light_source1._lightPos = glm::vec4(2.0,0.0,2.0,0.0); _light_source1._ambient_intensity = 0.0; _light_source1._specular_intensity = 1.0; _light_source1._diffuse_intensity = 1.0; _light_source1._attenuation_coeff = 0.02; // Read all the index values from the shader program _light_source1._ambientIdx = glGetUniformLocation(_program, "ambient_intensity"); _light_source1._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity"); _light_source1._specularIdx = glGetUniformLocation(_program, "specular_intensity"); _light_source1._attenuation_coeffIdx = glGetUniformLocation(_program, "attenuationCoefficient"); _light_source1._lightPosIdx = glGetUniformLocation(_program, "light_position"); // Send the light information to your shader program glUniform1f(_light_source1._ambientIdx, _light_source1._ambient_intensity ); glUniform1f(_light_source1._diffuseIdx, _light_source1._diffuse_intensity); glUniform1f(_light_source1._specularIdx, _light_source1._specular_intensity); glUniform1f(_light_source1._attenuation_coeffIdx, _light_source1._attenuation_coeff); glUniform4fv(_light_source1._lightPosIdx, 1, &_light_source1._lightPos[0]); glUseProgram(0); }
Matrix4f SpotLight::lightProjectionMatrix() const { return projectionMatrix() * lightMatrix(); }
void AutoBlend::init() { // Add widget auto toolsWidgetContainer = new QWidget(); widget = new Ui::AutoBlendWidget(); widget->setupUi(toolsWidgetContainer); widgetProxy = new QGraphicsProxyWidget(this); widgetProxy->setWidget(toolsWidgetContainer); // Place at bottom left corner auto delta = widgetProxy->sceneBoundingRect().bottomLeft() - scene()->views().front()->rect().bottomLeft(); widgetProxy->moveBy(-delta.x(), -delta.y()); // Fill categories box { for(auto cat : document->categories.keys()){ widget->categoriesBox->insertItem(widget->categoriesBox->count(), cat); } int idx = widget->categoriesBox->findText(document->categoryOf(document->firstModelName())); widget->categoriesBox->setCurrentIndex(idx); } // Create gallery of shapes gallery = new Gallery(this, QRectF(0,0,this->bounds.width(), 220)); // Create container that holds results results = new Gallery(this, QRectF(0,0, this->bounds.width(), bounds.height() - gallery->boundingRect().height()), QRectF(0,0,256,256), true); results->moveBy(0, gallery->boundingRect().height()); // Gallery on top of results gallery->setZValue(results->zValue() + 10); auto dropShadow = new QGraphicsDropShadowEffect(); dropShadow->setOffset(0, 5); dropShadow->setColor(QColor(0, 0, 0, 150)); dropShadow->setBlurRadius(10); gallery->setGraphicsEffect(dropShadow); // Connect UI with actions { connect(widget->categoriesBox, &QComboBox::currentTextChanged, [&](QString text){ document->currentCategory = text; }); connect(widget->analyzeButton, &QPushButton::pressed, [&](){ document->computePairwise(widget->categoriesBox->currentText()); }); // Default view angle { // Camera target and initial position auto camera = new Eigen::Camera(); auto frame = camera->frame(); frame.position = Eigen::Vector3f(-1, 0, 0.5); camera->setTarget(Eigen::Vector3f(0, 0, 0.5)); camera->setFrame(frame); int deltaZoom = document->extent().length() * 1.0; // Default view angle double theta1 = acos(-1) * 0.75; double theta2 = acos(-1) * 0.10; camera->rotateAroundTarget(Eigen::Quaternionf(Eigen::AngleAxisf(theta1, Eigen::Vector3f::UnitY()))); camera->zoom(-(4+deltaZoom)); camera->rotateAroundTarget(Eigen::Quaternionf(Eigen::AngleAxisf(theta2, Eigen::Vector3f::UnitX()))); auto cp = camera->position(); cameraPos = QVector3D(cp[0], cp[1], cp[2]); // Camera settings camera->setViewport(128, 128); Eigen::Matrix4f p = camera->projectionMatrix(); Eigen::Matrix4f v = camera->viewMatrix().matrix(); p.transposeInPlace(); v.transposeInPlace(); cameraMatrix = QMatrix4x4(p.data()) * QMatrix4x4(v.data()); } connect(document, &Document::categoryAnalysisDone, [=](){ if (gallery == nullptr) return; // Fill gallery gallery->clearThumbnails(); auto catModels = document->categories[document->currentCategory].toStringList(); for (auto targetName : catModels) { auto targetModel = document->cacheModel(targetName); auto t = gallery->addTextItem(targetName); QVariantMap data = t->data; data["targetName"].setValue(targetName); t->setData(data); t->setCamera(cameraPos, cameraMatrix); t->setFlag(QGraphicsItem::ItemIsSelectable); // Add parts of target shape for (auto n : targetModel->nodes){ t->addAuxMesh(toBasicMesh(targetModel->getMesh(n->id), n->vis_property["color"].value<QColor>())); } scene()->update(t->sceneBoundingRect()); } scene()->update(this->sceneBoundingRect()); QTimer::singleShot(500, [=]{ gallery->update(); }); }); // Do blend connect(widget->blendButton, SIGNAL(pressed()), SLOT(doBlend())); } }
void CustomVehicleController::DrawSchematic (dFloat scale) const { dVector array [32]; dMatrix projectionMatrix (dGetIdentityMatrix()); projectionMatrix[0][0] = scale; projectionMatrix[1][1] = 0.0f; projectionMatrix[2][1] = scale; projectionMatrix[2][2] = 0.0f; CustomVehicleControllerManager* const manager = (CustomVehicleControllerManager*)GetManager(); const dMatrix& chassisMatrix = m_chassisState.GetMatrix(); const dMatrix& chassisFrameMatrix = m_chassisState.GetLocalMatrix(); dMatrix worldToComMatrix ((chassisFrameMatrix * chassisMatrix).Inverse() * projectionMatrix); { // draw vehicle chassis dVector p0 (1.0e10f, 1.0e10f, 1.0e10f, 0.0f); dVector p1 (-1.0e10f, -1.0e10f, -1.0e10f, 0.0f); for (dList<CustomVehicleControllerBodyStateTire>::dListNode* node = m_tireList.GetFirst(); node; node = node->GetNext()) { CustomVehicleControllerBodyStateTire* const tire = &node->GetInfo(); dMatrix matrix (tire->CalculateSteeringMatrix() * m_chassisState.GetMatrix()); dVector p (worldToComMatrix.TransformVector(matrix.m_posit)); p0 = dVector (dMin (p.m_x, p0.m_x), dMin (p.m_y, p0.m_y), dMin (p.m_z, p0.m_z), 1.0f); p1 = dVector (dMax (p.m_x, p1.m_x), dMax (p.m_y, p1.m_y), dMax (p.m_z, p1.m_z), 1.0f); } array[0] = dVector (p0.m_x, p0.m_y, p0.m_z, 1.0f); array[1] = dVector (p1.m_x, p0.m_y, p0.m_z, 1.0f); array[2] = dVector (p1.m_x, p1.m_y, p0.m_z, 1.0f); array[3] = dVector (p0.m_x, p1.m_y, p0.m_z, 1.0f); manager->DrawSchematicCallback(this, "chassis", 0, 4, array); } { // draw vehicle tires for (dList<CustomVehicleControllerBodyStateTire>::dListNode* node = m_tireList.GetFirst(); node; node = node->GetNext()) { CustomVehicleControllerBodyStateTire* const tire = &node->GetInfo(); dFloat width = tire->m_width * 0.5f; dFloat radio = tire->m_radio; dMatrix matrix (tire->CalculateSteeringMatrix() * m_chassisState.GetMatrix()); array[0] = worldToComMatrix.TransformVector(matrix.TransformVector(dVector ( width, 0.0f, radio, 0.0f))); array[1] = worldToComMatrix.TransformVector(matrix.TransformVector(dVector ( width, 0.0f, -radio, 0.0f))); array[2] = worldToComMatrix.TransformVector(matrix.TransformVector(dVector (-width, 0.0f, -radio, 0.0f))); array[3] = worldToComMatrix.TransformVector(matrix.TransformVector(dVector (-width, 0.0f, radio, 0.0f))); manager->DrawSchematicCallback(this, "tire", 0, 4, array); } } { // draw vehicle velocity //dVector veloc1; //NewtonBodyGetVelocity(GetBody(), &veloc[0]); dVector veloc (m_chassisState.GetVelocity()); //dVector xxx (veloc1 - veloc); //dAssert (dAbs(xxx % xxx) < 1.0e-3f); dVector localVelocity (chassisFrameMatrix.UnrotateVector (chassisMatrix.UnrotateVector (veloc))); localVelocity.m_y = 0.0f; localVelocity = projectionMatrix.RotateVector(localVelocity); array[0] = dVector (0.0f, 0.0f, 0.0f, 0.0f); array[1] = localVelocity.Scale (0.25f); manager->DrawSchematicCallback(this, "velocity", 0, 2, array); } { dFloat scale (2.0f / (m_chassisState.GetMass() * m_chassisState.m_gravityMag)); // draw vehicle forces for (dList<CustomVehicleControllerBodyStateTire>::dListNode* node = m_tireList.GetFirst(); node; node = node->GetNext()) { CustomVehicleControllerBodyStateTire* const tire = &node->GetInfo(); //dVector p0 (tire->GetCenterOfMass()); dMatrix matrix (tire->CalculateSteeringMatrix() * m_chassisState.GetMatrix()); //dTrace (("(%f %f %f) (%f %f %f)\n", p0.m_x, p0.m_y, p0.m_z, matrix.m_posit.m_x, matrix.m_posit.m_y, matrix.m_posit.m_z )); dVector origin (worldToComMatrix.TransformVector(matrix.m_posit)); dVector lateralForce (chassisFrameMatrix.UnrotateVector(chassisMatrix.UnrotateVector(tire->GetLateralForce()))); lateralForce = lateralForce.Scale (-scale); lateralForce = projectionMatrix.RotateVector (lateralForce); //dTrace (("(%f %f %f)\n", lateralForce.m_x, lateralForce.m_y, lateralForce.m_z )); array[0] = origin; array[1] = origin + lateralForce; manager->DrawSchematicCallback(this, "lateralForce", 0, 2, array); dVector longitudinalForce (chassisFrameMatrix.UnrotateVector(chassisMatrix.UnrotateVector(tire->GetLongitudinalForce()))); longitudinalForce = longitudinalForce.Scale (-scale); longitudinalForce = projectionMatrix.RotateVector (longitudinalForce); //dTrace (("(%f %f %f)\n", lateralForce.m_x, lateralForce.m_y, lateralForce.m_z )); array[0] = origin; array[1] = origin + longitudinalForce; manager->DrawSchematicCallback(this, "longitudinalForce", 0, 2, array); // dVector p2 (p0 - tire->GetLateralForce().Scale (scale)); /* // offset the origin of of tire force so that they are visible const dMatrix& tireMatrix = tire.GetLocalMatrix (); p0 += chassis.GetMatrix()[2].Scale ((tireMatrix.m_posit.m_z > 0.0f ? 1.0f : -1.0f) * 0.25f); // draw the tire load dVector p1 (p0 + tire.GetTireLoad().Scale (scale)); glColor3f (0.0f, 0.0f, 1.0f); glVertex3f (p0.m_x, p0.m_y, p0.m_z); glVertex3f (p1.m_x, p1.m_y, p1.m_z); // show tire lateral force dVector p2 (p0 - tire.GetLateralForce().Scale (scale)); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f (p0.m_x, p0.m_y, p0.m_z); glVertex3f (p2.m_x, p2.m_y, p2.m_z); // show tire longitudinal force dVector p3 (p0 - tire.GetLongitudinalForce().Scale (scale)); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f (p0.m_x, p0.m_y, p0.m_z); glVertex3f (p3.m_x, p3.m_y, p3.m_z); */ } } }
void QSGDefaultRenderer::render() { #if defined (QML_RUNTIME_TESTING) static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree")); if (dumpTree) { printf("\n\n"); QSGNodeDumper::dump(rootNode()); } #endif #ifdef RENDERER_DEBUG debugTimer.invalidate(); debugTimer.start(); geometryNodesDrawn = 0; materialChanges = 0; #endif glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); glFrontFace(isMirrored() ? GL_CW : GL_CCW); glDisable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthMask(true); glDepthFunc(GL_GREATER); #if defined(QT_OPENGL_ES) glClearDepthf(0); #else glClearDepth(0); #endif glDisable(GL_SCISSOR_TEST); glClearColor(m_clear_color.redF(), m_clear_color.greenF(), m_clear_color.blueF(), m_clear_color.alphaF()); #ifdef RENDERER_DEBUG int debugtimeSetup = debugTimer.elapsed(); #endif bindable()->clear(clearMode()); #ifdef RENDERER_DEBUG int debugtimeClear = debugTimer.elapsed(); #endif QRect r = viewportRect(); glViewport(r.x(), deviceRect().bottom() - r.bottom(), r.width(), r.height()); m_current_projection_matrix = projectionMatrix(); m_current_model_view_matrix.setToIdentity(); m_currentClip = 0; glDisable(GL_STENCIL_TEST); m_currentMaterial = 0; m_currentProgram = 0; m_currentMatrix = 0; if (m_rebuild_lists) { m_opaqueNodes.reset(); m_transparentNodes.reset(); m_currentRenderOrder = 1; buildLists(rootNode()); m_rebuild_lists = false; } #ifdef RENDERER_DEBUG int debugtimeLists = debugTimer.elapsed(); #endif if (m_needs_sorting) { if (!m_opaqueNodes.isEmpty()) { qSort(&m_opaqueNodes.first(), &m_opaqueNodes.first() + m_opaqueNodes.size(), m_sort_front_to_back ? nodeLessThanWithRenderOrder : nodeLessThan); } m_needs_sorting = false; } #ifdef RENDERER_DEBUG int debugtimeSorting = debugTimer.elapsed(); #endif m_renderOrderMatrix.setToIdentity(); m_renderOrderMatrix.scale(1, 1, qreal(1) / m_currentRenderOrder); glDisable(GL_BLEND); glDepthMask(true); #ifdef QML_RUNTIME_TESTING if (m_render_opaque_nodes) #endif { #if defined (QML_RUNTIME_TESTING) if (dumpTree) qDebug() << "Opaque Nodes:"; #endif renderNodes(m_opaqueNodes); } #ifdef RENDERER_DEBUG int debugtimeOpaque = debugTimer.elapsed(); int opaqueNodes = geometryNodesDrawn; int opaqueMaterialChanges = materialChanges; #endif glEnable(GL_BLEND); glDepthMask(false); #ifdef QML_RUNTIME_TESTING if (m_render_alpha_nodes) #endif { #if defined (QML_RUNTIME_TESTING) if (dumpTree) qDebug() << "Alpha Nodes:"; #endif renderNodes(m_transparentNodes); } #ifdef RENDERER_DEBUG int debugtimeAlpha = debugTimer.elapsed(); #endif if (m_currentProgram) m_currentProgram->deactivate(); #ifdef RENDERER_DEBUG if (debugTimer.elapsed() > DEBUG_THRESHOLD) { printf(" --- Renderer breakdown:\n" " - setup=%d, clear=%d, building=%d, sorting=%d, opaque=%d, alpha=%d\n" " - material changes: opaque=%d, alpha=%d, total=%d\n" " - geometry ndoes: opaque=%d, alpha=%d, total=%d\n", debugtimeSetup, debugtimeClear - debugtimeSetup, debugtimeLists - debugtimeClear, debugtimeSorting - debugtimeLists, debugtimeOpaque - debugtimeSorting, debugtimeAlpha - debugtimeOpaque, opaqueMaterialChanges, materialChanges - opaqueMaterialChanges, materialChanges, opaqueNodes, geometryNodesDrawn - opaqueNodes, geometryNodesDrawn); } #endif }
// // Vulkan update. // VkBool32 Example::update(const vkts::IUpdateThreadContext& updateContext) { for (size_t i = 0; i < allUpdateables.size(); i++) { allUpdateables[i]->update(updateContext.getDeltaTime(), updateContext.getDeltaTicks()); } // VkResult result = VK_SUCCESS; // if (windowDimension != updateContext.getWindowDimension(windowIndex)) { windowDimension = updateContext.getWindowDimension(windowIndex); result = VK_ERROR_OUT_OF_DATE_KHR; } // uint32_t currentBuffer; if (result == VK_SUCCESS) { result = swapchain->acquireNextImage(UINT64_MAX, imageAcquiredSemaphore->getSemaphore(), VK_NULL_HANDLE, currentBuffer); } if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { glm::mat4 projectionMatrix(1.0f); glm::mat4 viewMatrix(1.0f); const auto& dimension = updateContext.getWindowDimension(windowIndex); projectionMatrix = vkts::perspectiveMat4(45.0f, (float) dimension.x / (float) dimension.y, 1.0f, 100.0f); viewMatrix = camera->getViewMatrix(); glm::vec3 lightDirection = glm::mat3(viewMatrix) * glm::vec3(0.0f, 1.0f, 2.0f); lightDirection = glm::normalize(lightDirection); if (!fragmentUniformBuffer->upload(0, 0, lightDirection)) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not upload light direction."); return VK_FALSE; } if (!vertexViewProjectionUniformBuffer->upload(0 * sizeof(float) * 16, 0, projectionMatrix)) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not upload matrices."); return VK_FALSE; } if (!vertexViewProjectionUniformBuffer->upload(1 * sizeof(float) * 16, 0, viewMatrix)) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not upload matrices."); return VK_FALSE; } if (scene.get()) { scene->updateRecursive(updateContext); } // VkSemaphore waitSemaphores = imageAcquiredSemaphore->getSemaphore(); VkSemaphore signalSemaphores = renderingCompleteSemaphore->getSemaphore(); VkPipelineStageFlags waitDstStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submitInfo; memset(&submitInfo, 0, sizeof(VkSubmitInfo)); submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.waitSemaphoreCount = 1; submitInfo.pWaitSemaphores = &waitSemaphores; submitInfo.pWaitDstStageMask = &waitDstStageMask; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = cmdBuffer[currentBuffer]->getCommandBuffers(); submitInfo.signalSemaphoreCount = 1; submitInfo.pSignalSemaphores = &signalSemaphores; result = initialResources->getQueue()->submit(1, &submitInfo, VK_NULL_HANDLE); if (result != VK_SUCCESS) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not submit queue."); return VK_FALSE; } waitSemaphores = renderingCompleteSemaphore->getSemaphore(); VkSwapchainKHR swapchains = swapchain->getSwapchain(); result = swapchain->queuePresent(initialResources->getQueue()->getQueue(), 1, &waitSemaphores, 1, &swapchains, ¤tBuffer, nullptr); if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { result = initialResources->getQueue()->waitIdle(); if (result != VK_SUCCESS) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not wait for idle queue."); return VK_FALSE; } } else { if (result == VK_ERROR_OUT_OF_DATE_KHR) { terminateResources(updateContext); if (!buildResources(updateContext)) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not build resources."); return VK_FALSE; } } else { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not present queue."); return VK_FALSE; } } } else { if (result == VK_ERROR_OUT_OF_DATE_KHR) { terminateResources(updateContext); if (!buildResources(updateContext)) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not build resources."); return VK_FALSE; } } else { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not acquire next image."); return VK_FALSE; } } // result = imageAcquiredSemaphore->reset(); if (result != VK_SUCCESS) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not reset semaphore."); return VK_FALSE; } result = renderingCompleteSemaphore->reset(); if (result != VK_SUCCESS) { vkts::logPrint(VKTS_LOG_ERROR, "Example: Could not reset semaphore."); return VK_FALSE; } return VK_TRUE; }
void CSimulatorWindowHandler::init() { CEGUI::WindowManager &windowMngr = CEGUI::WindowManager::getSingleton(); m_continueButton = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/ContinueButton")); m_startButton = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/StartButton")); m_zoomButton = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/ZoomButton")); m_formation433Button = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/433Button")); m_formation442Button = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/442Button")); m_frameWindow = static_cast<CEGUI::FrameWindow*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/FrameWindow")); m_view2DButton = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/2DButton")); m_view3DButton = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/3DButton")); m_frameStartButtom = static_cast<CEGUI::PushButton*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/StartButton")); m_logHistoryList = static_cast<CEGUI::Listbox*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Log")); m_logHistoryListShort = static_cast<CEGUI::Listbox*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/Log")); m_teamPlayersList = static_cast<CEGUI::MultiColumnList*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/TeamPlayersList")); m_groundImage = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Image")); m_groundFrameImage = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/Image")); m_teamNames = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/TeamNames")); m_score = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Score")); m_frameHomeName = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/HomeName")); m_frameAwayName = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/AwayName")); m_frameHomeScore = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/HomeScore")); m_frameAwayScore = static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/Frame/AwayScore")); // i18n support m_continueButton->setText((CEGUI::utf8*)gettext("Continue")); m_startButton->setText((CEGUI::utf8*)gettext("Start")); m_zoomButton->setText((CEGUI::utf8*)gettext("Zoom")); m_frameWindow->setText((CEGUI::utf8*)gettext("Simulation View")); m_view2DButton->setText((CEGUI::utf8*)gettext("2D View")); m_view3DButton->setText((CEGUI::utf8*)gettext("3D View")); m_frameStartButtom->setText((CEGUI::utf8*)gettext("Start")); static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/TeamTab"))->setText((CEGUI::utf8*)gettext("Team")); static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/FormationTab"))->setText((CEGUI::utf8*)gettext("Formation")); static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/LogTab"))->setText((CEGUI::utf8*)gettext("Log")); static_cast<CEGUI::Window*>(windowMngr.getWindow((CEGUI::utf8*)"Simulator/StatisticsTab"))->setText((CEGUI::utf8*)gettext("Statistics")); // Event handle registerEventConnection(m_continueButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::continueButtonClicked, this))); registerEventConnection(m_startButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::startButtonClicked, this))); registerEventConnection(m_zoomButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::zoomButtonClicked, this))); registerEventConnection(m_formation433Button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::formation433ButtonClicked, this))); registerEventConnection(m_formation442Button->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::formation442ButtonClicked, this))); registerEventConnection(m_frameWindow->subscribeEvent(CEGUI::FrameWindow::EventCloseClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::frameWindowCloseClicked, this))); registerEventConnection(m_view2DButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::view2DButtonClicked, this))); registerEventConnection(m_view3DButton->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::view3DButtonClicked, this))); registerEventConnection(m_frameStartButtom->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::startButtonClicked, this))); registerEventConnection(windowMngr.getWindow("Simulator")->subscribeEvent(CEGUI::Window::EventKeyDown, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::keyDownHandler, this))); registerEventConnection(windowMngr.getWindow("Simulator")->subscribeEvent(CEGUI::Window::EventKeyUp, CEGUI::Event::Subscriber(&CSimulatorWindowHandler::keyUpHandler, this))); m_direction = Ogre::Vector3::ZERO; m_sceneMngr = Ogre::Root::getSingleton().createSceneManager(Ogre::ST_GENERIC, SIMULATION_SCENE_MANAGER_NODE_NAME); m_cam2D = m_sceneMngr->createCamera("2D_Camera"); m_cam2D->setNearClipDistance(1); int width = 120; int height = 90; double right = width/2.0, left = -width/2.0, top = height/2.0, bottom = -height/2.0, farZ = 150.0, nearZ = 10.0; Ogre::Matrix4 projectionMatrix( 2/(right-left), 0, 0, -(right+left)/(right-left), 0, 2/(top-bottom), 0, -(top+bottom)/(top-bottom), 0, 0, -2/(farZ-nearZ), -(farZ+nearZ)/(farZ-nearZ), 0, 0, 0, 1 ); m_cam2D->setProjectionType(Ogre::PT_ORTHOGRAPHIC); m_cam2D->setCustomProjectionMatrix(true, projectionMatrix); m_cam3D = m_sceneMngr->createCamera("3D_Camera"); m_cam3D->setProjectionType(Ogre::PT_PERSPECTIVE); m_cam3D->setCustomProjectionMatrix(false); m_cam3D->setNearClipDistance(5); Ogre::TexturePtr texturePtr = Ogre::TextureManager::getSingleton().createManual("RttTex", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, (int)m_groundImage->getPixelSize().d_width, (int)m_groundImage->getPixelSize().d_height, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); m_renderTexture = texturePtr->getBuffer()->getRenderTarget(); CEGUI::Texture *cTex = static_cast<CEGUI::OgreCEGUIRenderer*>(CEGUI::System::getSingleton().getRenderer())->createTexture((CEGUI::utf8*)"RttTex"); CEGUI::Imageset *imageSet = CEGUI::ImagesetManager::getSingleton().createImageset((CEGUI::utf8*)"RttImageset", cTex); imageSet->defineImage((CEGUI::utf8*)"RttImage", CEGUI::Point(0.0f, 0.0f), CEGUI::Size(cTex->getWidth(), cTex->getHeight()), CEGUI::Point(0.0f,0.0f)); m_groundImage->setProperty( "Image", CEGUI::PropertyHelper::imageToString(&imageSet->getImage((CEGUI::utf8*)"RttImage"))); m_groundFrameImage->setProperty("Image", CEGUI::PropertyHelper::imageToString(&imageSet->getImage((CEGUI::utf8*)"RttImage"))); m_groundFrameImage->disable(); m_initiated = true; }
void UsdMayaGLBatchRenderer::_RenderBatches( const MHWRender::MDrawContext* vp2Context, const MMatrix& viewMat, const MMatrix& projectionMat, const GfVec4d& viewport ) { if( _renderQueue.empty() ) return; if( !_populateQueue.empty() ) { TF_DEBUG(PXRUSDMAYAGL_QUEUE_INFO).Msg( "____________ POPULATE STAGE START ______________ (%zu)\n",_populateQueue.size()); std::vector<UsdImagingDelegate*> delegates; UsdPrimVector rootPrims; std::vector<SdfPathVector> excludedPrimPaths; std::vector<SdfPathVector> invisedPrimPaths; for( ShapeRenderer *shapeRenderer : _populateQueue ) { delegates.push_back(shapeRenderer->_delegate.get()); rootPrims.push_back(shapeRenderer->_rootPrim); excludedPrimPaths.push_back(shapeRenderer->_excludedPaths); invisedPrimPaths.push_back(SdfPathVector()); shapeRenderer->_isPopulated = true; } UsdImagingDelegate::Populate( delegates, rootPrims, excludedPrimPaths, invisedPrimPaths ); _populateQueue.clear(); TF_DEBUG(PXRUSDMAYAGL_QUEUE_INFO).Msg( "^^^^^^^^^^^^ POPULATE STAGE FINISH ^^^^^^^^^^^^^ (%zu)\n",_populateQueue.size()); } TF_DEBUG(PXRUSDMAYAGL_QUEUE_INFO).Msg( "____________ RENDER STAGE START ______________ (%zu)\n",_renderQueue.size()); // A new display refresh signifies that the cached selection data is no // longer valid. _selectQueue.clear(); _selectResults.clear(); // We've already populated with all the selection info we need. We Reset // and the first call to GetSoftSelectHelper in the next render pass will // re-populate it. _softSelectHelper.Reset(); GfMatrix4d modelViewMatrix(viewMat.matrix); GfMatrix4d projectionMatrix(projectionMat.matrix); _taskDelegate->SetCameraState(modelViewMatrix, projectionMatrix, viewport); // save the current GL states which hydra may reset to default glPushAttrib(GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT); // hydra orients all geometry during topological processing so that // front faces have ccw winding. We disable culling because culling // is handled by fragment shader discard. glFrontFace(GL_CCW); // < State is pushed via GL_POLYGON_BIT glDisable(GL_CULL_FACE); // note: to get benefit of alpha-to-coverage, the target framebuffer // has to be a MSAA buffer. glDisable(GL_BLEND); glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE); if (vp2Context) { _taskDelegate->SetLightingStateFromMayaDrawContext(*vp2Context); } else { _taskDelegate->SetLightingStateFromVP1(viewMat); } // The legacy viewport does not support color management, // so we roll our own gamma correction by GL means (only in // non-highlight mode) bool gammaCorrect = !vp2Context; if( gammaCorrect ) glEnable(GL_FRAMEBUFFER_SRGB_EXT); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); // render task setup HdTaskSharedPtrVector tasks = _taskDelegate->GetSetupTasks(); // lighting etc for( const auto &renderSetIter : _renderQueue ) { size_t hash = renderSetIter.first; const RenderParams ¶ms = renderSetIter.second.first; const _SdfPathSet &renderPaths = renderSetIter.second.second; TF_DEBUG(PXRUSDMAYAGL_QUEUE_INFO).Msg( "*** renderQueue, batch %zx, size %zu\n", renderSetIter.first, renderPaths.size() ); SdfPathVector roots(renderPaths.begin(), renderPaths.end()); tasks.push_back(_taskDelegate->GetRenderTask(hash, params, roots)); } _hdEngine.Execute(*_renderIndex, tasks); if( gammaCorrect ) glDisable(GL_FRAMEBUFFER_SRGB_EXT); glPopAttrib(); // GL_LIGHTING_BIT | GL_ENABLE_BIT | GL_POLYGON_BIT // Selection is based on what we have last rendered to the display. The // selection queue is cleared above, so this has the effect of resetting // the render queue and prepping the selection queue without any // significant memory hit. _renderQueue.swap( _selectQueue ); TF_DEBUG(PXRUSDMAYAGL_QUEUE_INFO).Msg( "^^^^^^^^^^^^ RENDER STAGE FINISH ^^^^^^^^^^^^^ (%zu)\n",_renderQueue.size()); }
/* Inits the shader program for this object */ void GLSphereDirect::initShader(void) { #ifdef _WIN32 // This loads the shader program from a file _program = LoadAndCreateShaderProgram("../data/shaders/p1.vs", "../data/shaders/p1.fs"); #else // This loads the shader program from a file _program = LoadAndCreateShaderProgram("../../data/shaders/p1.vs", "../../data/shaders/p1.fs"); #endif glUseProgram(_program); /////////////////////////////////////////////////////////////////////////////////////////////// // Vertex information / names glBindAttribLocation(_program, 0, "in_Position"); glBindAttribLocation(_program, 1, "in_Normal"); glBindAttribLocation(_program, 2, "in_Color"); /////////////////////////////////////////////////////////////////////////////////////////////// // Define the model view matrix. _modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model _projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader _viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader _modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader glUniformMatrix4fv(_projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader /////////////////////////////////////////////////////////////////////////////////////////////// // Material _material._diffuse_material = glm::vec3(0.0, 0.0, 1.0); _material._ambient_material = glm::vec3(0.0, 0.0, 0.0); _material._specular_material = glm::vec3(1.0, 1.0, 1.0); _material._shininess = 1.0; _material._ambientColorPos = glGetUniformLocation(_program, "ambient_color"); _material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color"); _material._specularColorPos = glGetUniformLocation(_program, "specular_color"); _material._shininessIdx = glGetUniformLocation(_program, "shininess"); // Send the material to your shader program glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] ); glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]); glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]); glUniform1f(_material._shininessIdx, _material._shininess); /////////////////////////////////////////////////////////////////////////////////////////////// // Light //Normal light // define the position of the light and send the light position to your shader program _light_source0._lightPos = glm::vec4(0.0, 0.0, 30.0, 1.0); _light_source0._ambient_intensity = 0.1; _light_source0._specular_intensity = 0.1; _light_source0._diffuse_intensity = 10.0; // Read all the index values from the shader program _light_source0._ambientIdx = glGetUniformLocation(_program, "ambient_intensity0"); _light_source0._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity0"); _light_source0._specularIdx = glGetUniformLocation(_program, "specular_intensity0"); _light_source0._lightPosIdx = glGetUniformLocation(_program, "light_position0"); // Send the light information to your shader program glUniform1f(_light_source0._ambientIdx, _light_source0._ambient_intensity ); glUniform1f(_light_source0._diffuseIdx, _light_source0._diffuse_intensity); glUniform1f(_light_source0._specularIdx, _light_source0._specular_intensity); glUniform4fv(_light_source0._lightPosIdx, 1, &_light_source0._lightPos[0]); //Spotlight // define the position of the light and send the light position to your shader program _light_source1._lightPos = glm::vec4(0.0, 0.0, 30, 0.0); _light_source1._ambient_intensity = 0.3; _light_source1._specular_intensity = 2.0; _light_source1._diffuse_intensity = 5.0; _light_source1._attenuation_coeff = 0.02; _light_source1._cone_angle = 6.0; // in degree _light_source1._cone_direction = glm::vec3(-2.0, 0.0, -25.0); // this must be aligned with the object and light position. // Read all the index values from the shader program _light_source1._ambientIdx = glGetUniformLocation(_program, "ambient_intensity"); _light_source1._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity"); _light_source1._specularIdx = glGetUniformLocation(_program, "specular_intensity"); _light_source1._attenuation_coeffIdx = glGetUniformLocation(_program, "attenuationCoefficient"); _light_source1._lightPosIdx = glGetUniformLocation(_program, "light_position"); _light_source1._cone_angleIdx = glGetUniformLocation(_program, "cone_angle"); _light_source1._cone_directionIdx = glGetUniformLocation(_program, "cone_direction"); // Send the light information to your shader program glUniform1f(_light_source1._ambientIdx, _light_source1._ambient_intensity ); glUniform1f(_light_source1._diffuseIdx, _light_source1._diffuse_intensity); glUniform1f(_light_source1._specularIdx, _light_source1._specular_intensity); glUniform1f(_light_source1._attenuation_coeffIdx, _light_source1._attenuation_coeff); glUniform4fv(_light_source1._lightPosIdx, 1, &_light_source1._lightPos[0]); glUniform1f(_light_source1._cone_angleIdx, _light_source1._cone_angle); glUniform3fv(_light_source1._cone_directionIdx, 1, &_light_source1._cone_direction[0]); glUseProgram(0); }
Matrix4x4f CameraUtility::getProjectionMatrix4x4() { float projection[16]; glGetFloatv(GL_PROJECTION_MATRIX, projection); Matrix4x4f projectionMatrix(projection); return projectionMatrix; }
void QSGDefaultRenderer::buildLists(QSGNode *node) { if (node->isSubtreeBlocked()) return; if (node->type() == QSGNode::GeometryNodeType) { QSGGeometryNode *geomNode = static_cast<QSGGeometryNode *>(node); qreal opacity = geomNode->inheritedOpacity(); QSGMaterial *m = geomNode->activeMaterial(); #ifdef FORCE_NO_REORDER if (true) { #else if ((m->flags() & QSGMaterial::Blending) || opacity < 1) { #endif geomNode->setRenderOrder(m_currentRenderOrder - 1); m_transparentNodes.add(geomNode); } else { geomNode->setRenderOrder(m_currentRenderOrder); m_opaqueNodes.add(geomNode); m_currentRenderOrder += 2; } } if (!node->firstChild()) return; #ifdef FORCE_NO_REORDER static bool reorder = false; #else static bool reorder = !qApp->arguments().contains(QLatin1String("--no-reorder")); #endif if (reorder && node->firstChild() != node->lastChild() && (node->flags() & QSGNode::ChildrenDoNotOverlap)) { QVarLengthArray<int, 16> beginIndices; QVarLengthArray<int, 16> endIndices; int baseCount = m_transparentNodes.size(); int count = 0; for (QSGNode *c = node->firstChild(); c; c = c->nextSibling()) { beginIndices.append(m_transparentNodes.size()); buildLists(c); endIndices.append(m_transparentNodes.size()); ++count; } int childNodeCount = m_transparentNodes.size() - baseCount; if (childNodeCount) { m_tempNodes.reset(); m_tempNodes.reserve(childNodeCount); while (childNodeCount) { for (int i = 0; i < count; ++i) { if (beginIndices[i] != endIndices[i]) m_heap.insert(IndexGeometryNodePair(i, m_transparentNodes.at(beginIndices[i]++))); } while (!m_heap.isEmpty()) { IndexGeometryNodePair pair = m_heap.pop(); m_tempNodes.add(pair.second); --childNodeCount; int i = pair.first; if (beginIndices[i] != endIndices[i] && !nodeLessThan(m_transparentNodes.at(beginIndices[i]), pair.second)) m_heap.insert(IndexGeometryNodePair(i, m_transparentNodes.at(beginIndices[i]++))); } } Q_ASSERT(m_tempNodes.size() == m_transparentNodes.size() - baseCount); qMemCopy(&m_transparentNodes.at(baseCount), &m_tempNodes.at(0), m_tempNodes.size() * sizeof(QSGGeometryNode *)); } } else { for (QSGNode *c = node->firstChild(); c; c = c->nextSibling()) buildLists(c); } } void QSGDefaultRenderer::renderNodes(const QDataBuffer<QSGGeometryNode *> &list) { const float scale = 1.0f / m_currentRenderOrder; int count = list.size(); int currentRenderOrder = 0x80000000; m_current_projection_matrix.setColumn(2, scale * projectionMatrix().column(2)); //int clipChangeCount = 0; //int programChangeCount = 0; //int materialChangeCount = 0; for (int i = 0; i < count; ++i) { QSGGeometryNode *geomNode = list.at(i); QSGMaterialShader::RenderState::DirtyStates updates; #if defined (QML_RUNTIME_TESTING) static bool dumpTree = qApp->arguments().contains(QLatin1String("--dump-tree")); if (dumpTree) qDebug() << geomNode; #endif bool changeMatrix = m_currentMatrix != geomNode->matrix(); if (changeMatrix) { m_currentMatrix = geomNode->matrix(); if (m_currentMatrix) m_current_model_view_matrix = *m_currentMatrix; else m_current_model_view_matrix.setToIdentity(); updates |= QSGMaterialShader::RenderState::DirtyMatrix; } bool changeOpacity = m_current_opacity != geomNode->inheritedOpacity(); if (changeOpacity) { updates |= QSGMaterialShader::RenderState::DirtyOpacity; m_current_opacity = geomNode->inheritedOpacity(); } Q_ASSERT(geomNode->activeMaterial()); QSGMaterial *material = geomNode->activeMaterial(); QSGMaterialShader *program = m_context->prepareMaterial(material); Q_ASSERT(program->program()->isLinked()); bool changeClip = geomNode->clipList() != m_currentClip; QSGRenderer::ClipType clipType = QSGRenderer::NoClip; if (changeClip) { clipType = updateStencilClip(geomNode->clipList()); m_currentClip = geomNode->clipList(); #ifdef FORCE_NO_REORDER glDepthMask(false); #else glDepthMask((material->flags() & QSGMaterial::Blending) == 0 && m_current_opacity == 1); #endif //++clipChangeCount; } bool changeProgram = (changeClip && clipType == QSGRenderer::StencilClip) || m_currentProgram != program; if (changeProgram) { if (m_currentProgram) m_currentProgram->deactivate(); m_currentProgram = program; m_currentProgram->activate(); //++programChangeCount; updates |= (QSGMaterialShader::RenderState::DirtyMatrix | QSGMaterialShader::RenderState::DirtyOpacity); #ifdef RENDERER_DEBUG materialChanges++; #endif } bool changeRenderOrder = currentRenderOrder != geomNode->renderOrder(); if (changeRenderOrder) { currentRenderOrder = geomNode->renderOrder(); m_current_projection_matrix.setColumn(3, projectionMatrix().column(3) + currentRenderOrder * m_current_projection_matrix.column(2)); updates |= QSGMaterialShader::RenderState::DirtyMatrix; } if (changeProgram || m_currentMaterial != material) { program->updateState(state(updates), material, changeProgram ? 0 : m_currentMaterial); m_currentMaterial = material; //++materialChangeCount; } //glDepthRange((geomNode->renderOrder() + 0.1) * scale, (geomNode->renderOrder() + 0.9) * scale); const QSGGeometry *g = geomNode->geometry(); bindGeometry(program, g); draw(geomNode); #ifdef RENDERER_DEBUG geometryNodesDrawn++; #endif } //qDebug("Clip: %i, shader program: %i, material: %i times changed while drawing %s items", // clipChangeCount, programChangeCount, materialChangeCount, // &list == &m_transparentNodes ? "transparent" : "opaque"); } QT_END_NAMESPACE