Closed Thread
Page 1 of 2 1 2 LastLast
Results 1 to 10 of 19

Thread: new fast ray tracing algorithm

  1. #1
    Junior Member
    Join Date
    Oct 2004
    Location
    Moscow
    Age
    27
    Posts
    3

    Name
    Alex Kossiakov
    Forum Username
    krio

    Russian Federation

    Default new fast ray tracing algorithm

    If You are interested in using this algorithm, with purposes please contact me
    via this e-mail: sinnlabs@list.ru
    Full documentation is here.
    I am not hosting it anywhere because mirrors could easily be brought down by someone not willing this to pass to the public.
    It also can't fit in the attachments.

    Tracing the rays for fun and profit:
    The ways of spherical ray tracing
    by
    (--Sinn-Labs--)



    -----------------------------------------------------------------------------------------------------------------------------------------------
    Intro:
    -----------------------------------------------------------------------------------------------------------------------------------------------
    Authors:
    Alex "krio" V. Kossiakov, student of Moscow State University, Faculty of Computational Mathematics and Cybernetics
    -----------------------------------------------------------------------------------------------------------------------------------------------
    Copyrights:
    © Alex V. Kossiakov, all rights reserved. If you read this document, then everything is copyrighted and protected by law. You may freely distribute this document only without any modifications. The original document in russian which was copyrighted MUST be distributed within this document, attached after the "[EOF]" marker. The attached document contains main concept of the algorithm so you can't use it or it's minor parts in commercial ways without my permission.
    -----------------------------------------------------------------------------------------------------------------------------------------------
    About Sinn Labs:
    Born in depth of Moscow school 1134, migrated to Moscow State University. With this document we are hoping to get some money resources for our next topic (which might blow you away). That's why we had to copyright this "technology".
    -----------------------------------------------------------------------------------------------------------------------------------------------
    About the topic:
    Ray tracing was a very expensive technology in computer graphics scene. In fact everybody thought it is not matching with traditional graphics pipeline. But it all was in past. And this document should explain why.
    -----------------------------------------------------------------------------------------------------------------------------------------------
    Special thanks:
    Kevin R. Harris for his opengl samples (www.codesampler.com)
    -----------------------------------------------------------------------------------------------------------------------------------------------

    Lets go!

    The spherical coordinates is a representation of 3d out of 3 parameters: two angles - alpha, beta and the distance r to the point. Well, nothing really new, because we all remember how to generate a sphere:
    x = r * cos(b) * cos(a)
    y = r * cos(b) * sin(a)
    z = r * sin(b)


    What if we will take alpha and beta to be equal our x*psi and y*phi on the screen??
    Yes! lines will still be lines, so triangles will still be triangles!!
    What does this mean? This means that we can forget about the distances for a while. Looks like a spherical projection. And we are just taking the part of that sphere as an our screen and the eye's location in the 0. Notice that we'll get a prospectively-correct image. But. For each frame we'll have to calculate millions of arctangents to know what alpha and what beta each vertex has. No problem. Let’s just use the standard algorithm to get a prospectively-nice image - instead of arctangents we'll just divide x and y by r (let’s call it ortho projection).

    Well, ok. But lets look how a plane looks like in spherical coordinates:
    Ax + By + Cz + D = 0
    means
    r * (A * cos(b) * cos(a) + B * cos(b) * sin(a) + C * sin(b)) + D = 0
    r * k + D = 0
    r = - D/k

    Good, but we must calculate lots of sin and cos, that will take a lot of time... If alpha and beta depend on screen's x and y, then we can just precalculate them and put in an array of lets say 640x480x3 elements: cos(b)*cos(a) ; cos(b)*sin(a) ; sin(b). And how should we calculate A,B,C and D? We have lets say all three vertexes of triangle M1(x1,y1,z1), M2(x2,y2,z2), M3(x3,y3,z3):
    A = y1 (z2 - z3) + y2 (z3 - z1) + y3(z1 - z2) B = z1 (x2 - x3) + z2 (x3 - x1) + z3(x1 - x2)
    C = x1 (y2 - y3) + x2 (y3 - y1) + x3(y1 - y2) - D = x1(y2 z3 - y3 z2) + x2 (y3 z1 - y1 z3) + x3 (y1 z2 - y2 z1)

    Looks like we can calculate the distance from an eye to any pixel on any triangle fast enough. Now, how do we use this all? How do we draw our scene?
    Well, personally I was shocked when realized that classical ray tracing is brute forcing all the pixels on the screen and at every pixel we search for triangles which we intersect with that ray and then looking which triangle is first on the distance. What else can we do instead this brute force?? Lets try it that way:

    Per frame before rendering: for each triangle to calculate all the needed above data AND where actually that triangle should be rendered on the screen: for each y that is in the bounding box of that triangle we precalculate xmin and xmax where the y is intersecting our triangle. Just a basic rasterization!!
    When rendering: for each triangle; for y that is in bounding box; for x that is from xmin to xmax DO: check if that pixel is in the screen; check if in the depth buffer for that x and y the ID of the triangle is the ID of our triangle, if so - we have intersection and can do our per pixel calculations.

    That is all for primary rays.. What's up with the secondary? We can do just exactly the same, but at first we only have to recalculate the spherical coordinates with a zero at the point where the second ray comes from. Oh, and normals are calculated with ortho projecting {A,B,C} vector. And reflection angle is just simple linear combination of the primary ray's angle and normal's angle. Just realize a line coming through this two 2d angles - what we need is a third point on that line which is as far away from the normal's as ray's from the normal's and is located in one of two ways:
    ray's - normal's - reflection's angles; or: reflection's - normal's - ray's angles. Refraction is calculated some similar way. Just draw a 2d projection of angles into dots on a paper and see it by your self.

    What’s up with spheres? Nothing really. Only the fact that we should calculate the r in a such way: -r^2 = alpha^2 + betta^2 - sphere_radius^2. Normals should be represented in angles and calculated with ortho projection, gladly we can convert our spherical coordinates to standard ones in a few multiplies. Reflections and refracts are calculated in similar to triangles way from this point.

    How to code it on gpu? There are actually number of ways. I'm not sure yet which one is the best.
    And now just realize how fast it will work if Nvidia/Ati will use it directly in the rasterization process to pass the data (pixel's distance or 3d location) to pixel shaders... But before it happens you may try to pass that data in a texture or three, depending on what depth quality you are aiming at. There are lots of other things for them to think about, and it's their job.

    This stuff works really faster than the traditional ray tracing. I did do a lot of test-coding, got amazing results, but we are not distributing inner sources just because I’m not the best coder around and I had a very tight time limit.

    ------------------------------------------------------------------------------------------------------------------------------------------------
    Outro:
    Everything what is imaginable IS possible.
    ------------------------------------------------------------------------------------------------------------------------------------------------
    [EOF]
    [ATTACHED ORIGINAL COPYRIGHTED DOCUMENT]
    Сферический ray-tracing.

    Стандартный алгоритм ray-tracing, или метод трассировки лучей, был предложен Артуром Аппелем (Arthur Appel) еще в 1968 году и дополнен алгоритмом общей рекурсии, разработанным Whitted в 1980 году.
    В основном он сводится к необходимости для каждого пикселя на экране в декартовой системе координат провести луч и искать пересечения с плоскостями треугольников, затем для каждого пересечения смотреть, попадает ли луч в треугольник. Первое попадание по лучу, заданного параметрически, и есть тот пиксель, цвет которого дальше надо считать.
    Прочие вариации этого алгоритма аналогично сложны по вычислениям.

    Используемые так же, пиксельные Shader'ы достаточно быстры и все последние видеокарты приспособлены именно под них. Но невозможно осуществить нормальный доступ из шейдера к прочей геометрии сцены. Для стандартных треугольников метод применим, но не для непрямолинейной геометрии - сфер и т.п.
    Визуальное качество применения пиксельных шейдеров не может сравниться даже с традиционным ray-tracing'ом.


    Суть предлагаемого сферического ray-tracing'a:
    Для каждого примитива считаются нужные сферические координаты раз в кадр. Что можно делать как стандартным способом перспективного преобразования для обычных декартовых систем координат, так и через формулы преобразования декартовых координат в сферические. Во втором случае мы получим перспективно-правильную проекцию.
    В итоге мы получаем линейную зависимость угловых составляющих сферических координат на плоскости от координат на нашем экране. Здесь не приводится доказательств того, что при такой аналогии сохраняются все возможные свойства, потому что способов доказательства очень много, это не входит в рамки данного текста и, к тому же, это проверено экспериментально.
    Затем осуществляется стандартная растеризация, например scan-line алгоритм, но в угловой составляющей сферических координат. После этого мы можем перебрать в цикле каждый примитив и трассировать только лучи, попадающие в эти примитивы: перебираем каждую строчку от минимальной до максимальной, а в каждой строчке перебираем от просчитанного ранее минимального столбца до максимального.
    Для каждого такого попадания просчитывается дистанция и сравнивается с буфером глубины.
    После этого попадание считается действительным и происходит расчет текстурных координат, вторичных и прочих лучей и других свойств, для вычисления цвета этого пикселя.
    Таким образом, мы почти полностью избавляемся от присущего ray-tracing'у метода грубой силы, сохраняя все его возможности, и внося еще множество разных оптимизаций.

    Основные отличия нового алгоритма, которые могут применяться по отдельности в реализации ray-tracing'a:
    1. использование сферических координат для трассировки первичного луча.
    2. использование сферических координат для трассировки вторичных лучей и всех остальных лучей.
    3. предварительный просчет принадлежности пикселей рабочей плоскости к примитивам (предварительная растеризация) через переход на рабочую плоскость, либо из сферических координат либо из декартовых.
    4. использование предварительной растеризации для по-примитивной трассировки.
    5. просчитывание углов лучей отражения и преломления линейной комбинацией двумерных углов предыдущего луча и нормали.
    6. предварительная растеризация примитивов в координатах вторичных и прочих лучей для их трассировки.
    Многие эти особенности могут быть реализованы, или уже реализованы в других, не ray-tracing`овых, методах отображения. Например можно использовать сферические координаты в реализации стандартных shader`ов.

    Основные отличия нового алгоритма позволяют:
    1. не высчитывать лучи параметрически.
    2. использовать угловые составляющие сферических координат как координаты пикселя на экране.
    3. в следствии применять к ray-tracing стандартные алгоритмы растеризации и буферизации.
    4. в следствии трассировать не каждый пиксель на экране, а лишь пиксели, попадающие в треугольник или другой приметив.
    5. в итоге - рисовать, перебирая в цикле все примитиве на сцене, пикселями, попадающими в примитивы, и при этом знать о каждом пикселе в примитиве его реальные координаты.
    6. на каждый пиксель на экране применять только те вычисления, которые требуются для вычисления его вторичных лучей, текстурных координат и т.п. Все остальные вычисления можно производить раз в кадр для каждого примитива в рамках его растеризации, если свойства растеризации изменились относительно предыдущего кадра.
    7. вторичные лучи, shadow rays и т.п. так же просчитывать в сферических координатах.
    8. осуществлять преобразования не переходя из сферических в декартовы координаты и обратно.


    Аннотация.
    Данный алгоритм является крупным шагом к рендерингу в реальном времени с высоким качеством изображения. На CPU можно получить существенное ускорения работы ray-tracing'a.
    Если этот метод возможно будет реализовать на GPU, то можно будет достичь очень хороших результатов, но для этого может потребоваться реорганизация pipeline'a.
    [END OF ATTACHED DOCUMENT, EVERYTHING ABOVE THIS LINE IN THE ATTACHED DOCUMENT IS COPYRIGHTED, ALEX V. KOSSIAKOV: ©2004 Алексей Косяков Валентинович]
    Last edited by krio; October 5th, 2004 at 10:02 AM.

  2. #2
    Veteran Member
    Join Date
    Nov 2003
    Location
    venezuela
    Posts
    575

    Name
    salf none
    Forum Username
    salf

    Venezuela

    Default Re: new fast ray tracing algorithm

    Quote Originally Posted by krio
    Well, ok. But lets look how a plane looks like in spherical coordinates:
    Ax + By + Cz + D = 0
    means
    r * (A * cos(b) * cos(a) + B * cos(b) * sin(a) + C * sin(b)) + D = 0
    r * k + D = 0
    r = - D/k

    Good, but we must calculate lots of sin and cos, that will take a lot of time... If alpha and beta depend on screen's x and y, then we can just precalculate them and put in an array of lets say 640x480x3 elements: cos(b)*cos(a) ; cos(b)*sin(a) ; sin(b). And how should we calculate A,B,C and D? We have lets say all three vertexes of triangle M1(x1,y1,z1), M2(x2,y2,z2), M3(x3,y3,z3):
    A = y1 (z2 - z3) + y2 (z3 - z1) + y3(z1 - z2) B = z1 (x2 - x3) + z2 (x3 - x1) + z3(x1 - x2)
    C = x1 (y2 - y3) + x2 (y3 - y1) + x3(y1 - y2) - D = x1(y2 z3 - y3 z2) + x2 (y3 z1 - y1 z3) + x3 (y1 z2 - y2 z1)
    No need for the russian version, that was already in russian for me.

  3. #3
    Moderator Crazy Homeless Guy's Avatar
    Join Date
    Nov 2002
    Posts
    4,950

    Name
    Travis Schmiesing
    Forum Username
    Crazy Homeless Guy



    Default Re: new fast ray tracing algorithm

    at 18 i was out drinking and chasing women, and hadn't used a computer for anything more than a text editor.

  4. #4
    Veteran Member Ernest Burden's Avatar
    Join Date
    Apr 2002
    Location
    Ossining, NY USA
    Posts
    5,388

    Name
    Ernest Burden III
    Forum Username
    Ernest Burden

    United_States

    Default Re: new fast ray tracing algorithm

    Quote Originally Posted by crazy homeless guy
    at 18 i was out drinking and chasing women, and hadn't used a computer for anything more than a text editor.
    At 18 I was a full-time renderer. Drawing perspectives by hand, airbrushing.

    I could have done the math thing...I'm sure I could.

    I am unsure what is being offered by this thread. There is some algorithm for raytracing, and it cannot be put on a website but it is put in text on our site? Is this an 'information wants to be free' exercise or a pitch to buy a product that uses this math? I just cannot tell. I cannot even tell what rendering engine would be able to use it.

    See, I didn't do the math thing. I did the rendering thing.
    Ernest Burden III
    AcmeDigital
    architectural rendering.

  5. #5
    Veteran Member wda's Avatar
    Join Date
    Nov 2002
    Location
    DFW
    Age
    49
    Posts
    1,092

    Name
    William Alexander
    Forum Username
    wda

    United States

    Default Re: new fast ray tracing algorithm

    Quote Originally Posted by crazy homeless guy
    at 18 i was out drinking and chasing women, and hadn't used a computer for anything more than a text editor.
    Gee, at 18 I had just gotten other the thrill of Pong. Although, shots & centipede were interesting, looking like 16 yrs old had to do something with my frustration. hehehehe
    From the calm seas.... Into the CG Fire...... Into the Heart of Texas

  6. #6
    Senior Member voltaire_ira's Avatar
    Join Date
    Jan 2004
    Location
    SeyBoooooooooo
    Age
    34
    Posts
    471

    Name
    John Voltaire Garcia
    Forum Username
    voltaire_ira

    Philippines

    Default Re: new fast ray tracing algorithm

    Quote Originally Posted by wda
    Gee, at 18 I had just gotten other the thrill of Pong. Although, shots & centipede were interesting, looking like 16 yrs old had to do something with my frustration. hehehehe
    gee, at 18 I had just cursed architecture for all the math subjects we were taking.hehehehe, i thought architecture had less math since its primarily graphical..hehe, i was wrong!
    QUICKRENDER VISUALIZATION STUDIO
    quickrender@smartbro.net

  7. #7
    Junior Member
    Join Date
    Oct 2004
    Location
    Moscow
    Age
    27
    Posts
    3

    Name
    Alex Kossiakov
    Forum Username
    krio

    Russian Federation

    Default Re: new fast ray tracing algorithm

    Quote Originally Posted by Ernest Burden
    At 18 I was a full-time renderer. Drawing perspectives by hand, airbrushing.

    I could have done the math thing...I'm sure I could.

    I am unsure what is being offered by this thread. There is some algorithm for raytracing, and it cannot be put on a website but it is put in text on our site? Is this an 'information wants to be free' exercise or a pitch to buy a product that uses this math? I just cannot tell. I cannot even tell what rendering engine would be able to use it.

    See, I didn't do the math thing. I did the rendering thing.

    It is posted on several forums for public testing.

  8. #8
    Veteran Member IC's Avatar
    Join Date
    Apr 2003
    Location
    Edinburgh, Scotland
    Age
    41
    Posts
    2,265

    Name
    Iain Collins
    Forum Username
    IC

    Scotland

    Default Re: new fast ray tracing algorithm

    18 year old Russian Mathematician?

    Never mind that-have you seen Sandrak, the 11 year old Latvian bodybuilder? Now that's advan...eh, wrong!

  9. #9
    Super Moderator STRAT's Avatar
    Join Date
    Dec 2001
    Location
    Cardiff, Wales, UK.
    Age
    40
    Posts
    6,997

    Name
    Stephen Leworthy
    Forum Username
    STRAT

    Wales

    Default Re: new fast ray tracing algorithm

    /me gets back to toast and coffee

  10. #10
    Veteran Member kippu's Avatar
    Join Date
    Jan 2003
    Location
    india
    Age
    37
    Posts
    1,995

    Name
    maria prem
    Forum Username
    kippu

    India

    Default Re: new fast ray tracing algorithm

    OMG OMG ...this is a cgarchitecture site ...architecture and computers ....please dont overload me with anything else

Closed Thread
Page 1 of 2 1 2 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

     

Similar Threads

  1. mental ray interior fast setup
    By joske in forum 2D/3D Tutorials
    Replies: 14
    Last Post: September 10th, 2007, 04:11 AM
  2. Mental Ray
    By charbroil in forum General Discussions
    Replies: 1
    Last Post: September 26th, 2004, 10:49 AM
  3. mentay ray exterior rendering (unchallenge)
    By Sirkus in forum The Unchallenge
    Replies: 47
    Last Post: August 22nd, 2004, 03:10 AM
  4. need a 3dsmax mental ray exterior rendering tutorial
    By Sirkus in forum 2D/3D Tutorials
    Replies: 8
    Last Post: June 16th, 2004, 02:48 AM
  5. 3dsmax6 and mental ray
    By lara in forum 3ds Max
    Replies: 7
    Last Post: April 30th, 2004, 02:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts