コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
72aa5d7351
|
||
|
|
a68c0fedd6
|
||
|
|
c5ed30bc72
|
||
|
|
6f44e30fa1
|
||
|
|
3db40f07cb
|
||
|
|
ff8791d086
|
||
|
|
f7f445bd3d
|
||
|
|
68af14bbf8
|
||
|
|
7a23318be3
|
||
|
|
4072d9b117
|
||
|
|
bc366a0af2
|
||
|
|
0c896d44ee
|
||
|
|
9a9acc4b85
|
||
|
|
a7e2285691
|
||
|
|
093e16feec
|
||
|
|
70b1b79fc2
|
||
|
|
995e1bc1aa
|
||
|
|
1120373e67
|
||
|
|
43b3ed7077
|
||
|
|
04ab6b111b
|
||
|
|
5d6787e7d6
|
||
|
|
6960406965
|
||
|
|
9454310988
|
||
|
|
d3118d20af
|
||
|
|
78337c06dd
|
||
|
|
85fc0f8e9f
|
||
|
|
c19ae507cf
|
||
|
|
004041b342
|
||
|
|
08f69cf76d
|
||
|
|
e10bfbe406
|
||
|
|
1a46a76b59
|
||
|
|
e2f32a6722
|
||
|
|
5a23f4329e
|
||
|
|
f5fd6cebdb
|
||
|
|
48f6711f1a
|
||
|
|
859046f5aa
|
||
|
|
7c7a60807f
|
||
|
|
1b23b2937e
|
||
|
|
4135f52499
|
||
|
|
8fda0bfec5
|
||
|
|
7e353053c7
|
||
|
|
d744d218fb
|
||
|
|
772fa6b678
|
||
|
|
154bc6a5c0
|
||
|
|
593939c2d4
|
||
|
|
6730c8ce70
|
||
|
|
b6a1e6e43c
|
||
|
|
fd06fdafe7
|
||
|
|
20a119c6c8
|
||
|
|
cfa8141424
|
検索条件に一致するファイルはありません
+48
-57
@@ -1,82 +1,73 @@
|
||||
# v1.16.2 - Lua スクリプト for YMM4
|
||||
# v1.18.0 - Lua スクリプト for YMM4
|
||||
|
||||
CPU / GPU カーネルへ変換できるスクリプトの範囲を広げたリリースです。ループの後の obj.putpixeldata(data)、if / elseif / else による local 変数への条件代入、local w = obj.w のような幅と高さの別名の 3 つの形を、新たにカーネル化の対象へ加えました。しきい値や二値化のような分岐を含むピクセル写像や、AviUtl から移植した getpixeldata の定型が、書き換え無しでそのままカーネルレーンへ乗るようになります。従来これらの形は高速ランタイム(LuaJIT)で実行され、毎フレームのピクセル転送とピクセル単位のループを伴っていましたが、カーネル化により転送を排した GPU カーネルまたは全コア並列の CPU カーネルで実行されます。実行結果は従来と変わらず、CPU カーネルは MoonSharp とビット単位で一致します。あわせて、エフェクトプロセッサの毎フレームのスクリプト比較を参照の同一性比較へ統一し、フレームあたりの固定費も削減しました。
|
||||
AviUtl の音声取得関数 obj.getaudio を追加したリリースです。編集中のシーン全体の音声、エフェクトを付けたアイテム自身の音声、任意の音声ファイルから、PCM・周波数スペクトラム・フーリエ変換のデータを取得し、音に反応する演出をスクリプトで作れます。あわせて obj.getobject が返すテーブルへ他アイテムのメタデータを追加し、合成音声アイテムも参照の対象にしました。どちらも従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で動作し、音声の取得とメタデータの解決はホスト側で一度だけ行うため、実行結果は両エンジンで一致します。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
|
||||
### ループの後の obj.putpixeldata(data)
|
||||
### obj.getaudio(buf, file [, type, size])
|
||||
|
||||
getpixeldata の形のカーネルで、二重ループの後に obj.putpixeldata(data) を書けるようにしました。
|
||||
音声データを取得します。
|
||||
|
||||
- AviUtl のスクリプトは、obj.getpixeldata() で取得したピクセルデータを編集した後、obj.putpixeldata(data) で書き戻す形が定型です。このプラグインではピクセルへの変更が即時に反映されるため obj.putpixeldata は何もしない関数ですが、従来はこの 1 行があるだけでスクリプト全体がカーネル化の対象から外れ、高速ランタイム(LuaJIT)で実行されていました。
|
||||
- 許容するのは、getpixeldata のハンドルを引数へ 1 個だけ渡す、ループの直後の 1 回の呼び出しです。別の名前を渡す形や、2 回以上書く形はカーネル化しません。
|
||||
- getpixel / setpixel の形には obj.putpixeldata を書けません。従来どおりカーネル化の対象から外れます。
|
||||
|
||||
### if / elseif / else による条件代入
|
||||
|
||||
二重ループの中に if / elseif / else 文を書き、local 変数へ条件付きで代入できるようにしました。
|
||||
|
||||
for y = 0, obj.h - 1 do
|
||||
for x = 0, obj.w - 1 do
|
||||
local r, g, b, a = obj.getpixel(x, y)
|
||||
local v = (r + g + b) / 3
|
||||
local o = 0
|
||||
if v > 170 then
|
||||
o = 255
|
||||
elseif v > 85 then
|
||||
o = 128
|
||||
end
|
||||
obj.setpixel(x, y, o, o, o, a)
|
||||
end
|
||||
local buf = {}
|
||||
local n, rate = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
|
||||
- 従来この形はカーネル化されず、しきい値の分岐は「条件 and 値1 or 値2」の 1 行で書く必要がありました。if 文で書いた同じ処理がそのままカーネル化されます。
|
||||
- elseif の連鎖と else、入れ子の if に対応します。分岐の中に書けるのは local 宣言と、すでに宣言済みの local 変数への代入だけです。
|
||||
- 分岐の中の local 宣言は Lua のブロックスコープのとおりに扱います。分岐の中で宣言した変数は分岐の外へ持ち出せず、外側と同じ名前を宣言したときは分岐の中だけで遮蔽します。ループ変数の x や y を遮蔽する宣言は、座標の参照と紛れるためカーネル化の対象から外します。
|
||||
- 条件に書けるのは、比較(< > <= >= == ~=)、and / or / not、obj.check0 ~ obj.check3 です。数値をそのまま条件に置く形は真偽値の判定と紛れるためカーネル化しません。
|
||||
- 分岐の中で obj.setpixel や set を呼ぶ形はカーネル化せず、従来どおりほかのエンジンで実行します。書き込まれなかったピクセルの元の値の保存は、アルファ乗算の往復を挟むとバイト単位の一致を保証できないためです。getpixeldata の形の get(読み取り)は分岐の中でも使えます。
|
||||
- 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.w と obj.h を local 変数へ受けた別名を使えるようにしました。
|
||||
obj.getobject(tag [, frame]) が返すテーブルへ、他アイテムのメタデータを追加しました。
|
||||
|
||||
local w = obj.w
|
||||
local h = obj.h
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
...
|
||||
end
|
||||
local o = obj.getobject("BGM")
|
||||
if o and o.exist then
|
||||
obj.load("text", o.character .. ": " .. o.text)
|
||||
end
|
||||
|
||||
- 別名として認めるのは、obj.w / obj.h / data.width / data.height のような幅と高さの値をそのまま受けた local 変数だけです。local w = 5 のような任意の値の変数を上限へ書いた形はカーネル化しません。
|
||||
- getpixeldata の形では、data.width と data.height をループの上限だけでなく、基底インデックスの local i = (y * w + x) * 4 の w や、式の中の値としても参照できます。
|
||||
- ループ変数が別名と同じ名前で外側の別名を遮蔽する形は、上限の値が座標に変わるためカーネル化の対象から外します。
|
||||
|
||||
### カーネルレーンへの昇格による高速化
|
||||
|
||||
上記に該当するスクリプトは、高速ランタイム(LuaJIT)からカーネルレーンへ昇格します。
|
||||
|
||||
- 高速ランタイムのピクセル処理は、毎フレームの GPU→CPU→GPU のピクセル転送と、ピクセル単位の Lua ループを伴います。カーネル化されたスクリプトは、GPU カーネルでは転送そのものを行わず、CPU カーネルでは実行時コンパイルした式ツリーを全コアで並列実行します。
|
||||
- GPU カーネルの自動選択の仕組みは従来のままです。初回に実機の GPU で処理して CPU カーネルとの一致を検証し、許容差に収まったプログラムだけを以後 GPU で実行します。収まらなければ CPU カーネルで実行します。
|
||||
- カーネル抽出の一箇所の拡張で、CPU カーネルの式ツリーと SIMD、GPU カーネルの HLSL のすべてのレーンへ反映されます。SIMD の適否の実測による自動選択も従来どおり適用されます。
|
||||
- .length : アイテムのフレーム数を返します。
|
||||
- .volume : 音量設定の現在値を返します。合成音声アイテム以外は 0 です。
|
||||
- .character : キャラクター名を返します。合成音声アイテム以外は空文字列です。
|
||||
- .text : セリフまたは表示テキストを返します。合成音声アイテムとテキストアイテム以外は空文字列です。
|
||||
- .kind : アイテムの種別名を返します。
|
||||
- 合成音声アイテムが参照の対象になりました。座標・拡大率・回転・不透明度は字幕の表示情報を返します。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- 実行結果に変更はありません。新たにカーネル化される形は、すべて MoonSharp を基準とするバイト単位の等価性テストで一致を確認しています。
|
||||
- カーネル化の条件に合わないスクリプトは、従来どおり自動的に LuaJIT または MoonSharp で実行され、結果は変わりません。エンジン指定ディレクティブの仕様と優先順位に変更はありません。
|
||||
- v1.16.1 までの構文拡張、obj.setanchor をはじめとする既存の API、実行エンジンの自動振り分けの仕様に変更はありません。
|
||||
- obj.getaudio は AviUtl 互換の関数として追加しました。"audiobuffer" の意味は AviUtl の「編集中の音声データ」に合わせています。buf の添字は 1 始まりで、AviUtl 向けの既存スクリプトの慣例と同じです。
|
||||
- "itembuffer" は AviUtl / AviUtl2 に存在しない YMM4 向けの独自拡張です。AviUtl 向けに書かれた既存スクリプトへの影響はありません。
|
||||
- obj.getaudio が 1 回で取得できるデータ数の上限は 1024 個です。AviUtl の代表的な用途(spectrum の帯域数 32 前後、fourier の 1024 個、pcm の 1000 個前後)はいずれも上限の範囲に収まります。
|
||||
- obj.getobject の既存フィールドの意味と値に変更はありません。メタデータは追加のみで、従来の呼び出しはそのまま動きます。
|
||||
- 未対応の type や読み取りの失敗はデータ数 0 の戻り値で表し、スクリプトを停止させません。
|
||||
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.17.0 までの構文拡張と既存の API に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- カーネル抽出器の条件分岐は、条件・分岐・合流を選択式へ降下して表現します。カーネルの中間表現は副作用と例外の無い純粋な式だけで構成されるため、両方の分岐を評価してから条件で選択しても結果が変わらないことを根拠にしています。条件は分岐へ入る前の束縛で評価し、合流は分岐の前を基準に、変わった変数だけを選択式で束ね直します。elseif の連鎖は入れ子の分岐として同じ仕組みで処理します。
|
||||
- 分岐の中の local 宣言の遮蔽は、宣言の時点の束縛を記録して分岐の終わりで復元します。宣言より前に外側の変数へ代入していた場合も、その代入を失わずに合流へ引き継ぎます。
|
||||
- 幅と高さの別名は、束縛の実体が幅または高さの参照であることを確認して受け付けます。ループ変数のスコープからの除去を外側と内側の軸判定の間へ移し、ループ変数が別名を遮蔽する形を内側の上限として誤って受け付けないようにしました。
|
||||
- エフェクトプロセッサのスクリプト依存キャッシュ(実行形への変換・カーネル抽出・ディレクティブ解決)の判定を、文字列の序数比較から参照の同一性比較へ統一しました。スクリプトの参照はフレーム間で安定しているため、毎フレームのスクリプト長に比例する比較が不要になります。obj.effect の互換対象の解決結果もスクリプトの参照を鍵にキャッシュし、obj.effect を使うスクリプトで毎フレーム行っていたスクリプト走査を排除しました。
|
||||
- ドキュメントは付属の 8 言語、サイトのエンジンとピクセル操作のページ、README を更新しました。getpixeldata の形が既にカーネル化の対象である点が従来の記載から漏れていたため、あわせて是正しました。
|
||||
- テストは 3317 件です。v1.16.1 の 3299 件から、if / elseif / else の条件代入、入れ子の分岐と遮蔽、幅と高さの別名、obj.putpixeldata を伴う getpixeldata の定型の MoonSharp との等価性の検証、分岐の中の setpixel / set、真偽値でない条件、座標を遮蔽する宣言、不正な obj.putpixeldata、任意の値の変数を上限とする形を拒否することの検証、条件分岐カーネルの HLSL 発行と SIMD 一致の検証を追加しました。
|
||||
- PCM・スペクトラム・フーリエ変換の計算は LuaScript.Compat へ追加した AviUtlAudioConverter が担います。pcm は ±32768 のスケール、spectrum は窓 1024 の FFT の帯域平均を 2/N×32768 で正規化、fourier は窓 2048 の FFT の振幅を 2/N で正規化した値です。計算はホスト側で一度だけ行い、両エンジンは同じ結果を受け取るため、エンジン間の一致は構造的に保証されます。
|
||||
- 音声の取得は新設の AudioSampleProvider が担い、3 つの経路を持ちます。"audiobuffer" はシーンの公開メソッド Scene.TryCreateAudioSource で得たタイムライン音源を用います。これは公式コミュニティプラグインの音量取得系の映像エフェクトが同じ状況(映像エフェクトからの音声参照)で使っているのと同じ経路です。ファイルはプラグイン公開 API の AudioFileSourceFactory を用います。
|
||||
- "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 個のエラーです。
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.16.2
|
||||
Luaスクリプト for YMM4 v1.18.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal sealed class AviUtlAudioConverter
|
||||
{
|
||||
public const int MaxSamples = 1024;
|
||||
public const int SpectrumWindow = 1024;
|
||||
public const int FourierWindow = 2048;
|
||||
public const int SpectrumBins = SpectrumWindow / 2;
|
||||
|
||||
private const double PcmScale = 32768d;
|
||||
|
||||
private readonly double[] _mono = new double[FourierWindow];
|
||||
private readonly double[] _real = new double[FourierWindow];
|
||||
private readonly double[] _imag = new double[FourierWindow];
|
||||
|
||||
private enum DataKind
|
||||
{
|
||||
Unknown,
|
||||
Pcm,
|
||||
Spectrum,
|
||||
Fourier,
|
||||
}
|
||||
|
||||
public static int RequiredFrames(string type, int size)
|
||||
{
|
||||
var (kind, _) = Parse(type);
|
||||
return kind switch
|
||||
{
|
||||
DataKind.Pcm => ResolveCount(kind, size),
|
||||
DataKind.Spectrum => SpectrumWindow,
|
||||
DataKind.Fourier => FourierWindow,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
|
||||
public int Convert(string type, ReadOnlySpan<float> interleaved, int frames, int size, Span<double> destination)
|
||||
{
|
||||
var (kind, channel) = Parse(type);
|
||||
if (kind == DataKind.Unknown || frames <= 0)
|
||||
return 0;
|
||||
|
||||
int window = kind switch
|
||||
{
|
||||
DataKind.Pcm => Math.Min(frames, ResolveCount(kind, size)),
|
||||
DataKind.Spectrum => SpectrumWindow,
|
||||
_ => FourierWindow,
|
||||
};
|
||||
FillMono(interleaved, frames, channel, window);
|
||||
|
||||
switch (kind)
|
||||
{
|
||||
case DataKind.Pcm:
|
||||
{
|
||||
int count = Math.Min(ResolveCount(kind, size), frames);
|
||||
for (int i = 0; i < count; i++)
|
||||
destination[i] = Math.Clamp(_mono[i] * PcmScale, -32768d, 32767d);
|
||||
return count;
|
||||
}
|
||||
case DataKind.Spectrum:
|
||||
{
|
||||
int bands = ResolveCount(kind, size);
|
||||
Fft(SpectrumWindow);
|
||||
double scale = 2d / SpectrumWindow * PcmScale;
|
||||
for (int b = 0; b < bands; b++)
|
||||
{
|
||||
int start = b * SpectrumBins / bands;
|
||||
int end = (b + 1) * SpectrumBins / bands;
|
||||
if (end <= start)
|
||||
end = start + 1;
|
||||
double sum = 0d;
|
||||
for (int bin = start; bin < end; bin++)
|
||||
sum += Magnitude(bin);
|
||||
destination[b] = sum / (end - start) * scale;
|
||||
}
|
||||
return bands;
|
||||
}
|
||||
case DataKind.Fourier:
|
||||
{
|
||||
int count = ResolveCount(kind, size);
|
||||
Fft(FourierWindow);
|
||||
double scale = 2d / FourierWindow;
|
||||
for (int i = 0; i < count; i++)
|
||||
destination[i] = Magnitude(i + 1) * scale;
|
||||
return count;
|
||||
}
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static int ResolveCount(DataKind kind, int size)
|
||||
{
|
||||
int fallback = kind == DataKind.Spectrum ? 32 : MaxSamples;
|
||||
int max = kind == DataKind.Spectrum ? SpectrumBins : MaxSamples;
|
||||
return size <= 0 ? Math.Min(fallback, max) : Math.Clamp(size, 1, max);
|
||||
}
|
||||
|
||||
private static (DataKind Kind, int Channel) Parse(string type)
|
||||
{
|
||||
int channel = 0;
|
||||
int length = type.Length;
|
||||
if (length >= 2 && type[length - 2] == '.')
|
||||
{
|
||||
char suffix = type[length - 1];
|
||||
if (suffix == 'l')
|
||||
channel = 1;
|
||||
else if (suffix == 'r')
|
||||
channel = 2;
|
||||
if (channel != 0)
|
||||
length -= 2;
|
||||
}
|
||||
|
||||
var name = type.AsSpan(0, length);
|
||||
DataKind kind = DataKind.Unknown;
|
||||
if (name.SequenceEqual("pcm"))
|
||||
kind = DataKind.Pcm;
|
||||
else if (name.SequenceEqual("spectrum"))
|
||||
kind = DataKind.Spectrum;
|
||||
else if (name.SequenceEqual("fourier"))
|
||||
kind = DataKind.Fourier;
|
||||
return (kind, channel);
|
||||
}
|
||||
|
||||
private void FillMono(ReadOnlySpan<float> interleaved, int frames, int channel, int window)
|
||||
{
|
||||
int available = Math.Min(frames, window);
|
||||
for (int i = 0; i < available; i++)
|
||||
{
|
||||
float left = interleaved[i * 2];
|
||||
float right = interleaved[i * 2 + 1];
|
||||
_mono[i] = channel switch
|
||||
{
|
||||
1 => left,
|
||||
2 => right,
|
||||
_ => (left + right) * 0.5d,
|
||||
};
|
||||
}
|
||||
for (int i = available; i < window; i++)
|
||||
_mono[i] = 0d;
|
||||
}
|
||||
|
||||
private double Magnitude(int bin) =>
|
||||
Math.Sqrt(_real[bin] * _real[bin] + _imag[bin] * _imag[bin]);
|
||||
|
||||
private void Fft(int n)
|
||||
{
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
_real[i] = _mono[i];
|
||||
_imag[i] = 0d;
|
||||
}
|
||||
|
||||
for (int i = 1, j = 0; i < n; i++)
|
||||
{
|
||||
int bit = n >> 1;
|
||||
for (; (j & bit) != 0; bit >>= 1)
|
||||
j ^= bit;
|
||||
j |= bit;
|
||||
if (i < j)
|
||||
{
|
||||
(_real[i], _real[j]) = (_real[j], _real[i]);
|
||||
(_imag[i], _imag[j]) = (_imag[j], _imag[i]);
|
||||
}
|
||||
}
|
||||
|
||||
for (int len = 2; len <= n; len <<= 1)
|
||||
{
|
||||
double angle = -2d * Math.PI / len;
|
||||
double wRe = Math.Cos(angle);
|
||||
double wIm = Math.Sin(angle);
|
||||
for (int i = 0; i < n; i += len)
|
||||
{
|
||||
double curRe = 1d;
|
||||
double curIm = 0d;
|
||||
for (int k = 0; k < len / 2; k++)
|
||||
{
|
||||
int a = i + k;
|
||||
int b = i + k + len / 2;
|
||||
double tRe = _real[b] * curRe - _imag[b] * curIm;
|
||||
double tIm = _real[b] * curIm + _imag[b] * curRe;
|
||||
_real[b] = _real[a] - tRe;
|
||||
_imag[b] = _imag[a] - tIm;
|
||||
_real[a] += tRe;
|
||||
_imag[a] += tIm;
|
||||
double nextRe = curRe * wRe - curIm * wIm;
|
||||
curIm = curRe * wIm + curIm * wRe;
|
||||
curRe = nextRe;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.2</Version>
|
||||
<Version>1.18.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.2</Version>
|
||||
<Version>1.18.0</Version>
|
||||
<IsRoslynComponent>true</IsRoslynComponent>
|
||||
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.2</Version>
|
||||
<Version>1.18.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.2</Version>
|
||||
<Version>1.18.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -72,6 +72,12 @@ namespace LuaScript
|
||||
|
||||
public Func<ISceneObjectResolver>? ResolverProvider { get; set; }
|
||||
|
||||
public Func<string, double, (byte[] Buffer, int Width, int Height)>? SceneImageLoader { get; set; }
|
||||
|
||||
public Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? BrushImageLoader { get; set; }
|
||||
|
||||
public Func<string, string, int, (int Count, int Rate, double[] Data)>? AudioLoader { get; set; }
|
||||
|
||||
private readonly Dictionary<string, string> _stringParameters = new(StringComparer.Ordinal);
|
||||
|
||||
public IReadOnlyDictionary<string, string> StringParameters => _stringParameters;
|
||||
|
||||
@@ -37,6 +37,7 @@ namespace LuaScript.Engine
|
||||
private readonly Dictionary<string, byte[]> _stringNameBytes = new(StringComparer.Ordinal);
|
||||
private byte[] _stringValueBytes = new byte[256];
|
||||
private byte[] _sceneValueBytes = new byte[256];
|
||||
private byte[] _objectMetaBytes = new byte[256];
|
||||
|
||||
private static readonly byte[] s_shaderTransparentPixel = new byte[4];
|
||||
private readonly PixelShaderInput[] _shaderInputs = new PixelShaderInput[NativeProtocol.ShaderResourcesMax];
|
||||
@@ -71,11 +72,14 @@ namespace LuaScript.Engine
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<DrawCommand> addDraw,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||
PixelShaderInvoke? runPixelShader,
|
||||
out bool pixelsDirty,
|
||||
out bool bufferReplaced,
|
||||
@@ -160,7 +164,7 @@ namespace LuaScript.Engine
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, setAnchor, sceneGetValue, sceneSetValue, runPixelShader);
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader);
|
||||
}
|
||||
_workEvent.Set();
|
||||
}
|
||||
@@ -321,10 +325,13 @@ namespace LuaScript.Engine
|
||||
Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)> loadText,
|
||||
Func<string, (byte[] buffer, int w, int h)> loadImage,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadMovie,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect,
|
||||
Action<string, int, bool, int, double[]> setAnchor,
|
||||
Func<string, SceneValue> sceneGetValue,
|
||||
Action<string, SceneValue> sceneSetValue,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio,
|
||||
PixelShaderInvoke? runPixelShader)
|
||||
{
|
||||
int kind = view.ReadInt32(NativeProtocol.OffCallbackKind);
|
||||
@@ -345,6 +352,15 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindLoadMovie:
|
||||
ResolveLoadMovieCallback(view, loadMovie);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadScene:
|
||||
ResolveLoadSceneCallback(view, loadScene);
|
||||
break;
|
||||
case NativeProtocol.CbKindLoadBrush:
|
||||
ResolveLoadBrushCallback(view, loadBrush);
|
||||
break;
|
||||
case NativeProtocol.CbKindBrush:
|
||||
ResolveBrushCallback(view, loadBrush);
|
||||
break;
|
||||
case NativeProtocol.CbKindEffect:
|
||||
ResolveEffectCallback(view, addEffect);
|
||||
break;
|
||||
@@ -357,6 +373,9 @@ namespace LuaScript.Engine
|
||||
case NativeProtocol.CbKindSceneSet:
|
||||
ResolveSceneSetCallback(view, sceneSetValue);
|
||||
break;
|
||||
case NativeProtocol.CbKindGetAudio:
|
||||
ResolveGetAudioCallback(view, loadAudio);
|
||||
break;
|
||||
case NativeProtocol.CbKindPixelShaderStage:
|
||||
ResolveShaderStageCallback(view);
|
||||
break;
|
||||
@@ -557,6 +576,40 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static readonly double[] s_noAudioData = [];
|
||||
|
||||
private void ResolveGetAudioCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, string, int, (int Count, int Rate, double[] Data)> loadAudio)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
int separator = Array.IndexOf(_callbackTag, (byte)0, 0, tagLen);
|
||||
string file = Encoding.UTF8.GetString(_callbackTag, 0, separator >= 0 ? separator : tagLen);
|
||||
string type = separator >= 0
|
||||
? Encoding.UTF8.GetString(_callbackTag, separator + 1, tagLen - separator - 1)
|
||||
: "pcm";
|
||||
int size = (int)view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
int count = 0;
|
||||
int rate = 0;
|
||||
double[] data = s_noAudioData;
|
||||
try { (count, rate, data) = loadAudio(file, type, size); }
|
||||
catch
|
||||
{
|
||||
count = 0;
|
||||
rate = 0;
|
||||
data = s_noAudioData;
|
||||
}
|
||||
|
||||
count = Math.Clamp(count, 0, Math.Min(data.Length, NativeProtocol.CallbackTagMax / 8));
|
||||
if (count > 0)
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, data, 0, count);
|
||||
view.Write(NativeProtocol.CallbackResultOffset, (double)count);
|
||||
view.Write(NativeProtocol.CallbackResultOffset + 8, (double)rate);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveSetAnchorCallback(MemoryMappedViewAccessor view, Action<string, int, bool, int, double[]> setAnchor)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
@@ -644,6 +697,9 @@ namespace LuaScript.Engine
|
||||
view.Write(result + NativeProtocol.CbRz * 8, value.Rz);
|
||||
view.Write(result + NativeProtocol.CbAlpha * 8, value.Alpha);
|
||||
view.Write(result + NativeProtocol.CbLayer * 8, (double)value.Layer);
|
||||
view.Write(result + NativeProtocol.CbVolume * 8, value.Volume);
|
||||
view.Write(result + NativeProtocol.CbLength * 8, (double)value.Length);
|
||||
WriteObjectMeta(view, value.Character, value.Text, value.Kind);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
else
|
||||
@@ -652,6 +708,27 @@ namespace LuaScript.Engine
|
||||
}
|
||||
}
|
||||
|
||||
private void WriteObjectMeta(MemoryMappedViewAccessor view, string character, string text, string kind)
|
||||
{
|
||||
character ??= string.Empty;
|
||||
text ??= string.Empty;
|
||||
kind ??= string.Empty;
|
||||
int maxBytes = Encoding.UTF8.GetMaxByteCount(character.Length + text.Length + kind.Length) + 2;
|
||||
if (_objectMetaBytes.Length < maxBytes)
|
||||
_objectMetaBytes = new byte[Math.Max(maxBytes, _objectMetaBytes.Length * 2)];
|
||||
|
||||
int length = Encoding.UTF8.GetBytes(character, 0, character.Length, _objectMetaBytes, 0);
|
||||
_objectMetaBytes[length++] = 0;
|
||||
length += Encoding.UTF8.GetBytes(text, 0, text.Length, _objectMetaBytes, length);
|
||||
_objectMetaBytes[length++] = 0;
|
||||
length += Encoding.UTF8.GetBytes(kind, 0, kind.Length, _objectMetaBytes, length);
|
||||
if (length > NativeProtocol.CallbackTagMax)
|
||||
length = NativeProtocol.CallbackTagMax;
|
||||
|
||||
view.WriteArray(NativeProtocol.CallbackTagOffset, _objectMetaBytes, 0, length);
|
||||
view.Write(NativeProtocol.OffCallbackTagLen, length);
|
||||
}
|
||||
|
||||
private void ResolveLoadFigureCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, int, double, double, double, (byte[] buffer, int w, int h)> loadFigure)
|
||||
@@ -772,16 +849,100 @@ namespace LuaScript.Engine
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||
private void ResolveLoadSceneCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, (byte[] buffer, int w, int h)> loadScene)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
double time = view.ReadDouble(NativeProtocol.CallbackResultOffset);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadScene(name, time); }
|
||||
catch { result = ([], 0, 0); }
|
||||
|
||||
long pixelSize = (long)result.w * result.h * 4;
|
||||
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static readonly KeyValuePair<string, object>[] s_noBrushArguments = [];
|
||||
|
||||
private void ResolveLoadBrushCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string name = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
|
||||
WriteBrushResult(view, loadBrush, name, s_noBrushArguments);
|
||||
}
|
||||
|
||||
private void ResolveBrushCallback(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||
if (segments.Length == 0)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
WriteBrushResult(view, loadBrush, segments[0], ParseNamedArguments(segments));
|
||||
}
|
||||
|
||||
private void WriteBrushResult(
|
||||
MemoryMappedViewAccessor view,
|
||||
Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> loadBrush,
|
||||
string name,
|
||||
IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
long rOff = NativeProtocol.CallbackResultOffset;
|
||||
double width = view.ReadDouble(rOff + 0 * 8);
|
||||
double height = view.ReadDouble(rOff + 1 * 8);
|
||||
|
||||
(byte[] buffer, int w, int h) result;
|
||||
try { result = loadBrush(name, width, height, arguments); }
|
||||
catch { result = ([], 0, 0); }
|
||||
|
||||
long pixelSize = (long)result.w * result.h * 4;
|
||||
if (result.w <= 0 || result.h <= 0 || pixelSize > PixelRegionCapacity)
|
||||
{
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, 0);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, 0);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
view.Write(NativeProtocol.OffLoadResultWidth, result.w);
|
||||
view.Write(NativeProtocol.OffLoadResultHeight, result.h);
|
||||
WritePixelRegion(result.buffer, (int)pixelSize);
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
private static IReadOnlyList<KeyValuePair<string, object>> ParseNamedArguments(string[] segments)
|
||||
{
|
||||
if (segments.Length < 3)
|
||||
return s_noBrushArguments;
|
||||
|
||||
string effectName = segments[0];
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < segments.Length; i += 2)
|
||||
{
|
||||
@@ -798,8 +959,19 @@ namespace LuaScript.Engine
|
||||
value = raw;
|
||||
arguments.Add(new KeyValuePair<string, object>(key, value));
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
try { addEffect(effectName, arguments); }
|
||||
private void ResolveEffectCallback(MemoryMappedViewAccessor view, Action<string, IReadOnlyList<KeyValuePair<string, object>>> addEffect)
|
||||
{
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
|
||||
var segments = Encoding.UTF8.GetString(_callbackTag, 0, tagLen).Split('\0');
|
||||
if (segments.Length == 0)
|
||||
return;
|
||||
|
||||
try { addEffect(segments[0], ParseNamedArguments(segments)); }
|
||||
catch { }
|
||||
view.Write(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
|
||||
@@ -548,6 +548,18 @@ namespace LuaScript
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
case "scene" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadScene(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? _activeContext.Time : _activeContext.Time);
|
||||
break;
|
||||
case "brush" when args.Count > 1 && args[1].Type == DataType.String:
|
||||
LoadBrush(
|
||||
args[1].String,
|
||||
args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d,
|
||||
args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d,
|
||||
s_noNamedArguments);
|
||||
break;
|
||||
}
|
||||
return DynValue.Void;
|
||||
}
|
||||
@@ -771,6 +783,47 @@ namespace LuaScript
|
||||
return value.Type == DataType.Number ? value : DynValue.NewNumber(0d);
|
||||
}
|
||||
|
||||
private static readonly double[] s_noAudioData = [];
|
||||
|
||||
[LuaFunction("getaudio")]
|
||||
private DynValue GetAudio(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 2 || args[1].Type != DataType.String)
|
||||
return DynValue.NewTuple(DynValue.NewNumber(0d), DynValue.NewNumber(0d));
|
||||
|
||||
string file = args[1].String;
|
||||
string type = args.Count > 2 && args[2].Type == DataType.String ? args[2].String : "pcm";
|
||||
int size = args.Count > 3 ? (int)(args[3].CastToNumber() ?? 0d) : 0;
|
||||
|
||||
int count = 0;
|
||||
int rate = 0;
|
||||
double[] data = s_noAudioData;
|
||||
var loader = _activeContext.AudioLoader;
|
||||
if (loader is not null)
|
||||
(count, rate, data) = loader(file, type, size);
|
||||
if (count > data.Length)
|
||||
count = data.Length;
|
||||
|
||||
var bufArg = args[0];
|
||||
Table? table = bufArg.Type == DataType.Table ? bufArg.Table : null;
|
||||
bool created = false;
|
||||
if (table is null && bufArg.IsNil())
|
||||
{
|
||||
table = new Table(_script);
|
||||
created = true;
|
||||
}
|
||||
if (table is not null)
|
||||
{
|
||||
for (int i = 0; i < count; i++)
|
||||
table.Set(i + 1, DynValue.NewNumber(data[i]));
|
||||
}
|
||||
|
||||
return created
|
||||
? DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate), DynValue.NewTable(table!))
|
||||
: DynValue.NewTuple(DynValue.NewNumber(count), DynValue.NewNumber(rate));
|
||||
}
|
||||
|
||||
[LuaFunction("setoption")]
|
||||
private DynValue SetOption(CallbackArguments args)
|
||||
{
|
||||
@@ -862,9 +915,19 @@ namespace LuaScript
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
string name = args[0].String;
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(args[0].String, CollectNamedArguments(args, 1)));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private static readonly KeyValuePair<string, object>[] s_noNamedArguments = [];
|
||||
|
||||
private static IReadOnlyList<KeyValuePair<string, object>> CollectNamedArguments(CallbackArguments args, int start)
|
||||
{
|
||||
if (start + 1 >= args.Count)
|
||||
return s_noNamedArguments;
|
||||
|
||||
var arguments = new List<KeyValuePair<string, object>>();
|
||||
for (int i = 1; i + 1 < args.Count; i += 2)
|
||||
for (int i = start; i + 1 < args.Count; i += 2)
|
||||
{
|
||||
if (args[i].Type != DataType.String)
|
||||
continue;
|
||||
@@ -878,8 +941,27 @@ namespace LuaScript
|
||||
};
|
||||
arguments.Add(new KeyValuePair<string, object>(args[i].String, boxed));
|
||||
}
|
||||
return arguments;
|
||||
}
|
||||
|
||||
_activeContext.AddEffect(new AviUtlEffectRequest(name, arguments));
|
||||
[LuaFunction("brush")]
|
||||
private DynValue Brush(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count == 0 || args[0].Type != DataType.String)
|
||||
return DynValue.Void;
|
||||
|
||||
int start = 1;
|
||||
double width = 0d;
|
||||
double height = 0d;
|
||||
if (args.Count > 2 && args[1].Type == DataType.Number && args[2].Type == DataType.Number)
|
||||
{
|
||||
width = args[1].Number;
|
||||
height = args[2].Number;
|
||||
start = 3;
|
||||
}
|
||||
|
||||
LoadBrush(args[0].String, width, height, CollectNamedArguments(args, start));
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
@@ -947,6 +1029,34 @@ namespace LuaScript
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadScene(string name, double time)
|
||||
{
|
||||
var ctx = _activeContext!;
|
||||
var loader = ctx.SceneImageLoader;
|
||||
if (loader is null)
|
||||
return;
|
||||
var (buffer, w, h) = loader(name, time);
|
||||
if (w <= 0 || h <= 0)
|
||||
return;
|
||||
ctx.ReplaceBuffer(buffer, w, h);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadBrush(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
var ctx = _activeContext!;
|
||||
var loader = ctx.BrushImageLoader;
|
||||
if (loader is null)
|
||||
return;
|
||||
double w = width > 0d ? width : ctx.ImageWidth;
|
||||
double h = height > 0d ? height : ctx.ImageHeight;
|
||||
var (buffer, bw, bh) = loader(name, w, h, arguments);
|
||||
if (bw <= 0 || bh <= 0)
|
||||
return;
|
||||
ctx.ReplaceBuffer(buffer, bw, bh);
|
||||
RefreshObjDimensions();
|
||||
}
|
||||
|
||||
private void LoadMovie(string path, double time)
|
||||
{
|
||||
_mediaLoader ??= _mediaLoaderFactory();
|
||||
@@ -989,6 +1099,11 @@ namespace LuaScript
|
||||
["rzr"] = info.Rz * Math.PI / 180d,
|
||||
["alpha"] = info.Alpha,
|
||||
["layer"] = info.Layer,
|
||||
["volume"] = info.Volume,
|
||||
["length"] = info.Length,
|
||||
["character"] = info.Character ?? string.Empty,
|
||||
["text"] = info.Text ?? string.Empty,
|
||||
["kind"] = info.Kind ?? string.Empty,
|
||||
};
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ namespace LuaScript.Engine
|
||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagMax = 8192;
|
||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||
public const int CallbackResultCount = 8;
|
||||
public const int CallbackResultCount = 10;
|
||||
|
||||
public const int StringParamsOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||
public const int MinStringParamsCapacity = 64 * 1024;
|
||||
@@ -63,6 +63,10 @@ namespace LuaScript.Engine
|
||||
public const int CbKindSceneSet = 12;
|
||||
public const int CbKindPixelShaderStage = 13;
|
||||
public const int CbKindPixelShaderRun = 14;
|
||||
public const int CbKindLoadScene = 15;
|
||||
public const int CbKindLoadBrush = 16;
|
||||
public const int CbKindBrush = 17;
|
||||
public const int CbKindGetAudio = 18;
|
||||
|
||||
public const int DrawRingCapacity = 4096;
|
||||
public const int DrawEntryDoubles = 24;
|
||||
@@ -77,6 +81,8 @@ namespace LuaScript.Engine
|
||||
public const int CbRz = 5;
|
||||
public const int CbAlpha = 6;
|
||||
public const int CbLayer = 7;
|
||||
public const int CbVolume = 8;
|
||||
public const int CbLength = 9;
|
||||
|
||||
public static long DrawRingOffset(int stringCapacity) => StringParamsOffset + stringCapacity;
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.2</Version>
|
||||
<Version>1.18.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -9,5 +9,10 @@ namespace LuaScript
|
||||
double Zoom,
|
||||
double Rz,
|
||||
double Alpha,
|
||||
int Layer);
|
||||
int Layer,
|
||||
int Length,
|
||||
double Volume,
|
||||
string Character,
|
||||
string Text,
|
||||
string Kind);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class AviUtlAudioConverterTests
|
||||
{
|
||||
private static float[] Interleave(double[] left, double[] right)
|
||||
{
|
||||
var data = new float[left.Length * 2];
|
||||
for (int i = 0; i < left.Length; i++)
|
||||
{
|
||||
data[i * 2] = (float)left[i];
|
||||
data[i * 2 + 1] = (float)right[i];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RequiredFrames_MatchesTypeWindows()
|
||||
{
|
||||
Assert.Equal(16, AviUtlAudioConverter.RequiredFrames("pcm", 16));
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 0));
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, AviUtlAudioConverter.RequiredFrames("pcm", 99999));
|
||||
Assert.Equal(AviUtlAudioConverter.SpectrumWindow, AviUtlAudioConverter.RequiredFrames("spectrum", 32));
|
||||
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier", 0));
|
||||
Assert.Equal(AviUtlAudioConverter.FourierWindow, AviUtlAudioConverter.RequiredFrames("fourier.l", 0));
|
||||
Assert.Equal(0, AviUtlAudioConverter.RequiredFrames("unknown", 8));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_ScalesMonoMixTo16BitRange()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.5d, -1d, 0d], [0.5d, -1d, 1d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("pcm", data, 3, 3, dest);
|
||||
|
||||
Assert.Equal(3, count);
|
||||
Assert.Equal(16384d, dest[0]);
|
||||
Assert.Equal(-32768d, dest[1]);
|
||||
Assert.Equal(16384d, dest[2]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_SelectsChannelBySuffix()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.25d, 0.25d], [-0.5d, -0.5d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
converter.Convert("pcm.l", data, 2, 2, dest);
|
||||
Assert.Equal(8192d, dest[0]);
|
||||
|
||||
converter.Convert("pcm.r", data, 2, 2, dest);
|
||||
Assert.Equal(-16384d, dest[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Pcm_ReturnsFewerWhenSourceIsShort()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var data = Interleave([0.1d, 0.2d], [0.1d, 0.2d]);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("pcm", data, 2, 100, dest);
|
||||
|
||||
Assert.Equal(2, count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Spectrum_PeaksInBandContainingSineFrequency()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
const int frames = AviUtlAudioConverter.SpectrumWindow;
|
||||
const int cycle = 64;
|
||||
var mono = new double[frames];
|
||||
for (int i = 0; i < frames; i++)
|
||||
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||
var data = Interleave(mono, mono);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("spectrum", data, frames, 32, dest);
|
||||
|
||||
Assert.Equal(32, count);
|
||||
int expectedBand = cycle * 32 / AviUtlAudioConverter.SpectrumBins;
|
||||
int peakBand = 0;
|
||||
for (int i = 1; i < count; i++)
|
||||
{
|
||||
if (dest[i] > dest[peakBand])
|
||||
peakBand = i;
|
||||
}
|
||||
Assert.Equal(expectedBand, peakBand);
|
||||
Assert.True(dest[peakBand] > 1000d);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fourier_ReturnsNormalizedMagnitudes()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
const int frames = AviUtlAudioConverter.FourierWindow;
|
||||
const int cycle = 8;
|
||||
var mono = new double[frames];
|
||||
for (int i = 0; i < frames; i++)
|
||||
mono[i] = Math.Sin(2d * Math.PI * i * cycle / frames);
|
||||
var data = Interleave(mono, mono);
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
int count = converter.Convert("fourier", data, frames, 0, dest);
|
||||
|
||||
Assert.Equal(AviUtlAudioConverter.MaxSamples, count);
|
||||
int peak = 0;
|
||||
for (int i = 1; i < count; i++)
|
||||
{
|
||||
if (dest[i] > dest[peak])
|
||||
peak = i;
|
||||
}
|
||||
Assert.Equal(cycle - 1, peak);
|
||||
Assert.Equal(1d, dest[peak], 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownTypeOrEmptySource_YieldsZero()
|
||||
{
|
||||
var converter = new AviUtlAudioConverter();
|
||||
var dest = new double[AviUtlAudioConverter.MaxSamples];
|
||||
|
||||
Assert.Equal(0, converter.Convert("waveform", new float[8], 4, 4, dest));
|
||||
Assert.Equal(0, converter.Convert("pcm", [], 0, 4, dest));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,8 +48,8 @@ namespace LuaScript.Tests
|
||||
"obj.getpixeldata", "obj.putpixeldata", "obj.rand", "obj.load",
|
||||
"obj.setfont", "obj.draw", "obj.drawpoly", "obj.copybuffer",
|
||||
"obj.pixelshader",
|
||||
"obj.getvalue", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.getinfo"
|
||||
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo"
|
||||
]),
|
||||
("math", [
|
||||
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineGetAudioTests
|
||||
{
|
||||
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()
|
||||
{
|
||||
return new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 2,
|
||||
ImageHeight = 2,
|
||||
Framerate = 30,
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_FillsBufferTableFromLoader()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedFile = null;
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
ctx.AudioLoader = (file, type, size) =>
|
||||
{
|
||||
capturedFile = file;
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (3, 44100, [1.5d, -2.5d, 3d]);
|
||||
};
|
||||
|
||||
engine.Execute(
|
||||
"local buf = {}\n" +
|
||||
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 3)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]\n" +
|
||||
"obj.oy = buf[3]",
|
||||
ctx);
|
||||
|
||||
Assert.Equal("audiobuffer", capturedFile);
|
||||
Assert.Equal("pcm", capturedType);
|
||||
Assert.Equal(3, capturedSize);
|
||||
Assert.Equal(3d, ctx.X);
|
||||
Assert.Equal(44100d, ctx.Y);
|
||||
Assert.Equal(1.5d, ctx.Z);
|
||||
Assert.Equal(-2.5d, ctx.Ox);
|
||||
Assert.Equal(3d, ctx.Oy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_NilBuffer_ReturnsTableAsThirdValue()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.AudioLoader = (_, type, _) => (2, 48000, [7d, 8d]);
|
||||
|
||||
engine.Execute(
|
||||
"local n, rate, buf = obj.getaudio(nil, 'C:/test.wav', 'spectrum.r', 2)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(2d, ctx.X);
|
||||
Assert.Equal(48000d, ctx.Y);
|
||||
Assert.Equal(7d, ctx.Z);
|
||||
Assert.Equal(8d, ctx.Ox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_DefaultsTypeToPcm()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
ctx.AudioLoader = (_, type, size) =>
|
||||
{
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (0, 48000, []);
|
||||
};
|
||||
|
||||
engine.Execute("obj.x = obj.getaudio({}, 'audiobuffer')", ctx);
|
||||
|
||||
Assert.Equal("pcm", capturedType);
|
||||
Assert.Equal(0, capturedSize);
|
||||
Assert.Equal(0d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_WithoutLoader_ReturnsZero()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
engine.Execute(
|
||||
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = #buf\n" +
|
||||
"obj.ox = obj.getaudio({}, 7)",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(0d, ctx.X);
|
||||
Assert.Equal(0d, ctx.Y);
|
||||
Assert.Equal(0d, ctx.Z);
|
||||
Assert.Equal(0d, ctx.Ox);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_ClampsCountToDataLength()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.AudioLoader = (_, _, _) => (10, 48000, [5d]);
|
||||
|
||||
engine.Execute(
|
||||
"local n, _, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 10)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = #buf",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(1d, ctx.X);
|
||||
Assert.Equal(1d, ctx.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +130,45 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(1d, ctx.Oy);
|
||||
}
|
||||
|
||||
private sealed class StubResolver : ISceneObjectResolver
|
||||
{
|
||||
private readonly SceneObjectInfo _info;
|
||||
public StubResolver(SceneObjectInfo info) => _info = info;
|
||||
public bool TryResolve(string tag, int timelineFrame, out SceneObjectInfo info)
|
||||
{
|
||||
if (tag == _info.Tag)
|
||||
{
|
||||
info = _info;
|
||||
return true;
|
||||
}
|
||||
info = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetObjectExposesItemMetadata()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
var info = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7, 120, 75d, "reimu", "hello", "VoiceItem");
|
||||
ctx.ResolverProvider = () => new StubResolver(info);
|
||||
|
||||
engine.Execute(
|
||||
"local o = obj.getobject('a')\n" +
|
||||
"obj.x = o.volume\n" +
|
||||
"obj.y = o.length\n" +
|
||||
"obj.z = (o.character == 'reimu') and 1 or 0\n" +
|
||||
"obj.ox = (o.text == 'hello') and 1 or 0\n" +
|
||||
"obj.oy = (o.kind == 'VoiceItem') and 1 or 0", ctx);
|
||||
|
||||
Assert.Equal(75d, ctx.X);
|
||||
Assert.Equal(120d, ctx.Y);
|
||||
Assert.Equal(1d, ctx.Z);
|
||||
Assert.Equal(1d, ctx.Ox);
|
||||
Assert.Equal(1d, ctx.Oy);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ObjectWritesFlowBackToContext()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineSceneBrushLoadTests
|
||||
{
|
||||
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()
|
||||
{
|
||||
return new AviUtlScriptContext
|
||||
{
|
||||
ImageWidth = 6,
|
||||
ImageHeight = 4,
|
||||
Time = 1.5,
|
||||
Framerate = 30,
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_ReplacesBufferAndUpdatesObjDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedTime = -1;
|
||||
var rendered = new byte[2 * 3 * 4];
|
||||
ctx.SceneImageLoader = (name, time) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedTime = time;
|
||||
return (rendered, 2, 3);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ', 4.25); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.Equal("サブ", capturedName);
|
||||
Assert.Equal(4.25d, capturedTime);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Same(rendered, ctx.GetPixelBuffer());
|
||||
Assert.Equal(2, ctx.ImageWidth);
|
||||
Assert.Equal(3, ctx.ImageHeight);
|
||||
Assert.Equal(2d, ctx.X);
|
||||
Assert.Equal(3d, ctx.Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_DefaultsTimeToObjTime()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedTime = -1;
|
||||
ctx.SceneImageLoader = (_, time) =>
|
||||
{
|
||||
capturedTime = time;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ')", ctx);
|
||||
|
||||
Assert.Equal(1.5d, capturedTime);
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_WithoutLoader_IsNoOp()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
engine.Execute("obj.load('scene', 'サブ'); obj.x = obj.w", ctx);
|
||||
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
Assert.Equal(6d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_ReplacesBufferWithRequestedSize()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
var rendered = new byte[8 * 5 * 4];
|
||||
ctx.BrushImageLoader = (name, w, h, _) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return (rendered, 8, 5);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('brush', '縞模様', 8, 5); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(8d, capturedW);
|
||||
Assert.Equal(5d, capturedH);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
Assert.Same(rendered, ctx.GetPixelBuffer());
|
||||
Assert.Equal(8d, ctx.X);
|
||||
Assert.Equal(5d, ctx.Y);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_DefaultsSizeToObjectDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
ctx.BrushImageLoader = (_, w, h, _) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.load('brush', '市松模様')", ctx);
|
||||
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_PassesParameterPairs()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
List<KeyValuePair<string, object>>? captured = null;
|
||||
var rendered = new byte[6 * 4 * 4];
|
||||
ctx.BrushImageLoader = (name, w, h, arguments) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return (rendered, 6, 4);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('縞模様', '色1', 0xff0000, 'ズーム', 250, '有効', true, 'ラベル', 'abc')", ctx);
|
||||
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(4, captured!.Count);
|
||||
Assert.Equal(new KeyValuePair<string, object>("色1", (double)0xff0000), captured[0]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ズーム", 250d), captured[1]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("有効", true), captured[2]);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ラベル", "abc"), captured[3]);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_AcceptsLeadingSizeBeforePairs()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
List<KeyValuePair<string, object>>? captured = null;
|
||||
ctx.BrushImageLoader = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('市松模様', 320, 240, 'ズーム', 50)", ctx);
|
||||
|
||||
Assert.Equal(320d, capturedW);
|
||||
Assert.Equal(240d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(new KeyValuePair<string, object>("ズーム", 50d), Assert.Single(captured!));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_WithoutPairs_UsesObjectDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
int capturedCount = -1;
|
||||
ctx.BrushImageLoader = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
capturedCount = arguments.Count;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
engine.Execute("obj.brush('市松模様')", ctx);
|
||||
|
||||
Assert.Equal(6d, capturedW);
|
||||
Assert.Equal(4d, capturedH);
|
||||
Assert.Equal(0, capturedCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_FailureKeepsCurrentImage()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext();
|
||||
|
||||
ctx.BrushImageLoader = (_, _, _, _) => ([], 0, 0);
|
||||
|
||||
engine.Execute("obj.load('brush', '不明'); obj.x = obj.w; obj.y = obj.h", ctx);
|
||||
|
||||
Assert.False(ctx.BufferReplaced);
|
||||
Assert.Equal(6d, ctx.X);
|
||||
Assert.Equal(4d, ctx.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,11 @@ namespace LuaScript.Tests
|
||||
|
||||
private readonly LuaJitWorker _worker = new(NativeDir, ScriptPath);
|
||||
|
||||
private Func<string, double, (byte[] buffer, int w, int h)> _loadScene = (_, _) => ([], 0, 0);
|
||||
private Func<string, double, double, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string, object>>, (byte[] buffer, int w, int h)> _loadBrush = (_, _, _, _) => ([], 0, 0);
|
||||
private Func<string, SceneValue> _sceneGet = _ => SceneValue.Nil;
|
||||
private Action<string, SceneValue> _sceneSet = (_, _) => { };
|
||||
private Func<string, string, int, (int Count, int Rate, double[] Data)> _loadAudio = (_, _, _) => (0, 0, []);
|
||||
private PixelShaderInvoke? _runPixelShader;
|
||||
|
||||
public void Dispose() => _worker.Dispose();
|
||||
@@ -70,8 +73,9 @@ namespace LuaScript.Tests
|
||||
System.Runtime.InteropServices.Marshal.Copy(uploaded, 0, address, uploaded.Length);
|
||||
},
|
||||
width, height, timeoutMs,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, addEffect, addDraw, setAnchor,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, _loadScene, _loadBrush, addEffect, addDraw, setAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
|
||||
|
||||
@@ -106,8 +110,9 @@ namespace LuaScript.Tests
|
||||
observedCapacity = capacity;
|
||||
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, address, pixels.Length);
|
||||
},
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, _loadScene, _loadBrush, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
out _, out _, out _, out _, out string? error);
|
||||
|
||||
@@ -523,7 +528,7 @@ namespace LuaScript.Tests
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7, 120, 75d, "reimu", "hello", "VoiceItem");
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
tag == "a" && frame == 5 ? resolved : null;
|
||||
|
||||
@@ -531,7 +536,11 @@ namespace LuaScript.Tests
|
||||
"local o = obj.getobject(\"a\", 5) " +
|
||||
"obj.x = o.x obj.y = o.y obj.z = o.z " +
|
||||
"obj.zoom = o.zoom obj.rz = o.rz obj.alpha = o.alpha " +
|
||||
"obj.sx = o.sy obj.rzr = o.rzr";
|
||||
"obj.sx = o.sy obj.rzr = o.rzr " +
|
||||
"obj.ox = o.volume obj.oy = o.length " +
|
||||
"obj.oz = (o.character == \"reimu\") and 1 or 0 " +
|
||||
"obj.rx = (o.text == \"hello\") and 1 or 0 " +
|
||||
"obj.ry = (o.kind == \"VoiceItem\") and 1 or 0";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, resolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
@@ -544,6 +553,11 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(200d, fields[NativeProtocol.Alpha]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
|
||||
Assert.Equal(75d, fields[NativeProtocol.Ox]);
|
||||
Assert.Equal(120d, fields[NativeProtocol.Oy]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Oz]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Rx]);
|
||||
Assert.Equal(1d, fields[NativeProtocol.Ry]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -557,7 +571,7 @@ namespace LuaScript.Tests
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
{
|
||||
calls++;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0) : null;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0, 0, 0d, "", "", "") : null;
|
||||
};
|
||||
|
||||
const string script =
|
||||
@@ -1027,6 +1041,215 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(frame, newPixels!.AsSpan(0, frame.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_RoundTripsNameAndTime()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int sw = 2, sh = 2;
|
||||
var rendered = new byte[sw * sh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 13 + 1) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedTime = -1;
|
||||
_loadScene = (name, time) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedTime = time;
|
||||
return (rendered, sw, sh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('scene', 'サブシーン', 2.5)",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("サブシーン", capturedName);
|
||||
Assert.Equal(2.5d, capturedTime);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(sw, rw);
|
||||
Assert.Equal(sh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadScene_DefaultsTimeToObjTime_AndKeepsImageOnFailure()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedTime = -1;
|
||||
_loadScene = (_, time) =>
|
||||
{
|
||||
capturedTime = time;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 1.25d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('scene', 'missing') obj.x = obj.w",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1.25d, capturedTime);
|
||||
Assert.False(dirty);
|
||||
Assert.False(bufferReplaced);
|
||||
Assert.Equal(2d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_RoundTripsNameAndSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int bw = 3, bh = 2;
|
||||
var rendered = new byte[bw * bh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 11 + 2) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
_loadBrush = (name, w, h, _) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return (rendered, bw, bh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('brush', '縞模様', 3, 2)",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(3d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(bw, rw);
|
||||
Assert.Equal(bh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_RoundTripsPairsAndDefaultSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int bw = 2, bh = 2;
|
||||
var rendered = new byte[bw * bh * 4];
|
||||
for (int i = 0; i < rendered.Length; i++)
|
||||
rendered[i] = (byte)((i * 7 + 4) & 0xFF);
|
||||
|
||||
string? capturedName = null;
|
||||
double capturedW = -1, capturedH = -1;
|
||||
System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, object>>? captured = null;
|
||||
_loadBrush = (name, w, h, arguments) =>
|
||||
{
|
||||
capturedName = name;
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
captured = [.. arguments];
|
||||
return (rendered, bw, bh);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 2 * 4];
|
||||
var fields = Fields(4, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.brush('縞模様', '色1', 0xff0000, '有効', true, 'ラベル', 'abc')",
|
||||
fields, NoStringParams, () => pixels, 4, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? newPixels, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("縞模様", capturedName);
|
||||
Assert.Equal(4d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.NotNull(captured);
|
||||
Assert.Equal(3, captured!.Count);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("色1", (double)0xff0000), captured[0]);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("有効", true), captured[1]);
|
||||
Assert.Equal(new System.Collections.Generic.KeyValuePair<string, object>("ラベル", "abc"), captured[2]);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(bw, rw);
|
||||
Assert.Equal(bh, rh);
|
||||
Assert.NotNull(newPixels);
|
||||
Assert.Equal(rendered, newPixels!.AsSpan(0, rendered.Length).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Brush_RoundTripsLeadingSize()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
int capturedCount = -1;
|
||||
_loadBrush = (_, w, h, arguments) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
capturedCount = arguments.Count;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.brush('市松模様', 320, 240, 'ズーム', 50)",
|
||||
fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(320d, capturedW);
|
||||
Assert.Equal(240d, capturedH);
|
||||
Assert.Equal(1, capturedCount);
|
||||
Assert.False(dirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadBrush_DefaultsSizeToObjectDimensions()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
double capturedW = -1, capturedH = -1;
|
||||
_loadBrush = (_, w, h, _) =>
|
||||
{
|
||||
capturedW = w;
|
||||
capturedH = h;
|
||||
return ([], 0, 0);
|
||||
};
|
||||
|
||||
var pixels = new byte[4 * 2 * 4];
|
||||
var fields = Fields(4, 2, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.load('brush', '市松模様')",
|
||||
fields, NoStringParams, () => pixels, 4, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(4d, capturedW);
|
||||
Assert.Equal(2d, capturedH);
|
||||
Assert.False(dirty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetValue_ReturnsObjFields()
|
||||
{
|
||||
@@ -1047,6 +1270,79 @@ namespace LuaScript.Tests
|
||||
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_RoundTripsThroughCallback()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
string? capturedFile = null;
|
||||
string? capturedType = null;
|
||||
int capturedSize = -1;
|
||||
_loadAudio = (file, type, size) =>
|
||||
{
|
||||
capturedFile = file;
|
||||
capturedType = type;
|
||||
capturedSize = size;
|
||||
return (4, 48000, [10d, -20d, 30.5d, 40d]);
|
||||
};
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
const string script =
|
||||
"local buf = {}\n" +
|
||||
"local n, rate = obj.getaudio(buf, 'audiobuffer', 'pcm', 4)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = buf[1]\n" +
|
||||
"obj.ox = buf[2]\n" +
|
||||
"obj.oy = buf[3]\n" +
|
||||
"obj.oz = buf[4]\n" +
|
||||
"local n2, rate2, buf2 = obj.getaudio(nil, 'C:/test.wav', 'spectrum.l', 2)\n" +
|
||||
"obj.sx = n2\n" +
|
||||
"obj.sy = buf2[1]";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal("C:/test.wav", capturedFile);
|
||||
Assert.Equal("spectrum.l", capturedType);
|
||||
Assert.Equal(2, capturedSize);
|
||||
Assert.Equal(4d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(48000d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(-20d, fields[NativeProtocol.Ox]);
|
||||
Assert.Equal(30.5d, fields[NativeProtocol.Oy]);
|
||||
Assert.Equal(40d, fields[NativeProtocol.Oz]);
|
||||
Assert.Equal(4d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(10d, fields[NativeProtocol.Sy]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetAudio_FailureYieldsZeroCount()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
_loadAudio = (_, _, _) => throw new InvalidOperationException();
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
const string script =
|
||||
"local n, rate, buf = obj.getaudio(nil, 'audiobuffer', 'pcm', 8)\n" +
|
||||
"obj.x = n\n" +
|
||||
"obj.y = rate\n" +
|
||||
"obj.z = #buf\n" +
|
||||
"local n2 = obj.getaudio({}, 7)\n" +
|
||||
"obj.ox = n2";
|
||||
|
||||
bool ok = RunWorker(script, fields, NoStringParams, () => pixels, 2, 2, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor, out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(0d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(0d, fields[NativeProtocol.Ox]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CopyBuffer_TmpSaveRestore_RoundTripsPixels()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using LuaScript.Compat;
|
||||
using YukkuriMovieMaker.ItemEditor;
|
||||
using YukkuriMovieMaker.Player.Audio.Effects;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.FileSource;
|
||||
using YukkuriMovieMaker.Project;
|
||||
using YukkuriMovieMaker.Project.Items;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class AudioSampleProvider : IDisposable
|
||||
{
|
||||
private readonly AviUtlAudioConverter _converter = new();
|
||||
private readonly double[] _data = new double[AviUtlAudioConverter.MaxSamples];
|
||||
private float[] _readBuffer = [];
|
||||
|
||||
private IAudioFileSource? _fileSource;
|
||||
private string _fileSourcePath = string.Empty;
|
||||
|
||||
private IAudioStream? _sceneSource;
|
||||
private Scene? _sceneSourceScene;
|
||||
|
||||
private IAudioStream? _itemSource;
|
||||
private IAudioItem? _itemSourceItem;
|
||||
private Scene? _itemSourceScene;
|
||||
private string? _itemSourceFile;
|
||||
|
||||
public double[] Data => _data;
|
||||
|
||||
public (int Count, int Rate) ReadFile(string path, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_fileSource is null || !string.Equals(path, _fileSourcePath, StringComparison.Ordinal))
|
||||
{
|
||||
_fileSource?.Dispose();
|
||||
_fileSource = null;
|
||||
_fileSource = AudioFileSourceFactory.Create(path, 0);
|
||||
_fileSourcePath = path;
|
||||
}
|
||||
|
||||
var source = _fileSource;
|
||||
if (source is null || source.Hz <= 0)
|
||||
return (0, 0);
|
||||
|
||||
int floats = EnsureReadBuffer(type, size);
|
||||
if (floats <= 0)
|
||||
return (0, source.Hz);
|
||||
|
||||
source.Seek(TimeSpan.FromSeconds(Math.Max(0d, time)));
|
||||
int total = 0;
|
||||
while (total < floats)
|
||||
{
|
||||
int read = source.Read(_readBuffer, total, floats - total);
|
||||
if (read <= 0)
|
||||
break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
return (_converter.Convert(type, _readBuffer, total / 2, size, _data), source.Hz);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public (int Count, int Rate) ReadScene(Scene? scene, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (scene is null)
|
||||
return (0, 0);
|
||||
|
||||
if (_sceneSource is null || !ReferenceEquals(scene, _sceneSourceScene))
|
||||
{
|
||||
_sceneSource?.Dispose();
|
||||
_sceneSource = null;
|
||||
scene.TryCreateAudioSource(out _sceneSource);
|
||||
_sceneSourceScene = scene;
|
||||
}
|
||||
|
||||
return ReadStream(_sceneSource, time, type, size);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public (int Count, int Rate) ReadItem(IAudioItem? item, Scene? scene, double time, string type, int size)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (item is null || scene is null)
|
||||
return (0, 0);
|
||||
|
||||
string? file = item switch
|
||||
{
|
||||
AudioItem audio => audio.FilePath,
|
||||
VideoItem video => video.FilePath,
|
||||
_ => null,
|
||||
};
|
||||
if (_itemSource is null ||
|
||||
!ReferenceEquals(item, _itemSourceItem) ||
|
||||
!ReferenceEquals(scene, _itemSourceScene) ||
|
||||
!string.Equals(file, _itemSourceFile, StringComparison.Ordinal))
|
||||
{
|
||||
_itemSource?.Dispose();
|
||||
_itemSource = null;
|
||||
_itemSource = CreateItemSource(item, scene) ?? CreateRawItemSource(item, scene);
|
||||
_itemSourceItem = item;
|
||||
_itemSourceScene = scene;
|
||||
_itemSourceFile = file;
|
||||
}
|
||||
|
||||
return ReadStream(_itemSource, time, type, size);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return (0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private (int Count, int Rate) ReadStream(IAudioStream? source, double time, string type, int size)
|
||||
{
|
||||
if (source is null || source.Hz <= 0)
|
||||
return (0, 0);
|
||||
|
||||
int floats = EnsureReadBuffer(type, size);
|
||||
if (floats <= 0)
|
||||
return (0, source.Hz);
|
||||
|
||||
source.Seek(TimeSpan.FromSeconds(Math.Max(0d, time)));
|
||||
int total = 0;
|
||||
while (total < floats)
|
||||
{
|
||||
int read = source.Read(_readBuffer, total, floats - total);
|
||||
if (read <= 0)
|
||||
break;
|
||||
total += read;
|
||||
}
|
||||
|
||||
return (_converter.Convert(type, _readBuffer, total / 2, size, _data), source.Hz);
|
||||
}
|
||||
|
||||
private int EnsureReadBuffer(string type, int size)
|
||||
{
|
||||
int frames = AviUtlAudioConverter.RequiredFrames(type, size);
|
||||
if (frames <= 0)
|
||||
return 0;
|
||||
int floats = frames * 2;
|
||||
if (_readBuffer.Length < floats)
|
||||
_readBuffer = new float[floats];
|
||||
return floats;
|
||||
}
|
||||
|
||||
private static IAudioStream? CreateItemSource(IAudioItem item, Scene scene)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreateEditorItemSource(item, scene);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static IAudioStream CreateEditorItemSource(IAudioItem item, Scene scene) =>
|
||||
new EffectedItemSourceForEditorInfo(item, item.AudioEffects, scene);
|
||||
|
||||
private static IAudioStream? CreateRawItemSource(IAudioItem item, Scene scene)
|
||||
{
|
||||
try
|
||||
{
|
||||
return item.CreateAudioSource(scene);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_fileSource?.Dispose();
|
||||
_fileSource = null;
|
||||
_sceneSource?.Dispose();
|
||||
_sceneSource = null;
|
||||
_sceneSourceScene = null;
|
||||
_itemSource?.Dispose();
|
||||
_itemSource = null;
|
||||
_itemSourceItem = null;
|
||||
_itemSourceScene = null;
|
||||
_itemSourceFile = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin.Brush;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class BrushImageRenderer(IGraphicsDevicesAndContext devices) : IDisposable
|
||||
{
|
||||
private const int MaxDimension = 8192;
|
||||
|
||||
private sealed class Entry(IBrushParameter parameter, IBrushSource source)
|
||||
{
|
||||
public IBrushParameter Parameter { get; } = parameter;
|
||||
public IBrushSource Source { get; } = source;
|
||||
public string[] AppliedKeys { get; set; } = [];
|
||||
}
|
||||
|
||||
private readonly Dictionary<string, Entry?> _sources = new(StringComparer.Ordinal);
|
||||
private GraphicsDevicesAndContext? _ctx;
|
||||
private PixelBufferManager? _pixels;
|
||||
|
||||
public bool TryRender(
|
||||
TimelineItemSourceDescription desc,
|
||||
string name,
|
||||
int width,
|
||||
int height,
|
||||
IReadOnlyList<KeyValuePair<string, object>> arguments,
|
||||
out byte[] pixels,
|
||||
out int outWidth,
|
||||
out int outHeight)
|
||||
{
|
||||
pixels = [];
|
||||
outWidth = 0;
|
||||
outHeight = 0;
|
||||
|
||||
if (width <= 0 || height <= 0 || width > MaxDimension || height > MaxDimension)
|
||||
return false;
|
||||
|
||||
if (!_sources.TryGetValue(name, out var entry))
|
||||
{
|
||||
entry = CreateEntry(name);
|
||||
_sources[name] = entry;
|
||||
}
|
||||
if (entry is null)
|
||||
return false;
|
||||
|
||||
if (!KeysMatch(entry.AppliedKeys, arguments))
|
||||
{
|
||||
entry.Source.Dispose();
|
||||
entry = CreateEntry(name);
|
||||
_sources[name] = entry;
|
||||
if (entry is null)
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (arguments.Count > 0)
|
||||
{
|
||||
ParameterBinder.ApplyArguments(entry.Parameter, arguments);
|
||||
if (entry.AppliedKeys.Length != arguments.Count)
|
||||
entry.AppliedKeys = new string[arguments.Count];
|
||||
for (int i = 0; i < arguments.Count; i++)
|
||||
entry.AppliedKeys[i] = arguments[i].Key;
|
||||
}
|
||||
|
||||
entry.Source.Update(desc);
|
||||
_pixels ??= new PixelBufferManager(_ctx!);
|
||||
pixels = _pixels.LoadBrushPixels(entry.Source.Brush, width, height);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_sources.Remove(name);
|
||||
entry.Source.Dispose();
|
||||
pixels = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
outWidth = width;
|
||||
outHeight = height;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool KeysMatch(string[] appliedKeys, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (appliedKeys.Length != arguments.Count)
|
||||
return false;
|
||||
for (int i = 0; i < appliedKeys.Length; i++)
|
||||
{
|
||||
if (!string.Equals(appliedKeys[i], arguments[i].Key, StringComparison.Ordinal))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Entry? CreateEntry(string name)
|
||||
{
|
||||
foreach (var plugin in BrushFactory.Plugins)
|
||||
{
|
||||
if (!string.Equals(plugin.Name, name, StringComparison.Ordinal))
|
||||
continue;
|
||||
_ctx ??= new GraphicsDevicesAndContext(devices);
|
||||
var parameter = plugin.CreateBrushParameter();
|
||||
return new Entry(parameter, parameter.CreateBrush(_ctx));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var entry in _sources.Values)
|
||||
entry?.Source.Dispose();
|
||||
_sources.Clear();
|
||||
_pixels?.Dispose();
|
||||
_ctx?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using LuaScript.Compat;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class ParameterBinder
|
||||
{
|
||||
public static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> s_propertyCache = [];
|
||||
|
||||
public static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
|
||||
public static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||
{
|
||||
lock (s_propertyCache)
|
||||
{
|
||||
if (s_propertyCache.TryGetValue(type, out var cached))
|
||||
return cached;
|
||||
}
|
||||
|
||||
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||
if (!usable)
|
||||
continue;
|
||||
|
||||
map.TryAdd(Normalize(property.Name), property);
|
||||
try
|
||||
{
|
||||
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||
if (!string.IsNullOrWhiteSpace(display))
|
||||
map.TryAdd(Normalize(display), property);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
lock (s_propertyCache)
|
||||
{
|
||||
s_propertyCache[type] = map;
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public static void ApplyArguments(object model, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out var property))
|
||||
continue;
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, Identity);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetValue(object model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||
{
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (type == typeof(Animation))
|
||||
{
|
||||
if (property.GetValue(model) is Animation animation)
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
property.SetValue(model, ToBool(value));
|
||||
return;
|
||||
}
|
||||
if (type.IsEnum)
|
||||
{
|
||||
property.SetValue(model, ToEnum(type, value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(Color))
|
||||
{
|
||||
property.SetValue(model, ToColor(value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
property.SetValue(model, value?.ToString());
|
||||
}
|
||||
|
||||
private static double ToDouble(object value) => value switch
|
||||
{
|
||||
double d => d,
|
||||
bool b => b ? 1d : 0d,
|
||||
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||
_ => 0d,
|
||||
};
|
||||
|
||||
private static bool ToBool(object value) => value switch
|
||||
{
|
||||
bool b => b,
|
||||
double d => d != 0d,
|
||||
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object ToEnum(Type type, object value)
|
||||
{
|
||||
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||
return parsed;
|
||||
return Enum.ToObject(type, (int)ToDouble(value));
|
||||
}
|
||||
|
||||
private static Color ToColor(object value)
|
||||
{
|
||||
int rgb = (int)ToDouble(value);
|
||||
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,32 @@ namespace LuaScript
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
RenderToStaging(input, bounds);
|
||||
return ReadStagingPixels(width, height);
|
||||
}
|
||||
|
||||
public byte[] LoadBrushPixels(ID2D1Brush brush, int width, int height)
|
||||
{
|
||||
EnsureBitmaps(width, height);
|
||||
|
||||
var dc = _ctx.DeviceContext;
|
||||
var rt = (ID2D1RenderTarget)dc;
|
||||
using var savedTarget = dc.Target;
|
||||
|
||||
dc.Target = _renderTarget;
|
||||
dc.BeginDraw();
|
||||
dc.Clear(null);
|
||||
rt.Transform = Matrix3x2.CreateTranslation(width / 2f, height / 2f);
|
||||
rt.FillRectangle(new RawRectF(-width / 2f, -height / 2f, width / 2f, height / 2f), brush);
|
||||
rt.Transform = Matrix3x2.Identity;
|
||||
dc.EndDraw();
|
||||
dc.Target = savedTarget;
|
||||
|
||||
_stagingBitmap!.CopyFromBitmap(_renderTarget!);
|
||||
return ReadStagingPixels(width, height);
|
||||
}
|
||||
|
||||
private unsafe byte[] ReadStagingPixels(int width, int height)
|
||||
{
|
||||
var mapped = _stagingBitmap!.Map(MapOptions.Read);
|
||||
try
|
||||
{
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Windows.Media;
|
||||
using Vortice.Direct2D1;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
@@ -23,11 +19,8 @@ namespace LuaScript
|
||||
public required int RequestIndex;
|
||||
}
|
||||
|
||||
private static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
private static Dictionary<string, Type>? _typeRegistry;
|
||||
private static Dictionary<string, Type>? _nameRegistry;
|
||||
private static readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _propertyCache = [];
|
||||
|
||||
private readonly IGraphicsDevicesAndContext _devices;
|
||||
private readonly List<Node> _nodes = [];
|
||||
@@ -190,34 +183,29 @@ namespace LuaScript
|
||||
map.TryAdd(Normalize(key), type);
|
||||
}
|
||||
|
||||
private static string Normalize(string value) => value.Trim().ToLowerInvariant();
|
||||
private static string Normalize(string value) => ParameterBinder.Normalize(value);
|
||||
|
||||
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
if (arguments.Count == 0)
|
||||
return;
|
||||
|
||||
var properties = GetProperties(model.GetType());
|
||||
if (mapping is null)
|
||||
{
|
||||
ParameterBinder.ApplyArguments(model, arguments);
|
||||
return;
|
||||
}
|
||||
|
||||
var properties = ParameterBinder.GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
PropertyInfo? property;
|
||||
AviUtlParameterMapping parameter;
|
||||
if (mapping is not null)
|
||||
{
|
||||
if (!mapping.TryGetParameter(key, out parameter) ||
|
||||
!properties.TryGetValue(Normalize(parameter.Property), out property))
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!properties.TryGetValue(Normalize(key), out property))
|
||||
continue;
|
||||
parameter = Identity;
|
||||
}
|
||||
if (!mapping.TryGetParameter(key, out var parameter) ||
|
||||
!properties.TryGetValue(Normalize(parameter.Property), out var property))
|
||||
continue;
|
||||
|
||||
try
|
||||
{
|
||||
SetValue(model, property, value, parameter);
|
||||
ParameterBinder.SetValue(model, property, value, parameter);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@@ -225,99 +213,6 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, PropertyInfo> GetProperties(Type type)
|
||||
{
|
||||
if (_propertyCache.TryGetValue(type, out var cached))
|
||||
return cached;
|
||||
|
||||
var map = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
|
||||
foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
|
||||
{
|
||||
if (property.GetIndexParameters().Length != 0)
|
||||
continue;
|
||||
bool usable = property.PropertyType == typeof(Animation) || property.GetSetMethod() is not null;
|
||||
if (!usable)
|
||||
continue;
|
||||
|
||||
map.TryAdd(Normalize(property.Name), property);
|
||||
try
|
||||
{
|
||||
var display = property.GetCustomAttribute<DisplayAttribute>()?.GetName();
|
||||
if (!string.IsNullOrWhiteSpace(display))
|
||||
map.TryAdd(Normalize(display), property);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
_propertyCache[type] = map;
|
||||
return map;
|
||||
}
|
||||
|
||||
private static void SetValue(IVideoEffect model, PropertyInfo property, object value, AviUtlParameterMapping parameter)
|
||||
{
|
||||
var type = property.PropertyType;
|
||||
|
||||
if (type == typeof(Animation))
|
||||
{
|
||||
if (property.GetValue(model) is Animation animation)
|
||||
animation.CopyFrom(new Animation(parameter.Transform(ToDouble(value))));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(bool))
|
||||
{
|
||||
property.SetValue(model, ToBool(value));
|
||||
return;
|
||||
}
|
||||
if (type.IsEnum)
|
||||
{
|
||||
property.SetValue(model, ToEnum(type, value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(Color))
|
||||
{
|
||||
property.SetValue(model, ToColor(value));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(short))
|
||||
{
|
||||
property.SetValue(model, Convert.ChangeType(parameter.Transform(ToDouble(value)), type, CultureInfo.InvariantCulture));
|
||||
return;
|
||||
}
|
||||
if (type == typeof(string))
|
||||
property.SetValue(model, value?.ToString());
|
||||
}
|
||||
|
||||
private static double ToDouble(object value) => value switch
|
||||
{
|
||||
double d => d,
|
||||
bool b => b ? 1d : 0d,
|
||||
string s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var r) ? r : 0d,
|
||||
_ => 0d,
|
||||
};
|
||||
|
||||
private static bool ToBool(object value) => value switch
|
||||
{
|
||||
bool b => b,
|
||||
double d => d != 0d,
|
||||
string s => s.Equals("true", StringComparison.OrdinalIgnoreCase) || s == "1",
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static object ToEnum(Type type, object value)
|
||||
{
|
||||
if (value is string s && Enum.TryParse(type, s, true, out var parsed))
|
||||
return parsed;
|
||||
return Enum.ToObject(type, (int)ToDouble(value));
|
||||
}
|
||||
|
||||
private static Color ToColor(object value)
|
||||
{
|
||||
int rgb = (int)ToDouble(value);
|
||||
return Color.FromRgb((byte)((rgb >> 16) & 0xFF), (byte)((rgb >> 8) & 0xFF), (byte)(rgb & 0xFF));
|
||||
}
|
||||
|
||||
private void DisposeNodes()
|
||||
{
|
||||
foreach (var node in _nodes)
|
||||
|
||||
@@ -138,6 +138,14 @@ namespace LuaScript
|
||||
private Func<string, string, double, bool, bool, int, (byte[] buffer, int w, int h)>? _nativeLoadText;
|
||||
private Func<string, (byte[] buffer, int w, int h)>? _nativeLoadImage;
|
||||
private Func<string, double, (byte[] buffer, int w, int h)>? _nativeLoadMovie;
|
||||
private Func<string, double, (byte[] Buffer, int Width, int Height)>? _loadSceneImage;
|
||||
private Func<string, double, double, IReadOnlyList<KeyValuePair<string, object>>, (byte[] Buffer, int Width, int Height)>? _loadBrushImage;
|
||||
private SceneImageRenderer? _sceneImageRenderer;
|
||||
private BrushImageRenderer? _brushImageRenderer;
|
||||
private bool _sceneImageLoaded;
|
||||
private Func<string, string, int, (int Count, int Rate, double[] Data)>? _loadAudio;
|
||||
private AudioSampleProvider? _audioProvider;
|
||||
private bool _audioLoaded;
|
||||
private Action<string, IReadOnlyList<KeyValuePair<string, object>>>? _nativeAddEffect;
|
||||
private Action<DrawCommand>? _nativeAddDraw;
|
||||
private Action<string, int, bool, int, double[]>? _nativeSetAnchor;
|
||||
@@ -182,6 +190,9 @@ namespace LuaScript
|
||||
_pixelShaderRunner = new PixelShaderRunner { Compositor = _bufferCompositor };
|
||||
_context.ResolverProvider = GetFrameResolver;
|
||||
_context.Compositor = _bufferCompositor;
|
||||
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
_context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -193,6 +204,9 @@ namespace LuaScript
|
||||
var context = new AviUtlScriptContext { ResolverProvider = GetFrameResolver };
|
||||
if (_bufferCompositor is not null)
|
||||
context.Compositor = _bufferCompositor;
|
||||
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -469,9 +483,19 @@ namespace LuaScript
|
||||
LuaScriptDiagnostics.Instance.Report(script, diagnostics);
|
||||
|
||||
_isFirst = false;
|
||||
if (_sceneImageLoaded)
|
||||
{
|
||||
_sceneImageLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
if (_audioLoaded)
|
||||
{
|
||||
_audioLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
_cachedKey = key;
|
||||
_cachedQueries = ctx.ObjectQueries.Count == 0 ? [] : [.. ctx.ObjectQueries];
|
||||
_cachedSceneValueQueries = ctx.SceneValueQueries.Count == 0 ? [] : [.. ctx.SceneValueQueries];
|
||||
_cachedQueries = SnapshotQueries(ctx.ObjectQueries, _cachedQueries);
|
||||
_cachedSceneValueQueries = SnapshotQueries(ctx.SceneValueQueries, _cachedSceneValueQueries);
|
||||
_cachedOutputDesc = outDesc;
|
||||
_cachedEffectOutput = effectOutput;
|
||||
|
||||
@@ -539,18 +563,49 @@ namespace LuaScript
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (item is not VisualItem visual)
|
||||
if (item is not IVideoItem video)
|
||||
continue;
|
||||
var tag = item.Remark;
|
||||
if (string.IsNullOrEmpty(tag))
|
||||
continue;
|
||||
|
||||
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, visual));
|
||||
var (character, text, kind, volume) = ExtractItemMetadata(item);
|
||||
entries.Add(new SceneObjectResolver.Entry(tag, item.Frame, item.Length, item.Layer, video, volume, character, text, kind));
|
||||
}
|
||||
|
||||
return new SceneObjectResolver([.. entries], desc.FPS);
|
||||
}
|
||||
|
||||
private static (string Character, string Text, string Kind, Animation? Volume) ExtractItemMetadata(IItem item)
|
||||
{
|
||||
string character = string.Empty;
|
||||
string text = string.Empty;
|
||||
string kind = string.Empty;
|
||||
Animation? volume = null;
|
||||
try
|
||||
{
|
||||
kind = item.GetType().Name;
|
||||
switch (item)
|
||||
{
|
||||
case VoiceItem voice:
|
||||
character = voice.CharacterName ?? string.Empty;
|
||||
text = voice.Serif ?? string.Empty;
|
||||
volume = voice.Volume;
|
||||
break;
|
||||
case TextItem textItem:
|
||||
text = textItem.Text ?? string.Empty;
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
character = string.Empty;
|
||||
text = string.Empty;
|
||||
volume = null;
|
||||
}
|
||||
return (character, text, kind, volume);
|
||||
}
|
||||
|
||||
private static bool SceneValuesMatch(SceneValueQuery[] queries, SceneSharedValues values, long generation)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -561,6 +616,17 @@ namespace LuaScript
|
||||
return true;
|
||||
}
|
||||
|
||||
private static T[] SnapshotQueries<T>(IReadOnlyList<T> source, T[] existing)
|
||||
{
|
||||
int count = source.Count;
|
||||
if (count == 0)
|
||||
return [];
|
||||
var target = existing.Length == count ? existing : new T[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
target[i] = source[i];
|
||||
return target;
|
||||
}
|
||||
|
||||
private static bool QueriesMatch(SceneObjectQuery[] queries, SceneObjectResolver resolver)
|
||||
{
|
||||
for (int i = 0; i < queries.Length; i++)
|
||||
@@ -970,6 +1036,9 @@ namespace LuaScript
|
||||
_nativeLoadText ??= NativeLoadText;
|
||||
_nativeLoadImage ??= NativeLoadImage;
|
||||
_nativeLoadMovie ??= NativeLoadMovie;
|
||||
_loadSceneImage ??= LoadSceneImage;
|
||||
_loadBrushImage ??= LoadBrushImage;
|
||||
_loadAudio ??= LoadAudio;
|
||||
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
|
||||
_nativeAddDraw ??= command => _context.AddDraw(command);
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
@@ -987,11 +1056,14 @@ namespace LuaScript
|
||||
_nativeLoadText,
|
||||
_nativeLoadImage,
|
||||
_nativeLoadMovie,
|
||||
_loadSceneImage,
|
||||
_loadBrushImage,
|
||||
_nativeAddEffect,
|
||||
_nativeAddDraw,
|
||||
_nativeSetAnchor,
|
||||
_nativeSceneGet,
|
||||
_nativeSceneSet,
|
||||
_loadAudio,
|
||||
_nativeRunPixelShader,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
@@ -1141,6 +1213,117 @@ namespace LuaScript
|
||||
return (buffer, w, h);
|
||||
}
|
||||
|
||||
private static readonly (byte[] Buffer, int Width, int Height) s_noLoadedImage = ([], 0, 0);
|
||||
|
||||
private (byte[] Buffer, int Width, int Height) LoadSceneImage(string name, double time)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
var devices = _hostDevices;
|
||||
if (desc is null || devices is null)
|
||||
return s_noLoadedImage;
|
||||
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_sceneImageRenderer ??= new SceneImageRenderer(devices);
|
||||
if (!_sceneImageRenderer.TryRender(desc, name, time, out var pixels, out int width, out int height))
|
||||
return s_noLoadedImage;
|
||||
_sceneImageLoaded = true;
|
||||
return (pixels, width, height);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private (byte[] Buffer, int Width, int Height) LoadBrushImage(string name, double width, double height, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
var devices = _hostDevices;
|
||||
if (desc is null || devices is null)
|
||||
return s_noLoadedImage;
|
||||
|
||||
int w = (int)Math.Round(width);
|
||||
int h = (int)Math.Round(height);
|
||||
|
||||
_pixelLoaderSemaphore.Wait();
|
||||
try
|
||||
{
|
||||
_brushImageRenderer ??= new BrushImageRenderer(devices);
|
||||
if (!_brushImageRenderer.TryRender(desc, name, w, h, arguments, out var pixels, out int outWidth, out int outHeight))
|
||||
return s_noLoadedImage;
|
||||
return (pixels, outWidth, outHeight);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pixelLoaderSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly (int Count, int Rate, double[] Data) s_noAudio = (0, 0, []);
|
||||
|
||||
private (int Count, int Rate, double[] Data) LoadAudio(string file, string type, int size)
|
||||
{
|
||||
var desc = _frameDesc;
|
||||
if (desc is null)
|
||||
return s_noAudio;
|
||||
|
||||
_audioProvider ??= new AudioSampleProvider();
|
||||
(int Count, int Rate) result;
|
||||
if (string.Equals(file, "audiobuffer", StringComparison.Ordinal))
|
||||
{
|
||||
result = _audioProvider.ReadScene(FindOwnScene(desc), desc.TimelinePosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
else if (string.Equals(file, "itembuffer", StringComparison.Ordinal))
|
||||
{
|
||||
var (audioItem, scene) = ResolveOwnAudioItem(desc);
|
||||
result = _audioProvider.ReadItem(audioItem, scene, desc.ItemPosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = _audioProvider.ReadFile(file, desc.ItemPosition.Time.TotalSeconds, type, size);
|
||||
}
|
||||
|
||||
if (result.Count > 0)
|
||||
_audioLoaded = true;
|
||||
return (result.Count, result.Rate, _audioProvider.Data);
|
||||
}
|
||||
|
||||
private static Scene? FindOwnScene(EffectDescription desc)
|
||||
{
|
||||
var scenes = desc.Scenes;
|
||||
if (scenes is null)
|
||||
return null;
|
||||
foreach (var info in scenes)
|
||||
{
|
||||
if (info is Scene scene && scene.ID == desc.SceneId)
|
||||
return scene;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private (IAudioItem? Item, Scene? Scene) ResolveOwnAudioItem(EffectDescription desc)
|
||||
{
|
||||
var scene = FindOwnScene(desc);
|
||||
if (scene is null)
|
||||
return (null, null);
|
||||
|
||||
var items = scene.Timeline.Items;
|
||||
for (int i = 0; i < items.Count; i++)
|
||||
{
|
||||
if (items[i] is not IVideoItem video)
|
||||
continue;
|
||||
var effects = video.VideoEffects;
|
||||
for (int k = 0; k < effects.Count; k++)
|
||||
{
|
||||
if (ReferenceEquals(effects[k], item))
|
||||
return (items[i] as IAudioItem, scene);
|
||||
}
|
||||
}
|
||||
return (null, scene);
|
||||
}
|
||||
|
||||
private (byte[] buffer, int w, int h) NativeLoadMovie(string path, double time)
|
||||
{
|
||||
_nativeMovieDecoder ??= new MovieDecoder();
|
||||
@@ -1188,6 +1371,9 @@ namespace LuaScript
|
||||
_bufferCompositor?.Dispose();
|
||||
_nativeTextRenderer?.Dispose();
|
||||
_nativeImageDecoder?.Dispose();
|
||||
_sceneImageRenderer?.Dispose();
|
||||
_brushImageRenderer?.Dispose();
|
||||
_audioProvider?.Dispose();
|
||||
_pixelLoaderSemaphore.Dispose();
|
||||
_pixelManager?.Dispose();
|
||||
_pixelManager = null;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.16.2</Version>
|
||||
<Version>1.18.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using Vortice;
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneImageRenderer(IGraphicsDevicesAndContext devices) : IDisposable
|
||||
{
|
||||
[ThreadStatic]
|
||||
private static bool t_rendering;
|
||||
|
||||
private readonly Dictionary<Guid, ITimelineSource> _sources = [];
|
||||
private GraphicsDevicesAndContext? _ctx;
|
||||
private PixelBufferManager? _pixels;
|
||||
|
||||
public bool TryRender(EffectDescription desc, string name, double time, out byte[] pixels, out int width, out int height)
|
||||
{
|
||||
pixels = [];
|
||||
width = 0;
|
||||
height = 0;
|
||||
|
||||
if (t_rendering)
|
||||
return false;
|
||||
|
||||
var info = FindScene(desc, name);
|
||||
if (info is null)
|
||||
return false;
|
||||
|
||||
_ctx ??= new GraphicsDevicesAndContext(devices);
|
||||
if (!_sources.TryGetValue(info.ID, out var source))
|
||||
{
|
||||
if (!info.TryCreateVideoSource(_ctx, out source))
|
||||
return false;
|
||||
_sources[info.ID] = source;
|
||||
}
|
||||
|
||||
int w = Math.Max(1, info.Width);
|
||||
int h = Math.Max(1, info.Height);
|
||||
|
||||
t_rendering = true;
|
||||
try
|
||||
{
|
||||
source.Update(TimeSpan.FromSeconds(time), desc.Usage);
|
||||
_pixels ??= new PixelBufferManager(_ctx);
|
||||
pixels = _pixels.LoadInputPixels(source.Output, new RawRectF(-w / 2f, -h / 2f, w / 2f, h / 2f), w, h);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_sources.Remove(info.ID);
|
||||
source.Dispose();
|
||||
pixels = [];
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
t_rendering = false;
|
||||
}
|
||||
|
||||
width = w;
|
||||
height = h;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static ISceneInfo? FindScene(EffectDescription desc, string name)
|
||||
{
|
||||
foreach (var info in desc.Scenes)
|
||||
{
|
||||
if (info.ID != desc.SceneId && string.Equals(info.Name, name, StringComparison.Ordinal))
|
||||
return info;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var source in _sources.Values)
|
||||
source.Dispose();
|
||||
_sources.Clear();
|
||||
_pixels?.Dispose();
|
||||
_ctx?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,20 @@
|
||||
using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Project.Items;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal sealed class SceneObjectResolver : ISceneObjectResolver
|
||||
{
|
||||
internal readonly record struct Entry(string Tag, int Frame, int Length, int Layer, VisualItem Item);
|
||||
internal readonly record struct Entry(
|
||||
string Tag,
|
||||
int Frame,
|
||||
int Length,
|
||||
int Layer,
|
||||
IVideoItem Item,
|
||||
Animation? Volume,
|
||||
string Character,
|
||||
string Text,
|
||||
string Kind);
|
||||
|
||||
private readonly Entry[] _entries;
|
||||
private readonly int _fps;
|
||||
@@ -46,24 +56,34 @@ namespace LuaScript
|
||||
|
||||
private SceneObjectInfo Evaluate(in Entry entry, int timelineFrame)
|
||||
{
|
||||
var visual = entry.Item;
|
||||
var video = entry.Item;
|
||||
int length = entry.Length;
|
||||
int local = Math.Clamp(timelineFrame - entry.Frame, 0, length);
|
||||
|
||||
double x = visual.X.GetValue(local, length, _fps);
|
||||
double y = visual.Y.GetValue(local, length, _fps);
|
||||
double z = visual.Z.GetValue(local, length, _fps);
|
||||
double zoom = visual.Zoom.GetValue(local, length, _fps) / 100d;
|
||||
double rz = visual.Rotation.GetValue(local, length, _fps);
|
||||
double x = video.X.GetValue(local, length, _fps);
|
||||
double y = video.Y.GetValue(local, length, _fps);
|
||||
double z = video.Z.GetValue(local, length, _fps);
|
||||
double zoom = video.Zoom.GetValue(local, length, _fps) / 100d;
|
||||
double rz = video.Rotation.GetValue(local, length, _fps);
|
||||
|
||||
double opacity = visual.Opacity.GetValue(local, length, _fps) / 100d;
|
||||
double opacity = video.Opacity.GetValue(local, length, _fps) / 100d;
|
||||
double timeSec = _fps > 0 ? local / (double)_fps : 0d;
|
||||
double durationSec = _fps > 0 ? length / (double)_fps : 0d;
|
||||
double fadeIn = visual.FadeIn <= 0d ? 1d : Math.Min(1d, timeSec / visual.FadeIn);
|
||||
double fadeOut = visual.FadeOut <= 0d ? 1d : Math.Min(1d, (durationSec - timeSec) / visual.FadeOut);
|
||||
double fadeIn = video.FadeIn <= 0d ? 1d : Math.Min(1d, timeSec / video.FadeIn);
|
||||
double fadeOut = video.FadeOut <= 0d ? 1d : Math.Min(1d, (durationSec - timeSec) / video.FadeOut);
|
||||
double alpha = opacity * Math.Min(fadeIn, fadeOut) * 255d;
|
||||
|
||||
return new SceneObjectInfo(entry.Tag, IsExist(entry, timelineFrame), x, y, z, zoom, rz, alpha, entry.Layer);
|
||||
double volume = 0d;
|
||||
if (entry.Volume is { } volumeAnimation)
|
||||
{
|
||||
try { volume = volumeAnimation.GetValue(local, length, _fps); }
|
||||
catch { volume = 0d; }
|
||||
}
|
||||
|
||||
return new SceneObjectInfo(
|
||||
entry.Tag, IsExist(entry, timelineFrame),
|
||||
x, y, z, zoom, rz, alpha, entry.Layer,
|
||||
length, volume, entry.Character, entry.Text, entry.Kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -332,10 +332,15 @@
|
||||
※ عند وجود عدة عناصر تحمل الوسم نفسه، يُعاد العنصر الظاهر في
|
||||
الإطار الهدف بأولوية. وإن لم يكن أي منها ظاهرًا، يُعاد أول
|
||||
عنصر مطابق.
|
||||
※ عناصر الصوت (أصوات مُركَّبة وغيرها) مشمولة أيضًا. بالنسبة لعنصر
|
||||
صوتي، فإن الإحداثيات والمقياس والدوران والشفافية تخص عرض
|
||||
الترجمة (الجيماكو) الخاص به.
|
||||
※ القيم المُعادة هي إحداثيات العنصر ودورانه ومقياسه الخاصة به.
|
||||
ولا تتضمن التحويلات الناتجة عن التحكم بالمجموعة أو التحكم
|
||||
بالكاميرا أو التأثيرات الأعلى.
|
||||
※ تستخدم كل قيمة نظام الوحدات نفسه المستخدم في جدول obj.
|
||||
※ .character / .text / .volume / .kind / .length امتدادات خاصة
|
||||
بـ YMM4 لا توجد في AviUtl. وتعمل في كِلا المحركين.
|
||||
tag : النص المضبوط في ملاحظة العنصر الهدف
|
||||
frame : الإطار المطلق على المخطط الزمني المراد أخذه (اختياري)
|
||||
القيمة المُعادة : جدول معلومات الكائن. يُعيد nil عند عدم وجود
|
||||
@@ -355,6 +360,12 @@
|
||||
.rzr : زاوية الدوران حول المحور Z (بالراديان)
|
||||
.alpha : الشفافية (0.0 - 255.0، مع تطبيق التلاشي)
|
||||
.layer : رقم الطبقة التي وُضع فيها
|
||||
.length : طول العنصر (عدد الإطارات)
|
||||
.volume : القيمة الحالية لإعداد مستوى الصوت (لعناصر الصوت فقط؛ وإلا 0)
|
||||
.character : اسم الشخصية (لعناصر الصوت فقط؛ وإلا سلسلة فارغة)
|
||||
.text : الحوار أو النص المعروض (لعناصر الصوت والنص فقط؛
|
||||
وإلا سلسلة فارغة)
|
||||
.kind : اسم نوع العنصر (مثل VoiceItem، TextItem، ImageItem)
|
||||
مثال:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -368,6 +379,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
تغيير اللون حسب اسم الشخصية (ملاحظة الهدف هي "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "ماريسا" then
|
||||
obj.effect("أحادي اللون", "القوة", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
يسترد معلومات البكسل عند الإحداثيات المحددة.
|
||||
@@ -451,9 +467,11 @@
|
||||
|
||||
○ obj.load(الهدف، ...)
|
||||
يستبدل مخزن الكائن بمحتوى مُولَّد. تُدعم الأهداف "figure" و"text"
|
||||
و"image" (ملف صورة) و"movie" (ملف فيديو). بعد التحميل تُحدَّث
|
||||
و"image" (ملف صورة) و"movie" (ملف فيديو) و"scene" (مشهد المشروع)
|
||||
و"brush" (نمط YMM4). بعد التحميل تُحدَّث
|
||||
obj.w / obj.h وغيرها إلى الحجم المُولَّد، ويمكن قراءتها بـ getpixel
|
||||
مباشرة بعد التحميل. يعمل على محرك MoonSharp والمحرك السريع (LuaJIT).
|
||||
※ "scene" و"brush" امتدادان خاصان بـ YMM4 لا وجود لهما في AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
يُولّد شكلاً ويستبدل المخزن (متوسَّطاً).
|
||||
@@ -485,6 +503,42 @@
|
||||
الفيديو الأصلية (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
|
||||
مثال: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", sceneName [, time])
|
||||
يرسم مشهداً آخر من المشروع ويستبدل المخزن.
|
||||
sceneName : الاسم الظاهر في قائمة المشاهد.
|
||||
time : بالثواني. الافتراضي obj.time عند الحذف.
|
||||
※ لا يمكن تحديد المشهد الذي يقع عليه الكائن الحالي، كما
|
||||
يُرفض تحميل مشهد من داخل رسم مشهد آخر.
|
||||
※ الإطارات التي تُحمِّل مشهداً تتجاوز ذاكرة التخزين المؤقت
|
||||
للرسم ويُعاد تنفيذها في كل مرة.
|
||||
مثال: obj.load("scene", "مشهد فرعي", obj.time)
|
||||
|
||||
obj.load("brush", patternName [, width [, height]])
|
||||
يُولّد صورة مملوءة بنمط (فرشاة) من YMM4 ويستبدل المخزن.
|
||||
يمكن أيضاً استخدام الأنماط المضافة عبر إضافات الفرش.
|
||||
patternName : الاسم الظاهر في قائمة الأنماط.
|
||||
width, height : حجم الإخراج بالبكسل. الافتراضي
|
||||
obj.w / obj.h الحاليان عند الحذف.
|
||||
※ يُرسم النمط بمعاملاته الافتراضية.
|
||||
مثال: obj.load("brush", "خطوط", 400, 300)
|
||||
|
||||
○ obj.brush(patternName [, width, height] [, paramName, value, ...])
|
||||
يرسم نمطاً (فرشاة) من YMM4 مع تحديد المعاملات ويستبدل المخزن.
|
||||
الرسم مطابق لـ obj.load("brush")، ويمكن إضافة إلى ذلك تغيير
|
||||
معاملات النمط بأزواج الاسم والقيمة نفسها المستخدمة في obj.effect.
|
||||
patternName : الاسم الظاهر في قائمة الأنماط.
|
||||
width, height : حجم الإخراج بالبكسل. الافتراضي obj.w / obj.h
|
||||
الحاليان. يُفسَّران كحجم فقط عندما يُعطى كلاهما
|
||||
كرقمين.
|
||||
paramName : الاسم الظاهر لإعداد النمط، أو اسم الخاصية
|
||||
الداخلي.
|
||||
value : رقم أو قيمة منطقية أو نص. الألوان أرقام بصيغة
|
||||
0xRRGGBB.
|
||||
※ المعاملات غير المحددة تُرسم بقيمها الافتراضية. الاستدعاء بلا
|
||||
أزواج يعادل obj.load("brush").
|
||||
※ هذا امتداد خاص بـ YMM4 لا وجود له في AviUtl.
|
||||
مثال: obj.brush("خطوط", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(font [, size [, style [, color]]])
|
||||
يحدد الخط المستخدم في obj.load("text").
|
||||
style : أعلام بِتّية. 1=عريض، 2=مائل، 3=عريض+مائل.
|
||||
@@ -564,6 +618,44 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" إلخ.
|
||||
المُرجَع : رقم (0 لهدف غير معروف).
|
||||
|
||||
○ obj.getaudio(buf, file [, type [, size]])
|
||||
يحصل على بيانات الصوت.
|
||||
buf : جدول يستقبل البيانات. تُخزَّن القيم في buf[1]..buf[n]. مرِّر
|
||||
nil لاستلام الجدول كقيمة إرجاع ثالثة.
|
||||
file : مسار ملف صوتي. تُقبل أيضًا الأسماء الخاصة التالية.
|
||||
"audiobuffer" : يقرأ صوت المشهد الكامل قيد التحرير (جميع
|
||||
العناصر على الخط الزمني ممزوجة معًا).
|
||||
"itembuffer" : يقرأ صوت العنصر الذي أُضيف إليه هذا التأثير
|
||||
(بعد تطبيق مستوى الصوت والتوزيع والتلاشي
|
||||
وتأثيرات الصوت). هذا امتداد خاص بـ YMM4.
|
||||
type : نوع البيانات المطلوبة كسلسلة نصية. الافتراضي "pcm".
|
||||
"pcm" : PCM أحادي على مقياس 16 بت (من -32768 إلى 32767).
|
||||
"spectrum" : مستوى الصوت لكل نطاق تردد (تقريبًا من 0 إلى 32768).
|
||||
size هو عدد النطاقات (حتى 512، الافتراضي 32).
|
||||
"fourier" : مقادير تحويل فورييه المتقطع (تقريبًا من 0.0 إلى
|
||||
1.0). نطاق التردد من 1/2048 إلى 1/2، والعدد
|
||||
الافتراضي 1024.
|
||||
"xxxx.l" / "xxxx.r" : نسخة القناة اليسرى / اليمنى من الأنواع
|
||||
أعلاه. بدون لاحقة يُؤخذ متوسط القناتين.
|
||||
size : عدد القيم المطلوبة. قد يُرجَع عدد أقل. يمكن قراءة 1024
|
||||
قيمة كحد أقصى في كل استدعاء.
|
||||
المُرجَع : عدد القيم المقروءة، ومعدل أخذ العينات[, الجدول].
|
||||
موضع القراءة هو موضع الخط الزمني الحالي مع "audiobuffer"،
|
||||
وموضع التشغيل الحالي للكائن (obj.time) فيما عدا ذلك. يُرجِع
|
||||
"pcm" عينات متتالية من ذلك الموضع، بينما يحلل "spectrum" /
|
||||
"fourier" الفترة التي تبدأ هناك.
|
||||
مثال:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ يعمل في كلا المحركين. عند تعذر قراءة الصوت يكون العدد 0 ولا
|
||||
يحدث أي خطأ.
|
||||
※ يُرجِع "itembuffer" العدد 0 للعناصر بلا صوت (الصور والأشكال
|
||||
وغيرها). عند تعذر استخدام المكونات الداخلية لـ YMM4 يُستخدم
|
||||
الصوت قبل تطبيق مستوى الصوت وبقية التأثيرات.
|
||||
|
||||
○ obj.getinfo(name)
|
||||
يحصل على معلومات بيئية متنوعة. الاسم غير المدعوم يُرجِع nil.
|
||||
"script_path" : يُرجِع مسار مجلد تثبيت الإضافة. ينتهي بفاصل مسار.
|
||||
@@ -915,7 +1007,7 @@
|
||||
يُدعم الرسم والتركيب عبر obj.draw / obj.drawpoly، وعمليات المخزن
|
||||
عبر obj.copybuffer، والتوليد والتحميل عبر
|
||||
obj.load("figure"/"text"/"image"/"movie")، و obj.setfont، و obj.effect،
|
||||
و obj.getvalue، و obj.getinfo، و obj.setoption / obj.getoption / obj.pixeloption.
|
||||
و obj.getvalue، و obj.getaudio، و obj.getinfo، و obj.setoption / obj.getoption / obj.pixeloption.
|
||||
انظر "جدول obj - الدوال" للتفاصيل.
|
||||
|
||||
○ خريطة توافق AviUtl / AviUtl2 لـ obj.effect
|
||||
|
||||
@@ -343,10 +343,15 @@
|
||||
* If multiple items share the same tag, the item visible at the
|
||||
target frame is returned with priority. If none is visible,
|
||||
the first matching item is returned.
|
||||
* Voice items (synthesized voices, etc.) are also targeted. For a
|
||||
voice item, the coordinates, scale, rotation and opacity are
|
||||
those of its caption (subtitle) display.
|
||||
* The returned values are the item's own coordinates, rotation
|
||||
and scale. Transforms from group control, camera control or
|
||||
upper effects are NOT included.
|
||||
* Each value uses the same unit system as the obj table.
|
||||
* .character / .text / .volume / .kind / .length are YMM4-specific
|
||||
extensions that do not exist in AviUtl. They work on both engines.
|
||||
tag : The string set in the target item's remark
|
||||
frame : The absolute timeline frame to sample (optional)
|
||||
Return : An object information table. Returns nil when no
|
||||
@@ -366,6 +371,12 @@
|
||||
.rzr : Rotation angle around Z axis (radians)
|
||||
.alpha : Opacity (0.0 - 255.0, fade applied)
|
||||
.layer : Layer number where it is placed
|
||||
.length : Item length (number of frames)
|
||||
.volume : Current volume setting (voice items only; 0 otherwise)
|
||||
.character : Character name (voice items only; empty string otherwise)
|
||||
.text : Dialogue or displayed text (voice and text items only;
|
||||
empty string otherwise)
|
||||
.kind : Item type name (e.g. VoiceItem, TextItem, ImageItem)
|
||||
Example:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -379,6 +390,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
Recoloring by character name (target remark is "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "Marisa" then
|
||||
obj.effect("Monochrome", "strength", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
o obj.getpixel(x, y)
|
||||
Retrieves pixel information at the specified coordinates.
|
||||
@@ -463,10 +479,13 @@
|
||||
|
||||
o obj.load(target, ...)
|
||||
Replaces the object buffer with generated content. The targets
|
||||
"figure", "text", "image" (image file) and "movie" (video file)
|
||||
are supported. After loading, obj.w / obj.h, etc. are updated to the
|
||||
"figure", "text", "image" (image file), "movie" (video file),
|
||||
"scene" (project scene) and "brush" (YMM4 pattern) are supported.
|
||||
After loading, obj.w / obj.h, etc. are updated to the
|
||||
generated size and can be read by getpixel right after the load.
|
||||
Works on both the MoonSharp and the fast (LuaJIT) engine.
|
||||
* "scene" and "brush" are YMM4-only extensions that do not exist
|
||||
in AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
Generates a shape and replaces the buffer (centered).
|
||||
@@ -498,6 +517,44 @@
|
||||
videos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF) are loaded.
|
||||
Example: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", sceneName [, time])
|
||||
Renders another scene of the project and replaces the buffer.
|
||||
sceneName : The name shown in the scene list.
|
||||
time : Seconds. Defaults to obj.time when omitted.
|
||||
* The scene the current object belongs to cannot be specified.
|
||||
Loading a scene from inside a scene render is also rejected.
|
||||
* Frames that load a scene bypass the render cache and are
|
||||
re-executed every time.
|
||||
Example: obj.load("scene", "Sub Scene", obj.time)
|
||||
|
||||
obj.load("brush", patternName [, width [, height]])
|
||||
Generates an image filled with a YMM4 pattern (brush) and
|
||||
replaces the buffer. Patterns added by brush plugins can
|
||||
also be used.
|
||||
patternName : The name shown in the pattern list.
|
||||
width, height : Output size in pixels. Defaults to the
|
||||
current obj.w / obj.h when omitted.
|
||||
* The pattern is drawn with its default parameters.
|
||||
Example: obj.load("brush", "Stripe", 400, 300)
|
||||
|
||||
o obj.brush(patternName [, width, height] [, paramName, value, ...])
|
||||
Draws a YMM4 pattern (brush) with parameter overrides and replaces
|
||||
the buffer. The drawing is the same as obj.load("brush"), and in
|
||||
addition the pattern parameters can be changed with the same
|
||||
name-and-value pairs as obj.effect.
|
||||
patternName : The name shown in the pattern list.
|
||||
width, height : Output size in pixels. Defaults to the current
|
||||
obj.w / obj.h. Interpreted as the size only when
|
||||
both are given as numbers.
|
||||
paramName : The display name of a pattern setting, or its
|
||||
internal property name.
|
||||
value : A number, a boolean or a string. Colors are
|
||||
0xRRGGBB numbers.
|
||||
* Parameters that are not specified are drawn with their default
|
||||
values. A call without pairs equals obj.load("brush").
|
||||
* This is a YMM4-only extension that does not exist in AviUtl.
|
||||
Example: obj.brush("Stripe", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
o obj.setfont(font [, size [, style [, color]]])
|
||||
Sets the font used by obj.load("text").
|
||||
style : Bit flags. 1=bold, 2=italic, 3=bold+italic.
|
||||
@@ -583,6 +640,50 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame", etc.
|
||||
Returns: a number (0 for an unknown target).
|
||||
|
||||
o obj.getaudio(buf, file [, type [, size]])
|
||||
Gets audio data.
|
||||
buf : A table that receives the data. Values are stored in
|
||||
buf[1]..buf[n]. Pass nil to receive the table as the third
|
||||
return value instead.
|
||||
file : Path of an audio file. The following special names are
|
||||
also accepted.
|
||||
"audiobuffer" : Reads the audio of the whole scene being edited
|
||||
(all items on the timeline mixed together).
|
||||
"itembuffer" : Reads the audio of the item this effect is
|
||||
attached to (after volume, pan, fade, and audio
|
||||
effects are applied). This is a YMM4-specific
|
||||
extension.
|
||||
type : Kind of data to get, as a string. Defaults to "pcm".
|
||||
"pcm" : Mono PCM on a 16-bit scale (-32768 to 32767).
|
||||
"spectrum" : Volume per frequency band (roughly 0 to 32768).
|
||||
size is the number of bands (up to 512, default 32).
|
||||
"fourier" : Magnitudes of the discrete Fourier transform
|
||||
(roughly 0.0 to 1.0). The frequency range is
|
||||
1/2048 to 1/2; the default count is 1024.
|
||||
"xxxx.l" / "xxxx.r" : Left / right channel variant of the kinds
|
||||
above. Without a suffix, both channels are averaged.
|
||||
size : Number of values to get. Fewer values may be returned.
|
||||
Up to 1024 values can be read per call.
|
||||
Returns: the number of values read, the sampling rate
|
||||
[, the table].
|
||||
The read position is the current timeline position for
|
||||
"audiobuffer", and the current playback position of the object
|
||||
(obj.time) otherwise. "pcm" returns consecutive samples from that
|
||||
position; "spectrum" / "fourier" analyze the interval starting
|
||||
there.
|
||||
Example:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
* Works in both engines. When the audio cannot be read, the count
|
||||
is 0 and no error is raised.
|
||||
* "itembuffer" returns a count of 0 for items without audio
|
||||
(images, shapes, etc.). When the YMM4 internals are not
|
||||
available, it falls back to the audio before volume and other
|
||||
effects are applied.
|
||||
|
||||
o obj.getinfo(name)
|
||||
Gets various environment information. An unsupported name returns nil.
|
||||
"script_path" : Returns the path of the plugin install folder. It
|
||||
@@ -948,7 +1049,7 @@
|
||||
Drawing and compositing with obj.draw / obj.drawpoly, buffer
|
||||
operations with obj.copybuffer, generation and loading with
|
||||
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||
obj.getvalue, obj.getinfo, and obj.setoption / obj.getoption / obj.pixeloption are
|
||||
obj.getvalue, obj.getaudio, obj.getinfo, and obj.setoption / obj.getoption / obj.pixeloption are
|
||||
supported. See "obj Table - Functions" for details.
|
||||
|
||||
o AviUtl / AviUtl2 compatibility map for obj.effect
|
||||
|
||||
@@ -346,10 +346,15 @@
|
||||
con prioridad el elemento visible en el fotograma de destino.
|
||||
Si ninguno es visible, se devuelve el primer elemento que
|
||||
coincida.
|
||||
* Los elementos de voz (voces sintetizadas, etc.) también son objetivo.
|
||||
Para un elemento de voz, las coordenadas, escala, rotación y
|
||||
opacidad corresponden a la visualización de su subtítulo.
|
||||
* Los valores devueltos son las coordenadas, rotación y escala
|
||||
propias del elemento. NO se incluyen las transformaciones por
|
||||
control de grupo, control de cámara o efectos superiores.
|
||||
* Cada valor usa el mismo sistema de unidades que la tabla obj.
|
||||
* .character / .text / .volume / .kind / .length son extensiones
|
||||
propias de YMM4 que no existen en AviUtl. Funcionan en ambos motores.
|
||||
tag : El texto definido en la observación del elemento de destino
|
||||
frame : El fotograma absoluto de la línea de tiempo (opcional)
|
||||
Retorno : Una tabla de información del objeto. Devuelve nil cuando
|
||||
@@ -369,6 +374,12 @@
|
||||
.rzr : Ángulo de rotación en el eje Z (radianes)
|
||||
.alpha : Opacidad (0.0 - 255.0, fundido aplicado)
|
||||
.layer : Número de capa donde está colocado
|
||||
.length : Duración del elemento (número de fotogramas)
|
||||
.volume : Valor actual del volumen (solo elementos de voz; 0 en otro caso)
|
||||
.character : Nombre del personaje (solo elementos de voz; cadena vacía en otro caso)
|
||||
.text : Diálogo o texto mostrado (solo elementos de voz y texto;
|
||||
cadena vacía en otro caso)
|
||||
.kind : Nombre del tipo de elemento (p. ej. VoiceItem, TextItem, ImageItem)
|
||||
Ejemplo:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -382,6 +393,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
Recolorear según el nombre del personaje (la observación del destino es "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "Marisa" then
|
||||
obj.effect("Monocromo", "intensidad", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
o obj.getpixel(x, y)
|
||||
Obtiene información del píxel en las coordenadas especificadas.
|
||||
@@ -466,10 +482,13 @@
|
||||
|
||||
o obj.load(target, ...)
|
||||
Reemplaza el búfer del objeto con contenido generado. Se admiten los
|
||||
targets "figure", "text", "image" (archivo de imagen) y "movie"
|
||||
(archivo de vídeo). Tras la carga, obj.w / obj.h, etc. se actualizan al
|
||||
targets "figure", "text", "image" (archivo de imagen), "movie"
|
||||
(archivo de vídeo), "scene" (escena del proyecto) y "brush"
|
||||
(patrón de YMM4). Tras la carga, obj.w / obj.h, etc. se actualizan al
|
||||
tamaño generado y pueden leerse con getpixel justo después de la carga.
|
||||
Funciona en el motor MoonSharp y en el motor rápido (LuaJIT).
|
||||
* "scene" y "brush" son extensiones exclusivas de YMM4 que no
|
||||
existen en AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
Genera una forma y reemplaza el búfer (centrada).
|
||||
@@ -501,6 +520,45 @@
|
||||
vídeos genuinos (MP4 / MOV / MKV / WebM / AVI / FLV / ASF).
|
||||
Ejemplo: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", nombreEscena [, tiempo])
|
||||
Dibuja otra escena del proyecto y reemplaza el búfer.
|
||||
nombreEscena : El nombre mostrado en la lista de escenas.
|
||||
tiempo : Segundos. Por defecto obj.time.
|
||||
* No se puede indicar la escena a la que pertenece el objeto
|
||||
actual, ni cargar una escena desde dentro del dibujado de
|
||||
otra escena.
|
||||
* Los fotogramas que cargan una escena omiten la caché de
|
||||
dibujado y se vuelven a ejecutar cada vez.
|
||||
Ejemplo: obj.load("scene", "Subescena", obj.time)
|
||||
|
||||
obj.load("brush", nombrePatron [, ancho [, alto]])
|
||||
Genera una imagen rellenada con un patrón (pincel) de YMM4 y
|
||||
reemplaza el búfer. También pueden usarse patrones añadidos
|
||||
por plugins de pincel.
|
||||
nombrePatron : El nombre mostrado en la lista de patrones.
|
||||
ancho, alto : Tamaño generado en píxeles. Por defecto los
|
||||
obj.w / obj.h actuales.
|
||||
* El patrón se dibuja con sus parámetros por defecto.
|
||||
Ejemplo: obj.load("brush", "Rayas", 400, 300)
|
||||
|
||||
o obj.brush(nombrePatron [, ancho, alto] [, nombreParam, valor, ...])
|
||||
Dibuja un patrón (pincel) de YMM4 con parámetros indicados y
|
||||
reemplaza el búfer. El dibujado es el mismo que obj.load("brush"),
|
||||
y además los parámetros del patrón pueden cambiarse con los mismos
|
||||
pares de nombre y valor que obj.effect.
|
||||
nombrePatron : El nombre mostrado en la lista de patrones.
|
||||
ancho, alto : Tamaño generado en píxeles. Por defecto los
|
||||
obj.w / obj.h actuales. Solo se interpreta como
|
||||
tamaño cuando ambos se dan como números.
|
||||
nombreParam : El nombre mostrado de un ajuste del patrón, o su
|
||||
nombre de propiedad interno.
|
||||
valor : Un número, un booleano o una cadena. Los colores
|
||||
son números 0xRRGGBB.
|
||||
* Los parámetros no indicados se dibujan con sus valores por
|
||||
defecto. Una llamada sin pares equivale a obj.load("brush").
|
||||
* Es una extensión exclusiva de YMM4 que no existe en AviUtl.
|
||||
Ejemplo: obj.brush("Rayas", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
o obj.setfont(fuente [, tamaño [, estilo [, color]]])
|
||||
Establece la fuente usada por obj.load("text").
|
||||
estilo : Bits. 1=negrita, 2=cursiva, 3=negrita+cursiva.
|
||||
@@ -589,6 +647,53 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame", etc.
|
||||
Devuelve: un número (0 para un target desconocido).
|
||||
|
||||
o obj.getaudio(buf, archivo [, tipo [, cantidad]])
|
||||
Obtiene datos de audio.
|
||||
buf : Tabla que recibe los datos. Los valores se guardan en
|
||||
buf[1]..buf[n]. Pase nil para recibir la tabla como el
|
||||
tercer valor de retorno.
|
||||
archivo : Ruta de un archivo de audio. También se aceptan los
|
||||
siguientes nombres especiales.
|
||||
"audiobuffer" : Lee el audio de toda la escena en edición
|
||||
(todos los elementos de la línea de tiempo
|
||||
mezclados).
|
||||
"itembuffer" : Lee el audio del elemento al que está aplicado
|
||||
este efecto (tras aplicar volumen, panorama,
|
||||
fundidos y efectos de audio). Es una extensión
|
||||
exclusiva de YMM4.
|
||||
tipo : Clase de datos a obtener, como cadena. Por defecto "pcm".
|
||||
"pcm" : PCM monoaural en escala de 16 bits (-32768 a 32767).
|
||||
"spectrum" : Volumen por banda de frecuencia (aprox. 0 a 32768).
|
||||
cantidad es el número de bandas (hasta 512, por
|
||||
defecto 32).
|
||||
"fourier" : Magnitudes de la transformada discreta de Fourier
|
||||
(aprox. 0.0 a 1.0). El rango de frecuencia es de
|
||||
1/2048 a 1/2; la cantidad por defecto es 1024.
|
||||
"xxxx.l" / "xxxx.r" : Variante del canal izquierdo / derecho de
|
||||
los tipos anteriores. Sin sufijo se promedian
|
||||
ambos canales.
|
||||
cantidad : Número de valores a obtener. Pueden devolverse menos.
|
||||
Se pueden leer hasta 1024 valores por llamada.
|
||||
Devuelve: el número de valores leídos, la frecuencia de muestreo
|
||||
[, la tabla].
|
||||
La posición de lectura es la posición actual de la línea de
|
||||
tiempo para "audiobuffer" y la posición de reproducción actual
|
||||
del objeto (obj.time) en los demás casos. "pcm" devuelve muestras
|
||||
consecutivas desde esa posición; "spectrum" / "fourier" analizan
|
||||
el intervalo que comienza allí.
|
||||
Ejemplo:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
* Funciona en ambos motores. Si el audio no puede leerse, la
|
||||
cantidad es 0 y no se produce ningún error.
|
||||
* "itembuffer" devuelve una cantidad de 0 para los elementos sin
|
||||
audio (imágenes, figuras, etc.). Cuando los componentes
|
||||
internos de YMM4 no están disponibles, recurre al audio previo
|
||||
a la aplicación del volumen y demás efectos.
|
||||
|
||||
o obj.getinfo(nombre)
|
||||
Obtiene diversa información del entorno. Un nombre no admitido
|
||||
devuelve nil.
|
||||
@@ -966,7 +1071,7 @@
|
||||
Se admiten el dibujo y composición con obj.draw / obj.drawpoly, las
|
||||
operaciones de búfer con obj.copybuffer, la generación y carga con
|
||||
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||
obj.getvalue, obj.getinfo y obj.setoption / obj.getoption / obj.pixeloption.
|
||||
obj.getvalue, obj.getaudio, obj.getinfo y obj.setoption / obj.getoption / obj.pixeloption.
|
||||
Consulte "Tabla obj - Funciones" para más detalles.
|
||||
|
||||
o Mapa de compatibilidad AviUtl / AviUtl2 para obj.effect
|
||||
|
||||
@@ -343,10 +343,15 @@
|
||||
* Jika beberapa item berbagi tag yang sama, item yang tampil
|
||||
pada frame target dikembalikan dengan prioritas. Jika tidak
|
||||
ada yang tampil, item pertama yang cocok dikembalikan.
|
||||
* Item suara (suara sintesis, dll.) juga menjadi target. Untuk item
|
||||
suara, koordinat, skala, rotasi, dan opasitas adalah milik
|
||||
tampilan takarir (subtitle)-nya.
|
||||
* Nilai yang dikembalikan adalah koordinat, rotasi, dan skala
|
||||
milik item itu sendiri. Transformasi dari kontrol grup,
|
||||
kontrol kamera, atau efek di atasnya TIDAK disertakan.
|
||||
* Setiap nilai menggunakan sistem satuan yang sama dengan tabel obj.
|
||||
* .character / .text / .volume / .kind / .length adalah ekstensi
|
||||
khusus YMM4 yang tidak ada di AviUtl. Bekerja pada kedua mesin.
|
||||
tag : Teks yang diatur pada catatan item target
|
||||
frame : Frame absolut pada lini masa yang diambil (opsional)
|
||||
Kembali : Tabel informasi objek. Mengembalikan nil jika tidak ada
|
||||
@@ -366,6 +371,12 @@
|
||||
.rzr : Sudut rotasi sumbu Z (radian)
|
||||
.alpha : Opasitas (0.0 - 255.0, fade diterapkan)
|
||||
.layer : Nomor layer tempat ditempatkan
|
||||
.length : Panjang item (jumlah frame)
|
||||
.volume : Nilai pengaturan volume saat ini (hanya item suara; selain itu 0)
|
||||
.character : Nama karakter (hanya item suara; selain itu string kosong)
|
||||
.text : Dialog atau teks yang ditampilkan (hanya item suara dan teks;
|
||||
selain itu string kosong)
|
||||
.kind : Nama jenis item (mis. VoiceItem, TextItem, ImageItem)
|
||||
Contoh:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -379,6 +390,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
Mewarnai ulang berdasarkan nama karakter (catatan target adalah "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "Marisa" then
|
||||
obj.effect("Monokrom", "kekuatan", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
o obj.getpixel(x, y)
|
||||
Mengambil informasi piksel pada koordinat yang ditentukan.
|
||||
@@ -463,10 +479,13 @@
|
||||
|
||||
o obj.load(target, ...)
|
||||
Mengganti buffer objek dengan konten yang dihasilkan. Target "figure",
|
||||
"text", "image" (berkas gambar) dan "movie" (berkas video) didukung.
|
||||
"text", "image" (berkas gambar), "movie" (berkas video), "scene"
|
||||
(adegan proyek) dan "brush" (pola YMM4) didukung.
|
||||
Setelah dimuat, obj.w / obj.h, dll. diperbarui ke ukuran yang
|
||||
dihasilkan dan dapat dibaca oleh getpixel tepat setelah pemuatan.
|
||||
Berfungsi pada mesin MoonSharp maupun mesin cepat (LuaJIT).
|
||||
* "scene" dan "brush" adalah ekstensi khusus YMM4 yang tidak ada
|
||||
di AviUtl.
|
||||
|
||||
obj.load("figure", name, color, size [, line [, aspect]])
|
||||
Menghasilkan bentuk dan mengganti buffer (dipusatkan).
|
||||
@@ -498,6 +517,45 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF) yang dimuat.
|
||||
Contoh: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", namaAdegan [, waktu])
|
||||
Menggambar adegan lain dalam proyek dan mengganti buffer.
|
||||
namaAdegan : Nama yang ditampilkan pada daftar adegan.
|
||||
waktu : Detik. Default obj.time bila dihilangkan.
|
||||
* Adegan tempat objek saat ini berada tidak dapat dipilih,
|
||||
dan memuat adegan dari dalam penggambaran adegan juga
|
||||
ditolak.
|
||||
* Frame yang memuat adegan melewati cache render dan
|
||||
dijalankan ulang setiap kali.
|
||||
Contoh: obj.load("scene", "Sub Adegan", obj.time)
|
||||
|
||||
obj.load("brush", namaPola [, lebar [, tinggi]])
|
||||
Menghasilkan gambar yang diisi pola (kuas) YMM4 dan
|
||||
mengganti buffer. Pola yang ditambahkan oleh plugin kuas
|
||||
juga dapat digunakan.
|
||||
namaPola : Nama yang ditampilkan pada daftar pola.
|
||||
lebar, tinggi : Ukuran keluaran dalam piksel. Default
|
||||
obj.w / obj.h saat ini bila dihilangkan.
|
||||
* Pola digambar dengan parameter default.
|
||||
Contoh: obj.load("brush", "Garis-garis", 400, 300)
|
||||
|
||||
o obj.brush(namaPola [, lebar, tinggi] [, namaParam, nilai, ...])
|
||||
Menggambar pola (kuas) YMM4 dengan parameter yang ditentukan dan
|
||||
mengganti buffer. Penggambarannya sama dengan obj.load("brush"),
|
||||
dan parameter pola dapat diubah dengan pasangan nama dan nilai
|
||||
yang sama seperti obj.effect.
|
||||
namaPola : Nama yang ditampilkan pada daftar pola.
|
||||
lebar, tinggi : Ukuran keluaran dalam piksel. Default
|
||||
obj.w / obj.h saat ini. Hanya ditafsirkan sebagai
|
||||
ukuran bila keduanya diberikan sebagai angka.
|
||||
namaParam : Nama tampilan pengaturan pola, atau nama properti
|
||||
internalnya.
|
||||
nilai : Angka, boolean atau string. Warna adalah angka
|
||||
0xRRGGBB.
|
||||
* Parameter yang tidak ditentukan digambar dengan nilai default.
|
||||
Panggilan tanpa pasangan sama dengan obj.load("brush").
|
||||
* Ini adalah ekstensi khusus YMM4 yang tidak ada di AviUtl.
|
||||
Contoh: obj.brush("Garis-garis", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
o obj.setfont(font [, size [, style [, color]]])
|
||||
Mengatur font yang digunakan oleh obj.load("text").
|
||||
style : Flag bit. 1=tebal, 2=miring, 3=tebal+miring.
|
||||
@@ -585,6 +643,50 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame", dll.
|
||||
Mengembalikan: sebuah angka (0 untuk target yang tidak dikenal).
|
||||
|
||||
o obj.getaudio(buf, file [, tipe [, jumlah]])
|
||||
Mengambil data audio.
|
||||
buf : Tabel yang menerima data. Nilai disimpan di buf[1]..buf[n].
|
||||
Berikan nil untuk menerima tabel sebagai nilai kembali
|
||||
ketiga.
|
||||
file : Jalur berkas audio. Nama khusus berikut juga diterima.
|
||||
"audiobuffer" : Membaca audio seluruh scene yang sedang
|
||||
disunting (semua item di lini masa dicampur
|
||||
menjadi satu).
|
||||
"itembuffer" : Membaca audio dari item tempat efek ini
|
||||
terpasang (setelah volume, pan, fade, dan efek
|
||||
audio diterapkan). Ini ekstensi khusus YMM4.
|
||||
tipe : Jenis data yang diambil, sebagai string. Bawaan "pcm".
|
||||
"pcm" : PCM mono pada skala 16-bit (-32768 sampai 32767).
|
||||
"spectrum" : Volume per pita frekuensi (sekitar 0 sampai 32768).
|
||||
jumlah adalah banyaknya pita (maksimal 512,
|
||||
bawaan 32).
|
||||
"fourier" : Magnitudo transformasi Fourier diskrit (sekitar
|
||||
0.0 sampai 1.0). Rentang frekuensinya 1/2048
|
||||
sampai 1/2; jumlah bawaannya 1024.
|
||||
"xxxx.l" / "xxxx.r" : Varian kanal kiri / kanan dari jenis di
|
||||
atas. Tanpa akhiran, kedua kanal dirata-ratakan.
|
||||
jumlah : Banyaknya nilai yang diambil. Hasilnya bisa lebih
|
||||
sedikit. Maksimal 1024 nilai per panggilan.
|
||||
Mengembalikan: banyaknya nilai yang terbaca, laju sampel
|
||||
[, tabel].
|
||||
Posisi baca adalah posisi lini masa saat ini untuk
|
||||
"audiobuffer", dan posisi pemutaran objek saat ini (obj.time)
|
||||
untuk lainnya. "pcm" mengembalikan sampel berurutan dari posisi
|
||||
itu; "spectrum" / "fourier" menganalisis interval yang dimulai
|
||||
dari sana.
|
||||
Contoh:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
* Bekerja di kedua mesin. Jika audio tidak dapat dibaca,
|
||||
jumlahnya 0 dan tidak terjadi kesalahan.
|
||||
* "itembuffer" mengembalikan jumlah 0 untuk item tanpa audio
|
||||
(gambar, bentuk, dsb.). Jika komponen internal YMM4 tidak
|
||||
tersedia, digunakan audio sebelum volume dan efek lainnya
|
||||
diterapkan.
|
||||
|
||||
o obj.getinfo(name)
|
||||
Mengambil berbagai informasi lingkungan. Nama yang tidak didukung
|
||||
mengembalikan nil.
|
||||
@@ -959,7 +1061,7 @@
|
||||
Penggambaran dan komposisi dengan obj.draw / obj.drawpoly, operasi
|
||||
buffer dengan obj.copybuffer, pembuatan dan pemuatan dengan
|
||||
obj.load("figure"/"text"/"image"/"movie"), obj.setfont, obj.effect,
|
||||
obj.getvalue, obj.getinfo, serta obj.setoption / obj.getoption / obj.pixeloption
|
||||
obj.getvalue, obj.getaudio, obj.getinfo, serta obj.setoption / obj.getoption / obj.pixeloption
|
||||
didukung. Lihat "Tabel obj - Fungsi" untuk detailnya.
|
||||
|
||||
o Peta kompatibilitas AviUtl / AviUtl2 untuk obj.effect
|
||||
|
||||
@@ -161,8 +161,8 @@
|
||||
|
||||
- scene テーブル -
|
||||
|
||||
scene.width : シーン(プロジェクト)の横解像度(ピクセル) [ReadOnly]
|
||||
scene.height : シーン(プロジェクト)の縦解像度(ピクセル) [ReadOnly]
|
||||
scene.width : シーンの横解像度(ピクセル) [ReadOnly]
|
||||
scene.height : シーンの縦解像度(ピクセル) [ReadOnly]
|
||||
scene.cx : シーンの横解像度の半分 (= scene.width / 2) [ReadOnly]
|
||||
scene.cy : シーンの縦解像度の半分 (= scene.height / 2) [ReadOnly]
|
||||
|
||||
@@ -334,9 +334,13 @@
|
||||
※ 同じタグを持つアイテムが複数ある場合、対象フレームで表示中の
|
||||
アイテムを優先して返します。表示中のものが無い場合は最初に
|
||||
一致したアイテムを返します。
|
||||
※ 音声アイテム(合成音声等)も対象になります。音声アイテムの
|
||||
座標・拡大率・回転・不透明度は字幕の表示情報を返します。
|
||||
※ 取得できる値はアイテム自身の座標・回転・拡大率です。
|
||||
グループ制御・カメラ制御・上位エフェクトによる変形は含まれません。
|
||||
※ 各値は obj テーブルと同一の単位系です。
|
||||
※ .character / .text / .volume / .kind / .length は AviUtl に存在しない
|
||||
YMM4 向けの独自拡張です。両エンジンで動作します。
|
||||
tag : 対象アイテムの備考に設定した文字列
|
||||
frame : 取得するタイムライン上の絶対フレーム (省略可)
|
||||
戻り値 : オブジェクト情報テーブル。一致するアイテムが存在しない場合は
|
||||
@@ -356,6 +360,12 @@
|
||||
.rzr : Z 軸回転角度 (ラジアン)
|
||||
.alpha : 不透明度 (0.0 ~ 255.0, フェード反映済み)
|
||||
.layer : 配置レイヤー番号
|
||||
.length : アイテムの長さ (フレーム数)
|
||||
.volume : 音量設定の現在値 (音声アイテムのみ。他は 0)
|
||||
.character : キャラクター名 (音声アイテムのみ。他は空文字列)
|
||||
.text : セリフまたは表示テキスト (音声・テキストアイテムのみ。
|
||||
他は空文字列)
|
||||
.kind : アイテムの種別名 (例:VoiceItem, TextItem, ImageItem)
|
||||
例:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -369,6 +379,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
キャラクター名で色を変える例 (対象の備考が "voice" の場合):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "魔理沙" then
|
||||
obj.effect("単色化", "強さ", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○obj.getpixel(x, y)
|
||||
指定座標のピクセル情報を取得します。
|
||||
@@ -453,9 +468,12 @@
|
||||
○obj.load(対象, ...)
|
||||
オブジェクトのバッファを生成した内容に置き換えます。
|
||||
対象は "figure"(図形) / "text"(テキスト) / "image"(画像ファイル) /
|
||||
"movie"(動画ファイル) に対応します。生成後 obj.w / obj.h 等は生成
|
||||
サイズへ更新され、load 直後の getpixel でも参照できます。
|
||||
"movie"(動画ファイル) / "scene"(シーン) / "brush"(模様) に対応
|
||||
します。生成後 obj.w / obj.h 等は生成サイズへ更新され、load 直後
|
||||
の getpixel でも参照できます。
|
||||
従来エンジン・高速エンジンの両方で動作します。
|
||||
※ "scene" と "brush" は AviUtl に存在しない YMM4 向けの独自拡張
|
||||
です。
|
||||
|
||||
obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])
|
||||
図形を生成してバッファを置き換えます(中心に配置)。
|
||||
@@ -488,6 +506,43 @@
|
||||
読み込みます。
|
||||
例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", シーン名 [, 時間])
|
||||
プロジェクト内の別シーンを描画してバッファを置き換えます。
|
||||
シーン名 : シーン一覧に表示される名前。
|
||||
時間 : 秒。省略時は obj.time。
|
||||
※ 現在のオブジェクトが乗っているシーン自身は指定でき
|
||||
ません。シーン描画の中からさらにシーンを読み込むこと
|
||||
もできません。
|
||||
※ シーンを読み込んだフレームは描画キャッシュを使わず
|
||||
毎回再実行されます。
|
||||
例:obj.load("scene", "サブシーン", obj.time)
|
||||
|
||||
obj.load("brush", 模様名 [, 幅 [, 高さ]])
|
||||
YMM4 の模様(ブラシ)で塗り潰した画像を生成してバッファを
|
||||
置き換えます。模様プラグインで追加した模様も使えます。
|
||||
模様名 : 模様一覧に表示される名前(例:縞模様、市松模様)。
|
||||
幅、高さ : 生成サイズ(ピクセル)。省略時は現在の
|
||||
obj.w / obj.h。
|
||||
※ 模様のパラメータは既定値で描画されます。
|
||||
例:obj.load("brush", "縞模様", 400, 300)
|
||||
|
||||
○obj.brush(模様名 [, 幅, 高さ] [, パラメータ名, 値, ...])
|
||||
YMM4 の模様(ブラシ)をパラメータ指定付きで描画してバッファを
|
||||
置き換えます。描画は obj.load("brush") と同じで、加えて
|
||||
obj.effect と同じ「名前と値の組」で模様のパラメータを変更
|
||||
できます。
|
||||
模様名 : 模様一覧に表示される名前。
|
||||
幅、高さ : 生成サイズ(ピクセル)。省略時は現在の
|
||||
obj.w / obj.h。両方を数値で並べたときだけ
|
||||
サイズとして解釈します。
|
||||
パラメータ名 : 模様の設定項目の表示名、または内部の
|
||||
プロパティ名。
|
||||
値 : 数値、真偽値、文字列。色は 0xRRGGBB の数値。
|
||||
※ 指定しなかったパラメータは既定値で描画されます。組を
|
||||
すべて省略した呼び出しは obj.load("brush") と同じです。
|
||||
※ AviUtl に存在しない YMM4 向けの独自拡張です。
|
||||
例:obj.brush("縞模様", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○obj.setfont(フォント名 [, サイズ [, スタイル [, 色]]])
|
||||
obj.load("text") で使用するフォントを設定します。
|
||||
スタイル : ビット和。1=太字, 2=斜体, 3=太字+斜体。
|
||||
@@ -567,6 +622,45 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 等。
|
||||
戻り値 : 数値(未知の対象は 0)。
|
||||
|
||||
○obj.getaudio(バッファ, ファイル名 [, 種別 [, 個数]])
|
||||
音声データを取得します。
|
||||
バッファ : 取得データを格納するテーブルを指定します。データは
|
||||
バッファ[1]~バッファ[n] へ格納されます。nil を指定
|
||||
すると 3 番目の戻り値としてテーブルを返します。
|
||||
ファイル名 : 音声ファイルのパスを指定します。次の特別な名前も
|
||||
指定できます。
|
||||
"audiobuffer" : 編集中のシーン全体の音声(タイムライン上の
|
||||
全アイテムを合成した音声)を取得します。
|
||||
"itembuffer" : このエフェクトを付けたアイテム自身の音声
|
||||
(音量・パン・フェード・音声エフェクト適用後)
|
||||
を取得します。YMM4独自の拡張です。
|
||||
種別 : 取得するデータの種類を文字列で指定します。省略時は "pcm"。
|
||||
"pcm" : 16bit スケール基準(-32768~32767)のモノラル PCM。
|
||||
"spectrum" : 周波数帯ごとの音量データ(0~32768 目安)。個数は
|
||||
分割する帯域の数です(最大 512、省略時 32)。
|
||||
"fourier" : 離散フーリエ変換の振幅データ(0.0~1.0 目安)。
|
||||
周波数範囲は 1/2048~1/2 で、省略時は 1024 個です。
|
||||
"xxxx.l" / "xxxx.r" : 上記種別の左 / 右チャンネル版。無指定の
|
||||
ときは左右の平均です。
|
||||
個数 : 取得するデータ数を指定します。取得できた数が指定より
|
||||
少ないことがあります。1 回で取得できるのは最大 1024 個です。
|
||||
戻り値 : 取得したデータ数, サンプリングレート[, テーブル]。
|
||||
読み取り位置は、"audiobuffer" はタイムラインの現在の再生位置、
|
||||
それ以外はオブジェクトの現在の再生位置(obj.time)です。pcm は
|
||||
現在位置から連続したサンプルを返し、spectrum / fourier は現在位置
|
||||
からの区間を解析して返します。
|
||||
例:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 両エンジンで動きます。取得できない場合はデータ数 0 を返し、
|
||||
エラーにはなりません。
|
||||
※ "itembuffer" は音声を持たないアイテム(画像や図形等)では
|
||||
データ数 0 になります。YMM4の内部実装を利用できない場合は
|
||||
音量等を適用する前の音声になります。
|
||||
|
||||
○obj.getinfo(名前)
|
||||
各種の環境情報を取得します。未対応の名前は nil を返します。
|
||||
"script_path" : プラグインの設置フォルダのパスを返します。末尾に
|
||||
@@ -640,7 +734,7 @@
|
||||
"xyz" : アンカーポイントを 3D 座標で扱います。既定は 2D です。
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
名前に "track" を指定した場合も対応し、個数 0 は 1 個として設置します。
|
||||
選択中のアンカーは アンカー グループの X / Y / Z スライダーで数値調整できます。
|
||||
選択中のアンカーは「アンカー」グループの X / Y / Z スライダーで数値調整できます。
|
||||
例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -890,7 +984,8 @@
|
||||
- AviUtl スクリプトの部分互換 -
|
||||
|
||||
AviUtl のアニメーション効果スクリプト(*.anm 系)のうち、座標・拡縮・回転・
|
||||
不透明度の変形と乱数を用いる範囲を、追加の記述変更なしで実行できる互換層です。
|
||||
不透明度の変形、乱数、図形描画、描画合成などを、追加の記述変更なしで
|
||||
実行できる互換層です。
|
||||
スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません
|
||||
(従来のスクリプトの挙動は変わりません)。
|
||||
|
||||
@@ -922,7 +1017,7 @@
|
||||
○描画・合成・読み込み
|
||||
obj.draw / obj.drawpoly による描画合成、obj.copybuffer による
|
||||
バッファ操作、obj.load("figure"/"text"/"image"/"movie") による生成・
|
||||
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.getinfo、obj.setoption /
|
||||
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.getaudio、obj.getinfo、obj.setoption /
|
||||
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
|
||||
関数」を参照してください。
|
||||
|
||||
|
||||
@@ -331,9 +331,13 @@
|
||||
※ 같은 태그를 가진 아이템이 여러 개인 경우, 대상 프레임에서
|
||||
표시 중인 아이템을 우선하여 반환합니다. 표시 중인 것이 없으면
|
||||
처음으로 일치한 아이템을 반환합니다.
|
||||
※ 음성 아이템(합성 음성 등)도 대상이 됩니다. 음성 아이템의
|
||||
좌표·확대율·회전·불투명도는 자막 표시 정보를 반환합니다.
|
||||
※ 취득되는 값은 아이템 자신의 좌표·회전·확대율입니다.
|
||||
그룹 제어·카메라 제어·상위 이펙트에 의한 변형은 포함되지 않습니다.
|
||||
※ 각 값은 obj 테이블과 동일한 단위 체계입니다.
|
||||
※ .character / .text / .volume / .kind / .length 은 AviUtl 에 없는
|
||||
YMM4 전용 확장입니다. 두 엔진 모두에서 동작합니다.
|
||||
tag : 대상 아이템의 비고에 설정한 문자열
|
||||
frame : 취득할 타임라인의 절대 프레임 (생략 가능)
|
||||
반환값 : 오브젝트 정보 테이블. 일치하는 아이템이 없으면 nil을 반환합니다.
|
||||
@@ -352,6 +356,11 @@
|
||||
.rzr : Z축 회전 각도 (라디안)
|
||||
.alpha : 불투명도 (0.0 ~ 255.0, 페이드 반영됨)
|
||||
.layer : 배치 레이어 번호
|
||||
.length : 아이템 길이 (프레임 수)
|
||||
.volume : 음량 설정의 현재 값 (음성 아이템만. 그 외는 0)
|
||||
.character : 캐릭터 이름 (음성 아이템만. 그 외는 빈 문자열)
|
||||
.text : 대사 또는 표시 텍스트 (음성·텍스트 아이템만. 그 외는 빈 문자열)
|
||||
.kind : 아이템 종류 이름 (예: VoiceItem, TextItem, ImageItem)
|
||||
예:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -365,6 +374,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
캐릭터 이름으로 색을 바꾸는 예 (대상의 비고가 "voice"인 경우):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "마리사" then
|
||||
obj.effect("단색화", "강도", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
지정 좌표의 픽셀 정보를 취득합니다.
|
||||
@@ -448,10 +462,13 @@
|
||||
|
||||
○ obj.load(대상, ...)
|
||||
오브젝트 버퍼를 생성한 내용으로 교체합니다. "figure"(도형) /
|
||||
"text"(텍스트) / "image"(이미지 파일) / "movie"(동영상 파일)를
|
||||
"text"(텍스트) / "image"(이미지 파일) / "movie"(동영상 파일) /
|
||||
"scene"(씬) / "brush"(무늬)를
|
||||
지원합니다. 로드 후 obj.w / obj.h 등은 생성 크기로 갱신되며, 로드
|
||||
직후의 getpixel로도 참조할 수 있습니다. 기존 엔진과 고속 엔진
|
||||
양쪽에서 동작합니다.
|
||||
※ "scene"과 "brush"는 AviUtl에 존재하지 않는 YMM4 전용
|
||||
확장입니다.
|
||||
|
||||
obj.load("figure", 이름, 색, 크기 [, 라인 [, 종횡비]])
|
||||
도형을 생성하여 버퍼를 교체합니다(중심 배치).
|
||||
@@ -483,6 +500,40 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)만 읽습니다.
|
||||
예: obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", 씬이름 [, 시간])
|
||||
프로젝트 안의 다른 씬을 그려 버퍼를 교체합니다.
|
||||
씬이름 : 씬 목록에 표시되는 이름.
|
||||
시간 : 초. 생략 시 obj.time.
|
||||
※ 현재 오브젝트가 놓인 씬 자신은 지정할 수 없으며, 씬
|
||||
그리기 도중에 다시 씬을 로드할 수도 없습니다.
|
||||
※ 씬을 로드한 프레임은 렌더 캐시를 사용하지 않고 매번
|
||||
다시 실행됩니다.
|
||||
예: obj.load("scene", "서브 씬", obj.time)
|
||||
|
||||
obj.load("brush", 무늬이름 [, 너비 [, 높이]])
|
||||
YMM4의 무늬(브러시)로 채운 이미지를 생성하여 버퍼를
|
||||
교체합니다. 브러시 플러그인으로 추가한 무늬도 사용할 수
|
||||
있습니다.
|
||||
무늬이름 : 무늬 목록에 표시되는 이름.
|
||||
너비, 높이 : 생성 크기(픽셀). 생략 시 현재 obj.w / obj.h.
|
||||
※ 무늬는 기본 매개변수로 그려집니다.
|
||||
예: obj.load("brush", "줄무늬", 400, 300)
|
||||
|
||||
○ obj.brush(무늬이름 [, 너비, 높이] [, 매개변수명, 값, ...])
|
||||
YMM4의 무늬(브러시)를 매개변수 지정과 함께 그려 버퍼를
|
||||
교체합니다. 그리기는 obj.load("brush")와 같고, 추가로
|
||||
obj.effect와 같은 「이름과 값의 쌍」으로 무늬의 매개변수를
|
||||
변경할 수 있습니다.
|
||||
무늬이름 : 무늬 목록에 표시되는 이름.
|
||||
너비, 높이 : 생성 크기(픽셀). 생략 시 현재 obj.w / obj.h.
|
||||
둘 다 숫자로 주어졌을 때만 크기로 해석합니다.
|
||||
매개변수명 : 무늬 설정 항목의 표시 이름, 또는 내부 속성 이름.
|
||||
값 : 숫자, 불리언, 문자열. 색은 0xRRGGBB 숫자.
|
||||
※ 지정하지 않은 매개변수는 기본값으로 그려집니다. 쌍을 모두
|
||||
생략한 호출은 obj.load("brush")와 같습니다.
|
||||
※ AviUtl에 존재하지 않는 YMM4 전용 확장입니다.
|
||||
예: obj.brush("줄무늬", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(글꼴 [, 크기 [, 스타일 [, 색]]])
|
||||
obj.load("text")에서 사용할 글꼴을 설정합니다.
|
||||
스타일 : 비트 플래그. 1=굵게, 2=기울임, 3=굵게+기울임.
|
||||
@@ -560,6 +611,45 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 등.
|
||||
반환값 : 숫자(알 수 없는 대상은 0).
|
||||
|
||||
○ obj.getaudio(버퍼, 파일명 [, 종류 [, 개수]])
|
||||
오디오 데이터를 가져옵니다.
|
||||
버퍼 : 데이터를 저장할 테이블입니다. 데이터는 버퍼[1]~버퍼[n]에
|
||||
저장됩니다. nil을 지정하면 테이블이 세 번째 반환값으로
|
||||
반환됩니다.
|
||||
파일명 : 오디오 파일의 경로입니다. 다음의 특별한 이름도 지정할
|
||||
수 있습니다.
|
||||
"audiobuffer" : 편집 중인 씬 전체의 오디오(타임라인의 모든
|
||||
아이템을 합성한 오디오)를 가져옵니다.
|
||||
"itembuffer" : 이 이펙트가 붙은 아이템 자신의 오디오(음량·
|
||||
팬·페이드·오디오 이펙트 적용 후)를 가져
|
||||
옵니다. YMM4 전용 확장입니다.
|
||||
종류 : 가져올 데이터의 종류를 문자열로 지정합니다. 생략 시 "pcm".
|
||||
"pcm" : 16bit 스케일 기준(-32768~32767)의 모노 PCM.
|
||||
"spectrum" : 주파수 대역별 음량 데이터(약 0~32768). 개수는
|
||||
분할할 대역의 수입니다(최대 512, 생략 시 32).
|
||||
"fourier" : 이산 푸리에 변환의 진폭 데이터(약 0.0~1.0).
|
||||
주파수 범위는 1/2048~1/2이며 생략 시 1024개입니다.
|
||||
"xxxx.l" / "xxxx.r" : 위 종류의 왼쪽 / 오른쪽 채널 버전.
|
||||
지정하지 않으면 좌우의 평균입니다.
|
||||
개수 : 가져올 데이터 개수입니다. 실제 개수가 지정보다 적을 수
|
||||
있습니다. 한 번에 최대 1024개까지 가져올 수 있습니다.
|
||||
반환값 : 가져온 데이터 개수, 샘플링 레이트[, 테이블].
|
||||
읽기 위치는 "audiobuffer"의 경우 타임라인의 현재 위치, 그 외에는
|
||||
오브젝트의 현재 재생 위치(obj.time)입니다. "pcm"은 현재 위치부터
|
||||
연속된 샘플을 반환하고, "spectrum" / "fourier"는 현재 위치부터의
|
||||
구간을 분석해 반환합니다.
|
||||
예:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 두 엔진 모두에서 동작합니다. 읽을 수 없는 경우 데이터 개수 0을
|
||||
반환하며 오류가 되지 않습니다.
|
||||
※ "itembuffer"는 오디오가 없는 아이템(이미지, 도형 등)에서는
|
||||
데이터 개수 0이 됩니다. YMM4 내부 구현을 사용할 수 없는 경우
|
||||
음량 등을 적용하기 전의 오디오가 됩니다.
|
||||
|
||||
○ obj.getinfo(이름)
|
||||
각종 환경 정보를 가져옵니다. 지원하지 않는 이름은 nil을 반환합니다.
|
||||
"script_path" : 플러그인 설치 폴더의 경로를 반환합니다. 끝에 경로
|
||||
@@ -913,7 +1003,7 @@
|
||||
○ 그리기·합성·로드
|
||||
obj.draw / obj.drawpoly에 의한 그리기 합성, obj.copybuffer에 의한
|
||||
버퍼 조작, obj.load("figure"/"text"/"image"/"movie")에 의한 생성·로드,
|
||||
obj.setfont, obj.effect, obj.getvalue, obj.getinfo, 그리고 obj.setoption /
|
||||
obj.setfont, obj.effect, obj.getvalue, obj.getaudio, obj.getinfo, 그리고 obj.setoption /
|
||||
obj.getoption / obj.pixeloption을 지원합니다. 자세한 내용은
|
||||
"obj 테이블 - 함수"를 참조하세요.
|
||||
|
||||
|
||||
@@ -322,9 +322,13 @@
|
||||
※ 指定第二个参数 frame 时,获取该时间轴帧的数值。省略时获取当前帧。
|
||||
※ 当多个项目拥有相同标签时,优先返回在目标帧显示中的项目。
|
||||
若没有显示中的项目,则返回第一个匹配的项目。
|
||||
※ 语音项目 (合成语音等) 也是对象。语音项目的坐标、缩放、
|
||||
旋转和不透明度返回其字幕显示信息。
|
||||
※ 获取的值是项目自身的坐标、旋转和缩放。
|
||||
不包含组控制、摄像机控制以及上层特效造成的变换。
|
||||
※ 各数值使用与 obj 表相同的单位体系。
|
||||
※ .character / .text / .volume / .kind / .length 是 AviUtl 中不存在的
|
||||
YMM4 独有扩展。两种引擎均可运行。
|
||||
tag : 设置在目标项目备注中的字符串
|
||||
frame : 要获取的时间轴绝对帧 (可省略)
|
||||
返回值 : 对象信息表。当不存在匹配项目时返回 nil。
|
||||
@@ -343,6 +347,11 @@
|
||||
.rzr : Z 轴旋转角度 (弧度)
|
||||
.alpha : 不透明度 (0.0 ~ 255.0, 已应用淡入淡出)
|
||||
.layer : 所在图层编号
|
||||
.length : 项目长度 (帧数)
|
||||
.volume : 音量设置的当前值 (仅语音项目。其他为 0)
|
||||
.character : 角色名 (仅语音项目。其他为空字符串)
|
||||
.text : 台词或显示文本 (仅语音和文本项目。其他为空字符串)
|
||||
.kind : 项目类别名 (例:VoiceItem, TextItem, ImageItem)
|
||||
示例:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -356,6 +365,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
按角色名改变颜色的示例 (目标备注为 "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "魔理沙" then
|
||||
obj.effect("单色化", "强度", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
获取指定坐标的像素信息。
|
||||
@@ -439,8 +453,10 @@
|
||||
|
||||
○ obj.load(目标, ...)
|
||||
将对象缓冲区替换为生成的内容。支持 "figure"(图形) / "text"(文本) /
|
||||
"image"(图像文件) / "movie"(视频文件)。加载后 obj.w / obj.h 等会更新为
|
||||
"image"(图像文件) / "movie"(视频文件) / "scene"(场景) /
|
||||
"brush"(图案)。加载后 obj.w / obj.h 等会更新为
|
||||
生成尺寸,紧接着的 getpixel 也可读取。传统引擎与高速引擎均可运行。
|
||||
※ "scene" 与 "brush" 是 AviUtl 中不存在的 YMM4 专用扩展。
|
||||
|
||||
obj.load("figure", 名称, 颜色, 大小 [, 线宽 [, 纵横比]])
|
||||
生成图形并替换缓冲区(居中)。
|
||||
@@ -472,6 +488,37 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
|
||||
示例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", 场景名 [, 时间])
|
||||
绘制项目内的另一个场景并替换缓冲区。
|
||||
场景名 : 场景列表中显示的名称。
|
||||
时间 : 秒。省略时为 obj.time。
|
||||
※ 不能指定当前对象所在的场景本身,也不能在场景绘制
|
||||
过程中再次加载场景。
|
||||
※ 加载了场景的帧不使用绘制缓存,每次都会重新执行。
|
||||
示例:obj.load("scene", "子场景", obj.time)
|
||||
|
||||
obj.load("brush", 图案名 [, 宽 [, 高]])
|
||||
以 YMM4 的图案(笔刷)填充生成图像并替换缓冲区。
|
||||
通过笔刷插件添加的图案也可以使用。
|
||||
图案名 : 图案列表中显示的名称(例:条纹、棋盘格)。
|
||||
宽、高 : 生成尺寸(像素)。省略时为当前 obj.w / obj.h。
|
||||
※ 图案以默认参数绘制。
|
||||
示例:obj.load("brush", "条纹", 400, 300)
|
||||
|
||||
○ obj.brush(图案名 [, 宽, 高] [, 参数名, 值, ...])
|
||||
以带参数指定的方式绘制 YMM4 的图案(笔刷)并替换缓冲区。
|
||||
绘制与 obj.load("brush") 相同,另外可以用与 obj.effect 相同的
|
||||
「名称与值的组」修改图案的参数。
|
||||
图案名 : 图案列表中显示的名称。
|
||||
宽、高 : 生成尺寸(像素)。省略时为当前 obj.w / obj.h。仅当两者
|
||||
都以数值给出时才解释为尺寸。
|
||||
参数名 : 图案设置项的显示名称,或其内部属性名。
|
||||
值 : 数值、布尔值、字符串。颜色为 0xRRGGBB 的数值。
|
||||
※ 未指定的参数以默认值绘制。省略所有组的调用与
|
||||
obj.load("brush") 相同。
|
||||
※ 这是 AviUtl 中不存在的 YMM4 专用扩展。
|
||||
示例:obj.brush("条纹", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(字体 [, 大小 [, 样式 [, 颜色]]])
|
||||
设置 obj.load("text") 使用的字体。
|
||||
样式 : 位标志。1=粗体, 2=斜体, 3=粗斜体。
|
||||
@@ -545,6 +592,41 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 等。
|
||||
返回值 : 数值(未知目标返回 0)。
|
||||
|
||||
○ obj.getaudio(缓冲区, 文件名 [, 类型 [, 数量]])
|
||||
获取音频数据。
|
||||
缓冲区 : 用于存放数据的表。数据存入 缓冲区[1]~缓冲区[n]。
|
||||
指定 nil 时,表将作为第 3 个返回值返回。
|
||||
文件名 : 音频文件的路径。也可以指定以下特殊名称。
|
||||
"audiobuffer" : 获取正在编辑的整个场景的音频(时间轴上全部
|
||||
项目混合后的音频)。
|
||||
"itembuffer" : 获取附加了本效果的项目自身的音频(应用音量、
|
||||
声像、淡入淡出和音频效果之后)。这是 YMM4
|
||||
专有的扩展。
|
||||
类型 : 以字符串指定要获取的数据种类。省略时为 "pcm"。
|
||||
"pcm" : 以 16bit 为基准(-32768~32767)的单声道 PCM。
|
||||
"spectrum" : 各频段的音量数据(约 0~32768)。数量为频段的
|
||||
分割数(最多 512,省略时 32)。
|
||||
"fourier" : 离散傅里叶变换的振幅数据(约 0.0~1.0)。频率
|
||||
范围为 1/2048~1/2,省略时为 1024 个。
|
||||
"xxxx.l" / "xxxx.r" : 上述类型的左 / 右声道版本。未指定时
|
||||
取左右声道的平均值。
|
||||
数量 : 要获取的数据个数。实际获取的个数可能少于指定值。
|
||||
一次最多可获取 1024 个。
|
||||
返回值 : 获取的数据个数, 采样率[, 表]。
|
||||
"audiobuffer" 的读取位置为时间轴的当前位置,其余为对象当前的
|
||||
播放位置(obj.time)。"pcm" 返回从该位置起连续的采样,
|
||||
"spectrum" / "fourier" 则分析从该位置开始的区间。
|
||||
示例:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 在两个引擎中均可使用。无法读取时返回数据个数 0,不会报错。
|
||||
※ "itembuffer" 对没有音频的项目(图像、图形等)返回数据个数 0。
|
||||
无法使用 YMM4 内部实现时,将回退为应用音量等效果之前的
|
||||
音频。
|
||||
|
||||
○ obj.getinfo(名称)
|
||||
获取各种环境信息。不支持的名称返回 nil。
|
||||
"script_path" : 返回插件安装文件夹的路径,末尾带有路径分隔符。
|
||||
@@ -879,7 +961,7 @@
|
||||
○ 绘制·合成·加载
|
||||
支持 obj.draw / obj.drawpoly 的绘制合成、obj.copybuffer 的缓冲区操作、
|
||||
obj.load("figure"/"text"/"image"/"movie") 的生成与加载、obj.setfont、
|
||||
obj.effect、obj.getvalue、obj.getinfo 以及 obj.setoption / obj.getoption /
|
||||
obj.effect、obj.getvalue、obj.getaudio、obj.getinfo 以及 obj.setoption / obj.getoption /
|
||||
obj.pixeloption。详情请参阅“obj 表 - 函数”。
|
||||
|
||||
○ obj.effect 的 AviUtl / AviUtl2 兼容映射
|
||||
|
||||
@@ -322,9 +322,13 @@
|
||||
※ 指定第二個參數 frame 時,取得該時間軸影格的數值。省略時取得目前影格。
|
||||
※ 當多個項目擁有相同標籤時,優先回傳在目標影格顯示中的項目。
|
||||
若沒有顯示中的項目,則回傳第一個相符的項目。
|
||||
※ 語音項目 (合成語音等) 也是對象。語音項目的座標、縮放、
|
||||
旋轉與不透明度回傳其字幕顯示資訊。
|
||||
※ 取得的值是項目自身的座標、旋轉與縮放。
|
||||
不包含群組控制、攝影機控制以及上層特效造成的變換。
|
||||
※ 各數值使用與 obj 表相同的單位體系。
|
||||
※ .character / .text / .volume / .kind / .length 是 AviUtl 中不存在的
|
||||
YMM4 獨有擴充。兩種引擎皆可運作。
|
||||
tag : 設定於目標項目備註中的字串
|
||||
frame : 要取得的時間軸絕對影格 (可省略)
|
||||
回傳值 : 物件資訊表。當不存在相符項目時回傳 nil。
|
||||
@@ -343,6 +347,11 @@
|
||||
.rzr : Z 軸旋轉角度 (弧度)
|
||||
.alpha : 不透明度 (0.0 ~ 255.0, 已套用淡入淡出)
|
||||
.layer : 所在圖層編號
|
||||
.length : 項目長度 (影格數)
|
||||
.volume : 音量設定的目前值 (僅語音項目。其他為 0)
|
||||
.character : 角色名 (僅語音項目。其他為空字串)
|
||||
.text : 台詞或顯示文字 (僅語音與文字項目。其他為空字串)
|
||||
.kind : 項目類別名 (例:VoiceItem, TextItem, ImageItem)
|
||||
範例:
|
||||
local funnel = obj.getobject("funnel")
|
||||
if funnel then
|
||||
@@ -356,6 +365,11 @@
|
||||
obj.x = src.x
|
||||
obj.y = src.y
|
||||
end
|
||||
依角色名改變顏色的範例 (目標備註為 "voice"):
|
||||
local v = obj.getobject("voice")
|
||||
if v and v.character == "魔理沙" then
|
||||
obj.effect("單色化", "強度", 100, "color", 0xffee55)
|
||||
end
|
||||
|
||||
○ obj.getpixel(x, y)
|
||||
取得指定座標的像素資訊。
|
||||
@@ -439,8 +453,10 @@
|
||||
|
||||
○ obj.load(目標, ...)
|
||||
將物件緩衝區替換為產生的內容。支援 "figure"(圖形) / "text"(文字) /
|
||||
"image"(影像檔) / "movie"(影片檔)。載入後 obj.w / obj.h 等會更新為產生
|
||||
"image"(影像檔) / "movie"(影片檔) / "scene"(場景) /
|
||||
"brush"(圖樣)。載入後 obj.w / obj.h 等會更新為產生
|
||||
尺寸,緊接著的 getpixel 亦可讀取。傳統引擎與高速引擎皆可執行。
|
||||
※ "scene" 與 "brush" 是 AviUtl 中不存在的 YMM4 專用擴充。
|
||||
|
||||
obj.load("figure", 名稱, 顏色, 大小 [, 線寬 [, 長寬比]])
|
||||
產生圖形並替換緩衝區(置中)。
|
||||
@@ -472,6 +488,37 @@
|
||||
(MP4 / MOV / MKV / WebM / AVI / FLV / ASF)。
|
||||
範例:obj.load("movie", "C:\\mov\\clip.mp4", obj.time)
|
||||
|
||||
obj.load("scene", 場景名 [, 時間])
|
||||
繪製專案內的另一個場景並替換緩衝區。
|
||||
場景名 : 場景清單中顯示的名稱。
|
||||
時間 : 秒。省略時為 obj.time。
|
||||
※ 不能指定目前物件所在的場景本身,也不能在場景繪製
|
||||
過程中再次載入場景。
|
||||
※ 載入了場景的影格不使用繪製快取,每次都會重新執行。
|
||||
範例:obj.load("scene", "子場景", obj.time)
|
||||
|
||||
obj.load("brush", 圖樣名 [, 寬 [, 高]])
|
||||
以 YMM4 的圖樣(筆刷)填滿產生影像並替換緩衝區。
|
||||
透過筆刷外掛新增的圖樣亦可使用。
|
||||
圖樣名 : 圖樣清單中顯示的名稱(例:條紋、棋盤格)。
|
||||
寬、高 : 產生尺寸(像素)。省略時為目前的 obj.w / obj.h。
|
||||
※ 圖樣以預設參數繪製。
|
||||
範例:obj.load("brush", "條紋", 400, 300)
|
||||
|
||||
○ obj.brush(圖樣名 [, 寬, 高] [, 參數名, 值, ...])
|
||||
以帶參數指定的方式繪製 YMM4 的圖樣(筆刷)並替換緩衝區。
|
||||
繪製與 obj.load("brush") 相同,另外可以用與 obj.effect 相同的
|
||||
「名稱與值的組」修改圖樣的參數。
|
||||
圖樣名 : 圖樣清單中顯示的名稱。
|
||||
寬、高 : 產生尺寸(像素)。省略時為目前的 obj.w / obj.h。僅當兩者
|
||||
都以數值給出時才解釋為尺寸。
|
||||
參數名 : 圖樣設定項目的顯示名稱,或其內部屬性名。
|
||||
值 : 數值、布林值、字串。顏色為 0xRRGGBB 的數值。
|
||||
※ 未指定的參數以預設值繪製。省略所有組的呼叫與
|
||||
obj.load("brush") 相同。
|
||||
※ 這是 AviUtl 中不存在的 YMM4 專用擴充。
|
||||
範例:obj.brush("條紋", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
○ obj.setfont(字型 [, 大小 [, 樣式 [, 顏色]]])
|
||||
設定 obj.load("text") 使用的字型。
|
||||
樣式 : 位元旗標。1=粗體, 2=斜體, 3=粗斜體。
|
||||
@@ -545,6 +592,41 @@
|
||||
"alpha","sx","sy","track0"~"track3","time","frame" 等。
|
||||
回傳值 : 數值(未知目標回傳 0)。
|
||||
|
||||
○ obj.getaudio(緩衝區, 檔案名 [, 類型 [, 數量]])
|
||||
取得音訊資料。
|
||||
緩衝區 : 用於存放資料的表。資料存入 緩衝區[1]~緩衝區[n]。
|
||||
指定 nil 時,表將作為第 3 個回傳值回傳。
|
||||
檔案名 : 音訊檔案的路徑。也可以指定以下特殊名稱。
|
||||
"audiobuffer" : 取得正在編輯的整個場景的音訊(時間軸上全部
|
||||
項目混合後的音訊)。
|
||||
"itembuffer" : 取得附加了本效果的項目自身的音訊(套用音量、
|
||||
聲像、淡入淡出與音訊效果之後)。這是 YMM4
|
||||
專有的擴充。
|
||||
類型 : 以字串指定要取得的資料種類。省略時為 "pcm"。
|
||||
"pcm" : 以 16bit 為基準(-32768~32767)的單聲道 PCM。
|
||||
"spectrum" : 各頻段的音量資料(約 0~32768)。數量為頻段的
|
||||
分割數(最多 512,省略時 32)。
|
||||
"fourier" : 離散傅立葉轉換的振幅資料(約 0.0~1.0)。頻率
|
||||
範圍為 1/2048~1/2,省略時為 1024 個。
|
||||
"xxxx.l" / "xxxx.r" : 上述類型的左 / 右聲道版本。未指定時
|
||||
取左右聲道的平均值。
|
||||
數量 : 要取得的資料個數。實際取得的個數可能少於指定值。
|
||||
一次最多可取得 1024 個。
|
||||
回傳值 : 取得的資料個數, 取樣率[, 表]。
|
||||
"audiobuffer" 的讀取位置為時間軸的目前位置,其餘為物件目前的
|
||||
播放位置(obj.time)。"pcm" 回傳從該位置起連續的取樣,
|
||||
"spectrum" / "fourier" 則分析從該位置開始的區間。
|
||||
範例:
|
||||
local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end
|
||||
※ 在兩個引擎中皆可使用。無法讀取時回傳資料個數 0,不會報錯。
|
||||
※ "itembuffer" 對沒有音訊的項目(圖片、圖形等)回傳資料個數 0。
|
||||
無法使用 YMM4 內部實作時,將回退為套用音量等效果之前的
|
||||
音訊。
|
||||
|
||||
○ obj.getinfo(名稱)
|
||||
取得各種環境資訊。未支援的名稱回傳 nil。
|
||||
"script_path" : 回傳外掛安裝資料夾的路徑,結尾附有路徑分隔字元。
|
||||
@@ -880,7 +962,7 @@
|
||||
○ 繪製·合成·載入
|
||||
支援 obj.draw / obj.drawpoly 的繪製合成、obj.copybuffer 的緩衝區操作、
|
||||
obj.load("figure"/"text"/"image"/"movie") 的產生與載入、obj.setfont、
|
||||
obj.effect、obj.getvalue、obj.getinfo 以及 obj.setoption / obj.getoption /
|
||||
obj.effect、obj.getvalue、obj.getaudio、obj.getinfo 以及 obj.setoption / obj.getoption /
|
||||
obj.pixeloption。詳情請參閱「obj 表 - 函式」。
|
||||
|
||||
○ obj.effect 的 AviUtl / AviUtl2 相容對應表
|
||||
|
||||
@@ -118,7 +118,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
### 4. scene テーブルと ymm4 テーブル
|
||||
|
||||
`scene` テーブルにはシーン(プロジェクト)の解像度情報と、シーン単位で値を共有する関数が格納されています。
|
||||
`scene` テーブルにはシーンの解像度情報と、シーン単位で値を共有する関数が格納されています。
|
||||
|
||||
| 変数 / 関数 | 説明 |
|
||||
|---|---|
|
||||
@@ -143,7 +143,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
### 5. anim ユーティリティテーブル
|
||||
|
||||
`anim` テーブルには、アニメーション計算に使う純粋な定数・関数群が登録されています。コンテキストに依存しない純粋関数であり、副作用はありません。
|
||||
`anim` テーブルには、アニメーション計算に使う定数・関数群が登録されています。コンテキストに依存しない純粋関数であり、副作用はありません。
|
||||
|
||||
| 関数 / 定数 | 説明 |
|
||||
|---|---|
|
||||
@@ -218,7 +218,11 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||
- **`obj.load("figure", 名前, 色, サイズ [, ライン [, アスペクト]])`**: 円・四角形・三角形・五角形・六角形・星形を生成し、オブジェクトのバッファを置き換えて描画します(出力は図形サイズに合わせて生成され、中心に配置されます)。`ライン` を省略するか `0` で塗りつぶし、サイズ以上の値でも塗りつぶしになります。`アスペクト`(-1.0〜1.0)で幅・高さを歪曲できます。
|
||||
- **`obj.brush(模様名 [, 幅, 高さ] [, パラメータ名, 値, ...])`**: AviUtl に存在しない YMM4 向けの独自拡張です。YMM4 の模様(ブラシ)をパラメータ指定付きで描画してオブジェクトの画像を置き換えます。描画は `obj.load("brush")` と同じで、加えて `obj.effect` と同じ「名前と値の組」で模様のパラメータを変更できます。パラメータ名には設定項目の表示名または内部のプロパティ名を指定し、値は数値・真偽値・文字列に対応します。色は `0xRRGGBB` の数値で指定します。指定しなかったパラメータは既定値で描画され、組をすべて省略した呼び出しは `obj.load("brush")` と同じです。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||
- **`obj.load("scene", シーン名 [, 時間])` と `obj.load("brush", 模様名 [, 幅, 高さ])`**: AviUtl に存在しない YMM4 向けの独自拡張です。`"scene"` はプロジェクト内の別シーンを指定時刻(省略時は `obj.time`)で描画してオブジェクトのバッファを置き換えます。シーン名にはシーン一覧に表示される名前を指定します。現在のオブジェクトが乗っているシーン自身は読み込めず、シーン描画の中からさらにシーンを読み込むこともできません。シーンを読み込んだフレームは描画キャッシュを使わず毎回再実行されます。`"brush"` は YMM4 の模様で塗り潰した画像を生成してバッファを置き換えます。模様名には模様一覧に表示される名前を指定し、ブラシプラグインで追加した模様も使えます。サイズを省略すると現在の `obj.w` / `obj.h` を用い、模様のパラメータは既定値で描画されます。どちらも従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||
- **描画・メディア・バッファ・オプション API**: `obj.draw` / `obj.drawpoly` による描画合成、`obj.load` の `"text"` / `"image"` / `"movie"`、`obj.setfont`、`obj.copybuffer`、`obj.effect`、`obj.getvalue`、`obj.getinfo`、`obj.setoption` / `obj.getoption` / `obj.pixeloption` に対応しています。これらは従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`obj.getinfo` は `"script_path"` / `"filter"` / `"saving"` / `"image_max"` / `"bpm"` / `"clock"` / `"script_time"` / `"version"` の環境情報を名前で取得します。`obj.setoption` では `antialias` に加えて、`obj.draw` / `obj.drawpoly` の合成モードを YMM4 の並びで指定する `blend`、描画先を `"framebuffer"` / `"tempbuffer"` で切り替える `drawtarget`、作業画像の出力可否を切り替える `draw_state` に対応します。MoonSharp では `tempbuffer` への合成を GPU で実行し、GPU を利用できない環境では CPU の合成へ自動的に切り替わります。丸めの違いにより、合成の結果はエンジン間でごく僅かに異なることがあります。
|
||||
- **`obj.getobject(tag [, frame])`**: 対象アイテムの「備考」に入力した文字列を `tag` として、他アイテムの描画情報を取得します。座標・拡大率・回転・不透明度・レイヤーに加えて、AviUtl に存在しない YMM4 向けの独自拡張として `.length`(フレーム数)、`.volume`(音量設定の現在値)、`.character`(キャラクター名)、`.text`(セリフまたは表示テキスト)、`.kind`(アイテム種別名)を返します。音声アイテム(合成音声等)も対象になり、その座標・拡大率・回転・不透明度は字幕の表示情報を返します。`.character` と `.volume` は音声アイテムのみ、`.text` は音声・テキストアイテムのみで値を持ち、他は空文字列または 0 になります。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||
- **`obj.getaudio(buf, file [, type, size])`**: 音声データを取得します。`buf` に渡したテーブルの `buf[1]`~`buf[n]` へデータを格納し、取得したデータ数とサンプリングレートを返します。`buf` に `nil` を渡すとテーブルを 3 番目の戻り値として返します。`file` には音声ファイルのパスを指定します。`"audiobuffer"` は AviUtl と同じく編集中の音声で、タイムライン上の全アイテムを合成したシーン全体の音声を取得します。加えて YMM4 独自の拡張として `"itembuffer"` を指定でき、このエフェクトを付けたアイテム自身の音声(音量・パン・フェード・音声エフェクト適用後)を取得します。`type` は `"pcm"`(16bit スケール基準のモノラル PCM)、`"spectrum"`(周波数帯ごとの音量。`size` は帯域数で最大 512、省略時 32)、`"fourier"`(離散フーリエ変換の振幅。省略時 1024 個)に対応し、`.l` / `.r` の接尾辞で左右チャンネルを選べます。読み取り位置は `"audiobuffer"` がタイムラインの現在位置、それ以外はオブジェクトの現在の再生位置(`obj.time`)で、1 回で取得できるデータ数は最大 1024 個です。取得できない場合はデータ数 0 を返し、エラーにはなりません。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。
|
||||
- **`obj.setanchor(name, count [, option, ...])`**: プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を `name` の Lua 変数(`pos={x0,y0,x1,y1,…}`、`"xyz"` 指定時は `{x0,y0,z0,…}`)へ格納します。座標はオブジェクトの中心が原点で、ドラッグで調整した値はプロジェクトへ保存されます。最大 32 個で、`"line"` / `"loop"` / `"star"` / `"arm"` の線結びと `"xyz"` の 3D 指定に対応します。設置数を返し、従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の双方で動作します。`name` に `"track"` を指定した場合も対応し、個数 0 は 1 個として設置します。選択中のアンカーは「アンカー」グループの `X` / `Y` / `Z` スライダーで数値調整できます。
|
||||
- **`obj.effect` の AviUtl/AviUtl2 互換マップ**: `obj.effect("エフェクト名", "パラメータ名", 値, …)` はまず互換マップを参照し、AviUtl/AviUtl2 の名前として宣言したエフェクトを、対応する YMM4 の映像エフェクトとプロパティへ変換して適用します。値の倍率とオフセットの変換まで宣言できます。互換マップに宣言が無い名前は、従来どおり YMM4 のエフェクト名・キーワードでそのまま解決するため、既存の呼び出しはそのまま動きます。この互換マップは YMM4 自身が AviUtl の `.exo` へ書き出す変換を逆向きにたどって構築しているため、往復しても結果が一致します。対象のエンジンは指定子 `--!aviutl` または `--!aviutl2` で切り替え、指定子を書かないときは `--!aviutl` として扱います。互換マップが対応するエフェクト名の一覧はドキュメントの「obj の関数」を参照してください。
|
||||
|
||||
@@ -400,7 +404,7 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
|
||||
## 注意事項
|
||||
|
||||
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・不透明度・乱数の範囲のみ実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。描画・フィルタ・ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
- **AviUtl 互換は部分的**: AviUtl のアニメーション効果スクリプトのうち、変形・乱数・図形描画・描画合成・エフェクト適用などの範囲を実行できます([AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。ファイルアクセス系の関数、および AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
- **実行タイムアウト**: スクリプトの実行は 5000ms(5秒)でタイムアウトし、超過した場合は強制終了されエラーとして扱われます。無限ループが発生しないよう注意してください。
|
||||
- **利用可能な標準ライブラリの制限**: `table`、`string`、`math`、`bit32` および基本関数のみ利用できます。`io`、`os`、`debug`、`ffi`、`require` は利用できません。
|
||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します(GPU カーネルはこの転送を行いません)。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは内容に応じて CPU カーネルまたは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
|
||||
+4
-3
@@ -61,10 +61,11 @@ Lua 5.2 互換の MoonSharp はフォールバックとして使われます。
|
||||
<tr><td>座標・回転・拡大率・不透明度の制御</td><td><code>obj.x</code>, <code>obj.rz</code>, <code>obj.zoom</code>, <code>obj.alpha</code> ほか</td><td><a href="obj.html">obj</a></td></tr>
|
||||
<tr><td>時間・フレーム情報</td><td><code>time</code>, <code>frame</code>, <code>obj.t</code>, <code>timelineframe</code></td><td><a href="globals.html">グローバル変数</a></td></tr>
|
||||
<tr><td>アニメーション補間・波・ノイズ・色</td><td><code>anim.lerp</code>, <code>anim.ease_in_out</code>, <code>anim.noise</code>, <code>anim.hsv_to_rgb</code></td><td><a href="anim.html">anim</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.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.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.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.draw</code>, <code>obj.drawpoly</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>scene.width</code>, <code>ymm4.is_saving</code></td><td><a href="scene-ymm4.html">scene / ymm4</a></td></tr>
|
||||
<tr><td>パラメータ UI の定義</td><td><code>--track@</code>, <code>--check@</code>, <code>--color@</code>, <code>--dialog:</code></td><td><a href="directives.html">パラメータ指定子</a></td></tr>
|
||||
<tr><td>高速化エンジンの選択</td><td><code>--!native</code>, <code>--!cpu</code>, <code>--!gpu</code></td><td><a href="engines.html">エンジンと高速化</a></td></tr>
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
<li>ファイルアクセス不可: <code>require</code>・<code>dofile</code>・<code>io</code> などは使えません。</li>
|
||||
<li>使えない標準ライブラリ: <code>io</code>・<code>os</code>・<code>debug</code>・<code>coroutine</code>・
|
||||
<code>package</code>・<code>ffi</code> は無効です(<a href="stdlib.html">標準ライブラリ</a>)。</li>
|
||||
<li><code>obj.getaudio</code> が 1 回で取得できるデータ数は最大 1024 個です。取得できない場合は
|
||||
データ数 0 を返し、エラーにはなりません。</li>
|
||||
</ul>
|
||||
|
||||
<h2>乱数について</h2>
|
||||
|
||||
+85
-2
@@ -31,6 +31,7 @@
|
||||
<p>
|
||||
返り値は対象アイテム自身の座標・回転・拡大率であり、グループ制御・カメラ制御による変形は含みません。
|
||||
同じタグのアイテムが複数あるときは、対象フレームで表示中のものが優先されます。
|
||||
音声アイテム(合成音声等)も対象になり、座標・拡大率・回転・不透明度は字幕の表示情報を返します。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
@@ -42,8 +43,24 @@
|
||||
<tr><td><code>rx</code> / <code>ry</code> / <code>rxr</code> / <code>ryr</code></td><td>常に 0(X・Y 軸回転は取得しません)</td></tr>
|
||||
<tr><td><code>alpha</code></td><td>不透明度(0.0 ~ 255.0)</td></tr>
|
||||
<tr><td><code>layer</code></td><td>レイヤー番号</td></tr>
|
||||
<tr><td><code>length</code></td><td>アイテムの長さ(フレーム数)</td></tr>
|
||||
<tr><td><code>volume</code></td><td>音量設定の現在値(音声アイテムのみ。他は 0)</td></tr>
|
||||
<tr><td><code>character</code></td><td>キャラクター名(音声アイテムのみ。他は空文字列)</td></tr>
|
||||
<tr><td><code>text</code></td><td>セリフまたは表示テキスト(音声・テキストアイテムのみ。他は空文字列)</td></tr>
|
||||
<tr><td><code>kind</code></td><td>アイテムの種別名(例:VoiceItem, TextItem, ImageItem)</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
<code>length</code> / <code>volume</code> / <code>character</code> / <code>text</code> / <code>kind</code> は
|
||||
AviUtl に存在しない YMM4 向けの独自拡張です。従来エンジンと高速ランタイムの両方で動作します。
|
||||
</div>
|
||||
|
||||
<h3>キャラクター名で演出を分ける</h3>
|
||||
<pre><code>local v = obj.getobject("voice")
|
||||
if v and v.character == "魔理沙" then
|
||||
obj.effect("単色化", "強さ", 100, "color", 0xffee55)
|
||||
end</code></pre>
|
||||
|
||||
<h3>発射元の座標に合わせる</h3>
|
||||
<pre><code>local src = obj.getobject("routersys")
|
||||
if src then
|
||||
@@ -114,7 +131,7 @@ end</code></pre>
|
||||
<code>anim.noise</code> が便利です。<code>obj.rand</code> は整数を返す AviUtl 互換の乱数です。
|
||||
</div>
|
||||
|
||||
<h2>obj.load — 図形・テキスト・画像・動画の読み込み</h2>
|
||||
<h2>obj.load — 図形・テキスト・画像・動画・シーン・模様の読み込み</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.load(種類, ...)</code> は、対象の画像バッファを生成した内容で置き換えます。
|
||||
@@ -127,8 +144,41 @@ end</code></pre>
|
||||
<tr><td><code>obj.load("text", str)</code></td><td>文字列を描画。フォントは <code>obj.setfont</code> の設定を使う</td></tr>
|
||||
<tr><td><code>obj.load("image", path)</code></td><td>画像ファイルを読み込む</td></tr>
|
||||
<tr><td><code>obj.load("movie", path [, time])</code></td><td>動画の指定時刻のフレームを読み込む(既定は現在時刻)</td></tr>
|
||||
<tr><td><code>obj.load("scene", name [, time])</code></td><td>プロジェクト内の別シーンを指定時刻で描画して読み込む(既定は現在時刻)</td></tr>
|
||||
<tr><td><code>obj.load("brush", name [, w, h])</code></td><td>YMM4 の模様(ブラシ)で塗り潰した画像を読み込む(既定サイズは現在の <code>obj.w</code> / <code>obj.h</code>)</td></tr>
|
||||
</table>
|
||||
|
||||
<div class="note">
|
||||
<code>"scene"</code> と <code>"brush"</code> は AviUtl に存在しない YMM4 向けの独自拡張です。
|
||||
シーン名と模様名には、それぞれ YMM4 のシーン一覧と模様一覧に表示される名前を指定します。
|
||||
現在のオブジェクトが乗っているシーン自身は読み込めず、シーン描画の中からさらにシーンを読み込むこともできません。
|
||||
シーンを読み込んだフレームは描画キャッシュを使わず毎回再実行されます。
|
||||
模様はブラシプラグインで追加したものも使えますが、パラメータは既定値で描画されます。
|
||||
パラメータを変更したいときは <code>obj.brush</code> を使います。
|
||||
</div>
|
||||
|
||||
<h2>obj.brush — 模様のパラメータ指定付き描画</h2>
|
||||
|
||||
<p>
|
||||
<code>obj.brush(模様名 [, 幅, 高さ] [, パラメータ名, 値, ...])</code> は、YMM4 の模様(ブラシ)を
|
||||
パラメータ指定付きで描画してオブジェクトの画像を置き換えます。描画は <code>obj.load("brush", ...)</code> と同じで、
|
||||
加えて <code>obj.effect</code> と同じ「名前と値の組」で模様のパラメータを変更できます。
|
||||
AviUtl に存在しない YMM4 向けの独自拡張です。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>引数</th><th>説明</th></tr>
|
||||
<tr><td><code>模様名</code></td><td>模様一覧に表示される名前</td></tr>
|
||||
<tr><td><code>幅, 高さ</code></td><td>生成サイズ(px)。省略時は現在の <code>obj.w</code> / <code>obj.h</code>。両方を数値で並べたときだけサイズとして解釈する</td></tr>
|
||||
<tr><td><code>パラメータ名, 値</code></td><td>模様の設定項目の表示名または内部のプロパティ名と、その値の組。値は数値・真偽値・文字列で、色は <code>0xRRGGBB</code> の数値</td></tr>
|
||||
</table>
|
||||
|
||||
<pre><code>obj.brush("縞模様", "Angle", 45, "Color1", 0xff3366)</code></pre>
|
||||
|
||||
<div class="note">
|
||||
指定しなかったパラメータは既定値で描画されます。組をすべて省略した呼び出しは <code>obj.load("brush")</code> と同じです。
|
||||
</div>
|
||||
|
||||
<p><code>obj.load("figure", ...)</code> で指定できる図形名は次のとおりです。</p>
|
||||
|
||||
<table>
|
||||
@@ -171,6 +221,7 @@ obj.load("text", "サンプル")</code></pre>
|
||||
<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.getvalue(name)</code></td><td><code>obj</code> の数値メンバーを名前で取得する</td></tr>
|
||||
<tr><td><code>obj.getaudio(buf, file [, type, size])</code></td><td>音声データを取得する。詳細は下記の「音声データ」を参照</td></tr>
|
||||
<tr><td><code>obj.getinfo(name)</code></td><td>各種の環境情報を名前で取得する。詳細は下記の「環境情報」を参照</td></tr>
|
||||
<tr><td><code>obj.pixeloption(name [, value])</code></td><td>ピクセル処理向けのオプションを設定する</td></tr>
|
||||
<tr><td><code>obj.setanchor(name, count [, option, ...])</code></td><td>プレビュー上にドラッグ可能なアンカーポイントを表示し、その座標を <code>name</code> の Lua 変数へ格納する。設置数を返す。詳細は下記の「アンカーポイント」を参照</td></tr>
|
||||
@@ -309,7 +360,7 @@ GPU を利用できない環境では呼び出しはスキップされ、画像
|
||||
|
||||
<p>
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
<code>name</code> に <code>"track"</code> を指定した場合も対応し、個数 0 は 1 個として設置します。選択中のアンカーは アンカー グループの <code>X</code> / <code>Y</code> / <code>Z</code> スライダーで数値調整できます。
|
||||
<code>name</code> に <code>"track"</code> を指定した場合も対応し、個数 0 は 1 個として設置します。選択中のアンカーは「アンカー」グループの <code>X</code> / <code>Y</code> / <code>Z</code> スライダーで数値調整できます。
|
||||
</p>
|
||||
|
||||
<pre><code>num = obj.track0
|
||||
@@ -318,6 +369,38 @@ for i = 0, num - 1 do
|
||||
obj.draw(pos[i * 2 + 1], pos[i * 2 + 2])
|
||||
end</code></pre>
|
||||
|
||||
<h3>音声データ</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.getaudio(buf, file [, type, size])</code> は音声データを取得します。
|
||||
<code>buf</code> に渡したテーブルの <code>buf[1]</code>~<code>buf[n]</code> へデータを格納し、取得したデータ数とサンプリングレートを返します。
|
||||
<code>buf</code> に <code>nil</code> を渡すと、テーブルを 3 番目の戻り値として返します。
|
||||
<code>file</code> には音声ファイルのパスを指定します。<code>"audiobuffer"</code> を指定すると、編集中のシーン全体の音声(タイムライン上の全アイテムを合成した音声)を取得します。
|
||||
YMM4 独自の拡張として <code>"itembuffer"</code> も指定でき、このエフェクトを付けたアイテム自身の音声(音量・パン・フェード・音声エフェクト適用後)を取得します。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr><th>type</th><th>内容</th></tr>
|
||||
<tr><td><code>"pcm"</code></td><td>16bit スケール基準(-32768~32767)のモノラル PCM</td></tr>
|
||||
<tr><td><code>"spectrum"</code></td><td>周波数帯ごとの音量データ(0~32768 目安)。<code>size</code> は分割する帯域の数で、最大 512、省略時は 32</td></tr>
|
||||
<tr><td><code>"fourier"</code></td><td>離散フーリエ変換の振幅データ(0.0~1.0 目安)。周波数範囲は 1/2048~1/2 で、省略時は 1024 個</td></tr>
|
||||
<tr><td><code>"xxxx.l"</code> / <code>"xxxx.r"</code></td><td>上記種別の左 / 右チャンネル版。無指定のときは左右の平均</td></tr>
|
||||
</table>
|
||||
|
||||
<p>
|
||||
読み取り位置は、<code>"audiobuffer"</code> はタイムラインの現在の再生位置、それ以外はオブジェクトの現在の再生位置(<code>obj.time</code>)です。
|
||||
<code>"pcm"</code> は現在位置から連続したサンプルを返し、<code>"spectrum"</code>/<code>"fourier"</code> は現在位置からの区間を解析して返します。
|
||||
1 回で取得できるデータ数は最大 1024 個で、取得できた数が指定より少ないことがあります。
|
||||
取得できない場合はデータ数 0 を返し、エラーにはなりません。両エンジンで動きます。
|
||||
<code>"itembuffer"</code> は音声を持たないアイテム(画像や図形等)ではデータ数 0 になります。
|
||||
</p>
|
||||
|
||||
<pre><code>local buf = {}
|
||||
local n = obj.getaudio(buf, "audiobuffer", "spectrum", 32)
|
||||
for i = 1, n do
|
||||
obj.draw((i - n / 2) * 8, -buf[i] / 200)
|
||||
end</code></pre>
|
||||
|
||||
<h3>環境情報</h3>
|
||||
|
||||
<p>
|
||||
|
||||
+6
-2
@@ -77,22 +77,26 @@
|
||||
<h2>obj 関数</h2>
|
||||
<table>
|
||||
<tr><th>関数</th><th>説明</th></tr>
|
||||
<tr><td><code>obj.getobject(tag [, frame])</code></td><td>他アイテムの描画情報を取得</td></tr>
|
||||
<tr><td><code>obj.getobject(tag [, frame])</code></td><td>他アイテムの描画情報・キャラクター名・セリフ・音量を取得</td></tr>
|
||||
<tr><td><code>obj.getpixel(x, y)</code></td><td>ピクセル取得</td></tr>
|
||||
<tr><td><code>obj.setpixel(x, y, r, g, b [, a])</code></td><td>ピクセル書き込み</td></tr>
|
||||
<tr><td><code>obj.getpixeldata()</code></td><td>ピクセル直接アクセスプロキシ</td></tr>
|
||||
<tr><td><code>obj.putpixeldata()</code></td><td>互換用の空実装</td></tr>
|
||||
<tr><td><code>obj.rand(a, b [, seed [, frame]])</code></td><td>整数の安定した乱数</td></tr>
|
||||
<tr><td><code>obj.load(種類, ...)</code></td><td>図形 / テキスト / 画像 / 動画の読み込み</td></tr>
|
||||
<tr><td><code>obj.load(種類, ...)</code></td><td>図形 / テキスト / 画像 / 動画 / シーン / 模様の読み込み</td></tr>
|
||||
<tr><td><code>obj.setfont(name [, size [, type [, color]]])</code></td><td>フォント設定</td></tr>
|
||||
<tr><td><code>obj.effect(name, key, val, ...)</code></td><td>AviUtl/AviUtl2 互換マップ経由でエフェクトを適用</td></tr>
|
||||
<tr><td><code>obj.brush(name [, w, h] [, key, val, ...])</code></td><td>YMM4 の模様をパラメータ指定付きで描画</td></tr>
|
||||
<tr><td><code>obj.draw([ox, oy, oz, zoom, alpha, aspect])</code></td><td>バッファの描画</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.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>HLSL のピクセルシェーダーを GPU で実行</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.getaudio(buf, file [, type, size])</code></td><td>音声データ(PCM・スペクトラム・フーリエ変換)の取得</td></tr>
|
||||
<tr><td><code>obj.getinfo(name)</code></td><td>環境情報を名前で取得</td></tr>
|
||||
<tr><td><code>obj.pixeloption(name [, value])</code></td><td>ピクセル処理オプション</td></tr>
|
||||
<tr><td><code>obj.setanchor(name, count [, option, ...])</code></td><td>ドラッグ可能なアンカーポイントの表示と座標の格納</td></tr>
|
||||
</table>
|
||||
|
||||
<h2>anim(定数)</h2>
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@
|
||||
</p>
|
||||
|
||||
<div class="note">
|
||||
変換は字句単位で行い、<strong>文字列とコメントの内側は変換しません</strong>。
|
||||
変換は字句単位で行い、文字列とコメントの内側は変換しません。
|
||||
また Lua に存在しない記号(<code>?</code> <code>!</code> <code>&</code> <code>|</code> <code>=></code> <code>`</code> や <code>in <</code> の並び)だけを入口にしているため、
|
||||
通常の Lua スクリプトはそのまま動作します。
|
||||
</div>
|
||||
|
||||
+118
-16
@@ -70,7 +70,7 @@ local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
|
||||
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
|
||||
local CB_TAG_MAX = 8192
|
||||
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
|
||||
local STRING_PARAMS_OFFSET = CB_RESULT_OFFSET + 8 * 8
|
||||
local STRING_PARAMS_OFFSET = CB_RESULT_OFFSET + 10 * 8
|
||||
local DRAW_RING_CAPACITY = 4096
|
||||
local DRAW_ENTRY_DOUBLES = 24
|
||||
local DRAW_RING_DOUBLES = 1 + DRAW_RING_CAPACITY * DRAW_ENTRY_DOUBLES
|
||||
@@ -95,6 +95,10 @@ local CB_KIND_SCENEGET = 11
|
||||
local CB_KIND_SCENESET = 12
|
||||
local CB_KIND_PIXELSHADER_STAGE = 13
|
||||
local CB_KIND_PIXELSHADER_RUN = 14
|
||||
local CB_KIND_LOADSCENE = 15
|
||||
local CB_KIND_LOADBRUSH = 16
|
||||
local CB_KIND_BRUSH = 17
|
||||
local CB_KIND_GETAUDIO = 18
|
||||
local MAX_PIXEL_BUFFER = 3840 * 2160 * 4
|
||||
local SHADER_META_DOUBLES = 20
|
||||
local SHADER_CONSTANTS_MAX = 1024
|
||||
@@ -519,25 +523,39 @@ local function loadMovie(path, time)
|
||||
applyLoadResult()
|
||||
end
|
||||
|
||||
function obj.load(kind, ...)
|
||||
if kind == "figure" then
|
||||
loadFigure(...)
|
||||
elseif kind == "text" then
|
||||
loadText(...)
|
||||
elseif kind == "image" then
|
||||
loadImage(...)
|
||||
elseif kind == "movie" then
|
||||
loadMovie(...)
|
||||
end
|
||||
local function loadScene(name, time)
|
||||
local payload = tostring(name or "")
|
||||
local len = #payload
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
i32[OFF_CB_KIND] = CB_KIND_LOADSCENE
|
||||
cbResult[0] = time or obj.time or 0
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
applyLoadResult()
|
||||
end
|
||||
|
||||
function obj.effect(name, ...)
|
||||
if type(name) ~= "string" then return end
|
||||
local args = { ... }
|
||||
local n = select("#", ...)
|
||||
local function loadBrush(name, w, h)
|
||||
local payload = tostring(name or "")
|
||||
local len = #payload
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
i32[OFF_CB_KIND] = CB_KIND_LOADBRUSH
|
||||
cbResult[0] = w or width
|
||||
cbResult[1] = h or height
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
applyLoadResult()
|
||||
end
|
||||
|
||||
local function writeNamedArgs(name, args, first, n)
|
||||
local parts = { name }
|
||||
local pos = #name + 1
|
||||
for i = 1, n - 1, 2 do
|
||||
for i = first, n - 1, 2 do
|
||||
local k = tostring(args[i])
|
||||
local v = args[i + 1]
|
||||
local encoded
|
||||
@@ -559,6 +577,30 @@ function obj.effect(name, ...)
|
||||
local len = #payload
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||
return len
|
||||
end
|
||||
|
||||
function obj.load(kind, ...)
|
||||
if kind == "figure" then
|
||||
loadFigure(...)
|
||||
elseif kind == "text" then
|
||||
loadText(...)
|
||||
elseif kind == "image" then
|
||||
loadImage(...)
|
||||
elseif kind == "movie" then
|
||||
loadMovie(...)
|
||||
elseif kind == "scene" then
|
||||
loadScene(...)
|
||||
elseif kind == "brush" then
|
||||
loadBrush(...)
|
||||
end
|
||||
end
|
||||
|
||||
function obj.effect(name, ...)
|
||||
if type(name) ~= "string" then return end
|
||||
local args = { ... }
|
||||
local n = select("#", ...)
|
||||
local len = writeNamedArgs(name, args, 1, n)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
i32[OFF_CB_KIND] = CB_KIND_EFFECT
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
@@ -566,6 +608,28 @@ function obj.effect(name, ...)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
end
|
||||
|
||||
function obj.brush(name, ...)
|
||||
if type(name) ~= "string" then return end
|
||||
local args = { ... }
|
||||
local n = select("#", ...)
|
||||
local first = 1
|
||||
local w, h
|
||||
if n >= 2 and type(args[1]) == "number" and type(args[2]) == "number" then
|
||||
w = args[1]
|
||||
h = args[2]
|
||||
first = 3
|
||||
end
|
||||
local len = writeNamedArgs(name, args, first, n)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
i32[OFF_CB_KIND] = CB_KIND_BRUSH
|
||||
cbResult[0] = w or width
|
||||
cbResult[1] = h or height
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
applyLoadResult()
|
||||
end
|
||||
|
||||
function obj.draw(ox, oy, oz, zoom, alpha, aspect)
|
||||
if drawTarget == "temp" then
|
||||
ensurePixels()
|
||||
@@ -627,6 +691,30 @@ function obj.getvalue(target)
|
||||
return 0
|
||||
end
|
||||
|
||||
function obj.getaudio(buf, file, datatype, size)
|
||||
if type(file) ~= "string" then return 0, 0 end
|
||||
local payload = file .. "\0" .. tostring(datatype or "pcm")
|
||||
local len = #payload
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, payload, len)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
cbResult[0] = tonumber(size) or 0
|
||||
i32[OFF_CB_KIND] = CB_KIND_GETAUDIO
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
local count = math.floor(cbResult[0])
|
||||
local rate = math.floor(cbResult[1])
|
||||
local out = buf
|
||||
if type(out) ~= "table" then
|
||||
if buf ~= nil then return count, rate end
|
||||
out = {}
|
||||
end
|
||||
for i = 0, count - 1 do out[i + 1] = cbTagD[i] end
|
||||
if buf == nil then return count, rate, out end
|
||||
return count, rate
|
||||
end
|
||||
|
||||
function obj.getinfo(name)
|
||||
if name == "script_path" then return scriptPath end
|
||||
if name == "filter" then return true end
|
||||
@@ -847,6 +935,7 @@ end
|
||||
|
||||
local cacheTag, cacheFrame, cacheFound
|
||||
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
|
||||
local cacheVolume, cacheLength, cacheCharacter, cacheText, cacheKind
|
||||
|
||||
local function buildObject()
|
||||
return {
|
||||
@@ -856,6 +945,8 @@ local function buildObject()
|
||||
rx = 0, ry = 0, rz = cacheRz,
|
||||
rxr = 0, ryr = 0, rzr = cacheRz * math.pi / 180,
|
||||
alpha = cacheAlpha, layer = cacheLayer,
|
||||
volume = cacheVolume, length = cacheLength,
|
||||
character = cacheCharacter, text = cacheText, kind = cacheKind,
|
||||
}
|
||||
end
|
||||
|
||||
@@ -1053,6 +1144,17 @@ function obj.getobject(tag, frame)
|
||||
cacheExist = cbResult[0] ~= 0
|
||||
cacheX = cbResult[1]; cacheY = cbResult[2]; cacheZ = cbResult[3]
|
||||
cacheZoom = cbResult[4]; cacheRz = cbResult[5]; cacheAlpha = cbResult[6]; cacheLayer = cbResult[7]
|
||||
cacheVolume = cbResult[8]; cacheLength = cbResult[9]
|
||||
local meta = ffi.string(base + CB_TAG_OFFSET, i32[OFF_CB_TAGLEN])
|
||||
local s1 = meta:find("\0", 1, true)
|
||||
local s2 = s1 and meta:find("\0", s1 + 1, true)
|
||||
if s1 and s2 then
|
||||
cacheCharacter = meta:sub(1, s1 - 1)
|
||||
cacheText = meta:sub(s1 + 1, s2 - 1)
|
||||
cacheKind = meta:sub(s2 + 1)
|
||||
else
|
||||
cacheCharacter = ""; cacheText = ""; cacheKind = ""
|
||||
end
|
||||
return buildObject()
|
||||
end
|
||||
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする