void FPSControls::computeXboxFoV( XINPUT_GAMEPAD* pGamepad, PerspectiveCamera& camera ) { ubyte lt = pGamepad->bLeftTrigger; ubyte rt = pGamepad->bRightTrigger; // do nothing if both triggers are held down if( lt > 0 && rt > 0 ) { return; } float fov = camera.fovYRadians(); // left trigger: zoom out if( lt > 0 ) { fov += lt * m_xboxGamepadParameters.fovRadiansPerTick; } // right trigger: zoom in else { fov -= rt * m_xboxGamepadParameters.fovRadiansPerTick; } float fovMin = MathUtils::degreesToRadians( 1.0f ); float fovMax = MathUtils::degreesToRadians( 179.0f ); fov = MathUtils::clampToRange( fov, fovMin, fovMax ); camera.setFovYRadians( fov ); }
void RenderManager::renderBucket(RenderBucket bucket, Camera &camera, Environment &env) { bool canRender = false; vector<Geometry*> geomList = buckets[bucket]; if (geomList.size() > 0) { for (size_t i = 0; i < geomList.size(); i++) { if (frustumCullingEnabled) { PerspectiveCamera *pers = static_cast<PerspectiveCamera*>(&camera); if (pers->getFrustum().intersectAABB(geomList[i]->getGlobalBoundingBox())) canRender = true; } else canRender = true; if (canRender) { geomList[i]->render(camera, env); } } } }
void LoadTestScene() { Scene* firstScene = new Scene(); engine->AddScene(firstScene); Transform* t = nullptr; PerspectiveCamera* camera = new PerspectiveCamera(Color::Red(), 1.f, 1000.f, 45.f, Screen::AspectRatio()); firstScene->AddGameObject(camera); firstScene->RegisterCamera(camera); t = camera->GetTransform(); t->SetRotation(glm::vec3(0, 180.f, 0)); GameObject* triangle = new GameObject(); firstScene->AddGameObject(triangle); triangle->SetName("Triangle"); triangle->ModifyMeshRenderer(Mesh::Triangle(), Shader::GetDefaultShader(Shader::DefaultShaderName::UNLIT_COLOR)); t = triangle->GetTransform(); t->Translate(glm::vec3(0.f, 0, 3.f)); auto mr = triangle->GetMeshRenderer(); mr->mesh->Colorize(Color::Yellow()); glm::vec4 colors[3]{ Color::Red() , Color::Green() ,Color::Blue() }; mr->mesh->Colorize(colors, 3); }
void XmlSceneParser::Parse (const ParseNode& decl, PerspectiveCamera& node, Node& parent, SceneContext& context) { try { //попытка найти параметры в кеше PerspectiveCameraDeclPtr node_decl = impl->PreparePerspectiveCamera (decl); //настройка камеры if (node_decl->params [PerspectiveCameraDecl::FovX].state) node.SetFovX (degree (node_decl->params [PerspectiveCameraDecl::FovX].value)); if (node_decl->params [PerspectiveCameraDecl::FovY].state) node.SetFovY (degree (node_decl->params [PerspectiveCameraDecl::FovY].value)); if (node_decl->params [PerspectiveCameraDecl::ZNear].state) node.SetZNear (node_decl->params [PerspectiveCameraDecl::ZNear].value); if (node_decl->params [PerspectiveCameraDecl::ZFar].state) node.SetZFar (node_decl->params [PerspectiveCameraDecl::ZFar].value); //разбор родительских параметров Parse (decl, static_cast<Camera&> (node), parent, context); } catch (xtl::exception& e) { e.touch ("scene_graph::XmlSceneParser::Parse(const ParseNode&,PerspectiveCamera&,Node&,SceneContext&)"); throw; } }
void PathHybridState::Init(const PathHybridRenderThread *thread) { PathHybridRenderEngine *renderEngine = (PathHybridRenderEngine *)thread->renderEngine; Scene *scene = renderEngine->renderConfig->scene; depth = 1; lastPdfW = 1.f; throuput = Spectrum(1.f); directLightRadiance = Spectrum(); // Initialize eye ray PerspectiveCamera *camera = scene->camera; Film *film = thread->threadFilm; const u_int filmWidth = film->GetWidth(); const u_int filmHeight = film->GetHeight(); sampleResults[0].screenX = std::min(sampler->GetSample(0) * filmWidth, (float)(filmWidth - 1)); sampleResults[0].screenY = std::min(sampler->GetSample(1) * filmHeight, (float)(filmHeight - 1)); camera->GenerateRay(sampleResults[0].screenX, sampleResults[0].screenY, &nextPathVertexRay, sampler->GetSample(2), sampler->GetSample(3)); sampleResults[0].alpha = 1.f; sampleResults[0].radiance = Spectrum(0.f); lastSpecular = true; }
void GameManager::update() { double elapsed = glutGet(GLUT_ELAPSED_TIME); double delta_t = elapsed - _elapsed; _elapsed = elapsed; _car->updateComp(delta_t); _car->update(delta_t); _car->resetLimits(); for (std::vector<StaticObject*>::iterator it = _gameobjects_static.begin(); it != _gameobjects_static.end(); it++) { (*it)->update(delta_t); (*it)->resetLimits(); } for (std::vector<DynamicObject*>::iterator it = _gameobjects_road.begin(); it != _gameobjects_road.end(); it++) { (*it)->update(delta_t); (*it)->resetLimits(); } for (std::vector<DynamicObject*>::iterator it = _gameobjects_road.begin(); it != _gameobjects_road.end(); it++) { if (_car->checkColision((*it))){ _car->treatColision(); for (std::vector<DynamicObject*>::iterator it = _gameobjects_road.begin(); it != _gameobjects_road.end(); it++) (*it)->resetClock(); break; } } for (std::vector<StaticObject*>::iterator it = _gameobjects_static.begin(); it != _gameobjects_static.end(); it++) { if (_car->checkColision((*it))){ _car->treatStaticColision(); break; } } PerspectiveCamera* camera = (PerspectiveCamera*)_cameras.at(_camera); if (_camera == 2) { camera->setPosition(_car->getPosition()->getX() - 15 * cos(_car->getDirection()*3.14 / 180), _car->getPosition()->getY() - 15 * sin(_car->getDirection()*3.14 / 180), 10); camera->setAt(_car->getPosition()->getX(), _car->getPosition()->getY(), 3); //camera->setUp(0, 1, 0); _cameras.at(_camera)->update(); } }
void DensityField::computePiDensity(const PerspectiveCamera& cam, const Scene& scene) { printInfo("Performing fog density preintegration."); printInfo("This will take a few seconds. Please wait! :-)"); const auto& res = m_pi_dens_res = ivec3{cam.resolution(), m_res.z}; // Allocate storage m_pi_dens_data = new float[piDensSize()]; // Set up render loop assert(0 == res.x % PACKET_SZ && 0 == res.y % PACKET_SZ); const ivec2 n_packets{cam.resolution() / PACKET_SZ}; #pragma omp parallel for for (int p_j = 0; p_j < n_packets.y; ++p_j) for (int p_i = 0; p_i < n_packets.x; ++p_i) for (int p_y = 0; p_y < PACKET_SZ; ++p_y) for (int p_x = 0; p_x < PACKET_SZ; ++p_x) { const int x{p_x + p_i * PACKET_SZ}; const int y{p_y + p_j * PACKET_SZ}; // Use pixel center: offset by 0.5 rt::Ray ray{cam.getPrimaryRay(x + 0.5f, y + 0.5f)}; // Intersect the bounding volume of density field const auto is = m_bbox.intersect(ray); if (is) { // Determine distance to the geometry scene.trace(ray); // Compute parametric ray bounds const float t_min{max(is.entr, 0.0f)}; const float t_max{min(is.exit, ray.inters.distance)}; // Sample density at interval endpoints const int n_intervals{res.z * 4}; const float dt{(t_max - t_min) / n_intervals}; // Perform ray marching float prev_dens{sampleDensity(ray.o + t_min * ray.d)}; float dens{0.0f}; for (int i = 1; i <= n_intervals; ++i) { // Distance to the end of the interval const float t{t_min + i * dt}; const float curr_dens{sampleDensity(ray.o + t * ray.d)}; // Use trapezoidal rule for integration dens += 0.5f * (curr_dens + prev_dens); prev_dens = curr_dens; if (2 == i % 4) { // We are in the middle of the camera-space voxel (froxel) const int z{i / 4}; m_pi_dens_data[x + y * res.x + z * res.x * res.y] = dens * dt; } } } else { // Set density to zero along the ray for (int z = 0; z < res.z; ++z) { m_pi_dens_data[x + y * res.x + z * res.x * res.y] = 0.0f; } } } // Save it to disk writePiDens("Assets\\pi_df.3dt"); // Load data into OpenGL texture createPiDensTex(); }
int main(int /*argc*/, char ** /*argv*/) { BaseApp app; ProgramObject program; auto mainWindow = app.getMainWindow(); std::string prefix = app.getResourceDir() + "Shaders/Examples/e06_ModelLoader/"; PerspectiveCamera cam; OrbitManipulator manipulator(&cam); manipulator.setupCallbacks(app); NodeShared root; GLuint query[2]; app.addInitCallback([&]() { auto vs = compileShader(GL_VERTEX_SHADER, Loader::text(prefix + "phong.vert")); auto fs = compileShader(GL_FRAGMENT_SHADER, Loader::text(prefix + "phong.frag")); program = createProgram(vs, fs); root = Loader::scene(app.getResourceDir() + "Models/sponza/sponza.fbx"); glCreateQueries(GL_TIMESTAMP, 2, query); SDL_GL_SetSwapInterval(0); }); app.addResizeCallback([&](int w, int h) { glViewport(0, 0, w, h); cam.setAspect(float(w) / float(h)); }); app.addDrawCallback([&]() { glQueryCounter(query[0], GL_TIMESTAMP); glClearColor(0.2, 0.2, 0.2, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); //bunny program.use(); program.setMatrix4fv("p", value_ptr(cam.getProjection())); program.setMatrix4fv("v", value_ptr(cam.getView())); drawNode(program, root); glQueryCounter(query[1], GL_TIMESTAMP); GLuint64 time1, time2; glGetQueryObjectui64v(query[0], GL_QUERY_RESULT, &time1); glGetQueryObjectui64v(query[1], GL_QUERY_RESULT, &time2); std::string s = "fps: " + std::to_string(1e9 / (time2 - time1)) + " (" + std::to_string(ImGui::GetIO().Framerate) + ")"; label(s, 0, 0, 300, 100); }); return app.run(); }
void TitleWindow::drawCallback() { const uvec2 &wsize = atmGetWindowSize(); PerspectiveCamera cam; cam.setAspect((float32)wsize.x/(float32)wsize.y); cam.setPosition(vec3(0.0f, 0.0f, 3.0f)); cam.setZNear(0.01f); cam.setZFar(10.0f); atmGetRenderer()->setGameCamera(cam); atmGetRenderer()->setTime(m_time); atmGetBackgroundPass()->setBGShader(SH_BG7); }
void PerspectiveCameraBase::execSyncV( FieldContainer &oFrom, ConstFieldMaskArg whichField, AspectOffsetStore &oOffsets, ConstFieldMaskArg syncMode, const UInt32 uiSyncInfo) { PerspectiveCamera *pThis = static_cast<PerspectiveCamera *>(this); pThis->execSync(static_cast<PerspectiveCamera *>(&oFrom), whichField, oOffsets, syncMode, uiSyncInfo); }
void testCamera() { ParamSet params; GaussianFilter *filter = new GaussianFilter(2, 2, 2); float crop[4] = { 0, 1, 0, 1 }; ImageFilm* film = new ImageFilm(100, 100, filter, crop, "filename", false); Transform t = LookAt(Point(0,0,0), Point(0,0,-100), Vector(0,1,0)); AnimatedTransform cam2world(&t, 0, &t, 0); //BoxFilter *filter = CreateBoxFilter(params); //ImageFilm *film = CreateImageFilm(params, filter); PerspectiveCamera *camera = CreatePerspectiveCamera(params, cam2world, film); bool jitter = false; //params.FindOneBool("jitter", true); // Initialize common sampler parameters int xstart, xend, ystart, yend; film->GetSampleExtent(&xstart, &xend, &ystart, ¥d); int xsamp = 1; int ysamp = 1; StratifiedSampler *sampler = new StratifiedSampler( xstart, xend, ystart, yend, xsamp, ysamp, jitter, camera->shutterOpen, camera->shutterClose); RNG rng; Sample sample(sampler, NULL, NULL, NULL); int count = 0; while (sampler->GetMoreSamples(&sample, rng) && count < 10) { //sample.imageX printf("sample imageX: %g, imageY: %g\n", sample.imageX, sample.imageY); Ray ray; camera->GenerateRay(sample, &ray); print("ray.o", ray.o); print("ray.d", ray.d); printf("ray mint: %g, maxt: %g", ray.mint, ray.maxt); count++; } //CameraSample sample; //camera->GenerateRay( }
void randomSpheres(Scene* &scene, Camera* &camera, QtFilm* &film) { // Create scene scene = new Scene(new ListAggregate()); *scene << new SkyLight(vec3(0.8f, 0.8f, 1.0f)); Texture* spheresTexture = ImageLoading::LoadImage("/Users/gael/Desktop/Courses/CSE_168/models/textures/earth.jpg"); Texture* planeTexture = ImageLoading::LoadImage("/Users/gael/Desktop/Courses/CSE_168/models/textures/scale_brown.png"); // Materials Matte* spheresMaterial = new Matte(spheresTexture); Matte* planeMaterial = new Matte(planeTexture); //white->setColor(vec3(0.6f)); // Create ground plane Plane* groundShape = new Plane(); GeometricPrimitive* ground = new GeometricPrimitive(groundShape, planeMaterial); *scene << ground; // Create spheres for(int i=0; i<20; ++i) { Sphere* sphereShape = new Sphere(); GeometricPrimitive* sphere = new GeometricPrimitive(sphereShape, spheresMaterial); float rad = RangeRand(0.25f,0.5f); vec3 pos(RangeRand(-5.0f,5.0f), rad, RangeRand(-5.0f,5.0f)); sphereShape->setRadius(rad); sphereShape->setCenter(pos); *scene << sphere; } // Create lights DirectionalLight* sunlgt = new DirectionalLight(); sunlgt->setSpectrum(Spectrum(vec3(1.0f, 1.0f, 0.9f))); sunlgt->setIntensity(1.0f); sunlgt->setDirection(vec3(2.0f, -3.0f, -2.0f)); *scene << sunlgt; // Create camera PerspectiveCamera* perspectiveCamera = new PerspectiveCamera(); perspectiveCamera->lookAt(vec3(-0.75f,0.25f,5.0f), vec3(0.0f,0.5f,0.0f)); film = new QtFilm(vec2(800, 600)); perspectiveCamera->setFilm(film); perspectiveCamera->setVFov(40.0f); perspectiveCamera->setAspect(1.33f); camera = perspectiveCamera; }
void Renderer::rayTrace(Film *film, Shape& scene, PerspectiveCamera& camera, Lights& lights) { int w = film->width(), h = film->height(); IntersectResult result; for (int y = 0; y < h; y++) { float sy = 1.0f - (float)y / h; for (int x = 0; x < w; x++) { float sx = (float)x / w; Ray& ray = camera.GenerateRay(sx, sy); scene.Intersect(ray, &result); if (result.geometry) { Material* pMaterial = result.geometry->material; Color color(0, 0, 0); for (int i = 0; i < lights.size(); i++) { Vector3dF incidence = lights[i]->incidence(result.position); Color c = pMaterial->Sample(ray, result.position, result.normal, incidence); color = color + c; } //printf("c=%f,%f,%f\n", color->r(),color->g(),color->b()); film->set(x, y, min(int(color.r() * 255), 255), min(int(color.g() * 255), 255), min(int(color.b() * 255), 255)); } } } }
void mouseCallback(GLFWwindow* window, double xpos, double ypos) { UNUSED(window); if (firstMouseEvent) { lastX = xpos; lastY = ypos; firstMouseEvent = false; } // Find the position difference of the mouse. GLfloat xoffset = xpos - lastX; GLfloat yoffset = lastY - ypos; // Reversed since positive y is up. // Set the history values to the current values. lastX = xpos; lastY = ypos; // Multiply the offset by the mouse sensitivity to prevent rapidly unplanned // seizures and the like. GLfloat mouseSensitivity = 0.12f / (45.0f / camera.fov); xoffset *= mouseSensitivity; yoffset *= mouseSensitivity; camera.rotation.y += xoffset; camera.rotation.x += yoffset; // Constrain the pitch so the FPS camera does not do sick backflips. if (camera.rotation.x > glm::radians(89.0f)) camera.rotation.x = glm::radians(89.0f); if (camera.rotation.x < glm::radians(-89.0f)) camera.rotation.x = glm::radians(-89.0f); camera.update(); }
void FPSControls::applyTranslation( float dx, float dy, float dz, PerspectiveCamera& camera ) { Vector3f eye = camera.eye(); Vector3f x = camera.right(); Vector3f y = camera.up(); Vector3f z = -( camera.forward() ); // project the y axis onto the ground plane //Vector3f zp = m_worldToGroundPlane * z; //zp[ 1 ] = 0; //zp = m_groundPlaneToWorld * zp; //zp.normalize(); eye = eye + dx * x + dy * upVector() + dz * z; camera.setLookAt( eye, eye - z, y ); }
void FPSControls::applyRotation( float yaw, float pitch, PerspectiveCamera& camera ) { Matrix3f worldToCamera = camera.viewMatrix().getSubmatrix3x3(); Matrix3f cameraToWorld = camera.inverseViewMatrix().getSubmatrix3x3(); Vector3f eye = camera.eye(); Vector3f y = camera.up(); Vector3f z = -( camera.forward() ); auto x = camera.right(); // Pitch around the local x axis. Matrix3f pitchMatrix = Matrix3f::rotateX( pitch ); y = cameraToWorld * pitchMatrix * worldToCamera * y; z = cameraToWorld * pitchMatrix * worldToCamera * z; // Yaw around the world up vector. Matrix3f yawMatrix = m_groundPlaneToWorld * Matrix3f::rotateY( yaw ) * m_worldToGroundPlane; y = yawMatrix * y; z = yawMatrix * z; camera.setLookAt( eye, eye - z, y ); }
void FPSCameraController::update(PerspectiveCamera& a_camera, float a_deltaSec, bool a_focused) { glm::ivec2 newMousePos; GLEngine::input->getMousePosition(newMousePos.x, newMousePos.y); if (m_mousePos.x == -1 && m_mousePos.y == -1) // First update, dont process movement m_mousePos = newMousePos; glm::ivec2 mouseMovement = m_mousePos - newMousePos; m_mousePos = newMousePos; if (!a_focused) return; if (!GLEngine::input->isMousePressed(EMouseButton::LEFT)) mouseMovement = glm::ivec2(0); const float xLookRotation = (mouseMovement.x * m_mouseLookSensitivity); const float yLookRotation = (mouseMovement.y * m_mouseLookSensitivity); glm::vec3 direction = a_camera.getDirection(); const glm::vec3 tmp = direction; const glm::vec3 side = glm::cross(direction, UP); const glm::vec3 up = glm::cross(side, direction); const glm::quat yaw = glm::angleAxis(glm::radians(xLookRotation), up); const float xzAngle = std::atan2(direction.x, direction.z); //calculate axis to rotate vertically on const glm::vec3 yRotAxis(-glm::cos(xzAngle), 0.0f, glm::sin(xzAngle)); const glm::quat pitch = glm::angleAxis(glm::radians(yLookRotation), yRotAxis); const glm::quat orientation = glm::normalize(glm::cross(pitch, yaw)); direction = glm::rotate(orientation, direction); const float newXZ = std::atan2(direction.x, direction.z); const float xzDiff = glm::abs(xzAngle - newXZ); if (xzDiff > 2.0f && xzDiff < 4.0f) // flip protection { direction = tmp; } a_camera.lookAtDir(direction); a_camera.translateRelative(getLocalSpaceMovementVector() * m_cameraSpeed * a_deltaSec); a_camera.updateMatrices(); }
void RenderingConfig::SetMotionBlur(const bool v) { boost::unique_lock<boost::mutex> lock(cfgMutex); bool wasRunning = renderThreadsStarted; // First stop all devices if (wasRunning) StopAllRenderThreadsLockless(); film->Reset(); PerspectiveCamera *camera = scene->camera; camera->motionBlur = v; if (camera->motionBlur) { camera->mbOrig = camera->orig; camera->mbTarget = camera->target; camera->mbUp = camera->up; } camera->Update(film->GetWidth(), film->GetHeight()); // Restart all devices if (wasRunning) StartAllRenderThreadsLockless(); }
void GridSystem::getLastClickedGrid(PerspectiveCamera pc, int &reti, int &retj){ int retij[2] = { -1, -1 }; float min_dist = FLT_MAX; Vector3f ray = pc.getRay(); float d = sqrt(pow(ray.x(), 2) + pow(ray.y(), 2) + pow(ray.z(), 2)); //dist from ray to projection pt Vector3f p = pc.getCameraLocation() + ray; for (int i = 0; i < grids.size(); i++) { for (int j = 0; j < grids[0].size(); j++) { Grid* g = grids[i][j]; Vector3f pt = g->getXYZ(); Vector3f newray = pt - pc.getCameraLocation(); //ray from camera to pt float dist = sqrt(pow(newray.x(), 2) + pow(newray.y(), 2) + pow(newray.z(), 2)); //dist from camera to pt Vector3f extNewray = newray.normalized() * d; Vector3f extPt = pc.getCameraLocation() + extNewray; //extended point in objective 3d space (0, 0, 592, 592) float threshold = (exp(4-(dist/15.0f))/d)*1500.0f*offset; //exp(3) = 20. (quite efficient for dist 4-30) if (abs(extPt.x() - p.x()) < threshold \ && abs(extPt.y() - p.y()) < threshold \ && abs(extPt.z() - p.z()) < threshold){ //NO LONGER DUMMY LOL //IT WORKS if (min_dist > dist){ min_dist = dist; retij[0] = i; retij[1] = j; //g->show(); //cout << "min_dist: " << min_dist << endl; } } } } //cout << "-------------" << endl; reti = retij[0]; retj = retij[1]; }
void LineRenderer::render(RenderDevice* device, uint16_t& view) { dcfx::Context* context = device->m_context; PerspectiveCamera* camera = device->m_camera; const glm::ivec2& windowSize = device->m_windowSize; // Write vertices to buffer context->updateBuffer(m_vertexBuffer, 0, m_vertexCount * sizeof(vertex::PC), &m_vertexData[0]); context->setView(view, camera->view()); context->setProj(view, camera->proj()); context->setFramebuffer(view, dcfx::Invalid<dcfx::FramebufferHandle>()); context->setViewport(view, glm::ivec4(0, 0, windowSize.x, windowSize.y)); context->setState(DCFX_DEFAULT_STATE); context->setPrimitiveMode(DCFX_STATE_PT_LINES); context->setIndexBuffer(dcfx::Invalid<dcfx::BufferHandle>(), 0, 0); context->setVertexBuffer(m_vertexBuffer, 0, m_vertexCount); context->setProgram(m_lineRenderProgram); context->submit(view, 1); m_vertexCount = 0; view++; }
void rayTraceReflection(Object& scene, PerspectiveCamera& camera, int maxReflect, DirectionalLight light) { for(int y=0;y<Y_RES;y++) { float sy = (float)y/Y_RES; for(int x=0;x<X_RES;x++) { float sx = (float)x/X_RES; Ray3 ray = camera.generateRay(sx,sy); Color color = rayTraceRecursive(scene, ray, maxReflect, light); fbuffer[y][x][0]=color.getR()*255; fbuffer[y][x][1]=color.getG()*255; fbuffer[y][x][2]=color.getB()*255; } } }
void Renderer::renderDepth(Film *film, Shape& scene, PerspectiveCamera& camera, float maxDepth) { int w = film->width(), h = film->height(); IntersectResult result; for (int y = 0; y < h; y++) { float sy = 1.0f - (float)y / h; for (int x = 0; x < w; x++) { float sx = (float)x / w; Ray& ray = camera.GenerateRay(sx, sy); scene.Intersect(ray, &result); if (result.geometry) { int depth = int(255.0f - min((result.distance / maxDepth) * 255.0f, 255.0f)); film->set(x, y, depth, depth, depth); } } } }
void Renderer::renderNormal(Film *film, Shape& scene, PerspectiveCamera& camera, float maxDepth) { int w = film->width(), h = film->height(); IntersectResult result; for (int y = 0; y < h; y++) { float sy = 1.0f - (float)y / h; for (int x = 0; x < w; x++) { float sx = (float)x / w; Ray&& ray = camera.GenerateRay(sx, sy); scene.Intersect(ray, &result); if (result.geometry) { Normal3dF& n = result.normal; film->set(x, y, (n.x + 1.0f) * 128.0f, (n.y + 1.0f) * 128.0f, (n.z + 1.0f) * 128.0f); } } } };
void renderNormal(Sphere scene, PerspectiveCamera camera) { for(int y=0;y<Y_RES;y++) { float sy = (float)y/Y_RES; for(int x=0;x<X_RES;x++) { float sx = (float)x/X_RES; Ray3 ray = camera.generateRay(sx,sy); IntersectResult result = scene.intersect(ray); if(result.getGeometry()) { fbuffer[y][x][0]=(result.getNormal().getx()+1)*128; fbuffer[y][x][1]=(result.getNormal().gety()+1)*128; fbuffer[y][x][2]=(result.getNormal().getz()+1)*128; } } } }
Vector3D PointLight::LightIntensity(Scene& scene, IntersectResult intersect, const PerspectiveCamera& cam) { Vector3D delta = mPosition - intersect.mPosition; float rr = Length2(delta); float r = sqrt(rr); float r1 = 1.0 / r; Vector3D inverseDire = Normalize(delta); if (mIsShadow) { Ray shadowRay(intersect.mPosition, inverseDire); IntersectResult shadowResult = scene.Intersect(shadowRay); if (shadowResult.mIsHit && shadowResult.mDistance <= r) { return -(this->mColor * this->mShadowReducingFactor); } } float diffuseAttenuation = 1.0 / (mAttenuation.x + mAttenuation.y * r + mAttenuation.z * rr); float specularAttenuation = 1.0 / (mAttenuation.x + mAttenuation.y * r + mAttenuation.z * rr); Vector3D colorRes; // Diffuse Material float NdotL = Dot(intersect.mNormal, inverseDire); // std::cout << NdotL << std::endl; if (NdotL > 0) { colorRes = colorRes + intersect.mPrimitive->GetDiffuseColor() * this->mColor * NdotL * diffuseAttenuation; } // Specular Material Vector3D Vo = cam.GetPosition() - intersect.mPosition; Vector3D V = Normalize(Vo); Vector3D h = Normalize(V + inverseDire); float NdotH = Dot(intersect.mNormal, h); if (NdotH > 0) { colorRes = colorRes + intersect.mPrimitive->GetSpecularColor() * this->mColor * powf(NdotH, intersect.mPrimitive->GetShininess()) * specularAttenuation; } return colorRes; }
void rayTrace2( Sphere scene, PerspectiveCamera camera) { for(int y=0;y<Y_RES;y++) { float sy = (float)y/Y_RES; for(int x=0;x<X_RES;x++) { float sx = (float)x/X_RES; Ray3 ray = camera.generateRay(sx,sy); IntersectResult result = scene.intersect(ray); if(result.getGeometry()) { cout<<"x:"<<y<<" y:"<<x<<endl; Color color = PhongMaterial(Color::red,Color::white,16,1).sample(ray, result.getPosition(), result.getNormal()); fbuffer[y][x][0]=color.getR()*255; fbuffer[y][x][1]=color.getG()*255; fbuffer[y][x][2]=color.getB()*255; } } } }
void Renderer::rayTraceReflection(Film *film, Shape* scene, PerspectiveCamera& camera, Lights& lights, int maxReflect, int px, int py, int pw, int ph) { int w = pw, h = ph, img_width = film->width(), img_height = film->height(); if (w == 0) w = img_width; if (h == 0) h = img_height; for (int y = py, yMax = py + h; y < yMax; y++) { float sy = 1.0f - (float)y / img_height; for (int x = px, xMax = px + w; x < xMax; x++) { float sx = (float)x / img_width; //printf("sx,sy=%f,%f\n",sx,sy); Ray& ray = camera.GenerateRay(sx, sy); Color color = rayTraceRecursive(&(*scene), ray, lights, maxReflect); int r = min(int(color.r() * 255), 255), g = min(int(color.g() * 255), 255), b = min(int(color.b() * 255), 255); //printf("[rgb] %d %d = %d %d %d\n", x, y, r, g, b); film->set(x, y, r, g, b); } } }
void rayTrace( Object& scene, PerspectiveCamera camera) { for(int y=0;y<Y_RES;y++) { float sy = (float)y/Y_RES; for(int x=0;x<X_RES;x++) { float sx = (float)x/X_RES; Ray3 ray = camera.generateRay(sx,sy); IntersectResult result = scene.intersect(ray); if(result.getGeometry()) { //Color color = scene.material->sample(ray, result.getPosition(), result.getNormal()); Color color = result.getGeometry()->material->sample(ray,result.getPosition(),result.getNormal()); //CheckMaterial(0.1,1).sample(ray, result.getPosition(), result.getNormal()); fbuffer[y][x][0]=color.getR()*255; fbuffer[y][x][1]=color.getG()*255; fbuffer[y][x][2]=color.getB()*255; } } } }
void renderDepth(Sphere scene, PerspectiveCamera camera, int maxDepth) { for(int y=0;y<Y_RES;y++) { float sy = (float)y/Y_RES; for(int x=0;x<X_RES;x++) { float sx = (float)x/X_RES; Ray3 ray = camera.generateRay(sx,sy); IntersectResult result = scene.intersect(ray); if(result.getGeometry()) { int depth = 255 - Min((result.getDistance()/maxDepth)*255,255); //cout<< "x: " << x << " y: " << y << " depth: "<<depth<<" dis: "<<result.getDistance()<<endl; fbuffer[y][x][0]=depth; fbuffer[y][x][1]=depth; fbuffer[y][x][2]=depth; } } } }
void GridSystem::forceGroundedView(PerspectiveCamera &pc) { float lookAt_distance = offset/2; float old_distance = pc.GetDistance(); //need? Vector3f _p = pc.getCameraLocation(); Vector3f p = _p - Vector3f(0, _p.y(), 0); //xz only Vector3f _vec = pc.GetCenter() - p; Vector3f vec = _vec - Vector3f(0, _vec.y(), 0); Vector3f lookAt = p + ((offset*2) * vec.normalized()); //from camera to lookAt direction (xz only) Vector3f p_ground = Vector3f(p.x(), getYLevel(p.x(), p.z()) + 0.5f, p.z()); Vector3f lookAt_ground = Vector3f(lookAt.x(), getYLevel(lookAt.x(), lookAt.z()) + 0.5f, lookAt.z()); Vector3f nvec = (lookAt_ground - p_ground); //new camera location to new camera center Vector3f lookAt_final = p_ground + (lookAt_distance * nvec.normalized()); //force distance to be at ground pc.SetCenter(lookAt_final); //apply new camera center //pc.SetCenter(lookAt_ground); //apply new camera center /*if (pc.GetCenter().y() < lookAt_ground.y() - 0.2){ pc.SetCenter(lookAt_ground - Vector3f(0, 0.2, 0)); //apply new camera center } else if (pc.GetCenter().y() > lookAt_ground.y() + 0.2) { pc.SetCenter(lookAt_ground + Vector3f(0, 0.2, 0)); }*/ //float lookAt_distance = sqrt(pow(nvec.x(), 2) + pow(nvec.y(), 2) + pow(nvec.z(), 2)); pc.SetDistance(lookAt_distance); Vector3f rotaxis = Vector3f::cross(nvec, Vector3f::UP); float angle_cur = atan((lookAt.y() - p_ground.y())/old_distance); float angle_new = atan((lookAt_ground.y() - p_ground.y())/lookAt_distance); float angle = angle_new - angle_cur; pc.SetViewRotation(RotationMatrixOnAxis(angle, rotaxis.x(), rotaxis.y(), rotaxis.z())); ////set view to correct Z axis //pc.SetCenter(lookAt_ground); //apply new camera center //Vector3f nvec = (lookAt_ground - p_ground); //new camera location to new camera center (alrd applied) ////float lookAt_distance = sqrt(pow(nvec.x(), 2) + pow(nvec.y(), 2) + pow(nvec.z(), 2)); //float lookAt_distance = lookAtDistance; //pc.SetDistance(lookAt_distance); cout << "p:" << p_ground.x() << " " << p_ground.y() << " " << p_ground.z() << endl; cout << "lookAt:" << lookAt_ground.x() << " " << lookAt_ground.y() << " " << lookAt_ground.z() << endl; //cout << "test:" << test.x() << " " << test.y() << " " << test.z() << endl; //cout << p.x() << " " << p.z() << " " << getYLevel(0.758, 0.875) << endl; }