Book connected to wen
The last bullet mainly introduced what WebGL is, and we understood what it is. I don’t know how much you remember, after all, this is a long time ago, if you forget, you can go back and quickly review it. Actually, it’s not much, it’s just a simple process of graphics programming. WebGL can provide hardware acceleration for HTML5 Canvas, which means using JS to call GL’s API to render in the browser. Wow! JS can do anything! Then I gave you a taste of how OpenGLES(WebGL is based on it) rendering pipeline and coloring language is written, but I haven’t actually written examples yet. Today this play I will share my introductory example!
Words say more, I am also a beginner, is front beginners, but also the beginner of WebGL, dare not say this is what is a few articles, this is just my study records, because just turn to the front, in order to cultivate interest in, find something fun, just met this thing, then with the help of spare time to learn from scratch, from work Then summarize and share it with you to exchange learning, which will inevitably have a lot of understanding mistakes, we can comment on the exchange of learning experience ah. Some students asked me how TO learn, in fact, very simple, nothing more than the Internet to search for all kinds of information to look up, buy books to read, hard to chew, and then understand, summarize, find examples of code practice, a long time, I learned. This process through the content of the far more than this a few articles of the much larger capacity, the article is just one of my learning process, may not be suitable for everyone, just as I also see a lot of other people’s articles and books, their ideas are not suitable for me, is just that I have been in the process of digestion of their content, the final summary to your understanding.
What is a Canvas
Remember, when Encyclopedia first learned about WebGL, the three points it got were JS, Canvas, and OpenGLES. Ok, we all know JS. Now let’s learn about Canvas. All of you are front-end masters, and Canvas is sure to know how to do it. I, who just entered the front of the pit, may still need to learn something. I don’t want to waste your time, I will go to W3School to learn, actually I am from Android, I have used Canvas, it is a Canvas, get a Paint brush, then call the API to draw things on it, points, lines, circles, arcs, rectangles, bitmaps, etc. In HTML5, too, the context is retrieved from the component and various apis are called to draw elements. If you think back to the history of HTML, if you wanted to display an image on a browser, that was all you had to doOf course, there are video and Flash solutions, but these are still limited to great artists. Until the emergence of Canvas, just like Ma Liang with magic brush ah!
(Photo from Internet)
Hardware acceleration and software acceleration
WebGL can provide hardware 3D accelerated rendering for HTML5 Canvas. What is hardware accelerated rendering? What is software acceleration?
The common explanation is that software acceleration is the programmer to write code to execute, to go further, that is to run the program on the CPU, hardware acceleration is not the programmer to write code to execute, handed to the hardware to execute, the most commonly said is GPU hardware acceleration. It’s like the programmer’s hands are free, it’s all hardware, so it’s faster? In fact, in a broad sense, CPU is also hardware ah, why not hardware acceleration? It due to the operating system, the credit of all the underlying hardware is “soft”, the university we have studied the computer composition principle and digital logic (digression, want to make up for the knowledge, my friends, I think amway a book all the code: the hidden behind the computer hardware and software of language, written really very good!) In fact, the CPU is the adder, modern CPU also provides a lot of instruction sets; As long as we don’t write assembly and program in a high-level language, everything about the underlying hardware is transparent, so we’re writing “soft” software.
(Photo from Internet)
Imagine, if we are to application performance bottlenecks, what do you think of the compiler may not achieve high-level language, not to maximize exert your CPU capacity, so you get to know all your CPU features, then write their own assembly call your CPU instruction set, use a variety of cache and register your function, if performance is improved. Is this hardware acceleration for the CPU?
Hardware acceleration does not go to the bottom to understand the characteristics of the hardware to programming, or programmers working, actually is just a field of everybody is different, also said before OpenGL and DirectX is in the middle tier for the graphics to help us do a lot of things, and different features of GPU and CPU is it has a huge number of nuclear, hundreds of thousands of all have, So it can run concurrently, which is the key to its acceleration.
(Photo from Internet)
The HelloWorld!
Based on all the previous learning, it can be understood that the drawing process of Canvas is actually completed in CPU, which consumes CPU computing time. Finally, a frame of image is produced, which is copied to video memory and then displayed by GPU. With WebGL, the drawing process of Canvas can be carried out on GPU, and CPU can be released to do other business logic.
Finally, the first code! Let’s start with a red dot on a green canvas, as shown below:
You can do it with canvas API in a couple of clicks, but how do you do it with WebGL? Try these steps step by step.
Write HTML code
Create a new hellworld.html file and write the following code:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>Hello World, WebGL! </title> </head> <body onload="main()"> <canvas id="webgl" width="800" height="800">Please use a browser that support "canvas".</canvas> <script type="text/javascript" src="Helloworld.js"></script> <script type="text/javascript" src="Helloworld-Shaders.js"></script> </body> </html>Copy the code
As you can see, the code is pretty simple. It’s just a simple HTML file that uses the tag (if the browser doesn’t support Canvas it will display the prompt text), introduces two JS files, and calls the main() function on the body onload. Helloworld.js is the js code logic, and helloworld-shaders. Js is the shader code wrapped around the string. We’ll talk about that in more detail.
Write shader code
Now comes the key to WebGL programming, where most of the programming will be done. Create a new helloworld-shaders.js file and write the following:
Var VERT_SHADER_SRC = 'void main() {gl_Position = vec4(0.0, 0.0, 0.0, 1.0); Gl_PointSize = 50.0; } `; Var FRAG_SHADER_SRC = 'void main() {gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0); } `;Copy the code
As you can see, this is basically just a js package with two strings, and of course it could be a plain text file, and then XMLHTTPRequest reads that file, but that’s a side note, and it doesn’t make a lot of sense. The code for these two shaders is very simple, not quite what it felt like the first time around. There are a lot of things missing.
Vertex shader
Just like in C, there is a main() function that doesn’t use any of the other variables passed in the first snap. It uses only two gl_xxx built-in variables, where gl_Position is the coordinate of the vertex. It must be set. Its type is VEC4, isn’t it strange why it’s not vec3 in three dimensions? (x, y, z, w) is the same thing as (x/w, y/w, z/w). You can go back and see why we use the homogeneous coordinate here. It’s mainly because it’s convenient to calculate in the future, and all kinds of transformations in the future will use matrix operations.
Gl_PointSize is the size of the vertex, that is, the number of pixels. It is not required and defaults to 1.0 if not set. Notice that they are all of type float, and you can’t write the type wrong, and the coloring language is strongly typed.
From the first bullet, we understand that every vertex of the graph we need to draw will be processed and transformed by vertex shader, and finally generate texture coordinates. Here, we do not need to transform the vertex receiving the graph, but only specify a central coordinate point for drawing.
Chip shader
It is also a built-in variable and the only output variable. From the first bullet, we learned that every rasterized fragment is executed once, which means that every pixel is executed once. In this example, it is used to draw a pixel. Gl_FragColor is a 4-dimensional vector. We learned that a pixel is RGBA 4 bytes, which requires 4 vectors. The difference is that a byte ranges from 0 to 255. This is because the GL inside the scope all have normalized processing, had learned maths all know this is what, elementary school, you will know what is a “unit”, the university should also know the normalized, so after processing, the processing of all would be simple, it also can bring the precision of a problem, it is commonly float precision. The subsequent study of texture size, coordinate system and so on will involve normalization.
You can modify the values above to see what happens.
Write JS code
The main flow code logic is in the helloworld.js file, we create a new js file, write the following code:
// Get the gl context from canvas, Function getWebGLContext(canvas, opt_attribs) {var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; var context = null; for (var i = 0; i < names.length; ++i) { try { context = canvas.getContext(names[i], opt_attribs); } catch(e) {} if (context) { break; } } return context; Function initShaders(GL, vshader, fshader) {// Create a shader that actually returns the int value, Var Program = createProgram(gl, vshader, fshader); if (! program) { console.log('Failed to create program'); return false; } // Specify that the gl context uses the shader gl.useProgram(program); gl.program = program; return true; } function createProgram(gl, vshader, fshader) { Var vertexShader = loadShader(gl, gl.vertex_shader, vshader); var fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fshader); if (! vertexShader || ! fragmentShader) { return null; } var program = gl.createProgram(); var program = gl.createProgram(); if (! program) { return null; } attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); // The link program is similar to the c compiler. gl.linkProgram(program); Var linked = gl.getprogramParameter (program, gl.link_status); var linked = gl.getprogramParameter (program, gl.link_status); if (! linked) { var error = gl.getProgramInfoLog(program); console.log('Failed to link program: ' + error); gl.deleteProgram(program); gl.deleteShader(fragmentShader); gl.deleteShader(vertexShader); return null; } return program; } function loadShader(gl, type, source) {var shader = gl.createshader (type); if (shader == null) { console.log('unable to create shader'); return null; } // load the source code for the shader gl.shadersource (shader, source); // Compile the shader code gl.pileshader (shader); Var compiled = gl.getShaderParameter(shader, gl.pile_status); var compiled = gl.getShaderParameter(shader, gl.pile_status); if (! compiled) { var error = gl.getShaderInfoLog(shader); console.log('Failed to compile shader: ' + error); gl.deleteShader(shader); return null; } return shader; Var canvas = document.getelementById ('webgl'); if(! canvas) { console.log('Failed to retrieve the <canvas> element'); return; Var gl = getWebGLContext(canvas); if(! gl) { console.log('Failed to get the rendering context for WebGL'); return; } // Initialize the shader if (! initShaders(gl, VERT_SHADER_SRC, FRAG_SHADER_SRC)) { console.log('Failed to intialize shaders.'); return; } // Set the canvas background color gl.clearcolor (0.0, 1.0, 0.0, 1.0); // Clear the color buffer gl.clear(gl.color_buffer_bit); // Draw a point gl.drawArrays(gl.POINTS, 0, 1); }Copy the code
Almost every line of the above code is commented, but I want to explain it in detail, which is the heart of it.
Execute the process
Looking at the main() function, the execution flow can be summarized in the following steps:
- The first step does not need to be explained too much. In WebGL, it works on Canvas and definitely needs to fetch elements.
- The getWebGLContext() function used in step 2 also calls the canvas.getContext() method, but it may be provided with a different name in different browsers. Context is an important concept here. A GL context corresponds to a GL instruction execution queue. If different contexts are mixed, the picture may break, which will be discussed later if encountered.
- The third step is to initialize the shader, as described below; The essence of the whole process is that the browser loads JS code and throws it to the JS engine for execution, while the JS code is loaded with shaders and then throws it to the WebGL system for execution.
- The fourth step is to set the background color of the canvas. ClearColor () is called, which can be understood as clearing the canvas and filling it with a color each time it is drawn. In addition, normalization has been mentioned above.
- The fifth step is to clear the color buffer, which is a very complicated concept, there are depth buffers, and there are template buffers, and the depth buffers I know are related to drawing in three dimensions, and the template buffers I don’t know much about; It is understood that the color buffer is a buffer that displays the drawing. The contents of this buffer will eventually be displayed on the screen, and if it is not cleared each time it is refreshed, the next display will be gaffed.
- The drawArrays() function is called. The first value tells you to draw a point, the second value tells you what point to draw from, and the third parameter tells you how many points to draw, as you’ll see later.
After this process, you can draw the point above, which means that the point will be executed by the shader code written above.
Initialize the shader process
Recall that OpenGLES ‘rendering pipeline 2.0 was introduced in the first shell. In such a complex pipeline, there are two shaders for programmers to develop code. We also know how to write shader code syntax, so how to write shader code in the pipeline to execute? How do I initialize the shader to execute the WebGL context with canvas?
- The first step is to create a shader, calling the createShader() method, which takes a constant type argument, VERTEX_SHADER or FRAGMENT_SHADER, either a vertex shader or a fragment shader, respectively. Note that the return value, OpenGL’s underlying specification is C, so all API returns are usually int, can be understood as the underlying reference to a handle, there is no actual object.
- The second step is to use the shader to load the source code, calling the shaderSource() method with the return of the first step as the first argument and the source string as the second argument.
- The third step is to compile the shader source, calling compileShader() and passing in the shader returned in the first step.
- The fourth step is to create a program that the pipeline will execute, calling createProgram().
- The fifth step is to attach the created pipeline to the compiled shader, calling attachShader() twice because there are two shaders.
- The sixth step is the link pipeline program, the call is linkProgram(), can be like learning C language need link library to understand it.
- The seventh step is to use the pipeline in the GL context, calling useProgram().
So far, a complete WebGL development process ran out, from the simple HTML, js, then how to run to the vertex shader, fragment to the pixel shader, to perform basically understand the development process of every link, although the content of the extension is not much, in the understanding is given priority to, from entry to not give up, Just be afraid of WebGL.
conclusion
This bullet I will first learn to understand these content, make up for the first bullet introductory example HelloWorld, the example is really simple, did not achieve anything valuable content, if the people who take over may be disappointed, I hope to understand the first bullet through a pixel to understand the rendering pipeline, Get a general idea of what WebGL programming is all about.
Follow-up for spare time again together learn more in-depth communication content, mostly because really busy work at ordinary times, also want to buy time exercise, after all we’re going to spend a lifetime time to write the code, rather than a retirement at age 35, so the body is the capital of revolution ah, in addition, the spare time or as far as possible and the ticket to play a more important, There’s really not much liver; The second is the same sentence, my study is based on understanding and developing interests, step by step, step by step, must have their own understanding.