블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2737)
Unity3D (817)
Script (91)
Extensions (14)
Effect (3)
NGUI (77)
UGUI (8)
Physics (2)
Shader (36)
Math (1)
Design Pattern (2)
Xml (1)
Tips (200)
Link (22)
World (1)
AssetBundle (25)
Mecanim (2)
Plugins (70)
Trouble Shooting (68)
Encrypt (7)
LightMap (4)
Shadow (4)
Editor (8)
Crash Report (3)
Utility (9)
UnityVS (2)
Facebook SDK (2)
iTween (3)
Font (11)
Ad (14)
Photon (2)
IAP (1)
Google (8)
Android (45)
iOS (41)
Programming (474)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-27 00:02

[링크] www.elopezr.com/photoshop-blend-modes-in-unity/

 

Photoshop Blend Modes Without Backbuffer Copy

[latexpage] For the past couple of weeks, I have been trying to replicate the Photoshop blend modes in Unity. It is no easy task; despite the advances of modern graphics hardware, the blend unit st…

www.elopezr.com

Photoshop Blend Modes Without Backbuffer Copy

 BY ADMINOCTOBER 7, 2016GRAPHICS, UNITY

For the past couple of weeks, I have been trying to replicate the Photoshop blend modes in Unity. It is no easy task; despite the advances of modern graphics hardware, the blend unit still resists being programmable and will probably remain fixed for some time. Some OpenGL ES extensions implement this functionality, but most hardware and APIs don’t. So what options do we have?

1) Backbuffer copy

A common approach is to copy the entire backbuffer before doing the blending. This is what Unity does. After that it’s trivial to implement any blending you want in shader code. The obvious problem with this approach is that you need to do a full backbuffer copy before you do the blending operation. There are certainly some possible optimizations like only copying what you need to a smaller texture of some sort, but it gets complicated once you have many objects using blend modes. You can also do just a single backbuffer copy and re-use it, but then you can’t stack different blended objects on top of each other. In Unity, this is done via a GrabPass. It is the approach used by the Blend Modes plugin.

2) Leveraging the Blend Unit

Modern GPUs have a little unit at the end of the graphics pipeline called the Output Merger. It’s the hardware responsible for getting the output of a pixel shader and blending it with the backbuffer. It’s not programmable, as to do so has quite a lot of complications (you can read about it here) so current GPUs don’t have one.

The blend mode formulas were obtained here and here. Use it as reference to compare it with what I provide. There are many other sources. One thing I’ve noticed is that provided formulas often neglect to mention that Photoshop actually uses modified formulas and clamps quantities in a different manner, especially when dealing with alpha. Gimp does the same. This is my experience recreating the Photoshop blend modes exclusively using a combination of blend unit and shaders. The first few blend modes are simple, but as we progress we’ll have to resort to more and more tricks to get what we want.

Two caveats before we start. First off, Photoshop blend modes do their blending in sRGB space, which means if you do them in linear space they will look wrong. Generally this isn’t a problem, but due to the amount of trickery we’ll be doing for these blend modes, many of the values need to go beyond the 0 – 1 range, which means we need an HDR buffer to do the calculations. Unity can do this by setting the camera to be HDR in the camera settings, and also setting Gamma for the color space in the Player Settings. This is clearly undesirable if you do your lighting calculations in linear space. In a custom engine you would probably be able to set this up in a different manner (to allow for linear lighting).

If you want to try the code out while you read ahead, download it here.

 

[File]

BlendModesNoBackbuffer.zip
0.00MB

 

A) Darken

Formula min(SrcColor, DstColor)
Shader Output color.rgb = lerp(float3(1, 1, 1), color.rgb, color.a);
Blend Unit Min(SrcColor · One, DstColor · One)

Darken

As alpha approaches 0, we need to tend the minimum value to DstColor, by forcing SrcColor to be the maximum possible color float3(1, 1, 1)

 

B) Multiply

