コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
481bce261e
|
||
|
|
421acf1a6a
|
||
|
|
1d01e9d275
|
||
|
|
1a3394b8f5
|
||
|
|
52bbff8284
|
||
|
|
b150970f83
|
||
|
|
6ce23d486a
|
||
|
|
024723a029
|
||
|
|
4746f01134
|
||
|
|
f2ea36ba49
|
||
|
|
adf47608d2
|
||
|
|
f916c810dc
|
||
|
|
9b86a3cb10
|
||
|
|
0fd1194596
|
||
|
|
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
|
検索条件に一致するファイルはありません
+15
-45
@@ -1,62 +1,32 @@
|
||||
# v1.17.0 - Lua スクリプト for YMM4
|
||||
# v1.19.2 - Lua スクリプト for YMM4
|
||||
|
||||
YMM4 のシーンと模様(ブラシ)をスクリプトから利用できるようにしたリリースです。obj.load へ読込種別 "scene" と "brush" を追加し、プロジェクト内の別シーンの映像と、模様で塗り潰した画像を、オブジェクトの画像として読み込めるようにしました。さらに obj.brush を追加し、obj.effect と同じ「名前と値の組」で模様のパラメータを変更しながら描画できるようにしました。いずれも AviUtl / AviUtl2 の obj.load と obj には存在しない YMM4 向けの独自拡張で、シーンの描画も模様の描画も YMM4 のプラグイン公開 API だけで実装しています。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)の両方で動作し、実行結果は両エンジンで一致します。
|
||||
従来エンジン(MoonSharp)の毎フレームのグローバル変数更新を高速化したパッチリリースです。スクリプトの書き方と実行結果は一切変わりません。高速ランタイム(LuaJIT)の実装にも変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 新機能
|
||||
## 改善
|
||||
|
||||
### obj.load("scene", シーン名 [, 時間])
|
||||
### 毎フレームのグローバル変数更新のボックス化を除去
|
||||
|
||||
プロジェクト内の別シーンを指定時刻で描画し、オブジェクトのバッファを置き換えます。
|
||||
従来エンジンは実行のたびに obj / scene / ymm4 / グローバルの約 70 個の変数をテーブルへ書き込みます。この書き込みが object 型のインデクサ経由で、数値・真偽値のボックス化と型変換のディスパッチを毎回発生させていました。ソースジェネレーターの発行を型付きの Table.Set へ変更し、ボックス化と変換ディスパッチを削除しました。
|
||||
|
||||
obj.load("scene", "サブシーン", obj.time)
|
||||
|
||||
- シーン名には YMM4 のシーン一覧に表示される名前を指定します。時間は秒で、省略すると obj.time を用います。読み込み後は obj.w / obj.h などの寸法がシーンの解像度へ更新され、load 直後の getpixel でも参照できます。
|
||||
- シーンの描画には YMM4 のプラグイン公開 API である ISceneInfo.TryCreateVideoSource を用います。YMM4 本体のシーンアイテムと同じ経路で描画するため、シーンの内容もエフェクトもそのまま反映されます。
|
||||
- 現在のオブジェクトが乗っているシーン自身は指定できません。シーン描画の中からさらにシーンを読み込む形も拒否し、シーン同士の相互参照による無限再帰を防ぎます。
|
||||
- 参照先シーンの内容の変化は描画鍵では検知できないため、シーンを読み込んだフレームは描画キャッシュを使わず毎回再実行します。編集中の参照先シーンの変更が、そのまま次の描画へ反映されます。
|
||||
|
||||
### obj.load("brush", 模様名 [, 幅, 高さ])
|
||||
|
||||
YMM4 の模様(ブラシ)で塗り潰した画像を生成し、オブジェクトのバッファを置き換えます。
|
||||
|
||||
obj.load("brush", "縞模様", 400, 300)
|
||||
|
||||
- 模様名には YMM4 の模様一覧に表示される名前を指定します。ブラシプラグインで追加した模様もそのまま使えます。
|
||||
- 幅と高さを省略すると現在の obj.w / obj.h を用います。模様のパラメータは既定値で描画されます。
|
||||
- 塗り潰しは Direct2D のブラシで中心原点の矩形に対して行い、生成した画像は他の読込種別と同じ乗算済みアルファの BGRA として扱われます。
|
||||
|
||||
### obj.brush(模様名 [, 幅, 高さ] [, パラメータ名, 値, ...])
|
||||
|
||||
模様のパラメータを変更しながら描画します。描画は obj.load("brush") と同じで、加えて obj.effect と同じ「名前と値の組」を受け付けます。
|
||||
|
||||
obj.brush("縞模様", "Angle", 45, "Color1", 0xff3366)
|
||||
|
||||
- パラメータ名には模様の設定項目の表示名、または内部のプロパティ名を指定します。値は数値・真偽値・文字列に対応し、色は 0xRRGGBB の数値で指定します。
|
||||
- 模様名の直後に数値を 2 つ並べたときだけ、それを幅と高さとして解釈します。パラメータ名は常に文字列のため、サイズと組が曖昧になることはありません。
|
||||
- 指定しなかったパラメータは既定値で描画されます。組をすべて省略した呼び出しは obj.load("brush") と同じです。
|
||||
- パラメータの解決は obj.effect と同じ仕組みです。表示名と内部名の両方を受け付け、対応しない名前の組は無視されます。
|
||||
- 数値は DynValue.NewNumber、文字列は DynValue.NewString の直接生成になります。
|
||||
- 真偽値は MoonSharp が共有する DynValue の参照になり、割り当てが完全になくなります。
|
||||
- obj.load / obj.copybuffer / obj.resize の後の寸法更新(obj.w 等の 8 個)も同じ形へ揃えました。
|
||||
|
||||
---
|
||||
|
||||
## 互換性・後方互換
|
||||
|
||||
- 既存の読込種別 "figure" / "text" / "image" / "movie" の挙動に変更はありません。新設の読込に失敗した場合は、従来の読込の失敗時と同様に現在の画像を保持します。
|
||||
- "scene" / "brush" / obj.brush は AviUtl / AviUtl2 に存在しない YMM4 向けの独自拡張です。AviUtl 向けに書かれた既存スクリプトへの影響はありません。
|
||||
- obj.effect のパラメータ適用の実装を模様と共有する形へ整理しましたが、名前の解決規則、値の変換、互換マップの扱いのいずれも従来のままで、適用結果は変わりません。
|
||||
- エンジンの自動振り分け、エンジン指定ディレクティブの仕様と優先順位、カーネル化の対象、v1.16.3 までの構文拡張と既存の API に変更はありません。
|
||||
- すべての変数の名前・型・値に変更はありません。ボックス化と変換ディスパッチの除去のみで、テーブルへ格納される内容は従来と同一です。
|
||||
- 両エンジンの実行結果はバイト単位まで一致したままです。
|
||||
- v1.19.1 までの構文拡張と既存の API に変更はありません。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- シーンの描画は新設の SceneImageRenderer が担います。シーン ID ごとに ITimelineSource をキャッシュし、専用のデバイスコンテキストで描画した出力をステージングビットマップ経由で読み戻します。読み戻し用の緩衝は伸長のみの再利用で、定常状態の毎フレームの割り当てはありません。入れ子のシーン読込の拒否はスレッド静的な深さガードで行い、同一スレッド上の再帰だけを対象にするため競合はありません。
|
||||
- 模様の描画は新設の BrushImageRenderer が担います。模様名ごとにブラシのパラメータとソースの組をキャッシュし、PixelBufferManager へ追加した LoadBrushPixels で中心原点の矩形を塗り潰して読み戻します。ブラシのソースは Update のたびにパラメータの現在値を読み直すため、キャッシュしたソースへのパラメータ変更がそのまま反映されます。
|
||||
- obj.brush のパラメータの組が前回の呼び出しと異なる名前の集合になったときは、パラメータを既定値から作り直してから適用します。結果が現在の呼び出しの引数だけで決まり、以前の呼び出しで変更した値が残らないようにするためです。同じ名前の集合の間は値の上書きだけで済ませ、毎フレームの作り直しを避けます。
|
||||
- パラメータの適用機構は VideoEffectChain から Ymm4PropertyBinder へ抽出し、obj.effect と obj.brush が同じ実装を共有します。プロパティ表のキャッシュは、エフェクトの適用が描画スレッド、模様の適用がスクリプトの実行スレッドで走るようになったため、ロックで保護しました。
|
||||
- どちらのレンダラーもエフェクトプロセッサの画素読込セマフォの中で実行し、実行スレッドと描画スレッドの Direct2D の競合を既存の合成経路と同じ方法で防ぎます。
|
||||
- 高速ランタイムにはプロセス間手順の呼出種別 CbKindLoadScene / CbKindLoadBrush / CbKindBrush を追加しました。シーンは動画読込と同じ経路、obj.brush は obj.effect と同じ名前と値の符号化に幅と高さを添えた経路で、ホスト側の描画結果を共有メモリへ書き戻します。名前と値の組の符号化と復号は、ワーカー側もホスト側も obj.effect の実装と共有しています。
|
||||
- MoonSharp レーンはコンテキストへ追加した読込委譲 SceneImageLoader / BrushImageLoader を経由してホスト側のレンダラーを呼び出します。委譲が未設定のテスト環境では読込は無操作になります。
|
||||
- ドキュメントは付属の 8 言語、サイトの obj の関数・リファレンス・トップのページ、README を更新しました。
|
||||
- テストは 3332 件です。v1.16.3 の 3317 件から、MoonSharp レーンの scene / brush 読込の委譲の往復・時間とサイズの既定値・失敗時の画像保持、obj.brush の組の解析・先頭サイズの解釈・組なしの呼び出し、高速ランタイムの scene / brush / obj.brush の呼出種別の往復の検証を追加しました。ソリューションは x64 で 0 個の警告、0 個のエラーです。
|
||||
- 型付き発行は LuaApiGenerator が担います。更新メソッドの戻り値型(double / int / bool / string とその null 許容)から値種別を判定し、DynValue.NewNumber / NewBoolean / NewString を包んだ Table.Set を発行します。未知の型は従来のインデクサ発行へ残すため、後方互換は構造的に保たれます。
|
||||
- 発行部 1 箇所の変更で全レジストラ(AviUtlGlobalRegistrar / SceneTableRegistrar / Ymm4TableRegistrar / obj テーブル)に波及します。個別の書き換えはありません。
|
||||
- 数値の DynValue 生成自体は値が毎フレーム変わるため残ります。共有インスタンスの書き換えはスクリプトが参照を保持しうるため行いません。
|
||||
- テストは 3366 件のまま全件成功です。ソリューションは x64 で 0 個の警告、0 個のエラーです。
|
||||
@@ -1,11 +1,11 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.17.0
|
||||
Luaスクリプト for YMM4 v1.19.2
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
スクリプトの実行にはMoonSharpによるLuaインタプリタを使用しており、座標・拡大率・
|
||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きにも
|
||||
対応しています。
|
||||
透明度・回転といった描画パラメータの変更に加えて、ピクセル単位での読み書きや、
|
||||
塗りつぶし・領域の一括読み書き・畳み込み・拡大縮小による画像加工にも対応しています。
|
||||
obj.x/y/zoom/alpha等の値はキーフレームアニメーションと連動するTrack0~3パラメータ
|
||||
からも参照でき、anim.*関数群によるイージングやノイズ等の演出も組み合わせられます。
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
@@ -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.17.0</Version>
|
||||
<Version>1.19.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -39,7 +39,15 @@ namespace LuaScript.Generator
|
||||
OptionalReference,
|
||||
}
|
||||
|
||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind);
|
||||
internal enum LuaValueKind
|
||||
{
|
||||
Number,
|
||||
Boolean,
|
||||
String,
|
||||
Other,
|
||||
}
|
||||
|
||||
internal sealed record LuaUpdateModel(string LuaName, string MethodName, LuaUpdateKind Kind, LuaValueKind ValueKind);
|
||||
|
||||
internal sealed record LuaCatalogEntry(
|
||||
string Table,
|
||||
@@ -309,12 +317,30 @@ namespace LuaScript.Generator
|
||||
|
||||
var returnType = method.ReturnType;
|
||||
LuaUpdateKind kind;
|
||||
ITypeSymbol valueType;
|
||||
if (returnType.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
|
||||
{
|
||||
kind = LuaUpdateKind.OptionalValue;
|
||||
valueType = ((INamedTypeSymbol)returnType).TypeArguments[0];
|
||||
}
|
||||
else if (returnType.IsReferenceType)
|
||||
{
|
||||
kind = LuaUpdateKind.OptionalReference;
|
||||
valueType = returnType;
|
||||
}
|
||||
else
|
||||
{
|
||||
kind = LuaUpdateKind.Direct;
|
||||
valueType = returnType;
|
||||
}
|
||||
|
||||
var valueKind = valueType.SpecialType switch
|
||||
{
|
||||
SpecialType.System_Double or SpecialType.System_Int32 => LuaValueKind.Number,
|
||||
SpecialType.System_Boolean => LuaValueKind.Boolean,
|
||||
SpecialType.System_String => LuaValueKind.String,
|
||||
_ => LuaValueKind.Other,
|
||||
};
|
||||
|
||||
bool inCatalog = true;
|
||||
foreach (var argument in attribute.NamedArguments)
|
||||
@@ -325,7 +351,7 @@ namespace LuaScript.Generator
|
||||
|
||||
if (inCatalog)
|
||||
entry = new LuaCatalogEntry(tableName, luaName, false, EquatableArray<string>.Empty);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind);
|
||||
return new LuaUpdateModel(luaName, method.Name, kind, valueKind);
|
||||
}
|
||||
|
||||
private static string FormatDouble(double value) =>
|
||||
@@ -387,13 +413,19 @@ namespace LuaScript.Generator
|
||||
switch (update.Kind)
|
||||
{
|
||||
case LuaUpdateKind.OptionalValue:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table[\"{update.LuaName}\"] = value.Value; }}"
|
||||
: $"{body}{{ var value = {update.MethodName}(context); if (value.HasValue) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value.Value")}); }}");
|
||||
break;
|
||||
case LuaUpdateKind.OptionalReference:
|
||||
builder.AppendLine($"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table[\"{update.LuaName}\"] = value; }}"
|
||||
: $"{body}{{ var value = {update.MethodName}(context); if (value is not null) table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, "value")}); }}");
|
||||
break;
|
||||
default:
|
||||
builder.AppendLine($"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);");
|
||||
builder.AppendLine(update.ValueKind == LuaValueKind.Other
|
||||
? $"{body}table[\"{update.LuaName}\"] = {update.MethodName}(context);"
|
||||
: $"{body}table.Set(\"{update.LuaName}\", {WrapValue(update.ValueKind, $"{update.MethodName}(context)")});");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -409,6 +441,13 @@ namespace LuaScript.Generator
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static string WrapValue(LuaValueKind kind, string expression) => kind switch
|
||||
{
|
||||
LuaValueKind.Number => $"global::MoonSharp.Interpreter.DynValue.NewNumber({expression})",
|
||||
LuaValueKind.Boolean => $"global::MoonSharp.Interpreter.DynValue.NewBoolean({expression})",
|
||||
_ => $"global::MoonSharp.Interpreter.DynValue.NewString({expression})",
|
||||
};
|
||||
|
||||
private static string EmitArguments(EquatableArray<LuaParameterModel> parameters)
|
||||
{
|
||||
var rendered = new List<string>();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.17.0</Version>
|
||||
<Version>1.19.2</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.17.0</Version>
|
||||
<Version>1.19.2</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.17.0</Version>
|
||||
<Version>1.19.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -76,6 +76,8 @@ namespace LuaScript
|
||||
|
||||
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;
|
||||
@@ -502,5 +504,281 @@ namespace LuaScript
|
||||
p[3] = (byte)Math.Clamp(a, 0d, 255d);
|
||||
}
|
||||
}
|
||||
|
||||
private double[]? _convolveSource;
|
||||
private byte[]? _resizeSource;
|
||||
private byte[]? _resizeBuffer;
|
||||
|
||||
public unsafe void FillBuffer(double r, double g, double b, double a, int x, int y, int w, int h)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
int x0 = Math.Clamp(x, 0, cw);
|
||||
int y0 = Math.Clamp(y, 0, ch);
|
||||
int x1 = Math.Clamp(x + w, 0, cw);
|
||||
int y1 = Math.Clamp(y + h, 0, ch);
|
||||
if (x1 <= x0 || y1 <= y0)
|
||||
return;
|
||||
|
||||
_isPixelsDirty = true;
|
||||
double aK = Math.Clamp(a, 0d, 255d) / 255d;
|
||||
byte pb = (byte)Math.Clamp(b * aK, 0d, 255d);
|
||||
byte pg = (byte)Math.Clamp(g * aK, 0d, 255d);
|
||||
byte pr = (byte)Math.Clamp(r * aK, 0d, 255d);
|
||||
byte pa = (byte)Math.Clamp(a, 0d, 255d);
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int py = y0; py < y1; py++)
|
||||
{
|
||||
byte* p = buf + (py * cw + x0) * 4;
|
||||
for (int px = x0; px < x1; px++)
|
||||
{
|
||||
p[0] = pb;
|
||||
p[1] = pg;
|
||||
p[2] = pr;
|
||||
p[3] = pa;
|
||||
p += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void ReadRegion(int x, int y, int w, int h, double[] destination)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
if (_pixelBuffer is null)
|
||||
{
|
||||
Array.Clear(destination, 0, w * h * 4);
|
||||
return;
|
||||
}
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int j = 0; j < h; j++)
|
||||
{
|
||||
int sy = y + j;
|
||||
for (int i = 0; i < w; i++)
|
||||
{
|
||||
int sx = x + i;
|
||||
int di = (j * w + i) * 4;
|
||||
if ((uint)sx >= (uint)cw || (uint)sy >= (uint)ch)
|
||||
{
|
||||
destination[di] = 0d;
|
||||
destination[di + 1] = 0d;
|
||||
destination[di + 2] = 0d;
|
||||
destination[di + 3] = 0d;
|
||||
continue;
|
||||
}
|
||||
byte* p = buf + (sy * cw + sx) * 4;
|
||||
double a = p[3];
|
||||
if (a <= 0d)
|
||||
{
|
||||
destination[di] = 0d;
|
||||
destination[di + 1] = 0d;
|
||||
destination[di + 2] = 0d;
|
||||
destination[di + 3] = 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double s = 255d / a;
|
||||
destination[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||
destination[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||
destination[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||
destination[di + 3] = a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void WriteRegion(int x, int y, int w, int h, double[] source)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
_isPixelsDirty = true;
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int j = 0; j < h; j++)
|
||||
{
|
||||
int dy = y + j;
|
||||
if ((uint)dy >= (uint)ch)
|
||||
continue;
|
||||
for (int i = 0; i < w; i++)
|
||||
{
|
||||
int dx = x + i;
|
||||
if ((uint)dx >= (uint)cw)
|
||||
continue;
|
||||
int si = (j * w + i) * 4;
|
||||
double a = Math.Clamp(source[si + 3], 0d, 255d);
|
||||
double aK = a / 255d;
|
||||
byte* p = buf + (dy * cw + dx) * 4;
|
||||
p[0] = (byte)Math.Clamp(source[si + 2] * aK, 0d, 255d);
|
||||
p[1] = (byte)Math.Clamp(source[si + 1] * aK, 0d, 255d);
|
||||
p[2] = (byte)Math.Clamp(source[si] * aK, 0d, 255d);
|
||||
p[3] = (byte)a;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Convolve(double[] kernel, int size, double divisor, double offset)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
int count = cw * ch * 4;
|
||||
if (_convolveSource is null || _convolveSource.Length < count)
|
||||
_convolveSource = new double[count];
|
||||
var src = _convolveSource;
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int pi = 0; pi < cw * ch; pi++)
|
||||
{
|
||||
byte* p = buf + pi * 4;
|
||||
int di = pi * 4;
|
||||
double a = p[3];
|
||||
src[di + 3] = a;
|
||||
if (a <= 0d)
|
||||
{
|
||||
src[di] = 0d;
|
||||
src[di + 1] = 0d;
|
||||
src[di + 2] = 0d;
|
||||
}
|
||||
else
|
||||
{
|
||||
double s = 255d / a;
|
||||
src[di] = Math.Clamp(p[2] * s, 0d, 255d);
|
||||
src[di + 1] = Math.Clamp(p[1] * s, 0d, 255d);
|
||||
src[di + 2] = Math.Clamp(p[0] * s, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int half = size / 2;
|
||||
_isPixelsDirty = true;
|
||||
|
||||
fixed (byte* buf = _pixelBuffer)
|
||||
{
|
||||
for (int y = 0; y < ch; y++)
|
||||
{
|
||||
for (int x = 0; x < cw; x++)
|
||||
{
|
||||
double sr = 0d, sg = 0d, sb = 0d, sa = 0d;
|
||||
for (int ky = 0; ky < size; ky++)
|
||||
{
|
||||
int sy = Math.Clamp(y + ky - half, 0, ch - 1);
|
||||
for (int kx = 0; kx < size; kx++)
|
||||
{
|
||||
int sx = Math.Clamp(x + kx - half, 0, cw - 1);
|
||||
double kv = kernel[ky * size + kx];
|
||||
int si = (sy * cw + sx) * 4;
|
||||
sr += src[si] * kv;
|
||||
sg += src[si + 1] * kv;
|
||||
sb += src[si + 2] * kv;
|
||||
sa += src[si + 3] * kv;
|
||||
}
|
||||
}
|
||||
double rr = Math.Clamp(sr / divisor + offset, 0d, 255d);
|
||||
double gg = Math.Clamp(sg / divisor + offset, 0d, 255d);
|
||||
double bb = Math.Clamp(sb / divisor + offset, 0d, 255d);
|
||||
double aa = Math.Clamp(sa / divisor + offset, 0d, 255d);
|
||||
double aK = aa / 255d;
|
||||
byte* p = buf + (y * cw + x) * 4;
|
||||
p[0] = (byte)Math.Clamp(bb * aK, 0d, 255d);
|
||||
p[1] = (byte)Math.Clamp(gg * aK, 0d, 255d);
|
||||
p[2] = (byte)Math.Clamp(rr * aK, 0d, 255d);
|
||||
p[3] = (byte)aa;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public unsafe void Resize(int newWidth, int newHeight, bool linear)
|
||||
{
|
||||
EnsurePixelBuffer();
|
||||
if (_pixelBuffer is null)
|
||||
return;
|
||||
|
||||
newWidth = Math.Max(1, newWidth);
|
||||
newHeight = Math.Max(1, newHeight);
|
||||
int cw = ImageWidth;
|
||||
int ch = ImageHeight;
|
||||
|
||||
int srcCount = cw * ch * 4;
|
||||
if (_resizeSource is null || _resizeSource.Length < srcCount)
|
||||
_resizeSource = new byte[srcCount];
|
||||
Buffer.BlockCopy(_pixelBuffer, 0, _resizeSource, 0, srcCount);
|
||||
|
||||
int dstCount = newWidth * newHeight * 4;
|
||||
if (_resizeBuffer is null || _resizeBuffer.Length != dstCount)
|
||||
_resizeBuffer = new byte[dstCount];
|
||||
var src = _resizeSource;
|
||||
var dst = _resizeBuffer;
|
||||
|
||||
fixed (byte* s = src)
|
||||
fixed (byte* d = dst)
|
||||
{
|
||||
for (int y = 0; y < newHeight; y++)
|
||||
{
|
||||
for (int x = 0; x < newWidth; x++)
|
||||
{
|
||||
byte* o = d + (y * newWidth + x) * 4;
|
||||
if (!linear)
|
||||
{
|
||||
int sx = Math.Clamp((int)((x + 0.5) * cw / newWidth), 0, cw - 1);
|
||||
int sy = Math.Clamp((int)((y + 0.5) * ch / newHeight), 0, ch - 1);
|
||||
byte* p = s + (sy * cw + sx) * 4;
|
||||
o[0] = p[0];
|
||||
o[1] = p[1];
|
||||
o[2] = p[2];
|
||||
o[3] = p[3];
|
||||
}
|
||||
else
|
||||
{
|
||||
double u = (x + 0.5) * cw / newWidth - 0.5;
|
||||
double v = (y + 0.5) * ch / newHeight - 0.5;
|
||||
int x0 = (int)Math.Floor(u);
|
||||
int y0 = (int)Math.Floor(v);
|
||||
double tx = u - x0;
|
||||
double ty = v - y0;
|
||||
for (int c = 0; c < 4; c++)
|
||||
{
|
||||
double acc = 0d;
|
||||
for (int j = 0; j < 2; j++)
|
||||
{
|
||||
int sy = Math.Clamp(y0 + j, 0, ch - 1);
|
||||
double wy = j == 0 ? 1d - ty : ty;
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int sx = Math.Clamp(x0 + i, 0, cw - 1);
|
||||
double wx = i == 0 ? 1d - tx : tx;
|
||||
acc += s[(sy * cw + sx) * 4 + c] * wy * wx;
|
||||
}
|
||||
}
|
||||
o[c] = (byte)Math.Clamp(acc, 0d, 255d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ReplaceBuffer(dst, newWidth, newHeight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
@@ -78,6 +79,7 @@ namespace LuaScript.Engine
|
||||
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,
|
||||
@@ -162,7 +164,7 @@ namespace LuaScript.Engine
|
||||
}
|
||||
else
|
||||
{
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, runPixelShader);
|
||||
DispatchCallback(view, resolveObject, loadFigure, loadText, loadImage, loadMovie, loadScene, loadBrush, addEffect, setAnchor, sceneGetValue, sceneSetValue, loadAudio, runPixelShader);
|
||||
}
|
||||
_workEvent.Set();
|
||||
}
|
||||
@@ -329,6 +331,7 @@ namespace LuaScript.Engine
|
||||
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);
|
||||
@@ -370,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;
|
||||
@@ -570,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);
|
||||
@@ -657,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
|
||||
@@ -665,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)
|
||||
|
||||
@@ -783,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)
|
||||
{
|
||||
@@ -946,6 +987,144 @@ namespace LuaScript
|
||||
};
|
||||
}
|
||||
|
||||
private double[] _regionScratch = [];
|
||||
private double[] _kernelScratch = [];
|
||||
|
||||
private static readonly DynValue[] s_byteNumbers = CreateByteNumbers();
|
||||
|
||||
private static DynValue[] CreateByteNumbers()
|
||||
{
|
||||
var values = new DynValue[256];
|
||||
for (int i = 0; i < values.Length; i++)
|
||||
values[i] = DynValue.NewNumber(i).AsReadOnly();
|
||||
return values;
|
||||
}
|
||||
|
||||
private static DynValue ChannelValue(double value)
|
||||
{
|
||||
int b = (int)value;
|
||||
return b == value && (uint)b < 256u ? s_byteNumbers[b] : DynValue.NewNumber(value);
|
||||
}
|
||||
|
||||
[LuaFunction("fill")]
|
||||
private DynValue Fill(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null)
|
||||
return DynValue.Void;
|
||||
|
||||
var ctx = _activeContext;
|
||||
double r = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double g = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double b = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double a = args.Count > 3 ? args[3].CastToNumber() ?? 255d : 255d;
|
||||
int x = args.Count > 4 ? (int)(args[4].CastToNumber() ?? 0d) : 0;
|
||||
int y = args.Count > 5 ? (int)(args[5].CastToNumber() ?? 0d) : 0;
|
||||
int w = args.Count > 6 ? (int)(args[6].CastToNumber() ?? 0d) : ctx.ImageWidth;
|
||||
int h = args.Count > 7 ? (int)(args[7].CastToNumber() ?? 0d) : ctx.ImageHeight;
|
||||
|
||||
ctx.FillBuffer(r, g, b, a, x, y, w, h);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("getpixelregion")]
|
||||
private DynValue GetPixelRegion(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || _script is null || args.Count < 4)
|
||||
return DynValue.Nil;
|
||||
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||
var table = new Table(_script);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.NewTable(table);
|
||||
|
||||
int count = w * h * 4;
|
||||
if (_regionScratch.Length < count)
|
||||
_regionScratch = new double[count];
|
||||
_activeContext.ReadRegion(x, y, w, h, _regionScratch);
|
||||
for (int i = 0; i < count; i++)
|
||||
table.Set(i + 1, ChannelValue(_regionScratch[i]));
|
||||
return DynValue.NewTable(table);
|
||||
}
|
||||
|
||||
[LuaFunction("putpixelregion")]
|
||||
private DynValue PutPixelRegion(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 5 || args[4].Type != DataType.Table)
|
||||
return DynValue.Void;
|
||||
|
||||
int x = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int y = (int)(args[1].CastToNumber() ?? 0d);
|
||||
int w = (int)(args[2].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[3].CastToNumber() ?? 0d);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.Void;
|
||||
|
||||
int count = w * h * 4;
|
||||
if (_regionScratch.Length < count)
|
||||
_regionScratch = new double[count];
|
||||
var table = args[4].Table;
|
||||
for (int i = 0; i < count; i++)
|
||||
_regionScratch[i] = table.Get(i + 1).CastToNumber() ?? 0d;
|
||||
_activeContext.WriteRegion(x, y, w, h, _regionScratch);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("convolve")]
|
||||
private DynValue Convolve(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2 || args[0].Type != DataType.Table)
|
||||
return DynValue.Void;
|
||||
|
||||
int size = (int)(args[1].CastToNumber() ?? 0d);
|
||||
if (size < 1 || (size & 1) == 0)
|
||||
return DynValue.Void;
|
||||
|
||||
int taps = size * size;
|
||||
var kernel = args[0].Table;
|
||||
if (_kernelScratch.Length < taps)
|
||||
_kernelScratch = new double[taps];
|
||||
double sum = 0d;
|
||||
for (int i = 0; i < taps; i++)
|
||||
{
|
||||
double v = kernel.Get(i + 1).CastToNumber() ?? 0d;
|
||||
_kernelScratch[i] = v;
|
||||
sum += v;
|
||||
}
|
||||
|
||||
double divisor = args.Count > 2 ? args[2].CastToNumber() ?? sum : sum;
|
||||
if (divisor == 0d)
|
||||
divisor = 1d;
|
||||
double offset = args.Count > 3 ? args[3].CastToNumber() ?? 0d : 0d;
|
||||
|
||||
_activeContext.Convolve(_kernelScratch, size, divisor, offset);
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
[LuaFunction("resize")]
|
||||
private DynValue Resize(CallbackArguments args)
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
if (_activeContext is null || args.Count < 2)
|
||||
return DynValue.Void;
|
||||
|
||||
int w = (int)(args[0].CastToNumber() ?? 0d);
|
||||
int h = (int)(args[1].CastToNumber() ?? 0d);
|
||||
if (w <= 0 || h <= 0)
|
||||
return DynValue.Void;
|
||||
|
||||
bool linear = !(args.Count > 2 && args[2].Type == DataType.String && args[2].String == "nearest");
|
||||
_activeContext.Resize(w, h, linear);
|
||||
RefreshObjDimensions();
|
||||
return DynValue.Void;
|
||||
}
|
||||
|
||||
private double CurrentAntialias() =>
|
||||
_options.TryGetValue("antialias", out var value) && value.Type == DataType.Number
|
||||
? value.Number
|
||||
@@ -1029,14 +1208,14 @@ namespace LuaScript
|
||||
int w = _activeContext!.ImageWidth;
|
||||
int h = _activeContext.ImageHeight;
|
||||
var obj = _objScope.Table;
|
||||
obj["w"] = w;
|
||||
obj["h"] = h;
|
||||
obj["hw"] = w / 2d;
|
||||
obj["hh"] = h / 2d;
|
||||
obj["cx"] = w / 2d;
|
||||
obj["cy"] = h / 2d;
|
||||
obj["cz"] = 0d;
|
||||
obj["diagonal"] = Math.Sqrt((double)w * w + (double)h * h);
|
||||
obj.Set("w", DynValue.NewNumber(w));
|
||||
obj.Set("h", DynValue.NewNumber(h));
|
||||
obj.Set("hw", DynValue.NewNumber(w / 2d));
|
||||
obj.Set("hh", DynValue.NewNumber(h / 2d));
|
||||
obj.Set("cx", DynValue.NewNumber(w / 2d));
|
||||
obj.Set("cy", DynValue.NewNumber(h / 2d));
|
||||
obj.Set("cz", DynValue.NewNumber(0d));
|
||||
obj.Set("diagonal", DynValue.NewNumber(Math.Sqrt((double)w * w + (double)h * h)));
|
||||
}
|
||||
|
||||
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
||||
@@ -1058,6 +1237,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;
|
||||
@@ -66,6 +66,7 @@ namespace LuaScript.Engine
|
||||
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;
|
||||
@@ -80,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.17.0</Version>
|
||||
<Version>1.19.2</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,9 @@ 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.brush", "obj.getinfo"
|
||||
"obj.getvalue", "obj.getaudio", "obj.setoption", "obj.getoption", "obj.pixeloption",
|
||||
"obj.setanchor", "obj.effect", "obj.brush", "obj.getinfo",
|
||||
"obj.fill", "obj.getpixelregion", "obj.putpixelregion", "obj.convolve", "obj.resize"
|
||||
]),
|
||||
("math", [
|
||||
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
using LuaScript;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public sealed class LuaScriptEngineBufferOpsTests
|
||||
{
|
||||
private sealed class StubMediaLoader : IMediaSourceLoader
|
||||
{
|
||||
public byte[] RenderText(string text, string fontFamily, double fontSize, bool bold, bool italic, int colorRgb, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeImage(string path, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public byte[] DecodeMovie(string path, double time, out int width, out int height)
|
||||
{
|
||||
width = 1;
|
||||
height = 1;
|
||||
return new byte[4];
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
|
||||
private static LuaScriptEngine CreateEngine() => new(static () => new StubMediaLoader());
|
||||
|
||||
private static AviUtlScriptContext NewContext(byte[] buffer, int width, int height)
|
||||
{
|
||||
var ctx = new AviUtlScriptContext { Framerate = 30 };
|
||||
ctx.SetResolvedBuffer(buffer, width, height);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static byte[] Bgra(params (byte B, byte G, byte R, byte A)[] pixels)
|
||||
{
|
||||
var buffer = new byte[pixels.Length * 4];
|
||||
for (int i = 0; i < pixels.Length; i++)
|
||||
{
|
||||
buffer[i * 4 + 0] = pixels[i].B;
|
||||
buffer[i * 4 + 1] = pixels[i].G;
|
||||
buffer[i * 4 + 2] = pixels[i].R;
|
||||
buffer[i * 4 + 3] = pixels[i].A;
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_WholeBuffer_WritesPremultipliedColor()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 2 * 4], 2, 2);
|
||||
|
||||
engine.Execute("obj.fill(200, 100, 50, 255)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
Assert.Equal(50, buffer[i * 4 + 0]);
|
||||
Assert.Equal(100, buffer[i * 4 + 1]);
|
||||
Assert.Equal(200, buffer[i * 4 + 2]);
|
||||
Assert.Equal(255, buffer[i * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[3 * 1 * 4], 3, 1);
|
||||
|
||||
engine.Execute("obj.fill(255, 255, 255, 255, 1, 0, 1, 1)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 255, 255, 255, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, buffer.AsSpan(8, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_ReturnsStraightRgba()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((50, 100, 200, 255)), 1, 1);
|
||||
|
||||
engine.Execute("local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]", ctx);
|
||||
|
||||
Assert.Equal(200d, ctx.X);
|
||||
Assert.Equal(100d, ctx.Y);
|
||||
Assert.Equal(50d, ctx.Z);
|
||||
Assert.Equal(255d, ctx.Alpha);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_OutOfBounds_YieldsTransparent()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((10, 20, 30, 255)), 1, 1);
|
||||
|
||||
engine.Execute("local t = obj.getpixelregion(1, 0, 1, 1) obj.x = t[1] + t[2] + t[3] + t[4]", ctx);
|
||||
|
||||
Assert.Equal(0d, ctx.X);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutPixelRegion_WritesPremultipliedColor()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[2 * 1 * 4], 2, 1);
|
||||
|
||||
engine.Execute("obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(new byte[] { 50, 100, 200, 255 }, buffer.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 30, 20, 10, 255 }, buffer.AsSpan(4, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||
|
||||
engine.Execute(
|
||||
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||
ctx);
|
||||
|
||||
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var original = Bgra((10, 20, 30, 255), (40, 50, 60, 255), (70, 80, 90, 255), (100, 110, 120, 255));
|
||||
var ctx = NewContext((byte[])original.Clone(), 2, 2);
|
||||
|
||||
engine.Execute("obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)", ctx);
|
||||
|
||||
Assert.Equal(original, ctx.GetPixelBuffer());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((0, 0, 0, 255), (255, 255, 255, 255)), 2, 1);
|
||||
|
||||
engine.Execute("obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)", ctx);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
Assert.Equal(85, buffer[2]);
|
||||
Assert.Equal(85, buffer[1]);
|
||||
Assert.Equal(85, buffer[0]);
|
||||
Assert.Equal(170, buffer[6]);
|
||||
Assert.Equal(255, buffer[3]);
|
||||
Assert.Equal(255, buffer[7]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_Nearest_ReplicatesBlocks()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(Bgra((11, 12, 13, 255), (21, 22, 23, 255), (31, 32, 33, 255), (41, 42, 43, 255)), 2, 2);
|
||||
|
||||
engine.Execute("obj.resize(4, 4, 'nearest')", ctx);
|
||||
|
||||
Assert.Equal(4, ctx.ImageWidth);
|
||||
Assert.Equal(4, ctx.ImageHeight);
|
||||
Assert.True(ctx.BufferReplaced);
|
||||
|
||||
var buffer = ctx.GetPixelBuffer()!;
|
||||
byte SampleR(int x, int y) => buffer[(y * 4 + x) * 4 + 2];
|
||||
Assert.Equal(13, SampleR(0, 0));
|
||||
Assert.Equal(13, SampleR(1, 1));
|
||||
Assert.Equal(23, SampleR(2, 0));
|
||||
Assert.Equal(33, SampleR(0, 2));
|
||||
Assert.Equal(43, SampleR(3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_UpdatesObjDimensions()
|
||||
{
|
||||
using var engine = CreateEngine();
|
||||
var ctx = NewContext(new byte[4 * 4 * 4], 4, 4);
|
||||
|
||||
engine.Execute("obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal", ctx);
|
||||
|
||||
Assert.Equal(8, ctx.ImageWidth);
|
||||
Assert.Equal(2, ctx.ImageHeight);
|
||||
Assert.Equal(8d, ctx.X);
|
||||
Assert.Equal(2d, ctx.Y);
|
||||
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), ctx.Z);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
{
|
||||
|
||||
@@ -26,6 +26,7 @@ namespace LuaScript.Tests
|
||||
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();
|
||||
@@ -74,6 +75,7 @@ namespace LuaScript.Tests
|
||||
width, height, timeoutMs,
|
||||
resolveObject, loadFigure, loadText, loadImage, loadMovie, _loadScene, _loadBrush, addEffect, addDraw, setAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
out pixelsDirty, out bufferReplaced, out resultWidth, out resultHeight, out error);
|
||||
|
||||
@@ -110,6 +112,7 @@ namespace LuaScript.Tests
|
||||
},
|
||||
w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, _loadScene, _loadBrush, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
_sceneGet, _sceneSet,
|
||||
_loadAudio,
|
||||
_runPixelShader,
|
||||
out _, out _, out _, out _, out string? error);
|
||||
|
||||
@@ -525,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;
|
||||
|
||||
@@ -533,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);
|
||||
|
||||
@@ -546,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]
|
||||
@@ -559,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 =
|
||||
@@ -1258,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()
|
||||
{
|
||||
@@ -1819,5 +1904,217 @@ namespace LuaScript.Tests
|
||||
Assert.True(ok2, error);
|
||||
Assert.Equal(7d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_WritesPremultipliedColor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(200, 100, 50, 255)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
for (int i = 0; i < w * h; i++)
|
||||
{
|
||||
Assert.Equal(50, pixels[i * 4 + 0]);
|
||||
Assert.Equal(100, pixels[i * 4 + 1]);
|
||||
Assert.Equal(200, pixels[i * 4 + 2]);
|
||||
Assert.Equal(255, pixels[i * 4 + 3]);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Fill_Rectangle_TouchesOnlyRequestedPixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 3, h = 1;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.fill(255, 255, 255, 255, 1, 0, 1, 1)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 255, 255, 255, 255 }, pixels.AsSpan(4, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 0, 0, 0, 0 }, pixels.AsSpan(8, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetPixelRegion_ReturnsStraightRgba()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[] { 50, 100, 200, 255 };
|
||||
var fields = Fields(1, 1, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"local t = obj.getpixelregion(0, 0, 1, 1) obj.x = t[1] obj.y = t[2] obj.z = t[3] obj.alpha = t[4]",
|
||||
fields, NoStringParams, () => pixels, 1, 1, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(200d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(100d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(50d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(255d, fields[NativeProtocol.Alpha]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PutPixelRegion_WritesPremultipliedColor()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 1;
|
||||
var pixels = new byte[w * h * 4];
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.putpixelregion(0, 0, 2, 1, {200, 100, 50, 255, 10, 20, 30, 255})",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(new byte[] { 50, 100, 200, 255 }, pixels.AsSpan(0, 4).ToArray());
|
||||
Assert.Equal(new byte[] { 30, 20, 10, 255 }, pixels.AsSpan(4, 4).ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RegionRoundTrip_PreservesOpaquePixels()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
10, 20, 30, 255, 40, 50, 60, 255,
|
||||
70, 80, 90, 255, 100, 110, 120, 255,
|
||||
};
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"local t = obj.getpixelregion(0, 0, obj.w, obj.h) obj.fill(0, 0, 0, 0) obj.putpixelregion(0, 0, obj.w, obj.h, t)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(original, pixels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_Identity_LeavesOpaqueBufferUnchanged()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
10, 20, 30, 255, 40, 50, 60, 255,
|
||||
70, 80, 90, 255, 100, 110, 120, 255,
|
||||
};
|
||||
var original = (byte[])pixels.Clone();
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({0, 0, 0, 0, 1, 0, 0, 0, 0}, 3)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(original, pixels);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Convolve_BoxBlur_AveragesHorizontalStep()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 1;
|
||||
var pixels = new byte[] { 0, 0, 0, 255, 255, 255, 255, 255 };
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.convolve({1, 1, 1, 1, 1, 1, 1, 1, 1}, 3)",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out _, out _, out _, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.Equal(85, pixels[0]);
|
||||
Assert.Equal(85, pixels[1]);
|
||||
Assert.Equal(85, pixels[2]);
|
||||
Assert.Equal(255, pixels[3]);
|
||||
Assert.Equal(170, pixels[6]);
|
||||
Assert.Equal(255, pixels[7]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_Nearest_ReplicatesBlocks()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
const int w = 2, h = 2;
|
||||
var pixels = new byte[]
|
||||
{
|
||||
13, 12, 13, 255, 23, 22, 23, 255,
|
||||
33, 32, 33, 255, 43, 42, 43, 255,
|
||||
};
|
||||
var fields = Fields(w, h, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(4, 4, 'nearest')",
|
||||
fields, NoStringParams, () => pixels, w, h, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out bool dirty, out bool bufferReplaced, out byte[]? result, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(4, rw);
|
||||
Assert.Equal(4, rh);
|
||||
Assert.NotNull(result);
|
||||
byte SampleR(int x, int y) => result![(y * 4 + x) * 4 + 2];
|
||||
Assert.Equal(13, SampleR(0, 0));
|
||||
Assert.Equal(13, SampleR(1, 1));
|
||||
Assert.Equal(23, SampleR(2, 0));
|
||||
Assert.Equal(33, SampleR(0, 2));
|
||||
Assert.Equal(43, SampleR(3, 3));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resize_UpdatesObjDimensions()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[4 * 4 * 4];
|
||||
var fields = Fields(4, 4, 0d);
|
||||
|
||||
bool ok = RunWorker(
|
||||
"obj.resize(8, 2) obj.x = obj.w obj.y = obj.h obj.z = obj.diagonal",
|
||||
fields, NoStringParams, () => pixels, 4, 4, 5000, NoResolver, NoLoadFigure, NoLoadText, NoLoadImage, NoLoadMovie, NoAddEffect, NoAddDraw, NoSetAnchor,
|
||||
out _, out bool bufferReplaced, out _, out int rw, out int rh, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(bufferReplaced);
|
||||
Assert.Equal(8, rw);
|
||||
Assert.Equal(2, rh);
|
||||
Assert.Equal(8d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(Math.Sqrt(8d * 8d + 2d * 2d), fields[NativeProtocol.Z]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ namespace LuaScript
|
||||
{
|
||||
if (arguments.Count > 0)
|
||||
{
|
||||
Ymm4PropertyBinder.ApplyArguments(entry.Parameter, arguments);
|
||||
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++)
|
||||
|
||||
@@ -9,7 +9,7 @@ using YukkuriMovieMaker.Commons;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
internal static class Ymm4PropertyBinder
|
||||
internal static class ParameterBinder
|
||||
{
|
||||
public static readonly AviUtlParameterMapping Identity = new(string.Empty, string.Empty, 1d, 0d);
|
||||
|
||||
@@ -183,7 +183,7 @@ namespace LuaScript
|
||||
map.TryAdd(Normalize(key), type);
|
||||
}
|
||||
|
||||
private static string Normalize(string value) => Ymm4PropertyBinder.Normalize(value);
|
||||
private static string Normalize(string value) => ParameterBinder.Normalize(value);
|
||||
|
||||
private static void ApplyParameters(IVideoEffect model, AviUtlEffectMapping? mapping, IReadOnlyList<KeyValuePair<string, object>> arguments)
|
||||
{
|
||||
@@ -192,11 +192,11 @@ namespace LuaScript
|
||||
|
||||
if (mapping is null)
|
||||
{
|
||||
Ymm4PropertyBinder.ApplyArguments(model, arguments);
|
||||
ParameterBinder.ApplyArguments(model, arguments);
|
||||
return;
|
||||
}
|
||||
|
||||
var properties = Ymm4PropertyBinder.GetProperties(model.GetType());
|
||||
var properties = ParameterBinder.GetProperties(model.GetType());
|
||||
foreach (var (key, value) in arguments)
|
||||
{
|
||||
if (!mapping.TryGetParameter(key, out var parameter) ||
|
||||
@@ -205,7 +205,7 @@ namespace LuaScript
|
||||
|
||||
try
|
||||
{
|
||||
Ymm4PropertyBinder.SetValue(model, property, value, parameter);
|
||||
ParameterBinder.SetValue(model, property, value, parameter);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
@@ -143,6 +143,9 @@ namespace LuaScript
|
||||
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;
|
||||
@@ -189,6 +192,7 @@ namespace LuaScript
|
||||
_context.Compositor = _bufferCompositor;
|
||||
_context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
_context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
_context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -202,6 +206,7 @@ namespace LuaScript
|
||||
context.Compositor = _bufferCompositor;
|
||||
context.SceneImageLoader = _loadSceneImage ??= LoadSceneImage;
|
||||
context.BrushImageLoader = _loadBrushImage ??= LoadBrushImage;
|
||||
context.AudioLoader = _loadAudio ??= LoadAudio;
|
||||
return context;
|
||||
}
|
||||
|
||||
@@ -483,6 +488,11 @@ namespace LuaScript
|
||||
_sceneImageLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
if (_audioLoaded)
|
||||
{
|
||||
_audioLoaded = false;
|
||||
_isFirst = true;
|
||||
}
|
||||
_cachedKey = key;
|
||||
_cachedQueries = SnapshotQueries(ctx.ObjectQueries, _cachedQueries);
|
||||
_cachedSceneValueQueries = SnapshotQueries(ctx.SceneValueQueries, _cachedSceneValueQueries);
|
||||
@@ -553,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++)
|
||||
@@ -997,6 +1038,7 @@ namespace LuaScript
|
||||
_nativeLoadMovie ??= NativeLoadMovie;
|
||||
_loadSceneImage ??= LoadSceneImage;
|
||||
_loadBrushImage ??= LoadBrushImage;
|
||||
_loadAudio ??= LoadAudio;
|
||||
_nativeAddEffect ??= (name, args) => _context.AddEffect(new AviUtlEffectRequest(name, args));
|
||||
_nativeAddDraw ??= command => _context.AddDraw(command);
|
||||
_nativeSetAnchor ??= ResolveNativeAnchor;
|
||||
@@ -1021,6 +1063,7 @@ namespace LuaScript
|
||||
_nativeSetAnchor,
|
||||
_nativeSceneGet,
|
||||
_nativeSceneSet,
|
||||
_loadAudio,
|
||||
_nativeRunPixelShader,
|
||||
out bool dirty, out bool bufferReplaced,
|
||||
out int resultW, out int resultH, out string? error);
|
||||
@@ -1218,6 +1261,69 @@ namespace LuaScript
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -1267,6 +1373,7 @@ namespace LuaScript
|
||||
_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.17.0</Version>
|
||||
<Version>1.19.2</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -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)
|
||||
يسترد معلومات البكسل عند الإحداثيات المحددة.
|
||||
@@ -596,12 +612,96 @@
|
||||
* يتخطى الاستدعاء في البيئات التي لا تتوفر فيها وحدة معالجة
|
||||
رسومات صالحة.
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (امتداد خاص بـ YMM4)
|
||||
يملأ صورة الكائن بلون محدد. يعطى اللون بصيغة RGBA مباشرة من 0 إلى
|
||||
255 (نفس نموذج الألوان في obj.setpixel).
|
||||
r, g, b : مكونات اللون (0-255).
|
||||
a : الشفافية (0-255). القيمة الافتراضية 255.
|
||||
x, y, w, h: المستطيل المراد ملؤه. الافتراضي كامل الصورة، ويقص ما خرج
|
||||
عن النطاق.
|
||||
مثال: obj.fill(0, 0, 0, 0) -- مسح الكل إلى شفاف
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
يعمل على المحركين معا.
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (امتداد خاص بـ YMM4)
|
||||
يقرأ منطقة مستطيلة من البكسلات إلى مصفوفة RGBA مباشرة. الترتيب هو
|
||||
r, g, b, a لكل بكسل ويبدأ من 1 (الفهرس (صف*w+عمود)*4+1..+4). البكسلات
|
||||
خارج الصورة تكون 0,0,0,0.
|
||||
القيمة المعادة: مصفوفة بطول w*h*4.
|
||||
مثال: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, البيانات) (امتداد خاص بـ YMM4)
|
||||
يكتب مصفوفة بنفس ترتيب obj.getpixelregion إلى منطقة مستطيلة. البكسلات
|
||||
خارج حدود الصورة لا تكتب.
|
||||
البيانات : مصفوفة RGBA مباشرة بطول w*h*4 (تبدأ من 1).
|
||||
مثال: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(النواة, الحجم [, المقسوم_عليه [, الإزاحة]]) (امتداد خاص بـ YMM4)
|
||||
يطبق التفاف بحجم الحجم×الحجم على صورة الكائن. مفيد للتمويه والتوضيح
|
||||
واكتشاف الحواف وغيرها.
|
||||
النواة : عدد الحجم*الحجم من المعاملات (حسب الصفوف، تبدأ من 1).
|
||||
الحجم : عدد فردي (3، 5، 7 …). الزوجي أو الأقل من 1 يتجاهل.
|
||||
المقسوم_عليه : يقسم مجموع كل بكسل على هذه القيمة. الافتراضي مجموع
|
||||
النواة (1 عندما يكون المجموع 0).
|
||||
الإزاحة : تضاف إلى كل مكون بعد القسمة. الافتراضي 0.
|
||||
تمدد بكسلات الحواف بأقرب بكسل. يطبق على r, g, b, a جميعا.
|
||||
مثال: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- تمويه متوسط
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- توضيح
|
||||
يعمل على المحركين معا.
|
||||
|
||||
○ obj.resize(العرض, الارتفاع [, الترشيح]) (امتداد خاص بـ YMM4)
|
||||
يغير حجم صورة الكائن إلى الحجم المحدد. تحدّث أيضا obj.w / obj.h وبقية
|
||||
الأبعاد.
|
||||
العرض, الارتفاع : أعداد صحيحة >= 1.
|
||||
الترشيح : "nearest" لأقرب جار، أو خطي عند الحذف.
|
||||
مثال: obj.resize(obj.w * 2, obj.h * 2)
|
||||
يعمل على المحركين معا. يترك التشغيل السريع الصورة دون تغيير عندما
|
||||
تتجاوز النتيجة أقصى حجم للصورة.
|
||||
|
||||
○ obj.getvalue(الهدف)
|
||||
يحصل على القيمة الحالية لـ obj (مثل obj.x و obj.track0).
|
||||
الهدف : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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" : يُرجِع مسار مجلد تثبيت الإضافة. ينتهي بفاصل مسار.
|
||||
@@ -953,7 +1053,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.
|
||||
@@ -618,12 +634,103 @@
|
||||
onto a transparent scene-sized area.
|
||||
* The call is skipped in environments without a usable GPU.
|
||||
|
||||
o obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 extension)
|
||||
Fills the object image with a color, given as straight RGBA in
|
||||
0-255 (same color model as obj.setpixel).
|
||||
r, g, b : Color components (0-255).
|
||||
a : Opacity (0-255). Default is 255.
|
||||
x, y, w, h: Rectangle to fill. Defaults to the whole image; out of
|
||||
range is clipped.
|
||||
Example: obj.fill(0, 0, 0, 0) -- clear to transparent
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
Runs on both engines.
|
||||
|
||||
o obj.getpixelregion(x, y, w, h) (YMM4 extension)
|
||||
Reads a rectangular region of pixels into a straight RGBA array.
|
||||
The layout is r, g, b, a per pixel and is 1-based (index
|
||||
(row*w+col)*4+1..+4). Pixels outside the image are 0,0,0,0.
|
||||
Returns: an array of length w*h*4.
|
||||
Example: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
o obj.putpixelregion(x, y, w, h, data) (YMM4 extension)
|
||||
Writes an array in the same layout as obj.getpixelregion back into a
|
||||
rectangular region. Pixels outside the image are not written.
|
||||
data : straight RGBA array of length w*h*4 (1-based).
|
||||
Example: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
o obj.convolve(kernel, size [, divisor [, offset]]) (YMM4 extension)
|
||||
Applies a size x size convolution to the object image. Useful for
|
||||
blur, sharpen, edge detection and so on.
|
||||
kernel : size*size coefficients, row-major and 1-based.
|
||||
size : odd number (3, 5, 7 ...). Even or below 1 is ignored.
|
||||
divisor : divides each pixel sum. Defaults to the kernel sum (1 when
|
||||
the sum is 0).
|
||||
offset : added to each component after the division. Default is 0.
|
||||
Edge pixels are extended by the nearest pixel. Applies to r, g, b, a.
|
||||
Example: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- box blur
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- sharpen
|
||||
Runs on both engines.
|
||||
|
||||
o obj.resize(width, height [, filter]) (YMM4 extension)
|
||||
Scales the object image to the given size. obj.w / obj.h and the
|
||||
other dimensions are updated too.
|
||||
width, height : integers >= 1.
|
||||
filter : "nearest" for nearest-neighbor, or linear when
|
||||
omitted.
|
||||
Example: obj.resize(obj.w * 2, obj.h * 2)
|
||||
Runs on both engines. The fast runtime leaves the image unchanged
|
||||
when the result exceeds the maximum image size.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Gets the current value of obj (same as obj.x, obj.track0, etc.).
|
||||
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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
|
||||
@@ -989,7 +1096,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.
|
||||
@@ -625,12 +641,107 @@
|
||||
sobre un area transparente del tamano de la escena.
|
||||
* La llamada se omite en entornos sin una GPU utilizable.
|
||||
|
||||
o obj.fill(r, g, b [, a [, x, y, w, h]]) (extension de YMM4)
|
||||
Rellena la imagen del objeto con un color, dado como RGBA directo en
|
||||
0-255 (mismo modelo de color que obj.setpixel).
|
||||
r, g, b : Componentes de color (0-255).
|
||||
a : Opacidad (0-255). Por defecto 255.
|
||||
x, y, w, h: Rectangulo a rellenar. Por defecto toda la imagen; lo que
|
||||
queda fuera de rango se recorta.
|
||||
Ejemplo: obj.fill(0, 0, 0, 0) -- borrar a transparente
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
Funciona en ambos motores.
|
||||
|
||||
o obj.getpixelregion(x, y, w, h) (extension de YMM4)
|
||||
Lee una region rectangular de pixeles en un arreglo RGBA directo. La
|
||||
disposicion es r, g, b, a por pixel y empieza en 1 (indice
|
||||
(fila*w+col)*4+1..+4). Los pixeles fuera de la imagen son 0,0,0,0.
|
||||
Devuelve: un arreglo de longitud w*h*4.
|
||||
Ejemplo: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
o obj.putpixelregion(x, y, w, h, datos) (extension de YMM4)
|
||||
Escribe un arreglo con la misma disposicion que obj.getpixelregion en
|
||||
una region rectangular. Los pixeles fuera de la imagen no se escriben.
|
||||
datos : arreglo RGBA directo de longitud w*h*4 (empieza en 1).
|
||||
Ejemplo: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
o obj.convolve(kernel, tamano [, divisor [, desplazamiento]]) (extension de YMM4)
|
||||
Aplica una convolucion de tamano x tamano a la imagen del objeto.
|
||||
Util para desenfoque, enfoque, deteccion de bordes, etc.
|
||||
kernel : tamano*tamano coeficientes, por filas y empieza en 1.
|
||||
tamano : numero impar (3, 5, 7 ...). Par o menor que 1 se ignora.
|
||||
divisor : divide la suma de cada pixel. Por defecto la suma del
|
||||
kernel (1 cuando la suma es 0).
|
||||
desplazamiento: se suma a cada componente tras la division. Por
|
||||
defecto 0.
|
||||
Los pixeles de borde se extienden con el pixel mas cercano. Se aplica
|
||||
a r, g, b, a.
|
||||
Ejemplo: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- desenfoque
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- enfoque
|
||||
Funciona en ambos motores.
|
||||
|
||||
o obj.resize(ancho, alto [, filtro]) (extension de YMM4)
|
||||
Escala la imagen del objeto al tamano indicado. obj.w / obj.h y las
|
||||
demas dimensiones tambien se actualizan.
|
||||
ancho, alto : enteros >= 1.
|
||||
filtro : "nearest" para vecino mas cercano, o lineal si se omite.
|
||||
Ejemplo: obj.resize(obj.w * 2, obj.h * 2)
|
||||
Funciona en ambos motores. El runtime rapido deja la imagen sin
|
||||
cambios cuando el resultado supera el tamano maximo de imagen.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Obtiene el valor actual de obj (igual que obj.x, obj.track0, etc.).
|
||||
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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.
|
||||
@@ -1008,7 +1119,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.
|
||||
@@ -621,12 +637,103 @@
|
||||
area transparan seukuran adegan.
|
||||
* Panggilan dilewati pada lingkungan tanpa GPU yang dapat digunakan.
|
||||
|
||||
o obj.fill(r, g, b [, a [, x, y, w, h]]) (ekstensi YMM4)
|
||||
Mengisi gambar objek dengan warna, diberikan sebagai RGBA lurus dalam
|
||||
0-255 (model warna sama dengan obj.setpixel).
|
||||
r, g, b : Komponen warna (0-255).
|
||||
a : Opasitas (0-255). Default 255.
|
||||
x, y, w, h: Persegi panjang yang diisi. Default seluruh gambar; di
|
||||
luar jangkauan dipangkas.
|
||||
Contoh: obj.fill(0, 0, 0, 0) -- bersihkan jadi transparan
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
Berjalan di kedua mesin.
|
||||
|
||||
o obj.getpixelregion(x, y, w, h) (ekstensi YMM4)
|
||||
Membaca wilayah piksel persegi panjang ke dalam larik RGBA lurus.
|
||||
Susunannya r, g, b, a per piksel dan berbasis 1 (indeks
|
||||
(baris*w+kolom)*4+1..+4). Piksel di luar gambar bernilai 0,0,0,0.
|
||||
Mengembalikan: larik sepanjang w*h*4.
|
||||
Contoh: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
o obj.putpixelregion(x, y, w, h, data) (ekstensi YMM4)
|
||||
Menulis larik dengan susunan sama seperti obj.getpixelregion kembali
|
||||
ke wilayah persegi panjang. Piksel di luar gambar tidak ditulis.
|
||||
data : larik RGBA lurus sepanjang w*h*4 (berbasis 1).
|
||||
Contoh: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
o obj.convolve(kernel, ukuran [, pembagi [, offset]]) (ekstensi YMM4)
|
||||
Menerapkan konvolusi ukuran x ukuran ke gambar objek. Berguna untuk
|
||||
blur, penajaman, deteksi tepi, dan sebagainya.
|
||||
kernel : ukuran*ukuran koefisien, urut baris dan berbasis 1.
|
||||
ukuran : bilangan ganjil (3, 5, 7 ...). Genap atau di bawah 1 diabaikan.
|
||||
pembagi : membagi jumlah tiap piksel. Default jumlah kernel (1 bila
|
||||
jumlahnya 0).
|
||||
offset : ditambahkan ke tiap komponen setelah pembagian. Default 0.
|
||||
Piksel tepi diperluas dengan piksel terdekat. Berlaku untuk r, g, b, a.
|
||||
Contoh: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- blur rata-rata
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- penajaman
|
||||
Berjalan di kedua mesin.
|
||||
|
||||
o obj.resize(lebar, tinggi [, filter]) (ekstensi YMM4)
|
||||
Menskala gambar objek ke ukuran yang diberikan. obj.w / obj.h dan
|
||||
dimensi lainnya ikut diperbarui.
|
||||
lebar, tinggi : bilangan bulat >= 1.
|
||||
filter : "nearest" untuk tetangga terdekat, atau linear bila
|
||||
dihilangkan.
|
||||
Contoh: obj.resize(obj.w * 2, obj.h * 2)
|
||||
Berjalan di kedua mesin. Runtime cepat membiarkan gambar tanpa
|
||||
perubahan bila hasilnya melebihi ukuran gambar maksimum.
|
||||
|
||||
o obj.getvalue(target)
|
||||
Mengambil nilai saat ini dari obj (sama dengan obj.x, obj.track0, dll.).
|
||||
target : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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.
|
||||
@@ -1001,7 +1108,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)
|
||||
指定座標のピクセル情報を取得します。
|
||||
@@ -601,12 +616,96 @@
|
||||
シーンサイズ領域へオブジェクトを合成した仮想の画像です。
|
||||
※ GPUが使用できない環境では呼び出しはスキップされます。
|
||||
|
||||
○obj.fill(r, g, b [, a [, x, y, w, h]]) ※YMM4独自拡張
|
||||
オブジェクト画像を指定色で塗りつぶします。色は 0~255 のストレート
|
||||
RGBA で指定します(obj.setpixel と同じ表色)。
|
||||
r, g, b : 色成分(0~255)。
|
||||
a : 不透明度(0~255)。省略時は 255。
|
||||
x, y, w, h : 塗りつぶす矩形。省略時は画像全体。範囲外は切り詰めます。
|
||||
例:obj.fill(0, 0, 0, 0) -- 全体を透明で消去
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
両エンジンで動きます。
|
||||
|
||||
○obj.getpixelregion(x, y, w, h) ※YMM4独自拡張
|
||||
矩形領域の画素をストレート RGBA の配列で取得します。並びは画素ごと
|
||||
に r, g, b, a の順で 1 始まりです(索引 (行*w+列)*4+1~+4)。範囲外の
|
||||
画素は 0,0,0,0 になります。
|
||||
戻り値 : 長さ w*h*4 の配列。
|
||||
例:local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○obj.putpixelregion(x, y, w, h, データ) ※YMM4独自拡張
|
||||
obj.getpixelregion と同じ並びの配列を矩形領域へ書き戻します。画像の
|
||||
範囲外へはみ出した画素は書き込みません。
|
||||
データ : 長さ w*h*4 のストレート RGBA 配列(1 始まり)。
|
||||
例:obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○obj.convolve(カーネル, サイズ [, 除数 [, オフセット]]) ※YMM4独自拡張
|
||||
オブジェクト画像へ サイズ×サイズ の畳み込みを適用します。ぼかし、
|
||||
シャープ、輪郭抽出などに使えます。
|
||||
カーネル : サイズ*サイズ 個の係数配列(行優先, 1 始まり)。
|
||||
サイズ : 奇数(3, 5, 7 …)。偶数や 1 未満は無視します。
|
||||
除数 : 各画素の合計をこの値で割ります。省略時はカーネルの
|
||||
合計(合計が 0 のときは 1)。
|
||||
オフセット : 除算後に各成分へ加算します。省略時は 0。
|
||||
端の画素は最も近い画素で補います。r, g, b, a すべてに適用します。
|
||||
例:obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 平均ぼかし
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- シャープ
|
||||
両エンジンで動きます。
|
||||
|
||||
○obj.resize(幅, 高さ [, 補間]) ※YMM4独自拡張
|
||||
オブジェクト画像を指定サイズへ拡大縮小します。obj.w / obj.h などの
|
||||
寸法も更新されます。
|
||||
幅, 高さ : 1 以上の整数。
|
||||
補間 : "nearest"(最近傍)または省略で線形補間。
|
||||
例:obj.resize(obj.w * 2, obj.h * 2)
|
||||
両エンジンで動きます。高速ランタイムでは結果が最大画像サイズを
|
||||
超える場合は変更しません。
|
||||
|
||||
○obj.getvalue(対象)
|
||||
obj の現在値を取得します(obj.x や obj.track0 等と同値)。
|
||||
対象 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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" : プラグインの設置フォルダのパスを返します。末尾に
|
||||
@@ -680,7 +779,7 @@
|
||||
"xyz" : アンカーポイントを 3D 座標で扱います。既定は 2D です。
|
||||
戻り値は設置したアンカーポイントの数です。両エンジンで動きます。
|
||||
名前に "track" を指定した場合も対応し、個数 0 は 1 個として設置します。
|
||||
選択中のアンカーは アンカー グループの X / Y / Z スライダーで数値調整できます。
|
||||
選択中のアンカーは「アンカー」グループの X / Y / Z スライダーで数値調整できます。
|
||||
例:
|
||||
num = obj.track0
|
||||
obj.setanchor("pos", num, "loop")
|
||||
@@ -930,7 +1029,8 @@
|
||||
- AviUtl スクリプトの部分互換 -
|
||||
|
||||
AviUtl のアニメーション効果スクリプト(*.anm 系)のうち、座標・拡縮・回転・
|
||||
不透明度の変形と乱数を用いる範囲を、追加の記述変更なしで実行できる互換層です。
|
||||
不透明度の変形、乱数、図形描画、描画合成などを、追加の記述変更なしで
|
||||
実行できる互換層です。
|
||||
スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません
|
||||
(従来のスクリプトの挙動は変わりません)。
|
||||
|
||||
@@ -961,8 +1061,10 @@
|
||||
|
||||
○描画・合成・読み込み
|
||||
obj.draw / obj.drawpoly による描画合成、obj.copybuffer による
|
||||
バッファ操作、obj.load("figure"/"text"/"image"/"movie") による生成・
|
||||
読み込み、obj.setfont、obj.effect、obj.getvalue、obj.getinfo、obj.setoption /
|
||||
バッファ操作、obj.fill / obj.getpixelregion / obj.putpixelregion /
|
||||
obj.convolve / obj.resize による画像加工、obj.load("figure"/"text"/
|
||||
"image"/"movie") による生成・読み込み、obj.setfont、obj.effect、
|
||||
obj.getvalue、obj.getaudio、obj.getinfo、obj.setoption /
|
||||
obj.getoption / obj.pixeloption に対応します。詳細は「obj テーブル -
|
||||
関数」を参照してください。
|
||||
|
||||
|
||||
@@ -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)
|
||||
지정 좌표의 픽셀 정보를 취득합니다.
|
||||
@@ -591,12 +605,98 @@
|
||||
장면 크기의 투명한 영역에 오브젝트를 합성한 가상 이미지입니다.
|
||||
※ GPU를 사용할 수 없는 환경에서는 호출이 건너뛰어집니다.
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 전용 확장)
|
||||
오브젝트 이미지를 지정한 색으로 채웁니다. 색은 0~255 의 스트레이트
|
||||
RGBA 로 지정합니다(obj.setpixel 과 같은 표색).
|
||||
r, g, b : 색 성분(0~255).
|
||||
a : 불투명도(0~255). 생략 시 255.
|
||||
x, y, w, h: 채울 사각형. 생략 시 이미지 전체이며 범위를 벗어나면
|
||||
잘립니다.
|
||||
예: obj.fill(0, 0, 0, 0) -- 전체를 투명으로 지움
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
두 엔진 모두에서 동작합니다.
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (YMM4 전용 확장)
|
||||
사각형 영역의 픽셀을 스트레이트 RGBA 배열로 가져옵니다. 배열은
|
||||
픽셀마다 r, g, b, a 순이며 1 부터 시작합니다(색인 (행*w+열)*4+1~+4).
|
||||
이미지 밖의 픽셀은 0,0,0,0 입니다.
|
||||
반환값 : 길이 w*h*4 의 배열.
|
||||
예: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, 데이터) (YMM4 전용 확장)
|
||||
obj.getpixelregion 과 같은 배열을 사각형 영역에 다시 씁니다. 이미지
|
||||
범위를 벗어난 픽셀은 쓰지 않습니다.
|
||||
데이터 : 길이 w*h*4 의 스트레이트 RGBA 배열(1 부터 시작).
|
||||
예: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(커널, 크기 [, 제수 [, 오프셋]]) (YMM4 전용 확장)
|
||||
오브젝트 이미지에 크기×크기 의 컨볼루션을 적용합니다. 흐림, 샤픈,
|
||||
윤곽 검출 등에 사용할 수 있습니다.
|
||||
커널 : 크기*크기 개의 계수 배열(행 우선, 1 부터 시작).
|
||||
크기 : 홀수(3, 5, 7 …). 짝수나 1 미만은 무시합니다.
|
||||
제수 : 각 픽셀의 합계를 이 값으로 나눕니다. 생략 시 커널의
|
||||
합계(합계가 0 이면 1).
|
||||
오프셋 : 나눗셈 후 각 성분에 더합니다. 생략 시 0.
|
||||
가장자리 픽셀은 가장 가까운 픽셀로 채웁니다. r, g, b, a 모두에
|
||||
적용됩니다.
|
||||
예: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 평균 흐림
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 샤픈
|
||||
두 엔진 모두에서 동작합니다.
|
||||
|
||||
○ obj.resize(너비, 높이 [, 보간]) (YMM4 전용 확장)
|
||||
오브젝트 이미지를 지정한 크기로 확대/축소합니다. obj.w / obj.h 등의
|
||||
치수도 갱신됩니다.
|
||||
너비, 높이 : 1 이상의 정수.
|
||||
보간 : "nearest"(최근접) 또는 생략 시 선형 보간.
|
||||
예: obj.resize(obj.w * 2, obj.h * 2)
|
||||
두 엔진 모두에서 동작합니다. 고속 런타임에서는 결과가 최대 이미지
|
||||
크기를 넘으면 변경하지 않습니다.
|
||||
|
||||
○ obj.getvalue(대상)
|
||||
obj의 현재 값을 가져옵니다(obj.x, obj.track0 등과 동일).
|
||||
대상 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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" : 플러그인 설치 폴더의 경로를 반환합니다. 끝에 경로
|
||||
@@ -950,7 +1050,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)
|
||||
获取指定坐标的像素信息。
|
||||
@@ -572,12 +586,89 @@
|
||||
场景大小透明区域后的虚拟图像。
|
||||
※ 在无法使用GPU的环境中会跳过该调用。
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 独有扩展)
|
||||
以指定颜色填充对象图像。颜色以 0~255 的直通 RGBA 指定(与
|
||||
obj.setpixel 相同的表色)。
|
||||
r, g, b : 颜色分量(0~255)。
|
||||
a : 不透明度(0~255)。省略时为 255。
|
||||
x, y, w, h: 要填充的矩形。省略时为整幅图像,超出范围会被裁剪。
|
||||
例: obj.fill(0, 0, 0, 0) -- 将整体清为透明
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
在两个引擎中均可使用。
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (YMM4 独有扩展)
|
||||
将矩形区域的像素读入直通 RGBA 数组。排列为每个像素 r, g, b, a,
|
||||
从 1 开始(索引 (行*w+列)*4+1~+4)。图像外的像素为 0,0,0,0。
|
||||
返回值: 长度为 w*h*4 的数组。
|
||||
例: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, 数据) (YMM4 独有扩展)
|
||||
将与 obj.getpixelregion 相同排列的数组写回矩形区域。超出图像范围的
|
||||
像素不会被写入。
|
||||
数据 : 长度为 w*h*4 的直通 RGBA 数组(从 1 开始)。
|
||||
例: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(卷积核, 大小 [, 除数 [, 偏移]]) (YMM4 独有扩展)
|
||||
对对象图像应用 大小×大小 的卷积。可用于模糊、锐化、边缘检测等。
|
||||
卷积核 : 大小*大小 个系数数组(行优先,从 1 开始)。
|
||||
大小 : 奇数(3、5、7 …)。偶数或小于 1 会被忽略。
|
||||
除数 : 每个像素的合计除以该值。省略时为卷积核的合计(合计为 0
|
||||
时为 1)。
|
||||
偏移 : 除法后加到各分量上。省略时为 0。
|
||||
边缘像素以最近的像素补充。对 r, g, b, a 全部生效。
|
||||
例: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 均值模糊
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 锐化
|
||||
在两个引擎中均可使用。
|
||||
|
||||
○ obj.resize(宽, 高 [, 插值]) (YMM4 独有扩展)
|
||||
将对象图像缩放到指定尺寸。obj.w / obj.h 等尺寸也会更新。
|
||||
宽, 高 : 大于等于 1 的整数。
|
||||
插值 : "nearest"(最近邻)或省略以进行线性插值。
|
||||
例: obj.resize(obj.w * 2, obj.h * 2)
|
||||
在两个引擎中均可使用。在快速运行时中,若结果超过最大图像尺寸
|
||||
则不做更改。
|
||||
|
||||
○ obj.getvalue(目标)
|
||||
获取 obj 的当前值(与 obj.x、obj.track0 等相同)。
|
||||
目标 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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" : 返回插件安装文件夹的路径,末尾带有路径分隔符。
|
||||
@@ -912,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.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)
|
||||
取得指定座標的像素資訊。
|
||||
@@ -572,12 +586,89 @@
|
||||
場景大小透明區域後的虛擬影像。
|
||||
※ 在無法使用GPU的環境中會跳過該呼叫。
|
||||
|
||||
○ obj.fill(r, g, b [, a [, x, y, w, h]]) (YMM4 獨有擴充)
|
||||
以指定顏色填滿物件影像。顏色以 0~255 的直通 RGBA 指定(與
|
||||
obj.setpixel 相同的表色)。
|
||||
r, g, b : 顏色分量(0~255)。
|
||||
a : 不透明度(0~255)。省略時為 255。
|
||||
x, y, w, h: 要填滿的矩形。省略時為整幅影像,超出範圍會被裁切。
|
||||
例: obj.fill(0, 0, 0, 0) -- 將整體清為透明
|
||||
obj.fill(255, 0, 0, 255, 10, 10, 20, 20)
|
||||
在兩個引擎中均可使用。
|
||||
|
||||
○ obj.getpixelregion(x, y, w, h) (YMM4 獨有擴充)
|
||||
將矩形區域的像素讀入直通 RGBA 陣列。排列為每個像素 r, g, b, a,
|
||||
從 1 開始(索引 (列*w+行)*4+1~+4)。影像外的像素為 0,0,0,0。
|
||||
回傳值: 長度為 w*h*4 的陣列。
|
||||
例: local t = obj.getpixelregion(0, 0, obj.w, obj.h)
|
||||
|
||||
○ obj.putpixelregion(x, y, w, h, 資料) (YMM4 獨有擴充)
|
||||
將與 obj.getpixelregion 相同排列的陣列寫回矩形區域。超出影像範圍的
|
||||
像素不會被寫入。
|
||||
資料 : 長度為 w*h*4 的直通 RGBA 陣列(從 1 開始)。
|
||||
例: obj.putpixelregion(0, 0, obj.w, obj.h, t)
|
||||
|
||||
○ obj.convolve(卷積核, 大小 [, 除數 [, 偏移]]) (YMM4 獨有擴充)
|
||||
對物件影像套用 大小×大小 的卷積。可用於模糊、銳化、邊緣偵測等。
|
||||
卷積核 : 大小*大小 個係數陣列(列優先,從 1 開始)。
|
||||
大小 : 奇數(3、5、7 …)。偶數或小於 1 會被忽略。
|
||||
除數 : 每個像素的合計除以該值。省略時為卷積核的合計(合計為 0
|
||||
時為 1)。
|
||||
偏移 : 除法後加到各分量上。省略時為 0。
|
||||
邊緣像素以最近的像素補足。對 r, g, b, a 全部生效。
|
||||
例: obj.convolve({1,1,1, 1,1,1, 1,1,1}, 3) -- 平均模糊
|
||||
obj.convolve({0,-1,0, -1,5,-1, 0,-1,0}, 3) -- 銳化
|
||||
在兩個引擎中均可使用。
|
||||
|
||||
○ obj.resize(寬, 高 [, 內插]) (YMM4 獨有擴充)
|
||||
將物件影像縮放到指定尺寸。obj.w / obj.h 等尺寸也會更新。
|
||||
寬, 高 : 大於等於 1 的整數。
|
||||
內插 : "nearest"(最近鄰)或省略以進行線性內插。
|
||||
例: obj.resize(obj.w * 2, obj.h * 2)
|
||||
在兩個引擎中均可使用。在快速執行環境中,若結果超過最大影像尺寸
|
||||
則不做變更。
|
||||
|
||||
○ obj.getvalue(目標)
|
||||
取得 obj 的目前值(與 obj.x、obj.track0 等相同)。
|
||||
目標 : "x","y","z","ox","oy","rx","ry","rz","zoom","aspect",
|
||||
"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" : 回傳外掛安裝資料夾的路徑,結尾附有路徑分隔字元。
|
||||
@@ -913,7 +1004,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 相容對應表
|
||||
|
||||
@@ -112,13 +112,22 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- **`obj.setpixel(x, y, r, g, b [, a])`**: 指定座標のピクセルを書き換えます。`a` 省略時は 255 として扱われます。内部ではプリマルチプライドアルファ(BGRA)形式で保持され、書き込み時に変換されます。範囲外の座標を指定した場合は何も行いません。
|
||||
- **`obj.getpixeldata()`**: 全ピクセルへ一括アクセスするためのプロキシオブジェクトを返します。`.width` / `.height` に加えて、`:get(index)` / `:set(index, value)` を持ちます。インデックスは 1 始まりで、R, G, B, A の順に並びます(`(y * obj.w + x) * 4 + 1` が R チャンネル)。アルファチャンネルを変更すると RGB が比率変換され、RGB チャンネルを変更すると内部的にプリマルチプライド変換が行われます。
|
||||
- **`obj.putpixeldata()`**: 互換性のために定義された空実装関数です。`setpixel` / `PixelDataProxy:set` による変更は自動的に反映されるため、呼び出す必要はありません。
|
||||
|
||||
さらに、作業画像をまとめて加工する次の関数を用意しています(いずれも AviUtl に無い YMM4 独自拡張で、従来エンジンと高速ランタイムの両方で動作します)。色は `getpixel` / `setpixel` と同じ 0〜255 のストレート RGBA で扱います。
|
||||
|
||||
- **`obj.fill(r, g, b [, a, x, y, w, h])`**: 作業画像(省略時は全体、指定時は矩形)を指定色で塗りつぶします。
|
||||
- **`obj.getpixelregion(x, y, w, h)`**: 矩形領域の画素を長さ `w*h*4` の配列(画素ごとに `r, g, b, a` の順・1 始まり)で取得します。範囲外は `0,0,0,0` です。
|
||||
- **`obj.putpixelregion(x, y, w, h, data)`**: `getpixelregion` と同じ並びの配列を矩形領域へ書き戻します。範囲外へはみ出した画素は書き込みません。
|
||||
- **`obj.convolve(kernel, size [, divisor, offset])`**: `size×size` の畳み込み(ぼかし・シャープ・輪郭抽出など)を適用します。`divisor` 省略時はカーネルの合計で割り、`offset` は除算後に加算します。端は最も近い画素で補います。
|
||||
- **`obj.resize(w, h [, filter])`**: 作業画像を指定サイズへ拡大縮小し、`obj.w` / `obj.h` 等の寸法も更新します。`filter` は `"nearest"` か省略で線形補間です。
|
||||
|
||||
`getpixel` / `setpixel` / `getpixeldata` のいずれかを最初に呼び出した時点で、GPU 上の画像データを CPU 側へ転送する処理が一度だけ発生します。ピクセル操作を行わないスクリプトではこの転送は発生しません。
|
||||
|
||||
これらのピクセル操作を含むスクリプトは自動的に高速化されます。自ピクセル完結のピクセル写像は CPU カーネル(式ツリー)へ、それ以外は高速ランタイム(LuaJIT)へ自動で振り分けられ、いずれも MoonSharp に比べて大幅(内部計測で数十倍)に高速化されます。CPU カーネルと LuaJIT の出力結果は MoonSharp と一致します(明示指定のみで使われる GPU カーネルは float32 精度のためごく僅かに異なり得ます)。詳細・制約は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照してください。
|
||||
|
||||
### 4. scene テーブルと ymm4 テーブル
|
||||
|
||||
`scene` テーブルにはシーン(プロジェクト)の解像度情報と、シーン単位で値を共有する関数が格納されています。
|
||||
`scene` テーブルにはシーンの解像度情報と、シーン単位で値を共有する関数が格納されています。
|
||||
|
||||
| 変数 / 関数 | 説明 |
|
||||
|---|---|
|
||||
@@ -143,7 +152,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
### 5. anim ユーティリティテーブル
|
||||
|
||||
`anim` テーブルには、アニメーション計算に使う純粋な定数・関数群が登録されています。コンテキストに依存しない純粋関数であり、副作用はありません。
|
||||
`anim` テーブルには、アニメーション計算に使う定数・関数群が登録されています。コンテキストに依存しない純粋関数であり、副作用はありません。
|
||||
|
||||
| 関数 / 定数 | 説明 |
|
||||
|---|---|
|
||||
@@ -219,8 +228,10 @@ AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、
|
||||
- **`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)の双方で動作します。
|
||||
- **`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 の関数」を参照してください。
|
||||
|
||||
@@ -402,7 +413,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)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
|
||||
+3
-1
@@ -61,8 +61,10 @@ 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.fill</code>, <code>obj.getpixelregion</code>, <code>obj.putpixelregion</code>, <code>obj.convolve</code>, <code>obj.resize</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||
<tr><td>図形・テキスト・画像・動画・シーン・模様の読み込み</td><td><code>obj.load</code>, <code>obj.setfont</code></td><td><a href="obj-functions.html">obj の関数</a></td></tr>
|
||||
<tr><td>他エフェクトの適用・描画</td><td><code>obj.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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
+93
-1
@@ -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
|
||||
@@ -201,9 +218,15 @@ obj.load("text", "サンプル")</code></pre>
|
||||
<tr><td><code>obj.drawpoly(x0,y0,z0, x1,y1,z1, x2,y2,z2, x3,y3,z3 [, u0,v0, ... ,u3,v3] [, alpha])</code></td><td>4 頂点のテクスチャ付きポリゴンを描画する。UV を省略すると画像全体を使う</td></tr>
|
||||
<tr><td><code>obj.copybuffer(dst, src)</code></td><td>バッファ間でコピーする。ID は <code>obj</code>(作業画像)・<code>tmp</code>・<code>cache:名前</code>・<code>frm</code>(コピー元のみ・仮想フレームバッファ)。書き込み先が <code>obj</code> のときのみ作業画像を置き換える</td></tr>
|
||||
<tr><td><code>obj.pixelshader(name, target, resources [, constants, blend, sampler])</code></td><td>スクリプト内に定義した HLSL のピクセルシェーダーを GPU で実行する。詳細は下記の「ピクセルシェーダー」を参照</td></tr>
|
||||
<tr><td><code>obj.fill(r, g, b [, a, x, y, w, h])</code></td><td>作業画像を指定色で塗りつぶす。色は 0〜255 のストレート RGBA。矩形を省略すると画像全体。<strong>YMM4 独自拡張</strong></td></tr>
|
||||
<tr><td><code>obj.getpixelregion(x, y, w, h)</code></td><td>矩形領域の画素をストレート RGBA の配列(1 始まり・<code>r,g,b,a</code> の順)で取得する。<strong>YMM4 独自拡張</strong></td></tr>
|
||||
<tr><td><code>obj.putpixelregion(x, y, w, h, data)</code></td><td><code>obj.getpixelregion</code> と同じ並びの配列を矩形領域へ書き戻す。<strong>YMM4 独自拡張</strong></td></tr>
|
||||
<tr><td><code>obj.convolve(kernel, size [, divisor, offset])</code></td><td>作業画像へ <code>size×size</code> の畳み込みを適用する(ぼかし・シャープ・輪郭抽出等)。<strong>YMM4 独自拡張</strong></td></tr>
|
||||
<tr><td><code>obj.resize(w, h [, filter])</code></td><td>作業画像を指定サイズへ拡大縮小し、<code>obj.w</code>/<code>obj.h</code> 等も更新する。<code>filter</code> は <code>"nearest"</code> か省略で線形補間。<strong>YMM4 独自拡張</strong></td></tr>
|
||||
<tr><td><code>obj.setoption(name [, value])</code></td><td>オプションを設定する。<code>antialias</code> は <code>obj.draw</code> で参照される。<code>blend</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の合成モードを番号で指定する。番号は下記の「合成モード」を参照。<code>draw_state</code> は真偽値で、<code>true</code> なら作業画像を出力し、<code>false</code> なら入力をそのまま通す。<code>drawtarget</code> は <code>obj.draw</code>/<code>obj.drawpoly</code> の描画先を <code>"framebuffer"</code> と <code>"tempbuffer"</code> で切り替える。詳細は下記の「描画先」を参照</td></tr>
|
||||
<tr><td><code>obj.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>
|
||||
@@ -322,6 +345,43 @@ HLSL のコンパイルエラーはエディターの診断へ表示されます
|
||||
GPU を利用できない環境では呼び出しはスキップされ、画像は変化しません。
|
||||
</p>
|
||||
|
||||
<h3>画像加工(YMM4 独自拡張)</h3>
|
||||
|
||||
<p>
|
||||
<code>obj.fill</code>・<code>obj.getpixelregion</code>・<code>obj.putpixelregion</code>・<code>obj.convolve</code>・<code>obj.resize</code> は、作業画像を直接加工する YMM4 独自の関数です。
|
||||
色は <code>obj.getpixel</code>/<code>obj.setpixel</code> と同じ 0〜255 のストレート RGBA で扱い、いずれも従来エンジンと高速ランタイムの両方で動作します。
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<code>obj.getpixelregion(x, y, w, h)</code> は矩形領域の画素を長さ <code>w*h*4</code> の配列で返します。並びは画素ごとに <code>r, g, b, a</code> で、索引は <code>(行*w+列)*4+1</code> から始まります。範囲外の画素は <code>0,0,0,0</code> です。
|
||||
<code>obj.putpixelregion</code> は同じ並びの配列を書き戻し、画像の範囲外へはみ出した画素は書き込みません。
|
||||
</p>
|
||||
|
||||
<pre><code>-- 左右反転
|
||||
local w, h = obj.w, obj.h
|
||||
local src = obj.getpixelregion(0, 0, w, h)
|
||||
local dst = {}
|
||||
for y = 0, h - 1 do
|
||||
for x = 0, w - 1 do
|
||||
local s = (y * w + (w - 1 - x)) * 4
|
||||
local d = (y * w + x) * 4
|
||||
for c = 1, 4 do dst[d + c] = src[s + c] end
|
||||
end
|
||||
end
|
||||
obj.putpixelregion(0, 0, w, h, dst)</code></pre>
|
||||
|
||||
<p>
|
||||
<code>obj.convolve(kernel, size [, divisor, offset])</code> は <code>size×size</code> の畳み込みを適用します。<code>kernel</code> は行優先で 1 始まりの係数配列、<code>size</code> は奇数です。<code>divisor</code> を省略するとカーネルの合計(合計が 0 のときは 1)で割ります。<code>offset</code> は除算後に各成分へ加算します。端の画素は最も近い画素で補い、<code>r, g, b, a</code> すべてに適用されます。
|
||||
</p>
|
||||
|
||||
<pre><code>obj.convolve({ 1,1,1, 1,1,1, 1,1,1 }, 3) -- 平均ぼかし
|
||||
obj.convolve({ 0,-1,0, -1,5,-1, 0,-1,0 }, 3) -- シャープ
|
||||
obj.convolve({ -1,-1,-1, -1,8,-1, -1,-1,-1 }, 3, 1, 0) -- 輪郭抽出</code></pre>
|
||||
|
||||
<p>
|
||||
<code>obj.resize(w, h [, filter])</code> は作業画像を指定サイズへ拡大縮小し、<code>obj.w</code>・<code>obj.h</code>・<code>obj.cx</code> などの寸法も更新します。<code>filter</code> は <code>"nearest"</code>(最近傍)か、省略で線形補間です。高速ランタイムでは結果が最大画像サイズを超える場合は変更しません。
|
||||
</p>
|
||||
|
||||
<h3>アンカーポイント</h3>
|
||||
|
||||
<p>
|
||||
@@ -342,7 +402,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
|
||||
@@ -351,6 +411,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>
|
||||
|
||||
+8
-1
@@ -77,7 +77,7 @@
|
||||
<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>
|
||||
@@ -90,10 +90,17 @@
|
||||
<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.fill(r, g, b [, a, x, y, w, h])</code></td><td>作業画像を指定色で塗りつぶす(YMM4 独自拡張)</td></tr>
|
||||
<tr><td><code>obj.getpixelregion(x, y, w, h)</code> / <code>obj.putpixelregion(x, y, w, h, data)</code></td><td>矩形領域の画素をストレート RGBA 配列で取得 / 書き戻す(YMM4 独自拡張)</td></tr>
|
||||
<tr><td><code>obj.convolve(kernel, size [, divisor, offset])</code></td><td>作業画像へ畳み込み(ぼかし・シャープ・輪郭抽出)を適用(YMM4 独自拡張)</td></tr>
|
||||
<tr><td><code>obj.resize(w, h [, filter])</code></td><td>作業画像を拡大縮小し寸法を更新(YMM4 独自拡張)</td></tr>
|
||||
<tr><td><code>obj.setoption(name [, value])</code> / <code>obj.getoption(name)</code></td><td>オプションの設定 / 取得</td></tr>
|
||||
<tr><td><code>obj.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>
|
||||
|
||||
+259
-1
@@ -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
|
||||
@@ -98,6 +98,7 @@ 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
|
||||
@@ -131,6 +132,8 @@ local dirty = false
|
||||
local pixelsValid = false
|
||||
local drawTarget = "frame"
|
||||
local pdData, pdCapacity, pdValid, pdDirty = nil, 0, false, false
|
||||
local convSrcData, convSrcCap = nil, 0
|
||||
local resizeSrcData, resizeSrcCap = nil, 0
|
||||
|
||||
local function ensurePixels()
|
||||
if pixelsValid then return end
|
||||
@@ -690,6 +693,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
|
||||
@@ -815,6 +842,223 @@ function obj.copybuffer(dst, src)
|
||||
end
|
||||
end
|
||||
|
||||
function obj.fill(r, g, b, a, x, y, w, h)
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
r = r or 0; g = g or 0; b = b or 0; a = a or 255
|
||||
x = math.floor(x or 0); y = math.floor(y or 0)
|
||||
w = math.floor(w or width); h = math.floor(h or height)
|
||||
local x0 = clamp(x, 0, width)
|
||||
local y0 = clamp(y, 0, height)
|
||||
local x1 = clamp(x + w, 0, width)
|
||||
local y1 = clamp(y + h, 0, height)
|
||||
if x1 <= x0 or y1 <= y0 then return end
|
||||
local aK = clamp(a, 0, 255) / 255
|
||||
local pb = math.floor(clamp(b * aK, 0, 255))
|
||||
local pg = math.floor(clamp(g * aK, 0, 255))
|
||||
local pr = math.floor(clamp(r * aK, 0, 255))
|
||||
local pa = math.floor(clamp(a, 0, 255))
|
||||
for py = y0, y1 - 1 do
|
||||
for px = x0, x1 - 1 do
|
||||
local p = pixels + (py * width + px) * 4
|
||||
p[0] = pb; p[1] = pg; p[2] = pr; p[3] = pa
|
||||
end
|
||||
end
|
||||
dirty = true
|
||||
pdValid = false
|
||||
end
|
||||
|
||||
function obj.getpixelregion(x, y, w, h)
|
||||
x = math.floor(x or 0); y = math.floor(y or 0)
|
||||
w = math.floor(w or 0); h = math.floor(h or 0)
|
||||
local out = {}
|
||||
if w <= 0 or h <= 0 then return out end
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
for j = 0, h - 1 do
|
||||
local sy = y + j
|
||||
for i = 0, w - 1 do
|
||||
local sx = x + i
|
||||
local di = (j * w + i) * 4
|
||||
if sx < 0 or sy < 0 or sx >= width or sy >= height then
|
||||
out[di + 1] = 0; out[di + 2] = 0; out[di + 3] = 0; out[di + 4] = 0
|
||||
else
|
||||
local p = pixels + (sy * width + sx) * 4
|
||||
local a = p[3]
|
||||
if a <= 0 then
|
||||
out[di + 1] = 0; out[di + 2] = 0; out[di + 3] = 0; out[di + 4] = 0
|
||||
else
|
||||
local s = 255 / a
|
||||
out[di + 1] = clamp(p[2] * s, 0, 255)
|
||||
out[di + 2] = clamp(p[1] * s, 0, 255)
|
||||
out[di + 3] = clamp(p[0] * s, 0, 255)
|
||||
out[di + 4] = a
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function obj.putpixelregion(x, y, w, h, data)
|
||||
if type(data) ~= "table" then return end
|
||||
x = math.floor(x or 0); y = math.floor(y or 0)
|
||||
w = math.floor(w or 0); h = math.floor(h or 0)
|
||||
if w <= 0 or h <= 0 then return end
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
for j = 0, h - 1 do
|
||||
local dy = y + j
|
||||
if dy >= 0 and dy < height then
|
||||
for i = 0, w - 1 do
|
||||
local dx = x + i
|
||||
if dx >= 0 and dx < width then
|
||||
local si = (j * w + i) * 4
|
||||
local a = clamp(data[si + 4] or 0, 0, 255)
|
||||
local aK = a / 255
|
||||
local p = pixels + (dy * width + dx) * 4
|
||||
p[0] = math.floor(clamp((data[si + 3] or 0) * aK, 0, 255))
|
||||
p[1] = math.floor(clamp((data[si + 2] or 0) * aK, 0, 255))
|
||||
p[2] = math.floor(clamp((data[si + 1] or 0) * aK, 0, 255))
|
||||
p[3] = math.floor(a)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
dirty = true
|
||||
pdValid = false
|
||||
end
|
||||
|
||||
function obj.convolve(kernel, size, divisor, offset)
|
||||
if type(kernel) ~= "table" then return end
|
||||
size = math.floor(size or 0)
|
||||
if size < 1 or size % 2 == 0 then return end
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
local taps = size * size
|
||||
local k = {}
|
||||
local sum = 0
|
||||
for i = 1, taps do
|
||||
local v = tonumber(kernel[i]) or 0
|
||||
k[i] = v
|
||||
sum = sum + v
|
||||
end
|
||||
local inv = divisor or sum
|
||||
if inv == 0 then inv = 1 end
|
||||
offset = offset or 0
|
||||
local total = width * height * 4
|
||||
if not convSrcData or convSrcCap < total then
|
||||
convSrcData = ffi.new("double[?]", total)
|
||||
convSrcCap = total
|
||||
end
|
||||
local src = convSrcData
|
||||
for pi = 0, width * height - 1 do
|
||||
local p = pixels + pi * 4
|
||||
local di = pi * 4
|
||||
local a = p[3]
|
||||
src[di + 3] = a
|
||||
if a <= 0 then
|
||||
src[di] = 0; src[di + 1] = 0; src[di + 2] = 0
|
||||
else
|
||||
local s = 255 / a
|
||||
src[di] = clamp(p[2] * s, 0, 255)
|
||||
src[di + 1] = clamp(p[1] * s, 0, 255)
|
||||
src[di + 2] = clamp(p[0] * s, 0, 255)
|
||||
end
|
||||
end
|
||||
local half = math.floor(size / 2)
|
||||
for y = 0, height - 1 do
|
||||
for x = 0, width - 1 do
|
||||
local sr, sg, sb, sa = 0, 0, 0, 0
|
||||
for ky = 0, size - 1 do
|
||||
local sy = clamp(y + ky - half, 0, height - 1)
|
||||
for kx = 0, size - 1 do
|
||||
local sx = clamp(x + kx - half, 0, width - 1)
|
||||
local kv = k[ky * size + kx + 1]
|
||||
local si = (sy * width + sx) * 4
|
||||
sr = sr + src[si] * kv
|
||||
sg = sg + src[si + 1] * kv
|
||||
sb = sb + src[si + 2] * kv
|
||||
sa = sa + src[si + 3] * kv
|
||||
end
|
||||
end
|
||||
local rr = clamp(sr / inv + offset, 0, 255)
|
||||
local gg = clamp(sg / inv + offset, 0, 255)
|
||||
local bb = clamp(sb / inv + offset, 0, 255)
|
||||
local aa = clamp(sa / inv + offset, 0, 255)
|
||||
local aK = aa / 255
|
||||
local p = pixels + (y * width + x) * 4
|
||||
p[0] = math.floor(clamp(bb * aK, 0, 255))
|
||||
p[1] = math.floor(clamp(gg * aK, 0, 255))
|
||||
p[2] = math.floor(clamp(rr * aK, 0, 255))
|
||||
p[3] = math.floor(aa)
|
||||
end
|
||||
end
|
||||
dirty = true
|
||||
pdValid = false
|
||||
end
|
||||
|
||||
function obj.resize(newW, newH, mode)
|
||||
newW = math.floor(newW or 0); newH = math.floor(newH or 0)
|
||||
if newW < 1 then newW = 1 end
|
||||
if newH < 1 then newH = 1 end
|
||||
local dstCount = newW * newH * 4
|
||||
if dstCount > pixelCapacity then return end
|
||||
ensurePixels()
|
||||
flushPixelData()
|
||||
local cw, ch = width, height
|
||||
local srcCount = cw * ch * 4
|
||||
if not resizeSrcData or resizeSrcCap < srcCount then
|
||||
resizeSrcData = ffi.new("uint8_t[?]", srcCount)
|
||||
resizeSrcCap = srcCount
|
||||
end
|
||||
ffi.copy(resizeSrcData, pixels, srcCount)
|
||||
local src = resizeSrcData
|
||||
local linear = mode ~= "nearest"
|
||||
for y = 0, newH - 1 do
|
||||
for x = 0, newW - 1 do
|
||||
local o = pixels + (y * newW + x) * 4
|
||||
if not linear then
|
||||
local sx = clamp(math.floor((x + 0.5) * cw / newW), 0, cw - 1)
|
||||
local sy = clamp(math.floor((y + 0.5) * ch / newH), 0, ch - 1)
|
||||
local p = src + (sy * cw + sx) * 4
|
||||
o[0] = p[0]; o[1] = p[1]; o[2] = p[2]; o[3] = p[3]
|
||||
else
|
||||
local u = (x + 0.5) * cw / newW - 0.5
|
||||
local v = (y + 0.5) * ch / newH - 0.5
|
||||
local x0 = math.floor(u)
|
||||
local y0 = math.floor(v)
|
||||
local tx = u - x0
|
||||
local ty = v - y0
|
||||
for c = 0, 3 do
|
||||
local acc = 0
|
||||
for j = 0, 1 do
|
||||
local sy = clamp(y0 + j, 0, ch - 1)
|
||||
local wy = (j == 0) and (1 - ty) or ty
|
||||
for i = 0, 1 do
|
||||
local sx = clamp(x0 + i, 0, cw - 1)
|
||||
local wx = (i == 0) and (1 - tx) or tx
|
||||
acc = acc + src[(sy * cw + sx) * 4 + c] * wy * wx
|
||||
end
|
||||
end
|
||||
o[c] = math.floor(clamp(acc, 0, 255))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
width = newW; height = newH
|
||||
i32[OFF_WIDTH] = newW; i32[OFF_HEIGHT] = newH
|
||||
dirty = true
|
||||
pixelsValid = true
|
||||
pdValid = false
|
||||
pdDirty = false
|
||||
obj.w = newW; obj.h = newH
|
||||
obj.hw = newW / 2; obj.hh = newH / 2
|
||||
obj.cx = newW / 2; obj.cy = newH / 2
|
||||
obj.cz = 0
|
||||
obj.diagonal = math.sqrt(newW * newW + newH * newH)
|
||||
end
|
||||
|
||||
local SCENE_VALUE_MAX = 4095
|
||||
local SCENE_NIL = {}
|
||||
local sceneReads = {}
|
||||
@@ -910,6 +1154,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 {
|
||||
@@ -919,6 +1164,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
|
||||
|
||||
@@ -1116,6 +1363,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
|
||||
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする