algorithm to use to find closest object on tile map - c#

I have a game map represented as a tile map. Currently there are two types of objects that are present on the map, relevant to this problem: gatherable resources (trees, rocks, etc.) and buildings built by the player. Buildings are also connected by roads.
I have a problem figuring out an efficient algorithm that could do the following:
find the closest resource to any relevant building (ie. find the closest tree to lumberjack/tree-gatherer)
find the closest relevant building to any building (ie. find the closest storage to any sawmill)
I separated those two issues because the first one does not need roads, but the second one is supposed to only use roads.
So, the result of this should be a single path to a single object, that is the closest to the one I'm figuring it out from. The path is then used by a worker to gather the resource and bring it back, or let's say, to pick a resource from a sawmill and bring it to the closest storage.
I know how to get the closest path itself (A*, Djikstra or even Floyd-Warshall), but I'm not sure how to optimally proceed with multiples of those and getting the best/closest one, especially if it's going to be run very regularly and the map object collections (roads and buildings) is expected to be changing regularly as well.
I'm doing this in Unity3D/c# but I guess this is not really Unity3D-related issue.
How should I proceed?

Finding the geographical distance between two objects is a cheap (quick) operation - you can afford to perform that many times per game tick. Use it if the option is available.
Finding the shortest path by making use of terrain features such as roads, tracks etc. is a much more complex operation. As you already mentioned in your post the A* search algorithm is probably your best option for it, but it is quite slow.
But generally, you should not need to run it too often - just compute the path every X seconds (for some value of X), and make your worker spend the next few game ticks following this computed path, until you "refresh" it. The more precision you have, and more responsiveness to changes to the game environment (e.g. obstacles appearing in your path), the more CPU time you will use.
Try different amounts of precision, and find one that gives decent precision while not being too expensive in terms of CPU time. (The update interval depends purely on the number of calls you are expected to make. Calculating paths for 100 workers is obviously much harder than for 1.)

Related

How can I reduce the optimality gap of the routing model's assignment by allow more time to search?

I am solving a pick and delivery problem. I was testing OR-Tools to know how good it is by the following example:
1. Two vehicles at same start, two pickup locations (one for each customer) that are actually the same point in terms of geolocation, two customers having the same geolocation too.
2. No demand or capacity, just a time dimension between points and constraints to satisfy pickup and delivery.
3. The objective is to reduce the global span of the cumulative time
It's obvious that the optimal solution will use both vehicles, but it doesn't! I tried a lot of settings to make it escape from a local optima, but it still doesn't and doesn't even try to use the time at hand to reach a better solution and just finishes in a couple of seconds.
So, how can I force it to continue search even if it thinks that the solution at hand is enough?
BTW: I checked if my logic is correct by giving it the optimal route as an initial route, and when I do that, it uses it. It also, indicated that the objective value of the optimal route is less than the original route, so I guess there are no bugs in the code.

Splitting up A* pathing of many units into seperate game frames

