Unity3d 镜面折射 

网上能找到的基本上是固定管道或表面渲染的shader。

特此翻译为顶点、片段渲染的Shader,

本源代码仅仅涉及shader与cs部分,

请自行下载NGUI 

unity3d 版本号:v4.3.1

RefractionMirror.cs

using UnityEngine;
using System.Collections;
using System; /// <summary>
/// 镜面折射效果
/// </summary>
[AddComponentMenu("GameCore/Effect/Refraction/Mirror")]
[ExecuteInEditMode]
public class RefractionMirror : MonoBehaviour
{
public bool DisablePixelLights = true;
public int TextureSize = 512;
public float ClipPlaneOffset = 0;
public LayerMask ReflectLayers = -1; private Hashtable _RefractionCameras = new Hashtable(); // Camera -> Camera table
private RenderTexture _RefractionTexture = null;
private int _OldRefractionTextureSize = 0; private static bool _InsideRendering = false; // This is called when it's known that the object will be rendered by some
// camera. We render Refractions and do other updates here.
// Because the script executes in edit mode, Refractions for the scene view
// camera will just work!
void OnWillRenderObject()
{
if (!enabled || !renderer || !renderer.sharedMaterial || !renderer.enabled)
return; Camera cam = Camera.current;
if (!cam)
return; // Safeguard from recursive Refractions.
if (_InsideRendering)
return;
_InsideRendering = true; Camera RefractionCamera;
CreateMirrorObjects(cam, out RefractionCamera); // find out the Refraction plane: position and normal in world space
Vector3 pos = transform.position;
Vector3 normal = transform.up;
// Optionally disable pixel lights for Refraction
int oldPixelLightCount = QualitySettings.pixelLightCount;
if (DisablePixelLights)
QualitySettings.pixelLightCount = 0; CoreTool.CloneCameraModes(cam, RefractionCamera); RefractionCamera.cullingMask = ~(1 << 4) & ReflectLayers.value; // never render water layer
RefractionCamera.targetTexture = _RefractionTexture;
RefractionCamera.transform.position = cam.transform.position;
RefractionCamera.transform.eulerAngles = cam.transform.eulerAngles;
RefractionCamera.Render();
Material[] materials = renderer.sharedMaterials;
foreach (Material mat in materials)
{
if (mat.HasProperty("_RefractionTex"))
mat.SetTexture("_RefractionTex", _RefractionTexture);
} // Set matrix on the shader that transforms UVs from object space into screen
// space. We want to just project Refraction texture on screen.
Matrix4x4 scaleOffset = Matrix4x4.TRS(
new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity, new Vector3(0.5f, 0.5f, 0.5f));
Vector3 scale = transform.lossyScale;
Matrix4x4 mtx = transform.localToWorldMatrix * Matrix4x4.Scale(new Vector3(1.0f / scale.x, 1.0f / scale.y, 1.0f / scale.z));
mtx = scaleOffset * cam.projectionMatrix * cam.worldToCameraMatrix * mtx;
foreach (Material mat in materials)
{
mat.SetMatrix("_ProjMatrix", mtx);
}
// Restore pixel light count
if (DisablePixelLights)
QualitySettings.pixelLightCount = oldPixelLightCount;
_InsideRendering = false;
} // Cleanup all the objects we possibly have created
void OnDisable()
{
if (_RefractionTexture)
{
DestroyImmediate(_RefractionTexture);
_RefractionTexture = null;
}
foreach (DictionaryEntry kvp in _RefractionCameras)
DestroyImmediate(((Camera)kvp.Value).gameObject);
_RefractionCameras.Clear();
} // On-demand create any objects we need
private void CreateMirrorObjects(Camera currentCamera, out Camera RefractionCamera)
{
RefractionCamera = null; // Refraction render texture
if (!_RefractionTexture || _OldRefractionTextureSize != TextureSize)
{
if (_RefractionTexture)
DestroyImmediate(_RefractionTexture);
_RefractionTexture = new RenderTexture(TextureSize, TextureSize, 0);
_RefractionTexture.name = "__MirrorRefraction" + GetInstanceID();
_RefractionTexture.isPowerOfTwo = true;
_RefractionTexture.hideFlags = HideFlags.DontSave;
_RefractionTexture.antiAliasing = 4;
_RefractionTexture.anisoLevel = 0;
_OldRefractionTextureSize = TextureSize;
} // Camera for Refraction
RefractionCamera = _RefractionCameras[currentCamera] as Camera;
if (!RefractionCamera) // catch both not-in-dictionary and in-dictionary-but-deleted-GO
{
GameObject go = new GameObject("Mirror Refl Camera id" + GetInstanceID() + " for " + currentCamera.GetInstanceID(), typeof(Camera), typeof(Skybox));
RefractionCamera = go.camera;
RefractionCamera.enabled = false;
RefractionCamera.transform.position = transform.position;
RefractionCamera.transform.rotation = transform.rotation;
RefractionCamera.gameObject.AddComponent("FlareLayer");
go.hideFlags = HideFlags.HideAndDontSave;
_RefractionCameras[currentCamera] = RefractionCamera;
}
}
}

