void MotionArea::updateMotionResult() { vec2 hitpointVec = glm::normalize(vec2((posx1 - posx), (posy1 - posy))); angle = glm::orientedAngle(hitpointVec, vec2(-1.0, 0.0)); factor = sqrt(pow((posx1 - posx), 2.0f) + pow((posy1 - posy), 2.0f)) / radius; // cout << "angle=" << angle << " degrees=" << // ES_TO_DEGREES(angle) << " factor=" << factor << endl; }
void Interpolate( PIXEL a, PIXEL b, vector<PIXEL>& result) { int N = result.size(); vec2 step1 = vec2(b.position2D-a.position2D) / float(max(N-1,1)); vec2 current1= vec2(a.position2D); float step2 = (b.zinv-a.zinv)/float(max(N-1,1)); float current2 = a.zinv; // vec3 step3 = (b.illumination - a.illumination)/ float(max(N-1,1)); // vec3 current3 = a.illumination; vec3 step4 =(b.position3D - a.position3D)/ float(max(N-1,1)); vec3 current4= a.position3D; for( int i=0; i<N; ++i ) { result[i].position2D =ivec2(current1); result[i].zinv = current2; // result[i].illumination = current3; result[i].position3D = current4; current1 = step1+current1; current2 = step2+current2; // current3 = step3+current3; current4 = step4+current4; } }
void Graph::CreateGrid(unsigned int cols, unsigned int rows, float screenWidth, float screenHeight) { GraphVertex* vertices = new GraphVertex[cols * rows]; GraphNode** gridNodes = new GraphNode*[cols * rows]; float nodeX = screenWidth / (float)cols; float nodeY = screenHeight / (float)rows; for (unsigned int c = 0; c < cols; ++c) { for (unsigned int r = 0; r < rows; ++r) { vertices[c * rows + r].position = vec2((float)c, (float)r); } } glm::vec2 currentPos; for (unsigned int c = 0; c < cols; c++) { for (unsigned int r = 0; r < rows; r++) { gridNodes[c * rows + r] = new GraphNode(); currentPos.x = (c * nodeX) + (nodeX / 2); currentPos.y = (r * nodeY) + (nodeY / 2); gridNodes[c * rows + r]->SetPos(currentPos); gridNodes[c * rows + r]->SetLoc(vec2(c, r)); } } for (unsigned int c = 0; c < cols; c++) { for (unsigned int r = 0; r < rows; r++) { if (c != 0) { gridNodes[c * rows + r]->NewEdge(gridNodes[c * rows + r], gridNodes[(c - 1) * rows + r], 1); } if (c != cols - 1) { gridNodes[c * rows + r]->NewEdge(gridNodes[c * rows + r], gridNodes[(c + 1) * rows + r], 1); } if (r != 0) { gridNodes[c * rows + r]->NewEdge(gridNodes[c * rows + r], gridNodes[c * rows + r - 1], 1); } if (r != rows - 1) { gridNodes[c * rows + r]->NewEdge(gridNodes[c * rows + r], gridNodes[c * rows + r + 1], 1); } AddNode(gridNodes[c * rows + r]); } } m_grid = gridNodes; m_gridCols = cols; m_gridRows = rows; }
vec2 RayTracer::iPlane(const vec3& ro, const vec3& rd, const int idx) { const vec4 &pln = this->objstack[idx].vec; //t = -(ax + by + cz + d)/ (ai + bj + ck) vec3 nor = vec3(pln.xyz); float denom = glm::dot(rd, nor); if(denom > 0) return vec2(FLT_MAX, idx); float t = -1.0 *(glm::dot(ro, nor) + pln.w)/denom; return vec2(t, idx); }
void updateBullets() { // namespace resolution using namespace glm; for (int b = 0; b < MAX_BULLET; ++b) { // Don't update bullets that don't exist: if (0.0f == bullets[b].rad || true == bullets[b].onPlanet) continue; // Sum of gravitational forces: vec2 sum = vec2(0.0f); for (int p = 0; p < MAX_PLANET; ++p) { // Optimize distance check: GLfloat dx = planets[p].pos[0] - bullets[b].pos[0]; GLfloat dy = planets[p].pos[1] - bullets[b].pos[1]; GLfloat sqrDis = dx*dx + dy*dy; GLfloat sqrRadSum = planets[p].maxRad + bullets[b].rad; sqrRadSum *= sqrRadSum; // If bullet is in relative area of a planet: //float r = distance(planets[p].pos, bullets[b].pos); //if (r <= planets[p].maxRad+bullets[b].rad) if (sqrDis < sqrRadSum) { // Check if the bullet is colliding with the planet: if (CollisionDetector::checkCollision(planets[p], bullets[b])) { bullets[b].vel = vec2(0.0f); bullets[b].startTime = glutGet(GLUT_ELAPSED_TIME)/1000.0f; bullets[b].onPlanet = true; bullets[b].rad = 0.0f; break; } } // Calculate the sum of all forces of gravity: vec2 ab = normalize(planets[p].pos-bullets[b].pos); float fg = (GRAVITATIONAL*planets[p].mass*bullets[b].mass)/(sqrDis); sum = sum+fg*ab; } if (true == bullets[b].onPlanet) continue; float t1 = glutGet(GLUT_ELAPSED_TIME)/1000.0f; float t = t1 - bullets[b].startTime; bullets[b].vel = sum*t + bullets[b].vel; // Maximum velocity? if (length(bullets[b].vel) > MAX_BULLET_SPEED) bullets[b].vel = MAX_BULLET_SPEED*normalize(bullets[b].vel); bullets[b].pos = sum*t*t + bullets[b].vel*t+bullets[b].pos; } }
void Room::makeTopology() { m_cameraTopology.clear(); vec3 pos1, pos2; vec3 dir1, dir2; cv::Mat intr1, intr2; float min = 181.0f, temp_angle; int min_index = -1; //get for(size_t i = 0; i < m_cameras.size(); i++) { pos1 = m_cameras[i]->getPosition(); dir1 = m_cameras[i]->getDirVector(); intr1 = m_cameras[i]->cameraMatrix(); for(size_t j = i+1; j < m_cameras.size(); j++) { pos2 = m_cameras[j]->getPosition(); dir2 = m_cameras[j]->getDirVector(); intr2 = m_cameras[j]->cameraMatrix(); temp_angle = Line::lineAngle(vec2(dir1.x, dir1.y),vec2(dir2.x, dir2.y)); if(glm::abs(temp_angle) < min) { min = temp_angle; min_index = j; } } if(min_index != -1) { Edge edge(i,min_index, m_maxError); //edge.setFundamentalMatrix(pos1, dir1, intr1, pos2, dir2, intr2); m_cameraTopology.push_back(edge); } } resolveTopologyDuplicates(); std::cout << "new camtopology size:" << m_cameraTopology.size() << std::endl; }
// Convert mouse coordinates to game coordinates: glm::vec2 mouseToGame() { using glm::vec2; // Mouse coordinates to game coordinates: float xScale = windowWidth/float(gameWidth); float yScale = windowHeight/float(gameHeight); return vec2(mouse[0]/float(xScale),(windowHeight-mouse[1])/float(yScale)); }
vec2 RayTracer::iSphere(const vec3 &ro, const vec3 &rd, const int &idx) {//sphere obj id = 1 const vec4 &sph = this->objstack[idx].vec; vec3 co = sph.xyz-ro; if(glm::dot(co, rd) < 0) //determine by geometric solution return vec2(FLT_MAX, idx); //no intersection vec3 oc = ro-sph.xyz; float b = 2.0 * glm::dot(oc, rd); float c = glm::dot(oc,oc) - sph.w*sph.w; float h = b*b - 4.0 *c; if(h <0.0) return vec2(FLT_MAX, idx); //no intersection //pick smaller one(i.e, close one) //not (-b+sqrt(h)) /2 float sqrth = sqrt(h); float t1 = 0.5*(-b - sqrth); return vec2(t1, idx); }
Point *Geometry::make_point(float x, float y, float z, float s, float t) { auto pnt = make_point(); auto point_positions = point_attributes().find_or_create<vec3>("point_locations"); auto point_texcoords = point_attributes().find_or_create<vec2>("point_texcoords"); point_positions->put(pnt, vec3(x, y, z)); point_texcoords->put(pnt, vec2(s, t)); return pnt; }
void Interpolate(ivec2 a, ivec2 b, vector<ivec2>& result) { int N = result.size(); vec2 step = vec2(b - a) / float(max(N - 1, 1)); vec2 current(a); for (int i = 0; i<N; ++i) { result[i] = current; current += step; } }
inline bool project(const vec3 & obj, const mat4 & mvp, const vec4 & viewport, vec2 & out) { vec4 tmp = vec4(obj, 1.0f); tmp = mvp * tmp; if (tmp.w < 0) return false; tmp /= tmp.w; tmp = tmp * 0.5f + 0.5f; tmp[0] = tmp[0] * viewport[2] + viewport[0]; tmp[1] = tmp[1] * viewport[3] + viewport[1]; out = vec2(tmp); return true; }
void Picking::CalculateRayFromPixel( const glm::ivec2& pixel, const glm::ivec2& windowSize, const glm::mat4& invViewProj, Ray* outRay ) const { // Clip space coordinates for the pixel. (-1,-1) in lower left corner, (-1,1) upper left corner, (1,-1) lower right corner. const vec2 mousePosNorm = vec2( -1.0f + 2.0f * (pixel.x / static_cast<float>(windowSize.x)), 1.0f - 2.0f * (pixel.y / static_cast<float>(windowSize.y)) ); // Translating pixel at near plane and far plane to world coordinates. Z-coordinate is depth into the screen (values between -1 and 1 are in view of camera). const vec4 nearHomogeneous = invViewProj * vec4( mousePosNorm.x, mousePosNorm.y, 0.0f, 1.0f ); const vec4 farHomogeneous = invViewProj * vec4( mousePosNorm.x, mousePosNorm.y, 1.0f, 1.0f ); const vec3 nearWorld = vec3( nearHomogeneous ) / nearHomogeneous.w; const vec3 farWorld = vec3( farHomogeneous ) / farHomogeneous.w; outRay->Position = nearWorld; outRay->Direction = glm::normalize( farWorld - nearWorld ); }
void easygl::movemouse(double x, double y){ mouse = ivec2(x, y); vec3 screen=vec3(x,viewportSize.y - y,zbuf); vec3 pos= unProject(screen,dragmodelview,projection,vec4(0,0, viewportSize.x, viewportSize.y)); glmouse = vec2(pos.x,pos.y); if(dragl && screen.z != 1) { vec2 gldiff = (gllastmouse - glmouse); movement -= glm::vec3(gldiff,0); }else{ dragmodelview = modelview; glReadPixels(x,viewportSize.y - y,1,1,GL_DEPTH_COMPONENT,GL_FLOAT,&zbuf); } gllastmouse = glmouse; lastMouse = mouse; }
OpenGLWindow::OpenGLWindow(QWidget *parent) : QGLWidget(parent) { zoom = 1.0f; twoDimensions = false; mdrawJoints = mdrawLines = mdrawBones = true; roomDims = vec3(100.0f, 100.0f, 100.0f); camRot = vec3(0.0f, 0.0f, 0.0f); //mouse currentMousePos = lastMousePos = vec2(0.0f, 0.0f); leftButton = false; //QImage temp(QDir::currentPath() + "/Pictures/checkboard_texture.jpg"); //texture = QGLWidget::convertToGLFormat(temp); generateNewRandomColor(); }
vector<vec2> objLoader::getTextures()const { vector<vec2> ret; auto texStr = "vt "; auto texStrLen = string(texStr).size(); auto pos = m_data.find(texStr); auto pos2 = m_data.find("\n",pos); float x, y; while(pos != string::npos && pos2 != string::npos) { stringstream tmp(m_data.substr(pos + texStrLen, pos2 - pos - texStrLen)); tmp >> x; tmp >> y; //printf("[TEX] x:%f, y:%f\n", x, y); ret.emplace_back(vec2(x,y)); pos = m_data.find(texStr, pos + 1); pos2 = m_data.find("\n", pos); } return ret; }
void init(int planecount, t_symbol * type, int width, int height) { w = width; h = height; t_jit_matrix_info info; jit_matrix_info_default(&info); info.planecount = planecount; info.type = type; info.dimcount = 2; info.dim[0] = w; info.dim[1] = h; //info.flags |= JIT_MATRIX_DATA_PACK_TIGHT; mat = (t_object *)jit_object_new(_jit_sym_jit_matrix, &info); if (!mat) post("failed to allocate matrix"); jit_object_method(mat, _jit_sym_clear); sym = jit_symbol_unique(); jit_object_method(mat, _jit_sym_getdata, &back); mat = (t_object *)jit_object_method(mat, _jit_sym_register, sym); atom_setsym(name, sym); dim = vec2(w, h); }
bool CCamera::OnMouseMotion(const SDL_MouseMotionEvent &event) { if (m_isActive) { const vec2 delta = vec2(-event.xrel, -event.yrel); // Движение мыши по оси X изменяет рысканье (yaw), // то есть поворачивает вектор forward вокруг up. const float deltaYaw = delta.x * RADIANS_IN_PIXEL; m_forward = glm::normalize(glm::rotate(m_forward, deltaYaw, m_up)); // Движение мыши по оси Y изменяет курс (roll), // то есть поворачивает вектора up вокруг right // и восстанавливаем вектор forward. const float deltaRoll = -delta.y * RADIANS_IN_PIXEL; const vec3 right = GetRightDirection(m_up, m_forward); m_up = glm::normalize(glm::rotate(m_up, deltaRoll, right)); m_forward = GetForwardDirection(m_up, right); } return m_isActive; }
void Agent::Update(float delta) { vec3 testInput = vec3(m_position.x, m_position.y, 0); m_clock += delta; m_memoryClock += delta; float memoryFrequency = 1.f; if (m_memoryClock > memoryFrequency) { m_memoryClock -= memoryFrequency; vec3 testInput = vec3(m_position.x, m_position.y, 0); AddToMemory(testInput); m_neuralNetwork->TrainNetwork(m_memory); } m_position += m_velocity * delta; if (CheckBounds()) { m_facingDirection = 44.f / 7.f * (float)((rand() % 1000) / 1000.f); m_velocity.x = m_maxSpeed * sin(m_facingDirection); m_velocity.y = m_maxSpeed * cos(m_facingDirection); } m_neuralNetwork->RenderDebug(vec2(30, 30), 200, m_memory); m_foodClock--; m_waterClock--; }
void RayTracer::RayLoop(const int& idx, const int& NumOfThread) {//Main loop of ray tracing vec2 step = vec2(2.0)/vec2(winw, winh); //increment step /*calculate block boundary for each thread*/ vec2 thstep = vec2(2.0, winw)/vec2(NumOfThread); vec2 ubound = vec2(thstep.x*idx, thstep.x*(idx+1)) - vec2(1.0); vec2 wbound = vec2(glm::floor(thstep.y*idx), glm::floor(thstep.y*(idx+1))); int i = wbound.x; //index of canvas array for(float u = ubound.x; u< ubound.y && i< wbound.y; u+=step.x, ++i) { int j{0}; for(float v = -1.0; v< 1.0 && j<winh; v+=step.y, ++j) { vec3 rd = glm::normalize(vec3(u* 1.33,v, -1.0)); //ray direction col[i][j] = ray(ro_eye, //ray origin rd, //ray direction -1, //object index 2); //reflection times } } }
Geometries::Robot::ShoulderJoint::ShoulderJoint( ModernGDV::Driver* mgdv ) : instanceCounter( new size_t( 1U ) ), vertexBuffer( 0U ), mgdv( mgdv ), texture( nullptr ) { std::vector<Vertex> vertices; vec3 cuboidBottomFrontLeft(-0.075f, -0.05f, +0.0375f); vec3 cuboidBottomFrontRight(+0.075f, -0.05f, +0.0375f); vec3 cuboidBottomBackLeft(-0.075f, -0.05f, -0.0375f); vec3 cuboidBottomBackRight(+0.075f, -0.05f, -0.0375f); vec3 cuboidTopFrontLeft(-0.075f, +0.05f, +0.0375f); vec3 cuboidTopFrontRight(+0.075f, +0.05f, +0.0375f); vec3 cuboidTopBackLeft(-0.075f, +0.05f, -0.0375f); vec3 cuboidTopBackRight(+0.075f, +0.05f, -0.0375f); Quad::Create(vertices, cuboidBottomFrontLeft, vec2(0.f, 0.f), cuboidBottomFrontRight, vec2(1.f, 0.f), cuboidBottomBackRight, vec2(1.f, 7.5f/15.f), cuboidBottomBackLeft, vec2(0.f, 7.5f/15.f)); //Bodenfläche Quader Quad::Create(vertices, cuboidTopFrontLeft, vec2(0.f, 0.f), cuboidTopFrontRight, vec2(1.f, 0.f), cuboidBottomFrontRight, vec2(1.f, 10.f/15.f), cuboidBottomFrontLeft, vec2(0.f, 10.f/15.f)); //Seitenflächen Quader Quad::Create(vertices, cuboidTopFrontRight, vec2(0.f, 0.f), cuboidTopBackRight, vec2(7.5f/10.f, 0.f), cuboidBottomBackRight, vec2(7.5f/10.f, 1.f), cuboidBottomFrontRight, vec2(0.f, 1.f)); Quad::Create(vertices, cuboidTopBackRight, vec2(0.f, 0.f), cuboidTopBackLeft, vec2(1.f, 0.f), cuboidBottomBackLeft, vec2(1.f, 10.f/15.f), cuboidBottomBackRight, vec2(0.f, 10.f/15.f)); Quad::Create(vertices, cuboidTopBackLeft, vec2(0.f, 0.f), cuboidTopFrontLeft, vec2(7.5f/10.f, 0.f), cuboidBottomFrontLeft, vec2(7.5f/10.f, 1.f), cuboidBottomBackLeft, vec2(0.f, 1.f)); Quad::Create(vertices, cuboidTopFrontLeft, vec2(0.f, 7.5f/15.f), cuboidTopBackLeft, vec2(0.f, 0.f), cuboidTopBackRight, vec2(1.f, 0.f), cuboidTopFrontRight, vec2(1.f, 7.5f/15.f)); //Oberseite Quader vertexBuffer = mgdv->CreateVertexBuffer(vertices); texture = mgdv->GetTexture("Joint"); }
vec2 getNorthEast() const { return vec2(maxX, maxY); }
vec2 getSouthWest() const { return vec2(minX, minY); }
// Converts a radian value to a unit vector inline vec2 DirToUnitVec2(float rads) { return vec2(cos(rads), sin(rads)); }
bool PhysicsSystem::Intersect(const vec3 &start, const vec3 &end, const VolumePtr &wall, vec3 &normal, vec3 &penetration) { using glm::vec2; static const unsigned int PLANE_FRONT = 0; static const unsigned int PLANE_BACK = 1; static const unsigned int ON_PLANE = 2; float radius = 0.05f; float p; vec3 n = wall->normal; vec3 offset = vec3(0); //n * radius; // This hack for adding radius to ball does not work when walls do not form convex shape float d = -glm::dot(n, (wall->vertices[0] + offset)); unsigned int start_loc = 3; unsigned int end_loc = 3; p = glm::dot(n, start) + d; if (p > 0.0f) { start_loc = PLANE_FRONT; } else if (p < 0.0f) { start_loc = PLANE_BACK; } else { start_loc = ON_PLANE; } p = glm::dot(n, end) + d; if (p > 0.0f) { end_loc = PLANE_FRONT; } else if (p < 0.0f) { end_loc = PLANE_BACK; } else { end_loc = ON_PLANE; } /* This hack only works if the walls form a convex shape // HACK: tries to prevent ball from ever being behind a wall if (start_loc == PLANE_BACK) { TransformPtr ball_transform = transform_mapper_(ball_); BallComponentPtr ball_comp = ball_comp_mapper_(ball_); vec3 new_start = start - ball_comp->velocity * Time::GetDeltaTime(); ball_transform->set_position(new_start); return false; } */ //MeshPtr mesh;// = EntityManager::GetComponent<Mesh>(wall_map_[wall], "Mesh"); //shared_ptr<BasicMaterial> bm;// = boost::dynamic_pointer_cast<BasicMaterial>(mesh->material); //bm->Ld_ = vec3(1, 0, 0); if (start_loc == end_loc) { return false; } //mesh = mesh_mapper_(wall_map_[wall]); //bm = boost::dynamic_pointer_cast<BasicMaterial>(mesh->material); //bm->Ld_ = vec3(1, 0, 1); vec3 ray = end - start; ray = glm::normalize(ray); float t = - (d + glm::dot(n, start)) / glm::dot(n, ray); vec3 intersect = start + (t * ray); bool x_axis = false; if (glm::abs(n.x) < glm::abs(n.z)) { x_axis = true; } vec2 pos; if (x_axis) { pos = vec2(intersect.x, intersect.y); } else { pos = vec2(intersect.z, intersect.y); } vec2 vert; vector<vec2> vertices; vector<vec3>::const_iterator it; for (it = wall->vertices.begin(); it != wall->vertices.end(); ++it) { if (x_axis) { vert = vec2(it->x, it->y); vert += vec2(offset.x, offset.y); vertices.push_back(vert); } else { vert = vec2(it->z, it->y); vert += vec2(offset.z, offset.y); vertices.push_back(vert); } } normal = n; penetration = intersect; bool result = PointInPolygon(pos, vertices); //if (result) { //mesh = mesh_mapper_(wall_map_[wall]); //bm = boost::dynamic_pointer_cast<BasicMaterial>(mesh->material); //bm->Ld_ = vec3(1, 1, 1); //} return result; }
bool PhysicsSystem::UpdateTile(const TransformPtr &ball_transform, const BallComponentPtr &ball_comp, const EntityPtr &tile, const int &depth) { using glm::vec2; TileComponentPtr tile_comp = tile_comp_mapper_(tile); VolumePtr tile_volume = volume_mapper_(tile); if (depth < 0) { return false; } vec3 v; vec2 p; vector<vec2> projected_vertices; for (int j = 0, sizej = tile_volume->vertices.size(); j < sizej; ++j) { v = tile_volume->vertices[j]; p = vec2(v.x, v.z); projected_vertices.push_back(p); } vec2 point(ball_transform->position().x, ball_transform->position().z); MeshPtr mesh = mesh_mapper_(tile); shared_ptr<BasicMaterial> bm = boost::dynamic_pointer_cast<BasicMaterial>(mesh->material); // is ball in this tile? if (PointInPolygon(point, projected_vertices)) { // color tile yellow bm->Ld_ = vec3(1, 1, 0); ProjectToSlope(ball_transform, ball_comp, tile); // set ball's current tile ball_comp->current_tile = tile; return true; } else { bm->Ld_ = vec3(0, 1, 0); vector<EntityPtr>::iterator it, ite; for (it = tile_comp->neighbors.begin(), ite = tile_comp->neighbors.end(); it != ite; ++it) { if (UpdateTile(ball_transform, ball_comp, *it, depth - 1)) { return true; } } /* // This hack is broken ball_comp->velocity = vec3(0); ball_comp->acceleration = vec3(0); VolumePtr volume = volume_mapper_(ball_comp->current_tile); int N = volume->vertices.size(); vec3 position(0); vector<vec3>::iterator jt, jte; for (jt = volume->vertices.begin(), jte = volume->vertices.end(); jt != jte; ++jt) { position += (*jt); } position /= N; ball_transform->set_position(position); ProjectToSlope(ball_transform, ball_comp, ball_comp->current_tile); */ return false; } /* float radius = 0.05f; VolumePtr curr_volume = tile_vols_[0]; // move ball up slopes using projections vec3 proj = Project(ball_transform->position(), curr_volume->normal, curr_volume->vertices[0]); ball_transform->set_position(proj); ball_transform->Translate(curr_volume->normal * radius); // loop through neighbors for (int i = 1, size = tile_vols_.size(); i < size; ++i) { VolumePtr neigh = tile_vols_[i]; // project neighbors vertices to xz plane vector<vec2> projected_vertices; for (int j = 0, sizej = neigh->vertices.size(); j < sizej; ++j) { vec3 v = neigh->vertices[j]; vec2 p(v.x, v.z); projected_vertices.push_back(p); } // project ball to xz plane vec2 point(ball_transform->position().x, ball_transform->position().z); // check to see if ball overlaps neighbor bool inter = PointInPolygon(point, projected_vertices); // does ball overlap? if (inter) { // set current ball to overlapped neighbor MeshPtr mesh = mesh_mapper_(ball_comp->current_tile); shared_ptr<BasicMaterial> bm = boost::dynamic_pointer_cast<BasicMaterial>(mesh->material); bm->Ld_ = vec3(0, 1, 0); //ball_comp->current_tile = curr_tile->neighbors[i - 1]; break; } } */ }
// Model method bool BVHM::intersect(Intersection &its, const Ray &ray) { using glm::vec2; using glm::vec3; vec2 t = vec2(-5000.0, 10000.0); vec3 halfv = (max - min) / 2.0f; vec3 ac = min + halfv; vec3 p = ac - ray.o; float h[3] = { halfv.x, halfv.y, halfv.z }; vec3 a[3] = { vec3(1, 0, 0), vec3(0, 1, 0), vec3(0, 0, 1) }; // Ray OBB intersection test for (int i = 0; i < 3; i++) { float e = glm::dot(a[i], p); float f = glm::dot(a[i], ray.d); if (abs(f) > EPSILON) { float t1 = (EPSILON + h[i]) / f; float t2 = (EPSILON - h[i]) / f; if (t1 > t2) { float temp = t1; t1 = t2; t2 = temp; } if (t1 > t.x) { t.x = t1; } if (t2 < t.y) { t.y = t2; } if (t.x > t.y || t.y < 0) { return false; } } else if (-EPSILON - h[i] > 0 || -EPSILON + h[i] < 0) { return false; } } // Test for child obb intersection if (left || right) { Intersection lft = Intersection(); Intersection rht = Intersection(); bool checkl = left->intersect(lft, ray); bool checkr = right->intersect(rht, ray); if (checkl && checkr) { if (lft.t < rht.t) { its = lft; return checkl; } its = rht; return checkr; } else if (checkl) { its = lft; return true; } else if (checkr) { its = rht; return true; } else { return false; } } else { // Test for triangle obb intersections Intersection first = Intersection(); first.t = INFINITY; bool pass = false; for (auto &o : obbs) { Intersection test = Intersection(); Ray tray = ray; glm::mat4 m = o.ModelMatrix; bool check = o.bvht->intersect(m, test, tray); if (test.t < first.t && check) { first = test; first.model = &o; pass |= check; } } its = first; return pass; } }
bool BVHT::intersect(glm::mat4 m, Intersection &its, const Ray &ray) { using glm::vec2; using glm::vec3; vec3 fmax = vec3(m * glm::vec4(max, 1)); vec3 fmin = vec3(m * glm::vec4(min, 1)); vec2 t = vec2(-5000.0, 10000.0); vec3 halfv = (fmax - fmin) / 2.0f; vec3 ac = min + halfv; vec3 p = ac - ray.o; float h[3] = { halfv.x, halfv.y, halfv.z }; vec3 a[3] = { vec3(1, 0, 0), vec3(0, 1, 0), vec3(0, 0, 1) }; // Ray OBB intersection test for (int i = 0; i < 3; i++) { float e = glm::dot(a[i], p); float f = glm::dot(a[i], ray.d); if (abs(f) > EPSILON) { float t1 = (EPSILON + h[i]) / f; float t2 = (EPSILON - h[i]) / f; if (t1 > t2) { float temp = t1; t1 = t2; t2 = temp; } if (t1 > t.x) { t.x = t1; } if (t2 < t.y) { t.y = t2; } if (t.x > t.y || t.y < 0) { return false; } } else if (-EPSILON - h[i] > 0 || -EPSILON + h[i] < 0) { return false; } } //printVec(min); //printVec(max); if (left || right) { Intersection lft = Intersection(); Intersection rht = Intersection(); bool checkl = left->intersect(m, lft, ray); bool checkr = right->intersect(m, rht, ray); if (checkl && checkr) { if (lft.t < rht.t) { its = lft; return checkl; } its = rht; return checkr; } else if (checkl) { its = lft; return true; } else if (checkr) { its = rht; return true; } else { return false; } } else { // Test for triangle intersection Intersection first = Intersection(); first.t = INFINITY; bool pass = false; for (auto &t : tris) { Intersection test = Intersection(); bool check = ::intersect(m, t, test, ray); if (check) int i = 0; if (test.t < first.t && check) { first = test; pass |= check; } } its = first; return pass; } }
vec2 Graph::GetGridDimentions() { return vec2(float(m_gridCols), float(m_gridRows)); }
GLuint GameTexture::Sky1Id, GameTexture::Sky2Id, GameTexture::Sky3Id, GameTexture::Sky4Id, GameTexture::SkyupId; GLuint GameTexture::RedScalesId, GameTexture::Fur1Id, GameTexture::Morran; GLuint GameTexture::LanternSideId, GameTexture::Teleport; GLuint GameTexture::LightBallsHeal, GameTexture::InventoryId, GameTexture::EquipmentId; GLuint GameTexture::RedColor, GameTexture::GreenColor, GameTexture::BlueColor, GameTexture::DarkGray; GLuint GameTexture::RedChunkBorder, GameTexture::BlueChunkBorder, GameTexture::GreenChunkBorder; GLuint GameTexture::CompassRose, GameTexture::DamageIndication; GLuint GameTexture::WEP1, GameTexture::WEP2, GameTexture::WEP3, GameTexture::WEP4; GLuint GameTexture::Coin, GameTexture::Quest; GLuint GameTexture::WEP1Text, GameTexture::WEP2Text, GameTexture::WEP3Text, GameTexture::WEP4Text; GLuint GameTexture::PoissonDisk; using glm::vec2; // This table is from http://asawicki.info/Download/Productions/Applications/PoissonDiscGenerator/2D.txt const vec2 gPoissonDisk[64] = { vec2( 0.282571, 0.023957 ), vec2( 0.792657, 0.945738 ), vec2( 0.922361, 0.411756 ), vec2( 0.165838, 0.552995 ), vec2( 0.566027, 0.216651 ), vec2( 0.335398, 0.783654 ), vec2( 0.0190741, 0.318522 ), vec2( 0.647572, 0.581896 ), vec2( 0.916288, 0.0120243 ), vec2( 0.0278329, 0.866634 ), vec2( 0.398053, 0.4214 ), vec2( 0.00289926, 0.051149 ), vec2( 0.517624, 0.989044 ), vec2( 0.963744, 0.719901 ), vec2( 0.76867, 0.018128 ), vec2( 0.684194, 0.167302 ),
int main() { //initialize the opengl window if (glfwInit() == false) return -1; GLFWwindow* window = glfwCreateWindow(1280, 720, "Computer Graphics", nullptr, nullptr); if (window == nullptr) { glfwTerminate(); return -2; } glfwMakeContextCurrent(window); //the rest of our code goes here! if (ogl_LoadFunctions() == ogl_LOAD_FAILED) { glfwDestroyWindow(window); glfwTerminate(); return -3; } //testing what version of OpenGL we are running auto major = ogl_GetMajorVersion(); auto minor = ogl_GetMinorVersion(); printf_s("GL: %i.%i\n", major, minor); //int imageWidth = 0, imageHeight = 0, imageFormat = 0; //unsigned char* data = stbi_load("crate.png", &imageWidth, &imageHeight, &imageFormat, STBI_default); //done initialize window and OpenGL //BEGIN SHADER SETUP string vshader = LoadShader("VertexShader.vert"); string fshader = LoadShader("FragmentShader.frag"); const char* vsSource = vshader.c_str(); const char* fsSource = fshader.c_str(); unsigned int vs = glCreateShader(GL_VERTEX_SHADER); unsigned int fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(vs, 1, (const char**)&vsSource, 0); glCompileShader(vs); glShaderSource(fs, 1, (const char**)&fsSource, 0); glCompileShader(fs); m_shader = glCreateProgram(); glAttachShader(m_shader, vs); glAttachShader(m_shader, fs); glBindAttribLocation(m_shader, 0, "Position"); glBindAttribLocation(m_shader, 1, "TexCoord"); glLinkProgram(m_shader); int success = GL_FALSE; glGetProgramiv(m_shader, GL_LINK_STATUS, &success); if (success == GL_FALSE) { int infoLogLength = 0; glGetShaderiv(m_shader, GL_INFO_LOG_LENGTH, &infoLogLength); char* infoLog = new char[infoLogLength]; glGetShaderInfoLog(m_shader, infoLogLength, 0, infoLog); printf("Error: Failed to link Gizmo shader program!\n%s\n", infoLog); delete[] infoLog; } //END SHADER SETUP int dims = 64; float *perlin_data = new float[dims * dims]; float scale = (1.0f / dims) * 3; for (int x = 0; x < 64; ++x) { for (int y = 0; y < 64; ++y) { perlin_data[y* dims + x] = glm::perlin(vec2(x, y) * scale) * 0.5f + 0.5f; } } //PLANE GENERATION int rows = 64; int cols = 64; // create opengl data for a grid Vertex* vertices = new Vertex[rows * cols]; for (int r = 0; r < rows; ++r) { for (int c = 0; c < cols; ++c) { // offset position so that the terrain is centered vertices[r * cols + c].position = vec4(c - cols * 0.5f, 0, r - rows * 0.5f, 1); // setting up UVs vertices[r * cols + c].texCoord = vec2(c * (1.f / cols), r * (1.f / rows)); } } // keep track of number of indices for rendering int m_indexCount = (rows - 1) * (cols - 1) * 6; unsigned int* indices = new unsigned int[m_indexCount]; unsigned int index = 0; for (int r = 0; r < (rows - 1); ++r) { for (int c = 0; c < (cols - 1); ++c) { // triangle 1 indices[index++] = r * cols + c; indices[index++] = (r + 1) * cols + c; indices[index++] = (r + 1) * cols + (c + 1); // triangle 2 indices[index++] = r * cols + c; indices[index++] = (r + 1) * cols + (c + 1); indices[index++] = r * cols + (c + 1); } } //BUFFER GENERATION // generate buffers glGenBuffers(1, &m_VBO); glGenBuffers(1, &m_IBO); // generate vertex array object (descriptors) glGenVertexArrays(1, &m_VAO); // all changes will apply to this handle glBindVertexArray(m_VAO); // set vertex buffer data glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData( GL_ARRAY_BUFFER, //type of buffer to bind to (rows * cols) * sizeof(Vertex), //how large should the buffer be //in this example we have 64 * 64 elements //they are of size (Vertex) which is the size of a glm::vec4 and a glm::vec2 vertices, //the actual data GL_STATIC_DRAW); // index data glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_indexCount * sizeof(unsigned int), indices, GL_STATIC_DRAW); // position glEnableVertexAttribArray(0); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); // texcoords glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(vec4)); // safety glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); /* In order to see our generated data, we are going to create a texture, fill it with the noise data, and display it on our quad*/ glGenTextures(1, &m_perlin_texture); glBindTexture(GL_TEXTURE_2D, m_perlin_texture); // bind data as float for a single channel glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, dims, dims, 0, GL_RED, GL_FLOAT, perlin_data); // enable blending else samples must be "exact" centre of texels glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // set wrap to stop errors at edge of noise sampling glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // unbind texture glBindTexture(GL_TEXTURE_2D, 0); //setup some matricesa mat4 m_model = mat4(); mat4 m_view = lookAt(vec3(120.0, 80.0, 120.0), vec3(0.0, 0.0, 0.0), vec3(0.0, 1.0, 0.0)); mat4 m_projection = glm::perspective(glm::pi<float>()*0.25f, 16 / 9.f, 0.1f, 1000.f); mat4 m_projectionViewMatrix = m_projection * m_view; //end setup matrices unsigned int projectionViewUniform = glGetUniformLocation(m_shader, "ProjectionViewModel"); //start using shader... glUseProgram(m_shader); //because we are sending it to the uniform with this function glUniformMatrix4fv(projectionViewUniform, 1, false, value_ptr(m_projectionViewMatrix)); GLfloat height = glGetUniformLocation(m_shader, "heightScale"); int texUniform = glGetUniformLocation(m_shader, "noiseTexture"); glUniform1i(texUniform, 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_perlin_texture); int i = 0; bool rise = true;; while (glfwWindowShouldClose(window) == false && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS) { glClearColor(0.25f, 0.25f, 0.25f, 1); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUniform1f(height, i); if (i >= dims) { rise = false; } else if (i <= -dims / 2) { rise = true; } if (rise == true) { i += 5; } else { i-=2; } unsigned int modelID = glGetUniformLocation(m_shader, "Model"); //float time = glfwGetTime(); //m_model = rotate(mat4(), 5.0f * cos(time), vec3(0, 1, 0)); glUniformMatrix4fv(modelID, 1, false, value_ptr(m_model)); glBindVertexArray(m_VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO); //draw glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, nullptr); //unbind glBindVertexArray(0); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; }