11 ms·
Recursive raytracer in 35 lines of JavaScript
- ohwp 13y agoIf you like this, maybe you also like this Path Tracer written in 99 lines of C++: http://www.kevinbeason.com/smallpt/ http://www.kevinbeason.com/smallpt/ (+ source code and explanation)
- eonil 13y agoEven more interesting!
- ggambetta 13y agoNow that is impressive.
- reirob 13y agoThanks for sharing this. Especially on the page there is a presentation as well as several ports of this same program to other languages like OCaml, Haskell and JavaScript. Interesting to see that the OCaml version is on par with the C++ version performance wise, but is 47% shorter. However the Haskell version is not shorter and 4.5 times slower?
- thenomad 13y agoAnd here's a comparison between that (smallpt) and the equivalent (smallptGPU) using a GPU: http://davibu.interfree.it/opencl/smallptgpu/smallptGPU.html http://davibu.interfree.it/opencl/smallptgpu/smallptGPU.html All VERY interesting stuff.
- hxa7241 13y agoAnd if you like that (spheres only), you might also like this (general triangles-based), in 444 lines of Scala (and OCaml, Python, Ruby, Lua, Scheme, C++, and C): http://www.hxa.name/minilight/ http://www.hxa.name/minilight/
- 1gn1t10n 13y agoAll this reminds me of Paul Heckbert's ray tracer written on the back of his business card: http://www.cs.cmu.edu/~ph/src/minray/minray.card.c http://www.cs.cmu.edu/~ph/src/minray/minray.card.c
- mrcactu5 13y agoit is great to see the reflections upon reflections.
- ggambetta 13y ago<inception>Reflections upon reflections? We need to go deeper.</inception>
- jcutrell 13y agoThis is absolutely fantastic. Really impressive work with the material itself.
- 10098 13y agopretty sure it's using standard blinn-phong shading. however, with the added shadows and reflections it becomes much more interesting, doesn't it? :)
- bemmu 13y agoReplace first line with this to get rid of jaggies with "supersampling" :) var w = 1000;c.style.width = '500px';
- onion2k 13y agoImpressive not only from a "ooo-that's-clever" perspective, but it's also readable, tweakable code. Many of these tiny JS toys aren't things you can really do anything with; this example is a great basis for learning.
- ggambetta 13y agoGlad you liked it. It should be far more readable, though; the constraint here was code size in bytes, so even the non-minified code (http://gabrielgambetta.com/tiny_raytracer_full.js http://gabrielgambetta.com/tiny_raytracer_full.js) is quite hacky (especially with the global vars, the horrible "tImageData" hack, the assignments within if conditions, putting all the sphere data in a flat array and playing with the indices,...)
- 10098 13y agoTo be fair, it's not exactly a "raytracer", it's a program capable of rendering that specific scene (i.e. bunch of spheres) using a recursive raytracing algorithm, which isn't awfully complex in itself. Not trying to say it's bad or anything, just want to point out that it's not very surprising for something like this to be under 100 loc in a high-level language.
- yason 13y agoI didn't know there's a required set of features for raytracer besides tracing rays. If it uses a recursive raytracing algorithm does that not make it a raytracer? It traces rays recursively like all, well, ray tracers.
- 10098 13y agoWell, to answer that question, let me make an analogy. There's no required set of features for calculators either. Technically a tiny box that can only add two numbers can be considered a calculator, since it calculates. I guess we might call it so, but it isn't the same, is it? It's just that people tend to think about povray and renderman when "raytracers" are mentioned, and thus, fitting a raytracer into 30 lines of javascript may seem impossible, while actually it's entirely possible because the core idea of the algorithm is quite simple - this is what this demo shows and it is exactly the reason it's a good demo.
- coldtea 13y ago>It's just that people tend to think about povray and renderman when "raytracers" are mentioned, and thus, fitting a raytracer into 30 lines of javascript may seem impossible Not really. At least neither me, nor (I'd say) the HN crowd, would expect something like povray or renderman given the title of the article. What we'd expect, an implementation of a ray tracing algorithm, and not a full featured program, we got.
- GuiA 13y agoA tiny tip coming from a friendly place, if I may- your comment comes off as slightly pedant and elitist. I'm sure it was not in your intention to bring down the original author of this demo, who is probably very excited about what he worked hard on, but rather to highlight how deep of a field raytracing is and to encourage him to not be content with this first venture into it, and to explore more of it. A good way to do that is to write your comment from a "Yes and..." perspective, rather than a "Yes but..." perspective. In one case you're showing the author how tall the wall front of him is, in the other you show him how you yourself climbed that wall when you were in his position. It helps a lot :)
- Taylorious 13y agoThis is very cool. Interestingly it was generated by Google's Closure compiler. The author has the full source with excellent comments on his site. link: http://www.gabrielgambetta.com/tiny_raytracer.html http://www.gabrielgambetta.com/tiny_raytracer.html
- 10098 13y agofrom his site: > Their combination of a simple algorithm and stunning results are hard to beat. that's exactly what fascinates me about raytracing. It's pretty straightforward, you literally emulate the light bouncing around, but given enough resources the results can be surprisingly good-looking.
- maggit 13y agoFor interest, the method of literally emulating light bouncing around seems to be called Photon tracing (http://en.wikipedia.org/wiki/Photon_tracing http://en.wikipedia.org/wiki/Photon_tracing). It creates realistic renderings of just about anything if you can afford the time to render it. Rendering times are prohibitively high, though, because this rendering method emulates lots of photons that never hit the sensor. Ray tracing, although very powerful, has some limitations because it goes the other way: It casts rays from the sensor into the scene.
- ohwp 13y agoThis is where path tracing steps in. Bi-directional path tracing combines both photon tracing and ray tracing. http://en.wikipedia.org/wiki/Path_tracing http://en.wikipedia.org/wiki/Path_tracing
- logicallee 13y agocould you elaborate on where the symmetry breaks down? From your comment and another one here, it seems to be the case that actually some of the photons that don't hit the sensor still affect the image (either that, or you can't get back to the source starting at the sensor for some of the photons). In other words, if a light source emits a trillion photons everywhere in the room, and your sensor (the idealized camera) catches ten million photons, then it's not strictly equivalent to trace back the ten million maths to the light source, and ignore the ones that didn't make it to the idealized camera. If it were equivalent, you wouldn't need "photon tracing and ray tracing" or bidirectionality. But I'm struggling at where the symmetry breaks down, since it seems that tracing a path back from the sensor along the same angles should produce the same result as tracing it forward from the light source - for the photons that directly or indirectly (after a certain number of bounces or passing through the materials) make it to the idealized camera. But the ones that don't make it to the idealized camera - how can they still affect the frame? Or (equivalently), when is it the case that you can trace it forward to the camera but not backward from the camera? Why do you need bidirectionality? Where does the symmetry break down?
- lignuist 13y agoThose [anything] in [n] lines of JavaScript pieces are a great way to dive into the code in order to learn. It is usually much easier to read through 30 lines than through 3000 lines. So it probably not very important that these projects are not finished products.
- filipedeschamps 13y agoAmazing job. This is one of the coolest points of Javascript IMHO: you can see the result and interact with it directly in your browser. Right here you will find someone tweaking the code for supersampling, and you can apply it yourself and see the result without hassle. This generates an uncontrollable and very positive propagation effect.
- ttty 13y agoWhy this? // Shorten some names. var math = Math;
- minikomi 13y agoBecause when it's run through the Google closure compiler it becomes E=Math,F=E.sqrt,G=E.max
- choult 13y agoCapital letters are bigger, and therefore take up more space.
- stickupkid 13y agoNo.
- rejschaap 13y agoThat is before minifying. The variable name "math" was chosen for readibility in the non-minified version. The variable math can be renamed during the minifying process to a short identifier, in this case "E". Since the Math object is used quite a lot, it is worth the assignment to rename it.
- deleted 13y ago[deleted]
- ggambetta 13y agoFor minification, as someone else said. I originally wrote this for a JS1K competition some years ago, so it's not geared towards readability, but towards small code size. I had a really, really ugly trick that saved me a couple of bytes which I removed before posting to HN. I figured out I was using canvas.getImageData() and canvas.putImageData(). So I did this: var tID = "tImageDatA"; canvas["ge"+tID](); canvas["pu"+tID"](); You can see that in the original source: http://gabrielgambetta.com/tiny_raytracer_full.js http://gabrielgambetta.com/tiny_raytracer_full.js Not my proudest hack :D
- 13y ago
- CmonDev 13y ago[well-known-trivial-app] in [substantially-small-number] lines of [any-high-level-script-language-with-graphics-libs]
- fekberg 13y agoI think this is awesome, however, I think it would be even more awesome to get a walk through of the code and the thought process behind minifying it in a blog post, the past days with all the jsfiddles are nice so don't get me wrong on that part. I just think it adds more value if the code is somewhat explained (I know ray tracing is explained on tons of places). Just my two cents.
- ggambetta 13y agoThe fully commented (but not entirely clean) code is here: http://www.gabrielgambetta.com/tiny_raytracer_full.js http://www.gabrielgambetta.com/tiny_raytracer_full.js Also, I'm halfway through writing a Computer Graphics textbook, half of it dedicated to raytracing.
- davidpardo 13y agoYou can find the whole commented source at http://www.gabrielgambetta.com/tiny_raytracer_full.js http://www.gabrielgambetta.com/tiny_raytracer_full.js
- fekberg 13y agoThank you for that!
- gumuz 13y agoAwesome! I tried to look into building a simple raytracer many times, but the either math gets me everytime or I just didn't come across the right "raytracer for dummies" tutorials. Any suggestions?
- ggambetta 13y agoThe fully commented (but not entirely clean) code is here: http://www.gabrielgambetta.com/tiny_raytracer_full.js http://www.gabrielgambetta.com/tiny_raytracer_full.js Also, I'm halfway through writing a Computer Graphics textbook, half of it dedicated to raytracing.
- jamiek88 13y agoI'd buy it, please post the link once its done, or if you want any proof readers or people to type in the code to check for typos I'd be happy to help.
- ohwp 13y agoFor many year I also tried to build a simple ray tracer. The math got me to, but in the end I was able to write different types of render engines. What helped me: learn about vectors learn about (vector) normalization learn about camera models http://www.ventrella.com/Ideas/Camera/Arm_Camera.pdf learn about pixels (pixels are just dots without size) use a 3D coordinate-system that works for you (mine is: x = right, y = forward, z = up) start with a simple camera model (always looking forward) normalize all direction vectors place the screen of pixels 1 unit in front of the camera normalize the screen of pixels know that the center pixel is on the forward vector of the camera try to calculate a vector from the camera position to the left top of the pixel screen in front of the camera
- tripzilch 13y agoPossibly more than you asked for, but it's great material: http://scratchapixel.com/ http://scratchapixel.com/ (on a not-particularly-raytracing-related note, I can really recommend to anyone interested the lesson about colour spaces, first time the point of CIExy and sRGB became clear to me. also for anyone wondering why the colours in F.lux / Redshift shift the way they do, check the "blackbody radiation" chapter)
- kitsune_ 13y agoComputers have become fast, I remember rendering a scene like this in PovRay in the mid-90's and it took hours.
- Angelo8000 13y agoVery nice. I myself have been learning SPAs.. Seems to be the future of web dev: http://www.amazon.com/gp/product/1617290750/ref=as_li_tf_il?ie=UTF8&camp=1789&creative=9325&creativeASIN=1617290750&linkCode=as2&tag=produc05-20 http://www.amazon.com/gp/product/1617290750/ref=as_li_tf_il?...
- eonil 13y agoThis is interesting!
- ThePhysicist 13y agomind = blown
- jasongaya 13y agoGreat, thanks for share with us.
- brador 13y agoI'm loving this jsfiddle 1-upmanship. Really squeezing out what it's capable of.
- be5invis 13y agoI've got an interesting performance measurement: On Chrome 31, it takes 3307 ms to render the image and on IE11 it takes only 2320 milliseconds. So am I in the matrix?
- albertzeyer 13y agoRaytracing works really good when you use the GPU for calculation, e.g. via OpenCL or CUDA. I just checked, there is already WebCL and an implementation for WebKit (https://github.com/SRA-SiliconValley/webkit-webcl https://github.com/SRA-SiliconValley/webkit-webcl). Here is a video: http://www.youtube.com/watch?v=9Ttux1A-Nuc http://www.youtube.com/watch?v=9Ttux1A-Nuc
- thenomad 13y agoAlong similar lines and (arguably) even cooler: full-on path tracing in WebGL using a GLSL shader: http://madebyevan.com/webgl-path-tracing/ http://madebyevan.com/webgl-path-tracing/
- chii 13y agohis other stuff is also really amazing: http://madebyevan.com/webgl-water/ http://madebyevan.com/webgl-water/
- hrjet 13y agoThat has been optimised further by this guy here: http://mmmovania.blogspot.in/2011/11/snapshot-from-my-latest-glsl-path.html http://mmmovania.blogspot.in/2011/11/snapshot-from-my-latest...
- jebblue 13y agoThat's impressive to me, don't like JavaScript but doing that is impressive. It's also interesting to see how useful a canvas element is.
- nwh 13y agoChange the "w" variable to > 9000 and it completely kills Safari, can't even close the tab or the browser. Sweet demo though, I remember being amazed seeing this sort of thing the first time.
- cocoflunchy 13y agoI'm currently trying to write a raytracer in Python (I know, I know) but I'm already at like 200 lines and no reflections, refraction, shadows or light sources :( But I won't quit! If you're interested, I'm already proud of what I have :) http://i.imgur.com/8wwSsab.png http://i.imgur.com/8wwSsab.png
- cobrausn 13y agoImpressive, especially since it is still fairly readable. On the other end of the spectrum, I give you raytracing on the back of a business card, in C++. http://fabiensanglard.net/rayTracing_back_of_business_card/ http://fabiensanglard.net/rayTracing_back_of_business_card/
- ggambetta 13y agoNot quite "the other end" - the code I posted can be reduced to 960 bytes: http://gabrielgambetta.com/tiny_raytracer.html http://gabrielgambetta.com/tiny_raytracer.html
- IvanK_net 13y agoI have written Path Tracer in JS (http://renderer.ivank.net/ http://renderer.ivank.net/) and rendered these images: http://renderer.ivank.net/balls.jpg http://renderer.ivank.net/balls.jpg http://renderer.ivank.net/cornell.jpg http://renderer.ivank.net/cornell.jpg but nobody is talking about it :( Maybe I should render a movie or something.
- ggambetta 13y agoThat's really impressive! Someone did post links to SmallPT somewhere in this discussion, though.
- jheriko 13y agoi dont really understand why these things are considered impressive. all of the technically challenging bits are handled by the enormous stack of technology involved. granted the js is highly size optimised, and that probably required some reasonable effort. i see nothing clever here at all. also, the fact that its 35 lines is a weird measure - i can see ways to reduce that trivially - why isn't everything to do with the render baked into the final loop?. the byte count is a more useful measure. 4k/64k executable demos are much more impressive - even though there is a stack of technology underneath you have to do things like butcher your C/C++ standard libraries or not use them at all...
- PhasmaFelis 13y ago> i dont really understand why these things are considered impressive. all of the technically challenging bits are handled by the enormous stack of technology involved. For one thing, it's a reminder of how awesome the technology stack that we all take for granted is.
- DanBC 13y agoFeel free to release a bunch of your own Thing in 30 lines, or to code-golf all the existing Things in 30 lines to 5 lines, or whatever.
- ggambetta 13y agoFine, 959 bytes: http://gabrielgambetta.com/tiny_raytracer.html http://gabrielgambetta.com/tiny_raytracer.html
- staunch 13y agoIf you haven't seen this yet, "The Physics of Light and Rendering | A Talk by John Carmack" is really enjoyable. http://www.youtube.com/watch?v=MG4QuTe8aUw http://www.youtube.com/watch?v=MG4QuTe8aUw
- snake_plissken 13y agoAnyone got some good links to the algebra/geometry behind raytracing?
- berkut 13y agoDepends how far you want to take it... There's plenty of links on the web, but if you're really serious (it can be quite addictive writing one), get hold of the "Raytracing/Rendering bible" : Physically Based Rendering by Matt Pharr and Greg Humphreys. There's also a plethora of research freely available with cutting edge techniques to read.
- snake_plissken 13y agoThanks for the book reco!
- tripzilch 13y agohttp://scratchapixel.com http://scratchapixel.com + see my other comment https://news.ycombinator.com/item?id=6771403 https://news.ycombinator.com/item?id=6771403
- vittore 13y agoGuys if you have links to other tiny things in js like that, of about 30 lines of code or less, please send me links. http://30lines.info http://30lines.info
- awredtrht 13y agoafdfawesergsdf