void GameLayer::doGameEnd(CCNode* pSender){
	CCDirector* pDirector = CCDirector::sharedDirector();
	CCSize winSize = pDirector->getWinSize();

	//stop all acitons
	isGameEnded = true;
	heroLayer->unscheduleUpdate();
	heroLayer->unscheduleAllSelectors();
	_enemyAI->unscheduleUpdate();
	_enemyAI->unscheduleAllSelectors();

	//check game win or not
	CCSprite* resultPad = NULL;
	if (my_hero->getLife() <= 0){
		//game lose
		resultPad = CCSprite::create("ui/lose.png");
	}
	else{
		//game win
		resultPad = CCSprite::create("ui/win.png");
		MapLayer* thisMap = MapLayer::getMap();
		thisMap->unlockNextLevel();
		thisMap->setLevelAccomp();
	}
	this->addChild(resultPad, 101);
	resultPad->setPosition(ccp(winSize.width / 2, 
		winSize.height / 2 + resultPad->getContentSize().height / 3));

	//disable touches except back to menu
	CCLayerColor* maskLayer = CCLayerColor::create(ccc4(255, 255, 255, 160), winSize.width, winSize.height);
	this->setZOrder(1);
	this->addChild(maskLayer, 100);
	backIcon->setZOrder(101);
	backIcon->setPosition(ccp(winSize.width / 2, winSize.height / 2 - backIcon->getContentSize().height));
}
예제 #2
0
/**
 * ÄLÄ VITTU KOSKE IKINÄ TÄHÄN
 */
void TileMap::draw(SpriteBatch *batch, SDL_Rect *camera) {
	SDL_Rect from;
	SDL_Rect viewPoint;
	viewPoint.x = (camera->x + camera->w) / tileEngine.tileWidth  ;
	viewPoint.y = (camera->y + camera->h)  / tileEngine.tileHeight ;
	from.x = std::max(0, camera->x / tileEngine.tileWidth - 1);
	from.y = std::max(0, camera->y / tileEngine.tileHeight - 1);
	int toX = std::min(viewPoint.x + 1, tileEngine.width);
	int toY = std::min(viewPoint.y  + 1 , tileEngine.height);
	SDL_Rect to;
	to.x = toX;
	to.y = toY;
	Vector position(0,0);
	for (int layer = layers.size()-1; layer >= 0; layer--) {
		MapLayer mapLayer = layers[layer];
		for (int y = from.y; y < to.y; ++y) {
			position.y = y * tileEngine.tileHeight  - camera->y;
			for (int x = from.x; x < to.x; ++x) {
				if (mapLayer.getTile(y,x)->textureX >= 0) {
					position.x = x * tileEngine.tileWidth - camera->x;
					batch->draw(mapLayer.sheet->sheet, &position, mapLayer.getSource(y,x));
				}
			}
		}
	}

}
예제 #3
0
void j1Map::Draw()
{
	if(map_loaded == false)
		return;
	//STL CHANGE
	list<MapLayer*>::iterator item = data.layers.begin();

	for(; item != data.layers.end(); ++item)
	{
		MapLayer* layer = *item;

		if(layer->properties.Get("Nodraw") != 0)
			continue;

		for(int y = 0; y < data.height; ++y)
		{
			for(int x = 0; x < data.width; ++x)
			{
				int tile_id = layer->Get(x, y);
				if(tile_id > 0)
				{
					TileSet* tileset = GetTilesetFromTileId(tile_id);

					SDL_Rect r = tileset->GetTileRect(tile_id);
					iPoint pos = MapToWorld(x, y);

					App->render->Blit(tileset->texture, pos.x, pos.y, &r);
				}
			}
		}
	}
}
예제 #4
0
void j1Map::Draw()
{
	if(map_loaded == false)
		return;

	p2List_item<MapLayer*>* item = data.layers.start;

	for(; item != NULL; item = item->next)
	{
		MapLayer* layer = item->data;

		if(layer->properties.Get("Nodraw") != 0)
			continue;

		for(int y = 0; y < data.height; ++y)
		{
			for(int x = 0; x < data.width; ++x)
			{
				int tile_id = layer->Get(x, y);
				if(tile_id > 0)
				{
					TileSet* tileset = GetTilesetFromTileId(tile_id);

					SDL_Rect r = tileset->GetTileRect(tile_id);
					iPoint pos = MapToWorld(x, y);

					App->render->Blit(tileset->texture, pos.x, pos.y, &r);
				}
			}
		}
	}
}
예제 #5
0
void j1Map::Draw()
{
	if(map_loaded == false)
		return;

	// TODO 5: Prepare the loop to draw all tilesets + Blit
	MapLayer* layer = data.layers.start->data;

	for(int y = 0; y < data.height; ++y)
	{
		for(int x = 0; x < data.width; ++x)
		{
			int tile_id = layer->Get(x, y);
			if(tile_id > 0)
			{
				// TODO 10(old): Complete the draw function
				TileSet* tileset = data.tilesets.start->data;

				SDL_Rect r = tileset->GetTileRect(tile_id);
				iPoint pos = MapToWorld(x, y);

				App->render->Blit(tileset->texture, pos.x, pos.y, &r);
			}
		}
	}
}
예제 #6
0
MapLayer *MapLayer::create(Level *level)
{
    MapLayer *mapLayer = new MapLayer();
    if (mapLayer->initWithLevel(level)) {
        mapLayer->autorelease();
        return mapLayer;
    }
    CC_SAFE_RELEASE(mapLayer);
    return NULL;
}
예제 #7
0
void j1Map::Draw()
{
	if(map_loaded == false)
		return;
	//STL CHANGE
	//NOTE: well
	//Camera Culling
	//----------------------
	SDL_Rect cam = App->render->camera;
	//----------------------

	list<MapLayer*>::iterator item = data.layers.begin();

	for(; item != data.layers.end(); ++item)
	{
		MapLayer* layer = *item;


		//NOTE: when drawing navigation map, framerate drops to the half
		if (!App->debug)
			if(layer->properties.Get("Nodraw") != 0)
				continue;

		for(int y = 0; y < data.height; ++y)
		{
			for(int x = 0; x < data.width; ++x)
			{
				int tile_id = layer->Get(x, y);
				if(tile_id > 0)
				{
					TileSet* tileset = GetTilesetFromTileId(tile_id);

					SDL_Rect r = tileset->GetTileRect(tile_id);
					iPoint pos = MapToWorld(x, y);

					//NOTE: Maybe this has to be implemented on Render.cpp
					//NOTE: changing the offset of the tiles because Ric cheated with the original, think about make it general for any map
					//NOTE: because of test sake
					//----------------------

						if (layer->name == "Background")
							App->render->Blit(tileset->texture, pos.x - data.tile_width / 2 + tileset->offset_x, pos.y, &r);
						else if (layer->name == "Navigation")
							App->render->Blit(tileset->texture, pos.x - data.tile_width / 2 , pos.y, &r);
						
					
					//----------------------
				}
			}
		}
	}
	
}
예제 #8
0
MapLayer * MapLayer::create(){
    if(instance)
        return instance;
    
    MapLayer *mapLayer = new (std::nothrow) MapLayer();
    if(mapLayer && mapLayer->init()){
        mapLayer->autorelease();
        instance = mapLayer;
        return mapLayer;
    }
    CC_SAFE_DELETE(mapLayer);
    return nullptr;
}
예제 #9
0
void CWet_hView::OnTopographiccalculationSideofstream()
   {
      MapLayer *pSourceLayer = gpMapWnd->m_pMap->GetLayer( "Cells" );
		MapLayer *pToLayer = gpMapWnd->m_pMap->GetLayer("STRGRID");
		MapLayer *pFlowDirectionLayer = gpMapWnd->m_pMap->GetLayer("FLOWDIR");
		int colToSet = pSourceLayer->GetFieldCol("SIDE");
 
		int thisCount = pSourceLayer->GetRecordCount();
      int order = -1;
      
      for ( int i=0; i < thisCount; i++ )
			{
			Poly *pPoly = pSourceLayer->GetPolygon(i);
         float test = pPoly->GetArea();
			Vertex centroid = pPoly->GetCentroid();
      //   int colOrder = pSourceLayer->GetFieldCol("ORDER");
            
      //   pSourceLayer->GetData(i,colOrder,order);
         int side = -1;      
     //    if (order == 1)
         //   side = 0;
      //   else
         //   {
		   	int row = 0;
		   	int col = 0;
		   	pFlowDirectionLayer->GetGridCellFromCoord( centroid.x, centroid.y, row, col);
		   	side = pFlowDirectionLayer->GetSideOfStream(row, col, pToLayer);
         //   }

         pSourceLayer->SetData(i, colToSet, side);
         }
   }
