[OpenGL] 使用折射与反射的玻璃球

2023-10-29 12:40

本文主要是介绍[OpenGL] 使用折射与反射的玻璃球,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

        本次demo绘制了一个球体,包含了反射以及折射效果,两者通过菲涅尔公式进行混合。这篇文章主要是记录一下个人的实现细节,有一些细节的实现步骤还不是非常确定,还在查证中,所以此篇仅供参考。上面两图中折射取值不同。

        框架:Qt 5.11, OpenGL ES 2.0

球体绘制

        首先,为了更好的表现效果,此demo需要绘制一个球体。如果使用了glut框架,有现成的球体绘制函数,但是在原生的Qt中没有找到类似的函数,所以先花了时间做了球体绘制的计算。

        本次计算使用了vertex buffer和index buffer。

        首先计算所有顶点。外层循环是从最高点沿着纬度变化的,左图的圆圈为沿着大球半径的纵切面,每次循环对应着一个a角,可由此计算出球的y坐标,即y = cos(a); 内层循环沿着经度变化的,右图的圆圈是沿着外层循环纬度处的横切面,它的半径可由a角求出,即 r = sin(a) ; 之后,可以对应求出该点处的x,z坐标分别为x = r * sin(b), z = r * cos(b)。

        之后开始逐三角形记录顶点索引。

       取上图的一个面片,求出对应的两个三角形,需要特别注意顺序要按照右手定则来取(四指沿着图中箭头走向,大拇指为法线方向),否则法线以及背面消隐都会是错误的。


struct VertexData2
{QVector3D position;QVector3D normal;int adjoinPlane = 0;
};void GeometryEngine::initSphereGeometry()
{const int latitude = 40;const int longtitude = 40;const float PI = 3.14159f;QVector<VertexData2> Vertices;for(int i = 0;i <= latitude;i++) // 纬度{float y = cos(i * PI / latitude);for(int j = 0;j < longtitude; j++) // 经度{VertexData2 vertex;float x = sin(i * PI / latitude) * sin(2 * j * PI / longtitude);float z = sin(i * PI / latitude) * cos(2 * j * PI / longtitude);vertex.position = QVector3D(x,y,z);Vertices.push_back(vertex);}}QVector<GLushort> Indices;for(int i = 0;i < latitude;i++) // 纬度{for(int j = 0;j < longtitude; j++) // 经度{GLushort p1 = longtitude * i + j;GLushort p2 = longtitude * (i + 1) + j;GLushort p3 = longtitude * (i + 1) + j + 1;GLushort p4 = longtitude * i + j + 1;p1 = p1 % Vertices.size();p2 = p2 % Vertices.size();p3 = p3 % Vertices.size();p4 = p4 % Vertices.size();Indices.push_back(p4);Indices.push_back(p1);Indices.push_back(p2);Indices.push_back(p4);Indices.push_back(p2);Indices.push_back(p3);}}for(int i=0;i<Indices.size()/3;i++){CalNormal(Vertices[Indices[3 * i]],Vertices[Indices[3 * i + 1]],Vertices[Indices[3 * i + 2]]);}sphereArrayBuf.bind();sphereArrayBuf.allocate(Vertices.data(), Vertices.size() * sizeof(VertexData2));sphereIndexBuf.bind();sphereIndexBuf.allocate(Indices.data(), Indices.size() * sizeof(GLushort));
}void GeometryEngine::CalNormal(VertexData2& vertex0, VertexData2& vertex1, VertexData2& vertex2)
{QVector3D e0 = vertex1.position - vertex0.position;QVector3D e1 = vertex2.position - vertex0.position;QVector3D normal;normal = QVector3D::crossProduct(e0, e1);normal.normalize();QVector<VertexData2*> vertexArr = { &vertex0, &vertex1, &vertex2};for(int i = 0;i < vertexArr.size();i++){vertexArr[i]->adjoinPlane++;float ratio = 1.0f / vertexArr[i]->adjoinPlane;vertexArr[i]->normal = vertexArr[i]->normal * (1 - ratio) + normal * ratio;vertexArr[i]->normal.normalize();}
}

