Skip to content

Instantly share code, notes, and snippets.

@WillzZz
Created September 16, 2014 06:34
Show Gist options
  • Save WillzZz/0d8d6ea94ef569ec50cf to your computer and use it in GitHub Desktop.
Save WillzZz/0d8d6ea94ef569ec50cf to your computer and use it in GitHub Desktop.
Unity3d Animated Material / Facial Animations
/*
* Copyright (c) 2014 William Corwin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*
*/
using UnityEngine;
/// <summary>
/// Animated Materials / Facial Animations using anim curves!
/// Uses an existing skinned mesh renderer and generated material atlas
/// Works in editor to allow for easy real-time content creation
/// Short and sweet 100 lines of code!
///
/// Just three easy steps:
/// 1) Use an existing skinned mesh renderer with an atlased material and add this script
/// 2) Supply the image size, frame size and frame padding
/// 3) Open up your animation curve editor and go to town!
///
/// Gotchas:
/// Only square image, frame, padding sizes are supported.
/// After deliberating with artists, it was not useful given UVs are square.
/// If you find a use case, adding support yourself is easy!
/// Use constant/stepped curves! (Right-click on animation keyframe -> tangents -> constant)
/// Otherwise it will smooth your curves
/// Mecanim transitions will not work!
/// It has no idea how to interpolate between two frame values and you will get crazy values!
/// </summary>
[ExecuteInEditMode]
[RequireComponent (typeof (SkinnedMeshRenderer))]
public class AnimatedMaterial : MonoBehaviour
{
public float frameFloat = 0f; // Only floats may be animated in the curve editor
public Mesh mesh; //The original mesh we are using UVs from
public float imageSize = -1f; //The full image atlas size (px)
public float frameSize = -1f; //Frame size from the image (px)
public float framePadding = -1f;
private SkinnedMeshRenderer meshRenderer;
private Mesh tempMesh;
private int lastFrame = -1;
void Start()
{
if (!hasValidImageInfo)
Debug.LogError("Animated material " + name + " needs image info to work correctly.");
meshRenderer = gameObject.GetComponent<SkinnedMeshRenderer>();
}
void Update ()
{
if (dirty && hasValidImageInfo)
{
setUvs(multVector, offsetVector(frame));
lastFrame = frame;
}
}
private int frame { get { return (int) frameFloat; }}
private bool dirty { get { return lastFrame != frame && frame >= 0; } }
private bool hasValidImageInfo { get
{
return imageSize > 0 && frameSize > 0 && framePadding >= 0;
}}
private int framesPerRow { get
{
return (int) (imageSize/(frameSize + framePadding));
}}
private Vector2 multVector { get
{
return new Vector2(frameSize/imageSize, frameSize/imageSize);
}}
private Vector2 offsetVector(int frame)
{
//Remember that frame is a 0-based index. (and so are row and col)
int row = (int) (frame+1) / framesPerRow;
int col = frame % framesPerRow;
//Pixel values - Top Left origin
float offsetX = ((col + 1)*framePadding) + (col*frameSize);
float offsetY = ((row+1)*framePadding) + (row*frameSize);
//Invert the y because UVs are bottom left origin.
offsetY = imageSize - offsetY - frameSize;
//Offset as a percentage of image size for UV
offsetX = offsetX / imageSize;
offsetY = offsetY / imageSize;
return new Vector2(offsetX, offsetY);
}
/// <summary>
/// Set the UVs on our temp mesh using these mult and offset values
/// </summary>
/// <param name="mult">Multiplier as % of image size (UV)</param>
/// <param name="offset">Offset as % of image size (UV)</param>
private void setUvs(Vector2 mult, Vector2 offset)
{
Vector2[] newUvs = new Vector2[mesh.uv.Length];
int len = mesh.uv.Length;
for (int i = 0; i < len; i++)
{
Vector2 originalMeshUv = mesh.uv[i];
//Multiply and then add the offset!
Vector2 updated = new Vector2((originalMeshUv.x * mult.x) + offset.x, (originalMeshUv.y * mult.y) + offset.y);
newUvs[i] = updated;
}
if (tempMesh == null)
CreateTempMeshIfNotExist();
tempMesh.uv = newUvs;
}
/// <summary>
/// This is called and gated from SetUvs so we aren't throwing errors in Start
/// Every new asset would throw before we set a mesh.
/// </summary>
private void CreateTempMeshIfNotExist()
{
//This will (purposefully) throw if you have not assigned a mesh.
tempMesh = (Mesh)Instantiate(mesh);
tempMesh.name = "tempmesh_" + gameObject.name;
meshRenderer.sharedMesh = tempMesh;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment