WebGL简易教程(十一):纹理

【基于Leaflet和Canvas绘图的前端大量栅格数据渲染】 基于Leaflet地图引擎,利用canvas绘制大量栅格数据,30万坐标点的渲染时间在500ms以内。 阅读详情

1. 概述

在之前的之前的教程《WebGL简易教程(九):综合实例:地形的绘制》中,绘制了一个带颜色的地形场景。地形的颜色是根据高程赋予的RGB值,通过不同的颜色来表示地形的起伏,这是表达地形渲染的一种方式。除此之外,还可以将拍摄得到的数字影像,贴到地形上面,得到更逼真的地形效果。这就要用到我们这一章的新知识——纹理了。

这里用到的纹理图像,是一张从GoogleEarth上下载的卫星影像DOM.tif,其范围正好覆盖地形数据。为了方便使用,特意将其转换为JPG格式的影像:tex.jpg。并放到与HTML和JS同目录下。用图像查看软件打开图像的显示效果为:
image

注意,在大部分浏览器(如chrome)中,基于安全策略是不允许访问本地文件的。WebGL的纹理需要用到本地的图像,所以需要将浏览器设置成支持跨域访问或者建立服务器在域内使用。

2. 实例

基于《WebGL简易教程(九):综合实例:地形的绘制》中的JS代码进行改进:

// 顶点着色器程序
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' + //位置
  'attribute vec4 a_Color;\n' + //颜色
  'uniform mat4 u_MvpMatrix;\n' +
  'varying vec4 v_Color;\n' +
  'varying vec4 v_position;\n' +
  'void main() {\n' +
  '  v_position = a_Position;\n' +
  '  gl_Position = u_MvpMatrix * a_Position;\n' + // 设置顶点坐标
  '  v_Color = a_Color;\n' +
  '}\n';

// 片元着色器程序
var FSHADER_SOURCE =
  'precision mediump float;\n' +
  'uniform vec2 u_RangeX;\n' + //X方向范围
  'uniform vec2 u_RangeY;\n' + //Y方向范围
  'uniform sampler2D u_Sampler;\n' +
  'varying vec4 v_Color;\n' +
  'varying vec4 v_position;\n' +
  'void main() {\n' +
  '  vec2 v_TexCoord = vec2((v_position.x-u_RangeX[0]) / (u_RangeX[1]-u_RangeX[0]), 1.0-(v_position.y-u_RangeY[0]) / (u_RangeY[1]-u_RangeY[0]));\n' +
  '  gl_FragColor = texture2D(u_Sampler, v_TexCoord);\n' +
  '}\n';

//定义一个矩形体:混合构造函数原型模式
function Cuboid(minX, maxX, minY, maxY, minZ, maxZ) {
  this.minX = minX;
  this.maxX = maxX;
  this.minY = minY;
  this.maxY = maxY;
  this.minZ = minZ;
  this.maxZ = maxZ;
}

Cuboid.prototype = {
  constructor: Cuboid,
  CenterX: function () {
    return (this.minX + this.maxX) / 2.0;
  },
  CenterY: function () {
    return (this.minY + this.maxY) / 2.0;
  },
  CenterZ: function () {
    return (this.minZ + this.maxZ) / 2.0;
  },
  LengthX: function () {
    return (this.maxX - this.minX);
  },
  LengthY: function () {
    return (this.maxY - this.minY);
  }
}

//定义DEM
function Terrain() { }
Terrain.prototype = {
  constructor: Terrain,
  setWH: function (col, row) {
    this.col = col;
    this.row = row;
  }
}

var currentAngle = [0.0, 0.0]; // 绕X轴Y轴的旋转角度 ([x-axis, y-axis])
var curScale = 1.0; //当前的缩放比例
var initTexSuccess = false; //纹理图像是否加载完成