立方体贴图(CubeMap)

        为了能够让球体反射/折射环境,我们需要提供这样一个环境贴图。为了达到这一目的,我们可以使用OpenGL提供的立方体贴图。简单来说,立方体六个面上有着贴图,根据输入的向量,如下图方式发出该射线得到与立方体的交点,从而采样得到像素。

        

        和普通纹理一样,我们首先需要生成这个纹理,区别是类型从GL_TEXTURE_2D变成了GL_TEXTURE_CUBE_MAP

    glGenTextures(1, &m_nTextureId);glBindTexture(GL_TEXTURE_CUBE_MAP, m_nTextureId);

        之后,我们按照右,左,顶,底,后 ,前的顺序准备六张贴图,调用glTexImage2D来指定cubemap的纹理,由于GL_TEXTURE_CUBE_MAP_POSITIVE_X以及之后的值是连续存储的,所以可以写成一个for循环。

        由于QImage读出的数据是bgra格式,所以需要对数据做一点特殊处理,转换为rgb格式。

    QString path[] ={":/right.jpg",":/left.jpg",":/top.jpg",":/bottom.jpg",":/back.jpg",":/front.jpg",};for(int i = 0;i < 6;i++){QImage image(path[i]);const int count = image.byteCount() / 4 * 3;unsigned char* data = new unsigned char[count];int cnt = 0;for(int j = 0;j < count / 3; j++){data[3 * j] = image.bits()[cnt + 2];data[3 * j + 1] = image.bits()[cnt + 1];data[3 * j + 2] = image.bits()[cnt];cnt += 4;}glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,0,GL_RGB,image.width(),image.height(),0,GL_RGB,GL_UNSIGNED_BYTE,data);delete[] data;}

       最后,也和普通纹理类似,需要指定纹理环绕(采样坐标不在0~1之间)以及minmag(映射最终大小和原大小不一样)方式。

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_REPEAT);glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

反射效果

        

        反射效果的只需要通过反射向量来采样立方体即可,在高光的计算中已经使用了反射向量,需要输入的是视线和法线位置。glsl已经有了内置的反射计算函数:

vec3 N = normalize(v_normal);
vec3 I = normalize(worldPos - cameraPos);
vec3 R = reflect(I, N);
vec4 reflectedColor = textureCube(cubemap, R);

折射效果

        

         关于折射,使用折射参数0.66之后成像在球体里是反的,随着相机参数(改的是相机距离视点的位置参数)以及折射参数改变,图像可能变正,玻璃球本身有这么一个透镜的倒立成像属性,但是我不能确定是写错了还是事实如此,查了挺久资料~如果有人清楚求科普!

         

       该图来自网络的摄影作品。

       同样,类似于反射,折射是通过折射向量来采样立方体纹理的,glsl也为折射提供了内置函数。

    vec3 N = normalize(v_normal);vec3 I = normalize(worldPos - cameraPos);vec3 T = refract(I, N, 0.66);vec4 refractedColor = textureCube(cubemap, T);

菲涅尔效应

        菲涅尔效应的直观表现就是,视线与表面法线越垂直,反射越弱,反之则越明显。

        对于球体而言,中间部分以折射为主,看到的是对面的景象,有一种透明的效果;边缘部分以反射为主。下图中菲涅尔效应更为明显。

        近似的计算公式: fresnel = base + scale * pow(1.0 - dot(I,N), indensity);

        Refraction 1

Qt内置的一个玻璃效果的着色器

        

        Qt的官方样例中,自带了一个玻璃的材质,思路同样也是折射 + 反射 + 菲涅尔效应混合。折射和反射是直接求解得到的,没有使用内置函数。不过大部分计算是在相机空间中完成的,之后再转到了世界空间。

varying vec3 position, normal;
varying vec4 specular, ambient, diffuse, lightDirection;uniform sampler2D tex;
uniform samplerCube env;
uniform mat4 view;// Some arbitrary values
// Arrays don't work here on glsl < 120, apparently.
//const float coeffs[6] = float[6](1.0/4.0, 1.0/4.1, 1.0/4.2, 1.0/4.3, 1.0/4.4, 1.0/4.5);
float coeffs(int i)
{return 1.0 / (3.0 + 0.1 * float(i));
}void main()
{vec3 N = normalize(normal);vec3 I = -normalize(position);mat3 V = mat3(view[0].xyz, view[1].xyz, view[2].xyz);float IdotN = dot(I, N);float scales[6];vec3 C[6];for (int i = 0; i < 6; ++i) {scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN)));C[i] = textureCube(env, (-I + coeffs(i) * N) * V).xyz;}vec4 refractedColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y,C[3].z + 2.0*C[4].z + C[5].z, 4.0);vec3 R = 2.0 * dot(-position, N) * N + position;vec4 reflectedColor = textureCube(env, R * V);gl_FragColor = mix(refractedColor, reflectedColor, 0.4 + 0.6 * pow(1.0 - IdotN, 2.0));
}