Formula SrcColor · DstColor
Shader Output color.rgb = color.rgb * color.a;
Blend Unit SrcColor · DstColor + DstColor · OneMinusSrcAlpha

Multiply

 

C) Color Burn

Formula 1 – (1 – DstColor) / SrcColor
Shader Output color.rgb = 1.0 - (1.0 / max(0.001, color.rgb * color.a + 1.0 - color.a)); // max to avoid infinity
Blend Unit SrcColor · One + DstColor · OneMinusSrcColor

Color Burn

 

D) Linear Burn

Formula SrcColor + DstColor – 1
Shader Output color.rgb = (color.rgb - 1.0) * color.a;
Blend Unit SrcColor · One + DstColor · One

Linear Burn

 

E) Lighten

Formula Max(SrcColor, DstColor)
Shader Output color.rgb = lerp(float3(0, 0, 0), color.rgb, color.a);
Blend Unit Max(SrcColor · One, DstColor · One)

Lighten

 

F) Screen

Formula 1 – (1 – DstColor) · (1 – SrcColor) = Src + Dst – Src · Dst
Shader Output color.rgb = color.rgb * color.a;
Blend Unit SrcColor · One + DstColor · OneMinusSrcColor

Screen

 

G) Color Dodge

Formula DstColor / (1 – SrcColor)
Shader Output color.rgb = 1.0 / max(0.01, (1.0 - color.rgb * color.a));
Blend Unit SrcColor · DstColor + DstColor · Zero

Color Dodge

You can see discrepancies between the Photoshop and the Unity version in the alpha blending, especially at the edges.

 

H) Linear Dodge

Formula SrcColor + DstColor
Shader Output color.rgb = color.rgb;
Blend Unit SrcColor · SrcAlpha + DstColor · One

Linear Dodge

This one also exhibits color “bleeding” at the edges. To be honest I prefer the one to the right just because it looks more “alive” than the other one. Same goes for Color Dodge. However this limits the 1-to-1 mapping to Photoshop/Gimp.

All of the previous blend modes have simple formulas and one way or another they can be implemented via a few instructions and the correct blending mode. However, some blend modes have conditional behavior or complex expressions (complex relative to the blend unit) that need a bit of re-thinking. Most of the blend modes that follow needed a two-pass approach (using the Pass syntax in your shader). Two-pass shaders in Unity have a limitation in that the two passes aren’t guaranteed to render one after the other for a given material. These blend modes rely on the previous pass, so you’ll get weird artifacts. If you have two overlapping sprites (as in a 2D game, such as our use case) the sorting will be undefined. The workaround around this is to move the Order in Layer property to force them to sort properly.

 

I) Overlay

Formula 1 – (1 – 2 · (DstColor – 0.5)) · (1 – SrcColor), if DstColor > 0.5
2 · DstColor · SrcColor, if DstColor <= 0.5
Shader Pass 1 color.rgb *= color.a;
float3 A = (4.0 * color.rgb - 1.0) / (2.0 - 4.0 * color.rgb);
float3 B = (1.0 * color.a) / ((2.0 - 4.0 * color.rgb) * max(0.001, color.a));
color.rgb = A + B;
Blend Pass 1 SrcColor · DstColor + DstColor · DstColor
Shader Pass 2 color.rgb = (2.0 - 4.0 * color.rgb * color.a) max(0.001, color.a);
Blend Pass 2 SrcColor · DstColor + DstColor · Zero

Overlay

How I ended up with Overlay requires an explanation. We take the original formula and approximate via a linear blend:

We simplify as much as we can and end up with this

The only way I found to get DstColor · DstColor is to isolate the term and do it in two passes, therefore we extract the same factor in both sides:

However this formula doesn’t take alpha into account. We still need to linearly interpolate this big formula with alpha, where an alpha of 0 should return Dst. Therefore

