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
$29.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
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
Estimated delivery fee Deliver to Argentina

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Argentina

Standard delivery 10 - 13 business days

$12.95

Premium delivery 3 - 6 business days

$40.95
(Includes tracking information)

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
$19.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
$199.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
$279.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 $ 158.97
Unity 5.x Game AI Programming Cookbook
$48.99
Unity UI Cookbook
$54.99
Unity 5.x Shaders and Effects Cookbook
$54.99
Total $ 158.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela