Example #1
0
void Camera2D::reset()
{
    pos = vec2f(0, 0);
    zoom = 55.0f;
}
vec2f Platform::getMousePosition()
{
	return vec2f(deviceState.x, deviceState.y);
}
Example #3
0
void Gource::processCommit(const RCommit& commit, float t) {

    //find user of this commit or create them
    RUser* user = 0;

    //see if user already exists but if not wait until
    //we actually use one of their files before adding them
    std::map<std::string, RUser*>::iterator seen_user = users.find(commit.username);
    if(seen_user != users.end()) user = seen_user->second;

    //find files of this commit or create it
    for(std::list<RCommitFile>::const_iterator it = commit.files.begin(); it != commit.files.end(); it++) {

        const RCommitFile& cf = *it;

        bool filtered_filename = false;

        //check filename against filters
        for(std::vector<Regex*>::iterator ri = filters.begin(); ri != filters.end(); ri++) {
            Regex* r = *ri;

            if(r->match(cf.filename)) {
                filtered_filename = true;
                break;
            }
        }

        if(filtered_filename) continue;

        std::map<std::string, RFile*>::iterator seen_file;

        seen_file = files.find(cf.filename);

        RFile* file = 0;

        if(seen_file != files.end()) {

            file = seen_file->second;

        } else {

            //if we already have max files in circulation
            //we cant add any more
            if(static_cast<int>(files.size()) >= gGourceMaxFiles) continue;

            int tagid = tag_seq++;

            file = new RFile(cf.filename, cf.colour, vec2f(0.0,0.0), tagid);

            files[cf.filename] = file;
            tagfilemap[tagid]  = file;

            root->addFile(file);

            while(root->getParent() != 0) {
                debugLog("parent changed to %s\n", root->getPath().c_str());
                root = root->getParent();
            }
        }

        //create user if havent yet. do it here to ensure at least one of there files
        //was added (incase we hit gGourceMaxFiles!)

        if(user == 0) {
            vec2f pos;

            if(dir_bounds.area() > 0) {
                pos = dir_bounds.centre();
            } else {
                pos = vec2f(0,0);
            }

            int tagid = tag_seq++;

            user = new RUser(commit.username, pos, tagid);

            users[commit.username] = user;
            tagusermap[tagid]     = user;

            if(gGourceHighlightAllUsers) {
                user->setHighlighted(true);
            } else {

                // set the highlighted flag if name matches a highlighted user
                for(std::vector<std::string>::iterator hi = highlight_users.begin(); hi != highlight_users.end(); hi++) {
                    std::string highlight = *hi;

                    if(highlight.size() && user->getName() == highlight) {
                        user->setHighlighted(true);
                        break;
                    }
                }
            }

            debugLog("added user %s, tagid = %d\n", commit.username.c_str(), tagid);
        }

        //create action

        RAction* action = 0;

        int commitNo = commit_seq++;

        if(cf.action == "D") {
            action = new RemoveAction(user, file, t);
        } else {
            if(cf.action == "A") {
                action = new CreateAction(user, file, t);
            } else {
                action = new ModifyAction(user, file, t);
            }
        }

        user->addAction(action);
    }
}
Example #4
0
vec2f Entity::getCollisionRectCenterPosition()
{
	return vec2f(_collisionRect.x + _collisionRect.w / 2, _collisionRect.y + + _collisionRect.h / 2);
}
Example #5
0
void Player::processKeys(float deltaTime) {
    World* w = (World*)getGame()->getObjectByName("world");
    //Move player
    const float speedKeys = 30.0f*deltaTime;
    vec2f speedPad = vec2f(Gamepad::axis(0, Gamepad::AxisLeftX), Gamepad::axis(0, Gamepad::AxisLeftY));
    vec2f dir = vec2f(cam->getForward().x,cam->getForward().z);
    dir = (dir == vec2f(0.0f))? vec2f(1.0f,0.0f) : glm::normalize(dir);
    if(Keyboard::pressed(Keyboard::W)) {
        disp.x += dir.x*speedKeys;
        disp.z += dir.y*speedKeys;
    }
    if(Keyboard::pressed(Keyboard::S)) {
        disp.x += -dir.x*speedKeys;
        disp.z += -dir.y*speedKeys;
    }
    if(Keyboard::pressed(Keyboard::A)) {
        disp.x += dir.y*speedKeys;
        disp.z += -dir.x*speedKeys;
    }
    if(Keyboard::pressed(Keyboard::D)) {
        disp.x += -dir.y*speedKeys;
        disp.z += dir.x*speedKeys;
    }
    if(glm::length(speedPad) > 0.3f) {
        disp.x += -dir.x*speedPad.y*speedKeys;
        disp.z += -dir.y*speedPad.y*speedKeys;
        disp.x += -dir.y*speedPad.x*speedKeys;
        disp.z += dir.x*speedPad.x*speedKeys;
    }
    if(Keyboard::pressed(Keyboard::Space) || Gamepad::pressed(0, Gamepad::ButtonA))
        //if (onFloor && !isJumping)
        disp.y = 15;

    //look around
    vec2f displacement = glm::radians(vec2f(Mouse::movement())*0.1f);
    vec2f padDisplacement = vec2f(Gamepad::axis(0, Gamepad::AxisRightX), Gamepad::axis(0, Gamepad::AxisRightY));
    if(glm::length(padDisplacement) > 0.3f) //death zone
        displacement += glm::radians(padDisplacement * 2.0f);

    cam->rotateGlobal(displacement.x, vec3f(0,1,0));
    //limit x rotation
    if(glm::degrees(std::abs(xRot+displacement.y)) < 90.0f) {
        cam->rotateLocal(displacement.y, vec3f(1,0,0));
        xRot += displacement.y;
    }

    //take block
    if(Mouse::justPressed(Mouse::Left) && targetsBlock)
        w->setCubeRange(targetedBlock-vec3i(5), vec3i(11), 0);

    //put block
    if(Mouse::justPressed(Mouse::Right) && targetsBlock) {
        w->setCube(targetedBlockEnter.x,targetedBlockEnter.y,targetedBlockEnter.z,4);
        vec3f pos = vec3f(targetedBlockEnter)+vec3f(0.5f);
        DeferredCubeLight* l = new DeferredCubeLight(pos, glm::abs(glm::sphericalRand(1.0f)));
        l->addTo(w);
    }

    if(Keyboard::justPressed(Keyboard::R) && targetsBlock) {
        w->setCube(targetedBlockEnter.x,targetedBlockEnter.y,targetedBlockEnter.z,4);
        vec3f pos = vec3f(targetedBlockEnter)+vec3f(0.5f);
        DeferredCubeLight* l = new DeferredCubeLight(pos, vec3f(1,0,0));
        l->addTo(w);
    }

    if(Keyboard::justPressed(Keyboard::B) && targetsBlock) {
        w->setCube(targetedBlockEnter.x,targetedBlockEnter.y,targetedBlockEnter.z,4);
        vec3f pos = vec3f(targetedBlockEnter)+vec3f(0.5f);
        DeferredCubeLight* l = new DeferredCubeLight(pos, vec3f(0,0,1));
        l->addTo(w);
    }
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function Name: CheckStaticCollisions()
// Purpose: Check collisions with all static objects
// Original Author: Ethan Pendergraft
// Creation Date: 6/13/2012
// Last Modification By: 
// Last Modification Date: 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void CComponent_CrateCollision::CheckStaticCollisions( CComponent_Collision* pCurCollision, CCollisionVolume* pCurVolume, float fDT )
{
	Box* BoxCollisionVolume = (Box*)m_pParent->GetCollidableObject();
	vec2f Contact;
	vec2f Direction;

	switch( pCurVolume->GetVolumeType() )
	{
	case VMT_AABB:
		{
			// handle crate collision
			// with world AABB
			if ( BoxCollisionVolume->BoxToAABBWorld( *(AABB*)pCurVolume, Contact, Direction ) )
			{
				// Create an offset vector.
				vec3f MoveDirection = vec3f (Direction.x, Direction.y, 0.0f);

				//Save the last offset for use elsewhere.
				m_fLastOffset = vec3f( Direction.x, Direction.y, 0.0f );

				// If it has a physics Box.
				//if(!m_bPlayed && !m_bCollideSoundCap)
				//{
				//	if(m_nCollisionCount < 5)
				//	{
				//		m_pSoundComponent->PlaySound(SFX_CRATE_CRASH);
				//		m_bPlayed = true;
				//		++m_nCollisionCount;
				//	}
				//	else
				//	{
				//		m_bCollideSoundCap = true;
				//	}
				//}

				////////// FRICTION
				vec3f fCross;
				cross_product( fCross, MoveDirection, vec3f( 0.0f, 0.0f, 1.0f ) );
				float3 fProj = prjPoint2Line( m_pPhysicsBox->m_pPoints[0]->m_CurrPos, m_pPhysicsBox->m_pPoints[0]->m_PrevPos, m_pPhysicsBox->m_pPoints[0]->m_PrevPos + fCross );
				float3 fPrevPush = fProj - m_pPhysicsBox->m_pPoints[0]->m_PrevPos;
				fPrevPush *= -0.1f;
				//////////

				vec3f NormalizedDirection = vec3f (Direction.x, Direction.y, 0.0f).normalize();
				float fDotProductUp = dot_product( NormalizedDirection, vec3f( 0.0f, 1.0f, 0.0f ) );
				float fDotProductSide = dot_product( NormalizedDirection, vec3f( 1.0f, 0.0f, 0.0f ) );
				if( fDotProductUp > 0.5f )
				{
					m_bCollidingGround = true;
				}
				if( abs( fDotProductSide ) > 0.5f )
				{
					fPrevPush = vec3f( 0.0f, 0.0f, 0.0f );
				}
				
				CleanOffset( vec2f( MoveDirection.x, MoveDirection.y ) );
				CleanForce( vec2f( fPrevPush.x, fPrevPush.y ) + vec2f( MoveDirection.x, MoveDirection.y ) * 0.1f );
				m_bCol = true;
			}
			break;
		}
	default:
		break;
	}
}
Example #7
0
 inline vec2f fromTileCoords(vec2f pos) const { return vec2f(pos.x*m_tileSize, pos.y*m_tileSize); }
Example #8
0
int main ()
{
  printf ("Results of xmesh_saver_test:\n");
  
  try
  {
    VertexStream vs1 (4, make_vertex_declaration<CustomVertex> ());    

    CustomVertex* verts1 = vs1.Data<CustomVertex> ();

    if (verts1)
    {
      for (uint32_t i=0; i<vs1.Size (); i++)
      {
        verts1 [i].position  = vec3f  ((float)i, (float)i * 2, (float)i * 3);
        verts1 [i].normal    = vec3f  ((float)(i & 1), (float)((i + 1) & 1), 0);
        verts1 [i].texcoord0 = vec2f  (0, -(float)i, 0);
        verts1 [i].color     = vec4ub (0, i, 0, i);
        verts1 [i].tangent   = vec3f  (1.0f, 0.0f, 0.0f);
      }
    }
    
    VertexWeightStream vws (5);
    
    VertexWeight* weights = vws.Data ();
    
    for (uint32_t i=0; i<vws.Size (); i++)
    {
      weights [i].joint_index  = i;
      weights [i].joint_weight = float (i) / float (vws.Size ());
    }
    
    typedef Vertex<VertexInfluence, Position3f> MyVertex;
    
    VertexStream vs2 (4, make_vertex_declaration<MyVertex> ());
    
    MyVertex* verts2 = vs2.Data<MyVertex> ();
    
    if (verts2)
    {
      for (uint32_t i=0; i<vs1.Size (); i++)
      {
        verts2 [i].first_weight  = i;
        verts2 [i].weights_count = 1;
        verts2 [i].position      = 0.0f;
      }
    }
    
    IndexBuffer ib (5);
    
    for (uint32_t i=0; i<ib.Size (); i++)
      ib.Data<unsigned int> () [i] = i;

    Mesh mesh1;

    mesh1.Rename ("mesh1");
    
    VertexBuffer vb1;
    
    vb1.Attach (vs1);

    mesh1.Attach (vb1);
    mesh1.Attach (ib);
    
    mesh1.AddPrimitive (PrimitiveType_TriangleList, 0, 0, 1, "material1");
    mesh1.AddPrimitive (PrimitiveType_TriangleStrip, 0, 1, 1, "material2");

    Mesh mesh2;
    
    mesh2.Rename ("mesh2");
    
    VertexBuffer vb2;
    
    vb2.Attach (vs1);
    vb2.Attach (vs2);
    vb2.AttachWeights (vws);
    
    mesh2.Attach (vb2);
    
    mesh2.AddPrimitive (PrimitiveType_LineList, 0, 0, 1, "material1");
    mesh2.AddPrimitive (PrimitiveType_LineStrip, 0, 1, 2, "material2");    

    MeshLibrary mesh_library;

    mesh_library.Rename ("my_mesh_library");
    
    mesh_library.Attach ("mesh1", mesh1);
    mesh_library.Attach ("mesh2", mesh2);

    mesh_library.Save (DST_FILE_NAME);
  }
  catch (std::exception& exception)
  {
    printf ("exception: %s\n", exception.what ());
  }

  return 0;
}
Example #9
0
void Player::die() {
    deathCount++;
    invulTime = 2.5;
    position = stage->getPosition()+vec2f(0, 200);
}
	void AttackMoveOrders::move( float deltaTime )
	{
		if( m_unit )
		{
			if( m_currentPathIndex >= 0 && m_currentTargetEntity == nullptr )
			{				
				m_currentGoal = vec2f( (float)m_path[ m_currentPathIndex ].x, (float)m_path[ m_currentPathIndex ].y );
			}
			else if( m_currentPathToTargetIndex >= 0 && m_currentTargetEntity != nullptr )
			{
				m_currentGoal = vec2f( (float)m_pathToTargetEntity[ m_currentPathToTargetIndex ].x, 
					(float)m_pathToTargetEntity[ m_currentPathToTargetIndex ].y );
			}
			else if( m_needNewNaiveTarget || m_currentTargetEntity != nullptr )
			{
				m_currentGoal = getNextNaiveTarget( m_unit->m_position );
				m_needNewNaiveTarget = false;
			}

			vec2f dir = m_currentGoal - m_unit->m_position;
			dir.normalize();
			vec2f dx = dir * m_unit->m_movement.speed * deltaTime;
			vec2f newPos = m_unit->m_position + dx;

			m_unit->setPosition( newPos );

			vec2f delta = m_unit->m_position - m_currentGoal;
			float distSqrd = delta.dot( delta );
			if( distSqrd < m_tolerance )
			{
				if( m_currentPathIndex >= 0 && m_recievedPath && m_currentTargetEntity == nullptr  )
				{
					--m_currentPathIndex;
					if( m_currentPathIndex < 0 )
						m_ordersComplete = true;
				}
				else if( m_currentTargetEntity == nullptr )
				{
					delta = m_currentGoal - m_finalTargetLocation;
					distSqrd = delta.dot( delta );
					if( distSqrd < m_finalTargetTolerance )
						m_ordersComplete = true;
					else
						m_needNewNaiveTarget = true;
				}
				else
				{
					if( m_currentPathToTargetIndex >= 0 && m_recievedPathToTarget )
					{
						--m_currentPathToTargetIndex;						
					}
					else
					{
						delta = m_currentGoal - m_targetLocation;
						distSqrd = delta.dot( delta );
						if( distSqrd >= m_tolerance )
							m_needNewNaiveTarget = true;
					}
				}
			}
		}
	}
Example #11
0
void Gource::draw(float t, float dt) {

    display.mode2D();

    drawBackground(dt);

    if(draw_loading) {
        loadingScreen();
        draw_loading = false;
        return;
    }

    Frustum frustum(camera);

    trace_time = SDL_GetTicks();

    mousetrace(frustum,dt);

    trace_time = SDL_GetTicks() - trace_time;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    camera.focus();

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    //draw tree
    drawTree(frustum, dt);

    glColor4f(1.0, 1.0, 0.0, 1.0);
    for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) {
        trace_debug ? it->second->drawSimple(dt) : it->second->draw(dt);
    }

    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);

    //draw bloom
    drawBloom(frustum, dt);

    root->drawNames(font,frustum);

    if(!(gGourceSettings.hide_usernames || gGourceSettings.hide_users)) {
        for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) {
            it->second->drawName();
        }
    }

    //draw selected item names again so they are over the top
    if(selectedUser !=0) selectedUser->drawName();

    if(selectedFile !=0) {
        vec2f dirpos = selectedFile->getDir()->getPos();

        glPushMatrix();
            glTranslatef(dirpos.x, dirpos.y, 0.0);
            selectedFile->drawName();
        glPopMatrix();
    }

    if(debug) {
        glDisable(GL_TEXTURE_2D);
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

        track_users ? user_bounds.draw() : dir_bounds.draw();
    }

    if(gGourceQuadTreeDebug) {
        glDisable(GL_TEXTURE_2D);
        glColor4f(0.0f, 1.0f, 0.0f, 1.0f);

        glLineWidth(1.0);
        dirNodeTree->outline();

        glColor4f(0.0f, 1.0f, 1.0f, 1.0f);

        userTree->outline();
    }

    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

    display.mode2D();

    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);
    glEnable(GL_TEXTURE_2D);

    vec3f campos = camera.getPos();

    if(logotex!=0) {
        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glEnable(GL_BLEND);
        glEnable(GL_TEXTURE_2D);

        glColor4f(1.0, 1.0, 1.0, 1.0);

        glBindTexture(GL_TEXTURE_2D, logotex->textureid);

        vec2f logopos = vec2f(display.width, display.height) - vec2f(logotex->w, logotex->h) - gGourceSettings.logo_offset;

        glPushMatrix();

            glTranslatef(logopos.x, logopos.y, 0.0);

            glBegin(GL_QUADS);
                glTexCoord2f(0.0f,0.0f);
                glVertex2i(0, 0);

                glTexCoord2f(1.0f,0.0f);
                glVertex2i(logotex->w, 0);

                glTexCoord2f(1.0f,1.0f);
                glVertex2i(logotex->w, logotex->h);

                glTexCoord2f(0.0f,1.0f);
                glVertex2i(0, logotex->h);
            glEnd();

        glPopMatrix();
    }

    if(splash>0.0f) {
        int logowidth = fontlarge.getWidth("Gource");
        int logoheight = 100;
        int cwidth    = font.getWidth("Software Version Control Visualization");
        int awidth    = font.getWidth("(C) 2009 Andrew Caudwell");

        vec2f corner(display.width/2 - logowidth/2 - 30.0f, display.height/2 - 40);

        glDisable(GL_TEXTURE_2D);
        glColor4f(0.0f, 0.5f, 1.0f, splash * 0.015f);
        glBegin(GL_QUADS);
            glVertex2f(0.0f,                 corner.y);
            glVertex2f(0.0f,                 corner.y + logoheight);
            glVertex2f(display.width, corner.y + logoheight);
            glVertex2f(display.width, corner.y);
        glEnd();

        glEnable(GL_TEXTURE_2D);

        glColor4f(1.0,1.0,1.0,1.0);
        fontlarge.draw(display.width/2 - logowidth/2,display.height/2 - 30, "Gource");
        font.draw(display.width/2 - cwidth/2,display.height/2 + 10, "Software Version Control Visualization");
        font.draw(display.width/2 - awidth/2,display.height/2 + 30, "(C) 2009 Andrew Caudwell");
    }

    // text using the specified font goes here

    glColor4f(gGourceSettings.font_colour.x, gGourceSettings.font_colour.y, gGourceSettings.font_colour.z, 1.0f);

    if(!gGourceSettings.hide_date) {
        fontmedium.draw(display.width/2 - date_x_offset, 20, displaydate);
    }

    if(gGourceSettings.title.size()>0) {
        fontmedium.alignTop(false);
        fontmedium.draw(10, display.height - 10, gGourceSettings.title);
        fontmedium.alignTop(true);
    }

    if(message_timer>0.0f) {
         fontmedium.draw(1, 3, message);
    }

    // end text

    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

    if(debug) {
        font.print(1,20, "FPS: %.2f", fps);
        font.print(1,40,"Days Per Second: %.2f",
            gGourceSettings.days_per_second);
        font.print(1,60,"Time Scale: %.2f", time_scale);
        font.print(1,80,"Users: %d", users.size());
        font.print(1,100,"Files: %d", files.size());
        font.print(1,120,"Dirs: %d",  gGourceDirMap.size());

        font.print(1,140,"Log Position: %.4f", commitlog->getPercent());
        font.print(1,160,"Camera: (%.2f, %.2f, %.2f)", campos.x, campos.y, campos.z);
        font.print(1,180,"Gravity: %.2f", gGourceForceGravity);
        font.print(1,200,"Update Tree: %u ms", update_dir_tree_time);
        font.print(1,220,"Draw Tree: %u ms", draw_tree_time);
        font.print(1,240,"Mouse Trace: %u ms", trace_time);
        font.print(1,260,"Logic Time: %u ms", logic_time);
        font.print(1,280,"Draw Time: %u ms", SDL_GetTicks() - draw_time);
        font.print(1,300,"File Inner Loops: %d", gGourceFileInnerLoops);
        font.print(1,320,"User Inner Loops: %d", gGourceUserInnerLoops);
        font.print(1,340,"Dir Inner Loops: %d (QTree items = %d, nodes = %d)", gGourceDirNodeInnerLoops,
            dirNodeTree->item_count, dirNodeTree->node_count);

        if(selectedUser != 0) {

        }

        if(selectedFile != 0) {
            font.print(1,360,"%s: %d files (%d visible)", selectedFile->getDir()->getPath().c_str(),
                    selectedFile->getDir()->fileCount(), selectedFile->getDir()->visibleFileCount());
        }

    }

    glDisable(GL_TEXTURE_2D);

    if(canSeek()) slider.draw(dt);

    mousemoved=false;
    mouseclicked=false;
}
Example #12
0
float simplex_noise_2d(vector2f pos)
{
	const float F2 = 0.5f * (math_sqrtf(3.0f) - 1.0f);
	const float G2 = (3.0f - math_sqrtf(3.0f)) / 6.0f;
	
	float s = (pos.x + pos.y) * F2;
	
	int i = math_fast_floorf(pos.x + s);
	int j = math_fast_floorf(pos.y + s);
	
	float t = (i + j) * G2;
	float X0 = i - t;
	float Y0 = j - t;
	
	float x0 = pos.x - X0;
	float y0 = pos.y - Y0;
	
	int i1, j1;
	
	if(x0 > y0) {
		i1 = 1; j1 = 0;
	} else {
		i1 = 0; j1 = 1;
	}
	
	float x1 = x0 - i1 + G2;
	float y1 = y0 - j1 + G2;
	float x2 = x0 - 1.0f + 2.0f * G2;
	float y2 = y0 - 1.0f + 2.0f * G2;
	
	int ii = i & 255;
	int jj = j & 255;
	
	int gi0 = perm[ii +		 perm[jj	 ]] % 12;
	int gi1 = perm[ii + i1 + perm[jj + j1]] % 12;
	int gi2 = perm[ii + 1  + perm[jj + 1]] % 12;
	
	float n0 = 0.0f, n1 = 0.0f, n2 = 0.0f;
	
#define dot2_3(v1, v2) ( v1.x*v2.x + v1.y*v2.y )
	
	float t0 = 0.5f - x0*x0 - y0*y0;
	if(t0 < 0.0f) { 
		n0 = 0.0f;
	} else {
		t0 *= t0;
		n0 = t0 * t0 * dot2_3(grad3[gi0], vec2f(x0, y0));
	}
	
	float t1 = 0.5f - x1*x1 - y1*y1;
	if(t1 < 0.0f) { 
		n1 = 0.0f;
	} else {
		t1 *= t1;
		n1 = t1 * t1 * dot2_3(grad3[gi1], vec2f(x1, y1));
	}
	
	float t2 = 0.5f - x2*x2 - y2*y2;
	if(t2 < 0.0f) { 
		n2 = 0.0f;
	} else {
		t2 *= t2;
		n2 = t2 * t2 * dot2_3(grad3[gi2], vec2f(x2, y2));
	}
	
#undef dot2_3

	return 70.0f * (n0 + n1 + n2);
}
Example #13
0
 /*! returns the number of pixels (in x and y, respectively) that
   the bezel will cover. Note we do not care whether bezels are
   symmetric in left/right respective in top/bottom direction:
   the 'x' value is the sum of left and right bezel area; the
   'y' value the sum of top and bottom area' */
 vec2i WallConfig::bezelPixelsPerDisplay() const
 {
   return vec2i(relativeBezelWidth*vec2f(pixelsPerDisplay)); 
 }
