第七课:纹理滤波、光源和键盘控制



  • 纹理滤波

    在纹理映射的过程中,如果图元的大小不等于纹理的大小,OpenGL便会对纹理进行缩放以适应图元的尺寸。我们可以通过设置纹理滤镜来决定OpenGL对某个纹理采用的放大、缩小的算法

    滤镜 描述
    GL_NEAREST 取最邻近像素
    GL_LINEAR 线性内部插值
    GL_NEAREST_MIPMAP_NEAREST 最近多贴图等级的最邻近像素
    GL_NEAREST_MIPMAP_LINEAR 在最近多贴图等级的内部线性插值
    GL_LINEAR_MIPMAP_NEAREST 在最近多贴图等级的外部线性插值
    GL_LINEAR_MIPMAP_LINEAR 在最近多贴图等级的外部和内部线性插值

    光源

    环境光

    因为我们使用的OpenGL 3.x API,使用可编程管线,不使用glLightfv

    修改着色器代码

    • 颜色=环境光强度(0.5)* 环境光颜色 * 物体本身颜色
    static const char *vertexShaderSource =
        "attribute highp vec4 posAttr;\n"
        "attribute lowp vec3 colAttr;\n"
        "varying lowp vec3 col;\n"
        "uniform highp mat4 projection;\n"
        "uniform highp mat4 view;\n"
        "uniform highp mat4 model;\n"
        "attribute vec2 a_texcoord;\n"
        "varying highp vec2 v_texcoord;\n"
        "void main() {\n"
        "   gl_Position = projection * view * model * posAttr;\n"
        "   v_texcoord = a_texcoord;\n"
        "   col = colAttr;\n"
        "}\n";
    
    static const char *fragmentShaderSource =
        "varying lowp vec3 col;\n"
        "uniform sampler2D texture;\n"
        "uniform lowp vec3 ambientColAttr;\n"
        "varying highp vec2 v_texcoord;\n"
        "void main() {\n"
        "   float ambientStrength = 0.5f;\n"
        "   gl_FragColor = vec4(ambientStrength * ambientColAttr * col, 1.0f);\n"
        "}\n";
    

    获取 环境光属性

    //环境光属性
    m_ambientColAttr = m_program->uniformLocation("ambientColAttr");
    

    绘制时候设置环境光

    QVector3D ambient(1.0f, 1.0f, 1.0f);
    m_program->setUniformValue(m_ambientColAttr, ambient);
    

    效果

    之所以有这样的效果,是因为左上角白色受环境光影响,反射了环境光颜色

    • 白色环境光
      0_1526954839519_f40f63b4-9d0a-46c9-a505-a98451d42c33-image.png
    • 红色环境光
      0_1526954873463_d6a83b40-63bb-4986-8a4f-d5df3a1475a4-image.png
    • 绿色环境光
      0_1526954902270_14818a8e-daf4-4f8c-8563-2c711e200dbf-image.png
    • 蓝色环境光
      0_1526954923358_7a242e55-54fe-4108-9d41-d39813facab2-image.png

    点光源-漫反射

    修改着色器代码

    我们追加了点光源颜色,光源位置,物体的法线(实际具有增幅/衰减光亮的效果)

    static const char *vertexShaderSource =
        "attribute highp vec3 posAttr;\n"
        "attribute lowp vec3 colAttr;\n"
        "varying lowp vec3 col;\n"
        "uniform lowp vec3 aNormal;\n"
        "uniform highp mat4 projection;\n"
        "uniform highp mat4 view;\n"
        "uniform highp mat4 model;\n"
        "attribute vec2 a_texcoord;\n"
    
        "varying highp vec2 v_texcoord;\n"
        "varying vec3 Normal;\n"
        "varying vec3 FragPos;\n"
    
        "void main() {\n"
        "   gl_Position = projection * view * model * vec4(posAttr, 1.0);\n"
        "   FragPos = vec3(model * vec4(posAttr, 1.0));\n"
        "   v_texcoord = a_texcoord;\n"
        "   Normal = mat3(transpose(inverse(model))) * aNormal;\n"
        "   col = colAttr;\n"
        "}\n";
    
    static const char *fragmentShaderSource =
        "varying lowp vec3 col;\n"
        "uniform sampler2D texture;\n"
        "uniform lowp vec3 ambientColAttr;\n"
        "uniform lowp vec3 lightColAttr;\n"
        "uniform lowp vec3 lightPosAttr;\n"
    
        "varying highp vec2 v_texcoord;\n"
        "varying vec3 Normal;\n"
        "varying vec3 FragPos;\n"
    
        "void main() {\n"
        "   vec3 norm = normalize(Normal);\n"
        "   vec3 lightDir = normalize(lightPosAttr - FragPos);\n"
        "   float ambientStrength = 0.1;\n"
        "   float diffuse = max(dot(norm, lightDir), 0.0);\n"
        "   gl_FragColor = vec4((ambientStrength + diffuse) * lightColAttr * col, 1.0);\n"
        "}\n";
    

    获取 点光源属性

    //点光源属性
        m_lightColAttr = m_program->uniformLocation("lightColAttr");
        m_lightPosAttr = m_program->uniformLocation("lightPosAttr");
        m_aNormal = m_program->uniformLocation("aNormal");
    

    绘制时候设置点光

    //环境光
        QVector3D ambient(1.0f, 1.0f, 1.0f);
        m_program->setUniformValue(m_ambientColAttr, ambient);
    
        //点光源-漫反射
        QVector3D pointLightCol(1.0f, 1.0f, 1.0f);
        m_program->setUniformValue(m_lightColAttr, pointLightCol);
    
        QVector3D pointLightPos(2.0f, 0.0f, 2.0f);
        m_program->setUniformValue(m_lightPosAttr, pointLightPos);
    
        //法线=强度
        QVector3D objNormal(0.0f, 1.0f, 1.0f);
        m_program->setUniformValue(m_aNormal, objNormal);
    

    效果

    0_1526965557596_20180522_125850.gif

    高光-镜面反射

    光源照射到物体然后反射到人的眼睛里时,物体上最亮的那个点就是高光,
    所以我们需要知道眼睛(摄像机)的位置,然后根据光的方向,法线求出反射

    修改着色器代码

    static const char *vertexShaderSource =
        "attribute highp vec3 posAttr;\n"
        "attribute lowp vec3 colAttr;\n"
        "varying lowp vec3 col;\n"
        "uniform lowp vec3 aNormal;\n"
        "uniform highp mat4 projection;\n"
        "uniform highp mat4 view;\n"
        "uniform highp mat4 model;\n"
        "attribute vec2 a_texcoord;\n"
    
        "varying highp vec2 v_texcoord;\n"
        "varying vec3 Normal;\n"
        "varying vec3 FragPos;\n"
    
        "void main() {\n"
        "   gl_Position = projection * view * model * vec4(posAttr, 1.0);\n"
        "   FragPos = vec3(model * vec4(posAttr, 1.0));\n"
        "   v_texcoord = a_texcoord;\n"
        "   Normal = mat3(transpose(inverse(model))) * aNormal;\n"
        "   col = colAttr;\n"
        "}\n";
    
    static const char *fragmentShaderSource =
        "varying lowp vec3 col;\n"
        "uniform sampler2D texture;\n"
        "uniform lowp vec3 ambientColAttr;\n"
        "uniform lowp vec3 lightColAttr;\n"
        "uniform lowp vec3 lightPosAttr;\n"
        "uniform lowp vec3 viewPosAttr;\n"
    
        "varying highp vec2 v_texcoord;\n"
        "varying vec3 Normal;\n"
        "varying vec3 FragPos;\n"
    
        "void main() {\n"
        //漫反射
        "   vec3 norm = normalize(Normal);\n"
        "   vec3 lightDir = normalize(lightPosAttr - FragPos);\n"
        "   float ambientStrength = 0.1;\n"
        "   float diffuse = max(dot(norm, lightDir), 0.0);\n"
    
        //高光
        "   vec3 viewDir = normalize(viewPosAttr - FragPos);\n"
        "   vec3 reflecDir = reflect(-lightDir, norm);\n"
        "   float specularStrength = 0.5;\n"
        "   float specular = pow(max(dot(viewDir, reflecDir), 0.0), 64) * specularStrength;\n"
        "   gl_FragColor = vec4((ambientStrength + diffuse + specular) * lightColAttr * col, 1.0);\n"
        "}\n";
    

    获取 视点属性

    //视点属性
        m_viewPosAttr = m_program->uniformLocation("viewPosAttr");
    

    绘制时候设置视点

    //视点为摄像机位置
        m_program->setUniformValue(m_viewPosAttr, camera);
    

    效果

    仔细看,有高光
    0_1526968253241_20180522_134903.gif

    源代码

    https://gitee.com/chen227/opengl_OpenGLFunctions7



  • @青山白云 纹理滤波的选择,可以让纹理放大或者缩小的时候避免失真。还有一个叫做Anisotropic的扩展,中文名是各向异性采样,是更高级也是更好看的一个。


