Skip to content

Instantly share code, notes, and snippets.

@kyubuns
Last active April 12, 2025 06:03
Show Gist options
  • Save kyubuns/1c76b7f2ff09e4d062237de35089062f to your computer and use it in GitHub Desktop.
Save kyubuns/1c76b7f2ff09e4d062237de35089062f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using Unity.ProjectAuditor.Editor.Core;
using Unity.ProjectAuditor.Editor.Utils;
using UnityEngine;
using UnityEngine.Rendering;
namespace Unity.ProjectAuditor.Editor.Modules
{
class ShaderAnalyzer : ShaderModuleAnalyzer
{
internal const string PAA2000 = nameof(PAA2000);
internal static readonly Descriptor k_SrpBatcherDescriptor = new Descriptor(
PAA2000,
"Shader: Not compatible with SRP batcher",
Areas.CPU,
"The shader is not compatible with SRP Batcher.",
"Consider adding SRP Batcher compatibility to the shader. This will reduce the CPU time Unity requires to prepare and dispatch draw calls for materials that use the same shader variant."
)
{
MessageFormat = "Shader '{0}' is not compatible with SRP Batcher",
DocumentationUrl = "https://docs.unity3d.com/Manual/SRPBatcher.html"
};
public override void Initialize(Action<Descriptor> registerDescriptor)
{
registerDescriptor(k_SrpBatcherDescriptor);
}
public override IEnumerable<ReportItem> Analyze(ShaderAnalysisContext context)
{
if (!IsSrpBatchingEnabled)
{
yield break;
}
if (context.Shader.name.StartsWith("Hidden/"))
{
yield break;
}
var subShaderIndex = ShaderUtilProxy.GetShaderActiveSubshaderIndex(context.Shader);
var errorCode = ShaderUtilProxy.GetSRPBatcherCompatibilityCode(context.Shader, subShaderIndex);
var isSrpBatchingCompatible = errorCode == 0;
if (errorCode == 1) // not initialized
{
var srpCompatibilityCheckMaterial = new Material(context.Shader);
srpCompatibilityCheckMaterial.SetPass(0);
subShaderIndex = ShaderUtilProxy.GetShaderActiveSubshaderIndex(context.Shader);
errorCode = ShaderUtilProxy.GetSRPBatcherCompatibilityCode(context.Shader, subShaderIndex);
isSrpBatchingCompatible = errorCode == 0;
GameObject.DestroyImmediate(srpCompatibilityCheckMaterial);
}
if (!isSrpBatchingCompatible && IsSrpBatchingEnabled)
{
yield return context.CreateIssue(IssueCategory.AssetIssue, k_SrpBatcherDescriptor.Id, context.Shader.name)
.WithLocation(context.AssetPath);
}
}
internal static bool IsSrpBatchingEnabled => GraphicsSettings.defaultRenderPipeline != null &&
GraphicsSettings.useScriptableRenderPipelineBatching;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment