Heim > Web-Frontend > js-Tutorial > Hauptteil

Aufschlüsselung des WebGL-Dreiecks-Setups

Mary-Kate Olsen
Freigeben: 2024-10-11 10:44:02
Original
966 Leute haben es durchsucht

WebGL a la réputation d’être l’une des API Javascript les plus complexes. En tant que développeur Web intrigué par tout ce qui est interactif, j'ai décidé de me plonger dans la documentation MDN de WebGL. J'ai travaillé avec Three.js qui résume une grande partie des difficultés de WebGL mais je n'ai pas pu m'empêcher d'ouvrir le capot !

Le but de cette étude approfondie était de voir si je pouvais donner suffisamment de sens à la documentation pour l'expliquer en termes plus simples. Avis de non-responsabilité — J'ai travaillé avec Three.js et j'ai quelques connaissances en terminologie et modèles graphiques 3D. Je ne manquerai pas d'expliquer ces concepts s'ils s'appliquent de quelque manière que ce soit.

Pour commencer, nous allons nous concentrer sur la création d’un triangle. La raison en est de comprendre les éléments nécessaires à la configuration de WebGL.

Pour avoir une idée de ce qui sera couvert, voici les étapes que nous allons suivre.

  • Configurer le canevas HTML

  • Obtenir le contexte WebGL

  • Effacez la couleur de la toile et définissez-en une nouvelle

  • Créer un tableau de coordonnées triangulaires (x,y)

  • Ajouter du code de vertex et de fragment shader

  • Traiter et compiler le code du shader

  • Créer un programme webGL

  • Créer et lier des tampons au programme webGL

  • Utiliser le programme

  • Liez les informations du GPU au CPU

  • Dessine le triangle

Configurer le canevas HTML

  1. Créez un dossier appelé « RenderTriangle »
  2. Dans ce dossier, créez un fichier index.html et main.js

Dans le fichier index.html ajoutez le code suivant :

index.js

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="main.js"></script>
</html>
Nach dem Login kopieren
  1. est le point d'entrée pour le rendu du contexte WebGL

  2. Nous configurons le code HTML de base et lions le fichier main.js.

  3. Dans le fichier main.js, nous accéderons à l'identifiant du canevas pour restituer le contenu webGL.

Préparer le canevas HTML

Dans le fichier main.js, ajoutez le code suivant qui prépare le canevas HTML :

main.js

// get canvas
const canvas = document.getElementById("canvas");

// set width and height of canvas
canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

