Esempio n. 1
0
 TEST_F(ViewPlane_Iterator, ShouldReturnZeroAsCurrentColumnForEndIterator) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   ASSERT_EQ(0, plane.end(this->fullRect).column());
 }
void BrushByPlaneClipper::split(const BrushPtrVector& brushes)
{
	Plane3 plane(_p0, _p1, _p2);

	if (!plane.isValid())
	{
		return;
	}

	for (BrushPtrVector::const_iterator i = brushes.begin(); i != brushes.end(); ++i)
	{
		const BrushNodePtr& node = *i;

		// Don't clip invisible nodes
		if (!node->visible())
		{
			continue;
		}

		Brush& brush = node->getBrush();

		scene::INodePtr parent = node->getParent();

		if (!parent)
		{
			continue;
		}

		// greebo: Analyse the brush to find out which shader is the most used one
		getMostUsedTexturing(brush);

		BrushSplitType split = Brush_classifyPlane(brush, _split == eFront ? -plane : plane);

		if (split.counts[ePlaneBack] && split.counts[ePlaneFront])
		{
			// the plane intersects this brush
			if (_split == eFrontAndBack)
			{
				scene::INodePtr fragmentNode = GlobalBrushCreator().createBrush();

				assert(fragmentNode != NULL);

				// Put the fragment in the same layer as the brush it was clipped from
				// Do this before adding the fragment to the parent, since there is an
				// update algorithm setting the visibility of the fragment right there.
				scene::assignNodeToLayers(fragmentNode, node->getLayers());

				// greebo: For copying the texture scale the new node needs to be inserted in the scene
				// otherwise the shaders cannot be captured and the scale is off

				// Insert the child into the designated parent
				scene::addNodeToContainer(fragmentNode, parent);

				// Select the child
				Node_setSelected(fragmentNode, true);

				Brush* fragment = Node_getBrush(fragmentNode);
				assert(fragment != NULL);
				fragment->copy(brush);

				FacePtr newFace = fragment->addPlane(_p0, _p1, _p2, _mostUsedShader, _mostUsedProjection);

				if (newFace != NULL && _split != eFront)
				{
					newFace->flipWinding();
				}

				fragment->removeEmptyFaces();
				ASSERT_MESSAGE(!fragment->empty(), "brush left with no faces after split");
			}

			FacePtr newFace = brush.addPlane(_p0, _p1, _p2, _mostUsedShader, _mostUsedProjection);

			if (newFace != NULL && _split == eFront) {
				newFace->flipWinding();
			}

			brush.removeEmptyFaces();
			ASSERT_MESSAGE(!brush.empty(), "brush left with no faces after split");
		}
		// the plane does not intersect this brush
		else if (_split != eFrontAndBack && split.counts[ePlaneBack] != 0)
		{
			// the brush is "behind" the plane
			// Remove the node from the scene
			scene::removeNodeFromParent(node);
		}
	}
}
Esempio n. 3
0
  void DemoState::initialize( Game* game, GameTime time )
  {
    State::initialize( game, time );

    Locator::getGraphics().setRenderWindowTitle( cDemoStateTitle );

    Ogre::Plane plane( Vector3::UNIT_Y, 0.0f );
    Real width = 128.0f;
    Real height = 128.0f;
    mPrimitives.push_back( new Primitives::Plane( gEngine->getWorld()->getPhysics(), plane, width, height, Vector3::ZERO, 32.0f, 32.0f ) );
    mPrimitives.push_back( new Primitives::Box( gEngine->getWorld()->getPhysics(), Vector3( 1.0f, 10.0f, 1.0f ), Vector3( -5.5f, 5.0f, 5.5f ), Quaternion::IDENTITY ) );
    mPrimitives.push_back( new Primitives::Box( gEngine->getWorld()->getPhysics(), Vector3( 1.0f, 10.0f, 1.0f ), Vector3( 5.5f, 5.0f, -5.5f ), Quaternion::IDENTITY ) );
    mPrimitives.push_back( new Primitives::Box( gEngine->getWorld()->getPhysics(), Vector3( 1.0f, 10.0f, 1.0f ), Vector3( 5.5f, 5.0f, 5.5f ), Quaternion::IDENTITY ) );
    mPrimitives.push_back( new Primitives::Box( gEngine->getWorld()->getPhysics(), Vector3( 1.0f, 10.0f, 1.0f ), Vector3( -5.5f, 5.0f, -5.5f ), Quaternion::IDENTITY ) );

    // TODO this really needs to be in a background thread. or something.
    OgreItemVector navSources;
    for ( auto primitive : mPrimitives )
    {
      navSources.push_back( primitive->getItem() );
    }
    NavigationInputGeometry navGeometry( navSources );
    NavigationMeshParameters navParams;
    navParams.cellSize = 0.2f;
    navParams.cellHeight = 0.2f;
    navParams.agentMaxSlope = 20;
    navParams.agentHeight = 1.8f;
    navParams.agentMaxClimb = 1;
    navParams.agentRadius = 0.2f;
    navParams.edgeMaxLength = 12;
    navParams.edgeMaxError = 1.3f;
    navParams.regionMinSize = 50;
    navParams.regionMergeSize = 20;
    navParams.vertsPerPoly = DT_VERTS_PER_POLYGON;
    navParams.detailSampleDist = 6;
    navParams.detailSampleMaxError = 1;
    mNavigationMesh = new NavigationMesh( navParams );
    mNavigationMesh->buildFrom( &navGeometry );
    // mNavigationMesh->loadFrom( "poop.navmesh" );

#ifndef GLACIER_NO_NAVIGATION_DEBUG
    mNavVis = new NavigationDebugVisualizer( gEngine );
    duDebugDrawPolyMesh( mNavVis, *mNavigationMesh->getPolyMesh() );
#endif

    auto player = Locator::getEntities().create( "player", "player" );
    gEngine->getInput()->getLocalController()->setCharacter( (Character*)player );
    player->spawn( Vector3( 0.0f, 1.0f, 0.0f ), Quaternion::IDENTITY );

    auto dummy = Locator::getEntities().create( "dev_dummy" );
    dummy->spawn( Vector3( 0.0f, 1.0f, 5.0f ), Quaternion::IDENTITY );

    for ( int i = 1; i < 11; i++ )
    {
      auto cube = (Entities::DevCube*)Locator::getEntities().create( "dev_cube" );
      cube->setType( Entities::DevCube::DevCube_025 );
      cube->spawn( Vector3( 5.0f, i * 15.0f, 0.0f ), Quaternion::IDENTITY );
    }
    for ( int i = 1; i < 11; i++ )
    {
      auto cube = ( Entities::DevCube* )Locator::getEntities().create( "dev_cube" );
      cube->setType( Entities::DevCube::DevCube_050 );
      cube->spawn( Vector3( -5.0f, i * 15.0f, 0.0f ), Quaternion::IDENTITY );
    }

    mDirector = new Director( &Locator::getGraphics(), player->getNode() );

    Locator::getMusic().beginScene();
  }
