include(CMakeParseArguments)

# 查找Python解释器
find_package(Python3 REQUIRED)

# 存储脚本路径
set(SHADER_COMPILE_SCRIPT "${CMAKE_CURRENT_SOURCE_DIR}/tools/compile_shaders.py")

# 在cache目录下创建着色器目录.txt
set(SHADER_PATH_FILE ${CMAKE_CACHEFILE_DIR}/shader_paths.txt)
file(REMOVE ${SHADER_PATH_FILE})
file(WRITE ${SHADER_PATH_FILE} "")

# 添加着色器目录的函数
function(add_mirage_shader_directory path)
    # 将路径写入shader_paths.txt
    file(APPEND ${SHADER_PATH_FILE} "${path}\n")

    # 观察目录文件是否修改, 触发compile_shaders目标重新编译
    file(GLOB_RECURSE SHADER_FILES "${path}/*.slang")

    # 设置依赖关系，当shader文件变化时重新编译
    foreach(SHADER_FILE ${SHADER_FILES})
        set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${SHADER_FILE})
    endforeach()
endfunction()

set(SHADER_COMPILE_ARGS "")
set(SHADER_SHDC "")
if (WIN32)
    list(APPEND SHADER_COMPILE_ARGS "--hlsl")
    set(SHADER_SHDC ${MIRAGE_ROOT_DIR}/tools/win_mirage_shdc.exe)
elseif (APPLE)
    list(APPEND SHADER_COMPILE_ARGS "--metal")
    set(SHADER_SHDC ${MIRAGE_ROOT_DIR}/tools/mac_mirage_shdc)
else()
    list(APPEND SHADER_COMPILE_ARGS "--glsl")
    set(SHADER_SHDC ${MIRAGE_ROOT_DIR}/tools/linux_mirage_shdc)
endif()

# 如果是Debug模式, 添加--debug选项
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
    list(APPEND SHADER_COMPILE_ARGS "--debug")
endif ()

# 添加编译目标, 调用tools/compile_shaders.py
add_custom_target(compile_shaders ALL
        COMMAND ${Python3_EXECUTABLE} ${SHADER_COMPILE_SCRIPT}
        --shdc ${SHADER_SHDC}
        --shader_list ${SHADER_PATH_FILE}
        ${SHADER_COMPILE_ARGS}
        COMMENT "编译着色器"
        VERBATIM
)

# 定义一个宏，将编译着色器作为其他目标的依赖
function(add_shader_dependencies target)
    add_dependencies(${target} compile_shaders)
endfunction()