function main() {
  var demFile = document.getElementById('demFile');
  if (!demFile) {
    console.log("Failed to get demFile element!");
    return;
  }

  //加载文件后的事件
  demFile.addEventListener("change", function (event) {
    //判断浏览器是否支持FileReader接口
    if (typeof FileReader == 'undefined') {
      console.log("你的浏览器不支持FileReader接口!");
      return;
    }

    //读取文件后的事件
    var reader = new FileReader();
    reader.onload = function () {
      if (reader.result) {
        var terrain = new Terrain();
        if (!readDEMFile(reader.result, terrain)) {
          console.log("文件格式有误,不能读取该文件!");
        }

        //绘制函数
        onDraw(gl, canvas, terrain);
      }
    }

    var input = event.target;
    reader.readAsText(input.files[0]);
  });

  // 获取 <canvas> 元素
  var canvas = document.getElementById('webgl');

  // 获取WebGL渲染上下文
  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for WebGL');
    return;
  }

  // 初始化着色器
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }

  // 指定清空<canvas>的颜色
  gl.clearColor(0.0, 0.0, 0.0, 1.0);

  // 开启深度测试
  gl.enable(gl.DEPTH_TEST);

  //清空颜色和深度缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}

//绘制函数
function onDraw(gl, canvas, terrain) {
  // 设置顶点位置
  //var cuboid = new Cuboid(399589.072, 400469.072, 3995118.062, 3997558.062, 732, 1268); 
  var n = initVertexBuffers(gl, terrain);
  if (n < 0) {
    console.log('Failed to set the positions of the vertices');
    return;
  }

  //设置纹理
  if (!initTextures(gl, terrain)) {
    console.log('Failed to intialize the texture.');
    return;
  }

  //注册鼠标事件
  initEventHandlers(canvas);

  //绘制函数
  var tick = function () {
    if (initTexSuccess) {
      //设置MVP矩阵
      setMVPMatrix(gl, canvas, terrain.cuboid);

      //清空颜色和深度缓冲区
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

      //绘制矩形体
      gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_SHORT, 0);
      //gl.drawArrays(gl.Points, 0, n);
    }

    //请求浏览器调用tick
    requestAnimationFrame(tick);
  };

  //开始绘制
  tick();
}

function initTextures(gl, terrain) {
  // 传递X方向和Y方向上的范围到着色器
  var u_RangeX = gl.getUniformLocation(gl.program, 'u_RangeX');
  var u_RangeY = gl.getUniformLocation(gl.program, 'u_RangeY');
  if (!u_RangeX || !u_RangeY) {
    console.log('Failed to get the storage location of u_RangeX or u_RangeY');
    return;
  }
  gl.uniform2f(u_RangeX, terrain.cuboid.minX, terrain.cuboid.maxX);
  gl.uniform2f(u_RangeY, terrain.cuboid.minY, terrain.cuboid.maxY);

  //创建一个image对象
  var image = new Image();
  if (!image) {
    console.log('Failed to create the image object');
    return false;
  }
  //图像加载的响应函数 
  image.onload = function () {
    if (loadTexture(gl, image)) {
      initTexSuccess = true;
    }
  };

  //浏览器开始加载图像
  image.src = 'tex.jpg';

  return true;
}

function loadTexture(gl, image) {
  // 创建纹理对象
  var texture = gl.createTexture();
  if (!texture) {
    console.log('Failed to create the texture object');
    return false;
  }

  // 开启0号纹理单元
  gl.activeTexture(gl.TEXTURE0);
  // 绑定纹理对象
  gl.bindTexture(gl.TEXTURE_2D, texture);

  // 设置纹理参数
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  // 配置纹理图像
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);

  // 将0号单元纹理传递给着色器中的取样器变量 
  var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
  if (!u_Sampler) {
    console.log('Failed to get the storage location of u_Sampler');
    return false;
  }
  gl.uniform1i(u_Sampler, 0);

  return true;
}