If we include the last term into the original formula, we can still do it in 2 passes. We need to be careful to clamp the alpha value with max(0.001, a) because we’re now potentially dividing by 0. The final formula is

 

J) Soft Light

Formula 1 – (1 – DstColor) · (1 – (SrcColor – 0.5)), if SrcColor > 0.5
DstColor · (SrcColor + 0.5), if SrcColor <= 0.5
Shader Pass 1

float3 A = 2.0 * color.rgb * color.a / (1.0 - 2.0 * color.rgb * color.a);
float3 B = (1.0 - color.a) / ((1.0 - 2.0 * color.rgb * color.a) * max(0.001, color.a));
color.rgb = A + B;

Blend Pass 1 SrcColor · DstColor + SrcColor · DstColor
Shader Pass 2 color.rgb = (1.0 - 2.0 * color.rgb * color.a) * max(0.001, color.a);
Blend Pass 2 SrcColor · DstColor + SrcColor * Zero

Soft Light

For the Soft Light we apply a very similar reasoning to Overlay, which in the end leads us to Pegtop’s formula. Both are different from Photoshop’s version in that they don’t have discontinuities. This one also has a darker fringe when alpha blending.

 

K) Hard Light

Formula 1 – (1 – DstColor) · (1 – 2 · (SrcColor – 0.5)), if SrcColor> 0.5
DstColor · (2 · SrcColor), if SrcColor <= 0.5
Shader Pass 1

float3 A (2.0 * color.rgb * color.rgb - color.rgb) * color.a;

float3 B max(0.001, (4.0 * color.rgb - 4.0 * color.rgb * color.rgb) * color.a + 1.0 - color.a);

color.rgb = A B;

Blend Pass 1 SrcColor · One + DstColor · One
Shader Pass 2 color.rgb = max(0.001, (4.0 * color.rgb - 4.0 * color.rgb * color.rgb) * color.a + 1.0 - color.a);
Blend Pass 2 SrcColor · DstColor + SrcColor * Zero

Hard Light

Hard Light has a very delicate hack that allows it to work and blend with alpha. In the first pass we divide by some magic number, only to multiply it back in the second pass! That’s because when alpha is 0 it needs to result in DstColor, but it was resulting in black.

 

L) Vivid Light

Formula 1 – (1 – DstColor) / (2 · (SrcColor – 0.5)), if SrcColor > 0.5
DstColor / (1 – 2 · SrcColor), if SrcColor <= 0.5
Shader Pass 1

color.rgb *= color.a;

color.rgb = color.rgb &gt;0.5 ? 1.0 / max(0.0001, 2.0 - 2.0 * color.rgb) : 1.0);

Blend Pass 1 SrcColor · DstColor + SrcColor · Zero
Shader Pass 2 color.rgb = color.rgb &lt; 0.5 ? (color.a - color.a / max(0.0001, 2.0 * color.rgb)) : 0.0;
Blend Pass 2 SrcColor · One + SrcColor · OneMinusSrcColor

Vivid Light

 

M) Linear Light

Formula DstColor + 2 · (SrcColor – 0.5), if SrcColor > 0.5
DstColor + 2 · SrcColor – 1, if SrcColor <= 0.5
Shader Output color.rgb = (2 * color.rgb - 1.0) * color.a;
Blend Unit  SrcColor · One + DstColor · One

Linear Light

[29/04/2019] Roman in the comments below reports that he couldn’t get Linear Light to work using the proposed method and found an alternative. His reasoning is that the output color becomes negative which gets clamped. I’m not sure what changed in Unity between when I did it and now but perhaps it relied on having an RGBA16F render target which may have changed since then to some other HDR format such as RG11B10F or RGB10A2 which do not support negative values. His alternative becomes (using RevSub as the blend op):

Formula DstColor + 2 · (SrcColor – 0.5), if SrcColor > 0.5
DstColor + 2 · SrcColor – 1, if SrcColor <= 0.5
Shader Output color.rgb = -(2 * color.rgb - 1.0) * color.a;
Blend Unit DstColor · One – SrcColor · One

 

 

 
반응형
Posted by blueasa
, |