Esempio n. 4
0
void MenuScene::createScene(void)
{
	// title
	Ogre::Entity* title = mSceneMgr->createEntity("boomb_title", "cube.mesh");
	title->setMaterialName("Examples/terrain_texture");
	title->setCastShadows(false);
	Ogre::SceneNode* titleNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("boomb_title");
	titleNode->setPosition(0, 0, 100);
	//Ogre::Quaternion q1 = titleNode->getOrientation();
	//Ogre::Quaternion q2(Ogre::Degree(45), Ogre::Vector3::UNIT_X);
	//titleNode->setOrientation(q1*q2);
	titleNode->attachObject(title);

	// Start text
	//Ogre::Entity* startText = mSceneMgr->createEntity("boomb_starttext", "cube.mesh");
	//Ogre::SceneNode* textNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("boomb_starttext");
	//textNode->setPosition(0, 800, 900);
	//textNode->attachObject(startText);

	// background
	Ogre::SceneNode *backgroundNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("boomb_background");
	backgroundNode->setPosition(0, 0, 0);

	//Ogre::Entity *grass = mSceneMgr->createEntity("boomb_grass", "cube.mesh");
	//grass->setMaterialName("Examples/Rockwall");
	//grass->setCastShadows(true);
	//Ogre::SceneNode *grassNode = backgroundNode->createChildSceneNode("boomb_grass");
	//grassNode->setPosition(-300, 0, 1200);
	//grassNode->setScale(2, 2, 2);
	//grassNode->attachObject(grass);

	//Ogre::Entity *tree = mSceneMgr->createEntity("boomb_tree", "cube.mesh");
	//tree->setMaterialName("Examples/Rockwall");
	//tree->setCastShadows(true);
	//Ogre::SceneNode *treeNode = backgroundNode->createChildSceneNode("boomb_tree");
	//treeNode->setPosition(-100, 0, -100);
	//treeNode->setScale(10, 10, 10);
	//treeNode->attachObject(tree);

	//Ogre::Entity *building = mSceneMgr->createEntity("boomb_building", "cube.mesh");
	//Ogre::SceneNode *buildingNode = backgroundNode->createChildSceneNode("boomb_building");
	//building->setMaterialName("Examples/Rockwall");
	//building->setCastShadows(true);
	//buildingNode->setPosition(400, 0, -400);
	//buildingNode->setScale(500,500,500);
	//q1 = buildingNode->getOrientation();
	//q2 = Ogre::Quaternion(Ogre::Degree(45), Ogre::Vector3::UNIT_Y);
	//buildingNode->setOrientation(q1*q2);
	//buildingNode->attachObject(building);

	Ogre::Plane plane(Ogre::Vector3::UNIT_Y, 0);
	Ogre::MeshManager::getSingleton().createPlane("ground2", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		plane, 3000, 3000, 20, 20, true, 1, 12.5, 12.5, Ogre::Vector3::UNIT_Z);
	Ogre::Entity* entGround = mSceneMgr->createEntity("GroundEntity", "ground2");
	Ogre::SceneNode* planeNode= mSceneMgr->getRootSceneNode()->createChildSceneNode();
	planeNode->attachObject(entGround);
	planeNode->setPosition(-570,0,-100);
	planeNode->setScale(3.15,3.15,3.15);
	entGround->setMaterialName("Examples/BumpyMetal");
	entGround->setCastShadows(false);
	// Set Fog

	// Set ambient light
	mSceneMgr->setAmbientLight(Ogre::ColourValue(0.7, 0.7, 0.7));
	mSceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	// Create a light
	Ogre::Light* l = mSceneMgr->createLight("directlight");
	l->setType(Ogre::Light::LT_DIRECTIONAL);
	l->setDirection(Ogre::Vector3(-1, -1, -1));

	// Create Overlay

	this->createAnimation();
}
Esempio n. 5
0
CRhinoCommand::result CGenCylinder::RunCommand( const CRhinoCommandContext& context )
{

	Cscript1PlugIn& plugin = script1PlugIn();
	if( !plugin.IsDlgVisible() )
	{
		return CRhinoCommand::nothing;
	}

	/*****************************************/
	/*CHECKING IF THERE IS ALREADY A CYLINDER*/
	/*****************************************/
	const CRhinoLayer& layer = context.m_doc.m_layer_table.CurrentLayer();
	ON_SimpleArray<CRhinoObject*> objects;
	int object_count = context.m_doc.LookupObject( layer, objects );
	const CRhinoBrepObject* brep_obj;
	const CRhinoCurveObject* curve_obj;
	const CRhinoSurfaceObject* surface_obj;
	int surf_count=0;
	if( object_count > 0 )
	{
		int brep_obj_count = 0;
		int polycurve_count = 0;
		const CRhinoObject* object = 0;
		for(int i = 0; i < object_count; i++ )
		{
			object = objects[ i ];
			/************************************/
			/*TRY CASTING AS A RHINO BREP OBJECT*/ 
			/************************************/
			brep_obj = CRhinoBrepObject::Cast( object );
			if( brep_obj && object->IsSolid())
			{
				brep_obj_count++;
			}
			/*******************************/
			/*TRY CASTING AS A CURVE OBJECT*/ 
			/*******************************/
			curve_obj = CRhinoCurveObject::Cast( object );
			if( curve_obj )
			{
				polycurve_count++;
			}
			//surface_obj = CRhinoSurfaceObject::Cast( object );
		 //   if( surface_obj )
		 //   {
			//surf_count++;
		 //   }
		}
		if( brep_obj_count == 0)
		{
			ON_3dPoint center_point( 0.0, 0.0, 0.0 );
			double radius = 63.5;
			int __count = plugin.m_dialog->m_comboAltTacco.GetCount();

			int nIndex = plugin.m_dialog->m_comboAltTacco.GetCurSel();
			CString strCBText;
			plugin.m_dialog->m_comboAltTacco.GetLBText( nIndex, strCBText);
			int height = _wtoi(strCBText);


			ON_3dPoint height_point( 0.0, 0.0, height);
			ON_3dVector zaxis = height_point - center_point;
			ON_Plane planeCir( center_point, zaxis );

			/*ADD CIRCLE FOR CYLINDER'S BASE*/
			ON_Circle circle( planeCir, radius );

			/*ADD CYLINDER*/
			ON_Cylinder cylinder( circle, zaxis.Length() );
			ON_Brep* brep = ON_BrepCylinder( cylinder, TRUE, TRUE );
			unsigned int first_SN;
			unsigned int next_SN;
			if( brep )
			{
				first_SN = CRhinoObject::NextRuntimeObjectSerialNumber();
				/********************/
				/*TRANSLATE CYLINDER*/
				/********************/
				int nIndex1 = plugin.m_dialog->AltezzaFondelloControllo.GetCurSel();
				CString strCBText1;
				plugin.m_dialog->AltezzaFondelloControllo.GetLBText( nIndex1, strCBText1);
				int altfondello = _wtoi(strCBText1);
				ON_wString obj_nameCyl = L"CILINDRO";
								
				
				brep->Translate(ON_3dVector( 0.0, 0.0, -altfondello));
				CRhinoBrepObject* cylinder_object = new CRhinoBrepObject();
				cylinder_object->SetBrep( brep );
				if( context.m_doc.AddObject(cylinder_object) )
				{
					context.m_doc.Redraw();
					next_SN = CRhinoObject::NextRuntimeObjectSerialNumber();
					if( first_SN == next_SN )
					{
						return CRhinoCommand::nothing;
					}
					else
					{
						SetNametoObject(context.m_doc,first_SN,obj_nameCyl,true);			  
					}
				}
				else
				{
					delete cylinder_object;
				}

				/*********************************************/
				/*               DA SISTEMARE                */
				/*********************************************/
				
				CRhinoSnapContext snap;
				bool dec1 = snap.SnapToPoint(ON_3dPoint(63.5, 0.0, (height - altfondello)));
				bool dec2 = snap.SnapToPoint(ON_3dPoint(63.5, 0.0, -altfondello));
				bool dec3 = snap.SnapToPoint(ON_3dPoint(63.5, 0.0, 0.0));
				if(dec1 && dec2)
				{
					CRhinoLinearDimension* dim_obj = new CRhinoLinearDimension();
					ON_Plane plane( ON_zx_plane );
					plane.SetOrigin( ON_3dPoint(63.5, 0.0, 0.0) );
					dim_obj->SetPlane( plane );
					ON_3dPoint pt_1(63.5, 0.0, (height - altfondello));
					ON_3dPoint pt_2(63.5, 0.0, -altfondello);

					double u, v;
					plane.ClosestPointTo( pt_1, &u, &v );
					dim_obj->SetPoint( 0, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 1, ON_2dPoint(u, (v + height/2)) );


					plane.ClosestPointTo( pt_2, &u, &v );
					dim_obj->SetPoint( 2, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 3, ON_2dPoint(u, (v + height/2)) );

					dim_obj->UpdateText();
					 
					if( context.m_doc.AddObject(dim_obj) )
					{
						context.m_doc.Redraw();
					}		
					else
					{
						delete dim_obj;
					}
				}
				/*********************************************/
				/*               DA SISTEMARE                */
				/*********************************************/
				if(dec2 && dec3)
				{
					CRhinoLinearDimension* dim_obj = new CRhinoLinearDimension();
					ON_Plane plane( ON_zx_plane );
					plane.SetOrigin( ON_3dPoint(63.5, 0.0, 0.0) );
					dim_obj->SetPlane( plane );
					ON_3dPoint pt_1(63.5, 0.0, 0.0);
					ON_3dPoint pt_2(63.5, 0.0, -altfondello);

					double u, v;
					plane.ClosestPointTo( pt_1, &u, &v );
					dim_obj->SetPoint( 0, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 1, ON_2dPoint(u, (v + height/2)) );


					plane.ClosestPointTo( pt_2, &u, &v );
					dim_obj->SetPoint( 2, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 3, ON_2dPoint(u, (v + height/2)) );

					dim_obj->UpdateText();
					 
					if( context.m_doc.AddObject(dim_obj) )
					{
						context.m_doc.Redraw();
					}		
					else
					{
						delete dim_obj;
					}
				}
				/*********************************************/
				/*               DA SISTEMARE  By Nello              */
				/*********************************************/
				
				ON_3dPoint provapunto2 = AltezzaTacco;
				ON_3dPoint provapunto(59.5,0,provapunto2.z);
				provapunto.z-=0.7;
				ON_3dPoint pt_1(59.5, 0.0, (height - altfondello));
				CRhinoLinearDimension* dim_obj = new CRhinoLinearDimension();
					ON_Plane plane( ON_zx_plane );
					plane.SetOrigin(pt_1);
					dim_obj->SetPlane( plane );
					//ON_3dPoint pt_1(63.5, 0.0, 0.0);
					ON_3dPoint pt_2 = provapunto;

					double u, v;
					plane.ClosestPointTo( pt_1, &u, &v );
					dim_obj->SetPoint( 0, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 1, ON_2dPoint(u, (v + height/2)) );


					plane.ClosestPointTo( pt_2, &u, &v );
					dim_obj->SetPoint( 2, ON_2dPoint(u, v) );
					dim_obj->SetPoint( 3, ON_2dPoint(u, (v + height/2)) );

					dim_obj->UpdateText();
					 
					if( context.m_doc.AddObject(dim_obj) )
					{
						context.m_doc.Redraw();
					}		
					else
					{
						delete dim_obj;
					}
				
					/*INIZIO FUNZIONE CONTROLLO*/
			
					if ( (height - altfondello)>=provapunto.z+10){
						::RhinoApp().Print( L"Funzione controllo altezza OK");
					}
					else{
						::RhinoApp().Print( L"Funzione controllo altezza NOK: CONTROLLARE!! Il valore della testa e' minore del valore minimo di 10 mm. Occorre diminuire l'altezza del fondello o aumentare l'altezza dello stampo.");
					}


				/*********************************************/
				/*           CREATE FONDELLO PLANE           */
				/*********************************************/

				ON_3dPoint point0((63.5 + 20.0),0.0, 0.0);
				ON_3dPoint point1(-(63.5 + 20.0),0.0, 0.0);
				ON_LineCurve curve0( point0, point1 );

				context.m_doc.AddCurveObject(curve0);
				context.m_doc.Redraw();


				/******************************************************/
				/*****************************/
				/*USER GIVES NAME TO SURFACES*/ 
				/*****************************/
				unsigned int first_sn;
				unsigned int next_sn;
				ON_wString obj_name;
				object_count = context.m_doc.LookupObject( layer, objects );
				for(int i = 0; i < object_count; i++ )
				{
					object = objects[ i ];
					first_sn = CRhinoObject::NextRuntimeObjectSerialNumber();

					/*******************************/
					/*TRY CASTING AS A CURVE OBJECT*/ 
					/*******************************/
					curve_obj = CRhinoCurveObject::Cast( object );
					if( curve_obj )
					{
						const ON_Geometry* geo = curve_obj->Geometry();
						const ON_Curve* curve00 = ON_Curve::Cast(geo); 
						ON_3dPoint point  = curve00->PointAt(0.0);
						ON_3dPoint point_ = curve00->PointAt(1.0);
						if((point.z + point_.z)/2 > 0.0)
						{
							obj_name = L"SURFPV";
						}
						else
						{
							obj_name = L"SURFFO";
						}
						ON_3dPoint point0(point.x, (point.y + 70.0), point.z);
						ON_3dPoint point1(point.x, (point.y - 70.0), point.z);
						ON_LineCurve* curve = new ON_LineCurve();
						curve->SetStartPoint(point0);
						curve->SetEndPoint(point1);
						ON_SumSurface sumSurf0;
						sumSurf0.Create(*curve, *curve00);

						if( context.m_doc.AddSurfaceObject(sumSurf0) )
						{

							context.m_doc.Redraw();
							next_sn = CRhinoObject::NextRuntimeObjectSerialNumber();
							if( first_sn == next_sn )
							{
								return CRhinoCommand::nothing;
							}
							else
							{
								SetNametoObject(context.m_doc,first_sn,obj_name,true);			  
							}
						}

					}
				}/*CLOSED FOR*/

				//int R = 0;
				//object_count = context.m_doc.LookupObject( layer, objects );
				//for(int i = 0; i < object_count; i++)
				//{
				//	object = objects[ i ];
				//	const CRhinoCurveObject* surface_obj = CRhinoCurveObject::Cast(object);
				//	if(surface_obj)
				//	{
				//		R++;
				//	}
				//}

				 // // Get the string entered by the user
				 // ON_wString obj_name = gs.String();
				 // obj_name.TrimLeftAndRight();
				 //
				 // // Is name the same?
				 // if( obj_name.Compare(obj_attribs.m_name) == 0 )
					//return CRhinoCommand::nothing;
				 //
				 // // Modify the attributes of the object
				 // obj_attribs.m_name = obj_name;
				 // context.m_doc.ModifyObjectAttributes( objref, obj_attribs );
				 // if(selectobjectbyuuid_s(context.m_doc,obj_Surf[j],false))
				 // {
					//int R = 0;
				 // }



			  
			  ON_wString obj_Surf[2];
			  ON_wString name;
              obj_Surf[0] = L"SURFPV";
			  obj_Surf[1] = L"SURFFO";
			  object_count = context.m_doc.LookupObject( layer, objects );
			  int R = 0;
			  /************************/
			  /*TRY SPLITTING THE BREP*/
			  /************************/
			  for(int j = 0; j < 2; j++)
			  {
				  for(int i = 0; i < object_count; i++)
				  {
					  object = objects[ i ];

					  /*MAKE COPY OF OBJECT ATTRIBUTES. THIS OBJECTS*/ 
					  /*HOLDS AN OBJECT'S USER-DEFINED NAME.*/ 
					  ON_3dmObjectAttributes obj_attribs = object->Attributes();
			
					  name = object->Attributes().m_name;

					  surface_obj = CRhinoSurfaceObject::Cast( object );
					  if( surface_obj && !surface_obj->IsSolid())
					  {
						  ON_wString obj_SurfLoc = obj_Surf[j];

						  /*IS THE CUTTING SURFACE?*/
						  if( obj_SurfLoc.Compare(name) == 0 )
						  {							
							R++;
						  }
					  }/*CHIUSURA IF SUPERFICIE*/
				  } 
				 

				 // /************************/
				 // /*PICK THE BREP TO SPLIT*/ 
				 // /************************/
				 // CRhinoGetObject go;
				 // go.SetCommandPrompt( L"SELECT SOLID TO SPLIT" );
				 // go.SetGeometryFilter( CRhinoGetObject::polysrf_object  );//CRhinoGetObject::surface_object | CRhinoGetObject::polysrf_object 
				 // go.GetObjects( 1, 1 );
				 // if( go.CommandResult() != success )
				 // {
					//return go.CommandResult();
				 // }
				 // else
				 // {
					//	RhinoMessageBox(L"CYLINDER IS SELECTED", PlugIn()->PlugInName(), MB_OK | MB_ICONEXCLAMATION );
				 // }
				 //
				 // const CRhinoObjRef& split_ref = go.Object(0);
				 //
				 // const CRhinoObject* split_object = split_ref.Object();
				 // if( !split_object )
				 // {
					//return failure;
				 // }
				 //
				 // const ON_Brep* split = split_ref.Brep();
				 // if( !split )
				 // {
					//return failure;
				 // }

				 // ON_SimpleArray<ON_Brep*> pieces;
				 // double tol = context.m_doc.AbsoluteTolerance();
			 
				 // /***********************/
				 // /*PICK THE CUTTING BREP*/
				 // /***********************/
				 // go.SetCommandPrompt( L"SELECT CUTTING SURFACE OR POLYSUFACE" );
				 // go.SetGeometryFilter( CRhinoGetObject::surface_object | CRhinoGetObject::polysrf_object  ); 
				 // go.EnablePreSelect( FALSE );
				 // go.EnableDeselectAllBeforePostSelect( FALSE );
				 // go.GetObjects( 1, 2 );
				 // if( go.CommandResult() != success )
				 // {
					//return go.CommandResult();
				 // }

				 // const ON_Brep* cutter = go.Object(0).Brep();
				 // if( !cutter )
				 // {
					//return failure;
				 // }
				 //

				 // if( !RhinoBrepSplit(*split, *cutter, tol, pieces) )
				 // {
					//RhinoApp().Print( L"UNABLE TO SPLIT BREP.\n" );
				 // }
				 //
				 // int i, count = pieces.Count();
				 // if( count == 0 | count == 1 )
				 // {
					//if( count == 1 )
					//{
					//  delete pieces[0];
					//}
					//return nothing;
				 // }
				 //
				 // CRhinoObjectAttributes attrib = split_object->Attributes();
				 // attrib.m_uuid = ON_nil_uuid; 
				 //
				 // const CRhinoObjectVisualAnalysisMode* vam_list = split_object->m_analysis_mode_list;
				 //
				 // for( i = 0; i < count; i++ )
				 // {
					//CRhinoBrepObject* brep_object = new CRhinoBrepObject( attrib );
					//if( brep_object )
					//{
					//  brep_object->SetBrep( pieces[i] );
					//  if( context.m_doc.AddObject(brep_object) )
					//  {
					//	RhinoCopyAnalysisModes( vam_list, brep_object );

					//  }
					//  else
					//  {
					//	delete brep_object;
					//  }
					//}
				 // }
				 //
				 // context.m_doc.DeleteObject( split_ref ); 
				 // context.m_doc.Redraw();
			  }



		    /*CREATE A NEW LAYER*/
			  ON_Layer layer;
			  int layer_index = 0;
			  ON_Color color = ON_Color(0, 0, 0);
			  ON_wString layer_name_FONDELLO = L"FONDELLO";
			  layer.SetLayerName( layer_name_FONDELLO );
			  layer.SetPlotColor(color.Green());

			/*ADD THE LAYER TO THE LAYER TABLE*/ 
			  layer_index = context.m_doc.m_layer_table.AddLayer( layer );

			  ON_wString layer_name_MATRICE  = L"MATRICE";
			  layer.SetLayerName( layer_name_MATRICE );
			  layer.SetColor(color.Red());

			/*ADD THE LAYER TO THE LAYER TABLE*/ 
			  layer_index = context.m_doc.m_layer_table.AddLayer( layer );


			  ON_wString layer_name_FISSO    = L"FISSO";
			  layer.SetLayerName( layer_name_FISSO );
			  layer.SetColor(color.Blue());

			/*ADD THE LAYER TO THE LAYER TABLE*/ 
			  layer_index = context.m_doc.m_layer_table.AddLayer( layer );
	  
			  context.m_doc.Redraw();
			/*********************************************************/
			}
		}/*CLOSED IF OVER CHECKING BREP COUNT OBJECT*/
		else
		{
			RhinoMessageBox(L"THERE IS ALREADY A CYLINDER OBJECT", PlugIn()->PlugInName(), MB_OK | MB_ICONEXCLAMATION );
		}
	}
	/**********************************************************************/



  return CRhinoCommand::success;
}
Esempio n. 6
0
bool ConvexShape::castRay( const Point3F &start, const Point3F &end, RayInfo *info )
{
   if ( mPlanes.empty() )
      return false;   

   const Vector< PlaneF > &planeList = mPlanes;
   const U32 planeCount = planeList.size();  

   F32 t;
   F32 tmin = F32_MAX;
   S32 hitFace = -1;
   Point3F hitPnt, pnt;
   VectorF rayDir( end - start );
   rayDir.normalizeSafe();

   if ( false )
   {
      PlaneF plane( Point3F(0,0,0), Point3F(0,0,1) );
      Point3F sp( 0,0,-1 );
      Point3F ep( 0,0,1 );

      F32 t = plane.intersect( sp, ep );
      Point3F hitPnt;
      hitPnt.interpolate( sp, ep, t );
   }

   for ( S32 i = 0; i < planeCount; i++ )
   {
      // Don't hit the back-side of planes.
      if ( mDot( rayDir, planeList[i] ) >= 0.0f )
         continue;

      t = planeList[i].intersect( start, end );

      if ( t >= 0.0f && t <= 1.0f && t < tmin )
      {
         pnt.interpolate( start, end, t );

         S32 j = 0;
         for ( ; j < planeCount; j++ )
         {
            if ( i == j )
               continue;

            F32 dist = planeList[j].distToPlane( pnt );
            if ( dist > 1.0e-004f )
               break;
         }

         if ( j == planeCount )
         {
            tmin = t;
            hitFace = i;
         }
      }
   }

   if ( hitFace == -1 )
      return false;

   info->face = hitFace;            
   info->material = mMaterialInst;
   info->normal = planeList[ hitFace ];
   info->object = this;
   info->t = tmin;

   //mObjToWorld.mulV( info->normal );

   return true;
}
Esempio n. 7
0
File: User.cpp Progetto: ALX5/PJS
void User::updatePosition(double &x, double &y, double &z) {
    //Update the position
    _position.x = x;
    _position.y = y;
    _position.z = z;

    //Get the projection center and surfaces
    cv::Point3f projectionCenter = _projection.getCenter();
    std::vector<Plane3d> planes = _projection.getPlanes();

    GeometryUtils gUtils;

    //Compute the projection plane normal
    cv::Point3f normal = gUtils.normalizeVector(_position - projectionCenter);

    //This vector will store the projection of the projected surfaces
    //onto the plane orthogonal to the user's point of view
    std::vector<Plane3d> projectedPlanes;

    //The plane orthogonal to the user's point of view
    UserPlane userPlane(projectionCenter, normal);
    
    //Iterate over projected surfaces
    //to find the corresponding intersections
    std::vector<Plane3d>::iterator ii;
    for (ii = planes.begin(); ii != planes.end(); ii++) {
        
        //Get the points of the current surface
        std::vector<cv::Point3f> points = (*ii).getPoints();
        
        //Find the intersections
        std::vector<cv::Point3f> intersections = this->findIntersections(points, 
                userPlane);
        
        //Create a plane out of the intersections and add it to the list
        Plane3d projectedPlane(intersections);
        projectedPlanes.push_back(projectedPlane);
    }

    //************************************************************************
    //Rotate the obtained intersections to align them to the orthogonal plane
    //************************************************************************
    
    //Normalize the plane normal (equivalent to the user's position from
    //the projection center)
    cv::Vec3f normalized = gUtils.normalizeVector(normal);

    //Get the rotation axis
    cv::Vec3f zed(0, 0, -1);
    cv::Vec3f axis = gUtils.crossProduct(normalized, zed);

    cv::Point3f normalAxis = gUtils.normalizeVector(axis);

    double angle = std::acos(normalized[0] * zed[0] +
            normalized[1] * zed[1] +
            normalized[2] * zed[2]);

    //Rotate all intersections to align them with the plane
    for (ii = projectedPlanes.begin(); ii != projectedPlanes.end(); ii++) {
        //Get the points of the current surface
        std::vector<cv::Point3f> points = (*ii).getPoints();
        std::vector<cv::Point3f>::iterator jj;

        std::vector<cv::Point3f> rotatedPoints;

        for (jj = points.begin(); jj != points.end(); jj++) {
            cv::Point3f p = *jj;
            p = p - projectionCenter;
            cv::Point3f rotated = gUtils.rotateAroundAxis(p, normalAxis, -angle);
            rotatedPoints.push_back(rotated);
        }

        Plane3d plane(rotatedPoints);
        _projectedPlanes.push_back(plane);
    }
}
Esempio n. 8
0
 TEST_F(ViewPlane_Iterator, ShouldReturnCurrentColumn) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   ASSERT_EQ(0, plane.begin(this->fullRect).column());
 }