//读取DEM函数
function readDEMFile(result, terrain) {
  var stringlines = result.split("\n");
  if (!stringlines || stringlines.length <= 0) {
    return false;
  }

  //读取头信息
  var subline = stringlines[0].split("\t");
  if (subline.length != 6) {
    return false;
  }
  var col = parseInt(subline[4]); //DEM宽
  var row = parseInt(subline[5]); //DEM高
  var verticeNum = col * row;
  if (verticeNum + 1 > stringlines.length) {
    return false;
  }
  terrain.setWH(col, row);

  //读取点信息
  var ci = 0;
  terrain.verticesColors = new Float32Array(verticeNum * 6);
  for (var i = 1; i < stringlines.length; i++) {
    if (!stringlines[i]) {
      continue;
    }

    var subline = stringlines[i].split(',');
    if (subline.length != 9) {
      continue;
    }

    for (var j = 0; j < 6; j++) {
      terrain.verticesColors[ci] = parseFloat(subline[j]);
      ci++;
    }
  }

  if (ci !== verticeNum * 6) {
    return false;
  }

  //包围盒
  var minX = terrain.verticesColors[0];
  var maxX = terrain.verticesColors[0];
  var minY = terrain.verticesColors[1];
  var maxY = terrain.verticesColors[1];
  var minZ = terrain.verticesColors[2];
  var maxZ = terrain.verticesColors[2];
  for (var i = 0; i < verticeNum; i++) {
    minX = Math.min(minX, terrain.verticesColors[i * 6]);
    maxX = Math.max(maxX, terrain.verticesColors[i * 6]);
    minY = Math.min(minY, terrain.verticesColors[i * 6 + 1]);
    maxY = Math.max(maxY, terrain.verticesColors[i * 6 + 1]);
    minZ = Math.min(minZ, terrain.verticesColors[i * 6 + 2]);
    maxZ = Math.max(maxZ, terrain.verticesColors[i * 6 + 2]);
  }

  terrain.cuboid = new Cuboid(minX, maxX, minY, maxY, minZ, maxZ);

  return true;
}


//注册鼠标事件
function initEventHandlers(canvas) {
  var dragging = false; // Dragging or not
  var lastX = -1,
    lastY = -1; // Last position of the mouse

  //鼠标按下
  canvas.onmousedown = function (ev) {
    var x = ev.clientX;
    var y = ev.clientY;
    // Start dragging if a moue is in <canvas>
    var rect = ev.target.getBoundingClientRect();
    if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
      lastX = x;
      lastY = y;
      dragging = true;
    }
  };

  //鼠标离开时
  canvas.onmouseleave = function (ev) {
    dragging = false;
  };

  //鼠标释放
  canvas.onmouseup = function (ev) {
    dragging = false;
  };

  //鼠标移动
  canvas.onmousemove = function (ev) {
    var x = ev.clientX;
    var y = ev.clientY;
    if (dragging) {
      var factor = 100 / canvas.height; // The rotation ratio
      var dx = factor * (x - lastX);
      var dy = factor * (y - lastY);
      currentAngle[0] = currentAngle[0] + dy;
      currentAngle[1] = currentAngle[1] + dx;
    }
    lastX = x, lastY = y;
  };

  //鼠标缩放
  canvas.onmousewheel = function (event) {
    if (event.wheelDelta > 0) {
      curScale = curScale * 1.1;
    } else {
      curScale = curScale * 0.9;
    }
  };
}

//设置MVP矩阵
function setMVPMatrix(gl, canvas, cuboid) {
  // Get the storage location of u_MvpMatrix
  var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
  if (!u_MvpMatrix) {
    console.log('Failed to get the storage location of u_MvpMatrix');
    return;
  }

  //模型矩阵
  var modelMatrix = new Matrix4();
  modelMatrix.scale(curScale, curScale, curScale);
  modelMatrix.rotate(currentAngle[0], 1.0, 0.0, 0.0); // Rotation around x-axis 
  modelMatrix.rotate(currentAngle[1], 0.0, 1.0, 0.0); // Rotation around y-axis 
  modelMatrix.translate(-cuboid.CenterX(), -cuboid.CenterY(), -cuboid.CenterZ());

  //投影矩阵
  var fovy = 60;
  var near = 1;
  var projMatrix = new Matrix4();
  projMatrix.setPerspective(fovy, canvas.width / canvas.height, 1, 10000);

  //计算lookAt()函数初始视点的高度
  var angle = fovy / 2 * Math.PI / 180.0;
  var eyeHight = (cuboid.LengthY() * 1.2) / 2.0 / angle;

  //视图矩阵  
  var viewMatrix = new Matrix4(); // View matrix   
  viewMatrix.lookAt(0, 0, eyeHight, 0, 0, 0, 0, 1, 0);

  //MVP矩阵
  var mvpMatrix = new Matrix4();
  mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix);

  //将MVP矩阵传输到着色器的uniform变量u_MvpMatrix
  gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
}

