1 前言
? ? ? ? 紋理貼圖的本質是將圖片的紋理坐標與模型的頂點坐標建立一一映射關系。紋理坐標的 x、y 軸正方向分別朝右和朝下,如下。
2 紋理貼圖
????????本節將使用?Mesh、ShaderProgram、Shader 實現紋理貼圖,OpenGL ES 的實現見博客 →?紋理貼圖。
????????DesktopLauncher.java
package com.zhyan8.game;import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.zhyan8.game.Chartlet;public class DesktopLauncher {public static void main (String[] arg) {Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();config.setForegroundFPS(60);config.setTitle("Chartlet");new Lwjgl3Application(new Chartlet(), config);}
}
????????Chartlet.java
package com.zhyan8.game;import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;public class Chartlet extends ApplicationAdapter {private ShaderProgram mShaderProgram;private Mesh mMesh;private Texture mTexture;@Overridepublic void create() {initShader();initMesh();mTexture = new Texture(Gdx.files.internal("textures/girl.jpg"));}@Overridepublic void render() {Gdx.gl.glClearColor(0.455f, 0.725f, 1.0f, 1.0f);Gdx.gl.glClear(GL30.GL_COLOR_BUFFER_BIT);mShaderProgram.bind();// mShaderProgram.setUniformi("u_texture", 0); // 設置紋理單元mTexture.bind(0);mMesh.render(mShaderProgram, GL30.GL_TRIANGLE_FAN);}@Overridepublic void dispose() {mShaderProgram.dispose();mMesh.dispose();}private void initShader() { // 初始化著色器程序String vertex = Gdx.files.internal("shaders/chartlet_vertex.glsl").readString();String fragment = Gdx.files.internal("shaders/chartlet_fragment.glsl").readString();mShaderProgram = new ShaderProgram(vertex, fragment);}private void initMesh() { // 初始化網格float[] vertices = {-1f, -1f, 0f, 0f, 1f, // 左下1f, -1f, 0f, 1f, 1f, // 右下1f, 1f, 0f, 1f, 0f, // 右上-1f, 1f, 0f, 0f, 0f // 左上};short[] indices = {0, 1, 2, 3};VertexAttribute vertexPosition = new VertexAttribute(Usage.Position, 3, "a_position");VertexAttribute texCoords = new VertexAttribute(Usage.TextureCoordinates, 2, "a_texCoord0");mMesh = new Mesh(true, vertices.length / 5, indices.length, vertexPosition, texCoords);mMesh.setVertices(vertices);mMesh.setIndices(indices);}
}
?????????chartlet_vertex.glsl
#version 300 esin vec3 a_position;
in vec2 a_texCoord0;out vec2 v_texCoord0;void main() {gl_Position = vec4(a_position, 1.0);v_texCoord0 = a_texCoord0;
}
????????chartlet_fragment.glsl
#version 300 es
precision mediump float; // 聲明float型變量的精度為mediumpin vec2 v_texCoord0;uniform sampler2D u_texture;out vec4 fragColor;void main() {fragColor = texture(u_texture, v_texCoord0);
}
? ? ? ? 運行效果。