[링크] https://www.shadertoy.com/browse

 

Browse (1) - Shadertoy BETA

Results (40693):

www.shadertoy.com

 

반응형
Posted by blueasa
, |

Rim lighting and realtime shadows for sprites in Unity (2D) – 1/2

Rim lighting and realtime shadows for sprites in Unity (2D) – 2/2

 

[github] https://github.com/Rafarfn/SpriteLighting

 

Rafarfn/SpriteLighting

Custom 2D sprite lighting with shadow casting and rim lighting - Rafarfn/SpriteLighting

github.com

 

반응형
Posted by blueasa
, |

 

https://github.com/sunduk/UnityRoundedShader

 

 

유니티에서 셰이더로 원이나 모서리가 둥근 사각형 만들때 쓸 수 있는 셰이더 입니다.

구글 검색하면 자료는 많이 나오는데 쉽게 이해되는 코드가 없는것 같아서 정리할겸 만들어 봤습니다.

 

UI쪽은 사실 유니티에서 지원하는 mask기능도 있어서 쓸일이 많지는 않겠지만

실시간으로 만든 텍스쳐 다룰때는 유용할것 같습니다.

 

 

p.s 

이거 구현하면서 인터넷과 구글이 없었으면 어떻게 이런 기법들을 배우고 공유할 수 있었을까 하는 생각이 많이 들었습니다.

특히 셰이더토이, 더 북 오브 셰이더 여기 두곳은 정말 보물섬 같은 곳이네요.

 

https://www.shadertoy.com/view/ldfSDj

https://thebookofshaders.com/

 

 

[출처]

게임코디 태풍의그라운드

http://www.gamecodi.com/board/zboard.php?id=GAMECODI_Talkdev&page=1&page_num=35&select_arrange=headnum&desc=asc&sn=off&ss=on&sc=on&keyword=&no=5239&category=

반응형
Posted by blueasa
, |

Note:

Unity 5.6’s release made some changes to the default sprite shader which make parts of the shader in the following post invalid. At the bottom of this post you’ll find an updated version of the demo project that works in Unity 5.6.

Unity provides a component to outline UI objects, but it doesn’t work on world space sprites. This post will demonstrate a simple way to add outlines to sprites using an extended version of the default sprite shader along with a simple component. This could be used to highlight sprites on mouse over, highlight items in the environment, or just to make sprites stand out from their surroundings.

To begin, create a new shader in your project called Sprite-Outline. This shader provides all the functionality of the default sprite shader, with the additions to allow sprite outlines.

Shader "Sprites/Outline"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0

        // Add values to determine if outlining is enabled and outline color.
        [PerRendererData] _Outline ("Outline", Float) = 0
        [PerRendererData] _OutlineColor("Outline Color", Color) = (1,1,1,1)
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma multi_compile _ PIXELSNAP_ON
            #pragma shader_feature ETC1_EXTERNAL_ALPHA
            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                float2 texcoord  : TEXCOORD0;
            };

            fixed4 _Color;
            float _Outline;
            fixed4 _OutlineColor;

            v2f vert(appdata_t IN)
            {
                v2f OUT;
                OUT.vertex = mul(UNITY_MATRIX_MVP, IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif

                return OUT;
            }

            sampler2D _MainTex;
            sampler2D _AlphaTex;
            float4 _MainTex_TexelSize;

            fixed4 SampleSpriteTexture (float2 uv)
            {
                fixed4 color = tex2D (_MainTex, uv);

                #if ETC1_EXTERNAL_ALPHA
                // get the color from an external texture (usecase: Alpha support for ETC1 on android)
                color.a = tex2D (_AlphaTex, uv).r;
                #endif //ETC1_EXTERNAL_ALPHA

                return color;
            }

            fixed4 frag(v2f IN) : SV_Target
            {
                fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;

                // If outline is enabled and there is a pixel, try to draw an outline.
                if (_Outline > 0 && c.a != 0) {
                    // Get the neighbouring four pixels.
                    fixed4 pixelUp = tex2D(_MainTex, IN.texcoord + fixed2(0, _MainTex_TexelSize.y));
                    fixed4 pixelDown = tex2D(_MainTex, IN.texcoord - fixed2(0, _MainTex_TexelSize.y));
                    fixed4 pixelRight = tex2D(_MainTex, IN.texcoord + fixed2(_MainTex_TexelSize.x, 0));
                    fixed4 pixelLeft = tex2D(_MainTex, IN.texcoord - fixed2(_MainTex_TexelSize.x, 0));

                    // If one of the neighbouring pixels is invisible, we render an outline.
                    if (pixelUp.a * pixelDown.a * pixelRight.a * pixelLeft.a == 0) {
                        c.rgba = fixed4(1, 1, 1, 1) * _OutlineColor;
                    }
                }

                c.rgb *= c.a;

                return c;
            }
            ENDCG
        }
    }
}

