Пример #1
0
void FileDataPersister::persistEquation(const std::string& directoryPath, const LLSSolver::LLSEquationPtr& equation, const int counter)
{
    const std::string prefix1 = "matX_";
    const std::string filePath1 = generatePath(directoryPath, prefix1, counter);

    const std::string prefix2 = "matY_";
    const std::string filePath2 = generatePath(directoryPath, prefix2, counter);

    writeMatToFile(equation->X, filePath1);
    writeMatToFile(equation->Y, filePath2);
}
Пример #2
0
Spectrum BidirIntegrator::Li(const Scene *scene,
		const RayDifferential &ray,
		const Sample *sample, float *alpha) const {
	Spectrum L(0.);
	// Generate eye and light sub-paths
	BidirVertex eyePath[MAX_VERTS], lightPath[MAX_VERTS];
	int nEye = generatePath(scene, ray, sample, eyeBSDFOffset,
		eyeBSDFCompOffset, eyePath, MAX_VERTS);
	if (nEye == 0) {
		*alpha = 0.;
		return L;
	}
	*alpha = 1;
	// Choose light for bidirectional path
	int lightNum = Floor2Int(sample->oneD[lightNumOffset][0] *
		scene->lights.size());
	lightNum = min(lightNum, (int)scene->lights.size() - 1);
	Light *light = scene->lights[lightNum];
	float lightWeight = float(scene->lights.size());
	// Sample ray from light source to start light path
	Ray lightRay;
	float lightPdf;
	float u[4];
	u[0] = sample->twoD[lightPosOffset][0];
	u[1] = sample->twoD[lightPosOffset][1];
	u[2] = sample->twoD[lightDirOffset][0];
	u[3] = sample->twoD[lightDirOffset][1];
	Spectrum Le = light->Sample_L(scene, u[0], u[1], u[2], u[3],
		&lightRay, &lightPdf);
	if (lightPdf == 0.) return 0.f;
	Le = lightWeight / lightPdf;
	int nLight = generatePath(scene, lightRay, sample, lightBSDFOffset,
		lightBSDFCompOffset, lightPath, MAX_VERTS);
	// Connect bidirectional path prefixes and evaluate throughput
	Spectrum directWt(1.0);
	for (int i = 1; i <= nEye; ++i) {
		// Handle direct lighting for bidirectional integrator
		directWt /= eyePath[i-1].rrWeight;
		L += directWt *
			UniformSampleOneLight(scene, eyePath[i-1].p, eyePath[i-1].ng, eyePath[i-1].wi,
			eyePath[i-1].bsdf, sample, directLightOffset[i-1], directLightNumOffset[i-1],
			directBSDFOffset[i-1], directBSDFCompOffset[i-1]) /
			weightPath(eyePath, i, lightPath, 0);
		directWt *= eyePath[i-1].bsdf->f(eyePath[i-1].wi, eyePath[i-1].wo) *
			AbsDot(eyePath[i-1].wo, eyePath[i-1].ng) /
			eyePath[i-1].bsdfWeight;
		for (int j = 1; j <= nLight; ++j)
			L += Le * evalPath(scene, eyePath, i, lightPath, j) /
				weightPath(eyePath, i, lightPath, j);
	}
	return L;
}
Пример #3
0
bool DemoApp::camMouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
	if (mTrayMgr->injectMouseUp(arg, id))
		return true;

	switch (id)
	{
		case OIS::MB_Left:
			{
				// If visible set to invisible
				if(mSelectionBox->isVisible())
				{
					mSelectionBox->setVisible(false);
					mSelecting = false;
				}
				if(boxTimeout<6)
				{
					quickSelect();
				}
				boxTimeout=0;
				mousePressedVar=false;
			}
			break;
			case OIS::MB_Right:
			{
				generatePath();
			}
			break;
		default:
			break;
	}

	return true;
}
Пример #4
0
const QString gcode::generateGcode()
{
    QString sGcode;
    for (int i=0; i< m_allPaths.size(); i++)
        sGcode += generatePath(m_allPaths[i]);

    return sGcode;
}
Пример #5
0
int main( int argc, char** argv )
{
	// Initialize GLFW
	glfwInit();
	if( !setupWindow( appWidth, appHeight, fullScreen ) ) return -1;
	
	// Initalize application and engine
	app = new Application( generatePath( argv[0], "../Content" ) );
	if ( !app->init() )
	{
		// Fake message box
		glfwCloseWindow();
		glfwOpenWindow( 800, 16, 8, 8, 8, 8, 24, 8, GLFW_WINDOW );
		glfwSetWindowTitle( "Unable to initalize engine - Make sure you have an OpenGL 2.0 compatible graphics card" );
		glfwSleep( 5 );
		
		std::cout << "Unable to initalize engine" << std::endl;
		std::cout << "Make sure you have an OpenGL 2.0 compatible graphics card";
		glfwTerminate();
		return -1;
	}
	app->resize( appWidth, appHeight );
	TwWindowSize( appWidth, appHeight );
	//glfwDisable( GLFW_MOUSE_CURSOR );

	int frames = 0;
	float fps = 30.0f;
	t0 = glfwGetTime();
	running = true;

	// Game loop
	while( running )
	{
		// Calc FPS
		++frames;
		if( frames >= 3 )
		{
			double t = glfwGetTime();
			fps = frames / (float)(t - t0);
			frames = 0;
			t0 = t;
		}

		// Render
		app->mainLoop( fps );
		TwDraw();
		glfwSwapBuffers();
	}

	glfwEnable( GLFW_MOUSE_CURSOR );

	// Quit
	app->release();
	delete app;
	glfwTerminate();

	return 0;
}
Пример #6
0
 void render(QGraphicsScene *scene) {
     for (size_t i = 0; i < cubes.size(); ++i) {
         float size = cubes[i]->getSize();
         float x = cubes[i]->getX();
         float y = cubes[i]->getY();
         QGraphicsPixmapItem *buf = cubes[i]->getCubePicture();
         buf = scene->addPixmap(QPixmap(generatePath(PATH_PROJECT, PATH_CUBE, F_CUBE2)));
         buf->setPos(x - size / 2,y - size / 2);
     }
 }