Example #14
0
    void importOBJ(const std::shared_ptr<Node> &world, const FileName &fileName)
    {
      tinyobj::attrib_t attrib;
      std::vector<tinyobj::shape_t> shapes;
      std::vector<tinyobj::material_t> materials;

      std::string err;
      const std::string containingPath = fileName.path();

      std::cout << "parsing OBJ input file... \n";
      bool ret = tinyobj::LoadObj(&attrib,
                                  &shapes,
                                  &materials,
                                  &err,
                                  fileName.c_str(),
                                  containingPath.c_str());

#if 0 // NOTE(jda) - enable if you want to see warnings from TinyOBJ
      if (!err.empty())
        std::cerr << "#ospsg: obj parsing warning(s)...\n" << err << std::endl;
#endif

      if (!ret) {
        std::cerr << "#ospsg: FATAL error parsing obj file, no geometry added"
                  << " to the scene!" << std::endl;
        return;
      }

      auto sgMaterials = createSgMaterials(materials, containingPath);

      std::string base_name = fileName.name() + '_';
      int shapeId           = 0;

      std::cout << "...adding found triangle groups to the scene...\n";

      size_t shapeCounter = 0;
      size_t numShapes    = shapes.size();
      size_t increment    = numShapes / size_t(10);
      int    incrementer  = 0;

#if !USE_INSTANCES
      auto objInstance = createNode("instance", "Instance");
      world->add(objInstance);
#endif
      for (auto &shape : shapes) {
        for (int numVertsInFace : shape.mesh.num_face_vertices) {
          if (numVertsInFace != 3) {
            std::cerr << "Warning: more thant 3 verts in face!";
            PRINT(numVertsInFace);
          }
        }

        if (shapeCounter++ > (increment * incrementer + 1))
          std::cout << incrementer++ * 10 << "%\n";

        auto name = base_name + std::to_string(shapeId++) + '_' + shape.name;
        auto mesh = createNode(name, "TriangleMesh")->nodeAs<TriangleMesh>();

        auto v = createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
        auto numSrcIndices = shape.mesh.indices.size();
        v->v.reserve(numSrcIndices);

        auto vi = createNode("index", "DataVector3i")->nodeAs<DataVector3i>();
        vi->v.reserve(numSrcIndices / 3);

        auto vn = createNode("normal", "DataVector3f")->nodeAs<DataVector3f>();
        vn->v.reserve(numSrcIndices);

        auto vt =
            createNode("texcoord", "DataVector2f")->nodeAs<DataVector2f>();
        vt->v.reserve(numSrcIndices);

        for (size_t i = 0; i < shape.mesh.indices.size(); i += 3) {
          auto idx0 = shape.mesh.indices[i + 0];
          auto idx1 = shape.mesh.indices[i + 1];
          auto idx2 = shape.mesh.indices[i + 2];

          auto prim = vec3i(i + 0, i + 1, i + 2);
          vi->push_back(prim);

          v->push_back(vec3f(attrib.vertices[idx0.vertex_index * 3 + 0],
                             attrib.vertices[idx0.vertex_index * 3 + 1],
                             attrib.vertices[idx0.vertex_index * 3 + 2]));
          v->push_back(vec3f(attrib.vertices[idx1.vertex_index * 3 + 0],
                             attrib.vertices[idx1.vertex_index * 3 + 1],
                             attrib.vertices[idx1.vertex_index * 3 + 2]));
          v->push_back(vec3f(attrib.vertices[idx2.vertex_index * 3 + 0],
                             attrib.vertices[idx2.vertex_index * 3 + 1],
                             attrib.vertices[idx2.vertex_index * 3 + 2]));

          // TODO create missing normals&texcoords if only some faces have them
          if (!attrib.normals.empty() && idx0.normal_index != -1) {
            vn->push_back(vec3f(attrib.normals[idx0.normal_index * 3 + 0],
                                attrib.normals[idx0.normal_index * 3 + 1],
                                attrib.normals[idx0.normal_index * 3 + 2]));
            vn->push_back(vec3f(attrib.normals[idx1.normal_index * 3 + 0],
                                attrib.normals[idx1.normal_index * 3 + 1],
                                attrib.normals[idx1.normal_index * 3 + 2]));
            vn->push_back(vec3f(attrib.normals[idx2.normal_index * 3 + 0],
                                attrib.normals[idx2.normal_index * 3 + 1],
                                attrib.normals[idx2.normal_index * 3 + 2]));
          }

          if (!attrib.texcoords.empty() && idx0.texcoord_index != -1) {
            vt->push_back(vec2f(attrib.texcoords[idx0.texcoord_index * 2 + 0],
                                attrib.texcoords[idx0.texcoord_index * 2 + 1]));
            vt->push_back(vec2f(attrib.texcoords[idx1.texcoord_index * 2 + 0],
                                attrib.texcoords[idx1.texcoord_index * 2 + 1]));
            vt->push_back(vec2f(attrib.texcoords[idx2.texcoord_index * 2 + 0],
                                attrib.texcoords[idx2.texcoord_index * 2 + 1]));
          }
        }

        mesh->add(v);
        mesh->add(vi);
        if (!vn->empty())
          mesh->add(vn);
        if (!vt->empty())
          mesh->add(vt);

        auto pmids = createNode("prim.materialID",
                                "DataVector1i")->nodeAs<DataVector1i>();

        auto numMatIds = shape.mesh.material_ids.size();
        pmids->v.reserve(numMatIds);

        for (auto id : shape.mesh.material_ids)
          pmids->v.push_back(id);

        mesh->add(pmids);
        mesh->add(sgMaterials);

        auto model = createNode(name + "_model", "Model");
        model->add(mesh);

        // TODO: Large .obj models with lots of groups run much slower with each
        //       group put in a separate instance. In the future, we want to
        //       support letting the user (ospExampleViewer, for starters)
        //       specify if each group should be placed in an instance or not.
#if USE_INSTANCES
        auto instance = createNode(name + "_instance", "Instance");
        instance->setChild("model", model);
        model->setParent(instance);

        world->add(instance);
#else
        (*objInstance)["model"].add(mesh);
#endif

      }

      std::cout << "...finished import!\n";
    }
