r/dailyprogrammer • u/nint22 1 2 • Aug 08 '13
[08/08/13] Challenge #131 [Intermediate] Simple Ray-Casting
(Intermediate): Simple Ray-Casting
Ray Casting is a method of [rendering 3D computer graphics](http://en.wikipedia.org/wiki/Rendering_(computer_graphics)), popular in the early/mid 90's. Famous games like Wolfenstein and [Doom](http://en.wikipedia.org/wiki/Doom_(video_game)) are great examples of ray-casting based graphics. Real-time computer graphics today are based on hardware-accelerated polygon rasterization, while film-quality computer graphics are based on ray-tracing.
Your goal is to implement a single ray-cast query within a 2D world: you will be given the ray's origin and direction, as well as a top-down view of a tile-based world, and must return the position of the first wall you hit. The world will be made of a grid of tiles that are either occupied (as defined by the 'X' character), or empty (as defined by the space ' ' character). Check out these graphics as a visualization of example 1; it should help clarify the input data. Real ray-casting applications do many of these wall-collision hits, generally one per column of pixels you want to render, but today you only have to solve for a single ray!
Original author: /u/nint22
Formal Inputs & Outputs
Input Description
On standard console input you will be given two integers, N and M. N is the number of columns, while M is the number of rows. This will be followed by M rows of N-characters, which are either 'x' or ' ' (space), where 'x' is a wall that you can collide with or ' ' which is empty space. After this world-definition data, you will be given three space-delimited floating-point values: X, Y, and R. X and Y are world positions, following this coordinate system description, with R being a radian-value degree representing your ray direction (using the unit-circle definition where if R is zero, it points to the right, with positive R growth rotation counter-clockwise). R is essentially how much you rotate the ray from the default position of X+ in a counter-clockwise manner.
Output Description
Simply print the collision coordinate with three-digit precision.
Sample Inputs & Outputs
Sample Input
Note that this input is rendered and explained in more detail here.
10 10
xxxxxxxxxx
x x x x
x x x x
x x xxx
xxxx x
x x x
x x
x x x
x x xx
xxxxxxxxxx
6.5 6.5 1.571Sample Output
6.500 1.000
4
u/nint22 1 2 Aug 09 '13
My initial solution, without much testing, was posted here on Gist. The overall approach was to figure out which direction the growth of the ray is in, and to iterate over each of the closest collisions on tile-edges until we either hit the world's limit or walls.
The math all revolves around the slope-intercept form of a line, to quickly test for axis-aligned intersections. If you let Y = M*X + B, and pre-compute M and B with the original X and Y values, you can very quickly iterate through all tile-edge intersections by letting Y or X be a whole integer (which are where edges lie).
Though written in C++, it's essentially C-style code. Note the "df", or delta-fudge factor, is a terrible terrible approach to looking ahead. My only justification: I generally solve these challenges with the ACM-competition attitude, which is that quick-and-dirty wins every time.
As per usual, always feel free to discuss, criticize, and tear-apart.
5
u/tim25314 Aug 08 '13 edited Aug 09 '13
Python (not fully tested yet):
3
u/[deleted] Aug 08 '13
I'd like some extra test input to check for correctness, since my math is very messy.
Anyhow, here's my solution in python 2.7 32-bit:
I don't think it's optimal.
Mine has an extra feature, it shows the progress of the ray displaying a 'dungeon' every iteration.
The output looks like this
I hope it's correct :)
Also, instead of taking the width and height of the dungeon, my
Automatically generates the dungeon without those.
10
u/shangas Aug 09 '13 edited Aug 09 '13
Here's some input data for corner case tests
The above should collide at 3.000 1.000
The second one should collide at 2.000 2.000
Third one should collide at 1.000 3.000
Final one at 2.000 2.000
4
u/missblit Aug 08 '13 edited Aug 08 '13
edit #1: added 3 digit precision as specified in problem description
Edit #2: And here's some input to try that's slightly less trivial than the sample input:
3.2 3.1 2.35619449Answer should be
3.1 3Conceptually easy, but there are a bunch of gotchas when implementing it.
Perhaps I would have had a better time if I looked up the raycasting algorithm instead of relying on my memory of how line painting works...
I tested the 8 cardinal directions, I really should test some evil input but I've spent enough time on this as is.
C++
Output for sample:
6.5 14
u/shadowX015 Aug 08 '13 edited Aug 09 '13
Edit: Added the exact solution (in Java) and fixed some things, added formatting.
3
u/zengargoyle Aug 09 '13
A Perl programming language solution, not thoroughly tested (especially the part that trims down the matrix pre-searching).
Went wild and tested the line segment formed from the starting position and direction of travel against the 'walls' of a subset of the tiles of the grid.
Output is: 6.499 1.000 And: 3.100 3.000 for the second test someone provided.
3
u/shangas Aug 09 '13 edited Aug 10 '13
My Haskell solution:
This program calculates each point where the ray intersects with a grid-line and then determines the first intersection point that is adjacent to a wall to determine the point of collision. It avoids error accumulation in floating point operations by calculating each intersection point with a linear equation from the initial ray position instead of summing up step values.
This was actually a very interesting task! It seems simple at first, but there are several floating point pitfalls that need to be taken into account. E.g. which way to round at an intersection since the floating point presentation might a little bit over or a little bit under the integer value. I did a couple of revisions, but finally found a way to calculate all the values as closely as double precision allows without any "fudging".
3
u/robsonq Sep 20 '13
C++. Propably not cleanest and fastest solution and it give bad (?) output because angle given by author is simplified. Author meant 90 degress, when his input equals roughly 89.99~ if your program gives not exactly 6.500 its perfectly fine. If you give program exactly 90 degress as input (commented line in my main function) it's ok!
Any feedback highly appreciated!
2
u/ReginaldIII Aug 08 '13
Nice question, OP. About a year ago I wrote a Ray Cast game engine and made a Pacman clone in the first person, in the theme of the movie Aliens. Link
I'm working on about 1000 projects at the moment but seeing this makes me want to go back and work on the game again!
2
u/toodim Aug 09 '13
Python 3.3. Not super accurate but works ok to 2-3 decimal places.
2
u/h3ckf1r3 Aug 10 '13 edited Aug 10 '13
Here is my solution in ruby:
if someone knows of a better way to change the type of all of the values in an array other than mapping, I would love to hear it :).
After looking at other people's solutions, I can only assume that I overlooked something. but it's late so I'll have to worry about this in the morning.
2
u/bytbox Aug 11 '13
Go. I need to start checking this sub on the daily. Anyway, while this may work for the sample input(okay it's really close and all i would need to do is a math.Ceil) I have a bad feeling that it's one of those that works only for the input. Anyone who would like to test please do and let me know. Edit: forgot to say that it is run like "go run 134.go input.txt"
2
u/Blackllama79 Aug 12 '13 edited Aug 12 '13
Well, here we go. This is my attempt in java. Problems: At first it wasn't hitting the corner tests /u/shangas posted. After some testing, I concluded I wasn't incrementing by small enough values. I continued to shrink the values until I noticed a delay in speed of the program. It increments by the one-hundred-millionth of a sin/cos of the radian value.
What it comes down to is that if you give it a value too close to 45 degrees, it will go right through the corners. Ramping up the accuracy was my method of combating that. Silly as it is, I don't know how else to deal with it. If anyone knows how I could change it to fix that, I would love you forever if you told me.
I put a ton of comments in here, albeit the fact they make this post huge. Sorry!
Oops, just occurred to me that this will crash if the direction never hits a wall. I'm feeling kinda lazy so dunno if I'll fix this.
2
u/lukz 2 0 Aug 27 '13 edited Aug 28 '13
BASIC interpreter 1Z-016 running in an emulator.
Simplified version. Map is fixed to the one at problem description. As input you give the X, Y coordinates and the angle R, output is the collision point.
Sample output
1
u/in_rod_we_trust Aug 14 '13 edited Aug 14 '13
Hello all, first time submission on this subreddit. I implemented using python:
https://gist.github.com/NashS/6233283
It's rather verbose, but It worked with all the cases provided. Feedback would be appreciated.
0
u/[deleted] Aug 09 '13
[deleted] — view deleted comment