shader

Shader "GameCore/Mobile/Refraction/Mirror"
{
Properties {
_RefractionTex ("Refraction", 2D) = "white" {TexGen ObjectLinear }
_RefractionColor("Color",Color) = (1,1,1,1)
}
SubShader {
Tags {
"RenderType"="Opaque"}
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc" uniform float4x4 _ProjMatrix;
uniform sampler2D _RefractionTex;
float4 _RefractionColor;
struct outvertex {
float4 pos : SV_POSITION;
float3 uv : TEXCOORD0;
float4 posProj;
};
outvertex vert(appdata_tan v) {
outvertex o;
o.pos = mul (UNITY_MATRIX_MVP,v.vertex);
o.posProj = mul(_ProjMatrix, v.vertex);
return o;
}
float4 frag(outvertex i) : COLOR {
half4 reflcol = tex2D(_RefractionTex,float2(i.posProj) / i.posProj.w);
return reflcol*_RefractionColor;
}
ENDCG
}
}
}
Shader "GameCore/Refraction/Mirror"
{
Properties {
_RefractionTex ("Refraction ", 2D) = "white" {TexGen ObjectLinear }
_RefractionColor("Color",Color) = (1,1,1,1)
}
SubShader {
Tags {
"RenderType"="Opaque"}
LOD 100
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc" uniform float4x4 _ProjMatrix;
uniform sampler2D _RefractionTex;
float4 _RefractionColor;
struct outvertex {
float4 pos : SV_POSITION;
float3 uv : TEXCOORD0;
};
outvertex vert(appdata_tan v) {
outvertex o;
o.pos = mul (UNITY_MATRIX_MVP,v.vertex);
float3 viewDir = ObjSpaceViewDir(v.vertex);
o.uv = mul(_ProjMatrix,float4(viewDir,0));
return o;
} float4 frag(outvertex i) : COLOR {
half4 reflcol = tex2Dproj(_RefractionTex,i.uv);
return reflcol*_RefractionColor;
}
ENDCG
}
}
}