//
function initVertexBuffers(gl, terrain) {
  //DEM的一个网格是由两个三角形组成的
  //      0------1            1
  //      |                   |
  //      |                   |
  //      col       col------col+1    
  var col = terrain.col;
  var row = terrain.row;

  var indices = new Uint16Array((row - 1) * (col - 1) * 6);
  var ci = 0;
  for (var yi = 0; yi < row - 1; yi++) {
    //for (var yi = 0; yi < 10; yi++) {
    for (var xi = 0; xi < col - 1; xi++) {
      indices[ci * 6] = yi * col + xi;
      indices[ci * 6 + 1] = (yi + 1) * col + xi;
      indices[ci * 6 + 2] = yi * col + xi + 1;
      indices[ci * 6 + 3] = (yi + 1) * col + xi;
      indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
      indices[ci * 6 + 5] = yi * col + xi + 1;
      ci++;
    }
  }

  //
  var verticesColors = terrain.verticesColors;
  var FSIZE = verticesColors.BYTES_PER_ELEMENT; //数组中每个元素的字节数

  // 创建缓冲区对象
  var vertexColorBuffer = gl.createBuffer();
  var indexBuffer = gl.createBuffer();
  if (!vertexColorBuffer || !indexBuffer) {
    console.log('Failed to create the buffer object');
    return -1;
  }

  // 将缓冲区对象绑定到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
  // 向缓冲区对象写入数据
  gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);

  //获取着色器中attribute变量a_Position的地址 
  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;
  }
  // 将缓冲区对象分配给a_Position变量
  gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0);

  // 连接a_Position变量与分配给它的缓冲区对象
  gl.enableVertexAttribArray(a_Position);

  //获取着色器中attribute变量a_Color的地址 
  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;
  }
  // 将缓冲区对象分配给a_Color变量
  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3);
  // 连接a_Color变量与分配给它的缓冲区对象
  gl.enableVertexAttribArray(a_Color);

  // 将顶点索引写入到缓冲区对象
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);

  return indices.length;
}

主要作了以下三点的改动以使用纹理。

2.1. 准备纹理

在WebGL中,由于JS的异步特性,需要在JS加载图片完成之后,再把图片当做纹理传入着色器进行绘制,所以首先这里定义了一个boolean全局变量initTexSuccess来标识纹理图像是否加载完成。在绘制函数onDraw()中,增加了一个设置纹理函数initTextures()。最后,在重绘刷新函数tick()中检测initTexSuccess变量,如果完成,就进行绘制。

var initTexSuccess = false;       //纹理图像是否加载完成

//...

//绘制函数
function onDraw(gl, canvas, terrain) {

  //...

  //设置纹理
  if (!initTextures(gl)) {
    console.log('Failed to intialize the texture.');
    return;
  }

  //...

  //绘制函数
  var tick = function () {
    if (initTexSuccess) {
         //...
    }

    //请求浏览器调用tick
    requestAnimationFrame(tick);
  };

  //开始绘制
  tick();
}

在初始化纹理函数initTextures()中,首先给着色器传入了X方向和Y方向上的实际坐标(局部坐标系坐标)范围,这个范围是用来计算纹理坐标的。接着创建了一个Image对象,通过这个对象来加载图像。最后给图像加载编写响应函数,一旦纹理配置函数loadTexture()成功,就设置initTexSuccess为true。

function initTextures(gl, terrain) {
  // 传递X方向和Y方向上的范围到着色器
  var u_RangeX = gl.getUniformLocation(gl.program, 'u_RangeX');
  var u_RangeY = gl.getUniformLocation(gl.program, 'u_RangeY');
  if (!u_RangeX || !u_RangeY) {
    console.log('Failed to get the storage location of u_RangeX or u_RangeY');
    return;
  }
  gl.uniform2f(u_RangeX, terrain.cuboid.minX, terrain.cuboid.maxX);
  gl.uniform2f(u_RangeY, terrain.cuboid.minY, terrain.cuboid.maxY);

  //创建一个image对象
  var image = new Image(); 
  if (!image) {
    console.log('Failed to create the image object');
    return false;
  }
  //图像加载的响应函数 
  image.onload = function () {
    if (loadTexture(gl, image)) {
      initTexSuccess = true;
    }
  };


  //浏览器开始加载图像
  image.src = 'tex.jpg';

  return true;
}

2.2. 配置纹理

在配置纹理函数loadTexture()中,首先创建了一个纹理对象,并将其绑定到0号纹理单元。WebGL至少支持8个纹理单元,内置的变量名形如gl.TEXTURE0、gl.TEXTURE1…gl.TEXTURE7。