// get the webgl context
const gl = canvas.getContext("webgl2");
Nach dem Login kopieren
  1. Récupérez le canevas HTML par identifiant et stockez-le dans une variable appelée « canevas » (vous pouvez utiliser n'importe quel nom).

  2. Définissez les propriétés canvas.width et canvas.height du canevas en accédant aux window.innerWidth et window.innerHeight . Cela définit l'affichage rendu à la taille de la fenêtre du navigateur.

  3. Récupérez le contexte WebGL en utilisant canvas.getContext("webgl2") et stockez-le dans une variable appelée "gl".

Couleur claire

main.js

gl.clearColor(0.1, 0.2, 0.3, 1.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
Nach dem Login kopieren

Avant d'écrire un programme webGL, vous devez définir la couleur d'arrière-plan de votre canevas. WebGL dispose de deux méthodes pour y parvenir.

clearColor() — est une méthode qui définit une couleur d'arrière-plan spécifique. Cela s'appelle « clearColor » car lorsque vous affichez WebGL dans le canevas HTML, CSS définit l'arrière-plan sur la couleur noire. Lorsque vous appelez clearColor(), cela efface la couleur par défaut et définit la couleur souhaitée. Nous pouvons le voir ci-dessous.

Remarque : Le clearColor() a 4 paramètres (r, g, b, a)

clear() — après l'appel de clearColor() et la définition d'une couleur d'arrière-plan explicite,
**clear()** doit être appelé pour « effacer » ou réinitialiser les tampons aux valeurs prédéfinies (les tampons sont un stockage temporaire pour les informations de couleur et de profondeur).

La méthode clear() est l'une des méthodes de dessin, ce qui signifie que c'est la méthode qui restitue réellement la couleur. Sans appeler la méthode clear(), le canevas n'affichera pas le clearColor. Les options du paramètre clear() sont,
sont gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT ou gl.STENCIL_BUFFER_BIT.

Dans le code ci-dessous, vous pouvez ajouter plusieurs paramètres à réinitialiser dans différents scénarios.

  1. gl.DEPTH_BUFFER_BIT — indique des tampons pour les informations sur la profondeur des pixels

  2. gl.COLOR_BUFFER_BIT — indique les tampons pour les informations sur la couleur des pixels

Définir les coordonnées du triangle

main.js

// set position coordinates for shape
const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];
Nach dem Login kopieren

Une fois l'arrière-plan défini, nous pouvons définir les coordonnées nécessaires pour créer le triangle. Les coordonnées sont stockées dans un tableau sous forme de coordonnées (x, y).

Le tableau ci-dessous contient des coordonnées à 3 points. Ces points se connectent pour former le triangle.

0.0, -1.0
0.0 , 1.0
1.0, 1.0

Ajout de vertex et de fragments shaders

main.js

const vertexShader = `#version 300 es
precision mediump float;

in vec2 position;

void main() {
 gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w
}
`;


const fragmentShader = `#version 300 es
precision mediump float;

out vec4 color;

void main () {
 color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a
}
`;
Nach dem Login kopieren

Après avoir créé une variable pour les coordonnées du triangle, nous pouvons configurer les shaders.

A shader is a program written in OpenGL ES Shading Language. The program takes position and color information about each vertice point. This information is what’s needed to render geometry.

There are two types of shaders functions that are needed to draw webgl content, the vertex shader and fragment shader

*vertex shader *— The vertex shader function uses position information to render each pixel. Per every render, the vertex shader function runs on each vertex. The vertex shader then transforms each vertex from it’s original coordinates to WebGL coordinates. Each transformed vertex is then saved to the gl_Position variable in the vertex shader program.

*fragment shader *— The fragment shader function is called once for every pixel on a shape to be drawn. This occurs after the vertex shader runs. The fragment shader determines how the color of each pixel and “texel (pixel within a texture)” should be applied. The fragment shader color is saved in the gl_FragColor variable in the fragment shader program.

In the code above we are creating both a vertexShader and fragmentShader constant and storing the shader code in them. The Book of Shaders is a great resource for learning how to write GLSL code.

Processing the Vertex and Fragment Shaders

main.js

// process vertex shader
const shader = gl.createShader(gl.VERTEX_SHADER);

gl.shaderSource(shader, vertexShader);

gl.compileShader(shader);

if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log(gl.getShaderInfoLog(vertexShader));
}


// process fragment shader
const shader = gl.createShader(gl.FRAGMENT_SHADER);

gl.shaderSource(shader, fragmentShader);

gl.compileShader(shader);

if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log(gl.getShaderInfoLog(fragmentShader));
}
Nach dem Login kopieren

Now that we wrote the shader code (GLSL), we need to create the shader. The shader code still needs to compile. To do this we call the following functions:

createShader() — This creates the shader within the WebGL context

shaderSource() — This takes the GLSL source code that we wrote and sets it into the webGLShader object that was created with createShader.

compileShader() — This compiles the GLSL shader program into data for the WebGLProgram.

The code above processes the vertex and fragment shaders to eventually compile into the WebGLProgram.

Note: An if conditional is added to check if both shaders have compiled properly. If not, an info log will appear. Debugging can be tricky in WebGL so adding these checks is a must.

Creating a WebGL Program

main.js

const program = gl.createProgram();