Example #15
0
vec2f operator*(const float k, const vec2f& v1){
    return vec2f(v1.peekx()*k,
                 v1.peeky()*k);
}
Example #16
0
 void TransferFunction::commit()
 {
   vec2f valueRange = getParam2f("valueRange", vec2f(0.0f, 1.0f));
   ispc::TransferFunction_setValueRange(ispcEquivalent,
                                        (const ispc::vec2f &)valueRange);
 }
Example #17
0
void Logger::recordDrawEvent(MyD3DAssets &assets, const DrawParameters &params)
{
    if (capturingFrame && assets.viewportFullScreen())
    {
        GPUDrawBuffers buffers(assets);

        LocalizedObject object;

        object.load(assets, params, buffers, true);
        
        if (object.vertices.size() > 0)
        {
            frameCaptureObjects.frames[0]->objectData.push_back(object.data);
            frameCaptureObjects.frames[0]->objectMeshes.push_back(object);
        }

        const BufferCPU *VSConstants = assets.getVSConstantBuffer();
        const auto &indexBuffer = assets.getActiveIndexBuffer();
        const auto &vertexBuffer = assets.getActiveVertexBuffer();
        
        const string imagePrefix = "render" + (useLinearCaptureNumbering ? util::zeroPad(frameOutputIndex, 5) : util::zeroPad(frameRenderIndex, 5));
        const string frameImageFile = imagePrefix + "_frame.png";
        const string frameDeltaImageFile = imagePrefix + "_delta.png";
        const string texImageFile = imagePrefix + "_tex";

        if (outputImages)
        {
            Bitmap image;
            assets.context->readRenderTarget(image);
            LodePNG::save(image, g_logger->captureDir + frameImageFile);
            frameOutputIndex++;

            if (prevCaptureImage.getDimensions() == image.getDimensions())
            {
                Bitmap deltaImage = image;
                for (auto &p : deltaImage)
                {
                    if (p.value == prevCaptureImage(p.x, p.y))
                        p.value = vec4uc(0, 0, 0, 255);
                }

                LodePNG::save(deltaImage, g_logger->captureDir + frameDeltaImageFile);
            }

            prevCaptureImage = image;
        }

        auto modifyImage = [](Bitmap &b)
        {
            if (b.size() == 0) return;
            for (auto &p : b)
            {
                p.value.r = unsigned char((int)p.value.r * (int)p.value.a / 255);
                p.value.g = unsigned char((int)p.value.g * (int)p.value.a / 255);
                p.value.b = unsigned char((int)p.value.b * (int)p.value.a / 255);
                p.value.a = 255;
            }
        };

        for (int textureIndex = 0; textureIndex < textureOutputCount; textureIndex++)
        {
            assets.loadPSTexture(textureIndex);
            modifyImage(assets.PSTexture);
            if (assets.PSTexture.size() > 0 && outputImages)
                LodePNG::save(assets.PSTexture, g_logger->captureDir + texImageFile + to_string(textureIndex) + ".png");
        }

        auto makeHTMLImage = [](const string &filename)
        {
            return "<img src=\"" + filename + "\" />";
        };

        logFrameCaptureHtml << "<tr>" << endl;
        logFrameCaptureHtml << "<td>" << frameRenderIndex << "</td>" << endl;
        logFrameCaptureHtml << "<td>" << makeHTMLImage(frameImageFile) << "</td>" << endl;
        logFrameCaptureHtml << "<td>" << makeHTMLImage(frameDeltaImageFile) << "</td>" << endl;

        for (int texIndex = 0; texIndex < textureOutputCount; texIndex++)
            logFrameCaptureHtml << "<td>" << makeHTMLImage(texImageFile + to_string(texIndex) + ".png") << "</td>" << endl;
        
        auto viewport = assets.getViewport();
        logFrameCaptureHtml << "<td>" << object.data.signature << "<br />" << "viewport: " << viewport.Width << "," << viewport.Height << "</td>" << endl;
        logFrameCaptureHtml << "<td>" << params.IndexCount << ", " << params.StartIndexLocation << ", " << params.BaseVertexLocation << "</td>" << endl;
        logFrameCaptureHtml << "<td>" << ((indexBuffer.buffer == nullptr) ? "invalid" : to_string(indexBuffer.buffer->data.size())) + " " + pointerToString(indexBuffer.buffer->GPUHandle) << "</td>" << endl;
        //logFrameCaptureHtml << "<td>" << indexBuffer.offset << "</td>" << endl;
        logFrameCaptureHtml << "<td>" << ((vertexBuffer.buffer == nullptr) ? "invalid" : to_string(vertexBuffer.buffer->data.size())) + " " + pointerToString(vertexBuffer.buffer->GPUHandle) << "</td>" << endl;
        //logFrameCaptureHtml << "<td>" << vertexBuffer.offset << "</td>" << endl;
        logFrameCaptureHtml << "<td>" << vertexBuffer.stride << "</td>" << endl;

        string v0Data = "<none>";
        if (params.BaseVertexLocation != -1 && vertexBuffer.buffer != nullptr && indexBuffer.buffer != nullptr)
        {
            const WORD *indexDataStart = (WORD *)indexBuffer.buffer->data.data() + params.StartIndexLocation;
            
            const BYTE *vertexData = vertexBuffer.buffer->data.data();

            v0Data = "";

            const auto *layout = assets.activeVertexLayout;

            if (layout == nullptr)
            {
                v0Data = "layout not found";
            }
            else
            {
                v0Data += layout->htmlDescription;
                v0Data += "data:<br />";

                for (int indexIndex = 0; indexIndex < min((int)params.IndexCount, 32); indexIndex++)
                {
                    string vertexPrefix = "V" + to_string(indexIndex) + " ";

                    const int curIndex = indexDataStart[indexIndex] + params.BaseVertexLocation;
                    const BYTE *curVertex = (vertexData + (vertexBuffer.stride * curIndex));

                    if (vertexBuffer.buffer->data.size() < vertexBuffer.stride * (curIndex + 1))
                    {
                        v0Data += "*out of bounds*<br />";
                        continue;
                    }

                    const int pOffset = assets.activeVertexLayout->positionOffset;
                    const int bOffset = assets.activeVertexLayout->blendOffset;
                    const int tOffset = assets.activeVertexLayout->tex0Offset;
                    
                    int blendMatrixIndex = -1;
                    if (bOffset != -1)
                    {
                        vec4uc blendIndices = *((const vec4uc *)(curVertex + bOffset));
                        blendMatrixIndex = blendIndices.x;
                    }

                    const float *pStart = (const float *)(curVertex + pOffset);
                    const vec3f basePos(pStart[0], pStart[1], pStart[2]);
                    vec3f pos = assets.transformObjectToWorldGamecube(VSConstants, basePos, blendMatrixIndex);

                    vec2f tex = vec2f::origin;
                    if (tOffset != -1)
                    {
                        const float *tStart = (const float *)(curVertex + tOffset);
                        tex = vec2f(tStart[0], tStart[1]);
                    }

                    v0Data += vertexPrefix + "world=" + pos.toString(", ") + " <br/>";
                    v0Data += vertexPrefix + "index=" + to_string(curIndex) + " <br/>";
                    v0Data += vertexPrefix + "tex=" + tex.toString(", ") + " <br/>";
                }
            }
        }

        logFrameCaptureHtml << "<td>" << v0Data << "</td>" << endl;
        logFrameCaptureHtml << "</tr>" << endl;
    }
Example #18
0
File: Game.cpp Project: w23/o08
vec2i Game::screenToWorld(vec2f screen) {
  return vec2i(vec2f(logic_.field().getSize()) * (screen * .5 + vec2f(.5)));
}
Example #19
0
 inline vec2f toTileCoords(vec2f pos) const { return vec2f(pos.x/m_tileSize, pos.y/m_tileSize); }
Example #20
0
void ClientApplication::run()
{
	int lastFPS = -1;
	auto driver = _device->getVideoDriver();

	sf::Clock c;
	while(_device->run())
	{
		float timeDelta = c.restart().asSeconds();
		scene::ICameraSceneNode* camera = getCamera();
		if(camera) {
			if(camera->isInputReceiverEnabled() && !_controller.isCameraFree())
				bindCameraToControlledEntity();
			if(!camera->isInputReceiverEnabled()) {
				vec3f cameraLookDir((_cameraElevation-PI_2)/PI*180,(_cameraYAngle+PI_2)/PI*180,0);
				cameraLookDir = cameraLookDir.rotationToDirection().normalize();
				camera->setTarget(camera->getAbsolutePosition()+cameraLookDir*10000);
				if(_sharedRegistry.hasKey("controlled_object_id")) {
					auto controlledCharSceneNode = _device->getSceneManager()->getSceneNodeFromId(_sharedRegistry.getValue<ID>("controlled_object_id"));
					if(controlledCharSceneNode) {
						controlledCharSceneNode->setVisible(false);
						camera->setPosition(controlledCharSceneNode->getPosition() + vec3f(0,1.6,0) + 0.23f*(cameraLookDir*vec3f(1,0,1)).normalize());
					}
				}
			}
		}

		while(receive());		
		//TODO fix frameLen spike after win inactivity (mind the physics)
		if(true)//if(_device->isWindowActive())
		{
			if(_device->isWindowActive())
				_device->getCursorControl()->setPosition(vec2f(0.5));
			driver->beginScene(/*true,true,video::SColor(255,255,255,255)*/);
			f32 ar = (float)driver->getScreenSize().Width/(float)driver->getScreenSize().Height;
			camera = getCamera();
			if(camera && ar != camera->getAspectRatio())
				camera->setAspectRatio(ar);
			//std::cout << "number of scene nodes: " << _device->getSceneManager()->getRootSceneNode()->getChildren().size() << std::endl;
				
			if(_yAngleSetCommandFilter.tick(timeDelta) && _yAngleSetCommandFilter.objUpdated()) {
				Command c(Command::Type::Y_ANGLE_SET);
				c._float = _yAngleSetCommandFilter.reset();
				sendCommand(c);
			}

			if(_physics)
				_physics->update(timeDelta);
			if(_vs)
				_vs->update(timeDelta);
			if(_gui)
				_gui->update(timeDelta);

			_device->getSceneManager()->drawAll();
			_device->getGUIEnvironment()->drawAll();

			driver->runAllOcclusionQueries(false);
			driver->updateAllOcclusionQueries();

			driver->endScene();

			// display frames per second in window title
			int fps = driver->getFPS();
			if (lastFPS != fps)
			{
				core::stringw str = L"MyGame [";
				str += driver->getName();
				str += "] FPS:";
				str += fps;

				_device->setWindowCaption(str.c_str());
				lastFPS = fps;
			}
		}
		sf::sleep(sf::milliseconds(1));
	}
}
Example #21
0
vec2f Entity::getCollisionRectPosition()
{
	return vec2f(_collisionRect.x, _collisionRect.y);
}
/**
 * LAB WORKSHEET 4, ASSIGNMENT 1
 *
 * compute the intersection between a sphere and a box
 */
bool CPhysicsIntersections::sphereBox(iPhysicsObject &physics_object_sphere, iPhysicsObject &physics_object_box, CPhysicsCollisionData &c)
{
#if WORKSHEET_4
	float sphereRadius = static_cast<cObjectFactorySphere *>(&physics_object_sphere.object->objectFactory.getClass())->radius;
	vec4f spherePos = physics_object_box.object->inverse_model_matrix * physics_object_sphere.object->position;
	Vector boxHalfSize = static_cast<cObjectFactoryBox *>(&physics_object_box.object->objectFactory.getClass())->half_size;
	
	c.physics_object1 = &physics_object_box;
	c.physics_object2 = &physics_object_sphere;
	
	//planes
	//yz-plane
	if (fabs(spherePos[0]) < sphereRadius + boxHalfSize[0] && fabs(spherePos[1]) < boxHalfSize[1] && fabs(spherePos[2]) < boxHalfSize[2]) {
					
		int sgn = (spherePos[0] >= 0) - (spherePos[0] < 0);
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(sgn, 0, 0);
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(sgn*boxHalfSize[0], spherePos[1], spherePos[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal * sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}
	
	//xz-plane
	if (fabs(spherePos[1]) < sphereRadius + boxHalfSize[1] && fabs(spherePos[0]) < boxHalfSize[0] && fabs(spherePos[2]) < boxHalfSize[2]) {
				   
		int sgn = (spherePos[1] >= 0) - (spherePos[1] < 0);
		
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(0, sgn, 0);
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(spherePos[0], sgn*boxHalfSize[1], spherePos[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal * sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}
	
	//xy-plane
	if (fabs(spherePos[2]) < sphereRadius + boxHalfSize[2] && fabs(spherePos[0]) < boxHalfSize[0] && fabs(spherePos[1]) < boxHalfSize[1]) {
					
		int sgn = (spherePos[2] >= 0) - (spherePos[2] < 0);
		
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(0, 0, sgn);
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(spherePos[0], spherePos[1], sgn*boxHalfSize[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal * sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}
	
	
	//edges
	//edges parallel to x
	if (fabs(spherePos[0]) < boxHalfSize[0] && vec2f(fabs(spherePos[1]) - boxHalfSize[1], fabs(spherePos[2]) - boxHalfSize[2]).length() - sphereRadius <= 0) {
		
		int ySgn = (spherePos[1] >= 0) - (spherePos[1] < 0);
		int zSgn = (spherePos[2] >= 0) - (spherePos[2] < 0);
		
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(0, spherePos[1] - ySgn*boxHalfSize[1], spherePos[2] - ySgn*boxHalfSize[2]).getNormalized();
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(spherePos[0], ySgn*boxHalfSize[1], zSgn*boxHalfSize[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal * sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}

	//edges parallel to y
	if (fabs(spherePos[1]) < boxHalfSize[1] && vec2f(fabs(spherePos[0]) - boxHalfSize[0], fabs(spherePos[2]) - boxHalfSize[2]).length() - sphereRadius <= 0) {
		
		int xSgn = (spherePos[0] >= 0) - (spherePos[0] < 0);
		int zSgn = (spherePos[2] >= 0) - (spherePos[2] < 0);
		
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(spherePos[0] - xSgn*boxHalfSize[0], 0, spherePos[2] - zSgn*boxHalfSize[2]).getNormalized();
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(xSgn*boxHalfSize[0], spherePos[1], zSgn*boxHalfSize[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal * sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}
	
	//edges parallel to z
	if (fabs(spherePos[2]) < boxHalfSize[2] && vec2f(fabs(spherePos[0]) - boxHalfSize[0], fabs(spherePos[1]) - boxHalfSize[1]).length() - sphereRadius <= 0) {
		
		int xSgn = (spherePos[0] >= 0) - (spherePos[0] < 0);
		int ySgn = (spherePos[1] >= 0) - (spherePos[1] < 0);
		
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(spherePos[0] - xSgn*boxHalfSize[0], spherePos[1] - ySgn*boxHalfSize[1], 0).getNormalized();
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(xSgn*boxHalfSize[0], ySgn*boxHalfSize[1], spherePos[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal *sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}
	
	
	//corners
	if (Vector(fabs(spherePos[0]) - boxHalfSize[0], fabs(spherePos[1]) - boxHalfSize[1], fabs(spherePos[2]) - boxHalfSize[2]).getLength() - sphereRadius <= 0) {
		
		int xSgn = (spherePos[0] >= 0) - (spherePos[0] < 0);
		int ySgn = (spherePos[1] >= 0) - (spherePos[1] < 0);
		int zSgn = (spherePos[2] >= 0) - (spherePos[2] < 0);
		
		c.collision_normal = physics_object_box.object->inverse_model_matrix.getTranspose() * Vector(spherePos[0] - xSgn*boxHalfSize[0], spherePos[1] - ySgn*boxHalfSize[1], spherePos[2] - zSgn*boxHalfSize[2]).getNormalized();
		c.collision_point1 = physics_object_box.object->model_matrix * Vector(xSgn*boxHalfSize[0], ySgn*boxHalfSize[1], zSgn*boxHalfSize[2]);
		c.collision_point2 = physics_object_sphere.object->position - (c.collision_normal * sphereRadius);
		c.interpenetration_depth = (c.collision_point2 - c.collision_point1).getLength();
		
		return true;
	}
	
	return false;
#else
	return false;
#endif
}
	//-------------------------------------------------------------------
	void ReturnResource::followOrders( float deltaTime )
	{
		if( m_unit && m_buildingToReturnTo )
		{
			if( m_currentPathIndex >= 0 )
			{				
				m_currentGoal = vec2f( (float)m_path[ m_currentPathIndex ].x, (float)m_path[ m_currentPathIndex ].y );
			}
			else if( m_needNewNaiveTarget )
			{
				m_currentGoal = getNextNaiveTarget( m_unit->m_position );
				m_needNewNaiveTarget = false;
			}

			vec2f dir = m_currentGoal - m_unit->m_position;
			dir.normalize();
			vec2f dx = dir * m_unit->m_movement.speed * deltaTime;
			vec2f newPos = m_unit->m_position + dx;
							
			m_unit->setPosition( newPos );		

			vec2f delta = m_unit->m_position - m_currentGoal;
			float distSqrd = delta.dot( delta );
			float tolerance = m_tolerance;
			
			vec2f deltaBetweenCurrentAndTarget = m_targetLocation - m_currentGoal;
			float distSqrdBetweenCurrentAndTarget = deltaBetweenCurrentAndTarget.dot( deltaBetweenCurrentAndTarget );
			if( distSqrdBetweenCurrentAndTarget < m_tolerance )
			{
				float buildingTolerance = m_buildingToReturnTo->getWidth() * m_buildingToReturnTo->getWidth(); 
				tolerance = buildingTolerance;
			}

			if( distSqrd < tolerance )
			{
				if( m_currentPathIndex >= 0 )
				{
					--m_currentPathIndex;
					if( m_currentPathIndex < 0 )
					{
						m_ordersComplete = true;
						if( m_mapTile.hasResource() )
							m_unit->pushOrders( new GotoResource( m_mapTile ) );
						else
						{
							TileCoords newResourceTileCoords = m_unit->getMap()->getNextClosestTileCoordsWithResource( m_mapTile.getTilecoords(), m_unit->m_resource.resourceType );
							if( newResourceTileCoords.x != -1 )
								m_unit->pushOrders( new GotoResource( m_unit->getMap()->getMapTile( newResourceTileCoords ) ) );
						}

						// Dump resources to controller and remove from unit
						m_unit->m_owner->giveResource( m_unit->m_resource.resourceType, m_unit->m_resource.currentAmount );
						m_unit->m_resource.currentAmount = 0;
						m_unit->m_resource.resourceType = Map::NONE;
					}
				}
				else
				{
					delta = m_currentGoal - m_targetLocation;
					distSqrd = delta.dot( delta );
					if( distSqrd < tolerance )
						m_ordersComplete = true;
					else
						m_needNewNaiveTarget = true;
				}
			}
		}
		else
		{
			m_ordersComplete = true;
		}
	}
Example #24
0
        void PhotonTracer::traceSinglePhoton(IPhotonMap& photonMap, int photonCount) const {
            float randomVector[RANDOM_DIMENSION];

            randomSet_->nextf(randomVector);

            Spectrum power;

            ray3f ray(light_->samplePhoton(
                power,
                vec2f(
                    Lcg::global().nextf(),
                    Lcg::global().nextf()),
                vec2f(
                    randomAt(randomVector, 0), 
                    randomAt(randomVector, 1))));

            power /= static_cast<float>(photonCount); // split power

            HitInfo hit = HitInfo::createUninitialized();

            float currentRefractiveIndex = 1;

            int bounceCount = 0;

            while( scene_->raytrace(ray, hit) ) {
                if(bounceCount > 0) {
                    Photon photon(
                        hit.position(),
                        hit.normal(),
                        power);

                    photonMap.add(photon);
                }

                Material const& material = hit.material();

                if(material.getType() == Material::MATERIAL_DIFFUSE) {
                    float u = Lcg::global().nextf();

                    // Russian roulette.
                    if(u <= material.getReflectance().average()) {
                        power *= material.getReflectance() 
                            / material.getReflectance().average();

                        ray = ray3f(
                            hit.position(),
                            Hemisphere::cosineWeightedDirection(
                                hit.normal(),
                                randomAt(randomVector, 2+2*bounceCount),
                                randomAt(randomVector, 3+2*bounceCount)));
                    } else {
                        break;
                    }
                } else if(material.getType() == Material::MATERIAL_SPECULAR) {
                    float u = Lcg::global().nextf();

                    // Russian roulette.
                    if(u <= material.getReflectance().average()) {
                        power *= material.getReflectance() 
                            / material.getReflectance().average();

                        ray = ray3f(
                            hit.position(),
                            Hemisphere::mirrorReflection(
                                hit.normal(),
                                ray.getDirection()));
                    } else {
                        break;
                    }
                } else if(material.getType() == Material::MATERIAL_DIELECTRIC) {
                    float fresnel = Hemisphere::fresnelCoefficient(
                        hit.normal(), ray.getDirection(),
                        currentRefractiveIndex,
                        material.getRefractiveIndex());

                    float u = Lcg::global().nextf();

                    if(u < 1 - fresnel) {
                        // refraction

                        vec3f excitantDirection;

                        if( Hemisphere::computeRefraction(
                                hit.normal(), ray.getDirection(),
                                currentRefractiveIndex,
                                material.getRefractiveIndex(),
                                excitantDirection) ) {
                            ray = ray3f(
                                hit.position(),
                                excitantDirection);

                            currentRefractiveIndex = material.getRefractiveIndex();
                        } else {
                            // total internal reflection

                            ray = ray3f(
                                hit.position(),
                                Hemisphere::mirrorReflection(
                                    hit.normal(),
                                    ray.getDirection()));
                        }
                    } else {
                        // reflection

                        ray = ray3f(
                            hit.position(),
                            Hemisphere::mirrorReflection(
                                hit.normal(),
                                ray.getDirection()));
                    }
                } else {
                    break;
                }

                ++bounceCount;
            }
        }
Example #25
0
File: ui.cpp Project: hyp/Arpheg
void Service::render() {
	auto size = services::rendering()->context()->frameBufferSize();
	mat44f matrix = mat44f::ortho(vec2f(0,0),vec2f(float(size.x),float(size.y)));
	renderer_->render(matrix);
}
namespace WE
{
    const float CameraComponent::CAMERA_COMPONENT_DEFAULT_FOV = 3.14f / 2.0f;
    const vec2f CameraComponent::CAMERA_COMPONENT_DEFAULT_DEPTH = vec2f(1.0f, 100000.0f);

    CameraComponent::CameraComponent() : m_FOV(CAMERA_COMPONENT_DEFAULT_FOV),
        m_Depth(CAMERA_COMPONENT_DEFAULT_DEPTH)
	{
		m_WorldSize = Config::WINDOW_SIZE;
		m_ScreenSize = vec2f(1.0f, 1.0f);
        m_RealScreenSize = Config::WINDOW_SIZE;
	}


	void CameraComponent::SetScreenPosition(vec2f pos)
	{
		m_ScreenPositon = pos;
	}
	vec2f CameraComponent::GetScreenPosition()
	{
		return m_ScreenPositon;
	}
	void CameraComponent::SetScreenSize(vec2f size)
	{
		m_ScreenSize = size;
	}
	vec2f CameraComponent::GetScreenSize()
	{
		return m_ScreenSize;
	}
	void CameraComponent::SetWorldSize(vec2f size)
	{
		m_WorldSize = size;
	}
	vec2f CameraComponent::GetWorldSize()
	{
		return m_WorldSize;
	}

    //set the depth of the camera
    void CameraComponent::SetDepth(vec2f depth)
    {
        m_Depth = depth;
    }
    //get the depth of the camera
    vec2f CameraComponent::GetDepth()
    {
        return m_Depth; 
    }

    //set the field of vision
    //takes an angle in radians
    void CameraComponent::SetFieldOfVision(float f)
    {
        m_FOV = f;
    }
    //return the field of vision
    float CameraComponent::GetFieldOfVision()
    {
        return m_FOV;
    }

	void CameraComponent::View(RenderState* program)
	{
		//set the viewport
        glViewport(static_cast<int>(m_ScreenPositon.x* m_RealScreenSize.x), static_cast<int>(m_ScreenPositon.y* m_RealScreenSize.y), static_cast<int>(m_ScreenSize.x* m_RealScreenSize.x), static_cast<int>(m_ScreenSize.y* m_RealScreenSize.y));

        float aspect = (m_WorldSize.x) / (m_WorldSize.y);
        mat4f::Frustum(aspect, m_Depth.x, m_Depth.y, m_FOV, &program->stack->Top(), true);

	}

    //set the screen size in pixels
    void CameraComponent::SetRealScreenSize(vec2f size)
    {
        m_RealScreenSize = size;
    }
    //return the size of the camera in pixels
    vec2f CameraComponent::GetRealScreenSize()
    {
        return m_RealScreenSize;
    }
}
Example #27
0
void Gource::interactUsers() {


    // update quad tree
    Bounds2D quadtreebounds = user_bounds;

    quadtreebounds.min -= vec2f(1.0f, 1.0f);
    quadtreebounds.max += vec2f(1.0f, 1.0f);

    update_user_tree_time = SDL_GetTicks();

    if(userTree != 0) delete userTree;

    int max_depth = 1;

    //dont use deep quad tree initially when all the nodes are in one place
    if(dir_bounds.area() > 10000.0) {
        max_depth = 6;
    }

    userTree = new QuadTree(quadtreebounds, max_depth, 1);

    for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) {
        RUser* user = it->second;

        user->updateQuadItemBounds();
        userTree->addItem(user);
    }

    //move users - interact with other users and files
    for(std::map<std::string,RUser*>::iterator ait = users.begin(); ait!=users.end(); ait++) {

        RUser* a = ait->second;

        std::set<int> seen;
        std::set<int>::iterator seentest;

        std::vector<QuadItem*> inbounds;

        int found = userTree->getItemsInBounds(inbounds, a->quadItemBounds);

        for(std::vector<QuadItem*>::iterator it = inbounds.begin(); it != inbounds.end(); it++) {

            RUser* b = (RUser*) (*it);

            if(b==a) continue;

            if((seentest = seen.find(b->getTagID())) != seen.end()) {
                continue;
            }

            seen.insert(b->getTagID());

            a->applyForceUser(b);
            gGourceUserInnerLoops++;
        }

        a->applyForceToActions();
    }

    update_user_tree_time = SDL_GetTicks() - update_user_tree_time;
}
Example #28
0
vec2f operator-(const vec2f& v1, const vec2f &v2){
    return vec2f(v1.peekx()-v2.peekx(),
                 v1.peeky()-v2.peeky());
}
Example #29
0
void StackGraph::mouseMove(SDL_MouseMotionEvent *e) {
    mousepos = vec2f(e->x, e->y);
    mousemoved=true;
}
Example #30
0
int main()
{
    int exit = 0;
    MAP* map = load_map("e1m1.wad");
    VEC2F vp = vec2f(0.f, 0.f);
    float ang, move_speed = 200.f, rot_speed = 2.5f;
    
    init();
    
    //VEC2F vn = vec2f(-v.y, v.x);
    //VEC2F ray_dir = vec2f();
    
    //short s = -1;
    //s &= ~(1 << 15);
    //printf("ZOMG = %d\n", s);
    
    clock_t last_clock = clock();
    
    while(!exit)
    {
        clock_t now = clock();
        float dt = (float)(now - last_clock) / CLOCKS_PER_SEC;
        last_clock = now;
        
        VEC2F view_dir = vec2f(cos(ang), sin(ang));
        VEC2F view_dir_norm = vec2f(-view_dir.y, view_dir.x);
        
        if(key[KEY_ESC]) exit = 1;
        if(key[KEY_S]) vp = vec2f_sum(vp, vec2f_uscale(view_dir, -move_speed * dt));
        if(key[KEY_W]) vp = vec2f_sum(vp, vec2f_uscale(view_dir, move_speed * dt));
        if(key[KEY_A]) vp = vec2f_sum(vp, vec2f_uscale(view_dir_norm, -move_speed * dt));
        if(key[KEY_D]) vp = vec2f_sum(vp, vec2f_uscale(view_dir_norm, move_speed * dt));
        if(key[KEY_LEFT]) ang -= rot_speed * dt;
        if(key[KEY_RIGHT]) ang += rot_speed * dt;
        
        clear_to_color(buffer, 0);
        
        SECTOR* s = find_sector(map, map->node_num - 1, vp);
        float h = s->floor_height + 45;
        
        int i;
        
        for(i = 0; i < H_RES; ++i)
        {
            float t = i - H_RES / 2;
            float u = FOCAL_DIST;
            
            VEC2F ray_dir = vec2f_sum(vec2f_uscale(view_dir, u), vec2f_uscale(view_dir_norm, t)); //vec2f(view_dir.x * FOCAL_DIST + view_dir_norm.x * t, view_dir.y * FOCAL_DIST + view_dir_norm.y * t);
            float ray_len = sqrt(ray_dir.x * ray_dir.x + ray_dir.y * ray_dir.y);
            ray_dir.x /= ray_len;
            ray_dir.y /= ray_len;
            render_col(buffer, map, map->node_num - 1, vp, -h, ray_dir, i);
            
            //line(buffer, SCREEN_W / 2, SCREEN_H / 2, SCREEN_W / 2 + ray_dir.x * 200, SCREEN_H / 2 + ray_dir.y * 200, makecol(255, 255, 255));
        }

        
        
        if(key[KEY_TAB])
        for(i = 0; i < map->seg_num; ++i)
        {
            VERTEX v1t = map->vertexes[map->segs[i].v1_idx];
            VERTEX v2t = map->vertexes[map->segs[i].v2_idx];
            VEC2F v1 = vec2f(v1t.x, v1t.y);
            VEC2F v2 = vec2f(v2t.x, v2t.y);
            VEC2F mid = vec2f((v1.x + v2.x) / 2, (v1.y + v2.y) / 2);
            
            VEC2F n = normalized_normal(vec2f_diff(v2, v1));
            float scl = 1.f / 2.f;
            
            line(buffer, v1.x*scl + SCREEN_W / 2,
                         v1.y*scl + SCREEN_H / 2,
                         v2.x*scl + SCREEN_W / 2,
                         v2.y*scl + SCREEN_H / 2, makecol(255, 255, 255));
            circlefill(buffer, (int)vp.x*scl + SCREEN_W/2, (int)vp.y*scl +SCREEN_H/2, 3, makecol(255, 255, 255));
            
            
            line(buffer, SCREEN_W/2+ mid.x*scl,
                        SCREEN_H/2 +  mid.y*scl,
                        SCREEN_W/2+ (mid.x + n.x * 10)*scl,
                        SCREEN_H/2+ (mid.y + n.y * 10)*scl, makecol(255, 255, 255));
            
            
            line(buffer, SCREEN_W/2+vp.x*scl,
                        SCREEN_H/2+vp.y*scl,
                        SCREEN_W/2+(vp.x+view_dir.x*100)*scl,
                        SCREEN_H/2+(vp.y+view_dir.y*100)*scl, makecol(255, 255, 255));
        }
        
        //
        
        draw_sprite(buffer, mouse_sprite, mouse_x, mouse_y);
        blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H);
    }
    
    destroy_map(map);
    deinit();
    return 0;
}END_OF_MAIN()