void ScreenMVCullVisitor::apply(LightSource& node) { // push the node's state. StateSet* node_state = node.getStateSet(); if(node_state) pushStateSet(node_state); StateAttribute* light = node.getLight(); if(light) { if(node.getReferenceFrame() == osg::LightSource::RELATIVE_RF) { RefMatrix& matrix = *getModelViewMatrix(); addPositionedAttribute(&matrix,light); } else { // relative to absolute. addPositionedAttribute(0,light); } } handle_cull_callbacks_and_traverse(node); // pop the node's state off the geostate stack. if(node_state) popStateSet(); }
//Outputs the color of the object as enlightened by at the point where `ray` hits it. rt::color Object::render_direct(const Ray & ray, Scene & scene, const LightSource & light_source) { rt::color basic = compose(light_source.get_color(), color); Impact imp = get_impact(ray); Ray to_light(imp.point, light_source.get_origin()); double scalar = -(ray.get_direction() | imp.normale); if (((light_source.get_origin()-imp.point) | imp.normale) <= 0) { return rt::color::BLACK; } std::list<Object *> others; Object* interceptor = scene.get_interceptor(to_light, &others); // In case there has been mixups due to rounding errors and the object catches // its own ray back to the light when it shouldn't (which is NOT always the case) // detect it if (interceptor) { if (interceptor != this && interceptor->intersects(ray) < (imp.point - light_source.get_origin()).norm()) return rt::color::BLACK; if (intersects(to_light) >= OWNRAY_EPSILON) return rt::color::BLACK; if (others.size() > 1) return rt::color::BLACK; } return rt::color( static_cast<unsigned char>(scalar*basic.get_red()), static_cast<unsigned char>(scalar*basic.get_green()), static_cast<unsigned char>(scalar*basic.get_blue()) ); }
LightSource::LightSource(LightSource const& original) : Thing(original), impl(new Impl()) { impl->direction = original.get_light_direction(); impl->level = original.get_light_level(); impl->color = original.get_light_color(); impl->max_strength = original.get_max_light_strength(); impl->lit = original.is_lit(); }
virtual void apply( LightSource &node ) { if( node.getStateSet() ) { apply( *node.getStateSet() ); } ++_numInstancedLightSources; _lightSourceSet.insert( &node ); traverse( node ); }
void init() { camera.position[2] = 15; libpng_version(); light0.slot = GL_LIGHT0; light0.setDiffuse(1.0, 1.0, 1.0, 1.0); light0.setPosition(0.0, 0.0, 1.0, 0.0); light0.load(); light0.enable(); glewInit(); loadObj((char*) "models/350z.obj", &mesh); VBOfromMesh(vbo, mesh); vbo.generate(); int w, h; test_texture = texture_bank.findOrReg((char*) "textures/350z/vinyls.png"); //test_texture = PNG_load((const char*) "textures/vinyls.png", &w, &h); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, test_texture); programID = loadShaders("shaders/vertex.glsl", "shaders/fragment.glsl"); glUseProgram(programID); uTex = glGetUniformLocation(programID, "texDiff"); glUniform1i(uTex, 0); uProjection = glGetUniformLocation(programID, "projection"); uView = glGetUniformLocation(programID, "view"); uModel = glGetUniformLocation(programID, "model"); uLightPos = glGetUniformLocation(programID, "lightPos"); uLightDiff = glGetUniformLocation(programID, "lightDiff"); uLightSpec = glGetUniformLocation(programID, "lightSpec"); uCameraPosition = glGetUniformLocation(programID, "cameraPosition"); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glEnable(GL_ALPHA_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_DEPTH_TEST); }
void Canvas::setup(int bots, int lights, QVector<QPointF> botLoc, QVector<QPointF> lightLoc, int **matrix) { this->addLine(0,0,400,400); if (bots == 0) { bots = 1; qDebug() << "ERROR: Invalid number of robots. Defaulting to 1."; } if (lights == 0) { lights = 1; qDebug() << "ERROR: Invalid number of lights. Defaulting to 1."; } if (botLoc.size() < bots) { botLoc.clear(); botLoc = defaultBotLoc(bots); qDebug() << "ERROR: Not enough robot locations. Using the default locations."; } if (lightLoc.size() < bots) { lightLoc.clear(); lightLoc = defaultLightLoc(lights); qDebug() << "ERROR: Not enough light locations. Using the default locations."; } m_robotManager->setKMatrix(matrix); Robot* robot; for(int i = 0; i < bots; i++) { robot = new Robot(); robot->setTransformOriginPoint(ROBOT_HEIGHT, ROBOT_HEIGHT); robot->setPos(botLoc[i]); createRobot(robot); } LightSource *light; for (int i = 0; i < lights; i++) { light = new LightSource(); light->setPos(lightLoc[i]); // TODO: take intensity from a file light->setIntensity(100); createLight(light); } }
CAMLprim value lightsource_process(value record_lightsource, value list_polygon_objects, value polygon_view) { CAMLparam3(record_lightsource, list_polygon_objects, polygon_view); CAMLlocal5(polygon_prev_head, list_polygon_head, vector_prev_head, list_vector_head, tmp_polygon); CAMLlocal1(tmp_vector); LightSource l = LightSource(Vector_val(Field(record_lightsource, 0)), Double_val(Field(record_lightsource, 1)), Double_val(Field(record_lightsource, 2))); std::vector<Polygon> tmp_polygon_list = std::vector<Polygon>(); polygon_list_to_std_vector(list_polygon_objects, &tmp_polygon_list); std::vector<Vector> tmp_vector_list = std::vector<Vector>(); vector_list_to_std_vector(Field(polygon_view, 0), &tmp_vector_list); Polygon polygon = Polygon(tmp_vector_list); // auto start = std::chrono::steady_clock::now(); std::vector<Polygon> list_polygon = l.process(tmp_polygon_list); // auto duration = std::chrono::duration_cast<std::chrono::milliseconds>( // std::chrono::steady_clock::now() - start); // printf("--> %lld\n", duration.count()); polygon_prev_head = Val_unit; for (Polygon p : list_polygon) { vector_prev_head = Val_unit; for (Vector v : p.get_vertices()) { tmp_vector = caml_alloc_small(2, Double_array_tag); Double_field(tmp_vector, 0) = v.x; Double_field(tmp_vector, 1) = v.y; list_vector_head = caml_alloc_small(2, 0); Field(list_vector_head, 0) = tmp_vector; Field(list_vector_head, 1) = vector_prev_head; vector_prev_head = list_vector_head; } tmp_polygon = caml_alloc_small(1, 0); Field(tmp_polygon, 0) = list_vector_head; list_polygon_head = caml_alloc_small(2, 0); Field(list_polygon_head, 0) = tmp_polygon; Field(list_polygon_head, 1) = polygon_prev_head; polygon_prev_head = list_polygon_head; } CAMLreturn(list_polygon_head); }
void OpenGLSceneRenderer::showLight(const LightSource& l, const SkyDragonEngineOptions& engineOptions) { float p[4]; float a[4]; float d[4]; float s[4]; for (int i = 0; i < 4; i++) { p[i] = l.GetPosition()[i]; a[i] = l.GetAmbient()[i]; d[i] = l.GetDiffuse()[i]; s[i] = l.GetSpecular()[i]; } glLightfv(_glLightSources[_curLight], GL_POSITION, p); glLightfv(_glLightSources[_curLight], GL_AMBIENT, a); glLightfv(_glLightSources[_curLight], GL_DIFFUSE, d); glLightfv(_glLightSources[_curLight], GL_SPECULAR, s); _curLight++; }
LightSource* ChessUtils::createLightSource(StateSet* stateSet, int lightNumber, Vec4 position, Vec3 direction, float spotCutoff, float spotExponent, float constanteAttenuation, Vec4 ambientLight, Vec4 diffuseLight, Vec4 specularLight) { Light* light = new Light(); light->setLightNum(lightNumber); light->setPosition(position); light->setDirection(direction); light->setAmbient(ambientLight); light->setDiffuse(diffuseLight); light->setSpecular(specularLight); light->setConstantAttenuation(constanteAttenuation); light->setSpotCutoff(spotCutoff); light->setSpotExponent(spotExponent); LightSource* lightS = new LightSource(); lightS->setLight(light); lightS->setLocalStateSetModes(osg::StateAttribute::ON); lightS->setStateSetModes(*stateSet, osg::StateAttribute::ON); return lightS; }
bool SVGFESpecularLightingElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) { FESpecularLighting* specularLighting = static_cast<FESpecularLighting*>(effect); if (attrName == SVGNames::lighting_colorAttr) { RenderObject* renderer = this->renderer(); ASSERT(renderer); ASSERT(renderer->style()); return specularLighting->setLightingColor(renderer->style()->svgStyle().lightingColor()); } if (attrName == SVGNames::surfaceScaleAttr) return specularLighting->setSurfaceScale(m_surfaceScale->currentValue()->value()); if (attrName == SVGNames::specularConstantAttr) return specularLighting->setSpecularConstant(m_specularConstant->currentValue()->value()); if (attrName == SVGNames::specularExponentAttr) return specularLighting->setSpecularExponent(m_specularExponent->currentValue()->value()); LightSource* lightSource = const_cast<LightSource*>(specularLighting->lightSource()); SVGFELightElement* lightElement = SVGFELightElement::findLightElement(*this); ASSERT(lightSource); ASSERT(lightElement); ASSERT(effect->filter()); if (attrName == SVGNames::azimuthAttr) return lightSource->setAzimuth(lightElement->azimuth()->currentValue()->value()); if (attrName == SVGNames::elevationAttr) return lightSource->setElevation(lightElement->elevation()->currentValue()->value()); if (attrName == SVGNames::xAttr || attrName == SVGNames::yAttr || attrName == SVGNames::zAttr) return lightSource->setPosition(effect->filter()->resolve3dPoint(lightElement->position())); if (attrName == SVGNames::pointsAtXAttr || attrName == SVGNames::pointsAtYAttr || attrName == SVGNames::pointsAtZAttr) return lightSource->setPointsAt(effect->filter()->resolve3dPoint(lightElement->pointsAt())); if (attrName == SVGNames::specularExponentAttr) return lightSource->setSpecularExponent(lightElement->specularExponent()->currentValue()->value()); if (attrName == SVGNames::limitingConeAngleAttr) return lightSource->setLimitingConeAngle(lightElement->limitingConeAngle()->currentValue()->value()); ASSERT_NOT_REACHED(); return false; }
void Config::load(SceneRenderer * sceneRenderer, Manager * manager) { Json::Value root; // will contains the root value after parsing. Json::Reader reader; std::ifstream file; file.open(fileName); bool parsingSuccessful = reader.parse(file, root, false); file.close(); if(!parsingSuccessful) { // report to the user the failure and their locations in the document. System::Console::WriteLine("Failed to parse configuration\n"); System::Console::WriteLine(gcnew System::String(reader.getFormatedErrorMessages().c_str())); throw std::runtime_error("Failed to parse configuration file: "+fileName); } Json::Value sceneJSON = root.get("scene", NULL); Scene * scene = sceneRenderer->getScene(); Json::Value bgColorJSON = sceneJSON.get("backgroundColor", NULL); if(bgColorJSON != NULL) { scene->setBackgroundColor(jsonToColor(bgColorJSON)); } Json::Value lightsJSON = sceneJSON.get("lights", NULL); if(lightsJSON != NULL) { Json::Value::Members lightsName = lightsJSON.getMemberNames(); for(std::vector<std::string>::iterator it = lightsName.begin(); it != lightsName.end(); it++) { std::string lightName = *it; Json::Value lightJSON = lightsJSON[lightName]; RGBColor lightColor = jsonToColor(lightJSON["color"]); LightSource * light; std::string lightTypeStr = lightJSON["type"].asString(); if(lightTypeStr == "AmbientLightSource") { light = new AmbientLightSource(lightColor); } else if(lightTypeStr == "PointLightSource") { light = new PointLightSource(jsonToP3(lightJSON["position"]), lightColor); Json::Value specularCoefJSON = lightJSON.get("specularCoef", NULL); PointLightSource * pLight = static_cast<PointLightSource*>(light); if(specularCoefJSON != NULL) { pLight->setSpecularCoef(specularCoefJSON.asDouble()); } Json::Value specularExpJSON = lightJSON.get("specularExponent", NULL); if(specularExpJSON != NULL) { pLight->setSpecularExponent(specularExpJSON.asDouble()); } } Json::Value diffuseCoefJSON = lightJSON.get("diffuseCoef", NULL); if(diffuseCoefJSON != NULL) { light->setDiffuseCoef(diffuseCoefJSON.asDouble()); } //scene->addLightSource(light); manager->getLightSources()->add(lightName, light, lightTypeStr); } } Json::Value objectsJSON = sceneJSON.get("objects", NULL); if(objectsJSON != NULL) { Json::Value::Members objectsName = objectsJSON.getMemberNames(); for(std::vector<std::string>::iterator it = objectsName.begin(); it != objectsName.end(); it++) { std::string objectName = *it; Json::Value object3DJSON = objectsJSON[objectName]; Object3D * object3D; std::string oject3DTypeStr = object3DJSON["type"].asString(); if(oject3DTypeStr == "Sphere") { object3D = new Sphere(jsonToP3(object3DJSON["center"]), object3DJSON["radius"].asDouble()); } else if(oject3DTypeStr == "Plane") { if(object3DJSON.get("u", NULL) != NULL) { object3D = new Plane(jsonToP3(object3DJSON["p"]), jsonToP3(object3DJSON["u"]), jsonToP3(object3DJSON["v"])); } else { object3D = new Plane(jsonToP3(object3DJSON["p"]), jsonToP3(object3DJSON["normal"])); } } else if(oject3DTypeStr == "Triangle") { object3D = new Triangle(jsonToP3(object3DJSON["A"]), jsonToP3(object3DJSON["B"]), jsonToP3(object3DJSON["C"])); } //scene->addObject3D(object3D); manager->getObjects3D()->add(objectName, object3D, oject3DTypeStr); } } Json::Value polyhedraJSON = sceneJSON.get("polyhedra", NULL); if(polyhedraJSON != NULL) { Json::Value::Members polyhedraName = polyhedraJSON.getMemberNames(); for(std::vector<std::string>::iterator it = polyhedraName.begin(); it != polyhedraName.end(); it++) { std::string objectName = *it; Json::Value polyhedronJSON = polyhedraJSON[objectName]; Polyhedron * polyhedron; std::string polyhedronTypeStr = polyhedronJSON["type"].asString(); if(polyhedronTypeStr == "Parallelepiped") { polyhedron = new Parallelepiped(jsonToP3(polyhedronJSON["A"]), jsonToP3(polyhedronJSON["B"]), jsonToP3(polyhedronJSON["C"]), jsonToP3(polyhedronJSON["D"])); } else if(polyhedronTypeStr == "Maya") { std::vector<Triangle*> triangles; std::string filename = polyhedronJSON["FileName"].asString(); Json::Value pJSON = polyhedronJSON.get("p", NULL); P3 centerObj(0,0,0); if(pJSON != NULL) centerObj = jsonToP3(polyhedronJSON["p"]); Json::Value scaleJSON = polyhedronJSON.get("scale", NULL); double scale = 1.0; if(scaleJSON != NULL) scale = scaleJSON.asDouble(); parseObjFile(filename, &triangles, centerObj, scale); polyhedron = new Polyhedron(triangles); } else continue; /*std::vector<Triangle*> triangles = polyhedron->getTriangles(); for(std::vector<Triangle*>::iterator it = triangles.begin(); it != triangles.end(); it++) { scene->addObject3D(*it); }*/ manager->getPolyhedra()->add(objectName, polyhedron, polyhedronTypeStr); } } Json::Value texturesJSON = root.get("textures", NULL); if(texturesJSON != NULL) { Json::Value::Members texturesName = texturesJSON.getMemberNames(); for(std::vector<std::string>::iterator it = texturesName.begin(); it != texturesName.end(); it++) { std::string textureName = *it; Json::Value textureJSON = texturesJSON[textureName]; Texture * texture = new Texture(textureJSON["FileName"].asString()); manager->getTextures()->add(textureName, texture); } } Json::Value sceneRendererJSON = root.get("sceneRenderer", NULL); if(sceneRendererJSON == NULL) throw std::runtime_error("sceneRenderer not defined in "+fileName); Json::Value cameraJSON = sceneRendererJSON["camera"]; Camera * camera = new Camera(jsonToP3(cameraJSON["position"]), jsonToP3(cameraJSON["direction"]), cameraJSON.get("rotation", 0).asDouble()); sceneRenderer->setCamera(camera); sceneRenderer->setCameraScreenDist(sceneRendererJSON.get("cameraScreenDist", 200).asDouble()); manager->getCameras()->add("camera1", camera); std::string methodType = sceneRendererJSON["method"].get("type", "OrthographicProjection").asString(); RenderingMethod * renderingMethod = NULL; if(methodType == "OrthographicProjection") { renderingMethod = new OrthographicProjection(); } else if(methodType == "RayCasting") { renderingMethod = new RayCasting(); } else if(methodType == "RayTracing") { renderingMethod = new RayTracing(); } if(renderingMethod != NULL) sceneRenderer->setRenderingMethod(renderingMethod); Json::Value modelsJSON = sceneRendererJSON.get("models", NULL); if(modelsJSON != NULL) { Json::Value::Members modelsName = modelsJSON.getMemberNames(); for(std::vector<std::string>::iterator it = modelsName.begin(); it != modelsName.end(); it++) { std::string modelName = *it; Json::Value modelJSON = modelsJSON[modelName]; Json::Value modelTypeJSON = modelJSON.get("type", NULL); if(modelTypeJSON != NULL) { std::string modelTypeStr = modelTypeJSON.asString(); Model * model; if(modelTypeStr == "SphereModel") { model = new SphereModel(); } else if( modelTypeStr == "PlaneModel" || modelTypeStr == "TriangleModel") { model = new PlaneModel(); } else if(modelTypeStr == "PolyhedronModel" || modelTypeStr == "ParallelepipedModel" || modelTypeStr == "MayaModel") { model = new PolyhedronModel(); } Json::Value textureJSON = modelJSON.get("texture", NULL); if(textureJSON != NULL) { model->setTexture(manager->getTextures()->get(textureJSON.asString())); } Json::Value colorJSON = modelJSON.get("color", NULL); if(colorJSON != NULL) { model->setColor(jsonToColor(colorJSON)); } Json::Value bumpJSON = modelJSON.get("bump", NULL); if(bumpJSON != NULL) { model->setBump(manager->getTextures()->get(bumpJSON.asString())); } Json::Value materialJSON = modelJSON.get("material", NULL); if(materialJSON != NULL) { model->setMaterial(jsonToMaterial(materialJSON)); } Json::Value textureScaleJSON = modelJSON.get("textureScale", NULL); if(textureScaleJSON != NULL) { model->setTextureScale(textureScaleJSON.asDouble()); } manager->getModels()->add(modelName, model); Json::Value modelObjectsJSON = modelJSON.get("objects", NULL); if(modelObjectsJSON != NULL) { for(unsigned int i=0; i < modelObjectsJSON.size(); i++) { std::string objectName = modelObjectsJSON[i].asString(); Object3D * object3D = manager->getObjects3D()->get(objectName); Polyhedron * polyhedron = manager->getPolyhedra()->get(objectName); if(object3D != NULL) { sceneRenderer->getObject3DRenderer(object3D)->setModel(model); } else if(polyhedron != NULL) { std::vector<Triangle*> triangles = polyhedron->getTriangles(); for(std::vector<Triangle*>::iterator it = triangles.begin(); it != triangles.end(); it++) { sceneRenderer->getObject3DRenderer(*it)->setModel(model); } } else continue; } } } } } }
Node* Universe::createUniverse() { // we need the scene's state set to enable the light for the entire scene Group *scene = new Group(); lightStateSet = scene->getOrCreateStateSet(); lightStateSet->ref(); // create a light LightSource *lightSource = new LightSource(); lightSource->setLight(createLight(Vec4(0.9, 0.9, 0.9, 1.0))); // enable the light for the entire scene lightSource->setLocalStateSetModes(StateAttribute::ON); lightSource->setStateSetModes(*lightStateSet, StateAttribute::ON); lightTransform = new PositionAttitudeTransform(); lightTransform->addChild(lightSource); lightTransform->setPosition(Vec3(3, 0, 0)); // create objects try { CrfGeometry* crfGeometry = new CrfGeometry(); // Stars Material *material = new Material(); material->setEmission(Material::FRONT, Vec4(1.0, 1.0, 1.0, 1.0)); material->setAmbient(Material::FRONT, Vec4(1.0, 1.0, 1.0, 1.0)); material->setShininess(Material::FRONT, 25.0); crfGeometry->prepareMaterial(material); if(_starfield_enabled) { for (int i = 0; i < 6; i++) { starField[i] = crfGeometry->createPlane(_diameter, "./textures/stars.jpg", true); scene->addChild(starField[i]); } this->positionStarField(); } if(_spacewarp_enabled) scene->addChild(this->createSpacewarp()); // sun crfGeometry->prepareMaterial(material); sun = crfGeometry->createSphere(300, "./textures/sunmap.jpg", false); // planets Material *material2 = new Material(); material2->setEmission(Material::FRONT, Vec4(0.1, 0.1, 0.1, 1.0)); crfGeometry->prepareMaterial(material2); mercury= crfGeometry->createSphere(3.8, "./textures/mercurymap.jpg", false); venus = crfGeometry->createSphere(9.5, "./textures/venusmap.jpg", false); earth = crfGeometry->createSphere(10, "./textures/earthmap1k.jpg", false); emoon = crfGeometry->createSphere(2, "./textures/moonmap1k.jpg", false); mars = crfGeometry->createSphere(5.3, "./textures/mars_1k_color.jpg", false); jupiter = crfGeometry->createSphere(109, "./textures/jupitermap.jpg", false); saturn = crfGeometry->createSphere(91, "./textures/saturnmap.jpg", false); } catch (char *e) { std::cerr << e; } lightTransform->addChild(sun); scene->addChild(lightTransform); scene->addChild(mercury); scene->addChild(venus); earth->addChild(emoon); scene->addChild(earth); scene->addChild(mars); scene->addChild(jupiter); scene->addChild(saturn); return scene; }
void GameManager::init() { int quadrante; double direction; std::srand(std::time(0)); //Initializing Flags wireFlag = false; dirLightFlag = false; spotLightFlag = false; pointLightFlag = false; activateLights = false; shadeFlag = false; pauseFlag = false; startFlag = false; //Constructing Textures //_pauseTex = new Texture("C:\\Users\\DanielaD\\Desktop\\MicroMachines CG\\pause.jpg"); //_gameOverTex = new Texture("C:\\Users\\DanielaD\\Desktop\\MicroMachines CG\\gameover.jpg"); _pausePlane = new Plane(0, 0, 10); _pausePlane->setFileName("C:\\Users\\DanielaD\\Desktop\\MicroMachines CG\\pause.png"); _gameOverPlane = new Plane(0, 0, 10); _gameOverPlane->setFileName("C:\\Users\\DanielaD\\Desktop\\MicroMachines CG\\rip.png"); //Constructing Objects// Table * table = new Table(); table->setPosition(0, 0, 0); //table->setTexture("C:\\Users\\DanielaD\\Desktop\\MicroMachines CG\\wood.png"); _gameObjects.push_back(table); Roadside * roadside = new Roadside(); roadside->setPosition(0, 0, 0.05); _gameObjects.push_back(roadside); //criar a posicao de cada cheerio (outer road) int angle = 0; double x, y; while (angle < 360) { x = OUTTERLENGTH * cos((angle)*(PI / 180)); y = OUTTERLENGTH * sin((angle)*(PI / 180)); Cheerio *cNew = new Cheerio(x, y, 1.6); roadside->insertCheerio(cNew); _gameObjects.push_back(cNew); angle += OUTTER_ANGLE_INCREASE; } //criar a posicao de cada cheerio (inner road) angle = 0; while (angle < 360) { x = INNERLENGTH * cos((angle)*(PI / 180)); y = INNERLENGTH * sin((angle)*(PI / 180)); Cheerio *cNew = new Cheerio(x, y, 1.6); roadside->insertCheerio(cNew); _gameObjects.push_back(cNew); angle += INNER_ANGLE_INCREASE; } _car = new Car(); _car->setPosition(-12, 0, 1.7); _car->setRight(false); _car->setLeft(false); _car->setUp(false); _car->setDown(false); _gameObjects.push_back(_car); x = -14, y = -14; for (int i = 0; i < _lifes; i++) { Car* tempLife = new Car(); tempLife->setPosition(x, y, 10); tempLife->setRight(false); tempLife->setLeft(false); tempLife->setUp(false); tempLife->setDown(false); _lifeVector.push_back(tempLife); x += 1.5; } Butter * butter1 = new Butter(); butter1->setPosition(3, 12, 1.6); _gameObjects.push_back(butter1); Butter * butter2 = new Butter(); butter2->setPosition(4, 13, 1.6); _gameObjects.push_back(butter2); Butter * butter3 = new Butter(); butter3->setPosition(5, 12, 1.6); _gameObjects.push_back(butter3); Butter * butter4 = new Butter(); butter4->setPosition(-3, -10, 1.6); _gameObjects.push_back(butter4); Butter * butter5 = new Butter(); butter5->setPosition(-2, -11, 1.6); _gameObjects.push_back(butter5); for (int i = 0; i < NORANGES; i++) { Orange * orange = new Orange(); quadrante = rand() % NQUADRANTES; direction = generateNumber(365, 1); orange->setId(i); orange->setPosition(generatePosition(quadrante, 0), generatePosition(quadrante, 1), 2.5); orange->setCurrentSpeed(generateNumber(SPEEDHIGHERINI, SPEEDLOWERINI)); orange->setDirection(cos(direction*(PI / 180)), sin(direction*(PI / 180)), 0); orange->setLifeState(true); _gameObjects.push_back(orange); _oranges.push_back(orange); } //Constructing Camera _2dCamera = new OrthogonalCamera(); _2dCamera->setEye(0, 0, 15); _2dCamera->setCenter(0, 0, 1); _2dCamera->setUp(0, 1, 0); _2dCamera->setLowerLimits(-15, -15, -15); _2dCamera->setUpperLimits(15, 15, 15); _activeCamera = _2dCamera; _guiCamera = new OrthogonalCamera(); _guiCamera->setEye(0, 0, 20); _guiCamera->setCenter(0, 0, 1); _guiCamera->setUp(0, 1, 0); _guiCamera->setLowerLimits(-15, -15, -15); _guiCamera->setUpperLimits(15, 15, 15); _fieldCamera = new PerspectiveCamera(); _fieldCamera->setEye(-20, -20, 20); _fieldCamera->setCenter(0, 0, 2); _fieldCamera->setUp(20, 20, 19); _fieldCamera->update(90, 1, 0.01, 150); _carCamera = new PerspectiveCamera(); _carCamera->setEye(_car->getPosition()->getX() - (CAR_CAMERA_DISTANCE * (cos(_car->getCurrentAngle() * (PI / 180)))), _car->getPosition()->getY() - (CAR_CAMERA_DISTANCE * (sin(_car->getCurrentAngle() * (PI / 180)))), CAR_CAMERA_DISTANCE); _carCamera->setCenter(_car->getPosition()->getX(), _car->getPosition()->getY(), _car->getPosition()->getZ()); //_carCamera->setUp(_car->getSpeed()->getX(), _car->getSpeed()->getY(), _car->getSpeed()->getZ()); _carCamera->setUp(0, 0, 1); _carCamera->update(60, 1, 0.01, 150); //Constructing light sources Vela* vela1 = new Vela(); vela1->setPosition(-6, 6, 1.6); _gameObjects.push_back(vela1); Vela* vela2 = new Vela(); vela2->setPosition(6, 6, 1.6); _gameObjects.push_back(vela2); Vela* vela3 = new Vela(); vela3->setPosition(0, -6, 1.6); _gameObjects.push_back(vela3); Vela* vela4 = new Vela(); vela4->setPosition(-10, -10, 1.6); _gameObjects.push_back(vela4); Vela* vela5 = new Vela(); vela5->setPosition(10, -10, 1.6); _gameObjects.push_back(vela5); Vela* vela6 = new Vela(); vela6->setPosition(0, 14, 1.6); _gameObjects.push_back(vela6); LightSource* daylight = new LightSource(0); daylight->setPosition(0, 0, 10, 0); daylight->setAmbient(0.5, 0.5, 0.5, 1); daylight->setDiffuse(1, 1, 1, 1); daylight->setSpecular(1, 1, 1, 1); _lightSources.push_back(daylight); LightSource* candle1 = new LightSource(1); candle1->setPosition(-6, 6, 1, 1); candle1->setAmbient(0.7, 0.7, 0.7, 1); candle1->setDiffuse(1, 1, 1, 1); candle1->setSpecular(1, 1, 1, 1); candle1->setAttenuation(1, 0, 0.1); _lightSources.push_back(candle1); LightSource* candle2 = new LightSource(2); candle2->setPosition(6, 6, 1, 1); candle2->setAmbient(0.7, 0.7, 0.7, 1); candle2->setDiffuse(1, 1, 1, 1); candle2->setSpecular(1, 1, 1, 1); candle2->setAttenuation(1, 0, 0.1); _lightSources.push_back(candle2); LightSource* candle3 = new LightSource(3); candle3->setPosition(0, -6, 1, 1); candle3->setAmbient(0.7, 0.7, 0.7, 1); candle3->setDiffuse(1, 1, 1, 1); candle3->setSpecular(1, 1, 1, 1); candle3->setAttenuation(1, 0, 0.1); _lightSources.push_back(candle3); LightSource* candle4 = new LightSource(4); candle4->setPosition(-10, -10, 1, 1); candle4->setAmbient(0.7, 0.7, 0.7, 1); candle4->setDiffuse(1, 1, 1, 1); candle4->setSpecular(1, 1, 1, 1); candle4->setAttenuation(1, 0, 0.1); _lightSources.push_back(candle4); LightSource* candle5 = new LightSource(5); candle5->setPosition(10, -10, 1, 1); candle5->setAmbient(0.7, 0.7, 0.7, 1); candle5->setDiffuse(1, 1, 1, 1); candle5->setSpecular(1, 1, 1, 1); candle5->setAttenuation(1, 0, 0.1); _lightSources.push_back(candle5); LightSource* candle6 = new LightSource(6); candle6->setPosition(0, 15, 1, 1); candle6->setAmbient(0.7, 0.7, 0.7, 1); candle6->setDiffuse(1, 1, 1, 1); candle6->setSpecular(1, 1, 1, 1); candle6->setAttenuation(1.0, 0, 0.1); _lightSources.push_back(candle6); LightSource* spotlight = new LightSource(7); spotlight->setAmbient(0.8, 0.8, 0.8, 1); spotlight->setDiffuse(1, 1, 1, 1); spotlight->setSpecular(1, 1, 1, 1); spotlight->setExponent(new GLfloat(5)); spotlight->setCutOff(new GLfloat(40)); spotlight->setAttenuation(0, 0.6, 0.3); _lightSources.push_back(spotlight); initIsDone = true; }
void InstantRadiosity::castIndirect(RayTracer *rt, MeshWithColors *scene, const LightSource& ls, int num) { // If the caller requests a different number of lights than before, reallocate everything. // (This is OpenGL resource management stuff, don't touch unless you specifically need to) if (m_indirectLights.size() != num) { printf("Deleting %i indirect light sources.\n", num); for (auto iter = m_indirectLights.begin(); iter != m_indirectLights.end(); iter++) iter->freeShadowMap(); m_indirectLights.resize(num); for (auto iter = m_indirectLights.begin(); iter != m_indirectLights.end(); iter++) iter->setEnabled(false); } // Request #num exiting rays from the light. std::vector<Vec3f> origs, dirs, E_times_pdf; ls.sampleEmittedRays(num, origs, dirs, E_times_pdf); // At this point m_indirectLights holds #num lights that are off. // Loop through the rays and fill in the corresponding lights in m_indirectLights // based on what happens to the ray. for (int i = 0; i < num; i++) { // Intersect against the scene Hit h = rt->rayCast(origs[i], dirs[i]); const RTTriangle* tri = h.triangle; if ( tri != 0 ) { // YOUR CODE HERE // Ray hit the scene, now position the light m_indirectLights[i] correctly, // color it based on the texture or diffuse color, etc. (see the LightSource declaration for the list // of things that a light source needs to have) // A lot of this code is like in the Assignment 2's corresponding routine. const RTToMesh* map = (const RTToMesh*)tri->m_userPointer; const Vec3i& indices = scene->indices( map->submesh )[ map->tri_idx ]; // Fetch the barycentrics Vec3f barycentrics = tri->getBarycentrics(h.intersection); // Check for backfaces => don't accumulate if we hit a surface from below! const Vec3f tnormal = tri->getNormal(h.intersection, barycentrics); // Divide incident irradiance by PI so that we can turn it into outgoing // radiosity by multiplying by the reflectance factor below. //Ei *= (1.0f / FW_PI); Vec3f Ei; // check for texture const MeshBase::Material& mat = scene->material(map->submesh); if ( mat.textures[MeshBase::TextureType_Diffuse].exists() ) { // Yes, texture; fetch diffuse albedo from there. // First interpolate UV coordinates from the vertices using barycentrics // Then turn those into pixel coordinates within the texture // Finally fetch the color using Image::getVec4f() (point sampling is fine). // Use the result as the diffuse reflectance instead of mat.diffuse. const Texture& tex = mat.textures[MeshBase::TextureType_Diffuse]; const Image& teximg = *tex.getImage(); Vec2f texCoord = barycentrics[0] * scene->vertex(indices[0]).t + barycentrics[1] * scene->vertex(indices[1]).t + barycentrics[2] * scene->vertex(indices[2]).t; Vec2i texCoordi = Vec2i( (texCoord.x - floor(texCoord.x))*teximg.getSize().x, (texCoord.y - floor(texCoord.y))*teximg.getSize().y ); Ei = teximg.getVec4f(texCoordi).getXYZ(); } else { Ei = mat.diffuse.getXYZ(); } Vec3f emission = E_times_pdf[i] * Ei; // Set the indirect light parameters m_indirectLights[i].setPosition(h.intersection); Mat3f orientation = LightSource::formBasis(-tnormal); m_indirectLights[i].setOrientation(orientation); m_indirectLights[i].setEmission(emission); m_indirectLights[i].setFOV(m_indirectFOV); // Replace this with true once your light is ready to be used in rendering m_indirectLights[i].setEnabled(true); } else { // If we missed the scene, disable the light so it's skipped in all rendering operations. m_indirectLights[i].setEnabled(false); } } }
bool SVGFEDiffuseLightingElement::setFilterEffectAttribute(FilterEffect* effect, const QualifiedName& attrName) { FEDiffuseLighting* diffuseLighting = static_cast<FEDiffuseLighting*>(effect); if (attrName == SVGNames::lighting_colorAttr) { RenderObject* renderer = this->renderer(); ASSERT(renderer); ASSERT(renderer->style()); return diffuseLighting->setLightingColor(renderer->style()->svgStyle()->lightingColor()); } if (attrName == SVGNames::surfaceScaleAttr) return diffuseLighting->setSurfaceScale(surfaceScale()); if (attrName == SVGNames::diffuseConstantAttr) return diffuseLighting->setDiffuseConstant(diffuseConstant()); LightSource* lightSource = const_cast<LightSource*>(diffuseLighting->lightSource()); const SVGFELightElement* lightElement = SVGFELightElement::findLightElement(this); ASSERT(lightSource); ASSERT(lightElement); if (attrName == SVGNames::azimuthAttr) return lightSource->setAzimuth(lightElement->azimuth()); if (attrName == SVGNames::elevationAttr) return lightSource->setElevation(lightElement->elevation()); if (attrName == SVGNames::xAttr) return lightSource->setX(lightElement->x()); if (attrName == SVGNames::yAttr) return lightSource->setY(lightElement->y()); if (attrName == SVGNames::zAttr) return lightSource->setZ(lightElement->z()); if (attrName == SVGNames::pointsAtXAttr) return lightSource->setPointsAtX(lightElement->pointsAtX()); if (attrName == SVGNames::pointsAtYAttr) return lightSource->setPointsAtY(lightElement->pointsAtY()); if (attrName == SVGNames::pointsAtZAttr) return lightSource->setPointsAtZ(lightElement->pointsAtZ()); if (attrName == SVGNames::specularExponentAttr) return lightSource->setSpecularExponent(lightElement->specularExponent()); if (attrName == SVGNames::limitingConeAngleAttr) return lightSource->setLimitingConeAngle(lightElement->limitingConeAngle()); ASSERT_NOT_REACHED(); return false; }
void WorldObject::Draw(Camera* camera) { glMatrixMode(GL_MODELVIEW); camera->LoadMatrix(); glTranslatef(this->position.x, this->position.y, this->position.z); glRotatef(this->rotation.z, 0, 0, 1.0f); glRotatef(this->rotation.y, 0, 1.0f, 0); glRotatef(this->rotation.x, 1.f, 0, 0); glScalef(this->scale, this->scale, this->scale); glBegin(GL_TRIANGLES); for(int i = 0; i < this->faceCount; i++) { modelFace face = this->faces[i]; vector3 v1 = this->vertices[face.v1]; vector3 v2 = this->vertices[face.v2]; vector3 v3 = this->vertices[face.v3]; vector3 transformedv1 = this->GetTransformedVertex(face.v1); vector3 transformedv2 = this->GetTransformedVertex(face.v2); vector3 transformedv3 = this->GetTransformedVertex(face.v3); vector3 v1norm = this->GetVertexNormal(face.v1); vector3 v2norm = this->GetVertexNormal(face.v2); vector3 v3norm = this->GetVertexNormal(face.v3); vector3 v1Color = { 0, 0, 0 }; vector3 v2Color = { 0, 0, 0 }; vector3 v3Color = { 0, 0, 0 }; std::vector<LightSource*> lightSources = this->world->GetLightSources(); for(int i = 0; i < lightSources.size(); i++) { LightSource* ls = lightSources[i]; vector3 v1LightColor = ls->CalculateLight(this, transformedv1, v1norm, camera); vector3 v2LightColor = ls->CalculateLight(this, transformedv2, v2norm, camera); vector3 v3LightColor = ls->CalculateLight(this, transformedv3, v3norm, camera); v1Color.x += v1LightColor.x; v1Color.y += v1LightColor.y; v1Color.z += v1LightColor.z; v2Color.x += v2LightColor.x; v2Color.y += v2LightColor.y; v2Color.z += v2LightColor.z; v3Color.x += v3LightColor.x; v3Color.y += v3LightColor.y; v3Color.z += v3LightColor.z; } glColor3f(v1Color.x, v1Color.y, v1Color.z); glVertex3f(v1.x, v1.y, v1.z); glColor3f(v2Color.x, v2Color.y, v2Color.z); glVertex3f(v2.x, v2.y, v2.z); glColor3f(v3Color.x, v3Color.y, v3Color.z); glVertex3f(v3.x, v3.y, v3.z); } glEnd(); this->transformedNormalsAreValid = true; }
void Scene::addLightSource(const LightSource& lightSource) { _lightSources.push_back(lightSource.clone()); }
int main() { //Declaration of the objects that will form our scene osgViewer::Viewer viewer; ref_ptr<Group> scene (new Group); ref_ptr<Geode> objectGeode (new Geode); ref_ptr<Geode> terrainGeode (new Geode); ref_ptr<Geode> lightMarkerGeode (new Geode); //Shadow stuff!!! ref_ptr<osgShadow::ShadowedScene> shadowedScene = new osgShadow::ShadowedScene; ref_ptr<osgShadow::ShadowMap> sm = new osgShadow::ShadowMap; shadowedScene->setShadowTechnique(sm.get()); //Main light source Vec3 lightPosition(0,0,3); LightSource* ls = new LightSource; ls->getLight()->setPosition(Vec4(lightPosition,1)); ls->getLight()->setAmbient(Vec4(0.2,0.2,0.2,1.0)); ls->getLight()->setDiffuse(Vec4(0.6,0.6,0.6,1.0)); shadowedScene->addChild(scene.get()); shadowedScene->addChild(ls); shadowedScene->addChild(lightMarkerGeode.get()); //Next we define the material property of our objects // material ref_ptr<Material> matirial = new Material; matirial->setColorMode(Material::DIFFUSE); matirial->setAmbient(Material::FRONT_AND_BACK, Vec4(0, 0, 0, 1)); matirial->setSpecular(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1)); matirial->setShininess(Material::FRONT_AND_BACK, 64); scene->getOrCreateStateSet()->setAttributeAndModes(matirial.get(), StateAttribute::ON); //Adding the terrain and object nodes to the root node scene->addChild(objectGeode.get()); scene->addChild(terrainGeode.get()); //The terrain first, a flatten box terrainGeode->addDrawable(new ShapeDrawable(new Box(Vec3f(),5,7,0.05f))); terrainGeode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new osg::Texture2D(osgDB::readImageFile("terrain.jpg"))); //Now we can define our world made of several objects //The capsule objectGeode->getOrCreateStateSet()->setTextureAttributeAndModes(0, new Texture2D(osgDB::readImageFile("Fieldstone.jpg"))); objectGeode->addDrawable(new ShapeDrawable(new Capsule(Vec3(1,-1,1),0.3f,0.5f))); //The box objectGeode->addDrawable(new ShapeDrawable(new Box(Vec3(-1,1,1),1,1,1))); //The sphere objectGeode->addDrawable(new ShapeDrawable(new Sphere(Vec3(1,2,1),0.5f))); //objectGeode->addDrawable(new ShapeDrawable(new Sphere(Vec3(0,0,4.5f),0.1f))); //And finally the light marker: a small sphere lightMarkerGeode->addDrawable(new ShapeDrawable(new Sphere(lightPosition+osg::Vec3(0,0,0.5f),0.1f))); viewer.setSceneData( shadowedScene.get() ); //Stats Event Handler s key viewer.addEventHandler(new osgViewer::StatsHandler); // add the state manipulator viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) ); //Windows size handler viewer.addEventHandler(new osgViewer::WindowSizeHandler); return (viewer.run()); }