- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
问题在于当我将要绘制的纹理传递给片段着色器时,它是一个 64x64 RGBA 无符号 8 位纹理。我看过其他人的代码,阅读函数定义。使用 glGetError()
检查错误,无论我将它放在程序中的什么位置,它都会返回 0,直到它在调用 glDrawArrays(GL_TRIANGLES, 0, 6);
后抛出访问冲突可能是非常明显的事情,我最近问了一个问题,但我一直在努力自己解决这个问题。所以我希望我不会觉得问这个问题很麻烦。
这是我尝试将纹理加载到内存中的代码
glGenTextures(1, textures);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, BTH_IMAGE_WIDTH, BTH_IMAGE_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, BTH_IMAGE_DATA);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
这是我尝试将它传递给着色器的地方
GLint texture0 = glGetUniformLocation(gShaderProgram, "texture0");
glUniform1i(texture0, 0);
我的片段着色器
#version 400
out vec4 fragment_color;
uniform sampler2D texture0;
in fData
{
vec3 normal;
vec4 color;
mat4 v;
vec2 tex_coord;
} frag;
void main () {
vec3 n = normalize(frag.normal);
float intensity = min(max(dot(n, vec3(0,0,-1)), 0.0), 1.0);
//fragment_color = frag.color * (intensity);
fragment_color = texture(texture0,frag.tex_coord.st) * intensity;
}
完整的 main.cpp
//--------------------------------------------------------------------------------------
// BTH - Stefan Petersson 2014.
//--------------------------------------------------------------------------------------
#include <vector>
#include <windows.h>
#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
#include <chrono>
#include <gl/glew.h>
#include <gl/GL.h>
# define M_PI 3.14159265358979323846
#include "glm\glm.hpp"
#include "glm\gtc\matrix_transform.hpp"
#include "bth_image.h"
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glew32.lib")
using namespace std;
using namespace glm;
HWND InitWindow(HINSTANCE hInstance);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
HGLRC CreateOpenGLContext(HWND wndHandle);
GLuint gVertexBuffer = 0;
GLuint gVertexAttribute = 0;
GLuint gShaderProgram = 0;
GLuint textures[1];
mat4x4 view;
mat4x4 world;
mat4x4 projection;
float DT;
struct CPUvalues
{
float v1;
float v2;
float v3;
float v4;
};
CPUvalues Gv = { 0.5, 0, 0, 0 };
GLuint gu = 0;
#define BUFFER_OFFSET(i) ((char *)nullptr + (i))
void CreateShaders()
{
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
ifstream shaderFile("VertexShader.glsl");
std::string shaderText((std::istreambuf_iterator<char>(shaderFile)), std::istreambuf_iterator<char>());
shaderFile.close();
const char* shaderTextPtr = shaderText.c_str();
glShaderSource(vs, 1, &shaderTextPtr, nullptr);
glCompileShader(vs);
//create fragment shader | same process.
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
shaderFile.open("Fragment.glsl");
shaderText.assign((std::istreambuf_iterator<char>(shaderFile)), std::istreambuf_iterator<char>());
shaderFile.close();
shaderTextPtr = shaderText.c_str();
glShaderSource(fs, 1, &shaderTextPtr, nullptr);
glCompileShader(fs);
GLuint gs = glCreateShader(GL_GEOMETRY_SHADER);
shaderFile.open("GMshader.glsl");
shaderText.assign((std::istreambuf_iterator<char>(shaderFile)), std::istreambuf_iterator<char>());
shaderFile.close();
shaderTextPtr = shaderText.c_str();
glShaderSource(gs, 1, &shaderTextPtr, nullptr);
glCompileShader(gs);
GLint success = 0;
glGetShaderiv(gs, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
GLint logSize = 0;
glGetShaderiv(gs, GL_INFO_LOG_LENGTH, &logSize);
std::vector<GLchar> errorLog(logSize);
glGetShaderInfoLog(gs, logSize, &logSize, &errorLog[0]);
for (int i = 0; i < errorLog.size(); i++)
{
cout << errorLog.at(i);
}
}
//link shader program (connect vs and ps)
gShaderProgram = glCreateProgram();
glAttachShader(gShaderProgram, fs);
glAttachShader(gShaderProgram, gs);
glAttachShader(gShaderProgram, vs);
glLinkProgram(gShaderProgram);
glGenTextures(1, textures);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, BTH_IMAGE_WIDTH, BTH_IMAGE_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, BTH_IMAGE_DATA);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
GLint isLinked = 0;
glGetProgramiv(gShaderProgram, GL_LINK_STATUS, &isLinked);
if (isLinked == GL_FALSE)
{
GLint maxLength = 0;
glGetProgramiv(gShaderProgram, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(gShaderProgram, maxLength, &maxLength, &infoLog[0]);
for (GLint i = 0; i < maxLength; i++)
{
cout << infoLog.at(i);
}
}
}
void CreateTriangleData()
{
// this is how we will structure the input data for the vertex shader
// every six floats, is one vertex.
struct TriangleVertex
{
float x, y, z;
float r, g, b;
float s, t;
};
// create the actual data in plane Z = 0
TriangleVertex triangleVertices[6] =
{
// pos and color for each vertex
{ -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f },
{ 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f },
{ -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f },
{ 0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f },
{ 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f },
{ -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f }
};
// Vertex Array Object (VAO)
glGenVertexArrays(1, &gVertexAttribute);
// bind == enable
glBindVertexArray(gVertexAttribute);
// this activates the first and second attributes of this VAO
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
// create a vertex buffer object (VBO) id
glGenBuffers(1, &gVertexBuffer);
// Bind the buffer ID as an ARRAY_BUFFER
glBindBuffer(GL_ARRAY_BUFFER, gVertexBuffer);
// This "could" imply copying to the GPU, depending on what the driver wants to do...
glBufferData(GL_ARRAY_BUFFER, sizeof(triangleVertices), triangleVertices, GL_STATIC_DRAW);
// query where which slot corresponds to the input vertex_position in the Vertex Shader
GLint vertexPos = glGetAttribLocation(gShaderProgram, "vertex_position");
// specify that: the vertex attribute "vertexPos", of 3 elements of type FLOAT, not normalized, with STRIDE != 0,
// starts at offset 0 of the gVertexBuffer (it is implicitly bound!)
glVertexAttribPointer(vertexPos, 3, GL_FLOAT, GL_FALSE, sizeof(TriangleVertex), BUFFER_OFFSET(0));
// query where which slot corresponds to the input vertex_color in the Vertex Shader
//GLint vertexColor = glGetAttribLocation(gShaderProgram, "vertex_color");
// specify that: the vertex attribute "vertex_color", of 3 elements of type FLOAT, not normalized, with STRIDE != 0,
// starts at offset (12 bytes) of the gVertexBuffer
//glVertexAttribPointer(vertexColor, 3, GL_FLOAT, GL_FALSE, sizeof(TriangleVertex), BUFFER_OFFSET(sizeof(float)*3));
GLint tex_coord = glGetAttribLocation(gShaderProgram, "coord");
glVertexAttribPointer(tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(TriangleVertex), BUFFER_OFFSET(sizeof(float)*6));
//cout << "Error: "<< glGetError() << endl;
}
void SetViewport()
{
glViewport(0, 0, 640, 480);
}
void Render()
{
// set the color TO BE used
glClearColor(0, 0, 0, 1);
// use the color to clear the color buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(gShaderProgram);
glBindVertexArray(gVertexAttribute);
glGenBuffers(1, &gu);
glBindBuffer(GL_UNIFORM_BUFFER, gu);
//glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(CPUvalues), &Gv);
GLint _p = glGetUniformLocation(gShaderProgram, "p");
GLint _m = glGetUniformLocation(gShaderProgram, "m");
GLint _v = glGetUniformLocation(gShaderProgram, "v");
//glActiveTexture(GL_TEXTURE0);
//glBindTexture(GL_TEXTURE_2D, textures[0]);
GLint texture0 = glGetUniformLocation(gShaderProgram, "texture0");
glUniform1i(texture0, 0);
glUniformMatrix4fv(_p, 1, GL_FALSE, &projection[0][0]);
glUniformMatrix4fv(_m, 1, GL_FALSE, &world[0][0]);
glUniformMatrix4fv(_v, 1, GL_FALSE, &view[0][0]);
//GLint texture0 = glGetUniformLocation(gShaderProgram, "texture0");
//glUniform1i(texture0, GL_TEXTURE0);
// draw 3 vertices starting from index 0 in the vertex array currently bound (VAO), with current in-use shader
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
cout << "Error: " << glGetError() << endl;
glDrawArrays(GL_TRIANGLES, 0, 6);
}
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
AllocConsole();
freopen("CONOUT$", "w", stdout);
DT = 0.016;
MSG msg = { 0 };
HWND wndHandle = InitWindow(hInstance); //1. Skapa fönster
if (wndHandle)
{
HDC hDC = GetDC(wndHandle);
HGLRC hRC = CreateOpenGLContext(wndHandle); //2. Skapa och koppla OpenGL context
glewInit(); //3. Initiera The OpenGL Extension Wrangler Library (GLEW)
SetViewport(); //4. Sätt viewport
CreateShaders(); //5. Skapa vertex- och fragment-shaders
CreateTriangleData(); //6. Definiera triangelvertiser, 7. Skapa vertex buffer object (VBO), 8.Skapa vertex array object (VAO)
ShowWindow(wndHandle, nCmdShow);
view = lookAt(vec3(0, 0, -2), vec3(0, 0, 0), vec3(0, 1, 0));
mat4x4 sm;
sm = scale(sm, vec3(1, 1, 1));
mat4x4 tm;
tm = translate(tm, vec3(0, 0, 0));
mat4x4 rm;
rm = mat4x4(1);
projection = perspective<float>(M_PI*0.45, 640 / 480, 0.1, 20);
while (WM_QUIT != msg.message)
{
auto start_time = chrono::high_resolution_clock::now();
//Gv.v1 += 0.05 * DT;
Gv.v1 += 1 * DT;
world = tm * rotate(rm, Gv.v1, vec3(0, 1, 0)) * sm;
if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Render(); //9. Rendera
SwapBuffers(hDC); //10. Växla front- och back-buffer
}
auto final_time = chrono::high_resolution_clock::now() - start_time;
DT = chrono::duration_cast<std::chrono::milliseconds>(final_time).count() / (double)1000;
}
wglMakeCurrent(NULL, NULL);
ReleaseDC(wndHandle, hDC);
wglDeleteContext(hRC);
DestroyWindow(wndHandle);
}
return (int) msg.wParam;
}
HWND InitWindow(HINSTANCE hInstance)
{
WNDCLASSEX wcex = { 0 };
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = L"BTH_GL_DEMO";
if( !RegisterClassEx(&wcex) )
return false;
RECT rc = { 0, 0, 640, 480 };
AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
HWND handle = CreateWindow(
L"BTH_GL_DEMO",
L"BTH OpenGL Demo",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
rc.right - rc.left,
rc.bottom - rc.top,
nullptr,
nullptr,
hInstance,
nullptr);
return handle;
}
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
switch (message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
HGLRC CreateOpenGLContext(HWND wndHandle)
{
//get handle to a device context (DC) for the client area
//of a specified window or for the entire screen
HDC hDC = GetDC(wndHandle);
//details: http://msdn.microsoft.com/en-us/library/windows/desktop/dd318286(v=vs.85).aspx
static PIXELFORMATDESCRIPTOR pixelFormatDesc =
{
sizeof(PIXELFORMATDESCRIPTOR), // size of this pfd
1, // version number
PFD_DRAW_TO_WINDOW | // support window
PFD_SUPPORT_OPENGL | // support OpenGL
PFD_DOUBLEBUFFER, // double buffered
PFD_TYPE_RGBA, // RGBA type
32, // 32-bit color depth
0, 0, 0, 0, 0, 0, // color bits ignored
0, // no alpha buffer
0, // shift bit ignored
0, // no accumulation buffer
0, 0, 0, 0, // accum bits ignored
0, // 0-bits for depth buffer <-- modified by Stefan
0, // no stencil buffer
0, // no auxiliary buffer
PFD_MAIN_PLANE, // main layer
0, // reserved
0, 0, 0 // layer masks ignored
};
//attempt to match an appropriate pixel format supported by a
//device context to a given pixel format specification.
int pixelFormat = ChoosePixelFormat(hDC, &pixelFormatDesc);
//set the pixel format of the specified device context
//to the format specified by the iPixelFormat index.
SetPixelFormat(hDC, pixelFormat, &pixelFormatDesc);
//create a new OpenGL rendering context, which is suitable for drawing
//on the device referenced by hdc. The rendering context has the same
//pixel format as the device context.
HGLRC hRC = wglCreateContext(hDC);
//makes a specified OpenGL rendering context the calling thread's current
//rendering context. All subsequent OpenGL calls made by the thread are
//drawn on the device identified by hdc.
wglMakeCurrent(hDC, hRC);
return hRC;
}
BTH_IMAGE_WIDTH、BTH_IMAGE_HEIGHT 和 BTH_IMAGE_DATA 在 bth_image.h 中定义,以下是其定义的内容(由于 BTH_IMAGE_DATA 较大,将不包括整个定义)
const unsigned int BTH_IMAGE_WIDTH = 64;
const unsigned int BTH_IMAGE_HEIGHT = 64;
//Image data stored in 8-bit RGBA format
unsigned char BTH_IMAGE_DATA[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,16,16,16,16,16,16,16...........
};
调用 sizeof(BTH_IMAGE_DATA) 得到 16384,它的大小与未压缩的 8 位 64x64 RGBA 编码纹理相匹配(它被硬编码为大学作业的一部分,我对此无能为力)
最佳答案
这次崩溃与纹理无关,而是与您设置顶点属性数组指针的方式有关。
GL 将从您启用的每个数组中获取属性值,并且您在此处为通用顶点属性 0、1 和 2 启用属性数组:
glBindVertexArray(gVertexAttribute);
// this activates the first and second attributes of this VAO
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
稍后,您为两个数组设置属性指针:
GLint vertexPos = glGetAttribLocation(gShaderProgram, "vertex_position");
glVertexAttribPointer(vertexPos, 3, GL_FLOAT, GL_FALSE, sizeof(TriangleVertex), BUFFER_OFFSET(0));
GLint tex_coord = glGetAttribLocation(gShaderProgram, "coord");
glVertexAttribPointer(tex_coord, 2, GL_FLOAT, GL_FALSE, sizeof(TriangleVertex), BUFFER_OFFSET(sizeof(float)*6));
这里有两个错误:
您的第一部分假定 0、1、2 是着色器使用的相关属性索引。由于您从未手动明确分配属性位置(通过顶点着色器代码中的 layout(location=...)
,或在链接程序之前通过 glBindAttribLocation
,此假设是完全错误。GL 不需要从 0 开始按顺序分配属性位置(尽管大多数情况下如此),而且您也不能假定任何特定顺序。
您启用了 3 个数组,但只为两个数组设置了一个属性指针。在最好的情况下,其中两个实际上是您启用的两个,在最坏的情况下,它们是完全不同的集合——尽管如此,您仍然至少有一个启用的数组,您从未为其设置指针.默认的顶点指针在客户端内存中只是NULL
。因此,您的绘制调用将尝试取消引用 NULL
指针,操作系统将在尝试中终止您的进程,这是应该的。
关于c++ - 尝试将纹理映射到 GLSL 中的三角形时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48014641/
下面的代码旨在在首次打开工作簿时运行。 Sub Auto_Open() Dim LastRow As Integer LastRow = Sheet6.UsedRange.Rows.Count Act
当我尝试操作我的代码时,除了弹出调试错误外,它执行得很好。错误信息在这里。 我的完整代码在这里。 #include using namespace std; class String { publi
The invocation of the constructor on type 'WpfApplication1.MainWindow' that matches the specified bi
我正在使用 BaseAdapter: public class MyAdapter extends BaseAdapter{ private final LayoutInflater mInflate
我想做网页抓取。我写了代码 var connection = require('./mysqlConnection'); var c = new Crawler({ maxConnections
我的系统中发生 Java 堆空间错误。我尝试了很多来自 Stack Overflow 的解决方案,但没有任何效果。当我工作时 当按下 OK 然后 (我的项目没有错误) 我的 eclipse.ini 是
环境: i5 750 DDR3 4GWin7 专业版 x64 sp1 DXSDK 9.0c 2010 年 6 月 GeForce GT240(驱动程序 275.33)512MB MSVC 2008 s
这段代码是我写的。 import socket host = 'localhost' port = 3794 s = socket.socket(socket.AF_INET, socket.SOCK
我正在尝试引用 UTC 时间间隔获取本地日期时间,我正在执行下面的代码。 var dtString =DateTime.UtcNow.ToString(@"yyyy-MM-ddTHH\:mm\:ss
我有一个非常简单的 C# 问题,它从库中加载 Windows WPF 窗口。这是代码: public partial class App : Application { public App(
我目前正在使用带有导航组件的底部导航,它工作正常但是当我们点击导航项 fragment 正在加载然后闪烁正在发生,即使当前选择的项目也会发生闪烁。它在加载 fragment 时发生。我的应用程序屏幕背
我是新来的 kotlin , 当我开始 Null Safety 时,我对下面的情况感到困惑. There's some data inconsistency with regard to initia
我有一个框,其中包含同时发生的两个独立的 css 转换。 当转换发生时,图标下方的标题和段落文本移动位置 参见 JS Fiddle:http://jsfiddle.net/Lsnbpt8r/ 这是我的
在为黑莓 10 构建电话间隙应用程序时,我遇到了异常情况。 [BUILD] Populating application source [BUILD] Parsing config.xml [
这个问题在这里已经有了答案: How to properly stop the Thread in Java? (8 个回答) 3年前关闭。 我看过How to properly stop the T
我试图弄清楚发生 fatal error 时如何刷新页面。基本上我正在访问图像 api 并将图像复制到我的服务器。我还每次都创建照片的缩略图版本。我会每隔一段时间收到一条错误消息,指出我的脚本试图分配
我正在尝试使用断言函数检查元素是否在屏幕上。我在我的测试应用程序 (AndroidDriver) 中使用 Appium 和 Java。我期望的是,如果元素在屏幕上,则返回 1;如果不在屏幕上,则返回
我正在开发图像上传系统。我使用 CommonsMultipartResolver 设置 maxUploadSize。当我尝试上传超过最大尺寸的图像文件时,会发生 MaxUploadSizeExcced
我有以下代码和@ComponentScan(basePackages = "com.project.shopping"),包结构为 com.project.shopping.Controller co
我尝试运行此程序作为测试,但收到错误“发生了 JNI 错误,请检查您的安装并重试”,然后是“发生了 Java 异常”。关于如何解决这个问题有什么想法吗? package java; public cl
我是一名优秀的程序员,十分优秀!