//The main invoker routine. It takes as argument the next command to execute and does what is necessary
//Self-explanatory code!
void my_invoker (unsigned char command) {
	if(command == BUZZER_ON){
		buzzer_on();
		return;
	}
	else if(command == BUZZER_OFF){
		buzzer_off();
		return;
	}
	else if(command == MOVE_FORWARD) 
    {
        forward();  //forward
        return;
    }

    else if(command == MOVE_BACKWARD)
    {
        back(); //back
        return;
    }

    else if(command == MOVE_LEFT) 
    {
        left();  //left
        return;
    }

    else if(command == MOVE_RIGHT)
    {
        right(); //right
        return;
    }

    else if(command == STOP) 
    {
        stop(); //stop
        return;
    }
	
	else if(command == SET_VELOCITY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        
		//assert(numargs == 1);

		int velleft = (int)*(ch);
		int velright = (int)*(ch+1);
		velocity(velleft,velright);

        return;
    }
	
	else if(command == MOVE_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		//int pos = 10;
		//while (pos_b--) pos *= 10;
		//pos *= pos_a;
		//forward_mm(pos);
		pos_a += (pos_b << 8);

		forward();
		velocity(120,120);

		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}
		stop();
		send_char(SUCCESS);		
		leftInt = 0;
		rightInt = 0;
		
		return;
    }

	else if(command == MOVE_BACK_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		//int pos = 10;
		//while (pos_b--) pos *= 10;
		//pos *= pos_a;
		//forward_mm(pos);
		pos_a += (pos_b << 8);

		back();
		velocity(120,120);

		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}
		stop();
		send_char(SUCCESS);		
		leftInt = 0;
		rightInt = 0;
		
		return;
    }
	
	else if(command == TURN_LEFT_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        already_stopped = 0;
		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		pos_a += (pos_b << 8);

		_delay_ms(500);
		left();
		velocity(200,200);

		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}
		stop();
		send_char(SUCCESS);		
		leftInt = 0;
		rightInt = 0;
		already_modified_stopped = 0;

        return;
    }

	else if(command == TURN_RIGHT_BY) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        
		//assert(numargs == 2);

		int pos_a = (int)*(ch);
		int pos_b = (int)*(ch+1);

		pos_a += (pos_b << 8);

		_delay_ms(500);
		right();
		velocity(200,200);


		while (pos_a--) {
			//delay on 5 ms
			stop_on_timer4_overflow = 1;
			start_timer4();
			while (stop_on_timer4_overflow != 0) {;}
		}		

		stop();
		send_char(SUCCESS);
		leftInt = 0;
		rightInt = 0;
		already_modified_stopped = 0;
        return;
    }

    else if(command == LCD_SET_STRING) 
    {
        int numargs;
		unsigned char * ch = recieve_args(&numargs);
        
        int i =0;
		lcd_clear();
        for(;i<numargs;i++)
        {
            lcd_wr_char(*(ch+i));
        }
        return;
    }
	
	else if (command == SET_PORT){
    	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 2){
   
	    }
    	int portnum = (int) *(ch);
    	unsigned char value = (unsigned char) *(ch+1); 
    
		setPort(portnum,value);
    }

    else if(command == GET_SENSOR_VALUE)
    {
    	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 1){
   
	    }
    	int sensornum = (int) *(ch);
    
		//setPort(portnum,value);
		getSensorValue(sensornum);
       
    }
    else if(command == GET_PORT)
    {
      	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 1){
   
	    }
    	int portnum = (int) *(ch); 
    
		getPort(portnum);
        
    }
    else if (command == WHITELINE_FOLLOW_START) {
		whiteline_follow_start();
	}
	else if(command == PRINT_STATE){
		buzzer_on();
		lcd_num(state);
		_delay_ms(1000);
		buzzer_off();
	}
	else if (command == WHITELINE_FOLLOW_END) {
		whiteline_follow_end();
	}
	else if (command == WHITELINE_STOP_INTERSECTION) {
		whiteline_stop_intersection_flag = 1;
	}
    else if(command == ACC_START) {
   		acc_flag = 1;
		
   
    }
	else if(command == ACC_STOP) {
		acc_flag = 0;
		acc_modified_flag = 0;
		buzzer_off();
	}
	else if(command == ACC_MODIFIED){
		acc_modified_flag = 1;
		already_modified_stopped = 0;
	}
	else if(command == ACC_CHECK){
		if (acc_modified_flag == 1 && already_modified_stopped == 1){
			send_char((char)1);
		}
		else {
			char value = PORTA;
			if (value == 0) send_char((char)2);
			else send_char((char)0);
		}
	}
	else if (command == ENABLE_LEFT_WHEEL_INTERRUPT) {
		leftInt = 0;
		left_position_encoder_interrupt_init();
	}
	else if (command == ENABLE_RIGHT_WHEEL_INTERRUPT) {
		rightInt = 0;
		right_position_encoder_interrupt_init();
	}
	else if (command == GET_LEFT_WHEEL_INTERRUPT_COUNT) {
		send_int (leftInt);
		leftInt = 0;
	}
	else if (command == GET_RIGHT_WHEEL_INTERRUPT_COUNT) {
		send_int (rightInt);
		rightInt = 0;
	}
	else if (command == SET_TIMER) {
	int numargs;
    	unsigned char * ch = recieve_args(&numargs); ; 
    	if (numargs != 1){
   
	    }
    	int time = (int) *(ch); 
    
		timer4_init2(time);
	}
	else if (command == DISCONNECT) {
		disconnect();
	}
	else { //Error!!! Unrecognized Command
		buzzer_on();
		_delay_ms(1000);
		buzzer_off();
	}
}
 void WorldMenuController::PositionItems()
 {
     
     if(!m_menuItemsShouldRender)
         return;
     
     Eegeo::m33 headTrackedOrientation;
     Eegeo::m33::Mul(headTrackedOrientation, m_uiCameraProvider.GetBaseOrientation(), m_cachedHeadTracker);
     
     float halfCount = m_viewsByModel.size()/2;
     if(m_viewsByModel.size()%2==0)
         halfCount-=0.5f;
     
     Eegeo::dv3 center = m_uiCameraProvider.GetRenderCameraForUI().GetEcefLocation();
     Eegeo::v3 forward(headTrackedOrientation.GetRow(2));
     Eegeo::v3 top(center.ToSingle().Norm());
     Eegeo::v3 right(Eegeo::v3::Cross(top, forward));
     
     Eegeo::v3 vA = center.ToSingle();
     Eegeo::v3 vB = m_uiCameraProvider.GetOrientation().GetRow(2);
     float angle = Eegeo::Math::Rad2Deg(Eegeo::Math::ACos(Eegeo::v3::Dot(vA, vB)/(vA.Length()*vB.Length())));
     
     
     const float MarginAngle = 85;
     const int PositionMultiplier = 600;
     
     bool shouldUpdatePosition = false;
     
     if(!m_isMenuShown && angle<=MarginAngle)
     {
         m_isMenuShown = true;
         shouldUpdatePosition = true;
         m_cachedHeadTracker = m_uiCameraProvider.GetHeadTrackerOrientation();
         m_cachedCenter = center;
     }
     else if(m_isMenuShown && angle>MarginAngle)
     {
         m_isMenuShown = false;
         shouldUpdatePosition = true;
     }
     
     if ((m_cachedCenter - center).LengthSq() > 1) {
         m_cachedCenter = center;
         shouldUpdatePosition = true;
     }
     
     if(shouldUpdatePosition || m_isMenuShown)
     {
         
         std::vector<WorldMenuItemView*> items;
         for(TViewsByModel::iterator it = m_viewsByModel.begin(); it != m_viewsByModel.end(); ++it)
         {
             std::vector<WorldMenuItemView*>::iterator itItems = items.begin();
             for(; itItems != items.end(); ++itItems)
             {
                 if((*itItems)->GetWorldMenuItem().GetId() < it->second->GetWorldMenuItem().GetId())
                 {
                     break;
                 }
             }
             items.insert(itItems, it->second);
         }
         
         float margin = 0.f;
         
         for(std::vector<WorldMenuItemView*>::iterator it = items.begin(); it != items.end(); ++it)
         {
             WorldMenuItemView* pView = *it;
             if(!m_isMenuShown)
             {
                 pView->SetItemShouldRender(false);
                 m_pSelectedArrow->SetItemShouldRender(false);
                 continue;
             }
             margin += pView->GetWorldMenuItem().GetMarginRight();
             
             Eegeo::dv3 position(center + (forward*PositionMultiplier) + (top*45) + ((right*55*halfCount)-(right*margin)));
             pView->SetEcefPosition(position);
             pView->SetItemShouldRender(true);
             m_pSelectedArrow->SetItemShouldRender(true);
             if(m_menuItemId==pView->GetWorldMenuItem().GetId())
             {
                 m_pSelectedArrow->SetEcefPosition(center + (forward*PositionMultiplier) + (top*92) + (right*55*halfCount)-(right*margin));
             }
             halfCount-=1;
             
             margin += pView->GetWorldMenuItem().GetMarginLeft();
             pView->SetItemShouldRender(m_menuItemsShouldRender);
         }
         
         items.clear();
         m_lastCameraPosition = center;
     }
 }