function loadTexture(gl, image) {
  // 创建纹理对象
  var texture = gl.createTexture();
  if (!texture) {
    console.log('Failed to create the texture object');
    return false;
  }

  // 开启0号纹理单元
  gl.activeTexture(gl.TEXTURE0);
  // 绑定纹理对象
  gl.bindTexture(gl.TEXTURE_2D, texture);

  //...  

  return true;
}

接着通过gl.texParameteri()函数配置纹理的参数,这个函数规定了纹理在缩放时的插值方法,以及纹理填充时采用何种方式铺填。这里表示纹理缩放时采用线性插值,填充范围不够时采用纹理图像边缘值进行填充:

function loadTexture(gl, image) {
  //...

  // 设置纹理参数
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

  //...

  return true;
}

最后通过gl.texImage2D()函数将纹理对象分配给纹理对象。而该纹理对象已经与0号纹理单元绑定,因此直接将0号纹理单元作为Uniform变量传递给着色器:

function loadTexture(gl, image) {
  //...

  // 配置纹理图像
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);

  // 将0号单元纹理传递给着色器中的取样器变量 
  var u_Sampler = gl.getUniformLocation(gl.program, 'u_Sampler');
  if (!u_Sampler) {
    console.log('Failed to get the storage location of u_Sampler');
    return false;
  }
  gl.uniform1i(u_Sampler, 0);

  return true;
}

2.3. 使用纹理

在顶点着色器中,将顶点坐标值a_Position赋值为varying变量v_position,这个变量是用来传递给片元着色器的。

// 顶点着色器程序
var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' + //位置
  'attribute vec4 a_Color;\n' + //颜色
  'uniform mat4 u_MvpMatrix;\n' +
  'varying vec4 v_Color;\n' +
  'varying vec4 v_position;\n' +
  'void main() {\n' +
  '  v_position = a_Position;\n' +
  '  gl_Position = u_MvpMatrix * a_Position;\n' + // 设置顶点坐标
  '  v_Color = a_Color;\n' +
  '}\n';

经过内插,片元着色器接受到了每个片元对应的顶点坐标v_position。由于这个值是根据实际的顶点坐标(局部坐标系坐标)内插的,所以这个值也是实际坐标值。同时片元着色器也接收到了传递过来的纹理对象u_Sampler,可以通过texture2D()函数来获取对应坐标的像素,将其作为片元最终值:

// 片元着色器程序
var FSHADER_SOURCE =
  'precision mediump float;\n' +
  'uniform vec2 u_RangeX;\n' + //X方向范围
  'uniform vec2 u_RangeY;\n' + //Y方向范围
  'uniform sampler2D u_Sampler;\n' +
  'varying vec4 v_Color;\n' +
  'varying vec4 v_position;\n' +
  'void main() {\n' +
  '  vec2 v_TexCoord = vec2((v_position.x-u_RangeX[0]) / (u_RangeX[1]-u_RangeX[0]), 1.0-(v_position.y-u_RangeY[0]) / (u_RangeY[1]-u_RangeY[0]));\n' +
  '  gl_FragColor = texture2D(u_Sampler, v_TexCoord);\n' +
  '}\n';

上述代码可以看到并没有直接用v_position来进行插值。这是因为纹理坐标范围是在0~1之间,需要经过一个纹理映射的换算。如图所示,这是一个简单的线性变换的过程:
image

3. 结果

用浏览器运行,最终的显示结果如下,可以清楚的看到山川河流等纹理:
image
image

再次说明下这个实例用到了本地图片,需要让浏览器设置跨域或者建立服务器在域内使用。

4. 参考

本来部分代码和插图来自《WebGL编程指南》,源代码链接:地址 。会在此共享目录中持续更新后续的内容。

WebGL自学教程——WebGL示例:3. 纹理三角形 3. 纹理三角形       上章中的三角形虽然看起来比较鲜艳,但很多时候并不实用。我们想在三角形上显示一幅图片,或者更恰当点说,我们想让一张图片中和三角形对应的那一部分显示出来。这可以通过实用纹理图像来实现。这是本章的目的。     为了让WebGL可以访问我们指定图像数据,我们需要将图像数据保存到WebGL内部的纹理对象中。首先,我们要创建纹理对象,使用WebGL函数createText 阅读详情