예제 #10
0
bool j1Map::CreateWalkabilityMap(int& width, int& height, uchar** buffer) const
{
	//STL CHANGE
	bool ret = false;
	list<MapLayer*>::const_iterator item;
	item = data.layers.begin();

	for(item = data.layers.begin(); item != data.layers.end(); item++)
	{
		MapLayer* layer = *item;

		if(layer->properties.Get("Navigation", 0) == 0)
			continue;

		uchar* map = new uchar[layer->width*layer->height];
		memset(map, 1, layer->width*layer->height);

		for(int y = 0; y < data.height; ++y)
		{
			for(int x = 0; x < data.width; ++x)
			{
				int i = (y*layer->width) + x;

				int tile_id = layer->Get(x, y);
				TileSet* tileset = (tile_id > 0) ? GetTilesetFromTileId(tile_id) : NULL;
				
				if(tileset != NULL)
				{
					map[i] = (tile_id - tileset->firstgid) > 0 ? 0 : 1;
					/*TileType* ts = tileset->GetTileType(tile_id);
					if(ts != NULL)
					{
						map[i] = ts->properties.Get("walkable", 1);
					}*/
				}
			}
		}

		*buffer = map;
		width = data.width;
		height = data.height;
		ret = true;

		break;
	}

	return ret;
}
예제 #11
0
KDbool MainScene::initWithMapInformation ( KDint nLevel, KDint nStatus, KDint nLife )
{
	if ( !CCLayer::initWithVisibleViewport ( ) )
	{
		return KD_FALSE;
	}

	const CCSize&		tLyrSize = this->getContentSize ( );

	SimpleAudioEngine::sharedEngine ( )->playEffect ( "Sounds/02 start.wav" );

	CCLayerColor*		pBackColor = CCLayerColor::create ( ccc4 ( 192, 192, 192, 255 ), tLyrSize );
	this->addChild ( pBackColor );

	CCSpriteFrameCache::sharedSpriteFrameCache ( )->addSpriteFramesWithFile ( "Images/images.plist" );

	m_pIconArray = CCArray::create ( );
	m_pIconArray->retain ( );

	this->iconTank ( );

	CCSprite*		pLife = CCSprite::createWithSpriteFrameName ( "IP.png" );
	pLife->setPosition ( ccp ( 30, tLyrSize.cy - 50 ) );
	this->addChild ( pLife );
    
    CCSprite*		pLifeIcon = CCSprite::createWithSpriteFrameName ( "p1.png" );
	pLifeIcon->setPosition ( ccp ( 20, tLyrSize.cy - 70 ) );
	pLifeIcon->setScale ( 0.5f );
	this->addChild ( pLifeIcon );
	this->showLife ( nLife );
    
	CCSprite*		pFlag = CCSprite::createWithSpriteFrameName ( "flag.png" );
    pFlag->setPosition ( ccp ( tLyrSize.cx - 50 , tLyrSize.cy - 200 ) );
	this->addChild ( pFlag );
	this->showLevel ( nLevel );

	MapLayer*		pMapLayer = MapLayer::create ( nLevel, nStatus, nLife );
	pMapLayer->setDelegate ( this );
	this->addChild ( pMapLayer );

	InputLayer*		pInputLayer = InputLayer::create ( );
	pInputLayer->setMapLayer ( pMapLayer );
	this->addChild ( pInputLayer );

	return KD_TRUE;
}
예제 #12
0
void CWet_hView::GetFPDistGrid()
   {
   MapLayer *pFlowDir = gpMapWnd->m_pMap->GetLayer( "FLOWDIR" );
   MapLayer *pStreamGrid = gpMapWnd->m_pMap->GetLayer( "STRGRID" );
   MapLayer *pDEM = gpMapWnd->m_pMap->GetLayer( "DEM" );
   MapLayer *pFPDistGrid = gpMapWnd->m_pMap->GetLayer( "FLOWDIRX" );
   
 //  pFPDistGrid->m_name = "FP DistGrad";
   MapLayer *pWatershed = gpMapWnd->m_pMap->GetLayer( "CATCH" );


   float flowPathDistance=0.0f;
   int flowPathCount=0;

   int rows = pDEM->GetRowCount();
   int cols = pDEM->GetColCount();
   for ( int row=0; row < rows; row++ )
      {
      for ( int col=0; col < cols; col++ )
         {
         float distance = pFlowDir->GetDownFlowPathDistance( row, col, pStreamGrid );
         pFPDistGrid->m_pData->Set(col, row, (distance));
         }  // end of:  for ( col < cols )
      }  // end of:  for ( row < rows )
      pFPDistGrid->SaveGridFile("c:\\research\\maimai\\nato\\fpDist.grd");
   }