Now create a new material called SpriteOutline and assign the newly created shader to it in the inspector.

Sprite Outline Material

Next create a new C# script and name it SpriteOutline. This component is going to handle updating our material in the editor and at runtime to toggle the outline off or on and also change the color. This component can also be targetted in an animation to enable or disable outlines for specific animation frames or to change the outline color.

using UnityEngine;

[ExecuteInEditMode]
public class SpriteOutline : MonoBehaviour {
    public Color color = Color.white;

    private SpriteRenderer spriteRenderer;

    void OnEnable() {
        spriteRenderer = GetComponent<SpriteRenderer>();

        UpdateOutline(true);
    }

    void OnDisable() {
        UpdateOutline(false);
    }

    void Update() {
        UpdateOutline(true);
    }

    void UpdateOutline(bool outline) {
        MaterialPropertyBlock mpb = new MaterialPropertyBlock();
        spriteRenderer.GetPropertyBlock(mpb);
        mpb.SetFloat("_Outline", outline ? 1f : 0);
        mpb.SetColor("_OutlineColor", color);
        spriteRenderer.SetPropertyBlock(mpb);
    }
}

Now that the hard work is done, add a few sprites to your scene. Change the material field of the SpriteRenderer component to the SpriteOutline material created above. You’ll also want to add the SpriteOutline component to this game object to show a white outline by default. To hide the outline simply disable or remove the component.

Completed Sprite

With all that completed, you should now have a sprite with a white outline. In the inspector you can change the color to anything you’d like, independently from the SpriteRenderer color. The custom shader also maintains all existing functionality of the default sprite shader.

Completed Sprite

Please download the demo project and play around with it to get a better idea of how this technique looks and works. It contains a single scene with three examples of outlined sprites, one of which is animated.

Shaders can be complicated, but they are very powerful and make it quite easy to implement graphical features, even in 2D. If you have any further questions please feel free to message me on Twitter @RyanNielson or comment below.

Update (June 2, 2016)

Some people have been asking about how to change the thickness of the sprite outlines. Please download this new demo project with the changes to add this functionality. Changes were made to both the shader and component. Just adjust the outline size slider on the sprite outline component to change outline size. There is a limited outline size of 16 to prevent issues with shader for loop unrolling. It hasn’t been tested throughly, so your results may vary, but it’s probably a good place to start.

Update (April 7, 2017)

Unity 5.6 has been released, and along with that came some changes to the default sprite shader. Unfortunetely this seems to be causing issues with parts of the method used above. Please download this new demo project which changes the sprite outline shader to incorporate the 5.6 shader changes.



[출처] https://nielson.io/2016/04/2d-sprite-outlines-in-unity/

반응형
Posted by blueasa
, |

[파일]

Super-Blur-master.zip




[링크] https://github.com/PavelDoGreat/Super-Blur



