コミットを比較

...
74 コミット
作成者 SHA1 メッセージ 日付
routersys 96558947ed Gitea Actions のワークフローを直す 2026-11-08 13:05:42 +09:00
routersys d9fcd6fcfc Gitea Actions のワークフローを直す 2026-11-08 10:15:17 +09:00
routersys b3703e1afc Gitea Actions のワークフローを直す 2026-11-08 09:48:15 +09:00
routersys 20e19a9d9f 過去のタグ用ワークフローを消す 2026-11-08 03:57:47 +09:00
routersys 64e5799493 Gitea Actions のワークフローを直す 2026-11-08 03:55:52 +09:00
routersys 87c861bc16 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:34:20 +09:00
routersys 9e8fd2d897 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-08 01:06:49 +09:00
routersys 50b21ccb01 Gitea Actions の過去のタグ用ワークフローを足す 2026-11-07 22:35:57 +09:00
routersys 8fe4a86246 Gitea Actions のワークフローを直す 2026-11-07 22:07:52 +09:00
routersys cce60990e2 Gitea Actions のワークフローを足す 2026-11-07 19:52:56 +09:00
routersys cf62a6ef5d 画像の参照先をGiteaへ移す 2026-11-07 18:21:33 +09:00
routersys 8d4f771f8d サブモジュールの参照先をGiteaへ移す 2026-11-07 18:17:35 +09:00
routersys dc2e015b1a READMEの数式をLaTeXで書く 2026-10-20 19:06:24 +09:00
routersys b0a0c5cc8f バージョンをv1.20.3へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.3 のコミットから作成しました
2026-07-05 19:52:33 +09:00
routersys 40f1322042 [fast]に小処理時の低速化リスクの注意書きを追加 2026-07-05 19:37:27 +09:00
routersys d1b0439611 バージョンをv1.20.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.2 のコミットから作成しました
2026-07-05 19:19:02 +09:00
routersys 30d6f62d15 READMEを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:52 +09:00
routersys ac3a1e350e サイトを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:45 +09:00
routersys 0a7a2c7d40 全言語ドキュメントを[fast]強制委譲の仕様へ更新 2026-07-05 19:17:39 +09:00
routersys 1a97536bc5 テストへ[fast]の強制委譲を検証する項目を追加 2026-07-05 19:17:29 +09:00
routersys 8f954c7a2e 従来エンジンにもforce引数を復元 2026-07-05 19:17:21 +09:00
routersys 20509b19c9 ワーカーにforce引数を復元し[fast]で強制委譲 2026-07-05 19:17:13 +09:00
routersys e4bdf0df19 GPU処理にforce引数を追加しきい値を無視可能に 2026-07-05 19:17:06 +09:00
routersys 1f421dd158 バージョンをv1.20.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.1 のコミットから作成しました
2026-07-05 18:45:22 +09:00
routersys e56a2d85d7 CHANGELOGをv1.20.1の内容へ更新 2026-07-05 18:45:22 +09:00
routersys 969cf52299 READMEを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 01785267fc サイトを自動GPU委譲の仕様へ更新 2026-07-05 18:24:08 +09:00
routersys 206001888c 全言語ドキュメントを自動GPU委譲の仕様へ更新 2026-07-05 18:24:07 +09:00
routersys 7c8776dd05 MoonSharpの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys d6756ad3c8 ワーカーの画像加工を自動GPU委譲へ統一 2026-07-05 18:24:07 +09:00
routersys 57c3b346d8 バージョンをv1.20.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.20.0 のコミットから作成しました
2026-07-05 17:44:48 +09:00
routersys 55dde273ae CHANGELOGをv1.20.0の内容へ全置換 2026-07-05 17:43:02 +09:00
routersys a6a9963c85 補完候補へ構文拡張キーワードfastを登録 2026-07-05 17:26:28 +09:00
routersys fb7614d6fb 構文規則属性にIsCatalogとKeywordを追加 2026-07-05 17:26:28 +09:00
routersys a7a8c6b117 ハードウェアデバイス再生成に予算制限を適用 2026-07-05 17:12:16 +09:00
routersys 8b59897992 ホストコールバック時間をネイティブタイムアウトから除外 2026-07-05 17:12:15 +09:00
routersys 0d8f1e5102 [fast]の記載例を単独行形式へ統一 2026-07-05 16:37:10 +09:00
routersys e6165ca5a3 [fast]の診断を英語化し単独行形式をテスト 2026-07-05 16:37:10 +09:00
routersys 2bd54674c1 READMEへ[fast]高速化マーカーを追記 2026-07-05 16:13:11 +09:00
routersys 9a733807e8 [fast]をサイト構文ドキュメントへ追記 2026-07-05 16:13:08 +09:00
routersys f14c689353 [fast]を全言語ドキュメントへ追記 2026-07-05 16:13:05 +09:00
routersys d4443a1eef [fast]と高速化経路のテストを追加 2026-07-05 16:12:51 +09:00
routersys b618a3093b [fast]マーカーの書き換え規則を追加 2026-07-05 16:12:47 +09:00
routersys a03ba45f2a 拡張構文の書き換え診断を全経路へ通す 2026-07-05 16:12:44 +09:00
routersys 56c38b2891 エンジンに__fast_*プリミティブを配線 2026-07-05 16:12:31 +09:00
routersys 68b730e6d2 ワーカーに[fast]高速化プリミティブを追加 2026-07-05 16:12:28 +09:00
routersys ce7b15121c 画像加工にGPU委譲の明示フラグを追加 2026-07-05 16:12:26 +09:00
routersys 50b20e3060 GPU生成器の増分キャッシュをEquatableArray化 2026-07-05 13:52:30 +09:00
routersys c1f4fa2dc5 生成器をLua/Gpuへ整理し型を1ファイル1クラス化 2026-07-05 13:36:03 +09:00
routersys af9c5af173 GPU内部シェーダーをビルド時DXBC化 2026-07-05 13:22:06 +09:00
routersys 406a4c1a1b LuaJIT画像処理をGPU委譲 2026-07-05 11:19:28 +09:00
routersys b732dd1b90 畳み込みHLSLの予約語衝突を修正 2026-07-05 10:49:56 +09:00
routersys 1e93df21ef MoonSharp画像処理をGPU委譲 2026-07-05 10:44:17 +09:00
routersys 3bd6133bef GPUシェーダー管理を属性生成化 2026-07-05 10:40:33 +09:00
routersys 0c05fe2198 GPU画像処理をHW実行へ限定 2026-07-05 10:22:19 +09:00
routersys 775791d1e1 画像処理CPU基準を共有化 2026-07-05 10:16:12 +09:00
routersys a291d66567 画像処理のGPU委譲契約を追加 2026-07-05 10:11:26 +09:00
routersys 31d26c0a70 GPU基盤を専用プロジェクトへ分離 2026-07-05 10:05:41 +09:00
routersys 88b95cc09a 構文規則モデルを専用ファイルへ分離 2026-07-05 09:08:25 +09:00
routersys 9ff328d03a API生成器の型宣言を1ファイル1型へ分離 2026-07-05 09:08:19 +09:00
routersys 481bce261e バージョンをv1.19.2へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.19.2 のコミットから作成しました
2026-07-05 08:57:20 +09:00
routersys 421acf1a6a CHANGELOGへ毎フレーム更新の改善を追記 2026-07-05 08:53:47 +09:00
routersys 1d01e9d275 obj寸法の更新をボックス化しないSetへ置換 2026-07-05 08:53:46 +09:00
routersys 1a3394b8f5 変数更新の発行を型付きDynValueへ変更しボックス化を除去 2026-07-05 08:53:45 +09:00
routersys 52bbff8284 バージョンをv1.19.1へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.19.1 のコミットから作成しました
2026-07-05 08:39:44 +09:00
routersys b150970f83 getpixelregionの値生成を共有DynValueキャッシュへ置換 2026-07-05 08:39:43 +09:00
routersys 6ce23d486a バージョンをv1.19.0へ更新
リリース / build-and-release (workflow_dispatch) Actions がタグ v1.19.0 のコミットから作成しました
2026-07-05 08:27:35 +09:00
routersys 024723a029 READMEへ画像加工5関数を追加 2026-07-05 08:27:34 +09:00
routersys 4746f01134 サイトへ画像加工5関数の説明を追加 2026-07-05 08:27:32 +09:00
routersys f2ea36ba49 全言語ドキュメントへ画像加工5関数を追加 2026-07-05 08:27:32 +09:00
routersys adf47608d2 画像加工5関数の両エンジンテストと補完カタログを追加 2026-07-05 08:27:13 +09:00
routersys f916c810dc MoonSharpレーンへ画像加工5関数を追加 2026-07-05 08:27:12 +09:00
routersys 9b86a3cb10 ワーカーへfill/pixelregion/convolve/resizeを追加 2026-07-05 08:27:11 +09:00
routersys 0fd1194596 コンテキストへ塗り・領域・畳み込み・拡縮のバッファ演算を追加 2026-07-05 08:27:10 +09:00
80個のファイルの変更、4277行の追加、173行の削除

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