// Attach pre-existing shaders
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);

gl.linkProgram(program);

if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  const info = gl.getProgramInfoLog(program);
  throw "Could not compile WebGL program. \n\n${info}";
}
Nach dem Login kopieren

Let’s review the code above:

After compiling the vertexShader and fragmentShader, we can now create a WebGLProgram. A WebGLProgram is an object that holds the compiled vertexShader and fragmentShader.

createProgram() — Creates and initializes the WebGLProgram

attachShader() — This method attaches the shader to the webGLProgram

linkProgram() — This method links the program object with the shader objects

Lastly, we need to make a conditional check to see if the program is running properly. We do this with the gl.getProgramParameter.

Create and Bind the Buffers

Now that the WebGL Program is created and the shader programs are linked to it, it’s time to create the buffers. What are buffers?

To simplify it as much as possible, buffers are objects that store vertices and colors. Buffers don’t have any methods or properties that are accessible. Instead, the WebGL context has it’s own methods for handling buffers.

Buffer — “a temporary storage location for data that’s being moved from one place to another”
-wikipedia

We need to create a buffer so that we can store our triangle colors and vertices.

To do this we add the following:

main.js

const buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW);

gl.bindBuffer(gl.ARRAY_BUFFER, null);
Nach dem Login kopieren

In the code above we’re creating a buffer (or temporary storage object) using the createBuffer() method. Then we store it in a constant. Now that we have a buffer object we need to bind it to a target. There are several different target but since we’re storing coordinates in an array we will be using the gl.ARRAY_BUFFER.

To bind the buffer to a target, we use gl.bindBuffer() and pass in the gl.ARRAY_BUFFER (target) and the buffer itself as parameters.

The next step would be to use gl.bufferData() which creates the data store. gl.bufferData() takes the following parameters:

targetgl.ARRAY_BUFFER
datanew Float32Array(triangleCoords)
usage (draw type) — gl.STATIC_DRAW

Lastly, we unbind the buffer from the target to reduce side effects.

Use Program

main.js

gl.useProgram(program);
Nach dem Login kopieren

Once the buffer creation and binding is complete, we can now call the method that sets the WebGLProgram to the rendering state.

Link GPU and CPU

As we get closer to the final step, we need to talk about attributes.

In WebGL, vertex data is stored in a special variable called attributes. attributes are only available to the javascript program and the vertex shader. To access the attributes variable we need to first get the location of the attributes from the GPU. The GPU uses an index to reference the location of the attributes.

main.js

// get index that holds the triangle position information
const position = gl.getAttribLocation(obj.program, obj.gpuVariable);

gl.enableVertexAttribArray(position);

gl.bindBuffer(gl.ARRAY_BUFFER, buffer);

gl.vertexAttribPointer(position, 2, gl.FLOAT, obj.normalize, obj.stride, obj.offset);
Nach dem Login kopieren

Let’s review the code above:

Since we’re rendering a triangle we need the index of the position variable that we set in the vertex shader. We do this using the gl.getAttribLocation() method. By passing in the WebGL program and the position variable name (from the vertex shader) we can get the position attribute’s index.

