Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Unity 5.x Shaders and Effects Cookbook
Unity 5.x Shaders and Effects Cookbook

Unity 5.x Shaders and Effects Cookbook: Master the art of Shader programming to bring life to your Unity projects

eBook
€22.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Unity 5.x Shaders and Effects Cookbook

Chapter 2. Surface Shaders and Texture Mapping

In this chapter, we will explore Surface Shaders. We will start from a very simple matte material and end with holographic projections and advanced terrains blending. We can also use textures to animate, blend, and drive any other property that we want. In this chapter, you will learn about the following methods:

  • Diffuse shading
  • Using packed arrays
  • Adding a texture to a shader
  • Scrolling textures by modifying UV values
  • Normal mapping
  • Creating a transparent material
  • Creating a Holographic Shader
  • Packing and blending textures
  • Creating a circle around your terrain

Introduction

Surface Shaders have been introduced in Chapter 1, Creating Your First Shader, as the main type of shader used in Unity. This chapter will show in detail what these actually are and how they work. Generally speaking, there are two essential steps in every Surface Shader. First, you have to specify certain physical properties of the material that you want to describe, such as its diffuse color, smoothness, and transparency. These properties are initialized in a function called surface function and stored in a structure called surface output. Secondly, the surface output is passed to a lighting model. This is a special function that will also take information about the nearby lights in the scene. Both these parameters are then used to calculate the final color for each pixel of your model. The lighting function is where the real calculations of a shader take place as it's the piece of code that determines how light should behave when it touches a material.

The following...

Diffuse shading

Before starting our journey into texture mapping, it is important to understand how diffuse materials work. Certain objects might have a uniform color and smooth surface, but not smooth enough to shine on reflected light. These matte materials are best represented with a Diffuse shader. While in the real world, pure diffuse materials do not exist; Diffuse shaders are relatively cheap to implement and find a large application in games with low-poly aesthetics.

Getting ready

There are several ways in which you can create your own Diffuse shader. A quick way is to start with the Standard Shader in Unity 5 and edit it to remove any texture, similarly to what was previously done in Chapter 1, Creating Your First Shader.

How to do it...

Let's start with our Standard Shader, and apply the following changes:

  1. Remove all the properties except _Color:
    _Color ("Color", Color) = (1,1,1,1)
  2. From the SubShader{} section, remove the _MainTex, _Glossiness, and _Metallic variables...

Using packed arrays

Loosely speaking, the code inside a shader has to be executed for at least every pixel in your screen. This is the reason why GPUs are highly optimized for parallel computing. This philosophy is also evident in the standard type of variables and operators available in Cg. Understanding them is essential not just to use shaders correctly, but also to write highly optimized ones.

How to do it...

There are two types of variables in Cg: single values and packed arrays. The latter can be identified because their type ends with a number such as float3 or int4. As their names suggest, these types of variables are similar to structs, which means that they each contain several single values. Cg calls them packed arrays, though they are not exactly arrays in the traditional sense.

The elements of a packed array can be accessed as a normal struct. They are typically called x, y, z, and w. However, Cg also provides you with another alias for them, that is, r, g, b, and a. Despite...

Adding a texture to a shader

Textures can bring our shaders to life very quickly in terms of achieving very realistic effects. In order to effectively use textures, we need to understand how a 2D image is mapped to a 3D model. This process is called texture mapping, and it requires some work to be done on the shader and 3D model that we want to use. Models, in fact, are made out of triangles; each vertex can store data that shaders can access. One of the most important information stored in vertices is the UV data. It consists of two coordinates, U and V, ranging from 0 to 1. They represent the XY position of the pixel in the 2D image that will be mapped to the vertices. UV data is present only for vertices; when the inner points of a triangle have to be texture-mapped, the GPU interpolates the closest UV values to find the right pixel in the texture to be used. The following image shows you how a 2D texture is mapped to a triangle from a 3D model:

Adding a texture to a shader

The UV data is stored in the 3D model...

Scrolling textures by modifying UV values

One of the most common texture techniques used in today's game industry is the process of allowing you to scroll the textures over the surface of an object. This allows you to create effects such as waterfalls, rivers, lava flows, and so on. It's also a technique that is the basis to create animated sprite effects, but we will cover this in a subsequent recipe of this chapter. Let's first see how we will create a simple scrolling effect in a Surface Shader.