Пример #7
0
void Player::update(float elapsed)
{
	// Pfad wird je nach Spielgeschwindigkeit aktualisiert
	delta += elapsed * game.getGameSpeed();

	if (delta > 0)
		generatePath(target.position);

	delta -= (int)delta;
}
Пример #8
0
	TEST_F(MCFManagerFixture, generatePath_unauthed)
	{
		DesuraId id("1", "games");
		gcString strPath = generatePath(id, MCFBranch::BranchFromInt(2), MCFBuild::BuildFromInt(3), true);

#ifdef WIN32
		ASSERT_STREQ("mcfroot\\games\\1\\b2_m3_unauthed.mcf", strPath.c_str());
#else
		ASSERT_STREQ("mcfroot/games/1/b2_m3_unauthed.mcf", strPath.c_str());
#endif
	}
Пример #9
0
 virtual void vSave(unsigned int* pKey, unsigned int keynum, GPContents* c)
 {
     GPASSERT(NULL!=c);
     GPASSERT(keynum>0);
     for (int i=0; i<c->size(); ++i)
     {
         auto type = c->getType(i);
         std::string path = generatePath(pKey, keynum, type->name());
         GPPtr<GPWStream> writeStream = GPStreamFactory::NewWStream(path.c_str());
         type->vSave(c->get(i), writeStream.get());
     }
 }
void MainWindow::newproject()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),"/home",QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    projectPath = dir;
    if(projectPath != ""){
        for(int i = 0;i<3;i++){
            generatePath(i);
        }
        dm = new DotMatch(this, projectPath, ui->matchAssistant->isChecked());
        connect(dm,SIGNAL(receivedmanualmatch()),this,SLOT(finishmanualmatch()));
    }
}
Пример #11
0
 virtual GPContents* vLoad(unsigned int* pKey, unsigned int keynum)
 {
     GPASSERT(!pTypes.empty());
     GPContents* c = new GPContents;
     GPASSERT(keynum>0);
     for (int i=0; i<pTypes.size(); ++i)
     {
         std::string path = generatePath(pKey, keynum, pTypes[i]->name());
         GPPtr<GPStream> readStream = GPStreamFactory::NewStream(path.c_str());
         GPASSERT(NULL!=readStream.get());
         c->push(pTypes[i]->vLoad(readStream.get()), pTypes[i]);
     }
     return c;
 }
