24 コミット
作成者 SHA1 メッセージ 日付
routersys 52ec2e183b Gitea Actions のワークフローを直す 2026-11-08 13:06:24 +09:00
routersys 9b1d1d84d2 Gitea Actions のワークフローを直す 2026-11-08 10:15:45 +09:00
routersys cc5c19cb94 Gitea Actions のワークフローを直す 2026-11-08 09:48:44 +09:00
routersys d180efc42a 過去のタグ用ワークフローを消す 2026-11-08 03:58:08 +09:00
routersys 9249e3f8d6 Gitea Actions のワークフローを直す 2026-11-08 03:56:15 +09:00
routersys 6e99e0eed9 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:34:48 +09:00
routersys b596a00e25 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:07:19 +09:00
routersys 1a14dbfc0f Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 22:36:29 +09:00
routersys 5a65d8943d Gitea Actions のワークフローを直す 2026-11-07 22:08:33 +09:00
routersys 8ce057ebcd Gitea Actions のワークフローを足す 2026-11-07 19:53:36 +09:00
routersys 59c275292c 画像の参照先をGiteaへ移す 2026-11-07 18:22:10 +09:00
routersys 9648361fbf サブモジュールの参照先をGiteaへ移す 2026-11-07 18:19:03 +09:00
routersys bc13f1964a 不具合の報告の説明を送信の上限と項目へ合わせる 2026-11-02 11:35:46 +09:00
routersys 80709bde22 サムネイル画像を更新する 2026-10-13 16:39:58 +09:00
routersys de6901f898 バージョンをv1.2.1へ更新する
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.2.1 のコミットから作成しました
2026-10-13 16:12:22 +09:00
routersys c627206917 sRGBの変換の名前に接頭辞を付け、使われない定数を除く 2026-10-13 16:05:50 +09:00
routersys 0c097c3eb8 シェーダーの個数の一覧を共有の設定に集め、同梱するシェーダーを一覧から決める 2026-10-13 15:59:39 +09:00
routersys a77dbbe13f エフェクトが基底を継承せずに前処理のエフェクトを持つ形にし、光の入力の名前を直す 2026-10-13 15:55:26 +09:00
routersys 31a052feb1 エフェクトの更新の管理を設定の組から決まる形にし、使われない定数を除く 2026-10-13 15:46:46 +09:00
routersys 38d280b3e8 シェーダーの系統と分光表の1ステップを型にして、切り上げの重複をなくす 2026-10-13 15:37:25 +09:00
routersys 6f23e211de 軸に平行な直線のずれを、タップを減らしたフィルターで描いて速くする
・「物理ベース」で軸に平行な短い直線のずれを、ステップの合計を畳み込んだタップのフィルターで描くよう変更-M
2026-10-13 15:03:11 +09:00
routersys 5579e7a4ed 物理ベースのシェーダーの共通部分を別ファイルに取り出す 2026-10-13 12:35:48 +09:00
routersys 307acd1f22 方式ごとに分けたシェーダーで64ステップの描画と初回描画を速くする
・直線、放射、回転の方式ごとにコンパイルしたシェーダーを選んで使うよう変更-M
2026-10-13 11:12:46 +09:00
routersys d5a114d14c 表示名を「色ズレ(スペクトラム)」へ変更する
・プラグインの表示名を「色ずれ(スペクトラム)」から「色ズレ(スペクトラム)」へ変更-M
2026-10-13 10:24:35 +09:00
41個のファイルの変更、1724行の追加、487行の削除

検索条件に一致するファイルはありません