Getting ready

To begin this recipe, you will need to create a new shader file and material. This will set us up with a nice clean shader that we can use to study the scrolling effect by itself.

How to do it…

To begin with, we will launch our new shader file that we just created and enter the code mentioned in the following steps:

  1. The shader will need two new properties that will allow us to control the speed of the texture scrolling. So, let's add a speed property for the...

Normal mapping

Every triangle of a 3D model has a facing direction, which is the direction that it is pointing toward. It is often represented with an arrow placed in the center of the triangle and orthogonal to the surface. The facing direction plays an important role in the way light reflects on a surface. If two adjacent triangles face different directions, they will reflect lights at different angles, hence they'll be shaded differently. For curved objects, this is a problem: it is obvious that the geometry is made out of flat triangles.

To avoid this problem, the way the light reflects on a triangle doesn't take into account its facing direction, but its normal direction instead. As stated in Adding a texture to a shader recipe, vertices can store data; the normal direction is the most used information after the UV data. This is a vector of unit length that indicates the direction faced by the vertex. Regardless of the facing direction, every point within a triangle has its...

Introduction


Surface Shaders have been introduced in Chapter 1, Creating Your First Shader, as the main type of shader used in Unity. This chapter will show in detail what these actually are and how they work. Generally speaking, there are two essential steps in every Surface Shader. First, you have to specify certain physical properties of the material that you want to describe, such as its diffuse color, smoothness, and transparency. These properties are initialized in a function called surface function and stored in a structure called surface output. Secondly, the surface output is passed to a lighting model. This is a special function that will also take information about the nearby lights in the scene. Both these parameters are then used to calculate the final color for each pixel of your model. The lighting function is where the real calculations of a shader take place as it's the piece of code that determines how light should behave when it touches a material.

The following diagram...

Diffuse shading


Before starting our journey into texture mapping, it is important to understand how diffuse materials work. Certain objects might have a uniform color and smooth surface, but not smooth enough to shine on reflected light. These matte materials are best represented with a Diffuse shader. While in the real world, pure diffuse materials do not exist; Diffuse shaders are relatively cheap to implement and find a large application in games with low-poly aesthetics.

Getting ready

There are several ways in which you can create your own Diffuse shader. A quick way is to start with the Standard Shader in Unity 5 and edit it to remove any texture, similarly to what was previously done in Chapter 1, Creating Your First Shader.

How to do it...

Let's start with our Standard Shader, and apply the following changes:

  1. Remove all the properties except _Color:

    _Color ("Color", Color) = (1,1,1,1)
  2. From the SubShader{} section, remove the _MainTex, _Glossiness, and _Metallic variables. You should not...

Using packed arrays


Loosely speaking, the code inside a shader has to be executed for at least every pixel in your screen. This is the reason why GPUs are highly optimized for parallel computing. This philosophy is also evident in the standard type of variables and operators available in Cg. Understanding them is essential not just to use shaders correctly, but also to write highly optimized ones.

How to do it...

There are two types of variables in Cg: single values and packed arrays. The latter can be identified because their type ends with a number such as float3 or int4. As their names suggest, these types of variables are similar to structs, which means that they each contain several single values. Cg calls them packed arrays, though they are not exactly arrays in the traditional sense.

The elements of a packed array can be accessed as a normal struct. They are typically called x, y, z, and w. However, Cg also provides you with another alias for them, that is, r, g, b, and a. Despite there...

Adding a texture to a shader


Textures can bring our shaders to life very quickly in terms of achieving very realistic effects. In order to effectively use textures, we need to understand how a 2D image is mapped to a 3D model. This process is called texture mapping, and it requires some work to be done on the shader and 3D model that we want to use. Models, in fact, are made out of triangles; each vertex can store data that shaders can access. One of the most important information stored in vertices is the UV data. It consists of two coordinates, U and V, ranging from 0 to 1. They represent the XY position of the pixel in the 2D image that will be mapped to the vertices. UV data is present only for vertices; when the inner points of a triangle have to be texture-mapped, the GPU interpolates the closest UV values to find the right pixel in the texture to be used. The following image shows you how a 2D texture is mapped to a triangle from a 3D model:

The UV data is stored in the 3D model and...

Left arrow icon Right arrow icon