Пример #12
0
osg::ref_ptr<osg::AnimationPath> CVehicle::outputScene(const osg::ref_ptr<osg::Vec3Array>& junctionArray , double width, unsigned int num)
{
	osg::ref_ptr<osg::Vec3Array> driveway = new osg::Vec3Array;
	for (int i = 0; i != m_index.size(); i++ )
	{
		driveway->push_back((*junctionArray)[m_index[i]]);
	}

	m_loc = rand() % num ;
	double w = width / 2.0 + width * m_loc;
	generatePath(driveway,w);


	
	typedef osg::AnimationPath::ControlPoint ControlPoint;
	osg::Vec3 yoz(1.0, 0.0, 0.0), xoz(0.0, 1.0, 0.0), xoy(0.0, 0.0, 1.0);
	osg::ref_ptr<osg::AnimationPath> path = new osg::AnimationPath;




	double m = 0;

	for (int i = 0; i != m_index.size(); i++ )
	{
		if( i == 0)
		{
			path->insert( 0,
				ControlPoint((*driveway)[i],osg::Quat( 0.0,yoz,0.0,xoz, 0.0,xoy)) );
			
		}

		else
		{
			m += m_angleList[i-1];
				
			path->insert( (i-1) * m_speed + 0.1,
				ControlPoint((*driveway)[i-1],osg::Quat( 0.0,yoz,0.0,xoz,m,xoy)) );
			path->insert( i * m_speed , 
				ControlPoint((*driveway)[i],osg::Quat( 0.0,yoz,0.0,xoz,m,xoy)) );
		
		}

	}

	return path.release();

}
Пример #13
0
void Pathfinder::search()
{
	init();

	BinaryHeap openHeap;

	mStart->g = 0;
	mStart->h = manhattan(mStart, mGoal);
	mStart->opened = true;

	openHeap.push(mStart);

	while (openHeap.size() > 0)
	{
		// Pop the node with the smallest f value
		Node* currentNode = openHeap.pop();

		// Check if we hit the target
		if (currentNode == mGoal)
		{
			// Compute the path and exit
			generatePath(currentNode);
			return;
		}

		currentNode->closed = true;

		std::vector<Node*> neighbors = getNeighborsAdjacentTo(currentNode);
		for (int i = 0; i < neighbors.size(); i++)
		{
			Node* neighbor = neighbors[i];
			if (neighbor->closed || neighbor->worldRef->getMaterial()->isCollidable())
				continue;

			int gScore = currentNode->g + 1;

			if(!neighbor->opened || gScore < neighbor->g)
			{
				neighbor->g = currentNode->g + 1;
				neighbor->h = manhattan(currentNode, neighbor);
				neighbor->parent = currentNode;
				neighbor->opened = true;
				openHeap.push(neighbor);
			}
		}
	}
}
Пример #14
0
void Field::setPath(word character_offset, word target_coord_xw, word target_coord_yw, bool use_alternative)
{
	if (option->game_type != GAME_NANPA2) {
		return;
	}

	if (is_path_found) {
		is_path_found = false;
		return;
	}

	word character_coord_xw = data->queryWord(character_offset + CHARACTER_COORD_XW);
	word character_coord_yw = data->queryWord(character_offset + CHARACTER_COORD_YW);

	word start_offset = calculatePathOffset(character_coord_xw, character_coord_yw);
	word target_offset = calculatePathOffset(target_coord_xw, target_coord_yw);

	// initialize path
	initializePath(character_offset);

	if (data->queryByte(target_offset) != PATH_MARK_CLOSED) {
		data->writeByte(start_offset, PATH_MARK_CHARACTER);

		if ((generatePath(character_offset, target_coord_xw, target_coord_yw, PATH_MARK_INITIAL, PATH_SEQUENCE_DEFAULT) == false)) {
			data->writeByte(start_offset, PATH_MARK_CLOSED);
		}

//TODO: remove this
//DUMPPATH;

		if (data->queryByte(target_offset) < PATH_MARK_OPENED) {
			is_path_found = true;
			return;
		}
	}

	if (use_alternative) {
		//TODO: implement alternative pathfinding method
	}

	is_path_found = false;
	return;
}
Пример #15
0
QString TUrlRoute::findUrl(const QString &controller, const QString &action, const QStringList &params) const
{
    if (_routes.isEmpty()) {
        return QString();
    }

    for (const auto &rt : _routes) {
        const QByteArray ctrl = controller.toLower().toLatin1() + "controller";
        const QByteArray act = action.toLower().toLatin1();

        if (rt.controller == ctrl && rt.action == act) {
            if ((rt.paramNum == params.count() && !rt.hasVariableParams)
                || (rt.paramNum <= params.count() && rt.hasVariableParams)) {
                return generatePath(rt.componentList, params);
            }
        }
    }

    return QString();
}
Пример #16
0
bool Map::initialize(Game* gamePtr)
{
	char errorStr[200];

	Wall* curWall = NULL;


   if(!wallTexture.initialize(gamePtr->getGraphics(), "pictures\\wall4x36_grey.png")) {
      throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing wall texture"));
   }

   // initialize walls and make all visible
   for(int i = 0; i < 2; i++) {
      std::vector<Wall*>* walls;
      enum ORIENTATION orientation;
      if(i == 0) {
         walls = &horizontalWalls;
         orientation = HORIZONTAL;
      } else {
         walls = &verticalWalls;
         orientation = VERTICAL;
//         visible = false;
      }
      for(int x = 0; x < MAX_COLS+1; x++) { // +1 to include top/bottom and left/right wall
         for(int y = 0; y < MAX_ROWS+1; y++) {
//            visible = !visible;
            curWall = new Wall;

            if(!curWall->initialize(gamePtr, &wallTexture)) {
               sprintf_s(errorStr, "Error initializing wall i = %d, x = %d, y = %d", i, x, y);
               throw(GameError(gameErrorNS::FATAL_ERROR, errorStr));
               return false;
            }
            curWall->setCoord(GridVector(x,y), orientation);
            walls->push_back(curWall);
         }
      }
   }
   generatePath(GridVector(MAX_COLS/2,MAX_ROWS/2));
   /*
	curWall = firstWall;
	for(tempSize = size/2; tempSize > 0; tempSize--) {
		curWall->setCoord(rand() % MAX_COLS, rand() % MAX_ROWS, ROW);
		curWall = curWall->getNextWall();
	}
	for(tempSize = size/2; tempSize > 0; tempSize--) {
		curWall->setCoord(rand() % MAX_COLS, rand() % MAX_ROWS, COL);
		curWall = curWall->getNextWall();
	}
   */


/*	while(curWall) {
		curWall->setCoord(curX, curY, COL);
		curWall = curWall->getNextWall();
		curX += 1;
	}
	*/
	return true;

}
Пример #17
0
void SkScalerContext::internalGetPath(const SkGlyph& glyph, SkPath* fillPath,
                                  SkPath* devPath, SkMatrix* fillToDevMatrix) {
    SkPath  path;
    generatePath(glyph, &path);

    if (fRec.fFlags & SkScalerContext::kSubpixelPositioning_Flag) {
        SkFixed dx = glyph.getSubXFixed();
        SkFixed dy = glyph.getSubYFixed();
        if (dx | dy) {
            path.offset(SkFixedToScalar(dx), SkFixedToScalar(dy));
        }
    }

    if (fRec.fFrameWidth > 0 || fPathEffect != nullptr) {
        // need the path in user-space, with only the point-size applied
        // so that our stroking and effects will operate the same way they
        // would if the user had extracted the path themself, and then
        // called drawPath
        SkPath      localPath;
        SkMatrix    matrix, inverse;

        fRec.getMatrixFrom2x2(&matrix);
        if (!matrix.invert(&inverse)) {
            // assume fillPath and devPath are already empty.
            return;
        }
        path.transform(inverse, &localPath);
        // now localPath is only affected by the paint settings, and not the canvas matrix

        SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);

        if (fRec.fFrameWidth > 0) {
            rec.setStrokeStyle(fRec.fFrameWidth,
                               SkToBool(fRec.fFlags & kFrameAndFill_Flag));
            // glyphs are always closed contours, so cap type is ignored,
            // so we just pass something.
            rec.setStrokeParams((SkPaint::Cap)fRec.fStrokeCap,
                                (SkPaint::Join)fRec.fStrokeJoin,
                                fRec.fMiterLimit);
        }

        if (fPathEffect) {
            SkPath effectPath;
            if (fPathEffect->filterPath(&effectPath, localPath, &rec, nullptr)) {
                localPath.swap(effectPath);
            }
        }

        if (rec.needToApply()) {
            SkPath strokePath;
            if (rec.applyToPath(&strokePath, localPath)) {
                localPath.swap(strokePath);
            }
        }

        // now return stuff to the caller
        if (fillToDevMatrix) {
            *fillToDevMatrix = matrix;
        }
        if (devPath) {
            localPath.transform(matrix, devPath);
        }
        if (fillPath) {
            fillPath->swap(localPath);
        }
    } else {   // nothing tricky to do
        if (fillToDevMatrix) {
            fillToDevMatrix->reset();
        }
        if (devPath) {
            if (fillPath == nullptr) {
                devPath->swap(path);
            } else {
                *devPath = path;
            }
        }

        if (fillPath) {
            fillPath->swap(path);
        }
    }

    if (devPath) {
        devPath->updateBoundsCache();
    }
    if (fillPath) {
        fillPath->updateBoundsCache();
    }
}
bool CvSelectionGroupAI::AI_tradeRoutes()
{
	PROFILE_FUNC();

	const IDInfo kEurope(getOwnerINLINE(), CvTradeRoute::EUROPE_CITY_ID);

	CvCity* pPlotCity = plot()->getPlotCity();
	CvPlayerAI& kOwner = GET_PLAYER(getOwnerINLINE());
	std::set<int>::iterator it;

	std::map<IDInfo, int> cityValues;

	std::vector<CvTradeRoute*> routes;
	std::vector<int> routeValues;

	std::vector<bool> yieldsDelivered(NUM_YIELD_TYPES, false);
	std::vector<bool> yieldsToUnload(NUM_YIELD_TYPES, false);
	std::vector<int> yieldsOnBoard(NUM_YIELD_TYPES, false);

	if (!isHuman() || (getAutomateType() == AUTOMATE_TRANSPORT_FULL))
	{
		std::vector<CvTradeRoute*> aiRoutes;
		kOwner.getTradeRoutes(aiRoutes);
		for (uint i = 0; i < aiRoutes.size(); ++i)
		{
			CvTradeRoute* pRoute = aiRoutes[i];

			// transport feeder - start - Nightinggale
			CvCity* pDestinationCity = ::getCity(pRoute->getDestinationCity());
			if (pDestinationCity != NULL && pDestinationCity->isAutoImportStopped(pRoute->getYield()))
			{
				// ignore trade routes where destination is using feeder service and is full
				continue;
			}
			// transport feeder - end - Nightinggale

			// traderoute fix - start - Nightinggale
			if (isHuman() && pRoute->getDestinationCity().eOwner != getOwnerINLINE())
			{
				// humans can't transport to allied cities with fully automated transports
				continue;
			}
			// traderoute fix - end - Nightinggale

			CvCity* pSourceCity = ::getCity(pRoute->getSourceCity());
			CvArea* pSourceWaterArea = pSourceCity->waterArea();
			if ((pSourceCity != NULL) && ((getDomainType() != DOMAIN_SEA) || (pSourceWaterArea != NULL)))
			{
				int iSourceArea = (getDomainType() == DOMAIN_SEA) ? pSourceWaterArea->getID() : pSourceCity->getArea();
				if (getDomainType() == DOMAIN_SEA ? plot()->isAdjacentToArea(iSourceArea) : (iSourceArea == getArea()))
				{
					if ((getDomainType() == DOMAIN_SEA) || (pRoute->getDestinationCity() != kEurope))
					{
						routes.push_back(pRoute);
						routeValues.push_back(0);

						yieldsDelivered[pRoute->getYield()] = true;

						if (pPlotCity != NULL && ::getCity(pRoute->getDestinationCity()) == pPlotCity)
						{
							yieldsToUnload[pRoute->getYield()] = true;
						}


						cityValues[pRoute->getSourceCity()] = 0;
						cityValues[pRoute->getDestinationCity()] = 0;
					}
				}
			}
		}
	}
	else
	{
		for (it = m_aTradeRoutes.begin(); it != m_aTradeRoutes.end(); ++it)
		{
			CvTradeRoute* pRoute = kOwner.getTradeRoute(*it);
			CvCity* pSourceCity = ::getCity(pRoute->getSourceCity());
			if (pSourceCity != NULL)
			{
				CvArea* pSourceWaterArea = pSourceCity->waterArea();
				if (getDomainType() != DOMAIN_SEA || pSourceWaterArea != NULL)
				{
					int iSourceArea = (getDomainType() == DOMAIN_SEA) ? pSourceWaterArea->getID() : pSourceCity->getArea();
					if (getDomainType() == DOMAIN_SEA ? plot()->isAdjacentToArea(iSourceArea) : (iSourceArea == getArea()))
					{
						if ((getDomainType() == DOMAIN_SEA) || (pRoute->getDestinationCity() != kEurope))
						{
							routes.push_back(pRoute);
							routeValues.push_back(0);

							yieldsDelivered[pRoute->getYield()] = true;

							if (pPlotCity != NULL && ::getCity(pRoute->getDestinationCity()) == pPlotCity)
							{
								yieldsToUnload[pRoute->getYield()] = true;
							}


							cityValues[pRoute->getSourceCity()] = 0;
							cityValues[pRoute->getDestinationCity()] = 0;
						}
					}
					else
					{
						FAssertMsg(false, "Unexpected : Unit can't run trade route it's assigned to");
					}

				}
			}
		}


	}

	if ((pPlotCity != NULL) && hasCargo())
	{
		std::vector<CvUnit*> units;

		//Unload everything which we should unload here, or can't unload anywhere...
		CLLNode<IDInfo>* pUnitNode = plot()->headUnitNode();
		while (pUnitNode != NULL)
		{
			CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
			pUnitNode = plot()->nextUnitNode(pUnitNode);

			if (pLoopUnit != NULL)
			{
				YieldTypes eYield = pLoopUnit->getYield();
				CvUnit* pTransport = pLoopUnit->getTransportUnit();

				if ((eYield != NO_YIELD) && pTransport != NULL && (yieldsToUnload[eYield] || !(yieldsDelivered[eYield])))
				{
					if (pTransport->getGroup() == this && pLoopUnit->canUnload())
					{
						units.push_back(pLoopUnit);
					}
				}
			}
		}

		for (uint i = 0; i < units.size(); ++i)
		{
			units[i]->unload();
		}
	}

	short aiYieldsLoaded[NUM_YIELD_TYPES];
	AI_getYieldsLoaded(aiYieldsLoaded);

	bool bNoCargo = true;
	for (int i = 0; i < NUM_YIELD_TYPES; ++i)
	{
		if (aiYieldsLoaded[i] > 0)
		{
			bNoCargo = false;
			break;
		}
	}

	if (!bNoCargo)
	{
		//We need to iterate over every destination city and see if we can unload.
		for (uint i = 0; i < routes.size(); ++i)
		{
			CvCity* pDestinationCity = ::getCity(routes[i]->getDestinationCity());
			if ((pDestinationCity == NULL) || (pDestinationCity != pPlotCity))
			{
				int iRouteValue = kOwner.AI_transferYieldValue(routes[i]->getDestinationCity(), routes[i]->getYield(), aiYieldsLoaded[routes[i]->getYield()]);

				if (iRouteValue > 0)
				{
					cityValues[routes[i]->getDestinationCity()] += iRouteValue;
					routeValues[i] += iRouteValue;
				}
			}
		}
	}

	//We need to iterate over every source city, and see if there's anything which needs moving to the respective destination city.
	//We apply some bias to the city we are presently at, but not too much - sometimes empty runs need to be made...
	//Basically this looks at the entire NEXT trade run (source-city to dest-city), with some bias given towards
	//starting it from pPlotCity as sourceCity.
	//If we are carrying cargo, only count cities where we can unload.
	for (uint i = 0; i < routes.size(); ++i)
	{
		CvCity* pSourceCity = ::getCity(routes[i]->getSourceCity());

		if ((pSourceCity != NULL) && (bNoCargo || (cityValues[routes[i]->getSourceCity()] > 0)))
		{
			CvCity* pDestinationCity = ::getCity(routes[i]->getDestinationCity());
			YieldTypes eYield = routes[i]->getYield();

			// transport feeder - start - Nightinggale
			//int iAmount = pSourceCity->getYieldStored(eYield) - pSourceCity->getMaintainLevel(eYield);
			int iAmount = pSourceCity->getYieldStored(eYield) - pSourceCity->getAutoMaintainThreshold(eYield);
			// transport feeder - end - Nightinggale

			if (iAmount > 0)
			{

				int iExportValue = kOwner.AI_transferYieldValue(routes[i]->getSourceCity(), routes[i]->getYield(), -iAmount);
				int iImportValue = kOwner.AI_transferYieldValue(routes[i]->getDestinationCity(), routes[i]->getYield(), iAmount);
				int iRouteValue = (iExportValue + iImportValue + 2 * std::min(iExportValue, iImportValue)) / 4;

				if (pSourceCity == pPlotCity)
				{
					cityValues[routes[i]->getDestinationCity()] += 2 * iRouteValue;
				}
				else
				{
					cityValues[routes[i]->getSourceCity()] += iRouteValue;
				}

				routeValues[i] = iRouteValue;
			}
		}
	}

	IDInfo kBestDestination(NO_PLAYER, -1);
	int iBestDestinationValue = 0;

	for (std::map<IDInfo, int>::iterator it = cityValues.begin(); it != cityValues.end(); ++it)
	{
		int iValue = it->second;

		if (iValue > 0)
		{
			CvCity* pCity = ::getCity(it->first);
			if (pCity != NULL)
			{
				FAssert(!atPlot(pCity->plot()));
				if (generatePath(plot(), pCity->plot(), MOVE_NO_ENEMY_TERRITORY, true))
				{
					iValue /= 1 + kOwner.AI_plotTargetMissionAIs(pCity->plot(), MISSIONAI_TRANSPORT, this, 0);
				}
				else
				{
					iValue = 0;
				}
			}

			if (iValue > iBestDestinationValue)
			{
				iBestDestinationValue = iValue;
				kBestDestination = it->first;
			}
		}
	}


	if ((pPlotCity != NULL) && (kBestDestination.eOwner != NO_PLAYER))
	{
		//We need to keep looping and recalculating
		//For example a city might have "101" of an item, we want to move the first 100 but not the 1.
		//But it could also have 200, in which case we might want 2 loads of 100...
		//But it could also have 200 of two resources, and we'd want to move 100 of each...
		///TKs MEd
		int iTestCount = 0;
		while (!isFull())
		{
		    iTestCount++;
		    if (iTestCount == 1000)
		    {
		        FAssert(iTestCount == 0);
		        int iID = pPlotCity->getID();
		        int iIDplayer = GET_PLAYER(kBestDestination.eOwner).getID();
		       // break;
		    }

		    if (iTestCount == 1001)
		    {
		        break;
		    }
		    ///TKe
			int iBestRoute = -1;
			int iBestRouteValue = 0;
			//Now, for any trade routes which this group is assigned to, try to pick up cargo here.
			for (uint i = 0; i < routes.size(); ++i)
			{
				CvCity* pSourceCity = ::getCity(routes[i]->getSourceCity());
				if ((pSourceCity != NULL) && (routes[i]->getDestinationCity() == kBestDestination))
				{
					CvCity* pDestinationCity = ::getCity(routes[i]->getDestinationCity());
					YieldTypes eYield = routes[i]->getYield();

					if ((pPlotCity == pSourceCity))
					{
						// transport feeder - start - Nightinggale
						//int iAmount = pSourceCity->getYieldStored(eYield) - pSourceCity->getMaintainLevel(eYield);
						int iAmount = pSourceCity->getYieldStored(eYield) - pSourceCity->getAutoMaintainThreshold(eYield);
						// transport feeder - end - Nightinggale

						if (iAmount > 0)
						{
							int iExportValue = kOwner.AI_transferYieldValue(routes[i]->getSourceCity(), routes[i]->getYield(), -iAmount);
							int iImportValue = kOwner.AI_transferYieldValue(routes[i]->getDestinationCity(), routes[i]->getYield(), iAmount);
							int iRouteValue = (iExportValue + iImportValue + 2 * std::min(iExportValue, iImportValue)) / 4;

							if (iRouteValue > iBestRouteValue)
							{
								iBestRouteValue = iRouteValue;
								iBestRoute = i;
							}
						}
					}
				}
			}

			if (iBestRouteValue > 0)
			{
				CLLNode<IDInfo>* pUnitNode = headUnitNode();
				while (pUnitNode != NULL)
				{
					CvUnit* pLoopUnit = ::getUnit(pUnitNode->m_data);
					pUnitNode = nextUnitNode(pUnitNode);

					if (pLoopUnit != NULL)
					{
						if (pLoopUnit->canLoadYield(plot(), routes[iBestRoute]->getYield(), false))
						{
							pLoopUnit->loadYield(routes[iBestRoute]->getYield(), false);
							break;
						}
					}
				}
			}
			else
			{
				break;
			}
		}
		//XXX fill hold.
	}

	if ((kBestDestination.eOwner == NO_PLAYER) && hasCargo())
	{
		// Transport group is full and can't find any destination
		CvCity* pCity = kOwner.AI_findBestPort();
		if (pCity != NULL && !atPlot(pCity->plot()))
		{
			kBestDestination = pCity->getIDInfo();
		}
	}

	//As a final step, we could consider loading yields which would be useful as parts of delivery runs...
	if (kBestDestination != kEurope)
	{
		CvCity* pBestDestinationCity = ::getCity(kBestDestination);
		if (pBestDestinationCity != NULL)
		{
			FAssert(!atPlot(pBestDestinationCity->plot()));
			pushMission(MISSION_MOVE_TO, pBestDestinationCity->getX_INLINE(), pBestDestinationCity->getY_INLINE(), MOVE_NO_ENEMY_TERRITORY, false, false, MISSIONAI_TRANSPORT, pBestDestinationCity->plot());
			if (atPlot(pBestDestinationCity->plot()))
			{
				//Unload any goods if required (we can always pick them back up if this is an i+e city).
				std::vector<CvUnit*> units;

				CLLNode<IDInfo>* pUnitNode = plot()->headUnitNode();
				CvUnit* pLoopUnit;
				while (pUnitNode != NULL)
				{
					pLoopUnit = ::getUnit(pUnitNode->m_data);
					pUnitNode = plot()->nextUnitNode(pUnitNode);
					YieldTypes eYield = pLoopUnit->getYield();

					if ((eYield != NO_YIELD) && pLoopUnit->isCargo())
					{
						if (pLoopUnit->getTransportUnit()->getGroup() == this && pLoopUnit->canUnload())
						{
							units.push_back(pLoopUnit);
						}
					}
				}
				for (uint i = 0; i < units.size(); ++i)
				{
					units[i]->unload();
				}
			}

			return true;
		}
	}
	else
	{
		if (isHuman())
		{
			getHeadUnit()->AI_setUnitAIState(UNITAI_STATE_SAIL);
		}
	}

	return false;
}
Пример #19
0
void enemyMove() {
	//Calculate shortest path
	generatePath(spook.currentNode, skull.currentNode);
}
Пример #20
0
bool CPathFind::PathFind(int startx, int starty, int endx, int endy) {
    InitNode(startx,starty,endx,endy);
    //首先做几个预先判断
    if ((startx == endx) && (starty == endy)) {
        cout << "起点就是终点";
    }
    m_startx = startx;
    m_starty = starty;
    m_endx = endx;
    m_endy = endy;
    pNode node = CreateFirstNode(startx, starty);
    //将这个节点放入openlist
    m_openlist.push_back(node);
    //对这个地方进行排序
    push_heap(m_openlist.begin(),m_openlist.end(),NodeSort);
    pNode tmpnode = NULL;
    for(;;)
    {
        if(m_openlist.empty())
        {
            cout<<"错误:不能找到目标节点"<<endl;
            return false;
        }
        tmpnode = m_openlist.front();
        ++m_step;
        pop_heap(m_openlist.begin(),m_openlist.end(),NodeSort);
        m_openlist.pop_back();
        if (!CheckIsDestination(tmpnode))
        {
            //这里不是是目标地点
            for(int i = 0 ;i<8 ;i++)
            {
                int nextx ;
                int nexty ;
                GetShiftByDirectory(i,&nextx,&nexty);
                nextx = tmpnode->x + nextx;
                nexty = tmpnode->y + nexty;
                //判断这个点是可以通过的
                cout<<"next is"<<nextx<<":"<<nexty<<endl;
                if(isIllegle(nextx,nexty))
                {
                   //这里可以通过
                    //计算这个点的G值
                    int newGvalue;
                    if(i % 2 ==0)
                      newGvalue = tmpnode->G+10;
                    else
                      newGvalue = tmpnode->G+14;

                    vector<pNode>::iterator OpenIt;
                    //说明该节点在OPEN表中
                    for(OpenIt=m_openlist.begin();OpenIt<m_openlist.end();OpenIt++)
                    {
                        if (((*OpenIt)->x == nextx)&&((*OpenIt)->y ==nexty))
                        {
                             break;
                        }
                    }

                    if(OpenIt != m_openlist.end())
                    {
                       if ((*OpenIt)->G <= newGvalue)
                           continue;
                    }
                    //说明该节点在close表中
                    vector<pNode>::iterator CloseIt;

                    for(CloseIt=m_closelist.begin();CloseIt<m_closelist.end();CloseIt++)
                    {
                        if (((*CloseIt)->x == nextx)&&((*CloseIt)->y ==nexty))
                        {
                             break;
                        }
                    }

                    if(CloseIt != m_closelist.end())
                    {
                       if ((*CloseIt)->G <= newGvalue)
                           continue;
                    }

                    //如果都不满足上边的条件那么说明这个节点是最优节点
                    Node *bestNode = new Node;
                    bestNode->x = nextx;
                    bestNode->y = nexty;
                    bestNode->father = tmpnode;
                    bestNode->G = newGvalue;
                    bestNode->H = CalcG(nextx,nexty);
                    bestNode->F = bestNode->G + bestNode->H;

                    if (CloseIt != m_closelist.end())
                    {
                        delete(*CloseIt);
                        m_closelist.erase(CloseIt);
                    }

                    if (OpenIt != m_openlist.end())
                    {
                        delete(*OpenIt);
                        m_openlist.erase(OpenIt);
                        make_heap(m_openlist.begin(),m_openlist.end(),NodeSort);

                    }
                    m_openlist.push_back(bestNode);
                    push_heap(m_openlist.begin(),m_openlist.end(),NodeSort);
                    for(vector<pNode>::iterator k = m_openlist.begin() ;k<m_openlist.end();k++)
                    {
                        cout<<"x:"<<(*k)->x<<",y:"<<(*k)->y<<endl;


                    }
                    cout<<" isIlleglea is true"<<endl;
                }
                else
                {
                    cout<<" isIlleglea is false"<<endl;
                    //不能通过
                }


            }
            m_closelist.push_back(tmpnode);


        }
        else
        {
                generatePath();
                return true;
         }


    }


}