相关推荐

WebGL系列教程六(纹理映射与立方体贴图)

上一讲我们讲了如何使用索引绘制彩色立方体,还留了一个思考题:怎么让立方体的每个面都保持一个颜色这一讲我们就来解决这个问题,并引出纹理映射和立方体贴图。其实这个词语还是比较好理解。见名知意,大概意思就是把纹理映射到某个地方,纹理是什么?现在你可以简单的认为纹理就是一张图片。把一张二维的图片映射到一个三维物体的表面,就叫纹理映射。本节我们从如何将立方体每个面的颜色改为相同的颜色开始,介绍到了如何将图片贴到立方体的表面,系统的分析了为什么不能再共用顶点,并将代码进行了修改,以及讲解了纹理坐标的使用。

rgrgrwfe的博客 1091

在 WebGL 中使用纹理贴图 (texture)

由美术工作人员生成的纹理最终在用来渲染前都应该使用放大或缩小的方式把它生成为 2 的幂纹理,其实事实上来说,在创作纹理之初就应该直接使用大小是 2 的幂的宽和高。纹理的每一边都应该是像 1,2,4,8,16,32,64,128,256,512,1024 或 2048 这样的值。这样虽然已经可以使用非 2 的幂纹理了,但是你将无法使用多级渐进纹理,纹理坐标包装,纹理坐标重复,而且无法控制设备如何处理你的纹理。现在我们只使用一张单一的纹理贴到立方体的 6 个面上,但是同样的方法可以用来加载任意数量的纹理贴图。

Kristen的博客 1590

WEBGL Shader零基础教程(十):顶点纹理拾取

本文介绍了WebGL着色器开发中的顶点纹理拾取技术,重点讲解了其原理、应用场景和实现方法。通过对比顶点纹理拾取与片元纹理拾取的差异,阐述了顶点纹理拾取在3D地形生成、数据可视化等场景的优势。文章详细拆解了顶点纹理拾取的四个核心步骤:纹理准备、坐标映射、采样计算和属性应用,并提供了两个基于Three.js的实战案例(顶点颜色控制和高度图地形生成)。最后总结了常见问题排查方法及优化技巧,如纹理格式选择、顶点数量优化等,为开发者提供了从基础到进阶的学习路径。掌握这项技术可实现更高效的3D渲染效果。

分享知识,拥抱变化 1158

一起学 WebGL:纹理对象学习

大家好,我是前端西瓜哥,今天我们来了解 WebGL 的纹理对象(Texture)纹理对象,是将像素(texels)以数组方式传给 GPU 的对象,常见场景是贴图,就是将图片的数据应用到 3D 物体上。

fe_watermelon的博客 1541

八、WebGL入门,纹理贴图

本节我们来讲WebGL里面很重要的纹理 纹理贴图在游戏开发中十分常见,但是纹理不单单只是一张贴图那么简单。 在WebGL中,纹理有多种,一维纹理:就是一条线;二维纹理:一张二维图片;二维纹理数组:由多张二维图片组成;还有三维纹理,立体纹理,本节主要介绍二维纹理 在早期的OpenGL中,只支持图片大小为2^n的纹理,但现在支持,但是最好用大小为2^n的纹理,这样效率会比较高 先看

a23366192007的博客 8341

七星棋牌顶级运营产品全开源修复版源码教程:6端支持,200+子游戏玩法,完整搭建指南(含代码解析)

让您从源码下载到本地运行一步到位!此外,文中还将附带详细代码解析与操作步骤,即便没有开发经验,也能轻松完成二开与定制。数据库是棋牌游戏中极为关键的组成部分,用于存储用户信息、乐豆余额、游戏记录、提现申请等数据。以下是部分核心数据表结构示例,便于存储用户信息与游戏记录。AI模块能够控制游戏中的胜率,常用于调节玩家体验。防沉迷功能旨在限制未成年人游戏时间。的完整搭建流程,特别适合。首先,获取七星棋牌源码。本教程将为您详细讲解。

aa2031171的博客 7911

webGL图片纹理

基础概念 坐标定义: 纹理坐标系范围是(0,1),左下角为(0,0),右上角为(1,1); webGL几何坐标系:x(-1, 1) y(-1, 1) gl.createTexture() —— 创建并初始化一个WebGLTexture对象,即创建一个纹理; gl.bindTexture(target, texture) 将给定的texture绑定到目标,其中texture参数为创建的纹理对象,target为绑定点,类型为GLenum,支持的值包括gl.TEXTURE_2D(二维纹理)、gl.T