Super Blur

Blur effect that you can apply on Camera and UI. Gaussian weights was taken from this project.

view

Usage

Just add SuperBlur.cs or SuperBlurFast.cs script to Camera and attach Blur Material and UI Material to it.

  • SuperBlur - (recommended way) It's using OnRenderImage to grab screen texture.

  • SuperBlurFast - Render scene directly to render texture. Much better perfomance on mobile devices, but doesn't work with other post effects.

Properties

editor

  • Render Mode - Chooses to render as Post Effect or just apply blurred texture to UI material.

  • Kernel Size - Bigger kernels produces bigger blur, but are more expensive.

  • Interpolation - Use if you want to create smooth blurring transition.

  • Downsample - Controls buffer resolution (0 = no downsampling, 1 = half resolution... etc.).

  • Iterations - More iterations = bigger blur, but comes at perfomance cost.

  • Gamma Correction - Enables gamma correction to produce correct blur in Gamma Colorspace. Disable this option if you use Linear Colorspace.

License

If you'd try to sell it on Asset Store, then I'm gonna find you.

See LICENSE for details.



반응형
Posted by blueasa
, |

[파일]

Dvornik-Unity-Distortion.zip



Unity 3D Anoxemia Heat Distort Tutorial



Hello. It is a part of Anoxemia tutorials. Here I want to share some experience of creating 2D game with Unity

What we going to do here:



DOWNLOAD:
https://dl.dropboxusercontent.com/u/106482752/Dvornik-Unity-Distortion.zip

Root tutorial: http://kostiantyn-dvornik.blogspot.com/2014/07/anoxemia-unity-2d-tutorial.html


If you ever want to create cool effects like hot air waving or thick glass refraction or some underwater streams you will came to Detonator package and HeatDistort shader.But as for me it looks very complicated, so write my own and use it well with latest Unity 2D system.

NOTE: it works only with Unity Pro and Deffered lighting on. It works the same way how Detonator'a works. It tooks image and project it correctly on a plane with texture distortion.

We will split tutorial into 2 steps.
1.Explain shader
2. How to use it.

1.
Lets take a look at the shader:

Shader "Dvornik/Distort" {
Properties {
_Refraction ("Refraction", Range (0.00, 100.0)) = 1.0
_DistortTex ("Base (RGB)", 2D) = "white" {}
}

SubShader {

Tags { "RenderType"="Transparent" "Queue"="Overlay" }
LOD 100

GrabPass
{

}

CGPROGRAM
#pragma surface surf NoLighting
#pragma vertex vert

fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten){
        fixed4 c;
        c.rgb = s.Albedo;
        c.a = s.Alpha;
        return c;
  }

sampler2D _GrabTexture : register(s0);
sampler2D _DistortTex : register(s2);
float _Refraction;

float4 _GrabTexture_TexelSize;

struct Input {
float2 uv_DistortTex;
float3 color;
float3 worldRefl;
float4 screenPos;
INTERNAL_DATA
};

void vert (inout appdata_full v, out Input o) {
  UNITY_INITIALIZE_OUTPUT(Input,o);
  o.color = v.color;
}

void surf (Input IN, inout SurfaceOutput o) {

    float3 distort = tex2D(_DistortTex, IN.uv_DistortTex) * float3(IN.color.r,IN.color.g,IN.color.b );
    float2 offset = distort * _Refraction * _GrabTexture_TexelSize.xy;
    IN.screenPos.xy = offset * IN.screenPos.z + IN.screenPos.xy;
    float4 refrColor = tex2Dproj(_GrabTexture, IN.screenPos);
    o.Alpha = refrColor.a;
    o.Emission = refrColor.rgb;
}
ENDCG
}
}

We have just 2 properties. It is

_Refraction -amount of distortion
_DistortText - texture according to what we gonna distort our environment. You can use any colored texture. To make distortion. But in fact only Red and Green channels are working as distortion vector.