Unity3d 镜面折射 vertex and frag Shader源代码的更多相关文章

  1. Unity3d 镜面反射 vertex and frag Shader源代码

    Unity3d 镜面反射 网上能找到的基本上是固定管道或表面渲染的shader. 特此翻译为顶点.片段渲染的Shader, 本源代码仅仅涉及shader与cs部分. Editor部分使用NGUI绘制的 ...

  2. Unity3d 实时折射和反射

    这里只是张贴在实时折射和脚本反思shader, 大约NGUI第一部分请下载. 这个版本的主要缺点是折射平面部Layer必须是water层.假设有专家谁可以摆脱这一个.请记得把代码回该条,谢谢! Wat ...

  3. UnityShader之顶点片段着色器Vertex and Fragment Shader【Shader资料】

    顶点片段着色器 V&F Shader:英文全称Vertex and Fragment Shader,最强大的Shader类型,也是我们在使用ShaderLab中的重点部分,属于可编程管线,使用 ...

  4. Unity3D for VR 学习(9): Unity Shader 光照模型 (illumination model)

    关于光照模型 所谓模型,一般是由学术算法发起, 经过大量实际数据验证而成的可靠公式 现在还记得2009年做TD-SCDMA移动通信算法的时候,曾经看过自由空间传播模型(Free space propa ...

  5. Vertex And Fragment Shader(顶点和片段着色器)

    Vertex And Fragment Shader(顶点和片段着色器) Shader "Unlit/ Vertex­_And_Fragment_Shader " { Proper ...

  6. ShaderLab中vertex fragment类Shader基础格式笔记

    //U3D用的shader语言叫ShaderLab,基础语法官方文档地址 //https://docs.unity3d.com/Manual/SL-Shader.html //开头指明名字,可以在别的 ...

  7. Vertex and Fragment Shader

    Semantics语义词: 定义:GPU工作时,数据通常暂存在寄存器,那么在Cg中,语义词就指定了输入/输出数据和图形硬件寄存器之间的映射关系. 原理:根据输入语义,图形处理器从某个寄存器取数据:然后 ...

  8. Unity3D for VR 学习(8): Unity Shader概述

    从西安到北京高铁上,一位VR老外团队的华人leader对VR技术做了画龙点睛: “3D游戏的核心部分在Render, 国内很多团队美术.程序中间缺失严重.所以3d游戏做不好. VR这块更是至关重要.” ...

  9. 3D Computer Grapihcs Using OpenGL - 07 Passing Data from Vertex to Fragment Shader

    上节的最后我们实现了两个绿色的三角形,而绿色是直接在Fragment Shader中指定的. 这节我们将为这两个三角形进行更加自由的着色——五个顶点各自使用不同的颜色. 要实现这个目的,我们分两步进行 ...

随机推荐

  1. creat-react-app 如何在组件中img的src引入图片路径??

    把图片文件夹放到public中,然后以这种方式来动态写路径: process.env.PUBLIC_URL + '/img/' + url + '.jpg'

  2. 在input中既隐藏边框,也隐藏轮廓的设置

    在设置input的时候,我们往往不想显示边框,所以通常会在css里面写"border"none",但是结果往往差强人意,如下图 我们这个时候可以加一个属性来把它的轮廓也隐 ...

  3. 《计算机图形学》2.1.4 彩色CRT监视器

    CRT监视器利用能发射不同颜色光的荧光层的组合来显示彩色图形.不同荧光层的发射光组合起来,可以生成一种按其比例而定的可见颜色. 显示彩色图形的一种方法是在屏幕上涂上多层不同的荧光粉.发射颜色由电子束在 ...

  4. [Win32]一个调试器的实现(五)调试符号

    一个调试器应该可以跟踪被调试程序执行到了什么地方,显示下一条将要执行的语句,显示各个变量的值,设置断点,进行单步执行等等,这些功能都需要一个基础设施的支持,那就是调试符号. 什么是调试符号 我们知道, ...

  5. <转>Python: __init__.py 用法

    转自 http://www.cnblogs.com/BeginMan/p/3183629.html python的每个模块的包中,都有一个__init__.py文件,有了这个文件,我们才能导入这个目录 ...

  6. Win8交互UX——用于 Windows 的触摸交互

    用于 Windows 的触摸交互   Windows 8.1 提供一组在整个系统中使用的简单触摸交互功能.一致地应用此触摸语言可让用户对你的应用感觉已经很熟悉.通过让你的应用更容易学习和使用,可提高用 ...

  7. Qt编写网络中转服务器(开源)

    需求1:手机端或者其他端可以对设备进行回控,并查看设备各种运行状态,接收报警推送等.2:同时支持在局域网.广域网.互联网访问,尤其是互联网访问.3:权限控制,给定账号控制授权的设备,并自动拉取设备信息 ...

  8. 【大数据系列】windows搭建hadoop开发环境

    一.安装JDK配置环境变量 已经安装略过 二.安装eclipse 已经安装略过 三.安装Ant 1.下载http://ant.apache.org/bindownload.cgi 2.解压 3.配置A ...

  9. javascript解析器原理

    浏览器在读取HTML文件的时候,只有当遇到<script>标签的时候,才会唤醒所谓的“JavaScript解析器”开始工作. JavaScript解析器工作步骤 1. “找一些东西”: v ...

  10. sencha touch 在线实战培训 第一期 第二节

    2013.12.30晚上8点开的课,仍然有些紧张,开始讲课进度很慢,后面又有些快了... 本期培训一共八节,前三堂免费,后面的课程需要付费才可以观看. 本节内容: 页面实现及跳转控制 跳转容器.路由理 ...