예제 #13
0
void CusefulView::OnShpFileOpen()
{
	// TODO: 在此添加命令处理程序代码
	CusefulDoc *pDoc = this->GetDocument();
	FeatureClass *pFeatureClass = pDoc->load_shapefile_file();
	if ( pFeatureClass == 0 ) return ;

	Layers& layers = m_pMapControl->GetLayers();
	LayerProperty *pLayerProperty = new LayerProperty(layers.Count()+1,pFeatureClass->GetName());
	pLayerProperty->SetRelateDataSet( pFeatureClass);
	MapLayer *pMapLayer = new MapLayer( pLayerProperty );
	pMapLayer->SetRender( new ShpRender( pMapLayer) );
	layers.Add( pMapLayer );

	this->m_pMapControl->Reset();
	CRect clientRect;
	this->GetClientRect(&clientRect);
	this->m_pMapControl->ReDraw(clientRect.left,clientRect.top,clientRect.Width(),clientRect.Height());
	this->Invalidate(false);
}
예제 #14
0
bool
MapEngine::isCached(Map* map, const osgEarth::TileKey *key)
{
    Threading::ScopedReadLock lock( map->getMapDataMutex() );

    const Profile* mapProfile = key->getProfile();

    //Check the imagery layers
    for( MapLayerList::const_iterator i = map->getImageMapLayers().begin(); i != map->getImageMapLayers().end(); i++ )
    {
        MapLayer* layer = i->get();
	    osg::ref_ptr< Cache > cache = layer->getCache();
    	if (!cache.valid()) return false;

        std::vector< osg::ref_ptr< const TileKey > > keys;

        if ( map->getProfile()->isEquivalentTo( layer->getProfile() ) )
        {
            keys.push_back( key );
        }
        else
        {
            layer->getProfile()->getIntersectingTiles( key, keys );
        }

        for (unsigned int j = 0; j < keys.size(); ++j)
        {
            if ( layer->isKeyValid( keys[j].get() ) )
            {
                if ( !cache->isCached( keys[j].get(), layer->getName(), layer->cacheFormat().value() ) )
                {
                    return false;
                }
            }
        }
    }

    //Check the elevation layers
    for( MapLayerList::const_iterator i = map->getHeightFieldMapLayers().begin(); i != map->getHeightFieldMapLayers().end(); i++ )
    {
        MapLayer* layer = i->get();
		osg::ref_ptr< Cache > cache = layer->getCache();
		if (!cache.valid()) return false;

        std::vector< osg::ref_ptr< const TileKey > > keys;

        if ( map->getProfile()->isEquivalentTo( layer->getProfile() ) )
        {
            keys.push_back( key );
        }
        else
        {
            layer->getProfile()->getIntersectingTiles( key, keys );
        }

        for (unsigned int j = 0; j < keys.size(); ++j)
        {
            if ( layer->isKeyValid( keys[j].get() ) )
            {
                if ( !cache->isCached( keys[j].get(), layer->getName(), layer->cacheFormat().value() ) )
                {
                    return false;
                }
            }
        }
    }
    return true;
}
예제 #15
0
		/*
	//read Willamette Shapefile
    //read data with 365 rows and 9 cols.  1 column for each major subwatershed (minus the middle Willamette, for which we don't have data. 1 row for each day in year
    //for each day, classify map according to data
    //append to avi file
    //finish
    BOOL m_saveEmfOutput = TRUE;
    if (m_saveEmfOutput)
         { 
         numMovies = 1;
         movieFrameRate = 30;
         AVIGenerators = new CAVIGenerator*[numMovies];  // array of pointers to AVI generators
         auxMovieStuff = new AuxMovieStuff[numMovies];
         CDC* dc = gpView->GetWindowDC();
         // get the window's dimensions
         CRect rect;
         gpView->GetWindowRect(rect);
         for(int i = 0; i < numMovies; i++)
            {
            // get output filename from user
            CFileDialog movieSaveDlg(FALSE, "avi", NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Movie Files (*.avi)|*.avi");
            CString movieFileName;
            if (movieSaveDlg.DoModal() == IDOK)
               {
               movieFileName = movieSaveDlg.GetPathName();
               }
            // need to handle canceling out of the file dialog box somehow

            AVIGenerators[i] = new CAVIGenerator(movieFileName, (CView*)gpView, movieFrameRate);

            AVIGenerators[i]->InitEngine();
            auxMovieStuff[i].bitmapDC.CreateCompatibleDC(dc);
            auxMovieStuff[i].bitmap.CreateCompatibleBitmap(dc, rect.Width(), rect.Height());
            auxMovieStuff[i].bitmapDC.SelectObject(&auxMovieStuff[i].bitmap);
            auxMovieStuff[i].bi.bmiHeader = *AVIGenerators[i]->GetBitmapHeader();
            auxMovieStuff[i].lpbi = &auxMovieStuff[i].bi;
            auxMovieStuff[i].bitAddress = new BYTE[3*rect.Width()*rect.Height()];
            }
         gpView->ReleaseDC(dc);
         }
	


    ASSERT ( gpMapWnd != NULL );
    ASSERT ( gpMapWnd->m_pMap != NULL );
	gpMapWnd->m_pMap->AddShapeLayer("c:\\research\\willamette\\will2.shp", true);
	MapLayer *pWill = gpMapWnd->m_pMap->GetLayer(0);
	FDataObj pAsciiData = FDataObj();
	pAsciiData.ReadAscii("c:\\research\\willamette\\willINDI.csv", ',');
	int numDays = pAsciiData.GetRowCount();
	int numWshed = pAsciiData.GetColCount()-1;
	float ti = -1.0f;
    
	gpMapWnd->m_pScatterPrecip = gpMapWnd->AllocateScatter( &pAsciiData, 0 );
	gpMapWnd->m_pScatterPrecip->RedrawWindow();

    for (int i=0;i<numDays;i++)           // for each day of the year (or row in the data)
		{
		int numSheds = pWill->m_pData->GetRowCount();
		float time = -1.0f;
		pAsciiData.Get(0,i,time);
        gpMapWnd->m_pScatterPrecip->UpdateCurrentPos( time );
		//gpMapWnd->m_pScatterPrecip->RedrawWindow();
		for (int j=0;j<numSheds;j++)  // go through each watershed (there are 12 of them)
			{
			float value = -1.0f;                              // and stick the data from pAsciiData into the datatable
			pAsciiData.Get(j+1,i,value);                         //dischargeValue
			pWill->SetData(j,pWill->GetFieldCol("EXTRA_2"),value); //add the value to the correct column in the Maplayer
			
			}
        CString msg;
		COleDateTime t( time );
		CString s = t.Format("%m/%d" );
		msg.Format( "Completed %s" , s );
        gpMain->SetStatusMsg( msg );

		pWill->SetBinColorFlag( BCF_BLUEGREEN );
		pWill->SetBins( -0.2, 0.4, 20 );
		pWill->SetActiveField( pWill->GetFieldCol( "EXTRA_2" ) );
	    pWill->ClassifyData();
        
		if ( gpMapWnd != NULL )
     	   gpMapWnd->RefreshList();

	    gpMapWnd->m_pMapList->RedrawWindow();
	    CDC *dc = gpMapWnd->m_pMap->GetDC();
	    gpMapWnd->m_pMap->DrawMap(*dc);
	    gpMapWnd->m_pMap->ReleaseDC(dc);
   
		if (m_saveEmfOutput)
			{
			CDC* dc = gpView->GetWindowDC();
			CRect rect;
			gpView->GetWindowRect(rect);

			for(int i = 0; i < numMovies; i++)
				{
				// copy from the application window to the new device context (and thus the bitmap)
				BOOL blitSuc = auxMovieStuff[i].bitmapDC.BitBlt(0, 0,
																rect.Width(),
																rect.Height(),
																dc, 0, 0, SRCCOPY);

				GetDIBits(auxMovieStuff[i].bitmapDC, HBITMAP(auxMovieStuff[i].bitmap),
							0, rect.Height(), auxMovieStuff[i].bitAddress,
							auxMovieStuff[i].lpbi, DIB_RGB_COLORS);

				AVIGenerators[i]->AddFrame((BYTE*)auxMovieStuff[i].bitAddress);
				}
			gpView->ReleaseDC(dc);
			}
		}
		

	if(m_saveEmfOutput)
		{
		for(int i = 0; i < numMovies; i++)
			{
			AVIGenerators[i]->ReleaseEngine();
			delete AVIGenerators[i];
			AVIGenerators[i] = 0;

			//ReleaseDC(NULL,auxMovieStuff[i].bitmapDC);
			delete [] auxMovieStuff[i].bitAddress;
			}
		delete [] AVIGenerators;
		delete [] auxMovieStuff;
		AVIGenerators = 0;
		}
	}
   */
