Skip to content

Instantly share code, notes, and snippets.

@TheStoneBook
Last active November 10, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheStoneBook/11cfa3399f8547ac9171379f6af9f5d4 to your computer and use it in GitHub Desktop.
Save TheStoneBook/11cfa3399f8547ac9171379f6af9f5d4 to your computer and use it in GitHub Desktop.
【Unity】ジオメトリーシェーダーでポリゴンをバラバラにする【Shader】
Shader "Unlit/Polygonoperator"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_MainColor("Color",Color)=(1,1,1,1)
_PositionFactor("Position Factor", Range(0.0, 1.0)) = 1.0
_RotationFactor("Rotation Factor", Range(0.0, 1.0)) = 1.0
_ScaleFactor("Scale Factor", Range(0.0, 1.0)) = 1.0
_Destruction("Destruction Factor", Range(0.0, 1.0)) = 0.0
}
SubShader
{
Tags
{
"RenderType" = "Transparent"
"Queue" = "Transparent"
}
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma geometry geom
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct g2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
float rand(fixed2 seed){
return frac(sin(dot(seed.xy ,fixed2(12.9898,78.233))) * 43758.5453);
}
fixed3 rotate(fixed3 p, fixed3 rotation)
{
fixed3 a = normalize(rotation);
fixed angle = length(rotation);
if (abs(angle) < 0.001) return p;
fixed s = sin(angle);
fixed c = cos(angle);
fixed r = 1.0 - c;
fixed3x3 m = fixed3x3(
a.x * a.x * r + c,
a.y * a.x * r + a.z * s,
a.z * a.x * r - a.y * s,
a.x * a.y * r - a.z * s,
a.y * a.y * r + c,
a.z * a.y * r + a.x * s,
a.x * a.z * r + a.y * s,
a.y * a.z * r - a.x * s,
a.z * a.z * r + c
);
return mul(m, p);
}
sampler2D _MainTex;
fixed4 _MainColor;
fixed _PositionFactor;
fixed _RotationFactor;
fixed _ScaleFactor;
fixed _Destruction;
appdata vert (appdata v)
{
return v;
}
[maxvertexcount(3)]
void geom(triangle appdata input[3], inout TriangleStream<g2f> outStream)
{
//ポリゴンの中心を計算。
float3 center = (input[0].vertex + input[1].vertex + input[2].vertex).xyz / 3;
//法線計算
float3 vec1 = input[1].vertex - input[0].vertex;
float3 vec2 = input[2].vertex - input[0].vertex;
float3 normal = normalize(cross(vec1, vec2));
fixed r = 2.0 * (rand(center.xy) - 0.5);
fixed3 r3 = r.xxx;
[unroll]
for(int i=0;i<3;i++)
{
appdata v=input[i];
g2f o;
//scale
v.vertex.xyz = (v.vertex.xyz - center) * (1-_Destruction * _ScaleFactor) + center;
//rotation
v.vertex.xyz = rotate(v.vertex.xyz - center, r3 * _Destruction * _RotationFactor) + center;
//position
v.vertex.xyz += normal * _Destruction * _PositionFactor * r3;
o.vertex=UnityObjectToClipPos(v.vertex);
o.uv=v.uv;
outStream.Append(o);
}
outStream.RestartStrip();
}
fixed4 frag (g2f i) : SV_Target
{
fixed4 col=tex2D(_MainTex, i.uv)*_MainColor;
return col;
}
ENDCG
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment