<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sushindhran Harikrishnan on Medium]]></title>
        <description><![CDATA[Stories by Sushindhran Harikrishnan on Medium]]></description>
        <link>https://medium.com/@sushi_21846?source=rss-2e00188ad2a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RFpVOGyUmDZCLmdr.</url>
            <title>Stories by Sushindhran Harikrishnan on Medium</title>
            <link>https://medium.com/@sushi_21846?source=rss-2e00188ad2a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 07:51:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sushi_21846/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebGL with Perlin Noise — Part 1]]></title>
            <link>https://medium.com/neosavvy-labs/webgl-with-perlin-noise-part-1-a87b56bbc9fb?source=rss-2e00188ad2a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a87b56bbc9fb</guid>
            <dc:creator><![CDATA[Sushindhran Harikrishnan]]></dc:creator>
            <pubDate>Thu, 07 Sep 2017 14:01:11 GMT</pubDate>
            <atom:updated>2017-09-07T14:01:11.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YS2mdUzHZxv77aIZvclTNQ.jpeg" /></figure><p>I have been intrigued by Perlin Noise ever since I learned of it at my Computer Graphics class at NYU from the man himself, Ken Perlin. He won an <a href="http://mrl.nyu.edu/~perlin/doc/oscar.html">academy award</a> for the original implementation and in 2002 he wrote a paper on his <a href="http://mrl.nyu.edu/~perlin/paper445.pdf">improved noise</a>.</p><h4>What is Perlin Noise?</h4><p>Perlin Noise is an algorithm that is used in procedural content generation. Perlin Noise can be used for any sort of wave-like material or texture. It could be used for procedural terrain (side-scrolling terrains in games for example), clouds, snow, water and fire effects. These effects are mostly Perlin noise in the 2nd and 3rd dimensions, but it can also be extended into the 4th dimension.</p><p>There are several really great articles out there explaining perlin noise and the math behind it. So I’m not going to go into that, but we’re going to use the noise function to build on what we’ve done in the <a href="https://medium.com/neosavvy-labs/webgl/home">previous WebGL articles</a>.</p><p>Here are a couple of articles for reference.</p><blockquote><a href="https://mzucker.github.io/html/perlin-noise-math-faq.html">https://mzucker.github.io/html/perlin-noise-math-faq.html</a></blockquote><blockquote><a href="https://thebookofshaders.com/11/">https://thebookofshaders.com/11/</a></blockquote><h4>Noise in 2D</h4><p>Here is the Perlin Noise function we’re going to use. We’re going to call noise() with a 2D vector as a parameter and get a float value.</p><pre>// Noise<br>vec3 mod289(vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }<br>vec4 mod289(vec4 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; }<br>vec4 permute(vec4 x) { return mod289(((x*34.0)+1.0)*x); }<br>vec4 taylorInvSqrt(vec4 r) { return 1.79284291400159 - 0.85373472095314 * r; }<br>vec3 fade(vec3 t) { return t*t*t*(t*(t*6.0-15.0)+10.0); }<br>float noise(vec3 P) {<br>    vec3 i0 = mod289(floor(P)), i1 = mod289(i0 + vec3(1.0));<br>    vec3 f0 = fract(P), f1 = f0 - vec3(1.0), f = fade(f0);<br>    vec4 ix = vec4(i0.x, i1.x, i0.x, i1.x), iy = vec4(i0.yy, i1.yy);<br>    vec4 iz0 = i0.zzzz, iz1 = i1.zzzz;<br>    vec4 ixy = permute(permute(ix) + iy), ixy0 = permute(ixy + iz0), ixy1 = permute(ixy + iz1);<br>    vec4 gx0 = ixy0 * (1.0 / 7.0), gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;<br>    vec4 gx1 = ixy1 * (1.0 / 7.0), gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;<br>    gx0 = fract(gx0); gx1 = fract(gx1);<br>    vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0), sz0 = step(gz0, vec4(0.0));<br>    vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1), sz1 = step(gz1, vec4(0.0));<br>    gx0 -= sz0 * (step(0.0, gx0) - 0.5); gy0 -= sz0 * (step(0.0, gy0) - 0.5);<br>    gx1 -= sz1 * (step(0.0, gx1) - 0.5); gy1 -= sz1 * (step(0.0, gy1) - 0.5);<br>    vec3 g0 = vec3(gx0.x,gy0.x,gz0.x), g1 = vec3(gx0.y,gy0.y,gz0.y),<br>        g2 = vec3(gx0.z,gy0.z,gz0.z), g3 = vec3(gx0.w,gy0.w,gz0.w),<br>        g4 = vec3(gx1.x,gy1.x,gz1.x), g5 = vec3(gx1.y,gy1.y,gz1.y),<br>        g6 = vec3(gx1.z,gy1.z,gz1.z), g7 = vec3(gx1.w,gy1.w,gz1.w);<br>    vec4 norm0 = taylorInvSqrt(vec4(dot(g0,g0), dot(g2,g2), dot(g1,g1), dot(g3,g3)));<br>    vec4 norm1 = taylorInvSqrt(vec4(dot(g4,g4), dot(g6,g6), dot(g5,g5), dot(g7,g7)));<br>    g0 *= norm0.x; g2 *= norm0.y; g1 *= norm0.z; g3 *= norm0.w;<br>    g4 *= norm1.x; g6 *= norm1.y; g5 *= norm1.z; g7 *= norm1.w;<br>    vec4 nz = mix(vec4(dot(g0, vec3(f0.x, f0.y, f0.z)), dot(g1, vec3(f1.x, f0.y, f0.z)),<br>        dot(g2, vec3(f0.x, f1.y, f0.z)), dot(g3, vec3(f1.x, f1.y, f0.z))),<br>        vec4(dot(g4, vec3(f0.x, f0.y, f1.z)), dot(g5, vec3(f1.x, f0.y, f1.z)),<br>            dot(g6, vec3(f0.x, f1.y, f1.z)), dot(g7, vec3(f1.x, f1.y, f1.z))), f.z);<br>    return 2.2 * mix(mix(nz.x,nz.z,f.y), mix(nz.y,nz.w,f.y), f.x);<br>}<br>float noise(vec2 P) { return noise(vec3(P, 0.0)); }</pre><p>Now let’s call noise() in our main() function.</p><pre>void main() {<br>     vec3 color;<br>     float x = vPosition.x;<br>     float y = vPosition.y;<br>     color = vec3(noise(vec2(x * 21., y * 15.)));<br>     gl_FragColor = vec4(color, 1.);<br>}</pre><p>This generates a texture that looks as follows. Click on the image to view the webGL canvas for this. You can also view the source <a href="https://github.com/neosavvyinc/WebGL/blob/gh-pages/src/html/noise.texture.html">here</a>.</p><figure><a href="https://neosavvyinc.github.io/WebGL/src/html/noise.texture.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SmVx7nLvRgf7NoO6l8FSg.png" /></a><figcaption><strong>2D Noise</strong></figcaption></figure><h4>Turbulence</h4><p>Now let’s do something more interesting. When you take the <a href="https://en.wikipedia.org/wiki/Curl_(mathematics)">curl</a> of Perlin Noise, you get a nice turbulence function that helps us fake fluid dynamics. The turbulence function looks like this</p><pre>float turbulence(vec3 P) {<br>    float f = 0., s = 1.;<br>    for (int i = 0 ; i &lt; 9 ; i++) {<br>        f += abs(noise(s * P)) / s;<br>        s *= 2.;<br>        P = vec3(.866 * P.x + .5 * P.z, P.y + 100., -.5 * P.x + .866 * P.z);<br>    }<br>    return f;<br>}</pre><p>Now let’s try and create a gaseous cloud like effect with the turbulence function. Note that we’re using <strong>uTime</strong> to animate the fluid-like texture.</p><pre>vec3 clouds(float x, float y) {<br>    float L = turbulence(vec3(x, y, uTime * .1));<br>    return vec3(noise(vec3(.5, .5, L) * .7));<br>}</pre><p>Our main function now looks like this. We’re passing in the x and y coordinates to the cloud function.</p><pre>void main() {<br>     vec3 color;<br>     float x = vPosition.x;<br>     float y = vPosition.y;<br>     vec3 cloudEffect = clouds(vPosition.x, vPosition.y);<br>     color = cloudEffect + vec3(.5, .8, 0.95);<br>     gl_FragColor = vec4(color, 1.);<br>}</pre><p>The cloud texture looks like this. Click on the image to see the animation in action. Click <a href="https://github.com/neosavvyinc/WebGL/blob/gh-pages/src/html/noise.clouds.html">here</a> to view the source for this.</p><figure><a href="https://neosavvyinc.github.io/WebGL/src/html/noise.clouds.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvoQxTplqnc5aL4gWpPf-w.png" /></a><figcaption><strong>Cloud Effect</strong></figcaption></figure><h4>Applying noise to shapes</h4><p>Let’s apply the cloud like effect to a sphere that we created in our previous ray tracing posts. We will still have the same initialize() and checkIntersectSphere() functions from the previous post, but we’re making a small tweak to the way we calculate the color for a pixel when the ray intersects with the sphere. Note how we multiply the cloudEffect value to the sphere color.</p><pre>if (t &gt; 0.0) {<br>    vec3 surfacePoint = cameraSource + (t * cameraDirection);<br>    vec3 surfaceNormal = normalize(surfacePoint - sphereCenter);<br>    sphereBaseColor = colorOfSphere * (ambience + ((1.0 - ambience) * max(0.0, dot(surfaceNormal, lightSource))));<br>    color = vec3(cloudEffect * sphereBaseColor) + vec3(0.5, 0.2, 0.1);<br>}</pre><p>Our main() function will remain the same.</p><pre>void main() {<br>     vec3 color;<br>     float x = vPosition.x;<br>     float y = vPosition.y;</pre><pre>     initialize();<br>     color = checkIntersectSphere(spheres[0], rays[0], light[0]);<br>     gl_FragColor = vec4(color, 1.);<br>}</pre><p>This is how our sphere looks now. Click on the image to view the animated texture. Click <a href="https://github.com/neosavvyinc/WebGL/blob/gh-pages/src/html/noise.sphere.html">here</a> to view the source for this.</p><figure><a href="https://neosavvyinc.github.io/WebGL/src/html/noise.sphere.html"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shd8KwA8jw5naYjULIQ-uw.png" /></a><figcaption><strong>Sphere with gaseous texture.</strong></figcaption></figure><p>I will follow this up with more textures and more in-depth explanations using noise functions in a new article. As always, if there are any questions or if there are any problems or mistakes in the code here, feel free to reach out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a87b56bbc9fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neosavvy-labs/webgl-with-perlin-noise-part-1-a87b56bbc9fb">WebGL with Perlin Noise — Part 1</a> was originally published in <a href="https://medium.com/neosavvy-labs">Neosavvy Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoughts of a software consultant.]]></title>
            <link>https://medium.com/neosavvy-labs/thoughts-of-a-software-consultant-3720de0a7909?source=rss-2e00188ad2a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3720de0a7909</guid>
            <dc:creator><![CDATA[Sushindhran Harikrishnan]]></dc:creator>
            <pubDate>Thu, 27 Jul 2017 14:01:02 GMT</pubDate>
            <atom:updated>2017-07-27T14:53:02.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1CGyxxQUPdCddxPqMOmKw.jpeg" /></figure><p>I’ve been working as a software developer consultant for over three years now. A couple of weeks ago after <a href="https://medium.com/u/f3774fd3fb39">Adam Parrish</a>’s <a href="https://medium.com/neosavvy-labs/dispelling-the-rumor-that-consultants-are-mercenaries-a371523438ac">article</a> on consulting, I was looking back and reminiscing, wondering how I’ve changed and if those changes were for the better or worse. I decided to take some time to introspect, assess myself and collect my thoughts. Here are some things I’ve realized and/or experienced over the last few years as a consultant.</p><h4>Jump right into the job</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngGRhCyfE575bRCh9pSO9Q.jpeg" /></figure><p>As a consultant you’re expected to hit the ground running. Time is of the essence and someone wants efficiency, quality and experience all bundled into one package. If you’re spending time experimenting on whether <a href="https://www.npmjs.com/package/express">express</a> is better than <a href="https://www.npmjs.com/package/koa">koa</a>, you’re doing it wrong. You’re brought in to do the job because you already know which one is better.</p><h4>Thought leadership and direction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NKHT6bSAxQj41K2EbAMnhg.jpeg" /></figure><p>A consultant’s input towards making architectural decisions and changes are valued highly. More often than not, you’re expected to lead those decision making processes and provide technical direction for the project. It could be anything from architecting a feature end-to-end to something like suggesting and carrying out a framework upgrade.</p><h4>Accountability</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1mhp2p9KBl6Zd49v0DbCQ.jpeg" /></figure><p>In most projects, the role of a consultant in a project is clearly defined. Even when it is not, consultants are held more accountable for the work they do. This actually isn’t a bad thing. Accountability is not only a great source of motivation, but also a good way to ensure that all the stakeholders in the project clearly define what needs to be done. This way everyone is focused and has their work cut out.</p><h4>Timeliness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av3MfP7tEC72pkPKkLAfeQ.jpeg" /></figure><p>It’s always good to keep up good impressions as a consultant. Besides not looking disheveled all the time, there is nothing that goes farther than timeliness in making a good impression. Being in time for meetings and just to work in general is a great characteristic trait to have. This is great for productivity and keeping up momentum in a project, and it also embodies professionalism and conveys that you care about what you’re doing.</p><h4>Objectivity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFSMdWkgKuBgrmENbMW7_Q.jpeg" /></figure><p>Consultants are expected to have objective opinions about the project, whether it’s technical or otherwise. Being objective does not mean caring less about the project. The objectivity not only stems from the consultant being aloof from the client organization’s hierarchy, but also the experience gained from working on a plethora of other projects.</p><h4>Imparting knowledge</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5FBObjeM-t6kok0prSTPpg.jpeg" /></figure><p>Part of your job as a consultant is also to ensure that you leave something behind that can be maintained. You’re not going to be around on the project forever, which means you have to do a lot of knowledge transfer and sometimes even training at some level. To do this efficiently and thoroughly, you need to have a lot of patience and extra levels of commitment. Having said that, this experience will only add to your growing repertoire of skills.</p><h4>Diversity</h4><p>As you gain more experience as a consultant, the nature of your job ensures that you are exposed to a variety of technologies. Good consultants tend to have a faster learning curve because of this. The diversity in experience is an invaluable addition to any project. It serves to demonstrate that you’ve been around the block and you can handle almost anything that is thrown at you.</p><h4>TL;DR</h4><p>I’ve realized that consulting is in many ways more challenging than being an employee. Consultants are usually brought in to provide technical direction and to steady the metaphorical ship. The nature of this work implies that there is likely to be more pressure at times to deliver, and for that reason consulting is not for everyone.</p><p>On the other hand, consulting can also be fun in many ways. You get to work on a more diverse set of projects, meet new people and gain varied experience. For example, I’ve already worked in media and finance tech. I can say that I’ve come out from my experiences for the better and I’ve thoroughly enjoyed the challenges laid in front of me over the last few years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3720de0a7909" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neosavvy-labs/thoughts-of-a-software-consultant-3720de0a7909">Thoughts of a software consultant.</a> was originally published in <a href="https://medium.com/neosavvy-labs">Neosavvy Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Unit Testing Quandary]]></title>
            <link>https://medium.com/neosavvy-labs/the-unit-testing-quandary-574a9e95a0d2?source=rss-2e00188ad2a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/574a9e95a0d2</guid>
            <category><![CDATA[neosavvy]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Sushindhran Harikrishnan]]></dc:creator>
            <pubDate>Thu, 01 Jun 2017 19:10:50 GMT</pubDate>
            <atom:updated>2017-06-02T16:48:23.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dq06KB2a_hJeGy55RQ8mug.png" /></figure><p>I’ve worked on a handful of projects in my still fledgling career, and I’ve seen several takes on unit testing in each of those projects. Here are a few things I’ve heard people say about unit testing, that I don’t agree with at all.</p><h4>I write perfect code, so it does not need tests.</h4><p>Besides the fact that it sounds very conceited, it’s also a very ego-centric way of thinking. Calling your own code perfect is debatable, which is why we have a peer review process before code is checked-in.</p><h4>Writing tests pushes out feature delivery timelines.</h4><p>This usually tends to be the way a product manager thinks, and it is absolutely true. When we’re building out an MVP that is going to be thrown away, it makes sense to overlook unit tests. But that way of thinking needs to change when we’re building out a complicated product, because unit tests ensure long-term maintainability of a feature.</p><h4>Unit tests are another thing that needs maintenance in a codebase.</h4><p>I’ve heard a few people argue that unit tests are expensive to maintain in a codebase. Tests are code too and they do need to be maintained, but unit tests are actually quite easy to write once you get the hang of it.</p><h4>I have to modify tests every time I make changes to a feature.</h4><p>That is the whole point of writing tests! When you see broken tests, you know something has changed. Sometimes those changes may have been unintentional or many have unforeseen side-effects.</p><h4>We need 100% code coverage.</h4><p>Having 100% code coverage is a great target to have. Sometimes it’s easy to get really close. It’s always the last 5% that kills you. The cost of getting the last 5% of code coverage may outweigh the benefits by a mile. That’s when we can replace that unit test with a scenario test.</p><p>Most of the negativity around writing unit tests stems from a lack of experience writing tests, strict deadlines or just a disregard for other programmers on your team. It’s hard to have arguments with people when you know that their points of view are baseless. Nevertheless, I think unit tests are an absolute necessity for any project of reasonable complexity. Unit tests are quick and easy to write when you’re in the groove and they are an insurance policy that protects you from an unforeseen catastrophe that awaits the project. I’m going to list a few, not so apparent, advantages of having tests from my experience.</p><h4>1. Bug-free code with TDD</h4><p>Test driven development is a very idealistic way of thinking for a software developer. If it is indeed followed, then your code is going to be almost bug-free. You tend to think through and cover each and every edge case in your implementation of that feature. Even otherwise, I’ve found that I realize that my code does not work the way it’s intended to while writing tests for it. This definitely saves us time as a team. Less bugs means that QA has one less bug to file, that has to be prioritized, assigned and then worked on. It may seem trivial, but these tiny bugs definitely add up.</p><h4>2. Forgetting features</h4><p>As a developer, I definitely tend to forget some finer details about how a feature is supposed to work. Those finer details are sometimes not very obvious from just looking at the code. When you come back to a chunk of code you wrote a year ago, the unit tests are a handy tool to help understand what it is doing exactly.</p><h4>3. Protection against staff churn</h4><p>In a large project that is moving really fast, with continual staff churn, the only way to ensure productivity and knowledge transfer of features is unit tests. A new developer understands a feature better when there are unit tests to look at. I have definitely found myself in the situation where I’m looking at spaghetti code and wishing it had unit tests that would prevent me from completely unravelling a feature.</p><h4>Summary</h4><p>Unit testing is awesome and we have to be more accepting of it. In a long term project, especially in a javascript(thanks to its quirks) codebase, tests are important. It’s also a useful skill set to have and it definitely looks great on your resume if you are adept at it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574a9e95a0d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neosavvy-labs/the-unit-testing-quandary-574a9e95a0d2">The Unit Testing Quandary</a> was originally published in <a href="https://medium.com/neosavvy-labs">Neosavvy Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebGL — 2.1 Ray Tracing with reflections]]></title>
            <link>https://medium.com/neosavvy-labs/webgl-2-1-ray-tracing-with-reflections-bd5e52953e2f?source=rss-2e00188ad2a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5e52953e2f</guid>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sushindhran Harikrishnan]]></dc:creator>
            <pubDate>Thu, 04 May 2017 13:20:38 GMT</pubDate>
            <atom:updated>2017-05-17T13:16:49.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tl1M0KZGK-rJKQoLOsDmlA.jpeg" /></figure><p>In this post, we’re going to do something slightly more engrossing using the same building blocks we put in place in the <a href="https://medium.com/neosavvy-labs/webgl-2-0-ray-tracing-34866baca7c1">previous post</a>. We are going to add multiple spheres to our scene and add reflections.</p><h3>1. Adding Multiple Spheres</h3><p>Let’s first add multiple spheres and start by defining a macro for the number of spheres we want.</p><pre>#define NUM_SPHERES 5</pre><p>We already defined a struct for our sphere in our previous post. Let’s use that and define 4 new spheres in the <strong>initialize()</strong> function to add to our scene.</p><pre>// Create spheres<br>spheres[0].center = vec3(-0.25, 1.5 * sin(uTime), -0.25);<br>spheres[0].radius = 0.3;<br>spheres[0].color = vec3(1.0, 0.0, 0.0);</pre><pre>spheres[1].center = vec3(0.5 * sin(uTime), 0.25, 0.75);<br>spheres[1].radius = 0.2;<br>spheres[1].color = vec3(0.0, 1.0, 0.0);</pre><pre>spheres[2].center = vec3(-0.75, 0.0, 0.5);<br>spheres[2].radius = 0.2;<br>spheres[2].color = vec3(0.0, 0.0, 1.0);</pre><pre>spheres[3].center = vec3(-0.25 , 0.4 * sin(uTime), 0.1* sin(uTime));<br>spheres[3].radius = 0.25;<br>spheres[3].color = vec3(0.0, 1.0, 1.0);</pre><pre>spheres[4].center = vec3(-1.5, 0.15 * sin(uTime), 0.15 * sin(uTime));<br>spheres[4].radius = 0.35;<br>spheres[4].color = vec3(1.0, 1.0, 0.0);</pre><h3>2. Drawing the spheres</h3><p>We now have multiple spheres and we have to draw them on the screen keeping in mind that the nearest sphere to the camera/ray origin gets rendered. So I’ve modified our <strong>getIntersection()</strong> function from the previous post to be more generic, and take in a sphere and the ray, and just return the intersection point of the ray with that sphere.</p><pre>float getIntersection(Sphere sphere, Ray ray) {<br>    vec3 sphereCenter = sphere.center;<br>    vec3 colorOfSphere = sphere.color;<br>    float radius = sphere.radius;<br>    vec3 cameraSource = ray.origin;<br>    vec3 cameraDirection = ray.direction;</pre><pre>vec3 distanceFromCenter = (cameraSource - sphereCenter);<br>    float B = 2.0 * dot(cameraDirection, distanceFromCenter);<br>    float C = dot(distanceFromCenter, distanceFromCenter) - pow(radius, 2.0);<br>    float delta = pow(B, 2.0) - 4.0 * C;<br>    float t = 0.0;<br>    if (delta &gt; 0.0) {<br>        float sqRoot = sqrt(delta);<br>        float t1 = (-B + sqRoot) / 2.0;<br>        float t2 = (-B - sqRoot) / 2.0;<br>        t = min(t1, t2);<br>    }<br>    if (delta == 0.0) {<br>        t = -B / 2.0;<br>    }<br>    return t;<br>}</pre><p>This function now has to be called for each sphere in the scene, and the smallest intersection point is what is considered in our fragment shader.</p><pre>for (int i=0; i &lt; NUM_SPHERES; i++) {<br>    float t = getIntersection(spheres[i], ray);<br>    if (t &gt; 0.0 &amp;&amp; t &lt; minT) {<br>        minT = t;<br>        sphereToShow = spheres[i];<br>    }<br>}</pre><p>Note that the initial value of <strong>minT</strong> is <strong>INFINITY</strong>. So we define a macro for that. Let INFINITY be a relatively large number for our scene. I’m defining it to be 100000.0</p><pre>#define INFINITY 100000.0</pre><p>Now that we have <strong>sphereToShow </strong>for our scene, we can return the color of that sphere to `gl_FragColor`. But we also need to return the reflectedRay for that point along with the color. So I’ve defined a new struct called <strong>RayTracerOutput</strong>.</p><pre>struct RayTracerOutput {<br>    Ray reflectedRay;<br>    vec3 color;<br>};</pre><h3>3. Computing the Reflected Ray</h3><p>A good mathematical explanation for computing the reflected ray can be found <a href="http://paulbourke.net/geometry/reflected/">here</a>. Essentially, if we have an incoming ray direction <strong>W</strong> and a surface normal direction <strong>n</strong>, we can calculate the emergent reflection direction by:</p><p><em>R = 2 (</em><strong><em>-W</em></strong><em> • </em><strong><em>n</em></strong><em>) </em><strong><em>n</em></strong><em> + </em><strong><em>W</em></strong></p><p>We can therefore form a new ray, starting a small distance ε outside the sphere surface, as:</p><p><strong><em>Origin = S + ε R, </em></strong><em>where S is the surface point and ε is a very small number</em></p><p><strong><em>Direction = R</em></strong></p><p>Now our new ray (ie the reflected ray) would be:</p><p><strong><em>Origin + t * Direction</em></strong></p><p>This is how all this looks in code.</p><pre>if (minT &gt; 0.0 &amp;&amp; minT != INFINITY) {<br>    vec3 surfacePoint = cameraSource + (minT * cameraDirection);<br>    vec3 surfaceNormal = normalize(surfacePoint - sphereCenter);</pre><pre>// Reflection<br>    vec3 reflection = 2.0 * dot(-ray.direction, surfaceNormal) * surfaceNormal + ray.direction;<br>    reflectionRay.origin = surfaceNormal + epsilon * reflection;<br>    reflectionRay.direction = reflection;<br>    color = colorOfSphere * (ambience + ((1.0 - ambience) * max(0.0, dot(surfaceNormal, lightSource))));<br>    rayTracer.color = color;<br>    rayTracer.reflectedRay = reflectionRay;<br>}</pre><p>I’ve collated all of this into one function called <strong>trace().</strong></p><pre>RayTracerOutput trace(Sphere spheres[NUM_SPHERES], Ray ray, Light light) {<br>    RayTracerOutput rayTracer;<br>    Ray reflectionRay;<br>    Sphere sphereToShow;<br>    float minT = INFINITY;<br>    vec3 cameraSource = ray.origin;<br>    vec3 cameraDirection = ray.direction;<br>    vec3 lightSource = light.position;<br>    float ambience = light.ambience;<br>    vec3 color = vec3(0.0, 0.0, 0.0);</pre><pre>for (int i=0; i &lt; NUM_SPHERES; i++) {<br>        float t = getIntersection(spheres[i], ray);<br>        if (t &gt; 0.0 &amp;&amp; t &lt; minT) {<br>            minT = t;<br>            sphereToShow = spheres[i];<br>        }<br>    }</pre><pre>vec3 sphereCenter = sphereToShow.center;<br>    vec3 colorOfSphere = sphereToShow.color;</pre><pre>if (minT &gt; 0.0 &amp;&amp; minT != INFINITY) {<br>        vec3 surfacePoint = cameraSource + (minT * cameraDirection);<br>        vec3 surfaceNormal = normalize(surfacePoint - sphereCenter);</pre><pre>// Reflection<br>        vec3 reflection = 2.0 * dot(-ray.direction, surfaceNormal) * surfaceNormal + ray.direction;<br>        reflectionRay.origin = surfaceNormal + epsilon * reflection;<br>        reflectionRay.direction = reflection;<br>        color = colorOfSphere * (ambience + ((1.0 - ambience) * max(0.0, dot(surfaceNormal, lightSource))));<br>        rayTracer.color = color;<br>        rayTracer.reflectedRay = reflectionRay;<br>    }<br>    return rayTracer;<br>}</pre><h3>4. Adding reflected color to other spheres.</h3><p>Now all we have to do is call <strong>trace()</strong> with the reflected ray and the same set of spheres. But this time, we are concerned with the color of the sphere that is hit by the reflected ray. We add that color to the original color of the sphere from the first <strong>trace()</strong> call to see reflections. This is how the <strong>main() </strong>function looks.</p><pre>void main() {<br>    initialize();<br>    RayTracer rayTracer = trace(spheres, rays[0], light[0]);<br>    // Second call to get reflections<br>    RayTracer reflection = trace(spheres, rayTracer.reflectedRay, light[0]);<br>    gl_FragColor = vec4(rayTracer.color + reflection.color, 1.0);<br>}</pre><p>We now have a working ray tracer with multiple spheres and reflections!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FLOLr2_WMDKk%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DLOLr2_WMDKk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FLOLr2_WMDKk%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa42d650df81e3711f9fcc9f9eac483/href">https://medium.com/media/4fa42d650df81e3711f9fcc9f9eac483/href</a></iframe><p>If you have any thoughts, suggestions or notice bugs in the code, please leave a comment. You can find the code <a href="https://github.com/neosavvyinc/WebGL/blob/gh-pages/src/html/rayTracing.shapes.html">here</a> and a running version of it <a href="https://neosavvyinc.github.io/WebGL/src/html/rayTracing.shapes.html">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5e52953e2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neosavvy-labs/webgl-2-1-ray-tracing-with-reflections-bd5e52953e2f">WebGL — 2.1 Ray Tracing with reflections</a> was originally published in <a href="https://medium.com/neosavvy-labs">Neosavvy Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebGL — 2.0 Ray Tracing]]></title>
            <link>https://medium.com/neosavvy-labs/webgl-2-0-ray-tracing-34866baca7c1?source=rss-2e00188ad2a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/34866baca7c1</guid>
            <category><![CDATA[neosavvy]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sushindhran Harikrishnan]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 14:02:01 GMT</pubDate>
            <atom:updated>2017-05-16T02:49:57.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLPsQVNuL-BCMDcxcMM00g.png" /><figcaption>Sphere — Ray Tracing</figcaption></figure><p>We’re going to build on the simple vertex and fragment shaders from the <a href="https://medium.com/neosavvy-labs/webgl-1-introduction-to-shaders-b20fa62c7c4">last WebGL post</a> and do something more exciting this time with ray tracing. What is ray tracing? In simple terms, a ray tracing program reproduces the path of light rays in the reverse direction from the camera back to the origin of the rays. <a href="https://www.siggraph.org/education/materials/HyperGraph/raytrace/rtrace1.htm">This article</a> gives a good overview of how ray tracing works.</p><p>So let’s draw a sphere on our screen today using ray tracing. We will define three structures — one each for the sphere, the ray and the light source.</p><pre>struct Sphere {<br>    vec3 center;<br>    float radius;<br>    vec3 color;<br>};<br><br>struct Ray {<br>    vec3 origin;<br>    vec3 direction;<br>};<br><br>struct Light {<br>    vec3 position;<br>    float ambience;<br>    vec3 specular;<br>    vec3 diffuse;<br>};</pre><pre>Sphere spheres[1];<br>Ray rays[1];<br>Light light[1];</pre><h3><strong>1. Initialize Scene</strong></h3><p>Now let’s initialize our scene by defining our sphere, the ray and the light source. We’re creating a red sphere with a radius of 0.7 with it’s center at the origin of the x, y and z axes.</p><pre>spheres[0].center = vec3(0.0, 0.0, 0.0);<br>spheres[0].radius = 0.7;<br>spheres[0].color = vec3(1.0, 0.0, 0.0);</pre><p>Let’s define our light ray with it’s point of origin at (0,0,2), where 2 will be our focal length. The direction of the ray would be the normalized vector (unit vector) for (x-0.5, 0.5-y, -focalLength) assuming x and y ranges from -0.5 to 0.5 on our screen. Note that the the z value is -focalLength for the direction of the ray that is being traced.</p><pre>rays[0].origin = vec3(0.0, 0.0, focalLength);<br>rays[0].direction = normalize(vec3(x-0.5, 0.5-y, -focalLength));</pre><p>For our light source, we are only going to define two properties — position and ambience. We are getting the x and y values for the light position from the cursor. I will explain how we’re setting that up with our shaders in a bit.</p><pre>light[0].position = vec3(uCursor.x, -uCursor.y, 0.9);<br>light[0].ambience = 0.01;</pre><h3>2. Intersection points for the Ray and the Sphere</h3><p>The formula for getting the intersection points for the sphere and the ray is derived by substituting the x, y and z components of the ray into the equation for the sphere. For more details, look at this article <a href="https://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-sphere-intersection">here</a>. I will try and explain the derivation for this in detail in a separate post, but we will essentially have to solve this quadratic equation</p><p><strong><em>A = rayDirection • rayDirection</em></strong></p><p><strong><em>B = 2 * rayDirection • (rayOrigin - sphereCenter)</em></strong></p><p><strong><em>C = (rayOrigin-sphereCenter) • (rayOrigin-sphereCenter)- radius²</em></strong></p><p>where <em>• </em>represents the dot product and<em> </em>the quadratic equation is:</p><p><strong><em>t = (-B ± √B²–4AC) / 2A</em></strong></p><p><strong>A</strong> will be <strong>1.0</strong> since we normalized the ray direction which will be a unit vector. So we arrive at</p><p><strong><em>t = (-B ± √B²–4C) / 2</em></strong></p><p>Here is how that looks in code.</p><pre>vec3 sphereCenter = sphere.center;<br>vec3 colorOfSphere = sphere.color;<br>float radius = sphere.radius;<br>vec3 cameraSource = ray.origin;<br>vec3 cameraDirection = ray.direction;<br>vec3 lightSource = light.position;<br>float ambience = light.ambience;<br>vec3 color = vec3(0.0, 0.0, 0.0);<br><br>vec3 distanceFromCenter = (cameraSource - sphereCenter);<br>float B = 2.0 * dot(cameraDirection, distanceFromCenter);<br>float C = dot(distanceFromCenter, distanceFromCenter) - pow(radius, 2.0);<br>float delta = pow(B, 2.0) - 4.0 * C;</pre><p>The intersection point is the the bigger of the two roots of the quadratic equation. So we have two scenarios — real and equal roots and real and unequal roots. For unequal roots, the value of <strong>t</strong> will be the greater of the two roots.</p><pre>float t = 0.0;<br>if (delta &gt; 0.0) {<br>    float sqRoot = sqrt(delta);<br>    float t1 = (-B + sqRoot) / 2.0;<br>    float t2 = (-B - sqRoot) / 2.0;<br>    t = min(t1, t2);<br>}<br>if (delta == 0.0) {<br>    t = -B / 2.0;<br>}</pre><h3>3. Lambert Shading</h3><p>We are going to treat our sphere as a Lambertian surface, which means that all incoming light is scattered/diffused equally in all directions. Lambertian reflectance is the resultant vector of the surface normal at any given surface point on the sphere and the direction of the light at that point.</p><p>The surface point is a projection on the screen from the camera source/ray origin in a direction. So the surface point can be calculated from the ray equation as follows.</p><pre>vec3 surfacePoint = cameraSource + (t * cameraDirection);</pre><p>The surface normal at a point on the sphere is just the unit vector from the center of the sphere to that point.</p><pre>vec3 surfaceNormal = normalize(surfacePoint - sphereCenter);</pre><p>So now we have everything we need to calculate <a href="https://en.wikipedia.org/wiki/Lambertian_reflectance">Lambertian Reflectance</a>.</p><pre>max(0.0, dot(surfaceNormal, lightSource));</pre><p>There usually is a lot of ambient light in a scene. We can account for that by doing this. Ambience is usually a very low value.</p><pre>(ambience + ((1.0 - ambience) * max(0.0, dot(surfaceNormal, lightSource))));</pre><p>We can now multiply this value with the color of our sphere to get our final color to set as the value for <strong>gl_FragColor</strong>.</p><pre>color = colorOfSphere + (ambience + ((1.0 - ambience) * max(0.0, dot(surfaceNormal, lightSource))));</pre><h3><strong>4. Hooking up mouse events to our shader</strong></h3><p>I tweaked the gl_utils.js file that we used in our first shader lesson to add mouse events. I added this line to the gl_init function, similar to how we define uTime.</p><pre>gl.uCursor = gl.getUniformLocation(program, “uCursor”);</pre><p>We also need to add mouse event listeners to our canvas. I added the following to the start_gl function</p><pre><strong>function </strong>setMouse(z) {<br>    <strong>var </strong>r = event.target.getBoundingClientRect();<br>    gl.cursor.x = (event.clientX - r.left  ) / (r.right - r.left) * 2 - 1;<br>    gl.cursor.y = (event.clientY - r.bottom) / (r.top - r.bottom) * 2 - 1;<br>    <strong>if </strong>(z !== undefined)<br>        gl.cursor.z = z;<br>}<br>canvas.onmousedown = <strong>function</strong>(event) { setMouse(1); } // On mouse down, set z to 1.<br>canvas.onmousemove = <strong>function</strong>(event) { setMouse() ; }<br>canvas.onmouseup   = <strong>function</strong>(event) { setMouse(0); } // On mouse up  , set z to 0<br>gl.cursor = <strong>new </strong>Vector3();</pre><p>Lastly, I added this line to the gl_update function to pass the updated cursor values to the shaders.</p><pre>gl.uniform3f(gl.uCursor, gl.cursor.x, gl.cursor.y, gl.cursor.z); // Set cursor uniform variable.</pre><p>Now we should be all set to fire up our ray tracing program to render a sphere. Click <a href="https://neosavvyinc.github.io/WebGL/src/html/rayTracing.sphere.html">here</a> to see a running version of this. You can check out and download the code from our github repository <a href="https://github.com/neosavvyinc/WebGL">here</a>.</p><p>We will do more ray tracing next time with different shapes and I’ll introduce the phong algorithm along with refections and collisions between these moving shapes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34866baca7c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neosavvy-labs/webgl-2-0-ray-tracing-34866baca7c1">WebGL — 2.0 Ray Tracing</a> was originally published in <a href="https://medium.com/neosavvy-labs">Neosavvy Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebGL — 1. Introduction to shaders]]></title>
            <link>https://medium.com/neosavvy-labs/webgl-1-introduction-to-shaders-b20fa62c7c4?source=rss-2e00188ad2a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b20fa62c7c4</guid>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[shaders]]></category>
            <dc:creator><![CDATA[Sushindhran Harikrishnan]]></dc:creator>
            <pubDate>Thu, 09 Mar 2017 14:02:02 GMT</pubDate>
            <atom:updated>2017-04-04T03:47:30.164Z</atom:updated>
            <content:encoded><![CDATA[<p>My interest in WebGL was recently reignited by my desire for a refresher on my Computer Graphics course at NYU under <a href="http://mrl.nyu.edu/~perlin/">Professor Ken Perlin</a>. My class was the first batch to do this course in WebGL, the previous batches were doing it in Java. I figured that blogging about it would be a good way to keep my motivation levels up, as I relearn/refresh some of those concepts. One blog post for one concept along with some working code is my target. As I always tend to do, I’m starting from the basics.</p><p>So What is WebGL? What are Vertex and Fragment Shaders? WebGL is a Javascript API that is based on OpenGL ES, to render content on HTML canvas. WebGL programs run both vertex shader and fragment shader code that is executed on the Graphics card’s GPU, enabling the CPU to do other work.</p><h3>1. Vertex Shader</h3><p>Consider rendering any primitive 3D shape like a cube that has vertices. The vertex shader takes each one of the vertices and does what it wants with them. But it eventually has to set something called <strong>gl_Position</strong>, a 4D floating point vector, which is the final position of the vertex on the screen. We are essentially taking a 3D position with x, y, z coordinates and projecting it onto a 2D surface. The code for a simple vertex shader would look something like this.</p><pre>&lt;script id=&quot;vs&quot; type=&quot;other&quot;&gt;<br>   attribute vec3 aPosition;<br>   varying   vec3 vPosition;<br>   void main() {<br>      gl_Position = vec4(aPosition, 1.0);<br>      vPosition = aPosition;<br>   }<br>&lt;/script&gt;</pre><h3>2. Fragment Shader</h3><p>Now that we have all the vertices for the object, how do we add lighting, colors and textures? That’s where the fragment shader comes in. The fragment shader can have some logic for all of this, but it eventually has to set something called <strong>gl_FragColor</strong>, another 4D floating point vector, which is the final color of our fragment. Think of fragments as something akin to a vertex that is passed to a vertex shader. A primitive is broken down into discrete elements called fragments in the rasterization process. So if you are drawing a square, a fragment is the data provided by those three vertices to color each pixel within that square. In other words, fragments receive interpolated values from those three vertices. If one vertex is colored blue, and its adjacent vertex is green we would see the color values for the fragments interpolate from green to cyan to blue. We are just assigning the vertex position coordinates to the color vector. Our fragment shader code will look something like this.</p><pre>&lt;script id=&quot;fs&quot; type=&quot;x-shader/x-fragment&quot;&gt;<br>    precision mediump float;<br>    varying vec3 vPosition; // vertex position</pre><pre>    void main() {<br>        float x = vPosition.x;<br>        float y = vPosition.y;<br>        float z = vPosition.z;<br>        vec3 color = vec3(x, y, z);</pre><pre>        // Send final color to output, and add opacity<br>        gl_FragColor = vec4(color, 1.0);<br>   }<br>&lt;/script&gt;</pre><p>The above snippet would produce the same result as this simplified snippet below</p><pre>&lt;script id=&quot;fs&quot; type=&quot;x-shader/x-fragment&quot;&gt;<br>    precision mediump float;<br>    varying vec3 vPosition; // vertex position</pre><pre>    void main() {<br>        vec3 color = vPosition;</pre><pre>        // Send final color to output, and add opacity<br>        gl_FragColor = vec4(color, 1.0);<br>   }<br>&lt;/script&gt;</pre><p>You will see a nice gradient on your WebGL canvas when you run the above code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8dD5NEww4GKAMKNvrUGIw.png" /><figcaption>Gradient for the fragment shader</figcaption></figure><p>To get this working, I had to write some straightforward boilerplate code that I will go over briefly.</p><h3>3. Creating the program and compiling your shaders</h3><p>The program is created by calling <strong>gl.createProgram(). </strong>The shaders are created by calling <strong>gl.createShader(type)</strong>. The type of shader is either <strong>gl.VERTEX_SHADER</strong> or <strong>gl.FRAGMENT_SHADER. </strong>This function creates the shaders, compiles them and attaches them to the program.</p><pre><strong>function </strong>addshader(gl, program, type, src) {<br>    <strong>var </strong>shader = gl.createShader(type);<br>    gl.shaderSource(shader, src);<br>    gl.compileShader(shader);<br>    <strong>if </strong>(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {<br>        <strong>throw </strong>&quot;Cannot compile shader:\n\n&quot; +  gl.getShaderInfoLog(shader);<br>    }<br>    gl.attachShader(program, shader);<br>}</pre><h3>4. Using the program and initializing the buffer</h3><p>After creating the program, adding shaders and linking it, we tell WebGL to use it in subsequent render calls to use the program using <strong>gl.userProgram(program). </strong>Now we want to draw a square on the screen, consisting of two triangles, which serves as the canvas for our fragment shader above.</p><pre>// Create a square as a strip of two triangles.<br>gl.bindBuffer(gl.ARRAY_BUFFER, buffer);<br>gl.bufferData(<br>    gl.ARRAY_BUFFER,<br>    <strong>new </strong>Float32Array([<br>        -1,1,<br>        0,1,<br>        1,0,<br>        -1,-1,<br>        0,1,<br>        -1,0]),<br>    gl.STATIC_DRAW<br>);</pre><h3>5. Passing the vertex data from the buffer to the shaders</h3><p>To render whatever is in the buffer on the screen, we need to tell WebGL to provide the vertex shader with the position data from the buffer we have created above. We do that as follows.</p><pre>gl.aPosition = gl.getAttribLocation(program, &quot;aPosition&quot;);<br>gl.enableVertexAttribArray(gl.aPosition);<br>gl.vertexAttribPointer(gl.aPosition, 3, gl.FLOAT, <strong>false</strong>, 0, 0);</pre><p>I mushed the last few steps together into a function called <strong>gl_init.</strong></p><pre><strong>function </strong>gl_init(gl, vertexShader, fragmentShader) {<br>    <strong>var </strong>program = gl.createProgram();<br>    <strong>var </strong>buffer = gl.createBuffer();<br>    addshader(gl, program, gl.VERTEX_SHADER, vertexShader);<br>    addshader(gl, program, gl.FRAGMENT_SHADER, fragmentShader);<br>    gl.linkProgram(program);</pre><pre>    <strong>if </strong>(! gl.getProgramParameter(program, gl.LINK_STATUS))<br>        <strong>throw </strong>&quot;Could not link the shader program!&quot;;<br>    gl.useProgram(program);</pre><pre>    // Create a square as a strip of two triangles.<br>    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);<br>    gl.bufferData(<br>        gl.ARRAY_BUFFER,<br>        <strong>new </strong>Float32Array([<br>            -1,1,<br>            0,1,<br>            1,0,<br>            -1,-1,<br>            0,1,<br>            -1,0]),<br>        gl.STATIC_DRAW<br>    );</pre><pre>    gl.aPosition = gl.getAttribLocation(program, &quot;aPosition&quot;);<br>    gl.enableVertexAttribArray(gl.aPosition);<br>    gl.vertexAttribPointer(gl.aPosition, 3, gl.FLOAT, <strong>false</strong>, 0, 0);<br>    gl.uTime = gl.getUniformLocation(program, &quot;uTime&quot;);<br>}</pre><h3>6. Drawing on the screen</h3><p>Now we get to the important part. We need to draw these vertices on the screen. <strong>gl.drawArrays() </strong>does that for us.</p><h3>7. Animation</h3><p>We use <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">requestAnimationFrame</a> to call our render function. The number of callbacks is usually 60 times a second. This is a cross-browser way of doing that.</p><pre>requestAnimFrame = (<strong>function</strong>() {<br>    <strong>return </strong>requestAnimationFrame<br>        || webkitRequestAnimationFrame<br>        || mozRequestAnimationFrame<br>        || oRequestAnimationFrame<br>        || msRequestAnimationFrame<br>        || <strong>function</strong>(callback) {<br>               setTimeout(callback, 1000 / 60);<br>           }; })();</pre><p>Our render function would be something like this.</p><pre><strong>function </strong>gl_update(gl) {<br>    gl.uniform1f(gl.uTime, (<strong>new </strong>Date()).getTime() / 1000 - time0);<br>    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);<br>    // Start the next frame<br>    requestAnimFrame(<strong>function</strong>() { gl_update(gl); });<br>}</pre><h3>8. Firing up our program</h3><p>The gl variable we have been passing around until now is nothing but our html canvas element.</p><pre><strong>function </strong>start_gl(canvas_id, vertexShader, fragmentShader) {<br>    // Make sure the browser supports WebGL.<br>    <strong>try </strong>{<br>        <strong>var </strong>canvas = document.getElementById(canvas_id);<br>        <strong>var </strong>gl = canvas.getContext(&quot;experimental-webgl&quot;);<br>    } <strong>catch </strong>(e) {<br>        <strong>throw </strong>&quot;Sorry, your browser does not support WebGL.&quot;;<br>    }</pre><pre>    // Initialize gl. Then start the frame loop.<br>    gl_init(gl, vertexShader, fragmentShader);<br>    gl_update(gl);<br>}</pre><p>Finally, I wrote this small utility function to recurse through the DOM tree and pull out the vertex and fragment shader code from the &lt;script&gt;&lt;/script&gt; tags, which we pass as parameters to <strong>gl_start()</strong>.</p><pre><strong>function </strong>getStringFromDOMElement(id) {<br>    <strong>var </strong>node = document.getElementById(id);</pre><pre>    // Recurse and get all text in the node<br>    <strong>var </strong>recurseThroughDOMNode = <strong>function </strong>recurseThroughDOMNode(childNode, textContext) {<br>        <strong>if </strong>(childNode) {<br>            <strong>if </strong>(childNode.nodeType === 3) {<br>                textContext += childNode.textContent;<br>            }<br>            <strong>return </strong>recurseThroughDOMNode(childNode.nextSibling, textContext);<br>        } <strong>else </strong>{<br>            <strong>return </strong>textContext;<br>        }<br>    };<br>    <strong>return </strong>recurseThroughDOMNode(node.firstChild, &#39;&#39;);<br>}</pre><h3>9. Using time</h3><p>You may have noticed that the <strong>gl_init() </strong>function has this line.</p><pre>gl.uTime = gl.getUniformLocation(program, &quot;uTime&quot;);</pre><p>I’ve modified my fragment shader to use that and produce some crazy animations.</p><pre>&lt;script id=&quot;fs&quot; type=&quot;x-shader/x-fragment&quot;&gt;<br>    precision mediump float;<br>    uniform float uTime;<br>    varying vec3  vPosition;</pre><pre>    void main() {<br>        float x = vPosition.x;<br>        float y = vPosition.y;<br>        float z = vPosition.z;<br>        float xTime = uTime * x/sin(uTime);<br>        float yTime = uTime * y/sin(uTime);<br>        float zTime = uTime * z/sin(uTime);<br>        vec3 color = vec3(sin(xTime), sin(yTime), sin(zTime));<br>        gl_FragColor = vec4(color, 1.0);<br>   }<br>&lt;/script&gt;</pre><p>Click <a href="https://neosavvyinc.github.io/WebGL/src/html/shaders.html">here</a> to see a running version of this. You can check out and download the code from our github repository <a href="https://github.com/neosavvyinc/WebGL">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b20fa62c7c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/neosavvy-labs/webgl-1-introduction-to-shaders-b20fa62c7c4">WebGL — 1. Introduction to shaders</a> was originally published in <a href="https://medium.com/neosavvy-labs">Neosavvy Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>