Esempio n. 9
0
 TEST_F(ViewPlane_Iterator, ShouldReturnHeightAsCurrentRowForEndIterator) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   ASSERT_EQ(6, plane.end(this->fullRect).row());
 }
Esempio n. 10
0
 TEST_F(ViewPlane_Iterator, ShouldReturnTrueWhenTwoEndIteratorsAreCompared) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   ASSERT_TRUE(plane.end(this->fullRect) == plane.end(this->fullRect));
 }
Esempio n. 11
0
 TEST_F(ViewPlane_Iterator, ShouldCompareForInEquality) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   ASSERT_TRUE(plane.begin(this->fullRect) != plane.end(this->fullRect));
 }
Esempio n. 12
0
 TEST_F(ViewPlane_Iterator, ShouldMultiplyCurrentByPixelSize) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   plane.setPixelSize(2);
   auto iterator = plane.begin(this->fullRect);
   ASSERT_EQ(Vector3d(-8, -6, 0), *iterator);
 }
Esempio n. 13
0
 TEST_F(ViewPlane_Iterator, ShouldReturnPixel) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   auto iterator = plane.begin(this->fullRect);
   ASSERT_EQ(Vector2d(0, 0), iterator.pixel());
 }
Esempio n. 14
0
 TEST_F(ViewPlane_Iterator, ShouldReturnCurrent) {
   ViewPlane plane(Matrix4d(), this->fullRect);
   auto iterator = plane.begin(this->fullRect);
   ASSERT_EQ(Vector3d(-4, -3, 0), *iterator);
 }
 void FindObjectOnPlane::find(
   const sensor_msgs::Image::ConstPtr& image_msg,
   const sensor_msgs::CameraInfo::ConstPtr& info_msg,
   const pcl_msgs::ModelCoefficients::ConstPtr& polygon_3d_coefficient_msg)
 {
   cv::Mat object_image = cv_bridge::toCvShare(image_msg, image_msg->encoding)->image;
   
   image_geometry::PinholeCameraModel model;
   pcl::ModelCoefficients::Ptr polygon_coefficients
     (new pcl::ModelCoefficients);
   pcl_conversions::toPCL(*polygon_3d_coefficient_msg, *polygon_coefficients);
   jsk_recognition_utils::Plane::Ptr plane
     (new jsk_recognition_utils::Plane(polygon_coefficients->values));
   model.fromCameraInfo(info_msg);
   std::vector<cv::Point> all_points;
   for (int j = 0; j < object_image.rows; j++) {
     for (int i = 0; i < object_image.cols; i++) {
       if (object_image.at<uchar>(j, i) == 255) {
         all_points.push_back(cv::Point(i, j));
       }
     }
   }
   cv::RotatedRect obb = cv::minAreaRect(all_points);
   
   cv::Mat min_area_rect_image;
   cv::cvtColor(object_image, min_area_rect_image, CV_GRAY2BGR);
   cv::Point2f vertices2f[4];
   obb.points(vertices2f);
   cv::line(min_area_rect_image, vertices2f[0], vertices2f[1],
            cv::Scalar(0, 0, 255), 4);
   cv::line(min_area_rect_image, vertices2f[1], vertices2f[2],
            cv::Scalar(0, 0, 255), 4);
   cv::line(min_area_rect_image, vertices2f[2], vertices2f[3],
            cv::Scalar(0, 0, 255), 4);
   cv::line(min_area_rect_image, vertices2f[3], vertices2f[0],
            cv::Scalar(0, 0, 255), 4);
   cv::Rect bb = obb.boundingRect();
   std::vector<cv::Point3f> search_points_3d;
   std::vector<cv::Point2f> search_points_2d;
   generateStartPoints(cv::Point2f(bb.x, bb.y),
                       model, polygon_coefficients,
                       search_points_3d, search_points_2d);
   for (size_t i = 0; i < search_points_2d.size(); i++) {
     cv::circle(min_area_rect_image, search_points_2d[i], 5, cv::Scalar(0, 255, 0), 1);
   }
   
   //for (size_t i = 0; i < search_points_3d.size(); i++) {
   double min_area = DBL_MAX;
   double min_angle;
   cv::Point2f min_search_point;
   double min_x;
   double min_y;
   for (size_t i = 0; i < search_points_2d.size(); i++) {
     std::vector<double> angles;
     std::vector<double> max_x;
     std::vector<double> max_y;
     generateAngles(object_image, search_points_2d[i], angles,
                    max_x, max_y,
                    model, plane);
     // draw angles
     for (size_t j = 0; j < angles.size(); j++) {
       double area = drawAngle(min_area_rect_image, search_points_2d[i], angles[j],
                               max_x[j], max_y[j], model, plane, cv::Scalar(0, 255, 0));
       if (area < min_area) {
         min_area = area;
         min_x = max_x[j];
         min_y = max_y[j];
         min_angle = angles[j];
         min_search_point = search_points_2d[i];
       }
     }
   }
   drawAngle(min_area_rect_image, min_search_point, min_angle,
             min_x, min_y, model, plane, cv::Scalar(0, 255, 255));
   // convert the points into 3-D
   pub_min_area_rect_image_.publish(
     cv_bridge::CvImage(image_msg->header,
                        sensor_msgs::image_encodings::BGR8,
                        min_area_rect_image).toImageMsg());
   JSK_NODELET_INFO("published");
 }
Esempio n. 16
0
	 void createScene(){
		_sceneManager->setAmbientLight(Ogre::ColourValue(1.0f,1.0f,1.0f));
		_sceneManager->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

		_sceneManager->setSkyBox(true, "OMV/SkyBoxUnderwater1");

		Ogre::Plane plane(Ogre::Vector3::UNIT_Y , -5000.0);

		Ogre::MeshManager::getSingleton().createPlane("plane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, 
						plane, 60000,100000,200,200,true, 1,10,10, Ogre::Vector3::UNIT_Z);
		Ogre::SceneNode* nodePlano;
		Ogre::Entity* entPlano = _sceneManager->createEntity("PlanoEntity","plane");
		nodePlano = _sceneManager->createSceneNode("NodePlano");
		nodePlano->attachObject(entPlano);
		_sceneManager->getRootSceneNode()->addChild(nodePlano);
		entPlano->setMaterialName("plano");
		nodePlano->translate(Ogre::Vector3(0.0f,0.0f,45000.0f));
		
		
		Ogre::SceneNode* nodeEsfera02;
		Ogre::Light* light02;
		Ogre::Entity* entEsfera02 = _sceneManager->createEntity("EntEsfera02","sphere.mesh");
		//Ogre::SceneNode* nodeEsfera02 = mSceneMgr->createSceneNode("NodeEsfera02");
		nodeEsfera02 = _sceneManager->createSceneNode("NodeEsfera02");
		_sceneManager->getRootSceneNode()->addChild(nodeEsfera02);
		nodeEsfera02->attachObject(entEsfera02);
		
		 //NODO LUZ
		float lightScale = 0.9f;
		Ogre::SceneNode* nodeLuz02 = _sceneManager->createSceneNode("NodeLuz02");		
		light02 = _sceneManager->createLight("LuzPoint01");
		light02->setType(Ogre::Light::LT_POINT);		
		light02->setDiffuseColour(lightScale*Ogre::ColourValue(2.0f,2.0f,2.0f));	
		nodeLuz02->attachObject(light02);


		nodeEsfera02->addChild(nodeLuz02);
		nodeEsfera02->setScale(0.05f,0.05f,0.05f);
		nodeEsfera02->setPosition(0.0f,5000.0f,0.0f);

		banderin[0] = new Banderin("Inicio",_sceneManager, 5105.0, -2000.0, 0.0);
		_sceneManager->getRootSceneNode()->addChild(banderin[0]->nodoBanderin);
		banderin[1] = new Banderin("Fin",_sceneManager, 5105.0, -2000.0, 90000.0);
		_sceneManager->getRootSceneNode()->addChild(banderin[1]->nodoBanderin);

		
		

		nave = new Nave(_sceneManager, _sceneManager->getCamera("Camera"));

		for (int i = 0; i < num_monedas; i++)
		{
			crearMoneda(i,4000,5000,90000);
		}

		for (int i = 0; i < num_aros; i++)
		{
			crearAro(i,4000,5000,90000);
		}

		for (int i = 0; i < num_obstaculo; i++)
		{
			crearObstaculo(i,4000,5000,90000);
		}
		
	 }