//	This function read KeyBoard and Mouse control to control this scene
//  The control are read at the simulation rate, and two states are kept 
void InputControl(NewtonWorld* world)
{
	// read the mouse position and set the camera direction
	
	static dVector mouse0 (GetMousePos());
	dVector mouse1 (GetMousePos());

	gPrevYawAngle = gYawAngle;
	gPrevRollAngle = gRollAngle;

	if (!MousePick (world, mouse1)) {
		int leftKetDown;

		leftKetDown = IsKeyDown (KeyCode_L_BUTTON);
		// we are not in mouse pick mode, then we are in camera tracking mode
		if (leftKetDown) {
			// when click left mouse button the first time, we reset the camera
			// convert the mouse x position to delta yaw angle
			if (mouse1.m_x > (mouse0.m_x + 1)) {
				gYawAngle += 1.0f * 3.1416f / 180.0f;
				if (gYawAngle > (360.0f * 3.1416f / 180.0f)) {
					gYawAngle -= (360.0f * 3.1416f / 180.0f);
				}
			} else if (mouse1.m_x < (mouse0.m_x - 1)) {
				gYawAngle -= 1.0f * 3.1416f / 180.0f;
				if (gYawAngle < 0.0f) {
					gYawAngle += (360.0f * 3.1416f / 180.0f);
				}
			}

			if (mouse1.m_y > (mouse0.m_y + 1)) {
				gRollAngle += 1.0f * 3.1416f / 180.0f;
				if (gRollAngle > (80.0f * 3.1416f / 180.0f)) {
					gRollAngle = 80.0f * 3.1416f / 180.0f;
				}
			} else if (mouse1.m_y < (mouse0.m_y - 1)) {
				gRollAngle -= 1.0f * 3.1416f / 180.0f;
				if (gRollAngle < -(80.0f * 3.1416f / 180.0f)) {
					gRollAngle = -80.0f * 3.1416f / 180.0f;
				}
			}

			dMatrix cameraDirMat (dRollMatrix(gRollAngle) * dYawMatrix(gYawAngle));
			gCurrCameraDir = cameraDirMat.m_front;
		}
	}

	// save mouse position and left mouse key state for next frame
	mouse0 = mouse1;


	// camera control
	gPrevCameraEyepoint = gCameraEyepoint;
	if (IsKeyDown ('W')) {
		gCameraEyepoint += gCurrCameraDir.Scale (CAMERA_SPEED / 60.0f);
	} else if (IsKeyDown  ('S')) {
		gCameraEyepoint -= gCurrCameraDir.Scale (CAMERA_SPEED / 60.0f);
	}

	if (IsKeyDown ('D')) {
		dVector up (0.0f, 1.0f, 0.0f);
		dVector right (gCurrCameraDir * up);
		gCameraEyepoint += right.Scale (CAMERA_SPEED / 60.0f);
	} else if (IsKeyDown ('A')) {
		dVector up (0.0f, 1.0f, 0.0f);
		dVector right (gCurrCameraDir * up);
		gCameraEyepoint -= right.Scale (CAMERA_SPEED / 60.0f);
	}
} 
Example #4
0
//-----------------------------------------------------------------------------
// Strider muzzle flashes
//-----------------------------------------------------------------------------
void MuzzleFlash_Strider( ClientEntityHandle_t hEntity, int attachmentIndex )
{
	VPROF_BUDGET( "MuzzleFlash_Strider", VPROF_BUDGETGROUP_PARTICLE_RENDERING );

	// If the client hasn't seen this entity yet, bail.
	matrix3x4_t	matAttachment;
	if ( !FX_GetAttachmentTransform( hEntity, attachmentIndex, matAttachment ) )
		return;

	CSmartPtr<CLocalSpaceEmitter> pSimple = CLocalSpaceEmitter::Create( "MuzzleFlash_Strider", hEntity, attachmentIndex );

	SimpleParticle *pParticle;
	Vector			forward(1,0,0), offset; //NOTENOTE: All coords are in local space

	float flScale = random->RandomFloat( 3.0f, 4.0f );

	float burstSpeed = random->RandomFloat( 400.0f, 600.0f );

#define	FRONT_LENGTH 12

	// Front flash
	for ( int i = 1; i < FRONT_LENGTH; i++ )
	{
		offset = (forward * (i*2.0f*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.1f;

		pParticle->m_vecVelocity = forward * burstSpeed;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255.0f;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 6.0f, 8.0f ) * (FRONT_LENGTH-(i))/(FRONT_LENGTH*0.75f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}
	
	Vector right(0,1,0), up(0,0,1);
	Vector dir = right - up;

#define	SIDE_LENGTH	8

	burstSpeed = random->RandomFloat( 400.0f, 600.0f );

	// Diagonal flash
	for ( int i = 1; i < SIDE_LENGTH; i++ )
	{
		offset = (dir * (i*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.2f;

		pParticle->m_vecVelocity = dir * burstSpeed * 0.25f;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	dir = right + up;
	burstSpeed = random->RandomFloat( 400.0f, 600.0f );

	// Diagonal flash
	for ( int i = 1; i < SIDE_LENGTH; i++ )
	{
		offset = (-dir * (i*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.2f;

		pParticle->m_vecVelocity = dir * -burstSpeed * 0.25f;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	dir = up;
	burstSpeed = random->RandomFloat( 400.0f, 600.0f );

	// Top flash
	for ( int i = 1; i < SIDE_LENGTH; i++ )
	{
		offset = (dir * (i*flScale));

		pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( VarArgs( "effects/combinemuzzle%d", random->RandomInt(1,2) ) ), offset );
			
		if ( pParticle == NULL )
			return;

		pParticle->m_flLifetime		= 0.0f;
		pParticle->m_flDieTime		= 0.2f;

		pParticle->m_vecVelocity = dir * burstSpeed * 0.25f;

		pParticle->m_uchColor[0]	= 255;
		pParticle->m_uchColor[1]	= 255;
		pParticle->m_uchColor[2]	= 255;

		pParticle->m_uchStartAlpha	= 255;
		pParticle->m_uchEndAlpha	= 0;

		pParticle->m_uchStartSize	= ( (random->RandomFloat( 2.0f, 4.0f ) * (SIDE_LENGTH-(i))/(SIDE_LENGTH*0.5f)) * flScale );
		pParticle->m_uchEndSize		= pParticle->m_uchStartSize;
		pParticle->m_flRoll			= random->RandomInt( 0, 360 );
		pParticle->m_flRollDelta	= 0.0f;
	}

	pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), pSimple->GetPMaterial( "effects/strider_muzzle" ), vec3_origin );
		
	if ( pParticle == NULL )
		return;

	pParticle->m_flLifetime		= 0.0f;
	pParticle->m_flDieTime		= random->RandomFloat( 0.3f, 0.4f );

	pParticle->m_vecVelocity.Init();

	pParticle->m_uchColor[0]	= 255;
	pParticle->m_uchColor[1]	= 255;
	pParticle->m_uchColor[2]	= 255;

	pParticle->m_uchStartAlpha	= 255;
	pParticle->m_uchEndAlpha	= 0;

	pParticle->m_uchStartSize	= flScale * random->RandomFloat( 12.0f, 16.0f );
	pParticle->m_uchEndSize		= 0.0f;
	pParticle->m_flRoll			= random->RandomInt( 0, 360 );
	pParticle->m_flRollDelta	= 0.0f;

	Vector		origin;
	MatrixGetColumn( matAttachment, 3, &origin );

	int entityIndex = ClientEntityList().HandleToEntIndex( hEntity );
	if ( entityIndex >= 0 )
	{
		dlight_t *el = effects->CL_AllocElight( LIGHT_INDEX_MUZZLEFLASH + entityIndex );

		el->origin	= origin;

		el->color.r = 64;
		el->color.g = 128;
		el->color.b = 255;
		el->color.exponent = 5;

		el->radius	= random->RandomInt( 100, 150 );
		el->decay	= el->radius / 0.05f;
		el->die		= gpGlobals->curtime + 0.1f;
	}
}
Example #5
0
osg::Node* createLogo(const std::string& filename, const std::string& label, const std::string& subscript)
{
    osg::BoundingBox bb(osg::Vec3(0.0f,0.0f,0.0f),osg::Vec3(100.0f,100.0f,100.0f));
    float chordRatio = 0.5f; 
    float sphereRatio = 0.6f; 

    // create a group to hold the whole model.
    osg::Group* logo_group = new osg::Group;

    osg::Quat r1,r2;
    r1.makeRotate(-osg::inDegrees(45.0f),0.0f,0.0f,1.0f);
    r2.makeRotate(osg::inDegrees(45.0f),1.0f,0.0f,0.0f);


    MyBillboardTransform* xform = new MyBillboardTransform;
    xform->setPivotPoint(bb.center());
    xform->setPosition(bb.center());
    xform->setAttitude(r1*r2);


//     // create a transform to orientate the box and globe.
//     osg::MatrixTransform* xform = new osg::MatrixTransform;
//     xform->setDataVariance(osg::Object::STATIC);
//     xform->setMatrix(osg::Matrix::translate(-bb.center())*
//                      osg::Matrix::rotate(-osg::inDegrees(45.0f),0.0f,0.0f,1.0f)*
//                      osg::Matrix::rotate(osg::inDegrees(45.0f),1.0f,0.0f,0.0f)*
//                      osg::Matrix::translate(bb.center()));

    // add the box and globe to it.
    //xform->addChild(createBox(bb,chordRatio));
    //xform->addChild(createBoxNo5(bb,chordRatio));
    xform->addChild(createBoxNo5No2(bb,chordRatio));
    // add the transform to the group.
    logo_group->addChild(xform);

    logo_group->addChild(createGlobe(bb,sphereRatio,filename));

    // add the text to the group.
    //group->addChild(createTextBelow(bb));
    logo_group->addChild(createTextLeft(bb, label, subscript));
    
    
    // create the backdrop to render the shadow to.
    osg::Vec3 corner(-900.0f,150.0f,-100.0f);
    osg::Vec3 top(0.0f,0.0f,300.0f); top += corner;
    osg::Vec3 right(1100.0f,0.0f,0.0f); right += corner;
    
    
//     osg::Group* backdrop = new osg::Group;
//     backdrop->addChild(createBackdrop(corner,top,right));

    osg::ClearNode* backdrop = new osg::ClearNode;
    backdrop->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,0.0f));

    //osg::Vec3 lightPosition(-500.0f,-2500.0f,500.0f);
    //osg::Node* scene = createShadowedScene(logo_group,backdrop,lightPosition,0.0f,0);

    osg::Group* scene = new osg::Group;

    osg::StateSet* stateset = scene->getOrCreateStateSet();
    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE|osg::StateAttribute::OFF);


    scene->addChild(logo_group);
    scene->addChild(backdrop);

    return scene;
}
Example #6
0
 void strafe( Scalar _right )
 {
   Tracker::center( Tracker::center() + right().normalized() * _right );
 }
Example #7
0
void rc_recieve() {
  if (mySwitch.available()) {
    
    char recieved_value = mySwitch.getReceivedValue();

    if(DEBUG) {
        Serial.print("RC recieved: "); Serial.println(recieved_value);
    }

    bool do_record = true;

    switch(recieved_value) {
    case 'w':
        // straight forward
        //if (!ultrasound_stop(25)) {
        forward(speed);
        //}
        break;
    case 's':
        // straight backward
        backward(speed);
        break;
    case 'a':
        // Turn left on axis by spinning both
        // motors in opposite directions
        left(speed * TURN_SPEED_ADJ);
        break;
    case 'q':
        // Turn left spinning only right motor
        // So move slightly forward
        left(0, speed * TURN_SPEED_ADJ);
        break;
    case 'z':
        // Turn left spinning only left motor
        // So move slightly backward
        left(speed * TURN_SPEED_ADJ, 0);
        break;
    case 'd':
        // Turn right on axis by spinning both
        // motors in opposite directions
        right(speed * TURN_SPEED_ADJ);
        break;
    case 'e':
        // Turn right spinning only left motor
        // So move slightly forward
        right(speed * TURN_SPEED_ADJ, 0);
        break;
    case 'c':
        // Turn right spinning only right motor
        // So move slightly backward
         right(0, speed * TURN_SPEED_ADJ);
        break;
    case char(32): // <space>
        brake();
        break;
    case '1':
    case '2':
    case '3':
    case '4':
        speed = SPEEDS[int(recieved_value) - 49];
        break;
    case 'o':
        delay(STOP_DELAY);
        break;
    case 'x':
        mySwitch.clear();
        do_record = false;
        break;
    case 'p':
        // Debug by printing values to serial
        if(DEBUG)
            mySwitch.print_values();
        mySwitch.play_back();
        do_record = false;
        break;
    default:
        // If a value is not handled, do not record it
        do_record = false;
    }

    // Don't record debugging and recording control characters
    if(do_record && mySwitch.can_record()) {
        mySwitch.record_value(recieved_value);
    }

    mySwitch.resetAvailable();
  } else {
      delay(STOP_DELAY);
      stop();
  }
}
Example #8
0
int main(int argc, char **argv) {
	char * image = NULL;
	char * activity = NULL;
	switch(argc){
		case 3:
			if (strcmp(argv[1],"-in")==0){
				image= argv[2];
				activity = NULL;
			}else{
				perror("Wrong parameters");
				exit(-1);
			}
			break;
		case 5:
			if (strcmp(argv[1],"-in")==0 && strcmp(argv[3],"-z")==0){
				image= argv[2];
				activity = argv[4];
			}else{
				if (strcmp(argv[1],"-z")==0 && strcmp(argv[3],"-in")==0){
					activity = argv[2];
					image= argv[4];
				}else{
					perror("Wrong parameters");
					exit(-1);
				}
			}
			break;
		default:
			perror("Wrong parameters");
			exit(-1);
			break;
	}

	QApplication app(argc, argv);

	RenderWidget *widget = new RenderWidget(image, activity);


	QPushButton front("vorn");
	QObject::connect( &front, SIGNAL( clicked() ),
			widget, SLOT( setCameraFront() ) );
	front.show();

	QPushButton back("hinten");
	QObject::connect( &back, SIGNAL( clicked() ),
			widget, SLOT( setCameraBack() ) );
	back.show();

	QPushButton right("rechts");
	QObject::connect( &right, SIGNAL( clicked() ),
			widget, SLOT( setCameraRight() ) );
	right.show();

	QPushButton left("links");
	QObject::connect( &left, SIGNAL( clicked() ),
			widget, SLOT( setCameraLeft() ) );
	left.show();

	QPushButton top("oben");
	QObject::connect( &top, SIGNAL( clicked() ),
			widget, SLOT( setCameraTop() ) );
	top.show();

	QPushButton bottom("unten");
	QObject::connect( &bottom, SIGNAL( clicked() ),
			widget, SLOT( setCameraBottom() ) );
	bottom.show();

	widget->show();	
	return app.exec();
}
Example #9
0
//rangemax query, change returns to answer different questions.
int rmq(int i, int L, int R, int l, int r){
    if(l > R || r < L) return -1;
    if(L >= l && R <= r) return st[i];
    return max( rmq(left(i), L,(L+R)/2, l,r, st), rmq(right(i),((L+R)/2)+1, R,l,r));
}
Example #10
0
/*** edit
*
* Purpose:
*   Inserts character in text at current cursor position.
*
* Input:
*   c		= Character to be entered
*
* Output:
*   FALSE if the line was too long, else true.
*
* Notes:
*
*************************************************************************/
flagType
edit (
    char c
    )
{
    COL     dx;
    fl      fl;                             /* loc to place cursor at       */
    COL     tmpx;
    COL     x;

    /*
     * point at current location
     */
    fl.col = XCUR(pInsCur);
    fl.lin = YCUR(pInsCur);

    if (fWordWrap && xMargin > 0) {

        /*
         * if space entered just past right margin, then copy everything to the right
         * of the space to the next line.
         */
	if (c == ' ' && fl.col >= xMargin) {
	    tmpx = softcr ();
	    CopyStream (NULL, pFileHead, fl.col, fl.lin,
					 tmpx,	 fl.lin+1,
					 fl.col, fl.lin);
	    fl.lin++;
	    fl.col = tmpx;
	    cursorfl (fl);
	    return TRUE;
        } else if (fl.col >= xMargin + 5) {

	    /*	move backward to the beginning of the current word
	     *	and break it there.
	     *
	     *	Make sure we have a line that contains the cursor
	     */
            fInsSpace (fl.col, fl.lin, 0, pFileHead, buf);

	    /*	We'll go backwards to find the first place where
	     *	the char there is non-space and the char to
	     *	the left of it is a space.  We'll break the line at
	     *	that place.
	     */
            for (x = fl.col - 1; x > 1; x--) {
                if (buf[x-1] == ' ' && buf[x] != ' ') {
                    break;
                }
            }

	    /*	if we've found the appropriate word, break it there
	     */
	    if (x > 1) {
		dx = fl.col - x;
		tmpx = softcr ();
		CopyStream (NULL, pFileHead, x,    fl.lin,
					     tmpx, fl.lin + 1,
					     x,    fl.lin);
		fl.col = tmpx + dx;
		fl.lin++;
		cursorfl (fl);
            }
        }
    }

    if (Replace (c, fl.col, fl.lin, pFileHead, fInsert)) {
	right ((CMDDATA)0, (ARG *)NULL, FALSE);
	return TRUE;
    } else {
	LengthCheck (fl.lin, 0, NULL);
	return FALSE;
    }
}
int main()
{
    cv::Mat image = cv::imread("/home/ees/Pictures/images.jpeg");
  BlobDetector<LoG> detector(image);
  cv::Mat blobs = detector.highlightBlobs();
  cv::imshow("b", blobs);
  cv::waitKey();
  return 0;

  const std::string WALL_STR = "./images/wall/";
  const std::string GRAF_STR = "./images/graf/";
  const std::string BIKES_STR = "./images/bikes/";
  const std::string LEUVEN_STR = "./images/leuven/";

  const std::string stringArr[] {WALL_STR, GRAF_STR, BIKES_STR, LEUVEN_STR};

  for (int imagePack = 0; imagePack < 4; ++imagePack)
  {
    HarrisMatcher matcher((Type)imagePack);
    std::vector<Match> result = matcher.getSortedPairSet();
    std::ofstream resultFile(stringArr[imagePack] + "Harris/" + "results.txt");

    int i = 0;
    for (const Match& match : result)
    {
      cv::Mat im1 = match.im1->clone();
      cv::Mat im2 = match.im2->clone();

      cv::Mat stitched = cv::Mat::zeros(std::max(im1.rows, im2.rows), im1.cols + im2.cols, CV_8UC3);
      cv::Mat left(stitched, cv::Rect(0, 0, im1.cols, im1.rows));
      cv::Mat right(stitched, cv::Rect(im1.cols, 0, im2.cols, im2.rows));

      cv::Mat transform = readTransform(transforms[i]);

      im1.copyTo(left);
      im2.copyTo(right);

      cv::RNG rng;
      int totalPairs = match.pairs.size();
      int correctCount = 0;

      for (auto it = match.pairs.begin(); it != match.pairs.end(); ++it)
      {
        cv::Point orig = it->p2;
        cv::Point transformed = applyTransform(transform, it->p1, im1);

        bool isCorrect = false;
        if (std::abs(orig.x - transformed.x) <= 5 && std::abs(orig.y - transformed.y) <= 5)
        {
          ++correctCount;
          isCorrect = true;
        }

        /*if (it->distance < 0.1)*/ {
          cv::Point p(it->p2.x + im1.cols, it->p2.y);
          cv::Scalar color = isCorrect ? cv::Scalar(0,0,0) : cv::Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
          cv::circle(stitched, it->p1, 3, color, 3);
          cv::circle(stitched, p, 3, color, 3);
          cv::line(stitched, it->p1, p, color);
        }
      }

      static std::string pics[] { "img1", "img2", "img3"};
      cv::imwrite(stringArr[imagePack] + "Harris/" + std::string("img0->") + pics[i] + ".jpg", stitched);
      resultFile << "img0 -> " << pics[i] << ":\n"
                 << "Total pairs: " << totalPairs << '\n'
                 << "Correct pairs: " << correctCount << '\n'
                 << "Persentage: " << (int)ceil(((double)correctCount / (double)totalPairs) * 100) << "%\n" << std::endl;
      ++i;
    }
    resultFile.close();
  }

  for (int i = 0; i < 4; ++i)
  {
    SiftMatcher matcher((Type)i);
    matcher.match();
  }

  return 0;
}
Example #12
0
/* Test the method 'distance'*/
TEST_F(PositionVectorTest, test_method_distance) {
    {
        PositionVector vec1;
        vec1.push_back(Position(1,0));
        vec1.push_back(Position(10,0));
        vec1.push_back(Position(10,5));
        vec1.push_back(Position(20,5));
        Position on(4,0);
        Position left(4,1);
        Position right(4,-1);
        Position left2(4,2);
        Position right2(4,-2);
        Position cornerRight(13,-4);
        Position cornerLeft(7,9);
        Position before(-3,-3);
        Position beyond(24,8);

        EXPECT_EQ(0, vec1.distance2D(on));
        EXPECT_EQ(1, vec1.distance2D(left));
        EXPECT_EQ(1, vec1.distance2D(right));
        EXPECT_EQ(2, vec1.distance2D(left2));
        EXPECT_EQ(2, vec1.distance2D(right2));
        EXPECT_EQ(5, vec1.distance2D(cornerRight));
        EXPECT_EQ(5, vec1.distance2D(cornerLeft));

        EXPECT_EQ(GeomHelper::INVALID_OFFSET,  vec1.distance2D(before, true));
        EXPECT_EQ(GeomHelper::INVALID_OFFSET,  vec1.distance2D(beyond, true));
        EXPECT_EQ(5, vec1.distance2D(before));
        EXPECT_EQ(5, vec1.distance2D(beyond));
    }

    {
        PositionVector vec1; // the same tests as before, mirrored on x-axis
        vec1.push_back(Position(1,0));
        vec1.push_back(Position(10,0));
        vec1.push_back(Position(10,-5));
        vec1.push_back(Position(20,-5));
        Position on(4,0);
        Position left(4,-1);
        Position right(4,1);
        Position left2(4,-2);
        Position right2(4,2);
        Position cornerRight(13,4);
        Position cornerLeft(7,-9);
        Position before(-3,3);
        Position beyond(24,-8);

        EXPECT_EQ(0, vec1.distance2D(on));
        EXPECT_EQ(1, vec1.distance2D(left));
        EXPECT_EQ(1, vec1.distance2D(right));
        EXPECT_EQ(2, vec1.distance2D(left2));
        EXPECT_EQ(2, vec1.distance2D(right2));
        EXPECT_EQ(5, vec1.distance2D(cornerRight));
        EXPECT_EQ(5, vec1.distance2D(cornerLeft));

        EXPECT_EQ(GeomHelper::INVALID_OFFSET,  vec1.distance2D(before, true));
        EXPECT_EQ(GeomHelper::INVALID_OFFSET,  vec1.distance2D(beyond, true));
        EXPECT_EQ(5, vec1.distance2D(before));
        EXPECT_EQ(5, vec1.distance2D(beyond));
    }
}
Example #13
0
/* Test the method 'transformToVectorCoordinates'*/
TEST_F(PositionVectorTest, test_method_transformToVectorCoordinates) {
    {
        PositionVector vec1;
        vec1.push_back(Position(1,0));
        vec1.push_back(Position(10,0));
        vec1.push_back(Position(10,5));
        vec1.push_back(Position(20,5));
        Position on(4,0);
        Position left(4,1);
        Position right(4,-1);
        Position left2(4,2);
        Position right2(4,-2);
        Position cornerRight(13,-4);
        Position cornerLeft(7,9);
        Position before(0,-1);
        Position beyond(24,9);

        EXPECT_EQ(Position(3, 0),  vec1.transformToVectorCoordinates(on));
        EXPECT_EQ(Position(3, -1),  vec1.transformToVectorCoordinates(left));
        EXPECT_EQ(Position(3, 1),  vec1.transformToVectorCoordinates(right));
        EXPECT_EQ(Position(3, -2),  vec1.transformToVectorCoordinates(left2));
        EXPECT_EQ(Position(3, 2),  vec1.transformToVectorCoordinates(right2));
        EXPECT_EQ(Position(9, 5),  vec1.transformToVectorCoordinates(cornerRight));
        EXPECT_EQ(Position(14, -5),  vec1.transformToVectorCoordinates(cornerLeft));

        EXPECT_EQ(Position::INVALID,  vec1.transformToVectorCoordinates(before));
        EXPECT_EQ(Position::INVALID,  vec1.transformToVectorCoordinates(beyond));
        EXPECT_EQ(Position(-1, 1),  vec1.transformToVectorCoordinates(before, true));
        EXPECT_EQ(Position(28, -4),  vec1.transformToVectorCoordinates(beyond, true));
    }

    {
        PositionVector vec1; // the same tests as before, mirrored on x-axis
        vec1.push_back(Position(1,0));
        vec1.push_back(Position(10,0));
        vec1.push_back(Position(10,-5));
        vec1.push_back(Position(20,-5));
        Position on(4,0);
        Position left(4,-1);
        Position right(4,1);
        Position left2(4,-2);
        Position right2(4,2);
        Position cornerRight(13,4);
        Position cornerLeft(7,-9);
        Position before(0,1);
        Position beyond(24,-9);

        EXPECT_EQ(Position(3, 0),  vec1.transformToVectorCoordinates(on));
        EXPECT_EQ(Position(3, 1),  vec1.transformToVectorCoordinates(left));
        EXPECT_EQ(Position(3, -1),  vec1.transformToVectorCoordinates(right));
        EXPECT_EQ(Position(3, 2),  vec1.transformToVectorCoordinates(left2));
        EXPECT_EQ(Position(3, -2),  vec1.transformToVectorCoordinates(right2));
        EXPECT_EQ(Position(9, -5),  vec1.transformToVectorCoordinates(cornerRight));
        EXPECT_EQ(Position(14, 5),  vec1.transformToVectorCoordinates(cornerLeft));

        EXPECT_EQ(Position::INVALID,  vec1.transformToVectorCoordinates(before));
        EXPECT_EQ(Position::INVALID,  vec1.transformToVectorCoordinates(beyond));
        EXPECT_EQ(Position(-1, -1),  vec1.transformToVectorCoordinates(before, true));
        EXPECT_EQ(Position(28, 4),  vec1.transformToVectorCoordinates(beyond, true));
    }
}
Example #14
0
 bool contains(int x, int y) const {
     return (x >= left() && x < right() &&
             y >= top() && y < bottom());
 }
Example #15
0
void MythRenderOpenGL2::DrawRoundRectPriv(const QRect &area, int cornerRadius,
                                          const QBrush &fillBrush,
                                          const QPen &linePen, int alpha)
{
    int lineWidth = linePen.width();
    int halfline  = lineWidth / 2;
    int rad = cornerRadius - halfline;

    if ((area.width() / 2) < rad)
        rad = area.width() / 2;

    if ((area.height() / 2) < rad)
        rad = area.height() / 2;
    int dia = rad * 2;


    QRect r(area.left() + halfline, area.top() + halfline,
            area.width() - (halfline * 2), area.height() - (halfline * 2));

    QRect tl(r.left(),  r.top(), rad, rad);
    QRect tr(r.left() + r.width() - rad, r.top(), rad, rad);
    QRect bl(r.left(),  r.top() + r.height() - rad, rad, rad);
    QRect br(r.left() + r.width() - rad, r.top() + r.height() - rad, rad, rad);

    SetBlend(true);
    DisableTextures();

    m_glEnableVertexAttribArray(VERTEX_INDEX);

    if (fillBrush.style() != Qt::NoBrush)
    {
        // Get the shaders
        int elip = m_shaders[kShaderCircle];
        int fill = m_shaders[kShaderSimple];

        // Set the fill color
        m_glVertexAttrib4f(COLOR_INDEX,
                           fillBrush.color().red() / 255.0,
                           fillBrush.color().green() / 255.0,
                           fillBrush.color().blue() / 255.0,
                          (fillBrush.color().alpha() / 255.0) * (alpha / 255.0));

        // Set the radius
        m_parameters[0][2] = rad;
        m_parameters[0][3] = rad - 1.0;

        // Enable the Circle shader
        SetShaderParams(elip, &m_projection[0][0], "u_projection");
        SetShaderParams(elip, &m_transforms.top().m[0][0], "u_transform");

        // Draw the top left segment
        m_parameters[0][0] = tl.left() + rad;
        m_parameters[0][1] = tl.top() + rad;
        SetShaderParams(elip, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, tl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the top right segment
        m_parameters[0][0] = tr.left();
        m_parameters[0][1] = tr.top() + rad;
        SetShaderParams(elip, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, tr);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the bottom left segment
        m_parameters[0][0] = bl.left() + rad;
        m_parameters[0][1] = bl.top();
        SetShaderParams(elip, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, bl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the bottom right segment
        m_parameters[0][0] = br.left();
        m_parameters[0][1] = br.top();
        SetShaderParams(elip, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, br);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Fill the remaining areas
        QRect main(r.left() + rad, r.top(), r.width() - dia, r.height());
        QRect left(r.left(), r.top() + rad, rad, r.height() - dia);
        QRect right(r.left() + r.width() - rad, r.top() + rad, rad, r.height() - dia);

        EnableShaderObject(fill);
        SetShaderParams(fill, &m_projection[0][0], "u_projection");
        SetShaderParams(fill, &m_transforms.top().m[0][0], "u_transform");

        GetCachedVBO(GL_TRIANGLE_STRIP, main);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        GetCachedVBO(GL_TRIANGLE_STRIP, left);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        GetCachedVBO(GL_TRIANGLE_STRIP, right);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        m_glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

    if (linePen.style() != Qt::NoPen)
    {
        // Get the shaders
        int edge = m_shaders[kShaderCircleEdge];
        int vline = m_shaders[kShaderVertLine];
        int hline = m_shaders[kShaderHorizLine];

        // Set the line color
        m_glVertexAttrib4f(COLOR_INDEX,
                           linePen.color().red() / 255.0,
                           linePen.color().green() / 255.0,
                           linePen.color().blue() / 255.0,
                          (linePen.color().alpha() / 255.0) * (alpha / 255.0));

        // Set the radius and width
        m_parameters[0][2] = rad - lineWidth / 2.0;
        m_parameters[0][3] = lineWidth / 2.0;

        // Enable the edge shader
        SetShaderParams(edge, &m_projection[0][0], "u_projection");
        SetShaderParams(edge, &m_transforms.top().m[0][0], "u_transform");

        // Draw the top left edge segment
        m_parameters[0][0] = tl.left() + rad;
        m_parameters[0][1] = tl.top() + rad;
        SetShaderParams(edge, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, tl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the top right edge segment
        m_parameters[0][0] = tr.left();
        m_parameters[0][1] = tr.top() + rad;
        SetShaderParams(edge, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, tr);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the bottom left edge segment
        m_parameters[0][0] = bl.left() + rad;
        m_parameters[0][1] = bl.top();
        SetShaderParams(edge, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, bl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the bottom right edge segment
        m_parameters[0][0] = br.left();
        m_parameters[0][1] = br.top();
        SetShaderParams(edge, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, br);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Vertical lines
        SetShaderParams(vline, &m_projection[0][0], "u_projection");
        SetShaderParams(vline, &m_transforms.top().m[0][0], "u_transform");

        m_parameters[0][1] = lineWidth / 2.0;
        QRect vl(r.left(), r.top() + rad,
                 lineWidth, r.height() - dia);

        // Draw the left line segment
        m_parameters[0][0] = vl.left() + lineWidth;
        SetShaderParams(vline, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, vl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the right line segment
        vl.translate(r.width() - lineWidth, 0);
        m_parameters[0][0] = vl.left();
        SetShaderParams(vline, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, vl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Horizontal lines
        SetShaderParams(hline, &m_projection[0][0], "u_projection");
        SetShaderParams(hline, &m_transforms.top().m[0][0], "u_transform");
        QRect hl(r.left() + rad, r.top(),
                 r.width() - dia, lineWidth);

        // Draw the top line segment
        m_parameters[0][0] = hl.top() + lineWidth;
        SetShaderParams(hline, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, hl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        // Draw the bottom line segment
        hl.translate(0, r.height() - lineWidth);
        m_parameters[0][0] = hl.top();
        SetShaderParams(hline, &m_parameters[0][0], "u_parameters");
        GetCachedVBO(GL_TRIANGLE_STRIP, hl);
        m_glVertexAttribPointer(VERTEX_INDEX, VERTEX_SIZE, GL_FLOAT, GL_FALSE,
                                VERTEX_SIZE * sizeof(GLfloat),
                               (const void *) kVertexOffset);
        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        m_glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

    m_glDisableVertexAttribArray(VERTEX_INDEX);
}
Example #16
0
void Ui::AspectRatioResizebleWnd::_applyFrameAspectRatio(float was_ar) {
    if (_use_aspect && _aspect_ratio > 0.001f && _self_resize_effect && !isFullScreen()) {
        const QRect rc = rect();
        const QPoint p = mapToGlobal(rc.topLeft());

        QRect end_rc;
        if (was_ar > 0.001f && fabs((1.0f / _aspect_ratio) - was_ar) < 0.0001f) {
            end_rc = QRect(p.x(), p.y(), rc.height(), rc.width());
        } else {
            end_rc = QRect(p.x(), p.y(), rc.width(), rc.width() / _aspect_ratio);
        }

        const QSize minimum_size = minimumSize();
        if (end_rc.width() < minimum_size.width()) {
            const int w = minimum_size.width();
            const int h = w / _aspect_ratio;
            end_rc.setRight(end_rc.left() + w);
            end_rc.setBottom(end_rc.top() + h);
        }
        if (end_rc.height() < minimum_size.height()) {
            const int h = minimum_size.height();
            const int w = h * _aspect_ratio;
            end_rc.setRight(end_rc.left() + w);
            end_rc.setBottom(end_rc.top() + h);
        }

        QDesktopWidget dw;
        const auto screen_rect = dw.availableGeometry(dw.primaryScreen());

        if (end_rc.right() > screen_rect.right()) {
            const int w = end_rc.width();
            end_rc.setRight(screen_rect.right());
            end_rc.setLeft(end_rc.right() - w);
        }

        if (end_rc.bottom() > screen_rect.bottom()) {
            const int h = end_rc.height();
            end_rc.setBottom(screen_rect.bottom());
            end_rc.setTop(end_rc.bottom() - h);
        }

        if (screen_rect.width() < end_rc.width()) {
            end_rc.setLeft(screen_rect.left());
            end_rc.setRight(screen_rect.right());

            const int h = end_rc.width() / _aspect_ratio;
            end_rc.setTop(end_rc.bottom() - h);
        }

        if (screen_rect.height() < end_rc.height()) {
            end_rc.setTop(screen_rect.top());
            end_rc.setBottom(screen_rect.bottom());

            const int w = end_rc.height() * _aspect_ratio;
            end_rc.setLeft(end_rc.right() - w);
        }

        if (_first_time_use_aspect_ratio) {
            {
                const int best_w = 0.6f * screen_rect.width();
                if (end_rc.width() > best_w) {
                    const int best_h = best_w / _aspect_ratio;
                    end_rc.setLeft((screen_rect.x() + screen_rect.width() - best_w) / 2);
                    end_rc.setRight(end_rc.left() + best_w);

                    end_rc.setTop((screen_rect.y() + screen_rect.height() - best_h) / 2);
                    end_rc.setBottom(end_rc.top() + best_h);
                }
            }
            {/* NEED TO EXECUTE 2 TIMES, BECAUSE CALC FOR BEST W NOT MEANS USING BEST H*/
                const int best_h = 0.8f * screen_rect.height();
                if (end_rc.height() > best_h) {
                    const int best_w = best_h * _aspect_ratio;
                    end_rc.setLeft((screen_rect.x() + screen_rect.width() - best_w) / 2);
                    end_rc.setRight(end_rc.left() + best_w);

                    end_rc.setTop((screen_rect.y() + screen_rect.height() - best_h) / 2);
                    end_rc.setBottom(end_rc.top() + best_h);
                }
            }
            _first_time_use_aspect_ratio = false;
        }

        _self_resize_effect->geometryTo(end_rc, 500);
    }
}
void PlayerController::update()
{
	// NOTE(juha): Get game controller button states.
	if (gamepad_ready) {
		AButton =	SDL_GameControllerGetButton(ControllerHandle, SDL_CONTROLLER_BUTTON_A);
		XButton =	SDL_GameControllerGetButton(ControllerHandle, SDL_CONTROLLER_BUTTON_X);
		Up =		SDL_GameControllerGetButton(ControllerHandle, SDL_CONTROLLER_BUTTON_DPAD_UP);
		Down =		SDL_GameControllerGetButton(ControllerHandle, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
		Left =		SDL_GameControllerGetButton(ControllerHandle, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
		Right =		SDL_GameControllerGetButton(ControllerHandle, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
	
		// NOTE(juha): Get button up/down states.
		if (!AButton)	AButton_up =	true;
		if (!XButton)	XButton_up =	true;
		if (!Up)		Up_up =			true;
		if (!Down)		Down_up =		true;
		if (!Left)		Left_up =		true;
		if (!Right)		Right_up =		true;
	}

	if (!in_menu) {
		// NOTE(juha): Gravitational stuff
		velocity_y += GRAVITY * (16.f / 1000);
		desired.y += (int)velocity_y;
		crouching = false;
	
		if (velocity_y >= 1) {
			in_air = true;
			knight->falling = true;
			knight->is_landed = false;
		}
	
		if (velocity_y >= 7) {
			velocity_y = 7;
		}
	
		if (!in_air) {
			jumping = false;
		}
	}
	
	// NOTE(juha): If there are only two players in the game and the current
	// player controller is for the fourth player, then lock the controller.
	if (in_menu) {
		if (player == 3 && *players == 2) {
			controller_locked = true;
		} else {
			controller_locked = false;
		}
	} else {
		controller_locked = false;
	}
	
	// NOTE(juha): Reading the inputs for single player and multiplayer.
	
	// NOTE(juha): If no input is given, tmp_imput is 9999.
	int tmp_input = 9999;
	
	// TODO(juha): NEEDS REWRITE!
	// Too many conditions, all parts too similar to eachother,
	// input reading from both controller and keyboard too convoluted.

	// MOVE LEFT
	if (playerInput.keyState(key_left) || (Left && !controller_locked)) {
		if ((playerInput.isKeyPressed(key_left) && playerInput.isKeyDown(key_left)) || 
			(Left_up && !controller_locked && gamepad_ready)) {
			if (!in_menu) {
				if (facing_direction == FACING_LEFT) {
					tmp_input = knight->FORWARD;
				} else {
					tmp_input = knight->BACKWARD;
				}
			}
			if (in_menu) {
				menu_x -= 1;
				sfx_select2.play(1);
			}
		}
		left();
		Left_up = false;
	}
	
	// MOVE RIGHT
	if (playerInput.keyState(key_right) || (Right && !controller_locked)) {
		if ((playerInput.isKeyPressed(key_right) && playerInput.isKeyDown(key_right)) || 
			(Right_up && !controller_locked && gamepad_ready)) {
			if (!in_menu) {
				if (facing_direction == FACING_RIGHT) {
					tmp_input = knight->FORWARD;
				} else {
					tmp_input = knight->BACKWARD;
				}
			}
			menu_x += 1;
			if (in_menu) {
				sfx_select2.play(1);
			}
		}
		right();
		Right_up = false;
	}
		
	// DOWN BUTTON
	if (playerInput.keyState(key_down) || (Down && !controller_locked)) {
		if ((playerInput.isKeyPressed(key_down) && playerInput.isKeyDown(key_down)) || 
			(Down_up && !controller_locked && gamepad_ready)) {
			if (!in_menu) {
				tmp_input = knight->DOWN;
			}
			menu_y += 1;
			if (in_menu) {
				sfx_select2.play(1);
			}
		}
		crouch();
		Down_up = false;
	}
		
	// UP BUTTON
	if (playerInput.keyState(key_up) || (Up && !controller_locked)) {
		if ((playerInput.isKeyPressed(key_up) && playerInput.isKeyDown(key_up)) || 
			(Up_up && !controller_locked && gamepad_ready)) {
			if (!in_menu) {
				tmp_input = knight->UP;
			}
			menu_y -= 1;
			if (in_menu) {
				sfx_select2.play(1);
			}
		}
		up();
		Up_up = false;
	}
	
	// JUMP BUTTON
	if (playerInput.keyState(key_jump) || (AButton && !controller_locked)) {
		if ((playerInput.isKeyPressed(key_jump) && playerInput.isKeyDown(key_jump) && !in_menu) || 
			(AButton_up && !controller_locked && gamepad_ready)) {
			tmp_input = knight->JUMP;
		}
		if (!has_jumped) {
			jump();
			AButton_up = false;
			has_jumped = true;
		}
	}
	// NOTE(juha): Prevent players from holding the jump key down.
	if (playerInput.isKeyUp(key_jump)) {
		has_jumped = false;
	}
		
	// ACTION BUTTON
	if (playerInput.keyState(key_action) || (XButton && !controller_locked)) {
		if ((playerInput.isKeyPressed(key_action) && playerInput.isKeyDown(key_action)) || 
			(XButton_up && !controller_locked && gamepad_ready)) {
			if (!in_menu) {
				tmp_input = knight->ACTION;
			} else {
				if (in_game == false) {
					in_game = true;
					*players += 1;
				}
			}
		}
		if (!has_attacked) {
			basicAttack();
			XButton_up = false;
			has_attacked = true;
		}
	}
	
	// NOTE(juha): Prevent players from holding the attack key down.
	if (playerInput.isKeyUp(key_action)) {
		has_attacked = false;
	}

	// MENU BUTTON
	if (playerInput.keyState(key_menu)) {
	}
	
	if (!in_menu) {
		// NOTE(juha): respawn timer
		if (knight->alive == false) {
			if (deathTimer.isStarted() == false) {
				deathTimer.start();
			}
			if (deathTimer.getTicks() >= RESPAWN_TIME) {
				knight->respawn();
				deathTimer.stop();
			}
		}

		// NOTE(juha): Goes through all the special combos.
		for (int i = 0; i < (*moves).size(); ++i) {
			(*moves)[i].tmp_input = tmp_input;
			
			bool continue_execution = false;
			if ((*moves)[i].keys.size() > 0) {
				
				if ((*moves)[i].keys.size() > 1) {
					// NOTE(juha): If the player just turned, then the first
					// key can be counted as forward instead of backward.
					if ((*moves)[i].keys[0].keycode == knight->FORWARD &&
						(*moves)[i].tmp_input == knight->BACKWARD &&
						(*moves)[i].state == 0) {
						(*moves)[i].tmp_input = knight->FORWARD;
					}

					// NOTE(juha): tmp_input 9999 means that no keys were pressed.
					// NOTE(juha): If a right key was pressed, move combos that had that key
					// to the next state. If nothing was pressed, do nothing. If the key
					// wasn't a part of the combo, then return it to the beginning state.
					if ((*moves)[i].keys[(*moves)[i].state].keycode == (*moves)[i].tmp_input &&
						(*moves)[i].executing == false) {
						(*moves)[i].state++;
					} else if ((*moves)[i].tmp_input == 9999) {
						// Do nothing.
					} else {
						(*moves)[i].state = 0;
					}
				
					// NOTE(juha): For combos that require that the player
					// holds a key down, this loop checks if the key is
					// pressed down as the combo is executed.
					for (unsigned int j = 0; j < (*moves)[i].keys.size(); j++) {
						if ((*moves)[i].keys[j].pressed == true) {

							if ((*moves)[i].keys[j].keycode == knight->FORWARD &&
								facing_direction == FACING_LEFT) {
								
								if (playerInput.isKeyPressed(key_left)) {
									continue_execution = true;
								}
							} else if ((*moves)[i].keys[j].keycode == knight->BACKWARD &&
								facing_direction == FACING_LEFT) {
								
								if (playerInput.isKeyPressed(key_right)) {
									continue_execution = true;
								}
							}  else if ((*moves)[i].keys[j].keycode == knight->FORWARD &&
								facing_direction == FACING_RIGHT) {
								
								if (playerInput.isKeyPressed(key_right)) {
									continue_execution = true;
								}
							}  else if ((*moves)[i].keys[j].keycode == knight->BACKWARD &&
								facing_direction == FACING_RIGHT) {
								
								if (playerInput.isKeyPressed(key_left)) {
									continue_execution = true;
								}
							} else if ((*moves)[i].keys[j].keycode == knight->JUMP) {
								
								if (playerInput.isKeyPressed(key_jump)) {
									continue_execution = true;
								}
							} else if ((*moves)[i].keys[j].keycode == knight->DOWN) {
								
								if (playerInput.isKeyPressed(key_down)) {
									continue_execution = true;
								}
							} else if ((*moves)[i].keys[j].keycode == knight->UP) {
								
								if (playerInput.isKeyPressed(key_up)) {
									continue_execution = true;
								}
							} else if ((*moves)[i].keys[j].keycode == knight->ACTION) {
								
								if (playerInput.isKeyPressed(key_action)) {
									continue_execution = true;
								}
							}

						} else {
							continue_execution = true;
						}
						
						// NOTE(juha): For combos that require that the knight
						// is in air, checks if the knight is in air.
						if ((*moves)[i].keys[j].in_air && !in_air) {
							continue_execution = false;
						}
					}
					
					// NOTE(juha): For combos that require that the knight
					// is on ground, checks if the knight is on ground.
					if ((*moves)[i].in_ground && in_air) {
						continue_execution = false;
					}
					
					if (continue_execution == false) {
						(*moves)[i].state = 0;
					}
					
					// NOTE(juha): How much power do the combos require for
					// execution.
					int combopower = 5;
					if ((*moves)[i].keys.size() == (*moves)[i].state &&
						continue_execution == true) {
						if ((*moves)[i].disabled == false && 
							knight->getSpecialPower() > combopower) {
							(*moves)[i].executing = true;
							executing_combo = true;
							knight->executeCombo(combopower);
							printf("executing\n");
						}
						(*moves)[i].state = 0;
					}
				}
			}
		}

		if (jumping) {
			jump();
		}
	
		// NOTE(juha): Calculate horizontal movement.
		velocity_x += ((targetVx - velocity_x) * acceleration) * 0.16667f;
	
		if (fabs(velocity_x) > speed) {
			velocity_x = (velocity_x > 0) ? (speed+1) : -speed;
		}

		if (fabs(velocity_x) < stoppedThreshold) {
			velocity_x = 0;
		}

		if (facing_direction == FACING_RIGHT) {
			desired.x += (int)ceilf(fabs(velocity_x));
		} else {
			desired.x -= (int)ceilf(fabs(velocity_x));
		}

		int deduct = 0;
		attack_hb.y = desired.y + 8;
		targetVx = 0;

		// NOTE(juha): Movements are effects that move the character.
		if (movements.size() > 0) {
			for (unsigned int i = 0; i < movements.size(); i++) {
				if (movements.at(i).executing &&
					movements.at(i).distance_travelled < movements.at(i).range) {
				
					double new_x = movements.at(0).speed * cos(movements.at(i).angle * PI / 180);
					double new_y = movements.at(0).speed * sin(movements.at(i).angle * PI / 180);
	
					if (facing_direction == 1) {
						desired.x += (int)new_x;
					} else {
						desired.x -= (int)new_x;
					}

					desired.y -= (int)new_y;
					movements.at(i).distance_travelled += movements.at(i).speed;
				} else {
					movements.erase(movements.begin() + i);
				}
			}
		}
	}
}
Example #18
0
void right(byte speed)
{
    right(speed, speed);
}
Example #19
0
 void lift( Scalar _up )
 {
   Vec ortho_up = cross(right(),Tracker::direction());
   Tracker::center( Tracker::center() + ortho_up.normalized() * _up );
 }
void Robot::right(bool forward){ right(_speed, forward); }
Example #21
0
void DrawSpriteTangentSpace( const Vector &vecOrigin, float flWidth, float flHeight, color32 color )
{
	unsigned char pColor[4] = { color.r, color.g, color.b, color.a };

	// Generate half-widths
	flWidth *= 0.5f;
	flHeight *= 0.5f;

	// Compute direction vectors for the sprite
	Vector fwd, right( 1, 0, 0 ), up( 0, 1, 0 );
	VectorSubtract( CurrentViewOrigin(), vecOrigin, fwd );
	float flDist = VectorNormalize( fwd );
	if (flDist >= 1e-3)
	{
		CrossProduct( CurrentViewUp(), fwd, right );
		flDist = VectorNormalize( right );
		if (flDist >= 1e-3)
		{
			CrossProduct( fwd, right, up );
		}
		else
		{
			// In this case, fwd == g_vecVUp, it's right above or 
			// below us in screen space
			CrossProduct( fwd, CurrentViewRight(), up );
			VectorNormalize( up );
			CrossProduct( up, fwd, right );
		}
	}

	Vector left = -right;
	Vector down = -up;
	Vector back = -fwd;

	CMeshBuilder meshBuilder;
	Vector point;
	CMatRenderContextPtr pRenderContext( materials );
	IMesh* pMesh = pRenderContext->GetDynamicMesh( );

	meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );

	meshBuilder.Color4ubv (pColor);
	meshBuilder.TexCoord2f (0, 0, 1);
	VectorMA (vecOrigin, -flHeight, up, point);
	VectorMA (point, -flWidth, right, point);
	meshBuilder.TangentS3fv( left.Base() );
	meshBuilder.TangentT3fv( down.Base() );
	meshBuilder.Normal3fv( back.Base() );
	meshBuilder.Position3fv (point.Base());
	meshBuilder.AdvanceVertex();

	meshBuilder.Color4ubv (pColor);
	meshBuilder.TexCoord2f (0, 0, 0);
	VectorMA (vecOrigin, flHeight, up, point);
	VectorMA (point, -flWidth, right, point);
	meshBuilder.TangentS3fv( left.Base() );
	meshBuilder.TangentT3fv( down.Base() );
	meshBuilder.Normal3fv( back.Base() );
	meshBuilder.Position3fv (point.Base());
	meshBuilder.AdvanceVertex();

	meshBuilder.Color4ubv (pColor);
	meshBuilder.TexCoord2f (0, 1, 0);
	VectorMA (vecOrigin, flHeight, up, point);
	VectorMA (point, flWidth, right, point);
	meshBuilder.TangentS3fv( left.Base() );
	meshBuilder.TangentT3fv( down.Base() );
	meshBuilder.Normal3fv( back.Base() );
	meshBuilder.Position3fv (point.Base());
	meshBuilder.AdvanceVertex();

	meshBuilder.Color4ubv (pColor);
	meshBuilder.TexCoord2f (0, 1, 1);
	VectorMA (vecOrigin, -flHeight, up, point);
	VectorMA (point, flWidth, right, point);
	meshBuilder.TangentS3fv( left.Base() );
	meshBuilder.TangentT3fv( down.Base() );
	meshBuilder.Normal3fv( back.Base() );
	meshBuilder.Position3fv (point.Base());
	meshBuilder.AdvanceVertex();
	
	meshBuilder.End();
	pMesh->Draw();
}
 void right(int dist){check("right"); right(float(dist));}
long PilotListBox::AddItem( aListItem* add )
{
	bDone= 0;
	DeadPilotListItem* pItem = dynamic_cast< DeadPilotListItem* >(  add );
	if ( pItem )
	{

		if (itemCount >= MAX_LIST_ITEMS)
		return TOO_MANY_ITEMS;

	
		float lastX = x() + add->x();
		float lastY = y() + skipAmount;
	
		if ( itemCount > 1 )
		{
			lastX = items[itemCount-2]->x();
			lastY = items[itemCount-2]->bottom()  + skipAmount;
		}
		else if ( itemCount )
		{
			lastY = items[itemCount-1]->bottom() + skipAmount;
		}

		if ( (itemCount && !(itemCount % 2)) ) // even ones go somewhere else
		{
			lastX = items[itemCount-1]->x() + add->width() + skipAmount;
			lastY = items[itemCount-1]->y();
		}
	
		

		items[itemCount++] = add;
		add->moveTo( lastX, lastY );

		if ( add->right() > right() ) // can't have it hanging over the edge
		{
			float shrink = right() - add->right();
			add->resize( add->width() +  shrink, add->height() );
		}



		if ( scrollBar  && !(itemCount % 2))
		{
			int itemsTotalHeight = 0;
			if ( items )
				itemsTotalHeight = items[itemCount-1]->bottom() - items[0]->top();

				if ( itemsTotalHeight > scrollBar->height() )
					scrollBar->SetScrollMax( itemsTotalHeight - scrollBar->height() );
				else
					scrollBar->SetScrollMax( 0 );
				
		}		
	}
	else
	{
		aListBox::AddItem( add );
	}

	return NO_ERR;

}
Example #24
0
bool XorNode::accept(AbstractCalculationData* data) const
{
	return (left() ? left()->accept(data) : true) ^ (right() ? right()->accept(data) : true );
}
Example #25
0
int isright(node *nd)
{
	return father(nd) && nd == right(father(nd));
}
Example #26
0
const QRect XfitMan::availableGeometry(int screen) const
{
    QDesktopWidget *d = QApplication::desktop();

    if (screen < 0 || screen >= d->screenCount())
        screen = d->primaryScreen();

    QRect available = d->screenGeometry(screen);

    // Iterate over all the client windows and subtract from the available
    // area the space they reserved on the edges (struts).
    // Note: _NET_WORKAREA is not reliable as it exposes only one
    // rectangular area spanning all screens.
    Display *display = QX11Info::display();
    int x11Screen = d->isVirtualDesktop() ? DefaultScreen(display) : screen;

    Atom ret;
    int format, status;
    uchar* data = 0;
    ulong nitems, after;

    status = XGetWindowProperty(display, QX11Info::appRootWindow(x11Screen),
                                atom("_NET_CLIENT_LIST"), 0L, ~0L, False, XA_WINDOW,
                                &ret, &format, &nitems, &after, &data);

    if (status == Success && ret == XA_WINDOW && format == 32 && nitems)
    {
        const QRect desktopGeometry = d->rect();

        Window* xids = (Window*) data;
        for (quint32 i = 0; i < nitems; ++i)
        {
            ulong nitems2;
            uchar* data2 = 0;
            status = XGetWindowProperty(display, xids[i],
                                        atom("_NET_WM_STRUT_PARTIAL"), 0, 12, False, XA_CARDINAL,
                                        &ret, &format, &nitems2, &after, &data2);

            if (status == Success && ret == XA_CARDINAL && format == 32 && nitems2 == 12)
            {
                ulong* struts = (ulong*) data2;

                QRect left(desktopGeometry.x(),
                           desktopGeometry.y() + struts[4],
                           struts[0],
                           struts[5] - struts[4]);
                if (available.intersects(left))
                    available.setX(left.width());

                QRect right(desktopGeometry.x() + desktopGeometry.width() - struts[1],
                            desktopGeometry.y() + struts[6],
                            struts[1],
                            struts[7] - struts[6]);
                if (available.intersects(right))
                    available.setWidth(right.x() - available.x());

                QRect top(desktopGeometry.x() + struts[8],
                          desktopGeometry.y(),
                          struts[9] - struts[8],
                          struts[2]);
                if (available.intersects(top))
                    available.setY(top.height());

                QRect bottom(desktopGeometry.x() + struts[10],
                             desktopGeometry.y() + desktopGeometry.height() - struts[3],
                             struts[11] - struts[10],
                             struts[3]);
                if (available.intersects(bottom))
                    available.setHeight(bottom.y() - available.y());
            }
            if (data2)
                XFree(data2);
        }
    }
    if (data)
        XFree(data);

    return available;
}
Example #27
0
QRectF CartesianChartLayout::calculateAxisGeometry(const QRectF &geometry, const QList<ChartAxisElement *> &axes) const
{
    QSizeF left(0,0);
    QSizeF minLeft(0,0);
    QSizeF right(0,0);
    QSizeF minRight(0,0);
    QSizeF bottom(0,0);
    QSizeF minBottom(0,0);
    QSizeF top(0,0);
    QSizeF minTop(0,0);
    QSizeF labelExtents(0,0);
    int leftCount = 0;
    int rightCount = 0;
    int topCount = 0;
    int bottomCount = 0;

    foreach (ChartAxisElement *axis , axes) {

        if (!axis->isVisible())
            continue;


        QSizeF size = axis->effectiveSizeHint(Qt::PreferredSize);
        //this is used to get single thick font size
        QSizeF minSize = axis->effectiveSizeHint(Qt::MinimumSize);

        switch (axis->axis()->alignment()) {
        case Qt::AlignLeft:
           left.setWidth(left.width()+size.width());
           left.setHeight(qMax(left.height(),size.height()));
           minLeft.setWidth(minLeft.width()+minSize.width());
           minLeft.setHeight(qMax(minLeft.height(),minSize.height()));
           labelExtents.setHeight(qMax(size.height(), labelExtents.height()));
           leftCount++;
           break;
        case Qt::AlignRight:
            right.setWidth(right.width()+size.width());
            right.setHeight(qMax(right.height(),size.height()));
            minRight.setWidth(minRight.width()+minSize.width());
            minRight.setHeight(qMax(minRight.height(),minSize.height()));
            labelExtents.setHeight(qMax(size.height(), labelExtents.height()));
            rightCount++;
            break;
        case Qt::AlignTop:
            top.setWidth(qMax(top.width(),size.width()));
            top.setHeight(top.height()+size.height());
            minTop.setWidth(qMax(minTop.width(),minSize.width()));
            minTop.setHeight(minTop.height()+minSize.height());
            labelExtents.setWidth(qMax(size.width(), labelExtents.width()));
            topCount++;
            break;
        case Qt::AlignBottom:
            bottom.setWidth(qMax(bottom.width(), size.width()));
            bottom.setHeight(bottom.height() + size.height());
            minBottom.setWidth(qMax(minBottom.width(),minSize.width()));
            minBottom.setHeight(minBottom.height() + minSize.height());
            labelExtents.setWidth(qMax(size.width(), labelExtents.width()));
            bottomCount++;
            break;
        default:
            qWarning()<<"Axis is without alignment !";
            break;
        }
    }

    qreal totalVerticalAxes = leftCount + rightCount;
    qreal leftSqueezeRatio = 1.0;
    qreal rightSqueezeRatio = 1.0;
    qreal vratio = 0;

    if (totalVerticalAxes > 0)
        vratio = (maxAxisPortion * geometry.width()) / totalVerticalAxes;

    if (leftCount > 0) {
        int maxWidth = vratio * leftCount;
        if (left.width() > maxWidth) {
            leftSqueezeRatio = maxWidth / left.width();
            left.setWidth(maxWidth);
        }
    }
    if (rightCount > 0) {
        int maxWidth = vratio * rightCount;
        if (right.width() > maxWidth) {
            rightSqueezeRatio = maxWidth / right.width();
            right.setWidth(maxWidth);
        }
    }

    qreal totalHorizontalAxes = topCount + bottomCount;
    qreal topSqueezeRatio = 1.0;
    qreal bottomSqueezeRatio = 1.0;
    qreal hratio = 0;

    if (totalHorizontalAxes > 0)
        hratio = (maxAxisPortion * geometry.height()) / totalHorizontalAxes;

    if (topCount > 0) {
        int maxHeight = hratio * topCount;
        if (top.height() > maxHeight) {
            topSqueezeRatio = maxHeight / top.height();
            top.setHeight(maxHeight);
        }
    }
    if (bottomCount > 0) {
        int maxHeight = hratio * bottomCount;
        if (bottom.height() > maxHeight) {
            bottomSqueezeRatio = maxHeight / bottom.height();
            bottom.setHeight(maxHeight);
        }
    }

    qreal minHeight = qMax(minLeft.height(),minRight.height()) + 1;
    qreal minWidth = qMax(minTop.width(),minBottom.width()) + 1;

    // Ensure that there is enough space for first and last tick labels.
    left.setWidth(qMax(labelExtents.width(), left.width()));
    right.setWidth(qMax(labelExtents.width(), right.width()));
    top.setHeight(qMax(labelExtents.height(), top.height()));
    bottom.setHeight(qMax(labelExtents.height(), bottom.height()));

    QRectF chartRect = geometry.adjusted(qMax(left.width(),minWidth/2), qMax(top.height(), minHeight/2),-qMax(right.width(),minWidth/2),-qMax(bottom.height(),minHeight/2));

    qreal leftOffset = 0;
    qreal rightOffset = 0;
    qreal topOffset = 0;
    qreal bottomOffset = 0;

    foreach (ChartAxisElement *axis , axes) {

        if (!axis->isVisible())
            continue;

        QSizeF size = axis->effectiveSizeHint(Qt::PreferredSize);

        switch (axis->axis()->alignment()){
        case Qt::AlignLeft:{
            qreal width = size.width();
            if (leftSqueezeRatio < 1.0)
                width *= leftSqueezeRatio;
            leftOffset+=width;
            axis->setGeometry(QRect(chartRect.left()-leftOffset, geometry.top(),width, geometry.bottom()),chartRect);
            break;
        }
        case Qt::AlignRight:{
            qreal width = size.width();
            if (rightSqueezeRatio < 1.0)
                width *= rightSqueezeRatio;
            axis->setGeometry(QRect(chartRect.right()+rightOffset,geometry.top(),width,geometry.bottom()),chartRect);
            rightOffset+=width;
            break;
        }
        case Qt::AlignTop: {
            qreal height = size.height();
            if (topSqueezeRatio < 1.0)
                height *= topSqueezeRatio;
            axis->setGeometry(QRect(geometry.left(), chartRect.top() - topOffset - height, geometry.width(), height), chartRect);
            topOffset += height;
            break;
        }
        case Qt::AlignBottom:
            qreal height = size.height();
            if (bottomSqueezeRatio < 1.0)
                height *= bottomSqueezeRatio;
            axis->setGeometry(QRect(geometry.left(), chartRect.bottom() + bottomOffset, geometry.width(), height), chartRect);
            bottomOffset += height;
            break;
        }
    }

    return chartRect;
}
Example #28
0
void edgewalk(std::vector<std::pair<tetra*, unsigned int>> &leaves, const point *p) {

    assert(leaves.size() == 1);

    auto pivot = leaves[0].first;
    auto pivot_pos = leaves[0].second;

    assert(pivot);

    tetra *left(nullptr), *right(nullptr);
    tetra *left_prev(pivot), *right_prev(pivot);

    for (unsigned int i = 0; i < 4; ++i) {
        if (!(pivot_pos & (1 << i))) {
            if (pivot->ngb[i]) {
                if (!left)
                    left = pivot->ngb[i];
                else
                    right = pivot->ngb[i];
            }
        }
    }

    if (!left) // no walk is possible
        return;

    while (left || right) {

        auto tmp = left;

        if (left && left == right) {

            leaves.emplace_back(std::pair<tetra*, unsigned int>(left, fast_inclusion(left, p)));
            return;
        }

        if (left) {

            auto left_pos = fast_inclusion(left, p);

            leaves.emplace_back(std::pair<tetra*, unsigned int>(left, left_pos));

            int i = 0;

            for ( ; i < 4; ++i) {

                if (!(left_pos & (1 << i))) {
                    if (left->ngb[i]) {
                        if (left->ngb[i] != left_prev && left->ngb[i] != right) {

                            left_prev = left;
                            left = left->ngb[i];
                            break;
                        }    
                    }
                }
            }

            if (i == 4)
                left = nullptr;
        }

        if (right) {

            auto right_pos = fast_inclusion(right, p);

            leaves.emplace_back(std::pair<tetra*, unsigned int>(right, right_pos));

            int i = 0;

            for ( ; i < 4; ++i) {

                if (!(right_pos & (1 << i))) {
                    if (right->ngb[i]) {
                        if (right->ngb[i] != right_prev && right->ngb[i] != tmp) {

                            right_prev = right;
                            right = right->ngb[i];
                            break;
                        }    
                    }
                }
            }

            if (i == 4)
                right = nullptr;
        }
    }

    return;
}
Example #29
0
File: rect.hpp Project: LeDYoM/sgh
		inline vector2d<T> rightBottom() const { return vector2d<T>{right(), bottom()}; }
std::string DualOperatorExpression::eval(
    const server::Request& request,
    const util::ParametersMap& additionalParametersMap,
    const Webpage& page,
    util::ParametersMap& variables
) const	{

    // Check if all operands are not null
    if(	!_left.get() ||
            !_right.get()
      ) {
        return string();
    }

    // Operands evaluation
    string left(_left->eval(request, additionalParametersMap, page, variables));
    string right(_right->eval(request, additionalParametersMap, page, variables));

    // Non numeric operator
    switch(_operator)
    {
    case OR:
        trim(left);
        trim(right);
        if ((!left.empty() && left != "0") || (!right.empty() && right != "0"))
        {
            return "1";
        }
        else
        {
            return "0";
        }

    case AND:
        trim(left);
        trim(right);
        if((!left.empty() && left != "0") && (!right.empty() && right != "0"))
        {
            return "1";
        }
        else
        {
            return "0";
        }

    // Decimal operator
    case ADD:
    case SUB:
    case MUL:
    case DIV:
    case POW:
    case SUP:
    case SUP_EQ:
    case INF:
    case INF_EQ:
        try
        {
            double leftDbl(lexical_cast<double>(trim_copy(left)));
            double rightDbl(lexical_cast<double>(trim_copy(right)));

            switch(_operator)
            {
            case ADD:
                return lexical_cast<string>(leftDbl + rightDbl);

            case SUB:
                return lexical_cast<string>(leftDbl - rightDbl);

            case MUL:
                return lexical_cast<string>(leftDbl * rightDbl);

            case DIV:
                return lexical_cast<string>(leftDbl / rightDbl);

            case POW:
                return lexical_cast<string>(pow(leftDbl, rightDbl));

            case SUP:
                return lexical_cast<string>(leftDbl > rightDbl);

            case SUP_EQ:
                return lexical_cast<string>(leftDbl >= rightDbl);

            case INF:
                return lexical_cast<string>(leftDbl < rightDbl);

            case INF_EQ:
                return lexical_cast<string>(leftDbl <= rightDbl);
            default:
                break;
            }
        }
        catch(bad_lexical_cast&)
        {
            break;
        }

    // Integer operator
    case MOD:
    case BIT_AND:
    case BIT_OR:
        trim(left);
        trim(right);
        try
        {
            long long int leftInt(lexical_cast<long long int>(left));
            long long int rightInt(lexical_cast<long long int>(right));

            switch(_operator)
            {
            case MOD:
                return lexical_cast<string>(leftInt - (rightInt * (leftInt / rightInt)));

            case BIT_AND:
                return lexical_cast<string>(leftInt & rightInt);

            case BIT_OR:
                return lexical_cast<string>(leftInt | rightInt);

            default:
                break;
            }
        }
        catch(bad_lexical_cast&)
        {
            break;
        }

    // Strig operator
    case EQ:
        return lexical_cast<string>(left == right);

    case DIFF:
        return lexical_cast<string>(left != right);
    }

    // Admit + as concatenation operator
    if(_operator == ADD)
    {
        return left + right;
    }
    else if(_operator == SUP)
    {
        return lexical_cast<string>(left > right);
    }
    else if(_operator == SUP_EQ)
    {
        return lexical_cast<string>(left >= right);
    }
    else if(_operator == INF)
    {
        return lexical_cast<string>(left < right);
    }
    else if(_operator == INF_EQ)
    {
        return lexical_cast<string>(left <= right);
    }

    return string();
}