コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
52ec2e183b
|
||
|
|
9b1d1d84d2
|
||
|
|
cc5c19cb94
|
||
|
|
d180efc42a
|
||
|
|
9249e3f8d6
|
||
|
|
6e99e0eed9
|
||
|
|
b596a00e25
|
||
|
|
1a14dbfc0f
|
||
|
|
5a65d8943d
|
||
|
|
8ce057ebcd
|
||
|
|
59c275292c
|
||
|
|
9648361fbf
|
||
|
|
bc13f1964a
|
||
|
|
80709bde22
|
||
|
|
de6901f898
|
||
|
|
c627206917
|
||
|
|
0c097c3eb8
|
||
|
|
a77dbbe13f
|
||
|
|
31a052feb1
|
||
|
|
38d280b3e8
|
||
|
|
6f23e211de
|
||
|
|
5579e7a4ed
|
||
|
|
307acd1f22
|
||
|
|
d5a114d14c
|
||
|
|
61f17b4469
|
||
|
|
0600b6a159
|
||
|
|
15fda80d2d
|
||
|
|
1505b0e1c8
|
||
|
|
709ec11404
|
||
|
|
cd9b17e057
|
||
|
|
64eb8c2b22
|
||
|
|
6ea6542267
|
||
|
|
a1150d0ee8
|
||
|
|
ee2a0c9120
|
||
|
|
cd433e5d75
|
検索条件に一致するファイルはありません
@@ -0,0 +1,517 @@
|
|||||||
|
name: リリース
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
tag:
|
||||||
|
description: リリースするタグ
|
||||||
|
required: true
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-release:
|
||||||
|
runs-on: windows-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: ソースコードのチェックアウト
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
env:
|
||||||
|
GIT_CONFIG_COUNT: "2"
|
||||||
|
GIT_CONFIG_KEY_0: url.https://git.routersys.com/routersys/.insteadOf
|
||||||
|
GIT_CONFIG_VALUE_0: https://github.com/routersys/
|
||||||
|
GIT_CONFIG_KEY_1: url.https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.insteadOf
|
||||||
|
GIT_CONFIG_VALUE_1: https://github.com/manju-summoner/YukkuriMovieMaker.Generator
|
||||||
|
with:
|
||||||
|
ref: ${{ inputs.tag || github.ref_name }}
|
||||||
|
submodules: recursive
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: MSBuild のセットアップ
|
||||||
|
uses: microsoft/setup-msbuild@v3
|
||||||
|
|
||||||
|
- name: YMM4 最新リリースの取得と解凍
|
||||||
|
id: ymm4
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$list = 'C:\runner\cache\ymm4\releases.json'
|
||||||
|
New-Item -ItemType Directory -Force -Path (Split-Path $list) | Out-Null
|
||||||
|
if (-not (Test-Path $list) -or (Get-Item $list).Length -lt 1000 -or ((Get-Date) - (Get-Item $list).LastWriteTime).TotalHours -gt 6) {
|
||||||
|
$fetched = $null
|
||||||
|
for ($attempt = 1; $attempt -le 6 -and -not $fetched; $attempt++) {
|
||||||
|
try {
|
||||||
|
$fetched = Invoke-RestMethod -Uri "https://api.github.com/repos/manju-summoner/YukkuriMovieMaker4/releases?per_page=100" `
|
||||||
|
-Headers @{ "User-Agent" = "SpectrumColorShift-CI" } -ErrorAction Stop
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
$message = $_.Exception.Message
|
||||||
|
Write-Host "リリース一覧の取得に失敗しました($attempt 回目): $($message.Substring(0, [Math]::Min(80, $message.Length)))"
|
||||||
|
Start-Sleep -Seconds (5 * $attempt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (@($fetched).Count -gt 0) {
|
||||||
|
$fetched | Select-Object tag_name, published_at, prerelease, draft, assets |
|
||||||
|
ConvertTo-Json -Depth 6 | Set-Content -Path $list -Encoding UTF8
|
||||||
|
}
|
||||||
|
elseif (-not (Test-Path $list)) { throw 'the list of releases could not be fetched' }
|
||||||
|
else { Write-Host '保存済みのリリース一覧を使います' }
|
||||||
|
}
|
||||||
|
$when = [DateTimeOffset](git log -1 --format=%cI)
|
||||||
|
$releases = @(Get-Content -Raw -Path $list | ConvertFrom-Json | Where-Object { -not $_.draft -and -not $_.prerelease })
|
||||||
|
$release = $releases | Where-Object { [DateTimeOffset]$_.published_at -le $when } | Select-Object -First 1
|
||||||
|
if (-not $release) { $release = $releases | Select-Object -Last 1 }
|
||||||
|
Write-Host "最後のコミット $when に合わせた YMM4: $($release.tag_name)"
|
||||||
|
$asset = $release.assets | Where-Object { $_.name -like "*_Lite.zip" } | Select-Object -First 1
|
||||||
|
if (-not $asset) {
|
||||||
|
$asset = $release.assets | Where-Object { $_.name -like "*.zip" } | Select-Object -First 1
|
||||||
|
}
|
||||||
|
Write-Host "ダウンロード対象: $($asset.name)"
|
||||||
|
$cache = Join-Path 'C:\runner\cache\ymm4' $asset.name
|
||||||
|
$extracted = "$cache.extracted"
|
||||||
|
$lock = New-Object System.Threading.Mutex($false, 'Global\ci-ymm4-cache')
|
||||||
|
[void]$lock.WaitOne()
|
||||||
|
try {
|
||||||
|
if (-not (Test-Path "$extracted\.complete")) {
|
||||||
|
New-Item -ItemType Directory -Force -Path (Split-Path $cache) | Out-Null
|
||||||
|
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $cache
|
||||||
|
Remove-Item -Recurse -Force $extracted -ErrorAction SilentlyContinue
|
||||||
|
Expand-Archive -Path $cache -DestinationPath $extracted -Force
|
||||||
|
New-Item -ItemType File -Path "$extracted\.complete" | Out-Null
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Write-Host "保存済みの YMM4 を使います: $extracted"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
$lock.ReleaseMutex()
|
||||||
|
}
|
||||||
|
$ymm4Dir = (Get-ChildItem -Path $extracted -Recurse -Filter "YukkuriMovieMaker.dll" |
|
||||||
|
Select-Object -First 1).DirectoryName
|
||||||
|
Write-Host "YMM4 DLL ディレクトリ: $ymm4Dir"
|
||||||
|
echo "YMM4_DIR=$ymm4Dir\" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: タグ名からバージョンを取得
|
||||||
|
id: version
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$tag = "${{ inputs.tag || github.ref_name }}"
|
||||||
|
echo "TAG=$tag" >> $env:GITHUB_OUTPUT
|
||||||
|
echo "VERSION=$($tag.TrimStart('v'))" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: バージョン記載の照合
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$tag = "${{ steps.version.outputs.TAG }}"
|
||||||
|
$version = "${{ steps.version.outputs.VERSION }}"
|
||||||
|
$problems = @()
|
||||||
|
|
||||||
|
$csprojPath = "SpectrumColorShift/SpectrumColorShift.csproj"
|
||||||
|
$csproj = Get-Content $csprojPath -Raw
|
||||||
|
if (-not $csproj.Contains("<Version>$version</Version>")) {
|
||||||
|
$current = if ($csproj -match '<Version>([^<]*)</Version>') { $Matches[1] } else { "記載なし" }
|
||||||
|
$problems += "$csprojPath の <Version> が $current です。$version にしてください。"
|
||||||
|
}
|
||||||
|
|
||||||
|
$readmePath = ".github/Plugin_Readme.txt"
|
||||||
|
$readme = Get-Content $readmePath -Raw
|
||||||
|
if (-not $readme.Contains(" 色ズレ(スペクトラム) for YMM4 $tag")) {
|
||||||
|
$current = if ($readme -match '(?m)^ 色ズレ(スペクトラム) for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
|
||||||
|
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($problems.Count -eq 0) {
|
||||||
|
Write-Host "バージョン記載は $tag と一致しています"
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($problem in $problems) {
|
||||||
|
Write-Host "::error::$problem"
|
||||||
|
}
|
||||||
|
Write-Host "::error::リリースの対象は $tag が指すコミットです。タグを付けた後で main へ訂正を積んでも、その訂正はリリースに入りません。タグを削除し、記載を直したコミットを積んでから付け直してください。"
|
||||||
|
exit 1
|
||||||
|
|
||||||
|
- name: シェーダーのビルド
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
msbuild SpectrumColorShift.Shader/SpectrumColorShift.Shader.vcxproj `
|
||||||
|
/p:Configuration=Release `
|
||||||
|
/p:Platform=Win32 `
|
||||||
|
/nologo
|
||||||
|
|
||||||
|
- name: プロジェクトのビルド
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$proj = "SpectrumColorShift/SpectrumColorShift.csproj"
|
||||||
|
dotnet build "$proj" `
|
||||||
|
-c Release `
|
||||||
|
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
|
||||||
|
-p:SkipPluginDeploy=true
|
||||||
|
|
||||||
|
- name: パッケージの作成
|
||||||
|
id: package
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$version = "${{ steps.version.outputs.TAG }}"
|
||||||
|
$outDir = "SpectrumColorShift/bin/Release/net10.0-windows10.0.19041.0"
|
||||||
|
$stageRoot = "stage/SpectrumColorShift"
|
||||||
|
$pkgName = "SpectrumColorShift_$version.ymme"
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Path $stageRoot -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||||
|
|
||||||
|
$dll = "$outDir/SpectrumColorShift.dll"
|
||||||
|
if (-not (Test-Path $dll)) {
|
||||||
|
Write-Error "ビルド結果に SpectrumColorShift.dll が見つかりませんでした: $dll"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
Copy-Item $dll "$stageRoot/"
|
||||||
|
|
||||||
|
foreach ($lang in @("ar-sa", "en-us", "es-es", "id-id", "ko-kr", "zh-cn", "zh-tw")) {
|
||||||
|
$src = "$outDir/$lang"
|
||||||
|
if (Test-Path $src) {
|
||||||
|
New-Item -ItemType Directory -Path "$stageRoot/$lang" -Force | Out-Null
|
||||||
|
Copy-Item "$src/*.dll" "$stageRoot/$lang/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
|
||||||
|
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||||
|
|
||||||
|
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
|
||||||
|
if (-not $readme.Contains(" 色ズレ(スペクトラム) for YMM4 $version")) {
|
||||||
|
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
||||||
|
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: 変更履歴の作成
|
||||||
|
id: changelog
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ github.token }}
|
||||||
|
TAG: ${{ steps.version.outputs.TAG }}
|
||||||
|
REPOSITORY: ${{ github.repository }}
|
||||||
|
SERVER_URL: ${{ github.server_url }}
|
||||||
|
PACKAGE: ${{ steps.package.outputs.PKG_NAME }}
|
||||||
|
run: |
|
||||||
|
$tag = $env:TAG
|
||||||
|
$repository = $env:REPOSITORY
|
||||||
|
$server = $env:SERVER_URL
|
||||||
|
$code = [char]0x60
|
||||||
|
$fence = [string]::new($code, 3)
|
||||||
|
$unit = [char]0x1f
|
||||||
|
$record = [char]0x1e
|
||||||
|
|
||||||
|
$previous = ""
|
||||||
|
$candidates = @(git tag --list "v*" --merged $tag --sort=-creatordate | Where-Object { $_ -ne $tag })
|
||||||
|
if ($candidates.Count -gt 0) {
|
||||||
|
$previous = $candidates[0]
|
||||||
|
}
|
||||||
|
Write-Host "直前のタグ: $previous"
|
||||||
|
|
||||||
|
$range = if ($previous) { "$previous..$tag" } else { $tag }
|
||||||
|
$log = (@(git log "--format=%H%x1f%s%x1f%an%x1f%ad%x1f%b%x1e" --date=short $range) -join "`n") -split $record
|
||||||
|
|
||||||
|
$commits = @()
|
||||||
|
foreach ($entry in $log) {
|
||||||
|
if (-not $entry.Trim()) { continue }
|
||||||
|
$fields = $entry.TrimStart("`n") -split $unit
|
||||||
|
if ($fields.Count -lt 5) { continue }
|
||||||
|
$commits += [pscustomobject]@{
|
||||||
|
Sha = $fields[0]
|
||||||
|
Subject = $fields[1]
|
||||||
|
Name = $fields[2]
|
||||||
|
Date = $fields[3]
|
||||||
|
Body = $fields[4]
|
||||||
|
Login = ""
|
||||||
|
Avatar = ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Write-Host "コミット数: $($commits.Count)"
|
||||||
|
|
||||||
|
$categories = [ordered]@{
|
||||||
|
A = @{ Title = "追加"; Symbol = "+"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||||
|
M = @{ Title = "変更"; Symbol = "~"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||||
|
D = @{ Title = "削除"; Symbol = "-"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||||
|
F = @{ Title = "修正"; Symbol = "!"; Items = [System.Collections.Generic.List[pscustomobject]]::new() }
|
||||||
|
}
|
||||||
|
foreach ($commit in $commits) {
|
||||||
|
if (-not $commit.Body) { continue }
|
||||||
|
foreach ($bodyLine in ($commit.Body -split "`n")) {
|
||||||
|
$trimmed = $bodyLine.Trim()
|
||||||
|
if ($trimmed -notmatch '^・(.+)-([AMDF])$') { continue }
|
||||||
|
$categories[$Matches[2]].Items.Add([pscustomobject]@{ Text = $Matches[1]; Sha = $commit.Sha })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$pending = [System.Collections.Generic.HashSet[string]]::new()
|
||||||
|
foreach ($commit in $commits) {
|
||||||
|
[void]$pending.Add($commit.Sha)
|
||||||
|
}
|
||||||
|
|
||||||
|
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
|
||||||
|
|
||||||
|
$accounts = @{}
|
||||||
|
$page = 1
|
||||||
|
while ($pending.Count -gt 0 -and $page -le 20) {
|
||||||
|
$rows = @()
|
||||||
|
try {
|
||||||
|
$rows = @(Invoke-RestMethod -Uri "$server/api/v1/repos/$repository/commits?sha=$tag&limit=50&page=$page&stat=false&verification=false&files=false" -Headers $headers)
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Host "コミットの作者を取得できませんでした: $($_.Exception.Message)"
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if ($rows.Count -eq 0) { break }
|
||||||
|
|
||||||
|
foreach ($row in $rows) {
|
||||||
|
if ($pending.Remove($row.sha)) {
|
||||||
|
$login = ""
|
||||||
|
$avatar = ""
|
||||||
|
if ($row.author) {
|
||||||
|
$login = [string]$row.author.login
|
||||||
|
$avatar = [string]$row.author.avatar_url
|
||||||
|
}
|
||||||
|
$accounts[$row.sha] = @{ Login = $login; Avatar = $avatar }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($rows.Count -lt 50) { break }
|
||||||
|
$page++
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($commit in $commits) {
|
||||||
|
if ($accounts.ContainsKey($commit.Sha)) {
|
||||||
|
$commit.Login = $accounts[$commit.Sha].Login
|
||||||
|
$commit.Avatar = $accounts[$commit.Sha].Avatar
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$emptyTree = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
|
||||||
|
$base = if ($previous) { $previous } else { $emptyTree }
|
||||||
|
$shortstat = (@(git diff --shortstat $base $tag) -join " ")
|
||||||
|
$changedFiles = 0
|
||||||
|
$insertions = 0
|
||||||
|
$deletions = 0
|
||||||
|
if ($shortstat -match "(\d+) file") { $changedFiles = [int]$Matches[1] }
|
||||||
|
if ($shortstat -match "(\d+) insertion") { $insertions = [int]$Matches[1] }
|
||||||
|
if ($shortstat -match "(\d+) deletion") { $deletions = [int]$Matches[1] }
|
||||||
|
$diffStat = @(git diff --stat $base $tag)
|
||||||
|
$tagDate = (git log -1 "--format=%ad" --date=short $tag)
|
||||||
|
|
||||||
|
$contributors = @($commits |
|
||||||
|
Group-Object -Property { if ($_.Login) { $_.Login } else { $_.Name } } |
|
||||||
|
Sort-Object -Property Count -Descending)
|
||||||
|
|
||||||
|
function Get-Icon($avatar, $login, $size) {
|
||||||
|
if (-not $avatar) { return "" }
|
||||||
|
$sized = if ($avatar.Contains("?")) { "$avatar&s=$($size * 2)" } else { "$avatar" + "?s=$($size * 2)" }
|
||||||
|
return "<img src=""$sized"" width=""$size"" height=""$size"" alt=""$login""> "
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Get-Item $env:PACKAGE
|
||||||
|
$size = [math]::Round($package.Length / 1MB, 2)
|
||||||
|
|
||||||
|
$body = [System.Collections.Generic.List[string]]::new()
|
||||||
|
$body.Add("## 概要")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("| 項目 | 内容 |")
|
||||||
|
$body.Add("|---|---|")
|
||||||
|
$body.Add("| タグ | [$tag]($server/$repository/tree/$tag) |")
|
||||||
|
$body.Add("| 公開日 | $tagDate |")
|
||||||
|
if ($previous) {
|
||||||
|
$body.Add("| 直前のリリース | [$previous]($server/$repository/releases/tag/$previous) |")
|
||||||
|
}
|
||||||
|
$body.Add("| コミット数 | $($commits.Count) |")
|
||||||
|
$body.Add("| 貢献者 | $($contributors.Count) 名 |")
|
||||||
|
$body.Add("| 変更されたファイル | $changedFiles |")
|
||||||
|
$body.Add("| 追加された行 | $insertions |")
|
||||||
|
$body.Add("| 削除された行 | $deletions |")
|
||||||
|
|
||||||
|
$hasHighlights = ($categories.Values | ForEach-Object { $_.Items.Count } | Measure-Object -Sum).Sum -gt 0
|
||||||
|
if ($hasHighlights) {
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("## 主な変更")
|
||||||
|
foreach ($key in $categories.Keys) {
|
||||||
|
$category = $categories[$key]
|
||||||
|
if ($category.Items.Count -eq 0) { continue }
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("### [$($category.Symbol)] $($category.Title)")
|
||||||
|
$body.Add("")
|
||||||
|
foreach ($item in $category.Items) {
|
||||||
|
$short = $item.Sha.Substring(0, 7)
|
||||||
|
$body.Add("- $($item.Text) ([$code$short$code]($server/$repository/commit/$($item.Sha)))")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("## ダウンロード")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("| ファイル | サイズ |")
|
||||||
|
$body.Add("|---|---|")
|
||||||
|
$body.Add("| $($package.Name) | $size MB |")
|
||||||
|
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("## 貢献者")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("| 貢献者 | コミット数 |")
|
||||||
|
$body.Add("|---|---|")
|
||||||
|
foreach ($contributor in $contributors) {
|
||||||
|
$first = $contributor.Group[0]
|
||||||
|
if ($first.Login) {
|
||||||
|
$name = (Get-Icon $first.Avatar $first.Login 40) + "[@$($first.Login)]($server/$($first.Login))"
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$name = $first.Name
|
||||||
|
}
|
||||||
|
$body.Add("| $name | $($contributor.Count) |")
|
||||||
|
}
|
||||||
|
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("## 変更履歴")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("| コミット | 内容 | 貢献者 | 日付 |")
|
||||||
|
$body.Add("|---|---|---|---|")
|
||||||
|
$maximumCommits = 300
|
||||||
|
$listed = 0
|
||||||
|
foreach ($commit in $commits) {
|
||||||
|
if ($listed -ge $maximumCommits) { break }
|
||||||
|
$short = $commit.Sha.Substring(0, 7)
|
||||||
|
$subject = $commit.Subject -replace '\|', '\|'
|
||||||
|
if ($commit.Login) {
|
||||||
|
$author = (Get-Icon $commit.Avatar $commit.Login 20) + "[@$($commit.Login)]($server/$($commit.Login))"
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$author = $commit.Name
|
||||||
|
}
|
||||||
|
$body.Add("| [$code$short$code]($server/$repository/commit/$($commit.Sha)) | $subject | $author | $($commit.Date) |")
|
||||||
|
$listed++
|
||||||
|
}
|
||||||
|
if ($commits.Count -gt $maximumCommits) {
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("残り $($commits.Count - $maximumCommits) 件のコミットは省略しました。")
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($diffStat.Count -gt 0) {
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("## 変更されたファイル")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("<details>")
|
||||||
|
$body.Add("<summary>差分の統計</summary>")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add($fence)
|
||||||
|
$maximumStatLines = 200
|
||||||
|
$shown = 0
|
||||||
|
foreach ($line in $diffStat) {
|
||||||
|
if ($shown -ge $maximumStatLines) { break }
|
||||||
|
$body.Add($line)
|
||||||
|
$shown++
|
||||||
|
}
|
||||||
|
if ($diffStat.Count -gt $maximumStatLines) {
|
||||||
|
$body.Add("... 残り $($diffStat.Count - $maximumStatLines) 行は省略しました。")
|
||||||
|
}
|
||||||
|
$body.Add($fence)
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("</details>")
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($previous) {
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("## 全ての変更")
|
||||||
|
$body.Add("")
|
||||||
|
$body.Add("$server/$repository/compare/$previous...$tag")
|
||||||
|
}
|
||||||
|
|
||||||
|
$path = "release-body.md"
|
||||||
|
Set-Content -Path $path -Value ($body -join "`n") -Encoding utf8NoBOM
|
||||||
|
if (-not (Test-Path $path)) {
|
||||||
|
throw "変更履歴を作成できませんでした。"
|
||||||
|
}
|
||||||
|
Write-Host "変更履歴の行数: $($body.Count)"
|
||||||
|
$global:LASTEXITCODE = 0
|
||||||
|
|
||||||
|
- name: Gitea リリースの作成
|
||||||
|
shell: pwsh
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ github.token }}
|
||||||
|
REPOSITORY: ${{ github.repository }}
|
||||||
|
SERVER_URL: ${{ github.server_url }}
|
||||||
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
|
WORKFLOW_NAME: ${{ github.workflow }}
|
||||||
|
JOB_NAME: ${{ github.job }}
|
||||||
|
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_number }}
|
||||||
|
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||||
|
RELEASE_NAME: ${{ steps.version.outputs.TAG }}
|
||||||
|
RELEASE_BODY: ''
|
||||||
|
RELEASE_BODY_PATH: release-body.md
|
||||||
|
RELEASE_DRAFT: false
|
||||||
|
RELEASE_PRERELEASE: false
|
||||||
|
RELEASE_FILES: |
|
||||||
|
${{ steps.package.outputs.PKG_NAME }}
|
||||||
|
run: |
|
||||||
|
$headers = @{ Authorization = "token $env:GITEA_TOKEN" }
|
||||||
|
$api = "$env:SERVER_URL/api/v1/repos/$env:REPOSITORY"
|
||||||
|
$tag = $env:RELEASE_TAG
|
||||||
|
|
||||||
|
$body = $env:RELEASE_BODY
|
||||||
|
if ($env:RELEASE_BODY_PATH -and (Test-Path $env:RELEASE_BODY_PATH)) {
|
||||||
|
$body = Get-Content $env:RELEASE_BODY_PATH -Raw -Encoding utf8
|
||||||
|
}
|
||||||
|
|
||||||
|
$files = @()
|
||||||
|
foreach ($pattern in ($env:RELEASE_FILES -split "[`r`n,]+" | Where-Object { $_.Trim() })) {
|
||||||
|
$found = @(Get-ChildItem -Path $pattern.Trim() -File -ErrorAction SilentlyContinue)
|
||||||
|
if ($found.Count -eq 0) { throw "リリースに付けるファイルが見つかりません: $pattern" }
|
||||||
|
$files += $found
|
||||||
|
}
|
||||||
|
|
||||||
|
$payload = @{
|
||||||
|
tag_name = $tag
|
||||||
|
name = $env:RELEASE_NAME
|
||||||
|
body = [string]$body
|
||||||
|
draft = ($env:RELEASE_DRAFT -eq 'true')
|
||||||
|
prerelease = ($env:RELEASE_PRERELEASE -eq 'true')
|
||||||
|
} | ConvertTo-Json
|
||||||
|
$bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
|
||||||
|
|
||||||
|
$existing = $null
|
||||||
|
try { $existing = Invoke-RestMethod -Uri "$api/releases/tags/$([System.Uri]::EscapeDataString($tag))" -Headers $headers } catch { }
|
||||||
|
if ($existing) {
|
||||||
|
$release = Invoke-RestMethod -Method Patch -Uri "$api/releases/$($existing.id)" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
|
||||||
|
foreach ($asset in @($existing.assets)) {
|
||||||
|
Invoke-RestMethod -Method Delete -Uri "$api/releases/$($existing.id)/assets/$($asset.id)" -Headers $headers | Out-Null
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$release = Invoke-RestMethod -Method Post -Uri "$api/releases" -Headers $headers -ContentType "application/json; charset=utf-8" -Body $bytes
|
||||||
|
}
|
||||||
|
foreach ($file in $files) {
|
||||||
|
$name = [System.Uri]::EscapeDataString($file.Name)
|
||||||
|
Invoke-RestMethod -Method Post -Uri "$api/releases/$($release.id)/assets?name=$name" -Headers $headers -Form @{ attachment = Get-Item $file.FullName } | Out-Null
|
||||||
|
Write-Host "添付しました: $($file.Name)"
|
||||||
|
}
|
||||||
|
Write-Host "リリースを作成しました: $($release.html_url)"
|
||||||
|
|
||||||
|
if ($env:EVENT_NAME -eq 'workflow_dispatch') {
|
||||||
|
try {
|
||||||
|
$sha = (git rev-parse HEAD).Trim()
|
||||||
|
$status = @{
|
||||||
|
state = 'success'
|
||||||
|
context = "$env:WORKFLOW_NAME / $env:JOB_NAME (workflow_dispatch)"
|
||||||
|
description = "Actions がタグ $tag のコミットから作成しました"
|
||||||
|
target_url = $env:RUN_URL
|
||||||
|
} | ConvertTo-Json
|
||||||
|
Invoke-RestMethod -Method Post -Uri "$api/statuses/$sha" -Headers $headers -ContentType "application/json; charset=utf-8" -Body ([System.Text.Encoding]::UTF8.GetBytes($status)) | Out-Null
|
||||||
|
Write-Host "タグのコミット $sha に成功の状態を付けました"
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Warning "タグのコミットに状態を付けられませんでした: $($_.Exception.Message)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+32
-14
@@ -1,5 +1,5 @@
|
|||||||
========================================
|
========================================
|
||||||
色ずれ(スペクトラム) for YMM4 v1.0.1
|
色ズレ(スペクトラム) for YMM4 v1.2.1
|
||||||
========================================
|
========================================
|
||||||
YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長に分け、波長ごとに
|
YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長に分け、波長ごとに
|
||||||
異なる量だけずらして足し合わせ、虹色の縁として描画する
|
異なる量だけずらして足し合わせ、虹色の縁として描画する
|
||||||
@@ -7,12 +7,17 @@ YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長
|
|||||||
等色関数の計算は、Wyman, Sloan and Shirleyの論文「Simple Analytic Approximations
|
等色関数の計算は、Wyman, Sloan and Shirleyの論文「Simple Analytic Approximations
|
||||||
to the CIE XYZ Color Matching Functions」(Journal of Computer Graphics
|
to the CIE XYZ Color Matching Functions」(Journal of Computer Graphics
|
||||||
Techniques、2013年)に基づきます。
|
Techniques、2013年)に基づきます。
|
||||||
|
「物理ベース」をオンにすると、映像の色から光のスペクトルを推定し、波長ごとの
|
||||||
|
光をずらして足し合わせます。スペクトルの推定は、Mallett and Yukselの
|
||||||
|
論文「Spectral Primary Decomposition for Rendering with sRGB
|
||||||
|
Reflectance」(Eurographics Symposium on Rendering、2019年)に基づきます。既定は
|
||||||
|
オフで、オフのときの結果は、従来のバージョンと同じです。
|
||||||
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
履歴フレーム、参照画像、深度情報、学習済みモデルは使用しません。
|
||||||
色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ
|
色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ
|
||||||
絵になります。
|
絵になります。
|
||||||
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに
|
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに
|
||||||
対応しています。
|
対応しています。
|
||||||
エフェクトの種類一覧では「色ずれ(スペクトラム)」として表示されます。
|
エフェクトの種類一覧では「色ズレ(スペクトラム)」として表示されます。
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
■ 動作要件
|
■ 動作要件
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
@@ -29,19 +34,25 @@ Techniques、2013年)に基づきます。
|
|||||||
エフェクトを適用せず入力映像を表示します。
|
エフェクトを適用せず入力映像を表示します。
|
||||||
|
|
||||||
- 処理対象: 色のずれの計算には現在のフレームの色と不透明度だけを使用します。
|
- 処理対象: 色のずれの計算には現在のフレームの色と不透明度だけを使用します。
|
||||||
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。映像の赤、緑、
|
履歴フレーム、外部画像、深度情報、学習済みモデルは使用しません。
|
||||||
青の3つの値から色を作り直すため、映像に含まれない波長の情報を取り出す
|
「物理ベース」がオフのときは、映像の赤、緑、青の3つの値から色を作り直すため、
|
||||||
機能はありません。
|
映像に含まれない波長の情報を取り出す機能はありません。オンのときは、3つの
|
||||||
|
値から滑らかなスペクトルを推定します。同じ色になるスペクトルは無数にあるため、
|
||||||
|
元の映像が実際に出していた光のスペクトルとは違うことがあります。
|
||||||
|
|
||||||
- 等色関数: 論文の式(4)の近似式で求めています。CIEの数表との差は、400nmから
|
- 等色関数: 論文の式(4)の近似式で求めています。CIEの数表との差は、400nmから
|
||||||
700nmまでの範囲で、ピーク値の約1.3%以内です。色を混ぜる計算は、映像の
|
700nmまでの範囲で、ピーク値の約1.3%以内です。「物理ベース」がオフのときの色の
|
||||||
値をそのまま使い、ガンマ補正を取り除く変換はしません。
|
足し合わせは、映像の値をそのまま使い、ガンマ補正を取り除く変換はしません。
|
||||||
|
「物理ベース」がオンのときも、「強さ」で元の映像と混ぜる計算は、光の量ではなく
|
||||||
|
映像の値で行います。
|
||||||
|
|
||||||
- 放射の上限: 各点の動きの上限は、その点の中心からの距離の半分です。
|
- 放射の上限: 各点の動きの上限は、その点の中心からの距離の半分です。
|
||||||
「距離」がそれを超えても、それ以上は動きません。
|
「距離」がそれを超えても、それ以上は動きません。
|
||||||
|
|
||||||
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、
|
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、
|
||||||
ステップ数が多いほど処理は重くなります。
|
ステップ数が多いほど処理は重くなります。「物理ベース」がオンのときは、
|
||||||
|
オフのときより処理が重く、GPUメモリも多く使います。映像とほぼ同じ画素数の
|
||||||
|
画像を、内部で1枚余分に作るためです。
|
||||||
|
|
||||||
- 強さ0%と距離0px: 強さが0%のときと、距離が0pxのときは、映像の色を変更しません。
|
- 強さ0%と距離0px: 強さが0%のときと、距離が0pxのときは、映像の色を変更しません。
|
||||||
|
|
||||||
@@ -52,10 +63,10 @@ Techniques、2013年)に基づきます。
|
|||||||
大きくなります。直線では、「角度」で決めた向きに沿って「距離」を横の長さと縦の
|
大きくなります。直線では、「角度」で決めた向きに沿って「距離」を横の長さと縦の
|
||||||
長さに分け、その長さをそれぞれ切り上げて2pxを足した幅だけ、出力範囲を
|
長さに分け、その長さをそれぞれ切り上げて2pxを足した幅だけ、出力範囲を
|
||||||
広げます。放射と回転では、ずらした色が描かれる範囲を求め、さらに2pxを足した
|
広げます。放射と回転では、ずらした色が描かれる範囲を求め、さらに2pxを足した
|
||||||
範囲まで広げます。どの色も描かれなかった画素は透明です。赤、緑、青の成分ごとに
|
範囲まで広げます。どの色も描かれなかった画素は透明です。「物理ベース」が
|
||||||
映像が覆う割合が違うため、輪郭の外側には一部の成分だけが届いた縁ができ、元の
|
オフのときは、赤、緑、青の成分ごとに映像が覆う割合が違うため、輪郭の外側には
|
||||||
色にその成分が少ないと縁は暗く見えます。不透明度は、成分ごとの割合のうち最も
|
一部の成分だけが届いた縁ができ、元の色にその成分が少ないと縁は暗く見えます。
|
||||||
大きいものです。
|
不透明度は、成分ごとの割合のうち最も大きいものです。
|
||||||
|
|
||||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい
|
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい
|
||||||
正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。
|
正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。
|
||||||
@@ -67,15 +78,22 @@ Techniques、2013年)に基づきます。
|
|||||||
■ 不具合の報告
|
■ 不具合の報告
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
|
||||||
送信します。同意は求めず、常に送信します。
|
送信します。同意は求めません。止める設定もありません。
|
||||||
|
|
||||||
|
送信する数には上限があります。YMM4の1回の起動で送る報告は、
|
||||||
|
YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。
|
||||||
|
例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、
|
||||||
|
送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
|
||||||
|
|
||||||
送信する情報は次のとおりです。
|
送信する情報は次のとおりです。
|
||||||
例外 : 型の完全名、メッセージ、スタックトレース
|
例外 : 型の完全名、メッセージ、スタックトレース
|
||||||
発生位置 : モジュール名、関数名、ファイル名、行番号
|
発生位置 : モジュール名、関数名、ファイル名、行番号、
|
||||||
|
プラグイン自身のコードかどうか
|
||||||
プラグイン : アセンブリ名、バージョン
|
プラグイン : アセンブリ名、バージョン
|
||||||
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
実行環境 : OSの名前とバージョン、.NETのバージョン、
|
||||||
CPUのアーキテクチャ、論理プロセッサ数
|
CPUのアーキテクチャ、論理プロセッサ数
|
||||||
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
|
||||||
|
時刻 : 報告を作った時刻(UTC)
|
||||||
|
|
||||||
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
|
||||||
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
|
||||||
|
|||||||
@@ -69,8 +69,8 @@ jobs:
|
|||||||
|
|
||||||
$readmePath = ".github/Plugin_Readme.txt"
|
$readmePath = ".github/Plugin_Readme.txt"
|
||||||
$readme = Get-Content $readmePath -Raw
|
$readme = Get-Content $readmePath -Raw
|
||||||
if (-not $readme.Contains(" 色ずれ(スペクトラム) for YMM4 $tag")) {
|
if (-not $readme.Contains(" 色ズレ(スペクトラム) for YMM4 $tag")) {
|
||||||
$current = if ($readme -match '(?m)^ 色ずれ(スペクトラム) for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
|
$current = if ($readme -match '(?m)^ 色ズレ(スペクトラム) for YMM4 (\S+)') { $Matches[1] } else { "記載なし" }
|
||||||
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
|
$problems += "$readmePath の見出しが $current です。$tag にしてください。"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,7 +133,7 @@ jobs:
|
|||||||
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||||
|
|
||||||
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
|
$readme = Get-Content "$stageRoot/Readme.txt" -Raw
|
||||||
if (-not $readme.Contains(" 色ずれ(スペクトラム) for YMM4 $version")) {
|
if (-not $readme.Contains(" 色ズレ(スペクトラム) for YMM4 $version")) {
|
||||||
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
|
Write-Error "同梱する Readme.txt の見出しが $version と一致しません"
|
||||||
exit 1
|
exit 1
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-3
@@ -1,9 +1,9 @@
|
|||||||
[submodule "YukkuriMovieMaker.Generator"]
|
[submodule "YukkuriMovieMaker.Generator"]
|
||||||
path = YukkuriMovieMaker.Generator
|
path = YukkuriMovieMaker.Generator
|
||||||
url = https://github.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
url = https://git.routersys.com/manju-summoner/YukkuriMovieMaker.Generator.git
|
||||||
[submodule "YMM4-GitHubUpdateNotifier"]
|
[submodule "YMM4-GitHubUpdateNotifier"]
|
||||||
path = YMM4-GitHubUpdateNotifier
|
path = YMM4-GitHubUpdateNotifier
|
||||||
url = https://github.com/routersys/YMM4-GitHubUpdateNotifier.git
|
url = https://git.routersys.com/routersys/YMM4-GitHubUpdateNotifier.git
|
||||||
[submodule "YMM4-Telemetry"]
|
[submodule "YMM4-Telemetry"]
|
||||||
path = YMM4-Telemetry
|
path = YMM4-Telemetry
|
||||||
url = https://github.com/routersys/YMM4-Telemetry.git
|
url = https://git.routersys.com/routersys/YMM4-Telemetry.git
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# 色ずれ(スペクトラム) for YMM4
|
# 色ズレ(スペクトラム) for YMM4
|
||||||
|
|
||||||
[](#)
|
[](#)
|
||||||
[](#)
|
[](#)
|
||||||
@@ -11,7 +11,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ絵になります。
|
色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ絵になります。
|
||||||
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに対応しています。
|
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに対応しています。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -27,6 +27,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
- [4. 分散](#4-分散)
|
- [4. 分散](#4-分散)
|
||||||
- [5. ステップ数](#5-ステップ数)
|
- [5. ステップ数](#5-ステップ数)
|
||||||
- [6. 強さと映像の外形](#6-強さと映像の外形)
|
- [6. 強さと映像の外形](#6-強さと映像の外形)
|
||||||
|
- [7. 物理ベース](#7-物理ベース)
|
||||||
5. [パラメータ一覧](#パラメータ一覧)
|
5. [パラメータ一覧](#パラメータ一覧)
|
||||||
- [色ずれグループ](#色ずれグループ)
|
- [色ずれグループ](#色ずれグループ)
|
||||||
- [スペクトルグループ](#スペクトルグループ)
|
- [スペクトルグループ](#スペクトルグループ)
|
||||||
@@ -40,12 +41,14 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
|
|
||||||
## 概要
|
## 概要
|
||||||
|
|
||||||
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「色ずれ(スペクトラム)」として表示されます。カテゴリは加工です。
|
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「色ズレ(スペクトラム)」として表示されます。カテゴリは加工です。
|
||||||
|
|
||||||
波長は光の色を表す値で、短いほど青く、長いほど赤くなります。400nmから700nmまでの波長の並びが、スペクトルです。映像の各画素について、波長ごとにずらした位置の色を読み取り、波長ごとの重みを掛けて足し合わせた色で描き直します。ずらす量は波長と「基準波長」との違いから決め、「分散」で回折格子とプリズムのどちらの決め方にするかを選びます。
|
波長は光の色を表す値で、短いほど青く、長いほど赤くなります。400nmから700nmまでの波長の並びが、スペクトルです。映像の各画素について、波長ごとにずらした位置の色を読み取り、波長ごとの重みを掛けて足し合わせた色で描き直します。ずらす量は波長と「基準波長」との違いから決め、「分散」で回折格子とプリズムのどちらの決め方にするかを選びます。
|
||||||
|
|
||||||
重みは、人の目が各波長の光をどんな色として感じるかを表す等色関数から求めます。等色関数の計算は、Wyman, Sloan and Shirleyの論文「Simple Analytic Approximations to the CIE XYZ Color Matching Functions」(Journal of Computer Graphics Techniques、2013年)に基づきます。
|
重みは、人の目が各波長の光をどんな色として感じるかを表す等色関数から求めます。等色関数の計算は、Wyman, Sloan and Shirleyの論文「Simple Analytic Approximations to the CIE XYZ Color Matching Functions」(Journal of Computer Graphics Techniques、2013年)に基づきます。
|
||||||
|
|
||||||
|
「物理ベース」をオンにすると、赤、緑、青の3つの値を別々にずらす代わりに、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせと、画素の間の補間は、映像の値を光の量に変換してから行います。既定はオフで、オフのときの結果は、従来のバージョンと同じです。詳しくは「7. 物理ベース」に書いています。
|
||||||
|
|
||||||
結果は設定と画素の位置だけから決まります。時間値と乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
結果は設定と画素の位置だけから決まります。時間値と乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||||
|
|
||||||
処理はDirect2Dのカスタムピクセルシェーダーが行います。波長ごとの重みとずれの大きさの表はCPUで求め、シェーダーの定数として渡します。CPUへの画素の読み戻しは行いません。
|
処理はDirect2Dのカスタムピクセルシェーダーが行います。波長ごとの重みとずれの大きさの表はCPUで求め、シェーダーの定数として渡します。CPUへの画素の読み戻しは行いません。
|
||||||
@@ -69,7 +72,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
1. [Releases](https://github.com/routersys/YMM4-SpectrumColorShift/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
|
1. [Releases](https://github.com/routersys/YMM4-SpectrumColorShift/releases/latest)ページから最新のプラグインファイル(`.ymme`)をダウンロードしてください。
|
||||||
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
|
2. YMM4が起動していないことを確認し、ダウンロードしたファイルを実行してインストールします。
|
||||||
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
3. YMM4を起動し、タイムライン上のアイテムに映像エフェクトを追加します。
|
||||||
4. 映像エフェクトの種類として「色ずれ(スペクトラム)」を選択してください。
|
4. 映像エフェクトの種類として「色ズレ(スペクトラム)」を選択してください。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -87,7 +90,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
|
|
||||||
次の画像は、左上が元の映像で、ほかの3つは「距離」を24pxにして「方式」だけを変えた例です。ほかの項目は既定値です。
|
次の画像は、左上が元の映像で、ほかの3つは「距離」を24pxにして「方式」だけを変えた例です。ほかの項目は既定値です。
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
放射と回転の中心は、画面の中心ではなく、このエフェクトに入る映像の中心です。「中心X」と「中心Y」で、この中心を動かせます。「角度」は方式が直線のときだけ、「中心X」と「中心Y」は方式が放射か回転のときだけ表示されます。
|
放射と回転の中心は、画面の中心ではなく、このエフェクトに入る映像の中心です。「中心X」と「中心Y」で、この中心を動かせます。「角度」は方式が直線のときだけ、「中心X」と「中心Y」は方式が放射か回転のときだけ表示されます。
|
||||||
|
|
||||||
@@ -118,6 +121,22 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
|
|
||||||
赤、緑、青の各成分には、波長ごとに違う重みを掛けます。そのため、映像の縁や半透明の部分では、成分ごとに映像が覆う割合が違います。不透明度は、そのうち最も大きい割合になります。輪郭の外側には、赤、緑、青の一部だけが届いた縁ができ、元の色にその成分が少ないと、縁は暗く見えます。
|
赤、緑、青の各成分には、波長ごとに違う重みを掛けます。そのため、映像の縁や半透明の部分では、成分ごとに映像が覆う割合が違います。不透明度は、そのうち最も大きい割合になります。輪郭の外側には、赤、緑、青の一部だけが届いた縁ができ、元の色にその成分が少ないと、縁は暗く見えます。
|
||||||
|
|
||||||
|
### 7. 物理ベース
|
||||||
|
|
||||||
|
「物理ベース」は、色の計算の方式を選ぶ項目です。オフでは、赤、緑、青のそれぞれに、波長ごとの重みを掛けて足し合わせます。オンでは、映像の色から推定したスペクトルを使って計算します。
|
||||||
|
|
||||||
|
次の画像は、「距離」を24pxにして、左が「物理ベース」オフ、右がオンの例です。上が直線、下が放射で、ほかの項目は既定値です。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
映像の値は、まずsRGBの変換式で光の量に変換します。以降の計算は、画素の間の補間も含めて、この光の量で行い、最後にsRGBの値へ戻します。
|
||||||
|
|
||||||
|
画素の赤、緑、青の値から、その画素のスペクトルを推定します。推定は、Mallett and Yukselの論文「Spectral Primary Decomposition for Rendering with sRGB Reflectance」(Eurographics Symposium on Rendering、2019年)の方法に基づきます。赤、緑、青のそれぞれに、波長ごとの大きさを表す基底スペクトルがあり、画素の値を掛けて足したものが、その画素のスペクトルです。基底スペクトルは、sRGBの赤、緑、青の色を標準光源D65の下で再現する条件のもとで、波長方向に滑らかになるよう求めたものです。どの波長でも0以上で、3つを足すとどの波長でも1になります。このため、白は、すべての波長で同じ大きさのスペクトルになり、標準光源D65の白と一致します。
|
||||||
|
|
||||||
|
ずらしたあとのスペクトルは、等色関数と標準光源D65の分布を掛けて足し合わせ、赤、緑、青の値に変換します。この変換は、ステップ数ごとに、基底スペクトルの足し合わせが元の赤、緑、青の値と一致するよう揃えます。このため、「距離」が0pxのときと、色が一様な領域では、ステップ数がいくつでも、映像の色は変わりません。負になる成分は0にします。
|
||||||
|
|
||||||
|
オンのときの不透明度は、次の2つのうち大きいほうです。1つは、波長ごとの映像が覆う割合を、人の目の明るさの感じ方で重み付けして足した値です。もう1つは、描かれた赤、緑、青の最大の値です。輪郭の外側には、一部の波長の光だけが届いた縁ができます。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## パラメータ一覧
|
## パラメータ一覧
|
||||||
@@ -137,6 +156,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
|
|
||||||
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
| パラメータ名 | 型 | デフォルト | スライダー表示範囲 | アニメーション | 説明 |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
|
| 物理ベース | 真偽値 | オフ | オフ / オン | 非対応 | オンにすると、映像の色から推定したスペクトルを動かします。 |
|
||||||
| 分散 | 列挙 | 回折格子 | 回折格子 / プリズム | 非対応 | 波長ごとの動きの大きさの決め方です。 |
|
| 分散 | 列挙 | 回折格子 | 回折格子 / プリズム | 非対応 | 波長ごとの動きの大きさの決め方です。 |
|
||||||
| 基準波長 | 数値 | 550nm | 400〜700nm | 対応 | 位置が動かない色の波長です。 |
|
| 基準波長 | 数値 | 550nm | 400〜700nm | 対応 | 位置が動かない色の波長です。 |
|
||||||
| ステップ数 | 整数 | 32 | 8〜64 | 非対応 | 400nmから700nmまでを等間隔に分ける波長の数です。 |
|
| ステップ数 | 整数 | 32 | 8〜64 | 非対応 | 400nmから700nmまでを等間隔に分ける波長の数です。 |
|
||||||
@@ -148,9 +168,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
- AviUtl向けのEXO出力には対応していません。
|
- AviUtl向けのEXO出力には対応していません。
|
||||||
- Direct2Dのカスタムエフェクトを作成できない場合は、エフェクトを適用せず入力映像を表示します。
|
- Direct2Dのカスタムエフェクトを作成できない場合は、エフェクトを適用せず入力映像を表示します。
|
||||||
- 色のずれの計算には現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
|
- 色のずれの計算には現在のフレームの色と不透明度だけを使用します。履歴フレーム、外部画像、学習済みモデルは使用しません。
|
||||||
- 映像の赤、緑、青の3つの値から色を作り直します。映像に含まれない波長の情報を取り出す機能はありません。
|
- 「物理ベース」がオフのときは、映像の赤、緑、青の3つの値から色を作り直します。映像に含まれない波長の情報を取り出す機能はありません。
|
||||||
|
- 「物理ベース」がオンのときは、映像の赤、緑、青の3つの値からスペクトルを推定します。同じ色になるスペクトルは無数にあり、推定したスペクトルは、そのうちの滑らかな1つです。元の映像が実際に出していた光のスペクトルとは違うことがあります。
|
||||||
- 等色関数は、論文の式(4)の近似式で求めています。CIEの数表との差は、400nmから700nmまでの範囲で、ピーク値の約1.3%以内です。
|
- 等色関数は、論文の式(4)の近似式で求めています。CIEの数表との差は、400nmから700nmまでの範囲で、ピーク値の約1.3%以内です。
|
||||||
- 色を混ぜる計算は、映像の値をそのまま使います。ガンマ補正を取り除く変換はしません。
|
- 「物理ベース」がオフのときの色の足し合わせは、映像の値をそのまま使います。ガンマ補正を取り除く変換はしません。「物理ベース」がオンのときも、「強さ」で元の映像と混ぜる計算は、光の量ではなく映像の値で行います。
|
||||||
- 放射では、各点の動きの上限が、その点の中心からの距離の半分です。「距離」がそれを超えても、それ以上は動きません。
|
- 放射では、各点の動きの上限が、その点の中心からの距離の半分です。「距離」がそれを超えても、それ以上は動きません。
|
||||||
- 色をずらした映像は元の外形の外へ出るため、出力範囲は元の映像より大きくなります。
|
- 色をずらした映像は元の外形の外へ出るため、出力範囲は元の映像より大きくなります。
|
||||||
|
|
||||||
@@ -158,10 +179,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
|
|
||||||
## 注意事項
|
## 注意事項
|
||||||
|
|
||||||
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、ステップ数が多いほど処理は重くなります。
|
- 処理負荷: 画素ごとの映像の読み取りは「ステップ数」に応じて増えるため、ステップ数が多いほど処理は重くなります。「物理ベース」がオンのときは、オフのときより処理が重く、GPUメモリも多く使います。映像とほぼ同じ画素数の画像を、内部で1枚余分に作るためです。
|
||||||
- 強さ0%と距離0px: 強さが0%のときと、距離が0pxのときは、映像の色を変更しません。
|
- 強さ0%と距離0px: 強さが0%のときと、距離が0pxのときは、映像の色を変更しません。
|
||||||
- 再現性: 結果は設定と画素の位置だけから決まります。時間値と乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
- 再現性: 結果は設定と画素の位置だけから決まります。時間値と乱数は使いません。同じフレームは何度描いても同じ結果になります。
|
||||||
- 透明部分: 色をずらした映像は元の外形の外へはみ出すため、出力範囲は元の映像より大きくなります。赤、緑、青の成分ごとに映像が覆う割合が違うため、輪郭の外側には一部の成分だけが届いた縁ができ、元の色にその成分が少ないと縁は暗く見えます。不透明度は、成分ごとの割合のうち最も大きいものです。
|
- 透明部分: 色をずらした映像は元の外形の外へはみ出すため、出力範囲は元の映像より大きくなります。「物理ベース」がオフのときは、赤、緑、青の成分ごとに映像が覆う割合が違うため、輪郭の外側には一部の成分だけが届いた縁ができ、元の色にその成分が少ないと縁は暗く見えます。不透明度は、成分ごとの割合のうち最も大きいものです。
|
||||||
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
- 更新通知: エフェクトを最初に生成したときに、YMM4の実行中に一度だけ新しい正式版を確認します。更新情報を取得できない場合は通知せず、そのまま動作します。プレリリースは通知の対象に含めません。
|
||||||
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
- 不具合の自動送信: 想定していない例外が起きたときは、その内容を開発者へ自動で送信します。内容は「不具合の報告」に書いています。
|
||||||
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
- 本プラグインを使用する前に、YMM4のプロジェクトファイルのバックアップを作成することを推奨します。
|
||||||
@@ -170,17 +191,20 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
|
|||||||
|
|
||||||
## 不具合の報告
|
## 不具合の報告
|
||||||
|
|
||||||
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めず、常に送信します。
|
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で送信します。同意は求めません。止める設定もありません。
|
||||||
|
|
||||||
|
送信する数には上限があります。YMM4の1回の起動で送る報告は、YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
|
||||||
|
|
||||||
送信する情報は次のとおりです。
|
送信する情報は次のとおりです。
|
||||||
|
|
||||||
| 種類 | 内容 |
|
| 種類 | 内容 |
|
||||||
|---|---|
|
|---|---|
|
||||||
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
| 例外 | 型の完全名、メッセージ、スタックトレース |
|
||||||
| 発生位置 | モジュール名、関数名、ファイル名、行番号 |
|
| 発生位置 | モジュール名、関数名、ファイル名、行番号、プラグイン自身のコードかどうか |
|
||||||
| プラグイン | アセンブリ名、バージョン |
|
| プラグイン | アセンブリ名、バージョン |
|
||||||
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
| 実行環境 | OSの名前とバージョン、.NETのバージョン、CPUのアーキテクチャ、論理プロセッサ数 |
|
||||||
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
| 識別子 | YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 |
|
||||||
|
| 時刻 | 報告を作った時刻(UTC) |
|
||||||
|
|
||||||
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
メッセージとファイル名は、送信の前に置き換えを通します。置き換えるのは、Windowsのユーザー名、ユーザーフォルダー、AppDataのパス、マシン名、ドメイン名、メールアドレス、IPv4アドレスです。送信元のIPアドレスは受信側へ渡す手前で取り除いています。
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,50 @@ internal static class HarnessCases
|
|||||||
yield return ("reference-650", Create(effect => effect.ReferenceWavelength.Values[0].Value = 650), [0]);
|
yield return ("reference-650", Create(effect => effect.ReferenceWavelength.Values[0].Value = 650), [0]);
|
||||||
yield return ("steps-8", Create(effect => effect.Steps = 8), [0]);
|
yield return ("steps-8", Create(effect => effect.Steps = 8), [0]);
|
||||||
yield return ("strength-50", Create(effect => effect.Strength.Values[0].Value = 50), [0]);
|
yield return ("strength-50", Create(effect => effect.Strength.Values[0].Value = 50), [0]);
|
||||||
|
yield return ("physical", Create(effect => effect.Physical = true), [0]);
|
||||||
|
yield return ("physical-distance-24", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Distance.Values[0].Value = 24;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-distance-100-steps-64", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Distance.Values[0].Value = 100;
|
||||||
|
effect.Steps = 64;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-radial-24", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Mode = ShiftMode.Radial;
|
||||||
|
effect.Distance.Values[0].Value = 24;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-rotational-24", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Mode = ShiftMode.Rotational;
|
||||||
|
effect.Distance.Values[0].Value = 24;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-prism", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Dispersion = DispersionLaw.Prism;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-reference-450", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.ReferenceWavelength.Values[0].Value = 450;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-steps-8", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Steps = 8;
|
||||||
|
}), [0]);
|
||||||
|
yield return ("physical-strength-50", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Strength.Values[0].Value = 50;
|
||||||
|
}), [0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IEnumerable<(string Name, Func<SpectrumColorShiftEffect> Create, Action<SpectrumColorShiftEffect> Change, int Frame)> Transitions()
|
public static IEnumerable<(string Name, Func<SpectrumColorShiftEffect> Create, Action<SpectrumColorShiftEffect> Change, int Frame)> Transitions()
|
||||||
@@ -60,6 +104,9 @@ internal static class HarnessCases
|
|||||||
yield return ("reference-550-to-450", () => Create(), effect => effect.ReferenceWavelength.Values[0].Value = 450, 0);
|
yield return ("reference-550-to-450", () => Create(), effect => effect.ReferenceWavelength.Values[0].Value = 450, 0);
|
||||||
yield return ("steps-32-to-8", () => Create(), effect => effect.Steps = 8, 0);
|
yield return ("steps-32-to-8", () => Create(), effect => effect.Steps = 8, 0);
|
||||||
yield return ("steps-8-to-64", () => Create(effect => effect.Steps = 8), effect => effect.Steps = 64, 0);
|
yield return ("steps-8-to-64", () => Create(effect => effect.Steps = 8), effect => effect.Steps = 64, 0);
|
||||||
|
yield return ("physical-off-to-on", () => Create(), effect => effect.Physical = true, 0);
|
||||||
|
yield return ("physical-on-to-off", () => Create(effect => effect.Physical = true), effect => effect.Physical = false, 0);
|
||||||
|
yield return ("physical-steps-32-to-8", () => Create(effect => effect.Physical = true), effect => effect.Steps = 8, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IEnumerable<(string Name, SpectrumColorShiftEffect Effect)> Benchmarks()
|
public static IEnumerable<(string Name, SpectrumColorShiftEffect Effect)> Benchmarks()
|
||||||
@@ -76,6 +123,30 @@ internal static class HarnessCases
|
|||||||
effect.Mode = ShiftMode.Rotational;
|
effect.Mode = ShiftMode.Rotational;
|
||||||
effect.Distance.Values[0].Value = 24;
|
effect.Distance.Values[0].Value = 24;
|
||||||
}));
|
}));
|
||||||
|
yield return ("physical", Create(effect => effect.Physical = true));
|
||||||
|
yield return ("physical-steps-64", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Steps = 64;
|
||||||
|
}));
|
||||||
|
yield return ("physical-distance-48-steps-64", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Distance.Values[0].Value = 48;
|
||||||
|
effect.Steps = 64;
|
||||||
|
}));
|
||||||
|
yield return ("physical-radial-24", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Mode = ShiftMode.Radial;
|
||||||
|
effect.Distance.Values[0].Value = 24;
|
||||||
|
}));
|
||||||
|
yield return ("physical-rotational-24", Create(effect =>
|
||||||
|
{
|
||||||
|
effect.Physical = true;
|
||||||
|
effect.Mode = ShiftMode.Rotational;
|
||||||
|
effect.Distance.Values[0].Value = 24;
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
static SpectrumColorShiftEffect Create(Action<SpectrumColorShiftEffect>? configure = null)
|
static SpectrumColorShiftEffect Create(Action<SpectrumColorShiftEffect>? configure = null)
|
||||||
|
|||||||
@@ -115,6 +115,69 @@
|
|||||||
0
|
0
|
||||||
],
|
],
|
||||||
"hash": "C2D79B67A9585C913BFBB67E70038229CC7D9596CAB67FFD366FAA0C7BCF5F2D"
|
"hash": "C2D79B67A9585C913BFBB67E70038229CC7D9596CAB67FFD366FAA0C7BCF5F2D"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "BFCB9E307B4EC0823A9DA134EC63CC8989F1B978EE89B8CED3576DBB972C2F98"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-distance-24",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "C3EFCE6A5A4E9A737926D359AF302FFA10D15ED56E58EA8EB040ADAEF6F083D7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-distance-100-steps-64",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "514B1C1FF62D4C5F28AFC9D4158B5182B7A55E7CDBFC1D02531D86E22C0019AC"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-radial-24",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "09C9FFD797F751E21CDB8A1AC4487193D0C2701FDD404F91B3AD452D1D5B61C1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-rotational-24",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "7A86209757529922BB33B2C5060E80A7DEC7D853F1F45536FEEB09C53D15A2D2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-prism",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "7CFAFE05228475887147E95781919A4A961C4C0D467513824B517327A05BB249"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-reference-450",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "B792437ECF90657E41E3164FAB3A1967548938A7F38747A4B75B177FF7F44ED2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-steps-8",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "160C24673BB43AE035287C22DB8366D0DB89D9D27CA65F9473E3DF3469BB747C"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "physical-strength-50",
|
||||||
|
"frames": [
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"hash": "C562CBC11A831C10C1ACEFF8742C89FD9695629B753DC31EECC6541042242E8D"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
#ifndef ShaderMode
|
||||||
|
#error ShaderMode must be defined by the build.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "Srgb.hlsli"
|
||||||
|
|
||||||
|
Texture2D LightTexture : register(t1);
|
||||||
|
SamplerState LightSampler : register(s1);
|
||||||
|
|
||||||
|
static const int TableSize = 128;
|
||||||
|
static const int FilterTableSize = 132;
|
||||||
|
static const int ModeRadial = 2;
|
||||||
|
static const int ModeRotational = 4;
|
||||||
|
static const int CompiledMode = ShaderMode;
|
||||||
|
static const float MaxRadialShift = 0.5;
|
||||||
|
static const float InteriorGuard = 0.51;
|
||||||
|
|
||||||
|
cbuffer Constants : register(b0)
|
||||||
|
{
|
||||||
|
float4 inputBounds : packoffset(c0);
|
||||||
|
float2 direction : packoffset(c1.x);
|
||||||
|
float2 center : packoffset(c1.z);
|
||||||
|
float shiftDistance : packoffset(c2.x);
|
||||||
|
float radius : packoffset(c2.y);
|
||||||
|
float strength : packoffset(c2.z);
|
||||||
|
int steps : packoffset(c2.w);
|
||||||
|
float spreadScale : packoffset(c3.x);
|
||||||
|
float filterOrigin : packoffset(c3.y);
|
||||||
|
int filterVertical : packoffset(c3.z);
|
||||||
|
float4 samples[TableSize] : packoffset(c4);
|
||||||
|
float4 taps[FilterTableSize] : packoffset(c132);
|
||||||
|
};
|
||||||
|
|
||||||
|
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
|
||||||
|
{
|
||||||
|
float shift = coefficient * shiftDistance;
|
||||||
|
|
||||||
|
if (CompiledMode == ModeRadial)
|
||||||
|
{
|
||||||
|
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
|
||||||
|
return center + offset * scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (CompiledMode == ModeRotational)
|
||||||
|
{
|
||||||
|
float sine;
|
||||||
|
float cosine;
|
||||||
|
sincos(shift / radius, sine, cosine);
|
||||||
|
return center + float2(cosine * offset.x + sine * offset.y, cosine * offset.y - sine * offset.x);
|
||||||
|
}
|
||||||
|
|
||||||
|
return scenePosition - shift * direction;
|
||||||
|
}
|
||||||
|
|
||||||
|
float2 Spread(float2 offset)
|
||||||
|
{
|
||||||
|
if (CompiledMode == ModeRadial)
|
||||||
|
return abs(offset) * spreadScale;
|
||||||
|
|
||||||
|
if (CompiledMode == ModeRotational)
|
||||||
|
return length(offset) * spreadScale;
|
||||||
|
|
||||||
|
return abs(shiftDistance) * abs(direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 SampleCovered(float2 uv, float2 pixelStep, float2 scenePosition, float2 target)
|
||||||
|
{
|
||||||
|
float2 minimum = inputBounds.xy + 0.5;
|
||||||
|
float2 maximum = inputBounds.zw - 0.5;
|
||||||
|
float2 clamped = clamp(target, minimum, maximum);
|
||||||
|
float4 color = LightTexture.SampleLevel(LightSampler, uv + (clamped - scenePosition) * pixelStep, 0);
|
||||||
|
float2 coverage = saturate(min(target - inputBounds.xy, inputBounds.zw - target) + 0.5);
|
||||||
|
return color * (coverage.x * coverage.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Accumulate(float4 gain, float3 basis, float4 shifted, inout float3 color, inout float alpha)
|
||||||
|
{
|
||||||
|
color += gain.rgb * dot(basis, shifted.rgb);
|
||||||
|
alpha += gain.w * shifted.a;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 Resolve(float3 color, float alpha)
|
||||||
|
{
|
||||||
|
float3 positive = max(color, 0.0);
|
||||||
|
float resolved = saturate(max(alpha, max(positive.r, max(positive.g, positive.b))));
|
||||||
|
return EncodePremultiplied(float4(positive, resolved));
|
||||||
|
}
|
||||||
|
|
||||||
|
void AccumulateCovered(int index, float2 uv, float2 pixelStep, float2 scenePosition, float2 offset, inout float3 color, inout float alpha)
|
||||||
|
{
|
||||||
|
float4 gain = samples[index * 2];
|
||||||
|
float4 basis = samples[index * 2 + 1];
|
||||||
|
Accumulate(gain, basis.rgb, SampleCovered(uv, pixelStep, scenePosition, SamplePosition(scenePosition, offset, basis.w)), color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 GatherCovered(float2 uv, float2 pixelStep, float2 scenePosition)
|
||||||
|
{
|
||||||
|
float2 offset = scenePosition - center;
|
||||||
|
float3 color = 0.0;
|
||||||
|
float alpha = 0.0;
|
||||||
|
|
||||||
|
[loop]
|
||||||
|
for (int index = 0; index < steps; index++)
|
||||||
|
AccumulateCovered(index, uv, pixelStep, scenePosition, offset, color, alpha);
|
||||||
|
|
||||||
|
return Resolve(color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition);
|
||||||
|
|
||||||
|
float4 main(
|
||||||
|
float4 position : SV_POSITION,
|
||||||
|
float4 scenePosition : SCENE_POSITION,
|
||||||
|
float4 uv0 : TEXCOORD0,
|
||||||
|
float4 uv1 : TEXCOORD1
|
||||||
|
) : SV_TARGET
|
||||||
|
{
|
||||||
|
if (shiftDistance == 0.0 || strength <= 0.0)
|
||||||
|
return EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy));
|
||||||
|
|
||||||
|
float2 margin = Spread(scenePosition.xy - center) + InteriorGuard;
|
||||||
|
bool inside = all(scenePosition.xy >= inputBounds.xy + margin) && all(scenePosition.xy <= inputBounds.zw - margin);
|
||||||
|
|
||||||
|
float4 result;
|
||||||
|
[branch]
|
||||||
|
if (inside)
|
||||||
|
result = GatherInside(uv1.xy, uv1.zw, scenePosition.xy);
|
||||||
|
else
|
||||||
|
result = GatherCovered(uv1.xy, uv1.zw, scenePosition.xy);
|
||||||
|
|
||||||
|
if (strength >= 1.0)
|
||||||
|
return result;
|
||||||
|
|
||||||
|
return lerp(EncodePremultiplied(SampleCovered(uv1.xy, uv1.zw, scenePosition.xy, scenePosition.xy)), result, strength);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<Project>
|
||||||
|
<ItemGroup>
|
||||||
|
<StepCount Include="8;12;16;20;24;28;32;36;40;44;48;52;56;60;64" />
|
||||||
|
<TapCount Include="4;8;12;16;20;24;28;32;36;40;44" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -144,13 +144,64 @@
|
|||||||
</FxCompile>
|
</FxCompile>
|
||||||
</ItemDefinitionGroup>
|
</ItemDefinitionGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<FxCompile Include="SpectrumColorShift.hlsl">
|
<FxCompile Include="SpectrumColorShiftLinearize.hlsl">
|
||||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
|
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
|
||||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
|
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
|
||||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
|
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
|
||||||
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
|
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
|
||||||
</FxCompile>
|
</FxCompile>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="SpectrumColorShift.hlsl" />
|
||||||
|
<None Include="SpectrumColorShiftPhysical.hlsl" />
|
||||||
|
<None Include="SpectrumColorShiftPhysicalFilter.hlsl" />
|
||||||
|
<None Include="Physical.hlsli" />
|
||||||
|
<None Include="Srgb.hlsli" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Import Project="ShaderVariants.props" />
|
||||||
|
<Target Name="AddVariantShaders" BeforeTargets="FxCompile">
|
||||||
|
<ItemGroup>
|
||||||
|
<StaleShader Include="$(OutDir)SpectrumColorShift*.cso" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Delete Files="@(StaleShader)" />
|
||||||
|
<ItemGroup>
|
||||||
|
<FxCompile Include="SpectrumColorShift.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=1</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftLinear%(StepCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
<FxCompile Include="SpectrumColorShift.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=2</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftRadial%(StepCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
<FxCompile Include="SpectrumColorShift.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=4</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftRotational%(StepCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=1</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalLinear%(StepCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=2</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalRadial%(StepCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
<FxCompile Include="SpectrumColorShiftPhysical.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=4</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalRotational%(StepCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
<FxCompile Include="SpectrumColorShiftPhysicalFilter.hlsl">
|
||||||
|
<ShaderType>Pixel</ShaderType>
|
||||||
|
<PreprocessorDefinitions>TapCount=%(TapCount.Identity);ShaderMode=1</PreprocessorDefinitions>
|
||||||
|
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysicalFilterLinear%(TapCount.Identity).cso</ObjectFileOutput>
|
||||||
|
</FxCompile>
|
||||||
|
</ItemGroup>
|
||||||
|
</Target>
|
||||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||||
<ImportGroup Label="ExtensionTargets">
|
<ImportGroup Label="ExtensionTargets">
|
||||||
</ImportGroup>
|
</ImportGroup>
|
||||||
|
|||||||
@@ -15,8 +15,25 @@
|
|||||||
</Filter>
|
</Filter>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<FxCompile Include="SpectrumColorShift.hlsl">
|
<FxCompile Include="SpectrumColorShiftLinearize.hlsl">
|
||||||
<Filter>ソース ファイル</Filter>
|
<Filter>ソース ファイル</Filter>
|
||||||
</FxCompile>
|
</FxCompile>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<None Include="SpectrumColorShift.hlsl">
|
||||||
|
<Filter>ソース ファイル</Filter>
|
||||||
|
</None>
|
||||||
|
<None Include="SpectrumColorShiftPhysical.hlsl">
|
||||||
|
<Filter>ソース ファイル</Filter>
|
||||||
|
</None>
|
||||||
|
<None Include="SpectrumColorShiftPhysicalFilter.hlsl">
|
||||||
|
<Filter>ソース ファイル</Filter>
|
||||||
|
</None>
|
||||||
|
<None Include="Physical.hlsli">
|
||||||
|
<Filter>ヘッダー ファイル</Filter>
|
||||||
|
</None>
|
||||||
|
<None Include="Srgb.hlsli">
|
||||||
|
<Filter>ヘッダー ファイル</Filter>
|
||||||
|
</None>
|
||||||
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,9 +1,18 @@
|
|||||||
|
#ifndef StepCount
|
||||||
|
#error StepCount must be defined by the build.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef ShaderMode
|
||||||
|
#error ShaderMode must be defined by the build.
|
||||||
|
#endif
|
||||||
|
|
||||||
Texture2D SourceTexture : register(t0);
|
Texture2D SourceTexture : register(t0);
|
||||||
SamplerState SourceSampler : register(s0);
|
SamplerState SourceSampler : register(s0);
|
||||||
|
|
||||||
static const int MaxSteps = 64;
|
static const int MaxSteps = 64;
|
||||||
static const int ModeRadial = 2;
|
static const int ModeRadial = 2;
|
||||||
static const int ModeRotational = 4;
|
static const int ModeRotational = 4;
|
||||||
|
static const int CompiledMode = ShaderMode;
|
||||||
static const float MaxRadialShift = 0.5;
|
static const float MaxRadialShift = 0.5;
|
||||||
static const float InteriorGuard = 0.51;
|
static const float InteriorGuard = 0.51;
|
||||||
|
|
||||||
@@ -15,9 +24,8 @@ cbuffer Constants : register(b0)
|
|||||||
float shiftDistance : packoffset(c2.x);
|
float shiftDistance : packoffset(c2.x);
|
||||||
float radius : packoffset(c2.y);
|
float radius : packoffset(c2.y);
|
||||||
float strength : packoffset(c2.z);
|
float strength : packoffset(c2.z);
|
||||||
int mode : packoffset(c2.w);
|
int steps : packoffset(c2.w);
|
||||||
int steps : packoffset(c3.x);
|
float spreadScale : packoffset(c3.x);
|
||||||
float spreadScale : packoffset(c3.y);
|
|
||||||
float4 samples[MaxSteps] : packoffset(c4);
|
float4 samples[MaxSteps] : packoffset(c4);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -25,13 +33,13 @@ float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
|
|||||||
{
|
{
|
||||||
float shift = coefficient * shiftDistance;
|
float shift = coefficient * shiftDistance;
|
||||||
|
|
||||||
if (mode == ModeRadial)
|
if (CompiledMode == ModeRadial)
|
||||||
{
|
{
|
||||||
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
|
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
|
||||||
return center + offset * scale;
|
return center + offset * scale;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mode == ModeRotational)
|
if (CompiledMode == ModeRotational)
|
||||||
{
|
{
|
||||||
float sine;
|
float sine;
|
||||||
float cosine;
|
float cosine;
|
||||||
@@ -44,10 +52,10 @@ float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
|
|||||||
|
|
||||||
float2 Spread(float2 offset)
|
float2 Spread(float2 offset)
|
||||||
{
|
{
|
||||||
if (mode == ModeRadial)
|
if (CompiledMode == ModeRadial)
|
||||||
return abs(offset) * spreadScale;
|
return abs(offset) * spreadScale;
|
||||||
|
|
||||||
if (mode == ModeRotational)
|
if (CompiledMode == ModeRotational)
|
||||||
return length(offset) * spreadScale;
|
return length(offset) * spreadScale;
|
||||||
|
|
||||||
return abs(shiftDistance) * abs(direction);
|
return abs(shiftDistance) * abs(direction);
|
||||||
@@ -69,6 +77,29 @@ void Accumulate(float4 entry, float4 shifted, inout float3 color, inout float3 c
|
|||||||
coverage += entry.rgb * shifted.a;
|
coverage += entry.rgb * shifted.a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float3 coverage)
|
||||||
|
{
|
||||||
|
float4 entry = samples[index];
|
||||||
|
float scale = clamp(entry.w * rate, -MaxRadialShift, MaxRadialShift);
|
||||||
|
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, coverage);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float3 coverage)
|
||||||
|
{
|
||||||
|
float4 entry = samples[index];
|
||||||
|
float sine;
|
||||||
|
float cosine;
|
||||||
|
sincos(entry.w * rate, sine, cosine);
|
||||||
|
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
|
||||||
|
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, coverage);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float3 coverage)
|
||||||
|
{
|
||||||
|
float4 entry = samples[index];
|
||||||
|
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - entry.w * stride, 0), color, coverage);
|
||||||
|
}
|
||||||
|
|
||||||
float4 Resolve(float3 color, float3 coverage)
|
float4 Resolve(float3 color, float3 coverage)
|
||||||
{
|
{
|
||||||
float alpha = max(coverage.r, max(coverage.g, coverage.b));
|
float alpha = max(coverage.r, max(coverage.g, coverage.b));
|
||||||
@@ -97,44 +128,30 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
|
|||||||
float3 color = 0.0;
|
float3 color = 0.0;
|
||||||
float3 coverage = 0.0;
|
float3 coverage = 0.0;
|
||||||
|
|
||||||
if (mode == ModeRadial)
|
if (CompiledMode == ModeRadial)
|
||||||
{
|
{
|
||||||
float2 offsetStep = offset * pixelStep;
|
float2 offsetStep = offset * pixelStep;
|
||||||
float rate = shiftDistance / radius;
|
float rate = shiftDistance / radius;
|
||||||
|
|
||||||
[loop]
|
[unroll]
|
||||||
for (int index = 0; index < steps; index++)
|
for (int index = 0; index < StepCount; index++)
|
||||||
{
|
AccumulateRadial(index, uv, offsetStep, rate, color, coverage);
|
||||||
float4 entry = samples[index];
|
|
||||||
float scale = clamp(entry.w * rate, -MaxRadialShift, MaxRadialShift);
|
|
||||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - offsetStep * scale, 0), color, coverage);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else if (mode == ModeRotational)
|
else if (CompiledMode == ModeRotational)
|
||||||
{
|
{
|
||||||
float rate = shiftDistance / radius;
|
float rate = shiftDistance / radius;
|
||||||
|
|
||||||
[loop]
|
[unroll]
|
||||||
for (int index = 0; index < steps; index++)
|
for (int index = 0; index < StepCount; index++)
|
||||||
{
|
AccumulateRotational(index, uv, offset, pixelStep, rate, color, coverage);
|
||||||
float4 entry = samples[index];
|
|
||||||
float sine;
|
|
||||||
float cosine;
|
|
||||||
sincos(entry.w * rate, sine, cosine);
|
|
||||||
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
|
|
||||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv + delta * pixelStep, 0), color, coverage);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
float2 stride = shiftDistance * direction * pixelStep;
|
float2 stride = shiftDistance * direction * pixelStep;
|
||||||
|
|
||||||
[loop]
|
[unroll]
|
||||||
for (int index = 0; index < steps; index++)
|
for (int index = 0; index < StepCount; index++)
|
||||||
{
|
AccumulateLinear(index, uv, stride, color, coverage);
|
||||||
float4 entry = samples[index];
|
|
||||||
Accumulate(entry, SourceTexture.SampleLevel(SourceSampler, uv - entry.w * stride, 0), color, coverage);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return Resolve(color, coverage);
|
return Resolve(color, coverage);
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
#include "Srgb.hlsli"
|
||||||
|
|
||||||
|
Texture2D SourceTexture : register(t0);
|
||||||
|
SamplerState SourceSampler : register(s0);
|
||||||
|
|
||||||
|
float4 main(
|
||||||
|
float4 position : SV_POSITION,
|
||||||
|
float4 scenePosition : SCENE_POSITION,
|
||||||
|
float4 uv0 : TEXCOORD0
|
||||||
|
) : SV_TARGET
|
||||||
|
{
|
||||||
|
return DecodePremultiplied(SourceTexture.SampleLevel(SourceSampler, uv0.xy, 0));
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
#ifndef StepCount
|
||||||
|
#error StepCount must be defined by the build.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "Physical.hlsli"
|
||||||
|
|
||||||
|
void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float alpha)
|
||||||
|
{
|
||||||
|
float4 gain = samples[index * 2];
|
||||||
|
float4 basis = samples[index * 2 + 1];
|
||||||
|
float scale = clamp(basis.w * rate, -MaxRadialShift, MaxRadialShift);
|
||||||
|
Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, uv - offsetStep * scale, 0), color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float alpha)
|
||||||
|
{
|
||||||
|
float4 gain = samples[index * 2];
|
||||||
|
float4 basis = samples[index * 2 + 1];
|
||||||
|
float sine;
|
||||||
|
float cosine;
|
||||||
|
sincos(basis.w * rate, sine, cosine);
|
||||||
|
float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
|
||||||
|
Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, uv + delta * pixelStep, 0), color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float alpha)
|
||||||
|
{
|
||||||
|
float4 gain = samples[index * 2];
|
||||||
|
float4 basis = samples[index * 2 + 1];
|
||||||
|
Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, uv - basis.w * stride, 0), color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
|
||||||
|
{
|
||||||
|
float2 offset = scenePosition - center;
|
||||||
|
float3 color = 0.0;
|
||||||
|
float alpha = 0.0;
|
||||||
|
|
||||||
|
if (CompiledMode == ModeRadial)
|
||||||
|
{
|
||||||
|
float2 offsetStep = offset * pixelStep;
|
||||||
|
float rate = shiftDistance / radius;
|
||||||
|
|
||||||
|
[unroll]
|
||||||
|
for (int index = 0; index < StepCount; index++)
|
||||||
|
AccumulateRadial(index, uv, offsetStep, rate, color, alpha);
|
||||||
|
}
|
||||||
|
else if (CompiledMode == ModeRotational)
|
||||||
|
{
|
||||||
|
float rate = shiftDistance / radius;
|
||||||
|
|
||||||
|
[unroll]
|
||||||
|
for (int index = 0; index < StepCount; index++)
|
||||||
|
AccumulateRotational(index, uv, offset, pixelStep, rate, color, alpha);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
float2 stride = shiftDistance * direction * pixelStep;
|
||||||
|
|
||||||
|
[unroll]
|
||||||
|
for (int index = 0; index < StepCount; index++)
|
||||||
|
AccumulateLinear(index, uv, stride, color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Resolve(color, alpha);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#ifndef TapCount
|
||||||
|
#error TapCount must be defined by the build.
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include "Physical.hlsli"
|
||||||
|
|
||||||
|
void AccumulateTap(int tap, float2 position, inout float3 color, inout float alpha)
|
||||||
|
{
|
||||||
|
float4 shifted = LightTexture.SampleLevel(LightSampler, position, 0);
|
||||||
|
float4 red = taps[tap * 3];
|
||||||
|
float4 green = taps[tap * 3 + 1];
|
||||||
|
float4 blue = taps[tap * 3 + 2];
|
||||||
|
color += float3(dot(red.rgb, shifted.rgb), dot(green.rgb, shifted.rgb), dot(blue.rgb, shifted.rgb));
|
||||||
|
alpha += red.w * shifted.a;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
|
||||||
|
{
|
||||||
|
float2 tapStep = filterVertical != 0 ? float2(0.0, pixelStep.y) : float2(pixelStep.x, 0.0);
|
||||||
|
float2 first = uv + filterOrigin * tapStep;
|
||||||
|
float3 color = 0.0;
|
||||||
|
float alpha = 0.0;
|
||||||
|
|
||||||
|
[unroll]
|
||||||
|
for (int tap = 0; tap < TapCount; tap++)
|
||||||
|
AccumulateTap(tap, first + tap * tapStep, color, alpha);
|
||||||
|
|
||||||
|
return Resolve(color, alpha);
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
static const float SrgbDecodeThreshold = 0.04045;
|
||||||
|
static const float SrgbEncodeThreshold = 0.0031308;
|
||||||
|
static const float SrgbLowSlope = 12.92;
|
||||||
|
static const float SrgbOffset = 0.055;
|
||||||
|
static const float SrgbScale = 1.055;
|
||||||
|
static const float SrgbExponent = 2.4;
|
||||||
|
|
||||||
|
float3 SrgbDecode(float3 encoded)
|
||||||
|
{
|
||||||
|
float3 low = encoded / SrgbLowSlope;
|
||||||
|
float3 high = pow((encoded + SrgbOffset) / SrgbScale, SrgbExponent);
|
||||||
|
return encoded <= SrgbDecodeThreshold ? low : high;
|
||||||
|
}
|
||||||
|
|
||||||
|
float3 SrgbEncode(float3 linearColor)
|
||||||
|
{
|
||||||
|
float3 low = linearColor * SrgbLowSlope;
|
||||||
|
float3 high = SrgbScale * pow(linearColor, 1.0 / SrgbExponent) - SrgbOffset;
|
||||||
|
return linearColor <= SrgbEncodeThreshold ? low : high;
|
||||||
|
}
|
||||||
|
|
||||||
|
float3 Unpremultiply(float4 premultiplied)
|
||||||
|
{
|
||||||
|
return premultiplied.a > 0.0 ? saturate(premultiplied.rgb / premultiplied.a) : 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 DecodePremultiplied(float4 encoded)
|
||||||
|
{
|
||||||
|
return float4(SrgbDecode(Unpremultiply(encoded)) * encoded.a, encoded.a);
|
||||||
|
}
|
||||||
|
|
||||||
|
float4 EncodePremultiplied(float4 linearColor)
|
||||||
|
{
|
||||||
|
return float4(SrgbEncode(Unpremultiply(linearColor)) * linearColor.a, linearColor.a);
|
||||||
|
}
|
||||||
@@ -46,6 +46,7 @@ public sealed class AllocationTests
|
|||||||
impl.Dispersion = step & 1;
|
impl.Dispersion = step & 1;
|
||||||
impl.ReferenceWavelength = 400f + step % 300;
|
impl.ReferenceWavelength = 400f + step % 300;
|
||||||
impl.Steps = Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1);
|
impl.Steps = Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1);
|
||||||
|
impl.Physical = step & 1;
|
||||||
});
|
});
|
||||||
|
|
||||||
Assert.Equal(0, allocated);
|
Assert.Equal(0, allocated);
|
||||||
@@ -67,4 +68,40 @@ public sealed class AllocationTests
|
|||||||
|
|
||||||
Assert.Equal(0, allocated);
|
Assert.Equal(0, allocated);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RefreshingTheFilterAllocatesNothing()
|
||||||
|
{
|
||||||
|
var impl = new EffectImpl { Physical = 1 };
|
||||||
|
var step = 0;
|
||||||
|
|
||||||
|
var allocated = Allocation.Of(() =>
|
||||||
|
{
|
||||||
|
step++;
|
||||||
|
impl.Angle = step % 4 * 90f;
|
||||||
|
impl.Distance = step % 40 - 20;
|
||||||
|
impl.Steps = Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1);
|
||||||
|
impl.Dispersion = step & 1;
|
||||||
|
_ = impl.FilterTaps;
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.Equal(0, allocated);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(DispersionLaw.Grating)]
|
||||||
|
[InlineData(DispersionLaw.Prism)]
|
||||||
|
public void FillingTheSpectralTableAllocatesNothing(DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||||
|
var step = 0;
|
||||||
|
|
||||||
|
var allocated = Allocation.Of(() =>
|
||||||
|
{
|
||||||
|
step++;
|
||||||
|
Spectrum.FillSpectral(table, Spectrum.MinSteps + step % (Spectrum.MaxSteps - Spectrum.MinSteps + 1), 400f + step % 300, law);
|
||||||
|
});
|
||||||
|
|
||||||
|
Assert.Equal(0, allocated);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
internal static partial class ConstantBufferContract
|
||||||
|
{
|
||||||
|
[GeneratedRegex(@"^\s*(?:float4|float2|float|int)\s+(?<name>\w+)(?:\[\w+\])?\s*:\s*packoffset\(c(?<register>\d+)(?:\.(?<component>[xyzw]))?\);", RegexOptions.Multiline)]
|
||||||
|
private static partial Regex MemberPattern();
|
||||||
|
|
||||||
|
public static IReadOnlyDictionary<string, int> Declared(string source)
|
||||||
|
=> MemberPattern().Matches(source).ToDictionary(
|
||||||
|
match => match.Groups["name"].Value,
|
||||||
|
match => int.Parse(match.Groups["register"].Value) * 16 + (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
|
||||||
|
|
||||||
|
public static int OffsetOf(Type type, string path)
|
||||||
|
{
|
||||||
|
var offset = 0;
|
||||||
|
foreach (var name in path.Split('.'))
|
||||||
|
{
|
||||||
|
offset += (int)Marshal.OffsetOf(type, name);
|
||||||
|
type = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)!.FieldType;
|
||||||
|
}
|
||||||
|
|
||||||
|
return offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int SizeOf(Type type) => (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(type).Invoke(null, null)!;
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
[Collection("Direct2D")]
|
||||||
|
public sealed class FilterRenderingTests
|
||||||
|
{
|
||||||
|
static Bgra Gradient(int x, int y)
|
||||||
|
{
|
||||||
|
if ((x / 5 + y / 7) % 5 == 4)
|
||||||
|
return Bgra.Transparent;
|
||||||
|
|
||||||
|
return new Bgra((byte)(25 + x * 5 % 225), (byte)(15 + y * 9 % 235), (byte)(250 - (x * 2 + y * 3) % 210), (byte)(100 + (x * 3 + y * 5) % 156));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly TheoryData<float, float, int, DispersionLaw> Shifts = new()
|
||||||
|
{
|
||||||
|
{ 0f, 8f, 32, DispersionLaw.Grating },
|
||||||
|
{ 0f, 2.5f, 16, DispersionLaw.Prism },
|
||||||
|
{ 0f, -9f, 32, DispersionLaw.Grating },
|
||||||
|
{ 180f, 6f, 24, DispersionLaw.Grating },
|
||||||
|
{ 90f, 8f, 32, DispersionLaw.Grating },
|
||||||
|
{ 270f, 5.25f, 20, DispersionLaw.Prism },
|
||||||
|
{ 0f, 19f, 64, DispersionLaw.Grating },
|
||||||
|
{ 90f, 0.6f, 12, DispersionLaw.Grating },
|
||||||
|
{ 0f, 4f, 8, DispersionLaw.Grating },
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Shifts))]
|
||||||
|
public void AnAxisAlignedShiftMatchesTheCpuRendering(float angle, float distance, int steps, DispersionLaw law)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 40, Gradient);
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
|
effect.SetSource(source.Bitmap, true);
|
||||||
|
using var output = effect.Output;
|
||||||
|
var settings = new ShiftSettings(ShiftMode.Linear, distance, angle, default, 1f, law, 550f, steps, true);
|
||||||
|
settings.Apply(effect);
|
||||||
|
var reference = new SpectralReferenceRenderer(source, settings);
|
||||||
|
|
||||||
|
var rendering = Rendering.Capture(context, output);
|
||||||
|
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
var expected = reference.Pixel(x, y) * 255f;
|
||||||
|
var actual = rendering[x, y];
|
||||||
|
Assert.True(
|
||||||
|
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
|
||||||
|
$"({x}, {y}) expected {expected}, actual {actual}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SwitchingBetweenTheFilterAndTheStepwiseShaderKeepsTheReferenceImage()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 40, Gradient);
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
|
effect.SetSource(source.Bitmap, true);
|
||||||
|
using var output = effect.Output;
|
||||||
|
|
||||||
|
foreach (var (angle, distance) in new[] { (0f, 8f), (30f, 8f), (0f, 8f), (0f, 40f), (90f, 8f), (0f, 0f), (0f, 8f) })
|
||||||
|
{
|
||||||
|
var settings = new ShiftSettings(ShiftMode.Linear, distance, angle, default, 1f, DispersionLaw.Grating, 550f, 32, true);
|
||||||
|
settings.Apply(effect);
|
||||||
|
var reference = new SpectralReferenceRenderer(source, settings);
|
||||||
|
|
||||||
|
var rendering = Rendering.Capture(context, output);
|
||||||
|
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
var expected = reference.Pixel(x, y) * 255f;
|
||||||
|
var actual = rendering[x, y];
|
||||||
|
Assert.True(
|
||||||
|
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
|
||||||
|
$"angle {angle}, distance {distance}: ({x}, {y}) expected {expected}, actual {actual}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ using System.Globalization;
|
|||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
using System.Runtime.InteropServices;
|
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
|
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
|
||||||
|
|
||||||
@@ -12,14 +11,13 @@ public sealed partial class ShaderContractTests
|
|||||||
{
|
{
|
||||||
static readonly Dictionary<string, string> Fields = new()
|
static readonly Dictionary<string, string> Fields = new()
|
||||||
{
|
{
|
||||||
["inputBounds"] = "InputBounds",
|
["inputBounds"] = "Header.InputBounds",
|
||||||
["direction"] = "Direction",
|
["direction"] = "Header.Direction",
|
||||||
["center"] = "Center",
|
["center"] = "Header.Center",
|
||||||
["shiftDistance"] = "Distance",
|
["shiftDistance"] = "Header.Distance",
|
||||||
["radius"] = "Radius",
|
["radius"] = "Header.Radius",
|
||||||
["strength"] = "Strength",
|
["strength"] = "Header.Strength",
|
||||||
["mode"] = "Mode",
|
["steps"] = "Header.Steps",
|
||||||
["steps"] = "Steps",
|
|
||||||
["spreadScale"] = "SpreadScale",
|
["spreadScale"] = "SpreadScale",
|
||||||
["samples"] = "Samples",
|
["samples"] = "Samples",
|
||||||
};
|
};
|
||||||
@@ -33,9 +31,6 @@ public sealed partial class ShaderContractTests
|
|||||||
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
|
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
|
||||||
private static partial Regex ConstantPattern();
|
private static partial Regex ConstantPattern();
|
||||||
|
|
||||||
[GeneratedRegex(@"^\s*(?:float4|float2|float|int)\s+(?<name>\w+)(?:\[\w+\])?\s*:\s*packoffset\(c(?<register>\d+)(?:\.(?<component>[xyzw]))?\);", RegexOptions.Multiline)]
|
|
||||||
private static partial Regex MemberPattern();
|
|
||||||
|
|
||||||
static float Constant(string name)
|
static float Constant(string name)
|
||||||
=> float.Parse(ConstantPattern().Matches(Source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
|
=> float.Parse(ConstantPattern().Matches(Source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
@@ -51,21 +46,15 @@ public sealed partial class ShaderContractTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void TheConstantBufferMatchesTheShaderLayout()
|
public void TheConstantBufferMatchesTheShaderLayout()
|
||||||
{
|
{
|
||||||
var members = MemberPattern().Matches(Source)
|
var members = ConstantBufferContract.Declared(Source);
|
||||||
.ToDictionary(
|
|
||||||
match => match.Groups["name"].Value,
|
|
||||||
match => int.Parse(match.Groups["register"].Value, CultureInfo.InvariantCulture) * 16
|
|
||||||
+ (match.Groups["component"].Success ? "xyzw".IndexOf(match.Groups["component"].Value[0]) * 4 : 0));
|
|
||||||
|
|
||||||
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
|
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
|
||||||
Assert.All(members, member => Assert.Equal(member.Value, (int)Marshal.OffsetOf(ConstantBuffer, Fields[member.Key])));
|
Assert.All(members, member => Assert.Equal(member.Value, ConstantBufferContract.OffsetOf(ConstantBuffer, Fields[member.Key])));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
|
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
|
||||||
{
|
{
|
||||||
var size = (int)typeof(Unsafe).GetMethod(nameof(Unsafe.SizeOf))!.MakeGenericMethod(ConstantBuffer).Invoke(null, null)!;
|
Assert.Equal(16 * (4 + Spectrum.MaxSteps), ConstantBufferContract.SizeOf(ConstantBuffer));
|
||||||
|
|
||||||
Assert.Equal(16 * (4 + Spectrum.MaxSteps), size);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
public sealed partial class ShaderVariantsTests
|
||||||
|
{
|
||||||
|
static string Project { get; } = ShaderProjectFile("SpectrumColorShift.Shader.vcxproj");
|
||||||
|
|
||||||
|
static string Props { get; } = ShaderProjectFile("ShaderVariants.props");
|
||||||
|
|
||||||
|
static string ShaderProjectFile(string name) => File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", name));
|
||||||
|
|
||||||
|
static string Here([CallerFilePath] string path = "") => path;
|
||||||
|
|
||||||
|
static IEnumerable<(ShaderFamily Family, bool Physical)> SteppedFamilies => [(ShaderVariants.Legacy, false), (ShaderVariants.Physical, true)];
|
||||||
|
|
||||||
|
[GeneratedRegex(@"<StepCount Include=""(?<counts>[^""]+)""")]
|
||||||
|
private static partial Regex StepCountsPattern();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"<TapCount Include=""(?<counts>[^""]+)""")]
|
||||||
|
private static partial Regex TapCountsPattern();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"ShaderMode=(?<value>\d+)</PreprocessorDefinitions>\s*<ObjectFileOutput>\$\(OutDir\)(?<prefix>SpectrumColorShiftPhysicalFilter|SpectrumColorShiftPhysical|SpectrumColorShift)(?<mode>[A-Za-z]+)%\((?<list>StepCount|TapCount)\.Identity\)\.cso")]
|
||||||
|
private static partial Regex VariantPattern();
|
||||||
|
|
||||||
|
static IEnumerable<int> Listed(Regex pattern) => pattern.Match(Props).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheStepCountsCoverTheWholeRangeInWholeQuanta()
|
||||||
|
{
|
||||||
|
Assert.Equal(0, Spectrum.MinSteps % Spectrum.StepQuantum);
|
||||||
|
Assert.Equal(0, Spectrum.MaxSteps % Spectrum.StepQuantum);
|
||||||
|
Assert.Equal(Enumerable.Range(0, (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1).Select(index => Spectrum.MinSteps + index * Spectrum.StepQuantum), ShaderVariants.Legacy.Counts);
|
||||||
|
Assert.Equal(ShaderVariants.Legacy.Counts, ShaderVariants.Physical.Counts);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheTapCountsCoverTheWholeRangeInWholeQuanta()
|
||||||
|
{
|
||||||
|
Assert.Equal(0, SpectralFilter.MaxTaps % SpectralFilter.TapQuantum);
|
||||||
|
Assert.Equal(Enumerable.Range(1, SpectralFilter.MaxTaps / SpectralFilter.TapQuantum).Select(index => index * SpectralFilter.TapQuantum), ShaderVariants.Filter.Counts);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheSharedPropsListExactlyTheseCounts()
|
||||||
|
{
|
||||||
|
Assert.Equal(ShaderVariants.Legacy.Counts, Listed(StepCountsPattern()));
|
||||||
|
Assert.Equal(ShaderVariants.Filter.Counts, Listed(TapCountsPattern()));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheShaderProjectCompilesEveryModeOfEveryFamilyWithItsEnumValue()
|
||||||
|
{
|
||||||
|
var compiled = VariantPattern().Matches(Project).Select(match => (match.Groups["prefix"].Value, match.Groups["mode"].Value, int.Parse(match.Groups["value"].Value, CultureInfo.InvariantCulture), match.Groups["list"].Value));
|
||||||
|
var stepped = from mode in ShaderVariants.Legacy.Modes from prefix in new[] { "SpectrumColorShift", "SpectrumColorShiftPhysical" } select (prefix, mode.ToString(), (int)mode, "StepCount");
|
||||||
|
var expected = stepped.Append(("SpectrumColorShiftPhysicalFilter", ShiftMode.Linear.ToString(), (int)ShiftMode.Linear, "TapCount"));
|
||||||
|
|
||||||
|
Assert.Equal(expected.Order(), compiled.Order());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EveryModeAndCountHasItsOwnShaderInEveryFamily()
|
||||||
|
{
|
||||||
|
var families = new[] { ShaderVariants.Legacy, ShaderVariants.Physical, ShaderVariants.Filter };
|
||||||
|
var ids = (from family in families from mode in family.Modes from count in family.Counts select family.Id(mode, count)).ToList();
|
||||||
|
|
||||||
|
Assert.Equal(families.Sum(family => family.Modes.Count * family.Counts.Count()), ids.Distinct().Count());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StepsShareTheShaderOfTheirPaddedCount()
|
||||||
|
{
|
||||||
|
foreach (var (family, _) in SteppedFamilies)
|
||||||
|
{
|
||||||
|
foreach (var mode in family.Modes)
|
||||||
|
{
|
||||||
|
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
|
||||||
|
Assert.Equal(family.Id(mode, Spectrum.Padded(steps)), family.Id(mode, steps));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void AModeOutsideAFamilyHasNoShader()
|
||||||
|
{
|
||||||
|
Assert.Throws<ArgumentOutOfRangeException>(() => ShaderVariants.Filter.Id(ShiftMode.Radial, 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EveryVariantIsShippedAsAResource()
|
||||||
|
{
|
||||||
|
foreach (var family in new[] { ShaderVariants.Legacy, ShaderVariants.Physical, ShaderVariants.Filter })
|
||||||
|
{
|
||||||
|
foreach (var mode in family.Modes)
|
||||||
|
{
|
||||||
|
foreach (var count in family.Counts)
|
||||||
|
{
|
||||||
|
var name = family.ResourceName(mode, count);
|
||||||
|
Assert.True(PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(name)).Length > 0, name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
public sealed class SpectralFilterTests
|
||||||
|
{
|
||||||
|
const int SignalLength = 256;
|
||||||
|
|
||||||
|
static Vector4[] Spectral(int steps, DispersionLaw law, float reference = 550f)
|
||||||
|
{
|
||||||
|
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||||
|
Spectrum.FillSpectral(table, steps, reference, law);
|
||||||
|
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vector2 Direction(float degrees)
|
||||||
|
{
|
||||||
|
var radians = degrees * MathF.PI / 180f;
|
||||||
|
|
||||||
|
return new Vector2(MathF.Cos(radians), MathF.Sin(radians));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vector4 Signal(int position)
|
||||||
|
{
|
||||||
|
var seed = (uint)(position * 2654435761u);
|
||||||
|
float Next()
|
||||||
|
{
|
||||||
|
seed = seed * 1664525u + 1013904223u;
|
||||||
|
|
||||||
|
return (seed >> 8) / (float)(1 << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Vector4(Next(), Next(), Next(), Next());
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vector3 Rgb(Vector4 value) => new(value.X, value.Y, value.Z);
|
||||||
|
|
||||||
|
static (Vector3 Color, float Alpha) Stepwise(Vector4[] table, int steps, float distance, float along, int pixel)
|
||||||
|
{
|
||||||
|
var color = Vector3.Zero;
|
||||||
|
var alpha = 0f;
|
||||||
|
for (var step = 0; step < steps; step++)
|
||||||
|
{
|
||||||
|
var gain = table[step * Spectrum.EntriesPerStep];
|
||||||
|
var basis = table[step * Spectrum.EntriesPerStep + 1];
|
||||||
|
var offset = -(double)basis.W * distance * along;
|
||||||
|
var floor = (int)Math.Floor(offset);
|
||||||
|
var fraction = (float)(offset - floor);
|
||||||
|
var shifted = Vector4.Lerp(Signal(pixel + floor), Signal(pixel + floor + 1), fraction);
|
||||||
|
color += Rgb(gain) * Vector3.Dot(Rgb(basis), Rgb(shifted));
|
||||||
|
alpha += gain.W * shifted.W;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
static (Vector3 Color, float Alpha) Filtered(Vector4[] taps, SpectralFilter.Layout layout, int pixel)
|
||||||
|
{
|
||||||
|
var color = Vector3.Zero;
|
||||||
|
var alpha = 0f;
|
||||||
|
for (var tap = 0; tap < layout.Taps; tap++)
|
||||||
|
{
|
||||||
|
var shifted = Signal(pixel + layout.Origin + tap);
|
||||||
|
var red = taps[tap * SpectralFilter.EntriesPerTap];
|
||||||
|
var green = taps[tap * SpectralFilter.EntriesPerTap + 1];
|
||||||
|
var blue = taps[tap * SpectralFilter.EntriesPerTap + 2];
|
||||||
|
color += new Vector3(Vector3.Dot(Rgb(red), Rgb(shifted)), Vector3.Dot(Rgb(green), Rgb(shifted)), Vector3.Dot(Rgb(blue), Rgb(shifted)));
|
||||||
|
alpha += red.W * shifted.W;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly TheoryData<float, float, int, DispersionLaw> Shifts = new()
|
||||||
|
{
|
||||||
|
{ 0f, 8f, 32, DispersionLaw.Grating },
|
||||||
|
{ 180f, 8f, 32, DispersionLaw.Grating },
|
||||||
|
{ 90f, 6.5f, 24, DispersionLaw.Prism },
|
||||||
|
{ 270f, -5f, 24, DispersionLaw.Grating },
|
||||||
|
{ 0f, 2f, 16, DispersionLaw.Grating },
|
||||||
|
{ 0f, 0.4f, 32, DispersionLaw.Prism },
|
||||||
|
{ 180f, 18.75f, 64, DispersionLaw.Grating },
|
||||||
|
{ 90f, -12.3f, 48, DispersionLaw.Prism },
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Shifts))]
|
||||||
|
public void TheTapsReproduceTheStepwiseBilinearSum(float angle, float distance, int steps, DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = Spectral(steps, law);
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
var direction = Direction(angle);
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, table, steps, distance, direction);
|
||||||
|
|
||||||
|
Assert.True(layout.Taps > 0);
|
||||||
|
var along = layout.Vertical ? direction.Y : direction.X;
|
||||||
|
for (var pixel = 64; pixel < 128; pixel++)
|
||||||
|
{
|
||||||
|
var expected = Stepwise(table, steps, distance, along, pixel);
|
||||||
|
var actual = Filtered(taps, layout, pixel);
|
||||||
|
Assert.True(Vector3.Distance(expected.Color, actual.Color) <= 2e-5f && Math.Abs(expected.Alpha - actual.Alpha) <= 2e-5f, $"pixel {pixel}: {expected} against {actual}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Shifts))]
|
||||||
|
public void TheTapsSumToTheIdentityAndAUnitAlpha(float angle, float distance, int steps, DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = Spectral(steps, law);
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, table, steps, distance, Direction(angle));
|
||||||
|
|
||||||
|
var rows = new Vector3[3];
|
||||||
|
var alpha = 0f;
|
||||||
|
for (var tap = 0; tap < layout.Taps; tap++)
|
||||||
|
{
|
||||||
|
for (var row = 0; row < 3; row++)
|
||||||
|
rows[row] += Rgb(taps[tap * SpectralFilter.EntriesPerTap + row]);
|
||||||
|
|
||||||
|
alpha += taps[tap * SpectralFilter.EntriesPerTap].W;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(Vector3.Distance(rows[0], Vector3.UnitX) <= 1e-5f, $"{rows[0]}");
|
||||||
|
Assert.True(Vector3.Distance(rows[1], Vector3.UnitY) <= 1e-5f, $"{rows[1]}");
|
||||||
|
Assert.True(Vector3.Distance(rows[2], Vector3.UnitZ) <= 1e-5f, $"{rows[2]}");
|
||||||
|
Assert.Equal(1f, alpha, 1e-5f);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0f, false)]
|
||||||
|
[InlineData(180f, false)]
|
||||||
|
[InlineData(90f, true)]
|
||||||
|
[InlineData(270f, true)]
|
||||||
|
public void TheAxisOfTheDirectionDecidesWhetherTheTapsRunVertically(float angle, bool vertical)
|
||||||
|
{
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 8f, Direction(angle));
|
||||||
|
|
||||||
|
Assert.True(layout.Taps > 0);
|
||||||
|
Assert.Equal(vertical, layout.Vertical);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(1f)]
|
||||||
|
[InlineData(30f)]
|
||||||
|
[InlineData(45f)]
|
||||||
|
[InlineData(89f)]
|
||||||
|
[InlineData(135f)]
|
||||||
|
[InlineData(200f)]
|
||||||
|
public void ADirectionOffTheAxesUsesNoTaps(float angle)
|
||||||
|
{
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 8f, Direction(angle));
|
||||||
|
|
||||||
|
Assert.Equal(default, layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0f, 32, 40f)]
|
||||||
|
[InlineData(0f, 64, 60f)]
|
||||||
|
[InlineData(0f, 8, 6f)]
|
||||||
|
[InlineData(90f, 32, 24f)]
|
||||||
|
public void ADistanceTooLongForTheTapsUsesNoTaps(float angle, int steps, float distance)
|
||||||
|
{
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, Spectral(steps, DispersionLaw.Grating), steps, distance, Direction(angle));
|
||||||
|
|
||||||
|
Assert.Equal(default, layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NoDistanceUsesNoTaps()
|
||||||
|
{
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 0f, Direction(0f));
|
||||||
|
|
||||||
|
Assert.Equal(default, layout);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheTapsAreWholeQuantaAndStayWithinTheShareOfTheSteps()
|
||||||
|
{
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
var used = 0;
|
||||||
|
foreach (var steps in new[] { 8, 12, 16, 24, 32, 40, 48, 64 })
|
||||||
|
{
|
||||||
|
var table = Spectral(steps, DispersionLaw.Grating);
|
||||||
|
for (var distance = 0.25f; distance <= 30f; distance += 0.25f)
|
||||||
|
{
|
||||||
|
var layout = SpectralFilter.Fill(taps, table, steps, distance, Direction(0f));
|
||||||
|
if (layout.Taps == 0)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
used++;
|
||||||
|
Assert.Equal(0, layout.Taps % SpectralFilter.TapQuantum);
|
||||||
|
Assert.InRange(layout.Taps, SpectralFilter.TapQuantum, SpectralFilter.MaxTaps);
|
||||||
|
Assert.True(layout.Taps <= Spectrum.Padded(steps) * SpectralFilter.MaxTapShare, $"{layout.Taps} taps for {steps} steps at {distance}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(used > 100, $"{used}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheEntriesBeyondTheTapsAreCleared()
|
||||||
|
{
|
||||||
|
var taps = new Vector4[SpectralFilter.TableLength];
|
||||||
|
Array.Fill(taps, new Vector4(7f));
|
||||||
|
|
||||||
|
var layout = SpectralFilter.Fill(taps, Spectral(32, DispersionLaw.Grating), 32, 8f, Direction(0f));
|
||||||
|
|
||||||
|
Assert.All(taps[(layout.Taps * SpectralFilter.EntriesPerTap)..], entry => Assert.Equal(Vector4.Zero, entry));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
internal sealed class SpectralReferenceRenderer
|
||||||
|
{
|
||||||
|
readonly SourceImage source;
|
||||||
|
readonly ShiftSettings settings;
|
||||||
|
readonly Vector4[] table = new Vector4[Spectrum.SpectralTableLength];
|
||||||
|
readonly Vector2 direction;
|
||||||
|
readonly Vector2 center;
|
||||||
|
readonly float radius;
|
||||||
|
readonly int steps;
|
||||||
|
|
||||||
|
public SpectralReferenceRenderer(SourceImage source, ShiftSettings settings)
|
||||||
|
{
|
||||||
|
this.source = source;
|
||||||
|
this.settings = settings;
|
||||||
|
steps = Spectrum.ClampSteps(settings.Steps);
|
||||||
|
Spectrum.FillSpectral(table, steps, settings.ReferenceWavelength, settings.Dispersion);
|
||||||
|
var radians = settings.Angle * MathF.PI / 180f;
|
||||||
|
direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
|
||||||
|
var rect = new Vortice.RawRect(0, 0, source.Width, source.Height);
|
||||||
|
center = ShiftGeometry.Center(rect, settings.Center);
|
||||||
|
radius = ShiftGeometry.Radius(rect, center);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Vector4 Pixel(int x, int y)
|
||||||
|
{
|
||||||
|
var position = new Vector2(x + 0.5f, y + 0.5f);
|
||||||
|
var original = Srgb.EncodePremultiplied(Covered(position));
|
||||||
|
if (settings.Distance == 0f || settings.Strength <= 0f)
|
||||||
|
return original;
|
||||||
|
|
||||||
|
var (color, alpha) = Accumulated(position);
|
||||||
|
var positive = Vector3.Max(color, Vector3.Zero);
|
||||||
|
var resolved = Math.Clamp(Math.Max(alpha, Math.Max(positive.X, Math.Max(positive.Y, positive.Z))), 0f, 1f);
|
||||||
|
var result = Srgb.EncodePremultiplied(new Vector4(positive, resolved));
|
||||||
|
|
||||||
|
return Vector4.Lerp(original, result, Math.Clamp(settings.Strength, 0f, 1f));
|
||||||
|
}
|
||||||
|
|
||||||
|
public (Vector3 Color, float Alpha) Accumulated(Vector2 position)
|
||||||
|
{
|
||||||
|
var color = Vector3.Zero;
|
||||||
|
var alpha = 0f;
|
||||||
|
for (var index = 0; index < steps; index++)
|
||||||
|
{
|
||||||
|
var gain = table[index * Spectrum.EntriesPerStep];
|
||||||
|
var basis = table[index * Spectrum.EntriesPerStep + 1];
|
||||||
|
var target = ShiftReference.SamplePosition(settings.Mode, position, basis.W, settings.Distance, direction, center, radius);
|
||||||
|
var lit = Covered(target);
|
||||||
|
color += new Vector3(gain.X, gain.Y, gain.Z) * Vector3.Dot(new Vector3(basis.X, basis.Y, basis.Z), new Vector3(lit.X, lit.Y, lit.Z));
|
||||||
|
alpha += gain.W * lit.W;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (color, alpha);
|
||||||
|
}
|
||||||
|
|
||||||
|
Vector4 Covered(Vector2 target)
|
||||||
|
{
|
||||||
|
var (light, coverage) = Sample(target);
|
||||||
|
|
||||||
|
return light * coverage;
|
||||||
|
}
|
||||||
|
|
||||||
|
(Vector4 Light, float Coverage) Sample(Vector2 target)
|
||||||
|
{
|
||||||
|
var size = new Vector2(source.Width, source.Height);
|
||||||
|
var clamped = Vector2.Clamp(target, new Vector2(0.5f), size - new Vector2(0.5f));
|
||||||
|
var edge = Vector2.Min(target, size - target) + new Vector2(0.5f);
|
||||||
|
var coverage = Vector2.Clamp(edge, Vector2.Zero, Vector2.One);
|
||||||
|
|
||||||
|
return (Bilinear(clamped), coverage.X * coverage.Y);
|
||||||
|
}
|
||||||
|
|
||||||
|
Vector4 Bilinear(Vector2 position)
|
||||||
|
{
|
||||||
|
var shifted = position - new Vector2(0.5f);
|
||||||
|
var x = (int)MathF.Floor(shifted.X);
|
||||||
|
var y = (int)MathF.Floor(shifted.Y);
|
||||||
|
var fraction = new Vector2(shifted.X - x, shifted.Y - y);
|
||||||
|
|
||||||
|
return Vector4.Lerp(
|
||||||
|
Vector4.Lerp(Texel(x, y), Texel(x + 1, y), fraction.X),
|
||||||
|
Vector4.Lerp(Texel(x, y + 1), Texel(x + 1, y + 1), fraction.X),
|
||||||
|
fraction.Y);
|
||||||
|
}
|
||||||
|
|
||||||
|
Vector4 Texel(int x, int y)
|
||||||
|
{
|
||||||
|
var pixel = source[Math.Clamp(x, 0, source.Width - 1), Math.Clamp(y, 0, source.Height - 1)];
|
||||||
|
|
||||||
|
return Srgb.DecodePremultiplied(new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,750 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
using Vortice.Direct2D1;
|
||||||
|
using Vortice.Direct2D1.Effects;
|
||||||
|
using Vortice.Mathematics;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
[Collection("Direct2D")]
|
||||||
|
public sealed class SpectralRenderingTests
|
||||||
|
{
|
||||||
|
const int Seam = 32;
|
||||||
|
|
||||||
|
static ShiftSettings Settings(
|
||||||
|
ShiftMode Mode = ShiftMode.Linear,
|
||||||
|
float Distance = 8f,
|
||||||
|
float Angle = 0f,
|
||||||
|
Vector2 Center = default,
|
||||||
|
float Strength = 1f,
|
||||||
|
DispersionLaw Dispersion = DispersionLaw.Grating,
|
||||||
|
float ReferenceWavelength = 550f,
|
||||||
|
int Steps = 32)
|
||||||
|
=> new(Mode, Distance, Angle, Center, Strength, Dispersion, ReferenceWavelength, Steps, true);
|
||||||
|
|
||||||
|
static Bgra HalfAndHalf(int x, int y) => x < Seam ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||||
|
|
||||||
|
static Bgra TopAndBottom(int x, int y) => y < Seam ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||||
|
|
||||||
|
static Bgra Stripes(int x, int y) => Math.Abs(x + 0.5 - 64) is >= 30 and < 34 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||||
|
|
||||||
|
static Bgra Dot(int x, int y) => Math.Abs(x + 0.5 - 104) < 3 && Math.Abs(y + 0.5 - 64) < 3 ? Bgra.Opaque(255, 255, 255) : Bgra.Opaque(0, 0, 0);
|
||||||
|
|
||||||
|
static Bgra Textured(int x, int y)
|
||||||
|
{
|
||||||
|
if ((x / 8 + y / 8) % 5 == 4)
|
||||||
|
return Bgra.Transparent;
|
||||||
|
|
||||||
|
return new Bgra((byte)(40 + x * 3 % 200), (byte)(30 + y * 5 % 210), (byte)(255 - (x + y) * 2 % 220), (byte)(110 + (x * 7 + y * 11) % 146));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Bgra PointSymmetric(int x, int y, int mirroredX, int mirroredY)
|
||||||
|
{
|
||||||
|
var value = Math.Min(x * 3 + y * 5, mirroredX * 3 + mirroredY * 5);
|
||||||
|
|
||||||
|
return Bgra.Opaque((byte)(40 + value * 7 % 200), (byte)(30 + value * 11 % 210), (byte)(255 - value * 13 % 220));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
|
||||||
|
{
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(devices);
|
||||||
|
effect.SetSource(source.Bitmap, true);
|
||||||
|
settings.Apply(effect);
|
||||||
|
using var output = effect.Output;
|
||||||
|
|
||||||
|
return Rendering.Capture(devices, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool WithinRounding(Bgra expected, Bgra actual, int tolerance = 1)
|
||||||
|
=> Math.Abs(expected.Blue - actual.Blue) <= tolerance && Math.Abs(expected.Green - actual.Green) <= tolerance && Math.Abs(expected.Red - actual.Red) <= tolerance && Math.Abs(expected.Alpha - actual.Alpha) <= tolerance;
|
||||||
|
|
||||||
|
static double DistanceToBorder(SourceImage source, int x, int y)
|
||||||
|
=> Math.Min(Math.Min(x, source.Width - 1 - x), Math.Min(y, source.Height - 1 - y));
|
||||||
|
|
||||||
|
static double Crossing(Func<int, byte> value, int from, int to)
|
||||||
|
{
|
||||||
|
for (var index = from; index < to; index++)
|
||||||
|
{
|
||||||
|
double a = value(index);
|
||||||
|
double b = value(index + 1);
|
||||||
|
if (a >= 127.5 && b < 127.5)
|
||||||
|
return index + 0.5 + (a - 127.5) / (a - b);
|
||||||
|
}
|
||||||
|
|
||||||
|
return double.NaN;
|
||||||
|
}
|
||||||
|
|
||||||
|
static double EdgeWidth(Func<int, byte> value, int from, int to)
|
||||||
|
{
|
||||||
|
double high = double.NaN;
|
||||||
|
double low = double.NaN;
|
||||||
|
for (var index = from; index < to; index++)
|
||||||
|
{
|
||||||
|
double a = value(index);
|
||||||
|
double b = value(index + 1);
|
||||||
|
if (double.IsNaN(high) && a >= 230 && b < 230)
|
||||||
|
high = index + 0.5 + (a - 230) / (a - b);
|
||||||
|
if (double.IsNaN(low) && a >= 25 && b < 25)
|
||||||
|
low = index + 0.5 + (a - 25) / (a - b);
|
||||||
|
}
|
||||||
|
|
||||||
|
return low - high;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Func<int, byte> ExpectedProfile(ShiftSettings settings, int channel, float axisDirection)
|
||||||
|
{
|
||||||
|
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||||
|
Spectrum.FillSpectral(table, settings.Steps, settings.ReferenceWavelength, settings.Dispersion);
|
||||||
|
var steps = Spectrum.ClampSteps(settings.Steps);
|
||||||
|
|
||||||
|
return index =>
|
||||||
|
{
|
||||||
|
var sum = 0d;
|
||||||
|
for (var step = 0; step < steps; step++)
|
||||||
|
{
|
||||||
|
var gain = table[step * Spectrum.EntriesPerStep];
|
||||||
|
var basis = table[step * Spectrum.EntriesPerStep + 1];
|
||||||
|
var position = index + 0.5 - basis.W * settings.Distance * axisDirection;
|
||||||
|
var value = Math.Clamp(Seam + 0.5 - position, 0d, 1d);
|
||||||
|
sum += (channel switch { 0 => gain.X, 1 => gain.Y, _ => gain.Z }) * (basis.X + basis.Y + basis.Z) * value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (byte)Math.Round(Srgb.Encode(Math.Clamp(sum, 0d, 1d)) * 255d);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
static Bgra Blob(int x, int y)
|
||||||
|
{
|
||||||
|
var distance = Math.Sqrt(Math.Pow(x + 0.5 - 64, 2) + Math.Pow(y + 0.5 - 64, 2));
|
||||||
|
var coverage = Math.Clamp((26 - distance) / 8, 0d, 1d);
|
||||||
|
|
||||||
|
return new Bgra(160, 160, 160, (byte)Math.Round(coverage * 255d));
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vector3 TotalLight(IEnumerable<Bgra> pixels)
|
||||||
|
{
|
||||||
|
var total = Vector3.Zero;
|
||||||
|
foreach (var pixel in pixels)
|
||||||
|
{
|
||||||
|
var light = Srgb.DecodePremultiplied(new Vector4(pixel.Red, pixel.Green, pixel.Blue, pixel.Alpha) / 255f);
|
||||||
|
total += new Vector3(light.X, light.Y, light.Z);
|
||||||
|
}
|
||||||
|
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Func<int, byte> Channel(Rendering rendering, int channel, Func<int, (int X, int Y)> position)
|
||||||
|
=> index =>
|
||||||
|
{
|
||||||
|
var (x, y) = position(index);
|
||||||
|
var pixel = rendering[x, y];
|
||||||
|
|
||||||
|
return channel switch { 0 => pixel.Red, 1 => pixel.Green, _ => pixel.Blue };
|
||||||
|
};
|
||||||
|
|
||||||
|
static int PeakAt(Rendering rendering, int channel, int from, int to, Func<int, (int X, int Y)> position)
|
||||||
|
{
|
||||||
|
var value = Channel(rendering, channel, position);
|
||||||
|
|
||||||
|
return Enumerable.Range(from, to - from + 1).MaxBy(index => value(index));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly TheoryData<ShiftMode> Modes = new() { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational };
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void WithoutADistanceTheImagePassesThroughUntouched(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 0f, Center: new Vector2(9f, -5f)));
|
||||||
|
|
||||||
|
Assert.Equal((0, 0, source.Width, source.Height), (rendering.Left, rendering.Top, rendering.Width, rendering.Height));
|
||||||
|
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(255)]
|
||||||
|
[InlineData(200)]
|
||||||
|
[InlineData(128)]
|
||||||
|
[InlineData(7)]
|
||||||
|
public void EveryGrayLevelSurvivesTheRoundTripThroughLinearLight(int alpha)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 256, 4, (x, _) => new Bgra((byte)x, (byte)x, (byte)x, (byte)alpha));
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Distance: 0f));
|
||||||
|
|
||||||
|
Assert.All(rendering.Coordinates(), point => Assert.Equal(source[point.X, point.Y], rendering[point.X, point.Y]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void WithoutStrengthTheImageIsUntouchedAndTheSpillStaysTransparent(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f, Strength: 0f));
|
||||||
|
|
||||||
|
Assert.True(rendering.Left < 0 && rendering.Top < 0);
|
||||||
|
Assert.All(rendering.Coordinates(), point => Assert.Equal(source.Contains(point.X, point.Y) ? source[point.X, point.Y] : Bgra.Transparent, rendering[point.X, point.Y]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(ShiftMode.Linear, DispersionLaw.Grating, 8)]
|
||||||
|
[InlineData(ShiftMode.Linear, DispersionLaw.Prism, 33)]
|
||||||
|
[InlineData(ShiftMode.Radial, DispersionLaw.Grating, 32)]
|
||||||
|
[InlineData(ShiftMode.Radial, DispersionLaw.Prism, 64)]
|
||||||
|
[InlineData(ShiftMode.Rotational, DispersionLaw.Grating, 17)]
|
||||||
|
[InlineData(ShiftMode.Rotational, DispersionLaw.Prism, 32)]
|
||||||
|
public void AUniformImageKeepsItsColorInTheInterior(ShiftMode mode, DispersionLaw law, int steps)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
var color = new Bgra(200, 90, 30, 255);
|
||||||
|
using var source = SourceImage.Solid(context, 96, 96, color);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f, Dispersion: law, Steps: steps, ReferenceWavelength: 600f));
|
||||||
|
|
||||||
|
var checkedPixels = 0;
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
|
||||||
|
{
|
||||||
|
Assert.True(WithinRounding(color, rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
|
||||||
|
checkedPixels++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(checkedPixels > 3000, $"{checkedPixels}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly TheoryData<ShiftMode, int> DarkLevels = [.. from mode in new[] { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational } from level in new[] { 1, 2, 3, 5, 8, 16, 40 } select (mode, level)];
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(DarkLevels))]
|
||||||
|
public void ADarkUniformImageKeepsItsColorInTheInterior(ShiftMode mode, int level)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
var color = Bgra.Opaque((byte)level, (byte)level, (byte)level);
|
||||||
|
using var source = SourceImage.Solid(context, 96, 96, color);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f));
|
||||||
|
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
|
||||||
|
Assert.True(WithinRounding(color, rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void ASemiTransparentUniformImageKeepsItsPremultipliedColor(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
var color = new Bgra(200, 90, 30, 128);
|
||||||
|
using var source = SourceImage.Solid(context, 96, 96, color);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 12f));
|
||||||
|
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
if (source.Contains(x, y) && DistanceToBorder(source, x, y) > 16)
|
||||||
|
Assert.True(WithinRounding(color.Premultiplied(), rendering[x, y]), $"({x}, {y}) {rendering[x, y]}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(8f, 0f, DispersionLaw.Grating, 550f, 32)]
|
||||||
|
[InlineData(8f, 0f, DispersionLaw.Prism, 550f, 32)]
|
||||||
|
[InlineData(8f, 0f, DispersionLaw.Grating, 450f, 32)]
|
||||||
|
[InlineData(8f, 0f, DispersionLaw.Grating, 650f, 32)]
|
||||||
|
[InlineData(8f, 180f, DispersionLaw.Grating, 550f, 32)]
|
||||||
|
[InlineData(-8f, 0f, DispersionLaw.Grating, 550f, 32)]
|
||||||
|
[InlineData(16f, 0f, DispersionLaw.Grating, 550f, 64)]
|
||||||
|
[InlineData(6f, 0f, DispersionLaw.Prism, 500f, 16)]
|
||||||
|
public void TheEdgeOfEachChannelFollowsTheOneDimensionalModelAlongTheAngle(float distance, float angle, DispersionLaw law, float reference, int steps)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||||
|
var settings = Settings(Distance: distance, Angle: angle, Dispersion: law, ReferenceWavelength: reference, Steps: steps);
|
||||||
|
var direction = MathF.Cos(angle * MathF.PI / 180f);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, settings);
|
||||||
|
|
||||||
|
for (var channel = 0; channel < 3; channel++)
|
||||||
|
{
|
||||||
|
var crossing = Crossing(Channel(rendering, channel, x => (x, 16)), 4, 58);
|
||||||
|
var expected = Crossing(ExpectedProfile(settings, channel, direction), 4, 58);
|
||||||
|
Assert.True(Math.Abs(crossing - expected) <= 0.15, $"channel {channel}: {crossing} against {expected}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(90f)]
|
||||||
|
[InlineData(-90f)]
|
||||||
|
public void AVerticalAngleMovesTheEdgesOfAHorizontalSeam(float angle)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 32, 64, TopAndBottom);
|
||||||
|
var settings = Settings(Distance: 8f, Angle: angle);
|
||||||
|
var direction = MathF.Sin(angle * MathF.PI / 180f);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, settings);
|
||||||
|
|
||||||
|
for (var channel = 0; channel < 3; channel++)
|
||||||
|
{
|
||||||
|
var crossing = Crossing(Channel(rendering, channel, y => (16, y)), 4, 58);
|
||||||
|
var expected = Crossing(ExpectedProfile(settings, channel, direction), 4, 58);
|
||||||
|
Assert.True(Math.Abs(crossing - expected) <= 0.15, $"channel {channel}: {crossing} against {expected}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(10f, 0f)]
|
||||||
|
[InlineData(10f, 37f)]
|
||||||
|
[InlineData(18f, 90f)]
|
||||||
|
[InlineData(-14f, 200f)]
|
||||||
|
public void ALinearShiftLosesNoLightAndGainsOnlyWhatClippingAdds(float distance, float angle)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 128, 128, Blob);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Distance: distance, Angle: angle));
|
||||||
|
|
||||||
|
var before = TotalLight(Enumerable.Range(0, source.Width * source.Height).Select(index => source[index % source.Width, index / source.Width]));
|
||||||
|
var after = TotalLight(rendering.Coordinates().Select(point => rendering[point.X, point.Y]));
|
||||||
|
var ratio = after / before;
|
||||||
|
foreach (var (channel, value) in new[] { ("red", ratio.X), ("green", ratio.Y), ("blue", ratio.Z) })
|
||||||
|
Assert.True(value is >= 0.995f and <= 1.08f, $"{channel} {value}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(8f, 0f, DispersionLaw.Grating, 32)]
|
||||||
|
[InlineData(8f, 180f, DispersionLaw.Prism, 33)]
|
||||||
|
[InlineData(16f, 0f, DispersionLaw.Grating, 64)]
|
||||||
|
public void TheEdgeProfileOfEachChannelFollowsTheOneDimensionalModel(float distance, float angle, DispersionLaw law, int steps)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||||
|
var settings = Settings(Distance: distance, Angle: angle, Dispersion: law, Steps: steps);
|
||||||
|
var direction = MathF.Cos(angle * MathF.PI / 180f);
|
||||||
|
var margin = (int)MathF.Ceiling(MathF.Abs(distance)) + 1;
|
||||||
|
|
||||||
|
var rendering = Render(context, source, settings);
|
||||||
|
|
||||||
|
for (var channel = 0; channel < 3; channel++)
|
||||||
|
{
|
||||||
|
var actual = Channel(rendering, channel, x => (x, 16));
|
||||||
|
var expected = ExpectedProfile(settings, channel, direction);
|
||||||
|
for (var x = margin; x < 64 - margin; x++)
|
||||||
|
Assert.True(Math.Abs(actual(x) - expected(x)) <= 2, $"channel {channel}, x {x}: {actual(x)} against {expected(x)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BlueMovesAheadOfGreenAndRedAlongTheDirection()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings());
|
||||||
|
var red = Crossing(Channel(rendering, 0, x => (x, 16)), 4, 58);
|
||||||
|
var green = Crossing(Channel(rendering, 1, x => (x, 16)), 4, 58);
|
||||||
|
var blue = Crossing(Channel(rendering, 2, x => (x, 16)), 4, 58);
|
||||||
|
|
||||||
|
Assert.True(red is >= 28d and <= 30.5d && green is >= 32.5d and <= 34.5d && blue is >= 37d and <= 39.5d, $"red {red}, green {green}, blue {blue}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0f)]
|
||||||
|
[InlineData(37f)]
|
||||||
|
[InlineData(90f)]
|
||||||
|
[InlineData(200f)]
|
||||||
|
public void ANegativeDistanceMirrorsAPositiveOneAtTheOppositeAngle(float angle)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
|
||||||
|
var negative = Render(context, source, Settings(Distance: -10f, Angle: angle));
|
||||||
|
var opposite = Render(context, source, Settings(Distance: 10f, Angle: angle + 180f));
|
||||||
|
|
||||||
|
Assert.Equal((negative.Left, negative.Top, negative.Width, negative.Height), (opposite.Left, opposite.Top, opposite.Width, opposite.Height));
|
||||||
|
Assert.All(negative.Coordinates(), point => Assert.True(WithinRounding(negative[point.X, point.Y], opposite[point.X, point.Y]), $"({point.X}, {point.Y})"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ThePrismLawNarrowsTheRedEdgeComparedWithTheGrating()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||||
|
|
||||||
|
var grating = Render(context, source, Settings(Dispersion: DispersionLaw.Grating));
|
||||||
|
var prism = Render(context, source, Settings(Dispersion: DispersionLaw.Prism));
|
||||||
|
var gratingWidth = EdgeWidth(Channel(grating, 0, x => (x, 16)), 4, 58);
|
||||||
|
var prismWidth = EdgeWidth(Channel(prism, 0, x => (x, 16)), 4, 58);
|
||||||
|
|
||||||
|
Assert.True(prismWidth < gratingWidth * 0.7, $"prism {prismWidth}, grating {gratingWidth}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void MoreStepsConvergeTowardsTheDenseSpectrum()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
var dense = Render(context, source, Settings(Distance: 24f, Steps: 64));
|
||||||
|
|
||||||
|
long Distance(int steps)
|
||||||
|
{
|
||||||
|
var coarse = Render(context, source, Settings(Distance: 24f, Steps: steps));
|
||||||
|
return dense.Coordinates().Sum(point =>
|
||||||
|
{
|
||||||
|
var a = dense[point.X, point.Y];
|
||||||
|
var b = coarse[point.X, point.Y];
|
||||||
|
return (long)(Math.Abs(a.Blue - b.Blue) + Math.Abs(a.Green - b.Green) + Math.Abs(a.Red - b.Red) + Math.Abs(a.Alpha - b.Alpha));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var eight = Distance(8);
|
||||||
|
var sixteen = Distance(16);
|
||||||
|
var thirtyTwo = Distance(32);
|
||||||
|
|
||||||
|
Assert.True(eight > sixteen, $"8: {eight}, 16: {sixteen}");
|
||||||
|
Assert.True(sixteen > thirtyTwo, $"16: {sixteen}, 32: {thirtyTwo}");
|
||||||
|
}
|
||||||
|
|
||||||
|
static readonly ShiftSettings[] ReferenceSettings =
|
||||||
|
[
|
||||||
|
Settings(),
|
||||||
|
Settings(Distance: 20f, Angle: 37f),
|
||||||
|
Settings(Distance: -14f, Angle: 215f, Dispersion: DispersionLaw.Prism),
|
||||||
|
Settings(Mode: ShiftMode.Radial, Distance: 20f),
|
||||||
|
Settings(Mode: ShiftMode.Radial, Distance: -18f, Center: new Vector2(30f, -12f)),
|
||||||
|
Settings(Mode: ShiftMode.Rotational, Distance: 20f, Center: new Vector2(12f, -9f)),
|
||||||
|
Settings(Mode: ShiftMode.Rotational, Distance: 35f),
|
||||||
|
Settings(Mode: ShiftMode.Radial, Distance: 60f),
|
||||||
|
Settings(Mode: ShiftMode.Radial, Distance: -75f, Center: new Vector2(-25f, 10f), Steps: 16),
|
||||||
|
Settings(Mode: ShiftMode.Rotational, Distance: 90f, Center: new Vector2(20f, 14f), Steps: 64),
|
||||||
|
Settings(Distance: 14f, Dispersion: DispersionLaw.Prism, ReferenceWavelength: 480f, Steps: 8, Strength: 0.6f),
|
||||||
|
Settings(Distance: 18f, Angle: 120f, Steps: 13),
|
||||||
|
Settings(Mode: ShiftMode.Radial, Distance: 30f, Center: new Vector2(-10f, 6f), Steps: 33),
|
||||||
|
Settings(Mode: ShiftMode.Rotational, Distance: 50f, Dispersion: DispersionLaw.Prism, Steps: 21),
|
||||||
|
Settings(Distance: 40f, Angle: 200f, Dispersion: DispersionLaw.Prism, ReferenceWavelength: 650f, Steps: 64),
|
||||||
|
];
|
||||||
|
|
||||||
|
public static readonly TheoryData<int> ReferenceCases = [.. Enumerable.Range(0, ReferenceSettings.Length)];
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ReferenceCases))]
|
||||||
|
public void TheOutputMatchesAnIndependentCpuRendering(int index)
|
||||||
|
{
|
||||||
|
var settings = ReferenceSettings[index];
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
var reference = new SpectralReferenceRenderer(source, settings);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, settings);
|
||||||
|
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
var expected = reference.Pixel(x, y) * 255f;
|
||||||
|
var actual = rendering[x, y];
|
||||||
|
Assert.True(
|
||||||
|
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
|
||||||
|
$"({x}, {y}) expected {expected}, actual {actual}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ReferenceCases))]
|
||||||
|
public void NothingVisibleLiesBeyondTheOutputBounds(int index)
|
||||||
|
{
|
||||||
|
var settings = ReferenceSettings[index];
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
var reference = new SpectralReferenceRenderer(source, settings);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, settings);
|
||||||
|
|
||||||
|
for (var y = rendering.Top - 8; y < rendering.Bottom + 8; y++)
|
||||||
|
{
|
||||||
|
for (var x = rendering.Left - 8; x < rendering.Right + 8; x++)
|
||||||
|
{
|
||||||
|
if (!rendering.Contains(x, y))
|
||||||
|
Assert.True(reference.Pixel(x, y).W * 255f <= 1f, $"({x}, {y}) {reference.Pixel(x, y)}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BlueSpillsOutwardAndRedInwardOfARadialStripe()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 128, 128, Stripes);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: ShiftMode.Radial, Distance: 20f));
|
||||||
|
var red = PeakAt(rendering, 0, 80, 120, x => (x, 64));
|
||||||
|
var green = PeakAt(rendering, 1, 80, 120, x => (x, 64));
|
||||||
|
var blue = PeakAt(rendering, 2, 80, 120, x => (x, 64));
|
||||||
|
|
||||||
|
Assert.True(red < 94 && green is >= 94 and <= 97 && blue > 98, $"red {red}, green {green}, blue {blue}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ARadialShiftKeepsTheMirrorSymmetryOfTheImage()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 128, 128, Stripes);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: ShiftMode.Radial, Distance: 20f));
|
||||||
|
|
||||||
|
Assert.Equal(rendering.Left + rendering.Right, source.Width);
|
||||||
|
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(rendering[point.X, point.Y], rendering[source.Width - 1 - point.X, point.Y]), $"({point.X}, {point.Y})"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BlueTurnsClockwiseAndRedCounterclockwiseAroundTheCenter()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 160, 128, Dot);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: ShiftMode.Rotational, Distance: 40f));
|
||||||
|
var red = PeakAt(rendering, 0, 40, 90, y => (104, y));
|
||||||
|
var green = PeakAt(rendering, 1, 40, 90, y => (104, y));
|
||||||
|
var blue = PeakAt(rendering, 2, 40, 90, y => (104, y));
|
||||||
|
|
||||||
|
Assert.True(red < 62 && green is >= 62 and <= 66 && blue > 66, $"red {red}, green {green}, blue {blue}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(ShiftMode.Radial)]
|
||||||
|
[InlineData(ShiftMode.Rotational)]
|
||||||
|
public void APointSymmetricImageStaysPointSymmetric(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 128, 128, (x, y) => PointSymmetric(x, y, 127 - x, 127 - y));
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f));
|
||||||
|
|
||||||
|
Assert.Equal((rendering.Left + rendering.Right, rendering.Top + rendering.Bottom), (source.Width, source.Height));
|
||||||
|
Assert.All(rendering.Coordinates(), point => Assert.True(WithinRounding(rendering[point.X, point.Y], rendering[source.Width - 1 - point.X, source.Height - 1 - point.Y]), $"({point.X}, {point.Y})"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(ShiftMode.Radial)]
|
||||||
|
[InlineData(ShiftMode.Rotational)]
|
||||||
|
public void TheCenterOffsetMovesThePointOfSymmetry(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 128, 128, (x, y) => PointSymmetric(x, y, 167 - x, 107 - y));
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f, Center: new Vector2(20f, -10f)));
|
||||||
|
|
||||||
|
var compared = 0;
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
var mirroredX = 167 - x;
|
||||||
|
var mirroredY = 107 - y;
|
||||||
|
if (DistanceToBorder(source, x, y) > 24 && source.Contains(mirroredX, mirroredY) && DistanceToBorder(source, mirroredX, mirroredY) > 24)
|
||||||
|
{
|
||||||
|
Assert.True(WithinRounding(rendering[x, y], rendering[mirroredX, mirroredY]), $"({x}, {y})");
|
||||||
|
compared++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(compared > 1000, $"{compared}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(ShiftMode.Linear, 100, 50)]
|
||||||
|
[InlineData(ShiftMode.Linear, -37, 21)]
|
||||||
|
[InlineData(ShiftMode.Radial, 100, 50)]
|
||||||
|
[InlineData(ShiftMode.Radial, -37, 21)]
|
||||||
|
[InlineData(ShiftMode.Rotational, 100, 50)]
|
||||||
|
[InlineData(ShiftMode.Rotational, -37, 21)]
|
||||||
|
public void TheShiftTravelsWithTheImage(ShiftMode mode, int dx, int dy)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
using var moved = new AffineTransform2D(context.DeviceContext)
|
||||||
|
{
|
||||||
|
InterPolationMode = AffineTransform2DInterpolationMode.NearestNeighbor,
|
||||||
|
BorderMode = BorderMode.Hard,
|
||||||
|
TransformMatrix = Matrix3x2.CreateTranslation(dx, dy),
|
||||||
|
};
|
||||||
|
moved.SetInput(0, source.Bitmap, true);
|
||||||
|
using var movedOutput = moved.Output;
|
||||||
|
var settings = Settings(Mode: mode, Distance: 16f, Angle: 30f, Center: new Vector2(6f, -4f));
|
||||||
|
|
||||||
|
var inPlace = Render(context, source, settings);
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
|
effect.SetSource(movedOutput, true);
|
||||||
|
settings.Apply(effect);
|
||||||
|
using var output = effect.Output;
|
||||||
|
var travelled = Rendering.Capture(context, output);
|
||||||
|
|
||||||
|
Assert.Equal((inPlace.Left + dx, inPlace.Top + dy, inPlace.Width, inPlace.Height), (travelled.Left, travelled.Top, travelled.Width, travelled.Height));
|
||||||
|
Assert.All(inPlace.Coordinates(), point => Assert.True(WithinRounding(inPlace[point.X, point.Y], travelled[point.X + dx, point.Y + dy]), $"({point.X}, {point.Y})"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheSpectrumSpillsOverTheEdgesInTheDirectionOfTheShift()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = SourceImage.Solid(context, 40, 24, Bgra.Opaque(255, 255, 255));
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Distance: 20f));
|
||||||
|
|
||||||
|
var left = rendering[-5, 12];
|
||||||
|
var right = rendering[44, 12];
|
||||||
|
Assert.True(left.Alpha > 100 && left.Red > left.Blue + 100, $"{left}");
|
||||||
|
Assert.True(right.Alpha > 100 && right.Blue > right.Red + 100, $"{right}");
|
||||||
|
Assert.True(rendering[rendering.Left, 12].Alpha <= 2 && rendering[rendering.Right - 1, 12].Alpha <= 2);
|
||||||
|
Assert.Equal(Bgra.Transparent, rendering[20, rendering.Top]);
|
||||||
|
Assert.Equal(Bgra.Transparent, rendering[20, rendering.Bottom - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PixelsBeyondTheReachOfTheDistanceStayUnchanged()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 32, HalfAndHalf);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Distance: 8f));
|
||||||
|
|
||||||
|
var checkedPixels = 0;
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
if (source.Contains(x, y) && Math.Abs(x + 0.5 - Seam) > 9 && DistanceToBorder(source, x, y) > 9 && y > 9 && y < 22)
|
||||||
|
{
|
||||||
|
Assert.True(WithinRounding(source[x, y], rendering[x, y]), $"({x}, {y})");
|
||||||
|
checkedPixels++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(checkedPixels > 100, $"{checkedPixels}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void ATransparentImageStaysTransparent(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = SourceImage.Solid(context, 48, 32, Bgra.Transparent);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 20f));
|
||||||
|
|
||||||
|
Assert.All(rendering.Coordinates(), point => Assert.Equal(Bgra.Transparent, rendering[point.X, point.Y]));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void EveryPixelIsAValidPremultipliedColor(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
|
||||||
|
var rendering = Render(context, source, Settings(Mode: mode, Distance: 24f, Strength: 0.8f));
|
||||||
|
|
||||||
|
Assert.All(rendering.Coordinates(), point =>
|
||||||
|
{
|
||||||
|
var pixel = rendering[point.X, point.Y];
|
||||||
|
Assert.True(pixel.Red <= pixel.Alpha + 1 && pixel.Green <= pixel.Alpha + 1 && pixel.Blue <= pixel.Alpha + 1, $"({point.X}, {point.Y}) {pixel}");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void AnOverbrightInputIsClampedToItsAlpha(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
var stride = 96 * SourceImage.BytesPerPixel;
|
||||||
|
var pixels = new byte[stride * 96];
|
||||||
|
for (var offset = 0; offset < pixels.Length; offset += SourceImage.BytesPerPixel)
|
||||||
|
{
|
||||||
|
pixels[offset + 2] = 255;
|
||||||
|
pixels[offset + 3] = 64;
|
||||||
|
}
|
||||||
|
|
||||||
|
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
|
||||||
|
bitmap.CopyFromMemory(pixels, stride);
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
|
effect.SetSource(bitmap, true);
|
||||||
|
Settings(Mode: mode, Distance: 12f).Apply(effect);
|
||||||
|
using var output = effect.Output;
|
||||||
|
|
||||||
|
var rendering = Rendering.Capture(context, output);
|
||||||
|
|
||||||
|
var interior = rendering[48, 48];
|
||||||
|
Assert.Equal(64, interior.Alpha);
|
||||||
|
Assert.True(interior.Red <= interior.Alpha && interior.Green <= interior.Alpha && interior.Blue <= interior.Alpha, $"{interior}");
|
||||||
|
Assert.True(interior.Red >= interior.Alpha - 1, $"{interior}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheSameSettingsAlwaysProduceTheSamePixels()
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
var settings = Settings(Mode: ShiftMode.Rotational, Distance: 18f, Dispersion: DispersionLaw.Prism);
|
||||||
|
|
||||||
|
var first = Render(context, source, settings);
|
||||||
|
var second = Render(context, source, settings);
|
||||||
|
|
||||||
|
Assert.True(first.SamePixelsAs(second));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Modes))]
|
||||||
|
public void TurningTheToggleOnAndOffRestoresTheLegacyImage(ShiftMode mode)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 64, 48, Textured);
|
||||||
|
var legacy = new ShiftSettings(Mode: mode, Distance: 14f);
|
||||||
|
var expected = Render(context, source, legacy);
|
||||||
|
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
|
effect.SetSource(source.Bitmap, true);
|
||||||
|
legacy.Apply(effect);
|
||||||
|
effect.Physical = 1;
|
||||||
|
using var output = effect.Output;
|
||||||
|
var physical = Rendering.Capture(context, output);
|
||||||
|
effect.Physical = 0;
|
||||||
|
var restored = Rendering.Capture(context, output);
|
||||||
|
|
||||||
|
Assert.Contains(physical.Coordinates(), point => physical[point.X, point.Y] != expected[point.X, point.Y]);
|
||||||
|
Assert.Equal((expected.Left, expected.Top, expected.Width, expected.Height), (restored.Left, restored.Top, restored.Width, restored.Height));
|
||||||
|
Assert.All(expected.Coordinates(), point => Assert.Equal(expected[point.X, point.Y], restored[point.X, point.Y]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using static SpectrumColorShift.SpectrumColorShiftCustomEffect;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
public sealed partial class SpectralShaderContractTests
|
||||||
|
{
|
||||||
|
static readonly Dictionary<string, string> Fields = new()
|
||||||
|
{
|
||||||
|
["inputBounds"] = "Header.InputBounds",
|
||||||
|
["direction"] = "Header.Direction",
|
||||||
|
["center"] = "Header.Center",
|
||||||
|
["shiftDistance"] = "Header.Distance",
|
||||||
|
["radius"] = "Header.Radius",
|
||||||
|
["strength"] = "Header.Strength",
|
||||||
|
["steps"] = "Header.Steps",
|
||||||
|
["spreadScale"] = "SpreadScale",
|
||||||
|
["filterOrigin"] = "FilterOrigin",
|
||||||
|
["filterVertical"] = "FilterVertical",
|
||||||
|
["samples"] = "Samples",
|
||||||
|
["taps"] = "Taps",
|
||||||
|
};
|
||||||
|
|
||||||
|
static string Source { get; } = ShaderSource("Physical.hlsli");
|
||||||
|
|
||||||
|
static string SrgbSource { get; } = ShaderSource("Srgb.hlsli");
|
||||||
|
|
||||||
|
static string ShaderSource(string name) => File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", name));
|
||||||
|
|
||||||
|
static string Here([CallerFilePath] string path = "") => path;
|
||||||
|
|
||||||
|
static Type ConstantBuffer => typeof(EffectImpl).GetNestedType("PhysicalConstantBuffer", BindingFlags.NonPublic)!;
|
||||||
|
|
||||||
|
[GeneratedRegex(@"static const (?:int|float) (?<name>\w+) = (?<value>[0-9.]+);")]
|
||||||
|
private static partial Regex ConstantPattern();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"Texture2D\s+LightTexture\s*:\s*register\(t(?<register>\d+)\)")]
|
||||||
|
private static partial Regex TexturePattern();
|
||||||
|
|
||||||
|
[GeneratedRegex(@"float4\s+\w+\s*:\s*TEXCOORD(?<index>\d+)")]
|
||||||
|
private static partial Regex CoordinatePattern();
|
||||||
|
|
||||||
|
static float Constant(string name) => Constant(Source, name);
|
||||||
|
|
||||||
|
static float Constant(string source, string name)
|
||||||
|
=> float.Parse(ConstantPattern().Matches(source).Single(match => match.Groups["name"].Value == name).Groups["value"].Value, CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheShaderAndTheEffectAgreeOnTheConstants()
|
||||||
|
{
|
||||||
|
Assert.Equal(Spectrum.SpectralTableLength, Constant("TableSize"));
|
||||||
|
Assert.Equal(SpectralFilter.TableLength, Constant("FilterTableSize"));
|
||||||
|
Assert.Equal((int)ShiftMode.Radial, Constant("ModeRadial"));
|
||||||
|
Assert.Equal((int)ShiftMode.Rotational, Constant("ModeRotational"));
|
||||||
|
Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheShaderReadsTheTextureOfTheLinearizedInput()
|
||||||
|
{
|
||||||
|
Assert.Equal(SpectrumColorShiftCustomEffect.LightInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheShaderDeclaresTheTextureCoordinateOfEveryInputUpToTheOneItReads()
|
||||||
|
{
|
||||||
|
var declared = CoordinatePattern().Matches(Source).Select(match => int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture));
|
||||||
|
|
||||||
|
Assert.Equal(Enumerable.Range(0, SpectrumColorShiftCustomEffect.LightInput + 1), declared.Order());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("SrgbDecodeThreshold", 0.04045f)]
|
||||||
|
[InlineData("SrgbEncodeThreshold", 0.0031308f)]
|
||||||
|
[InlineData("SrgbLowSlope", 12.92f)]
|
||||||
|
[InlineData("SrgbOffset", 0.055f)]
|
||||||
|
[InlineData("SrgbScale", 1.055f)]
|
||||||
|
[InlineData("SrgbExponent", 2.4f)]
|
||||||
|
public void TheSrgbHeaderHoldsTheStandardTransferConstants(string name, float expected)
|
||||||
|
=> Assert.Equal(expected, Constant(SrgbSource, name));
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheSrgbCurvesMeetAtTheThresholds()
|
||||||
|
{
|
||||||
|
var slope = Constant(SrgbSource, "SrgbLowSlope");
|
||||||
|
var linearEnd = Constant(SrgbSource, "SrgbEncodeThreshold");
|
||||||
|
var power = Constant(SrgbSource, "SrgbScale") * MathF.Pow(linearEnd, 1f / Constant(SrgbSource, "SrgbExponent")) - Constant(SrgbSource, "SrgbOffset");
|
||||||
|
|
||||||
|
Assert.Equal(Constant(SrgbSource, "SrgbDecodeThreshold"), slope * linearEnd, 1e-5f);
|
||||||
|
Assert.Equal(slope * linearEnd, power, 1e-5f);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheConstantBufferMatchesTheShaderLayout()
|
||||||
|
{
|
||||||
|
var members = ConstantBufferContract.Declared(Source);
|
||||||
|
|
||||||
|
Assert.Equal(Fields.Keys.Order(), members.Keys.Order());
|
||||||
|
Assert.All(members, member => Assert.Equal(member.Value, ConstantBufferContract.OffsetOf(ConstantBuffer, Fields[member.Key])));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheConstantBufferFillsWholeRegistersAndHoldsTheTable()
|
||||||
|
{
|
||||||
|
Assert.Equal(16 * (4 + Spectrum.SpectralTableLength + SpectralFilter.TableLength), ConstantBufferContract.SizeOf(ConstantBuffer));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
public sealed class SpectralSpectrumTests
|
||||||
|
{
|
||||||
|
static Vector4[] Table(int steps, float reference, DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = new Vector4[Spectrum.SpectralTableLength];
|
||||||
|
Spectrum.FillSpectral(table, steps, reference, law);
|
||||||
|
return table;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vector4 Gain(Vector4[] table, int index) => table[index * Spectrum.EntriesPerStep];
|
||||||
|
|
||||||
|
static Vector4 Basis(Vector4[] table, int index) => table[index * Spectrum.EntriesPerStep + 1];
|
||||||
|
|
||||||
|
static double Wavelength(int index, int steps) => 400d + 300d * index / (steps - 1);
|
||||||
|
|
||||||
|
static double Offset(DispersionLaw law, double wavelength, double reference)
|
||||||
|
=> law == DispersionLaw.Prism ? 1d / (wavelength * wavelength) - 1d / (reference * reference) : reference - wavelength;
|
||||||
|
|
||||||
|
static (double X, double Y, double Z) Integrate(Func<int, double> spectrum)
|
||||||
|
{
|
||||||
|
double x = 0d, y = 0d, z = 0d;
|
||||||
|
for (var index = 0; index < SpectralBasis.Count; index++)
|
||||||
|
{
|
||||||
|
var wavelength = SpectralBasis.First + SpectralBasis.Interval * index;
|
||||||
|
var (cx, cy, cz) = Spectrum.ColorMatching(wavelength);
|
||||||
|
var weight = spectrum(index) * SpectralBasis.IlluminantAt(wavelength) * (index == 0 || index == SpectralBasis.Count - 1 ? 0.5 : 1d);
|
||||||
|
x += weight * cx;
|
||||||
|
y += weight * cy;
|
||||||
|
z += weight * cz;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (x, y, z);
|
||||||
|
}
|
||||||
|
|
||||||
|
static double[] RgbOf(ReadOnlySpan<double> xyz, double[] white)
|
||||||
|
{
|
||||||
|
var primaries = new (double X, double Y)[] { (0.64, 0.33), (0.30, 0.60), (0.15, 0.06) };
|
||||||
|
var columns = primaries.Select(p => new[] { p.X / p.Y, 1d, (1d - p.X - p.Y) / p.Y }).ToArray();
|
||||||
|
var scale = Solve(columns, white);
|
||||||
|
var matrix = columns.Select((column, c) => column.Select(value => value * scale[c]).ToArray()).ToArray();
|
||||||
|
|
||||||
|
return Solve(matrix, xyz.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
static double[] Solve(double[][] columns, double[] target)
|
||||||
|
{
|
||||||
|
double[,] m = new double[3, 3];
|
||||||
|
for (var c = 0; c < 3; c++)
|
||||||
|
for (var r = 0; r < 3; r++)
|
||||||
|
m[r, c] = columns[c][r];
|
||||||
|
|
||||||
|
var det = m[0, 0] * (m[1, 1] * m[2, 2] - m[1, 2] * m[2, 1]) - m[0, 1] * (m[1, 0] * m[2, 2] - m[1, 2] * m[2, 0]) + m[0, 2] * (m[1, 0] * m[2, 1] - m[1, 1] * m[2, 0]);
|
||||||
|
var result = new double[3];
|
||||||
|
for (var c = 0; c < 3; c++)
|
||||||
|
{
|
||||||
|
var t = (double[,])m.Clone();
|
||||||
|
for (var r = 0; r < 3; r++)
|
||||||
|
t[r, c] = target[r];
|
||||||
|
|
||||||
|
result[c] = (t[0, 0] * (t[1, 1] * t[2, 2] - t[1, 2] * t[2, 1]) - t[0, 1] * (t[1, 0] * t[2, 2] - t[1, 2] * t[2, 0]) + t[0, 2] * (t[1, 0] * t[2, 1] - t[1, 1] * t[2, 0])) / det;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Vector3 BasisAt(int index) => SpectralBasis.At(SpectralBasis.First + SpectralBasis.Interval * index);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheIlluminantIsNormalizedTo100AtFiveHundredSixtyNanometers()
|
||||||
|
{
|
||||||
|
Assert.Equal(100d, SpectralBasis.IlluminantAt(560d), 1e-4);
|
||||||
|
Assert.Equal(82.7549d, SpectralBasis.IlluminantAt(400d), 1e-4);
|
||||||
|
Assert.Equal(71.6091d, SpectralBasis.IlluminantAt(700d), 1e-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheIlluminantHasTheChromaticityOfD65()
|
||||||
|
{
|
||||||
|
var (x, y, z) = Integrate(_ => 1d);
|
||||||
|
var sum = x + y + z;
|
||||||
|
|
||||||
|
Assert.Equal(0.3127d, x / sum, 1e-3);
|
||||||
|
Assert.Equal(0.3290d, y / sum, 1e-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheBasisSpectraAreNeverNegativeAndSumToOneAtEveryWavelength()
|
||||||
|
{
|
||||||
|
for (var index = 0; index < SpectralBasis.Count; index++)
|
||||||
|
{
|
||||||
|
var basis = BasisAt(index);
|
||||||
|
|
||||||
|
Assert.True(basis.X >= 0f && basis.Y >= 0f && basis.Z >= 0f, $"{index}");
|
||||||
|
Assert.Equal(1d, basis.X + basis.Y + basis.Z, 1e-6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0)]
|
||||||
|
[InlineData(1)]
|
||||||
|
[InlineData(2)]
|
||||||
|
public void TheBasisSpectraReproduceTheSrgbPrimaries(int channel)
|
||||||
|
{
|
||||||
|
var white = Integrate(_ => 1d);
|
||||||
|
var normalization = Integrate(_ => 1d).Y;
|
||||||
|
var whiteXyz = new[] { white.X / normalization, white.Y / normalization, white.Z / normalization };
|
||||||
|
var xyz = Integrate(index => channel switch { 0 => BasisAt(index).X, 1 => BasisAt(index).Y, _ => BasisAt(index).Z });
|
||||||
|
var rgb = RgbOf([xyz.X / normalization, xyz.Y / normalization, xyz.Z / normalization], whiteXyz);
|
||||||
|
|
||||||
|
for (var component = 0; component < 3; component++)
|
||||||
|
Assert.Equal(component == channel ? 1d : 0d, rgb[component], 1e-5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0, 600d, 700d)]
|
||||||
|
[InlineData(1, 500d, 580d)]
|
||||||
|
[InlineData(2, 400d, 480d)]
|
||||||
|
public void EachBasisSpectrumLivesInItsOwnPartOfTheSpectrum(int channel, double from, double to)
|
||||||
|
{
|
||||||
|
var peak = Enumerable.Range(0, SpectralBasis.Count)
|
||||||
|
.MaxBy(index => channel switch { 0 => BasisAt(index).X, 1 => BasisAt(index).Y, _ => BasisAt(index).Z });
|
||||||
|
|
||||||
|
Assert.InRange(SpectralBasis.First + SpectralBasis.Interval * peak, from, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheBasisIsSmoothEnoughForTheSampledSpectrum()
|
||||||
|
{
|
||||||
|
for (var channel = 0; channel < 3; channel++)
|
||||||
|
for (var index = 1; index < SpectralBasis.Count - 1; index++)
|
||||||
|
{
|
||||||
|
var before = BasisAt(index - 1);
|
||||||
|
var here = BasisAt(index);
|
||||||
|
var after = BasisAt(index + 1);
|
||||||
|
var bend = channel switch
|
||||||
|
{
|
||||||
|
0 => before.X - 2f * here.X + after.X,
|
||||||
|
1 => before.Y - 2f * here.Y + after.Y,
|
||||||
|
_ => before.Z - 2f * here.Z + after.Z,
|
||||||
|
};
|
||||||
|
|
||||||
|
Assert.InRange(Math.Abs(bend), 0f, 0.05f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheBasisInterpolatesLinearlyBetweenItsSamples()
|
||||||
|
{
|
||||||
|
var left = BasisAt(10);
|
||||||
|
var right = BasisAt(11);
|
||||||
|
var middle = SpectralBasis.At(SpectralBasis.First + SpectralBasis.Interval * 10.5);
|
||||||
|
|
||||||
|
Assert.Equal((left.X + right.X) / 2f, middle.X, 1e-6f);
|
||||||
|
Assert.Equal((left.Y + right.Y) / 2f, middle.Y, 1e-6f);
|
||||||
|
Assert.Equal((left.Z + right.Z) / 2f, middle.Z, 1e-6f);
|
||||||
|
Assert.Equal(BasisAt(0), SpectralBasis.At(100d));
|
||||||
|
Assert.Equal(BasisAt(SpectralBasis.Count - 1), SpectralBasis.At(900d));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(8, 550f, DispersionLaw.Grating)]
|
||||||
|
[InlineData(32, 550f, DispersionLaw.Grating)]
|
||||||
|
[InlineData(64, 550f, DispersionLaw.Grating)]
|
||||||
|
[InlineData(13, 400f, DispersionLaw.Prism)]
|
||||||
|
[InlineData(40, 700f, DispersionLaw.Prism)]
|
||||||
|
[InlineData(25, 620f, DispersionLaw.Prism)]
|
||||||
|
public void TheGainsAndTheBasisReproduceEveryColorWhenNothingMoves(int steps, float reference, DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = Table(steps, reference, law);
|
||||||
|
|
||||||
|
var identity = new double[3, 3];
|
||||||
|
for (var index = 0; index < steps; index++)
|
||||||
|
{
|
||||||
|
var gain = Gain(table, index);
|
||||||
|
var basis = Basis(table, index);
|
||||||
|
double[] g = [gain.X, gain.Y, gain.Z];
|
||||||
|
double[] b = [basis.X, basis.Y, basis.Z];
|
||||||
|
for (var row = 0; row < 3; row++)
|
||||||
|
for (var column = 0; column < 3; column++)
|
||||||
|
identity[row, column] += g[row] * b[column];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var row = 0; row < 3; row++)
|
||||||
|
for (var column = 0; column < 3; column++)
|
||||||
|
Assert.Equal(row == column ? 1d : 0d, identity[row, column], 2e-5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void EveryStepCountFromEightToSixtyFourReproducesWhiteAndKeepsTheCoverageNormalized()
|
||||||
|
{
|
||||||
|
for (var steps = Spectrum.MinSteps; steps <= Spectrum.MaxSteps; steps++)
|
||||||
|
{
|
||||||
|
var table = Table(steps, 550f, DispersionLaw.Grating);
|
||||||
|
var red = 0d;
|
||||||
|
var green = 0d;
|
||||||
|
var blue = 0d;
|
||||||
|
var coverage = 0d;
|
||||||
|
for (var index = 0; index < steps; index++)
|
||||||
|
{
|
||||||
|
var gain = Gain(table, index);
|
||||||
|
var basis = Basis(table, index);
|
||||||
|
var amplitude = basis.X + basis.Y + basis.Z;
|
||||||
|
red += gain.X * amplitude;
|
||||||
|
green += gain.Y * amplitude;
|
||||||
|
blue += gain.Z * amplitude;
|
||||||
|
coverage += gain.W;
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.True(Math.Abs(red - 1d) < 2e-5 && Math.Abs(green - 1d) < 2e-5 && Math.Abs(blue - 1d) < 2e-5, $"{steps} steps");
|
||||||
|
Assert.Equal(1d, coverage, 1e-5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(8)]
|
||||||
|
[InlineData(20)]
|
||||||
|
[InlineData(63)]
|
||||||
|
public void EntriesBeyondTheStepsAreCleared(int steps)
|
||||||
|
{
|
||||||
|
var table = Enumerable.Repeat(new Vector4(9f), Spectrum.SpectralTableLength).ToArray();
|
||||||
|
|
||||||
|
Spectrum.FillSpectral(table, steps, 550f, DispersionLaw.Grating);
|
||||||
|
|
||||||
|
Assert.All(table.Skip(steps * Spectrum.EntriesPerStep), entry => Assert.Equal(Vector4.Zero, entry));
|
||||||
|
Assert.All(table.Take(steps * Spectrum.EntriesPerStep), entry => Assert.NotEqual(new Vector4(9f), entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(DispersionLaw.Grating, 550f)]
|
||||||
|
[InlineData(DispersionLaw.Grating, 450f)]
|
||||||
|
[InlineData(DispersionLaw.Grating, 650f)]
|
||||||
|
[InlineData(DispersionLaw.Prism, 550f)]
|
||||||
|
[InlineData(DispersionLaw.Prism, 400f)]
|
||||||
|
[InlineData(DispersionLaw.Prism, 700f)]
|
||||||
|
public void TheShiftCoefficientFollowsTheDispersionLaw(DispersionLaw law, float reference)
|
||||||
|
{
|
||||||
|
const int steps = 24;
|
||||||
|
var table = Table(steps, reference, law);
|
||||||
|
var norm = Math.Max(Math.Abs(Offset(law, 400d, reference)), Math.Abs(Offset(law, 700d, reference)));
|
||||||
|
|
||||||
|
for (var index = 0; index < steps; index++)
|
||||||
|
Assert.Equal(Offset(law, Wavelength(index, steps), reference) / norm, Basis(table, index).W, 1e-5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(DispersionLaw.Grating, 550f, 1f, -1f)]
|
||||||
|
[InlineData(DispersionLaw.Grating, 650f, 1f, -0.2f)]
|
||||||
|
[InlineData(DispersionLaw.Grating, 450f, 0.2f, -1f)]
|
||||||
|
[InlineData(DispersionLaw.Grating, 400f, 0f, -1f)]
|
||||||
|
[InlineData(DispersionLaw.Grating, 700f, 1f, 0f)]
|
||||||
|
[InlineData(DispersionLaw.Prism, 700f, 1f, 0f)]
|
||||||
|
public void TheSpectrumEndsReachAtMostTheFullDistance(DispersionLaw law, float reference, float shortEnd, float longEnd)
|
||||||
|
{
|
||||||
|
var table = Table(16, reference, law);
|
||||||
|
|
||||||
|
Assert.Equal(shortEnd, Basis(table, 0).W, 1e-5);
|
||||||
|
Assert.Equal(longEnd, Basis(table, 15).W, 1e-5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(DispersionLaw.Grating)]
|
||||||
|
[InlineData(DispersionLaw.Prism)]
|
||||||
|
public void TheShiftCoefficientFallsAsTheWavelengthGrows(DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = Table(Spectrum.MaxSteps, 550f, law);
|
||||||
|
|
||||||
|
for (var index = 1; index < Spectrum.MaxSteps; index++)
|
||||||
|
Assert.True(Basis(table, index).W < Basis(table, index - 1).W, $"{index}");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(DispersionLaw.Grating)]
|
||||||
|
[InlineData(DispersionLaw.Prism)]
|
||||||
|
public void TheSampleAtTheReferenceWavelengthDoesNotMove(DispersionLaw law)
|
||||||
|
{
|
||||||
|
var table = Table(13, 550f, law);
|
||||||
|
|
||||||
|
Assert.Equal(0f, Basis(table, 6).W);
|
||||||
|
Assert.NotEqual(0f, Basis(table, 5).W);
|
||||||
|
Assert.NotEqual(0f, Basis(table, 7).W);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ThePrismLawSpreadsBlueMoreThanRed()
|
||||||
|
{
|
||||||
|
var table = Table(16, 550f, DispersionLaw.Prism);
|
||||||
|
|
||||||
|
Assert.InRange(-Basis(table, 15).W, 0.40f, 0.46f);
|
||||||
|
Assert.True(Basis(table, 0).W > -Basis(table, 15).W * 2f);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheTwoLawsGiveDifferentCoefficients()
|
||||||
|
{
|
||||||
|
var grating = Table(24, 550f, DispersionLaw.Grating);
|
||||||
|
var prism = Table(24, 550f, DispersionLaw.Prism);
|
||||||
|
|
||||||
|
Assert.NotEqual(Basis(grating, 5).W, Basis(prism, 5).W);
|
||||||
|
Assert.NotEqual(Basis(grating, 18).W, Basis(prism, 18).W);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheCoverageWeightsFollowTheLuminousEfficiency()
|
||||||
|
{
|
||||||
|
var table = Table(32, 550f, DispersionLaw.Grating);
|
||||||
|
var centroid = Enumerable.Range(0, 32).Sum(index => Wavelength(index, 32) * Gain(table, index).W);
|
||||||
|
|
||||||
|
Assert.InRange(centroid, 548d, 560d);
|
||||||
|
Assert.True(Gain(table, 0).W < Gain(table, 16).W / 100f);
|
||||||
|
Assert.True(Gain(table, 31).W < Gain(table, 16).W / 10f);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(300f, 400f)]
|
||||||
|
[InlineData(400f, 400f)]
|
||||||
|
[InlineData(550f, 550f)]
|
||||||
|
[InlineData(700f, 700f)]
|
||||||
|
[InlineData(900f, 700f)]
|
||||||
|
[InlineData(float.PositiveInfinity, 700f)]
|
||||||
|
[InlineData(float.NegativeInfinity, 400f)]
|
||||||
|
[InlineData(float.NaN, 550f)]
|
||||||
|
public void TheReferenceStaysWithinTheSpectrum(float requested, float expected)
|
||||||
|
{
|
||||||
|
Assert.Equal(expected, Spectrum.ClampReference(requested));
|
||||||
|
Assert.Equal(Table(16, expected, DispersionLaw.Grating), Table(16, requested, DispersionLaw.Grating));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(int.MinValue, 8)]
|
||||||
|
[InlineData(9, 12)]
|
||||||
|
[InlineData(33, 36)]
|
||||||
|
[InlineData(61, 64)]
|
||||||
|
[InlineData(int.MaxValue, 64)]
|
||||||
|
public void ThePaddedStepsAreWholeMultiplesOfTheStepQuantum(int requested, int expected)
|
||||||
|
{
|
||||||
|
Assert.Equal(expected, Spectrum.Padded(requested));
|
||||||
|
Assert.Equal(0, Spectrum.Padded(requested) % Spectrum.StepQuantum);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(int.MinValue, 8)]
|
||||||
|
[InlineData(7, 8)]
|
||||||
|
[InlineData(8, 8)]
|
||||||
|
[InlineData(40, 40)]
|
||||||
|
[InlineData(64, 64)]
|
||||||
|
[InlineData(65, 64)]
|
||||||
|
[InlineData(int.MaxValue, 64)]
|
||||||
|
public void TheStepsStayWithinTheirRange(int requested, int expected)
|
||||||
|
{
|
||||||
|
Assert.Equal(expected, Spectrum.ClampSteps(requested));
|
||||||
|
Assert.Equal(Table(expected, 550f, DispersionLaw.Grating), Table(requested, 550f, DispersionLaw.Grating));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,14 +10,14 @@ public sealed class SpectrumColorShiftCustomEffectTests
|
|||||||
{
|
{
|
||||||
const float MaxInputPixel = 4096f;
|
const float MaxInputPixel = 4096f;
|
||||||
|
|
||||||
static float Read(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.GetFloatValue((int)index);
|
static float Read(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.ReadFloat(index);
|
||||||
|
|
||||||
static int ReadInt(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.GetIntValue((int)index);
|
static int ReadInt(SpectrumColorShiftCustomEffect effect, PropertyIndex index) => effect.ReadInt(index);
|
||||||
|
|
||||||
static (float Left, float Top, float Right, float Bottom) Bounds(IGraphicsDevicesAndContext devices, SourceImage source, Action<SpectrumColorShiftCustomEffect> configure)
|
static (float Left, float Top, float Right, float Bottom) Bounds(IGraphicsDevicesAndContext devices, SourceImage source, Action<SpectrumColorShiftCustomEffect> configure)
|
||||||
{
|
{
|
||||||
using var effect = new SpectrumColorShiftCustomEffect(devices);
|
using var effect = new SpectrumColorShiftCustomEffect(devices);
|
||||||
effect.SetInput(0, source.Bitmap, true);
|
effect.SetSource(source.Bitmap, true);
|
||||||
configure(effect);
|
configure(effect);
|
||||||
using var output = effect.Output;
|
using var output = effect.Output;
|
||||||
var bounds = devices.DeviceContext.GetImageLocalBounds(output);
|
var bounds = devices.DeviceContext.GetImageLocalBounds(output);
|
||||||
@@ -318,7 +318,7 @@ public sealed class SpectrumColorShiftCustomEffectTests
|
|||||||
using var context = devices.CreateContext();
|
using var context = devices.CreateContext();
|
||||||
using var source = SourceImage.Solid(context, 40, 30, Bgra.Opaque(10, 20, 30));
|
using var source = SourceImage.Solid(context, 40, 30, Bgra.Opaque(10, 20, 30));
|
||||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
effect.SetInput(0, source.Bitmap, true);
|
effect.SetSource(source.Bitmap, true);
|
||||||
effect.Mode = (int)ShiftMode.Rotational;
|
effect.Mode = (int)ShiftMode.Rotational;
|
||||||
effect.Distance = MaxInputPixel;
|
effect.Distance = MaxInputPixel;
|
||||||
using var output = effect.Output;
|
using var output = effect.Output;
|
||||||
@@ -388,7 +388,7 @@ public sealed class SpectrumColorShiftCustomEffectTests
|
|||||||
crop.SetInput(0, source.Bitmap, true);
|
crop.SetInput(0, source.Bitmap, true);
|
||||||
using var cropped = crop.Output;
|
using var cropped = crop.Output;
|
||||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
effect.SetInput(0, cropped, true);
|
effect.SetSource(cropped, true);
|
||||||
effect.Mode = (int)mode;
|
effect.Mode = (int)mode;
|
||||||
effect.Distance = 3f;
|
effect.Distance = 3f;
|
||||||
using var output = effect.Output;
|
using var output = effect.Output;
|
||||||
|
|||||||
@@ -69,6 +69,30 @@ public sealed class SpectrumColorShiftEffectImplTests
|
|||||||
Assert.Equal(new RawRect(-7, -2, 57, 52), requested);
|
Assert.Equal(new RawRect(-7, -2, 57, 52), requested);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheLegacyShaderRequestsOnlyTheSourceInput()
|
||||||
|
{
|
||||||
|
var impl = new EffectImpl { Distance = 5f };
|
||||||
|
Map(impl, new RawRect(0, 0, 40, 24));
|
||||||
|
var inputs = new RawRect[2];
|
||||||
|
|
||||||
|
impl.MapOutputRectToInputRects(new RawRect(0, 0, 50, 50), inputs);
|
||||||
|
|
||||||
|
Assert.Equal([new RawRect(-7, -2, 57, 52), default], inputs);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ThePhysicalShaderRequestsOnlyTheLinearizedInput()
|
||||||
|
{
|
||||||
|
var impl = new EffectImpl { Distance = 5f, Physical = 1 };
|
||||||
|
Map(impl, new RawRect(0, 0, 40, 24));
|
||||||
|
var inputs = new RawRect[2];
|
||||||
|
|
||||||
|
impl.MapOutputRectToInputRects(new RawRect(0, 0, 50, 50), inputs);
|
||||||
|
|
||||||
|
Assert.Equal([default, new RawRect(-7, -2, 57, 52)], inputs);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ANoInputRequestIsIgnored()
|
public void ANoInputRequestIsIgnored()
|
||||||
{
|
{
|
||||||
@@ -89,6 +113,44 @@ public sealed class SpectrumColorShiftEffectImplTests
|
|||||||
Assert.Equal(new RawRect(-12, -2, 52, 26), invalid);
|
Assert.Equal(new RawRect(-12, -2, 52, 26), invalid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0f, 8f, 1, ShiftMode.Linear, true)]
|
||||||
|
[InlineData(90f, 8f, 1, ShiftMode.Linear, true)]
|
||||||
|
[InlineData(180f, -6f, 1, ShiftMode.Linear, true)]
|
||||||
|
[InlineData(45f, 8f, 1, ShiftMode.Linear, false)]
|
||||||
|
[InlineData(0f, 40f, 1, ShiftMode.Linear, false)]
|
||||||
|
[InlineData(0f, 0f, 1, ShiftMode.Linear, false)]
|
||||||
|
[InlineData(0f, 8f, 1, ShiftMode.Radial, false)]
|
||||||
|
[InlineData(0f, 8f, 1, ShiftMode.Rotational, false)]
|
||||||
|
[InlineData(0f, 8f, 0, ShiftMode.Linear, false)]
|
||||||
|
public void TheFilterIsUsedOnlyForAnAxisAlignedPhysicalShiftThatIsShortEnough(float angle, float distance, int physical, ShiftMode mode, bool used)
|
||||||
|
{
|
||||||
|
var impl = new EffectImpl { Mode = (int)mode, Angle = angle, Distance = distance, Physical = physical };
|
||||||
|
|
||||||
|
Assert.Equal(used, impl.FilterTaps > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TheFilterFollowsTheSettingsThatChangeIt()
|
||||||
|
{
|
||||||
|
var impl = new EffectImpl { Physical = 1, Distance = 8f };
|
||||||
|
Assert.True(impl.FilterTaps > 0);
|
||||||
|
|
||||||
|
impl.Angle = 30f;
|
||||||
|
Assert.Equal(0, impl.FilterTaps);
|
||||||
|
|
||||||
|
impl.Angle = 0f;
|
||||||
|
impl.Distance = 60f;
|
||||||
|
Assert.Equal(0, impl.FilterTaps);
|
||||||
|
|
||||||
|
impl.Distance = 8f;
|
||||||
|
impl.Steps = 8;
|
||||||
|
Assert.Equal(0, impl.FilterTaps);
|
||||||
|
|
||||||
|
impl.Steps = 32;
|
||||||
|
Assert.True(impl.FilterTaps > 0);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void EveryPropertyCanBeSetBeforeTheEffectIsDrawn()
|
public void EveryPropertyCanBeSetBeforeTheEffectIsDrawn()
|
||||||
{
|
{
|
||||||
@@ -103,6 +165,7 @@ public sealed class SpectrumColorShiftEffectImplTests
|
|||||||
Dispersion = (int)DispersionLaw.Prism,
|
Dispersion = (int)DispersionLaw.Prism,
|
||||||
ReferenceWavelength = 480f,
|
ReferenceWavelength = 480f,
|
||||||
Steps = 16,
|
Steps = 16,
|
||||||
|
Physical = 1,
|
||||||
};
|
};
|
||||||
|
|
||||||
Assert.Equal(12f, impl.Distance);
|
Assert.Equal(12f, impl.Distance);
|
||||||
@@ -114,5 +177,6 @@ public sealed class SpectrumColorShiftEffectImplTests
|
|||||||
Assert.Equal((int)DispersionLaw.Prism, impl.Dispersion);
|
Assert.Equal((int)DispersionLaw.Prism, impl.Dispersion);
|
||||||
Assert.Equal(480f, impl.ReferenceWavelength);
|
Assert.Equal(480f, impl.ReferenceWavelength);
|
||||||
Assert.Equal(16, impl.Steps);
|
Assert.Equal(16, impl.Steps);
|
||||||
|
Assert.Equal(1, impl.Physical);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,7 +228,7 @@ public sealed class SpectrumColorShiftEffectProcessorTests
|
|||||||
using var processor = effect.CreateVideoEffect(context);
|
using var processor = effect.CreateVideoEffect(context);
|
||||||
processor.SetInput(source.Bitmap);
|
processor.SetInput(source.Bitmap);
|
||||||
using var direct = new SpectrumColorShiftCustomEffect(context);
|
using var direct = new SpectrumColorShiftCustomEffect(context);
|
||||||
direct.SetInput(0, source.Bitmap, true);
|
direct.SetSource(source.Bitmap, true);
|
||||||
direct.Distance = 14.5f;
|
direct.Distance = 14.5f;
|
||||||
direct.Mode = (int)ShiftMode.Rotational;
|
direct.Mode = (int)ShiftMode.Rotational;
|
||||||
direct.Angle = 33f;
|
direct.Angle = 33f;
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ internal sealed record ShiftSettings(
|
|||||||
float Strength = 1f,
|
float Strength = 1f,
|
||||||
DispersionLaw Dispersion = DispersionLaw.Grating,
|
DispersionLaw Dispersion = DispersionLaw.Grating,
|
||||||
float ReferenceWavelength = 550f,
|
float ReferenceWavelength = 550f,
|
||||||
int Steps = 32)
|
int Steps = 32,
|
||||||
|
bool Physical = false)
|
||||||
{
|
{
|
||||||
public void Apply(SpectrumColorShiftCustomEffect effect)
|
public void Apply(SpectrumColorShiftCustomEffect effect)
|
||||||
{
|
{
|
||||||
@@ -23,6 +24,7 @@ internal sealed record ShiftSettings(
|
|||||||
effect.Dispersion = (int)Dispersion;
|
effect.Dispersion = (int)Dispersion;
|
||||||
effect.ReferenceWavelength = ReferenceWavelength;
|
effect.ReferenceWavelength = ReferenceWavelength;
|
||||||
effect.Steps = Steps;
|
effect.Steps = Steps;
|
||||||
|
effect.Physical = Physical ? 1 : 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ public sealed class SpectrumColorShiftRenderingTests
|
|||||||
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
|
static Rendering Render(IGraphicsDevicesAndContext devices, SourceImage source, ShiftSettings settings)
|
||||||
{
|
{
|
||||||
using var effect = new SpectrumColorShiftCustomEffect(devices);
|
using var effect = new SpectrumColorShiftCustomEffect(devices);
|
||||||
effect.SetInput(0, source.Bitmap, true);
|
effect.SetSource(source.Bitmap, true);
|
||||||
settings.Apply(effect);
|
settings.Apply(effect);
|
||||||
using var output = effect.Output;
|
using var output = effect.Output;
|
||||||
|
|
||||||
@@ -476,7 +476,7 @@ public sealed class SpectrumColorShiftRenderingTests
|
|||||||
|
|
||||||
var inPlace = Render(context, source, settings);
|
var inPlace = Render(context, source, settings);
|
||||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
effect.SetInput(0, movedOutput, true);
|
effect.SetSource(movedOutput, true);
|
||||||
settings.Apply(effect);
|
settings.Apply(effect);
|
||||||
using var output = effect.Output;
|
using var output = effect.Output;
|
||||||
var travelled = Rendering.Capture(context, output);
|
var travelled = Rendering.Capture(context, output);
|
||||||
@@ -572,7 +572,7 @@ public sealed class SpectrumColorShiftRenderingTests
|
|||||||
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
|
using var bitmap = context.DeviceContext.CreateBitmap(new SizeI(96, 96), nint.Zero, stride, new BitmapProperties1(SourceImage.PixelFormat, SourceImage.Dpi, SourceImage.Dpi, BitmapOptions.None));
|
||||||
bitmap.CopyFromMemory(pixels, stride);
|
bitmap.CopyFromMemory(pixels, stride);
|
||||||
using var effect = new SpectrumColorShiftCustomEffect(context);
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
effect.SetInput(0, bitmap, true);
|
effect.SetSource(bitmap, true);
|
||||||
new ShiftSettings(Mode: mode, Distance: 12f).Apply(effect);
|
new ShiftSettings(Mode: mode, Distance: 12f).Apply(effect);
|
||||||
using var output = effect.Output;
|
using var output = effect.Output;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
internal static class Srgb
|
||||||
|
{
|
||||||
|
public static double Decode(double encoded)
|
||||||
|
=> encoded <= 0.04045 ? encoded / 12.92 : Math.Pow((encoded + 0.055) / 1.055, 2.4);
|
||||||
|
|
||||||
|
public static double Encode(double linear)
|
||||||
|
=> linear <= 0.0031308 ? linear * 12.92 : 1.055 * Math.Pow(linear, 1d / 2.4) - 0.055;
|
||||||
|
|
||||||
|
public static Vector3 Decode(Vector3 encoded)
|
||||||
|
=> new((float)Decode(encoded.X), (float)Decode(encoded.Y), (float)Decode(encoded.Z));
|
||||||
|
|
||||||
|
public static Vector3 Encode(Vector3 linear)
|
||||||
|
=> new((float)Encode(linear.X), (float)Encode(linear.Y), (float)Encode(linear.Z));
|
||||||
|
|
||||||
|
public static Vector4 DecodePremultiplied(Vector4 encoded)
|
||||||
|
=> encoded.W <= 0f ? Vector4.Zero : new Vector4(Decode(Straight(encoded)) * encoded.W, encoded.W);
|
||||||
|
|
||||||
|
public static Vector4 EncodePremultiplied(Vector4 linear)
|
||||||
|
=> linear.W <= 0f ? Vector4.Zero : new Vector4(Encode(Straight(linear)) * linear.W, linear.W);
|
||||||
|
|
||||||
|
static Vector3 Straight(Vector4 premultiplied)
|
||||||
|
=> Vector3.Clamp(new Vector3(premultiplied.X, premultiplied.Y, premultiplied.Z) / premultiplied.W, Vector3.Zero, Vector3.One);
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift.Tests;
|
||||||
|
|
||||||
|
[Collection("Direct2D")]
|
||||||
|
public sealed class StepCountRenderingTests
|
||||||
|
{
|
||||||
|
public static readonly TheoryData<ShiftMode, bool> Cases = [.. from physical in new[] { false, true } from mode in new[] { ShiftMode.Linear, ShiftMode.Radial, ShiftMode.Rotational } select (mode, physical)];
|
||||||
|
|
||||||
|
static Bgra Gradient(int x, int y)
|
||||||
|
{
|
||||||
|
if ((x / 6 + y / 6) % 4 == 3)
|
||||||
|
return Bgra.Transparent;
|
||||||
|
|
||||||
|
return new Bgra((byte)(30 + x * 4 % 220), (byte)(20 + y * 7 % 230), (byte)(250 - (x + y) * 3 % 200), (byte)(120 + (x * 5 + y * 9) % 136));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Cases))]
|
||||||
|
public void EveryStepCountMatchesTheCpuRendering(ShiftMode mode, bool physical)
|
||||||
|
{
|
||||||
|
using var devices = new GraphicsDevices();
|
||||||
|
using var context = devices.CreateContext();
|
||||||
|
using var source = new SourceImage(context, 48, 32, Gradient);
|
||||||
|
using var effect = new SpectrumColorShiftCustomEffect(context);
|
||||||
|
effect.SetSource(source.Bitmap, true);
|
||||||
|
using var output = effect.Output;
|
||||||
|
|
||||||
|
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
|
||||||
|
{
|
||||||
|
var settings = new ShiftSettings(Mode: mode, Distance: 16f, Angle: 30f, Steps: steps, Physical: physical);
|
||||||
|
settings.Apply(effect);
|
||||||
|
Func<int, int, Vector4> reference = physical ? new SpectralReferenceRenderer(source, settings).Pixel : new ShiftReferenceRenderer(source, settings).Pixel;
|
||||||
|
|
||||||
|
var rendering = Rendering.Capture(context, output);
|
||||||
|
|
||||||
|
foreach (var (x, y) in rendering.Coordinates())
|
||||||
|
{
|
||||||
|
var expected = reference(x, y) * 255f;
|
||||||
|
var actual = rendering[x, y];
|
||||||
|
Assert.True(
|
||||||
|
Math.Abs(expected.X - actual.Red) <= 2f && Math.Abs(expected.Y - actual.Green) <= 2f && Math.Abs(expected.Z - actual.Blue) <= 2f && Math.Abs(expected.W - actual.Alpha) <= 2f,
|
||||||
|
$"steps {steps}, ({x}, {y}) expected {expected}, actual {actual}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -46,7 +46,7 @@ public sealed class TextsTests
|
|||||||
{
|
{
|
||||||
var neutral = Texts.ResourceManager.GetString(nameof(Texts.SpectrumColorShift), CultureInfo.InvariantCulture);
|
var neutral = Texts.ResourceManager.GetString(nameof(Texts.SpectrumColorShift), CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
Assert.Equal("色ずれ(スペクトラム)", neutral);
|
Assert.Equal("色ズレ(スペクトラム)", neutral);
|
||||||
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.SpectrumColorShift), CultureInfo.GetCultureInfo("ja-JP")));
|
Assert.Equal(neutral, Texts.ResourceManager.GetString(nameof(Texts.SpectrumColorShift), CultureInfo.GetCultureInfo("ja-JP")));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
using Vortice.Direct2D1;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
using YukkuriMovieMaker.Player.Video;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal sealed class LinearizeCustomEffect : D2D1CustomShaderEffectBase
|
||||||
|
{
|
||||||
|
public LinearizeCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices))
|
||||||
|
{
|
||||||
|
if (IsEnabled)
|
||||||
|
SetValue((int)Property.Precision, BufferPrecision.PerChannel16Float);
|
||||||
|
}
|
||||||
|
|
||||||
|
[CustomEffect(1)]
|
||||||
|
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||||
|
{
|
||||||
|
public EffectImpl() : base(ShaderResourceUri.Get("SpectrumColorShiftLinearize"))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void UpdateConstants()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal static class Quantum
|
||||||
|
{
|
||||||
|
public static int RoundUp(int value, int quantum) => (value + quantum - 1) / quantum * quantum;
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
using Vortice.Direct2D1;
|
||||||
|
using YukkuriMovieMaker.Commons;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal sealed class ShaderFamily
|
||||||
|
{
|
||||||
|
private readonly string _name;
|
||||||
|
private readonly int _minimum;
|
||||||
|
private readonly int _maximum;
|
||||||
|
private readonly int _quantum;
|
||||||
|
private readonly int _length;
|
||||||
|
private readonly Guid[] _ids;
|
||||||
|
private readonly Lazy<byte[]>[] _bytes;
|
||||||
|
|
||||||
|
public ShaderFamily(string name, IReadOnlyList<ShiftMode> modes, int minimum, int maximum, int quantum)
|
||||||
|
{
|
||||||
|
_name = name;
|
||||||
|
Modes = modes;
|
||||||
|
_minimum = minimum;
|
||||||
|
_maximum = maximum;
|
||||||
|
_quantum = quantum;
|
||||||
|
_length = (maximum - minimum) / quantum + 1;
|
||||||
|
_ids = [.. Enumerable.Range(0, modes.Count * _length).Select(_ => Guid.NewGuid())];
|
||||||
|
_bytes = [.. Enumerable.Range(0, modes.Count * _length).Select(index => new Lazy<byte[]>(() => Read(index)))];
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<ShiftMode> Modes { get; }
|
||||||
|
|
||||||
|
public IEnumerable<int> Counts => Enumerable.Range(0, _length).Select(CountAt);
|
||||||
|
|
||||||
|
public string ResourceName(ShiftMode mode, int count) => $"{_name}{mode}{count}";
|
||||||
|
|
||||||
|
public Guid Id(ShiftMode mode, int count) => _ids[IndexOf(mode, count)];
|
||||||
|
|
||||||
|
public byte[] Bytes(ShiftMode mode, int count) => _bytes[IndexOf(mode, count)].Value;
|
||||||
|
|
||||||
|
public void LoadAll(ID2D1EffectContext effectContext)
|
||||||
|
{
|
||||||
|
for (var index = 0; index < _ids.Length; index++)
|
||||||
|
{
|
||||||
|
var bytes = _bytes[index].Value;
|
||||||
|
effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int CountAt(int index) => _minimum + index * _quantum;
|
||||||
|
|
||||||
|
private int IndexOf(ShiftMode mode, int count)
|
||||||
|
{
|
||||||
|
var offset = Quantum.RoundUp(Math.Clamp(count, _minimum, _maximum) - _minimum, _quantum) / _quantum;
|
||||||
|
|
||||||
|
return IndexOfMode(mode) * _length + offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int IndexOfMode(ShiftMode mode)
|
||||||
|
{
|
||||||
|
for (var index = 0; index < Modes.Count; index++)
|
||||||
|
{
|
||||||
|
if (Modes[index] == mode)
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(mode), mode, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] Read(int index)
|
||||||
|
=> PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(ResourceName(Modes[index / _length], CountAt(index % _length))));
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using Vortice.Direct2D1;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal static class ShaderVariants
|
||||||
|
{
|
||||||
|
public static ShaderFamily Legacy { get; } = new("SpectrumColorShift", Enum.GetValues<ShiftMode>(), Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum);
|
||||||
|
|
||||||
|
public static ShaderFamily Physical { get; } = new("SpectrumColorShiftPhysical", Enum.GetValues<ShiftMode>(), Spectrum.MinSteps, Spectrum.MaxSteps, Spectrum.StepQuantum);
|
||||||
|
|
||||||
|
public static ShaderFamily Filter { get; } = new("SpectrumColorShiftPhysicalFilter", [ShiftMode.Linear], SpectralFilter.TapQuantum, SpectralFilter.MaxTaps, SpectralFilter.TapQuantum);
|
||||||
|
|
||||||
|
public static byte[] DefaultBytes => Legacy.Bytes(ShiftMode.Linear, Spectrum.DefaultSteps);
|
||||||
|
|
||||||
|
public static ShaderFamily Stepped(bool physical) => physical ? Physical : Legacy;
|
||||||
|
|
||||||
|
public static void LoadAll(ID2D1EffectContext effectContext)
|
||||||
|
{
|
||||||
|
Legacy.LoadAll(effectContext);
|
||||||
|
Physical.LoadAll(effectContext);
|
||||||
|
Filter.LoadAll(effectContext);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal static class SpectralBasis
|
||||||
|
{
|
||||||
|
public const double First = 400.0;
|
||||||
|
public const double Interval = 5.0;
|
||||||
|
public const int Count = 61;
|
||||||
|
|
||||||
|
private static ReadOnlySpan<float> Red =>
|
||||||
|
[
|
||||||
|
0.192512361f, 0.16935988f, 0.146196031f, 0.123059145f, 0.100109343f, 0.0777127425f, 0.0564703934f, 0.0371695051f,
|
||||||
|
0.0207353365f, 0.00830780452f, 0.00137841186f, 7.5479875e-07f, 9.01286255e-07f, 1.06360691e-06f, 5.45645767e-07f, 3.57413785e-07f,
|
||||||
|
2.57572257e-07f, 2.02100568e-07f, 1.641348e-07f, 1.31969263e-07f, 1.0800669e-07f, 9.0420405e-08f, 7.66890265e-08f, 6.68081003e-08f,
|
||||||
|
5.99273434e-08f, 5.42758659e-08f, 4.43178079e-08f, 4.17441579e-08f, 4.91125451e-08f, 5.06339275e-08f, 4.67123455e-08f, 6.02243933e-08f,
|
||||||
|
3.32734569e-08f, 0.00218982151f, 0.0301830399f, 0.0943962603f, 0.194844971f, 0.323868219f, 0.468912693f, 0.615343668f,
|
||||||
|
0.748929449f, 0.858055159f, 0.935683229f, 0.980840619f, 0.99893757f, 0.999999877f, 0.999999636f, 0.999999509f,
|
||||||
|
0.999999413f, 0.999999252f, 0.999999011f, 0.999998673f, 0.999998148f, 0.999997337f, 0.99999599f, 0.999993519f,
|
||||||
|
0.99998865f, 0.999971924f, 0.99992753f, 0.999857504f, 0.99977574f,
|
||||||
|
];
|
||||||
|
|
||||||
|
private static ReadOnlySpan<float> Green =>
|
||||||
|
[
|
||||||
|
1.81116187e-05f, 4.76598665e-06f, 2.06583504e-06f, 1.14787887e-06f, 7.01859312e-07f, 4.9802927e-07f, 3.91446971e-07f, 2.9659085e-07f,
|
||||||
|
2.51710459e-07f, 1.52383012e-07f, 9.82642489e-08f, 0.0030716171f, 0.0200009702f, 0.0564915036f, 0.114178186f, 0.191829222f,
|
||||||
|
0.285986432f, 0.391619914f, 0.502778259f, 0.613202335f, 0.716844931f, 0.808340572f, 0.883459214f, 0.939549555f,
|
||||||
|
0.975987013f, 0.994593092f, 0.999999794f, 0.999999852f, 0.999999666f, 0.99999969f, 0.999999848f, 0.999548594f,
|
||||||
|
0.992259651f, 0.973278248f, 0.929308352f, 0.85554009f, 0.753853787f, 0.631069348f, 0.497157023f, 0.363430426f,
|
||||||
|
0.240949244f, 0.139096042f, 0.0643157669f, 0.0191591542f, 0.00106195131f, 4.56685713e-08f, 1.58152571e-07f, 2.22023037e-07f,
|
||||||
|
2.65629655e-07f, 3.38276201e-07f, 4.47483004e-07f, 6.00414965e-07f, 8.37904682e-07f, 1.20521489e-06f, 1.81520325e-06f, 2.94309258e-06f,
|
||||||
|
5.13254026e-06f, 1.23204315e-05f, 3.2743966e-05f, 6.68620547e-05f, 0.000107581877f,
|
||||||
|
];
|
||||||
|
|
||||||
|
private static ReadOnlySpan<float> Blue =>
|
||||||
|
[
|
||||||
|
0.807469527f, 0.830635354f, 0.853801904f, 0.876939707f, 0.899889955f, 0.92228676f, 0.943529215f, 0.962830198f,
|
||||||
|
0.979264412f, 0.991692043f, 0.99862149f, 0.996927628f, 0.979998128f, 0.943507433f, 0.885821269f, 0.808170421f,
|
||||||
|
0.71401331f, 0.608379884f, 0.497221577f, 0.386797533f, 0.283154961f, 0.191659337f, 0.11654071f, 0.0604503786f,
|
||||||
|
0.0240129266f, 0.00540685411f, 1.61548711e-07f, 1.06184152e-07f, 2.84808058e-07f, 2.59130901e-07f, 1.04914227e-07f, 0.000451346134f,
|
||||||
|
0.00774031585f, 0.0245319302f, 0.0405086082f, 0.0500636496f, 0.051301242f, 0.0450624333f, 0.0339302845f, 0.021225906f,
|
||||||
|
0.0101213068f, 0.00284879946f, 1.00408131e-06f, 2.26836029e-07f, 4.78697571e-07f, 7.77024557e-08f, 2.06003424e-07f, 2.68621395e-07f,
|
||||||
|
3.21384151e-07f, 4.09280481e-07f, 5.4140573e-07f, 7.26436417e-07f, 1.01373333e-06f, 1.45801888e-06f, 2.19525189e-06f, 3.5375357e-06f,
|
||||||
|
6.21747073e-06f, 1.57553175e-05f, 3.9726355e-05f, 7.56335619e-05f, 0.000116677997f,
|
||||||
|
];
|
||||||
|
|
||||||
|
private static ReadOnlySpan<float> D65 =>
|
||||||
|
[
|
||||||
|
82.7549f, 87.1204f, 91.486f, 92.4589f, 93.4318f, 90.057f, 86.6823f, 95.7736f,
|
||||||
|
104.865f, 110.936f, 117.008f, 117.41f, 117.812f, 116.336f, 114.861f, 115.392f,
|
||||||
|
115.923f, 112.367f, 108.811f, 109.082f, 109.354f, 108.578f, 107.802f, 106.296f,
|
||||||
|
104.79f, 106.239f, 107.689f, 106.047f, 104.405f, 104.225f, 104.046f, 102.023f,
|
||||||
|
100f, 98.1671f, 96.3342f, 96.0611f, 95.788f, 92.2368f, 88.6856f, 89.3459f,
|
||||||
|
90.0062f, 89.8026f, 89.5991f, 88.6489f, 87.6987f, 85.4936f, 83.2886f, 83.4939f,
|
||||||
|
83.6992f, 81.863f, 80.0268f, 80.1207f, 80.2146f, 81.2462f, 82.2778f, 80.281f,
|
||||||
|
78.2842f, 74.0027f, 69.7213f, 70.6652f, 71.6091f,
|
||||||
|
];
|
||||||
|
|
||||||
|
public static Vector3 At(double wavelength)
|
||||||
|
{
|
||||||
|
var (index, fraction) = Locate(wavelength);
|
||||||
|
|
||||||
|
return new Vector3(
|
||||||
|
Lerp(Red, index, fraction),
|
||||||
|
Lerp(Green, index, fraction),
|
||||||
|
Lerp(Blue, index, fraction));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static double IlluminantAt(double wavelength)
|
||||||
|
{
|
||||||
|
var (index, fraction) = Locate(wavelength);
|
||||||
|
|
||||||
|
return Lerp(D65, index, fraction);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static (int Index, float Fraction) Locate(double wavelength)
|
||||||
|
{
|
||||||
|
var position = Math.Clamp((wavelength - First) / Interval, 0.0, Count - 1);
|
||||||
|
var index = Math.Min((int)position, Count - 2);
|
||||||
|
|
||||||
|
return (index, (float)(position - index));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static float Lerp(ReadOnlySpan<float> table, int index, float fraction)
|
||||||
|
=> table[index] + (table[index + 1] - table[index]) * fraction;
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal static class SpectralFilter
|
||||||
|
{
|
||||||
|
public const int EntriesPerTap = 3;
|
||||||
|
public const int TapQuantum = 4;
|
||||||
|
public const int MaxTaps = 44;
|
||||||
|
public const int TableLength = MaxTaps * EntriesPerTap;
|
||||||
|
public const float MaxTapShare = 0.65f;
|
||||||
|
|
||||||
|
private const float AxisTolerance = 1e-5f;
|
||||||
|
private const int Channels = 3;
|
||||||
|
private const int ValuesPerTap = Channels * Channels + 1;
|
||||||
|
|
||||||
|
public readonly record struct Layout(int Taps, int Origin, bool Vertical);
|
||||||
|
|
||||||
|
private readonly record struct Placement(int Floor, double Fraction);
|
||||||
|
|
||||||
|
public static Layout Fill(Span<Vector4> table, ReadOnlySpan<Vector4> spectral, int steps, float distance, Vector2 direction)
|
||||||
|
{
|
||||||
|
if (distance == 0f || !TryAxis(direction, out var vertical, out var along))
|
||||||
|
return default;
|
||||||
|
|
||||||
|
steps = Spectrum.ClampSteps(steps);
|
||||||
|
Span<Placement> placements = stackalloc Placement[Spectrum.MaxSteps];
|
||||||
|
var layout = Plan(spectral, steps, distance * along, vertical, placements);
|
||||||
|
if (layout.Taps == 0)
|
||||||
|
return default;
|
||||||
|
|
||||||
|
Span<double> sums = stackalloc double[layout.Taps * ValuesPerTap];
|
||||||
|
sums.Clear();
|
||||||
|
for (var step = 0; step < steps; step++)
|
||||||
|
{
|
||||||
|
var spectralStep = SpectralStep.Read(spectral, step);
|
||||||
|
var placement = placements[step];
|
||||||
|
Add(sums, placement.Floor - layout.Origin, 1d - placement.Fraction, spectralStep);
|
||||||
|
Add(sums, placement.Floor + 1 - layout.Origin, placement.Fraction, spectralStep);
|
||||||
|
}
|
||||||
|
|
||||||
|
Write(table, sums, layout.Taps);
|
||||||
|
|
||||||
|
return layout;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Layout Plan(ReadOnlySpan<Vector4> spectral, int steps, float signedDistance, bool vertical, Span<Placement> placements)
|
||||||
|
{
|
||||||
|
var low = int.MaxValue;
|
||||||
|
var high = int.MinValue;
|
||||||
|
for (var step = 0; step < steps; step++)
|
||||||
|
{
|
||||||
|
var offset = -(double)SpectralStep.Read(spectral, step).Displacement * signedDistance;
|
||||||
|
var floor = (int)Math.Floor(offset);
|
||||||
|
placements[step] = new Placement(floor, offset - floor);
|
||||||
|
low = Math.Min(low, floor);
|
||||||
|
high = Math.Max(high, floor + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
var taps = Quantum.RoundUp(high - low + 1, TapQuantum);
|
||||||
|
|
||||||
|
return taps <= MaxTaps && taps <= Spectrum.Padded(steps) * MaxTapShare ? new Layout(taps, low, vertical) : default;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryAxis(Vector2 direction, out bool vertical, out float along)
|
||||||
|
{
|
||||||
|
vertical = false;
|
||||||
|
along = direction.X;
|
||||||
|
if (MathF.Abs(direction.Y) <= AxisTolerance)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
vertical = true;
|
||||||
|
along = direction.Y;
|
||||||
|
return MathF.Abs(direction.X) <= AxisTolerance;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Add(Span<double> sums, int tap, double weight, SpectralStep step)
|
||||||
|
{
|
||||||
|
var values = sums.Slice(tap * ValuesPerTap, ValuesPerTap);
|
||||||
|
for (var row = 0; row < Channels; row++)
|
||||||
|
{
|
||||||
|
for (var column = 0; column < Channels; column++)
|
||||||
|
values[row * Channels + column] += weight * step.Gain[row] * step.Basis[column];
|
||||||
|
}
|
||||||
|
|
||||||
|
values[Channels * Channels] += weight * step.AlphaGain;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Write(Span<Vector4> table, ReadOnlySpan<double> sums, int taps)
|
||||||
|
{
|
||||||
|
for (var tap = 0; tap < taps; tap++)
|
||||||
|
{
|
||||||
|
var values = sums.Slice(tap * ValuesPerTap, ValuesPerTap);
|
||||||
|
table[tap * EntriesPerTap] = new Vector4((float)values[0], (float)values[1], (float)values[2], (float)values[Channels * Channels]);
|
||||||
|
table[tap * EntriesPerTap + 1] = new Vector4((float)values[3], (float)values[4], (float)values[5], 0f);
|
||||||
|
table[tap * EntriesPerTap + 2] = new Vector4((float)values[6], (float)values[7], (float)values[8], 0f);
|
||||||
|
}
|
||||||
|
|
||||||
|
table[(taps * EntriesPerTap)..].Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
|
internal readonly record struct SpectralStep(Vector3 Gain, float AlphaGain, Vector3 Basis, float Displacement)
|
||||||
|
{
|
||||||
|
public static SpectralStep Read(ReadOnlySpan<Vector4> table, int step)
|
||||||
|
{
|
||||||
|
var gain = table[step * Spectrum.EntriesPerStep];
|
||||||
|
var basis = table[step * Spectrum.EntriesPerStep + 1];
|
||||||
|
|
||||||
|
return new SpectralStep(new Vector3(gain.X, gain.Y, gain.Z), gain.W, new Vector3(basis.X, basis.Y, basis.Z), basis.W);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Write(Span<Vector4> table, int step)
|
||||||
|
{
|
||||||
|
table[step * Spectrum.EntriesPerStep] = new Vector4(Gain, AlphaGain);
|
||||||
|
table[step * Spectrum.EntriesPerStep + 1] = new Vector4(Basis, Displacement);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,12 +7,17 @@ internal static class Spectrum
|
|||||||
public const int MinSteps = 8;
|
public const int MinSteps = 8;
|
||||||
public const int MaxSteps = 64;
|
public const int MaxSteps = 64;
|
||||||
public const int DefaultSteps = 32;
|
public const int DefaultSteps = 32;
|
||||||
|
public const int EntriesPerStep = 2;
|
||||||
|
public const int StepQuantum = 4;
|
||||||
|
public const int SpectralTableLength = MaxSteps * EntriesPerStep;
|
||||||
public const float ShortestWavelength = 400f;
|
public const float ShortestWavelength = 400f;
|
||||||
public const float LongestWavelength = 700f;
|
public const float LongestWavelength = 700f;
|
||||||
public const float DefaultReferenceWavelength = 550f;
|
public const float DefaultReferenceWavelength = 550f;
|
||||||
|
|
||||||
public static int ClampSteps(int steps) => Math.Clamp(steps, MinSteps, MaxSteps);
|
public static int ClampSteps(int steps) => Math.Clamp(steps, MinSteps, MaxSteps);
|
||||||
|
|
||||||
|
public static int Padded(int steps) => Quantum.RoundUp(ClampSteps(steps), StepQuantum);
|
||||||
|
|
||||||
public static float ClampReference(float wavelength)
|
public static float ClampReference(float wavelength)
|
||||||
=> float.IsNaN(wavelength) ? DefaultReferenceWavelength : Math.Clamp(wavelength, ShortestWavelength, LongestWavelength);
|
=> float.IsNaN(wavelength) ? DefaultReferenceWavelength : Math.Clamp(wavelength, ShortestWavelength, LongestWavelength);
|
||||||
|
|
||||||
@@ -70,6 +75,79 @@ internal static class Spectrum
|
|||||||
table[steps..].Clear();
|
table[steps..].Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static double Wavelength(int index, int steps)
|
||||||
|
=> ShortestWavelength + (LongestWavelength - ShortestWavelength) * index / (steps - 1);
|
||||||
|
|
||||||
|
private static (double X, double Y, double Z) Emission(int index, int steps)
|
||||||
|
{
|
||||||
|
var wavelength = Wavelength(index, steps);
|
||||||
|
var weight = (index == 0 || index == steps - 1 ? 0.5 : 1.0) * SpectralBasis.IlluminantAt(wavelength);
|
||||||
|
var (x, y, z) = ColorMatching(wavelength);
|
||||||
|
|
||||||
|
return (weight * x, weight * y, weight * z);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void FillSpectral(Span<Vector4> table, int steps, float referenceWavelength, DispersionLaw law)
|
||||||
|
{
|
||||||
|
steps = ClampSteps(steps);
|
||||||
|
var reference = ClampReference(referenceWavelength);
|
||||||
|
var norm = Math.Max(
|
||||||
|
Math.Abs(Displacement(law, ShortestWavelength, reference)),
|
||||||
|
Math.Abs(Displacement(law, LongestWavelength, reference)));
|
||||||
|
|
||||||
|
Span<double> matrix = stackalloc double[9];
|
||||||
|
Span<double> inverse = stackalloc double[9];
|
||||||
|
matrix.Clear();
|
||||||
|
var luminance = 0.0;
|
||||||
|
for (var index = 0; index < steps; index++)
|
||||||
|
{
|
||||||
|
var (x, y, z) = Emission(index, steps);
|
||||||
|
var basis = SpectralBasis.At(Wavelength(index, steps));
|
||||||
|
matrix[0] += x * basis.X;
|
||||||
|
matrix[1] += x * basis.Y;
|
||||||
|
matrix[2] += x * basis.Z;
|
||||||
|
matrix[3] += y * basis.X;
|
||||||
|
matrix[4] += y * basis.Y;
|
||||||
|
matrix[5] += y * basis.Z;
|
||||||
|
matrix[6] += z * basis.X;
|
||||||
|
matrix[7] += z * basis.Y;
|
||||||
|
matrix[8] += z * basis.Z;
|
||||||
|
luminance += y;
|
||||||
|
}
|
||||||
|
|
||||||
|
Invert(matrix, inverse);
|
||||||
|
for (var index = 0; index < steps; index++)
|
||||||
|
{
|
||||||
|
var wavelength = Wavelength(index, steps);
|
||||||
|
var (x, y, z) = Emission(index, steps);
|
||||||
|
var basis = SpectralBasis.At(wavelength);
|
||||||
|
var gain = new Vector3(
|
||||||
|
(float)(inverse[0] * x + inverse[1] * y + inverse[2] * z),
|
||||||
|
(float)(inverse[3] * x + inverse[4] * y + inverse[5] * z),
|
||||||
|
(float)(inverse[6] * x + inverse[7] * y + inverse[8] * z));
|
||||||
|
new SpectralStep(gain, (float)(y / luminance), basis, (float)(Displacement(law, wavelength, reference) / norm)).Write(table, index);
|
||||||
|
}
|
||||||
|
|
||||||
|
table[(steps * EntriesPerStep)..].Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Invert(ReadOnlySpan<double> m, Span<double> inverse)
|
||||||
|
{
|
||||||
|
var c0 = m[4] * m[8] - m[5] * m[7];
|
||||||
|
var c1 = m[5] * m[6] - m[3] * m[8];
|
||||||
|
var c2 = m[3] * m[7] - m[4] * m[6];
|
||||||
|
var scale = 1.0 / (m[0] * c0 + m[1] * c1 + m[2] * c2);
|
||||||
|
inverse[0] = c0 * scale;
|
||||||
|
inverse[1] = (m[2] * m[7] - m[1] * m[8]) * scale;
|
||||||
|
inverse[2] = (m[1] * m[5] - m[2] * m[4]) * scale;
|
||||||
|
inverse[3] = c1 * scale;
|
||||||
|
inverse[4] = (m[0] * m[8] - m[2] * m[6]) * scale;
|
||||||
|
inverse[5] = (m[2] * m[3] - m[0] * m[5]) * scale;
|
||||||
|
inverse[6] = c2 * scale;
|
||||||
|
inverse[7] = (m[1] * m[6] - m[0] * m[7]) * scale;
|
||||||
|
inverse[8] = (m[0] * m[4] - m[1] * m[3]) * scale;
|
||||||
|
}
|
||||||
|
|
||||||
private static double Displacement(DispersionLaw law, double wavelength, double reference)
|
private static double Displacement(DispersionLaw law, double wavelength, double reference)
|
||||||
=> law == DispersionLaw.Prism
|
=> law == DispersionLaw.Prism
|
||||||
? 1.0 / (wavelength * wavelength) - 1.0 / (reference * reference)
|
? 1.0 / (wavelength * wavelength) - 1.0 / (reference * reference)
|
||||||
|
|||||||
@@ -5,12 +5,14 @@
|
|||||||
<UseWPF>true</UseWPF>
|
<UseWPF>true</UseWPF>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<Version>1.0.1</Version>
|
<Version>1.2.1</Version>
|
||||||
<Platforms>AnyCPU;x64</Platforms>
|
<Platforms>AnyCPU;x64</Platforms>
|
||||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||||
<ShaderDirPath>..\Release\</ShaderDirPath>
|
<ShaderDirPath>..\Release\</ShaderDirPath>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<Import Project="..\SpectrumColorShift.Shader\ShaderVariants.props" />
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">
|
||||||
<_Parameter1>SpectrumColorShift.Tests</_Parameter1>
|
<_Parameter1>SpectrumColorShift.Tests</_Parameter1>
|
||||||
@@ -61,7 +63,14 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Resource Include="$(ShaderDirPath)SpectrumColorShift.cso" Link="Resources\Shader\SpectrumColorShift.cso" />
|
<Resource Include="$(ShaderDirPath)SpectrumColorShiftLinearize.cso" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftLinear%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftRadial%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftRotational%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalLinear%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalRadial%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(StepCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalRotational%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
|
<Resource Include="@(TapCount->'$(ShaderDirPath)SpectrumColorShiftPhysicalFilterLinear%(Identity).cso')" Link="Resources\Shader\%(Filename)%(Extension)" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
using System.Runtime.InteropServices;
|
using System.Runtime.InteropServices;
|
||||||
|
using SharpGen.Runtime;
|
||||||
using Vortice;
|
using Vortice;
|
||||||
using Vortice.Direct2D1;
|
using Vortice.Direct2D1;
|
||||||
using YukkuriMovieMaker.Commons;
|
using YukkuriMovieMaker.Commons;
|
||||||
@@ -8,8 +9,42 @@ using YukkuriMovieMaker.Player.Video;
|
|||||||
|
|
||||||
namespace SpectrumColorShift;
|
namespace SpectrumColorShift;
|
||||||
|
|
||||||
internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : D2D1CustomShaderEffectBase(Create<EffectImpl>(devices))
|
internal sealed class SpectrumColorShiftCustomEffect : IDisposable
|
||||||
{
|
{
|
||||||
|
internal const int SourceInput = 0;
|
||||||
|
internal const int LightInput = 1;
|
||||||
|
private const int EffectInputs = LightInput + 1;
|
||||||
|
|
||||||
|
private readonly ShiftEffect _shift;
|
||||||
|
private readonly LinearizeCustomEffect _linearized;
|
||||||
|
|
||||||
|
public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices)
|
||||||
|
{
|
||||||
|
_shift = new ShiftEffect(devices);
|
||||||
|
_linearized = new LinearizeCustomEffect(devices);
|
||||||
|
if (!IsEnabled)
|
||||||
|
return;
|
||||||
|
|
||||||
|
using var light = _linearized.Output;
|
||||||
|
_shift.SetInput(LightInput, light, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsEnabled => _shift.IsEnabled && _linearized.IsEnabled;
|
||||||
|
|
||||||
|
public ID2D1Image Output => _shift.Output;
|
||||||
|
|
||||||
|
public void SetSource(ID2D1Image? source, RawBool invalidate)
|
||||||
|
{
|
||||||
|
_shift.SetInput(SourceInput, source, invalidate);
|
||||||
|
_linearized.SetInput(0, source, invalidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_linearized.Dispose();
|
||||||
|
_shift.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
internal enum PropertyIndex
|
internal enum PropertyIndex
|
||||||
{
|
{
|
||||||
Distance = 0,
|
Distance = 0,
|
||||||
@@ -21,36 +56,51 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
Dispersion,
|
Dispersion,
|
||||||
ReferenceWavelength,
|
ReferenceWavelength,
|
||||||
Steps,
|
Steps,
|
||||||
|
Physical,
|
||||||
}
|
}
|
||||||
|
|
||||||
public float Distance { set => SetValue((int)PropertyIndex.Distance, value); }
|
public float Distance { set => _shift.SetValue((int)PropertyIndex.Distance, value); }
|
||||||
public int Mode { set => SetValue((int)PropertyIndex.Mode, value); }
|
public int Mode { set => _shift.SetValue((int)PropertyIndex.Mode, value); }
|
||||||
public float Angle { set => SetValue((int)PropertyIndex.Angle, value); }
|
public float Angle { set => _shift.SetValue((int)PropertyIndex.Angle, value); }
|
||||||
public float CenterX { set => SetValue((int)PropertyIndex.CenterX, value); }
|
public float CenterX { set => _shift.SetValue((int)PropertyIndex.CenterX, value); }
|
||||||
public float CenterY { set => SetValue((int)PropertyIndex.CenterY, value); }
|
public float CenterY { set => _shift.SetValue((int)PropertyIndex.CenterY, value); }
|
||||||
public float Strength { set => SetValue((int)PropertyIndex.Strength, value); }
|
public float Strength { set => _shift.SetValue((int)PropertyIndex.Strength, value); }
|
||||||
public int Dispersion { set => SetValue((int)PropertyIndex.Dispersion, value); }
|
public int Dispersion { set => _shift.SetValue((int)PropertyIndex.Dispersion, value); }
|
||||||
public float ReferenceWavelength { set => SetValue((int)PropertyIndex.ReferenceWavelength, value); }
|
public float ReferenceWavelength { set => _shift.SetValue((int)PropertyIndex.ReferenceWavelength, value); }
|
||||||
public int Steps { set => SetValue((int)PropertyIndex.Steps, value); }
|
public int Steps { set => _shift.SetValue((int)PropertyIndex.Steps, value); }
|
||||||
|
public int Physical { set => _shift.SetValue((int)PropertyIndex.Physical, value); }
|
||||||
|
|
||||||
[CustomEffect(1)]
|
internal float ReadFloat(PropertyIndex index) => _shift.GetFloatValue((int)index);
|
||||||
|
|
||||||
|
internal int ReadInt(PropertyIndex index) => _shift.GetIntValue((int)index);
|
||||||
|
|
||||||
|
private sealed class ShiftEffect(IGraphicsDevicesAndContext devices) : D2D1CustomShaderEffectBase(Create<EffectImpl>(devices));
|
||||||
|
|
||||||
|
[CustomEffect(EffectInputs)]
|
||||||
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
internal sealed class EffectImpl : D2D1CustomShaderEffectImplBase<EffectImpl>
|
||||||
{
|
{
|
||||||
|
private ShiftHeader _header;
|
||||||
private ConstantBuffer _cb;
|
private ConstantBuffer _cb;
|
||||||
|
private PhysicalConstantBuffer _physicalCb;
|
||||||
private ShiftMode _mode = ShiftMode.Linear;
|
private ShiftMode _mode = ShiftMode.Linear;
|
||||||
private DispersionLaw _dispersion = DispersionLaw.Grating;
|
private DispersionLaw _dispersion = DispersionLaw.Grating;
|
||||||
private Vector2 _centerOffset;
|
private Vector2 _centerOffset;
|
||||||
private float _referenceWavelength = Spectrum.DefaultReferenceWavelength;
|
private float _referenceWavelength = Spectrum.DefaultReferenceWavelength;
|
||||||
private int _steps = Spectrum.DefaultSteps;
|
private int _steps = Spectrum.DefaultSteps;
|
||||||
private bool _tableStale = true;
|
private bool _physical;
|
||||||
|
private SpectrumKey? _tableKey;
|
||||||
|
private SpectrumKey? _spectralKey;
|
||||||
|
private FilterKey? _filterKey;
|
||||||
|
private SpectralFilter.Layout _filter;
|
||||||
|
private Guid _shader = GUID_PixelShader;
|
||||||
|
|
||||||
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Distance)]
|
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Distance)]
|
||||||
public float Distance
|
public float Distance
|
||||||
{
|
{
|
||||||
get => _cb.Distance;
|
get => _header.Distance;
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
_cb.Distance = Sanitize(value, -MaxInputPixel, MaxInputPixel);
|
_header.Distance = Sanitize(value, -MaxInputPixel, MaxInputPixel);
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -62,7 +112,6 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
set
|
set
|
||||||
{
|
{
|
||||||
_mode = value is (int)ShiftMode.Radial or (int)ShiftMode.Rotational ? (ShiftMode)value : ShiftMode.Linear;
|
_mode = value is (int)ShiftMode.Radial or (int)ShiftMode.Rotational ? (ShiftMode)value : ShiftMode.Linear;
|
||||||
_cb.Mode = (int)_mode;
|
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,11 +119,11 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Angle)]
|
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Angle)]
|
||||||
public float Angle
|
public float Angle
|
||||||
{
|
{
|
||||||
get => MathF.Atan2(_cb.Direction.Y, _cb.Direction.X) * 180f / MathF.PI;
|
get => MathF.Atan2(_header.Direction.Y, _header.Direction.X) * 180f / MathF.PI;
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
var radians = float.IsFinite(value) ? value * MathF.PI / 180f : 0f;
|
var radians = float.IsFinite(value) ? value * MathF.PI / 180f : 0f;
|
||||||
_cb.Direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
|
_header.Direction = new Vector2(MathF.Cos(radians), MathF.Sin(radians));
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -106,10 +155,10 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Strength)]
|
[CustomEffectProperty(PropertyType.Float, (int)PropertyIndex.Strength)]
|
||||||
public float Strength
|
public float Strength
|
||||||
{
|
{
|
||||||
get => _cb.Strength;
|
get => _header.Strength;
|
||||||
set
|
set
|
||||||
{
|
{
|
||||||
_cb.Strength = Sanitize(value, 0f, 1f);
|
_header.Strength = Sanitize(value, 0f, 1f);
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -121,7 +170,6 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
set
|
set
|
||||||
{
|
{
|
||||||
_dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating;
|
_dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating;
|
||||||
_tableStale = true;
|
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,7 +181,6 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
set
|
set
|
||||||
{
|
{
|
||||||
_referenceWavelength = Spectrum.ClampReference(value);
|
_referenceWavelength = Spectrum.ClampReference(value);
|
||||||
_tableStale = true;
|
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,19 +192,38 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
set
|
set
|
||||||
{
|
{
|
||||||
_steps = Spectrum.ClampSteps(value);
|
_steps = Spectrum.ClampSteps(value);
|
||||||
_cb.Steps = _steps;
|
_header.Steps = _steps;
|
||||||
_tableStale = true;
|
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public EffectImpl() : base(ShaderResourceUri.Get("SpectrumColorShift"))
|
[CustomEffectProperty(PropertyType.Int32, (int)PropertyIndex.Physical)]
|
||||||
|
public int Physical
|
||||||
{
|
{
|
||||||
_cb.Direction = Vector2.UnitX;
|
get => _physical ? 1 : 0;
|
||||||
_cb.Radius = 1f;
|
set
|
||||||
_cb.Strength = 1f;
|
{
|
||||||
_cb.Mode = (int)ShiftMode.Linear;
|
_physical = value != 0;
|
||||||
_cb.Steps = Spectrum.DefaultSteps;
|
UpdateConstants();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal int FilterTaps => _physical ? CurrentFilter().Taps : 0;
|
||||||
|
|
||||||
|
private SpectrumKey CurrentSpectrum => new(_steps, _referenceWavelength, _dispersion);
|
||||||
|
|
||||||
|
public EffectImpl() : base(ShaderVariants.DefaultBytes)
|
||||||
|
{
|
||||||
|
_header.Direction = Vector2.UnitX;
|
||||||
|
_header.Radius = 1f;
|
||||||
|
_header.Strength = 1f;
|
||||||
|
_header.Steps = Spectrum.DefaultSteps;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
|
||||||
|
{
|
||||||
|
base.Initialize(effectContext, transformGraph);
|
||||||
|
ShaderVariants.LoadAll(effectContext);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void UpdateConstants()
|
protected override void UpdateConstants()
|
||||||
@@ -167,14 +233,14 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (_tableStale)
|
var spread = ShiftGeometry.Spread(_mode, _header.Distance, _header.Radius);
|
||||||
{
|
var filter = _physical ? CurrentFilter() : default;
|
||||||
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion);
|
|
||||||
_tableStale = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius);
|
SelectShader(filter);
|
||||||
drawInformation.SetPixelShaderConstantBuffer(_cb);
|
if (_physical)
|
||||||
|
SendPhysicalConstants(spread, filter);
|
||||||
|
else
|
||||||
|
SendConstants(spread);
|
||||||
}
|
}
|
||||||
catch (Exception exception)
|
catch (Exception exception)
|
||||||
{
|
{
|
||||||
@@ -183,6 +249,60 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private SpectralFilter.Layout CurrentFilter()
|
||||||
|
{
|
||||||
|
var spectral = CurrentSpectrum;
|
||||||
|
if (_spectralKey != spectral)
|
||||||
|
{
|
||||||
|
Spectrum.FillSpectral(_physicalCb.Samples, spectral.Steps, spectral.Reference, spectral.Law);
|
||||||
|
_spectralKey = spectral;
|
||||||
|
}
|
||||||
|
|
||||||
|
var key = new FilterKey(spectral, _header.Distance, _header.Direction, _mode);
|
||||||
|
if (_filterKey != key)
|
||||||
|
{
|
||||||
|
_filter = _mode == ShiftMode.Linear ? SpectralFilter.Fill(_physicalCb.Taps, _physicalCb.Samples, _steps, _header.Distance, _header.Direction) : default;
|
||||||
|
_filterKey = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
return _filter;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SelectShader(SpectralFilter.Layout filter)
|
||||||
|
{
|
||||||
|
var shader = filter.Taps > 0
|
||||||
|
? ShaderVariants.Filter.Id(ShiftMode.Linear, filter.Taps)
|
||||||
|
: ShaderVariants.Stepped(_physical).Id(_mode, _steps);
|
||||||
|
if (shader == _shader)
|
||||||
|
return;
|
||||||
|
|
||||||
|
drawInformation!.SetPixelShader(shader, PixelOptions.None);
|
||||||
|
_shader = shader;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SendConstants(float spread)
|
||||||
|
{
|
||||||
|
var spectral = CurrentSpectrum;
|
||||||
|
if (_tableKey != spectral)
|
||||||
|
{
|
||||||
|
Spectrum.Fill(_cb.Samples, spectral.Steps, spectral.Reference, spectral.Law);
|
||||||
|
_tableKey = spectral;
|
||||||
|
}
|
||||||
|
|
||||||
|
_cb.Header = _header;
|
||||||
|
_cb.SpreadScale = spread;
|
||||||
|
drawInformation!.SetPixelShaderConstantBuffer(_cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SendPhysicalConstants(float spread, SpectralFilter.Layout filter)
|
||||||
|
{
|
||||||
|
_physicalCb.Header = _header;
|
||||||
|
_physicalCb.SpreadScale = spread;
|
||||||
|
_physicalCb.FilterOrigin = filter.Origin;
|
||||||
|
_physicalCb.FilterVertical = filter.Vertical ? 1 : 0;
|
||||||
|
drawInformation!.SetPixelShaderConstantBuffer(_physicalCb);
|
||||||
|
}
|
||||||
|
|
||||||
public override void MapInputRectsToOutputRect(
|
public override void MapInputRectsToOutputRect(
|
||||||
RawRect[] inputRects,
|
RawRect[] inputRects,
|
||||||
RawRect[] inputOpaqueSubRects,
|
RawRect[] inputOpaqueSubRects,
|
||||||
@@ -197,30 +317,27 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_cb.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
|
_header.InputBounds = new Vector4(inputRect.Left, inputRect.Top, inputRect.Right, inputRect.Bottom);
|
||||||
RefreshGeometry();
|
RefreshGeometry();
|
||||||
UpdateConstants();
|
UpdateConstants();
|
||||||
|
|
||||||
outputRect = ShiftGeometry.Output(inputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
|
outputRect = ShiftGeometry.Output(inputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
|
||||||
outputOpaqueSubRect = default;
|
outputOpaqueSubRect = default;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
|
public override void MapOutputRectToInputRects(RawRect outputRect, RawRect[] inputRects)
|
||||||
{
|
{
|
||||||
if (inputRects.Length == 0)
|
var requested = inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top
|
||||||
return;
|
? inputRect
|
||||||
|
: ShiftGeometry.Input(outputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
|
||||||
|
var activeInput = _physical ? LightInput : SourceInput;
|
||||||
|
|
||||||
if (inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top)
|
for (var index = 0; index < inputRects.Length; index++)
|
||||||
{
|
inputRects[index] = index == activeInput ? requested : default;
|
||||||
inputRects[0] = inputRect;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
inputRects[0] = ShiftGeometry.Input(outputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public override RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect)
|
public override RawRect MapInvalidRect(int inputIndex, RawRect invalidInputRect)
|
||||||
=> ShiftGeometry.Output(invalidInputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius);
|
=> ShiftGeometry.Output(invalidInputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
|
||||||
|
|
||||||
private static float Sanitize(float value, float minimum, float maximum)
|
private static float Sanitize(float value, float minimum, float maximum)
|
||||||
=> float.IsNaN(value) ? 0f : Math.Clamp(value, minimum, maximum);
|
=> float.IsNaN(value) ? 0f : Math.Clamp(value, minimum, maximum);
|
||||||
@@ -230,18 +347,34 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
if (inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top)
|
if (inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
_cb.Center = ShiftGeometry.Center(inputRect, _centerOffset);
|
_header.Center = ShiftGeometry.Center(inputRect, _centerOffset);
|
||||||
_cb.Radius = ShiftGeometry.Radius(inputRect, _cb.Center);
|
_header.Radius = ShiftGeometry.Radius(inputRect, _header.Center);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private readonly record struct SpectrumKey(int Steps, float Reference, DispersionLaw Law);
|
||||||
|
|
||||||
|
private readonly record struct FilterKey(SpectrumKey Spectral, float Distance, Vector2 Direction, ShiftMode Mode);
|
||||||
|
|
||||||
[InlineArray(Spectrum.MaxSteps)]
|
[InlineArray(Spectrum.MaxSteps)]
|
||||||
private struct SampleTable
|
private struct SampleTable
|
||||||
{
|
{
|
||||||
private Vector4 _element;
|
private Vector4 _element;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[InlineArray(Spectrum.SpectralTableLength)]
|
||||||
|
private struct SpectralSampleTable
|
||||||
|
{
|
||||||
|
private Vector4 _element;
|
||||||
|
}
|
||||||
|
|
||||||
|
[InlineArray(SpectralFilter.TableLength)]
|
||||||
|
private struct FilterTapTable
|
||||||
|
{
|
||||||
|
private Vector4 _element;
|
||||||
|
}
|
||||||
|
|
||||||
[StructLayout(LayoutKind.Sequential)]
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
private struct ConstantBuffer
|
private struct ShiftHeader
|
||||||
{
|
{
|
||||||
public Vector4 InputBounds;
|
public Vector4 InputBounds;
|
||||||
public Vector2 Direction;
|
public Vector2 Direction;
|
||||||
@@ -249,12 +382,30 @@ internal sealed class SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext
|
|||||||
public float Distance;
|
public float Distance;
|
||||||
public float Radius;
|
public float Radius;
|
||||||
public float Strength;
|
public float Strength;
|
||||||
public int Mode;
|
|
||||||
public int Steps;
|
public int Steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct ConstantBuffer
|
||||||
|
{
|
||||||
|
public ShiftHeader Header;
|
||||||
public float SpreadScale;
|
public float SpreadScale;
|
||||||
public float Pad1;
|
public float Pad1;
|
||||||
public float Pad2;
|
public float Pad2;
|
||||||
|
public float Pad3;
|
||||||
public SampleTable Samples;
|
public SampleTable Samples;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[StructLayout(LayoutKind.Sequential)]
|
||||||
|
private struct PhysicalConstantBuffer
|
||||||
|
{
|
||||||
|
public ShiftHeader Header;
|
||||||
|
public float SpreadScale;
|
||||||
|
public float FilterOrigin;
|
||||||
|
public int FilterVertical;
|
||||||
|
public float Pad;
|
||||||
|
public SpectralSampleTable Samples;
|
||||||
|
public FilterTapTable Taps;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -78,6 +78,15 @@ public sealed class SpectrumColorShiftEffect : VideoEffectBase
|
|||||||
}
|
}
|
||||||
private int _steps = Spectrum.DefaultSteps;
|
private int _steps = Spectrum.DefaultSteps;
|
||||||
|
|
||||||
|
[Display(GroupName = nameof(Texts.SpectrumGroup), Name = nameof(Texts.Physical), Description = nameof(Texts.PhysicalDescription), Order = 9, ResourceType = typeof(Texts))]
|
||||||
|
[ToggleSlider]
|
||||||
|
public bool Physical
|
||||||
|
{
|
||||||
|
get => _physical;
|
||||||
|
set => Set(ref _physical, value);
|
||||||
|
}
|
||||||
|
private bool _physical;
|
||||||
|
|
||||||
private IAnimatable[]? _animatables;
|
private IAnimatable[]? _animatables;
|
||||||
|
|
||||||
public override IEnumerable<string> CreateExoVideoFilters(
|
public override IEnumerable<string> CreateExoVideoFilters(
|
||||||
|
|||||||
@@ -46,7 +46,8 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
|||||||
(float)(_item.Strength.GetValue(frame, length, fps) / 100.0),
|
(float)(_item.Strength.GetValue(frame, length, fps) / 100.0),
|
||||||
(int)_item.Dispersion,
|
(int)_item.Dispersion,
|
||||||
(float)_item.ReferenceWavelength.GetValue(frame, length, fps),
|
(float)_item.ReferenceWavelength.GetValue(frame, length, fps),
|
||||||
_item.Steps);
|
_item.Steps,
|
||||||
|
_item.Physical);
|
||||||
|
|
||||||
if (_isFirst || _parameters.Distance != parameters.Distance)
|
if (_isFirst || _parameters.Distance != parameters.Distance)
|
||||||
_effect.Distance = parameters.Distance;
|
_effect.Distance = parameters.Distance;
|
||||||
@@ -66,6 +67,8 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
|||||||
_effect.ReferenceWavelength = parameters.ReferenceWavelength;
|
_effect.ReferenceWavelength = parameters.ReferenceWavelength;
|
||||||
if (_isFirst || _parameters.Steps != parameters.Steps)
|
if (_isFirst || _parameters.Steps != parameters.Steps)
|
||||||
_effect.Steps = parameters.Steps;
|
_effect.Steps = parameters.Steps;
|
||||||
|
if (_isFirst || _parameters.Physical != parameters.Physical)
|
||||||
|
_effect.Physical = parameters.Physical ? 1 : 0;
|
||||||
|
|
||||||
_parameters = parameters;
|
_parameters = parameters;
|
||||||
_isFirst = false;
|
_isFirst = false;
|
||||||
@@ -91,7 +94,7 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
|||||||
|
|
||||||
protected override void setInput(ID2D1Image? input)
|
protected override void setInput(ID2D1Image? input)
|
||||||
{
|
{
|
||||||
_effect?.SetInput(0, input, true);
|
_effect?.SetSource(input, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override void ClearEffectChain()
|
protected override void ClearEffectChain()
|
||||||
@@ -109,7 +112,7 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
|||||||
|
|
||||||
private void ClearEffectChainCore()
|
private void ClearEffectChainCore()
|
||||||
{
|
{
|
||||||
_effect?.SetInput(0, null, true);
|
_effect?.SetSource(null, true);
|
||||||
_isFirst = true;
|
_isFirst = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,5 +125,6 @@ internal sealed class SpectrumColorShiftEffectProcessor(
|
|||||||
float Strength,
|
float Strength,
|
||||||
int Dispersion,
|
int Dispersion,
|
||||||
float ReferenceWavelength,
|
float ReferenceWavelength,
|
||||||
int Steps);
|
int Steps,
|
||||||
|
bool Physical);
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
|
Key,Parameter,ja-jp,en-us,zh-cn,zh-tw,ko-kr,es-es,ar-sa,id-id
|
||||||
SpectrumColorShift,,色ずれ(スペクトラム),Color Shift (Spectrum),色偏(光谱),色偏(光譜),색 어긋남 (스펙트럼),Desfase de color (espectro),إزاحة اللون (الطيف),Pergeseran Warna (Spektrum)
|
SpectrumColorShift,,色ズレ(スペクトラム),Color Shift (Spectrum),色偏(光谱),色偏(光譜),색 어긋남 (스펙트럼),Desfase de color (espectro),إزاحة اللون (الطيف),Pergeseran Warna (Spektrum)
|
||||||
ShiftGroup,,色ずれ,Color Shift,色偏,色偏,색 어긋남,Desfase de color,إزاحة اللون,Pergeseran Warna
|
ShiftGroup,,色ずれ,Color Shift,色偏,色偏,색 어긋남,Desfase de color,إزاحة اللون,Pergeseran Warna
|
||||||
SpectrumGroup,,スペクトル,Spectrum,光谱,光譜,스펙트럼,Espectro,الطيف,Spektrum
|
SpectrumGroup,,スペクトル,Spectrum,光谱,光譜,스펙트럼,Espectro,الطيف,Spektrum
|
||||||
Distance,,距離,Distance,距离,距離,거리,Distancia,المسافة,Jarak
|
Distance,,距離,Distance,距离,距離,거리,Distancia,المسافة,Jarak
|
||||||
@@ -30,6 +30,8 @@ ReferenceWavelength,,基準波長,Reference Wavelength,基准波长,基準波長
|
|||||||
ReferenceWavelengthDescription,,ずれずにその位置に残る色の波長です。単位はnmで、450付近が青、550付近が緑、650付近が赤です,"Sets the wavelength in nm of the color that stays in place. Around 450 is blue, 550 is green, and 650 is red.",设置保持原位的颜色的波长,单位为nm。450附近为蓝色,550附近为绿色,650附近为红色。,設定保持原位的顏色的波長,單位為nm。450附近為藍色,550附近為綠色,650附近為紅色。,"제자리에 남는 색의 파장입니다. 단위는 nm이며 450 부근이 파랑, 550 부근이 초록, 650 부근이 빨강입니다.","Establece la longitud de onda, en nm, del color que permanece en su sitio. Alrededor de 450 es azul, 550 verde y 650 rojo.",يحدد الطول الموجي، بوحدة nm، للون الذي يبقى في مكانه. حوالي 450 أزرق و550 أخضر و650 أحمر.,"Mengatur panjang gelombang warna yang tetap di tempatnya, dalam nm. Sekitar 450 biru, 550 hijau, dan 650 merah."
|
ReferenceWavelengthDescription,,ずれずにその位置に残る色の波長です。単位はnmで、450付近が青、550付近が緑、650付近が赤です,"Sets the wavelength in nm of the color that stays in place. Around 450 is blue, 550 is green, and 650 is red.",设置保持原位的颜色的波长,单位为nm。450附近为蓝色,550附近为绿色,650附近为红色。,設定保持原位的顏色的波長,單位為nm。450附近為藍色,550附近為綠色,650附近為紅色。,"제자리에 남는 색의 파장입니다. 단위는 nm이며 450 부근이 파랑, 550 부근이 초록, 650 부근이 빨강입니다.","Establece la longitud de onda, en nm, del color que permanece en su sitio. Alrededor de 450 es azul, 550 verde y 650 rojo.",يحدد الطول الموجي، بوحدة nm، للون الذي يبقى في مكانه. حوالي 450 أزرق و550 أخضر و650 أحمر.,"Mengatur panjang gelombang warna yang tetap di tempatnya, dalam nm. Sekitar 450 biru, 550 hijau, dan 650 merah."
|
||||||
Steps,,ステップ数,Steps,步数,步數,단계 수,Pasos,عدد الخطوات,Langkah
|
Steps,,ステップ数,Steps,步数,步數,단계 수,Pasos,عدد الخطوات,Langkah
|
||||||
StepsDescription,,スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます,"Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies.",设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。,設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。,스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다.,"Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas.",يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة.,"Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah."
|
StepsDescription,,スペクトルを分ける数です。距離を大きくするときは増やすと、色が段になって見えるのを防げます,"Sets how many wavelengths the spectrum is divided into. For large distances, raise it to keep the colors from appearing as separate copies.",设置光谱的分割数。距离较大时请增大该值,以免颜色呈分层的重影。,設定光譜的分割數。距離較大時請增大此值,以免顏色呈分層的重影。,스펙트럼을 나누는 수입니다. 거리를 크게 할 때는 늘리면 색이 계단처럼 보이는 것을 막을 수 있습니다.,"Establece en cuántas longitudes de onda se divide el espectro. Con distancias grandes, auméntelo para evitar que los colores se vean como copias separadas.",يحدد عدد الأطوال الموجية التي يقسم إليها الطيف. عند المسافات الكبيرة، ارفعه لتجنب ظهور الألوان كنسخ منفصلة.,"Mengatur jumlah panjang gelombang yang dipakai untuk membagi spektrum. Untuk jarak besar, naikkan agar warna tidak tampak sebagai salinan terpisah."
|
||||||
|
Physical,,物理ベース,Physically Based,基于物理,基於物理,물리 기반,Basado en física,قائم على الفيزياء,Berbasis fisika
|
||||||
|
PhysicalDescription,,オンにすると、映像の色から光のスペクトルを推定し、波長ごとの光をずらして足し合わせます。色の足し合わせは、光の量で行います。オフでは、赤、緑、青を別々にずらします,"When on, the spectrum of light is estimated from the color of the image, and the light of each wavelength is shifted before being summed. Colors are summed as amounts of light. When off, red, green and blue are shifted separately.",开启后,根据图像的颜色估计光的光谱,将各波长的光错开后再叠加。颜色的叠加以光量进行。关闭时,红、绿、蓝分别错开。,開啟後,根據影像的顏色估計光的光譜,將各波長的光錯開後再疊加。顏色的疊加以光量進行。關閉時,紅、綠、藍分別錯開。,"켜면 영상의 색에서 빛의 스펙트럼을 추정하고, 파장별 빛을 어긋나게 한 뒤 더합니다. 색의 합산은 빛의 양으로 합니다. 끄면 빨강, 초록, 파랑을 따로 어긋나게 합니다.","Al activarlo, se estima el espectro de la luz a partir del color de la imagen y se desplaza la luz de cada longitud de onda antes de sumarla. Los colores se suman como cantidades de luz. Desactivado, el rojo, el verde y el azul se desplazan por separado.",عند التفعيل، يُقدَّر طيف الضوء من لون الصورة، ويُزاح ضوء كل طول موجي ثم تُجمع الأطوال الموجية. يتم جمع الألوان بوصفها كميات من الضوء. عند الإيقاف، تُزاح ألوان الأحمر والأخضر والأزرق بشكل منفصل.,"Jika diaktifkan, spektrum cahaya diperkirakan dari warna gambar, lalu cahaya tiap panjang gelombang digeser sebelum dijumlahkan. Warna dijumlahkan sebagai jumlah cahaya. Jika dinonaktifkan, merah, hijau, dan biru digeser secara terpisah."
|
||||||
TagColorShift,,色ずれ,color shift,色偏,色偏,색 어긋남,desfase de color,إزاحة اللون,pergeseran warna
|
TagColorShift,,色ずれ,color shift,色偏,色偏,색 어긋남,desfase de color,إزاحة اللون,pergeseran warna
|
||||||
TagChromaticAberration,,色収差,chromatic aberration,色差,色差,색수차,aberración cromática,الزيغ اللوني,aberasi kromatik
|
TagChromaticAberration,,色収差,chromatic aberration,色差,色差,색수차,aberración cromática,الزيغ اللوني,aberasi kromatik
|
||||||
TagSpectrum,,スペクトル,spectrum,光谱,光譜,스펙트럼,espectro,الطيف,spektrum
|
TagSpectrum,,スペクトル,spectrum,光谱,光譜,스펙트럼,espectro,الطيف,spektrum
|
||||||
|
|||||||
|
バイナリファイルは表示されません。
|
変更後 幅: | 高さ: | サイズ: 257 KiB |
バイナリファイルは表示されません。
|
変更前 幅: | 高さ: | サイズ: 1.3 MiB 変更後 幅: | 高さ: | サイズ: 1.4 MiB |
新しいイシューから参照
ユーザーをブロックする