So my issues is that, for large groups of units, attempting to pathfind for all of them in the same frame is causing a pretty noticeable slow down. When pathing for 1 or 2 units the slow down is generally not noticeable but for many more than that, depending on the complexity of the path, it can get very slow.
While my A* could probably afford a bit of a tune up, I also know that another way to speed up the pathing is to just divy up the pathfinding over multiple game frames. Whats a good method to accomplish this?
I apologize if this is an obvious or easily searched question, I couldn't really think of how to put it into a searchable string of words.
More info: This is A* on a rectilinear grid, and programmed using C# and the XNA framework. I plan on having potentially up to 50-75 units in need of pathing.
Thanks.
Scalability
There's several ways of optimizing for this situation. For one, you may not have to split up into multiple game frames. To some extent it seems scalability is the issue. 100 units is at least 100 times more expensive than 1 unit.
So, how can we make pathing more optimized for scalability? Well, that does depend on your game design. I'm going to (perhaps wrongly) assume a typical RTS scenario. Several groups of units, with each group being relatively close in proximity. The pathing solution for many units in close proximity will be rather similar. The units could request pathing from some kind of pathing solver. This pathing solver could keep a table of recent pathing requests and their solutions and avoid calculating the same output from the same input multiple times. This is called memoization.
Another addition to this could involve making a hierarchy out of your grid or graph. Solve on the simpler graph first, then switch to a more detailed graph. Multiple units could use the same low-resolution path, taking advantage of memoization, but each calculate their own high-resolution path individually if the high-resolution paths are too numerous to reasonably memoize.
Multi-Frame Calculations
As for trying to split the calculations among frames, there are a few approaches I can think of off hand.
If you want to take the multi-threaded route, you could use a worker-thread-pooling model. Each time a unit requests a path, it is queued for a solution. When a worker-thread is free, it is assigned a task to solve. When the thread solves the task, you could either have a callback to inform the unit or you could have the unit query if the task is complete in some manner, most likely queried each frame.
If there are no dynamic obstacles or they are handled separately, you can have a constant state that the path solver uses. If not, then there will be a non-negligible amount of complexity and perhaps even overheard with having these threads lock mutable game state information. Paths could be rendered invalid from one frame to the next and require re-validation each frame. Multi-threading may end up being a pointless extra-overhead where, due to locking and synchronization, threads rarely run parallel. It's just a possibility.
Alternatively, you could design your path finding algorithms to run in discrete steps. After n number of steps, check the amount of time elapsed since the start of the algorithm. If it exceeds a certain amount of time, the pathing algorithm saves its progress and returns. The calling code could then check if the algorithm completed or not. On the next frame, resume the pathing algorithm from where it was. Repeat until solved.
Even with the single-threaded, voluntary approach to solving paths, if changes in game state affect the validity of a paths from frame to frame, you're going to run into having to re-validate current solutions on a frame to frame basis.
Use Partial Solutions
With either of the above approaches, you could run into the issue of units commanded to go somewhere idling for multiple frames before having a complete pathing solution. This may be acceptable and practically undetectable under typical circumstances. If it isn't, you could attempt to use the incomplete solution as is. If each incomplete solution differs too greatly, units will behave rather indecisively however. In practice, this "indecisiveness" may also not happen often enough to cause concern.
If your units are all pathing to the same destination, this answer may be applicable, otherwise, it'll just be food for thought.
I use a breadth-first distance algorithm to path units. Start at your destination and mark the distance from it as 0. Any adjacent cells are 1, cells adjacent to those are 2, etc. Do not path through obstacles, and path the entire board. Usually O(A) time complexity where A is the boards area.
Then, whenever you want to determine which direction a unit needs to go, you simply find the square with the minimal distance to the destination. O(1) time complexity.
I'll use this pathing algorithm for tower defense games quite often because its time complexity is entirely dependent on the size of the board (usually fairly small in TD games) rather than the number of units (usually fairly large). It allows the player to define their own path (a nice feature), and I only need to run it once a round because of the nature of the game.

Wireless GPS Positioning

I have a database of wireless access points and multiple readings (1-n) of signal strength (RSSI) for each access point. Along with this I record the GPS coordinates of each reading.
Now, what I want to do is given visible access points compute my approx. GPS position but I'm not sure how to go about doing this. I've read that I possibly need trilateration however I'm not maths savvy and a lot of articles on this seem to be that way inclined, can someone break it down for my simple mind with code examples (psuedo or otherwise)?
Many of these pages also talk about distance and I'm unsure how best to compute that. One thought is to infer it from the RSSI. Assuming I have at least two readings for a given access point at decreasing RSSI I should be able to roughly infer distance from that just by computing the distance between the GPS coords? I'm making the assumption the lowest RSSI is the nearest to the actual device and not taking into account signal propagation or anything like that.
Any thoughts, points and links would be most appreciated.
I believe you'll need at least four readings from reasonably separated locations for an access point to get a rough idea of where it is, however this only works even vaguely accurately in a vacuum :) Buildings, trees, and other interference will naturally skew the results, often quite dramatically. More readings in that case would improve the accuracy.
The theory is that at each point in space exists within a shell of radius r from the given access point. Theoretically, the signal strength drops off with the inverse square of the distance r, so you need to take that into account as well.
So say you measure a signal strength at some location - you know that the square root of one over the signal strength is proportional to the distance from you to the access point - but that access point could exist anywhere on the surface of the sphere with that radius from you.
A second reading at a different location produces a second sphere which should intersect with the first - however think about two overlapping beach balls and you'll see that the intersection is a circle, anywhere along which the AP could be located. The third reading will intersect with the circle from the first two at two places so now you have two target points where the access point could be located. The fourth and final reading will tell you which of these two it is.
Again, this is all assuming an ideal situation - far from likely in the real world. You'd need to apply ranges, statistical methods, and a lot more than 4 readings etc to get a good guess as to the location of the AP.
Also, the method used above to conceptualize the method to find the AP may not be the best way to actually do this in practice. You'd also need to ensure the user who is trying to locate the AP walks around a bit to get some decent readings.
Other things to consider: where the readings are taken from matters. If you just walk in a straight line or on a flat surface you'll most likely not be able to determine if the AP is to the left or right of the line or below or above you. Your walk must include some movement in all three dimensions. Also, you'll probably want a smattering of trig and Pythagoras to do the actual translation calcs :)
Anyway, I'd love to have an iPhone app that finds APs and puts them on google maps for me so I can figure out where they are and who they belong to... it'd be awesome. But yeah, I haven't tried any of the above, it just seems to me to be the way it would work. I'm happy to be corrected if this turns out to be inaccurate :D

