Sunday, May 19, 2013

Ray tracing using time to collision

Ray tracing tutorial

1 Motivation


Imagine a 2D grid world with obstacles and walls in the form of blocks. Imagine a robot with a laser sensor inside this world. I am given the position of the robot and the angle at which laser is emitted, I want to know the grid cell with which this laser collides and the exact position where it collides.

I had a look at Stage library, but I was not able to understand the code in world.cc properly. It cites a book called Graphics Gems IV to which I didn’t have access. So to understand the algorithm, I derived it from first principles, which you will see is not very difficult.

2 Notation


Let the size of grid cells be denoted by (Δx, Δy) and the unit vector along the ray be denoted by (dx,dy). The distance from the nearest grid walls in the direction of ray be denoted by (ex,ey). Assume that the ray is as given in Fig 1 and intersects consecutive grid lines at P1 and P2.


PIC
Figure 1: A ray intersecting with grid lines in a grid world

3 Derivation


For ray tracing we want to find all the grid cell from which the ray crosses. Since we can do it recursively, support we are at point P1 and want to find point P2. The first question to be answered is whether P2 lies on the Y-axes or X-axes. In the case of given diagram, P2 lies on the Y-axes, or we have taken one step along X-axes. However, if the slope was greater than 45 than the line would have crossed the gridline x = 0.5 earlier than y = 1.5. This can be easily detected by the sign of ey2.
ey2 = ey1 ex1 dy dx  (1)  (2)
We take a step along X-axes when ey2 > 0 or
ey1 ex1 dy dx>   0  (3) ey1 dy > ex1 dx  Assuming dy > 0  (4)
Now, we just need a recursive formula for ext and eyt. Let’s compute ex2 and ey2 for this case when we know that ey1 dy > ex1 dx .

ey2 = ey1 ex1 dy dx  (5) ey2 dy = ey1 dy ex1 dx  (6)
Aren’t we lucky that we got a formula of ey2 dy in terms of ey1 dy and ex1 dx ? Both the terms we already knew and needed to compute for comparison. Also note that ex2 dx is simply Δx dx .

Also doesn’t the fraction ex dx looks something meaningful? Note that ex dx is proportional to ex dxdt which is makes me think it in terms of distance to next gridline upon velocity. This term is nothing but time to collision to nearest gridline. Lets denote this terms as tx = ex dx. We can also think of Tx = Δx dx as maximum possible time to collision when travelling along X axes. Using this simpler notation our recursive formula are:

So the complete recursive formula can be written as:
txt+1,tyt+1 = Tx,tyt txt  if tyt > txt txt tyt,Ty   otherwise  (7)
Extension to 3D case is trivial:

txt+1,tyt+1,tzt+1 = Tx,tyt txt,tzt txt  if tyt > txt tzt > txt txt tyt,Ty,tzt tyt   if txt > tyt tzt > tyt txt tzt,tyt tzt,Tz   otherwise  (8)

4 Algorithm


------------------------------------------------------------------------------------------
   Data:  Initial point (x ,y ), Direction of ray (dx, dy), Cell size (Δx, Δy ), Collision
                         0  0
          checking function IsCellOccupied (i,j), Maximum   range r
   Result:  Collision cell (i,j) and position of collision (xc, yc)
   Let us assume  that grid lines are at integral multiples of cell size.;
   Initial cell (i,j ) ← (⌊ x0-⌋,⌊ y0⌋);
                        Δx    Δy
   Direction of movement  (Δi, Δj ) ← (sgn(dx ),sgn (dy));
   Initial error (ex,ey) ← ((i + Δi )Δx  − x0e, (j + Δj )Δy  − y0);
   Initial time  to collision (tx,ty) ← (edxx,dyy);
   Maximum    time  to collision (T ,T  ) ← (Δx-, Δy);
                              --x-r-y--    dx  dy
   Maximum    iterations n ←  ⌊min(Δx,Δy)⌋;
   while  n > 0 do
    |  n ←  n − 1;
    |  if t  < t then
    |   | x(i,j)y ←  (i + Δi,j);
    |   |
    |   | (tx,ty) ← (Tx,ty − tx);
    |  else
    |   | (i,j) ← (i,j + Δj );
    |   | (tx,ty) ← (tx − ty,Ty);
    |   --
    |  if|IsCellOccupied (i,j) then
    |   | (xc,yc) ← ((i + Δi)Δx  − txdx,(j + Δj )Δy −  tydy );
    |   --return  (i,j),(xc,yc)
------------------------------------------------------------------------------------------

Monday, August 1, 2011

First bookmarklet

Convert

Sunday, December 12, 2010

Add reminder on Unix terminal

   echo "DISPLAY=':0' zenity --warning --text 'Tea time'" | at 1756 March 11

You can also make it a bash function as I have done

>> remind () {
    echo "DISPLAY=':0' zenity --warning --text '$@'" | at $1
}

Usage:
>> remind 17:56 Tea Time

>> remind 17:56today Tea Time

>> remind 17:56tomorrow Tea Time

>> remind now+30min Take break