void CWet_hView::OnTopographiccalculationDisgradientandquotientforgrid()
   {
   MapLayer *pFlowDir = gpMapWnd->m_pMap->GetLayer( "FLOWDIR" );
   MapLayer *pStreamGrid = gpMapWnd->m_pMap->GetLayer( "STRGRID" );
   MapLayer *pFPDistGrid = gpMapWnd->m_pMap->GetLayer( "FLOWDIRX" );
   MapLayer *pFPDistGrid1 = gpMapWnd->m_pMap->CloneLayer( *pFPDistGrid );
   MapLayer *pFPDistGrid2 = gpMapWnd->m_pMap->CloneLayer( *pFPDistGrid );
   MapLayer *pDEM = gpMapWnd->m_pMap->GetLayer("DEM");
   /*
   float flowPathDistance=0.0f;
   int flowPathCount=0;
   
   float flowPathGradient = 0.0001f;
   int rows = pFlowDir->GetRowCount();
   int cols = pFlowDir->GetColCount();
   int cellCount = rows*cols;
   int sofar=0;
   for ( int row=0; row < rows; row++ )
      {
      for ( int col=0; col < cols; col++ )
         {
         int flowPathCellCount=0;
         float distance = pFlowDir->GetDownFlowPathDistance( row, col, pStreamGrid );
         float gradient = pFlowDir->GetDownFlowPathGradient(row,col,pStreamGrid,pDEM,flowPathCellCount);
         gradient=gradient/flowPathCellCount;        
         float dist_grad = distance/gradient;
         if (distance==pFlowDir->GetNoDataValue())
            {
            dist_grad = pFlowDir->GetNoDataValue();
            gradient = pFlowDir->GetNoDataValue();
            }

         pFPDistGrid->m_pData->Set(col, row, gradient);  
         pFPDistGrid1->m_pData->Set(col, row, distance);  
         pFPDistGrid2->m_pData->Set(col, row, dist_grad);  
         sofar = sofar++;
         gpHydroModel->m_pMap->Notify( NT_CALCDIST, sofar, cellCount ); 
         }  // end of:  for ( col < cols )
      }  // end of:  for ( row < rows )
*/
   float flowPathDistance=0.0f;
   int flowPathCount=0;
    float flowPathGradient = 0.0001f;
   MapLayer *pWatershed = gpMapWnd->m_pMap->GetLayer( "Cells" );
   int polygonCount   = pWatershed->GetRecordCount();
   for ( int i=0; i < polygonCount; i++ )
		{    
		Poly *pThisPoly = pWatershed->m_polyArray[ i ];
      float flowPathDistance=0.0f;
      int flowPathCount=0;
      float flowPathGradient = 0.0001f;
      int rows = pDEM->GetRowCount();
      int cols = pDEM->GetColCount();
      for ( int row=0; row < rows; row++ )
         {
         for ( int col=0; col < cols; col++ )
            {
               float x = 0;
               float y = 0;
               pDEM->GetGridCellCenter(row, col, x, y);
              
               Vertex point;
               point.x = x;
               point.y = y;       
               if (pThisPoly->IsPointInPoly(point))
                  {
                  int flowPathCellCount=0;
                  float distance = pFlowDir->GetDownFlowPathDistance( row, col, pStreamGrid );
                  float gradient = pFlowDir->GetDownFlowPathGradient(row,col,pStreamGrid,pDEM,flowPathCellCount);
                  gradient=gradient/flowPathCellCount;        
                  float dist_grad = distance/gradient;
                  if (distance==pFlowDir->GetNoDataValue())
                     {
                     dist_grad = pFlowDir->GetNoDataValue();
                     gradient = pFlowDir->GetNoDataValue();
                     }
                  
                  pFPDistGrid->m_pData->Set(col, row, (distance/gradient));
                  flowPathGradient +=gradient;
                  flowPathDistance +=distance;

                  }
               }
            }  // end of:  for ( col < cols )
         }  // end of:  for ( row < rows )
      
      float averageFPDistance = flowPathDistance/flowPathCount;
      float averageFPGrad = flowPathGradient/flowPathCount;
      float averageFPDistGrad = averageFPDistance/averageFPGrad;
      //float rt = (0.00881f*averageFPDistGrad) + 0.00314f;
 		gpHydroModel->m_pMap->Notify( NT_CALCDIST, i, polygonCount );   
      pWatershed->SetData(i,pWatershed->m_pData->GetCol("EXTRA_1"), averageFPDistGrad);
















   pFPDistGrid2->SaveGridFile("c:\\temp\\Dist_Grad.asc");
   pFPDistGrid1->SaveGridFile("c:\\temp\\Dist.asc");
   pFPDistGrid->SaveGridFile("c:\\temp\\Grad.asc");
   }
