Search Unity

Writing a shader variant collection manually

Discussion in 'Shaders' started by thebarryman, Oct 4, 2019.

  1. thebarryman

    thebarryman

    Joined:
    Nov 22, 2012
    Posts:
    130
    Hi,

    I'm working on a tool that assembles a ShaderVariantCollection for all the shader variants required by our project.

    I've noticed that once the variant count for a specific shader/pass starts to get high, ShaderVariantCollection.Add() starts to take FOREVER - multiple seconds just to add a single variant (which I've already verified can be added to the collection through other means).

    This got me wondering if I could just write to the file manually, and after looking at it, it seems it should be pretty simple. Lots of blocks like this:

    - first: {fileID: 211, guid: 0000000000000000f000000000000000, type: 0}
    second:
    variants:
    - keywords: _ALPHABLEND_ON
    passType: 4
    - keywords: _ALPHABLEND_ON _COLORCOLOR_ON
    passType: 4

    I understand almost all of this...other than the "fileID" and "type" fields. I'm assuming guid here is the referenced shader asset GUID. I understand generally what fileID means, but how do I know what value it should be? The results in the generated collection seem kind of arbitrary to me. As for "type," I have no idea.

    Any ideas would be much appreciated and would ***dramatically*** improve the tool!

    Thanks
     
  2. thebarryman

    thebarryman

    Joined:
    Nov 22, 2012
    Posts:
    130
    Seems like type:0 is for built-in shaders and type:3 for custom shaders? Just a guess based on my output data.

    I still have no idea on fileID. I'm seeing unique values under 200 for builtin shaders, but multiple instances of 4800000 (with different GUIDs) for custom shaders, as well as some other values.

    Searching around I found this reference for DLL-defined types. But it doesn't seem to apply here, not only because the Shader type isn't defined in a DLL, but presumably every Shader shares the same type yet the fileIDs are different.

    Also the default explanation doesn't seem to apply since there are neither anywhere close to 4800000 lines to the file, but also because unique GUIDs are sharing the same fileID?
     
  3. thebarryman

    thebarryman

    Joined:
    Nov 22, 2012
    Posts:
    130
    So I was able to hack my way around this with the following method -

    for each shader to add to the collection
    - create a new collection
    - insert a single variant
    - serialize collection to disk
    - read serialized collection as text, extract exported fileID, guid and type
    - delete dummy collection asset

    And then writing the entire collection directly to disk. There's gotta be a better way but for now this works and is waaaaaay faster than adding all the variants directly to the collection.