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

Product feature icon Instant access to your Digital eBook purchase
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

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 : 9781785289187
Vendor :
Unity Technologies
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Product Details

Publication date : Feb 26, 2016
Length: 240 pages
Edition : 1st
Language : English
ISBN-13 : 9781785289187
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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.