Key benefits

  • This book will help you master the technique of physically based shading in Unity 5 to add realism to your game quickly through precise recipes
  • From an eminent author, this book offers you the fine technicalities of professional post-processing effects for stunning results
  • This book will help you master Shader programming through easy-to-follow examples to create stunning visual effects that can be used in 3D games and high quality graphics.

Description

Since their introduction to Unity, Shaders have been notoriously difficult to understand and implement in games: complex mathematics have always stood in the way of creating your own Shaders and attaining that level of realism you crave. With Shaders, you can transform your game into a highly polished, refined product with Unity’s post-processing effects. Unity Shaders and Effects Cookbook is the first of its kind to bring you the secrets of creating Shaders for Unity3D—guiding you through the process of understanding vectors, how lighting is constructed with them, and also how textures are used to create complex effects without the heavy math. We’ll start with essential lighting and finishing up by creating stunning screen Effects just like those in high quality 3D and mobile games. You’ll discover techniques including normal mapping, image-based lighting, and how to animate your models inside a Shader. We’ll explore the secrets behind some of the most powerful techniques, such as physically based rendering! With Unity Shaders and Effects Cookbook, what seems like a dark art today will be second nature by tomorrow.

Who is this book for?

Unity Effects and Shader Cookbook is written for developers who want to create their first Shaders in Unity 5 or wish to take their game to a whole new level by adding professional post-processing effects. A solid understanding of Unity is required.

What you will learn

  • Understand physically based rendering to fit the aesthetic of your game
  • Enter the world of post-processing effects to make your game look visually stunning
  • Add life to your materials, complementing Shader programming with interactive scripts
  • Design efficient Shaders for mobile platforms without sacrificing their realism
  • Use state-of-the-art techniques such as volumetric explosions and fur shading
  • Build your knowledge by understanding how Shader models have evolved and how you can create your own
  • Discover what goes into the structure of Shaders and why lighting works the way it does
  • Master the math and algorithms behind the most used lighting models

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 26, 2016
Length: 240 pages
Edition : 1st
Language : English
ISBN-13 : 9781785285240
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Feb 26, 2016
Length: 240 pages
Edition : 1st
Language : English
ISBN-13 : 9781785285240
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
Unity 5.x Game AI Programming Cookbook
€36.99
Unity UI Cookbook
€41.99
Unity 5.x Shaders and Effects Cookbook
€41.99
Total 120.97 Stars icon

Table of Contents

11 Chapters
1. Creating Your First Shader Chevron down icon Chevron up icon
2. Surface Shaders and Texture Mapping Chevron down icon Chevron up icon
3. Understanding Lighting Models Chevron down icon Chevron up icon
4. Physically Based Rendering in Unity 5 Chevron down icon Chevron up icon
5. Vertex Functions Chevron down icon Chevron up icon
6. Fragment Shaders and Grab Passes Chevron down icon Chevron up icon
7. Mobile Shader Adjustment Chevron down icon Chevron up icon
8. Screen Effects with Unity Render Textures Chevron down icon Chevron up icon
9. Gameplay and Screen Effects Chevron down icon Chevron up icon
10. Advanced Shading Techniques Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(9 Ratings)
5 star 66.7%
4 star 0%
3 star 11.1%
2 star 22.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Nicolas Dec 05, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
all is ok!!!
Amazon Verified review Amazon
Cid Jan 16, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I wish I had this book when I first started writing Unity shaders!
Amazon Verified review Amazon
Eldoir May 31, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Perfect reading for a beginner in shaders. Finally, someone explained it simply from scratch ! Alan is a great teacher. Don't hesitate to check on his website for other great tips about shaders, Unity, or other interesting stuff. (I was not paid to write this, I really mean it !)
Amazon Verified review Amazon
Bill Jones Apr 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
First I have to just say I love the cover for some reason, I suppose it fits the bill for shaders and so does the book. Absolutely loved the recipes in this book. However if you want to get something setup to test with this book also worked well for that given the approach the author used to get the test off the ground, you can see the pipelines, texture mapping, and rendering all in one! :)
Amazon Verified review Amazon
Edmon Dantés Oct 16, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Recomendado para personas con un conocimiento moderado de matemáticas con ganas de aprender las bases y metodologías de la programación de Shaders en Unity 5He quedado muy satisfecho con los temas que se tratan y como se explican paso por paso.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.