Unity3d 镜面折射 vertex and frag Shader源代码
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源代码的更多相关文章
- Unity3d 镜面反射 vertex and frag Shader源代码
Unity3d 镜面反射 网上能找到的基本上是固定管道或表面渲染的shader. 特此翻译为顶点.片段渲染的Shader, 本源代码仅仅涉及shader与cs部分. Editor部分使用NGUI绘制的 ...
- Unity3d 实时折射和反射
这里只是张贴在实时折射和脚本反思shader, 大约NGUI第一部分请下载. 这个版本的主要缺点是折射平面部Layer必须是water层.假设有专家谁可以摆脱这一个.请记得把代码回该条,谢谢! Wat ...
- UnityShader之顶点片段着色器Vertex and Fragment Shader【Shader资料】
顶点片段着色器 V&F Shader:英文全称Vertex and Fragment Shader,最强大的Shader类型,也是我们在使用ShaderLab中的重点部分,属于可编程管线,使用 ...
- Unity3D for VR 学习(9): Unity Shader 光照模型 (illumination model)
关于光照模型 所谓模型,一般是由学术算法发起, 经过大量实际数据验证而成的可靠公式 现在还记得2009年做TD-SCDMA移动通信算法的时候,曾经看过自由空间传播模型(Free space propa ...
- Vertex And Fragment Shader(顶点和片段着色器)
Vertex And Fragment Shader(顶点和片段着色器) Shader "Unlit/ Vertex_And_Fragment_Shader " { Proper ...
- ShaderLab中vertex fragment类Shader基础格式笔记
//U3D用的shader语言叫ShaderLab,基础语法官方文档地址 //https://docs.unity3d.com/Manual/SL-Shader.html //开头指明名字,可以在别的 ...
- Vertex and Fragment Shader
Semantics语义词: 定义:GPU工作时,数据通常暂存在寄存器,那么在Cg中,语义词就指定了输入/输出数据和图形硬件寄存器之间的映射关系. 原理:根据输入语义,图形处理器从某个寄存器取数据:然后 ...
- Unity3D for VR 学习(8): Unity Shader概述
从西安到北京高铁上,一位VR老外团队的华人leader对VR技术做了画龙点睛: “3D游戏的核心部分在Render, 国内很多团队美术.程序中间缺失严重.所以3d游戏做不好. VR这块更是至关重要.” ...
- 3D Computer Grapihcs Using OpenGL - 07 Passing Data from Vertex to Fragment Shader
上节的最后我们实现了两个绿色的三角形,而绿色是直接在Fragment Shader中指定的. 这节我们将为这两个三角形进行更加自由的着色——五个顶点各自使用不同的颜色. 要实现这个目的,我们分两步进行 ...
随机推荐
- jq判断滚动条向上还是向下
$(document).ready(function(){ ,t=; $(window).scroll(function(e){ p = $(this).scrollTop(); if(t<=p ...
- MyBatis中Like语句使用总结
原生写法 eg: select * from user where username like '%${value}%' 注意: ${value}里面必须要写value,不然会报错 oracl ...
- 【Java并发编程四】关卡
一.什么是关卡? 关卡类似于闭锁,它们都能阻塞一组线程,直到某些事件发生. 关卡和闭锁关键的不同在于,所有线程必须同时到达关卡点,才能继续处理.闭锁等待的是事件,关卡等待的是其他线程. 二.Cycli ...
- 【抓包分析】 charles + 网易mumu 模拟器数据包
charles 的使用.我就不再多说了.可以参考以往文章,传送门: https://www.cnblogs.com/richerdyoung/p/8616674.html 此处主要说网易模拟器的使用 ...
- 决策树归纳算法之ID3
学习是一个循序渐进的过程,我们首先来认识一下,什么是决策树.顾名思义,决策树就是拿来对一个事物做决策,作判断.那如何判断呢?凭什么判断呢?都是值得我们去思考的问题. 请看以下两个简单例子: 第一个例子 ...
- python基础---->python的使用(五)
这里记录一些python的一些基础知识,主要内容是高阶函数的使用.或许我的心包有一层硬壳,能破壳而入的东西是极其有限的.所以我才不能对人一往情深. python中的高阶函数 一.map().reduc ...
- smali-2.2.4.jar & baksmali-2.2.4.jar
https://bitbucket.org/JesusFreke/smali/downloads/
- LeetCode 13 Roman to Integer(罗马数字转为整数)
题目链接 https://leetcode.com/problems/roman-to-integer/?tab=Description int toNumber(char ch) { switc ...
- sencha touch 视图(view) activate与deactivate事件探讨
在sencha touch2.2中采用card布局 之前的需求是考虑show,hide事件发现不可取 http://www.cnblogs.com/mlzs/archive/2013/06/13/31 ...
- soanr - 企业用户角色管理
首先sonar支持群组 即 支持企业角色权限管理,其次sonar支持单项目用户权限管理 即 外包,客户,外编人员用户权限管理. (视图内可看到源码) 按照 管路员.产品/项目管理.产品/项目开发.外包 ...