Public Transportation using Buses in City

I am developing a Journey Planner website. There are few things that are simple in this case currently i.e. Right now the website will only be able to plan bus routes, the timings of buses are not currently available. So this means we only have bus routes stored in the db and since bus timings are not available so waiting times for traveler are not relevant as well. What is available is the time and distance covered between two stops for an individual bus.
I think that using an undirected weighted graph storing the time and distance costs of each bus stop for each individual bus would be the way to go. Then I could use Dijkstra algorithm to calculate the shortest path between two locations entered by the user based on either time or distance as per user preference. I would find out whether two or three buses are required through simple C# functions if the bus routes intersect at stops and then using those intersection stops for the traveler to change the bus. But there would be an individual graph for each bus. An alternative (not sure if this is correct) way would be to use a graph containing every bus stop of city as nodes and then using this technique to find out the way to travel between two stops. Which is the correct approach? Should I use A* algorithm in place of Dijkstra algo?
A few general points for the design: I would like the app to be extensible so I could add other transportation means later when the need arises. Moreover the bus times could also be added later if possible without major changes to the website. I have seen quite a few experts here who have worked on much complex projects of transportation. So please help me out with the best way to implement this functionality in the most scalable, modular and extensible fashion.
A graph is going to have to be a directional graph - bus stops on opposite sides of the roads (even in a country like the UK that rarely has medians) are NOT the same stop!
I started a similar application last summer and never finished it, but I do have some advice on this graph, and how to structure your data.
My plan was to have each stop as a node, and a path between each of these nodes for every time a bus went through. For example, if a bus stopped every half hour over a 6 hour period, then there would be 12 paths between the two nodes. Time was the main driver behind "cost" of the path, so typically the soonest path would be the one chosen.
Before starting the application would query the database for all paths in the next 5 hours (adjust as appropriate). It would then crunch with Dijkstra's algorithm.
Other things to factor in cost are the actual money cost of the route, transfers (and their cost), stops with no roofs (if you tend to have bad weather), etc.
This plan worked well for me. I live in an area with 3 bus systems.
Finally, it may do you some good to structure your data in a similar way to the Google Transit Feed Specification, as many agencies produce this type of data that you could import.
I think the most important optimization is separating stations where you can change routes and stations where you can't. Then you just need to consider stations where you can change route as intermediate stations in your graph. This should make the graph so small that Dijkstra is fine.
I'm distinguishing nodes with only two edges by simply cutting them out of the graph and instead connecting their two neighbors with an edge of the added length. Then I do pathfinding on this reduced graph which should be much faster. i.e. only consider stations where one might switch routes.
Maybe you can have some use of paddydubs work for TransportDublin found on github.
I coded such an algorithm for a test application. I had a dictionary for each stop, as source and as destination. The algorithm was recursive. Each step of the recursion was like this: Given source and target, it would generate a list of routes going into target, list of routes leaving source. If there were any common stops, we were done, we report the route. If not, then I generate neighboring stops for source, and recurse. The next recursion generates list of neighboring stops for sink, recurse. Before recursion I recorded the previous path of course, and at the end I would have a list.
I do remember I had to place some cutoff conditions because the recursion would sometimes get stuck in certain "bad" regions.
I also looked at this paper:
www.citeulike.org/user/rchauhan/article/819528
I am interested if you managed to solve this problem in a different way.

factory floor simulation