落枫秋歌 1451

保姆级教程 | MS构建三层石墨后转成LAMMPS的data文件

喜欢的话记得一键三连~

baguette的博客 2961

WebGL颜色与纹理

在WebGL中,varying变量是在顶点着色器和片元着色器之间传递数据的一种特殊类型的变量。它们被用于在顶点着色器和片元着色器之间传递信息,以便在渲染过程中进行插值。在顶点着色器中,varying变量的值被计算并传递到片元着色器中,然后在片元着色器中进行插值,然后被用来确定要绘制的像素的颜色。Varying变量通常被用于将光照和纹理坐标等信息从顶点着色器传递到片元着色器中。由于它们是在渲染过程中插值的,所以它们可以用来创建平滑的过渡,使得渲染出来的图像更加真实和细腻。

gghhb12的博客 1652

S.BUS协议及编解码,C语言源码

1、简介 SBUS本质是一种串口通信协议,采用100K的波特率,8位数据位,两位停止位,偶效验,即8E2的串口通信。 值得注意的有三点: 1.SBUS采用负逻辑,所以无论接收还是发送都要进行硬件取反(注意,一定要硬件取反),电路如下 这是我在网上看资料时看到的电路,实际上我用的是下面这个电路 2.SBUS有两种模式, a.高速模式:每4ms发送一次 b...

qq_31232793的博客 1万+

2024年上市公司ESG评级全解析:六大权威数据源横向对比与应用指南

本文深度解析2024年国内主流ESG评级数据源,包括华证、商道融绿、Wind、富时罗素和彭博,横向对比其覆盖范围、评分逻辑与应用侧重点。文章提供实战指南,帮助投资者与企业根据投资决策、风险管理和学术研究等不同场景,精准选择并有效应用ESG数据,实现从概念到实用分析工具的转变。

weixin_29229055的博客 315

WebGL简易教程——目录

WebGL简易教程的目录汇总

Charlee44的技术驿站 4042

使用 Mid360 从零开始搭建实物机器人入门级导航系统 —— 基于 Fast_Lio 和 Move_Base

本文详细介绍了如何使用Mid360机器人从零开始搭建一个基于Fast_Lio和Move_Base的入门级导航系统。通过配置 ROS2、集成激光雷达、IMU、Fast_Lio、Move_Base 等模块,我们成功构建了一个能够实现自动导航的机器人系统。在实际开发中,随着需求的变化,你可以不断调整参数、优化路径规划算法、增加新的传感器等,逐步提升机器人的智能与功能。

小蜗牛的珍贵百宝箱 3595

WebGL 纹理的使用

通过本文的介绍,我们了解了 WebGL 中纹理的基本概念、加载和使用方法,以及纹理参数设置、多纹理使用和纹理压缩等高级技术。纹理是 WebGL 中非常重要的一部分,它可以为 3D 场景带来更加真实和生动的效果。希望通过本文的代码示例和讲解,你能够更好地掌握 WebGL 纹理的使用,创造出更加精彩的 WebGL 应用。在实际开发中,还可以进一步探索纹理的更多应用,如纹理动画、纹理映射变形等,不断提升 WebGL 应用的质量和性能。

candy的博客 1192

DeerFlow 系列教程 第二十篇 | 前端定制与二次开发指南