Tags { "RenderType"="Transparent" "Queue"="Overlay" } - We set Queue to Overlay because we want to render this effect after everything.

#pragma surface surf NoLighting
#pragma vertex vert

We used custom NoLigthing model and custom vertex shader to have deal with vertex color that used in particle system. There is a little chunk, cuz we write only Emission to have absolutely No Lighting shader.

 float3 distort = tex2D(_DistortTex, IN.uv_DistortTex) * float3(IN.color.r,IN.color.g,IN.color.b );
 float2 offset = distort * _Refraction * _GrabTexture_TexelSize.xy;
 IN.screenPos.xy = offset * IN.screenPos.z + IN.screenPos.xy;
 float4 refrColor = tex2Dproj(_GrabTexture, IN.screenPos);

Here we read distort texture, calculate offset of the screen and project on the model correctly. That's it.

2. 
Create a simple material and apply that shader. Next if you use particle system apply particle render order script to that. Other way some object will be rendered after distortion so it will looks weird. You can use particle Color or Color Over LifeTime to make distortion more/less. I often setup it thats way:

to make distortion fade in and fade out. Thats probabbly all that you need to know about.

Know bugs:
1.

How to resolve:
Add particle order script to PS and set order to  bigger then foreground sprite.
Effect is not working with orthographic camera

2. To much distortion on large distance to camera

How to resolve: add script that decreasing material property distortion with distance to camera.




[출처] http://kostiantyn-dvornik.blogspot.kr/2014/10/unity-3d-anoxemia-heat-distort-tutorial.html

반응형
Posted by blueasa
, |


[사진 : 서브웨이 서퍼 플레이 스크린샷]



출처 : http://answers.unity3d.com/questions/288835/how-to-make-plane-look-curved.html

http://devkorea.co.kr/bbs/board.php?bo_table=m03_lecture&wr_id=3315&page=0&sca=&sfl=&stx=&sst=&sod=&spt=0&page=0&currentId=42


위의 사진처럼 땅이 평평하지 않고 휘어지는 듯한 효과를 연출하기 위함이다. 

땅 자체를 곡선으로 만들수도 있겠지만 

카메라가 보는 부분의 렌더링을 수정함으로써 효과를 낼 수 있다.



BendTheWorldShader.unitypackage


위의 파일은 예제 파일이며, 

https://dl.dropboxusercontent.com/u/7761356/UnityAnswers/Web/BendTheWorld/WebPlayer.html

웹에서도 실행을 해볼 수 있다.



적용 방법 : 


위의 예제파일이나, 웹에서 보듯이 shader프로그래밍을 하면 된다.

shader 파일을 생성한다.



shader 파일에 아래와 같이 코드를 입력한다.


접기


Shader "Custom/Curved" {

Properties {

_MainTex ("Base (RGB)"2D) = "white" {}

_QOffset ("Offset"Vector) = (0,0,0,0)

_Dist ("Distance"Float) = 100.0

}

SubShader {

Tags { "RenderType"="Opaque" }

Pass

{

CGPROGRAM

#pragma vertex vert

#pragma fragment frag

#include "UnityCG.cginc"


            sampler2D _MainTex;

float4 _QOffset;

float _Dist;

struct v2f {

    float4 pos : SV_POSITION;

    float4 uv : TEXCOORD0;

} ;

v2f vert (appdata_base v)

{

    v2f o;

    // The vertex position in view-space (camera space)

    float4 vPos = mul (UNITY_MATRIX_MV, v.vertex);

    

    // Get distance from camera and scale it down with the global _Dist parameter

    float zOff = vPos.z/_Dist;

    // Add the offset with a quadratic curve to the vertex position

    vPos += _QOffset*zOff*zOff;

    

    o.pos = mul (UNITY_MATRIX_P, vPos);

    o.uv = mul( UNITY_MATRIX_TEXTURE0, v.texcoord );

    return o;

}


half4 frag (v2f i) : COLOR

{

    half4 col = tex2D(_MainTex, i.uv.xy);

    return col;

}

ENDCG

}

}

FallBack "Diffuse"

}