Esempio n. 17
0
//------------------------------------------------------------------------------
//!
void
adjustRoot( const Vector<Puppeteer::PositionalConstraint>& pc, Vec3f& root, Vec3f& dRoot )
{
   // Test if root is contained into limbs spheres.
   Vec3f newRoot;

   bool in = true;
   for( uint i = 0; i < pc.size(); ++i )
   {
      in &= pc[i].sphere().isInside( root );
   }
   // Are we inside all constraints range?
   if( in ) return;

   // 1 sphere.
   if( pc.size() == 1 )
   {
      newRoot = pc[0].sphere().project( root );
   }
   // 2 spheres not intersecting.
   else if( !pc[0].sphere().isOverlapping( pc[1].sphere() ) )
   {
      // Return the projection on the most important one.
      uint s  = pc[0].weight() > pc[1].weight() ? 0 : 1;
      newRoot = pc[s].sphere().project( root );
   }
   else
   {
      // 2 spheres intersecting.
      // Test nearest point on spheres.
      Vec3f projPt[2];
      projPt[0] = pc[0].sphere().project( root );
      projPt[1] = pc[1].sphere().project( root );

      int minPt  = -1;
      float dist = CGConstf::infinity();
      if( pc[1].sphere().isInside( projPt[0] ) )
      {
         minPt = 0;
         dist  = (projPt[0]-root).sqrLength();
      }

      if( pc[0].sphere().isInside( projPt[1] ) )
      {
         float cdist = (projPt[1]-root).sqrLength();
         if( cdist < dist ) minPt = 1;
      }

      // Test circle.
      if( minPt < 0 )
      {
         const Spheref& s0 = pc[0].sphere();
         const Spheref& s1 = pc[1].sphere();

         // Compute center of intersection circle.
         Vec3f dir = s1.center()-s0.center();
         float d2  = dir.sqrLength();
         float t  = (d2 - s1.radius()*s1.radius() + s0.radius()*s0.radius())/(2.0f*d2);
         Vec3f center = s0.center() + dir*t;

         // Compute radius of intersection circle.
         float r = CGM::sqrt( (s0.radius()*s0.radius())-t*t*d2 );

         // Project root on the circle plane.
         Planef plane( dir, center );
         plane.normalize();
         Vec3f pRoot = plane.closest( root );

         // Nearest point on circle.
         newRoot = Spheref( center, r ).project( pRoot );
      }
      else
      {
         newRoot = projPt[minPt];
      }
   }

   // Compute new root and displacement.
   dRoot  += newRoot - root;
   root    = newRoot;
}
Esempio n. 18
0
void GameRenderer::initialize(){
	
	DEBUG("GameRenderer::initialize");
	
	Client::getInstance().getOgreManager().getRoot()->addFrameListener(this);
	
	// Tray manager, hacky fix for intel graphics
	mTrayMgr = new OgreBites::SdkTrayManager(
		"InterfaceName", 
		Client::getInstance().getOgreManager().getWindow(), 
		Client::getInstance().getOISManager().getMouse(), 
		this);
	mTrayMgr->showFrameStats(OgreBites::TL_BOTTOMLEFT);
	mTrayMgr->toggleAdvancedFrameStats();
	mTrayMgr->showLogo(OgreBites::TL_BOTTOMRIGHT);
	mTrayMgr->hideCursor();
	
	//cameraMan = new OgreBites::SdkCameraMan(Client::getInstance().getOgreManager().getCamera());
	Client::getInstance().getOISManager().addMouseListener(this);
	Client::getInstance().getOISManager().addKeyListener(this);
	
	Ogre::Plane plane(Ogre::Vector3::UNIT_Y, 0);
	
	Ogre::MeshManager::getSingleton().createPlane("ground", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
		plane, 1500, 1500, 20, 20, true, 1, 5, 5, Ogre::Vector3::UNIT_Z);
	
	Ogre::Entity* entGround = 
		Client::getInstance()
			.getOgreManager()
			.getSceneManager()
			->createEntity("GroundEntity", "ground");

	Ogre::SceneNode* groundNode = Client::getInstance().getOgreManager().getSceneManager()->getRootSceneNode()->createChildSceneNode();
	groundNode->attachObject(entGround);
	groundNode->scale(.1, .1, .1);
	
	entGround->setMaterialName("Examples/Rockwall");
	entGround->setCastShadows(false);
	entGround->setQueryFlags(0);
	
	//point light
	Ogre::Light* pointLight = Client::getInstance().getOgreManager().getSceneManager()->createLight("pointLight");
	pointLight->setType(Ogre::Light::LT_POINT);
	pointLight->setPosition(Ogre::Vector3(0, 10, 10));
	pointLight->setDiffuseColour(1.0, 1.0, 1.0);
	pointLight->setSpecularColour(1.0, 1.0, 1.0);
	
	Client::getInstance()
		.getOgreManager()
		.getSceneManager()
		->setAmbientLight(Ogre::ColourValue(0.5, 0.5, 0.5));
	
	orb = new OgreOrb(Client::getInstance().getOgreManager().getSceneManager());
	felhound = new OgreFelhound(Client::getInstance().getOgreManager().getSceneManager(),0);
	
	//TODO: magic strings
	cameraStyles["TOCameraMan"] = new TOCameraManStyle();
	cameraStyles["WC3Style"] = new WC3CameraStyle();
	//TODO: configurable default
	setCameraStyle("WC3Style");
	
	DEBUG("GameRenderer::initialize done");
}
Esempio n. 19
0
    bool  
    AxisRenderable::collideAxis(Ogre::Ray& ray)
    {   
        Ogre::Vector3 dir = getWorldPosition() - ray.getOrigin();
        Ogre::Real mAxisGizmoProjLen = mLength / mViewport->getActualWidth() * dir.length() * Ogre::Math::Tan(mCamera->getFOVy());

        dir.normalise();
        mAxisGizmoSelAxis = -1;

        // find axis to use...
        for(unsigned int  i = 0; i < 3; i++)
        {
            Ogre::Vector3 up, normal;

            up = dir.crossProduct(mAxisGizmoVector[i]);
            normal = up.crossProduct(mAxisGizmoVector[i]);

            if(normal.isZeroLength())
                break;

            Ogre::Plane plane(normal,getWorldPosition());


            // width of the axis poly is 1/10 the run   
            Ogre::Vector3 a = up * mAxisGizmoProjLen / 10;
            Ogre::Vector3 b = mAxisGizmoVector[i] * mAxisGizmoProjLen;

            Ogre::Vector3 poly [] = 
            {
                Ogre::Vector3(getWorldPosition() + a),
                    Ogre::Vector3(getWorldPosition() + a + b),
                    Ogre::Vector3(getWorldPosition() - a + b),
                    Ogre::Vector3(getWorldPosition() - a)
            };

            Ogre::Vector3 end = ray.getPoint(mProjectDistance);
            Ogre::Real t = intersect(&plane,ray.getOrigin(), end);

            if(t >= 0 && t <= 1)
            {
                Ogre::Vector3 pos = interpolate(ray.getOrigin(), end, t);

                // check if inside our 'poly' of this axis vector...
                bool inside = true;
                for(unsigned int  j = 0; inside && (j < 4); j++)
                {
                    unsigned int k = (j+1) % 4;
                    Ogre::Vector3 vec1 = poly[k] - poly[j];
                    Ogre::Vector3 vec2 = pos - poly[k];

                    if(vec1.dotProduct(vec2) >0.f)
                        inside = false;   
                }

                //
                if(inside)
                {
                    mAxisGizmoSelAxis = i;
                    return(true);
                }
            }
        }      

        return(false);
    }