支持的语言定义在locale.tsLocale 检测采用三级降级策略Cookie 优先:检查localeCookie浏览器语言默认值en-US.value;if (locale!DeerFlow 使用管理主题切换,在根布局中通过主题相关的 CSS 变量定义在中(约 10KB)。: boolean;// 是否支持深度思考。

weixin_43674738的博客 234

使用 Simulink + Simscape Electrical 对 级联H桥多电平整流器并网功率分配 进行建模与仿真

摘要:本文详细介绍了基于Simulink对级联H桥(CHB)多电平整流器并网功率分配进行建模的方法。内容包括系统组成、功率分配意义、Simulink建模流程、PWM控制策略实现、功率分配算法设计以及仿真分析。重点阐述了主电路搭建、双环控制结构(外环功率分配+内环电流控制)和载波层叠PWM调制技术,并提供了功率分配算法示例。通过优化参数和控制算法,可提升系统性能。该建模方法为电力电子变换器和新能源并网系统研究提供了有效工具。

amy_mhd的博客 259

在 WebGL 中使用纹理

现在我们已经创建好了一个可以旋转的 3D 的立方体,接下来是时候使用贴图来代替每个面的单一的颜色了。

qq_25547755的博客 1188

01 - 什么是SVM

摘要:SVM(共享虚拟内存)技术使CPU和GPU能共享同一虚拟地址空间,简化异构计算编程。传统模型需手动管理CPU/GPU内存和拷贝数据,而SVM允许直接传递指针,自动处理页面迁移和一致性维护。其核心包括统一地址空间、按需迁移、页面故障处理和一致性管理,显著降低编程复杂度并提升性能。通过HMM框架、MMU通知和GPU页面异常等机制实现高效内存共享,支持复杂数据结构,为异构计算带来便利。

图形/计算GPU的驱动与虚拟化技术分享园地 3180

WebGL简易教程(十五):加载gltf模型

详述了通过WebGL读取、解析并显示glTF格式数据的过程。

Charlee44的技术驿站 6683

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

WebGL纹理贴图

WebGL纹理贴图 本文是WebGL电子书的1.12节内容 在实际的工程中创建三维场景往往会使用纹理贴图,简单地说就是把png、jpg等格式图片显示在WebGL三维场景中,比如一个产品的三维模型上贴一个商标。一张图片从数据结构的角度看, 文件中包含的信息就是和颜色缓冲区中的RGB或RGBA数据一样,.jpg格式图片数据包含RGB红绿蓝三个颜色分量,.png格式图片的数据除了RGB三个分量还包含透明...

u014291990的博客 4851

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

webgl不同图像不同纹理_WebGL教程:图像处理

webgl不同图像不同纹理In this tutorial you will learn how to use WebGL for image processing. We will cover basic stuff like initialization, texture loading, and simple fragment shaders. I will try to cover all...

cullen2012的博客 1119

webgl纹理贴图机制

在计算机图形学中,为了模拟更加真实的效果,需要给每个像素赋予不同的颜色值,这种情况下如果手动指定每个像素点的rgb值,将会是一件难以完成的任务。这就需要有一种机制,能够让我们把图片素材渲染到模型的一个或者多个表面上,这种机制叫做纹理贴图,本文将详细介绍在webgl中如何把一张真实图像贴到计算器图形上的。

qq_37987033的博客 3282

WebGL 动画纹理

在本演示中,我们以上一个示例为基础,将静态纹理替换为正在播放的 mp4 视频文件的帧。实际上,这很容易做到,而且观看起来很有趣,所以让我们开始吧。你可以使用类似的代码来使用任何类型的数据(例如 )作为纹理的源。

qq_25547755的博客 1277

webgl纹理

效果图: 操作步骤: 1.创建HTML5 canvas 2.获取画布 canvas 的 ID 3.获取WebGL 4.编译着色器,合并程序 //顶点着色器程序 var VSHADER_SOURCE = "attribute vec4 a_Position;" + "attribute vec2 a_TextCoord;" + // 接受纹理坐标 "varying vec2 v_TexCoord;" + // 传递纹理坐标 "vo

静儿的博客 1865

第 4 篇:赋予表面生命 - WebGL 纹理贴图

WebGL 纹理贴图简介 本文介绍了WebGL中的纹理贴图技术,通过给3D模型包裹2D图片来增加表面细节。核心概念是UV坐标系统,它使用百分比定位纹理位置(0-1范围)。实现步骤包括:升级着色器处理纹理坐标,加载图片资源,创建WebGL纹理对象并配置取样方式。最终演示了如何给正方形模型贴图,通过两个三角形拼接并映射纹理图片。关键点在于顶点着色器传递UV坐标,片元着色器使用texture2D函数取样颜色,以及JavaScript中正确的纹理加载和配置流程。

waws520的博客 1892
上一篇: WebGL简易教程(十):光照
下一篇: GDAL集成对KML文件的支持
charlee44
charlee44 新星创作者: 数据科学与机器学习技术领域 新星创作者: 数据科学与机器学习技术领域
博客等级 码龄16年 3922粉丝 326原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

charlee44

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值