+228
ファイルの表示
@@ -0,0 +1,228 @@
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@v4
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
- 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" = "LuaScript-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
env:
CI: 'true'
run: |
dotnet build LuaScript/LuaScript.csproj `
-c Release `
-p:YMM4DirPath="${{ steps.ymm4.outputs.YMM4_DIR }}" `
-p:Platform=x64
- name: パッケージの作成
id: package
shell: pwsh
run: |
$version = "${{ steps.version.outputs.TAG }}"
$outDir = "LuaScript/bin/x64/Release/net10.0-windows10.0.19041.0"
$stageRoot = "stage/LuaScript"
$pkgName = "LuaScript_$version.ymme"
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Kernel.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
Copy-Item "$outDir/native/worker.lua" "$stageRoot/native/"
Copy-Item "$outDir/native/shim.lua" "$stageRoot/native/"
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 "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
echo "PKG_NAME=$pkgName" >> $env:GITHUB_OUTPUT
- 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: .github/CHANGELOG.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 -56
ファイルの表示
@@ -1,73 +1,28 @@
# v1.18.0 - Lua スクリプト for YMM4 # v1.20.3 - Lua スクリプト for YMM4
AviUtl の音声取得関数 obj.getaudio を追加したリリースです。編集中のシーン全体の音声、エフェクトを付けたアイテム自身の音声、任意の音声ファイルから、PCM・周波数スペクトラム・フーリエ変換のデータを取得し、音に反応する演出をスクリプトで作れます。あわせて obj.getobject が返すテーブルへ他アイテムのメタデータを追加し、合成音声アイテムも参照の対象にしました。どちらも従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で動作し、音声の取得とメタデータの解決はホスト側で一度だけ行うため、実行結果は両エンジンで一致します。 [fast] マーカーの注意書きを補うドキュメント更新リリースです。v1.20.2 で [fast] は obj.fill / obj.convolve / obj.resize の処理量のしきい値を無視して GPU へ委譲する仕様になりましたが、処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回り、かえって遅くなる場合があることを明記しました。動作に関わる実装、API、実行結果、エラーの扱いに変更はありません。
--- ---
## 新機能 ## 変更
### obj.getaudio(buf, file [, type, size]) ### [fast] は小さな処理で遅くなる場合があることを明記
音声データを取得します。 [fast] は obj.fill / obj.convolve / obj.resize のしきい値を無視しますが、GPU への委譲には往復コストがあります。処理量が小さいときは CPU 実行のほうが速い場合があるため、README、サイト、付属ドキュメントに注意書きを追加しました。
local buf = {} - 付属の 8 言語ドキュメントの [fast] の節へ、同じ注意書きを追加しました。
local n, rate = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
for i = 1, n do
obj.draw((i - n / 2) * 8, -buf[i] / 200)
end
- buf に渡したテーブルの buf[1]~buf[n] へデータを格納し、取得したデータ数とサンプリングレートを返します。buf に nil を渡すと、テーブルを 3 番目の戻り値として返します。
- file には音声ファイルのパスを指定します。特別な名前として "audiobuffer" と "itembuffer" を受け付けます。
- "audiobuffer" は編集中のシーン全体の音声で、タイムライン上の全アイテムを合成した音声を取得します。AviUtl の「編集中の音声データ」と同じ解釈です。読み取り位置はタイムラインの現在の再生位置です。
- "itembuffer" は AviUtl に存在しない YMM4 向けの独自拡張で、このエフェクトを付けたアイテム自身の音声を取得します。音量・パン・フェード・音声エフェクトを適用した後の音声で、合成音声アイテムに付ければそのセリフの音声だけに反応できます。音声を持たないアイテム(画像や図形等)ではデータ数 0 になります。
- type は取得するデータの種類で、省略すると "pcm" になります。
- "pcm" : 16bit スケール基準(-32768~32767)のモノラル PCM です。現在位置から連続したサンプルを返します。
- "spectrum" : 周波数帯ごとの音量データです。size は分割する帯域の数で、最大 512、省略時は 32 です。
- "fourier" : 離散フーリエ変換の振幅データ(0.0~1.0 目安)です。周波数範囲は 1/2048~1/2 で、省略時は 1024 個です。
- "xxxx.l" / "xxxx.r" : 上記種別の左 / 右チャンネル版です。無指定のときは左右の平均です。
- size は取得するデータ数で、取得できた数が指定より少ないことがあります。1 回で取得できるデータ数は最大 1024 個です。
- ファイルと "itembuffer" の読み取り位置はオブジェクトの現在の再生位置(obj.time)です。spectrum / fourier は読み取り位置からの区間を解析して返します。
- 取得できない場合はデータ数 0 を返し、エラーにはなりません。
### obj.getobject のメタデータ
obj.getobject(tag [, frame]) が返すテーブルへ、他アイテムのメタデータを追加しました。
local o = obj.getobject("BGM")
if o and o.exist then
obj.load("text", o.character .. ": " .. o.text)
end
- .length : アイテムのフレーム数を返します。
- .volume : 音量設定の現在値を返します。合成音声アイテム以外は 0 です。
- .character : キャラクター名を返します。合成音声アイテム以外は空文字列です。
- .text : セリフまたは表示テキストを返します。合成音声アイテムとテキストアイテム以外は空文字列です。
- .kind : アイテムの種別名を返します。
- 合成音声アイテムが参照の対象になりました。座標・拡大率・回転・不透明度は字幕の表示情報を返します。
--- ---
## 互換性・後方互換 ## 互換性・後方互換
- obj.getaudio は AviUtl 互換の関数として追加しました。"audiobuffer" の意味は AviUtl の「編集中の音声データ」に合わせています。buf の添字は 1 始まりで、AviUtl 向けの既存スクリプトの慣例と同じです。 - 動作に関わる実装の変更はありません。
- "itembuffer" は AviUtl / AviUtl2 に存在しない YMM4 向けの独自拡張です。AviUtl 向けに書かれた既存スクリプトへの影響はありません。 - API、構文、エンジンの自動振り分け、GPU 検証、CPU への自動フォールバックに変更はありません。
- obj.getaudio が 1 回で取得できるデータ数の上限は 1024 個です。AviUtl の代表的な用途(spectrum の帯域数 32 前後、fourier の 1024 個、pcm の 1000 個前後)はいずれも上限の範囲に収まります。 - v1.20.2 の [fast] の強制委譲仕様に変更はありません。
- obj.getobject の既存フィールドの意味と値に変更はありません。メタデータは追加のみで、従来の呼び出しはそのまま動きます。
- 未対応の type や読み取りの失敗はデータ数 0 の戻り値で表し、スクリプトを停止させません。
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.17.0 までの構文拡張と既存の API に変更はありません。
--- ---
## 内部実装 ## 内部実装
- PCM・スペクトラム・フーリエ変換の計算は LuaScript.Compat へ追加した AviUtlAudioConverter が担います。pcm は ±32768 のスケール、spectrum は窓 1024 の FFT の帯域平均を 2/N×32768 で正規化、fourier は窓 2048 の FFT の振幅を 2/N で正規化した値です。計算はホスト側で一度だけ行い、両エンジンは同じ結果を受け取るため、エンジン間の一致は構造的に保証されます。 - 動作に関わるコード変更はありません。
- 音声の取得は新設の AudioSampleProvider が担い、3 つの経路を持ちます。"audiobuffer" はシーンの公開メソッド Scene.TryCreateAudioSource で得たタイムライン音源を用います。これは公式コミュニティプラグインの音量取得系の映像エフェクトが同じ状況(映像エフェクトからの音声参照)で使っているのと同じ経路です。ファイルはプラグイン公開 API の AudioFileSourceFactory を用います。 - リリース対象のバージョン表記を v1.20.3 へ更新しました。
- "itembuffer" は EffectedItemSourceForEditorInfo を直接生成します。これは YMM4 のエディタ向けインターフェイス IEditorInfo.CreateItemAudioSource が返す実体と同じ公開クラスで、プロジェクトのサンプリングレートと音声アップサンプリング設定を反映した、YMM4 本体の編集時再生と同じ音声を返します。ただしこのクラスはプラグイン公開 API のアセンブリ(YukkuriMovieMaker.Plugin)ではなく本体側にあり、互換性の保証がありません。そのため生成はインライン展開を禁止した専用メソッドへ隔離し、将来の本体更新で型が失われた場合に発生する TypeLoadException を捕捉して、プラグイン公開 API の IAudioItem.CreateAudioSource(音量等を適用する前の音声)へ縮退します。例外がスクリプトへ漏れることはありません。
- "itembuffer" の自アイテムの特定は、シーンのアイテム一覧から自分のエフェクトを VideoEffects に含むアイテムを参照の同一性で探します。
- 音源はファイルパス・シーン・アイテムごとに 1 件ずつキャッシュし、対象が変わったときだけ作り直します。読み取り緩衝と結果配列は伸長のみの再利用で、定常状態の毎フレームの割り当てはありません。失敗はすべてデータ数 0 の戻り値で表し、例外を制御フローに使いません。
- 高速ランタイムにはプロセス間手順の呼出種別 CbKindGetAudio を追加しました。要求はタグ領域へ file と type の 2 文字列、応答は同じタグ領域へ double 配列で返します。タグ領域は 8192 バイトのため、1 回の取得上限が 1024 個になります。この返却方法は obj.setanchor の座標返却と同じ手口です。
- 音声は描画鍵で検知できない外部状態のため、obj.getaudio でデータを取得したフレームは描画キャッシュを使わず毎回再実行します。obj.load("scene") と同じ扱いです。
- obj.getobject のメタデータは、SceneObjectInfo へ Length / Volume / Character / Text / Kind を追加し、シーンオブジェクトリゾルバーを IVideoItem 基準へ改めて合成音声アイテムも列挙の対象にしました。高速ランタイムの応答は、数値を既存の結果領域、3 つの文字列をタグ領域へ区切り文字付きで返します。同じタグと同じフレームへの連続した問い合わせのフレーム内キャッシュは従来のままです。
- obj.effect と obj.brush が共有するパラメータ適用部品の名前を Ymm4PropertyBinder から ParameterBinder へ改めました。実装と適用結果に変更はありません。
- ドキュメントは付属の 8 言語、サイトの obj の関数・リファレンス・トップ・制限事項のページ、README を更新しました。あわせて既存ドキュメントの冗長なカッコ補足と強調記法を整理しました。
- テストは 3347 件です。v1.17.0 の 3332 件から、音声変換の pcm のスケールとチャンネル選択・不足時の短縮・スペクトラムの帯域位置・フーリエの正規化・未対応種別、MoonSharp レーンの getaudio の委譲の往復・既定値・失敗時の 0 返し・データ数の切り詰め、高速ランタイムの getaudio の呼出種別の往復と失敗時の 0 返し、両エンジンの getobject のメタデータの往復の検証を追加しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
+3 -3
ファイルの表示
@@ -1,11 +1,11 @@
======================================== ========================================
Luaスクリプト for YMM4 v1.18.0 Luaスクリプト for YMM4 v1.20.3
======================================== ========================================
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
ピクセルを直接制御できるプラグインです。 ピクセルを直接制御できるプラグインです。
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・ スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも 透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
対応しています。 塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。 からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
+1
ファイルの表示
@@ -77,6 +77,7 @@ jobs:
Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/" Copy-Item "$outDir/LuaScript.Compat.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/" Copy-Item "$outDir/LuaScript.Media.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/" Copy-Item "$outDir/LuaScript.Runtime.dll" "$stageRoot/"
Copy-Item "$outDir/LuaScript.Gpu.dll" "$stageRoot/"
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/" Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/" Copy-Item "$outDir/native/luajit.exe" "$stageRoot/native/"
Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/" Copy-Item "$outDir/native/lua51.dll" "$stageRoot/native/"
+1 -1
ファイルの表示
@@ -1,3 +1,3 @@
[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
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.18.0</Version> <Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
+7 -6
ファイルの表示
@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using LuaScript.Compat.Syntax;
namespace LuaScript.Compat namespace LuaScript.Compat
{ {
@@ -15,10 +16,10 @@ namespace LuaScript.Compat
public static string Transform(string source) => TransformWithMap(source).Code; public static string Transform(string source) => TransformWithMap(source).Code;
public static (string Code, int[] LineMap, int[] ChangedLines) TransformWithMap(string source) public static (string Code, int[] LineMap, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) TransformWithMap(string source)
{ {
if (string.IsNullOrEmpty(source)) if (string.IsNullOrEmpty(source))
return (source, [], []); return (source, [], [], []);
var lines = ScriptParserHelper.SplitLines(source); var lines = ScriptParserHelper.SplitLines(source);
bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd); bool hasSection = ScriptParserHelper.TryFindSection(lines, out int sectionStart, out int sectionEnd);
@@ -29,8 +30,8 @@ namespace LuaScript.Compat
if (!hasSection && prelude.Count == 0) if (!hasSection && prelude.Count == 0)
{ {
var (code, changed) = LuaSyntaxExtensions.RewriteWithMap(source); var (code, changed, preludeless) = LuaSyntaxExtensions.RewriteWithMap(source);
return (code, [], changed); return (code, [], changed, preludeless);
} }
var builder = new StringBuilder(source.Length + 64); var builder = new StringBuilder(source.Length + 64);
@@ -48,8 +49,8 @@ namespace LuaScript.Compat
lineMap[row++] = i; lineMap[row++] = i;
} }
var (rewritten, changedLines) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString()); var (rewritten, changedLines, diagnostics) = LuaSyntaxExtensions.RewriteWithMap(builder.ToString());
return (rewritten, lineMap, changedLines); return (rewritten, lineMap, changedLines, diagnostics);
} }
private static void AppendDeclarations(string line, List<string> prelude) private static void AppendDeclarations(string line, List<string> prelude)
+4 -3
ファイルの表示
@@ -6,10 +6,10 @@ namespace LuaScript.Compat
{ {
public static string Rewrite(string source) => RewriteWithMap(source).Code; public static string Rewrite(string source) => RewriteWithMap(source).Code;
public static (string Code, int[] ChangedLines) RewriteWithMap(string source) public static (string Code, int[] ChangedLines, LuaRewriteDiagnostic[] Diagnostics) RewriteWithMap(string source)
{ {
if (string.IsNullOrEmpty(source)) if (string.IsNullOrEmpty(source))
return (source, []); return (source, [], []);
var tokens = LuaSyntaxLexer.Tokenize(source); var tokens = LuaSyntaxLexer.Tokenize(source);
var context = new LuaRewriteContext(tokens); var context = new LuaRewriteContext(tokens);
@@ -42,7 +42,8 @@ namespace LuaScript.Compat
} }
} }
return context.Changed ? (context.Serialize(), context.ChangedLines) : (source, []); var diagnostics = context.Diagnostics;
return context.Changed ? (context.Serialize(), context.ChangedLines, diagnostics) : (source, [], diagnostics);
} }
} }
} }
+9
ファイルの表示
@@ -8,6 +8,7 @@ namespace LuaScript.Compat.Syntax
private readonly List<LuaSyntaxToken> _input; private readonly List<LuaSyntaxToken> _input;
private readonly List<LuaSyntaxToken> _output; private readonly List<LuaSyntaxToken> _output;
private List<int>? _changedLines; private List<int>? _changedLines;
private List<LuaRewriteDiagnostic>? _diagnostics;
private int _line = 1; private int _line = 1;
private int _lastChangedLine; private int _lastChangedLine;
private int _temporaries; private int _temporaries;
@@ -28,6 +29,14 @@ namespace LuaScript.Compat.Syntax
public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray(); public int[] ChangedLines => _changedLines is null ? [] : _changedLines.ToArray();
public LuaRewriteDiagnostic[] Diagnostics => _diagnostics is null ? [] : _diagnostics.ToArray();
public void AddDiagnostic(string message)
{
(_diagnostics ??= new List<LuaRewriteDiagnostic>()).Add(new LuaRewriteDiagnostic(_line, message));
MarkChanged();
}
public bool AtEnd => Index >= _input.Count; public bool AtEnd => Index >= _input.Count;
public LuaSyntaxToken Current => _input[Index]; public LuaSyntaxToken Current => _input[Index];
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Compat.Syntax
{
internal readonly record struct LuaRewriteDiagnostic(int Line, string Message);
}
+4
ファイルの表示
@@ -6,5 +6,9 @@ namespace LuaScript.Compat.Syntax
internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute internal sealed class LuaSyntaxRuleAttribute(int order) : Attribute
{ {
public int Order { get; } = order; public int Order { get; } = order;
public bool IsCatalog { get; set; }
public string Keyword { get; set; } = "";
} }
} }
+76
ファイルの表示
@@ -0,0 +1,76 @@
namespace LuaScript.Compat.Syntax.Rules
{
[LuaSyntaxRule(2, IsCatalog = true, Keyword = MarkerKeyword)]
internal sealed class LuaFastRule : ILuaSyntaxRule
{
private const string MarkerKeyword = "fast";
private const string Message = "[fast]: only obj.fill, obj.convolve and obj.resize can be accelerated.";
public bool TryApply(LuaRewriteContext context)
{
if (!context.Current.IsOperator("["))
return false;
if (context.TryPreviousOutputSignificantSameLine(out var previous) && LuaSyntaxFacts.IsValueEnd(previous))
return false;
int nameIndex = context.NextSignificant(context.Index + 1);
if (nameIndex < 0 || !context.Input[nameIndex].IsName(MarkerKeyword))
return false;
int closeIndex = context.NextSignificant(nameIndex + 1);
if (closeIndex < 0 || !context.Input[closeIndex].IsOperator("]"))
return false;
int targetIndex = context.NextSignificant(closeIndex + 1);
if (targetIndex < 0 || context.Input[targetIndex].Kind != LuaSyntaxTokenKind.Name)
return false;
if (TryResolveTarget(context, targetIndex, out int funcIndex, out string function))
{
EmitBetween(context, closeIndex + 1, targetIndex);
context.Index = funcIndex + 1;
context.EmitRaw("__fast_" + function);
return true;
}
context.AddDiagnostic(Message);
EmitBetween(context, closeIndex + 1, targetIndex);
context.Index = targetIndex;
return true;
}
private static bool TryResolveTarget(LuaRewriteContext context, int objIndex, out int funcIndex, out string function)
{
funcIndex = -1;
function = string.Empty;
if (!context.Input[objIndex].IsName("obj"))
return false;
int dot = context.NextSignificant(objIndex + 1);
if (dot < 0 || !context.Input[dot].IsOperator("."))
return false;
int name = context.NextSignificant(dot + 1);
if (name < 0)
return false;
string text = context.Input[name].Text;
if (text is not ("fill" or "convolve" or "resize"))
return false;
int paren = context.NextSignificant(name + 1);
if (paren < 0 || !context.Input[paren].IsOperator("("))
return false;
funcIndex = name;
function = text;
return true;
}
private static void EmitBetween(LuaRewriteContext context, int from, int to)
{
for (int i = from; i < to; i++)
context.Emit(context.Input[i]);
}
}
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderClass(
string Namespace,
EquatableArray<GpuShaderTypePart> TypeChain,
EquatableArray<GpuShaderMethod> Methods,
EquatableArray<string> Errors);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderFile(string Path, string Source);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderInvocation(string Resources, string Constants, string Target, string Width, string Height);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderMethod(
string Accessibility,
bool IsStatic,
string ReturnType,
string MethodName,
EquatableArray<GpuShaderParameter> Parameters,
string FileName,
string EntryPoint,
GpuShaderInvocation Invocation);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderMethodSource(GpuShaderMethod Method, string Bytecode);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderParameter(string Prefix, string Type, string Name);
}
+6
ファイルの表示
@@ -0,0 +1,6 @@
using System.Collections.Immutable;
namespace LuaScript.Generator
{
internal sealed record GpuShaderResolution(ImmutableArray<GpuShaderMethodSource> Methods, ImmutableArray<string> Errors);
}
+436
ファイルの表示
@@ -0,0 +1,436 @@
using System.Collections.Immutable;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator
{
[Generator]
public sealed class GpuShaderSourceGenerator : IIncrementalGenerator
{
private const string AttributeName = "LuaScript.Engine.Processing.GpuPixelOperationShaderAttribute";
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var classes = context.SyntaxProvider
.CreateSyntaxProvider(
static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 },
static (ctx, _) => CreateClass(ctx))
.Where(static model => model is not null)
.Select(static (model, _) => model!);
var files = context.AdditionalTextsProvider
.Where(static file => file.Path.EndsWith(".hlsl", StringComparison.OrdinalIgnoreCase))
.Select(static (file, token) => new GpuShaderFile(Normalize(file.Path), file.GetText(token)?.ToString() ?? string.Empty))
.Collect()
.Select(static (items, _) => new EquatableArray<GpuShaderFile>([.. items]));
context.RegisterSourceOutput(classes.Combine(files), static (context, source) =>
{
var (model, files) = source;
var resolved = Resolve(model, files);
if (resolved.Errors.Length > 0)
{
context.AddSource(ErrorHintName(model), SourceText.From(EmitErrors(resolved.Errors), Encoding.UTF8));
return;
}
context.AddSource(HintName(model), SourceText.From(Emit(model, resolved.Methods), Encoding.UTF8));
});
}
private static GpuShaderClass? CreateClass(GeneratorSyntaxContext context)
{
if (context.Node is not ClassDeclarationSyntax declaration)
return null;
if (context.SemanticModel.GetDeclaredSymbol(declaration) is not INamedTypeSymbol type)
return null;
var attributes = type.GetAttributes()
.Where(static attribute => attribute.AttributeClass?.ToDisplayString() == AttributeName)
.ToArray();
if (attributes.Length == 0)
return null;
var chain = new List<GpuShaderTypePart>();
for (var current = type; current is not null; current = current.ContainingType)
chain.Insert(0, new GpuShaderTypePart(current.Name, current.IsStatic));
var methods = ImmutableArray.CreateBuilder<GpuShaderMethod>();
var errors = ImmutableArray.CreateBuilder<string>();
foreach (var attribute in attributes)
{
if (attribute.ConstructorArguments.Length < 3 ||
attribute.ConstructorArguments[0].Value is not string methodName ||
attribute.ConstructorArguments[1].Value is not string fileName ||
attribute.ConstructorArguments[2].Value is not string entryPoint)
{
errors.Add("GPU shader attribute arguments are invalid");
continue;
}
var candidates = type.GetMembers(methodName).OfType<IMethodSymbol>().ToArray();
if (candidates.Length == 0)
{
errors.Add($"GPU shader method '{methodName}' was not found");
continue;
}
if (candidates.Length > 1)
{
errors.Add($"GPU shader method '{methodName}' is ambiguous");
continue;
}
var method = candidates[0];
string? error = Validate(method, fileName, entryPoint, out var invocation);
if (error is not null)
{
errors.Add($"GPU shader method '{methodName}': {error}");
continue;
}
var parameters = ImmutableArray.CreateBuilder<GpuShaderParameter>();
foreach (var parameter in method.Parameters)
parameters.Add(new GpuShaderParameter(ParameterPrefix(parameter), parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), parameter.Name));
methods.Add(new GpuShaderMethod(
AccessibilityName(method.DeclaredAccessibility),
method.IsStatic,
method.ReturnType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
method.Name,
new EquatableArray<GpuShaderParameter>([.. parameters]),
Normalize(fileName),
entryPoint,
invocation));
}
return new GpuShaderClass(
type.ContainingNamespace.IsGlobalNamespace ? string.Empty : type.ContainingNamespace.ToDisplayString(),
new EquatableArray<GpuShaderTypePart>([.. chain]),
new EquatableArray<GpuShaderMethod>([.. methods]),
new EquatableArray<string>([.. errors]));
}
private static string? Validate(IMethodSymbol method, string fileName, string entryPoint, out GpuShaderInvocation invocation)
{
invocation = new GpuShaderInvocation(string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
if (string.IsNullOrWhiteSpace(fileName))
return "file name is empty";
if (string.IsNullOrWhiteSpace(entryPoint))
return "entry point is empty";
if (method.ReturnType.SpecialType != SpecialType.System_Boolean)
return "return type must be bool";
var parameters = method.Parameters;
if (parameters.Length == 4 &&
IsReadOnlySpanSingle(parameters[0].Type) &&
IsByteArray(parameters[1].Type) &&
IsInt32(parameters[2].Type) &&
IsInt32(parameters[3].Type))
{
invocation = new GpuShaderInvocation("[]", parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name);
return null;
}
if (parameters.Length == 5 &&
IsReadOnlySpanPixelShaderInput(parameters[0].Type) &&
IsReadOnlySpanSingle(parameters[1].Type) &&
IsByteArray(parameters[2].Type) &&
IsInt32(parameters[3].Type) &&
IsInt32(parameters[4].Type))
{
invocation = new GpuShaderInvocation(parameters[0].Name, parameters[1].Name, parameters[2].Name, parameters[3].Name, parameters[4].Name);
return null;
}
return "signature is invalid";
}
private static GpuShaderResolution Resolve(GpuShaderClass model, EquatableArray<GpuShaderFile> files)
{
var methods = ImmutableArray.CreateBuilder<GpuShaderMethodSource>();
var errors = ImmutableArray.CreateBuilder<string>();
errors.AddRange(model.Errors);
foreach (var method in model.Methods)
{
var matched = files.Where(file => Matches(file.Path, method.FileName)).ToArray();
if (matched.Length == 0)
{
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' was not found");
continue;
}
if (matched.Length > 1)
{
errors.Add($"GPU shader file '{method.FileName}' for method '{method.MethodName}' matched multiple additional files");
continue;
}
string? failure = ShaderCompiler.Compile(matched[0].Source, method.EntryPoint, out string bytecode);
if (failure is not null)
{
errors.Add($"GPU shader method '{method.MethodName}' failed to compile: {failure}");
continue;
}
methods.Add(new GpuShaderMethodSource(method, bytecode));
}
return new GpuShaderResolution([.. methods], [.. errors]);
}
private static bool Matches(string filePath, string registrationPath)
{
if (string.Equals(filePath, registrationPath, StringComparison.OrdinalIgnoreCase))
return true;
return filePath.EndsWith("/" + registrationPath, StringComparison.OrdinalIgnoreCase);
}
private static bool IsReadOnlySpanSingle(ITypeSymbol type)
{
return type is INamedTypeSymbol named &&
named.OriginalDefinition.ToDisplayString() == "System.ReadOnlySpan<T>" &&
named.TypeArguments.Length == 1 &&
named.TypeArguments[0].SpecialType == SpecialType.System_Single;
}
private static bool IsReadOnlySpanPixelShaderInput(ITypeSymbol type)
{
string display = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
return display.Contains("ReadOnlySpan", StringComparison.Ordinal) &&
display.Contains("PixelShaderInput", StringComparison.Ordinal);
}
private static bool IsByteArray(ITypeSymbol type)
{
return type is IArrayTypeSymbol array &&
array.Rank == 1 &&
array.ElementType.SpecialType == SpecialType.System_Byte;
}
private static bool IsInt32(ITypeSymbol type) => type.SpecialType == SpecialType.System_Int32;
private static string Normalize(string path) => path.Replace(Path.DirectorySeparatorChar, '/').Replace(Path.AltDirectorySeparatorChar, '/');
private static string AccessibilityName(Accessibility accessibility)
{
return accessibility switch
{
Accessibility.Public => "public",
Accessibility.Internal => "internal",
Accessibility.Protected => "protected",
Accessibility.ProtectedAndInternal => "private protected",
Accessibility.ProtectedOrInternal => "protected internal",
_ => "private",
};
}
private static string ParameterPrefix(IParameterSymbol parameter)
{
return parameter.RefKind switch
{
RefKind.In => "in ",
RefKind.Ref => "ref ",
RefKind.Out => "out ",
_ => string.Empty,
};
}
private static string Emit(GpuShaderClass model, ImmutableArray<GpuShaderMethodSource> sources)
{
var builder = new StringBuilder();
builder.AppendLine("#nullable enable");
if (model.Namespace.Length > 0)
{
builder.AppendLine("namespace " + model.Namespace);
builder.AppendLine("{");
}
int indent = model.Namespace.Length > 0 ? 1 : 0;
foreach (var type in model.TypeChain)
{
AppendIndent(builder, indent);
builder.Append(type.IsStatic ? "static partial class " : "partial class ");
builder.AppendLine(type.Name);
AppendIndent(builder, indent);
builder.AppendLine("{");
indent++;
}
for (int i = 0; i < sources.Length; i++)
{
if (i > 0)
builder.AppendLine();
EmitMethod(builder, indent, sources[i]);
}
for (int i = model.TypeChain.Count - 1; i >= 0; i--)
{
indent--;
AppendIndent(builder, indent);
builder.AppendLine("}");
}
if (model.Namespace.Length > 0)
builder.AppendLine("}");
return builder.ToString();
}
private static void EmitMethod(StringBuilder builder, int indent, GpuShaderMethodSource source)
{
var method = source.Method;
string field = "s_shader_" + method.MethodName;
AppendIndent(builder, indent);
builder.Append("private static readonly byte[] ");
builder.Append(field);
builder.Append(" = global::System.Convert.FromBase64String(");
builder.Append(Literal(source.Bytecode));
builder.AppendLine(");");
builder.AppendLine();
AppendIndent(builder, indent);
builder.Append(method.Accessibility);
builder.Append(' ');
if (method.IsStatic)
builder.Append("static ");
builder.Append("partial ");
builder.Append(method.ReturnType);
builder.Append(' ');
builder.Append(method.MethodName);
builder.Append('(');
for (int i = 0; i < method.Parameters.Count; i++)
{
if (i > 0)
builder.Append(", ");
var parameter = method.Parameters[i];
builder.Append(parameter.Prefix);
builder.Append(parameter.Type);
builder.Append(' ');
builder.Append(parameter.Name);
}
builder.AppendLine(")");
AppendIndent(builder, indent);
builder.AppendLine("{");
AppendIndent(builder, indent + 1);
builder.Append("return Run(");
builder.Append(field);
builder.Append(", ");
builder.Append(method.Invocation.Resources);
builder.Append(", ");
builder.Append(method.Invocation.Constants);
builder.Append(", ");
builder.Append(method.Invocation.Target);
builder.Append(", ");
builder.Append(method.Invocation.Width);
builder.Append(", ");
builder.Append(method.Invocation.Height);
builder.AppendLine(");");
AppendIndent(builder, indent);
builder.AppendLine("}");
}
private static void AppendIndent(StringBuilder builder, int indent)
{
for (int i = 0; i < indent; i++)
builder.Append(" ");
}
private static string EmitErrors(ImmutableArray<string> errors)
{
var builder = new StringBuilder();
foreach (var error in errors)
builder.AppendLine("#error " + error);
return builder.ToString();
}
private static string HintName(GpuShaderClass model)
{
var builder = new StringBuilder("GpuPixelOperationShader");
if (model.Namespace.Length > 0)
{
builder.Append('.');
builder.Append(HintPart(model.Namespace));
}
foreach (var type in model.TypeChain)
{
builder.Append('.');
builder.Append(HintPart(type.Name));
}
builder.Append(".g.cs");
return builder.ToString();
}
private static string ErrorHintName(GpuShaderClass model)
{
return Path.ChangeExtension(HintName(model), ".Errors.g.cs");
}
private static string HintPart(string value)
{
var builder = new StringBuilder(value.Length);
foreach (char c in value)
builder.Append(char.IsLetterOrDigit(c) ? c : '_');
return builder.ToString();
}
private static string Literal(string value)
{
var builder = new StringBuilder(value.Length + 2);
builder.Append('"');
foreach (char c in value)
{
switch (c)
{
case '\\':
builder.Append(@"\\");
break;
case '"':
builder.Append("\\\"");
break;
case '\0':
builder.Append(@"\0");
break;
case '\a':
builder.Append(@"\a");
break;
case '\b':
builder.Append(@"\b");
break;
case '\f':
builder.Append(@"\f");
break;
case '\n':
builder.Append(@"\n");
break;
case '\r':
builder.Append(@"\r");
break;
case '\t':
builder.Append(@"\t");
break;
case '\v':
builder.Append(@"\v");
break;
default:
if (char.IsControl(c))
{
builder.Append(@"\u");
builder.Append(((int)c).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
builder.Append(c);
}
break;
}
}
builder.Append('"');
return builder.ToString();
}
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record GpuShaderTypePart(string Name, bool IsStatic);
}
+96
ファイルの表示
@@ -0,0 +1,96 @@
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
namespace LuaScript.Generator
{
internal static class ShaderCompiler
{
private const string Profile = "ps_5_0";
public static string? Compile(string source, string entryPoint, out string bytecode)
{
bytecode = string.Empty;
byte[] data = Encoding.UTF8.GetBytes(source);
IntPtr code = IntPtr.Zero;
IntPtr errors = IntPtr.Zero;
try
{
int hr = D3DCompile(data, (IntPtr)data.Length, null, IntPtr.Zero, IntPtr.Zero, entryPoint, Profile, 0u, 0u, out code, out errors);
if (hr < 0 || code == IntPtr.Zero)
return ReadError(errors, hr);
bytecode = Convert.ToBase64String(ReadBlob(code));
return null;
}
catch (DllNotFoundException)
{
return "the Direct3D shader compiler is unavailable on this build host";
}
catch (EntryPointNotFoundException)
{
return "the Direct3D shader compiler is unavailable on this build host";
}
finally
{
Release(errors);
Release(code);
}
}
private static byte[] ReadBlob(IntPtr blob)
{
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
var buffer = new byte[size];
Marshal.Copy(pointer, buffer, 0, size);
return buffer;
}
private static string ReadError(IntPtr blob, int hr)
{
string fallback = "HRESULT 0x" + hr.ToString("X8", CultureInfo.InvariantCulture);
if (blob == IntPtr.Zero)
return fallback;
IntPtr pointer = Invoke<GetBufferPointerDelegate>(blob, 3)(blob);
int size = checked((int)(long)Invoke<GetBufferSizeDelegate>(blob, 4)(blob));
string message = (Marshal.PtrToStringAnsi(pointer, size) ?? string.Empty).Trim();
return message.Length > 0 ? message : fallback;
}
private static void Release(IntPtr unknown)
{
if (unknown != IntPtr.Zero)
Invoke<ReleaseDelegate>(unknown, 2)(unknown);
}
private static T Invoke<T>(IntPtr instance, int slot) where T : Delegate
{
IntPtr table = Marshal.ReadIntPtr(instance);
IntPtr function = Marshal.ReadIntPtr(table, slot * IntPtr.Size);
return (T)Marshal.GetDelegateForFunctionPointer(function, typeof(T));
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr GetBufferPointerDelegate(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr GetBufferSizeDelegate(IntPtr self);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(IntPtr self);
[DllImport("d3dcompiler_47.dll", CallingConvention = CallingConvention.StdCall)]
private static extern int D3DCompile(
byte[] srcData,
IntPtr srcDataSize,
[MarshalAs(UnmanagedType.LPStr)] string? sourceName,
IntPtr defines,
IntPtr include,
[MarshalAs(UnmanagedType.LPStr)] string entryPoint,
[MarshalAs(UnmanagedType.LPStr)] string target,
uint flags1,
uint flags2,
out IntPtr code,
out IntPtr errorMsgs);
}
}
+35 -58
ファイルの表示
@@ -5,60 +5,6 @@ using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator namespace LuaScript.Generator
{ {
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
internal sealed record LuaConstantModel(string LuaName, string MemberName);
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
internal sealed record LuaCatalogEntry(
string Table,
string Name,
bool IsFunction,
EquatableArray<string> Parameters);
internal sealed record LuaTypePart(string Name, bool IsStatic);
internal sealed record LuaTableModel(
string Namespace,
EquatableArray<LuaTypePart> TypeChain,
string TableName,
string ContextType,
EquatableArray<LuaFunctionModel> Functions,
EquatableArray<LuaConstantModel> Constants,
EquatableArray<LuaUpdateModel> Updates,
EquatableArray<LuaCatalogEntry> Entries);
[Generator] [Generator]
public sealed class LuaApiGenerator : IIncrementalGenerator public sealed class LuaApiGenerator : IIncrementalGenerator
{ {
@@ -309,12 +255,30 @@ namespace LuaScript.Generator
var returnType = method.ReturnType; var returnType = method.ReturnType;
LuaUpdateKind kind; LuaUpdateKind kind;
ITypeSymbol valueType;
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
kind = LuaUpdateKind.OptionalValue; kind = LuaUpdateKind.OptionalValue;
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
}
else if (returnType.IsReferenceType) else if (returnType.IsReferenceType)
{
kind = LuaUpdateKind.OptionalReference; kind = LuaUpdateKind.OptionalReference;
valueType = returnType;
}
else else
{
kind = LuaUpdateKind.Direct; kind = LuaUpdateKind.Direct;
valueType = returnType;
}
var valueKind = valueType.SpecialType switch
{
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
SpecialType.System_Boolean => LuaValueKind.Boolean,
SpecialType.System_String => LuaValueKind.String,
_ => LuaValueKind.Other,
};
bool inCatalog = true; bool inCatalog = true;
foreach (var argument in attribute.NamedArguments) foreach (var argument in attribute.NamedArguments)
@@ -325,7 +289,7 @@ namespace LuaScript.Generator
if (inCatalog) if (inCatalog)
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty); entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
return new LuaUpdateModel(luaName, method.Name, kind); return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
} }
private static string FormatDouble(double value) => private static string FormatDouble(double value) =>
@@ -387,13 +351,19 @@ namespace LuaScript.Generator
switch (update.Kind) switch (update.Kind)
{ {
case LuaUpdateKind.OptionalValue: case LuaUpdateKind.OptionalValue:
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"); builder.AppendLine(update.ValueKind == LuaValueKind.Other
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
break; break;
case LuaUpdateKind.OptionalReference: case LuaUpdateKind.OptionalReference:
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"); builder.AppendLine(update.ValueKind == LuaValueKind.Other
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
break; break;
default: default:
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"); builder.AppendLine(update.ValueKind == LuaValueKind.Other
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
break; break;
} }
} }
@@ -409,6 +379,13 @@ namespace LuaScript.Generator
return builder.ToString(); return builder.ToString();
} }
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
{
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
};
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters) private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
{ {
var rendered = new List<string>(); var rendered = new List<string>();
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record LuaCatalogEntry(
string Table,
string Name,
bool IsFunction,
EquatableArray<string> Parameters);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaConstantModel(string LuaName, string MemberName);
}
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace LuaScript.Generator
{
internal sealed record LuaFunctionModel(
string LuaName,
string MethodName,
LuaReturnKind ReturnKind,
EquatableArray<LuaParameterModel> Parameters);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal enum LuaParameterKind
{
ExecutionContext,
Arguments,
DynValue,
Double,
Int,
Bool,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaParameterModel(string Name, LuaParameterKind Kind, string DefaultLiteral);
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Generator
{
internal enum LuaReturnKind
{
DynValue,
Double,
Void,
}
}
@@ -8,8 +8,6 @@ using Microsoft.CodeAnalysis.Text;
namespace LuaScript.Generator namespace LuaScript.Generator
{ {
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order);
[Generator] [Generator]
public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator public sealed class LuaSyntaxRuleGenerator : IIncrementalGenerator
{ {
@@ -47,7 +45,17 @@ namespace LuaScript.Generator
if (arguments.Length > 0 && arguments[0].Value is int value) if (arguments.Length > 0 && arguments[0].Value is int value)
order = value; order = value;
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order); bool isCatalog = false;
string keyword = string.Empty;
foreach (var argument in context.Attributes[0].NamedArguments)
{
if (argument.Key == "IsCatalog" && argument.Value.Value is bool catalogValue)
isCatalog = catalogValue;
else if (argument.Key == "Keyword" && argument.Value.Value is string keywordValue)
keyword = keywordValue;
}
return new LuaSyntaxRuleModel(symbol.ToDisplayString(), order, isCatalog ? keyword : string.Empty);
} }
private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models) private static string Emit(ImmutableArray<LuaSyntaxRuleModel> models)
@@ -68,6 +76,24 @@ namespace LuaScript.Generator
foreach (var model in ordered) foreach (var model in ordered)
builder.AppendLine($" new global::{model.TypeName}(),"); builder.AppendLine($" new global::{model.TypeName}(),");
builder.AppendLine(" };"); builder.AppendLine(" };");
var keywords = ordered
.Where(static m => m.CatalogKeyword.Length > 0)
.Select(static m => m.CatalogKeyword)
.Distinct()
.ToArray();
if (keywords.Length == 0)
{
builder.AppendLine(" internal static readonly string[] CatalogKeywords = global::System.Array.Empty<string>();");
}
else
{
builder.AppendLine(" internal static readonly string[] CatalogKeywords = new string[]");
builder.AppendLine(" {");
foreach (var keyword in keywords)
builder.AppendLine($" \"{keyword}\",");
builder.AppendLine(" };");
}
builder.AppendLine(" }"); builder.AppendLine(" }");
builder.AppendLine("}"); builder.AppendLine("}");
return builder.ToString(); return builder.ToString();
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaSyntaxRuleModel(string TypeName, int Order, string CatalogKeyword);
}
+12
ファイルの表示
@@ -0,0 +1,12 @@
namespace LuaScript.Generator
{
internal sealed record LuaTableModel(
string Namespace,
EquatableArray<LuaTypePart> TypeChain,
string TableName,
string ContextType,
EquatableArray<LuaFunctionModel> Functions,
EquatableArray<LuaConstantModel> Constants,
EquatableArray<LuaUpdateModel> Updates,
EquatableArray<LuaCatalogEntry> Entries);
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaTypePart(string Name, bool IsStatic);
}
+9
ファイルの表示
@@ -0,0 +1,9 @@
namespace LuaScript.Generator
{
internal enum LuaUpdateKind
{
Direct,
OptionalValue,
OptionalReference,
}
}
+4
ファイルの表示
@@ -0,0 +1,4 @@
namespace LuaScript.Generator
{
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
}
+10
ファイルの表示
@@ -0,0 +1,10 @@
namespace LuaScript.Generator
{
internal enum LuaValueKind
{
Number,
Boolean,
String,
Other,
}
}
+1 -1
ファイルの表示
@@ -5,7 +5,7 @@
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.18.0</Version> <Version>1.20.3</Version>
<IsRoslynComponent>true</IsRoslynComponent> <IsRoslynComponent>true</IsRoslynComponent>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
</PropertyGroup> </PropertyGroup>
+134
ファイルの表示
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunConvolve), "Shaders/convolve.hlsl", "convolve")]
internal sealed partial class GpuConvolveOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int ConvolveWorkThreshold = 262144;
private const int MaxConvolveSize = 31;
private const int MaxConvolveValidationCount = 64;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[1024];
private readonly List<ConvolveValidation> _validations = [];
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
if (!IsTextureSupported(target, width, height) || !IsSupported(kernel, size, divisor, offset))
return false;
long work = (long)width * height * size * size;
if (!force && work < ConvolveWorkThreshold || !EnsureValidated(target, width, height, kernel, size, divisor, offset))
return false;
SetConstants(width, height, kernel, size, divisor, offset);
_resources[0] = new PixelShaderInput(target, width, height);
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), target, width, height);
}
private bool EnsureValidated(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
for (int i = 0; i < _validations.Count; i++)
{
if (_validations[i].Matches(kernel, size, divisor, offset))
return _validations[i].Valid;
}
if (_validations.Count >= MaxConvolveValidationCount)
_validations.Clear();
bool valid = Validate(target, width, height, kernel, size, divisor, offset);
_validations.Add(new ConvolveValidation(kernel, size, divisor, offset, valid));
return valid;
}
private bool Validate(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset)
{
int probeWidth = Math.Min(width, 8);
int probeHeight = Math.Min(height, 7);
var probe = CopyProbe(target, width, height, probeWidth, probeHeight);
var cpu = (byte[])probe.Clone();
var gpu = (byte[])probe.Clone();
double[]? scratch = null;
PixelBufferSoftwareProcessor.Convolve(cpu, probeWidth, probeHeight, kernel, size, divisor, offset, ref scratch);
SetConstants(probeWidth, probeHeight, kernel, size, divisor, offset);
_resources[0] = new PixelShaderInput(gpu, probeWidth, probeHeight);
return RunConvolve(_resources.AsSpan(0, 1), _constants.AsSpan(0, size * size + 8), gpu, probeWidth, probeHeight) && Equal(cpu, gpu);
}
private void SetConstants(int width, int height, double[] kernel, int size, double divisor, double offset)
{
_constants[0] = width;
_constants[1] = height;
_constants[2] = (float)divisor;
_constants[3] = (float)offset;
_constants[4] = size;
_constants[5] = size / 2;
_constants[6] = 0f;
_constants[7] = 0f;
int taps = size * size;
for (int i = 0; i < taps; i++)
_constants[i + 8] = (float)kernel[i];
}
private static bool IsSupported(double[] kernel, int size, double divisor, double offset)
{
if (size < 1 || (size & 1) == 0 || size > MaxConvolveSize || divisor == 0d || !IsFloatCompatible(divisor) || !IsFloatCompatible(offset))
return false;
int taps = size * size;
if (kernel.Length < taps || taps + 8 > 1024)
return false;
for (int i = 0; i < taps; i++)
{
if (!IsFloatCompatible(kernel[i]))
return false;
}
return true;
}
private static bool IsFloatCompatible(double value)
{
return double.IsFinite(value) && float.IsFinite((float)value);
}
private partial bool RunConvolve(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
private sealed class ConvolveValidation
{
private readonly double[] _kernel;
private readonly int _size;
private readonly double _divisor;
private readonly double _offset;
public ConvolveValidation(double[] kernel, int size, double divisor, double offset, bool valid)
{
int taps = size * size;
_kernel = new double[taps];
Array.Copy(kernel, _kernel, taps);
_size = size;
_divisor = divisor;
_offset = offset;
Valid = valid;
}
public bool Valid { get; }
public bool Matches(double[] kernel, int size, double divisor, double offset)
{
if (_size != size || BitConverter.DoubleToInt64Bits(_divisor) != BitConverter.DoubleToInt64Bits(divisor) ||
BitConverter.DoubleToInt64Bits(_offset) != BitConverter.DoubleToInt64Bits(offset))
return false;
int taps = size * size;
for (int i = 0; i < taps; i++)
{
if (BitConverter.DoubleToInt64Bits(_kernel[i]) != BitConverter.DoubleToInt64Bits(kernel[i]))
return false;
}
return true;
}
}
}
}
+124
ファイルの表示
@@ -0,0 +1,124 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunFillFull), "Shaders/fill.hlsl", "fill_full")]
[GpuPixelOperationShader(nameof(RunFillPartial), "Shaders/fill.hlsl", "fill_partial")]
internal sealed partial class GpuFillOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int FillFullThreshold = 1048576;
private const int FillPartialThreshold = 1048576;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[8];
private bool? _fullValidated;
private bool? _partialValidated;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
if (!IsTextureSupported(target, width, height) || !AreFinite(r, g, b, a))
return false;
long pixels = (long)width * height;
bool full = x == 0 && y == 0 && fillWidth == width && fillHeight == height;
if (full)
{
if (!force && pixels < FillFullThreshold || !EnsureFullValidated())
return false;
SetConstants(r, g, b, a);
return RunFillFull(_constants.AsSpan(0, 4), target, width, height);
}
long area = (long)fillWidth * fillHeight;
if (!force && (pixels < FillPartialThreshold || area * 4L < pixels * 3L) || !EnsurePartialValidated())
return false;
SetConstants(r, g, b, a);
_constants[4] = x;
_constants[5] = y;
_constants[6] = x + fillWidth;
_constants[7] = y + fillHeight;
_resources[0] = new PixelShaderInput(target, width, height);
return RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), target, width, height);
}
private bool EnsureFullValidated()
{
if (_fullValidated.HasValue)
return _fullValidated.Value;
const int width = 7;
const int height = 5;
var source = CreateProbe(width, height);
var cpu = (byte[])source.Clone();
var gpu = (byte[])source.Clone();
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 0, 0, width, height);
SetConstants(23d, 197d, 89d, 173d);
_fullValidated = RunFillFull(_constants.AsSpan(0, 4), gpu, width, height) && Equal(cpu, gpu);
return _fullValidated.Value;
}
private bool EnsurePartialValidated()
{
if (_partialValidated.HasValue)
return _partialValidated.Value;
const int width = 7;
const int height = 5;
var source = CreateProbe(width, height);
var cpu = (byte[])source.Clone();
var gpu = (byte[])source.Clone();
PixelBufferSoftwareProcessor.Fill(cpu, width, height, 23d, 197d, 89d, 173d, 1, 2, 4, 2);
SetConstants(23d, 197d, 89d, 173d);
_constants[4] = 1f;
_constants[5] = 2f;
_constants[6] = 5f;
_constants[7] = 4f;
_resources[0] = new PixelShaderInput(gpu, width, height);
_partialValidated = RunFillPartial(_resources.AsSpan(0, 1), _constants.AsSpan(0, 8), gpu, width, height) && Equal(cpu, gpu);
return _partialValidated.Value;
}
private void SetConstants(double r, double g, double b, double a)
{
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
_constants[0] = pr / 255f;
_constants[1] = pg / 255f;
_constants[2] = pb / 255f;
_constants[3] = pa / 255f;
}
private static bool AreFinite(double r, double g, double b, double a)
{
return double.IsFinite(r) && double.IsFinite(g) && double.IsFinite(b) && double.IsFinite(a);
}
private static byte[] CreateProbe(int width, int height)
{
var data = new byte[width * height * 4];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int index = (y * width + x) * 4;
byte a = (byte)((x * 31 + y * 47) & 255);
data[index] = a == 0 ? (byte)0 : (byte)((x * 17 + y * 29) % (a + 1));
data[index + 1] = a == 0 ? (byte)0 : (byte)((x * 43 + y * 11) % (a + 1));
data[index + 2] = a == 0 ? (byte)0 : (byte)((x * 7 + y * 53) % (a + 1));
data[index + 3] = a;
}
}
return data;
}
private partial bool RunFillFull(ReadOnlySpan<float> constants, byte[] target, int width, int height);
private partial bool RunFillPartial(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
}
}
+30
ファイルの表示
@@ -0,0 +1,30 @@
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
internal sealed class GpuPixelBufferProcessor(PixelShaderRunner runner) : IPixelBufferProcessor
{
private readonly object _gate = new();
private readonly GpuFillOperation _fill = new(runner);
private readonly GpuConvolveOperation _convolve = new(runner);
private readonly GpuResizeOperation _resize = new(runner);
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
lock (_gate)
return _fill.TryFill(target, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force);
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
lock (_gate)
return _convolve.TryConvolve(target, width, height, kernel, size, divisor, offset, force);
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
lock (_gate)
return _resize.TryResize(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target, force);
}
}
}
+47
ファイルの表示
@@ -0,0 +1,47 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
internal abstract class GpuPixelOperation(PixelShaderRunner runner)
{
protected const int MaxTextureSize = 16384;
protected bool Run(byte[] bytecode, ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height)
{
return runner.TryRunHardware(
bytecode,
resources,
constants,
PixelShaderBlend.Copy,
PixelShaderSampler.None,
target,
width,
height,
out _) == PixelShaderRunStatus.Success;
}
protected static bool IsTextureSupported(byte[] buffer, int width, int height)
{
return IsTextureSizeSupported(width, height) && (long)buffer.Length >= (long)width * height * 4;
}
protected static bool IsTextureSizeSupported(int width, int height)
{
return width > 0 && height > 0 && width <= MaxTextureSize && height <= MaxTextureSize;
}
protected static bool Equal(byte[] expected, byte[] actual)
{
return expected.AsSpan().SequenceEqual(actual);
}
protected static byte[] CopyProbe(byte[] source, int width, int height, int probeWidth, int probeHeight)
{
var data = new byte[probeWidth * probeHeight * 4];
for (int y = 0; y < probeHeight; y++)
Buffer.BlockCopy(source, y * width * 4, data, y * probeWidth * 4, probeWidth * 4);
return data;
}
}
}
+14
ファイルの表示
@@ -0,0 +1,14 @@
using System;
namespace LuaScript.Engine.Processing
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal sealed class GpuPixelOperationShaderAttribute(string methodName, string fileName, string entryPoint) : Attribute
{
public string MethodName { get; } = methodName;
public string FileName { get; } = fileName;
public string EntryPoint { get; } = entryPoint;
}
}
+82
ファイルの表示
@@ -0,0 +1,82 @@
using System;
using LuaScript.Engine.Shader;
namespace LuaScript.Engine.Processing
{
[GpuPixelOperationShader(nameof(RunResizeNearest), "Shaders/resize.hlsl", "resize_nearest")]
[GpuPixelOperationShader(nameof(RunResizeLinear), "Shaders/resize.hlsl", "resize_linear")]
internal sealed partial class GpuResizeOperation(PixelShaderRunner runner) : GpuPixelOperation(runner)
{
private const int ResizeThreshold = 262144;
private readonly PixelShaderInput[] _resources = new PixelShaderInput[1];
private readonly float[] _constants = new float[4];
private byte[] _target = [];
private bool? _nearestValidated;
private bool? _linearValidated;
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
target = null;
if (!IsTextureSupported(source, sourceWidth, sourceHeight) || !IsTextureSizeSupported(targetWidth, targetHeight))
return false;
long pixels = (long)targetWidth * targetHeight;
if (!force && pixels < ResizeThreshold || !(linear ? EnsureLinearValidated(source, sourceWidth, sourceHeight) : EnsureNearestValidated(source, sourceWidth, sourceHeight)))
return false;
return RunShader(source, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out target);
}
private bool EnsureNearestValidated(byte[] source, int sourceWidth, int sourceHeight)
{
if (_nearestValidated.HasValue)
return _nearestValidated.Value;
_nearestValidated = Validate(source, sourceWidth, sourceHeight, false);
return _nearestValidated.Value;
}
private bool EnsureLinearValidated(byte[] source, int sourceWidth, int sourceHeight)
{
if (_linearValidated.HasValue)
return _linearValidated.Value;
_linearValidated = Validate(source, sourceWidth, sourceHeight, true);
return _linearValidated.Value;
}
private bool Validate(byte[] source, int sourceWidth, int sourceHeight, bool linear)
{
int probeWidth = Math.Min(sourceWidth, 8);
int probeHeight = Math.Min(sourceHeight, 7);
int targetWidth = Math.Max(1, probeWidth * 2 - 3);
int targetHeight = Math.Max(1, probeHeight * 2 - 5);
var probe = CopyProbe(source, sourceWidth, sourceHeight, probeWidth, probeHeight);
byte[]? sourceScratch = null;
byte[]? targetScratch = null;
var cpu = PixelBufferSoftwareProcessor.Resize(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, ref sourceScratch, ref targetScratch);
return RunShader(probe, probeWidth, probeHeight, targetWidth, targetHeight, linear, out var gpu) && gpu is not null && Equal(cpu, gpu);
}
private bool RunShader(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target)
{
int count = checked(targetWidth * targetHeight * 4);
if (_target.Length != count)
_target = new byte[count];
_constants[0] = sourceWidth;
_constants[1] = sourceHeight;
_constants[2] = targetWidth;
_constants[3] = targetHeight;
_resources[0] = new PixelShaderInput(source, sourceWidth, sourceHeight);
target = _target;
return linear
? RunResizeLinear(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight)
: RunResizeNearest(_resources.AsSpan(0, 1), _constants.AsSpan(0, 4), _target, targetWidth, targetHeight);
}
private partial bool RunResizeNearest(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
private partial bool RunResizeLinear(ReadOnlySpan<PixelShaderInput> resources, ReadOnlySpan<float> constants, byte[] target, int width, int height);
}
}
+50
ファイルの表示
@@ -0,0 +1,50 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
<ProjectReference Include="..\LuaScript.Generator\LuaScript.Generator.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
<AdditionalFiles Include="Shaders\*.hlsl" />
</ItemGroup>
<ItemGroup>
<Reference Include="SharpGen.Runtime">
<HintPath>$(YMM4DirPath)SharpGen.Runtime.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Direct3D11">
<HintPath>$(YMM4DirPath)Vortice.Direct3D11.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DirectX">
<HintPath>$(YMM4DirPath)Vortice.DirectX.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.D3DCompiler.dll">
<HintPath>$(YMM4DirPath)Vortice.D3DCompiler.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.DXGI.dll">
<HintPath>$(YMM4DirPath)Vortice.DXGI.dll</HintPath>
<Private>false</Private>
</Reference>
<Reference Include="Vortice.Mathematics">
<HintPath>$(YMM4DirPath)Vortice.Mathematics.dll</HintPath>
<Private>false</Private>
</Reference>
</ItemGroup>
</Project>
+106 -10
ファイルの表示
@@ -7,7 +7,6 @@ using Vortice.Direct3D;
using Vortice.Direct3D11; using Vortice.Direct3D11;
using Vortice.DXGI; using Vortice.DXGI;
using Vortice.Mathematics; using Vortice.Mathematics;
using YukkuriMovieMaker.Commons;
namespace LuaScript.Engine.Shader namespace LuaScript.Engine.Shader
{ {
@@ -43,6 +42,7 @@ namespace LuaScript.Engine.Shader
private readonly Lock _locker = new(); private readonly Lock _locker = new();
private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = []; private readonly Dictionary<(string Hlsl, string Entry), CompiledShader> _shaders = [];
private readonly Dictionary<byte[], ID3D11PixelShader> _precompiled = new(ReferenceEqualityComparer.Instance);
private readonly InputSlot[] _inputs = new InputSlot[MaxResources]; private readonly InputSlot[] _inputs = new InputSlot[MaxResources];
private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources]; private readonly ID3D11ShaderResourceView[] _boundViews = new ID3D11ShaderResourceView[MaxResources];
private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources]; private readonly ID3D11ShaderResourceView[] _nullViews = new ID3D11ShaderResourceView[MaxResources];
@@ -51,8 +51,11 @@ namespace LuaScript.Engine.Shader
public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance; public IBufferCompositor Compositor { get; set; } = SoftwareCompositor.Instance;
public Action<string, Exception?>? Logger { get; set; }
private ID3D11Device? _device; private ID3D11Device? _device;
private ID3D11DeviceContext? _context; private ID3D11DeviceContext? _context;
private DriverType _driverType;
private ID3D11VertexShader? _vertexShader; private ID3D11VertexShader? _vertexShader;
private ID3D11Buffer? _constantBuffer; private ID3D11Buffer? _constantBuffer;
private ID3D11RasterizerState? _rasterizer; private ID3D11RasterizerState? _rasterizer;
@@ -70,6 +73,7 @@ namespace LuaScript.Engine.Shader
private bool _disposed; private bool _disposed;
private bool _unavailable; private bool _unavailable;
private bool _hardwareUnavailable;
private bool _failureLogged; private bool _failureLogged;
private int _recreateBudget = 3; private int _recreateBudget = 3;
@@ -88,9 +92,7 @@ namespace LuaScript.Engine.Shader
error = null; error = null;
lock (_locker) lock (_locker)
{ {
if (_disposed || _unavailable) if (!CanRun(target, targetWidth, targetHeight))
return PixelShaderRunStatus.Unavailable;
if (targetWidth <= 0 || targetHeight <= 0 || (long)target.Length < (long)targetWidth * targetHeight * 4)
return PixelShaderRunStatus.Unavailable; return PixelShaderRunStatus.Unavailable;
try try
@@ -116,6 +118,46 @@ namespace LuaScript.Engine.Shader
} }
} }
public PixelShaderRunStatus TryRunHardware(
byte[] bytecode,
ReadOnlySpan<PixelShaderInput> resources,
ReadOnlySpan<float> constants,
PixelShaderBlend blend,
PixelShaderSampler sampler,
byte[] target,
int targetWidth,
int targetHeight,
out string? error)
{
error = null;
lock (_locker)
{
if (!CanRun(target, targetWidth, targetHeight))
return PixelShaderRunStatus.Unavailable;
try
{
if (!EnsureHardwareDevice())
return PixelShaderRunStatus.Unavailable;
Execute(GetOrCreate(bytecode), resources, constants, blend, sampler, target, targetWidth, targetHeight);
return PixelShaderRunStatus.Success;
}
catch (Exception ex)
{
HandleFailure(ex);
return PixelShaderRunStatus.Unavailable;
}
}
}
private bool CanRun(byte[] target, int targetWidth, int targetHeight)
{
return !_disposed && !_unavailable &&
targetWidth > 0 && targetHeight > 0 &&
(long)target.Length >= (long)targetWidth * targetHeight * 4;
}
public void Invalidate() public void Invalidate()
{ {
lock (_locker) lock (_locker)
@@ -146,19 +188,55 @@ namespace LuaScript.Engine.Shader
} }
_recreateBudget--; _recreateBudget--;
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context) && DriverType driverType;
!TryCreateDevice(DriverType.Warp, out device, out context)) if (TryCreateDevice(DriverType.Hardware, out var device, out var context))
{
driverType = DriverType.Hardware;
}
else if (TryCreateDevice(DriverType.Warp, out device, out context))
{
driverType = DriverType.Warp;
}
else
{ {
MarkUnavailable(null); MarkUnavailable(null);
return false; return false;
} }
return InitializeDevice(device, context, driverType, true);
}
private bool EnsureHardwareDevice()
{
if (_device is not null)
return _driverType == DriverType.Hardware;
if (_hardwareUnavailable)
return false;
if (_recreateBudget <= 0)
{
_hardwareUnavailable = true;
return false;
}
_recreateBudget--;
if (!TryCreateDevice(DriverType.Hardware, out var device, out var context))
{
_hardwareUnavailable = true;
return false;
}
return InitializeDevice(device, context, DriverType.Hardware, false);
}
private bool InitializeDevice(ID3D11Device? device, ID3D11DeviceContext? context, DriverType driverType, bool markUnavailable)
{
try try
{ {
var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0"); var vsBytecode = CompileOrThrow(VertexShaderSource, "vsmain", "vs_4_0");
var vertexShader = device!.CreateVertexShader(vsBytecode); var vertexShader = device!.CreateVertexShader(vsBytecode);
_device = device; _device = device;
_context = context; _context = context;
_driverType = driverType;
_hardwareUnavailable = driverType != DriverType.Hardware && _hardwareUnavailable;
_vertexShader = vertexShader; _vertexShader = vertexShader;
_constantBuffer = device.CreateBuffer(new BufferDescription( _constantBuffer = device.CreateBuffer(new BufferDescription(
ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write)); ConstantBufferSize, BindFlags.ConstantBuffer, ResourceUsage.Dynamic, CpuAccessFlags.Write));
@@ -178,7 +256,10 @@ namespace LuaScript.Engine.Shader
context?.Dispose(); context?.Dispose();
device?.Dispose(); device?.Dispose();
} }
MarkUnavailable(ex); if (markUnavailable)
MarkUnavailable(ex);
else
_hardwareUnavailable = true;
return false; return false;
} }
} }
@@ -267,6 +348,16 @@ namespace LuaScript.Engine.Shader
return compiled; return compiled;
} }
private ID3D11PixelShader GetOrCreate(byte[] bytecode)
{
if (_precompiled.TryGetValue(bytecode, out var cached))
return cached;
var shader = _device!.CreatePixelShader(bytecode);
_precompiled[bytecode] = shader;
return shader;
}
private static byte[] CompileOrThrow(string source, string entryPoint, string profile) private static byte[] CompileOrThrow(string source, string entryPoint, string profile)
{ {
var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors); var result = Compiler.Compile(Encoding.UTF8.GetBytes(source), entryPoint, string.Empty, profile, out var bytecode, out var errors);
@@ -503,7 +594,7 @@ namespace LuaScript.Engine.Shader
if (!_failureLogged) if (!_failureLogged)
{ {
_failureLogged = true; _failureLogged = true;
Log.Default.Write("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex); WriteLog("LuaScript: obj.pixelshader execution failed; the call is skipped.", ex);
} }
ReleaseDeviceObjects(); ReleaseDeviceObjects();
if (_recreateBudget <= 0) if (_recreateBudget <= 0)
@@ -517,16 +608,21 @@ namespace LuaScript.Engine.Shader
return; return;
_failureLogged = true; _failureLogged = true;
if (ex is null) if (ex is null)
Log.Default.Write("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled."); WriteLog("LuaScript: Direct3D 11 is unavailable; obj.pixelshader is disabled.", null);
else else
Log.Default.Write("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex); WriteLog("LuaScript: Direct3D 11 initialization failed; obj.pixelshader is disabled.", ex);
} }
private void WriteLog(string message, Exception? exception) => Logger?.Invoke(message, exception);
private void ReleaseShaders() private void ReleaseShaders()
{ {
foreach (var compiled in _shaders.Values) foreach (var compiled in _shaders.Values)
compiled.Shader?.Dispose(); compiled.Shader?.Dispose();
_shaders.Clear(); _shaders.Clear();
foreach (var shader in _precompiled.Values)
shader.Dispose();
_precompiled.Clear();
} }
private void ReleaseDeviceObjects() private void ReleaseDeviceObjects()
+58
ファイルの表示
@@ -0,0 +1,58 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 values[256];
};
float get_value(uint index)
{
uint row = index >> 2;
uint column = index & 3u;
float4 value = values[row];
if (column == 0u)
return value.x;
if (column == 1u)
return value.y;
if (column == 2u)
return value.z;
return value.w;
}
float convolve_channel(float value)
{
return floor(saturate(value) * 255.0) / 255.0;
}
float4 convolve(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
int width = (int)get_value(0u);
int height = (int)get_value(1u);
float divisor = get_value(2u);
float offset = get_value(3u) / 255.0;
int kernelSize = (int)get_value(4u);
int radius = (int)get_value(5u);
float4 sum = 0.0;
for (int ky = 0; ky < kernelSize; ky++)
{
int sy = clamp((int)p.y + ky - radius, 0, height - 1);
for (int kx = 0; kx < kernelSize; kx++)
{
int sx = clamp((int)p.x + kx - radius, 0, width - 1);
float kv = get_value((uint)(8 + ky * kernelSize + kx));
float4 sourceValue = source[uint2((uint)sx, (uint)sy)];
float3 rgb = sourceValue.a <= 0.0 ? 0.0 : saturate(sourceValue.rgb / sourceValue.a);
sum += float4(rgb, sourceValue.a) * kv;
}
}
float3 rgbOut = saturate(sum.rgb / divisor + offset);
float alpha = saturate(sum.a / divisor + offset);
return float4(
convolve_channel(rgbOut.r * alpha),
convolve_channel(rgbOut.g * alpha),
convolve_channel(rgbOut.b * alpha),
convolve_channel(alpha));
}
+21
ファイルの表示
@@ -0,0 +1,21 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 color;
float4 rect;
};
float4 fill_full(float4 pos : SV_Position) : SV_Target
{
return color;
}
float4 fill_partial(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
uint4 r = (uint4)rect;
if (p.x >= r.x && p.y >= r.y && p.x < r.z && p.y < r.w)
return color;
return source[p];
}
+56
ファイルの表示
@@ -0,0 +1,56 @@
Texture2D source : register(t0);
cbuffer Parameters : register(b0)
{
float4 size;
};
float channel(float value)
{
return floor(saturate(value) * 255.0) / 255.0;
}
float4 resize_pack(float4 value)
{
return float4(channel(value.r), channel(value.g), channel(value.b), channel(value.a));
}
float4 resize_nearest(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
uint sourceWidth = (uint)size.x;
uint sourceHeight = (uint)size.y;
uint targetWidth = (uint)size.z;
uint targetHeight = (uint)size.w;
uint sx = min(((p.x * 2u + 1u) * sourceWidth) / (targetWidth * 2u), sourceWidth - 1u);
uint sy = min(((p.y * 2u + 1u) * sourceHeight) / (targetHeight * 2u), sourceHeight - 1u);
return source[uint2(sx, sy)];
}
float4 resize_linear(float4 pos : SV_Position) : SV_Target
{
uint2 p = (uint2)floor(pos.xy);
float sourceWidth = size.x;
float sourceHeight = size.y;
float targetWidth = size.z;
float targetHeight = size.w;
float u = (p.x + 0.5) * sourceWidth / targetWidth - 0.5;
float v = (p.y + 0.5) * sourceHeight / targetHeight - 0.5;
int x0 = (int)floor(u);
int y0 = (int)floor(v);
float tx = u - x0;
float ty = v - y0;
int maxX = (int)sourceWidth - 1;
int maxY = (int)sourceHeight - 1;
uint xA = (uint)clamp(x0, 0, maxX);
uint yA = (uint)clamp(y0, 0, maxY);
uint xB = (uint)clamp(x0 + 1, 0, maxX);
uint yB = (uint)clamp(y0 + 1, 0, maxY);
float4 c00 = source[uint2(xA, yA)];
float4 c10 = source[uint2(xB, yA)];
float4 c01 = source[uint2(xA, yB)];
float4 c11 = source[uint2(xB, yB)];
float4 top = c00 * (1.0 - tx) + c10 * tx;
float4 bottom = c01 * (1.0 - tx) + c11 * tx;
return resize_pack(top * (1.0 - ty) + bottom * ty);
}
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.18.0</Version> <Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
+1 -1
ファイルの表示
@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.18.0</Version> <Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+1
ファイルの表示
@@ -60,6 +60,7 @@ namespace LuaScript.Api
} }
var candidates = Keywords var candidates = Keywords
.Concat(LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords)
.Concat(globals) .Concat(globals)
.Concat(tableMembers.Keys) .Concat(tableMembers.Keys)
.Concat(tableMembers.Values.SelectMany(x => x)) .Concat(tableMembers.Values.SelectMany(x => x))
+155
ファイルの表示
@@ -169,6 +169,8 @@ namespace LuaScript
internal IPixelShaderRunner? ShaderRunner { get; set; } internal IPixelShaderRunner? ShaderRunner { get; set; }
internal IPixelBufferProcessor? PixelProcessor { get; set; }
internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty; internal AviUtlPixelShaderLibrary PixelShaders { get; set; } = AviUtlPixelShaderLibrary.Empty;
internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) => internal bool TryGetShaderResource(string id, out byte[] data, out int width, out int height) =>
@@ -504,5 +506,158 @@ namespace LuaScript
p[3] = (byte)Math.Clamp(a, 0d, 255d); p[3] = (byte)Math.Clamp(a, 0d, 255d);
} }
} }
private double[]? _convolveSource;
private byte[]? _resizeSource;
private byte[]? _resizeBuffer;
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
int cw = ImageWidth;
int ch = ImageHeight;
int x0 = Math.Clamp(x, 0, cw);
int y0 = Math.Clamp(y, 0, ch);
int x1 = Math.Clamp(x + w, 0, cw);
int y1 = Math.Clamp(y + h, 0, ch);
if (x1 <= x0 || y1 <= y0)
return;
if (PixelProcessor?.TryFill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0, force) == true)
{
_isPixelsDirty = true;
return;
}
_isPixelsDirty = true;
PixelBufferSoftwareProcessor.Fill(_pixelBuffer, cw, ch, r, g, b, a, x0, y0, x1 - x0, y1 - y0);
}
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
{
EnsurePixelBuffer();
int cw = ImageWidth;
int ch = ImageHeight;
if (_pixelBuffer is null)
{
Array.Clear(destination, 0, w * h * 4);
return;
}
fixed (byte* buf = _pixelBuffer)
{
for (int j = 0; j < h; j++)
{
int sy = y + j;
for (int i = 0; i < w; i++)
{
int sx = x + i;
int di = (j * w + i) * 4;
if ((uint)sx >= (uint)cw || (uint)sy >= (uint)ch)
{
destination[di] = 0d;
destination[di + 1] = 0d;
destination[di + 2] = 0d;
destination[di + 3] = 0d;
continue;
}
byte* p = buf + (sy * cw + sx) * 4;
double a = p[3];
if (a <= 0d)
{
destination[di] = 0d;
destination[di + 1] = 0d;
destination[di + 2] = 0d;
destination[di + 3] = 0d;
}
else
{
double s = 255d / a;
destination[di] = Math.Clamp(p[2] * s, 0d, 255d);
destination[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
destination[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
destination[di + 3] = a;
}
}
}
}
}
public unsafe void WriteRegion(int x, int y, int w, int h, double[] source)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
int cw = ImageWidth;
int ch = ImageHeight;
_isPixelsDirty = true;
fixed (byte* buf = _pixelBuffer)
{
for (int j = 0; j < h; j++)
{
int dy = y + j;
if ((uint)dy >= (uint)ch)
continue;
for (int i = 0; i < w; i++)
{
int dx = x + i;
if ((uint)dx >= (uint)cw)
continue;
int si = (j * w + i) * 4;
double a = Math.Clamp(source[si + 3], 0d, 255d);
double aK = a / 255d;
byte* p = buf + (dy * cw + dx) * 4;
p[0] = (byte)Math.Clamp(source[si + 2] * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(source[si + 1] * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(source[si] * aK, 0d, 255d);
p[3] = (byte)a;
}
}
}
}
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
int cw = ImageWidth;
int ch = ImageHeight;
if (PixelProcessor?.TryConvolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, force) == true)
{
_isPixelsDirty = true;
return;
}
_isPixelsDirty = true;
PixelBufferSoftwareProcessor.Convolve(_pixelBuffer, cw, ch, kernel, size, divisor, offset, ref _convolveSource);
}
public unsafe void Resize(int newWidth, int newHeight, bool linear, bool force = false)
{
EnsurePixelBuffer();
if (_pixelBuffer is null)
return;
newWidth = Math.Max(1, newWidth);
newHeight = Math.Max(1, newHeight);
int cw = ImageWidth;
int ch = ImageHeight;
if (PixelProcessor?.TryResize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, out var processed, force) == true && processed is not null)
{
ReplaceBuffer(processed, newWidth, newHeight);
return;
}
var dst = PixelBufferSoftwareProcessor.Resize(_pixelBuffer, cw, ch, newWidth, newHeight, linear, ref _resizeSource, ref _resizeBuffer);
ReplaceBuffer(dst, newWidth, newHeight);
}
} }
} }
+11
ファイルの表示
@@ -0,0 +1,11 @@
namespace LuaScript
{
internal interface IPixelBufferProcessor
{
bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false);
bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false);
bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false);
}
}
+103 -3
ファイルの表示
@@ -44,6 +44,8 @@ namespace LuaScript.Engine
private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][]; private readonly byte[]?[] _shaderResourceData = new byte[NativeProtocol.ShaderResourcesMax][];
private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax]; private readonly float[] _shaderConstants = new float[NativeProtocol.ShaderConstantsMax];
private byte[] _shaderTarget = []; private byte[] _shaderTarget = [];
private byte[] _pixelProcessTarget = [];
private double[] _pixelProcessKernel = [];
private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes; private long PixelRegionCapacity => _allocatedSize - _pixelOffset - NativeProtocol.ShaderRegionBytes;
@@ -81,6 +83,7 @@ namespace LuaScript.Engine
Action<string, SceneValue> sceneSetValue, Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio, Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader, PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor,
out bool pixelsDirty, out bool pixelsDirty,
out bool bufferReplaced, out bool bufferReplaced,
out int resultWidth, out int resultWidth,
@@ -124,16 +127,18 @@ namespace LuaScript.Engine
view.Write(NativeProtocol.OffScriptVersion, _scriptVersion); view.Write(NativeProtocol.OffScriptVersion, _scriptVersion);
view.Write(NativeProtocol.OffPixelsDirty, 0); view.Write(NativeProtocol.OffPixelsDirty, 0);
view.Write(NativeProtocol.OffErrorLen, 0); view.Write(NativeProtocol.OffErrorLen, 0);
view.Write(NativeProtocol.OffCallbackFound, pixelProcessor is null ? -1 : 1);
view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle); view.Write(NativeProtocol.OffStatus, NativeProtocol.StatusIdle);
view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun); view.Write(NativeProtocol.OffCommand, NativeProtocol.CmdRun);
_workEvent!.Set(); _workEvent!.Set();
var stopwatch = Stopwatch.StartNew(); var stopwatch = Stopwatch.StartNew();
long budget = timeoutMs;
int status; int status;
while (true) while (true)
{ {
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds; long remaining = budget - stopwatch.ElapsedMilliseconds;
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining)) if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
{ {
KillWorker(); KillWorker();
@@ -145,6 +150,7 @@ namespace LuaScript.Engine
if (status != NativeProtocol.StatusCallback) if (status != NativeProtocol.StatusCallback)
break; break;
long callbackStart = stopwatch.ElapsedMilliseconds;
int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind); int callbackKind = view.ReadInt32(NativeProtocol.OffCallbackKind);
if (callbackKind == NativeProtocol.CbKindRequestPixels) if (callbackKind == NativeProtocol.CbKindRequestPixels)
{ {
@@ -164,8 +170,9 @@ namespace LuaScript.Engine
} }
else else
{ {
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader); DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader, pixelProcessor);
} }
budget += stopwatch.ElapsedMilliseconds - callbackStart;
_workEvent.Set(); _workEvent.Set();
} }
@@ -332,7 +339,8 @@ namespace LuaScript.Engine
Func<string, SceneValue> sceneGetValue, Func<string, SceneValue> sceneGetValue,
Action<string, SceneValue> sceneSetValue, Action<string, SceneValue> sceneSetValue,
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio, Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
PixelShaderInvoke? runPixelShader) PixelShaderInvoke? runPixelShader,
IPixelBufferProcessor? pixelProcessor)
{ {
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind); int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
switch (kind) switch (kind)
@@ -382,9 +390,101 @@ namespace LuaScript.Engine
case NativeProtocol.CbKindPixelShaderRun: case NativeProtocol.CbKindPixelShaderRun:
ResolveShaderRunCallback(view, runPixelShader); ResolveShaderRunCallback(view, runPixelShader);
break; break;
case NativeProtocol.CbKindPixelProcess:
ResolvePixelProcessCallback(view, pixelProcessor);
break;
} }
} }
private void ResolvePixelProcessCallback(MemoryMappedViewAccessor view, IPixelBufferProcessor? pixelProcessor)
{
bool processed = false;
if (pixelProcessor is not null)
{
int width = view.ReadInt32(NativeProtocol.OffWidth);
int height = view.ReadInt32(NativeProtocol.OffHeight);
long length = (long)width * height * 4;
if (width > 0 && height > 0 && length <= PixelRegionCapacity && length <= int.MaxValue)
{
int pixelLength = (int)length;
if (_pixelProcessTarget.Length < pixelLength)
_pixelProcessTarget = new byte[pixelLength];
int operation = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
bool force = view.ReadDouble(NativeProtocol.CallbackResultOffset + 9 * 8) != 0d;
processed = operation switch
{
NativeProtocol.PixelProcessFill => TryProcessFill(view, pixelProcessor, width, height, pixelLength, force),
NativeProtocol.PixelProcessConvolve => TryProcessConvolve(view, pixelProcessor, width, height, pixelLength, force),
NativeProtocol.PixelProcessResize => TryProcessResize(view, pixelProcessor, pixelLength, force),
_ => false,
};
}
}
view.Write(NativeProtocol.OffCallbackFound, processed ? 1 : pixelProcessor is null ? -1 : 0);
}
private bool TryProcessFill(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
double r = view.ReadDouble(offset + 1 * 8);
double g = view.ReadDouble(offset + 2 * 8);
double b = view.ReadDouble(offset + 3 * 8);
double a = view.ReadDouble(offset + 4 * 8);
int x = (int)view.ReadDouble(offset + 5 * 8);
int y = (int)view.ReadDouble(offset + 6 * 8);
int fillWidth = (int)view.ReadDouble(offset + 7 * 8);
int fillHeight = (int)view.ReadDouble(offset + 8 * 8);
if (x != 0 || y != 0 || fillWidth != width || fillHeight != height)
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
if (!pixelProcessor.TryFill(_pixelProcessTarget, width, height, r, g, b, a, x, y, fillWidth, fillHeight, force))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessConvolve(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int width, int height, int pixelLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
int size = (int)view.ReadDouble(offset + 1 * 8);
double divisor = view.ReadDouble(offset + 2 * 8);
double kernelOffset = view.ReadDouble(offset + 3 * 8);
if (size < 1 || (size & 1) == 0)
return false;
int taps = size * size;
if (taps <= 0 || taps * 8 > Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax))
return false;
if (_pixelProcessKernel.Length < taps)
_pixelProcessKernel = new double[taps];
ReadRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
view.ReadArray(NativeProtocol.CallbackTagOffset, _pixelProcessKernel, 0, taps);
if (!pixelProcessor.TryConvolve(_pixelProcessTarget, width, height, _pixelProcessKernel, size, divisor, kernelOffset, force))
return false;
WriteRegion(_pixelOffset, _pixelProcessTarget, pixelLength);
return true;
}
private bool TryProcessResize(MemoryMappedViewAccessor view, IPixelBufferProcessor pixelProcessor, int sourceLength, bool force)
{
long offset = NativeProtocol.CallbackResultOffset;
int targetWidth = (int)view.ReadDouble(offset + 1 * 8);
int targetHeight = (int)view.ReadDouble(offset + 2 * 8);
bool linear = view.ReadDouble(offset + 3 * 8) != 0d;
long length = (long)targetWidth * targetHeight * 4;
int sourceWidth = view.ReadInt32(NativeProtocol.OffWidth);
int sourceHeight = view.ReadInt32(NativeProtocol.OffHeight);
if (targetWidth <= 0 || targetHeight <= 0 || length > PixelRegionCapacity || length > int.MaxValue)
return false;
ReadRegion(_pixelOffset, _pixelProcessTarget, sourceLength);
if (!pixelProcessor.TryResize(_pixelProcessTarget, sourceWidth, sourceHeight, targetWidth, targetHeight, linear, out var target, force) || target is null)
return false;
WriteRegion(_pixelOffset, target, (int)length);
view.Write(NativeProtocol.OffWidth, targetWidth);
view.Write(NativeProtocol.OffHeight, targetHeight);
return true;
}
private void ResolveShaderStageCallback(MemoryMappedViewAccessor view) private void ResolveShaderStageCallback(MemoryMappedViewAccessor view)
{ {
long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize); long meta = NativeProtocol.ShaderMetaOffset(_allocatedSize);
+160 -8
ファイルの表示
@@ -181,9 +181,17 @@ namespace LuaScript
script.AttachDebugger(_debugger); script.AttachDebugger(_debugger);
_globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio); _globalRegistrar = new AviUtlGlobalRegistrar(CurrentTimeRatio);
_globalRegistrar.RegisterLuaMembers(script.Globals); _globalRegistrar.RegisterLuaMembers(script.Globals);
RegisterFastPrimitives(script);
_script = script; _script = script;
} }
private void RegisterFastPrimitives(Script script)
{
script.Globals.Set("__fast_fill", DynValue.NewCallback((_, args) => FillCore(args, true)));
script.Globals.Set("__fast_convolve", DynValue.NewCallback((_, args) => ConvolveCore(args, true)));
script.Globals.Set("__fast_resize", DynValue.NewCallback((_, args) => ResizeCore(args, true)));
}
private void EnsureScriptIntegrity() private void EnsureScriptIntegrity()
{ {
if (_script is null) return; if (_script is null) return;
@@ -987,6 +995,150 @@ namespace LuaScript
}; };
} }
private double[] _regionScratch = [];
private double[] _kernelScratch = [];
private static readonly DynValue[] s_byteNumbers = CreateByteNumbers();
private static DynValue[] CreateByteNumbers()
{
var values = new DynValue[256];
for (int i = 0; i < values.Length; i++)
values[i] = DynValue.NewNumber(i).AsReadOnly();
return values;
}
private static DynValue ChannelValue(double value)
{
int b = (int)value;
return b == value && (uint)b < 256u ? s_byteNumbers[b] : DynValue.NewNumber(value);
}
[LuaFunction("fill")]
private DynValue Fill(CallbackArguments args) => FillCore(args, false);
private DynValue FillCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null)
return DynValue.Void;
var ctx = _activeContext;
double r = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
double g = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
double b = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
double a = args.Count > 3 ? args[3].CastToNumber() ?? 255d : 255d;
int x = args.Count > 4 ? (int)(args[4].CastToNumber() ?? 0d) : 0;
int y = args.Count > 5 ? (int)(args[5].CastToNumber() ?? 0d) : 0;
int w = args.Count > 6 ? (int)(args[6].CastToNumber() ?? 0d) : ctx.ImageWidth;
int h = args.Count > 7 ? (int)(args[7].CastToNumber() ?? 0d) : ctx.ImageHeight;
ctx.FillBuffer(r, g, b, a, x, y, w, h, force);
return DynValue.Void;
}
[LuaFunction("getpixelregion")]
private DynValue GetPixelRegion(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || _script is null || args.Count < 4)
return DynValue.Nil;
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
int w = (int)(args[2].CastToNumber() ?? 0d);
int h = (int)(args[3].CastToNumber() ?? 0d);
var table = new Table(_script);
if (w <= 0 || h <= 0)
return DynValue.NewTable(table);
int count = w * h * 4;
if (_regionScratch.Length < count)
_regionScratch = new double[count];
_activeContext.ReadRegion(x, y, w, h, _regionScratch);
for (int i = 0; i < count; i++)
table.Set(i + 1, ChannelValue(_regionScratch[i]));
return DynValue.NewTable(table);
}
[LuaFunction("putpixelregion")]
private DynValue PutPixelRegion(CallbackArguments args)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 5 || args[4].Type != DataType.Table)
return DynValue.Void;
int x = (int)(args[0].CastToNumber() ?? 0d);
int y = (int)(args[1].CastToNumber() ?? 0d);
int w = (int)(args[2].CastToNumber() ?? 0d);
int h = (int)(args[3].CastToNumber() ?? 0d);
if (w <= 0 || h <= 0)
return DynValue.Void;
int count = w * h * 4;
if (_regionScratch.Length < count)
_regionScratch = new double[count];
var table = args[4].Table;
for (int i = 0; i < count; i++)
_regionScratch[i] = table.Get(i + 1).CastToNumber() ?? 0d;
_activeContext.WriteRegion(x, y, w, h, _regionScratch);
return DynValue.Void;
}
[LuaFunction("convolve")]
private DynValue Convolve(CallbackArguments args) => ConvolveCore(args, false);
private DynValue ConvolveCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
return DynValue.Void;
int size = (int)(args[1].CastToNumber() ?? 0d);
if (size < 1 || (size & 1) == 0)
return DynValue.Void;
int taps = size * size;
var kernel = args[0].Table;
if (_kernelScratch.Length < taps)
_kernelScratch = new double[taps];
double sum = 0d;
for (int i = 0; i < taps; i++)
{
double v = kernel.Get(i + 1).CastToNumber() ?? 0d;
_kernelScratch[i] = v;
sum += v;
}
double divisor = args.Count > 2 ? args[2].CastToNumber() ?? sum : sum;
if (divisor == 0d)
divisor = 1d;
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
_activeContext.Convolve(_kernelScratch, size, divisor, offset, force);
return DynValue.Void;
}
[LuaFunction("resize")]
private DynValue Resize(CallbackArguments args) => ResizeCore(args, false);
private DynValue ResizeCore(CallbackArguments args, bool force)
{
_activeCancellation.ThrowIfCancellationRequested();
if (_activeContext is null || args.Count < 2)
return DynValue.Void;
int w = (int)(args[0].CastToNumber() ?? 0d);
int h = (int)(args[1].CastToNumber() ?? 0d);
if (w <= 0 || h <= 0)
return DynValue.Void;
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
_activeContext.Resize(w, h, linear, force);
RefreshObjDimensions();
return DynValue.Void;
}
private double CurrentAntialias() => private double CurrentAntialias() =>
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number _options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
? value.Number ? value.Number
@@ -1070,14 +1222,14 @@ namespace LuaScript
int w = _activeContext!.ImageWidth; int w = _activeContext!.ImageWidth;
int h = _activeContext.ImageHeight; int h = _activeContext.ImageHeight;
var obj = _objScope.Table; var obj = _objScope.Table;
obj["w"] = w; obj.Set("w", DynValue.NewNumber(w));
obj["h"] = h; obj.Set("h", DynValue.NewNumber(h));
obj["hw"] = w / 2d; obj.Set("hw", DynValue.NewNumber(w / 2d));
obj["hh"] = h / 2d; obj.Set("hh", DynValue.NewNumber(h / 2d));
obj["cx"] = w / 2d; obj.Set("cx", DynValue.NewNumber(w / 2d));
obj["cy"] = h / 2d; obj.Set("cy", DynValue.NewNumber(h / 2d));
obj["cz"] = 0d; obj.Set("cz", DynValue.NewNumber(0d));
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h); obj.Set("diagonal", DynValue.NewNumber(Math.Sqrt((double)w * w + (double)h * h)));
} }
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info) private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
+5
ファイルの表示
@@ -67,6 +67,11 @@ namespace LuaScript.Engine
public const int CbKindLoadBrush = 16; public const int CbKindLoadBrush = 16;
public const int CbKindBrush = 17; public const int CbKindBrush = 17;
public const int CbKindGetAudio = 18; public const int CbKindGetAudio = 18;
public const int CbKindPixelProcess = 19;
public const int PixelProcessFill = 0;
public const int PixelProcessConvolve = 1;
public const int PixelProcessResize = 2;
public const int DrawRingCapacity = 4096; public const int DrawRingCapacity = 4096;
public const int DrawEntryDoubles = 24; public const int DrawEntryDoubles = 24;
+166
ファイルの表示
@@ -0,0 +1,166 @@
using System;
namespace LuaScript
{
internal static unsafe class PixelBufferSoftwareProcessor
{
public static void Fill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight)
{
double aK = Math.Clamp(a, 0d, 255d) / 255d;
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
byte pa = (byte)Math.Clamp(a, 0d, 255d);
int x1 = x + fillWidth;
int y1 = y + fillHeight;
fixed (byte* buf = target)
{
for (int py = y; py < y1; py++)
{
byte* p = buf + (py * width + x) * 4;
for (int px = x; px < x1; px++)
{
p[0] = pb;
p[1] = pg;
p[2] = pr;
p[3] = pa;
p += 4;
}
}
}
}
public static void Convolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, ref double[]? sourceScratch)
{
int count = width * height * 4;
if (sourceScratch is null || sourceScratch.Length < count)
sourceScratch = new double[count];
var src = sourceScratch;
fixed (byte* buf = target)
{
for (int pi = 0; pi < width * height; pi++)
{
byte* p = buf + pi * 4;
int di = pi * 4;
double a = p[3];
src[di + 3] = a;
if (a <= 0d)
{
src[di] = 0d;
src[di + 1] = 0d;
src[di + 2] = 0d;
}
else
{
double s = 255d / a;
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
}
}
}
int half = size / 2;
fixed (byte* buf = target)
{
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
for (int ky = 0; ky < size; ky++)
{
int sy = Math.Clamp(y + ky - half, 0, height - 1);
for (int kx = 0; kx < size; kx++)
{
int sx = Math.Clamp(x + kx - half, 0, width - 1);
double kv = kernel[ky * size + kx];
int si = (sy * width + sx) * 4;
sr += src[si] * kv;
sg += src[si + 1] * kv;
sb += src[si + 2] * kv;
sa += src[si + 3] * kv;
}
}
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
double aK = aa / 255d;
byte* p = buf + (y * width + x) * 4;
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
p[3] = (byte)aa;
}
}
}
}
public static byte[] Resize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, ref byte[]? sourceScratch, ref byte[]? targetScratch)
{
int srcCount = sourceWidth * sourceHeight * 4;
if (sourceScratch is null || sourceScratch.Length < srcCount)
sourceScratch = new byte[srcCount];
Buffer.BlockCopy(source, 0, sourceScratch, 0, srcCount);
int dstCount = targetWidth * targetHeight * 4;
if (targetScratch is null || targetScratch.Length != dstCount)
targetScratch = new byte[dstCount];
var src = sourceScratch;
var dst = targetScratch;
fixed (byte* s = src)
fixed (byte* d = dst)
{
for (int y = 0; y < targetHeight; y++)
{
for (int x = 0; x < targetWidth; x++)
{
byte* o = d + (y * targetWidth + x) * 4;
if (!linear)
{
int sx = Math.Clamp((int)((x + 0.5) * sourceWidth / targetWidth), 0, sourceWidth - 1);
int sy = Math.Clamp((int)((y + 0.5) * sourceHeight / targetHeight), 0, sourceHeight - 1);
byte* p = s + (sy * sourceWidth + sx) * 4;
o[0] = p[0];
o[1] = p[1];
o[2] = p[2];
o[3] = p[3];
}
else
{
double u = (x + 0.5) * sourceWidth / targetWidth - 0.5;
double v = (y + 0.5) * sourceHeight / targetHeight - 0.5;
int x0 = (int)Math.Floor(u);
int y0 = (int)Math.Floor(v);
double tx = u - x0;
double ty = v - y0;
for (int c = 0; c < 4; c++)
{
double acc = 0d;
for (int j = 0; j < 2; j++)
{
int sy = Math.Clamp(y0 + j, 0, sourceHeight - 1);
double wy = j == 0 ? 1d - ty : ty;
for (int i = 0; i < 2; i++)
{
int sx = Math.Clamp(x0 + i, 0, sourceWidth - 1);
double wx = i == 0 ? 1d - tx : tx;
acc += s[(sy * sourceWidth + sx) * 4 + c] * wy * wx;
}
}
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
}
}
}
}
}
return dst;
}
}
}
+3 -2
ファイルの表示
@@ -1,15 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.18.0</Version> <Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<InternalsVisibleTo Include="LuaScript.Gpu" />
<InternalsVisibleTo Include="LuaScript" /> <InternalsVisibleTo Include="LuaScript" />
<InternalsVisibleTo Include="LuaScript.Tests" /> <InternalsVisibleTo Include="LuaScript.Tests" />
</ItemGroup> </ItemGroup>
+5 -5
ファイルの表示
@@ -137,35 +137,35 @@ namespace LuaScript.Tests
[Fact] [Fact]
public void ChangedLines_EmptyWhenNoRewrite() public void ChangedLines_EmptyWhenNoRewrite()
{ {
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2"); var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = 2");
Assert.Empty(changed); Assert.Empty(changed);
} }
[Fact] [Fact]
public void ChangedLines_ReportRewrittenLineInRunnableSpace() public void ChangedLines_ReportRewrittenLineInRunnableSpace()
{ {
var (_, _, changed) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3"); var (_, _, changed, _) = AviUtlScript.TransformWithMap("obj.x = 1\nobj.y = obj.x != 0\nobj.z = 3");
Assert.Equal(new[] { 2 }, changed); Assert.Equal(new[] { 2 }, changed);
} }
[Fact] [Fact]
public void ChangedLines_AreSortedAndCoverEveryRewrittenLine() public void ChangedLines_AreSortedAndCoverEveryRewrittenLine()
{ {
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++"); var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0\nb = y\nc = z ?? 5\nw++");
Assert.Equal(new[] { 1, 3, 4 }, changed); Assert.Equal(new[] { 1, 3, 4 }, changed);
} }
[Fact] [Fact]
public void ChangedLines_DeduplicateMultipleRewritesOnOneLine() public void ChangedLines_DeduplicateMultipleRewritesOnOneLine()
{ {
var (_, _, changed) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2"); var (_, _, changed, _) = AviUtlScript.TransformWithMap("a = x != 0 and y != 1 and z != 2");
Assert.Equal(new[] { 1 }, changed); Assert.Equal(new[] { 1 }, changed);
} }
[Fact] [Fact]
public void ChangedLines_TrackRunnableLineAfterHoistedPrelude() public void ChangedLines_TrackRunnableLineAfterHoistedPrelude()
{ {
var (_, _, changed) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0"); var (_, _, changed, _) = AviUtlScript.TransformWithMap("--dialog:V,local v=3;\nresult = v != 0");
Assert.NotEmpty(changed); Assert.NotEmpty(changed);
for (int i = 1; i < changed.Length; i++) for (int i = 1; i < changed.Length; i++)
Assert.True(changed[i] > changed[i - 1]); Assert.True(changed[i] > changed[i - 1]);
+5 -1
ファイルの表示
@@ -11,6 +11,8 @@ namespace LuaScript.Tests
"repeat", "return", "then", "true", "until", "while" "repeat", "return", "then", "true", "until", "while"
]; ];
private static readonly string[] SyntaxKeywords = ["fast"];
private static readonly string[] Globals = private static readonly string[] Globals =
[ [
"time", "frame", "totalframe", "framerate", "time", "frame", "totalframe", "framerate",
@@ -49,7 +51,8 @@ namespace LuaScript.Tests
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer", "obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
"obj.pixelshader", "obj.pixelshader",
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption", "obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo" "obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo",
"obj.fill", "obj.getpixelregion", "obj.putpixelregion", "obj.convolve", "obj.resize"
]), ]),
("math", [ ("math", [
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor", "math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
@@ -103,6 +106,7 @@ namespace LuaScript.Tests
private static string[] ExpectedStaticCandidates() => private static string[] ExpectedStaticCandidates() =>
Keywords Keywords
.Concat(SyntaxKeywords)
.Concat(Globals) .Concat(Globals)
.Concat(Namespaces.SelectMany(n => n.Members)) .Concat(Namespaces.SelectMany(n => n.Members))
.Distinct() .Distinct()
+274
ファイルの表示
@@ -0,0 +1,274 @@
using LuaScript;
namespace LuaScript.Tests
{
public sealed class LuaScriptEngineBufferOpsTests
{
private sealed class StubMediaLoader : IMediaSourceLoader
{
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public byte[] DecodeImage(string path, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public byte[] DecodeMovie(string path, double time, out int width, out int height)
{
width = 1;
height = 1;
return new byte[4];
}
public void Dispose() { }
}
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
private static AviUtlScriptContext NewContext(byte[] buffer, int width, int height)
{
var ctx = new AviUtlScriptContext { Framerate = 30 };
ctx.SetResolvedBuffer(buffer, width, height);
return ctx;
}
private static byte[] Bgra(params (byte B, byte G, byte R, byte A)[] pixels)
{
var buffer = new byte[pixels.Length * 4];
for (int i = 0; i < pixels.Length; i++)
{
buffer[i * 4 + 0] = pixels[i].B;
buffer[i * 4 + 1] = pixels[i].G;
buffer[i * 4 + 2] = pixels[i].R;
buffer[i * 4 + 3] = pixels[i].A;
}
return buffer;
}
private sealed class RecordingProcessor : IPixelBufferProcessor
{
public int FillCalls;
public int ConvolveCalls;
public int ResizeCalls;
public bool LastFillForce;
public bool LastConvolveForce;
public bool LastResizeForce;
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
FillCalls++;
LastFillForce = force;
return false;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
ConvolveCalls++;
LastConvolveForce = force;
return false;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
ResizeCalls++;
LastResizeForce = force;
target = null;
return false;
}
}
[Fact]
public void BufferOps_ConsultPixelProcessorAndFallBackToCpu()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("obj.fill(200, 100, 50, 255) obj.convolve({1,1,1,1,1,1,1,1,1}, 3) obj.resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(4, ctx.ImageWidth);
Assert.Equal(4, ctx.ImageHeight);
Assert.False(processor.LastFillForce);
Assert.False(processor.LastConvolveForce);
Assert.False(processor.LastResizeForce);
}
[Fact]
public void FastMarker_ForcesPixelProcessorRegardlessOfSize()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
var processor = new RecordingProcessor();
ctx.PixelProcessor = processor;
engine.Execute("__fast_fill(200, 100, 50, 255) __fast_convolve({1,1,1,1,1,1,1,1,1}, 3) __fast_resize(4, 4)", ctx);
Assert.Equal(1, processor.FillCalls);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(1, processor.ResizeCalls);
Assert.True(processor.LastFillForce);
Assert.True(processor.LastConvolveForce);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void Fill_WholeBuffer_WritesPremultipliedColor()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
engine.Execute("obj.fill(200, 100, 50, 255)", ctx);
var buffer = ctx.GetPixelBuffer()!;
for (int i = 0; i < 4; i++)
{
Assert.Equal(50, buffer[i * 4 + 0]);
Assert.Equal(100, buffer[i * 4 + 1]);
Assert.Equal(200, buffer[i * 4 + 2]);
Assert.Equal(255, buffer[i * 4 + 3]);
}
}
[Fact]
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[3 * 1 * 4], 3, 1);
engine.Execute("obj.fill(255, 255, 255, 255, 1, 0, 1, 1)", ctx);
var buffer = ctx.GetPixelBuffer()!;
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(0, 4).ToArray());
Assert.Equal(new byte[] { 255, 255, 255, 255 }, buffer.AsSpan(4, 4).ToArray());
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(8, 4).ToArray());
}
[Fact]
public void GetPixelRegion_ReturnsStraightRgba()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((50, 100, 200, 255)), 1, 1);
engine.Execute("local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]", ctx);
Assert.Equal(200d, ctx.X);
Assert.Equal(100d, ctx.Y);
Assert.Equal(50d, ctx.Z);
Assert.Equal(255d, ctx.Alpha);
}
[Fact]
public void GetPixelRegion_OutOfBounds_YieldsTransparent()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((10, 20, 30, 255)), 1, 1);
engine.Execute("local t = obj.getpixelregion(1, 0, 1, 1) obj.x = t[1] + t[2] + t[3] + t[4]", ctx);
Assert.Equal(0d, ctx.X);
}
[Fact]
public void PutPixelRegion_WritesPremultipliedColor()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[2 * 1 * 4], 2, 1);
engine.Execute("obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})", ctx);
var buffer = ctx.GetPixelBuffer()!;
Assert.Equal(new byte[] { 50, 100, 200, 255 }, buffer.AsSpan(0, 4).ToArray());
Assert.Equal(new byte[] { 30, 20, 10, 255 }, buffer.AsSpan(4, 4).ToArray());
}
[Fact]
public void RegionRoundTrip_PreservesOpaquePixels()
{
using var engine = CreateEngine();
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
var ctx = NewContext((byte[])original.Clone(), 2, 2);
engine.Execute(
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
ctx);
Assert.Equal(original, ctx.GetPixelBuffer());
}
[Fact]
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
{
using var engine = CreateEngine();
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
var ctx = NewContext((byte[])original.Clone(), 2, 2);
engine.Execute("obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)", ctx);
Assert.Equal(original, ctx.GetPixelBuffer());
}
[Fact]
public void Convolve_BoxBlur_AveragesHorizontalStep()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((0, 0, 0, 255), (255, 255, 255, 255)), 2, 1);
engine.Execute("obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)", ctx);
var buffer = ctx.GetPixelBuffer()!;
Assert.Equal(85, buffer[2]);
Assert.Equal(85, buffer[1]);
Assert.Equal(85, buffer[0]);
Assert.Equal(170, buffer[6]);
Assert.Equal(255, buffer[3]);
Assert.Equal(255, buffer[7]);
}
[Fact]
public void Resize_Nearest_ReplicatesBlocks()
{
using var engine = CreateEngine();
var ctx = NewContext(Bgra((11, 12, 13, 255), (21, 22, 23, 255), (31, 32, 33, 255), (41, 42, 43, 255)), 2, 2);
engine.Execute("obj.resize(4, 4, 'nearest')", ctx);
Assert.Equal(4, ctx.ImageWidth);
Assert.Equal(4, ctx.ImageHeight);
Assert.True(ctx.BufferReplaced);
var buffer = ctx.GetPixelBuffer()!;
byte SampleR(int x, int y) => buffer[(y * 4 + x) * 4 + 2];
Assert.Equal(13, SampleR(0, 0));
Assert.Equal(13, SampleR(1, 1));
Assert.Equal(23, SampleR(2, 0));
Assert.Equal(33, SampleR(0, 2));
Assert.Equal(43, SampleR(3, 3));
}
[Fact]
public void Resize_UpdatesObjDimensions()
{
using var engine = CreateEngine();
var ctx = NewContext(new byte[4 * 4 * 4], 4, 4);
engine.Execute("obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal", ctx);
Assert.Equal(8, ctx.ImageWidth);
Assert.Equal(2, ctx.ImageHeight);
Assert.Equal(8d, ctx.X);
Assert.Equal(2d, ctx.Y);
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), ctx.Z);
}
}
}
+90
ファイルの表示
@@ -578,5 +578,95 @@ namespace LuaScript.Tests
{ {
Assert.Equal("for i = 0, 10 do end", Rewrite("for i in <0..10> do end")); Assert.Equal("for i = 0, 10 do end", Rewrite("for i in <0..10> do end"));
} }
[Theory]
[InlineData("[fast] obj.fill(0, 0, 0, 255)", " __fast_fill(0, 0, 0, 255)")]
[InlineData("[fast] obj.convolve(k, 3)", " __fast_convolve(k, 3)")]
[InlineData("[fast] obj.resize(100, 100)", " __fast_resize(100, 100)")]
[InlineData("[ fast ] obj.resize(100, 100)", " __fast_resize(100, 100)")]
[InlineData("[fast]obj.fill()", "__fast_fill()")]
[InlineData(" [fast] obj.fill()", " __fast_fill()")]
public void Fast_RewritesAcceleratedPrimitive(string source, string expected)
{
Assert.Equal(expected, Rewrite(source));
}
[Theory]
[InlineData("[fast]\nobj.fill(0, 0, 0, 255)", "\n__fast_fill(0, 0, 0, 255)")]
[InlineData("[fast]\nobj.convolve(k, 3)", "\n__fast_convolve(k, 3)")]
[InlineData("[fast]\nobj.resize(64, 64)", "\n__fast_resize(64, 64)")]
[InlineData("obj.x = 1\n[fast]\nobj.resize(64, 64)", "obj.x = 1\n\n__fast_resize(64, 64)")]
public void Fast_MarkerOnOwnLine_RewritesNextStatement(string source, string expected)
{
Assert.Equal(expected, Rewrite(source));
}
[Fact]
public void Fast_MarkerOnOwnLine_ReportsDiagnosticOnMarkerLine()
{
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast]\nobj.draw(0)");
Assert.Equal("obj.x = 1\n\nobj.draw(0)", code);
var diagnostic = Assert.Single(diagnostics);
Assert.Equal(2, diagnostic.Line);
}
[Fact]
public void Fast_KeywordIsRegisteredInCatalog()
{
Assert.Contains("fast", LuaScript.Compat.Syntax.LuaSyntaxRuleRegistry.CatalogKeywords);
}
[Fact]
public void Fast_RewritesInsideBlock()
{
Assert.Equal(
"for i = 1, 3 do __fast_fill(i, i, i, 255) end",
Rewrite("for i in <1..3> do [fast] obj.fill(i, i, i, 255) end"));
}
[Theory]
[InlineData("x = t[fast]")]
[InlineData("x = obj.data[fast]")]
[InlineData("x = f()[fast]")]
[InlineData("t = { [fast] = 1 }")]
[InlineData("x = \"[fast] obj.fill()\"")]
[InlineData("-- [fast] obj.fill()")]
public void Fast_DoesNotTouchNonMarkerBrackets(string source)
{
Assert.Equal(source, Rewrite(source));
}
[Fact]
public void Fast_OnUnsupportedTargetStripsMarkerAndReportsDiagnostic()
{
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.draw(0)");
Assert.Equal(" obj.draw(0)", code);
var diagnostic = Assert.Single(diagnostics);
Assert.Equal(1, diagnostic.Line);
Assert.Contains("fast", diagnostic.Message);
}
[Fact]
public void Fast_OnNonObjTargetReportsDiagnostic()
{
var (code, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] local x = 1");
Assert.Equal(" local x = 1", code);
Assert.Single(diagnostics);
}
[Fact]
public void Fast_SupportedTargetEmitsNoDiagnostic()
{
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("[fast] obj.fill(0, 0, 0, 255)");
Assert.Empty(diagnostics);
}
[Fact]
public void Fast_ReportsDiagnosticLineWithinBlock()
{
var (_, _, diagnostics) = LuaSyntaxExtensions.RewriteWithMap("obj.x = 1\n[fast] obj.draw(0)");
var diagnostic = Assert.Single(diagnostics);
Assert.Equal(2, diagnostic.Line);
}
} }
} }
+568
ファイルの表示
@@ -28,6 +28,7 @@ namespace LuaScript.Tests
private Action<string, SceneValue> _sceneSet = (_, _) => { }; private Action<string, SceneValue> _sceneSet = (_, _) => { };
private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []); private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []);
private PixelShaderInvoke? _runPixelShader; private PixelShaderInvoke? _runPixelShader;
private IPixelBufferProcessor? _pixelProcessor;
public void Dispose() => _worker.Dispose(); public void Dispose() => _worker.Dispose();
@@ -77,6 +78,7 @@ namespace LuaScript.Tests
_sceneGet, _sceneSet, _sceneGet, _sceneSet,
_loadAudio, _loadAudio,
_runPixelShader, _runPixelShader,
_pixelProcessor,
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error); out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
resultPixels = null; resultPixels = null;
@@ -114,6 +116,7 @@ namespace LuaScript.Tests
_sceneGet, _sceneSet, _sceneGet, _sceneSet,
_loadAudio, _loadAudio,
_runPixelShader, _runPixelShader,
null,
out _, out _, out _, out _, out string? error); out _, out _, out _, out _, out string? error);
Assert.True(ok, error); Assert.True(ok, error);
@@ -1904,5 +1907,570 @@ namespace LuaScript.Tests
Assert.True(ok2, error); Assert.True(ok2, error);
Assert.Equal(7d, fields2[NativeProtocol.X]); Assert.Equal(7d, fields2[NativeProtocol.X]);
} }
[Fact]
public void PixelProcess_Fill_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 1024, h = 1024;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.True(processor.LastFillForce);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
[Fact]
public void PixelProcess_Convolve_PassesKernelToHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 200, h = 200;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(3, processor.Size);
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
Assert.True(processor.LastConvolveForce);
Assert.Equal(0x42, pixels[0]);
Assert.Equal(0x42, pixels[^1]);
}
[Fact]
public void PixelProcess_Resize_ReplacesBufferWithHostResult()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"__fast_resize(512, 512, 'nearest') obj.x = obj.w obj.y = obj.h",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool replaced, out byte[]? result, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(replaced);
Assert.Equal(512, rw);
Assert.Equal(512, rh);
Assert.Equal(512d, processor.TargetWidth);
Assert.Equal(512d, processor.TargetHeight);
Assert.False(processor.Linear);
Assert.Equal(512d, fields[NativeProtocol.X]);
Assert.Equal(512d, fields[NativeProtocol.Y]);
Assert.NotNull(result);
Assert.Equal(0x43, result![0]);
Assert.Equal(0x43, result[^1]);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void PixelProcess_DefaultFill_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 1024, h = 1024;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40, 0, 0, 1024, 1024)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.FillCalls);
Assert.False(processor.LastFillForce);
Assert.Equal(0x41, pixels[0]);
Assert.Equal(0x41, pixels[^1]);
}
[Fact]
public void PixelProcess_DefaultConvolve_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 200, h = 200;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.convolve({1, 2, 3, 4, 5, 6, 7, 8, 9}, 3, 45, 6)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(1, processor.ConvolveCalls);
Assert.Equal(3, processor.Size);
Assert.Equal(45d, processor.Divisor);
Assert.Equal(6d, processor.Offset);
Assert.Equal(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, processor.Kernel);
Assert.False(processor.LastConvolveForce);
}
[Fact]
public void PixelProcess_DefaultResize_UsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.resize(512, 512, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out bool replaced, out _, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(replaced);
Assert.Equal(1, processor.ResizeCalls);
Assert.Equal(512, rw);
Assert.Equal(512, rh);
Assert.False(processor.LastResizeForce);
}
[Fact]
public void PixelProcess_BelowThresholdFill_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 64, h = 64;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.fill(10, 20, 30, 40)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.FillCalls);
}
[Fact]
public void PixelProcess_BelowThresholdConvolve_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 8, h = 8;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ConvolveCalls);
}
[Fact]
public void PixelProcess_BelowThresholdResize_SkipsHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"obj.resize(4, 4, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(0, processor.ResizeCalls);
}
[Fact]
public void PixelProcess_ForcedFastFill_BelowThresholdUsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 64, h = 64;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { FillResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_fill(10, 20, 30, 40)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, processor.FillCalls);
Assert.True(processor.LastFillForce);
}
[Fact]
public void PixelProcess_ForcedFastConvolve_BelowThresholdUsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 8, h = 8;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ConvolveResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, processor.ConvolveCalls);
Assert.True(processor.LastConvolveForce);
}
[Fact]
public void PixelProcess_ForcedFastResize_BelowThresholdUsesHostProcessor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var processor = new RecordingPixelProcessor { ResizeResult = true };
_pixelProcessor = processor;
bool ok = RunWorker(
"__fast_resize(4, 4, 'nearest')",
Fields(w, h, 0d), NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(1, processor.ResizeCalls);
Assert.True(processor.LastResizeForce);
}
[Fact]
public void HostCallbackTime_DoesNotConsumeScriptTimeout()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var decoded = new byte[4];
Func<string, (byte[], int, int)> slowLoadImage = _ =>
{
System.Threading.Thread.Sleep(1500);
return (decoded, 1, 1);
};
var pixels = new byte[2 * 2 * 4];
var fields = Fields(2, 2, 0d);
bool ok = RunWorker(
"obj.load('image', 'C:/sample.png') obj.x = 5",
fields, NoStringParams, () => pixels, 2, 2, 1000, NoResolver, NoLoadFigure, NoLoadText, slowLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(5d, fields[NativeProtocol.X]);
}
[Fact]
public void Fill_WritesPremultipliedColor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[w * h * 4];
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.fill(200, 100, 50, 255)",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
for (int i = 0; i < w * h; i++)
{
Assert.Equal(50, pixels[i * 4 + 0]);
Assert.Equal(100, pixels[i * 4 + 1]);
Assert.Equal(200, pixels[i * 4 + 2]);
Assert.Equal(255, pixels[i * 4 + 3]);
}
}
[Fact]
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 3, h = 1;
var pixels = new byte[w * h * 4];
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.fill(255, 255, 255, 255, 1, 0, 1, 1)",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(0, 4).ToArray());
Assert.Equal(new byte[] { 255, 255, 255, 255 }, pixels.AsSpan(4, 4).ToArray());
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(8, 4).ToArray());
}
[Fact]
public void GetPixelRegion_ReturnsStraightRgba()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[] { 50, 100, 200, 255 };
var fields = Fields(1, 1, 0d);
bool ok = RunWorker(
"local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]",
fields, NoStringParams, () => pixels, 1, 1, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.Equal(200d, fields[NativeProtocol.X]);
Assert.Equal(100d, fields[NativeProtocol.Y]);
Assert.Equal(50d, fields[NativeProtocol.Z]);
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
}
[Fact]
public void PutPixelRegion_WritesPremultipliedColor()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 1;
var pixels = new byte[w * h * 4];
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(new byte[] { 50, 100, 200, 255 }, pixels.AsSpan(0, 4).ToArray());
Assert.Equal(new byte[] { 30, 20, 10, 255 }, pixels.AsSpan(4, 4).ToArray());
}
[Fact]
public void RegionRoundTrip_PreservesOpaquePixels()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[]
{
10, 20, 30, 255, 40, 50, 60, 255,
70, 80, 90, 255, 100, 110, 120, 255,
};
var original = (byte[])pixels.Clone();
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(original, pixels);
}
[Fact]
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[]
{
10, 20, 30, 255, 40, 50, 60, 255,
70, 80, 90, 255, 100, 110, 120, 255,
};
var original = (byte[])pixels.Clone();
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(original, pixels);
}
[Fact]
public void Convolve_BoxBlur_AveragesHorizontalStep()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 1;
var pixels = new byte[] { 0, 0, 0, 255, 255, 255, 255, 255 };
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out _, out _, out _, out _, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.Equal(85, pixels[0]);
Assert.Equal(85, pixels[1]);
Assert.Equal(85, pixels[2]);
Assert.Equal(255, pixels[3]);
Assert.Equal(170, pixels[6]);
Assert.Equal(255, pixels[7]);
}
[Fact]
public void Resize_Nearest_ReplicatesBlocks()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
const int w = 2, h = 2;
var pixels = new byte[]
{
13, 12, 13, 255, 23, 22, 23, 255,
33, 32, 33, 255, 43, 42, 43, 255,
};
var fields = Fields(w, h, 0d);
bool ok = RunWorker(
"obj.resize(4, 4, 'nearest')",
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out bool dirty, out bool bufferReplaced, out byte[]? result, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(dirty);
Assert.True(bufferReplaced);
Assert.Equal(4, rw);
Assert.Equal(4, rh);
Assert.NotNull(result);
byte SampleR(int x, int y) => result![(y * 4 + x) * 4 + 2];
Assert.Equal(13, SampleR(0, 0));
Assert.Equal(13, SampleR(1, 1));
Assert.Equal(23, SampleR(2, 0));
Assert.Equal(33, SampleR(0, 2));
Assert.Equal(43, SampleR(3, 3));
}
[Fact]
public void Resize_UpdatesObjDimensions()
{
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
var pixels = new byte[4 * 4 * 4];
var fields = Fields(4, 4, 0d);
bool ok = RunWorker(
"obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal",
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
out _, out bool bufferReplaced, out _, out int rw, out int rh, out string? error);
Assert.True(ok, error);
Assert.True(bufferReplaced);
Assert.Equal(8, rw);
Assert.Equal(2, rh);
Assert.Equal(8d, fields[NativeProtocol.X]);
Assert.Equal(2d, fields[NativeProtocol.Y]);
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), fields[NativeProtocol.Z]);
}
private sealed class RecordingPixelProcessor : IPixelBufferProcessor
{
public bool FillResult { get; init; }
public bool ConvolveResult { get; init; }
public bool ResizeResult { get; init; }
public int FillCalls { get; private set; }
public int ConvolveCalls { get; private set; }
public int ResizeCalls { get; private set; }
public int Size { get; private set; }
public double Divisor { get; private set; }
public double Offset { get; private set; }
public double[] Kernel { get; private set; } = [];
public int TargetWidth { get; private set; }
public int TargetHeight { get; private set; }
public bool Linear { get; private set; }
public bool LastFillForce { get; private set; }
public bool LastConvolveForce { get; private set; }
public bool LastResizeForce { get; private set; }
public bool TryFill(byte[] target, int width, int height, double r, double g, double b, double a, int x, int y, int fillWidth, int fillHeight, bool force = false)
{
FillCalls++;
LastFillForce = force;
if (!FillResult)
return false;
Array.Fill(target, (byte)0x41, 0, width * height * 4);
return true;
}
public bool TryConvolve(byte[] target, int width, int height, double[] kernel, int size, double divisor, double offset, bool force = false)
{
ConvolveCalls++;
Size = size;
Divisor = divisor;
Offset = offset;
Kernel = kernel.AsSpan(0, size * size).ToArray();
LastConvolveForce = force;
if (!ConvolveResult)
return false;
Array.Fill(target, (byte)0x42, 0, width * height * 4);
return true;
}
public bool TryResize(byte[] source, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight, bool linear, out byte[]? target, bool force = false)
{
ResizeCalls++;
TargetWidth = targetWidth;
TargetHeight = targetHeight;
Linear = linear;
LastResizeForce = force;
target = null;
if (!ResizeResult)
return false;
target = new byte[targetWidth * targetHeight * 4];
Array.Fill(target, (byte)0x43);
return true;
}
}
} }
} }
+3
ファイルの表示
@@ -16,6 +16,9 @@
<Project Path="LuaScript.Runtime/LuaScript.Runtime.csproj"> <Project Path="LuaScript.Runtime/LuaScript.Runtime.csproj">
<Platform Solution="*|x64" Project="Any CPU" /> <Platform Solution="*|x64" Project="Any CPU" />
</Project> </Project>
<Project Path="LuaScript.Gpu/LuaScript.Gpu.csproj">
<Platform Solution="*|x64" Project="Any CPU" />
</Project>
<Project Path="LuaScript.Tests/LuaScript.Tests.csproj" /> <Project Path="LuaScript.Tests/LuaScript.Tests.csproj" />
<Project Path="LuaScript/LuaScript.csproj"> <Project Path="LuaScript/LuaScript.csproj">
<Platform Solution="*|x64" Project="x64" /> <Platform Solution="*|x64" Project="x64" />
+33 -3
ファイルの表示
@@ -7,6 +7,7 @@ using LuaScript.Compat;
using LuaScript.Diagnostics; using LuaScript.Diagnostics;
using LuaScript.Engine; using LuaScript.Engine;
using LuaScript.Engine.Kernel; using LuaScript.Engine.Kernel;
using LuaScript.Engine.Processing;
using LuaScript.Engine.Shader; using LuaScript.Engine.Shader;
using Vortice; using Vortice;
using Vortice.DCommon; using Vortice.DCommon;
@@ -158,6 +159,7 @@ namespace LuaScript
private string _runnableScript = string.Empty; private string _runnableScript = string.Empty;
private int[] _runnableLineMap = []; private int[] _runnableLineMap = [];
private int[] _runnableChangedLines = []; private int[] _runnableChangedLines = [];
private LuaScriptDiagnostic[] _runnableRewriteDiagnostics = [];
private bool _runnableCached; private bool _runnableCached;
private ID2D1Image? _cachedInput; private ID2D1Image? _cachedInput;
private RenderKey _cachedKey; private RenderKey _cachedKey;
@@ -167,6 +169,7 @@ namespace LuaScript
private ID2D1Image? _cachedEffectOutput; private ID2D1Image? _cachedEffectOutput;
private PixelShaderRunner? _pixelShaderRunner; private PixelShaderRunner? _pixelShaderRunner;
private GpuPixelBufferProcessor? _pixelProcessor;
private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty; private AviUtlPixelShaderLibrary _pixelShaderLibrary = AviUtlPixelShaderLibrary.Empty;
private string? _pixelShaderSourceRef; private string? _pixelShaderSourceRef;
@@ -187,9 +190,11 @@ namespace LuaScript
new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore), new SynchronizedCompositor(new HardwareCompositor(_ownCtx), _pixelLoaderSemaphore),
SoftwareCompositor.Instance, SoftwareCompositor.Instance,
WarnBufferCompositorDegraded); WarnBufferCompositorDegraded);
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor }; _pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor, Logger = WriteGpuLog };
_pixelProcessor = new GpuPixelBufferProcessor(_pixelShaderRunner);
_context.ResolverProvider = GetFrameResolver; _context.ResolverProvider = GetFrameResolver;
_context.Compositor = _bufferCompositor; _context.Compositor = _bufferCompositor;
_context.PixelProcessor = _pixelProcessor;
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage; _context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage; _context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
_context.AudioLoader = _loadAudio ??= LoadAudio; _context.AudioLoader = _loadAudio ??= LoadAudio;
@@ -199,11 +204,21 @@ namespace LuaScript
private static void WarnBufferCompositorDegraded(Exception ex) => private static void WarnBufferCompositorDegraded(Exception ex) =>
Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex); Log.Default.Write("LuaScript: hardware buffer compositing failed; falling back to the software compositor.", ex);
private static void WriteGpuLog(string message, Exception? exception)
{
if (exception is null)
Log.Default.Write(message);
else
Log.Default.Write(message, exception);
}
private AviUtlScriptContext CreateScriptContext() private AviUtlScriptContext CreateScriptContext()
{ {
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver }; var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
if (_bufferCompositor is not null) if (_bufferCompositor is not null)
context.Compositor = _bufferCompositor; context.Compositor = _bufferCompositor;
if (_pixelProcessor is not null)
context.PixelProcessor = _pixelProcessor;
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage; context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage; context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
context.AudioLoader = _loadAudio ??= LoadAudio; context.AudioLoader = _loadAudio ??= LoadAudio;
@@ -236,15 +251,27 @@ namespace LuaScript
if (_runnableCached && ReferenceEquals(source, _sourceScript)) if (_runnableCached && ReferenceEquals(source, _sourceScript))
return _runnableScript; return _runnableScript;
var (code, lineMap, changedLines) = AviUtlScript.TransformWithMap(source); var (code, lineMap, changedLines, rewriteDiagnostics) = AviUtlScript.TransformWithMap(source);
_runnableScript = code; _runnableScript = code;
_runnableLineMap = lineMap; _runnableLineMap = lineMap;
_runnableChangedLines = changedLines; _runnableChangedLines = changedLines;
_sourceScript = source; _sourceScript = source;
_runnableCached = true; _runnableCached = true;
_runnableRewriteDiagnostics = BuildRewriteDiagnostics(rewriteDiagnostics);
return _runnableScript; return _runnableScript;
} }
private LuaScriptDiagnostic[] BuildRewriteDiagnostics(LuaScript.Compat.Syntax.LuaRewriteDiagnostic[] source)
{
if (source.Length == 0)
return [];
var diagnostics = new LuaScriptDiagnostic[source.Length];
for (int i = 0; i < source.Length; i++)
diagnostics[i] = new LuaScriptDiagnostic(LuaScriptDiagnosticKind.Compile, MapRunnableLine(source[i].Line), 0, 0, source[i].Message);
return diagnostics;
}
private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source) private AviUtlPixelShaderLibrary GetPixelShaderLibrary(string source)
{ {
if (!ReferenceEquals(_pixelShaderSourceRef, source)) if (!ReferenceEquals(_pixelShaderSourceRef, source))
@@ -480,7 +507,9 @@ namespace LuaScript
_pixelLoaderSemaphore.Release(); _pixelLoaderSemaphore.Release();
} }
LuaScriptDiagnostics.Instance.Report(script, diagnostics); LuaScriptDiagnostics.Instance.Report(script, _runnableRewriteDiagnostics.Length == 0
? diagnostics
: [.. _runnableRewriteDiagnostics, .. diagnostics]);
_isFirst = false; _isFirst = false;
if (_sceneImageLoaded) if (_sceneImageLoaded)
@@ -1065,6 +1094,7 @@ namespace LuaScript
_nativeSceneSet, _nativeSceneSet,
_loadAudio, _loadAudio,
_nativeRunPixelShader, _nativeRunPixelShader,
_pixelProcessor,
out bool dirty, out bool bufferReplaced, out bool dirty, out bool bufferReplaced,
out int resultW, out int resultH, out string? error); out int resultW, out int resultH, out string? error);
+3 -2
ファイルの表示
@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
<UseWPF>true</UseWPF> <UseWPF>true</UseWPF>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Version>1.18.0</Version> <Version>1.20.3</Version>
<Platforms>AnyCPU;x64</Platforms> <Platforms>AnyCPU;x64</Platforms>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -97,6 +97,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" /> <ProjectReference Include="..\LuaScript.Kernel\LuaScript.Kernel.csproj" />
<ProjectReference Include="..\LuaScript.Compat\LuaScript.Compat.csproj" /> <ProjectReference Include="..\LuaScript.Compat\LuaScript.Compat.csproj" />
<ProjectReference Include="..\LuaScript.Gpu\LuaScript.Gpu.csproj" />
<ProjectReference Include="..\LuaScript.Media\LuaScript.Media.csproj" /> <ProjectReference Include="..\LuaScript.Media\LuaScript.Media.csproj" />
<ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" /> <ProjectReference Include="..\LuaScript.Runtime\LuaScript.Runtime.csproj" />
</ItemGroup> </ItemGroup>
+61
ファイルの表示
@@ -612,6 +612,52 @@
* يتخطى الاستدعاء في البيئات التي لا تتوفر فيها وحدة معالجة * يتخطى الاستدعاء في البيئات التي لا تتوفر فيها وحدة معالجة
رسومات صالحة. رسومات صالحة.
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (امتداد خاص بـ YMM4)
يملأ صورة الكائن بلون محدد. يعطى اللون بصيغة RGBA مباشرة من 0 إلى
255 (نفس نموذج الألوان في obj.setpixel).
r, g, b : مكونات اللون (0-255).
a : الشفافية (0-255). القيمة الافتراضية 255.
x, y, w, h: المستطيل المراد ملؤه. الافتراضي كامل الصورة، ويقص ما خرج
عن النطاق.
مثال: obj.fill(0, 0, 0, 0) -- مسح الكل إلى شفاف
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
يعمل على المحركين معا.
○ obj.getpixelregion(x, y, w, h) (امتداد خاص بـ YMM4)
يقرأ منطقة مستطيلة من البكسلات إلى مصفوفة RGBA مباشرة. الترتيب هو
r, g, b, a لكل بكسل ويبدأ من 1 (الفهرس (صف*w+عمود)*4+1..+4). البكسلات
خارج الصورة تكون 0,0,0,0.
القيمة المعادة: مصفوفة بطول w*h*4.
مثال: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
○ obj.putpixelregion(x, y, w, h, البيانات) (امتداد خاص بـ YMM4)
يكتب مصفوفة بنفس ترتيب obj.getpixelregion إلى منطقة مستطيلة. البكسلات
خارج حدود الصورة لا تكتب.
البيانات : مصفوفة RGBA مباشرة بطول w*h*4 (تبدأ من 1).
مثال: obj.putpixelregion(0, 0, obj.w, obj.h, t)
○ obj.convolve(النواة, الحجم [, المقسوم_عليه [, الإزاحة]]) (امتداد خاص بـ YMM4)
يطبق التفاف بحجم الحجم×الحجم على صورة الكائن. مفيد للتمويه والتوضيح
واكتشاف الحواف وغيرها.
النواة : عدد الحجم*الحجم من المعاملات (حسب الصفوف، تبدأ من 1).
الحجم : عدد فردي (3، 5، 7 …). الزوجي أو الأقل من 1 يتجاهل.
المقسوم_عليه : يقسم مجموع كل بكسل على هذه القيمة. الافتراضي مجموع
النواة (1 عندما يكون المجموع 0).
الإزاحة : تضاف إلى كل مكون بعد القسمة. الافتراضي 0.
تمدد بكسلات الحواف بأقرب بكسل. يطبق على r, g, b, a جميعا.
مثال: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- تمويه متوسط
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- توضيح
يعمل على المحركين معا.
○ obj.resize(العرض, الارتفاع [, الترشيح]) (امتداد خاص بـ YMM4)
يغير حجم صورة الكائن إلى الحجم المحدد. تحدّث أيضا obj.w / obj.h وبقية
الأبعاد.
العرض, الارتفاع : أعداد صحيحة >= 1.
الترشيح : "nearest" لأقرب جار، أو خطي عند الحذف.
مثال: obj.resize(obj.w * 2, obj.h * 2)
يعمل على المحركين معا. يترك التشغيل السريع الصورة دون تغيير عندما
تتجاوز النتيجة أقصى حجم للصورة.
○ obj.getvalue(الهدف) ○ obj.getvalue(الهدف)
يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0). يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0).
الهدف : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", الهدف : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -928,6 +974,21 @@
x in <1..5> يفحص 1 <= x and x <= 5. x in <1..5> يفحص 1 <= x and x <= 5.
<1..<5> لا يشمل الحد الأعلى. يُقيَّم الطرف الأيسر مرة واحدة. <1..<5> لا يشمل الحد الأعلى. يُقيَّم الطرف الأيسر مرة واحدة.
○ [fast] (علامة التسريع) * امتداد خاص بـ YMM4
تُفوَّض obj.fill / obj.convolve / obj.resize إلى وحدة معالجة الرسوميات
تلقائيًا عندما يتجاوز حجم المعالجة حدًا معينًا ويتم التحقق من تطابق نتيجة
وحدة معالجة الرسوميات مع نتيجة المعالج. تتجاهل [fast] هذا الحد وتفرض
التفويض إلى وحدة معالجة الرسوميات. عند عدم توفر وحدة معالجة الرسوميات
أو عدم تطابق نتيجتها مع المعالج، ترجع [fast] تلقائيًا إلى المعالج. يمكن
وضع العلامة في سطر مستقل أو في السطر نفسه.
مثال: [fast]
obj.convolve(kernel, 5)
* يظهر خطأ عندما يسبق [fast] أي شيء غير هذه الدوال الثلاث.
* يعمل في محرك MoonSharp والمحرك الأصلي على حد سواء.
* عند أحمال المعالجة الصغيرة، قد تتجاوز تكلفة الذهاب والإياب
الخاصة بتفويض وحدة معالجة الرسوميات تكلفة التنفيذ على المعالج،
فقد تجعل [fast] الأداء أبطأ بدلاً من أسرع.
- أمثلة على النصوص البرمجية - - أمثلة على النصوص البرمجية -
+63
ファイルの表示
@@ -634,6 +634,53 @@
onto a transparent scene-sized area. onto a transparent scene-sized area.
* The call is skipped in environments without a usable GPU. * The call is skipped in environments without a usable GPU.
o obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 extension)
Fills the object image with a color, given as straight RGBA in
0-255 (same color model as obj.setpixel).
r, g, b : Color components (0-255).
a : Opacity (0-255). Default is 255.
x, y, w, h: Rectangle to fill. Defaults to the whole image; out of
range is clipped.
Example: obj.fill(0, 0, 0, 0) -- clear to transparent
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
Runs on both engines.
o obj.getpixelregion(x, y, w, h) (YMM4 extension)
Reads a rectangular region of pixels into a straight RGBA array.
The layout is r, g, b, a per pixel and is 1-based (index
(row*w+col)*4+1..+4). Pixels outside the image are 0,0,0,0.
Returns: an array of length w*h*4.
Example: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
o obj.putpixelregion(x, y, w, h, data) (YMM4 extension)
Writes an array in the same layout as obj.getpixelregion back into a
rectangular region. Pixels outside the image are not written.
data : straight RGBA array of length w*h*4 (1-based).
Example: obj.putpixelregion(0, 0, obj.w, obj.h, t)
o obj.convolve(kernel, size [, divisor [, offset]]) (YMM4 extension)
Applies a size x size convolution to the object image. Useful for
blur, sharpen, edge detection and so on.
kernel : size*size coefficients, row-major and 1-based.
size : odd number (3, 5, 7 ...). Even or below 1 is ignored.
divisor : divides each pixel sum. Defaults to the kernel sum (1 when
the sum is 0).
offset : added to each component after the division. Default is 0.
Edge pixels are extended by the nearest pixel. Applies to r, g, b, a.
Example: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- box blur
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- sharpen
Runs on both engines.
o obj.resize(width, height [, filter]) (YMM4 extension)
Scales the object image to the given size. obj.w / obj.h and the
other dimensions are updated too.
width, height : integers >= 1.
filter : "nearest" for nearest-neighbor, or linear when
omitted.
Example: obj.resize(obj.w * 2, obj.h * 2)
Runs on both engines. The fast runtime leaves the image unchanged
when the result exceeds the maximum image size.
o obj.getvalue(target) o obj.getvalue(target)
Gets the current value of obj (same as obj.x, obj.track0, etc.). Gets the current value of obj (same as obj.x, obj.track0, etc.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -966,6 +1013,22 @@
x in <1..5> tests 1 <= x and x <= 5. x in <1..5> tests 1 <= x and x <= 5.
<1..<5> excludes the upper bound. The left side is evaluated once. <1..<5> excludes the upper bound. The left side is evaluated once.
o [fast] (acceleration marker) * YMM4 extension
obj.fill / obj.convolve / obj.resize are delegated to the GPU
automatically when the workload exceeds a threshold and the GPU
result is verified to match the CPU. [fast] ignores that
workload threshold and forces GPU delegation. When no GPU is
available or the GPU result does not match the CPU, [fast]
still falls back to the CPU automatically. The marker may be
on its own line or on the same line.
Example: [fast]
obj.convolve(kernel, 5)
* An error is shown when [fast] precedes anything other than those three functions.
* Works in both the MoonSharp and native engines.
* For small workloads, the round-trip cost of delegating to the GPU
can exceed plain CPU execution, so [fast] may make things slower
rather than faster.
- Script Examples - - Script Examples -
+64
ファイルの表示
@@ -641,6 +641,54 @@
sobre un area transparente del tamano de la escena. sobre un area transparente del tamano de la escena.
* La llamada se omite en entornos sin una GPU utilizable. * La llamada se omite en entornos sin una GPU utilizable.
o obj.fill(r, g, b [, a [, x, y, w, h]]) (extension de YMM4)
Rellena la imagen del objeto con un color, dado como RGBA directo en
0-255 (mismo modelo de color que obj.setpixel).
r, g, b : Componentes de color (0-255).
a : Opacidad (0-255). Por defecto 255.
x, y, w, h: Rectangulo a rellenar. Por defecto toda la imagen; lo que
queda fuera de rango se recorta.
Ejemplo: obj.fill(0, 0, 0, 0) -- borrar a transparente
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
Funciona en ambos motores.
o obj.getpixelregion(x, y, w, h) (extension de YMM4)
Lee una region rectangular de pixeles en un arreglo RGBA directo. La
disposicion es r, g, b, a por pixel y empieza en 1 (indice
(fila*w+col)*4+1..+4). Los pixeles fuera de la imagen son 0,0,0,0.
Devuelve: un arreglo de longitud w*h*4.
Ejemplo: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
o obj.putpixelregion(x, y, w, h, datos) (extension de YMM4)
Escribe un arreglo con la misma disposicion que obj.getpixelregion en
una region rectangular. Los pixeles fuera de la imagen no se escriben.
datos : arreglo RGBA directo de longitud w*h*4 (empieza en 1).
Ejemplo: obj.putpixelregion(0, 0, obj.w, obj.h, t)
o obj.convolve(kernel, tamano [, divisor [, desplazamiento]]) (extension de YMM4)
Aplica una convolucion de tamano x tamano a la imagen del objeto.
Util para desenfoque, enfoque, deteccion de bordes, etc.
kernel : tamano*tamano coeficientes, por filas y empieza en 1.
tamano : numero impar (3, 5, 7 ...). Par o menor que 1 se ignora.
divisor : divide la suma de cada pixel. Por defecto la suma del
kernel (1 cuando la suma es 0).
desplazamiento: se suma a cada componente tras la division. Por
defecto 0.
Los pixeles de borde se extienden con el pixel mas cercano. Se aplica
a r, g, b, a.
Ejemplo: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- desenfoque
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- enfoque
Funciona en ambos motores.
o obj.resize(ancho, alto [, filtro]) (extension de YMM4)
Escala la imagen del objeto al tamano indicado. obj.w / obj.h y las
demas dimensiones tambien se actualizan.
ancho, alto : enteros >= 1.
filtro : "nearest" para vecino mas cercano, o lineal si se omite.
Ejemplo: obj.resize(obj.w * 2, obj.h * 2)
Funciona en ambos motores. El runtime rapido deja la imagen sin
cambios cuando el resultado supera el tamano maximo de imagen.
o obj.getvalue(target) o obj.getvalue(target)
Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.). Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -986,6 +1034,22 @@
x in <1..5> comprueba 1 <= x and x <= 5. x in <1..5> comprueba 1 <= x and x <= 5.
<1..<5> excluye el límite superior. El lado izquierdo se evalúa una sola vez. <1..<5> excluye el límite superior. El lado izquierdo se evalúa una sola vez.
o [fast] (marcador de aceleración) * extensión de YMM4
obj.fill / obj.convolve / obj.resize se delegan automáticamente a la
GPU cuando la carga supera un umbral y el resultado de la GPU se
verifica como idéntico al de la CPU. [fast] ignora ese umbral de
carga y fuerza la delegación a la GPU. Cuando no hay GPU disponible
o el resultado de la GPU no coincide con el de la CPU, [fast]
sigue recayendo automáticamente en la CPU. El marcador puede ir
en su propia línea o en la misma.
Ejemplo: [fast]
obj.convolve(kernel, 5)
* Se muestra un error cuando [fast] precede a algo distinto de esas tres funciones.
* Funciona tanto en el motor MoonSharp como en el nativo.
* En cargas pequeñas, el costo de ida y vuelta de delegar a la GPU
puede superar al de ejecutar en CPU, por lo que [fast] puede
hacer las cosas más lentas en vez de más rápidas.
- Ejemplos de script - - Ejemplos de script -
+63
ファイルの表示
@@ -637,6 +637,53 @@
area transparan seukuran adegan. area transparan seukuran adegan.
* Panggilan dilewati pada lingkungan tanpa GPU yang dapat digunakan. * Panggilan dilewati pada lingkungan tanpa GPU yang dapat digunakan.
o obj.fill(r, g, b [, a [, x, y, w, h]]) (ekstensi YMM4)
Mengisi gambar objek dengan warna, diberikan sebagai RGBA lurus dalam
0-255 (model warna sama dengan obj.setpixel).
r, g, b : Komponen warna (0-255).
a : Opasitas (0-255). Default 255.
x, y, w, h: Persegi panjang yang diisi. Default seluruh gambar; di
luar jangkauan dipangkas.
Contoh: obj.fill(0, 0, 0, 0) -- bersihkan jadi transparan
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
Berjalan di kedua mesin.
o obj.getpixelregion(x, y, w, h) (ekstensi YMM4)
Membaca wilayah piksel persegi panjang ke dalam larik RGBA lurus.
Susunannya r, g, b, a per piksel dan berbasis 1 (indeks
(baris*w+kolom)*4+1..+4). Piksel di luar gambar bernilai 0,0,0,0.
Mengembalikan: larik sepanjang w*h*4.
Contoh: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
o obj.putpixelregion(x, y, w, h, data) (ekstensi YMM4)
Menulis larik dengan susunan sama seperti obj.getpixelregion kembali
ke wilayah persegi panjang. Piksel di luar gambar tidak ditulis.
data : larik RGBA lurus sepanjang w*h*4 (berbasis 1).
Contoh: obj.putpixelregion(0, 0, obj.w, obj.h, t)
o obj.convolve(kernel, ukuran [, pembagi [, offset]]) (ekstensi YMM4)
Menerapkan konvolusi ukuran x ukuran ke gambar objek. Berguna untuk
blur, penajaman, deteksi tepi, dan sebagainya.
kernel : ukuran*ukuran koefisien, urut baris dan berbasis 1.
ukuran : bilangan ganjil (3, 5, 7 ...). Genap atau di bawah 1 diabaikan.
pembagi : membagi jumlah tiap piksel. Default jumlah kernel (1 bila
jumlahnya 0).
offset : ditambahkan ke tiap komponen setelah pembagian. Default 0.
Piksel tepi diperluas dengan piksel terdekat. Berlaku untuk r, g, b, a.
Contoh: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- blur rata-rata
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- penajaman
Berjalan di kedua mesin.
o obj.resize(lebar, tinggi [, filter]) (ekstensi YMM4)
Menskala gambar objek ke ukuran yang diberikan. obj.w / obj.h dan
dimensi lainnya ikut diperbarui.
lebar, tinggi : bilangan bulat >= 1.
filter : "nearest" untuk tetangga terdekat, atau linear bila
dihilangkan.
Contoh: obj.resize(obj.w * 2, obj.h * 2)
Berjalan di kedua mesin. Runtime cepat membiarkan gambar tanpa
perubahan bila hasilnya melebihi ukuran gambar maksimum.
o obj.getvalue(target) o obj.getvalue(target)
Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.). Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.).
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -977,6 +1024,22 @@
x in <1..5> menguji 1 <= x and x <= 5. x in <1..5> menguji 1 <= x and x <= 5.
<1..<5> tidak menyertakan batas atas. Sisi kiri dievaluasi sekali. <1..<5> tidak menyertakan batas atas. Sisi kiri dievaluasi sekali.
o [fast] (penanda akselerasi) * ekstensi YMM4
obj.fill / obj.convolve / obj.resize didelegasikan ke GPU secara
otomatis ketika beban kerja melebihi ambang batas dan hasil GPU
terverifikasi sama dengan CPU. [fast] mengabaikan ambang batas
beban kerja tersebut dan memaksa delegasi ke GPU. Saat GPU tidak
tersedia atau hasil GPU tidak sama dengan CPU, [fast] tetap
otomatis kembali ke CPU. Penanda boleh di baris tersendiri atau
di baris yang sama.
Contoh: [fast]
obj.convolve(kernel, 5)
* Kesalahan ditampilkan jika [fast] mendahului selain ketiga fungsi tersebut.
* Berfungsi pada mesin MoonSharp maupun native.
* Untuk beban kerja kecil, biaya bolak-balik pendelegasian ke GPU
bisa melebihi eksekusi CPU biasa, sehingga [fast] justru bisa
membuat lebih lambat, bukan lebih cepat.
- Contoh Skrip - - Contoh Skrip -
+64 -2
ファイルの表示
@@ -616,6 +616,51 @@
シーンサイズ領域へオブジェクトを合成した仮想の画像です。 シーンサイズ領域へオブジェクトを合成した仮想の画像です。
※ GPUが使用できない環境では呼び出しはスキップされます。 ※ GPUが使用できない環境では呼び出しはスキップされます。
○obj.fill(r, g, b [, a [, x, y, w, h]]) ※YMM4独自拡張
オブジェクト画像を指定色で塗りつぶします。色は 0~255 のストレート
RGBA で指定します(obj.setpixel と同じ表色)。
r, g, b : 色成分(0~255)。
a : 不透明度(0~255)。省略時は 255。
x, y, w, h : 塗りつぶす矩形。省略時は画像全体。範囲外は切り詰めます。
例:obj.fill(0, 0, 0, 0) -- 全体を透明で消去
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
両エンジンで動きます。
○obj.getpixelregion(x, y, w, h) ※YMM4独自拡張
矩形領域の画素をストレート RGBA の配列で取得します。並びは画素ごと
に r, g, b, a の順で 1 始まりです(索引 (行*w+列)*4+1~+4)。範囲外の
画素は 0,0,0,0 になります。
戻り値 : 長さ w*h*4 の配列。
例:local t = obj.getpixelregion(0, 0, obj.w, obj.h)
○obj.putpixelregion(x, y, w, h, データ) ※YMM4独自拡張
obj.getpixelregion と同じ並びの配列を矩形領域へ書き戻します。画像の
範囲外へはみ出した画素は書き込みません。
データ : 長さ w*h*4 のストレート RGBA 配列(1 始まり)。
例:obj.putpixelregion(0, 0, obj.w, obj.h, t)
○obj.convolve(カーネル, サイズ [, 除数 [, オフセット]]) ※YMM4独自拡張
オブジェクト画像へ サイズ×サイズ の畳み込みを適用します。ぼかし、
シャープ、輪郭抽出などに使えます。
カーネル : サイズ*サイズ 個の係数配列(行優先, 1 始まり)。
サイズ : 奇数(3, 5, 7 …)。偶数や 1 未満は無視します。
除数 : 各画素の合計をこの値で割ります。省略時はカーネルの
合計(合計が 0 のときは 1)。
オフセット : 除算後に各成分へ加算します。省略時は 0。
端の画素は最も近い画素で補います。r, g, b, a すべてに適用します。
例:obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 平均ぼかし
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- シャープ
両エンジンで動きます。
○obj.resize(幅, 高さ [, 補間]) ※YMM4独自拡張
オブジェクト画像を指定サイズへ拡大縮小します。obj.w / obj.h などの
寸法も更新されます。
幅, 高さ : 1 以上の整数。
補間 : "nearest"(最近傍)または省略で線形補間。
例:obj.resize(obj.w * 2, obj.h * 2)
両エンジンで動きます。高速ランタイムでは結果が最大画像サイズを
超える場合は変更しません。
○obj.getvalue(対象) ○obj.getvalue(対象)
obj の現在値を取得します(obj.x や obj.track0 等と同値)。 obj の現在値を取得します(obj.x や obj.track0 等と同値)。
対象 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", 対象 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -936,6 +981,21 @@
x in <1..5> は 1 <= x and x <= 5 を判定します。 x in <1..5> は 1 <= x and x <= 5 を判定します。
<1..<5> は上限を含みません。左辺は 1 度だけ評価します。 <1..<5> は上限を含みません。左辺は 1 度だけ評価します。
○[fast](高速化マーカー) ※YMM4独自拡張
obj.fill / obj.convolve / obj.resize は、処理量がしきい値以上で
GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲
します。[fast] を付けると、この処理量のしきい値を無視して強制的
に GPU へ委譲します。GPU が使えない環境や GPU の結果が CPU と
一致しない環境では、[fast] を付けても CPU へ自動的に戻ります。
マーカーは単独の行に置いても、同じ行に続けて書いても構いません。
例:[fast]
obj.convolve(kernel, 5)
※ [fast] を付けた対象が上記 3 関数以外のときはエラーを表示します。
※ 従来エンジンと高速ランタイムの両方で動作します。
※ 処理量が小さいときは、GPU への委譲自体の往復コストが CPU 実行
を上回ることがあり、[fast] を付けるとかえって遅くなる場合が
あります。
- スクリプト例 - - スクリプト例 -
@@ -1016,8 +1076,10 @@
○描画・合成・読み込み ○描画・合成・読み込み
obj.draw / obj.drawpoly による描画合成、obj.copybuffer による obj.draw / obj.drawpoly による描画合成、obj.copybuffer による
バッファ操作、obj.load("figure"/"text"/"image"/"movie") による生成・ バッファ操作、obj.fill / obj.getpixelregion / obj.putpixelregion /
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.getaudio、obj.getinfo、obj.setoption / obj.convolve / obj.resize による画像加工、obj.load("figure"/"text"/
"image"/"movie") による生成・読み込み、obj.setfont、obj.effect、
obj.getvalue、obj.getaudio、obj.getinfo、obj.setoption /
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル - obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
関数」を参照してください。 関数」を参照してください。
+61
ファイルの表示
@@ -605,6 +605,53 @@
장면 크기의 투명한 영역에 오브젝트를 합성한 가상 이미지입니다. 장면 크기의 투명한 영역에 오브젝트를 합성한 가상 이미지입니다.
※ GPU를 사용할 수 없는 환경에서는 호출이 건너뛰어집니다. ※ GPU를 사용할 수 없는 환경에서는 호출이 건너뛰어집니다.
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 전용 확장)
오브젝트 이미지를 지정한 색으로 채웁니다. 색은 0~255 의 스트레이트
RGBA 로 지정합니다(obj.setpixel 과 같은 표색).
r, g, b : 색 성분(0~255).
a : 불투명도(0~255). 생략 시 255.
x, y, w, h: 채울 사각형. 생략 시 이미지 전체이며 범위를 벗어나면
잘립니다.
예: obj.fill(0, 0, 0, 0) -- 전체를 투명으로 지움
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
두 엔진 모두에서 동작합니다.
○ obj.getpixelregion(x, y, w, h) (YMM4 전용 확장)
사각형 영역의 픽셀을 스트레이트 RGBA 배열로 가져옵니다. 배열은
픽셀마다 r, g, b, a 순이며 1 부터 시작합니다(색인 (행*w+열)*4+1~+4).
이미지 밖의 픽셀은 0,0,0,0 입니다.
반환값 : 길이 w*h*4 의 배열.
예: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
○ obj.putpixelregion(x, y, w, h, 데이터) (YMM4 전용 확장)
obj.getpixelregion 과 같은 배열을 사각형 영역에 다시 씁니다. 이미지
범위를 벗어난 픽셀은 쓰지 않습니다.
데이터 : 길이 w*h*4 의 스트레이트 RGBA 배열(1 부터 시작).
예: obj.putpixelregion(0, 0, obj.w, obj.h, t)
○ obj.convolve(커널, 크기 [, 제수 [, 오프셋]]) (YMM4 전용 확장)
오브젝트 이미지에 크기×크기 의 컨볼루션을 적용합니다. 흐림, 샤픈,
윤곽 검출 등에 사용할 수 있습니다.
커널 : 크기*크기 개의 계수 배열(행 우선, 1 부터 시작).
크기 : 홀수(3, 5, 7 …). 짝수나 1 미만은 무시합니다.
제수 : 각 픽셀의 합계를 이 값으로 나눕니다. 생략 시 커널의
합계(합계가 0 이면 1).
오프셋 : 나눗셈 후 각 성분에 더합니다. 생략 시 0.
가장자리 픽셀은 가장 가까운 픽셀로 채웁니다. r, g, b, a 모두에
적용됩니다.
예: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 평균 흐림
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 샤픈
두 엔진 모두에서 동작합니다.
○ obj.resize(너비, 높이 [, 보간]) (YMM4 전용 확장)
오브젝트 이미지를 지정한 크기로 확대/축소합니다. obj.w / obj.h 등의
치수도 갱신됩니다.
너비, 높이 : 1 이상의 정수.
보간 : "nearest"(최근접) 또는 생략 시 선형 보간.
예: obj.resize(obj.w * 2, obj.h * 2)
두 엔진 모두에서 동작합니다. 고속 런타임에서는 결과가 최대 이미지
크기를 넘으면 변경하지 않습니다.
○ obj.getvalue(대상) ○ obj.getvalue(대상)
obj의 현재 값을 가져옵니다(obj.x, obj.track0 등과 동일). obj의 현재 값을 가져옵니다(obj.x, obj.track0 등과 동일).
대상 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", 대상 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -923,6 +970,20 @@
x in <1..5>는 1 <= x and x <= 5를 판정합니다. x in <1..5>는 1 <= x and x <= 5를 판정합니다.
<1..<5>는 상한을 포함하지 않습니다. 왼쪽 값은 한 번만 평가합니다. <1..<5>는 상한을 포함하지 않습니다. 왼쪽 값은 한 번만 평가합니다.
○ [fast] (가속 마커) ※YMM4 고유 확장
obj.fill / obj.convolve / obj.resize는 처리량이 임계값 이상이고
GPU 결과가 CPU와 일치함이 확인되면 자동으로 GPU에 위임합니다.
[fast]를 붙이면 이 처리량 임계값을 무시하고 강제로 GPU에
위임합니다. GPU를 사용할 수 없거나 GPU 결과가 CPU와 일치하지
않는 환경에서는 [fast]를 붙여도 자동으로 CPU로 되돌아갑니다.
마커는 단독 행에 두어도, 같은 행에 이어 써도 됩니다.
예: [fast]
obj.convolve(kernel, 5)
※ [fast]를 붙인 대상이 위 3개 함수가 아니면 오류를 표시합니다.
※ 기존 엔진과 고속 런타임 양쪽에서 동작합니다.
※ 처리량이 작을 때는 GPU 위임 자체의 왕복 비용이 CPU 실행보다
커서, [fast]를 붙이면 오히려 느려질 수 있습니다.
- 스크립트 예 - - 스크립트 예 -
+55
ファイルの表示
@@ -586,6 +586,48 @@
场景大小透明区域后的虚拟图像。 场景大小透明区域后的虚拟图像。
※ 在无法使用GPU的环境中会跳过该调用。 ※ 在无法使用GPU的环境中会跳过该调用。
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 独有扩展)
以指定颜色填充对象图像。颜色以 0~255 的直通 RGBA 指定(与
obj.setpixel 相同的表色)。
r, g, b : 颜色分量(0~255)。
a : 不透明度(0~255)。省略时为 255。
x, y, w, h: 要填充的矩形。省略时为整幅图像,超出范围会被裁剪。
例: obj.fill(0, 0, 0, 0) -- 将整体清为透明
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
在两个引擎中均可使用。
○ obj.getpixelregion(x, y, w, h) (YMM4 独有扩展)
将矩形区域的像素读入直通 RGBA 数组。排列为每个像素 r, g, b, a,
从 1 开始(索引 (行*w+列)*4+1~+4)。图像外的像素为 0,0,0,0。
返回值: 长度为 w*h*4 的数组。
例: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
○ obj.putpixelregion(x, y, w, h, 数据) (YMM4 独有扩展)
将与 obj.getpixelregion 相同排列的数组写回矩形区域。超出图像范围的
像素不会被写入。
数据 : 长度为 w*h*4 的直通 RGBA 数组(从 1 开始)。
例: obj.putpixelregion(0, 0, obj.w, obj.h, t)
○ obj.convolve(卷积核, 大小 [, 除数 [, 偏移]]) (YMM4 独有扩展)
对对象图像应用 大小×大小 的卷积。可用于模糊、锐化、边缘检测等。
卷积核 : 大小*大小 个系数数组(行优先,从 1 开始)。
大小 : 奇数(3、5、7 …)。偶数或小于 1 会被忽略。
除数 : 每个像素的合计除以该值。省略时为卷积核的合计(合计为 0
时为 1)。
偏移 : 除法后加到各分量上。省略时为 0。
边缘像素以最近的像素补充。对 r, g, b, a 全部生效。
例: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 均值模糊
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 锐化
在两个引擎中均可使用。
○ obj.resize(宽, 高 [, 插值]) (YMM4 独有扩展)
将对象图像缩放到指定尺寸。obj.w / obj.h 等尺寸也会更新。
宽, 高 : 大于等于 1 的整数。
插值 : "nearest"(最近邻)或省略以进行线性插值。
例: obj.resize(obj.w * 2, obj.h * 2)
在两个引擎中均可使用。在快速运行时中,若结果超过最大图像尺寸
则不做更改。
○ obj.getvalue(目标) ○ obj.getvalue(目标)
获取 obj 的当前值(与 obj.x、obj.track0 等相同)。 获取 obj 的当前值(与 obj.x、obj.track0 等相同)。
目标 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", 目标 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -886,6 +928,19 @@
x in <1..5> 判断 1 <= x and x <= 5。 x in <1..5> 判断 1 <= x and x <= 5。
<1..<5> 不包含上限。左侧只求值一次。 <1..<5> 不包含上限。左侧只求值一次。
○ [fast](加速标记) ※YMM4专有扩展
当处理量达到阈值且 GPU 结果经验证与 CPU 一致时,obj.fill /
obj.convolve / obj.resize 会自动委托给 GPU。加上 [fast] 会
无视处理量阈值,强制委托给 GPU。若环境没有 GPU,或 GPU 结果
与 CPU 不一致,[fast] 仍会自动回退到 CPU。标记可以单独占一行,
也可以写在同一行。
例:[fast]
obj.convolve(kernel, 5)
※ 若 [fast] 修饰的目标不是上述 3 个函数,则显示错误。
※ 在传统引擎和高速运行时上均可运行。
※ 处理量较小时,委托给 GPU 本身的往返开销可能超过 CPU 执行,
加上 [fast] 反而可能更慢。
- 脚本示例 - - 脚本示例 -
+55
ファイルの表示
@@ -586,6 +586,48 @@
場景大小透明區域後的虛擬影像。 場景大小透明區域後的虛擬影像。
※ 在無法使用GPU的環境中會跳過該呼叫。 ※ 在無法使用GPU的環境中會跳過該呼叫。
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 獨有擴充)
以指定顏色填滿物件影像。顏色以 0~255 的直通 RGBA 指定(與
obj.setpixel 相同的表色)。
r, g, b : 顏色分量(0~255)。
a : 不透明度(0~255)。省略時為 255。
x, y, w, h: 要填滿的矩形。省略時為整幅影像,超出範圍會被裁切。
例: obj.fill(0, 0, 0, 0) -- 將整體清為透明
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
在兩個引擎中均可使用。
○ obj.getpixelregion(x, y, w, h) (YMM4 獨有擴充)
將矩形區域的像素讀入直通 RGBA 陣列。排列為每個像素 r, g, b, a,
從 1 開始(索引 (列*w+行)*4+1~+4)。影像外的像素為 0,0,0,0。
回傳值: 長度為 w*h*4 的陣列。
例: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
○ obj.putpixelregion(x, y, w, h, 資料) (YMM4 獨有擴充)
將與 obj.getpixelregion 相同排列的陣列寫回矩形區域。超出影像範圍的
像素不會被寫入。
資料 : 長度為 w*h*4 的直通 RGBA 陣列(從 1 開始)。
例: obj.putpixelregion(0, 0, obj.w, obj.h, t)
○ obj.convolve(卷積核, 大小 [, 除數 [, 偏移]]) (YMM4 獨有擴充)
對物件影像套用 大小×大小 的卷積。可用於模糊、銳化、邊緣偵測等。
卷積核 : 大小*大小 個係數陣列(列優先,從 1 開始)。
大小 : 奇數(3、5、7 …)。偶數或小於 1 會被忽略。
除數 : 每個像素的合計除以該值。省略時為卷積核的合計(合計為 0
時為 1)。
偏移 : 除法後加到各分量上。省略時為 0。
邊緣像素以最近的像素補足。對 r, g, b, a 全部生效。
例: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 平均模糊
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 銳化
在兩個引擎中均可使用。
○ obj.resize(寬, 高 [, 內插]) (YMM4 獨有擴充)
將物件影像縮放到指定尺寸。obj.w / obj.h 等尺寸也會更新。
寬, 高 : 大於等於 1 的整數。
內插 : "nearest"(最近鄰)或省略以進行線性內插。
例: obj.resize(obj.w * 2, obj.h * 2)
在兩個引擎中均可使用。在快速執行環境中,若結果超過最大影像尺寸
則不做變更。
○ obj.getvalue(目標) ○ obj.getvalue(目標)
取得 obj 的目前值(與 obj.x、obj.track0 等相同)。 取得 obj 的目前值(與 obj.x、obj.track0 等相同)。
目標 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect", 目標 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
@@ -887,6 +929,19 @@
x in <1..5> 判斷 1 <= x and x <= 5。 x in <1..5> 判斷 1 <= x and x <= 5。
<1..<5> 不包含上限。左側只求值一次。 <1..<5> 不包含上限。左側只求值一次。
○ [fast](加速標記) ※YMM4專有擴充
當處理量達到閾值且 GPU 結果經驗證與 CPU 一致時,obj.fill /
obj.convolve / obj.resize 會自動委派給 GPU。加上 [fast] 會
無視處理量閾值,強制委派給 GPU。若環境沒有 GPU,或 GPU 結果
與 CPU 不一致,[fast] 仍會自動回退到 CPU。標記可以單獨佔一行,
也可以寫在同一行。
例:[fast]
obj.convolve(kernel, 5)
※ 若 [fast] 修飾的目標不是上述 3 個函式,則顯示錯誤。
※ 在傳統引擎與高速執行環境上皆可運行。
※ 處理量較小時,委派給 GPU 本身的往返成本可能超過 CPU 執行,
加上 [fast] 反而可能更慢。
- 腳本範例 - - 腳本範例 -
+13 -3
ファイルの表示
@@ -11,7 +11,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。 座標・拡縮・回転・不透明度の制御に加えて、`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` によるピクセル単位の画像加工、アニメーション制作向けの数学ユーティリティ群(`anim` テーブル)、4 系統のトラックバー(Track0〜Track3)によるスクリプトへのパラメータ受け渡しに対応しています。
![Image](https://github.com/routersys/YMM4-LuaScript/blob/main/docs/LuaScript.png) ![Image](https://git.routersys.com/routersys/YMM4-LuaScript/raw/branch/main/docs/LuaScript.png)
--- ---
@@ -93,7 +93,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
| `obj.ox`, `obj.oy` | 変更可 | 中心点オフセット。描画の中心位置(CenterPoint.X/Y)に反映される | | `obj.ox`, `obj.oy` | 変更可 | 中心点オフセット。描画の中心位置(CenterPoint.X/Y)に反映される |
| `obj.oz` | 変更可(出力には未使用) | 値はスクリプト実行後に読み戻されるが、現状の出力計算では使用されない | | `obj.oz` | 変更可(出力には未使用) | 値はスクリプト実行後に読み戻されるが、現状の出力計算では使用されない |
| `obj.sx`, `obj.sy` | 変更可 | X/Y 方向の独立した拡大率。`obj.zoom` / `obj.aspect` の変更より優先される | | `obj.sx`, `obj.sy` | 変更可 | X/Y 方向の独立した拡大率。`obj.zoom` / `obj.aspect` の変更より優先される |
| `obj.zoom`, `obj.aspect` | 変更可 | `obj.sx` / `obj.sy` が同時に変更されていない場合のみ、`zoom × (1 ± aspect)` として sx/sy に反映される | | `obj.zoom`, `obj.aspect` | 変更可 | `obj.sx` / `obj.sy` が同時に変更されていない場合のみ、$\mathrm{zoom} \times (1 \pm \mathrm{aspect})$ として sx/sy に反映される |
| `obj.alpha` | 変更可 | 不透明度(0.0〜255.0)。出力時に 255 で除算され、0.0〜1.0 の Opacity に変換される | | `obj.alpha` | 変更可 | 不透明度(0.0〜255.0)。出力時に 255 で除算され、0.0〜1.0 の Opacity に変換される |
| `obj.rx`, `obj.ry`, `obj.rz` | 変更可 | 回転角(度)。対応する `obj.rxr` / `obj.ryr` / `obj.rzr` が同時に変更されている場合はそちらが優先される | | `obj.rx`, `obj.ry`, `obj.rz` | 変更可 | 回転角(度)。対応する `obj.rxr` / `obj.ryr` / `obj.rzr` が同時に変更されている場合はそちらが優先される |
| `obj.rxr`, `obj.ryr`, `obj.rzr` | 変更可 | 回転角(ラジアン)。同名の度数版より優先して反映される | | `obj.rxr`, `obj.ryr`, `obj.rzr` | 変更可 | 回転角(ラジアン)。同名の度数版より優先して反映される |
@@ -112,6 +112,15 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
- **`obj.setpixel(x, y, r, g, b [, a])`**: 指定座標のピクセルを書き換えます。`a` 省略時は 255 として扱われます。内部ではプリマルチプライドアルファ(BGRA)形式で保持され、書き込み時に変換されます。範囲外の座標を指定した場合は何も行いません。 - **`obj.setpixel(x, y, r, g, b [, a])`**: 指定座標のピクセルを書き換えます。`a` 省略時は 255 として扱われます。内部ではプリマルチプライドアルファ(BGRA)形式で保持され、書き込み時に変換されます。範囲外の座標を指定した場合は何も行いません。
- **`obj.getpixeldata()`**: 全ピクセルへ一括アクセスするためのプロキシオブジェクトを返します。`.width` / `.height` に加えて、`:get(index)` / `:set(index, value)` を持ちます。インデックスは 1 始まりで、R, G, B, A の順に並びます(`(y * obj.w + x) * 4 + 1` が R チャンネル)。アルファチャンネルを変更すると RGB が比率変換され、RGB チャンネルを変更すると内部的にプリマルチプライド変換が行われます。 - **`obj.getpixeldata()`**: 全ピクセルへ一括アクセスするためのプロキシオブジェクトを返します。`.width` / `.height` に加えて、`:get(index)` / `:set(index, value)` を持ちます。インデックスは 1 始まりで、R, G, B, A の順に並びます(`(y * obj.w + x) * 4 + 1` が R チャンネル)。アルファチャンネルを変更すると RGB が比率変換され、RGB チャンネルを変更すると内部的にプリマルチプライド変換が行われます。
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。 - **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
さらに、作業画像をまとめて加工する次の関数を用意しています(いずれも AviUtl に無い YMM4 独自拡張で、従来エンジンと高速ランタイムの両方で動作します)。色は `getpixel` / `setpixel` と同じ 0〜255 のストレート RGBA で扱います。
- **`obj.fill(r, g, b [, a, x, y, w, h])`**: 作業画像(省略時は全体、指定時は矩形)を指定色で塗りつぶします。
- **`obj.getpixelregion(x, y, w, h)`**: 矩形領域の画素を長さ `w*h*4` の配列(画素ごとに `r, g, b, a` の順・1 始まり)で取得します。範囲外は `0,0,0,0` です。
- **`obj.putpixelregion(x, y, w, h, data)`**: `getpixelregion` と同じ並びの配列を矩形領域へ書き戻します。範囲外へはみ出した画素は書き込みません。
- **`obj.convolve(kernel, size [, divisor, offset])`**: `size×size` の畳み込み(ぼかし・シャープ・輪郭抽出など)を適用します。`divisor` 省略時はカーネルの合計で割り、`offset` は除算後に加算します。端は最も近い画素で補います。
- **`obj.resize(w, h [, filter])`**: 作業画像を指定サイズへ拡大縮小し、`obj.w` / `obj.h` 等の寸法も更新します。`filter` は `"nearest"` か省略で線形補間です。
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。 `getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも MoonSharp に比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は MoonSharp と一致します(明示指定のみで使われる GPU カーネルは float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。 これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも MoonSharp に比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は MoonSharp と一致します(明示指定のみで使われる GPU カーネルは float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
@@ -252,6 +261,7 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
- **パイプ**: `x |> f`(`f((x))`。左辺を第 1 引数に渡す)、`x |> clamp(0, 255)`(`clamp((x), 0, 255)`) - **パイプ**: `x |> f`(`f((x))`。左辺を第 1 引数に渡す)、`x |> clamp(0, 255)`(`clamp((x), 0, 255)`)
- **補間文字列**: `` `x={a}` ``(`("x=" .. tostring(a))`。`{ }` の中に式を書く。拡張構文も使える) - **補間文字列**: `` `x={a}` ``(`("x=" .. tostring(a))`。`{ }` の中に式を書く。拡張構文も使える)
- **範囲判定**: `x in <1..5>`(`1 <= x and x <= 5`)、`<1..<5>`(上限を含まない) - **範囲判定**: `x in <1..5>`(`1 <= x and x <= 5`)、`<1..<5>`(上限を含まない)
- **高速化マーカー**(YMM4 独自拡張): `obj.fill` / `obj.convolve` / `obj.resize` は処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき自動で GPU へ委譲する。呼び出しの直前(単独行でも同一行でも可)に `[fast]` を置くと、このしきい値を無視して強制的に GPU へ委譲する。GPU が使えない環境や GPU の結果が CPU と一致しない環境では、`[fast]` を付けても CPU へ自動的に戻る。処理量が小さいときは GPU への委譲自体の往復コストが CPU 実行を上回ることがあり、`[fast]` を付けるとかえって遅くなる場合がある。文の先頭でのみ働くため `t[fast]` のような添字アクセスには影響しない
各記法の詳しい説明と例はドキュメント(`LuaScript/docs`)およびサイトの「構文拡張」を参照してください。 各記法の詳しい説明と例はドキュメント(`LuaScript/docs`)およびサイトの「構文拡張」を参照してください。
@@ -284,7 +294,7 @@ CPU / GPU カーネルが成立するのは、四則演算・`math.*`・比較
ネイティブ実行には次の制約があります。 ネイティブ実行には次の制約があります。
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜2³¹未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。 - `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜$2^{31}$未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
- `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。 - `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
> 高速ランタイム(`luajit.exe` / `lua51.dll` 等)はプラグインに同梱され、本体と同じ場所の `native` フォルダーへ自動配置されます。手動インストールは不要です。 > 高速ランタイム(`luajit.exe` / `lua51.dll` 等)はプラグインに同梱され、本体と同じ場所の `native` フォルダーへ自動配置されます。手動インストールは不要です。
+1
ファイルの表示
@@ -64,6 +64,7 @@ Lua 5.2 互換の MoonSharp はフォールバックとして使われます。
<tr><td>他アイテムの参照・キャラクター名・セリフ</td><td><code>obj.getobject</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr> <tr><td>他アイテムの参照・キャラクター名・セリフ</td><td><code>obj.getobject</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
<tr><td>音声波形・スペクトラムの取得</td><td><code>obj.getaudio</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr> <tr><td>音声波形・スペクトラムの取得</td><td><code>obj.getaudio</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
<tr><td>ピクセル操作</td><td><code>obj.getpixel</code>, <code>obj.setpixel</code>, <code>obj.getpixeldata</code></td><td><a href="pixels.html">ピクセル操作</a></td></tr> <tr><td>ピクセル操作</td><td><code>obj.getpixel</code>, <code>obj.setpixel</code>, <code>obj.getpixeldata</code></td><td><a href="pixels.html">ピクセル操作</a></td></tr>
<tr><td>画像加工(塗り・領域・畳み込み・拡大縮小)</td><td><code>obj.fill</code>, <code>obj.getpixelregion</code>, <code>obj.putpixelregion</code>, <code>obj.convolve</code>, <code>obj.resize</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
<tr><td>図形・テキスト・画像・動画・シーン・模様の読み込み</td><td><code>obj.load</code>, <code>obj.setfont</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr> <tr><td>図形・テキスト・画像・動画・シーン・模様の読み込み</td><td><code>obj.load</code>, <code>obj.setfont</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
<tr><td>他エフェクトの適用・描画</td><td><code>obj.effect</code>, <code>obj.brush</code>, <code>obj.draw</code>, <code>obj.drawpoly</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr> <tr><td>他エフェクトの適用・描画</td><td><code>obj.effect</code>, <code>obj.brush</code>, <code>obj.draw</code>, <code>obj.drawpoly</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
<tr><td>シーン・環境情報</td><td><code>scene.width</code>, <code>ymm4.is_saving</code></td><td><a href="scene-ymm4.html">scene / ymm4</a></td></tr> <tr><td>シーン・環境情報</td><td><code>scene.width</code>, <code>ymm4.is_saving</code></td><td><a href="scene-ymm4.html">scene / ymm4</a></td></tr>
+46
ファイルの表示
@@ -218,6 +218,11 @@ obj.load("text", "サンプル")</code></pre>
<tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr> <tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr>
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>・<code>frm</code>(コピー元のみ・仮想フレームバッファ)。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr> <tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>・<code>frm</code>(コピー元のみ・仮想フレームバッファ)。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
<tr><td><code>obj.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>スクリプト内に定義した HLSL のピクセルシェーダーを GPU で実行する。詳細は下記の「ピクセルシェーダー」を参照</td></tr> <tr><td><code>obj.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>スクリプト内に定義した HLSL のピクセルシェーダーを GPU で実行する。詳細は下記の「ピクセルシェーダー」を参照</td></tr>
<tr><td><code>obj.fill(r, g, b [, a, x, y, w, h])</code></td><td>作業画像を指定色で塗りつぶす。色は 0〜255 のストレート RGBA。矩形を省略すると画像全体。<strong>YMM4 独自拡張</strong></td></tr>
<tr><td><code>obj.getpixelregion(x, y, w, h)</code></td><td>矩形領域の画素をストレート RGBA の配列(1 始まり・<code>r,g,b,a</code> の順)で取得する。<strong>YMM4 独自拡張</strong></td></tr>
<tr><td><code>obj.putpixelregion(x, y, w, h, data)</code></td><td><code>obj.getpixelregion</code> と同じ並びの配列を矩形領域へ書き戻す。<strong>YMM4 独自拡張</strong></td></tr>
<tr><td><code>obj.convolve(kernel, size [, divisor, offset])</code></td><td>作業画像へ <code>size×size</code> の畳み込みを適用する(ぼかし・シャープ・輪郭抽出等)。<strong>YMM4 独自拡張</strong></td></tr>
<tr><td><code>obj.resize(w, h [, filter])</code></td><td>作業画像を指定サイズへ拡大縮小し、<code>obj.w</code>/<code>obj.h</code> 等も更新する。<code>filter</code> は <code>"nearest"</code> か省略で線形補間。<strong>YMM4 独自拡張</strong></td></tr>
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される。<code>blend</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の合成モードを番号で指定する。番号は下記の「合成モード」を参照。<code>draw_state</code> は真偽値で、<code>true</code> なら作業画像を出力し、<code>false</code> なら入力をそのまま通す。<code>drawtarget</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を <code>"framebuffer"</code> と <code>"tempbuffer"</code> で切り替える。詳細は下記の「描画先」を参照</td></tr> <tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される。<code>blend</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の合成モードを番号で指定する。番号は下記の「合成モード」を参照。<code>draw_state</code> は真偽値で、<code>true</code> なら作業画像を出力し、<code>false</code> なら入力をそのまま通す。<code>drawtarget</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を <code>"framebuffer"</code> と <code>"tempbuffer"</code> で切り替える。詳細は下記の「描画先」を参照</td></tr>
<tr><td><code>obj.getoption(name)</code></td><td>設定したオプションを取得する</td></tr> <tr><td><code>obj.getoption(name)</code></td><td>設定したオプションを取得する</td></tr>
<tr><td><code>obj.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr> <tr><td><code>obj.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr>
@@ -340,6 +345,47 @@ HLSL のコンパイルエラーはエディターの診断へ表示されます
GPU を利用できない環境では呼び出しはスキップされ、画像は変化しません。 GPU を利用できない環境では呼び出しはスキップされ、画像は変化しません。
</p> </p>
<h3>画像加工(YMM4 独自拡張)</h3>
<p>
<code>obj.fill</code>・<code>obj.getpixelregion</code>・<code>obj.putpixelregion</code>・<code>obj.convolve</code>・<code>obj.resize</code> は、作業画像を直接加工する YMM4 独自の関数です。
色は <code>obj.getpixel</code>/<code>obj.setpixel</code> と同じ 0〜255 のストレート RGBA で扱い、いずれも従来エンジンと高速ランタイムの両方で動作します。
</p>
<p>
<code>obj.getpixelregion(x, y, w, h)</code> は矩形領域の画素を長さ <code>w*h*4</code> の配列で返します。並びは画素ごとに <code>r, g, b, a</code> で、索引は <code>(行*w+列)*4+1</code> から始まります。範囲外の画素は <code>0,0,0,0</code> です。
<code>obj.putpixelregion</code> は同じ並びの配列を書き戻し、画像の範囲外へはみ出した画素は書き込みません。
</p>
<pre><code>-- 左右反転
local w, h = obj.w, obj.h
local src = obj.getpixelregion(0, 0, w, h)
local dst = {}
for y = 0, h - 1 do
for x = 0, w - 1 do
local s = (y * w + (w - 1 - x)) * 4
local d = (y * w + x) * 4
for c = 1, 4 do dst[d + c] = src[s + c] end
end
end
obj.putpixelregion(0, 0, w, h, dst)</code></pre>
<p>
<code>obj.convolve(kernel, size [, divisor, offset])</code> は <code>size×size</code> の畳み込みを適用します。<code>kernel</code> は行優先で 1 始まりの係数配列、<code>size</code> は奇数です。<code>divisor</code> を省略するとカーネルの合計(合計が 0 のときは 1)で割ります。<code>offset</code> は除算後に各成分へ加算します。端の画素は最も近い画素で補い、<code>r, g, b, a</code> すべてに適用されます。
</p>
<pre><code>obj.convolve({ 1,1,1, 1,1,1, 1,1,1 }, 3) -- 平均ぼかし
obj.convolve({ 0,-1,0, -1,5,-1, 0,-1,0 }, 3) -- シャープ
obj.convolve({ -1,-1,-1, -1,8,-1, -1,-1,-1 }, 3, 1, 0) -- 輪郭抽出</code></pre>
<p>
<code>obj.resize(w, h [, filter])</code> は作業画像を指定サイズへ拡大縮小し、<code>obj.w</code>・<code>obj.h</code>・<code>obj.cx</code> などの寸法も更新します。<code>filter</code> は <code>"nearest"</code>(最近傍)か、省略で線形補間です。高速ランタイムでは結果が最大画像サイズを超える場合は変更しません。
</p>
<p>
<code>obj.fill</code>・<code>obj.convolve</code>・<code>obj.resize</code> は、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。呼び出しの直前(単独行でも同一行でも可)に <code>[fast]</code> を置くと、このしきい値を無視して強制的に GPU へ委譲します。GPU が使えない環境や GPU の結果が CPU と一致しない環境では、<code>[fast]</code> を付けても CPU へ自動的に戻ります。処理量が小さいときは、GPU への委譲自体の往復コストが CPU 実行を上回ることがあり、<code>[fast]</code> を付けるとかえって遅くなる場合があります。詳細は <a href="syntax.html">拡張構文</a> を参照してください。
</p>
<h3>アンカーポイント</h3> <h3>アンカーポイント</h3>
<p> <p>
+4
ファイルの表示
@@ -91,6 +91,10 @@
<tr><td><code>obj.drawpoly(...)</code></td><td>4 頂点ポリゴンの描画</td></tr> <tr><td><code>obj.drawpoly(...)</code></td><td>4 頂点ポリゴンの描画</td></tr>
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファのコピー</td></tr> <tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファのコピー</td></tr>
<tr><td><code>obj.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>HLSL のピクセルシェーダーを GPU で実行</td></tr> <tr><td><code>obj.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>HLSL のピクセルシェーダーを GPU で実行</td></tr>
<tr><td><code>obj.fill(r, g, b [, a, x, y, w, h])</code></td><td>作業画像を指定色で塗りつぶす(YMM4 独自拡張)</td></tr>
<tr><td><code>obj.getpixelregion(x, y, w, h)</code> / <code>obj.putpixelregion(x, y, w, h, data)</code></td><td>矩形領域の画素をストレート RGBA 配列で取得 / 書き戻す(YMM4 独自拡張)</td></tr>
<tr><td><code>obj.convolve(kernel, size [, divisor, offset])</code></td><td>作業画像へ畳み込み(ぼかし・シャープ・輪郭抽出)を適用(YMM4 独自拡張)</td></tr>
<tr><td><code>obj.resize(w, h [, filter])</code></td><td>作業画像を拡大縮小し寸法を更新(YMM4 独自拡張)</td></tr>
<tr><td><code>obj.setoption(name [, value])</code> / <code>obj.getoption(name)</code></td><td>オプションの設定 / 取得</td></tr> <tr><td><code>obj.setoption(name [, value])</code> / <code>obj.getoption(name)</code></td><td>オプションの設定 / 取得</td></tr>
<tr><td><code>obj.getvalue(name)</code></td><td>obj の数値メンバーを名前で取得</td></tr> <tr><td><code>obj.getvalue(name)</code></td><td>obj の数値メンバーを名前で取得</td></tr>
<tr><td><code>obj.getaudio(buf, file [, type, size])</code></td><td>音声データ(PCM・スペクトラム・フーリエ変換)の取得</td></tr> <tr><td><code>obj.getaudio(buf, file [, type, size])</code></td><td>音声データ(PCM・スペクトラム・フーリエ変換)の取得</td></tr>
+28
ファイルの表示
@@ -249,6 +249,34 @@ end</code></pre>
左辺は 1 度だけ評価する無名関数に展開します。範囲 for の <code>for i in &lt;0..10&gt;</code> とは書く位置が異なるため、for のヘッダーには影響しません。 左辺は 1 度だけ評価する無名関数に展開します。範囲 for の <code>for i in &lt;0..10&gt;</code> とは書く位置が異なるため、for のヘッダーには影響しません。
</div> </div>
<h2>[fast] 高速化マーカー</h2>
<p>
<code>obj.fill</code> <code>obj.convolve</code> <code>obj.resize</code> は、処理量がしきい値以上で GPU の結果が CPU と一致すると確認できたとき、自動で GPU へ委譲します。<code>[fast]</code> を付けると、このしきい値を無視して強制的に GPU へ委譲します。<strong>YMM4 独自拡張</strong>です。
</p>
<table>
<tr><th>書き方</th><th>意味</th></tr>
<tr><td><code>[fast]</code> の次の行に <code>obj.convolve(k, 5)</code></td><td>しきい値を無視して GPU へ委譲を強制する</td></tr>
<tr><td><code>obj.convolve(k, 5)</code></td><td>処理量に応じて自動で GPU / CPU を判定する</td></tr>
</table>
<p>
マーカーは単独の行に置いても、同じ行に続けて書いても構いません。GPU が使えない環境や GPU の結果が CPU と一致しない環境では、<code>[fast]</code> を付けても自動で CPU 実行に戻ります。
</p>
<pre><code>--track@size:Size,1,15,3,2
local n = math.floor(obj.track0)
if n % 2 == 0 then n = n + 1 end
local k = {}
for i = 1, n * n do k[i] = 1 end
[fast]
obj.convolve(k, n)</code></pre>
<div class="note">
文の先頭でのみマーカーとして働くため、<code>t[fast]</code> のような添字アクセスは変換しません。<code>[fast]</code> を付けた対象が上記 3 関数以外のときはエラーを表示します。GPU 側の検証(ハードウェア対応と CPU との一致確認)は変わらず行われるため、結果が変わることはありません。従来エンジンと高速ランタイムの両方で動作します。処理量が小さいときは、GPU への委譲自体の往復コストが CPU 実行を上回ることがあり、<code>[fast]</code> を付けるとかえって遅くなる場合があります。
</div>
<div class="pager"> <div class="pager">
<a href="stdlib.html">← 標準ライブラリ</a> <a href="stdlib.html">← 標準ライブラリ</a>
<a href="globals.html">グローバル変数 →</a> <a href="globals.html">グローバル変数 →</a>
+310
ファイルの表示
@@ -99,6 +99,14 @@ local CB_KIND_LOADSCENE = 15
local CB_KIND_LOADBRUSH = 16 local CB_KIND_LOADBRUSH = 16
local CB_KIND_BRUSH = 17 local CB_KIND_BRUSH = 17
local CB_KIND_GETAUDIO = 18 local CB_KIND_GETAUDIO = 18
local CB_KIND_PIXELPROCESS = 19
local PIXEL_PROCESS_FILL = 0
local PIXEL_PROCESS_CONVOLVE = 1
local PIXEL_PROCESS_RESIZE = 2
local PIXEL_PROCESS_FILL_FULL_THRESHOLD = 1048576
local PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD = 1048576
local PIXEL_PROCESS_RESIZE_THRESHOLD = 262144
local PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD = 262144
local MAX_PIXEL_BUFFER = 3840 * 2160 * 4 local MAX_PIXEL_BUFFER = 3840 * 2160 * 4
local SHADER_META_DOUBLES = 20 local SHADER_META_DOUBLES = 20
local SHADER_CONSTANTS_MAX = 1024 local SHADER_CONSTANTS_MAX = 1024
@@ -132,6 +140,9 @@ local dirty = false
local pixelsValid = false local pixelsValid = false
local drawTarget = "frame" local drawTarget = "frame"
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
local convSrcData, convSrcCap = nil, 0
local resizeSrcData, resizeSrcCap = nil, 0
local pixelProcessAvailable = true
local function ensurePixels() local function ensurePixels()
if pixelsValid then return end if pixelsValid then return end
@@ -149,6 +160,20 @@ local function flushDraws()
k32.WaitForSingleObject(workEvent, INFINITE) k32.WaitForSingleObject(workEvent, INFINITE)
end end
local function tryPixelProcess(kind, force)
if not pixelProcessAvailable then return false end
cbResult[0] = kind
cbResult[9] = force and 1 or 0
i32[OFF_CB_FOUND] = 0
i32[OFF_CB_KIND] = CB_KIND_PIXELPROCESS
i32[OFF_STATUS] = STATUS_CALLBACK
k32.SetEvent(doneEvent)
k32.WaitForSingleObject(workEvent, INFINITE)
local found = i32[OFF_CB_FOUND]
if found < 0 then pixelProcessAvailable = false end
return found == 1
end
local function ringSlot(kind) local function ringSlot(kind)
local n = ringD[0] local n = ringD[0]
if n >= DRAW_RING_CAPACITY then if n >= DRAW_RING_CAPACITY then
@@ -840,6 +865,289 @@ function obj.copybuffer(dst, src)
end end
end end
local function fillImpl(force, r, g, b, a, x, y, w, h)
ensurePixels()
flushPixelData()
r = r or 0; g = g or 0; b = b or 0; a = a or 255
x = math.floor(x or 0); y = math.floor(y or 0)
w = math.floor(w or width); h = math.floor(h or height)
local x0 = clamp(x, 0, width)
local y0 = clamp(y, 0, height)
local x1 = clamp(x + w, 0, width)
local y1 = clamp(y + h, 0, height)
if x1 <= x0 or y1 <= y0 then return end
local imageArea = width * height
local fillArea = (x1 - x0) * (y1 - y0)
local fullFill = x0 == 0 and y0 == 0 and x1 == width and y1 == height
local usePixelProcess = force
if not usePixelProcess then
if fullFill then
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_FULL_THRESHOLD
else
usePixelProcess = imageArea >= PIXEL_PROCESS_FILL_PARTIAL_THRESHOLD and fillArea * 4 >= imageArea * 3
end
end
cbResult[1] = r
cbResult[2] = g
cbResult[3] = b
cbResult[4] = a
cbResult[5] = x0
cbResult[6] = y0
cbResult[7] = x1 - x0
cbResult[8] = y1 - y0
if usePixelProcess and tryPixelProcess(PIXEL_PROCESS_FILL, force) then
dirty = true
pdValid = false
pdDirty = false
return
end
local aK = clamp(a, 0, 255) / 255
local pb = math.floor(clamp(b * aK, 0, 255))
local pg = math.floor(clamp(g * aK, 0, 255))
local pr = math.floor(clamp(r * aK, 0, 255))
local pa = math.floor(clamp(a, 0, 255))
for py = y0, y1 - 1 do
for px = x0, x1 - 1 do
local p = pixels + (py * width + px) * 4
p[0] = pb; p[1] = pg; p[2] = pr; p[3] = pa
end
end
dirty = true
pdValid = false
end
function obj.fill(r, g, b, a, x, y, w, h) fillImpl(false, r, g, b, a, x, y, w, h) end
function __fast_fill(r, g, b, a, x, y, w, h) fillImpl(true, r, g, b, a, x, y, w, h) end
function obj.getpixelregion(x, y, w, h)
x = math.floor(x or 0); y = math.floor(y or 0)
w = math.floor(w or 0); h = math.floor(h or 0)
local out = {}
if w <= 0 or h <= 0 then return out end
ensurePixels()
flushPixelData()
for j = 0, h - 1 do
local sy = y + j
for i = 0, w - 1 do
local sx = x + i
local di = (j * w + i) * 4
if sx < 0 or sy < 0 or sx >= width or sy >= height then
out[di + 1] = 0; out[di + 2] = 0; out[di + 3] = 0; out[di + 4] = 0
else
local p = pixels + (sy * width + sx) * 4
local a = p[3]
if a <= 0 then
out[di + 1] = 0; out[di + 2] = 0; out[di + 3] = 0; out[di + 4] = 0
else
local s = 255 / a
out[di + 1] = clamp(p[2] * s, 0, 255)
out[di + 2] = clamp(p[1] * s, 0, 255)
out[di + 3] = clamp(p[0] * s, 0, 255)
out[di + 4] = a
end
end
end
end
return out
end
function obj.putpixelregion(x, y, w, h, data)
if type(data) ~= "table" then return end
x = math.floor(x or 0); y = math.floor(y or 0)
w = math.floor(w or 0); h = math.floor(h or 0)
if w <= 0 or h <= 0 then return end
ensurePixels()
flushPixelData()
for j = 0, h - 1 do
local dy = y + j
if dy >= 0 and dy < height then
for i = 0, w - 1 do
local dx = x + i
if dx >= 0 and dx < width then
local si = (j * w + i) * 4
local a = clamp(data[si + 4] or 0, 0, 255)
local aK = a / 255
local p = pixels + (dy * width + dx) * 4
p[0] = math.floor(clamp((data[si + 3] or 0) * aK, 0, 255))
p[1] = math.floor(clamp((data[si + 2] or 0) * aK, 0, 255))
p[2] = math.floor(clamp((data[si + 1] or 0) * aK, 0, 255))
p[3] = math.floor(a)
end
end
end
end
dirty = true
pdValid = false
end
local function convolveImpl(force, kernel, size, divisor, offset)
if type(kernel) ~= "table" then return end
size = math.floor(size or 0)
if size < 1 or size % 2 == 0 then return end
ensurePixels()
flushPixelData()
local taps = size * size
local k = {}
local sum = 0
for i = 1, taps do
local v = tonumber(kernel[i]) or 0
k[i] = v
sum = sum + v
end
local inv = divisor or sum
if inv == 0 then inv = 1 end
offset = offset or 0
if taps * 8 <= CB_TAG_MAX and (force or width * height * taps >= PIXEL_PROCESS_CONVOLVE_WORK_THRESHOLD) then
cbResult[1] = size
cbResult[2] = inv
cbResult[3] = offset
for i = 1, taps do
cbTagD[i - 1] = k[i]
end
i32[OFF_CB_TAGLEN] = taps * 8
if tryPixelProcess(PIXEL_PROCESS_CONVOLVE, force) then
dirty = true
pdValid = false
pdDirty = false
return
end
end
local total = width * height * 4
if not convSrcData or convSrcCap < total then
convSrcData = ffi.new("double[?]", total)
convSrcCap = total
end
local src = convSrcData
for pi = 0, width * height - 1 do
local p = pixels + pi * 4
local di = pi * 4
local a = p[3]
src[di + 3] = a
if a <= 0 then
src[di] = 0; src[di + 1] = 0; src[di + 2] = 0
else
local s = 255 / a
src[di] = clamp(p[2] * s, 0, 255)
src[di + 1] = clamp(p[1] * s, 0, 255)
src[di + 2] = clamp(p[0] * s, 0, 255)
end
end
local half = math.floor(size / 2)
for y = 0, height - 1 do
for x = 0, width - 1 do
local sr, sg, sb, sa = 0, 0, 0, 0
for ky = 0, size - 1 do
local sy = clamp(y + ky - half, 0, height - 1)
for kx = 0, size - 1 do
local sx = clamp(x + kx - half, 0, width - 1)
local kv = k[ky * size + kx + 1]
local si = (sy * width + sx) * 4
sr = sr + src[si] * kv
sg = sg + src[si + 1] * kv
sb = sb + src[si + 2] * kv
sa = sa + src[si + 3] * kv
end
end
local rr = clamp(sr / inv + offset, 0, 255)
local gg = clamp(sg / inv + offset, 0, 255)
local bb = clamp(sb / inv + offset, 0, 255)
local aa = clamp(sa / inv + offset, 0, 255)
local aK = aa / 255
local p = pixels + (y * width + x) * 4
p[0] = math.floor(clamp(bb * aK, 0, 255))
p[1] = math.floor(clamp(gg * aK, 0, 255))
p[2] = math.floor(clamp(rr * aK, 0, 255))
p[3] = math.floor(aa)
end
end
dirty = true
pdValid = false
end
function obj.convolve(kernel, size, divisor, offset) convolveImpl(false, kernel, size, divisor, offset) end
function __fast_convolve(kernel, size, divisor, offset) convolveImpl(true, kernel, size, divisor, offset) end
local function resizeImpl(force, newW, newH, mode)
newW = math.floor(newW or 0); newH = math.floor(newH or 0)
if newW < 1 then newW = 1 end
if newH < 1 then newH = 1 end
local dstCount = newW * newH * 4
if dstCount > pixelCapacity then return end
ensurePixels()
flushPixelData()
local cw, ch = width, height
local linear = mode ~= "nearest"
cbResult[1] = newW
cbResult[2] = newH
cbResult[3] = linear and 1 or 0
if (force or newW * newH >= PIXEL_PROCESS_RESIZE_THRESHOLD) and tryPixelProcess(PIXEL_PROCESS_RESIZE, force) then
width = newW; height = newH
i32[OFF_WIDTH] = newW; i32[OFF_HEIGHT] = newH
dirty = true
pixelsValid = true
pdValid = false
pdDirty = false
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
obj.cz = 0
obj.diagonal = math.sqrt(newW * newW + newH * newH)
return
end
local srcCount = cw * ch * 4
if not resizeSrcData or resizeSrcCap < srcCount then
resizeSrcData = ffi.new("uint8_t[?]", srcCount)
resizeSrcCap = srcCount
end
ffi.copy(resizeSrcData, pixels, srcCount)
local src = resizeSrcData
for y = 0, newH - 1 do
for x = 0, newW - 1 do
local o = pixels + (y * newW + x) * 4
if not linear then
local sx = clamp(math.floor((x + 0.5) * cw / newW), 0, cw - 1)
local sy = clamp(math.floor((y + 0.5) * ch / newH), 0, ch - 1)
local p = src + (sy * cw + sx) * 4
o[0] = p[0]; o[1] = p[1]; o[2] = p[2]; o[3] = p[3]
else
local u = (x + 0.5) * cw / newW - 0.5
local v = (y + 0.5) * ch / newH - 0.5
local x0 = math.floor(u)
local y0 = math.floor(v)
local tx = u - x0
local ty = v - y0
for c = 0, 3 do
local acc = 0
for j = 0, 1 do
local sy = clamp(y0 + j, 0, ch - 1)
local wy = (j == 0) and (1 - ty) or ty
for i = 0, 1 do
local sx = clamp(x0 + i, 0, cw - 1)
local wx = (i == 0) and (1 - tx) or tx
acc = acc + src[(sy * cw + sx) * 4 + c] * wy * wx
end
end
o[c] = math.floor(clamp(acc, 0, 255))
end
end
end
end
width = newW; height = newH
i32[OFF_WIDTH] = newW; i32[OFF_HEIGHT] = newH
dirty = true
pixelsValid = true
pdValid = false
pdDirty = false
obj.w = newW; obj.h = newH
obj.hw = newW / 2; obj.hh = newH / 2
obj.cx = newW / 2; obj.cy = newH / 2
obj.cz = 0
obj.diagonal = math.sqrt(newW * newW + newH * newH)
end
function obj.resize(newW, newH, mode) resizeImpl(false, newW, newH, mode) end
function __fast_resize(newW, newH, mode) resizeImpl(true, newW, newH, mode) end
local SCENE_VALUE_MAX = 4095 local SCENE_VALUE_MAX = 4095
local SCENE_NIL = {} local SCENE_NIL = {}
local sceneReads = {} local sceneReads = {}
@@ -1162,6 +1470,7 @@ sandbox = {
obj = obj, scene = scene, ymm4 = ymm4, obj = obj, scene = scene, ymm4 = ymm4,
anim = anim, bit32 = bit32, rawlen = rawlen, anim = anim, bit32 = bit32, rawlen = rawlen,
RGB = RGB, HSV = HSV, OR = OR, AND = AND, XOR = XOR, SHIFT = SHIFT, RGB = RGB, HSV = HSV, OR = OR, AND = AND, XOR = XOR, SHIFT = SHIFT,
__fast_fill = __fast_fill, __fast_convolve = __fast_convolve, __fast_resize = __fast_resize,
debug_print = debug_print, debug_print = debug_print,
math = math, string = string, table = table, math = math, string = string, table = table,
type = type, tostring = tostring, tonumber = tonumber, select = select, type = type, tostring = tostring, tonumber = tonumber, select = select,
@@ -1258,6 +1567,7 @@ while true do
pixelsValid = false pixelsValid = false
pdValid = false pdValid = false
pdDirty = false pdDirty = false
pixelProcessAvailable = i32[OFF_CB_FOUND] > 0
frameBufferValid = false frameBufferValid = false
ringD[0] = 0 ringD[0] = 0
local version = i32[OFF_SCRIPT_VERSION] local version = i32[OFF_SCRIPT_VERSION]