tag:blogger.com,1999:blog-53303945259861746882024-03-27T14:46:42.946-07:00Graphics, Game Development and Digital ArtWelcome to the enticing world of gaming and graphics.A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.comBlogger197125tag:blogger.com,1999:blog-5330394525986174688.post-53366247824412272742024-03-07T22:05:00.000-08:002024-03-07T22:11:44.385-08:00Create a Texture Online<p> I have been trying to do this online pattern generator using shading language.</p>
Enter a formula:
<form><br />
<br />Red: <input id="red" type="text" /><br />
<br />Green: <input id="green" type="text" /><br />
<br />Blue: <input id="blue" type="text" /><br /><br />
<button type="button">Generate</button>
</form>
Example formulas to enter: <div> (set1)</div><div> r = (0xff)*(x%2);</div><div> g = (0xff)*(y%2); </div><div> b = (0xff);//*(x^y); </div><div><br /></div><div>(set2) </div><div> r = (int)((0xff)*Math.sin(10*x*Math.PI/180));</div><div> g = (0xff);</div><div> b = (0xff);</div>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-22453353424307804292023-01-28T20:45:00.005-08:002023-01-28T20:52:22.566-08:00Sierpinski Gasket in an Android App<p>After making several apps which were not doing anything much but just to know the way android apps are created, sat down to create applications which might be a bit useful.</p><p>First of them, an android app that displays a sierpinski gasket.</p><p>Here is a snap:</p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEi10EkZt7h2o-2iPO_PV9wIP-nRGpfr_JYtfYsIQbECh33h_Fwpcx-yZ6fpQ1zpNF0wTyt0CrGd1W3Q-HcKNexYd3gPjtI8oGNxojPgXSgZP2szLZWrgIh2TKFsTHn4kf5ZE6gSdTzyiXQOfaOlD38R9Ls8nagIVgt4chYYArMoc4jKJUmPkVcKZwRr" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="779" data-original-width="1474" height="211" src="https://blogger.googleusercontent.com/img/a/AVvXsEi10EkZt7h2o-2iPO_PV9wIP-nRGpfr_JYtfYsIQbECh33h_Fwpcx-yZ6fpQ1zpNF0wTyt0CrGd1W3Q-HcKNexYd3gPjtI8oGNxojPgXSgZP2szLZWrgIh2TKFsTHn4kf5ZE6gSdTzyiXQOfaOlD38R9Ls8nagIVgt4chYYArMoc4jKJUmPkVcKZwRr=w400-h211" width="400" /></a></div><br /><br /><p></p><p>This is the autogenerated MainActivity.java with a little modifications:</p><pre style="background-color: #2b2b2b; color: #a9b7c6; font-family: "JetBrains Mono", monospace; font-size: 9.8pt;"><span style="color: #cc7832;">package </span>com.example.mukesh.seirpinskigasketandroid<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">import </span>android.opengl.GLSurfaceView<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>android.support.v7.app.AppCompatActivity<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>android.os.Bundle<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">public class </span>MainActivity <span style="color: #cc7832;">extends </span>AppCompatActivity {<br /> <span style="color: #cc7832;">private </span>GLSurfaceView <span style="color: #9876aa;">mGLView</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: #bbb529;">@Override<br /></span><span style="color: #bbb529;"> </span><span style="color: #cc7832;">protected void </span><span style="color: #ffc66d;">onCreate</span>(Bundle savedInstanceState) {<br /> <span style="color: #cc7832;">super</span>.onCreate(savedInstanceState)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">mGLView </span>= <span style="color: #cc7832;">new </span>MyGLSurfaceView(<span style="color: #cc7832;">this</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>setContentView(<span style="color: #9876aa;">mGLView</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br />}</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt;"><span style="background-color: white;">Next up the MyGLSurfaceView.java class</span></pre><pre><pre><div style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: left;"><pre style="background-color: #2b2b2b; color: #a9b7c6; font-family: "JetBrains Mono", monospace; font-size: 9.8pt;"><span style="color: #cc7832;">package </span>com.example.mukesh.seirpinskigasketandroid<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">import </span>android.content.Context<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>android.opengl.GLSurfaceView<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">public class </span>MyGLSurfaceView <span style="color: #cc7832;">extends </span>GLSurfaceView {<br /> <span style="color: #cc7832;">private final </span>MyGLRenderer <span style="color: #9876aa;">mRenderer</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> public </span><span style="color: #ffc66d;">MyGLSurfaceView</span>(Context context) {<br /> <span style="color: #cc7832;">super</span>(context)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Create an OpenGL ES 2.0 context<br /></span><span style="color: grey;"> </span>setEGLContextClientVersion(<span style="color: #6897bb;">2</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">mRenderer </span>= <span style="color: #cc7832;">new </span>MyGLRenderer()<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Set the Renderer for drawing on the GLSurfaceView<br /></span><span style="color: grey;"> </span>setRenderer(<span style="color: #9876aa;">mRenderer</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Render the view only when there is a change in the drawing data<br /></span><span style="color: grey;"> </span>setRenderMode(GLSurfaceView.<span style="color: #9876aa; font-style: italic;">RENDERMODE_WHEN_DIRTY</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br />}</pre></div><div style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: left;"><br /></div></pre></pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;"><span style="background-color: white;">Next the MyGlRenderer.java class</span></pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;"><pre style="background-color: #2b2b2b; color: #a9b7c6; font-family: "JetBrains Mono", monospace; font-size: 9.8pt;"><span style="color: #cc7832;">package </span>com.example.mukesh.seirpinskigasketandroid<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">import </span>android.opengl.GLES20<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>android.opengl.GLSurfaceView<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">import </span>javax.microedition.khronos.egl.EGLConfig<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>javax.microedition.khronos.opengles.GL10<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">public class </span>MyGLRenderer <span style="color: #cc7832;">implements </span>GLSurfaceView.Renderer {<br /> <span style="color: #cc7832;">private </span>Triangle <span style="color: #9876aa;">mTriangle</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: #bbb529;">@Override<br /></span><span style="color: #bbb529;"> </span><span style="color: #cc7832;">public void </span><span style="color: #ffc66d;">onSurfaceCreated</span>(GL10 gl10<span style="color: #cc7832;">, </span>EGLConfig eglConfig) {<br /> GLES20.<span style="font-style: italic;">glClearColor</span>(<span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">1.0f</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// initialize a triangle<br /></span><span style="color: grey;"> </span><span style="color: #9876aa;">mTriangle </span>= <span style="color: #cc7832;">new </span>Triangle()<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// initialize a square<br /></span><span style="color: grey;"> </span>}<br /><br /> <span style="color: #bbb529;">@Override<br /></span><span style="color: #bbb529;"> </span><span style="color: #cc7832;">public void </span><span style="color: #ffc66d;">onSurfaceChanged</span>(GL10 gl10<span style="color: #cc7832;">, int </span>width<span style="color: #cc7832;">, int </span>height) {<br /> GLES20.<span style="font-style: italic;">glViewport</span>(<span style="color: #6897bb;">0</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0</span><span style="color: #cc7832;">, </span>width<span style="color: #cc7832;">, </span>height)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br /><br /> <span style="color: #bbb529;">@Override<br /></span><span style="color: #bbb529;"> </span><span style="color: #cc7832;">public void </span><span style="color: #ffc66d;">onDrawFrame</span>(GL10 gl10) {<br /> GLES20.<span style="font-style: italic;">glClear</span>(GLES20.<span style="color: #9876aa; font-style: italic;">GL_COLOR_BUFFER_BIT</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">mTriangle</span>.draw()<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br /> <span style="color: #cc7832;">public static int </span><span style="color: #ffc66d;">loadShader</span>(<span style="color: #cc7832;">int </span>type<span style="color: #cc7832;">, </span>String shaderCode){<br /><br /> <span style="color: grey;">// create a vertex shader type (GLES20.GL_VERTEX_SHADER)<br /></span><span style="color: grey;"> // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)<br /></span><span style="color: grey;"> </span><span style="color: #cc7832;">int </span>shader = GLES20.<span style="font-style: italic;">glCreateShader</span>(type)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// add the source code to the shader and compile it<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glShaderSource</span>(shader<span style="color: #cc7832;">, </span>shaderCode)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>GLES20.<span style="font-style: italic;">glCompileShader</span>(shader)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> return </span>shader<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br />}<br /></pre></pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;">Next is the Triangle.java class</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;"><pre style="background-color: #2b2b2b; color: #a9b7c6; font-family: "JetBrains Mono", monospace; font-size: 9.8pt;"><span style="color: #cc7832;">package </span>com.example.mukesh.seirpinskigasketandroid<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">import </span>android.opengl.GLES20<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">import </span>java.nio.ByteBuffer<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>java.nio.ByteOrder<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;">import </span>java.nio.FloatBuffer<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;">public class </span>Triangle {<br /> <span style="color: #cc7832;">private final int </span><span style="color: #9876aa;">mProgram</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> private </span>FloatBuffer <span style="color: #9876aa;">vertexBuffer</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// number of coordinates per vertex in this array<br /></span><span style="color: grey;"> </span><span style="color: #cc7832;">static final int </span><span style="color: #9876aa; font-style: italic;">COORDS_PER_VERTEX </span>= <span style="color: #6897bb;">3</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> static float </span><span style="color: #9876aa; font-style: italic;">triangleCoords</span>[] = { <span style="color: grey;">// in counterclockwise order:<br /></span><span style="color: grey;"> </span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.622008459f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">, </span><span style="color: grey;">// top<br /></span><span style="color: grey;"> </span>-<span style="color: #6897bb;">0.5f</span><span style="color: #cc7832;">, </span>-<span style="color: #6897bb;">0.311004243f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">, </span><span style="color: grey;">// bottom left<br /></span><span style="color: grey;"> </span><span style="color: #6897bb;">0.5f</span><span style="color: #cc7832;">, </span>-<span style="color: #6897bb;">0.311004243f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.0f </span><span style="color: grey;">// bottom right<br /></span><span style="color: grey;"> </span>}<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> float </span><span style="color: #9876aa;">v</span>[][]={{-<span style="color: #6897bb;">1.0f</span><span style="color: #cc7832;">,</span>-<span style="color: #6897bb;">0.5f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span>}<span style="color: #cc7832;">,</span>{<span style="color: #6897bb;">1.0f</span><span style="color: #cc7832;">,</span>-<span style="color: #6897bb;">0.5f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span>}<span style="color: #cc7832;">,<br /></span><span style="color: #cc7832;"> </span>{<span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">1.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span>}}<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> float </span><span style="color: #9876aa;">colors</span>[][]={{<span style="color: #6897bb;">1.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span>}<span style="color: #cc7832;">,</span>{<span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">1.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span>}<span style="color: #cc7832;">,</span>{<span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">1.0f</span>}<span style="color: #cc7832;">,</span>{<span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span><span style="color: #cc7832;">,</span><span style="color: #6897bb;">0.0f</span>}}<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> int </span><span style="color: #9876aa;">n</span>=<span style="color: #6897bb;">5</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> int </span><span style="color: #9876aa;">vc1</span>=<span style="color: #6897bb;">0</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Set color with red, green, blue and alpha (opacity) values<br /></span><span style="color: grey;"> </span><span style="color: #cc7832;">float </span><span style="color: #9876aa;">color</span>[] = { <span style="color: #6897bb;">0.63671875f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.76953125f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0.22265625f</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">1.0f </span>}<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> public </span><span style="color: #ffc66d;">Triangle</span>() {<br /> <span style="color: grey;">// initialize vertex byte buffer for shape coordinates<br /></span><span style="color: grey;"> </span>ByteBuffer bb = ByteBuffer.<span style="font-style: italic;">allocateDirect</span>(<br /> <span style="color: grey;">// (number of coordinate values * 4 bytes per float)<br /></span><span style="color: grey;"> </span><span style="color: #6897bb;">10000</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// use the device hardware's native byte order<br /></span><span style="color: grey;"> </span>bb.order(ByteOrder.<span style="font-style: italic;">nativeOrder</span>())<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// create a floating point buffer from the ByteBuffer<br /></span><span style="color: grey;"> </span><span style="color: #9876aa;">vertexBuffer </span>= bb.asFloatBuffer()<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// add the coordinates to the FloatBuffer<br /></span><span style="color: grey;"> //vertexBuffer.put(triangleCoords);<br /></span><span style="color: grey;"> // set the buffer to read the first coordinate<br /></span><span style="color: grey;"><br /></span><span style="color: grey;"> </span>divide_tetra(<span style="color: #9876aa;">vertexBuffer</span><span style="color: #cc7832;">,</span><span style="color: #9876aa;">v</span>[<span style="color: #6897bb;">0</span>]<span style="color: #cc7832;">,</span><span style="color: #9876aa;">v</span>[<span style="color: #6897bb;">1</span>]<span style="color: #cc7832;">,</span><span style="color: #9876aa;">v</span>[<span style="color: #6897bb;">2</span>]<span style="color: #cc7832;">,</span><span style="color: #9876aa;">n</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">vertexBuffer</span>.position(<span style="color: #6897bb;">0</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> int </span>vertexShader = MyGLRenderer.<span style="font-style: italic;">loadShader</span>(GLES20.<span style="color: #9876aa; font-style: italic;">GL_VERTEX_SHADER</span><span style="color: #cc7832;">,<br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">vertexShaderCode</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> int </span>fragmentShader = MyGLRenderer.<span style="font-style: italic;">loadShader</span>(GLES20.<span style="color: #9876aa; font-style: italic;">GL_FRAGMENT_SHADER</span><span style="color: #cc7832;">,<br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">fragmentShaderCode</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// create empty OpenGL ES Program<br /></span><span style="color: grey;"> </span><span style="color: #9876aa;">mProgram </span>= GLES20.<span style="font-style: italic;">glCreateProgram</span>()<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// add the vertex shader to program<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glAttachShader</span>(<span style="color: #9876aa;">mProgram</span><span style="color: #cc7832;">, </span>vertexShader)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// add the fragment shader to program<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glAttachShader</span>(<span style="color: #9876aa;">mProgram</span><span style="color: #cc7832;">, </span>fragmentShader)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// creates OpenGL ES program executables<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glLinkProgram</span>(<span style="color: #9876aa;">mProgram</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br /> <span style="color: #cc7832;">void </span><span style="color: #ffc66d;">triangle</span>(FloatBuffer fb<span style="color: #cc7832;">,float </span>a[]<span style="color: #cc7832;">,float </span>b[]<span style="color: #cc7832;">,float </span>c[])<br /> {<br /><br /> fb.put(a)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span>fb.put(b)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span>fb.put(c)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">vc1</span>++<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br /><br /><br /> <span style="color: #cc7832;">void </span><span style="color: #ffc66d;">divide_tetra</span>(FloatBuffer fb<span style="color: #cc7832;">,float </span>a[]<span style="color: #cc7832;">,float </span>b[]<span style="color: #cc7832;">,float </span>c[]<span style="color: #cc7832;">,int </span>m)<br /> {<br /> <span style="color: #cc7832;">float </span>v1[]=<span style="color: #cc7832;">new float</span>[<span style="color: #6897bb;">3</span>]<span style="color: #cc7832;">,</span>v2[]=<span style="color: #cc7832;">new float</span>[<span style="color: #6897bb;">3</span>]<span style="color: #cc7832;">,</span>v3[]=<span style="color: #cc7832;">new float</span>[<span style="color: #6897bb;">3</span>]<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> int </span>j<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> if</span>(m><span style="color: #6897bb;">0</span>)<br /> { <span style="color: grey;">/*compute three midpoints*/<br /></span><span style="color: grey;"> </span><span style="color: #cc7832;">for</span>(j=<span style="color: #6897bb;">0</span><span style="color: #cc7832;">;</span>j<<span style="color: #6897bb;">3</span><span style="color: #cc7832;">;</span>j++)<br /> v1[j]=(a[j]+b[j])/<span style="color: #6897bb;">2</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> for</span>(j=<span style="color: #6897bb;">0</span><span style="color: #cc7832;">;</span>j<<span style="color: #6897bb;">3</span><span style="color: #cc7832;">;</span>j++)<br /> v2[j]=(a[j]+c[j])/<span style="color: #6897bb;">2</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> for</span>(j=<span style="color: #6897bb;">0</span><span style="color: #cc7832;">;</span>j<<span style="color: #6897bb;">3</span><span style="color: #cc7832;">;</span>j++)<br /> v3[j]=(c[j]+b[j])/<span style="color: #6897bb;">2</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span>divide_tetra(fb<span style="color: #cc7832;">,</span>a<span style="color: #cc7832;">,</span>v2<span style="color: #cc7832;">,</span>v1<span style="color: #cc7832;">,</span>m-<span style="color: #6897bb;">1</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>divide_tetra(fb<span style="color: #cc7832;">,</span>c<span style="color: #cc7832;">,</span>v3<span style="color: #cc7832;">,</span>v2<span style="color: #cc7832;">,</span>m-<span style="color: #6897bb;">1</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>divide_tetra(fb<span style="color: #cc7832;">,</span>b<span style="color: #cc7832;">,</span>v1<span style="color: #cc7832;">,</span>v3<span style="color: #cc7832;">,</span>m-<span style="color: #6897bb;">1</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span>}<br /> <span style="color: #cc7832;">else<br /></span><span style="color: #cc7832;"> </span>triangle(fb<span style="color: #cc7832;">, </span>a<span style="color: #cc7832;">, </span>b<span style="color: #cc7832;">, </span>c)<span style="color: #cc7832;">; </span><span style="color: grey;">//draw triangle at end of recursion//<br /></span><span style="color: grey;"> </span>}<br /><br /><br /> <span style="color: #cc7832;">private final </span>String <span style="color: #9876aa;">vertexShaderCode </span>=<br /> <span style="color: #6a8759;">"attribute vec4 vPosition;" </span>+<br /> <span style="color: #6a8759;">"void main() {" </span>+<br /> <span style="color: #6a8759;">" gl_Position = vPosition;" </span>+<br /> <span style="color: #6a8759;">"}"</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> private final </span>String <span style="color: #9876aa;">fragmentShaderCode </span>=<br /> <span style="color: #6a8759;">"precision mediump float;" </span>+<br /> <span style="color: #6a8759;">"uniform vec4 vColor;" </span>+<br /> <span style="color: #6a8759;">"void main() {" </span>+<br /> <span style="color: #6a8759;">" gl_FragColor = vColor;" </span>+<br /> <span style="color: #6a8759;">"}"</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> private int </span><span style="color: #9876aa;">mPositionHandle</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> private int </span><span style="color: #9876aa;">mColorHandle</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> private final int </span><span style="color: #9876aa;">vertexCount </span>= <span style="color: #9876aa; font-style: italic;">triangleCoords</span>.<span style="color: #9876aa;">length </span>/ <span style="color: #9876aa; font-style: italic;">COORDS_PER_VERTEX</span><span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> private final int </span><span style="color: #9876aa;">vertexStride </span>= <span style="color: #9876aa; font-style: italic;">COORDS_PER_VERTEX </span>*<span style="color: #6897bb;">4</span><span style="color: #cc7832;">; </span><span style="color: grey;">// 4 bytes per vertex<br /></span><span style="color: grey;"><br /></span><span style="color: grey;"> </span><span style="color: #cc7832;">public void </span><span style="color: #ffc66d;">draw</span>() {<br /> <span style="color: grey;">// Add program to OpenGL ES environment<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glUseProgram</span>(<span style="color: #9876aa;">mProgram</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// get handle to vertex shader's vPosition member<br /></span><span style="color: grey;"> </span><span style="color: #9876aa;">mPositionHandle </span>= GLES20.<span style="font-style: italic;">glGetAttribLocation</span>(<span style="color: #9876aa;">mProgram</span><span style="color: #cc7832;">, </span><span style="color: #6a8759;">"vPosition"</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Enable a handle to the triangle vertices<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glEnableVertexAttribArray</span>(<span style="color: #9876aa;">mPositionHandle</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Prepare the triangle coordinate data<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glVertexAttribPointer</span>(<span style="color: #9876aa;">mPositionHandle</span><span style="color: #cc7832;">, </span><span style="color: #9876aa; font-style: italic;">COORDS_PER_VERTEX</span><span style="color: #cc7832;">,<br /></span><span style="color: #cc7832;"> </span>GLES20.<span style="color: #9876aa; font-style: italic;">GL_FLOAT</span><span style="color: #cc7832;">, false,<br /></span><span style="color: #cc7832;"> </span><span style="color: #9876aa;">vertexStride</span><span style="color: #cc7832;">, </span><span style="color: #9876aa;">vertexBuffer</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// get handle to fragment shader's vColor member<br /></span><span style="color: grey;"> </span><span style="color: #9876aa;">mColorHandle </span>= GLES20.<span style="font-style: italic;">glGetUniformLocation</span>(<span style="color: #9876aa;">mProgram</span><span style="color: #cc7832;">, </span><span style="color: #6a8759;">"vColor"</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Set color for drawing the triangle<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glUniform4fv</span>(<span style="color: #9876aa;">mColorHandle</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">1</span><span style="color: #cc7832;">, </span><span style="color: #9876aa;">color</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Draw the triangle<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glDrawArrays</span>(GLES20.<span style="color: #9876aa; font-style: italic;">GL_TRIANGLES</span><span style="color: #cc7832;">, </span><span style="color: #6897bb;">0</span><span style="color: #cc7832;">,</span><span style="color: #9876aa;">vc1</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"><br /></span><span style="color: #cc7832;"> </span><span style="color: grey;">// Disable vertex array<br /></span><span style="color: grey;"> </span>GLES20.<span style="font-style: italic;">glDisableVertexAttribArray</span>(<span style="color: #9876aa;">mPositionHandle</span>)<span style="color: #cc7832;">;<br /></span><span style="color: #cc7832;"> </span>}<br />}<br /></pre></pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;">Several things need to be done majorly:</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;">Creating the run/Debug configurations and selecting the emulator device.</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;">This is how the output looks like:</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhmfDczX0Mph7r_Dhz0jpfLrtzsTmc-OENv9rqSB2d6HCh-dFbpbdTO0ywIxSbVuaxpUXJazHIOIGnglL4cNbpMvv9b21UtSxm_HXCIR0NgQBoAIk_KP7NQt1LYt_-A_669doRcq7HJJzozT7Um72GTky5G6FYY3jOZyR5wyKMF9to6kbbhYnvIuvlu" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="1055" data-original-width="655" height="240" src="https://blogger.googleusercontent.com/img/a/AVvXsEhmfDczX0Mph7r_Dhz0jpfLrtzsTmc-OENv9rqSB2d6HCh-dFbpbdTO0ywIxSbVuaxpUXJazHIOIGnglL4cNbpMvv9b21UtSxm_HXCIR0NgQBoAIk_KP7NQt1LYt_-A_669doRcq7HJJzozT7Um72GTky5G6FYY3jOZyR5wyKMF9to6kbbhYnvIuvlu" width="149" /></a></div><br />for n=4 the triangle subdivision is upto 3 levels and here is how it looks like:</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgquloDWbTpw0KDIEXQ-6-7sx4EG_6CEq4HdCBmh3KxV5sZHU7z8h5LfvmXDXdQeLUFh3iqu-mfJyv-_jPFcDWqF7pPQo12hPvR_9XMvtdJcFKGlypqbLycCNpjfw4eM9pB8FaFw9eLrB7y-GkoJGVm185LkynHz0kL5uKYIBSDvmvxR_LqyKKFlE8l" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="795" data-original-width="418" height="240" src="https://blogger.googleusercontent.com/img/a/AVvXsEgquloDWbTpw0KDIEXQ-6-7sx4EG_6CEq4HdCBmh3KxV5sZHU7z8h5LfvmXDXdQeLUFh3iqu-mfJyv-_jPFcDWqF7pPQo12hPvR_9XMvtdJcFKGlypqbLycCNpjfw4eM9pB8FaFw9eLrB7y-GkoJGVm185LkynHz0kL5uKYIBSDvmvxR_LqyKKFlE8l" width="126" /></a></div>for n=3 the subdivisions are:</pre><pre style="font-family: "JetBrains Mono", monospace; font-size: 9.8pt; text-align: justify;"><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEhl3P0gmgTfkF7Z-VcmyLuJbJfWyG1zMbF4QAfSst8upAOU-HVHyvRwf1A_7GAyXHbA6Wg5Nz1K3uDxNmzcsONhF5ulL7M31jgt-zSngo2n_QUXdVDuCWrz5kQNnaFRvx38q7fqaHPi_9EgIVz3AIg0Npv0Lhh8peqFvWBomUY2x_nrS7QCJpGlbP-2" style="margin-left: 1em; margin-right: 1em;"><img alt="" data-original-height="772" data-original-width="418" height="240" src="https://blogger.googleusercontent.com/img/a/AVvXsEhl3P0gmgTfkF7Z-VcmyLuJbJfWyG1zMbF4QAfSst8upAOU-HVHyvRwf1A_7GAyXHbA6Wg5Nz1K3uDxNmzcsONhF5ulL7M31jgt-zSngo2n_QUXdVDuCWrz5kQNnaFRvx38q7fqaHPi_9EgIVz3AIg0Npv0Lhh8peqFvWBomUY2x_nrS7QCJpGlbP-2" width="130" /></a></div><br />Thank you!!</pre><pre style="text-align: justify;"><span style="font-family: JetBrains Mono, monospace;"><span style="font-size: 13.0667px;"><a href="https://github.com/bmkamath2000/mukBoApps/tree/main/SeirpinskiGasketAndroid">https://github.com/bmkamath2000/mukBoApps/tree/main/SeirpinskiGasketAndroid</a></span></span></pre>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com1tag:blogger.com,1999:blog-5330394525986174688.post-28294455339385940922021-12-02T04:08:00.000-08:002021-12-02T04:08:18.298-08:00Stupidest Project I had ever laid my hands on<p> I need to get this out and out pretty quickly.</p><p>If blogging is a way of venting ones frustrations then so be it. I thought why would people be interested in my rants and deduced that they might like reading it if I act Stupid and Dumb.</p><p>From my experiences as a rickety software writer, I have come to believe that there exists a class of projects that lie at the border between the possible and the impossible.</p><p>No extra points for failing in a software project. But see my teachers were making it a point to force me to write the purpose I was writing a code for at the start of the program.</p><p>It used to be like:</p><p><b>"WAP to display the first n fibonacci numbers in the fibonacci series"</b></p><p>I never questioned them and being an obedient student followed every bit of instruction given.</p><p>Now no one writes code that does nothing and its presumed that people are into coding to do useful stuff.</p><p>But I never found anything interesting or useful in the series we generated.</p><p>Not that it mattered as long as we got those elusive extra marks.</p><p>Coming to the main topic of this post:</p><p>THE most stupid project I have ever laid my hands on that seemed to be at the border of the possible/impossible is <b>VISUAL PROGRAMMING</b></p><p>My advice to people dreaming of such things is to stop doing that and get real.</p><p>I in fact gave a seminar on this topic in my post graduation. Literature was hard to come by. There were classifications of programming languages. But not visual programming languages.</p><p>I hybridized literature that spoke about Programming by Example with some obscure software called Pygmalion. I also looked at some radically new ways of representing program execution and data.</p><p>I spoke on recording user actions as done in macros. I spoke of showing program actions by animation and representing data as visual elements such as boxes.</p><p>Finally when it came to implementation It never came to fruition. Post graduation is where you get your ideas tested and the feedback that I got from <b>Dr. Dobbs journal editor</b> can be summarized in one word: <span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span></p><p><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span> </span><span style="font-size: x-large;">"Interesting"</span></p><p><br /></p><p>Would like some comments if it helps clarify.. Don't know what use this technology, if I may call it that, might be put to use in. In light of recent developments in AR/VR and HMD may be its got some real uses in program debugging or tools to represent program visually so that programming errors become evident. It could also help in cases where programmer needs help to visualize complex data structures.</p>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-74342557106692028862021-11-23T02:18:00.098-08:002021-11-23T21:51:23.265-08:00Polyline Tweening in Javascript Canvas<p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://images-na.ssl-images-amazon.com/images/I/51bQ2Xjjs1L._SX384_BO1,204,203,200_.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="499" data-original-width="386" height="232" src="https://images-na.ssl-images-amazon.com/images/I/51bQ2Xjjs1L._SX384_BO1,204,203,200_.jpg" width="219" /></a></div>Excerpts from Computer Graphics using OpenGL by F S Hill Jr and Stephen M Kelly<p></p>Interesting tweens can be created that show one figure being tweened into another.<div>Its simplest if the two figures are polylines based on the same number of points.</div><div>Suppose if the first figure is based on the polyline A<span style="font-size: x-small;">i, </span>and the second polyline B is based on points B<span style="font-size: x-small;">i</span>, for i=0,.......,n-1</div><div>we can form a polyline P(t), called the tween at time t by forming the points</div><div>P<span style="font-size: x-small;">i</span>(t) = (1 - t) Ai + t B<span style="font-size: x-small;">i</span></div><div>if we look at the succession of values for t between 0 and 1, say t=0.0,0.1,0.2.... ,0.9,1.0</div><div>we see that this polyline begins with the shape of A and ends with the shape of B, but in-between it is a blend of shapes between A and B.</div><div><p><a href="https://books.google.co.in/books/about/Computer_Graphics.html?id=ffkYAQAAIAAJ&redir_esc=y" target="_blank">Here</a> is a link to google books for the said pages in the this book.</p>
<canvas height="200px" id="tweenPoly" width="200px"></canvas>
<script>
var t=0,dir=0.01;
let myVar = setInterval(myTimer, 100);
var canvas = document.getElementById('tweenPoly'),
ctx = canvas.getContext('2d');
var xarray = [0,0,50,100,100,75,75,25,25,0];
var yarray = [0,50,100,50,0,0,40,40,0,0];
var xarrayTree = [30,30,0,0,50,100,100,70,70,30];
var yarrayTree = [0,75,75,100,100,100,75,75,0,0];
ctx.lineWidth = 1.5;
ctx.strokeStyle = 'red';
ctx.transform(1, 0, 0, -1, 0, canvas.height)
function myTimer() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for (var i = 0; i < 10; i++)
{
ctx.lineTo((1-t)*xarray[i]+t*xarrayTree[i], (1-t)*yarray[i]+t*yarrayTree[i]);
}
ctx.stroke();
t = t + dir;
if(t>1.0) dir=-dir;
if(t<0) dir = -dir;
}
</script></div>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-61041044938843292092021-05-10T04:51:00.025-07:002021-05-10T05:37:34.514-07:00Can you create svg graphic from obj filesI was wondering if you can create a scalable vector graphic(svg) from things that we usually draw in opengl, like for example loading a model.<div><br /></div><div>Looks like someone has already tried this. I am showing his work of art and giving a link to his page.
<div><br /></div><div>Here is a simple SVG graphic that is a 3D cube rotated with buttons.</div></div>
<div>
<br />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript">
let svgDocument = null;
edges = [[0,1],[2,3],[0,2],[1,3],[4,5],[6,7],[4,6],[5,7],[0,4],[1,5],[2,6],[3,7]]
x_coords = [50,190,50,190,50,190,50,190];
y_coords = [50,50,190,190,50,50,190,190];
z_coords = [50,50,50,50,190,190,190,190];
centre_x = 120;
centre_y = 120;
centre_z = 120;
function init(evt)
{
if ( svgDocument == null )
{
svgDocument =document.querySelector('#svgdoc');
}
drawBox();
}
function drawBox()
{
for(var i=0; i<edges.length; i++)
{
edge = document.querySelector('#edge-'+i);
edge.setAttributeNS(null, 'x1', x_coords[edges[i][0]]);
edge.setAttributeNS(null, 'x2', x_coords[edges[i][1]]);
edge.setAttributeNS(null, 'y1', y_coords[edges[i][0]]);
edge.setAttributeNS(null, 'y2', y_coords[edges[i][1]]);
}
}
function rotateAboutX(radians)
{
for(var i=0; i<x_coords.length; i++)
{
y = y_coords[i] - centre_y;
z = z_coords[i] - centre_z;
d = Math.sqrt(y*y + z*z);
theta = Math.atan2(y, z) + radians;
y_coords[i] = centre_y + d * Math.sin(theta);
z_coords[i] = centre_z + d * Math.cos(theta);
}
drawBox();
}
function rotateAboutY(radians)
{
for(var i=0; i<x_coords.length; i++)
{
x = x_coords[i] - centre_x;
z = z_coords[i] - centre_z;
d = Math.sqrt(x*x + z*z);
theta = Math.atan2(x, z) + radians;
x_coords[i] = centre_x + d * Math.sin(theta);
z_coords[i] = centre_z + d * Math.cos(theta);
}
drawBox();
}
function beginRotateX(radians)
{
rotateAboutX(radians);
rotateX_timeout = setInterval("rotateAboutX(" + radians + ")", 20);
}
function endRotateX()
{
if (typeof(rotateX_timeout) != "undefined")
{
clearTimeout(rotateX_timeout);
}
}
function beginRotateY(radians)
{
rotateAboutY(radians);
rotateY_timeout = setInterval("rotateAboutY(" + radians + ")", 20);
}
function endRotateY()
{
if (typeof(rotateY_timeout) != "undefined")
{
clearTimeout(rotateY_timeout);
}
}
</script>
<div id="svgdoc">
<section >
<svg onload="init(evt)" viewbox="0 0 280 280" >
<style>
.edge{
fill: white;
stroke: black;
stroke-width: 1;
}
.button{
fill: #2060dd;
stroke: #2580ff;
stroke-width: 1;
}
.button:hover{
stroke-width: 3;
}
</style>
<line class="edge" id="edge-0" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-1" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-2" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-3" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-4" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-5" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-6" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-7" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-8" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-9" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-10" x1="100" x2="100" y1="100" y2="100"></line>
<line class="edge" id="edge-11" x1="100" x2="100" y1="100" y2="100"></line>
<path class="button" d="m50.5 250.5 15 -15 0 8 45 0 0 14 -45 0 0 8 z" onmousedown="beginRotateY(0.08)" onmouseout="endRotateY()" onmouseup="endRotateY()"></path>
<path class="button" d="m190.5 250.5 -15 -15 0 8 -45 0 0 14 45 0 0 8 z" onmousedown="beginRotateY(-0.08)" onmouseout="endRotateY()" onmouseup="endRotateY()"></path>
<path class="button" d="m255.5 50.5 15 15 -8 0 0 45 -14 0 0 -45 -8 0 z" onmousedown="beginRotateX(0.08)" onmouseout="endRotateX()" onmouseup="endRotateX()"></path>
<path class="button" d="m255.5 190.5 15 -15 -8 0 0 -45 -14 0 0 45 -8 0 z" onmousedown="beginRotateX(-0.08)" onmouseout="endRotateX()" onmouseup="endRotateX()"></path>
</svg>
</section>
</div>
</div><div><br /></div><div><br /></div><div>This is a 3D animation with a triangle hanging from a balance.</div><div><br /></div><div><a href="https://www.petercollingridge.co.uk/blog/3d-svg/3d-animation-svg/">https://www.petercollingridge.co.uk/blog/3d-svg/3d-animation-svg/</a></div><div><br /></div><div>Inspiring work indeed.</div>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com1tag:blogger.com,1999:blog-5330394525986174688.post-78754758833445756702020-12-05T00:54:00.002-08:002020-12-05T00:58:38.413-08:00Introduction to Three.js<p>
Three.JS is a graphics framework/library that can render into canvas/svg/webgl contexts.
The library has powerful capabilities to display complex 3D scenes with multiple models/camera/lights in it.
I will demonstrate a program that rotates a cube continuously.
I will attach event handlers to stop rotation when mouse or finger touch/click event happens.
</p>
<style>
#c {
width: 100%;
height: 100%;
display: block;
}
</style>
<canvas id="c1"></canvas>
<script type="module" type="text/javascript">
var globalpause=0;
function pauseAnim()
{
if(globalpause===0)
globalpause=1;
else globalpause=0;
}
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/build/three.module.js';
var scene = new THREE.Scene();
const canvas = document.querySelector('#c1');
var camera = new THREE.PerspectiveCamera( 25, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 4;
const renderer = new THREE.WebGLRenderer({canvas});
renderer.setClearColor("#0fff00");
//renderer.setSize( window.innerWidth, window.innerHeight );
document.getElementById("c1").addEventListener("click", pauseAnim);
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: "#433F81" } );
var cube = new THREE.Mesh( geometry, material );
// Add cube to Scene
scene.add( cube );
// Render Loop
var render = function () {
requestAnimationFrame( render );
if(globalpause===0)
{cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
}
// Render the scene
renderer.render(scene, camera);
};
render();
</script> A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-59979835862412817202020-12-04T20:42:00.001-08:002021-11-25T08:45:36.713-08:00Qt / QML - a tool for modern application programming<div class="separator" style="clear: both; text-align: center;"><a href="https://e7.pngegg.com/pngimages/15/119/png-clipart-qt-creator-qml-qt-quick-syntax-highlighting-visual-miscellaneous-text.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="800" data-original-width="679" height="320" src="https://e7.pngegg.com/pngimages/15/119/png-clipart-qt-creator-qml-qt-quick-syntax-highlighting-visual-miscellaneous-text.png" width="272" /></a></div><br /><p><br /></p><p> Qt and QML are tools that can increase productivity of application development big time. Qt is a framework consisting of C++ libraries that can do almost everything conceivable as far as app development is concerned. It can even create android/ios applications.</p><p><br /></p><p><br /></p><p><br /></p><p><br /></p><p><br /></p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://w7.pngwing.com/pngs/333/887/png-transparent-logo-qt-creator-computer-programming-software-framework-linux-text-logo-computer-programming.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="408" data-original-width="800" height="163" src="https://w7.pngwing.com/pngs/333/887/png-transparent-logo-qt-creator-computer-programming-software-framework-linux-text-logo-computer-programming.png" width="320" /></a></div><br /> Qt Creator is the IDE you can use to develop Qt/QML applications.<div class="separator" style="clear: both; text-align: center;"><a href="https://process.fs.teachablecdn.com/ADNupMnWyR7kCWRvm76Laz/resize=width:705/https://www.filepicker.io/api/file/Kw3CPmJkR7OGjyDC15r6" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://process.fs.teachablecdn.com/ADNupMnWyR7kCWRvm76Laz/resize=width:705/https://www.filepicker.io/api/file/Kw3CPmJkR7OGjyDC15r6" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><br /></a><a href="https://process.fs.teachablecdn.com/ADNupMnWyR7kCWRvm76Laz/resize=width:705/https://www.filepicker.io/api/file/Kw3CPmJkR7OGjyDC15r6" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="397" data-original-width="705" height="180" src="https://process.fs.teachablecdn.com/ADNupMnWyR7kCWRvm76Laz/resize=width:705/https://www.filepicker.io/api/file/Kw3CPmJkR7OGjyDC15r6" width="320" /></a></div><br /><p></p><p>The best thing about Qt is that you can even use javascript like QML language to program the widgets on screen.</p><p>In fact you can write an entire application in QML without even touching C++.</p>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-44423704037921648682020-12-04T02:45:00.005-08:002020-12-04T02:45:36.738-08:00Loading glTF models in Three.js<p>Hoi you... I am loading a glTF model to display a 3d scene. Please don't ask me how I did this. Just inspect in the browser the code. Better still visit this site:
<a href="https://threejsfundamentals.org/threejs/lessons/threejs-load-gltf.html" target="_blank">Link to Threejsfundamentals site</a></p>
<style>
#c {
width: 100%;
height: 100%;
display: block;
}
</style>
<canvas id="c"></canvas>
<script type="module" type="text/javascript">
import * as THREE from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/build/three.module.js';
import {OrbitControls} from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from 'https://threejsfundamentals.org/threejs/resources/threejs/r122/examples/jsm/loaders/GLTFLoader.js';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 45;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 100;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 10, 20);
const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
const scene = new THREE.Scene();
scene.background = new THREE.Color('black');
{
const planeSize = 40;
const loader = new THREE.TextureLoader();
const texture = loader.load('https://threejsfundamentals.org/threejs/resources/images/checker.png');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.magFilter = THREE.NearestFilter;
const repeats = planeSize / 2;
texture.repeat.set(repeats, repeats);
const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
const planeMat = new THREE.MeshPhongMaterial({
map: texture,
side: THREE.DoubleSide,
});
const mesh = new THREE.Mesh(planeGeo, planeMat);
mesh.rotation.x = Math.PI * -.5;
scene.add(mesh);
}
{
const skyColor = 0xB1E1FF; // light blue
const groundColor = 0xB97A20; // brownish orange
const intensity = 1;
const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
scene.add(light);
}
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(5, 10, 2);
scene.add(light);
scene.add(light.target);
}
function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
const halfFovY = THREE.MathUtils.degToRad(camera.fov * .5);
const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
// compute a unit vector that points in the direction the camera is now
// in the xz plane from the center of the box
const direction = (new THREE.Vector3())
.subVectors(camera.position, boxCenter)
.multiply(new THREE.Vector3(1, 0, 1))
.normalize();
// move the camera to a position distance units way from the center
// in whatever direction the camera was from the center already
camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));
// pick some near and far values for the frustum that
// will contain the box.
camera.near = boxSize / 100;
camera.far = boxSize * 100;
camera.updateProjectionMatrix();
// point the camera to look at the center of the box
camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
}
{
const gltfLoader = new GLTFLoader();
gltfLoader.load('https://threejsfundamentals.org/threejs/resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', (gltf) => {
const root = gltf.scene;
scene.add(root);
// compute the box that contains all the stuff
// from root and below
const box = new THREE.Box3().setFromObject(root);
const boxSize = box.getSize(new THREE.Vector3()).length();
const boxCenter = box.getCenter(new THREE.Vector3());
// set the camera to frame the box
frameArea(boxSize * 0.5, boxSize, boxCenter, camera);
// update the Trackball controls to handle the new size
controls.maxDistance = boxSize * 10;
controls.target.copy(boxCenter);
controls.update();
});
}
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com2tag:blogger.com,1999:blog-5330394525986174688.post-19689064059345062052020-11-29T23:24:00.002-08:002020-11-29T23:24:26.049-08:00Informal Talk: I wanted to play video games before doing B.E.<p> Hi There,</p><p>I can only hope that you the reader are doing good. I did do B.E. and was compelled to pursue an M.Tech from the prestigious Manipal Institute of Technology. I am not going to boast of it any further. What I wanna say is in retrospect I posted something in my FB post which students wanted to make viral.</p><p>We'll I was working for Christ University, Faculty of Engineering, Bengaluru back then. Once it so happened that I in my creative outburst penned or typed a post that read:</p><p><span style="font-family: courier; font-size: x-small;">I wanted to play video games before doing B.E, after B.E I wanted to make games</span></p><p><span style="font-family: courier; font-size: x-small;">I wanted to watch Porn before doing M.Tech, after M.Tech I wanted to ....</span></p><p>This short post garnered all round appreciation from the students. They were gung ho because they got another chance to besmirch the college reputation by making this post viral and I co-operated with them by making my post public for a short duration so that they could take snapshots. I even added masala to the post by commenting on it saying:</p><p><span style="font-family: courier; font-size: x-small;">Now, I am very careful what I want from a PhD.</span></p><p>They would not fathom what I had to endure during my student days. They knew only to complain of lack of placements and bad food in the canteen. Anyways past is past. Those were the days when Jio was recently launched and even a middle class kid got to enjoy high speed broadband.</p><p>I posted another post some time later that read:</p><p><span style="font-family: courier; font-size: x-small;">Din mein piyo raat mein Jio</span></p><p><span style="font-family: inherit;">I feel this much content is enough for the day as I don't want to bore you people with some more of my tasteless sarcasm.</span></p>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com2tag:blogger.com,1999:blog-5330394525986174688.post-86585089472084896832020-11-29T03:18:00.008-08:002020-11-29T03:39:19.608-08:00Parameters for Lighting in Computer Graphics<p> Lighting esp in a graphics library such as OpenGL can be implemented with techniques such as ray tracing, ray casting which solve visibility problem and shading as in phong shading which is for applying color.</p><p>Let's begin with basics:</p><p>Objects are represented in either boundary representations or using solid modeling. When it comes to coloring a 3D scene the objects in the scene interact with the light from light sources. There are multiple reflections, refractions etc..</p><p>If multiple reflections and refractions are neglected and light in the scene is modeled by splitting into ambient, diffuse and specular light then phong shading model becomes useful. In this matter is modeled as having a Bi-Directional Reflectance Distribution Function(BRDF). How much light falling on a surface is reflected is specified by it. <span style="font-family: inherit;"><b style="background-color: white; color: #202124; font-size: 16px;">Gouraud shading</b><span style="background-color: white; color: #202124; font-size: 16px;">: you evaluate the light color using the </span><b style="background-color: white; color: #202124; font-size: 16px;">reflectance</b><span style="background-color: white; color: #202124; font-size: 16px;"> model at the known points, and interpolate on the color; </span><b style="background-color: white; color: #202124; font-size: 16px;">Phong shading</b><span style="background-color: white; color: #202124; font-size: 16px;">: you interpolate the normals and apply the </span><b style="background-color: white; color: #202124; font-size: 16px;">reflectance</b><span style="background-color: white; color: #202124; font-size: 16px;"> model at every interpolated point.</span></span></p><p>There are several parameters of lighting that go into the phong shading calculations. Firstly the number and type of light sources. Light source types include point source, directional light and spot light.</p><p>Phong Shading parameters(Taken from wiki):</p><p style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px;">For each light source in the scene, components <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle i_{\text{s}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle i_{\text{s}}}</annotation></semantics></math></span><img alt="i_{\text{s}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/eb7bcb6985db5b408db56667d515c2d9e1ee9590" style="border: 0px; display: inline-block; height: 2.509ex; margin: 0px; vertical-align: -0.671ex; width: 1.683ex;" /></span> and <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle i_{\text{d}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle i_{\text{d}}}</annotation></semantics></math></span><img alt="i_{\text{d}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/9299271b182ed9b8c23b7a8890e57698f219113e" style="border: 0px; display: inline-block; height: 2.509ex; margin: 0px; vertical-align: -0.671ex; width: 1.949ex;" /></span> are defined as the intensities (often as <a class="mw-redirect" href="https://en.wikipedia.org/wiki/RGB" style="background: none; color: #0b0080; text-decoration-line: none;" title="RGB">RGB</a> values) of the specular and diffuse components of the light sources, respectively. A single term <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle i_{\text{a}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle i_{\text{a}}}</annotation></semantics></math></span><img alt="i_{\text{a}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/8e6b63ab06ff455254c1b05c721b269051e5e199" style="border: 0px; display: inline-block; height: 2.509ex; margin: 0px; vertical-align: -0.671ex; width: 1.857ex;" /></span> controls the ambient lighting; it is sometimes computed as a sum of contributions from all light sources.</p><p style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px;">For each <i>material</i> in the scene, the following parameters are defined:</p><dl style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin-bottom: 0.5em; margin-top: 0.2em;"><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle k_{\text{s}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle k_{\text{s}}}</annotation></semantics></math></span><img alt="k_{\text{s}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/a6d3b56b244b95797b7f2c3469a3bec08e79059e" style="border: 0px; display: inline-block; height: 2.509ex; vertical-align: -0.671ex; width: 2.091ex;" /></span>, which is a specular reflection constant, the ratio of reflection of the specular term of incoming light,</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle k_{\text{d}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle k_{\text{d}}}</annotation></semantics></math></span><img alt="k_{\text{d}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/f9ae4a99e7e47400ead72f5bb1a4f74dff397029" style="border: 0px; display: inline-block; height: 2.509ex; vertical-align: -0.671ex; width: 2.357ex;" /></span>, which is a diffuse reflection constant, the ratio of reflection of the diffuse term of incoming light (<a href="https://en.wikipedia.org/wiki/Lambertian_reflectance" style="background: none; color: #0b0080; text-decoration-line: none;" title="Lambertian reflectance">Lambertian reflectance</a>),</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle k_{\text{a}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle k_{\text{a}}}</annotation></semantics></math></span><img alt="k_{\text{a}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/5b1ad66379119006e60b450ed99edfe955af0488" style="border: 0px; display: inline-block; height: 2.509ex; vertical-align: -0.671ex; width: 2.265ex;" /></span>, which is an ambient reflection constant, the ratio of reflection of the ambient term present in all points in the scene rendered, and</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle \alpha }" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle \alpha }</annotation></semantics></math></span><img alt="\alpha" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/b79333175c8b3f0840bfb4ec41b8072c83ea88d3" style="border: 0px; display: inline-block; height: 1.676ex; vertical-align: -0.338ex; width: 1.488ex;" /></span>, which is a <i>shininess</i> constant for this material, which is larger for surfaces that are smoother and more mirror-like. When this constant is large the specular highlight is small.</dd></dl><div class="thumb tright" style="background-color: white; clear: right; color: #202122; float: right; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px 1.3em 1.4em; width: auto;"><div class="thumbinner" style="background-color: #f8f9fa; border: 1px solid rgb(200, 204, 209); font-size: 13.16px; min-width: 100px; overflow: hidden; padding: 3px; text-align: center; width: 222px;"><a class="image" href="https://en.wikipedia.org/wiki/File:Blinn_Vectors.svg" style="background: none; color: #0b0080; text-decoration-line: none;"><img alt="" class="thumbimage" data-file-height="750" data-file-width="1100" decoding="async" height="150" src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/Blinn_Vectors.svg/220px-Blinn_Vectors.svg.png" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/0/01/Blinn_Vectors.svg/330px-Blinn_Vectors.svg.png 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/0/01/Blinn_Vectors.svg/440px-Blinn_Vectors.svg.png 2x" style="background-color: white; border: 1px solid rgb(200, 204, 209); vertical-align: middle;" width="220" /></a><div class="thumbcaption" style="border: 0px; font-size: 12.3704px; line-height: 1.4em; padding: 3px; text-align: left;"><div class="magnify" style="float: right; margin-left: 3px; margin-right: 0px;"><a class="internal" href="https://en.wikipedia.org/wiki/File:Blinn_Vectors.svg" style="background-color: initial; background: linear-gradient(transparent, transparent), url("https:/w/resources/src/mediawiki.skinning/images/magnify-clip-ltr.svg?8330e"); color: #0b0080; display: block; height: 11px; overflow: hidden; text-decoration-line: none; text-indent: 15px; user-select: none; white-space: nowrap; width: 15px;" title="Enlarge"></a></div>Vectors for calculating Phong and Blinn–Phong shading</div></div></div><p style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px;">Furthermore, we have</p><dl style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin-bottom: 0.5em; margin-top: 0.2em;"><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\text{lights}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\text{lights}}}</annotation></semantics></math></span><img alt="{\displaystyle {\text{lights}}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/0b02af5f9a4f5c12b777928f8e2a3864f70b3c13" style="border: 0px; display: inline-block; height: 2.509ex; vertical-align: -0.671ex; width: 5.57ex;" /></span>, which is the <a href="https://en.wikipedia.org/wiki/Set_(mathematics)" style="background: none; color: #0b0080; text-decoration-line: none;" title="Set (mathematics)">set</a> of all light sources,</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {L}}_{m}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {L}}_{m}}</annotation></semantics></math></span><img alt="{\hat {L}}_{m}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/b6f9613854473e2cec1efe0dcdd54b46d649e93b" style="border: 0px; display: inline-block; height: 3.176ex; vertical-align: -0.671ex; width: 3.258ex;" /></span>, which is the direction vector from the point on the surface toward each light source (<span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle m}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle m}</annotation></semantics></math></span><img alt="m" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/0a07d98bb302f3856cbabc47b2b9016692e3f7bc" style="border: 0px; display: inline-block; height: 1.676ex; vertical-align: -0.338ex; width: 2.04ex;" /></span> specifies the light source),</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {N}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {N}}}</annotation></semantics></math></span><img alt="{\hat {N}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/1b9b81dbfd5ef1a73800b14a8d2e84a00c59667f" style="border: 0px; display: inline-block; height: 2.843ex; vertical-align: -0.338ex; width: 2.064ex;" /></span>, which is the <a class="mw-redirect" href="https://en.wikipedia.org/wiki/Surface_normal" style="background: none; color: #0b0080; text-decoration-line: none;" title="Surface normal">normal</a> at this point on the surface,</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {R}}_{m}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {R}}_{m}}</annotation></semantics></math></span><img alt="{\hat {R}}_{m}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/cdff1f3cb7481dfd94ce19f27a853621090a9158" style="border: 0px; display: inline-block; height: 3.176ex; vertical-align: -0.671ex; width: 3.439ex;" /></span>, which is the direction that a perfectly reflected ray of light would take from this point on the surface, and</dd><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {V}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {V}}}</annotation></semantics></math></span><img alt="{\hat {V}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/82dafc72bc12e1b85747770c7e2d4a48845d4c2c" style="border: 0px; display: inline-block; height: 2.843ex; vertical-align: -0.338ex; width: 1.787ex;" /></span>, which is the direction pointing towards the viewer (such as a virtual camera).</dd></dl><p style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px;">Then the Phong reflection model provides an equation for computing the illumination of each surface point <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle I_{\text{p}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle I_{\text{p}}}</annotation></semantics></math></span><img alt="I_{\text{p}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/061405f5fd9458cf15816b4f236ffa7d43a8889b" style="border: 0px; display: inline-block; height: 2.843ex; margin: 0px; vertical-align: -1.005ex; width: 2.169ex;" /></span>:</p><dl style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin-bottom: 0.5em; margin-top: 0.2em;"><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle I_{\text{p}}=k_{\text{a}}i_{\text{a}}+\sum _{m\;\in \;{\text{lights}}}(k_{\text{d}}({\hat {L}}_{m}\cdot {\hat {N}})i_{m,{\text{d}}}+k_{\text{s}}({\hat {R}}_{m}\cdot {\hat {V}})^{\alpha }i_{m,{\text{s}}}).}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle I_{\text{p}}=k_{\text{a}}i_{\text{a}}+\sum _{m\;\in \;{\text{lights}}}(k_{\text{d}}({\hat {L}}_{m}\cdot {\hat {N}})i_{m,{\text{d}}}+k_{\text{s}}({\hat {R}}_{m}\cdot {\hat {V}})^{\alpha }i_{m,{\text{s}}}).}</annotation></semantics></math></span><img alt="I_{\text{p}}=k_{\text{a}}i_{\text{a}}+\sum _{m\;\in \;{\text{lights}}}(k_{\text{d}}({\hat {L}}_{m}\cdot {\hat {N}})i_{m,{\text{d}}}+k_{\text{s}}({\hat {R}}_{m}\cdot {\hat {V}})^{\alpha }i_{m,{\text{s}}})." aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/4f244066a467e71d767b2015d1f368b624eb675f" style="border: 0px; display: inline-block; height: 5.843ex; vertical-align: -3.338ex; width: 55.984ex;" /></span></dd></dl><p style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px;">where the direction vector <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {R}}_{m}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {R}}_{m}}</annotation></semantics></math></span><img alt="{\hat {R}}_{m}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/cdff1f3cb7481dfd94ce19f27a853621090a9158" style="border: 0px; display: inline-block; height: 3.176ex; margin: 0px; vertical-align: -0.671ex; width: 3.439ex;" /></span> is calculated as the <a href="https://en.wikipedia.org/wiki/Specular_reflection#Direction_of_reflection" style="background: none; color: #0b0080; text-decoration-line: none;" title="Specular reflection">reflection</a> of <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {L}}_{m}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {L}}_{m}}</annotation></semantics></math></span><img alt="{\hat {L}}_{m}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/b6f9613854473e2cec1efe0dcdd54b46d649e93b" style="border: 0px; display: inline-block; height: 3.176ex; margin: 0px; vertical-align: -0.671ex; width: 3.258ex;" /></span> on the surface characterized by the surface normal <span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {N}}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {N}}}</annotation></semantics></math></span><img alt="{\hat {N}}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/1b9b81dbfd5ef1a73800b14a8d2e84a00c59667f" style="border: 0px; display: inline-block; height: 2.843ex; margin: 0px; vertical-align: -0.338ex; width: 2.064ex;" /></span> using</p><dl style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin-bottom: 0.5em; margin-top: 0.2em;"><dd style="margin-bottom: 0.1em; margin-left: 1.6em; margin-right: 0px;"><span class="mwe-math-element"><span class="mwe-math-mathml-inline mwe-math-mathml-a11y" style="clip: rect(1px, 1px, 1px, 1px); display: none; font-size: 16.52px; height: 1px; opacity: 0; overflow: hidden; position: absolute; width: 1px;"><math alttext="{\displaystyle {\hat {R}}_{m}=2({\hat {L}}_{m}\cdot {\hat {N}}){\hat {N}}-{\hat {L}}_{m}}" xmlns="http://www.w3.org/1998/Math/MathML"><semantics><annotation encoding="application/x-tex">{\displaystyle {\hat {R}}_{m}=2({\hat {L}}_{m}\cdot {\hat {N}}){\hat {N}}-{\hat {L}}_{m}}</annotation></semantics></math></span><img alt="{\hat {R}}_{m}=2({\hat {L}}_{m}\cdot {\hat {N}}){\hat {N}}-{\hat {L}}_{m}" aria-hidden="true" class="mwe-math-fallback-image-inline" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/d5acd56487631512ad0fc984bf3c11ce700589c4" style="border: 0px; display: inline-block; height: 3.343ex; vertical-align: -0.838ex; width: 24.672ex;" /></span></dd></dl><p style="background-color: white; color: #202122; font-family: sans-serif; font-size: 14px; margin: 0.5em 0px;">and the hats indicate that the vectors are <a href="https://en.wikipedia.org/wiki/Unit_vector" style="background: none; color: #0b0080; text-decoration-line: none;" title="Unit vector">normalized</a>.</p><p><br /></p><p><br /></p>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-10820287190047693292020-11-28T01:17:00.001-08:002020-11-28T01:17:44.582-08:00Here's how to create an SVG component and draw it in ReactJS<p> ReactJS project on SVG drawing using functional components-</p><p>Here is a really short piece of ReactJS code to draw SVGs:</p><div style="background-color: #1e1e1e; color: #d4d4d4; font-family: Consolas, "Courier New", monospace; font-size: 14px; line-height: 19px; white-space: pre;"><div><span style="color: #c586c0;">import</span> <span style="color: #9cdcfe;">React</span> <span style="color: #c586c0;">from</span> <span style="color: #ce9178;">'react'</span>;</div><div><span style="color: #569cd6;">function</span> <span style="color: #dcdcaa;">Parabola</span>() {</div><div> <span style="color: #c586c0;">return</span> <span style="color: grey;"><</span><span style="color: #569cd6;">path</span> <span style="color: #9cdcfe;">d</span>=<span style="color: #ce9178;">"M 100 350 q 150 -300 300 0"</span> <span style="color: #9cdcfe;">stroke</span>=<span style="color: #ce9178;">"blue"</span></div><div> <span style="color: #9cdcfe;">stroke-width</span>=<span style="color: #ce9178;">"5"</span> <span style="color: #9cdcfe;">fill</span>=<span style="color: #ce9178;">"none"</span> <span style="color: grey;">/></span>;</div><div> }</div><div><span style="color: #569cd6;">function</span> <span style="color: #dcdcaa;">Line</span>()</div><div>{</div><div> <span style="color: #c586c0;">return</span> <span style="color: grey;"><</span><span style="color: #569cd6;">path</span> <span style="color: #9cdcfe;">d</span>=<span style="color: #ce9178;">'M 175 200 l 150 0'</span> <span style="color: #9cdcfe;">stroke</span>=<span style="color: #ce9178;">'green'</span> <span style="color: #9cdcfe;">stroke-width</span>=<span style="color: #ce9178;">'3'</span></div><div> <span style="color: #9cdcfe;">fill</span>=<span style="color: #ce9178;">'none'</span> <span style="color: grey;">/></span>;</div><div>}</div><div><span style="color: #569cd6;">class</span> <span style="color: #4ec9b0;">SVG</span> <span style="color: #569cd6;">extends</span> <span style="color: #4ec9b0;">React</span>.<span style="color: #4ec9b0;">Component</span></div><div>{</div><div> <span style="color: #dcdcaa;">render</span>()</div><div> {</div><div> </div><div> <span style="color: #c586c0;">return</span>(</div><div> <span style="color: grey;"><</span><span style="color: #569cd6;">svg</span> <span style="color: #9cdcfe;">width</span>=<span style="color: #ce9178;">"400"</span> <span style="color: #9cdcfe;">height</span>=<span style="color: #ce9178;">"450"</span><span style="color: grey;">></span></div><div> <span style="color: grey;"><</span><span style="color: #4ec9b0;">Line</span><span style="color: grey;">/></span></div><div> <span style="color: grey;"><</span><span style="color: #4ec9b0;">Parabola</span><span style="color: grey;">/></span> <span style="color: grey;"></</span><span style="color: #569cd6;">svg</span><span style="color: grey;">></span></div><div> );</div><div> }</div><div>}</div><div><span style="color: #c586c0;">export</span> <span style="color: #c586c0;">default</span> <span style="color: #4ec9b0;">SVG</span>;</div></div><p>Which draws the following output on the screen:</p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUYThUtiiEMhNsRAWynwlaBEHdvxo1uS5M3XvF4NxNGNDjUaOdlI8gqFQVvMCyPaJTSt8bLEPnBBMr-kiKukmDbYQ8T6i4s5vQwAds8HXmiIK32l-RzbxMHNTMu-I7Yn2DZiH4NwFE7C8/s411/blog-react.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="277" data-original-width="411" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhUYThUtiiEMhNsRAWynwlaBEHdvxo1uS5M3XvF4NxNGNDjUaOdlI8gqFQVvMCyPaJTSt8bLEPnBBMr-kiKukmDbYQ8T6i4s5vQwAds8HXmiIK32l-RzbxMHNTMu-I7Yn2DZiH4NwFE7C8/s320/blog-react.png" width="320" /></a></div><div class="separator" style="clear: both; text-align: center;"><span style="text-align: left;">I have the project link here:</span></div><p><a href="https://github.com/bmkamath2000/React-Projs/tree/master/path-svg">https://github.com/bmkamath2000/React-Projs/tree/master/path-svg</a></p>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com2tag:blogger.com,1999:blog-5330394525986174688.post-69064071603217954242020-07-11T21:37:00.022-07:002020-07-18T00:07:51.226-07:00Sample Chart.js visualization of vertical bar<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
I have posted a Chart.js example of vertical bar chart.
<div>
It is from the site <a
href="https://www.chartjs.org/samples/latest/"
target="_blank"
>https://www.chartjs.org/samples/latest/</a
>
</div>
<p>This chart for some strange reason does not show up on viewing all blog posts. SO to see this chart please view(click on title) this post individually</p>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<!--Util.js-->
<script>
'use strict';
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
(function(global) {
var MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
var COLORS = [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
'#166a8f',
'#00a950',
'#58595b',
'#8549ba'
];
var Samples = global.Samples || (global.Samples = {});
var Color = global.Color;
Samples.utils = {
// Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/
srand: function(seed) {
this._seed = seed;
},
rand: function(min, max) {
var seed = this._seed;
min = min === undefined ? 0 : min;
max = max === undefined ? 1 : max;
this._seed = (seed * 9301 + 49297) % 233280;
return min + (this._seed / 233280) * (max - min);
},
numbers: function(config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 1;
var from = cfg.from || [];
var count = cfg.count || 8;
var decimals = cfg.decimals || 8;
var continuity = cfg.continuity || 1;
var dfactor = Math.pow(10, decimals) || 0;
var data = [];
var i, value;
for (i = 0; i < count; ++i) {
value = (from[i] || 0) + this.rand(min, max);
if (this.rand() <= continuity) {
data.push(Math.round(dfactor * value) / dfactor);
} else {
data.push(null);
}
}
return data;
},
labels: function(config) {
var cfg = config || {};
var min = cfg.min || 0;
var max = cfg.max || 100;
var count = cfg.count || 8;
var step = (max - min) / count;
var decimals = cfg.decimals || 8;
var dfactor = Math.pow(10, decimals) || 0;
var prefix = cfg.prefix || '';
var values = [];
var i;
for (i = min; i < max; i += step) {
values.push(prefix + Math.round(dfactor * i) / dfactor);
}
return values;
},
months: function(config) {
var cfg = config || {};
var count = cfg.count || 12;
var section = cfg.section;
var values = [];
var i, value;
for (i = 0; i < count; ++i) {
value = MONTHS[Math.ceil(i) % 12];
values.push(value.substring(0, section));
}
return values;
},
color: function(index) {
return COLORS[index % COLORS.length];
},
transparentize: function(color, opacity) {
var alpha = opacity === undefined ? 0.5 : 1 - opacity;
return Color(color).alpha(alpha).rgbString();
}
};
// DEPRECATED
window.randomScalingFactor = function() {
return Math.round(Samples.utils.rand(-100, 100));
};
// INITIALIZATION
Samples.utils.srand(Date.now());
}(this));
</script>
<div id="container364" style="width: 75%;">
<canvas id="canvas364"></canvas>
</div>
<button id="randomizeData364">Randomize Data</button>
<button id="addDataset364">Add Dataset</button>
<button id="removeDataset364">Remove Dataset</button>
<button id="addData364">Add Data</button>
<button id="removeData364">Remove Data</button>
<script>
var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var color = Chart.helpers.color;
var barChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}, {
label: 'Dataset 2',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
borderWidth: 1,
data: [
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor(),
randomScalingFactor()
]
}]
};
window.onload = function() {
var ctx = document.getElementById('canvas364').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
}
});
};
document.getElementById('randomizeData364').addEventListener('click', function() {
var zero = Math.random() < 0.2 ? true : false;
barChartData.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return zero ? 0.0 : randomScalingFactor();
});
});
window.myBar.update();
});
var colorNames = Object.keys(window.chartColors);
document.getElementById('addDataset364').addEventListener('click', function() {
var colorName = colorNames[barChartData.datasets.length % colorNames.length];
var dsColor = window.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (barChartData.datasets.length + 1),
backgroundColor: color(dsColor).alpha(0.5).rgbString(),
borderColor: dsColor,
borderWidth: 1,
data: []
};
for (var index = 0; index < barChartData.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
barChartData.datasets.push(newDataset);
window.myBar.update();
});
document.getElementById('addData364').addEventListener('click', function() {
if (barChartData.datasets.length > 0) {
var month = MONTHS[barChartData.labels.length % MONTHS.length];
barChartData.labels.push(month);
for (var index = 0; index < barChartData.datasets.length; ++index) {
// window.myBar.addData(randomScalingFactor(), index);
barChartData.datasets[index].data.push(randomScalingFactor());
}
window.myBar.update();
}
});
document.getElementById('removeDataset364').addEventListener('click', function() {
barChartData.datasets.pop();
window.myBar.update();
});
document.getElementById('removeData364').addEventListener('click', function() {
barChartData.labels.splice(-1, 1); // remove the label first
barChartData.datasets.forEach(function(dataset) {
dataset.data.pop();
});
window.myBar.update();
});
</script>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com1tag:blogger.com,1999:blog-5330394525986174688.post-16806048139599631152020-04-10T23:13:00.010-07:002022-07-11T21:59:38.715-07:00Truechet Tiles<div id="container2">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<script id="vertexShader" type="x-shader/x-vertex">
void main() {
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
// Author @patriciogv ( patriciogonzalezvivo.com ) - 2015
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform float u_time;
vec2 brickTile(vec2 _st, float _zoom){
_st *= _zoom;
// Here is where the offset is happening
_st.x += step(1., mod(_st.y,2.0)) * 0.5;
return fract(_st);
}
float box(vec2 _st, vec2 _size){
_size = vec2(0.5)-_size*0.5;
vec2 uv = smoothstep(_size,_size+vec2(1e-4),_st);
uv *= smoothstep(_size,_size+vec2(1e-4),vec2(1.0)-_st);
return uv.x*uv.y;
}
void main(void){
vec2 st = gl_FragCoord.xy/u_resolution.xy;
vec3 color = vec3(0.0);
// Modern metric brick of 215mm x 102.5mm x 65mm
// http://www.jaharrison.me.uk/Brickwork/Sizes.html
// st /= vec2(2.15,0.65)/1.5;
// Apply the brick tiling
st = brickTile(st,5.0);
color = vec3(box(st,vec2(0.9)));
// Uncomment to see the space coordinates
// color = vec3(st,0.0);
gl_FragColor = vec4(color,1.0);
}
</script>
<br />
<script>
(function(){
var container;
var camera, scene, renderer;
var uniforms;
init();
animate();
function init() {
container = document.getElementById( 'container2' );
camera = new THREE.Camera();
camera.position.z = 1;
scene = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry( 2, 2 );
uniforms = {
u_time: { type: "f", value: 1.0 },
u_resolution: { type: "v2", value: new THREE.Vector2() },
u_mouse: { type: "v2", value: new THREE.Vector2() }
};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: document.getElementById( 'vertexShader' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader' ).textContent
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
container.appendChild( renderer.domElement );
onWindowResize();
window.addEventListener( 'resize', onWindowResize, false );
document.onmousemove = function(e){
uniforms.u_mouse.value.x = e.pageX
uniforms.u_mouse.value.y = e.pageY
}
}
function onWindowResize( event ) {
renderer.setSize( 300, 600 );
uniforms.u_resolution.value.x = renderer.domElement.width;
uniforms.u_resolution.value.y = renderer.domElement.height;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
uniforms.u_time.value += 0.05;
renderer.render( scene, camera );
}
})();
</script>
<div dir="ltr" style="text-align: left;" trbidi="on">
While you may have observed there were a few posts on Kaleidoscope and patterns in my blog and I have promised on several occasions to create such patterns but I never delivered on my promise.
<br />
<br />
I feel the time has come to make good some of the promises and I want to now make some tiling code that repeats certain patterns on the screen.<br />
<br />
Here is a pattern of truchet tiles:
<br />
<br />
</div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div dir="ltr" style="text-align: left;" trbidi="on">Here is how its created:</div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" trbidi="on">Vertex Shader code:</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> void main() {</div><div dir="ltr" trbidi="on"> gl_Position = vec4( position, 1.0 );</div><div dir="ltr" trbidi="on"> }</div><div dir="ltr" trbidi="on"> </div><div dir="ltr" trbidi="on"><div dir="ltr" trbidi="on">Fragment Shader Code:</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on">// Author @patriciogv ( patriciogonzalezvivo.com ) - 2015</div><div dir="ltr" trbidi="on">#ifdef GL_ES</div><div dir="ltr" trbidi="on">precision mediump float;</div><div dir="ltr" trbidi="on">#endif</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on">uniform vec2 u_resolution;</div><div dir="ltr" trbidi="on">uniform float u_time;</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on">vec2 brickTile(vec2 _st, float _zoom){</div><div dir="ltr" trbidi="on"> _st *= _zoom;</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> // Here is where the offset is happening</div><div dir="ltr" trbidi="on"> _st.x += step(1., mod(_st.y,2.0)) * 0.5;</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> return fract(_st);</div><div dir="ltr" trbidi="on">}</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on">float box(vec2 _st, vec2 _size){</div><div dir="ltr" trbidi="on"> _size = vec2(0.5)-_size*0.5;</div><div dir="ltr" trbidi="on"> vec2 uv = smoothstep(_size,_size+vec2(1e-4),_st);</div><div dir="ltr" trbidi="on"> uv *= smoothstep(_size,_size+vec2(1e-4),vec2(1.0)-_st);</div><div dir="ltr" trbidi="on"> return uv.x*uv.y;</div><div dir="ltr" trbidi="on">}</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on">void main(void){</div><div dir="ltr" trbidi="on"> vec2 st = gl_FragCoord.xy/u_resolution.xy;</div><div dir="ltr" trbidi="on"> vec3 color = vec3(0.0);</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> // Modern metric brick of 215mm x 102.5mm x 65mm</div><div dir="ltr" trbidi="on"> // http://www.jaharrison.me.uk/Brickwork/Sizes.html</div><div dir="ltr" trbidi="on"> // st /= vec2(2.15,0.65)/1.5;</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> // Apply the brick tiling</div><div dir="ltr" trbidi="on"> st = brickTile(st,5.0);</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> color = vec3(box(st,vec2(0.9)));</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> // Uncomment to see the space coordinates</div><div dir="ltr" trbidi="on"> // color = vec3(st,0.0);</div><div dir="ltr" trbidi="on"><br /></div><div dir="ltr" trbidi="on"> gl_FragColor = vec4(color,1.0);</div><div dir="ltr" trbidi="on">}</div><div dir="ltr" trbidi="on"><br /></div></div></div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-33582096202056582512020-03-13T22:45:00.002-07:002020-03-13T22:45:53.500-07:00Post a message for me in Group Talk(Hangouts)<div dir="ltr" style="text-align: left;" trbidi="on">
Leave a message here:<br />
<br />
<a href="https://hangouts.google.com/group/9Q5CLrf2GA4FzvA39" target="_blank">Mercenaries of Change - Group Talk</a><br />
<br />
This is a google hangout that I am frequenting. Any queries on graphics, game development or programming in general would be entertained.<br />
<br />
India is a country with a huge skill gap between engineering and technology professionals and Industry trends and requirements.<br />
<br />
We should join forces to combat unemployment by helping each other out in doing what we would love to.<br />
<br />
I am skilled in OpenGL(immediate mode), Graphics, Gaming(2D) and a host of languages from Java, C, C++, C#, ASP.Net, Javascript, CSS, HTML, ReactJS(web) and Excel VBA.<br />
<br />
Visualizations of different kinds interest me the most. Want to learn Python in the near future.<br />
<br />
Thanks for reading about me. Now Its your turn. Introduce yourself.<br />
<br />
(All chat will be archived)</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-60486510003491684952019-12-22T01:37:00.001-08:002020-04-15T08:03:11.120-07:00Book of Shaders- Second Shader on Randomness(chaos)<div dir="ltr" style="text-align: left;" trbidi="on">
In this post I have shared a shader I found on the "Book of Shaders" site. I selected a shader on randomness. You can easily lookup the code of this shader by right clicking and selecting inspect. Now this is something you do very often to inspect your DOM from the browser. And some more advice to you is to experiment with Three.js that I used to render the shader.
<div id="container321">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<script id="vertexShaderrand" type="x-shader/x-vertex">
void main() {
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="fragmentShaderrand" type="x-shader/x-fragment">
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
float random (vec2 st) {
return fract(sin(dot(st.xy,
vec2(12.9898,78.233)))*43758.5453123);
}
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
float rnd = random( st );
gl_FragColor = vec4(vec3(rnd),1.0);
}
</script>
<script>
(function(){
var container;
var camera, scene, renderer;
var uniforms;
init();
animate();
function init() {
container = document.getElementById( 'container321' );
camera = new THREE.Camera();
camera.position.z = 1;
scene = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry( 2, 2 );
uniforms = {
u_time: { type: "f", value: 1.0 },
u_resolution: { type: "v2", value: new THREE.Vector2() },
u_mouse: { type: "v2", value: new THREE.Vector2() }
};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: document.getElementById( 'vertexShaderrand' ).textContent,
fragmentShader: document.getElementById( 'fragmentShaderrand' ).textContent
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
container.appendChild( renderer.domElement );
onWindowResize();
window.addEventListener( 'resize', onWindowResize, false );
document.onmousemove = function(e){
uniforms.u_mouse.value.x = e.pageX
uniforms.u_mouse.value.y = e.pageY
}
}
function onWindowResize( event ) {
renderer.setSize( 300, 600 );
uniforms.u_resolution.value.x = renderer.domElement.width;
uniforms.u_resolution.value.y = renderer.domElement.height;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
uniforms.u_time.value += 0.05;
renderer.render( scene, camera );
}
})();
</script>
</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-70171487159931938762019-12-22T01:22:00.003-08:002020-03-25T08:04:18.389-07:00Book of Shaders- Shader in Blogger<div dir="ltr" style="text-align: left;" trbidi="on">
Hi There,
I have used Three.js and posting some shader from the site: <a href="https://thebookofshaders.com/04/">Book of Shaders</a>
This is the vertex shader used here:
<br />
<pre> void main() {
gl_Position = vec4( position, 1.0 );
}
</pre>
and this is the corresponding fragment shader:
<br />
<pre> uniform vec2 u_resolution;
uniform float u_time;
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
gl_FragColor=vec4(st.x,st.y,0.0,1.0);
}
</pre>
For some strange reason my code for this post is interfering with the code of the other post.
I am really sorry about my lack of understanding of the nuances of HTML/CSS/JS.
Swalpa Adjust Maadi(Adjust a little) and view this post individually.
<br />
<div id="container123">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<script id="vertexShader1" type="x-shader/x-vertex">
void main() {
gl_Position = vec4( position, 1.0 );
}
</script>
<script id="fragmentShader1" type="x-shader/x-fragment">
uniform vec2 u_resolution;
uniform float u_time;
void main() {
vec2 st = gl_FragCoord.xy/u_resolution.xy;
gl_FragColor=vec4(st.x,st.y,0.0,1.0);
}
</script>
<script>
(function(){
var container;
var camera, scene, renderer;
var uniforms;
init();
animate();
function init() {
container = document.getElementById( 'container123' );
camera = new THREE.Camera();
camera.position.z = 1;
scene = new THREE.Scene();
var geometry = new THREE.PlaneBufferGeometry( 2, 2 );
uniforms = {
u_time: { type: "f", value: 1.0 },
u_resolution: { type: "v2", value: new THREE.Vector2() },
u_mouse: { type: "v2", value: new THREE.Vector2() }
};
var material = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: document.getElementById( 'vertexShader1' ).textContent,
fragmentShader: document.getElementById( 'fragmentShader1' ).textContent
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
container.appendChild( renderer.domElement );
onWindowResize();
window.addEventListener( 'resize', onWindowResize, false );
document.onmousemove = function(e){
uniforms.u_mouse.value.x = e.pageX
uniforms.u_mouse.value.y = e.pageY
}
}
function onWindowResize( event ) {
// renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setSize( 300, 600 );
uniforms.u_resolution.value.x = renderer.domElement.width;
uniforms.u_resolution.value.y = renderer.domElement.height;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
uniforms.u_time.value += 0.05;
renderer.render( scene, camera );
}
})();
</script>
</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-63107692350972070462019-11-10T04:40:00.001-08:002019-11-10T04:40:31.022-08:00Making my first game in Unity 3D<div dir="ltr" style="text-align: left;" trbidi="on">
I have become so confident of my skills that I have ventured into making a Unity 3D Game and started a blog post on it even before I finished it.<br />
<br />
This site =><a href="https://learn.unity.com/tutorial/your-first-game">https://learn.unity.com/tutorial/your-first-game</a><br />
<br />
Is where I am fixated on right now.<br />
<br />
My hope is to publish to the internet a rudimentary game that I make... hopefully it would allow me to post the game in this blog itself that visitors can play(I am not sure about this as yet)<br />
<br />
Well it turns out this first game didn't teach you anything yet set your aspirations and dreams on the right path.<br />
<br />
I hope I get some more time this weekend and am able to make a rudimentary playable game.<br />
<br />
As said in the four videos... A minimum value product.<br />
<br /></div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com5tag:blogger.com,1999:blog-5330394525986174688.post-56206594884500705492019-09-20T23:07:00.001-07:002020-03-29T08:45:39.926-07:003D Sierpinski Gasket in a Tetrahedron<div dir="ltr" style="text-align: left;" trbidi="on">
<br />
I Have lifted this program from this site: https://www.mobilefish.com/developer/webgl/webgl.html
which in turn lifted the programs from a coursera course on WebGL.
The 3D Sierpinski Gasket will in future be modified to rotate with interaction using mouse.
<br/>
PS: Browse individual posts. Looking at all posts in one page might break the code behind.
<a href="https://gamedev.stackexchange.com/questions/175323/webgl-html5-canvas-in-two-blogger-blog-posts-show-individually-but-not-together">Here</a> I posted in gamedev.stackoverflow.com a question about the same issue and it got solved instantly.
<canvas id="gl-canvas123" width="512" height="512">
Oops ... your browser doesn't support the HTML5 canvas element
</canvas>
<script id="vertex-shader" type="x-shader/x-vertex">
attribute vec3 vPosition;
attribute vec3 vColor;
varying vec4 color;
void main()
{
gl_Position = vec4(vPosition, 1.0);
color = vec4(vColor, 1.0);
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
varying vec4 color;
void
main()
{
gl_FragColor = color;
}
</script>
<script type="text/javascript">
/*
* Copyright 2010, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview This file contains functions every webgl program will need
* a version of one way or another.
*
* Instead of setting up a context manually it is recommended to
* use. This will check for success or failure. On failure it
* will attempt to present an approriate message to the user.
*
* gl = WebGLUtils.setupWebGL(canvas);
*
* For animated WebGL apps use of setTimeout or setInterval are
* discouraged. It is recommended you structure your rendering
* loop like this.
*
* function render() {
* window.requestAnimFrame(render, canvas);
*
* // do rendering
* ...
* }
* render();
*
* This will call your rendering function up to the refresh rate
* of your display but will stop rendering if your app is not
* visible.
*/
WebGLUtils = (function() {
/**
* Creates the HTLM for a failure message
* @param {string} canvasContainerId id of container of th
* canvas.
* @return {string} The html.
*/
var makeFailHTML = function(msg) {
return '' +
'<table style="background-color: #8CE; width: 100%; height: 100%;"><tr>' +
'<td align="center">' +
'<div style="display: table-cell; vertical-align: middle;">' +
'<div style="">' + msg + '</div>' +
'</div>' +
'</td></tr></table>';
};
/**
* Mesasge for getting a webgl browser
* @type {string}
*/
var GET_A_WEBGL_BROWSER = '' +
'This page requires a browser that supports WebGL.<br/>' +
'<a href="http://get.webgl.org">Click here to upgrade your browser.</a>';
/**
* Mesasge for need better hardware
* @type {string}
*/
var OTHER_PROBLEM = '' +
"It doesn't appear your computer can support WebGL.<br/>" +
'<a href="http://get.webgl.org/troubleshooting/">Click here for more information.</a>';
/**
* Creates a webgl context. If creation fails it will
* change the contents of the container of the <canvas>
* tag to an error message with the correct links for WebGL.
* @param {Element} canvas. The canvas element to create a
* context from.
* @param {WebGLContextCreationAttirbutes} opt_attribs Any
* creation attributes you want to pass in.
* @return {WebGLRenderingContext} The created context.
*/
var setupWebGL = function(canvas, opt_attribs) {
function showLink(str) {
var container = canvas.parentNode;
if (container) {
container.innerHTML = makeFailHTML(str);
}
};
if (!window.WebGLRenderingContext) {
showLink(GET_A_WEBGL_BROWSER);
return null;
}
var context = create3DContext(canvas, opt_attribs);
if (!context) {
showLink(OTHER_PROBLEM);
}
return context;
};
/**
* Creates a webgl context.
* @param {!Canvas} canvas The canvas tag to get context
* from. If one is not passed in one will be created.
* @return {!WebGLContext} The created context.
*/
var create3DContext = function(canvas, opt_attribs) {
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
try {
context = canvas.getContext(names[ii], opt_attribs);
} catch(e) {}
if (context) {
break;
}
}
return context;
}
return {
create3DContext: create3DContext,
setupWebGL: setupWebGL
};
})();
/**
* Provides requestAnimationFrame in a cross browser way.
*/
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000/60);
};
})();
//
// initShaders.js
//
function initShaders( gl, vertexShaderId, fragmentShaderId )
{
var vertShdr;
var fragShdr;
var vertElem = document.getElementById( vertexShaderId );
if ( !vertElem ) {
alert( "Unable to load vertex shader " + vertexShaderId );
return -1;
}
else {
vertShdr = gl.createShader( gl.VERTEX_SHADER );
gl.shaderSource( vertShdr, vertElem.text );
gl.compileShader( vertShdr );
if ( !gl.getShaderParameter(vertShdr, gl.COMPILE_STATUS) ) {
var msg = "Vertex shader failed to compile. The error log is:"
+ "<pre>" + gl.getShaderInfoLog( vertShdr ) + "</pre>";
alert( msg );
return -1;
}
}
var fragElem = document.getElementById( fragmentShaderId );
if ( !fragElem ) {
alert( "Unable to load vertex shader " + fragmentShaderId );
return -1;
}
else {
fragShdr = gl.createShader( gl.FRAGMENT_SHADER );
gl.shaderSource( fragShdr, fragElem.text );
gl.compileShader( fragShdr );
if ( !gl.getShaderParameter(fragShdr, gl.COMPILE_STATUS) ) {
var msg = "Fragment shader failed to compile. The error log is:"
+ "<pre>" + gl.getShaderInfoLog( fragShdr ) + "</pre>";
alert( msg );
return -1;
}
}
var program = gl.createProgram();
gl.attachShader( program, vertShdr );
gl.attachShader( program, fragShdr );
gl.linkProgram( program );
if ( !gl.getProgramParameter(program, gl.LINK_STATUS) ) {
var msg = "Shader program failed to link. The error log is:"
+ "<pre>" + gl.getProgramInfoLog( program ) + "</pre>";
alert( msg );
return -1;
}
return program;
}
//////////////////////////////////////////////////////////////////////////////
//
// Angel.js
//
//////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------
//
// Helper functions
//
function _argumentsToArray( args )
{
return [].concat.apply( [], Array.prototype.slice.apply(args) );
}
//----------------------------------------------------------------------------
function radians( degrees ) {
return degrees * Math.PI / 180.0;
}
//----------------------------------------------------------------------------
//
// Vector Constructors
//
function vec2()
{
var result = _argumentsToArray( arguments );
switch ( result.length ) {
case 0: result.push( 0.0 );
case 1: result.push( 0.0 );
}
return result.splice( 0, 2 );
}
function vec3()
{
var result = _argumentsToArray( arguments );
switch ( result.length ) {
case 0: result.push( 0.0 );
case 1: result.push( 0.0 );
case 2: result.push( 0.0 );
}
return result.splice( 0, 3 );
}
function vec4()
{
var result = _argumentsToArray( arguments );
switch ( result.length ) {
case 0: result.push( 0.0 );
case 1: result.push( 0.0 );
case 2: result.push( 0.0 );
case 3: result.push( 1.0 );
}
return result.splice( 0, 4 );
}
//----------------------------------------------------------------------------
//
// Matrix Constructors
//
function mat2()
{
var v = _argumentsToArray( arguments );
var m = [];
switch ( v.length ) {
case 0:
v[0] = 1;
case 1:
m = [
vec2( v[0], 0.0 ),
vec2( 0.0, v[0] )
];
break;
default:
m.push( vec2(v) ); v.splice( 0, 2 );
m.push( vec2(v) );
break;
}
m.matrix = true;
return m;
}
//----------------------------------------------------------------------------
function mat3()
{
var v = _argumentsToArray( arguments );
var m = [];
switch ( v.length ) {
case 0:
v[0] = 1;
case 1:
m = [
vec3( v[0], 0.0, 0.0 ),
vec3( 0.0, v[0], 0.0 ),
vec3( 0.0, 0.0, v[0] )
];
break;
default:
m.push( vec3(v) ); v.splice( 0, 3 );
m.push( vec3(v) ); v.splice( 0, 3 );
m.push( vec3(v) );
break;
}
m.matrix = true;
return m;
}
//----------------------------------------------------------------------------
function mat4()
{
var v = _argumentsToArray( arguments );
var m = [];
switch ( v.length ) {
case 0:
v[0] = 1;
case 1:
m = [
vec4( v[0], 0.0, 0.0, 0.0 ),
vec4( 0.0, v[0], 0.0, 0.0 ),
vec4( 0.0, 0.0, v[0], 0.0 ),
vec4( 0.0, 0.0, 0.0, v[0] )
];
break;
default:
m.push( vec4(v) ); v.splice( 0, 4 );
m.push( vec4(v) ); v.splice( 0, 4 );
m.push( vec4(v) ); v.splice( 0, 4 );
m.push( vec4(v) );
break;
}
m.matrix = true;
return m;
}
//----------------------------------------------------------------------------
//
// Generic Mathematical Operations for Vectors and Matrices
//
function equal( u, v )
{
if ( u.length != v.length ) { return false; }
if ( u.matrix && v.matrix ) {
for ( var i = 0; i < u.length; ++i ) {
if ( u[i].length != v[i].length ) { return false; }
for ( var j = 0; j < u[i].length; ++j ) {
if ( u[i][j] !== v[i][j] ) { return false; }
}
}
}
else if ( u.matrix && !v.matrix || !u.matrix && v.matrix ) {
return false;
}
else {
for ( var i = 0; i < u.length; ++i ) {
if ( u[i] !== v[i] ) { return false; }
}
}
return true;
}
//----------------------------------------------------------------------------
function add( u, v )
{
var result = [];
if ( u.matrix && v.matrix ) {
if ( u.length != v.length ) {
throw "add(): trying to add matrices of different dimensions";
}
for ( var i = 0; i < u.length; ++i ) {
if ( u[i].length != v[i].length ) {
throw "add(): trying to add matrices of different dimensions";
}
result.push( [] );
for ( var j = 0; j < u[i].length; ++j ) {
result[i].push( u[i][j] + v[i][j] );
}
}
result.matrix = true;
return result;
}
else if ( u.matrix && !v.matrix || !u.matrix && v.matrix ) {
throw "add(): trying to add matrix and non-matrix variables";
}
else {
if ( u.length != v.length ) {
throw "add(): vectors are not the same dimension";
}
for ( var i = 0; i < u.length; ++i ) {
result.push( u[i] + v[i] );
}
return result;
}
}
//----------------------------------------------------------------------------
function subtract( u, v )
{
var result = [];
if ( u.matrix && v.matrix ) {
if ( u.length != v.length ) {
throw "subtract(): trying to subtract matrices" +
" of different dimensions";
}
for ( var i = 0; i < u.length; ++i ) {
if ( u[i].length != v[i].length ) {
throw "subtract(): trying to subtact matrices" +
" of different dimensions";
}
result.push( [] );
for ( var j = 0; j < u[i].length; ++j ) {
result[i].push( u[i][j] - v[i][j] );
}
}
result.matrix = true;
return result;
}
else if ( u.matrix && !v.matrix || !u.matrix && v.matrix ) {
throw "subtact(): trying to subtact matrix and non-matrix variables";
}
else {
if ( u.length != v.length ) {
throw "subtract(): vectors are not the same length";
}
for ( var i = 0; i < u.length; ++i ) {
result.push( u[i] - v[i] );
}
return result;
}
}
//----------------------------------------------------------------------------
function mult( u, v )
{
var result = [];
if ( u.matrix && v.matrix ) {
if ( u.length != v.length ) {
throw "mult(): trying to add matrices of different dimensions";
}
for ( var i = 0; i < u.length; ++i ) {
if ( u[i].length != v[i].length ) {
throw "mult(): trying to add matrices of different dimensions";
}
}
for ( var i = 0; i < u.length; ++i ) {
result.push( [] );
for ( var j = 0; j < v.length; ++j ) {
var sum = 0.0;
for ( var k = 0; k < u.length; ++k ) {
sum += u[i][k] * v[k][j];
}
result[i].push( sum );
}
}
result.matrix = true;
return result;
}
else {
if ( u.length != v.length ) {
throw "mult(): vectors are not the same dimension";
}
for ( var i = 0; i < u.length; ++i ) {
result.push( u[i] * v[i] );
}
return result;
}
}
//----------------------------------------------------------------------------
//
// Basic Transformation Matrix Generators
//
function translate( x, y, z )
{
if ( Array.isArray(x) && x.length == 3 ) {
z = x[2];
y = x[1];
x = x[0];
}
var result = mat4();
result[0][3] = x;
result[1][3] = y;
result[2][3] = z;
return result;
}
//----------------------------------------------------------------------------
function rotate( angle, axis )
{
if ( !Array.isArray(axis) ) {
axis = [ arguments[1], arguments[2], arguments[3] ];
}
var v = normalize( axis );
var x = v[0];
var y = v[1];
var z = v[2];
var c = Math.cos( radians(angle) );
var omc = 1.0 - c;
var s = Math.sin( radians(angle) );
var result = mat4(
vec4( x*x*omc + c, x*y*omc - z*s, x*z*omc + y*s, 0.0 ),
vec4( x*y*omc + z*s, y*y*omc + c, y*z*omc - x*s, 0.0 ),
vec4( x*z*omc - y*s, y*z*omc + x*s, z*z*omc + c, 0.0 ),
vec4()
);
return result;
}
function rotateX(theta) {
var c = Math.cos( radians(theta) );
var s = Math.sin( radians(theta) );
var rx = mat4( 1.0, 0.0, 0.0, 0.0,
0.0, c, s, 0.0,
0.0, -s, c, 0.0,
0.0, 0.0, 0.0, 1.0 );
return rx;
}
function rotateY(theta) {
var c = Math.cos( radians(theta) );
var s = Math.sin( radians(theta) );
var ry = mat4( c, 0.0, -s, 0.0,
0.0, 1.0, 0.0, 0.0,
s, 0.0, c, 0.0,
0.0, 0.0, 0.0, 1.0 );
return ry;
}
function rotateZ(theta) {
var c = Math.cos( radians(theta) );
var s = Math.sin( radians(theta) );
var rz = mat4( c, -s, 0.0, 0.0,
s, c, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0 );
return rz;
}
//----------------------------------------------------------------------------
function scalem( x, y, z )
{
if ( Array.isArray(x) && x.length == 3 ) {
z = x[2];
y = x[1];
x = x[0];
}
var result = mat4();
result[0][0] = x;
result[1][1] = y;
result[2][2] = z;
return result;
}
//----------------------------------------------------------------------------
//
// ModelView Matrix Generators
//
function lookAt( eye, at, up )
{
if ( !Array.isArray(eye) || eye.length != 3) {
throw "lookAt(): first parameter [eye] must be an a vec3";
}
if ( !Array.isArray(at) || at.length != 3) {
throw "lookAt(): first parameter [at] must be an a vec3";
}
if ( !Array.isArray(up) || up.length != 3) {
throw "lookAt(): first parameter [up] must be an a vec3";
}
if ( equal(eye, at) ) {
return mat4();
}
var v = normalize( subtract(at, eye) ); // view direction vector
var n = normalize( cross(v, up) ); // perpendicular vector
var u = normalize( cross(n, v) ); // "new" up vector
v = negate( v );
var result = mat4(
vec4( n, -dot(n, eye) ),
vec4( u, -dot(u, eye) ),
vec4( v, -dot(v, eye) ),
vec4()
);
return result;
}
//----------------------------------------------------------------------------
//
// Projection Matrix Generators
//
function ortho( left, right, bottom, top, near, far )
{
if ( left == right ) { throw "ortho(): left and right are equal"; }
if ( bottom == top ) { throw "ortho(): bottom and top are equal"; }
if ( near == far ) { throw "ortho(): near and far are equal"; }
var w = right - left;
var h = top - bottom;
var d = far - near;
var result = mat4();
result[0][0] = 2.0 / w;
result[1][1] = 2.0 / h;
result[2][2] = -2.0 / d;
result[0][3] = (left + right) / w;
result[1][3] = (top + bottom) / h;
result[2][3] = (near + far) / d;
return result;
}
//----------------------------------------------------------------------------
function perspective( fovy, aspect, near, far )
{
var f = 1.0 / Math.tan( radians(fovy) / 2 );
var d = far - near;
var result = mat4();
result[0][0] = f / aspect;
result[1][1] = f;
result[2][2] = -(near + far) / d;
result[2][3] = -2 * near * far / d;
result[3][2] = -1;
result[3][3] = 0.0;
return result;
}
//----------------------------------------------------------------------------
//
// Matrix Functions
//
function transpose( m )
{
if ( !m.matrix ) {
return "transpose(): trying to transpose a non-matrix";
}
var result = [];
for ( var i = 0; i < m.length; ++i ) {
result.push( [] );
for ( var j = 0; j < m[i].length; ++j ) {
result[i].push( m[j][i] );
}
}
result.matrix = true;
return result;
}
//----------------------------------------------------------------------------
//
// Vector Functions
//
function dot( u, v )
{
if ( u.length != v.length ) {
throw "dot(): vectors are not the same dimension";
}
var sum = 0.0;
for ( var i = 0; i < u.length; ++i ) {
sum += u[i] * v[i];
}
return sum;
}
//----------------------------------------------------------------------------
function negate( u )
{
result = [];
for ( var i = 0; i < u.length; ++i ) {
result.push( -u[i] );
}
return result;
}
//----------------------------------------------------------------------------
function cross( u, v )
{
if ( !Array.isArray(u) || u.length < 3 ) {
throw "cross(): first argument is not a vector of at least 3";
}
if ( !Array.isArray(v) || v.length < 3 ) {
throw "cross(): second argument is not a vector of at least 3";
}
var result = [
u[1]*v[2] - u[2]*v[1],
u[2]*v[0] - u[0]*v[2],
u[0]*v[1] - u[1]*v[0]
];
return result;
}
//----------------------------------------------------------------------------
function length( u )
{
return Math.sqrt( dot(u, u) );
}
//----------------------------------------------------------------------------
function normalize( u, excludeLastComponent )
{
if ( excludeLastComponent ) {
var last = u.pop();
}
var len = length( u );
if ( !isFinite(len) ) {
throw "normalize: vector " + u + " has zero length";
}
for ( var i = 0; i < u.length; ++i ) {
u[i] /= len;
}
if ( excludeLastComponent ) {
u.push( last );
}
return u;
}
//----------------------------------------------------------------------------
function mix( u, v, s )
{
if ( typeof s !== "number" ) {
throw "mix: the last paramter " + s + " must be a number";
}
if ( u.length != v.length ) {
throw "vector dimension mismatch";
}
var result = [];
for ( var i = 0; i < u.length; ++i ) {
result.push( s * u[i] + (1.0 - s) * v[i] );
}
return result;
}
//----------------------------------------------------------------------------
//
// Vector and Matrix functions
//
function scale( s, u )
{
if ( !Array.isArray(u) ) {
throw "scale: second parameter " + u + " is not a vector";
}
result = [];
for ( var i = 0; i < u.length; ++i ) {
result.push( s * u[i] );
}
return result;
}
//----------------------------------------------------------------------------
//
//
//
function flatten( v )
{
if ( v.matrix === true ) {
v = transpose( v );
}
var n = v.length;
var elemsAreArrays = false;
if ( Array.isArray(v[0]) ) {
elemsAreArrays = true;
n *= v[0].length;
}
var floats = new Float32Array( n );
if ( elemsAreArrays ) {
var idx = 0;
for ( var i = 0; i < v.length; ++i ) {
for ( var j = 0; j < v[i].length; ++j ) {
floats[idx++] = v[i][j];
}
}
}
else {
for ( var i = 0; i < v.length; ++i ) {
floats[i] = v[i];
}
}
return floats;
}
//----------------------------------------------------------------------------
var sizeof = {
'vec2' : new Float32Array( flatten(vec2()) ).byteLength,
'vec3' : new Float32Array( flatten(vec3()) ).byteLength,
'vec4' : new Float32Array( flatten(vec4()) ).byteLength,
'mat2' : new Float32Array( flatten(mat2()) ).byteLength,
'mat3' : new Float32Array( flatten(mat3()) ).byteLength,
'mat4' : new Float32Array( flatten(mat4()) ).byteLength
};
"use strict";
var canvas;
var gl;
var points = [];
var colors = [];
var NumTimesToSubdivide = 3;
window.onload = function init()
{
canvas = document.getElementById( "gl-canvas123" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
//
// Initialize our data for the Sierpinski Gasket
//
// First, initialize the vertices of our 3D gasket
// Four vertices on unit circle
// Intial tetrahedron with equal length sides
var vertices = [
vec3( 0.0000, 0.0000, -1.0000 ),
vec3( 0.0000, 0.9428, 0.3333 ),
vec3( -0.8165, -0.4714, 0.3333 ),
vec3( 0.8165, -0.4714, 0.3333 )
];
divideTetra( vertices[0], vertices[1], vertices[2], vertices[3],
NumTimesToSubdivide);
//
// Configure WebGL
//
gl.viewport( 0, 0, canvas.width, canvas.height );
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
// enable hidden-surface removal
gl.enable(gl.DEPTH_TEST);
// Load shaders and initialize attribute buffers
var program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram( program );
// Create a buffer object, initialize it, and associate it with the
// associated attribute variable in our vertex shader
var cBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(colors), gl.STATIC_DRAW );
var vColor = gl.getAttribLocation( program, "vColor" );
gl.vertexAttribPointer( vColor, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vColor );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(points), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
render();
};
function triangle( a, b, c, color )
{
// add colors and vertices for one triangle
var baseColors = [
vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0),
vec3(0.0, 0.0, 0.0)
];
colors.push( baseColors[color] );
points.push( a );
colors.push( baseColors[color] );
points.push( b );
colors.push( baseColors[color] );
points.push( c );
}
function tetra( a, b, c, d )
{
// tetrahedron with each side using
// a different color
triangle( a, c, b, 0 );
triangle( a, c, d, 1 );
triangle( a, b, d, 2 );
triangle( b, c, d, 3 );
}
function divideTetra( a, b, c, d, count )
{
// check for end of recursion
if ( count === 0 ) {
tetra( a, b, c, d );
}
// find midpoints of sides
// divide four smaller tetrahedra
else {
var ab = mix( a, b, 0.5 );
var ac = mix( a, c, 0.5 );
var ad = mix( a, d, 0.5 );
var bc = mix( b, c, 0.5 );
var bd = mix( b, d, 0.5 );
var cd = mix( c, d, 0.5 );
--count;
divideTetra( a, ab, ac, ad, count );
divideTetra( ab, b, bc, bd, count );
divideTetra( ac, bc, c, cd, count );
divideTetra( ad, bd, cd, d, count );
}
}
function render()
{
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.drawArrays( gl.TRIANGLES, 0, points.length );
}
</script>
</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-77027140969630923342019-09-07T02:37:00.001-07:002020-03-25T07:43:10.863-07:00Draw an Interactive Cube in HTML5/WebGL<div dir="ltr" style="text-align: left;" trbidi="on">
This is a canvas that allows you to play with a cube with your mouse.
This interactive cube has been made possible with the miracle technology of HTML5 Canvas and WebGL
NJoy!!!
<br /></div>
<canvas width = "570" height = "570" id = "my_Canvas1"></canvas>
<pre>
<script>
(function(){
/*============= Creating a canvas ======================*/
var canvaspmet = document.getElementById('my_Canvas1');
var gl = canvaspmet.getContext('webgl');
/*========== Defining and storing the geometry ==========*/
var vertices = [
-1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,
-1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,
-1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,
1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,
-1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,
-1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1,
];
var colors = [
5,3,7, 5,3,7, 5,3,7, 5,3,7,
1,1,3, 1,1,3, 1,1,3, 1,1,3,
0,0,1, 0,0,1, 0,0,1, 0,0,1,
1,0,0, 1,0,0, 1,0,0, 1,0,0,
1,1,0, 1,1,0, 1,1,0, 1,1,0,
0,1,0, 0,1,0, 0,1,0, 0,1,0
];
var indices = [
0,1,2, 0,2,3, 4,5,6, 4,6,7,
8,9,10, 8,10,11, 12,13,14, 12,14,15,
16,17,18, 16,18,19, 20,21,22, 20,22,23
];
// Create and store data into vertex buffer
var vertex_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Create and store data into color buffer
var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// Create and store data into index buffer
var index_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
/*=================== SHADERS =================== */
var vertCode = 'attribute vec3 position;'+
'uniform mat4 Pmatrix;'+
'uniform mat4 Vmatrix;'+
'uniform mat4 Mmatrix;'+
'attribute vec3 color;'+//the color of the point
'varying vec3 vColor;'+
'void main(void) { '+//pre-built function
'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+
'vColor = color;'+
'}';
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
var shaderprogram = gl.createProgram();
gl.attachShader(shaderprogram, vertShader);
gl.attachShader(shaderprogram, fragShader);
gl.linkProgram(shaderprogram);
/*======== Associating attributes to vertex shader =====*/
var _Pmatrix = gl.getUniformLocation(shaderprogram, "Pmatrix");
var _Vmatrix = gl.getUniformLocation(shaderprogram, "Vmatrix");
var _Mmatrix = gl.getUniformLocation(shaderprogram, "Mmatrix");
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var _position = gl.getAttribLocation(shaderprogram, "position");
gl.vertexAttribPointer(_position, 3, gl.FLOAT, false,0,0);
gl.enableVertexAttribArray(_position);
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
var _color = gl.getAttribLocation(shaderprogram, "color");
gl.vertexAttribPointer(_color, 3, gl.FLOAT, false,0,0) ;
gl.enableVertexAttribArray(_color);
gl.useProgram(shaderprogram);
/*==================== MATRIX ====================== */
function get_projection(angle, a, zMin, zMax) {
var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5
return [
0.5/ang, 0 , 0, 0,
0, 0.5*a/ang, 0, 0,
0, 0, -(zMax+zMin)/(zMax-zMin), -1,
0, 0, (-2*zMax*zMin)/(zMax-zMin), 0
];
}
var proj_matrix = get_projection(40, canvaspmet.width/canvaspmet.height, 1, 100);
var mo_matrix = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 ];
var view_matrix = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 ];
view_matrix[14] = view_matrix[14]-6;
/*================= Mouse events ======================*/
var AMORTIZATION = 0.95;
var drag = false;
var old_x, old_y;
var dX = 0, dY = 0;
var mouseDown = function(e) {
drag = true;
old_x = e.pageX, old_y = e.pageY;
e.preventDefault();
return false;
};
var mouseUp = function(e){
drag = false;
};
var mouseMove = function(e) {
if (!drag) return false;
dX = (e.pageX-old_x)*2*Math.PI/canvaspmet.width,
dY = (e.pageY-old_y)*2*Math.PI/canvaspmet.height;
THETA+= dX;
PHI+=dY;
old_x = e.pageX, old_y = e.pageY;
e.preventDefault();
};
canvaspmet.addEventListener("mousedown", mouseDown, false);
canvaspmet.addEventListener("mouseup", mouseUp, false);
canvaspmet.addEventListener("mouseout", mouseUp, false);
canvaspmet.addEventListener("mousemove", mouseMove, false);
/*=========================rotation================*/
function rotateX(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv1 = m[1], mv5 = m[5], mv9 = m[9];
m[1] = m[1]*c-m[2]*s;
m[5] = m[5]*c-m[6]*s;
m[9] = m[9]*c-m[10]*s;
m[2] = m[2]*c+mv1*s;
m[6] = m[6]*c+mv5*s;
m[10] = m[10]*c+mv9*s;
}
function rotateY(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];
m[0] = c*m[0]+s*m[2];
m[4] = c*m[4]+s*m[6];
m[8] = c*m[8]+s*m[10];
m[2] = c*m[2]-s*mv0;
m[6] = c*m[6]-s*mv4;
m[10] = c*m[10]-s*mv8;
}
/*=================== Drawing =================== */
var THETA = 0,
PHI = 0;
var time_old = 0;
var animate = function(time) {
var dt = time-time_old;
if (!drag) {
dX *= AMORTIZATION, dY*=AMORTIZATION;
THETA+=dX, PHI+=dY;
}
//set model matrix to I4
mo_matrix[0] = 1, mo_matrix[1] = 0, mo_matrix[2] = 0,
mo_matrix[3] = 0,
mo_matrix[4] = 0, mo_matrix[5] = 1, mo_matrix[6] = 0,
mo_matrix[7] = 0,
mo_matrix[8] = 0, mo_matrix[9] = 0, mo_matrix[10] = 1,
mo_matrix[11] = 0,
mo_matrix[12] = 0, mo_matrix[13] = 0, mo_matrix[14] = 0,
mo_matrix[15] = 1;
rotateY(mo_matrix, THETA);
rotateX(mo_matrix, PHI);
time_old = time;
gl.enable(gl.DEPTH_TEST);
// gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvaspmet.width, canvaspmet.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix4fv(_Pmatrix, false, proj_matrix);
gl.uniformMatrix4fv(_Vmatrix, false, view_matrix);
gl.uniformMatrix4fv(_Mmatrix, false, mo_matrix);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
window.requestAnimationFrame(animate);
}
animate(0);
})();
</script>
</pre>A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com1tag:blogger.com,1999:blog-5330394525986174688.post-68574204033411675612019-09-07T01:56:00.004-07:002019-12-13T21:46:14.398-08:00HTML5 Canvas and WebGL - A new beginning<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
This post displays a text message inside a canvas which is drawn using a webgl context.<br />
<br />
<br /></div>
<canvas height="200" id="mycanvas" width="600"></canvas>
<br />
<pre><script>
(function(){
var canvastemp = document.getElementById('mycanvas');
var context = canvastemp.getContext('2d');
context.font = '20pt Calibri';
context.fillStyle = 'green';
context.fillText('Welcome to CGLABPROJECTS', 70, 70);
})();
</script>
</pre>
</div>
This is another canvas that displays a triangle in an experimental webgl context.
If you are not able to view the triangle then may be you need to upgrade to a better browser or enable webgl in your browser.
(BTW it is enabled by default in most modern browsers)
<br />
For more details about WebGL Application visit this site:
https://www.tutorialspoint.com/webgl/webgl_sample_application.htm
<canvas height="300" id="my_Canvas" width="300"></canvas>
<br />
<pre>
<script>
(function(){
/* Step1: Prepare the canvas and get WebGL context */
var canvas = document.getElementById('my_Canvas');
var gl = canvas.getContext('experimental-webgl');
/* Step2: Define the geometry and store it in buffer objects */
var vertices = [-0.5, 0.5, -0.5, -0.5, 0.0, -0.5,];
// Create a new buffer object
var vertex_buffer = gl.createBuffer();
// Bind an empty array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertices data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/* Step3: Create and compile Shader programs */
// Vertex shader source code
var vertCode =
'attribute vec2 coordinates;' +
'void main(void) {' + ' gl_Position = vec4(coordinates,0.0, 1.0);' + '}';
//Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
//Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
//Compile the vertex shader
gl.compileShader(vertShader);
//Fragment shader source code
var fragCode = 'void main(void) {' + 'gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' + '}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragment shader
gl.compileShader(fragShader);
// Create a shader program object to store combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/* Step 4: Associate the shader programs to buffer objects */
//Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
//Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
//point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 0, 0);
//Enable the attribute
gl.enableVertexAttribArray(coord);
/* Step5: Drawing the required object (triangle) */
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
// Draw the triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);
})();
</script>
</pre>
</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-34254140044481749882019-05-22T00:18:00.025-07:002023-02-06T20:22:44.720-08:00A Big Thank You<div dir="ltr" style="text-align: left;" trbidi="on">
<div>
<br /></div>
I thank all my blog viewers for so much love and appreciation... I have enjoyed blogging as much as you all have visiting this blog.</div><div dir="ltr" style="text-align: left;" trbidi="on">Popularity is down does not mean quality is down.</div><div dir="ltr" style="text-align: left;" trbidi="on"><div class="separator" style="clear: both; text-align: center;"><br /><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1eDnGl0DE4Cp7nTejSyPlWM5d7BJN9vTAuX5cxG1-hqRpUEQroyyAFU8Ap3djY9lzNfvIej1XPNHYaMcVP-L368R_gIkN7d-nCspEbOvT5uq1UAajFcfaYPm4B7ymdyLd_uiwHC1ZtmQBIBb3s2DVbmpXX4GNCTyOwCH2YzYOB0m2nLPXSLQf6Z2L/s1242/blog_popularity.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="447" data-original-width="1242" height="115" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1eDnGl0DE4Cp7nTejSyPlWM5d7BJN9vTAuX5cxG1-hqRpUEQroyyAFU8Ap3djY9lzNfvIej1XPNHYaMcVP-L368R_gIkN7d-nCspEbOvT5uq1UAajFcfaYPm4B7ymdyLd_uiwHC1ZtmQBIBb3s2DVbmpXX4GNCTyOwCH2YzYOB0m2nLPXSLQf6Z2L/s320/blog_popularity.png" width="320" /></a></div></div><br />A 10% improvement in frequency of posts and being upto date with quality reduces popularity by 10 times again I am cooking up these numbers.<br />
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB-skYsPFaCxvek90Fu3uxVPvn_Co4upFhE4GGI9ztimGpkLhshghdpV64SjlSgDaufGq_jfUydsYMX1HBK6-BWHKKV-qfw1u-H72Y_IX1jige5v-UylkEO9Pccgmv5S7GRrPLNyVoMOk/s1600/blogsnapsthanks.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="479" data-original-width="965" height="198" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgB-skYsPFaCxvek90Fu3uxVPvn_Co4upFhE4GGI9ztimGpkLhshghdpV64SjlSgDaufGq_jfUydsYMX1HBK6-BWHKKV-qfw1u-H72Y_IX1jige5v-UylkEO9Pccgmv5S7GRrPLNyVoMOk/s400/blogsnapsthanks.png" width="400" /></a></div>
<div>
<br /></div>
<div>
If you are from an impoverished country lower in income strata (esp african) than Indians this blog will not consume much of your data balance.<br />
I have as a goal, tried to be of help to learners of computer graphics. Blogging is a very effective way of reaching out to fellow learners. I have decided to now devote most of my weekends to seriously working on graphics projects with two goals:<br />
<br />
1) Impact more learners<br />
2) Make my blog more popular and cater to the needs of the those learners in need of guidance,<br />
<br />
So starting henceforth you will see a qualitatively different blog with lot more content, products, projects and features updated and posted more frequently. You will have links and access to world class literature curated personally by me from across the web.<br />
<br />
I also intend to cater to a wider community of visitors esp those who visit this blog for not more than 2 minutes.<br />
<br />
Happy Surfing...</div>
</div><br />
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-21362854763447137812018-07-01T04:21:00.007-07:002023-01-28T21:05:53.365-08:00Drawing a triangle in an ANDROID App using OpenGL ES<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Android apps are easily created using the android studio. Here the foremost priority for me was getting to create an OpenGL ES environment and draw a shape such as a triangle. I referred to the <a href="https://developer.android.com/training/graphics/opengl/shapes" target="_blank">developer.android.com</a> site where most of the explanation is voluminous and detailed to follow. It took me quite a while to fully understand.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
I had to download an android studio which took a lot of time and finally after a few days I was good to go. </div>
<div style="text-align: justify;">
I made my mobile work in developer mode and made several projects just to understand what developing for android feels like. </div>
<div style="text-align: justify;">
<b>The First app</b></div>
<div style="text-align: justify;">
The first app I made was an empty project. It involved just giving a name to the project and letting all the default settings as it is. I had seen one of my students fiddle with an app where he downloaded the app in his mobile and run it. I just did the same with this empty project and my mobile.</div>
<div style="text-align: justify;">
<b>The Second app</b></div>
<div style="text-align: justify;">
A hello world app followed next. It just displayed a hello world message on the screen which I learnt to change.</div>
<div style="text-align: justify;">
<b>The Third app</b></div>
<div style="text-align: justify;">
This one read a text message and upon clicking Ok button sent the message to the next screen that displayed the message.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
While all this was practice I jumped into making android apps which were more complex with the one where the app displays a triangle using OpenGL ES environment. I tried displaying a triangle using OpenGL.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
I launched the app in the emulator. It started with the following screen.</div>
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhupI1oSqEsWG9Ty3mpBGJ7jSX-qOHjkREoFODS6FUwnZFHnoltStQ-LWuzE6Z7LAd7WaASSg8tqkxSbgHdAk4vJWajfwccwk9Nn_KDjflg9Rx2CZoSdjlbZ2szq5TU6r3zhnzxZSJUPSk/s1600/androidtriangle1.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="619" data-original-width="353" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhupI1oSqEsWG9Ty3mpBGJ7jSX-qOHjkREoFODS6FUwnZFHnoltStQ-LWuzE6Z7LAd7WaASSg8tqkxSbgHdAk4vJWajfwccwk9Nn_KDjflg9Rx2CZoSdjlbZ2szq5TU6r3zhnzxZSJUPSk/s320/androidtriangle1.png" width="181" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
There were several problems I encountered esp with OpenGL ES environment. It was frustrating to expect a triangle on the screen and just getting a black background. I knew I needed to persevere so after a few days I found time to set the kinks in order and finally was able to draw a triangle in OpenGL ES on the emulator.</div>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwJseXeYoiX0XQkiwLNUgrLGJKZrpTiCd9bqjKfD25DfxrX57qkKsutxDa1NDNoBJTBvJBnxC4ZxwSbGDfzV5vSbQHH8B_p2WOHL3wMZq8U9qeoiaiDyReBKym3fGmVZsRDTFvH2HqAWI/s1600/androidtriangle2.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="595" data-original-width="351" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwJseXeYoiX0XQkiwLNUgrLGJKZrpTiCd9bqjKfD25DfxrX57qkKsutxDa1NDNoBJTBvJBnxC4ZxwSbGDfzV5vSbQHH8B_p2WOHL3wMZq8U9qeoiaiDyReBKym3fGmVZsRDTFvH2HqAWI/s320/androidtriangle2.png" width="188" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
I am well versed with OpenGL so immediately wanted to start off with drawing a Sierpinski gasket. I was very very tired that night. First up next morning I might not even have brushed. I was glued to the computer for nearly two hours. It was frustrating again.</div>
<div style="text-align: justify;">
I will list out exactly what went wrong.--- Will update Soon.</div><div style="text-align: justify;"><b>Update1:</b></div><div style="text-align: justify;">Here is the latest app which goes further ahead and divides the triangle into sierpinski gasket:</div><div style="text-align: justify;">https://cglabprojects.blogspot.com/2023/01/sierpinski-gasket-in-android-app.html</div>
</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-44541212127653978662018-06-06T05:46:00.000-07:002018-06-06T05:46:15.275-07:00Modern OpenGL- Drawing a Triangle(With Vertex and Fragment Shaders)<div dir="ltr" style="text-align: left;" trbidi="on">
It was quite exhausting to toil since the past two months trying to install Code::Blocks and getting GLFW,<br />
GLEW and<br />
GLM<br />
to run in it.<br />
I followed this <a href="http://www.codeincodeblock.com/2013/05/setup-modern-opengl-3-and-4-with-glfw.html" target="_blank">link</a> to get them installed.<br />
For the shader code I referred to this site: <a href="https://open.gl/drawing" target="_blank">Open.gl</a><br />
Also referred to this amazing <a href="https://learnopengl.com/" target="_blank">Site</a> also. I have coded this project so shabbily that I have not kept track of how many external libraries I have included. There is <b>Linmath</b>, there is <b>GLAD</b> and <b>SFML</b> and a few others were included without any real necessity.<br />
<br />
I hope they will become useful as I go along.<br />
<br />
<b><span style="font-size: large;"><i>Drawing a Triangle</i></span></b><br />
<b><span style="font-size: large;"><br /></span></b>
The drawing part has been explained very well in the sites I mentioned. We need to make use of VertexArrayObjects(VAOs) and VertexBufferObjects(VBOs).<br />
In modern OpenGL we need to include short programs called shader programs and get them <b>created, compiled, linked</b> and then <b>attach</b> them to a program, then <b>link</b> the program with our main project.<br />
Finally call glDrawArrays which does the <b>drawing </b>of the VBOs.<br />
<br />
<b><span style="font-size: large;"><i>The Book of Shaders</i></span></b><br />
This site which you can google is what I am following and will keep posting the solutions of the amazing pictures I generate.<br />
<br />
For the present I am simply sharing the code <a href="https://drive.google.com/open?id=1JVxQQ3cSBLi2sE3J3JeGXCWLTJUQvvB5" target="_blank">here</a>.<br />
<br />
Snapshot:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgziwTC2dOFxGaUsDQTfjEW-YP7xb8rz1tgumwsaeOM___y9mIQz8QEqdjZRxvoUAnhCau1HrJm3ITttMYdgr4cnDxgeL8WyDcvw2tcomKV7OyCMkKUrASrxiPJPZEQXOhqPi8YmY3vNzA/s1600/Triangle%2528shader%2529.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="527" data-original-width="664" height="316" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgziwTC2dOFxGaUsDQTfjEW-YP7xb8rz1tgumwsaeOM___y9mIQz8QEqdjZRxvoUAnhCau1HrJm3ITttMYdgr4cnDxgeL8WyDcvw2tcomKV7OyCMkKUrASrxiPJPZEQXOhqPi8YmY3vNzA/s400/Triangle%2528shader%2529.png" width="400" /></a></div>
<br />
When you move your mouse around the screen the color of the triangle changes. This change is brought about by the following fragment shader code.<br />
<br />
static const char* fragment_shader_text =<br />
"varying vec3 color;\n"<br />
"uniform float u_time;\n"<br />
"uniform vec2 u_resolution;\n"<br />
"uniform vec2 u_mouse;\n"<br />
"void main() {\n"<br />
" <span style="white-space: pre;"> </span>gl_FragColor = vec4(<b>u_mouse.x/u_resolution.x,u_mouse.y/u_resolution.y</b>,0.0,1.0);\n"<br />
"}\n";<br />
<div>
<br /></div>
<div>
Thanks for following till this point.</div>
<div>
Will try and keep you all abreast of any further project.</div>
</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0tag:blogger.com,1999:blog-5330394525986174688.post-57401507334951055022018-05-05T10:16:00.002-07:002018-05-05T10:16:32.131-07:00Procedural Terrain Generation<div dir="ltr" style="text-align: left;" trbidi="on">
I had written a post on texture generation using procedural noise. I use the same technique to generate a terrain. The explanation of this code is in this site: <a href="http://lodev.org/cgtutor/randomnoise.html">http://lodev.org/cgtutor/randomnoise.html</a><br />
<br />
<br />
Here is a snapshot:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNxkJjN-xMY4CSbc2xeMCPohE85NERTU7TTQdVe3JLxnoh97Mupsxi2mZABdg3zeZ7iurHDUZCNVGveufcfEfyyElJPnd-quzVkRWEtkTD3LCOP3BGzsu-7HE2lf56pRARIADa33MoEIM/s1600/ProceduralTerrainGeneration.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="729" data-original-width="1001" height="291" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNxkJjN-xMY4CSbc2xeMCPohE85NERTU7TTQdVe3JLxnoh97Mupsxi2mZABdg3zeZ7iurHDUZCNVGveufcfEfyyElJPnd-quzVkRWEtkTD3LCOP3BGzsu-7HE2lf56pRARIADa33MoEIM/s400/ProceduralTerrainGeneration.png" width="400" /></a></div>
<br />
Here is the <span id="goog_1189285599"></span><a href="https://drive.google.com/open?id=1jnh5mZcIbu2u_UaS_WrjaATtN-FXKqKy" target="_blank">code</a><span id="goog_1189285600"></span>.</div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com1tag:blogger.com,1999:blog-5330394525986174688.post-70303354301973417232018-05-04T11:03:00.000-07:002018-05-04T23:26:49.453-07:00Diamond Square Algorithm in C/C++<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
I have implemented the Diamond Square Algorithm as depicted in this site =><a href="https://www.bluh.org/code-the-diamond-square-algorithm/">https://www.bluh.org/code-the-diamond-square-algorithm/</a></div>
<div style="text-align: justify;">
It is a way of generating height maps for computer graphics. These height maps can be used as textures or landscapes. It is a slightly better algorithm than the three-dimensional implementation of the midpoint displacement algorithm which produces two-dimensional landscapes. It is also known as the <b>random midpoint displacement fractal</b>, the <b>cloud fractal</b> or the <b>plasma fractal</b>, because of the plasma effect produced when applied.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
For further details refer: <a href="https://en.wikipedia.org/wiki/Diamond-square_algorithm">https://en.wikipedia.org/wiki/Diamond-square_algorithm</a></div>
<div style="text-align: justify;">
<br /></div>
I chanced upon this topic while searching for Fractal Terrain Generation.<br />
<br />
Snapshots:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkD8Bmw1f6-HwpruI2Gczjy2EzJpvp0Rom-GCvbnqw4VfJa8OMTi12iXhdpTSK4krwzZuA5M1GucdW9HCY8RbmhzZfa9Blt0JHrq8qEegcJw0uH35TbIcZm7IF54P_niFzpIzQ1wHAkkc/s1600/DSA1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="512" data-original-width="640" height="256" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhkD8Bmw1f6-HwpruI2Gczjy2EzJpvp0Rom-GCvbnqw4VfJa8OMTi12iXhdpTSK4krwzZuA5M1GucdW9HCY8RbmhzZfa9Blt0JHrq8qEegcJw0uH35TbIcZm7IF54P_niFzpIzQ1wHAkkc/s320/DSA1.png" width="320" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGxvC1f0wg9noxw0ABV35fbE236kSjymO3U7ExbMN5qDEZRq3gjUaHHhMMV5aT1N0Xd5xcpr_smd1rIgkmmxWWa39LsIdt_18AQQzmb6oouzAr6XK2mlgAueLJNxVd_eaAHT3twhGh1ys/s1600/DSA.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="511" data-original-width="640" height="255" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGxvC1f0wg9noxw0ABV35fbE236kSjymO3U7ExbMN5qDEZRq3gjUaHHhMMV5aT1N0Xd5xcpr_smd1rIgkmmxWWa39LsIdt_18AQQzmb6oouzAr6XK2mlgAueLJNxVd_eaAHT3twhGh1ys/s320/DSA.png" width="320" /></a></div>
<div>
<br /></div>
<div>
Here is the <a href="https://drive.google.com/open?id=1CpMnX4lpZn9u2bFRpx4rtcWpF_8QDQZq" target="_blank">code</a>.</div>
<br /></div>
A Gaming Enthusiasthttp://www.blogger.com/profile/03993385858950822199noreply@blogger.com0