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. Linux终端多用户通信实用命令

    一  命令 1.1 write 该命令将当前终端(源)输入的字符拷贝至目标用户的终端,从而发送消息给系统中某个用户.用法如下: #write <user> <msg> [Ctr ...

  2. 【Linux基础学习】Ubuntu 常用命令大全

    一.文件目录类 1.建立目录:mkdir 目录名 2.删除空目录:rmdir 目录名 3.无条件删除子目录: rm -rf 目录名 4.改变当前目录:cd 目录名 (进入用户home目录:cd ~:进 ...

  3. docker 快速搭建Nexus3

    1.拉取镜像 docker pull sonatype/nexus3 2.启动容器 : -p : -p : -v /mnt/gv0/nexus-data:/nexus-data sonatype/ne ...

  4. Android设计和开发系列第一篇:Notifications通知(Develop—Training)

    Develop篇 Building a Notification PREVIOUSNEXT THIS LESSON TEACHES YOU TO Create a Notification Build ...

  5. JS笔记 - JQ事件委托( 适用于给动态生成的脚本元素添加事件)

    最近一段时间打了一个大仗,现在总算消停点,才有时间来做个总结吧算是: 移动端遇到一个项目,是一个列表的侧滑栏,在我这里用jq写的交互事件.自测各方面都挺好的,美滋滋的给了研发.研发也美滋滋的开始开发. ...

  6. Android单例模式

    Android设计模式系列(3)--SDK源码之单例模式:http://www.cnblogs.com/qianxudetianxia/archive/2011/08/07/2130306.html ...

  7. 题目1447:最短路(Floyd算法)

    题目链接:http://ac.jobdu.com/problem.php?pid=1447 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...

  8. linux route命令详解

    考试题一:linux下如何添加路由(百度面试题) 以上是原题,老男孩老师翻译成如下3道题. a.如何用命令行方式给linux机器添加一个默认网关,假设网关地址为10.0.0.254? b. 192.1 ...

  9. linux下find(文件查找)命令的用法总结

    关联文章:http://blog.chinaunix.net/uid-24648486-id-2998767.html

  10. 备忘,commons-codec中可能用到的一些加密字符串的方法

    commons-codec中提供了一些加密解密字符串的方法,我们可以直接使用 1.MD5加密: String source = "source"; DigestUtils.md5H ...