關(guān)于自定義shader的自發(fā)光烘培

一個(gè)bug

最近正在做交接工作,被問(wèn)到了一個(gè)問(wèn)題,如下圖:

image

左邊這個(gè)球用的是Unity內(nèi)置的Standard shader,開(kāi)啟了紅色的自發(fā)光??梢钥吹?,烘培后,自發(fā)光照亮了地面。

image

右邊這個(gè)球用的是我們自定義的shader,在 Meta Pass 我們同樣設(shè)置了 Emission,并且為了調(diào)試,我們把 Albedo 設(shè)置成了純黑色,并且簡(jiǎn)化了自發(fā)光的計(jì)算,但是烘培的結(jié)果,自發(fā)光并未對(duì)地面產(chǎn)生影響。

image
half4 FragMeta (v2f i) : SV_Target 
{
    float2 mainUV = i.uvTex0;
    half4 mainColor = tex2D(_MainTex, mainUV);
    half3 emissionColor = mainColor.rgb * _EmissionColor.rgb * _EmissionFactor * mainColor.a;
    half3 specularColor = mainColor.a * _SpecularFactor * _SpecularColor;

    UnityMetaInput metaIN;
    UNITY_INITIALIZE_OUTPUT(UnityMetaInput, metaIN);
    metaIN.Albedo = mainColor * 0;
    metaIN.Emission = _EmissionColor.rgb * _EmissionFactor;
    metaIN.SpecularColor = specularColor;
    return UnityMetaFragment(metaIN);
}

原因

搜了一下,發(fā)現(xiàn)也有人遇到了同樣的問(wèn)題,鏈接如下:

My Emissive Material/Shader Does Not Appear In The Lightmap.

文章給出了解決方案:如果是自定義的shader,我們需要特別設(shè)置一下材質(zhì)的GI屬性,代碼如下:

using UnityEngine;
using UnityEditor;

public class LightMapMenu : MonoBehaviour
{
    // The menu item.
    [MenuItem ("MyCustomBake/Bake")]
    
    static void Bake ()
    {
        // Find all objects with the tag <Emissive_to_baked>
        // We have to set the tag “Emissive_to_baked” on each GO to be baked.
        GameObject[] _emissiveObjs = GameObject.FindGameObjectsWithTag("Emissive_to_baked");

        // Then, by each object, set the globalIllumiationFlags to BakedEmissive.
        foreach (GameObject tmpObj in _emissiveObjs)
        {
            Material tmpMaterial = tmpObj.GetComponent<Renderer> ().sharedMaterial;
            tmpMaterial.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
        }

        // Bake the lightmap.
        Lightmapping.Bake ();
    }
}

這里的GI屬性,我們選擇 MaterialGlobalIlluminationFlags.BakedEmissive 即可。

關(guān)于 MaterialGlobalIlluminationFlags.BakedEmissive,官方文檔說(shuō)明如下:

The emissive lighting affects baked Global Illumination. It emits lighting into baked lightmaps and baked lightprobes.

設(shè)置了GI屬性后,我們可以看到,左右2個(gè)球的材質(zhì)都出現(xiàn)在了 Light ExplorerStatic Emissives 面板中:

image

并且右邊的自發(fā)光也參與了烘培:

image

其他

對(duì)比修改前后的材質(zhì)文件,我們發(fā)現(xiàn)主要就是 m_LightmapFlags 的設(shè)置發(fā)生了改變:

image

如果不想寫(xiě)代碼,我們也可以直接修改材質(zhì)文本中的 m_LightmapFlags 的設(shè)值,這里的設(shè)置和 MaterialGlobalIlluminationFlags 枚舉值是一一對(duì)應(yīng)的:

image

個(gè)人主頁(yè)

本文的個(gè)人主頁(yè)鏈接:https://baddogzz.github.io/2020/05/26/Emission-Bake/。

好了,拜拜!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容