+517
ファイルの表示
@@ -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)"
}
}
+11 -4
ファイルの表示
@@ -1,5 +1,5 @@
======================================== ========================================
色ずれ(スペクトラム) for YMM4 v1.2.0 色ズレ(スペクトラム) for YMM4 v1.2.1
======================================== ========================================
YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長に分け、波長ごとに YukkuriMovieMaker4上で動作する、映像の色を400nmから700nmの波長に分け、波長ごとに
異なる量だけずらして足し合わせ、虹色の縁として描画する 異なる量だけずらして足し合わせ、虹色の縁として描画する
@@ -17,7 +17,7 @@ Reflectance」(Eurographics Symposium on Rendering、2019年)に基づきま
絵になります。 絵になります。
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに 距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに
対応しています。 対応しています。
エフェクトの種類一覧では「色ずれ(スペクトラム)」として表示されます。 エフェクトの種類一覧では「色ズレ(スペクトラム)」として表示されます。
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
■ 動作要件 ■ 動作要件
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
@@ -78,15 +78,22 @@ Reflectance」(Eurographics Symposium on Rendering、2019年)に基づきま
■ 不具合の報告 ■ 不具合の報告
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で 本プラグインは、想定していない例外が起きたときに、その内容を開発者へ自動で
送信します。同意は求めず、常に送信します。 送信します。同意は求めません。止める設定もありません。
送信する数には上限があります。YMM4の1回の起動で送る報告は、
YMM4-Telemetryで報告する別のプラグインと合わせて20件までです。
例外の型と発生位置が同じ報告は3件までです。上限を超えた報告と、
送信先から待つよう求められている間に起きた報告は、送信も退避もしません。
送信する情報は次のとおりです。 送信する情報は次のとおりです。
例外 : 型の完全名、メッセージ、スタックトレース 例外 : 型の完全名、メッセージ、スタックトレース
発生位置 : モジュール名、関数名、ファイル名、行番号 発生位置 : モジュール名、関数名、ファイル名、行番号、
プラグイン自身のコードかどうか
プラグイン : アセンブリ名、バージョン プラグイン : アセンブリ名、バージョン
実行環境 : OSの名前とバージョン、.NETのバージョン、 実行環境 : OSの名前とバージョン、.NETのバージョン、
CPUのアーキテクチャ、論理プロセッサ数 CPUのアーキテクチャ、論理プロセッサ数
識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子 識別子 : YMM4の起動ごとに決まるセッション識別子、報告ごとの識別子
時刻 : 報告を作った時刻(UTC)
映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する 映像の中身とプロジェクトの内容は送信しません。継続して個人を追跡する
識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に 識別子も持ちません。セッション識別子はYMM4を起動し直すと別の値に
+3 -3
ファイルの表示
@@ -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
+11 -8
ファイルの表示
@@ -1,4 +1,4 @@
# 色ずれ(スペクトラム) for YMM4 # 色ズレ(スペクトラム) for YMM4
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](#) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](#)
[![.NET](https://img.shields.io/badge/.NET-10.0-purple.svg)](#) [![.NET](https://img.shields.io/badge/.NET-10.0-purple.svg)](#)
@@ -11,7 +11,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ絵になります。 色のずれ方は設定と画素の位置から決定論的に決まり、同じ設定では常に同じ絵になります。
距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに対応しています。 距離、角度、中心X、中心Y、強さ、基準波長の6項目はアニメーションに対応しています。
![Image](https://github.com/routersys/YMM4-SpectrumColorShift/blob/main/docs/SpectrumColorShift.png) ![Image](https://git.routersys.com/routersys/YMM4-SpectrumColorShift/raw/branch/main/docs/SpectrumColorShift.png)
--- ---
@@ -41,7 +41,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
## 概要 ## 概要
本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「色ずれ(スペクトラム)」として表示されます。カテゴリは加工です。 本プラグインはYMM4の映像エフェクトとして動作し、エフェクトの種類一覧では「色ズレ(スペクトラム)」として表示されます。カテゴリは加工です。
波長は光の色を表す値で、短いほど青く、長いほど赤くなります。400nmから700nmまでの波長の並びが、スペクトルです。映像の各画素について、波長ごとにずらした位置の色を読み取り、波長ごとの重みを掛けて足し合わせた色で描き直します。ずらす量は波長と「基準波長」との違いから決め、「分散」で回折格子とプリズムのどちらの決め方にするかを選びます。 波長は光の色を表す値で、短いほど青く、長いほど赤くなります。400nmから700nmまでの波長の並びが、スペクトルです。映像の各画素について、波長ごとにずらした位置の色を読み取り、波長ごとの重みを掛けて足し合わせた色で描き直します。ずらす量は波長と「基準波長」との違いから決め、「分散」で回折格子とプリズムのどちらの決め方にするかを選びます。
@@ -72,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. 映像エフェクトの種類として「色ズレ(スペクトラム)」を選択してください。
--- ---
@@ -90,7 +90,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
次の画像は、左上が元の映像で、ほかの3つは「距離」を24pxにして「方式」だけを変えた例です。ほかの項目は既定値です。 次の画像は、左上が元の映像で、ほかの3つは「距離」を24pxにして「方式」だけを変えた例です。ほかの項目は既定値です。
![Image](https://github.com/routersys/YMM4-SpectrumColorShift/blob/main/docs/SpectrumColorShift-Modes.png) ![Image](https://git.routersys.com/routersys/YMM4-SpectrumColorShift/raw/branch/main/docs/SpectrumColorShift-Modes.png)
放射と回転の中心は、画面の中心ではなく、このエフェクトに入る映像の中心です。「中心X」と「中心Y」で、この中心を動かせます。「角度」は方式が直線のときだけ、「中心X」と「中心Y」は方式が放射か回転のときだけ表示されます。 放射と回転の中心は、画面の中心ではなく、このエフェクトに入る映像の中心です。「中心X」と「中心Y」で、この中心を動かせます。「角度」は方式が直線のときだけ、「中心X」と「中心Y」は方式が放射か回転のときだけ表示されます。
@@ -127,7 +127,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、映像の色を400nmから700nm
次の画像は、「距離」を24pxにして、左が「物理ベース」オフ、右がオンの例です。上が直線、下が放射で、ほかの項目は既定値です。 次の画像は、「距離」を24pxにして、左が「物理ベース」オフ、右がオンの例です。上が直線、下が放射で、ほかの項目は既定値です。
![Image](https://github.com/routersys/YMM4-SpectrumColorShift/blob/main/docs/SpectrumColorShift-Physical.png) ![Image](https://git.routersys.com/routersys/YMM4-SpectrumColorShift/raw/branch/main/docs/SpectrumColorShift-Physical.png)
映像の値は、まずsRGBの変換式で光の量に変換します。以降の計算は、画素の間の補間も含めて、この光の量で行い、最後にsRGBの値へ戻します。 映像の値は、まずsRGBの変換式で光の量に変換します。以降の計算は、画素の間の補間も含めて、この光の量で行い、最後にsRGBの値へ戻します。
@@ -191,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アドレスは受信側へ渡す手前で取り除いています。
+4 -4
ファイルの表示
@@ -121,7 +121,7 @@
"frames": [ "frames": [
0 0
], ],
"hash": "872E6C69B6384487C4455B575FED039B973D8F0CD0C86E83476DB7F8C4D6C5E9" "hash": "BFCB9E307B4EC0823A9DA134EC63CC8989F1B978EE89B8CED3576DBB972C2F98"
}, },
{ {
"name": "physical-distance-24", "name": "physical-distance-24",
@@ -156,14 +156,14 @@
"frames": [ "frames": [
0 0
], ],
"hash": "F118C51CD7930A110A7842776BF9F55035FF91A83974FE525E632101BC23AF3C" "hash": "7CFAFE05228475887147E95781919A4A961C4C0D467513824B517327A05BB249"
}, },
{ {
"name": "physical-reference-450", "name": "physical-reference-450",
"frames": [ "frames": [
0 0
], ],
"hash": "4D5C824E9F9A790F546F27F2D6DB891C4AA10CFF3AAF0F5A64E92403C760BDDD" "hash": "B792437ECF90657E41E3164FAB3A1967548938A7F38747A4B75B177FF7F44ED2"
}, },
{ {
"name": "physical-steps-8", "name": "physical-steps-8",
@@ -177,7 +177,7 @@
"frames": [ "frames": [
0 0
], ],
"hash": "9491C6D44879AD71A7BAAA7AB7330D31507003C89F06179B056AE8415D19C7A0" "hash": "C562CBC11A831C10C1ACEFF8742C89FD9695629B753DC31EECC6541042242E8D"
} }
] ]
} }
+135
ファイルの表示
@@ -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);
}
+6
ファイルの表示
@@ -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>
+37 -8
ファイルの表示
@@ -154,22 +154,51 @@
<ItemGroup> <ItemGroup>
<None Include="SpectrumColorShift.hlsl" /> <None Include="SpectrumColorShift.hlsl" />
<None Include="SpectrumColorShiftPhysical.hlsl" /> <None Include="SpectrumColorShiftPhysical.hlsl" />
<None Include="SpectrumColorShiftPhysicalFilter.hlsl" />
<None Include="Physical.hlsli" />
<None Include="Srgb.hlsli" /> <None Include="Srgb.hlsli" />
</ItemGroup> </ItemGroup>
<ItemGroup> <Import Project="ShaderVariants.props" />
<StepCount Include="8;12;16;20;24;28;32;36;40;44;48;52;56;60;64" /> <Target Name="AddVariantShaders" BeforeTargets="FxCompile">
</ItemGroup> <ItemGroup>
<Target Name="AddStepCountShaders" BeforeTargets="FxCompile"> <StaleShader Include="$(OutDir)SpectrumColorShift*.cso" />
</ItemGroup>
<Delete Files="@(StaleShader)" />
<ItemGroup> <ItemGroup>
<FxCompile Include="SpectrumColorShift.hlsl"> <FxCompile Include="SpectrumColorShift.hlsl">
<ShaderType>Pixel</ShaderType> <ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions> <PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=1</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShift%(StepCount.Identity).cso</ObjectFileOutput> <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>
<FxCompile Include="SpectrumColorShiftPhysical.hlsl"> <FxCompile Include="SpectrumColorShiftPhysical.hlsl">
<ShaderType>Pixel</ShaderType> <ShaderType>Pixel</ShaderType>
<PreprocessorDefinitions>StepCount=%(StepCount.Identity)</PreprocessorDefinitions> <PreprocessorDefinitions>StepCount=%(StepCount.Identity);ShaderMode=1</PreprocessorDefinitions>
<ObjectFileOutput>$(OutDir)SpectrumColorShiftPhysical%(StepCount.Identity).cso</ObjectFileOutput> <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> </FxCompile>
</ItemGroup> </ItemGroup>
</Target> </Target>
+6
ファイルの表示
@@ -26,6 +26,12 @@
<None Include="SpectrumColorShiftPhysical.hlsl"> <None Include="SpectrumColorShiftPhysical.hlsl">
<Filter>ソース ファイル</Filter> <Filter>ソース ファイル</Filter>
</None> </None>
<None Include="SpectrumColorShiftPhysicalFilter.hlsl">
<Filter>ソース ファイル</Filter>
</None>
<None Include="Physical.hlsli">
<Filter>ヘッダー ファイル</Filter>
</None>
<None Include="Srgb.hlsli"> <None Include="Srgb.hlsli">
<Filter>ヘッダー ファイル</Filter> <Filter>ヘッダー ファイル</Filter>
</None> </None>
+13 -9
ファイルの表示
@@ -2,12 +2,17 @@
#error StepCount must be defined by the build. #error StepCount must be defined by the build.
#endif #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;
@@ -19,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);
}; };
@@ -29,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;
@@ -48,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);
@@ -124,7 +128,7 @@ 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;
@@ -133,7 +137,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
for (int index = 0; index < StepCount; index++) for (int index = 0; index < StepCount; index++)
AccumulateRadial(index, uv, offsetStep, rate, color, coverage); AccumulateRadial(index, uv, offsetStep, rate, color, coverage);
} }
else if (mode == ModeRotational) else if (CompiledMode == ModeRotational)
{ {
float rate = shiftDistance / radius; float rate = shiftDistance / radius;
+6 -131
ファイルの表示
@@ -2,100 +2,14 @@
#error StepCount must be defined by the build. #error StepCount must be defined by the build.
#endif #endif
#include "Srgb.hlsli" #include "Physical.hlsli"
Texture2D LinearTexture : register(t1);
SamplerState LinearSampler : register(s1);
static const int MaxSteps = 64;
static const int TableSize = 128;
static const int ModeRadial = 2;
static const int ModeRotational = 4;
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 mode : packoffset(c2.w);
int steps : packoffset(c3.x);
float spreadScale : packoffset(c3.y);
float4 samples[TableSize] : packoffset(c4);
};
float2 SamplePosition(float2 scenePosition, float2 offset, float coefficient)
{
float shift = coefficient * shiftDistance;
if (mode == ModeRadial)
{
float scale = 1.0 - clamp(shift / radius, -MaxRadialShift, MaxRadialShift);
return center + offset * scale;
}
if (mode == 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 (mode == ModeRadial)
return abs(offset) * spreadScale;
if (mode == 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 = LinearTexture.SampleLevel(LinearSampler, 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);
}
void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float alpha) void AccumulateRadial(int index, float2 uv, float2 offsetStep, float rate, inout float3 color, inout float alpha)
{ {
float4 gain = samples[index * 2]; float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1]; float4 basis = samples[index * 2 + 1];
float scale = clamp(basis.w * rate, -MaxRadialShift, MaxRadialShift); float scale = clamp(basis.w * rate, -MaxRadialShift, MaxRadialShift);
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - offsetStep * scale, 0), color, alpha); 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) void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep, float rate, inout float3 color, inout float alpha)
@@ -106,27 +20,14 @@ void AccumulateRotational(int index, float2 uv, float2 offset, float2 pixelStep,
float cosine; float cosine;
sincos(basis.w * rate, sine, 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); float2 delta = float2((cosine - 1.0) * offset.x + sine * offset.y, (cosine - 1.0) * offset.y - sine * offset.x);
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv + delta * pixelStep, 0), color, alpha); 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) void AccumulateLinear(int index, float2 uv, float2 stride, inout float3 color, inout float alpha)
{ {
float4 gain = samples[index * 2]; float4 gain = samples[index * 2];
float4 basis = samples[index * 2 + 1]; float4 basis = samples[index * 2 + 1];
Accumulate(gain, basis.rgb, LinearTexture.SampleLevel(LinearSampler, uv - basis.w * stride, 0), color, alpha); Accumulate(gain, basis.rgb, LightTexture.SampleLevel(LightSampler, uv - basis.w * stride, 0), 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 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
@@ -135,7 +36,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
float3 color = 0.0; float3 color = 0.0;
float alpha = 0.0; float alpha = 0.0;
if (mode == ModeRadial) if (CompiledMode == ModeRadial)
{ {
float2 offsetStep = offset * pixelStep; float2 offsetStep = offset * pixelStep;
float rate = shiftDistance / radius; float rate = shiftDistance / radius;
@@ -144,7 +45,7 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
for (int index = 0; index < StepCount; index++) for (int index = 0; index < StepCount; index++)
AccumulateRadial(index, uv, offsetStep, rate, color, alpha); AccumulateRadial(index, uv, offsetStep, rate, color, alpha);
} }
else if (mode == ModeRotational) else if (CompiledMode == ModeRotational)
{ {
float rate = shiftDistance / radius; float rate = shiftDistance / radius;
@@ -163,29 +64,3 @@ float4 GatherInside(float2 uv, float2 pixelStep, float2 scenePosition)
return Resolve(color, alpha); return Resolve(color, alpha);
} }
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);
}
+29
ファイルの表示
@@ -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);
}
+16 -16
ファイルの表示
@@ -1,22 +1,22 @@
static const float DecodeThreshold = 0.04045; static const float SrgbDecodeThreshold = 0.04045;
static const float EncodeThreshold = 0.0031308; static const float SrgbEncodeThreshold = 0.0031308;
static const float LowSlope = 12.92; static const float SrgbLowSlope = 12.92;
static const float Offset = 0.055; static const float SrgbOffset = 0.055;
static const float Scale = 1.055; static const float SrgbScale = 1.055;
static const float Exponent = 2.4; static const float SrgbExponent = 2.4;
float3 Decode(float3 encoded) float3 SrgbDecode(float3 encoded)
{ {
float3 low = encoded / LowSlope; float3 low = encoded / SrgbLowSlope;
float3 high = pow((encoded + Offset) / Scale, Exponent); float3 high = pow((encoded + SrgbOffset) / SrgbScale, SrgbExponent);
return encoded <= DecodeThreshold ? low : high; return encoded <= SrgbDecodeThreshold ? low : high;
} }
float3 Encode(float3 linearColor) float3 SrgbEncode(float3 linearColor)
{ {
float3 low = linearColor * LowSlope; float3 low = linearColor * SrgbLowSlope;
float3 high = Scale * pow(linearColor, 1.0 / Exponent) - Offset; float3 high = SrgbScale * pow(linearColor, 1.0 / SrgbExponent) - SrgbOffset;
return linearColor <= EncodeThreshold ? low : high; return linearColor <= SrgbEncodeThreshold ? low : high;
} }
float3 Unpremultiply(float4 premultiplied) float3 Unpremultiply(float4 premultiplied)
@@ -26,10 +26,10 @@ float3 Unpremultiply(float4 premultiplied)
float4 DecodePremultiplied(float4 encoded) float4 DecodePremultiplied(float4 encoded)
{ {
return float4(Decode(Unpremultiply(encoded)) * encoded.a, encoded.a); return float4(SrgbDecode(Unpremultiply(encoded)) * encoded.a, encoded.a);
} }
float4 EncodePremultiplied(float4 linearColor) float4 EncodePremultiplied(float4 linearColor)
{ {
return float4(Encode(Unpremultiply(linearColor)) * linearColor.a, linearColor.a); return float4(SrgbEncode(Unpremultiply(linearColor)) * linearColor.a, linearColor.a);
} }
+19
ファイルの表示
@@ -69,6 +69,25 @@ 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] [Theory]
[InlineData(DispersionLaw.Grating)] [InlineData(DispersionLaw.Grating)]
[InlineData(DispersionLaw.Prism)] [InlineData(DispersionLaw.Prism)]
+31
ファイルの表示
@@ -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)!;
}
+84
ファイルの表示
@@ -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}");
}
}
}
}
+10 -21
ファイルの表示
@@ -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);
} }
} }
+108
ファイルの表示
@@ -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);
}
}
}
}
}
+221
ファイルの表示
@@ -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));
}
}
+4 -4
ファイルの表示
@@ -48,7 +48,7 @@ public sealed class SpectralRenderingTests
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;
@@ -602,7 +602,7 @@ public sealed class SpectralRenderingTests
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);
@@ -698,7 +698,7 @@ public sealed class SpectralRenderingTests
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);
Settings(Mode: mode, Distance: 12f).Apply(effect); Settings(Mode: mode, Distance: 12f).Apply(effect);
using var output = effect.Output; using var output = effect.Output;
@@ -735,7 +735,7 @@ public sealed class SpectralRenderingTests
var expected = Render(context, source, legacy); var expected = Render(context, source, legacy);
using var effect = new SpectrumColorShiftCustomEffect(context); using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true); effect.SetSource(source.Bitmap, true);
legacy.Apply(effect); legacy.Apply(effect);
effect.Physical = 1; effect.Physical = 1;
using var output = effect.Output; using var output = effect.Output;
+28 -38
ファイルの表示
@@ -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,19 +11,21 @@ public sealed partial class SpectralShaderContractTests
{ {
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",
["filterOrigin"] = "FilterOrigin",
["filterVertical"] = "FilterVertical",
["samples"] = "Samples", ["samples"] = "Samples",
["taps"] = "Taps",
}; };
static string Source { get; } = ShaderSource("SpectrumColorShiftPhysical.hlsl"); static string Source { get; } = ShaderSource("Physical.hlsli");
static string SrgbSource { get; } = ShaderSource("Srgb.hlsli"); static string SrgbSource { get; } = ShaderSource("Srgb.hlsli");
@@ -32,22 +33,17 @@ public sealed partial class SpectralShaderContractTests
static string Here([CallerFilePath] string path = "") => path; static string Here([CallerFilePath] string path = "") => path;
static int LinearInput { get; } = (int)typeof(SpectrumColorShiftCustomEffect).GetField("LinearInput", BindingFlags.NonPublic | BindingFlags.Static)!.GetRawConstantValue()!;
static Type ConstantBuffer => typeof(EffectImpl).GetNestedType("PhysicalConstantBuffer", BindingFlags.NonPublic)!; static Type ConstantBuffer => typeof(EffectImpl).GetNestedType("PhysicalConstantBuffer", BindingFlags.NonPublic)!;
[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(@"Texture2D\s+LinearTexture\s*:\s*register\(t(?<register>\d+)\)")] [GeneratedRegex(@"Texture2D\s+LightTexture\s*:\s*register\(t(?<register>\d+)\)")]
private static partial Regex TexturePattern(); private static partial Regex TexturePattern();
[GeneratedRegex(@"float4\s+\w+\s*:\s*TEXCOORD(?<index>\d+)")] [GeneratedRegex(@"float4\s+\w+\s*:\s*TEXCOORD(?<index>\d+)")]
private static partial Regex CoordinatePattern(); private static partial Regex CoordinatePattern();
[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) => Constant(Source, name); static float Constant(string name) => Constant(Source, name);
static float Constant(string source, string name) static float Constant(string source, string name)
@@ -56,8 +52,8 @@ public sealed partial class SpectralShaderContractTests
[Fact] [Fact]
public void TheShaderAndTheEffectAgreeOnTheConstants() public void TheShaderAndTheEffectAgreeOnTheConstants()
{ {
Assert.Equal(Spectrum.MaxSteps, Constant("MaxSteps"));
Assert.Equal(Spectrum.SpectralTableLength, Constant("TableSize")); Assert.Equal(Spectrum.SpectralTableLength, Constant("TableSize"));
Assert.Equal(SpectralFilter.TableLength, Constant("FilterTableSize"));
Assert.Equal((int)ShiftMode.Radial, Constant("ModeRadial")); Assert.Equal((int)ShiftMode.Radial, Constant("ModeRadial"));
Assert.Equal((int)ShiftMode.Rotational, Constant("ModeRotational")); Assert.Equal((int)ShiftMode.Rotational, Constant("ModeRotational"));
Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift")); Assert.Equal(ShiftGeometry.MaxRadialShift, Constant("MaxRadialShift"));
@@ -66,7 +62,7 @@ public sealed partial class SpectralShaderContractTests
[Fact] [Fact]
public void TheShaderReadsTheTextureOfTheLinearizedInput() public void TheShaderReadsTheTextureOfTheLinearizedInput()
{ {
Assert.Equal(LinearInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture)); Assert.Equal(SpectrumColorShiftCustomEffect.LightInput, int.Parse(TexturePattern().Match(Source).Groups["register"].Value, CultureInfo.InvariantCulture));
} }
[Fact] [Fact]
@@ -74,48 +70,42 @@ public sealed partial class SpectralShaderContractTests
{ {
var declared = CoordinatePattern().Matches(Source).Select(match => int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture)); var declared = CoordinatePattern().Matches(Source).Select(match => int.Parse(match.Groups["index"].Value, CultureInfo.InvariantCulture));
Assert.Equal(Enumerable.Range(0, LinearInput + 1), declared.Order()); Assert.Equal(Enumerable.Range(0, SpectrumColorShiftCustomEffect.LightInput + 1), declared.Order());
} }
[Theory] [Theory]
[InlineData("DecodeThreshold", 0.04045f)] [InlineData("SrgbDecodeThreshold", 0.04045f)]
[InlineData("EncodeThreshold", 0.0031308f)] [InlineData("SrgbEncodeThreshold", 0.0031308f)]
[InlineData("LowSlope", 12.92f)] [InlineData("SrgbLowSlope", 12.92f)]
[InlineData("Offset", 0.055f)] [InlineData("SrgbOffset", 0.055f)]
[InlineData("Scale", 1.055f)] [InlineData("SrgbScale", 1.055f)]
[InlineData("Exponent", 2.4f)] [InlineData("SrgbExponent", 2.4f)]
public void TheSrgbHeaderHoldsTheStandardTransferConstants(string name, float expected) public void TheSrgbHeaderHoldsTheStandardTransferConstants(string name, float expected)
=> Assert.Equal(expected, Constant(SrgbSource, name)); => Assert.Equal(expected, Constant(SrgbSource, name));
[Fact] [Fact]
public void TheSrgbCurvesMeetAtTheThresholds() public void TheSrgbCurvesMeetAtTheThresholds()
{ {
var slope = Constant(SrgbSource, "LowSlope"); var slope = Constant(SrgbSource, "SrgbLowSlope");
var linearEnd = Constant(SrgbSource, "EncodeThreshold"); var linearEnd = Constant(SrgbSource, "SrgbEncodeThreshold");
var power = Constant(SrgbSource, "Scale") * MathF.Pow(linearEnd, 1f / Constant(SrgbSource, "Exponent")) - Constant(SrgbSource, "Offset"); var power = Constant(SrgbSource, "SrgbScale") * MathF.Pow(linearEnd, 1f / Constant(SrgbSource, "SrgbExponent")) - Constant(SrgbSource, "SrgbOffset");
Assert.Equal(Constant(SrgbSource, "DecodeThreshold"), slope * linearEnd, 1e-5f); Assert.Equal(Constant(SrgbSource, "SrgbDecodeThreshold"), slope * linearEnd, 1e-5f);
Assert.Equal(slope * linearEnd, power, 1e-5f); Assert.Equal(slope * linearEnd, power, 1e-5f);
} }
[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.SpectralTableLength + SpectralFilter.TableLength), ConstantBufferContract.SizeOf(ConstantBuffer));
Assert.Equal(16 * (4 + Spectrum.SpectralTableLength), size);
} }
} }
+5 -5
ファイルの表示
@@ -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;
+38
ファイルの表示
@@ -113,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()
{ {
+1 -1
ファイルの表示
@@ -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;
+3 -3
ファイルの表示
@@ -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;
+1 -1
ファイルの表示
@@ -24,7 +24,7 @@ public sealed class StepCountRenderingTests
using var context = devices.CreateContext(); using var context = devices.CreateContext();
using var source = new SourceImage(context, 48, 32, Gradient); using var source = new SourceImage(context, 48, 32, Gradient);
using var effect = new SpectrumColorShiftCustomEffect(context); using var effect = new SpectrumColorShiftCustomEffect(context);
effect.SetInput(0, source.Bitmap, true); effect.SetSource(source.Bitmap, true);
using var output = effect.Output; using var output = effect.Output;
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1)) foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
-61
ファイルの表示
@@ -1,61 +0,0 @@
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
namespace SpectrumColorShift.Tests;
public sealed partial class StepShadersTests
{
static string Project { get; } = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Here())!, "..", "SpectrumColorShift.Shader", "SpectrumColorShift.Shader.vcxproj"));
static string Here([CallerFilePath] string path = "") => path;
[GeneratedRegex(@"<StepCount Include=""(?<counts>[^""]+)""")]
private static partial Regex CountsPattern();
[Fact]
public void TheCountsCoverTheWholeRangeInWholeQuanta()
{
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), StepShaders.Counts);
}
[Fact]
public void TheShaderProjectCompilesExactlyTheseCounts()
{
var compiled = CountsPattern().Match(Project).Groups["counts"].Value.Split(';').Select(count => int.Parse(count, CultureInfo.InvariantCulture));
Assert.Equal(StepShaders.Counts, compiled);
}
[Fact]
public void EveryCountHasItsOwnShaderInEachFamily()
{
var ids = StepShaders.Counts.SelectMany(count => new[] { StepShaders.Select(false, count), StepShaders.Select(true, count) }).ToList();
Assert.Equal(2 * StepShaders.Counts.Count(), ids.Distinct().Count());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void StepsShareTheShaderOfTheirPaddedCount(bool physical)
{
foreach (var steps in Enumerable.Range(Spectrum.MinSteps, Spectrum.MaxSteps - Spectrum.MinSteps + 1))
Assert.Equal(StepShaders.Select(physical, Spectrum.Padded(steps)), StepShaders.Select(physical, steps));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void EveryCountIsShippedAsAResource(bool physical)
{
foreach (var count in StepShaders.Counts)
{
var bytes = YukkuriMovieMaker.Commons.PackResourceReader.ReadAllBytes(ShaderResourceUri.Get(StepShaders.ResourceName(physical, count)));
Assert.True(bytes.Length > 0, $"{StepShaders.ResourceName(physical, count)}");
}
}
}
+1 -1
ファイルの表示
@@ -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")));
} }
+6
ファイルの表示
@@ -0,0 +1,6 @@
namespace SpectrumColorShift;
internal static class Quantum
{
public static int RoundUp(int value, int quantum) => (value + quantum - 1) / quantum * quantum;
}
+69
ファイルの表示
@@ -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))));
}
+23
ファイルの表示
@@ -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);
}
}
+101
ファイルの表示
@@ -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();
}
}
+20
ファイルの表示
@@ -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);
}
}
+2 -3
ファイルの表示
@@ -16,7 +16,7 @@ internal static class Spectrum
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) => (ClampSteps(steps) + StepQuantum - 1) / StepQuantum * StepQuantum; 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);
@@ -125,8 +125,7 @@ internal static class Spectrum
(float)(inverse[0] * x + inverse[1] * y + inverse[2] * z), (float)(inverse[0] * x + inverse[1] * y + inverse[2] * z),
(float)(inverse[3] * x + inverse[4] * y + inverse[5] * z), (float)(inverse[3] * x + inverse[4] * y + inverse[5] * z),
(float)(inverse[6] * x + inverse[7] * y + inverse[8] * z)); (float)(inverse[6] * x + inverse[7] * y + inverse[8] * z));
table[index * EntriesPerStep] = new Vector4(gain, (float)(y / luminance)); new SpectralStep(gain, (float)(y / luminance), basis, (float)(Displacement(law, wavelength, reference) / norm)).Write(table, index);
table[index * EntriesPerStep + 1] = new Vector4(basis, (float)(Displacement(law, wavelength, reference) / norm));
} }
table[(steps * EntriesPerStep)..].Clear(); table[(steps * EntriesPerStep)..].Clear();
+11 -2
ファイルの表示
@@ -5,12 +5,14 @@
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<Version>1.2.0</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\%(Filename)%(Extension)" /> <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>
+138 -102
ファイルの表示
@@ -9,38 +9,40 @@ using YukkuriMovieMaker.Player.Video;
namespace SpectrumColorShift; namespace SpectrumColorShift;
internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBase internal sealed class SpectrumColorShiftCustomEffect : IDisposable
{ {
private const int SourceInput = 0; internal const int SourceInput = 0;
private const int LinearInput = 1; internal const int LightInput = 1;
private const int EffectInputs = LightInput + 1;
private readonly ShiftEffect _shift;
private readonly LinearizeCustomEffect _linearized; private readonly LinearizeCustomEffect _linearized;
public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices) : base(Create<EffectImpl>(devices)) public SpectrumColorShiftCustomEffect(IGraphicsDevicesAndContext devices)
{ {
_shift = new ShiftEffect(devices);
_linearized = new LinearizeCustomEffect(devices); _linearized = new LinearizeCustomEffect(devices);
if (!IsEnabled) if (!IsEnabled)
return; return;
using var linearized = _linearized.Output; using var light = _linearized.Output;
base.SetInput(LinearInput, linearized, true); _shift.SetInput(LightInput, light, true);
} }
public new bool IsEnabled => base.IsEnabled && _linearized.IsEnabled; public bool IsEnabled => _shift.IsEnabled && _linearized.IsEnabled;
public new void SetInput(int index, ID2D1Image? input, RawBool invalidate) public ID2D1Image Output => _shift.Output;
public void SetSource(ID2D1Image? source, RawBool invalidate)
{ {
base.SetInput(index, input, invalidate); _shift.SetInput(SourceInput, source, invalidate);
if (index == SourceInput) _linearized.SetInput(0, source, invalidate);
_linearized.SetInput(SourceInput, input, invalidate);
} }
protected override void DisposeCore(nint nativePointer, bool disposing) public void Dispose()
{ {
if (disposing) _linearized.Dispose();
_linearized.Dispose(); _shift.Dispose();
base.DisposeCore(nativePointer, disposing);
} }
internal enum PropertyIndex internal enum PropertyIndex
@@ -57,20 +59,27 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
Physical, 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 => SetValue((int)PropertyIndex.Physical, value); } public int Physical { set => _shift.SetValue((int)PropertyIndex.Physical, value); }
[CustomEffect(2)] 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 PhysicalConstantBuffer _physicalCb;
private ShiftMode _mode = ShiftMode.Linear; private ShiftMode _mode = ShiftMode.Linear;
@@ -78,18 +87,20 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
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 _spectralStale = true;
private bool _physical; private bool _physical;
private SpectrumKey? _tableKey;
private SpectrumKey? _spectralKey;
private FilterKey? _filterKey;
private SpectralFilter.Layout _filter;
private Guid _shader = GUID_PixelShader; 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();
} }
} }
@@ -101,7 +112,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
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();
} }
} }
@@ -109,11 +119,11 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
[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();
} }
} }
@@ -145,10 +155,10 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
[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();
} }
} }
@@ -160,8 +170,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set set
{ {
_dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating; _dispersion = value == (int)DispersionLaw.Prism ? DispersionLaw.Prism : DispersionLaw.Grating;
_tableStale = true;
_spectralStale = true;
UpdateConstants(); UpdateConstants();
} }
} }
@@ -173,8 +181,6 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set set
{ {
_referenceWavelength = Spectrum.ClampReference(value); _referenceWavelength = Spectrum.ClampReference(value);
_tableStale = true;
_spectralStale = true;
UpdateConstants(); UpdateConstants();
} }
} }
@@ -186,9 +192,7 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
set set
{ {
_steps = Spectrum.ClampSteps(value); _steps = Spectrum.ClampSteps(value);
_cb.Steps = _steps; _header.Steps = _steps;
_tableStale = true;
_spectralStale = true;
UpdateConstants(); UpdateConstants();
} }
} }
@@ -204,19 +208,22 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
} }
} }
public EffectImpl() : base(StepShaders.DefaultBytes) internal int FilterTaps => _physical ? CurrentFilter().Taps : 0;
private SpectrumKey CurrentSpectrum => new(_steps, _referenceWavelength, _dispersion);
public EffectImpl() : base(ShaderVariants.DefaultBytes)
{ {
_cb.Direction = Vector2.UnitX; _header.Direction = Vector2.UnitX;
_cb.Radius = 1f; _header.Radius = 1f;
_cb.Strength = 1f; _header.Strength = 1f;
_cb.Mode = (int)ShiftMode.Linear; _header.Steps = Spectrum.DefaultSteps;
_cb.Steps = Spectrum.DefaultSteps;
} }
public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph) public override void Initialize(ID2D1EffectContext effectContext, ID2D1TransformGraph transformGraph)
{ {
base.Initialize(effectContext, transformGraph); base.Initialize(effectContext, transformGraph);
StepShaders.Load(effectContext); ShaderVariants.LoadAll(effectContext);
} }
protected override void UpdateConstants() protected override void UpdateConstants()
@@ -226,19 +233,14 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
try try
{ {
_cb.SpreadScale = ShiftGeometry.Spread(_mode, _cb.Distance, _cb.Radius); var spread = ShiftGeometry.Spread(_mode, _header.Distance, _header.Radius);
var filter = _physical ? CurrentFilter() : default;
var shader = StepShaders.Select(_physical, _steps);
if (shader != _shader)
{
drawInformation.SetPixelShader(shader, PixelOptions.None);
_shader = shader;
}
SelectShader(filter);
if (_physical) if (_physical)
SendPhysicalConstants(); SendPhysicalConstants(spread, filter);
else else
SendConstants(); SendConstants(spread);
} }
catch (Exception exception) catch (Exception exception)
{ {
@@ -247,34 +249,57 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
} }
} }
private void SendConstants() private SpectralFilter.Layout CurrentFilter()
{ {
if (_tableStale) var spectral = CurrentSpectrum;
if (_spectralKey != spectral)
{ {
Spectrum.Fill(_cb.Samples, _steps, _referenceWavelength, _dispersion); Spectrum.FillSpectral(_physicalCb.Samples, spectral.Steps, spectral.Reference, spectral.Law);
_tableStale = false; _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); drawInformation!.SetPixelShaderConstantBuffer(_cb);
} }
private void SendPhysicalConstants() private void SendPhysicalConstants(float spread, SpectralFilter.Layout filter)
{ {
if (_spectralStale) _physicalCb.Header = _header;
{ _physicalCb.SpreadScale = spread;
Spectrum.FillSpectral(_physicalCb.Samples, _steps, _referenceWavelength, _dispersion); _physicalCb.FilterOrigin = filter.Origin;
_spectralStale = false; _physicalCb.FilterVertical = filter.Vertical ? 1 : 0;
}
_physicalCb.InputBounds = _cb.InputBounds;
_physicalCb.Direction = _cb.Direction;
_physicalCb.Center = _cb.Center;
_physicalCb.Distance = _cb.Distance;
_physicalCb.Radius = _cb.Radius;
_physicalCb.Strength = _cb.Strength;
_physicalCb.Mode = _cb.Mode;
_physicalCb.Steps = Spectrum.Padded(_steps);
_physicalCb.SpreadScale = _cb.SpreadScale;
drawInformation!.SetPixelShaderConstantBuffer(_physicalCb); drawInformation!.SetPixelShaderConstantBuffer(_physicalCb);
} }
@@ -292,11 +317,11 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
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;
} }
@@ -304,15 +329,15 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
{ {
var requested = inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top var requested = inputRect.Right <= inputRect.Left || inputRect.Bottom <= inputRect.Top
? inputRect ? inputRect
: ShiftGeometry.Input(outputRect, _mode, _cb.Distance, _cb.Direction, _cb.Center, _cb.Radius); : ShiftGeometry.Input(outputRect, _mode, _header.Distance, _header.Direction, _header.Center, _header.Radius);
var used = _physical ? LinearInput : SourceInput; var activeInput = _physical ? LightInput : SourceInput;
for (var index = 0; index < inputRects.Length; index++) for (var index = 0; index < inputRects.Length; index++)
inputRects[index] = index == used ? requested : default; inputRects[index] = index == activeInput ? requested : default;
} }
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);
@@ -322,10 +347,14 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
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
{ {
@@ -338,8 +367,14 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
private Vector4 _element; private Vector4 _element;
} }
[InlineArray(SpectralFilter.TableLength)]
private struct FilterTapTable
{
private Vector4 _element;
}
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
private struct PhysicalConstantBuffer private struct ShiftHeader
{ {
public Vector4 InputBounds; public Vector4 InputBounds;
public Vector2 Direction; public Vector2 Direction;
@@ -347,29 +382,30 @@ internal sealed class SpectrumColorShiftCustomEffect : D2D1CustomShaderEffectBas
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;
public float SpreadScale;
public float Pad1;
public float Pad2;
public SpectralSampleTable Samples;
} }
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
private struct ConstantBuffer private struct ConstantBuffer
{ {
public Vector4 InputBounds; public ShiftHeader Header;
public Vector2 Direction;
public Vector2 Center;
public float Distance;
public float Radius;
public float Strength;
public int Mode;
public int Steps;
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;
}
} }
} }
+2 -2
ファイルの表示
@@ -94,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()
@@ -112,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;
} }
-56
ファイルの表示
@@ -1,56 +0,0 @@
using Vortice.Direct2D1;
using YukkuriMovieMaker.Commons;
namespace SpectrumColorShift;
internal static class StepShaders
{
private const string LegacyName = "SpectrumColorShift";
private const string PhysicalName = "SpectrumColorShiftPhysical";
private static readonly Variants Legacy = new(LegacyName);
private static readonly Variants Physical = new(PhysicalName);
public static IEnumerable<int> Counts => Enumerable.Range(0, Variants.Length).Select(CountAt);
public static byte[] DefaultBytes => Legacy.Bytes(Spectrum.DefaultSteps);
public static string ResourceName(bool physical, int count) => (physical ? Physical : Legacy).ResourceName(count);
public static Guid Select(bool physical, int steps) => (physical ? Physical : Legacy).Id(steps);
public static void Load(ID2D1EffectContext effectContext)
{
Legacy.Load(effectContext);
Physical.Load(effectContext);
}
private static int CountAt(int index) => Spectrum.MinSteps + index * Spectrum.StepQuantum;
private sealed class Variants(string name)
{
public static int Length { get; } = (Spectrum.MaxSteps - Spectrum.MinSteps) / Spectrum.StepQuantum + 1;
private readonly Guid[] _ids = [.. Enumerable.Range(0, Length).Select(_ => Guid.NewGuid())];
private readonly Lazy<byte[]>[] _bytes = [.. Enumerable.Range(0, Length).Select(index => new Lazy<byte[]>(() => Read(name, CountAt(index))))];
public string ResourceName(int count) => $"{name}{count}";
public Guid Id(int steps) => _ids[IndexOf(steps)];
public byte[] Bytes(int steps) => _bytes[IndexOf(steps)].Value;
public void Load(ID2D1EffectContext effectContext)
{
for (var index = 0; index < Length; index++)
{
var bytes = _bytes[index].Value;
effectContext.LoadPixelShader(_ids[index], bytes, bytes.Length);
}
}
private static int IndexOf(int steps) => (Spectrum.Padded(steps) - Spectrum.MinSteps) / Spectrum.StepQuantum;
private static byte[] Read(string name, int count) => PackResourceReader.ReadAllBytes(ShaderResourceUri.Get($"{name}{count}"));
}
}
+1 -1
ファイルの表示
@@ -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
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
2 SpectrumColorShift 色ずれ(スペクトラム) 色ズレ(スペクトラム) Color Shift (Spectrum) 色偏(光谱) 色偏(光譜) 색 어긋남 (스펙트럼) Desfase de color (espectro) إزاحة اللون (الطيف) Pergeseran Warna (Spektrum)
3 ShiftGroup 色ずれ Color Shift 色偏 色偏 색 어긋남 Desfase de color إزاحة اللون Pergeseran Warna
4 SpectrumGroup スペクトル Spectrum 光谱 光譜 스펙트럼 Espectro الطيف Spektrum
5 Distance 距離 Distance 距离 距離 거리 Distancia المسافة Jarak
バイナリ
ファイルの表示
バイナリファイルは表示されません。

変更前

幅:  |  高さ:  |  サイズ: 1.3 MiB

変更後

幅:  |  高さ:  |  サイズ: 1.4 MiB