Log in to reply
 

最近的回复

  • 看了你的脚本,看来PowerShell是一种shell的方言,支持function和自定义的符号。和bash还不一样。
    我以前也写过Apple Script,看来大家都在shell语言上加上自己的特性啊。
    顺便了解到你们主要用Visual Studio开发Qt应用的。😁 😁

    read more
  • @wentaojia2014
    代码中的 {1} 是自动生成的,注意删掉

    read more
  • 脚本玩家路过一下😁
    我写了一段Powershell脚本,可以一键打开/关闭调试信息和代码优化。
    原理就是解析.sln文件(xml格式),找到关联的所有.vcproj文件(也是xml格式),并把其中的字段修改掉。

    看脚本

    # filename: DebugInfoSwitch.ps1 Add-Type -AssemblyName System.Xml.Linq # 获取绝对路径 function GetAbsolutePath { [OutputType([string])] param([string]$filePath) $aPath = Resolve-Path $filePath return Split-Path $aPath } # 解析sln文件,提取出project列表 function ParseSolution { [OutputType([string[]])] param([string]$solutionFile) $parttern = [regex]"^Project*" [string[]] $projs = @() Get-Content $solutionFile | Where-Object {$_ -match $parttern} | ForEach-Object { $items = $_.ToString().Split(',') if ($items[1].EndsWith("vcxproj`"")) { $projs += $items[1] } } return $projs } #Write-Host($debugGroup | Format-Table | Out-String ) function UpdateDebugInfo { param([System.Xml.Linq.XNamespace]$xNamespace,[System.Xml.Linq.XElement] $group, [bool]$isOpen) [System.Xml.Linq.XElement]$xClCompile = $group.Element($xNamespace + "ClCompile") [System.Xml.Linq.XElement]$xLink = $group.Element($xNamespace + "Link") [System.Xml.Linq.XElement]$format = $xClCompile.Element($xNamespace + "DebugInformationFormat") [System.Xml.Linq.XElement]$optimization = $xClCompile.Element($xNamespace + "Optimization") [System.Xml.Linq.XElement]$generate = $xLink.Element($xNamespace + "GenerateDebugInformation") if ($null -eq $format) { $format = [System.Xml.Linq.XElement]::new($xNamespace + "DebugInformationFormat") $xClCompile.Add($format) } if ($null -eq $optimization) { $optimization = [System.Xml.Linq.XElement]::new($xNamespace + "Optimization") $xClCompile.Add($optimization) } if ($null -eq $generate) { $generate = [System.Xml.Linq.XElement]::new($xNamespace + "GenerateDebugInformation") $xLink.Add($generate) } if ($isOpen) { $format.SetValue("ProgramDatabase"); $optimization.SetValue("Disabled"); $generate.SetValue("true"); } else { $format.SetValue("None"); $optimization.SetValue("MaxSpeed"); $generate.SetValue("false"); } } function SwitchDebugInfo { param([string]$projPath, [bool]$open, [bool]$isRelease) if (Test-Path($projPath)) { [System.Xml.Linq.XDocument]$xDoc = [System.Xml.Linq.XDocument]::Load($projPath) [System.Xml.Linq.XNamespace]$xNamespace = $xDoc.Root.GetDefaultNamespace(); [System.Xml.Linq.XElement]$group = $null $groups = $xDoc.Root.Elements($xNamespace + "ItemDefinitionGroup") foreach ($i in $groups) { if ($isRelease) { if ($i.Attribute("Condition").Value -match "^*Release*") { $group = $i; break; } } else { if ($i.Attribute("Condition").Value -match "^*Debug*") { $group = $i; break; } } } UpdateDebugInfo $xNamespace $group $open $xDoc.Save($projPath) } } #脚本入口函数 function Main { param([string]$sln, [bool]$open, [bool]$isRelease) Write-Host("sln file ", $sln) $slnPath= GetAbsolutePath $sln $projList = ParseSolution $sln $t = $projList.Split(' ') | ForEach-Object { $s = $_.ToString() if ($s) { $projPath=-Join($slnPath, '\', ($s.SubString(1, $s.Length - 2) )) SwitchDebugInfo $projPath $open $isRelease } } } function Usage { Write-Host ("Usage: DebugInfoSwitch.ps1 slnFilePath mode[D/d for Debug, R/r for Release] open[Y/y for open, N/n for close]") Write-Host ("Example for open Release mode debugInfo: DebugInfoSwitch.ps1 xxx.sln R y") Write-Host ("Example for close Debug mode debugInfo: DebugInfoSwitch.ps1 xxx.sln d N") } #检查参数 [string]$sln = "" [bool]$open = $true [bool]$isRelease = $false if ( $args.Count -ne 3) { Usage return } $sln = $args[0] if ($args[1] -eq "D" -or $args[1] -eq "d") { $isRelease = $false } elseif ($args[1] -eq "R" -or $args[1] -eq "r") { $isRelease = $true } else { Usage return } if ($args[2] -eq "Y" -or $args[2] -eq "y") { $open = $true } elseif ($args[2] -eq "N" -or $args[2] -eq "n") { $open = $false } else { Usage return } #调用主函数 Main $sln $open $isRelease

    用的时候,再写个bat脚本,调用这个ps1并传参数就行了。
    比如打开Release模式的调试信息、同时关掉优化开关

    @echo off powershell.exe -NoProfile -ExecutionPolicy Bypass -File DebugInfoSwitch.ps1 ./you/path/to.sln R N

    关闭调试信息、打开优化开关,则是传相反的参数

    @echo off powershell.exe -NoProfile -ExecutionPolicy Bypass -File DebugInfoSwitch.ps1 ./you/path/to.sln R Y

    read more
  • 我将USD在Linux中依赖的文件和脚本放在了我创建的QQ群里,我们的QQ群是“上海USD研究小组”。加入本小组,可以快速地在USD中上手解决编译问题,以及快速得到同行的响应。
    上海USD研究小组

    read more

关注我们

微博
QQ群