[ShaderToy ].

Source: Internet
Author: User

[ShaderToy ].
Preface

Sorry, I haven't written a blog for a long time. The bigger I feel, the more I miss my home. I hope I can stay with my family. Even if I just sit together and don't talk, I feel very warm. When I think of separating my eyes, I start to get sour. When I start school, I want to update my blog to learn more ~

Today, I found that the CSDN blog editor was updated! The progress is always good. The previous editor was very anxious. It is indeed much easier to use this markup language, but it seems that the color font cannot be set? Programmers have no pursuit of beauty.

ShaderToy

If you haven't heard of ShaderToy, you really missed a good shader learning website. I once heard friends mention this website in the group. Click it and you will find a lot of brilliant shader presentations.

To put it simply, this website allows people to share and compile pixel shaders of GLSL. In other words, which of the following effects can be achieved by pixel shaders alone (of course, there is also a combination of textures and models. If not, please point out). Is it very powerful? There are a lot of strong people in it, just like brainstorming, And you are amazed again and again. You can do this again! However, it also contains a lot of mathematical and algorithm knowledge, so you may often find that your head is not enough to keep up with the author's ideas... However, my head is trained, and there is no shortcut. It's always right to read more and write more ~

It is strongly recommended that you go for a stroll. There are a lot of interesting things. For example, this person wrote a mobius band, and this person wrote a dazzling little sun! At first, it was hard to believe that all of these were calculated using shader.

Features

As mentioned before, all shader on the Internet is the pixel shaders of GLSL. So what is pixel shader? If we need to render a square plate that is just full screen covering the entire screen, the square fragment shader is a pixel shader. This is because at this time, each fragment corresponds to a pixel on the screen. Therefore, many input values of pixel shader are the same. At the top of each shader in ShaderToy, you can see a Shader Input:

uniform vec3      iResolution;           // viewport resolution (in pixels)uniform float     iGlobalTime;           // shader playback time (in seconds)uniform float     iChannelTime[4];       // channel playback time (in seconds)uniform vec3      iChannelResolution[4]; // channel resolution (in pixels)uniform vec4      iMouse;                // mouse pixel coords. xy: current (if MLB down), zw: clickuniform samplerXX iChannel0..3;          // input channel. XX = 2D/Cubeuniform vec4      iDate;                 // (year, month, day, time in seconds)uniform float     iSampleRate;           // sound sample rate (i.e., 44100)

These are the public variables provided by ShaderToy, which can be accessed directly. For example, iResolution stores the screen resolution, iGlobalTime provides the shader running time, And iMouse provides the mouse click position.

Since ShaderToy is for pixel shaders, it also means that their vertex shaders are the same. You only need to calculate the basic vertex position and screen position.

Practice in Unity

The emergence of Unity indeed gives many shader learners a convenient compilation and display platform. We no longer need to prepare vertex data with a lot of code each time, set the texture each time, set the MVP matrix every time, and so on. Unity provides us with more convenient visual operations.

Many shader in ShaderToy can be compiled and run in Unity after some modifications. Of course, someone has done this. For example, this blogger.

To facilitate subsequent compilation, we can write a basic ShaderToy template shader. Before that, we need to figure out what the ShaderToy Shaders looks like. If you observe carefully, all shader in ShaderToy actually has only one essential function:

void mainImage( out vec4 fragColor, in vec2 fragCoord )

Its input is a fragCoord of vec2 type, which corresponds to the input screen position. It outputs a fragColor of vec4, which corresponds to the pixel color. It's easy, right!

Now we can write down the shader template.

Shader "shadertoy/template" {Properties {iMouse ("Mouse Pos", Vector) = (100,100,) iChannel0 ("iChannel0", 2D) = "white" {} iChannelResolution0 ("iChannelResolution0", Vector) = (100,100,)} CGINCLUDE # include "UnityCG. cginc "# pragma target 3.0 # define vec2 float2 # define vec3 float3 # define vec4 float4 # define mat2 float2x2 # define iGlobalTime _ Time. y # define mod fmod # define mix lerp # define atan atan2 # define fract frac # define texture2D tex2D // screen size # define iResolution _ ScreenParams // coordinates on the screen, in pixel # define gl_FragCoord (_ iParam. srcPos. xy/_ iParam. srcPos. w) * _ ScreenParams. xy) # define PI2 6.28318530718 # define pi 3.14159265358979 # define halfpi (pi * 0.5) # define oneoverpi (1.0/pi) fixed4 iMouse; sampler2D iChannel0; fixed4 iChannelResolution0; struct v2f {float4 pos: SV_POSITION; float4 srcPos: TEXCOORD0 ;}; v2f vert (appdata_base v) {v2f o; o. pos = mul (UNITY_MATRIX_MVP, v. vertex); o. srcPos = ComputeScreenPos (o. pos); return o;} vec4 main (vec2 fragCoord); fixed4 frag (v2f _ iParam): COLOR0 {vec2 fragCoord = gl_FragCoord; return main (gl_FragCoord );} vec4 main (vec2 fragCoord) {return vec4 (,);} ENDCG SubShader {Pass {CGPROGRAM # pragma vertex vert # pragma fragment frag # pragma fragmentoption implements ENDCG} FallBack Off}

The code is relatively simple. It mainly defines a series of macros at the beginning to connect to GLSL in ShaderToy. The main function corresponds to the previous mainImage function. Later, we only need to define other functions in CGINCLUDE and fill in the main function.

To respond to mouse operations, we can also write a C # script to transfer the cursor position to the shader when dragging the mouse.

using UnityEngine;using System.Collections;public class ShaderToyHelper : MonoBehaviour {    private Material _material = null;    private bool _isDragging = false;    // Use this for initialization    void Start () {        Renderer render  = GetComponent<Renderer>();        if (render != null) {            _material = render.material;        }        _isDragging = false;    }    // Update is called once per frame    void Update () {        Vector3 mousePosition = Vector3.zero;        if (_isDragging && _material != null) {            mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f);        } else {            mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0.0f);        }        _material.SetVector("iMouse", mousePosition);    }    void OnMouseDown() {        _isDragging = true;    }    void OnMouseUp() {        _isDragging = false;    }}

The code is very simple. When dragging the mouse, the Z component of mousePositon is 1, otherwise it is 0. This is consistent with how the mouse is judged in ShaderToy.

During use, you only need to drag the script to the object where the material is located, and make sure that the object is bound with Collider.

Conclusion

The vast majority of ShaderToy's Code relies on powerful mathematical computation, so it is really a brainstorm. Of course, some people will think it is of little use for popular mobile terminals, because it cannot be supported ~ However, I don't have a job yet, so I think it's good to exercise ~ In the future, I will try to update the shader in ShaderToy on a regular basis every week. In short, I hope you will enjoy have fun ~

P.S. always thinks that the articles written in the new editor are not as good as they are...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.