Esempio n. 20
0
void Render(float alpha, float elapsedtime)
{
	static float time = 0;
	LPDIRECT3DSURFACE9 backbuffer = 0;

	D3DXMATRIX		view, proj, viewproj;
	D3DXMATRIX		world, inv;

	D3DXVECTOR4		texelsize;
	D3DXVECTOR4		lightpos(-600, 350, 1000, 1);
	D3DXVECTOR4		refllight;
	D3DXVECTOR3		eye(0, 0, -5.0f);
	D3DXVECTOR3		look(0, 1.2f, 0);
	D3DXVECTOR3		refleye, refllook;
	D3DXVECTOR3		up(0, 1, 0);
	D3DXVECTOR2		orient	= cameraangle.smooth(alpha);

	D3DXMatrixRotationYawPitchRoll(&view, orient.x, orient.y, 0);
	D3DXVec3TransformCoord(&eye, &eye, &view);
	
	eye.y += 1.2f;

	D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI / 2, (float)screenwidth / (float)screenheight, 0.1f, 30);

	time += elapsedtime;

	if( SUCCEEDED(device->BeginScene()) )
	{
		device->GetRenderTarget(0, &backbuffer);

		// STEP 1: render reflection texture
		device->SetRenderTarget(0, reflectsurf);
		device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0);

		D3DXPLANE plane(0, 1, 0, 1);

		refleye = eye - 2 * D3DXPlaneDotCoord(&plane, &eye) * (D3DXVECTOR3&)plane;
		refllook = look - 2 * D3DXPlaneDotCoord(&plane, &look) * (D3DXVECTOR3&)plane;

		refllight = lightpos - 2 * D3DXPlaneDot(&plane, &lightpos) * (D3DXVECTOR4&)plane;
		refllight.w = 1;

		D3DXMatrixLookAtLH(&view, &refleye, &refllook, &up);
		D3DXMatrixMultiply(&viewproj, &view, &proj);

		D3DXMatrixInverse(&inv, 0, &viewproj);
		D3DXMatrixTranspose(&inv, &inv);
		D3DXPlaneTransform(&plane, &plane, &inv);

		device->SetClipPlane(0, &plane.a);

		RenderScene(viewproj, refleye, refllight, true);

		// STEP 2: render scene (later used for refraction)
		D3DXMatrixLookAtLH(&view, &eye, &look, &up);
		D3DXMatrixMultiply(&viewproj, &view, &proj);

		device->SetRenderTarget(0, refractsurf);
		device->Clear(0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, 0xff6694ed, 1.0f, 0);

		RenderScene(viewproj, eye, lightpos, false);

		// render water surface into alpha channel for masking
		device->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_ALPHA);

		D3DXMatrixTranslation(&world, 0, -1, 0);

		device->SetTransform(D3DTS_WORLD, &world);
		device->SetTransform(D3DTS_VIEW, &view);
		device->SetTransform(D3DTS_PROJECTION, &proj);

		waterplane->DrawSubset(0, DXObject::Opaque);

		device->SetRenderState(D3DRS_COLORWRITEENABLE, 0x0f);

		// STEP 3: light shafts
		quadvertices[6] = quadvertices[24] = quadvertices[30]	= (float)screenwidth - 0.5f;
		quadvertices[13] = quadvertices[19] = quadvertices[31]	= (float)screenheight - 0.5f;

		RenderLightShafts(view, proj, eye, lightpos);

		// STEP 4: gamma correct
		device->SetRenderTarget(0, sceneldrsurf);

		device->SetRenderState(D3DRS_ZENABLE, FALSE);
		device->SetVertexDeclaration(quaddecl);

		bloom->SetTechnique("gammacorrect");
		bloom->Begin(0, 0);
		bloom->BeginPass(0);
		{
			device->SetTexture(0, refraction);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		bloom->EndPass();
		bloom->End();

		device->SetRenderState(D3DRS_ZENABLE, TRUE);

		// STEP 5: water surface
		device->SetRenderState(D3DRS_SRGBWRITEENABLE, TRUE);

		D3DXMatrixTranslation(&world, 0, -1, 0);
		D3DXMatrixIdentity(&inv);

		water->SetMatrix("matViewProj", &viewproj);
		water->SetMatrix("matWorld", &world);
		water->SetMatrix("matWorldInv", &inv);
		water->SetVector("eyePos", (D3DXVECTOR4*)&eye);
		water->SetVector("lightPos", &lightpos);
		water->SetVector("lightColor", &lightcolor);
		water->SetFloat("time", time);

		water->Begin(0, 0);
		water->BeginPass(0);
		{
			device->SetTexture(0, refraction);
			device->SetTexture(1, reflection);
			device->SetTexture(2, waves);

			waterplane->DrawSubset(0, DXObject::Opaque);
		}
		water->EndPass();
		water->End();

		device->SetRenderState(D3DRS_SRGBWRITEENABLE, FALSE);

		// STEP 6: downsample & blur
		quadvertices[6] = quadvertices[24] = quadvertices[30]	= (float)screenwidth * 0.5f - 0.5f;
		quadvertices[13] = quadvertices[19] = quadvertices[31]	= (float)screenheight * 0.5f - 0.5f;

		device->SetRenderTarget(0, bloomsurf1);
		device->SetRenderState(D3DRS_ZENABLE, FALSE);
		device->SetVertexDeclaration(quaddecl);

		texelsize.x = 1.0f / screenwidth;
		texelsize.y = 1.0f / screenheight;

		bloom->SetTechnique("downsample");
		bloom->SetVector("texelSize", &texelsize);

		bloom->Begin(0, 0);
		bloom->BeginPass(0);
		{
			device->SetTexture(0, sceneldr);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		bloom->EndPass();
		bloom->End();

		device->SetRenderTarget(0, bloomsurf2);

		texelsize.x = 2.0f / screenwidth;
		texelsize.y = 2.0f / screenheight;

		bloom->SetTechnique("blur");
		bloom->SetVector("texelSize", &texelsize);

		bloom->Begin(0, 0);
		bloom->BeginPass(0);
		{
			device->SetTexture(0, bloomtex1);
			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		bloom->EndPass();
		bloom->End();

		// STEP 7: add light shafts
		quadvertices[6] = quadvertices[24] = quadvertices[30]	= (float)screenwidth - 0.5f;
		quadvertices[13] = quadvertices[19] = quadvertices[31]	= (float)screenheight - 0.5f;

		device->SetRenderTarget(0, backbuffer);

		godray->SetTechnique("final");
		godray->Begin(0, 0);
		godray->BeginPass(0);
		{
			device->SetTexture(0, sceneldr);
			device->SetTexture(1, occluders);
			device->SetTexture(2, bloomtex2);

			device->DrawPrimitiveUP(D3DPT_TRIANGLELIST, 2, quadvertices, 6 * sizeof(float));
		}
		godray->EndPass();
		godray->End();

		backbuffer->Release();

		device->SetRenderState(D3DRS_ZENABLE, TRUE);
		device->EndScene();
	}

	device->Present(NULL, NULL, NULL, NULL);
}
Esempio n. 21
0
int main( int argc, char** argv )
{
//     for( unsigned int i = 0; i < boost::lexical_cast< unsigned int >( argv[1] ); ++i )
//     {
//         double x = r() * 20 - 10;
//         double y = r() * 20 - 10;
//         double z = r() * 20 - 10;
//         std::cout << x << ',' << y << ',' << z << ',' << int( std::max( std::abs( x ), std::max( std::abs( y ), std::abs( z ) ) ) ) << std::endl;
//     }
//     return 0;

    try
    {
        std::string normal_string;
        std::string points_string;
        std::string point_outside;
        boost::program_options::options_description description( "options" );
        description.add_options()
            ( "help,h", "display help message" )
            ( "points,p", boost::program_options::value< std::string >( &points_string )->default_value( "0,0,0" ), "point(s) belonging to the plane, either 3 points, or 1 point, if --normal defined" )
            ( "point-outside", boost::program_options::value< std::string >( &point_outside ), "point on the side of the plane where the normal would point, a convenience option; 3 points are enough" )
            ( "normal,n", boost::program_options::value< std::string >( &normal_string ), "normal to the plane" )
            ( "intersections", "assume the input represents a trajectory, find all its intersections with the plane")
            ( "threshold", boost::program_options::value< double >(), "if --intersections present, any separation between contiguous points of trajectory greater than threshold will be treated as a gap in the trajectory (no intersections will lie in the gaps)");
        description.add( comma::csv::program_options::description( "x,y,z" ) );
        boost::program_options::variables_map vm;
        boost::program_options::store( boost::program_options::parse_command_line( argc, argv, description), vm );
        boost::program_options::notify( vm );
        if ( vm.count( "help" ) )
        {
            std::cerr << std::endl;
            std::cerr << "take points on stdin, append distance from a given plane" << std::endl;
            std::cerr << std::endl;
            std::cerr << "if --intersections is specified, assume the input represents a trajectory, find its intersections with the plane," << std::endl;
            std::cerr << "for each intersection, output adjacent points between which it occurs, the intersection point, and the direction of intersection (-1,0,+1)," << std::endl;
            std::cerr << "where 0 indicates that both adjacent points are in the plane, +1 if the trajectory's direction is the same as normal of the plane, and -1 otherwise" << std::endl;
            std::cerr << std::endl;
            std::cerr << "usage: " << std::endl;
            std::cerr << "    cat points.csv | points-slice [options] > points_with_distance.csv" << std::endl;
            std::cerr << "    cat trajectory.csv | points-slice [options] --intersections > intersections.csv" << std::endl;
            std::cerr << std::endl;
            std::cerr << description << std::endl;
            std::cerr << std::endl;
            std::cerr << "defining the plane" << std::endl;
            std::cerr << "    --points x1,y1,z1,x2,y2,z2,x3,y3,x3" << std::endl;
            std::cerr << "    --points x1,y1,z1,x2,y2,z2,x3,y3,x3 --point-outside x4,y4,z4" << std::endl;
            std::cerr << "    --points x,y,z --normal n1,n2,n3" << std::endl;
            std::cerr << "    --normal n1,n2,n3    (the plane passes through 0,0,0)" << std::endl;
            std::cerr << std::endl;
            std::cerr << "output" << std::endl;
            std::cerr << "    default: " << std::endl;
            std::cerr << "        x,y,z,distance, where distance is signed distance to the plane" << std::endl;
            std::cerr << std::endl;
            std::cerr << "    if --intersections is specified:" << std::endl;
            std::cerr << "        previous_input_line,input_line,intersection,direction" << std::endl;
            std::cerr << std::endl;
            std::cerr << "examples:" << std::endl;
            std::cerr << "   echo -e \"0,0,-1\\n0,0,0\\n0,0,1\" | points-slice --points 0,0,0,0,1,0,1,0,0" << std::endl;
            std::cerr << "   echo -e \"0,0,-1\\n0,0,0\\n0,0,1\" | points-slice --points 0,0,0,0,1,0,1,0,0 --point-outside 0,0,1" << std::endl;
            std::cerr << "   echo -e \"0,0,-1\\n0,0,0\\n0,0,1\" | points-slice --points 0,0,0 --normal 0,0,1" << std::endl;
            std::cerr << "   echo -e \"0,0,-1\\n0,0,0\\n0,0,1\" | points-slice --normal 0,0,1" << std::endl;
            std::cerr << "   echo -e \"0,0,-1\\n0,0,0\\n0,0,1\" | points-slice --normal 0,0,1 --intersections" << std::endl;
            std::cerr << "   echo -e \"0,0,-1\\n0,0,-0.5\\n0,0,0\\n0,0,1\\n0,0,1.5\" | points-slice --normal 0,0,1 --intersections --threshold=0.5" << std::endl;
            std::cerr << std::endl;
            return 1;
        }
        if( vm.count( "points" ) == 0 ) { std::cerr << "points-slice: please specify --points" << std::endl; return 1; }
        comma::csv::options csv = comma::csv::program_options::get( vm );
        Eigen::Vector3d normal;
        Eigen::Vector3d point;
        if( vm.count( "normal" ) )
        {
            normal = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( normal_string );
            point = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( points_string );
        }
        else
        {
            boost::array< Eigen::Vector3d, 3 > points; // quick and dirty
            std::vector< std::string > v = comma::split( points_string, ',' );
            if( v.size() != 9 ) { std::cerr << "points-slice: expected 3 points, got: \"" << points_string << "\"" << std::endl; return 1; }
            point = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( v[0] + ',' + v[1] + ',' + v[2] ); // quick and dirty
            Eigen::Vector3d a = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( v[3] + ',' + v[4] + ',' + v[5] ); // quick and dirty
            Eigen::Vector3d b = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( v[6] + ',' + v[7] + ',' + v[8] ); // quick and dirty
            a -= point;
            b -= point;
            if( comma::math::equal( std::abs( a.dot( b ) ), a.norm() * b.norm() ) ) { std::cerr << "points-slice: given points are not corners or a triangle: \"" << points_string << "\"" << std::endl; }
            normal = a.cross( b );
            if( vm.count( "point-outside" ) )
            {
                Eigen::Vector3d p = comma::csv::ascii< Eigen::Vector3d >( "x,y,z", ',' ).get( point_outside );
                if( comma::math::equal( ( p - point ).dot( normal ), 0 ) ) { std::cerr << "points-slice: expected a point outside of the plane, got: " << point_outside << ", which belongs to the plane" << std::endl; return 1; }
                normal *= normal.dot( p - point ) > 0 ? 1 : -1;
            }
        }
        normal.normalize();
        #ifdef WIN32
            _setmode( _fileno( stdout ), _O_BINARY ); /// @todo move to a library
        #endif
        comma::csv::input_stream< Eigen::Vector3d > istream( std::cin, csv, Eigen::Vector3d::Zero() );
        comma::signal_flag is_shutdown;
        comma::csv::ascii< Eigen::Vector3d > ascii( "x,y,z", csv.delimiter );
        comma::csv::binary< Eigen::Vector3d > binary( "3d", "x,y,z" );
        if( vm.count("intersections") )
        {
            Eigen::Hyperplane< double, 3 > plane( normal, point );
            boost::optional< Eigen::Vector3d > last;
            double d_last = 0;
            boost::optional< double > threshold;
            if( vm.count("threshold") ) { threshold.reset( vm["threshold"].as< double >() ); }
            std::string previous_line_ascii;
            std::vector< char > previous_data_binary;
            while( !is_shutdown && ( istream.ready() || ( !std::cin.eof() && std::cin.good() ) ) )
            {
                const Eigen::Vector3d* p = istream.read();
                if( !p ) { break; }
                double d = ( *p - point ).dot( normal );
                bool valid_intersection = false;
                if( last )
                {
                    bool intersects = d * d_last <= 0;
                    bool interval_within_threshold = !threshold || ( threshold && ( *p - *last ).norm() <= *threshold );
                    valid_intersection = intersects && interval_within_threshold;
                }
                if( valid_intersection )
                {
                    Eigen::Vector3d intersection_point;
                    BOOST_STATIC_ASSERT( sizeof( Eigen::Vector3d ) == sizeof( double ) * 3 );
                    bool lies_on_plane = ( d == 0 && d_last == 0 );
                    if( lies_on_plane )
                    {
                        intersection_point = *last; 
                    }
                    else
                    {
                        Eigen::ParametrizedLine< double, 3 > line = Eigen::ParametrizedLine< double, 3 >::Through( *last, *p );
                        intersection_point = line.intersectionPoint( plane );
                    }
                    comma::int32 direction;
                    if( d_last != 0 ) { direction = ( d_last < 0 ) ? 1 : -1; }
                    else if( d != 0 ) { direction = ( d > 0 ) ? 1 : -1; }
                    else { direction = 0; }
                    if( csv.binary() )
                    {
                        std::cout.write( &previous_data_binary[0], previous_data_binary.size() );
                        std::cout.write( istream.binary().last(), istream.binary().binary().format().size() );
                        std::cout.write( reinterpret_cast< const char* >( &intersection_point ), sizeof( double ) * 3 );
                        std::cout.write( reinterpret_cast< const char* >( &direction ), sizeof( comma::int32 ) );
                    }
                    else
                    {
                        std::cout << previous_line_ascii << csv.delimiter << comma::join( istream.ascii().last(), csv.delimiter ) << csv.delimiter
                                    << ascii.put( intersection_point ) << csv.delimiter << direction << std::endl;
                    }
                }
                last = *p;
                d_last = d;
                if( csv.binary() )
                {
                    if( previous_data_binary.size() != istream.binary().binary().format().size() )
                    {
                        previous_data_binary.resize( istream.binary().binary().format().size() );
                    }
                    ::memcpy( &previous_data_binary[0], istream.binary().last(), previous_data_binary.size() );
                }
                else
                {
                    previous_line_ascii = comma::join( istream.ascii().last(), csv.delimiter );
                }
            }
        }
        else
        {
            while( !is_shutdown && ( istream.ready() || ( !std::cin.eof() && std::cin.good() ) ) )
            {
                const Eigen::Vector3d* p = istream.read();
                if( !p ) { break; }
                double d = ( *p - point ).dot( normal );
                if( csv.binary() )
                {
                    std::cout.write( istream.binary().last(), istream.binary().binary().format().size() );
                    std::cout.write( reinterpret_cast< const char* >( &d ), sizeof( double ) );
                }
                else
                {
                    std::cout << comma::join( istream.ascii().last(), csv.delimiter ) << csv.delimiter << d << std::endl;
                }
            }
        }
        return 0;
    }
    catch( std::exception& ex )
    {
        std::cerr << "points-slice: " << ex.what() << std::endl;
    }
    catch( ... )
    {
        std::cerr << "points-slice: unknown exception" << std::endl;
    }
    return 1;
}
void StatePlaying::process(float dt)
{ 
  PlaneObject *planeObject = m_objects->getPlaneObject();

  // this should never happen but if it does leave
  if (planeObject == NULL) 
    return; 
    
  gConsole.process();
  
  // call process and move on all objects in the object manager
  m_objects->update(dt); 
    
  // process escape key and space bar
  processInput();

  // update location of camera
  processCamera(dt);
    
  // allow water to process per frame movements
  water->process(dt);
 
  // as soon as the plane crashes, start the timer
  if (planeObject->isPlaneAlive() == false && m_planeCrashed == false)
  {
    m_planeCrashed = true; // set that the plane has crashed
    m_timeSinceCrashed = 0.0f;
    m_crowID = -1;   
  }

  // once the timer hits 3 seconds, make the camera follow a crow
  if (m_planeCrashed)
  {
    m_timeSinceCrashed += dt;
    if (m_timeSinceCrashed >= 3.0f && m_crowID == -1)
    {
      // make the camera follow a crow around
      m_crowID = m_objects->getCrow();
      if (m_crowID != -1)
        m_tetherCamera->setTargetObject(m_crowID);

      // play the failed sound
      m_failedSound = gSoundManager.requestSoundHandle("Failed.wav");
      m_failedInstance = gSoundManager.requestInstance(m_failedSound);
      if(m_failedInstance != SoundManager::NOINSTANCE)
      {
        gSoundManager.setToListener(m_failedSound,m_failedInstance);
        gSoundManager.play(m_failedSound,m_failedInstance);
      }
    }
    else if(m_failedInstance != SoundManager::NOINSTANCE)
      gSoundManager.setToListener(m_failedSound,m_failedInstance);
  }

  // render reflection
  if (Water::m_bReflection)
  {
    // render water reflection    
    Plane plane( 0, 1, 0, -water->getWaterHeight());
    //get water texture ready  
    water->m_reflection.beginReflectedScene(plane);
    renderScene(true);
    water->m_reflection.endReflectedScene();    
  }

}
Esempio n. 23
0
int LevelAABBTree::GenerateTreeNode(int *lines, int num_lines, const FVector2 *centroids, int *work_buffer)
{
	if (num_lines == 0)
		return -1;

	// Find bounding box and median of the lines
	FVector2 median = FVector2(0.0f, 0.0f);
	FVector2 aabb_min, aabb_max;
	aabb_min.X = (float)level.lines[lines[0]].v1->fX();
	aabb_min.Y = (float)level.lines[lines[0]].v1->fY();
	aabb_max = aabb_min;
	for (int i = 0; i < num_lines; i++)
	{
		float x1 = (float)level.lines[lines[i]].v1->fX();
		float y1 = (float)level.lines[lines[i]].v1->fY();
		float x2 = (float)level.lines[lines[i]].v2->fX();
		float y2 = (float)level.lines[lines[i]].v2->fY();

		aabb_min.X = MIN(aabb_min.X, x1);
		aabb_min.X = MIN(aabb_min.X, x2);
		aabb_min.Y = MIN(aabb_min.Y, y1);
		aabb_min.Y = MIN(aabb_min.Y, y2);
		aabb_max.X = MAX(aabb_max.X, x1);
		aabb_max.X = MAX(aabb_max.X, x2);
		aabb_max.Y = MAX(aabb_max.Y, y1);
		aabb_max.Y = MAX(aabb_max.Y, y2);

		median += centroids[lines[i]];
	}
	median /= (float)num_lines;

	if (num_lines == 1) // Leaf node
	{
		nodes.Push(AABBTreeNode(aabb_min, aabb_max, lines[0]));
		return (int)nodes.Size() - 1;
	}

	// Find the longest axis
	float axis_lengths[2] =
	{
		aabb_max.X - aabb_min.X,
		aabb_max.Y - aabb_min.Y
	};
	int axis_order[2] = { 0, 1 };
	FVector2 axis_plane[2] = { FVector2(1.0f, 0.0f), FVector2(0.0f, 1.0f) };
	std::sort(axis_order, axis_order + 2, [&](int a, int b) { return axis_lengths[a] > axis_lengths[b]; });

	// Try sort at longest axis, then if that fails then the other one.
	// We place the sorted lines into work_buffer and then move the result back to the lines list when done.
	int left_count, right_count;
	for (int attempt = 0; attempt < 2; attempt++)
	{
		// Find the sort plane for axis
		FVector2 axis = axis_plane[axis_order[attempt]];
		FVector3 plane(axis, -(median | axis));

		// Sort lines into two based ib whether the line center is on the front or back side of a plane
		left_count = 0;
		right_count = 0;
		for (int i = 0; i < num_lines; i++)
		{
			int line_index = lines[i];

			float side = FVector3(centroids[lines[i]], 1.0f) | plane;
			if (side >= 0.0f)
			{
				work_buffer[left_count] = line_index;
				left_count++;
			}
			else
			{
				work_buffer[num_lines + right_count] = line_index;
				right_count++;
			}
		}

		if (left_count != 0 && right_count != 0)
			break;
	}

	// Check if something went wrong when sorting and do a random sort instead
	if (left_count == 0 || right_count == 0)
	{
		left_count = num_lines / 2;
		right_count = num_lines - left_count;
	}
	else
	{
		// Move result back into lines list:
		for (int i = 0; i < left_count; i++)
			lines[i] = work_buffer[i];
		for (int i = 0; i < right_count; i++)
			lines[i + left_count] = work_buffer[num_lines + i];
	}

	// Create child nodes:
	int left_index = -1;
	int right_index = -1;
	if (left_count > 0)
		left_index = GenerateTreeNode(lines, left_count, centroids, work_buffer);
	if (right_count > 0)
		right_index = GenerateTreeNode(lines + left_count, right_count, centroids, work_buffer);

	// Store resulting node and return its index
	nodes.Push(AABBTreeNode(aabb_min, aabb_max, left_index, right_index));
	return (int)nodes.Size() - 1;
}
dgInt32 dgCollisionConvexPolygon::CalculatePlaneIntersection (const dgVector& normalIn, const dgVector& origin, dgVector* const contactsOut) const
{
	dgVector normal(normalIn);
	dgInt32 count = 0;
	dgFloat32 maxDist = dgFloat32 (1.0f);
	dgFloat32 projectFactor = m_normal % normal;
	if (projectFactor < dgFloat32 (0.0f)) {
		projectFactor *= dgFloat32 (-1.0f);
		normal = normal.Scale3 (dgFloat32 (-1.0f));
	}

	if (projectFactor > dgFloat32 (0.9999f)) {
		for (dgInt32 i = 0; i < m_count; i ++) {
			contactsOut[count] = m_localPoly[i];
			count ++;
		}

		#ifdef _DEBUG
			dgInt32 j = count - 1;
			for (dgInt32 i = 0; i < count; i ++) {
				dgVector error (contactsOut[i] - contactsOut[j]);
				dgAssert ((error % error) > dgFloat32 (1.0e-20f));
				j = i;
			}
		#endif

	} else if (projectFactor > dgFloat32 (0.1736f)) {
		maxDist = dgFloat32 (0.0f);
		dgPlane plane (normal, - (normal % origin));

		dgVector p0 (m_localPoly[m_count - 1]);
		dgFloat32 side0 = plane.Evalue (p0);
		for (dgInt32 i = 0; i < m_count; i ++) {
			dgVector p1 (m_localPoly[i]);
			dgFloat32 side1 = plane.Evalue (p1);

			if (side0 > dgFloat32 (0.0f)) {
				maxDist = dgMax (maxDist, side0);
				contactsOut[count] = p0 - plane.Scale3 (side0);
				count ++;
				if (count > 1) {
					dgVector edgeSegment (contactsOut[count - 1] - contactsOut[count - 2]);
					dgFloat32 error = edgeSegment % edgeSegment;
					if (error < dgFloat32 (1.0e-8f)) {
						count --;
					}
				}

				if (side1 <= dgFloat32 (0.0f)) {
					dgVector dp (p1 - p0);
					dgFloat32 t = plane % dp;
					dgAssert (dgAbsf (t) >= dgFloat32 (0.0f));
					if (dgAbsf (t) < dgFloat32 (1.0e-8f)) {
						t = dgSign(t) * dgFloat32 (1.0e-8f);	
					}
					contactsOut[count] = p0 - dp.Scale3 (side0 / t);
					count ++;
					if (count > 1) {
						dgVector edgeSegment (contactsOut[count - 1] - contactsOut[count - 2]);
						dgFloat32 error = edgeSegment % edgeSegment;
						if (error < dgFloat32 (1.0e-8f)) {
							count --;
						}
					}
				} 
			} else if (side1 > dgFloat32 (0.0f)) {
				dgVector dp (p1 - p0);
				dgFloat32 t = plane % dp;
				dgAssert (dgAbsf (t) >= dgFloat32 (0.0f));
				if (dgAbsf (t) < dgFloat32 (1.0e-8f)) {
					t = dgSign(t) * dgFloat32 (1.0e-8f);	
				}
				contactsOut[count] = p0 - dp.Scale3 (side0 / t);
				count ++;
				if (count > 1) {
					dgVector edgeSegment (contactsOut[count - 1] - contactsOut[count - 2]);
					dgFloat32 error = edgeSegment % edgeSegment;
					if (error < dgFloat32 (1.0e-8f)) {
						count --;
					}
				}
			}

			side0 = side1;
			p0 = p1;
		}
	} else {
		maxDist = dgFloat32 (1.0e10f);
		dgPlane plane (normal, - (normal % origin));

		dgVector p0 (m_localPoly[m_count - 1]);
		dgFloat32 side0 = plane.Evalue (p0);
		for (dgInt32 i = 0; i < m_count; i ++) {
			dgVector p1 (m_localPoly[i]);
			dgFloat32 side1 = plane.Evalue (p1);

			if ((side0 * side1) < dgFloat32 (0.0f)) {
				dgVector dp (p1 - p0);
				dgFloat32 t = plane % dp;
				dgAssert (dgAbsf (t) >= dgFloat32 (0.0f));
				if (dgAbsf (t) < dgFloat32 (1.0e-8f)) {
					t = dgSign(t) * dgFloat32 (1.0e-8f);	
				}
				contactsOut[count] = p0 - dp.Scale3 (side0 / t);
				count ++;
				if (count > 1) {
					dgVector edgeSegment (contactsOut[count - 1] - contactsOut[count - 2]);
					dgFloat32 error = edgeSegment % edgeSegment;
					if (error < dgFloat32 (1.0e-8f)) {
						count --;
					}
				}
			}
			side0 = side1;
			p0 = p1;
		}
	}


	if (count > 1) {
		if (maxDist < dgFloat32 (1.0e-3f)) {
			dgVector maxPoint (contactsOut[0]);
			dgVector minPoint (contactsOut[0]);
			dgVector lineDir (m_normal * normal);

			dgFloat32 proj = contactsOut[0] % lineDir;
			dgFloat32 maxProjection = proj;
			dgFloat32 minProjection = proj;
			for (dgInt32 i = 1; i < count; i ++) {
				proj = contactsOut[i] % lineDir;
				if (proj > maxProjection) {
					maxProjection = proj;
					maxPoint = contactsOut[i];
				}
				if (proj < minProjection) {
					minProjection = proj;
					minPoint = contactsOut[i];
				}
			}	

			contactsOut[0] = maxPoint;
			contactsOut[1] = minPoint;
			count = 2;
		}


		dgVector error (contactsOut[count - 1] - contactsOut[0]);
		if ((error % error) < dgFloat32 (1.0e-8f)) {
			count --;
		}
	}

	#ifdef _DEBUG
		if (count > 1) {
			dgInt32 j = count - 1;
			for (dgInt32 i = 0; i < count; i ++) {
				dgVector error (contactsOut[i] - contactsOut[j]);
				dgAssert ((error % error) > dgFloat32 (1.0e-20f));
				j = i;
			}

			if (count >= 3) {
				dgVector n (dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f), dgFloat32 (0.0f));
				dgVector e0 (contactsOut[1] - contactsOut[0]);
				for (dgInt32 i = 2; i < count; i ++) {
					dgVector e1 (contactsOut[i] - contactsOut[0]);
					n += e0 * e1;
					e0 = e1;
				} 
				n = n.Scale3 (dgRsqrt(n % n));
				dgFloat32 val = n % normal;
				dgAssert (val > dgFloat32 (0.9f));
			}
		}
	#endif
	return count;
}
void BrushByPlaneClipper::visit(const scene::INodePtr& node) const
{
	// Don't clip invisible nodes
	if (!node->visible())
	{
		return;
	}

	// Try to cast the instance onto a brush
	Brush* brush = Node_getBrush(node);

	// Return if not brush
	if (brush == NULL)
	{
		return;
	}

	Plane3 plane(_p0, _p1, _p2);

	if (!plane.isValid())
	{
		return;
	}

	// greebo: Analyse the brush to find out which shader is the most used one
	getMostUsedTexturing(*brush);

	BrushSplitType split = Brush_classifyPlane(*brush, _split == eFront ? -plane : plane);

	if (split.counts[ePlaneBack] && split.counts[ePlaneFront])
	{
		// the plane intersects this brush
		if (_split == eFrontAndBack)
		{
			scene::INodePtr fragmentNode = GlobalBrushCreator().createBrush();

			// greebo: For copying the texture scale the new node needs a valid rendersystem
			fragmentNode->setRenderSystem(node->getRenderSystem());

			assert(fragmentNode != NULL);

			Brush* fragment = Node_getBrush(fragmentNode);
			assert(fragment != NULL);
			fragment->copy(*brush);

			// Put the fragment in the same layer as the brush it was clipped from
			scene::assignNodeToLayers(fragmentNode, node->getLayers());

			FacePtr newFace = fragment->addPlane(_p0, _p1, _p2, _mostUsedShader, _mostUsedProjection);

			if (newFace != NULL && _split != eFront)
			{
				newFace->flipWinding();
			}

			fragment->removeEmptyFaces();
			ASSERT_MESSAGE(!fragment->empty(), "brush left with no faces after split");

			// Mark this brush for insertion
			_insertList.insert(InsertMap::value_type(fragmentNode, node->getParent()));
		}

		FacePtr newFace = brush->addPlane(_p0, _p1, _p2, _mostUsedShader, _mostUsedProjection);

		if (newFace != NULL && _split == eFront) {
			newFace->flipWinding();
		}

		brush->removeEmptyFaces();
		ASSERT_MESSAGE(!brush->empty(), "brush left with no faces after split");
	}
	// the plane does not intersect this brush
	else if (_split != eFrontAndBack && split.counts[ePlaneBack] != 0)
	{
		// the brush is "behind" the plane
		_deleteList.insert(node);
	}
}
dgInt32 dgCollisionConvexPolygon::CalculateContactToConvexHullContinue(const dgWorld* const world, const dgCollisionInstance* const parentMesh, dgCollisionParamProxy& proxy)
{
	dgAssert(proxy.m_instance0->IsType(dgCollision::dgCollisionConvexShape_RTTI));
	dgAssert(proxy.m_instance1->IsType(dgCollision::dgCollisionConvexPolygon_RTTI));

	dgAssert(this == proxy.m_instance1->GetChildShape());
	dgAssert(m_count);
	dgAssert(m_count < dgInt32(sizeof (m_localPoly) / sizeof (m_localPoly[0])));

	const dgBody* const body0 = proxy.m_body0;
	const dgBody* const body1 = proxy.m_body1;

	dgAssert (proxy.m_instance1->GetGlobalMatrix().TestIdentity());

	dgVector relativeVelocity (body0->m_veloc - body1->m_veloc);

	dgFloat32 den = m_normal.DotProduct4(relativeVelocity).GetScalar();
	if (den > dgFloat32 (-1.0e-10f)) {
		return 0;
	}
	den = dgFloat32 (1.0f) / den;

	dgContact* const contactJoint = proxy.m_contactJoint;
	contactJoint->m_closestDistance = dgFloat32(1.0e10f);

	dgMatrix polygonMatrix;
	dgVector right (m_localPoly[1] - m_localPoly[0]);
	polygonMatrix[0] = right.CompProduct4(right.InvMagSqrt());
	polygonMatrix[1] = m_normal;
	polygonMatrix[2] = polygonMatrix[0] * m_normal;
	polygonMatrix[3] = dgVector::m_wOne;
	dgAssert (polygonMatrix.TestOrthogonal());

	dgVector polyBoxP0(dgFloat32(1.0e15f));
	dgVector polyBoxP1(dgFloat32(-1.0e15f));
	for (dgInt32 i = 0; i < m_count; i++) {
		dgVector point (polygonMatrix.UnrotateVector(m_localPoly[i]));
		polyBoxP0 = polyBoxP0.GetMin(point);
		polyBoxP1 = polyBoxP1.GetMax(point);
	}

	dgVector hullBoxP0;
	dgVector hullBoxP1;
	dgMatrix hullMatrix (polygonMatrix * proxy.m_instance0->m_globalMatrix);
	proxy.m_instance0->CalcAABB(hullMatrix, hullBoxP0, hullBoxP1);
	dgVector minBox(polyBoxP0 - hullBoxP1);
	dgVector maxBox(polyBoxP1 - hullBoxP0);
	dgVector veloc (polygonMatrix.UnrotateVector (relativeVelocity));
	dgFastRayTest ray(dgVector(dgFloat32(0.0f)), veloc);
 	dgFloat32 distance = ray.BoxIntersect(minBox, maxBox);

	dgInt32 count = 0;
	if (distance < dgFloat32(1.0f)) {
		bool inside = false;

		dgVector boxSize((hullBoxP1 - hullBoxP0).CompProduct4(dgVector::m_half));
		dgVector sphereMag2 (boxSize.DotProduct4(boxSize));
		boxSize = sphereMag2.Sqrt();

		dgVector pointInPlane (polygonMatrix.RotateVector(hullBoxP1 + hullBoxP0).CompProduct4(dgVector::m_half));
		dgFloat32 distToPlane = (m_localPoly[0] - pointInPlane) % m_normal;

		dgFloat32 timeToPlane0 = (distToPlane + boxSize.GetScalar()) * den;
		dgFloat32 timeToPlane1 = (distToPlane - boxSize.GetScalar()) * den;

		dgVector boxOrigin0 (pointInPlane + relativeVelocity.Scale4(timeToPlane0));
		dgVector boxOrigin1 (pointInPlane + relativeVelocity.Scale4(timeToPlane1));
		dgVector boxOrigin ((boxOrigin0 + boxOrigin1).CompProduct4(dgVector::m_half)); 
		dgVector boxProjectSize (((boxOrigin0 - boxOrigin1).CompProduct4(dgVector::m_half))); 
		sphereMag2 = boxProjectSize.DotProduct4(boxProjectSize);
		boxSize = sphereMag2.Sqrt();

		dgAssert (boxOrigin.m_w == 0.0f);
		boxOrigin = boxOrigin | dgVector::m_wOne;
		
		if (!proxy.m_intersectionTestOnly) {
			inside = true;
			dgInt32 i0 = m_count - 1;

			for (dgInt32 i = 0; i < m_count; i++) {
				dgVector e(m_localPoly[i] - m_localPoly[i0]);
				dgVector n(m_normal * e & dgVector::m_triplexMask);
				dgFloat32 param = dgSqrt (sphereMag2.GetScalar() / (n.DotProduct4(n)).GetScalar());
				dgPlane plane(n, -(m_localPoly[i0] % n));

				dgVector p0 (boxOrigin + n.Scale4 (param));
				dgVector p1 (boxOrigin - n.Scale4 (param));

				dgFloat32 size0 = (plane.DotProduct4 (p0)).GetScalar();
				dgFloat32 size1 = (plane.DotProduct4 (p1)).GetScalar();

				if ((size0 < 0.0f) && (size1 < 0.0f)) {
					return 0;
				}

				if ((size0 * size1) < 0.0f) {
					inside = false;
					break;
				}
				i0 = i;
			}
		}

		dgFloat32 convexSphapeUmbra = dgMax (proxy.m_instance0->GetUmbraClipSize(), boxSize.GetScalar());
		if (m_faceClipSize > convexSphapeUmbra) {
			BeamClipping(boxOrigin, convexSphapeUmbra);
			m_faceClipSize = proxy.m_instance0->m_childShape->GetBoxMaxRadius();
		}

		const dgInt32 hullId = proxy.m_instance0->GetUserDataID();
		if (inside & !proxy.m_intersectionTestOnly) {
			const dgMatrix& matrixInstance0 = proxy.m_instance0->m_globalMatrix;
			dgVector normalInHull(matrixInstance0.UnrotateVector(m_normal.Scale4(dgFloat32(-1.0f))));
			dgVector pointInHull(proxy.m_instance0->SupportVertex(normalInHull, NULL));
			dgVector p0 (matrixInstance0.TransformVector(pointInHull));

			dgFloat32 timetoImpact = dgFloat32(0.0f);
			dgFloat32 penetration = (m_localPoly[0] - p0) % m_normal + proxy.m_skinThickness;
			if (penetration < dgFloat32(0.0f)) {
				timetoImpact = penetration / (relativeVelocity % m_normal);
				dgAssert(timetoImpact >= dgFloat32(0.0f));
			}

			if (timetoImpact <= proxy.m_timestep) {
				dgVector contactPoints[64];
				contactJoint->m_closestDistance = penetration;
				proxy.m_timestep = timetoImpact;
				proxy.m_normal = m_normal;
				proxy.m_closestPointBody0 = p0;
				proxy.m_closestPointBody1 = p0 + m_normal.Scale4(penetration);

				if (!proxy.m_intersectionTestOnly) {
					pointInHull -= normalInHull.Scale4 (DG_ROBUST_PLANE_CLIP);
					count = proxy.m_instance0->CalculatePlaneIntersection(normalInHull, pointInHull, contactPoints);

					dgVector step(relativeVelocity.Scale4(timetoImpact));
					penetration = dgMax(penetration, dgFloat32(0.0f));
					dgContactPoint* const contactsOut = proxy.m_contacts;
					for (dgInt32 i = 0; i < count; i++) {
						contactsOut[i].m_point = matrixInstance0.TransformVector(contactPoints[i]) + step;
						contactsOut[i].m_normal = m_normal;
						contactsOut[i].m_shapeId0 = hullId;
						contactsOut[i].m_shapeId1 = m_faceId;
						contactsOut[i].m_penetration = penetration;
					}
				}
			}
		} else {
			m_vertexCount = dgUnsigned16 (m_count);
			count = world->CalculateConvexToConvexContacts(proxy);
			if (count >= 1) {
				dgContactPoint* const contactsOut = proxy.m_contacts;
				for (dgInt32 i = 0; i < count; i++) {
					contactsOut[i].m_shapeId0 = hullId;
					contactsOut[i].m_shapeId1 = m_faceId;
				}
			}
		}
	}

	return count;
}
Esempio n. 27
0
uchar* IPLImage::rgb32()
{
    if(_type == IMAGE_BW)
    {
        int i=0;
        for(int y=0; y < _height; y++)
        {
            for(int x=0; x < _width; x++)
            {
                uchar val = plane(0)->p(x,y) * FACTOR_TO_UCHAR;
                val = val < 0x80 ? 0x00 : 0xFF;
                _rgb32[i++] = val;
                _rgb32[i++] = val;
                _rgb32[i++] = val;
                _rgb32[i++] = 0xFF;
            }
        }
    }
    else if(_type == IMAGE_GRAYSCALE)
    {
        int i=0;
        for(int y=0; y < _height; y++)
        {
            for(int x=0; x < _width; x++)
            {
                uchar val = (plane(0)->p(x,y) * FACTOR_TO_UCHAR);
                _rgb32[i++] = val;
                _rgb32[i++] = val;
                _rgb32[i++] = val;
                _rgb32[i++] = 0xFF;
            }
        }
    }
    else if(_type == IMAGE_COLOR)
    {
        int i=0;
        for(int y=0; y < _height; y++)
        {
            for(int x=0; x < _width; x++)
            {
                uchar r = plane(0)->p(x,y) * FACTOR_TO_UCHAR;
                uchar g = plane(1)->p(x,y) * FACTOR_TO_UCHAR;
                uchar b = plane(2)->p(x,y) * FACTOR_TO_UCHAR;
                _rgb32[i++] = b;
                _rgb32[i++] = g;
                _rgb32[i++] = r;
                _rgb32[i++] = 0xFF;
            }
        }
    }
    else if(_type == IMAGE_ORIENTED)
    {
        double maxMag = 0.0;
        for(int x=0; x<_width; x++)
            for(int y=0; y<_height; y++)
                if( plane(0)->p(x,y) > maxMag ) maxMag = plane(0)->p(x,y);

        int i=0;
        for(int y=0; y < _height; y++)
        {
            for(int x=0; x < _width; x++)
            {
                ipl_basetype phase = fmod(plane(1)->p(x,y), 1.0);
                ipl_basetype magnitude = plane(0)->p(x,y) / maxMag;

                if(phase < 0)
                    phase = 0;
                if(phase > 1)
                    phase = 1;

                IPLColor color = IPLColor::fromHSV(phase, 1.0,  magnitude);

                uchar r = color.red()   * FACTOR_TO_UCHAR;
                uchar g = color.green() * FACTOR_TO_UCHAR;
                uchar b = color.blue()  * FACTOR_TO_UCHAR;
                _rgb32[i++] = b;
                _rgb32[i++] = g;
                _rgb32[i++] = r;
                _rgb32[i++] = 0xFF;
            }
        }
    }

    return _rgb32.data();
}
dgInt32 dgCollisionConvexPolygon::CalculateContactToConvexHullDescrete(const dgWorld* const world, const dgCollisionInstance* const parentMesh, dgCollisionParamProxy& proxy)
{
	dgInt32 count = 0;

	dgAssert(proxy.m_instance0->IsType(dgCollision::dgCollisionConvexShape_RTTI));
	dgAssert(proxy.m_instance1->IsType(dgCollision::dgCollisionConvexPolygon_RTTI));
	dgAssert (proxy.m_instance1->GetGlobalMatrix().TestIdentity());

	const dgCollisionInstance* const polygonInstance = proxy.m_instance1;
	dgAssert(this == polygonInstance->GetChildShape());
	dgAssert(m_count);
	dgAssert(m_count < dgInt32(sizeof (m_localPoly) / sizeof (m_localPoly[0])));

	const dgMatrix& hullMatrix = proxy.m_instance0->m_globalMatrix;
	dgContact* const contactJoint = proxy.m_contactJoint;
	const dgCollisionInstance* const hull = proxy.m_instance0;

	dgVector normalInHull(hullMatrix.UnrotateVector(m_normal));
	dgVector pointInHull(hull->SupportVertex(normalInHull.Scale4(dgFloat32(-1.0f)), NULL));
	dgVector p0(hullMatrix.TransformVector(pointInHull));

	dgFloat32 penetration = (m_localPoly[0] - p0) % m_normal + proxy.m_skinThickness;
	if (penetration < dgFloat32(-1.0e-5f)) {
		return 0;
	}

	dgVector p1(hullMatrix.TransformVector(hull->SupportVertex(normalInHull, NULL)));
	contactJoint->m_closestDistance = dgFloat32(0.0f);
	dgFloat32 distance = (m_localPoly[0] - p1) % m_normal;
	if (distance >= dgFloat32(0.0f)) {
		return 0;
	}

	dgVector boxSize;
	dgVector boxOrigin;
	hull->CalcObb(boxOrigin, boxSize);
	boxOrigin += dgVector::m_wOne;

	bool inside = true;
	dgInt32 i0 = m_count - 1;
	for (dgInt32 i = 0; i < m_count; i++) {
		dgVector e(m_localPoly[i] - m_localPoly[i0]);
		dgVector edgeBoundaryNormal(m_normal * e);
		dgPlane plane(edgeBoundaryNormal, - m_localPoly[i0].DotProduct4 (edgeBoundaryNormal).GetScalar());
		plane = hullMatrix.UntransformPlane(plane);

		dgFloat32 supportDist = boxSize.DotProduct4 (plane.Abs()).GetScalar();
		dgFloat32 centerDist = plane.DotProduct4 (boxOrigin).GetScalar();

		if ((centerDist + supportDist) < dgFloat32(0.0f)) {
			return 0;
		}

		if ((centerDist - supportDist) < dgFloat32(0.0f)) {
			inside = false;
			break;
		}
		i0 = i;
	}

	//inside = false;
	dgFloat32 convexSphapeUmbra = hull->GetUmbraClipSize();
	if (m_faceClipSize > convexSphapeUmbra) {
		BeamClipping(dgVector(dgFloat32(0.0f)), convexSphapeUmbra);
		m_faceClipSize = hull->m_childShape->GetBoxMaxRadius();
	}

	const dgInt32 hullId = hull->GetUserDataID();
	if (inside & !proxy.m_intersectionTestOnly) {
		penetration = dgMax (dgFloat32 (0.0f), penetration);
		dgAssert(penetration >= dgFloat32(0.0f));
		dgVector contactPoints[64];
		dgVector point(pointInHull + normalInHull.Scale4(penetration + DG_ROBUST_PLANE_CLIP));

		count = hull->CalculatePlaneIntersection(normalInHull.Scale4(dgFloat32(-1.0f)), point, contactPoints);
		dgVector step(normalInHull.Scale4((proxy.m_skinThickness - penetration) * dgFloat32(0.5f)));

		dgContactPoint* const contactsOut = proxy.m_contacts;
		dgAssert(contactsOut);
		for (dgInt32 i = 0; i < count; i++) {
			contactsOut[i].m_point = hullMatrix.TransformVector(contactPoints[i] + step);
			contactsOut[i].m_normal = m_normal;
			contactsOut[i].m_shapeId0 = hullId;
			contactsOut[i].m_shapeId1 = m_faceId;
			contactsOut[i].m_penetration = penetration;
		}
	} else {
		m_vertexCount = dgUnsigned16 (m_count);
		count = world->CalculateConvexToConvexContacts(proxy);
		dgAssert(proxy.m_intersectionTestOnly || (count >= 0));

		if (count >= 1) {
			dgContactPoint* const contactsOut = proxy.m_contacts;
			if (m_closestFeatureType == 3) {
				for (dgInt32 i = 0; i < count; i++) {
					//contactsOut[i].m_userId = m_faceId;
					contactsOut[i].m_shapeId0 = hullId;
					contactsOut[i].m_shapeId1 = m_faceId;
				}
			} else {
				dgVector normal (contactsOut[0].m_normal);

				if (normal.DotProduct4(m_normal).GetScalar() < dgFloat32(0.9995f)) {
					dgInt32 index = m_adjacentFaceEdgeNormalIndex[m_closestFeatureStartIndex];
					dgVector adjacentNormal (CalculateGlobalNormal (parentMesh, dgVector(&m_vertex[index * m_stride])));
					if ((m_normal.DotProduct4(adjacentNormal).GetScalar() > dgFloat32(0.9995f))) {
						normal = adjacentNormal;
					} else {
						dgVector dir0(adjacentNormal * m_normal);
						dgVector dir1(adjacentNormal * normal);
						dgFloat32 projection = dir0.DotProduct4(dir1).GetScalar();
						if (projection <= dgFloat32(0.0f)) {
							normal = adjacentNormal;
						}
					}
					normal = polygonInstance->m_globalMatrix.RotateVector(normal);

					for (dgInt32 i = 0; i < count; i++) {
						contactsOut[i].m_normal = normal;
						contactsOut[i].m_shapeId0 = hullId;
						contactsOut[i].m_shapeId1 = m_faceId;
					}
				} else {
					for (dgInt32 i = 0; i < count; i++) {
						contactsOut[i].m_shapeId0 = hullId;
						contactsOut[i].m_shapeId1 = m_faceId;
					}
				}
			}
		}
	}
	return count;
}
Esempio n. 29
0
void Planet::PlanetRenderImage::render(TSRenderContext &rc)
{
   // A simple planet culling scheme would be to dot the line of sight
   // with the vector from the camera to the planet.  This would eliminate
   // the length test of v below (after m_cross((Point3F)plane, vpNormal, &v))
   GFXSurface *gfxSurface = rc.getSurface();

   gfxSurface->setHazeSource(GFX_HAZE_NONE);
   gfxSurface->setShadeSource(GFX_SHADE_CONSTANT);
   gfxSurface->setAlphaSource(GFX_ALPHA_NONE);
	gfxSurface->setFillMode(GFX_FILL_TEXTURE);
   if (texture->attribute & BMA_TRANSPARENT) gfxSurface->setTransparency(true);
   else                                      gfxSurface->setTransparency(false);
   gfxSurface->setTexturePerspective(FALSE);
//   gfxSurface->setZTest(GFX_ZWRITE);

   gfxSurface->setConstantShade(1.0f);

   int textureHeight;
   gfxSurface->setTextureMap(texture);
   textureHeight = texture->height;
   
   TSCamera *camera = rc.getCamera();
  
   TS::PointArray *pointArray = rc.getPointArray();
   pointArray->reset();
   pointArray->useIntensities(false);
   pointArray->useTextures(textCoord);
   pointArray->useTextures(true);
	pointArray->setVisibility( TS::ClipMask );

   // find out how high the bitmap is at 100% as projected onto the viewport,
   // texel:pixel will be 1:1 at 640x480
   //const RectF &worldVP  = camera->getWorldViewport();
   //const float h = textureHeight*((worldVP.upperL.y - worldVP.lowerR.y)/480.0f);
   //const float sz = 0.5*distance*(h/camera->getNearDist());

   // find the position of the planet
   Point3F displacement = camera->getTCW().p;
   //displacement.z *= -(distance - visibleDistance)/visibleDistance;
//   displacement.z = -displacement.z*(distance/(visibleDistance*1.5f));
   Point3F pos = position;
   pos += displacement;
 
   // find the normal to the view plane in world coords
   Point3F v0(0.0f, 1.0f, 0.0f), vpNormal;
   m_mul(v0, (RMat3F)camera->getTCW(), &vpNormal);
   vpNormal.normalize();

   // construct the plane that the camera, planet pos & celestial NP all
   // lie on
   PlaneF plane(pos, camera->getTCW().p, 
      Point3F(displacement.x, displacement.y, displacement.z + distance));

   // the cross product of the VP normal and the normal to the plane just
   // constructed is the up vector for the planet
   Point3F v;
   m_cross((Point3F)plane, vpNormal, &v);
   if (IsEqual(v.len(), 0.0f)) {
      // planet is directly to the right or left of camera
      gfxSurface->setZTest(GFX_ZTEST_AND_WRITE);
      return;
   }
   v.normalize();
   
   // cross the up with the normal and we get the right vector
   Point3F u;
   m_cross(vpNormal, v, &u);
   u *= size;
   v *= size;

   TS::VertexIndexPair V[6];
   Point3F ul = pos;
   ul -= u; ul += v;
   V[0].fVertexIndex   = pointArray->addPoint(ul);
   V[0].fTextureIndex  = 0;
   Point3F ur = pos;
   ur += u; ur += v;
   V[1].fVertexIndex   = pointArray->addPoint(ur);
   V[1].fTextureIndex  = 1;
   Point3F lr = pos;
   lr += u; lr -= v;
   V[2].fVertexIndex   = pointArray->addPoint(lr);
   V[2].fTextureIndex  = 2;
   Point3F ll = pos;
   ll -= u; ll -=v;
   V[3].fVertexIndex   = pointArray->addPoint(ll);
   V[3].fTextureIndex  = 3;
	if (gfxSurface->getCaps() & GFX_DEVCAP_SUPPORTS_CONST_ALPHA)
	   gfxSurface->setZTest(GFX_NO_ZTEST);
   pointArray->drawPoly(4, V, 0);
	if (gfxSurface->getCaps() & GFX_DEVCAP_SUPPORTS_CONST_ALPHA)
	   gfxSurface->setZTest(GFX_ZTEST_AND_WRITE);
   if(lensFlare) {
      TS::TransformedVertex vx;
      camera->transformProject(pos, &vx);
      bool vis = vx.fStatus & TS::TransformedVertex::Projected;
      lensFlare->setSunPos(vis, vx.fPoint, pos);
   }
   gfxSurface->setZTest(GFX_ZTEST_AND_WRITE);
}
void CKWResearchWorkDoc::OnHelpTest()
{
	// TODO: Add your command handler code here
	vector<Point_3> SamplePoints;
	GeometryAlgorithm::SampleCircle(Point_3(0,0,0),0.3,20,SamplePoints);
	FILE* pfile=fopen("circle0.contour","w");
	for (unsigned int i=0;i<SamplePoints.size();i++)
	{
		fprintf(pfile,"%.3f %.3f %.3f\n",SamplePoints.at(i).x(),SamplePoints.at(i).y(),SamplePoints.at(i).z());
	}
	fclose(pfile);




	Polygon_2 PolyTest;
	PolyTest.push_back(Point_2(0,0));
	PolyTest.push_back(Point_2(1,1));
	PolyTest.push_back(Point_2(2,0));
	PolyTest.push_back(Point_2(2,2));
	PolyTest.push_back(Point_2(0,2));

	Point_2 ResultPoint;
	bool bResult=GeometryAlgorithm::GetArbiPointInPolygon(PolyTest,ResultPoint);
	DBWindowWrite("result point: %f %f\n",ResultPoint.x(),ResultPoint.y());



	SparseMatrix LHMatrix(2);
	LHMatrix.m = 3;
	LHMatrix[0][0] = 2;
	LHMatrix[0][1] = -1;
	LHMatrix[0][2] = 1;
	LHMatrix[1][1] = 1;
	LHMatrix[1][2] = 1;

	SparseMatrix LHMatrixAT(LHMatrix.NCols());
	CMath MathCompute;
	MathCompute.TAUCSFactorize(LHMatrix,LHMatrixAT);

	vector<vector<double>> RightMatB,ResultMat;
	vector<double> BRow;
	BRow.push_back(5);BRow.push_back(3);
	RightMatB.push_back(BRow);
	BRow.clear();
	BRow.push_back(10);BRow.push_back(1);
	RightMatB.push_back(BRow);
	BRow.clear();


	MathCompute.TAUCSComputeLSE(LHMatrixAT,RightMatB,ResultMat);

	return;

	int iVer=this->Mesh.size_of_vertices();
	int iEdge=this->Mesh.size_of_halfedges();
	int iFacet=this->Mesh.size_of_facets();

	Polygon_2 BoundingPolygon0;
	Polygon_2 BoundingPolygon1;

	bool bSimple0=BoundingPolygon0.is_simple();
	bool bSimple1=BoundingPolygon1.is_simple();
	bool bConvex0=BoundingPolygon0.is_convex();
	bool bConvex1=BoundingPolygon1.is_convex();
	bool bOrien0=BoundingPolygon0.is_clockwise_oriented();
	bool bOrien1=BoundingPolygon1.is_clockwise_oriented();

	BoundingPolygon0.reverse_orientation();
	BoundingPolygon1.reverse_orientation();
	//float?
	bool bIntersect=CGAL::do_intersect(BoundingPolygon0,BoundingPolygon1);

	bool bCW=BoundingPolygon0.is_clockwise_oriented();
	bool bConvex=BoundingPolygon0.is_convex();


	Plane_3 plane(1,1,1,0);
	vector<vector<Point_3>> IntersectCurves;
	int iNum=GeometryAlgorithm::GetMeshPlaneIntersection(this->Mesh,plane,IntersectCurves);



	CMath CMathTest;
	CMathTest.testTAUCS();



//	Vector_3 vec0(Point_3(0,0,1),Point_3(0,0,0));
	Vector_3 vec0(Point_3(0,0,0),Point_3(0,0,1));
//	Vector_3 vec0(0,0,1);
//	Vector_3 vec1(0,-1,-1);
	Vector_3 vec1(Point_3(0,0,0),Point_3(0,-1,-1));
	double dAngle=GeometryAlgorithm::GetAngleBetweenTwoVectors3d(vec0,vec1);


	vector<double> number;
	number.push_back(2);
	number.push_back(4);
	number.push_back(4);
	number.push_back(4);
	number.push_back(5);
	number.push_back(5);
	number.push_back(7);
	number.push_back(9);
	double dderi=GeometryAlgorithm::GetDerivation(number);





	Point_3 center(0,0,0);
	Sphere_3 sphere(center,1);
	Line_3 line(Point_3(0,2,1),Point_3(0,2,-1));
	vector<Point_3> points;
	GeometryAlgorithm::GetLineSphereIntersection(line,sphere,points);



	vector<Point_3> Group0,Group1;
	vector<Int_Int_Pair> GroupResult;

	Group0.push_back(Point_3(3,3,2));
	Group0.push_back(Point_3(5,3,2));
	Group0.push_back(Point_3(2,3,2));
	Group0.push_back(Point_3(6,3,2));
	Group0.push_back(Point_3(4,3,2));
	Group0.push_back(Point_3(1,3,2));

	Group1.push_back(Point_3(3,4,2));
	Group1.push_back(Point_3(1,4,2));
	Group1.push_back(Point_3(6,4,2));
	Group1.push_back(Point_3(2,4,2));
	Group1.push_back(Point_3(5,4,2));
	Group1.push_back(Point_3(4,4,2));

	vector<Point_3> vecMidPoint;
	GeometryAlgorithm::GroupNearestPoints(Group0,Group1,GroupResult,vecMidPoint);//

	vector<Point_3> OriginalCurve;
	OriginalCurve.push_back(Point_3(-1,0,2));
	OriginalCurve.push_back(Point_3(1,0,2));
	OriginalCurve.push_back(Point_3(1,0,0));
	OriginalCurve.push_back(Point_3(-1,0,0));
	vector<Point_3> NewCurve=OriginalCurve;
	vector<int> HandleInd;
	HandleInd.push_back(0);
	HandleInd.push_back(1);
	vector<Point_3> NewPos;
	NewPos.push_back(Point_3(-1,0,3));
	NewPos.push_back(Point_3(1,0,3));
//	CCurveDeform::ClosedCurveNaiveLaplacianDeform(NewCurve,HandleInd,NewPos,1);




	vector<vector<float>> MatrixA,MatrixB,Result;
	vector<float> CurrentRow;
	CurrentRow.push_back(2);CurrentRow.push_back(0);CurrentRow.push_back(1);
	MatrixA.push_back(CurrentRow);
	CurrentRow.clear();
	CurrentRow.push_back(3);CurrentRow.push_back(1);CurrentRow.push_back(2);
	MatrixA.push_back(CurrentRow);
	CurrentRow.clear();
	CurrentRow.push_back(0);CurrentRow.push_back(1);CurrentRow.push_back(0);
	MatrixA.push_back(CurrentRow);
	CurrentRow.clear();

	CurrentRow.push_back(1);CurrentRow.push_back(3);CurrentRow.push_back(0);
	MatrixB.push_back(CurrentRow);
	CurrentRow.clear();
	CurrentRow.push_back(2);CurrentRow.push_back(0);CurrentRow.push_back(2);
	MatrixB.push_back(CurrentRow);
	CurrentRow.clear();
	CurrentRow.push_back(1);CurrentRow.push_back(0);CurrentRow.push_back(1);
	MatrixB.push_back(CurrentRow);
	CurrentRow.clear();



	int iANonZeroSize=0;
	for (unsigned int i=0;i<MatrixA.size();i++)
	{
		for (unsigned int j=0;j<MatrixA.front().size();j++)
		{
			if (MatrixA.at(i).at(j)!=0)
			{
				iANonZeroSize++;
			}
		}
	}
	KW_SparseMatrix A(MatrixA.size(),MatrixA.front().size(),iANonZeroSize);
	for (unsigned int i=0;i<MatrixA.size();i++)
	{
		for (unsigned int j=0;j<MatrixA.front().size();j++)
		{
			if (MatrixA.at(i).at(j)!=0)
			{
				A.fput(i,j,MatrixA.at(i).at(j));
			}
		}
	}

	int iBNonZeroSize=0;
	for (unsigned int i=0;i<MatrixB.size();i++)
	{
		for (unsigned int j=0;j<MatrixB.front().size();j++)
		{
			if (MatrixB.at(i).at(j)!=0)
			{
				iBNonZeroSize++;
			}
		}
	}
	KW_SparseMatrix B(MatrixB.size(),MatrixB.front().size(),iBNonZeroSize);
	for (unsigned int i=0;i<MatrixB.size();i++)
	{
		for (unsigned int j=0;j<MatrixB.front().size();j++)
		{
			if (MatrixB.at(i).at(j)!=0)
			{
				B.fput(i,j,MatrixB.at(i).at(j));
			}
		}
	}


	KW_SparseMatrix C(A.m,B.n,0);
	KW_SparseMatrix::KW_multiply(A,B,C);

	int iIndex=0;
	Result.clear();
	for (int i=0;i<C.m;i++)
	{
		vector<float> CurrentRow;
		for (int j=0;j<C.n;j++)
		{
			iIndex=0;
			while (iIndex<C.vol)
			{
				if (C.indx[iIndex]==i&&C.jndx[iIndex]==j)
				{
					break;
				}
				iIndex++;
			}
			if (iIndex!=C.vol)
			{
				CurrentRow.push_back(C.array[iIndex]);
			}
			else
			{
				CurrentRow.push_back(0);
			}
		}
		Result.push_back(CurrentRow);
	}
}