The time formats that "at" command accepts are
At allows fairly complex time specifications, extending the POSIX.2 standard. It accepts times of the form HH:MM to run a job at a spe‐ cific time of day. (If that time is already past, the next day is assumed.) You may also specify midnight, noon, or teatime (4pm) and you can have a time-of-day suffixed with AM or PM for running in the morning or the evening. You can also say what day the job will be run, by giving a date in the form month-name day with an optional year, or giving a date of the form MMDD[CC]YY, MM/DD/[CC]YY, DD.MM.[CC]YY or [CC]YY-MM-DD. The specification of a date must follow the specifica‐ tion of the time of day. You can also give times like now + count time-units, where the time-units can be minutes, hours, days, or weeks and you can tell at to run the job today by suffixing the time with today and to run the job tomorrow by suffixing the time with tomorrow. For example, to run a job at 4pm three days from now, you would do at 4pm + 3 days, to run a job at 10:00am on July 31, you would do at 10am Jul 31 and to run a job at 1am tomorrow, you would do at 1am tomorrow. The definition of the time specification can be found in /usr/share/doc/at/timespec.
What if you want to be reminded every weekday at 6:17 PM to go to gym? For that you can use crontab
> > echo "17 18 1-5 * * DISPLAY=':0' zenity --warning --text 'Tea time'" | crontab -
The first 5 space separated words provide when the script should run in the format "minute hour weekday day-of-month month", followed by the script to execute. Google crontab to learn more.

Tuesday, September 28, 2010

4 Perl concepts to scare off Beginners

Perl [5.8.6] is a relatively easier language to learn and program, but a tough one if you are trying to read someone's else code. The features in Perl programming language go well beyond, what a beginner is expected to know.

Typeglobs

Today, I just scared off a guy by throwing at him the concept of a typeglob. I conf'ess, that at the time of writing this blog, even I am not clear of the concept of typeglob's. But the point of the blog is to find concepts that Perl beginners don't care to learn about.
Typeglobs are Perl's internal datatype to hold entries in Symbol Tables. Better if you read it from perlmod.

Tie

Well, you can modify the behavior of a normal scalar, array, hash or file handle by using tie. Read more at perltie.

Closures

Not going into technical definition of closures, it's usage for generating iterators is interesting.

Here's a code to demonstrate the usage of closure for reading a tab separated file.

# Closure use case. Here $itr is our closure which will be used as an iterator.
# In Perl terminology, $itr is just a subroutine reference
my $itr = tabfile_itr($ARGV[0], "\t");
while (my $row = $itr->()) {
    # Let's say tabular file has three columns namely name, age and rank
    print "$row->{name} with age $row->{age} has a rank of $row->{rank}\n";
}

# Here's the closure factory. This function takes a file name and a separator
# and returns an iterator that gives a hash reference for each row.
sub tabfile_itr {
    my ($file, $seperator) = @_;
    # Open file
    open(my $fh, "<", $file) or die $!;
 
    # Get the header of file and split by separator
    my $hline = <$fh>;
    chomp $hline;
    my @headers = split $seperator, $hline;

    # Now this thing is called the closure
    my $closure =  sub {
        # The file handle "$fh" was lexically scoped but it will stay
        # statically scoped as long as the $closure is referenced
        my $line = <$fh>;
        chomp $line;
  
        # This is an important part, to break the recursion.
        return unless (defined $line);
  
        # Another lexically scoped variable used in this closure is
        # @headers. To understand each column in the file, we need to
        # have a record of @headers.
        my %col_hash;
        @col_hash{@headers} = split $seperator, $line;
        return \%col_hash;
    };
    return $closure;
}

Read more at perlfaq and perlsub. More closure as iterators examples at perl.com.

use vs require

This is an easy one. "use" runs in the BEGIN block and calls the import function of the package after "require"ing the package. Read more at perldoc -f use.

Tuesday, August 31, 2010

Sweet Python

My first impression of Python was language that was over-hyped. Now, that I have got to experience and feel it's power, I have begun to love it.

Why not semicolons, braces, dollars, at-the-rates and all the rubbish symbols that have been so long in other programming languages.
That's the first surprise you see, when you get to know Python. Well there may be many reasons like it keeps your fingers in the home row while typing or makes the code looks beautiful. My favorite reason is that it removes redundancy-why have a semicolon when you are going to have a new line anyway; why have pair of braces when you are going to indent and de-indent anyway. I have observed that it does reduces syntax errors, especially when you are away from your favorite on the fly syntax checking IDE.

What is module, function, class, method and object? they are simply types.

Wow! this is coolest feature of Python I have learned so far: Metaclasses. Everything you can see is a type, even in the language it self. And all the classes that we understand in the usual sense are just the predecessors of the type "object". Using these with setattr and getattr, you can generate any kind of code on the fly, even that one which in-turn generates code on the fly. Of course, don't do that because it do not generates a debugger on the fly.

Tuesday, January 5, 2010

LaTeX for formatting resume

I was looking for something that had macros for formatting my resume. LaTeX was the perfect answer to provide a consistent formatting. Here is my resume and it's tex and the original template page .


LaTeX
LaTeX is like typesetting system to produce standard printable documents like articles, books, reports and resumes.
As in HTML we just provide the content and external CSS files take care of formatting or display. On the same lines, in LaTeX we can provide the content and LaTeX styles or classes take care of the formatting and display.

If you want quick results, you can use an existing resume latex file and replace the contents. You can convert LaTeX to pdf by using online tools.

Getting Started:
http://www.latex-project.org/intro.html

Wiki book is quite helpfull:
en.wikibooks.org/wiki/LaTeX

Other recommended books:
  • A beginner's introduction to typesetting with LATEX
  • The Latex Companion

Thanks to the LaTeX resume templates (Top few google results for "latex resume"):
Use online LaTeX to PDF converter, in case you are not planning to install LaTeX.