작성한 shader 파일을 texture의 shader로 적용한다.





그러면 카메라의 위치에서 멀리 있는 객체일수록 z축의 아래로 쳐져 있는 듯한 효과를 나타낼 수 있다. 




이제, 휘어지게 보여질 객체에 스크립트에서 처리해야 한다



mOffset =  new Vector2(0.0f,-1.8f)

        mModelsRenderer = mModel.GetComponentsInChildren<Renderer>();

mModelsMeshFilter = mModel.GetComponentsInChildren<MeshFilter>();

foreachRenderer render in mModelsRenderer )

render.material.SetVector("_QOffset", mOffset );

foreachMeshFilter meshfilter in mModelsMeshFilter )

meshfilter.mesh.bounds = new BoundsVector3.zero, Vector3.one * 3000 );



render.material.SetVector("_QOffset", mOffset )

 는 휘어지는 방향과 크기를 정하며


meshfilter.mesh.bounds = new BoundsVector3.zero, Vector3.one * 3000 );

는 mesh범위를 키워 카메라에서 멀리 있어도 휘어지는 효과 그대로 화면에 보이도록 함이다.




출처 : http://jenemia.tistory.com/258

반응형
Posted by blueasa
, |

 

참조 : http://blueasa.tistory.com/1777

참조 : http://www.tasharen.com/forum/index.php?topic=10223.0

 

[파일]

Photoshop Overlay.zip
다운로드

 

 

이전에 포토샵의 Overlay와 비슷한 느낌의 Shader가 필요해서 찾아서 올려놨는데 NGUI 패널에서 클리핑이 안돼서

 

수정 및 추가해서 올려 놓음.

 

 

 

반응형
Posted by blueasa
, |
  1. //Somehow achieves an effect similar to this:
  2. //#define BlendOverlayf(base, blend) (base < 0.5 ? (2.0 * base * blend) : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend)))
  3. Shader "Photoshop/Overlay"
  4. {
  5. Properties
  6. {
  7. _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {}
  8. }
  9. SubShader
  10. {
  11. Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"}
  12. ZWrite Off Lighting Off Cull Off Fog { Mode Off } Blend DstColor SrcColor
  13. LOD 110
  14. Pass
  15. {
  16. CGPROGRAM
  17. #pragma vertex vert_vct
  18. #pragma fragment frag_mult
  19. #pragma fragmentoption ARB_precision_hint_fastest
  20. #include "UnityCG.cginc"
  21. sampler2D _MainTex;
  22. float4 _MainTex_ST;
  23. struct vin_vct
  24. {
  25. float4 vertex : POSITION;
  26. float4 color : COLOR;
  27. float2 texcoord : TEXCOORD0;
  28. };
  29. struct v2f_vct
  30. {
  31. float4 vertex : POSITION;
  32. fixed4 color : COLOR;
  33. half2 texcoord : TEXCOORD0;
  34. };
  35. v2f_vct vert_vct(vin_vct v)
  36. {
  37. v2f_vct o;
  38. o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
  39. o.color = v.color;
  40. o.texcoord = v.texcoord;
  41. return o;
  42. }
  43. float4 frag_mult(v2f_vct i) : COLOR
  44. {
  45. float4 tex = tex2D(_MainTex, i.texcoord);
  46. float4 final;
  47. final.rgb = i.color.rgb * tex.rgb * 2;
  48. final.a = i.color.a * tex.a;
  49. return lerp(float4(0.5f,0.5f,0.5f,0.5f), final, final.a);
  50. }
  51. ENDCG
  52. }
  53. }
  54. }




출처 : http://answers.unity3d.com/questions/384550/shader-photoshop-overlay-effect.html

반응형
Posted by blueasa
, |