Next, we need to use the gl.enableVertexAttribArray() method and pass in the position index that we just obtained. This will enable the attributes` storage so we can access it.

We will then rebind our buffer using gl.bindBuffer() and pass in the gl.ARRAY_BUFFER and buffer parameters (the same as when we created the buffers before). Remember in the “Create and Bind the Buffers” section we set the buffer to null to avoid side effects.

When we binded the buffer to the gl.ARRAY_BUFFER we are now able to store our attributes in a specific order. gl.vertexAttribPointer() allows us to do that.

By using gl.vertexAttribPointer() we can pass in the attributes we’d like to store in a specific order. The parameters are ordered first to last.

The gl.vertexAttribPointer is a more complex concept that may take some additional research. You can think of it as a method that allows you to store your attributes in the vertex buffer object in a specific order of your choosing.

Sometimes 3D geometry already has a certain format in which the geometry information is set. vertexAttribPointer comes in handy if you need to make modifications to how that geometry information is organized.

Draw Triangle

main.js

gl.drawArrays(gl.TRIANGLES, 0, 3);
Nach dem Login kopieren

Lastly, we can use the gl.drawArrays method to render the triangle. There are other draw methods, but since our vertices are in an array, this method should be used.

gl.drawArrays() takes three parameters:

mode — which specifies the type of primitive to render. (in this case were rendering a triangle)

first — specifies the starting index in the array of vector points (our triangle coordinates). In this case it’s 0.

count — specifies the number of indices to be rendered. ( since it's a triangle we’re rendering 3 indices)

Note: For more complex geometry with a lot of vertices you can use **triangleCoords.length / 2 **to ****get how many indices your geometry has.

Finally, your triangle should be rendered to the screen! Let’s review the steps.

Breaking Down the WebGL Triangle Setup

  • Set up the HTML canvas

  • Get the WebGL context

  • Clear the canvas color and set a new one

  • Create an array of triangle (x,y )coordinates

  • Add vertex and fragment shader code

  • Process and compile the shader code

  • Create a webGL program

  • Create and bind buffers to the webGL program

  • Use the program

  • Link the GPU information to the CPU

  • Draw out the triangle

The API is a complex one so there’s still a lot to learn but understanding this setup has given me a better foundation.

// Set up the HTML canvas
const canvas = document.getElementById("canvas");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

// get the webgl context
const gl = canvas.getContext("webgl2");

// Clear the canvas color and set a new one
gl.clearColor(0.1, 0.2, 0.3, 1.0);
gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);


// Create an array of triangle (x,y )coordinates
const triangleCoords = [0.0, -1.0, 0.0, 1.0, 1.0, 1.0];

// Add vertex and fragment shader code
const vertexShader = `#version 300 es
precision mediump float;
in vec2 position;

void main() {
gl_Position = vec4(position.x, position.y, 0.0, 1.0); //x,y,z,w
}
`;

const fragmentShader = `#version 300 es
precision mediump float;
out vec4 color;

void main () {
color = vec4(0.0,0.0,1.0,1.0); //r,g,b,a
}
`;


// Process and compile the shader code
const vShader = gl.createShader(gl.VERTEX_SHADER);

gl.shaderSource(vShader, vertexShader);
gl.compileShader(vShader);

if (!gl.getShaderParameter(vShader, gl.COMPILE_STATUS)) {
 console.log(gl.getShaderInfoLog(vertexShader));
}


const fShader = gl.createShader(gl.FRAGMENT_SHADER);

gl.shaderSource(fShader, fragmentShader);
gl.compileShader(fShader);

if (!gl.getShaderParameter(fShader, gl.COMPILE_STATUS)) {
console.log(gl.getShaderInfoLog(fragmentShader));
}

// Create a webGL program
const program = gl.createProgram();


// Link the GPU information to the CPU
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);

gl.linkProgram(program);


if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
const info = gl.getProgramInfoLog(program);
throw "Could not compile WebGL program. \n\n${info}";
}


// Create and bind buffers to the webGL program
const buffer = gl.createBuffer();

gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(triangleCoords), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);


// Use the program
gl.useProgram(program);



// Link the GPU information to the CPU
const position = gl.getAttribLocation(program, "position");

gl.enableVertexAttribArray(position);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.vertexAttribPointer(position, 2, gl.FLOAT, gl.FALSE, 0, 0);


// render triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);
Nach dem Login kopieren

Here are some invaluable references to help understand this material better.

https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API
https://www.udemy.com/course/webgl-internals/
https://webglfundamentals.org/

Das obige ist der detaillierte Inhalt vonAufschlüsselung des WebGL-Dreiecks-Setups. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:dev.to
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!