예제 #16
0
bool GameScene::init(){
	if (!Scene::initWithPhysics())
	{
		return false;
	}
	
	SimpleAudioEngine::getInstance()->rewindBackgroundMusic();
	

	//英雄层
	HeroLayer *herolayer = HeroLayer::create();
	herolayer->setName("herolayer");
	this->addChild(herolayer,3);

	//显示边框,注释了就不显示了
	//this->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);
	//负数为添加向下的加速度
	this->getPhysicsWorld()->setGravity(Vec2(0,-1100));



	//可视区域大小
	Size visSize = Director::getInstance()->getVisibleSize();

	//背景图片
	Sprite *bg = Sprite::create("bg19a.jpg");
	bg->setScale(2);
	bg->setPosition(Vec2(visSize.width/2,visSize.height/2));
	this->addChild(bg);



	//创建Edge
	Edge *edge = Edge::create();
	//设置边界为整个可是区域
	edge->setPosition(visSize.width/2,visSize.height/2);
	//设置可以参与碰撞
	//edge->getPhysicsBody()->setContactTestBitmask(1);
	//添加到 层上面
	this->addChild(edge);

	//控制层
	ControlLayer *controller = ControlLayer::create();
	controller->setName("controller");
	this->addChild(controller,9);

	//添加 敌人层
	auto enemyLayer = EnemyLayer::create();
	enemyLayer->setName("enemylayer");
	this->addChild(enemyLayer,3);

	//地图
	MapLayer *maplayer = MapLayer::create();
	maplayer->setName("maplayer");
	this->addChild(maplayer,0);


	//逻辑层
	LogicLayer *logic = LogicLayer::create();
	this->addChild(logic);

	//添加动画层
	AnimateLayer * animatelayer = AnimateLayer::create();
	this->addChild(animatelayer);

	//怪物AI层
	auto enemyAILayer = EnemyAILayer::create();
	this->addChild(enemyAILayer);


	//创建一个底面
	auto background = Sprite::create();//就是一个精灵
	background->setTag(2001);
	background->setPhysicsBody(PhysicsBody::createBox(Size(visSize.width,74)));
	background->setTextureRect(Rect(0,0,visSize.width,74));//设置纹理的 宽 高
	background->getPhysicsBody()->setCategoryBitmask(16);
	background->getPhysicsBody()->setCollisionBitmask(31);
	background->getPhysicsBody()->setContactTestBitmask(0);
	background->setPosition(visSize.width/2,5);//设置地板的 位置 
	background->getPhysicsBody()->setDynamic(false);
	background->setOpacity(0);//设置透明度为0
	this->addChild(background);


	//创建积分层
	ScoreLayer *scoreLayer = ScoreLayer::create();
	scoreLayer->setName("scoreLayer");
	this->addChild(scoreLayer,9);

	SkillLayer *skill = SkillLayer::create();
	skill->setName("skilllayer");
	this->addChild(skill,9);

	return true;
}
예제 #17
0
osg::Node*
MapEngine::createPopulatedTile( Map* map, VersionedTerrain* terrain, const TileKey* key, bool wrapInPagedLOD, bool fallback, bool &validData )
{
    Threading::ScopedReadLock lock( map->getMapDataMutex() );

    bool isProjected = map->getCoordinateSystemType() == Map::CSTYPE_PROJECTED;
    bool isPlateCarre = isProjected && map->getProfile()->getSRS()->isGeographic();
    bool isGeocentric = !isProjected;

    double xmin, ymin, xmax, ymax;
    key->getGeoExtent().getBounds( xmin, ymin, xmax, ymax );

    GeoImageList image_tiles;

    const MapLayerList& imageMapLayers = map->getImageMapLayers();
    const MapLayerList& hfMapLayers = map->getHeightFieldMapLayers();

    // Collect the image layers
    bool empty_map = imageMapLayers.size() == 0 && hfMapLayers.size() == 0;
    
    // Whether to use a special mercator locator instead of reprojecting data to spherical mercator
    bool useMercatorLocator = true;

    // Create the images for the tile
    for( MapLayerList::const_iterator i = imageMapLayers.begin(); i != imageMapLayers.end(); i++ )
    {
        MapLayer* layer = i->get();

        osg::ref_ptr<GeoImage> image;
		//Only create images if the key is valid
        if ( layer->isKeyValid( key ) )
        {
            if ( _L2cache )
                image = _L2cache->createImage( layer, key );
            else
                image = layer->createImage( key );
        }
        image_tiles.push_back(image.get());

        // if any one of the layers explicity disables the merc fast path, disable for the whole thing:
        if ( layer->useMercatorFastPath().isSetTo( false ) )
            useMercatorLocator = false;
    }

    bool hasElevation = false;

    //Create the heightfield for the tile
    osg::ref_ptr<osg::HeightField> hf;
    if ( hfMapLayers.size() > 0 )
    {
        hf = map->createHeightField( key, false, _engineProps.elevationInterpolation().value());     
    }

    //If we are on the first LOD and we couldn't get a heightfield tile, just create an empty one.  Otherwise you can run into the situation
    //where you could have an inset heightfield on one hemisphere and the whole other hemisphere won't show up.
    if (map->isGeocentric() && key->getLevelOfDetail() <= 1 && !hf.valid())
    {
        hf = createEmptyHeightField( key );
    }
    hasElevation = hf.valid();

    //Determine if we've created any images
    unsigned int numValidImages = 0;
    for (unsigned int i = 0; i < image_tiles.size(); ++i)
    {
        if (image_tiles[i].valid()) numValidImages++;
    }


    //If we couldn't create any imagery or heightfields, bail out
    if (!hf.valid() && (numValidImages == 0) && !empty_map)
    {
        OE_DEBUG << LC << "Could not create any imagery or heightfields for " << key->str() <<".  Not building tile" << std::endl;
        validData = false;

        //If we're not asked to fallback on previous LOD's and we have no data, return NULL
        if (!fallback)
        {
            return NULL;
        }
    }
    else
    {
        validData = true;
    }
   
    //Try to interpolate any missing image layers from parent tiles
    for (unsigned int i = 0; i < imageMapLayers.size(); i++ )
    {
        if (!image_tiles[i].valid())
        {
			GeoImage* image = NULL;
            if (imageMapLayers[i]->isKeyValid(key))
            {
				//If the key was valid and we have no image, then something possibly went wrong with the image creation such as a server being busy.
                image = createValidGeoImage(imageMapLayers[i].get(), key);
            }

			//If we still couldn't create an image, either something is really wrong or the key wasn't valid, so just create a transparent placeholder image
			if (!image)
			{
				//If the image is not valid, create an empty texture as a placeholder
                image = new GeoImage(ImageUtils::createEmptyImage(), key->getGeoExtent());
			}

			//Assign the new image to the proper place in the list
			image_tiles[i] = image;
        }
    }

    //Fill in missing heightfield information from parent tiles
    if (!hf.valid())
    {
        //We have no heightfield sources, 
        if ( hfMapLayers.size() == 0 )
        {
            hf = createEmptyHeightField( key );
        }
        else
        {
            //Try to get a heightfield again, but this time fallback on parent tiles
            hf = map->createHeightField( key, true, _engineProps.elevationInterpolation().value());
            if (!hf.valid())
            {
                //We couldn't get any heightfield, so just create an empty one.
                hf = createEmptyHeightField( key );
            }
            else
            {
                hasElevation = true;
            }
        }
    }


    // In a Plate Carre tesselation, scale the heightfield elevations from meters to degrees
    if ( isPlateCarre )
    {
        HeightFieldUtils::scaleHeightFieldToDegrees( hf.get() );
    }

    osg::ref_ptr<GeoLocator> locator = GeoLocator::createForKey( key, map );
    osgTerrain::HeightFieldLayer* hf_layer = new osgTerrain::HeightFieldLayer();
    hf_layer->setLocator( locator.get() );
    hf_layer->setHeightField( hf.get() );

    VersionedTile* tile = new VersionedTile( key, locator.get() );
    tile->setTerrainTechnique( osg::clone(terrain->getTerrainTechniquePrototype(), osg::CopyOp::DEEP_COPY_ALL) );
    tile->setVerticalScale( _engineProps.verticalScale().value() );
    tile->setLocator( locator.get() );
    tile->setElevationLayer( hf_layer );
    tile->setRequiresNormals( true );
    tile->setDataVariance(osg::Object::DYNAMIC);

    //Attach an updatecallback to normalize the edges of TerrainTiles.
    if (hasElevation && _engineProps.normalizeEdges().get() )
    {
        tile->setUpdateCallback(new TerrainTileEdgeNormalizerUpdateCallback());
        tile->setDataVariance(osg::Object::DYNAMIC);
    }

    //Assign the terrain system to the TerrainTile.
    //It is very important the terrain system is set while the MapConfig's sourceMutex is locked.
    //This registers the terrain tile so that adding/removing layers are always in sync.  If you don't do this
    //you can end up with a situation where the database pager is waiting to merge a tile, then a layer is added, then
    //the tile is finally merged and is out of sync.

	double min_units_per_pixel = DBL_MAX;

    int layer = 0;
   // create contour layer:
    if (map->getContourTransferFunction() != NULL)
    {
      osgTerrain::ContourLayer* contourLayer(new osgTerrain::ContourLayer(map->getContourTransferFunction()));

      contourLayer->setMagFilter(_engineProps.getContourMagFilter().value());
      contourLayer->setMinFilter(_engineProps.getContourMinFilter().value());
      tile->setColorLayer(layer,contourLayer);
      ++layer;
    }

    for (unsigned int i = 0; i < image_tiles.size(); ++i)
    {
        if (image_tiles[i].valid())
        {
            double img_xmin, img_ymin, img_xmax, img_ymax;

            //Specify a new locator for the color with the coordinates of the TileKey that was actually used to create the image
            osg::ref_ptr<GeoLocator> img_locator;
			
            GeoImage* geo_image = image_tiles[i].get();

            // Use a special locator for mercator images (instead of reprojecting)
            if (map->getProfile()->getSRS()->isGeographic() &&
                geo_image->getSRS()->isMercator() && 
                useMercatorLocator )
            {
                GeoExtent geog_ext = image_tiles[i]->getExtent().transform(image_tiles[i]->getExtent().getSRS()->getGeographicSRS());
                geog_ext.getBounds( img_xmin, img_ymin, img_xmax, img_ymax );
                img_locator = key->getProfile()->getSRS()->createLocator( img_xmin, img_ymin, img_xmax, img_ymax );
                img_locator = new MercatorLocator( *img_locator.get(), geo_image->getExtent() );
            }
            else
            {
                image_tiles[i]->getExtent().getBounds( img_xmin, img_ymin, img_xmax, img_ymax );

                img_locator = key->getProfile()->getSRS()->createLocator( 
                    img_xmin, img_ymin, img_xmax, img_ymax, isPlateCarre );
            }

            if ( isGeocentric )
                img_locator->setCoordinateSystemType( osgTerrain::Locator::GEOCENTRIC );

			TransparentLayer* img_layer = new TransparentLayer(geo_image->getImage(), imageMapLayers[i].get());
            img_layer->setLevelOfDetail( key->getLevelOfDetail() );
            img_layer->setName( imageMapLayers[i]->getName() );
            img_layer->setLocator( img_locator.get());
			img_layer->setMinFilter( imageMapLayers[i]->getMinFilter().value());
			img_layer->setMagFilter( imageMapLayers[i]->getMagFilter().value());

			double upp = geo_image->getUnitsPerPixel();

			// Scale the units per pixel to degrees if the image is mercator (and the key is geo)
            if ( geo_image->getSRS()->isMercator() && key->getGeoExtent().getSRS()->isGeographic() )
                upp *= 1.0f/111319.0f;

			min_units_per_pixel = osg::minimum(upp, min_units_per_pixel);

            tile->setColorLayer( layer, img_layer );
            layer++;
        }
    }

    osg::BoundingSphere bs = tile->getBound();
    double max_range = 1e10;
    double radius = bs.radius();

#if 1
    double min_range = radius * _engineProps.minTileRangeFactor().get();
    osg::LOD::RangeMode mode = osg::LOD::DISTANCE_FROM_EYE_POINT;
#else
	double width = key->getGeoExtent().width();	
	if (min_units_per_pixel == DBL_MAX) min_units_per_pixel = width/256.0;
	double min_range = (width / min_units_per_pixel) * _engineProps.getMinTileRangeFactor(); 
    osg::LOD::RangeMode mode = osg::LOD::PIXEL_SIZE_ON_SCREEN;
#endif


    // a skirt hides cracks when transitioning between LODs:
    hf->setSkirtHeight(radius * _engineProps.heightFieldSkirtRatio().get() );

    // for now, cluster culling does not work for CUBE rendering
    bool isCube = map->getCoordinateSystemType() == Map::CSTYPE_GEOCENTRIC_CUBE;
    if ( isGeocentric && !isCube )
    {
        //TODO:  Work on cluster culling computation for cube faces
        osg::ClusterCullingCallback* ccc = createClusterCullingCallback(tile, locator->getEllipsoidModel() );
        tile->setCullCallback( ccc );
    }
    
    // Wait until now, when the tile is fully baked, to assign the terrain to the tile.
    // Placeholder tiles might try to locate this tile as an ancestor, and access its layers
    // and locators...so they must be intact before making this tile available via setTerrain.
    //
    // If there's already a placeholder tile registered, this will be ignored. If there isn't,
    // this will register the new tile.
    tile->setTerrain( terrain );
    terrain->registerTile( tile );

    // Set the tile's revision to the current terrain revision
    tile->setTerrainRevision( static_cast<VersionedTerrain*>(terrain)->getRevision() );

    if ( _engineProps.loadingPolicy()->mode() != LoadingPolicy::MODE_STANDARD && key->getLevelOfDetail())
    {
        tile->setUseLayerRequests( true );
        tile->setHasElevationHint( hasElevation );
    }

    tile->setTerrainRevision( terrain->getRevision() );
    tile->setDataVariance( osg::Object::DYNAMIC );

    osg::Node* result = 0L;

    if (wrapInPagedLOD)
    {
        // create a PLOD so we can keep subdividing:
        osg::PagedLOD* plod = new osg::PagedLOD();
        plod->setCenter( bs.center() );
        plod->addChild( tile, min_range, max_range );

        std::string filename = createURI( map->getId(), key );

        //Only add the next tile if it hasn't been blacklisted
        bool isBlacklisted = osgEarth::Registry::instance()->isBlacklisted( filename );
        if (!isBlacklisted && key->getLevelOfDetail() < this->getEngineProperties().maxLOD().value() && validData )
        {
            plod->setFileName( 1, filename  );
            plod->setRange( 1, 0.0, min_range );
        }
        else
        {
            plod->setRange( 0, 0, FLT_MAX );
        }

#if USE_FILELOCATIONCALLBACK
        osgDB::Options* options = new osgDB::Options;
        options->setFileLocationCallback( new osgEarth::FileLocationCallback);
        plod->setDatabaseOptions( options );
#endif
        result = plod;

        if ( tile->getUseLayerRequests() )
            result->addCullCallback( new TileImageBackfillCallback() );
    }
    else
    {
        result = tile;
    }

    return result;
}
예제 #18
0
void CacheSeed::seed( Map* map )
{
    Threading::ScopedReadLock lock( map->getMapDataMutex() );

    if (!map->getCache())
    {
        OE_WARN << "Warning:  Map does not have a cache defined, please define a cache." << std::endl;
        return;
    }

    osg::ref_ptr<MapEngine> engine = new MapEngine(); //map->createMapEngine();

    std::vector< osg::ref_ptr<TileKey> > keys;
    map->getProfile()->getRootKeys(keys);

    //Set the default bounds to the entire profile if the user didn't override the bounds
    if (_bounds.xMin() == 0 && _bounds.yMin() == 0 &&
        _bounds.xMax() == 0 && _bounds.yMax() == 0)
    {
        const GeoExtent& mapEx =  map->getProfile()->getExtent();
        _bounds = Bounds( mapEx.xMin(), mapEx.yMin(), mapEx.xMax(), mapEx.yMax() );
    }


    bool hasCaches = false;
    int src_min_level = INT_MAX;
    int src_max_level = 0;

    //Assumes the the TileSource will perform the caching for us when we call createImage
    for( MapLayerList::const_iterator i = map->getImageMapLayers().begin(); i != map->getImageMapLayers().end(); i++ )
    {
		MapLayer* layer = i->get();
        TileSource* src = i->get()->getTileSource();

        if (layer->cacheOnly().get())
        {
            OE_WARN << "Warning:  Cannot seed b/c Layer \"" << layer->getName() << "\" is cache only." << std::endl;
            return;
        }
        else if (!src)
        {
            OE_WARN << "Warning: Layer \"" << layer->getName() << "\" could not create TileSource." << std::endl;
        }
        else if ( !src->supportsPersistentCaching() )
        {
            OE_WARN << "Warning: Layer \"" << layer->getName() << "\" does not support seeding." << std::endl;
        }
        else if ( !layer->getCache() )
        {
            OE_NOTICE << "Notice: Layer \"" << layer->getName() << "\" has no persistent cache defined; skipping." << std::endl;
        }
        else
        {
            hasCaches = true;

			if (layer->minLevel().isSet() && layer->minLevel().get() < src_min_level)
                src_min_level = layer->minLevel().get();
			if (layer->maxLevel().isSet() && layer->maxLevel().get() > src_max_level)
                src_max_level = layer->maxLevel().get();
        }
    }

    for( MapLayerList::const_iterator i = map->getHeightFieldMapLayers().begin(); i != map->getHeightFieldMapLayers().end(); i++ )
    {
		MapLayer* layer = i->get();
        TileSource* src = i->get()->getTileSource();

        if (layer->cacheOnly().get())
        {
            OE_WARN << "Warning:  Cannot seed b/c Layer \"" << layer->getName() << "\" is cache only." << std::endl;
            return;
        }
        else if (!src)
        {
            OE_WARN << "Warning: Layer \"" << layer->getName() << "\" could not create TileSource." << std::endl;
        }
        else if ( !src->supportsPersistentCaching() )
        {
            OE_WARN << "Warning: Layer \"" << layer->getName() << "\" does not support seeding." << std::endl;
        }
        else if ( !layer->getCache() )
        {
            OE_NOTICE << "Notice: Layer \"" << src->getName() << "\" has no persistent cache defined; skipping." << std::endl;
        }
        else
        {
            hasCaches = true;

			if (layer->minLevel().isSet() && layer->minLevel().get() < src_min_level)
                src_min_level = layer->minLevel().get();
			if (layer->maxLevel().isSet() && layer->maxLevel().get() > src_max_level)
                src_max_level = layer->maxLevel().get();
		}
    }

    if (!hasCaches)
    {
        OE_NOTICE << "There are either no caches defined in the map, or no sources to cache. Exiting." << std::endl;
        return;
    }

    if ( src_max_level > 0 && src_max_level < _maxLevel )
    {
        _maxLevel = src_max_level;
    }

    OE_NOTICE << "Maximum cache level will be " << _maxLevel << std::endl;

    for (unsigned int i = 0; i < keys.size(); ++i)
    {
        processKey( map, engine.get(), keys[i].get() );
    }
}
예제 #19
0
void CWet_hView::OnTopographiccalculationMeanwatershedelevation()
   {
   MapLayer *pFlowDir = gpMapWnd->m_pMap->GetLayer( "FLOWDIR" );
   MapLayer *pStreamGrid = gpMapWnd->m_pMap->GetLayer( "STRGRID" );
   MapLayer *pDEM = gpMapWnd->m_pMap->GetLayer( "DEM" );
   MapLayer *pFPDistGrid = gpMapWnd->m_pMap->CloneLayer( *pDEM );
   pFPDistGrid->m_name = "FP DistGrad";
   MapLayer *pWatershed = gpMapWnd->m_pMap->GetLayer( "Cells" );
   MapLayer *pStreamV = gpMapWnd->m_pMap->GetLayer("Streams");
   
   int method = 2;
  // the third parameter is the method to use.  a 1 simply returns the average fpdist for each polygon
   // a two returns the entire fp distribution
   int watershedCount   = pWatershed->GetRecordCount();
   int reachCount = pStreamV->GetRecordCount();
   gpHydroModel->m_fpDistributionArray.SetSize(reachCount);
   gpHydroModel->m_fpDistributionArrayStream.SetSize(reachCount);
   for (int i=0; i < reachCount; i++ )
		{
      Poly *pStreamPoly = pStreamV->m_polyArray[i];
      int streamID;
      gpHydroModel->m_pStreamLayer->GetData(i,pStreamV->m_pData->GetCol("HYDRO_ID"), streamID);
      for ( int j=0; j < watershedCount; j++ )//this should be for each reach
         {
		   Poly *pThisPoly = pWatershed->m_polyArray[j];
         int watershedID;
         gpHydroModel->m_pCellLayer->GetData(j,pWatershed->m_pData->GetCol("HYDRO_ID"), watershedID);
         if (watershedID==streamID) // this polygon is in the current reach
            {
		      Poly *pThisPoly = pWatershed->m_polyArray[j];
            float flowPathDistance=0.0f;
            int flowPathCount=0;
            
            float flowPathGradient = 0.001f;
            int rows = pDEM->GetRowCount();
            int cols = pDEM->GetColCount();
            for ( int row=0; row < rows; row++ )
               {
               for ( int col=0; col < cols; col++ )
                  {
                  float x = 0;
                  float y = 0;
                  pDEM->GetGridCellCenter(row, col, x, y);
                  
                  Vertex point;
                  point.x = x;
                  point.y = y;       ///the stream grid is smaller than the flowdir grid
                  if (pThisPoly->IsPointInPoly(point))
                     {
                     int flowPathCellCount=0;
                     float distance = pFlowDir->GetDownFlowPathDistance( row, col, pStreamGrid );
                     float gradient = pFlowDir->GetDownFlowPathGradient(row,col,pStreamGrid,pDEM,flowPathCellCount);
                     gradient=gradient/flowPathCellCount;        
                     float dist_grad = distance/gradient;
                     if (distance==pFlowDir->GetNoDataValue())
                        {
                        dist_grad = pFlowDir->GetNoDataValue();
                        gradient = pFlowDir->GetNoDataValue();
                        }
                     pFPDistGrid->m_pData->Set(col, row, (distance/gradient)); 
                     if (method==1)// we just want the average fpdistance
                        {
                        flowPathGradient +=gradient;
                        flowPathDistance +=distance;
                        flowPathCount++;
                        }
                     if (method==2)// we want to maintain the entire distribution
                        {
                        int dist = (int)(distance/gradient);
                        gpHydroModel->m_fpDistributionArray[i].Add(dist);
                        }
                     }
                  }  // end of:  for ( col < cols )
               }  // end of:  for ( row < rows )
            } // end of :  if watershed==streamID
         }// end of j (watershedCount)
   //  we have found all the flowpaths in the jth reach, but want to now find the median value of that distribution
      float median=-1;
      if (method==2)
         {
         int  temp=-1;
         for (int bottom=gpHydroModel->m_fpDistributionArray[i].GetCount()-1; bottom>0;bottom--)
            {
            for (int position=0;position<bottom;position++)
               {
               int val = gpHydroModel->m_fpDistributionArray[i][position+1];
               int val2 = gpHydroModel->m_fpDistributionArray[i][position];
               if (val < val2)
                  {
                  int temp2 = gpHydroModel->m_fpDistributionArray[i][position];
                  gpHydroModel->m_fpDistributionArray[i][position] = gpHydroModel->m_fpDistributionArray[i][position+1];
                  gpHydroModel->m_fpDistributionArray[i][position+1] = temp2;
                  }
               }
            }
         if (gpHydroModel->m_fpDistributionArray[i].GetCount()<=1)//there were no watersheds for this reach
            {
            median = 0.0f;
            }
         else
            {
            int midValue = gpHydroModel->m_fpDistributionArray[i].GetCount()/2;
            median = (float)gpHydroModel->m_fpDistributionArray[i][midValue];
            }
         }//end of method
   //  float rt = (0.00881f*averageFPDistGrad) + 0.00314f;
 		gpHydroModel->m_pMap->Notify( NT_CALCDIST, i, reachCount );   
      pStreamV->SetData(i,pStreamV->m_pData->GetCol("EXTRA_1"), median);
      
      int cellID = -1;
      pStreamV->GetData(i,pStreamV->m_pData->GetCol("HYDRO_ID"), cellID);
      for (int k=0;k<pStreamV->GetRecordCount();k++)
         {
	      ReachNode *pNode = gpHydroModel->m_reachTree.m_nodeArray[k];
	      REACH_INFO_HYDRO *pHydro1 = (REACH_INFO_HYDRO*) pNode->m_reachInfo.pData; 
         if (pNode->m_reachInfo.index == i)
            pHydro1->cumSedimentOutflow = median;
         }
      }// end of this REACHs


      //Now are finished finding the median fpdist/gradient for each subwatershed and need to accumulate them downslope

      ReachNode *pNode = gpHydroModel->m_reachTree.FindLeftLeaf();  // find leftmost leaf of entire tree (no params defaults to m_pRoot )
	   REACH_INFO_HYDRO *pHydro = gpHydroModel->GetReachInfoHydroFromReachID( pNode->m_reachInfo.reachID );
      gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)pHydro->cumSedimentOutflow);
 	   int count=0;
      while ( pNode->m_pDown->m_reachInfo.index != ROOT_NODE )
         {
         ReachNode *pDown = pNode->m_pDown;
         if (( pDown->m_pLeft == pNode ) && ( pDown->m_pRight != NULL ))
            {
            pNode = gpHydroModel->m_reachTree.FindLeftLeaf( pDown->m_pRight );
			   REACH_INFO_HYDRO *pHydro = gpHydroModel->GetReachInfoHydroFromReachID( pNode->m_reachInfo.reachID );
            gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)pHydro->cumSedimentOutflow);
            count++;
            }

         else // We have all upstream orders, so can move downstream.
            {
		      pNode = pDown;
			   int reachID = pNode->m_reachInfo.reachID;
			   if ( pNode->m_reachInfo.index == PHANTOM_NODE)  //phantom node - we need our right's right and left pointers!
				//if (  pNode->m_reachInfo.reachID==-1)
            {
				   pNode = pNode->m_pDown;    // just move downstream one node
				   REACH_INFO_HYDRO *pHydro = gpHydroModel->GetReachInfoHydroFromReachID( pNode->m_reachInfo.reachID );
               gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)pHydro->cumSedimentOutflow);
               count++;
               int size = gpHydroModel->m_fpDistributionArray[pNode->m_pRight->m_pRight->m_reachInfo.index].GetSize();
               
               for (int i=0; i<gpHydroModel->m_fpDistributionArrayStream[pNode->m_pRight->m_pRight->m_reachInfo.index].GetSize();i++) 
                  gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)gpHydroModel->m_fpDistributionArrayStream[pNode->m_pRight->m_pRight->m_reachInfo.index][i]);
               
               for (int i=0; i<gpHydroModel->m_fpDistributionArrayStream[pNode->m_pRight->m_pLeft->m_reachInfo.index].GetSize();i++) 
                   gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)gpHydroModel->m_fpDistributionArrayStream[pNode->m_pRight->m_pLeft->m_reachInfo.index][i]);
               
               for (int i=0; i<gpHydroModel->m_fpDistributionArrayStream[pNode->m_pLeft->m_reachInfo.index].GetSize();i++) 
                   gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)gpHydroModel->m_fpDistributionArrayStream[pNode->m_pLeft->m_reachInfo.index][i]);

               }
			   else //Not a phantom so just add up the left, right and current area.
				   {
				   REACH_INFO_HYDRO *pHydro = gpHydroModel->GetReachInfoHydroFromReachID( pNode->m_reachInfo.reachID );
				   if ( pNode->m_pRight != NULL )
                  {
                  gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)pHydro->cumSedimentOutflow);
                  count++;
                  for (int i=0; i<gpHydroModel->m_fpDistributionArrayStream[pNode->m_pRight->m_reachInfo.index].GetSize();i++) 
                     gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)gpHydroModel->m_fpDistributionArrayStream[pNode->m_pRight->m_reachInfo.index][i]);
                  
                  for (int i=0; i<gpHydroModel->m_fpDistributionArrayStream[pNode->m_pLeft->m_reachInfo.index].GetSize();i++) 
                     gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)gpHydroModel->m_fpDistributionArrayStream[pNode->m_pLeft->m_reachInfo.index][i]);                                 
                  }
               else
                  {
                  gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)pHydro->cumSedimentOutflow); 
                  count++;
                  for (int i=0; i<gpHydroModel->m_fpDistributionArrayStream[pNode->m_pLeft->m_reachInfo.index].GetSize();i++) 
                     gpHydroModel->m_fpDistributionArrayStream[pNode->m_reachInfo.index].Add((int)gpHydroModel->m_fpDistributionArrayStream[pNode->m_pLeft->m_reachInfo.index][i]);
                  }
               }
         }//end of : else
      }//end of While (search for the root node...)

