const float HEAT_MAX = 10.; const float PointRadius = .42; // test data const int PointCount = 18; const vec3 Points[] = vec3[]( vec3(0., 0., 10.), vec3(.2, .6, 5.), vec3(.25, .7, 8.), vec3(.33, .9, 5.), vec3(.35, .8, 6.), vec3(.1, .1, 6.), vec3(-.45, .8, 4.), vec3(-.2, -.6, 5.), vec3(-.25, -.7, 8.), vec3(-.33, -.9, 8.), vec3(.35, -.45, 10.), vec3(-.1, -.8, 10.), vec3(.33, -.3, 5.), vec3(-.35, .75, 6.), vec3(.6, .4, 10.), vec3(-.4, -.8, 4.), vec3(.7, -.3, 6.), vec3(.3, -.8, 8.) ); vec3 gradient(float w, vec2 uv) { w = pow(clamp(w, 0., 1.) * 3.14159 * .5, .9); vec3 c = vec3(sin(w), sin(w * 2.), cos(w)) * 1.1; return mix(texture(iChannel0, uv).rgb, c, w); } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = (2. * fragCoord - iResolution.xy) / min(iResolution.x, iResolution.y); float d = 0.; for (int i = 0; i < PointCount; i++) { vec3 v = Points[i]; float intensity = v.z / HEAT_MAX; float pd = (1. - length(uv - v.xy) / PointRadius) * intensity; d += pow(max(0., pd), 2.); } fragColor = vec4(gradient(d, uv), 1.); } 将上述代码转为unity可读的shader
时间: 2023-12-30 19:04:13 浏览: 122
可以将上述代码转为以下的 Unity Shader:
```
Shader "Custom/HeatMap" {
Properties {
_MainTex ("Texture", 2D) = "white" {}
_HeatMax ("Heat Max", Range(0, 100)) = 10
_PointRadius ("Point Radius", Range(0, 1)) = 0.42
_PointCount ("Point Count", Range(0, 50)) = 18
_Points ("Points", Vector) = (
(0, 0, 10),
(0.2, 0.6, 5),
(0.25, 0.7, 8),
(0.33, 0.9, 5),
(0.35, 0.8, 6),
(0.1, 0.1, 6),
(-0.45, 0.8, 4),
(-0.2, -0.6, 5),
(-0.25, -0.7, 8),
(-0.33, -0.9, 8),
(0.35, -0.45, 10),
(-0.1, -0.8, 10),
(0.33, -0.3, 5),
(-0.35, 0.75, 6),
(0.6, 0.4, 10),
(-0.4, -0.8, 4),
(0.7, -0.3, 6),
(0.3, -0.8, 8)
)
}
SubShader {
Pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
uniform sampler2D _MainTex;
uniform float _HeatMax;
uniform float _PointRadius;
uniform int _PointCount;
uniform float3 _Points[_PointCount];
struct appdata {
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v) {
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
vec3 gradient(float w, vec2 uv) {
w = pow(clamp(w, 0., 1.) * 3.14159 * .5, .9);
vec3 c = vec3(sin(w), sin(w * 2.), cos(w)) * 1.1;
return mix(tex2D(_MainTex, uv).rgb, c, w);
}
void frag (v2f i, out float4 o : SV_Target) {
vec2 uv = (2. * i.uv - _ScreenParams.xy) / min(_ScreenParams.x, _ScreenParams.y);
float d = 0.;
for (int i = 0; i < _PointCount; i++) {
float3 v = _Points[i];
float intensity = v.z / _HeatMax;
float pd = (1. - length(uv - v.xy) / _PointRadius) * intensity;
d += pow(max(0., pd), 2.);
}
o = float4(gradient(d, uv), 1.);
}
ENDCG
}
}
FallBack "Diffuse"
}
```
在这个 Unity Shader 中,我们使用了 _MainTex 来加载纹理,_HeatMax、_PointRadius、_PointCount 和 _Points 分别表示热力图的最大值、点半径、点数量和点的位置。然后在 Pass 中进行了渲染,使用了 vertex 和 uv 的数据类型,同时还使用了 UnityCG.cginc 中的函数。最后,使用了 gradient 函数和 frag 函数来实现对应的渲染效果。
阅读全文