当前位置:网站首页>webgl_ Enter the three-dimensional world (2)
webgl_ Enter the three-dimensional world (2)
2022-07-07 15:39:00 【Vegetable chicken on the road】
in real life , We often encounter two objects on the table one after the other , During observation , The front object will cover part of the back object .
Hidden face elimination
In order to solve the above problems ,WebGL Provide hidden surface elimination function . Let's draw the scene without considering the order of the objects in the buffer , Because those distant objects will automatically be blocked by nearby objects , Will not be drawn .
Turn on the hidden surface elimination function , There are two steps to follow :
1. Turn on the hidden surface elimination function .(gl.enable (gl. DEPTH_TEST);
2. Before drawing , Clear depth buffer .(gl.clear (gl.DEPTH_BUFEER_BIT);
Deep conflict
When the two surfaces of a geometric figure or object are very close , The surface looks mottled , This phenomenon is called deep conflict
According to this phenomenon ,webGL Provide a mechanism called polygon offset to solve this problem . This mechanism will automatically be in Z Value plus an offset , The value of the offset is determined by the angle of the object surface relative to the observer's line of sight . Enabling this mechanism requires only two lines of code :
1. Enable polygon offset .gl.enable(gl . POLYGON_OFFSET_FILL) ;
2. Specify the parameters used to calculate the offset before drawing .gl.polygonoffset (1.0,1.0 ) ;
Cube
We split the cube into vertices and triangles , Here's the picture 2( Left ) Shown . The cube is broken into 6 Face to face ﹔ front 、 after 、 Left 、 Right 、 On 、 Next , Each face is made up of two triangles , Associated with two triangles in the triangle list . Every triangle has 3 vertices , And... In the vertex list 3 Associated with a vertex , Here's the picture 2( Right ) Shown . The number in the triangle list indicates the 3 The index value of vertices in the vertex list ( Here's the picture (1)). Common in vertex list 8 vertices , The index value is from 0 To 7.
Get these vertex index values , We can use based on these data webgl Of gl.drawElementss() Method to draw the cube ;
Code examples :
// Vertex shader program
var VSHADER_SOURCE =
'attribute vec4 a_Position;'+
'attribute vec4 a_Color;'+
'uniform mat4 u_MvpMatrix;'+
'varying vec4 v_Color;'+
'void main(){'+
'gl_Position = u_MvpMatrix * a_Position;'+
'v_Color = a_Color;'+
'}';
// Chip shader program
var FSHADER_SOURCE=
'#ifdef GL_ES\n' +
'precision mediump float;\n' +
'#endif\n' +
'varying vec4 v_Color;' +
'void main() {'+
'gl_FragColor = v_Color;'+
'}';
function main() {
// obtain canvas Elements
var canvas = document.getElementById("webgl");
if(!canvas){
console.log("Failed to retrieve the <canvas> element");
return;
}
// obtain WebGL Drawing context
var gl = getWebGLContext(canvas);
if(!gl){
console.log("Failed to get the rendering context for WebGL");
return;
}
// Initialize shaders
if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){
console.log("Failed to initialize shaders.");
return;
}
// Set vertex position
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
// Specify empty <canvas> Color
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.enable(gl.DEPTH_TEST);
// obtain u_ViewMatrix 、u_ModelMatrix and u_ProjMatrix Where variables are stored
var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
if(u_MvpMatrix < 0){
console.log("Failed to get the storage location of u_MvpMatrix");
return;
}
var mvpMatrix = new Matrix4();
mvpMatrix.setPerspective(30, 1, 1, 100);
mvpMatrix.lookAt(3, 3, 7, 0, 0, 0, 0, 1, 0);
gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
gl.clear(gl.COLOR_BUFFER_BIT || gl.DEPTH_BUFFER_BIT);
// Draw a cube
gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_BYTE, 0);
}
function initVertexBuffers(gl) {
var verticesColors = new Float32Array([
// Vertex coordinates and colors
1.0, 1.0, 1.0, 1.0, 1.0, 1.0, // v0 white
-1.0, 1.0, 1.0, 1.0, 0.0, 1.0, // v1 magenta
-1.0, -1.0, 1.0, 1.0, 0.0, 0.0, // v2 Red
1.0, -1.0, 1.0, 1.0, 1.0, 0.0, // v3 yellow
1.0, -1.0, -1.0, 0.0, 1.0, 0.0, // v4 green
1.0, 1.0, -1.0, 0.0, 1.0, 1.0, // v5 Cyan
-1.0, 1.0, -1.0, 0.0, 0.0, 1.0, // v6 Blue
-1.0, -1.0, -1.0, 0.0, 0.0, 0.0 // v7 black
]);
// Vertex Index
var indices = new Uint8Array([
0, 1, 2, 0, 2, 3, // front
0, 3, 4, 0, 4, 5, // Right
0, 5, 6, 0, 6, 1, // On
1, 6, 7, 1, 7, 2, // Left
7, 4, 3, 7, 3, 2, // Next
4, 7, 6, 4, 6, 5 // after
]);
// Create buffer object
var vertexColorBuffer = gl.createBuffer();
var indexBuffer = gl.createBuffer();
if(!vertexColorBuffer || !indexBuffer){
console.log("Failed to create thie buffer object");
return -1;
}
// Save the buffer object to the target
gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
// Write data to the cache object
gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);
var FSIZE = verticesColors.BYTES_PER_ELEMENT;
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if(a_Position < 0){
console.log("Failed to get the storage location of a_Position");
return -1;
}
gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE*6, 0);
gl.enableVertexAttribArray(a_Position);
var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
if(a_Color < 0){
console.log("Failed to get the storage location of a_Color");
return -1;
}
gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE*6, FSIZE*3);
gl.enableVertexAttribArray(a_Color);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
return indices.length;
}
here ,webgl The internal state is :
effect :
边栏推荐
- 【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)
- [data mining] visual pattern mining: hog feature + cosine similarity /k-means clustering
- [quick start of Digital IC Verification] 29. Ahb-sramc (9) (ahb-sramc svtb overview) of SystemVerilog project practice
- STM32F103C8T6 PWM驱动舵机(SG90)
- TypeScript 发布 4.8 beta 版本
- Ida Pro reverse tool finds the IP and port of the socket server
- Why do we use UTF-8 encoding?
- Ctfshow, information collection: web5
- Nacos conformance protocol cp/ap/jraft/distro protocol
- 知否|两大风控最重要指标与客群好坏的关系分析
猜你喜欢
With 8 modules and 40 thinking models, you can break the shackles of thinking and meet the thinking needs of different stages and scenes of your work. Collect it quickly and learn it slowly
使用cpolar建立一个商业网站(2)
15. Using the text editing tool VIM
【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
The bank needs to build the middle office capability of the intelligent customer service module to drive the upgrade of the whole scene intelligent customer service
How to create Apple Developer personal account P8 certificate
There is a cow, which gives birth to a heifer at the beginning of each year. Each heifer has a heifer at the beginning of each year since the fourth year. Please program how many cows are there in the
2. 堆排序『较难理解的排序』
Create lib Library in keil and use lib Library
[deep learning] image hyperspectral experiment: srcnn/fsrcnn
随机推荐
Android -- jetpack: the difference between livedata setValue and postvalue
【数字IC验证快速入门】20、SystemVerilog学习之基本语法7(覆盖率驱动...内含实践练习)
MongoD管理数据库的方法介绍
Oracle控制文件丢失恢复归档模式方法
leetcode 241. Different ways to add parentheses design priority for operational expressions (medium)
Ctfshow, information collection: web6
jacoco代码覆盖率
大表delete删数据导致数据库异常解决
【深度学习】语义分割实验:Unet网络/MSRC2数据集
Ctfshow, information collection: web2
【OBS】RTMPSockBuf_ Fill, remote host closed connection.
最安全的证券交易app都有哪些
写一篇万字长文《CAS自旋锁》送杰伦的新专辑登顶热榜
Implementation of crawling web pages and saving them to MySQL using the scrapy framework
What is data leakage
What is Base64?
【數字IC驗證快速入門】26、SystemVerilog項目實踐之AHB-SRAMC(6)(APB協議基本要點)
Ctfshow, information collection: web12
leetcode 241. Different Ways to Add Parentheses 为运算表达式设计优先级(中等)
With 8 modules and 40 thinking models, you can break the shackles of thinking and meet the thinking needs of different stages and scenes of your work. Collect it quickly and learn it slowly