附录

vertex shader

#ifdef GL_ES
// Set default precision to medium
precision mediump int;
precision mediump float;
#endifuniform mat4 ModelMatrix;
uniform mat4 IT_ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectMatrix;attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texcoord;varying vec2 v_texcoord;
varying vec3 v_normal;
varying vec3 worldPos;void main()
{gl_Position = ModelMatrix * a_position;worldPos = vec3(gl_Position);gl_Position = ViewMatrix * gl_Position;gl_Position = ProjectMatrix * gl_Position;v_texcoord = a_texcoord;mat3 M = mat3(IT_ModelMatrix[0].xyz, IT_ModelMatrix[1].xyz, IT_ModelMatrix[2].xyz);v_normal = M * a_normal;
}

fragment shader

#ifdef GL_ES
// Set default precision to medium
precision mediump int;
precision mediump float;
#endif
uniform samplerCube cubemap;
uniform mat4 ViewMatrix;
uniform int type;uniform vec3 cameraPos;
varying vec3 worldPos;
varying vec3 v_normal;float saturate(float data)
{if(data < 0.0){return 0.0;}else if(data > 1.0){return 1.0;}return data;
}void main()
{vec3 N = normalize(v_normal);vec3 I = normalize(worldPos - cameraPos);vec3 R = reflect(I, N);vec4 reflectedColor = textureCube(cubemap, R);vec3 T = refract(I, N, 0.66);vec4 refractedColor = textureCube(cubemap, T);if(type == 0){gl_FragColor = reflectedColor;}else if(type == 1){gl_FragColor = refractedColor;}else if(type == 2){float fresnel = 0.4 + 0.6 * pow(min(0.0, 1.0 - dot(-I, N)), 4.0);gl_FragColor = mix(refractedColor, reflectedColor, fresnel);}}

 

这篇关于[OpenGL] 使用折射与反射的玻璃球的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/300714

相关文章

使用Python创建一个功能完整的Windows风格计算器程序

《使用Python创建一个功能完整的Windows风格计算器程序》:本文主要介绍如何使用Python和Tkinter创建一个功能完整的Windows风格计算器程序,包括基本运算、高级科学计算(如三... 目录python实现Windows系统计算器程序(含高级功能)1. 使用Tkinter实现基础计算器2.

在.NET平台使用C#为PDF添加各种类型的表单域的方法

《在.NET平台使用C#为PDF添加各种类型的表单域的方法》在日常办公系统开发中,涉及PDF处理相关的开发时,生成可填写的PDF表单是一种常见需求,与静态PDF不同,带有**表单域的文档支持用户直接在... 目录引言使用 PdfTextBoxField 添加文本输入域使用 PdfComboBoxField

Git可视化管理工具(SourceTree)使用操作大全经典

《Git可视化管理工具(SourceTree)使用操作大全经典》本文详细介绍了SourceTree作为Git可视化管理工具的常用操作,包括连接远程仓库、添加SSH密钥、克隆仓库、设置默认项目目录、代码... 目录前言:连接Gitee or github,获取代码:在SourceTree中添加SSH密钥:Cl

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

windows和Linux使用命令行计算文件的MD5值

《windows和Linux使用命令行计算文件的MD5值》在Windows和Linux系统中,您可以使用命令行(终端或命令提示符)来计算文件的MD5值,文章介绍了在Windows和Linux/macO... 目录在Windows上:在linux或MACOS上:总结在Windows上:可以使用certuti

CentOS和Ubuntu系统使用shell脚本创建用户和设置密码

《CentOS和Ubuntu系统使用shell脚本创建用户和设置密码》在Linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设置密码,本文写了一个shell... 在linux系统中,你可以使用useradd命令来创建新用户,使用echo和chpasswd命令来设

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

使用Java将各种数据写入Excel表格的操作示例

《使用Java将各种数据写入Excel表格的操作示例》在数据处理与管理领域,Excel凭借其强大的功能和广泛的应用,成为了数据存储与展示的重要工具,在Java开发过程中,常常需要将不同类型的数据,本文... 目录前言安装免费Java库1. 写入文本、或数值到 Excel单元格2. 写入数组到 Excel表格