I would like to create a simulation of a factory floor, and I am looking for ideas on how to do this. My thoughts so far are:
• A factory is a made up of a bunch of processes, some of these processes are in series and some are in parallel. Each process would communicate with it's upstream and downstream and parallel neighbors to let them know of it’s through put
• Each process would it's own basic attributes like maximum throughput, cost of maintenance as a result of through put
Obviously I have not fully thought this out, but I was hoping somebody might be able to give me a few ideas or perhaps a link to an on line resource
update:
This project is only for my own entertainment, and perhaps learn a little bit alnong the way. I am not employed as a programmer, programming is just a hobby for me. I have decided to write it in C#.
Simulating an entire factory accurately is a big job.
Firstly you need to figure out: why are you making the simulation? Who is it for? What value will it give them? What parts of the simulation are interesting? How accurate does it need to be? What parts of the process don't need to be simulated accurately?
To figure out the answers to these questions, you will need to talk to whoever it is that wants the simulation written.
Once you have figured out what to simulate, then you need to figure out how to simulate it. You need some models and some parameters for those models. You can maybe get some actual figures from real production and try to derive models from the figures. The models could be a simple linear relationship between an input and an output, a more complex relationship, and perhaps even a stochastic (random) effect. If you don't have access to real data, then you'll have to make guesses in your model, but this will never be as good so try to get real data wherever possible.
You might also want to consider to probabilities of components breaking down, and what affect that might have. What about the workers going on strike? Unavailability of raw materials? Wear and tear on the machinery causing progressively lower output over time? Again you might not want to consider these details, it depends on what the customer wants.
If your simulation involves random events, you might want to run it many times and get an average outcome, for example using a Monte Carlo simulation.
To give a better answer, we need to know more about what you need to simulate and what you want to achieve.
Since your customer is yourself, you'll need to decide the answer to all of the questions that Mark Byers asked. However, I'll give you some suggestions and hopefully they'll give you a start.
Let's assume your factory takes a few different parts and assembles them into just one finished product. A flowchart of the assembly process might look like this:
Factory Flowchart http://img62.imageshack.us/img62/863/factoryflowchart.jpg
For the first diamond, where widgets A and B are assembled, assume it takes on average 30 seconds to complete this step. We'll assume the actual time it takes the two widgets to be assembled is distributed normally, with mean 30 s and variance 5 s. For the second diamond, assume it also takes on average 30 seconds, but most of the time it doesn't take nearly that long, and other times it takes a lot longer. This is well approximated by an exponential distribution, with 30 s as the rate parameter, often represented in equations by a lambda.
For the first process, compute the time to assemble widgets A and B as:
timeA = randn(mean, sqrt(variance)); // Assuming C# has a function for a normally
// distributed random number with mean and
// sigma as inputs
For the second process, compute the time to add widget C to the assembly as:
timeB = rand()/lambda; // Assuming C# has a function for a uniformly distributed
// random number
Now your total assembly time for each iGadget will be timeA + timeB + waitingTime. At each assembly point, store a queue of widgets waiting to be assembled. If the second assembly point is a bottleneck, it's queue will fill up. You can enforce a maximum size for its queue, and hold things further up stream when that max size is reached. If an item is in a queue, it's assembly time is increased by all of the iGadgets ahead of it in the assembly line. I'll leave it up to you to figure out how to code that up, and you can run lots of trials to see what the total assembly time will be, on average. What does the resultant distribution look like?
Ways to "spice this up":
Require 3 B widgets for every A widget. Play around with inventory. Replenish inventory at random intervals.
Add a quality assurance check (exponential distribution is good to use here), and reject some of the finished iGadgets. I suggest using a low rejection rate.
Try using different probability distributions than those I've suggested. See how they affect your simulation. Always try to figure out how the input parameters to the probability distributions would map into real world values.
You can do a lot with this simple simulation. The next step would be to generalize your code so that you can have an arbitrary number of widgets and assembly steps. This is not quite so easy. There is an entire field of applied math called operations research that is dedicated to this type of simulation and analysis.
What you're describing is a classical problem addressed by discrete event simulation. A variety of both general purpose and special purpose simulation languages have been developed to model these kinds of problems. While I wouldn't recommend programming anything from scratch for a "real" problem, it may be a good exercise to write your own code for a small queueing problem so you can understand event scheduling, random number generation, keeping track of calendars, etc. Once you've done that, a general purpose simulation language will do all that stuff for you so you can concentrate on the big picture.
A good reference is Law & Kelton. ARENA is a standard package. It is widely used and, IMHO, is very comprehensive for these kind of simulations. The ARENA book is also a decent book on simulation and it comes with the software that can be applied to small problems. To model bigger problems, you'll need to get a license. You should be able to download a trial version of ARENA here.
It maybe more then what you are looking for but visual components is a good industrial simulation tool.
To be clear I do not work for them nor does the company I work for currently use them, but we have looked at them.
Automod is the way to go.
http://www.appliedmaterials.com/products/automod_2.html
There is a lot to learn, and it won't be cheap.
ASI's Automod has been in the factory simulation business for about 30 years. It is now owned by Applied Materials. The big players who work with material handling in a warehouse use Automod because it is the proven leader.

Categories

Resources