//Now go through the m_fpDistributionArray and again find the median value.

 for (int j=0;j<pStreamV->GetRecordCount();j++)
    {  
   float median=-1.0f;
   float rt=0.0f;
   if (method==2)
      {
      int  temp=-1;
      int count = gpHydroModel->m_fpDistributionArrayStream[j].GetCount();
      for (int bottom=gpHydroModel->m_fpDistributionArrayStream[j].GetCount()-1; bottom>0;bottom--)
         {
         for (int position=0;position<bottom;position++)
            {
            int val = gpHydroModel->m_fpDistributionArrayStream[j][position+1];
            int val2 = gpHydroModel->m_fpDistributionArrayStream[j][position];
            if (val < val2)
               {
               int temp2 = gpHydroModel->m_fpDistributionArrayStream[j][position];
               gpHydroModel->m_fpDistributionArrayStream[j][position] = gpHydroModel->m_fpDistributionArrayStream[j][position+1];
               gpHydroModel->m_fpDistributionArrayStream[j][position+1] = temp2;
               }
            }
         }
     // if (gpHydroModel->m_fpDistributionArrayStream[j].GetCount()<=1)//there were no watersheds for this reach
       //  median = 0;
     // else
       //  {
         
         int midValue = gpHydroModel->m_fpDistributionArrayStream[j].GetCount();
         if (midValue<0)
            median=0.0f;
         else
            median = (float)gpHydroModel->m_fpDistributionArrayStream[j][(int)(midValue/2)];

         rt = (0.002347f*median) + 0.186f;
       //  }
      }//end of j - now on to the next stream reach in the array  

      // Then add the median value to somewhere that can be mapped...
    gpHydroModel->m_pMap->Notify( NT_CALCDIST, j, reachCount );   
    pStreamV->SetData(j,pStreamV->m_pData->GetCol("EXTRA_1"), median);
    int streamID=-1;
    pStreamV->GetData(j,pStreamV->m_pData->GetCol("HYDRO_ID"), streamID);

      for ( int jj=0; jj < watershedCount; jj++ )//this should be for each reach
         {
		   Poly *pThisPoly = pWatershed->m_polyArray[jj];
         int watershedID;
         gpHydroModel->m_pCellLayer->GetData(jj,pWatershed->m_pData->GetCol("HYDRO_ID"), watershedID);
         if (watershedID==streamID) // this polygon is in the current reach
            pWatershed->SetData(jj,pWatershed->m_pData->GetCol("EXTRA_1"), rt);
            
         }


    }   
    float minVal=0.0f;
    float maxVal=0.0f;
    pWatershed->GetDataMinMax( pWatershed->m_pData->GetCol("EXTRA_1"), &minVal, &maxVal );
    pWatershed->SetBins(minVal,maxVal,10);
    pWatershed->ClassifyData(pWatershed->m_pData->GetCol("EXTRA_1"));
    if ( gpMapWnd != NULL )
       gpMapWnd->RefreshList();  
	gpMapWnd->m_pMapList->RedrawWindow();
	CDC *dc = gpMapWnd->m_pMap->GetDC();
	gpMapWnd->m_pMap->DrawMap(*dc);
	gpMapWnd->m_pMap->ReleaseDC(dc);
    
    pWatershed->SaveShapeFile("c:\\temp\\test.shp",false);

   }//end of method...