Search Results

Search found 73 results on 3 pages for 'phong dang'.

Page 1/3 | 1 2 3  | Next Page >

  • What is wrong with my specular phong shading

    - by Thijser
    I'm sorry if this should be placed on stackoverflow instead however seeing as this is graphics related I was hoping you guys could help me: I'm attempting to write a phong shader and currently working on the specular. I came acros the following formula: base*pow(dot(V,R),shininess) and attempted to implement it (V is the posion of the viewer and R the reflective vector). This gave the following result and code: Vec3Df phongSpecular(const Vec3Df & vertexPos, Vec3Df & normal, const Vec3Df & lightPos, const Vec3Df & cameraPos, unsigned int index) { Vec3Df relativeLightPos=(lightPos-vertexPos); relativeLightPos.normalize(); Vec3Df relativeCameraPos= (cameraPos-vertexPos); relativeCameraPos.normalize(); int DotOfNormalAndLight = Vec3Df::dotProduct(normal,relativeLightPos); Vec3Df reflective =(relativeLightPos-(2*DotOfNormalAndLight*normal))*-1; reflective.normalize(); float phongyness= Vec3Df::dotProduct(reflective,relativeCameraPos); if (phongyness<0){ phongyness=0; } float shininess= Shininess[index]; float speculair = powf(phongyness,shininess); return Ks[index]*speculair; } I'm looking for something more like this:

    Read the article

  • What is wrong with my speculair phong shading

    - by Thijser
    I'm sorry if this should be placed on stackoverflow instead however seeing as this is graphics related I was hoping you guys could help me: I'm attempting to write a phong shader and currently working on the specular. I came acros the following formula: base*pow(dot(V,R),shininess) and attempted to implement it (V is the posion of the viewer and R the reflective vector). This gave the following result and code: Vec3Df phongSpecular(const Vec3Df & vertexPos, Vec3Df & normal, const Vec3Df & lightPos, const Vec3Df & cameraPos, unsigned int index) { Vec3Df relativeLightPos=(lightPos-vertexPos); relativeLightPos.normalize(); Vec3Df relativeCameraPos= (cameraPos-vertexPos); relativeCameraPos.normalize(); int DotOfNormalAndLight = Vec3Df::dotProduct(normal,relativeLightPos); Vec3Df reflective =(relativeLightPos-(2*DotOfNormalAndLight*normal))*-1; reflective.normalize(); float phongyness= Vec3Df::dotProduct(reflective,relativeCameraPos); if (phongyness<0){ phongyness=0; } float shininess= Shininess[index]; float speculair = powf(phongyness,shininess); return Ks[index]*speculair; } I'm looking for something more like this:

    Read the article

  • OpenGL 3.x Assimp trouble implementing phong shading (normals?)

    - by Defcronyke
    I'm having trouble getting phong shading to look right. I'm pretty sure there's something wrong with either my OpenGL calls, or the way I'm loading my normals, but I guess it could be something else since 3D graphics and Assimp are both still very new to me. When trying to load .obj/.mtl files, the problems I'm seeing are: The models seem to be lit too intensely (less phong-style and more completely washed out, too bright). Faces that are lit seem to be lit equally all over (with the exception of a specular highlight showing only when the light source position is moved to be practically right on top of the model) Because of problems 1 and 2, spheres look very wrong: picture of sphere And things with larger faces look (less-noticeably) wrong too: picture of cube I could be wrong, but to me this doesn't look like proper phong shading. Here's the code that I think might be relevant (I can post more if necessary): file: assimpRenderer.cpp #include "assimpRenderer.hpp" namespace def { assimpRenderer::assimpRenderer(std::string modelFilename, float modelScale) { initSFML(); initOpenGL(); if (assImport(modelFilename)) // if modelFile loaded successfully { initScene(); mainLoop(modelScale); shutdownScene(); } shutdownOpenGL(); shutdownSFML(); } assimpRenderer::~assimpRenderer() { } void assimpRenderer::initSFML() { windowWidth = 800; windowHeight = 600; settings.majorVersion = 3; settings.minorVersion = 3; app = NULL; shader = NULL; app = new sf::Window(sf::VideoMode(windowWidth,windowHeight,32), "OpenGL 3.x Window", sf::Style::Default, settings); app->setFramerateLimit(240); app->setActive(); return; } void assimpRenderer::shutdownSFML() { delete app; return; } void assimpRenderer::initOpenGL() { GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ std::cerr << "Error: " << glewGetErrorString(err) << std::endl; } // check the OpenGL context version that's currently in use int glVersion[2] = {-1, -1}; glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // get the OpenGL Major version glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // get the OpenGL Minor version std::cout << "Using OpenGL Version: " << glVersion[0] << "." << glVersion[1] << std::endl; return; } void assimpRenderer::shutdownOpenGL() { return; } void assimpRenderer::initScene() { // allocate heap space for VAOs, VBOs, and IBOs vaoID = new GLuint[scene->mNumMeshes]; vboID = new GLuint[scene->mNumMeshes*2]; iboID = new GLuint[scene->mNumMeshes]; glClearColor(0.4f, 0.6f, 0.9f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glEnable(GL_CULL_FACE); shader = new Shader("shader.vert", "shader.frag"); projectionMatrix = glm::perspective(60.0f, (float)windowWidth / (float)windowHeight, 0.1f, 100.0f); rot = 0.0f; rotSpeed = 50.0f; faceIndex = 0; colorArrayA = NULL; colorArrayD = NULL; colorArrayS = NULL; normalArray = NULL; genVAOs(); return; } void assimpRenderer::shutdownScene() { delete [] iboID; delete [] vboID; delete [] vaoID; delete shader; } void assimpRenderer::renderScene(float modelScale) { sf::Time elapsedTime = clock.getElapsedTime(); clock.restart(); if (rot > 360.0f) rot = 0.0f; rot += rotSpeed * elapsedTime.asSeconds(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); viewMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, -3.0f, -10.0f)); // move back a bit modelMatrix = glm::scale(glm::mat4(1.0f), glm::vec3(modelScale)); // scale model modelMatrix = glm::rotate(modelMatrix, rot, glm::vec3(0, 1, 0)); //modelMatrix = glm::rotate(modelMatrix, 25.0f, glm::vec3(0, 1, 0)); glm::vec3 lightPosition( 0.0f, -100.0f, 0.0f ); float lightPositionArray[3]; lightPositionArray[0] = lightPosition[0]; lightPositionArray[1] = lightPosition[1]; lightPositionArray[2] = lightPosition[2]; shader->bind(); int projectionMatrixLocation = glGetUniformLocation(shader->id(), "projectionMatrix"); int viewMatrixLocation = glGetUniformLocation(shader->id(), "viewMatrix"); int modelMatrixLocation = glGetUniformLocation(shader->id(), "modelMatrix"); int ambientLocation = glGetUniformLocation(shader->id(), "ambientColor"); int diffuseLocation = glGetUniformLocation(shader->id(), "diffuseColor"); int specularLocation = glGetUniformLocation(shader->id(), "specularColor"); int lightPositionLocation = glGetUniformLocation(shader->id(), "lightPosition"); int normalMatrixLocation = glGetUniformLocation(shader->id(), "normalMatrix"); glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix[0][0]); glUniformMatrix4fv(viewMatrixLocation, 1, GL_FALSE, &viewMatrix[0][0]); glUniformMatrix4fv(modelMatrixLocation, 1, GL_FALSE, &modelMatrix[0][0]); glUniform3fv(lightPositionLocation, 1, lightPositionArray); for (unsigned int i = 0; i < scene->mNumMeshes; i++) { colorArrayA = new float[3]; colorArrayD = new float[3]; colorArrayS = new float[3]; material = scene->mMaterials[scene->mNumMaterials-1]; normalArray = new float[scene->mMeshes[i]->mNumVertices * 3]; unsigned int normalIndex = 0; for (unsigned int j = 0; j < scene->mMeshes[i]->mNumVertices * 3; j+=3, normalIndex++) { normalArray[j] = scene->mMeshes[i]->mNormals[normalIndex].x; // x normalArray[j+1] = scene->mMeshes[i]->mNormals[normalIndex].y; // y normalArray[j+2] = scene->mMeshes[i]->mNormals[normalIndex].z; // z } normalIndex = 0; glUniformMatrix3fv(normalMatrixLocation, 1, GL_FALSE, normalArray); aiColor3D ambient(0.0f, 0.0f, 0.0f); material->Get(AI_MATKEY_COLOR_AMBIENT, ambient); aiColor3D diffuse(0.0f, 0.0f, 0.0f); material->Get(AI_MATKEY_COLOR_DIFFUSE, diffuse); aiColor3D specular(0.0f, 0.0f, 0.0f); material->Get(AI_MATKEY_COLOR_SPECULAR, specular); colorArrayA[0] = ambient.r; colorArrayA[1] = ambient.g; colorArrayA[2] = ambient.b; colorArrayD[0] = diffuse.r; colorArrayD[1] = diffuse.g; colorArrayD[2] = diffuse.b; colorArrayS[0] = specular.r; colorArrayS[1] = specular.g; colorArrayS[2] = specular.b; // bind color for each mesh glUniform3fv(ambientLocation, 1, colorArrayA); glUniform3fv(diffuseLocation, 1, colorArrayD); glUniform3fv(specularLocation, 1, colorArrayS); // render all meshes glBindVertexArray(vaoID[i]); // bind our VAO glDrawElements(GL_TRIANGLES, scene->mMeshes[i]->mNumFaces*3, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // unbind our VAO delete [] normalArray; delete [] colorArrayA; delete [] colorArrayD; delete [] colorArrayS; } shader->unbind(); app->display(); return; } void assimpRenderer::handleEvents() { sf::Event event; while (app->pollEvent(event)) { if (event.type == sf::Event::Closed) { app->close(); } if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)) { app->close(); } if (event.type == sf::Event::Resized) { glViewport(0, 0, event.size.width, event.size.height); } } return; } void assimpRenderer::mainLoop(float modelScale) { while (app->isOpen()) { renderScene(modelScale); handleEvents(); } } bool assimpRenderer::assImport(const std::string& pFile) { // read the file with some example postprocessing scene = importer.ReadFile(pFile, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); // if the import failed, report it if (!scene) { std::cerr << "Error: " << importer.GetErrorString() << std::endl; return false; } return true; } void assimpRenderer::genVAOs() { int vboIndex = 0; for (unsigned int i = 0; i < scene->mNumMeshes; i++, vboIndex+=2) { mesh = scene->mMeshes[i]; indexArray = new unsigned int[mesh->mNumFaces * sizeof(unsigned int) * 3]; // convert assimp faces format to array faceIndex = 0; for (unsigned int t = 0; t < mesh->mNumFaces; ++t) { const struct aiFace* face = &mesh->mFaces[t]; std::memcpy(&indexArray[faceIndex], face->mIndices, sizeof(float) * 3); faceIndex += 3; } // generate VAO glGenVertexArrays(1, &vaoID[i]); glBindVertexArray(vaoID[i]); // generate IBO for faces glGenBuffers(1, &iboID[i]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboID[i]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * mesh->mNumFaces * 3, indexArray, GL_STATIC_DRAW); // generate VBO for vertices if (mesh->HasPositions()) { glGenBuffers(1, &vboID[vboIndex]); glBindBuffer(GL_ARRAY_BUFFER, vboID[vboIndex]); glBufferData(GL_ARRAY_BUFFER, mesh->mNumVertices * sizeof(GLfloat) * 3, mesh->mVertices, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint)0); glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0); } // generate VBO for normals if (mesh->HasNormals()) { normalArray = new float[scene->mMeshes[i]->mNumVertices * 3]; unsigned int normalIndex = 0; for (unsigned int j = 0; j < scene->mMeshes[i]->mNumVertices * 3; j+=3, normalIndex++) { normalArray[j] = scene->mMeshes[i]->mNormals[normalIndex].x; // x normalArray[j+1] = scene->mMeshes[i]->mNormals[normalIndex].y; // y normalArray[j+2] = scene->mMeshes[i]->mNormals[normalIndex].z; // z } normalIndex = 0; glGenBuffers(1, &vboID[vboIndex+1]); glBindBuffer(GL_ARRAY_BUFFER, vboID[vboIndex+1]); glBufferData(GL_ARRAY_BUFFER, mesh->mNumVertices * sizeof(GLfloat) * 3, normalArray, GL_STATIC_DRAW); glEnableVertexAttribArray((GLuint)1); glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0); delete [] normalArray; } // tex coord stuff goes here // unbind buffers glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); delete [] indexArray; } vboIndex = 0; return; } } file: shader.vert #version 150 core in vec3 in_Position; in vec3 in_Normal; uniform mat4 projectionMatrix; uniform mat4 viewMatrix; uniform mat4 modelMatrix; uniform vec3 lightPosition; uniform mat3 normalMatrix; smooth out vec3 vVaryingNormal; smooth out vec3 vVaryingLightDir; void main() { // derive MVP and MV matrices mat4 modelViewProjectionMatrix = projectionMatrix * viewMatrix * modelMatrix; mat4 modelViewMatrix = viewMatrix * modelMatrix; // get surface normal in eye coordinates vVaryingNormal = normalMatrix * in_Normal; // get vertex position in eye coordinates vec4 vPosition4 = modelViewMatrix * vec4(in_Position, 1.0); vec3 vPosition3 = vPosition4.xyz / vPosition4.w; // get vector to light source vVaryingLightDir = normalize(lightPosition - vPosition3); // Set the position of the current vertex gl_Position = modelViewProjectionMatrix * vec4(in_Position, 1.0); } file: shader.frag #version 150 core out vec4 out_Color; uniform vec3 ambientColor; uniform vec3 diffuseColor; uniform vec3 specularColor; smooth in vec3 vVaryingNormal; smooth in vec3 vVaryingLightDir; void main() { // dot product gives us diffuse intensity float diff = max(0.0, dot(normalize(vVaryingNormal), normalize(vVaryingLightDir))); // multiply intensity by diffuse color, force alpha to 1.0 out_Color = vec4(diff * diffuseColor, 1.0); // add in ambient light out_Color += vec4(ambientColor, 1.0); // specular light vec3 vReflection = normalize(reflect(-normalize(vVaryingLightDir), normalize(vVaryingNormal))); float spec = max(0.0, dot(normalize(vVaryingNormal), vReflection)); if (diff != 0) { float fSpec = pow(spec, 128.0); // Set the output color of our current pixel out_Color.rgb += vec3(fSpec, fSpec, fSpec); } } I know it's a lot to look through, but I'm putting most of the code up so as not to assume where the problem is. Thanks in advance to anyone who has some time to help me pinpoint the problem(s)! I've been trying to sort it out for two days now and I'm not getting anywhere on my own.

    Read the article

  • point light illumination using Phong model

    - by Myx
    Hello: I wish to render a scene that contains one box and a point light source using the Phong illumination scheme. The following are the relevant code snippets for my calculation: R3Rgb Phong(R3Scene *scene, R3Ray *ray, R3Intersection *intersection) { R3Rgb radiance; if(intersection->hit == 0) { radiance = scene->background; return radiance; } ... // obtain ambient term ... // this is zero for my test // obtain emissive term ... // this is also zero for my test // for each light in the scene, obtain calculate the diffuse and specular terms R3Rgb intensity_diffuse(0,0,0,1); R3Rgb intensity_specular(0,0,0,1); for(unsigned int i = 0; i < scene->lights.size(); i++) { R3Light *light = scene->Light(i); R3Rgb light_color = LightIntensity(scene->Light(i), intersection->position); R3Vector light_vector = -LightDirection(scene->Light(i), intersection->position); // check if the light is "behind" the surface normal if(normal.Dot(light_vector)<=0) continue; // calculate diffuse reflection if(!Kd.IsBlack()) intensity_diffuse += Kd*normal.Dot(light_vector)*light_color; if(Ks.IsBlack()) continue; // calculate specular reflection ... // this I believe to be irrelevant for the particular test I'm doing } radiance = intensity_diffuse; return radiance; } R3Rgb LightIntensity(R3Light *light, R3Point position) { R3Rgb light_intensity; double distance; double denominator; if(light->type != R3_DIRECTIONAL_LIGHT) { distance = (position-light->position).Length(); denominator = light->constant_attenuation + (light->linear_attenuation*distance) + (light->quadratic_attenuation*distance*distance); } switch(light->type) { ... case R3_POINT_LIGHT: light_intensity = light->color/denominator; break; ... } return light_intensity; } R3Vector LightDirection(R3Light *light, R3Point position) { R3Vector light_direction; switch(light->type) { ... case R3_POINT_LIGHT: light_direction = position - light->position; break; ... } light_direction.Normalize(); return light_direction; } I believe that the error must be somewhere in either LightDirection(...) or LightIntensity(...) functions because when I run my code using a directional light source, I obtain the desired rendered image (thus this leads me to believe that the Phong illumination equation is correct). Also, in Phong(...), when I computed the intensity_diffuse and while debugging, I divided light_color by 10, I was obtaining a resulting image that looked more like what I need. Am I calculating the light_color correctly? Thanks.

    Read the article

  • Problem implementing Blinn–Phong shading model

    - by Joe Hopfgartner
    I did this very simple, perfectly working, implementation of Phong Relflection Model (There is no ambience implemented yet, but that doesn't bother me for now). The functions should be self explaining. /** * Implements the classic Phong illumination Model using a reflected light * vector. */ public class PhongIllumination implements IlluminationModel { @RGBParam(r = 0, g = 0, b = 0) public Vec3 ambient; @RGBParam(r = 1, g = 1, b = 1) public Vec3 diffuse; @RGBParam(r = 1, g = 1, b = 1) public Vec3 specular; @FloatParam(value = 20, min = 1, max = 200.0f) public float shininess; /* * Calculate the intensity of light reflected to the viewer . * * @param P = The surface position expressed in world coordinates. * * @param V = Normalized viewing vector from surface to eye in world * coordinates. * * @param N = Normalized normal vector at surface point in world * coordinates. * * @param surfaceColor = surfaceColor Color of the surface at the current * position. * * @param lights = The active light sources in the scene. * * @return Reflected light intensity I. */ public Vec3 shade(Vec3 P, Vec3 V, Vec3 N, Vec3 surfaceColor, Light lights[]) { Vec3 surfaceColordiffused = Vec3.mul(surfaceColor, diffuse); Vec3 totalintensity = new Vec3(0, 0, 0); for (int i = 0; i < lights.length; i++) { Vec3 L = lights[i].calcDirection(P); N = N.normalize(); V = V.normalize(); Vec3 R = Vec3.reflect(L, N); // reflection vector float diffuseLight = Vec3.dot(N, L); float specularLight = Vec3.dot(V, R); if (diffuseLight > 0) { totalintensity = Vec3.add(Vec3.mul(Vec3.mul( surfaceColordiffused, lights[i].calcIntensity(P)), diffuseLight), totalintensity); if (specularLight > 0) { Vec3 Il = lights[i].calcIntensity(P); Vec3 Ilincident = Vec3.mul(Il, Math.max(0.0f, Vec3 .dot(N, L))); Vec3 intensity = Vec3.mul(Vec3.mul(specular, Ilincident), (float) Math.pow(specularLight, shininess)); totalintensity = Vec3.add(totalintensity, intensity); } } } return totalintensity; } } Now i need to adapt it to become a Blinn-Phong illumination model I used the formulas from hearn and baker, followed pseudocodes and tried to implement it multiple times according to wikipedia articles in several languages but it never worked. I just get no specular reflections or they are so weak and/or are at the wrong place and/or have the wrong color. From the numerous wrong implementations I post some little code that already seems to be wrong. So I calculate my Half Way vector and my new specular light like so: Vec3 H = Vec3.mul(Vec3.add(L.normalize(), V), Vec3.add(L.normalize(), V).length()); float specularLight = Vec3.dot(H, N); With theese little changes it should already work (maby not with correct intensity but basically it should be correct). But the result is wrong. Here are two images. Left how it should render correctly and right how it renders. If i lower the shininess factor you can see a little specular light at the top right: Altough I understand the concept of Phong illumination and also the simplified more performant adaptaion of blinn phong I am trying around for days and just cant get it to work. Any help is appriciated. Edit: I was made aware of an error by this answer, that i am mutiplying by |L+V| instead of dividing by it when calculating H. I changed to deviding doing so: Vec3 H = Vec3.mul(Vec3.add(L.normalize(), V), 1/Vec3.add(L.normalize(), V).length()); Unfortunately this doesnt change much. The results look like this: and if I rise the specular constant and lower the shininess You can see the effects more clearly in a smilar wrong way: However this division just the normalisation. I think I am missing one step. Because the formulas like this just dont make sense to me. If you look at this picture: http://en.wikipedia.org/wiki/File:Blinn-Phong_vectors.svg The projection of H to N is far less than V to R. And if you imagine changing the vector V in the picture the angle is the same when the viewing vector is "on the left side". and becomes more and more different when going to the right. I pesonally would multiply the whole projection by two to become something similiar (and the hole point is to avoid the calculation of R). Altough I didnt read anythinga bout that anywehre i am gonna try this out... Result: The intension of the specular light is far too much (white areas) and the position is still wrong. I think I am messing something else up because teh reflection are just at the wrong place. But what? Edit: Now I read on wikipedia in the notes that the angle of N/H is in fact approximalty half or V/R. To compensate that i should multiply my shineness exponent by 4 rather than my projection. If i do that I end up with this: Far to intense but still one thing. The projection is at the wrong place. Where could i mess up my vectors?

    Read the article

  • OpenGL render vs. own Phong Illumination Implementation

    - by Myx
    Hello: I have implemented a Phong Illumination Scheme using a camera that's centered at (0,0,0) and looking directly at the sphere primitive. The following are the relevant contents of the scene file that is used to view the scene using OpenGL as well as to render the scene using my own implementation: ambient 0 1 0 dir_light 1 1 1 -3 -4 -5 # A red sphere with 0.5 green ambiance, centered at (0,0,0) with radius 1 material 0 0.5 0 1 0 0 1 0 0 0 0 0 0 0 0 10 1 0 sphere 0 0 0 0 1 The resulting image produced by OpenGL. The image that my rendering application produces. As you can see, there are various differences between the two: The specular highlight on my image is smaller than the one in OpenGL. The diffuse surface seems to not diffuse in the correct way, resulting in the yellow region to be unneccessarily large in my image, whereas in OpenGL there's a nice dark green region closer to the bottom of the sphere The color produced by OpenGL is much darker than the one in my image. Those are the most prominent three differences that I see. The following is my implementation of the Phong illumination: R3Rgb Phong(R3Scene *scene, R3Ray *ray, R3Intersection *intersection) { R3Rgb radiance; if(intersection->hit == 0) { radiance = scene->background; return radiance; } R3Vector normal = intersection->normal; R3Rgb Kd = intersection->node->material->kd; R3Rgb Ks = intersection->node->material->ks; // obtain ambient term R3Rgb intensity_ambient = intersection->node->material->ka*scene->ambient; // obtain emissive term R3Rgb intensity_emission = intersection->node->material->emission; // for each light in the scene, obtain calculate the diffuse and specular terms R3Rgb intensity_diffuse(0,0,0,1); R3Rgb intensity_specular(0,0,0,1); for(unsigned int i = 0; i < scene->lights.size(); i++) { R3Light *light = scene->Light(i); R3Rgb light_color = LightIntensity(scene->Light(i), intersection->position); R3Vector light_vector = -LightDirection(scene->Light(i), intersection->position); // calculate diffuse reflection intensity_diffuse += Kd*normal.Dot(light_vector)*light_color; // calculate specular reflection R3Vector reflection_vector = 2.*normal.Dot(light_vector)*normal-light_vector; reflection_vector.Normalize(); R3Vector viewing_vector = ray->Start() - intersection->position; viewing_vector.Normalize(); double n = intersection->node->material->shininess; intensity_specular += Ks*pow(max(0.,viewing_vector.Dot(reflection_vector)),n)*light_color; } radiance = intensity_emission+intensity_ambient+intensity_diffuse+intensity_specular; return radiance; } Here are the related LightIntensity(...) and LightDirection(...) functions: R3Vector LightDirection(R3Light *light, R3Point position) { R3Vector light_direction; switch(light->type) { case R3_DIRECTIONAL_LIGHT: light_direction = light->direction; break; case R3_POINT_LIGHT: light_direction = position-light->position; break; case R3_SPOT_LIGHT: light_direction = position-light->position; break; } light_direction.Normalize(); return light_direction; } R3Rgb LightIntensity(R3Light *light, R3Point position) { R3Rgb light_intensity; double distance; double denominator; if(light->type != R3_DIRECTIONAL_LIGHT) { distance = (position-light->position).Length(); denominator = light->constant_attenuation + light->linear_attenuation*distance + light->quadratic_attenuation*distance*distance; } switch(light->type) { case R3_DIRECTIONAL_LIGHT: light_intensity = light->color; break; case R3_POINT_LIGHT: light_intensity = light->color/denominator; break; case R3_SPOT_LIGHT: R3Vector from_light_to_point = position - light->position; light_intensity = light->color*( pow(light->direction.Dot(from_light_to_point), light->angle_attenuation)); break; } return light_intensity; } I would greatly appreciate any suggestions as to any implementation errors that are apparent. I am wondering if the differences could be occurring simply because of the gamma values used for display by OpenGL and the default gamma value for my display. I also know that OpenGL (or at least tha parts that I was provided) can't cast shadows on objects. Not that this is relevant for the point in question, but it just leads me to wonder if it's simply display and capability differences between OpenGL and what I am trying to do. Thank you for your help.

    Read the article

  • Dang Error #1009 !

    - by boz
    I'm building a simple flash site for a friend who has a spa. I keep getting this error: Error #1009: Cannot access a property or method of a null object reference. at spa7_fla::MainTimeline/frame1() through the process of commenting out code, i've narrowed down to my link section: vox_link.addEventListener(MouseEvent.CLICK,gotoVox); function gotoVox(evtObj:Event):void { var voxSite:URLRequest=new URLRequest("http://www.voxmundiproject.com"); navigateToURL(voxSite, "_blank"); } With this section commented out, i don't get the 1009 error. When the code is active, I get the error. My code syntax is correct so I'm stumped. Does someone have an idea what my be wrong? Thanks!

    Read the article

  • Lighting-Reflectance Models & Licensing Issues

    - by codey
    Generally, or specifically, is there any licensing issue with using any of the well known lighting/reflectance models (i.e. the BRDFs or other distribution or approximation functions): Phong, Blinn–Phong, Cook–Torrance, Blinn-Torrance-Sparrow, Lambert, Minnaert, Oren–Nayar, Ward, Strauss, Ashikhmin-Shirley and common modifications where applicable, such as: Beckmann distribution, Blinn distribution, Schlick's approximation, etc. in your shader code utilised in a commercial product? Or is it a non-issue?

    Read the article

  • How to share folders using Oracle, Windows and Ubuntu

    - by Daniel Dang
    I use my laptop TOSHIBA, 4gig RAM, more 40gig free disks spaces and Vista Home Premium 64bits with service pack 2. I installed Oracle VM VirtalBox with success, after I installed UBUNTU version 8 with success ! I need to transfer files between Vista and UBUNTU on the same laptop, how I can do that ? Can I use SAMBA ? I try to use SAMBA but it is not success ! How I can install SAMBA on UBUNTU v.8 ?

    Read the article

  • How to customize the pop up menu in iPhone?

    - by Allen Dang
    The application I'm creating needs a function like user selects some text, a pop up menu shows, and user clicks "search" menu to perform a search directly. Problem is the current pop up menu provided by UIMenuController doesn't support to be extended. So my thought is to subscribe "UIMenuControllerDidShowMenuNotification", get the frame of pop up menu, and display the "search" button right aside. But during the implementation, I met a strange problem, the notification seems never be sent, means after the menu shown, I still cannot be notified, following are the key section of code. - (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(menuDidShow:) name:UIMenuControllerWillShowMenuNotification object:nil]; } - (void)viewDidUnload { // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; [[NSNotificationCenter defaultCenter] removeObserver:self name:UIMenuControllerDidShowMenuNotification object:nil]; self.textView = nil; self.searchBar = nil; } - (void)menuDidShow:(NSNotification *)notification { NSLog(@"menu did show!"); } The code is too simple to make mistake, can someone help me to understand what's going on? Or what did I miss?

    Read the article

  • Doxygen, too heavy to maintain ?

    - by Phong
    I am currently starting using doxygen to document my source code. I have notice that the syntax is very heavy, every time I modify the source code, I also need to change the comment and I really have the impression to pass too much time modifying the comment for every change I make in the source code. Do you have some tips to document my source code efficiently ? Does some editor (or plugin for existing editor) for doxygen to do the following exist? automatically track unsynchronized code/comment and warn the programmer about it. automatically add doxygen comment format (template with parameter name in it for example) in the source code (template) for every new item PS: I am working on a C/C++ project.

    Read the article

  • Starting one BlackBerry screen from another.

    - by DanG
    I've recently run into a snag while putting on the finishing touches for my BlackBerry app. I'm building a login screen which, if the user is successful in logging in, goes to a data loading screen, and then to a home screen. From the home screen, you can use the app. Everything works great but one thing, I can't seamlessly move from the login screen to the loading screen, to the home screen. I can move from the login screen to the loading screen ok, because I'm doing that via a button click which is on the GUI thread, but then I have the login screen at the bottom of the stack and can't get it out using the dismiss method. Once in the loading screen, I can't push the home screen because I'm not doing it via the gui method, though I'm able to update the GUI via the following piece of code: private void checkData(){ Timer loadingTimer = new Timer(); TimerTask loadingTask = new TimerTask() { public void run() { // set the progress bar progressGaugeField.setValue(DataManager.getDataLoaded()); // for repainting the screen invalidate(); } }; loadingTimer.scheduleAtFixedRate(loadingTask, 500, 500); } Does anyone know how to solve my problem of moving seamlessly from the login screen to the loading screen to the home screen? Note: once I'm at the home screen I'd like to have it be the only screen on the stack. Thanks!

    Read the article

  • Set Height of Div Equal to Parent Tag

    - by Phong Dang
    Hello, I have a snip code HTML as below : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns:o="urn:schemas-microsoft-com:office:office" lang="en-us" dir="ltr"> <head> <meta http-equiv="X-UA-Compatible" content="IE=8" /> <meta name="GENERATOR" content="Microsoft SharePoint" /> <meta name="progid" content="SharePoint.WebPartPage.Document" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Expires" content="0" /> <title>Demo </title> <style type="text/css"> A { font-weight: normal; font-size: 10pt; text-decoration: none; } </style> <link rel="stylesheet" type="text/css" href="/_layouts/1033/styles/Themable/wiki.css?rev=AWRyZDbGxZSekWBubaxPXw%3D%3D" /> <link rel="stylesheet" type="text/css" href="/_layouts/1033/styles/Themable/corev4.css?rev=w9FW7ASZnUjiWWCtJEcnTw%3D%3D" /> </head> <body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="height:100%;"> <form method="" name="frm"> <table style="border-bottom: black 1px solid; border-left: black 1px solid; border-collapse: collapse; border-top: black 1px solid; border-right: black 1px solid" id="ctl00_m_g_510fd150_a968_41ee_a28d_d47ff4a7198e_BambooCalendarControl" height="100%"> <tbody> <tr> <td style="border-top: black 1px solid; border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> <span> <nobr>8:00 AM</nobr> </span> </td> <td style="border-bottom: #d4d0c8 1px dotted; background-color: #ccffcc; border-left: 0px; border-top: black 1px solid; border-right: black 1px solid" height="100%" valign="top" rowspan="8" width="50%"> <div style="border-bottom: gray 1px solid; border-left: gray 1px solid; background-color: #ffa500; height: 100%; overflow: hidden; border-top: gray 1px solid; border-right: gray 1px solid" nowrap width="100%" valign="top"> <a style="height: 100%; color: black" href="#"><font color="white">Item </font></a> </div> </td> <td style="border-bottom: #d4d0c8 1px dotted; border-left: 0px; border-top: black 1px solid; border-right: black 1px solid" height="25" valign="top" width="100%" colspan="1"> </td> </tr> <tr> <td style="border-bottom: black 1px solid; border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> </td> <td style="border-bottom: black 1px solid; border-left: 0px; border-right: black 1px solid" height="25" valign="top" width="100%" colspan="1"> </td> </tr> <tr> <td style="border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> <span> <nobr>9:00 AM</nobr> </span> </td> <td style="border-bottom: #d4d0c8 1px dotted; background-color: #ccffcc; border-left: 0px; border-right: black 1px solid" height="100%" valign="top" rowspan="4" width="50%"> <div style="border-bottom: gray 1px solid; border-left: gray 1px solid; background-color: #bdb76b; height: 100%; overflow: hidden; border-top: gray 1px solid; border-right: gray 1px solid" nowrap width="100%" valign="top"> <a style="height: 100%; color: black" title="" href="#"><font color="white">Item 2 </font> </a> </div> </td> </tr> <tr> <td style="border-bottom: black 1px solid; border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> </td> </tr> <tr style="border-left: medium none; border-right: #696969 1px solid"> <td style="border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> <span> <nobr>10:00 AM</nobr> </span> </td> </tr> <tr> <td style="border-bottom: black 1px solid; border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> </td> </tr> <tr> <td style="border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> <span> <nobr>11:00 AM</nobr> </span> </td> <td style="border-bottom: #d4d0c8 1px dotted; border-left: 0px; border-top: black 1px solid; border-right: black 1px solid" height="25" valign="top" width="100%" colspan="1"> </td> </tr> <tr> <td style="border-bottom: black 1px solid; border-right: black 1px solid" height="25" valign="top" rowspan="1" width="1%" align="right"> </td> <td style="border-bottom: black 1px solid; border-left: 0px; border-right: black 1px solid" height="25" valign="top" width="100%" colspan="2"> </td> </tr> </tbody> </table> </form> </body> </html> I set the height of the div 100% so that it full of TD but it did not effect. Please help me ! Thanks / PD

    Read the article

  • How do encrypt a long or int using the Bouncy Castle crypto routines for BlackBerry?

    - by DanG
    How do encrypt/decrypt a long or int using the Bouncy Castle crypto routines for BlackBerry? I know how to encrypt/decrypt a String. I can encrypt a long but can't get a long to decrypt properly. Some of this is poorly done, but I'm just trying stuff out at the moment. I've included my entire crypto engine here: import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; public class CryptoEngine { // Global Variables // Global Objects private static AESFastEngine engine; private static BufferedBlockCipher cipher; private static KeyParameter key; public static boolean setEncryptionKey(String keyText) { // adding in spaces to force a proper key keyText += " "; // cutting off at 128 bits (16 characters) keyText = keyText.substring(0, 16); keyText = HelperMethods.cleanUpNullString(keyText); byte[] keyBytes = keyText.getBytes(); key = new KeyParameter(keyBytes); engine = new AESFastEngine(); cipher = new PaddedBufferedBlockCipher(engine); // just for now return true; } public static String encryptString(String plainText) { try { byte[] plainArray = plainText.getBytes(); cipher.init(true, key); byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); cipher.doFinal(cipherBytes, cipherLength); String cipherString = new String(cipherBytes); return cipherString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } public static String decryptString(String encryptedText) { try { byte[] cipherBytes = encryptedText.getBytes(); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); cipher.doFinal(decryptedBytes, decryptedLength); String decryptedString = new String(decryptedBytes); // crop accordingly int index = decryptedString.indexOf("\u0000"); if (index >= 0) { decryptedString = decryptedString.substring(0, index); } return decryptedString; } catch (DataLengthException e) { Logger.logToConsole(e); } catch (IllegalArgumentException e) { Logger.logToConsole(e); } catch (IllegalStateException e) { Logger.logToConsole(e); } catch (InvalidCipherTextException e) { Logger.logToConsole(e); } catch (Exception ex) { Logger.logToConsole(ex); } // else return "";// default bad value } private static byte[] convertLongToByteArray(long longToConvert) { return new byte[] { (byte) (longToConvert >>> 56), (byte) (longToConvert >>> 48), (byte) (longToConvert >>> 40), (byte) (longToConvert >>> 32), (byte) (longToConvert >>> 24), (byte) (longToConvert >>> 16), (byte) (longToConvert >>> 8), (byte) (longToConvert) }; } private static long convertByteArrayToLong(byte[] byteArrayToConvert) { long returnable = 0; for (int counter = 0; counter < byteArrayToConvert.length; counter++) { returnable += ((byteArrayToConvert[byteArrayToConvert.length - counter - 1] & 0xFF) << counter * 8); } if (returnable < 0) { returnable++; } return returnable; } public static long encryptLong(long plainLong) { try { String plainString = String.valueOf(plainLong); String cipherString = encryptString(plainString); byte[] cipherBytes = cipherString.getBytes(); long returnable = convertByteArrayToLong(cipherBytes); return returnable; } catch (Exception e) { Logger.logToConsole(e); } // else return Integer.MIN_VALUE;// default bad value } public static long decryptLong(long encryptedLong) { byte[] cipherBytes = convertLongToByteArray(encryptedLong); cipher.init(false, key); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; int decryptedLength = cipherBytes.length; try { cipher.doFinal(decryptedBytes, decryptedLength); } catch (DataLengthException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidCipherTextException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } long plainLong = convertByteArrayToLong(decryptedBytes); return plainLong; } public static boolean encryptBoolean(int plainBoolean) { return false; } public static boolean decryptBoolean(int encryptedBoolean) { return false; } public static boolean testLongToByteArrayConversion() { boolean returnable = true; // fails out of the bounds of an integer, the conversion to long from byte // array does not hold, need to figure out a better solution for (long counter = -1000000; counter < 1000000; counter++) { long test = counter; byte[] bytes = convertLongToByteArray(test); long result = convertByteArrayToLong(bytes); if (result != test) { returnable = false; Logger.logToConsole("long conversion failed"); Logger.logToConsole("test = " + test + "\n result = " + result); } // regardless } // the end Logger.logToConsole("final returnable result = " + returnable); return returnable; } }

    Read the article

  • Static source code analysis with LLVM

    - by Phong
    I recently discover the LLVM (low level virtual machine) project, and from what I have heard It can be used to performed static analysis on a source code. I would like to know if it is possible to extract the different function call through function pointer (find the caller function and the callee function) in a program. I could find the kind of information in the website so it would be really helpful if you could tell me if such an library already exist in LLVM or can you point me to the good direction on how to build it myself (existing source code, reference, tutorial, example...). EDIT: With my analysis I actually want to extract caller/callee function call. In the case of a function pointer, I would like to return a set of possible callee. both caller and callee must be define in the source code (this does not include third party function in a library).

    Read the article

  • I'm getting a ServerException when I try to send objects from a BlackBerry to a Server via a webserv

    - by DanG
    I'm trying to send an array of objects wrapped in an array object wrapper to a WS via JSR172 WS calls. Using the generated stub, I'm able to download objects from the server, but I'm not able to upload objects to the server. This currently happens on all simulators in house. This is all the information I can get out of the server exception: javax.xml.rpc.JAXRPCException: java.rmi.ServerException: Server cannot handle the message because of some temporary condition. Here are the server specs: Windows 7 IIS 7 or 7.5 .NET 3.5 for the WS code written in C#. If anyone knows how to solve this problem, or knows where to look, I'd love to know. Thanks!

    Read the article

  • How to draw multiple line text to uiimageview iphone?

    - by Hu?nh Phong
    I have UITextView for text, after user press DONE, I convert text to UIImageView and show it. It works with one line of text very good, and Screenshot 1 . But if user types two lines, or more: the result is still one line??? Screenshot 2 I want to display two or more lines in UIimageView Can anybody help me! Thank you very much! Here is my code: -(UIImage *)convertTextToImage : (ObjectText *) objT; { UIGraphicsBeginImageContext(CGSizeMake(([objT.content sizeWithFont:objT.font].width+10), ([objT.content sizeWithFont:objT.font].height+10))); [[objT getcolor] set]; [objT.content drawAtPoint:CGPointMake(5, 5) withFont:objT.font]; UIImage *result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return result; }

    Read the article

1 2 3  | Next Page >