コミットを比較
| 作成者 | SHA1 | 日付 | |
|---|---|---|---|
|
|
4f2389702a
|
||
|
|
247bb83230
|
||
|
|
1d495039f0
|
||
|
|
56d7937be1
|
||
|
|
cade7e8a8f
|
||
|
|
9e8e024db9
|
||
|
|
69881878e4
|
||
|
|
42e0b2b0f7
|
||
|
|
954b1bfc49
|
||
|
|
41defa1059
|
||
|
|
876f05d277
|
||
|
|
227af2c75c
|
||
|
|
5cbd5ae8ff
|
||
|
|
bb97610454
|
||
|
|
968180c459
|
||
|
|
d9ad3692f2
|
検索条件に一致するファイルはありません
+40
-55
@@ -1,73 +1,58 @@
|
||||
# v1.3.0 - Lua スクリプト for YMM4
|
||||
# v1.4.0 - Lua スクリプト for YMM4
|
||||
|
||||
ピクセル操作スクリプトを**大幅に高速化**したリリースです。
|
||||
`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` を使うスクリプトは、同梱した高速
|
||||
ランタイム(LuaJIT)で自動的に実行されるようになり、内部計測では**最大で数十倍**
|
||||
(例:1920×1080 のフルフレーム加工で約 41 倍、小さめの画像では 70 倍前後)の
|
||||
高速化を確認しています。
|
||||
AviUtl のアニメーション効果スクリプト(`.anm` 系)に対する**部分互換層**を追加した
|
||||
リリースです。座標・拡縮・回転・不透明度の変形と乱数を用いる範囲について、追加の
|
||||
記述変更なしで AviUtl 向けスクリプトを実行できるようになりました。
|
||||
|
||||
---
|
||||
|
||||
## 新機能・改善
|
||||
## 新機能
|
||||
|
||||
### 1. ピクセル操作スクリプトの自動高速化
|
||||
### 1. AviUtl スクリプトの部分互換
|
||||
|
||||
ピクセル操作 API(`obj.getpixel` / `obj.setpixel` / `obj.getpixeldata`)を含むスクリプトは、
|
||||
**特別な記述なしで自動的に高速ランタイム(ネイティブ実行)へ振り分け**られます。
|
||||
変形のみ(座標・回転・拡縮・不透明度)のスクリプトは従来どおりの実行系で動作します
|
||||
(変形のみの処理は元々十分高速なため、速度差はありません)。
|
||||
AviUtl のアニメーション効果スクリプトのうち、本プラグインの変形・ピクセルモデルへ
|
||||
無理なく写像できる範囲を実行できる互換層を追加しました。スクリプトに AviUtl 固有の
|
||||
記法が含まれない場合、この互換層は一切介入しないため、従来のスクリプトの挙動は
|
||||
変わりません。
|
||||
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で
|
||||
受け渡されます。スクリプトが無限ループに陥っても、**5 秒のタイムアウトで強制終了**
|
||||
され、本体が固まることはありません(終了後は自動的に復帰します)。
|
||||
- **スクリプトヘッダの解釈**: コメント形式のパラメータ宣言を解釈し、スクリプト本体が
|
||||
参照する変数を実行前に定義します。これまでは単なるコメントとして無視され、参照変数が
|
||||
`nil` になり実行できなかったスクリプトが動作するようになります。
|
||||
- `--dialog:項目名,local 変数=既定値;…` … 各項目の宣言部を本体の先頭へ展開します。
|
||||
- `--color:0xRRGGBB` … 変数 `color` を指定色で定義します。
|
||||
- `--check0:項目名,既定値` … `obj.check0`(`0`〜`3`)を既定値で定義します。
|
||||
- `--param:任意のLua文` … 記述した Lua 文をそのまま本体の先頭へ展開します。
|
||||
- `--track0:`〜`--track3:` … 値は従来どおり `obj.track0`〜`obj.track3` から参照します
|
||||
(ラベル・範囲・既定値の UI 反映は行いません)。
|
||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されて
|
||||
いる場合、先頭のセクションのみを実行します。
|
||||
|
||||
### 2. 実行エンジンを指定するディレクティブ
|
||||
### 2. obj.rand の追加
|
||||
|
||||
スクリプトの先頭行に次のディレクティブを書くことで、実行エンジンを明示指定できます。
|
||||
|
||||
- `--!native` … 高速ランタイム(LuaJIT)で実行
|
||||
- `--!moonsharp` … 従来エンジン(MoonSharp)で実行
|
||||
- 記述なし … ピクセル操作を含む場合は自動的にネイティブ、それ以外は従来エンジン
|
||||
|
||||
### 3. bit32 の Lua 5.2 準拠化(ネイティブ実行時)
|
||||
|
||||
ネイティブ実行時の `bit32` ライブラリは、正しい Lua 5.2 の挙動になりました。
|
||||
実用域(0〜2^31 未満の値、0〜31 のシフト量)では従来と完全に一致するため、
|
||||
通常のスクリプトの見た目は変わりません。`bit32.lshift(1, 32)` のような範囲外の
|
||||
特殊なケースのみ結果が変わります(ネイティブ=正しい 0、従来=1)。
|
||||
|
||||
### 4. 変形処理のアロケーション削減
|
||||
|
||||
毎フレームの実行で発生していた一時オブジェクトの確保を削減し、シーンオブジェクトの
|
||||
解決を遅延化しました。長時間の出力における GC 負荷を軽減します。
|
||||
AviUtl 互換の決定論的な整数乱数 `obj.rand(st, ed [, seed [, frame]])` を追加しました。
|
||||
指定範囲 `st`〜`ed` の整数を返し、`seed` と `frame` が同じであれば常に同じ値を返します。
|
||||
`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム
|
||||
(LuaJIT)で同じ値を返すため、エンジンの自動振り分けによらず結果が一致します。
|
||||
|
||||
---
|
||||
|
||||
## 注意事項(ネイティブ実行時の制約)
|
||||
## 注意事項
|
||||
|
||||
- **`obj.getobject` はネイティブ実行では使用できません**(常に `nil` を返します)。
|
||||
他オブジェクトの参照を行うスクリプトには `--!native` を付けないでください
|
||||
(ピクセル操作と併用する場合は `--!moonsharp` を明示してください)。
|
||||
- `math.random` は両エンジンとも「フレーム番号でシードし直す決定論的乱数」ですが、
|
||||
乱数列の実装が異なるため、エンジンをまたぐと同じシードでも値が変わります。
|
||||
エンジンに依存しない乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
|
||||
- ネイティブ実行は最初のピクセルアクセス前から GPU→CPU の画像転送を行います。
|
||||
- 描画・フィルタ・ファイルアクセス系の関数(`obj.load` / `obj.draw` / `obj.drawpoly` /
|
||||
`obj.effect` / `obj.copybuffer` / `obj.setoption` / `obj.setfont`、`require`、`io` 等)は
|
||||
本体の描画パイプラインへの統合を要するため、この互換層では対象外です。これらを呼び出す
|
||||
スクリプトは意図どおりには動作しません。
|
||||
- `--track0:`〜`--track3:` のラベル・範囲・既定値はエフェクトパネルの UI へ反映されません。
|
||||
トラックバーの値は従来どおり Track0〜Track3 のスライダー値が使用されます。
|
||||
- エンジンに依存しない小数の乱数が必要な場合は、従来どおり `anim.rand` を使用してください。
|
||||
|
||||
---
|
||||
|
||||
## 内部実装
|
||||
|
||||
- 同梱した LuaJIT を別プロセスで常駐させ、名前付き共有メモリとイベントで往復します。
|
||||
タイムアウト時はプロセスを強制終了し、自動的に再起動します。
|
||||
- ネイティブ側に `bit32`(正しい 5.2)・`rawlen`・`anim.*`(`rand` / `noise` を含む)・
|
||||
`obj.getpixel` / `setpixel` / `getpixeldata` を実装し、従来エンジンとの**出力一致を
|
||||
自動テストで検証**しています(2800 件超のクロスエンジン等価テストを追加)。
|
||||
- ユーザースクリプトはサンドボックス環境で実行され、`io` / `os` / `ffi` / `require`
|
||||
などは従来どおり利用できません。
|
||||
|
||||
---
|
||||
|
||||
## 同梱物
|
||||
|
||||
- 本プラグインには高速ランタイム(`luajit.exe` / `lua51.dll`)と実行スクリプトを同梱して
|
||||
おり、プラグイン本体と同じ `native` フォルダーに配置されます(手動インストールは不要)。
|
||||
- スクリプトを実行可能な Lua へ変換する前処理を追加し、MoonSharp・LuaJIT の両実行系へ
|
||||
一貫して適用しました。変換結果はソース単位でキャッシュし、毎フレームの再解析を避けています。
|
||||
- `obj.rand` の数値コアを C# と LuaJIT で同一アルゴリズムとして実装し、両者がビット単位で
|
||||
一致することを等価性テストで検証しています。
|
||||
- AviUtl 固有の記法を含まないスクリプトでは前処理がソースをそのまま返すため、既存スクリプト
|
||||
および既存の実行・キャッシュ経路に対する影響はありません。
|
||||
@@ -0,0 +1,32 @@
|
||||
Lua License
|
||||
-----------
|
||||
|
||||
Lua is licensed under the terms of the MIT license reproduced below. This means
|
||||
that Lua is free software and can be used for both academic and commercial
|
||||
purposes at absolutely no cost.
|
||||
|
||||
For details and rationale, see https://www.lua.org/license.html .
|
||||
|
||||
===============================================================================
|
||||
|
||||
Copyright (C) 1994-2025 Lua.org, PUC-Rio.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
===============================================================================
|
||||
@@ -0,0 +1,56 @@
|
||||
===============================================================================
|
||||
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
|
||||
|
||||
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
[ MIT license: https://www.opensource.org/licenses/mit-license.php ]
|
||||
|
||||
===============================================================================
|
||||
[ LuaJIT includes code from Lua 5.1/5.2, which has this license statement: ]
|
||||
|
||||
Copyright (C) 1994-2012 Lua.org, PUC-Rio.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
===============================================================================
|
||||
[ LuaJIT includes code from dlmalloc, which has this license statement: ]
|
||||
|
||||
This is a version (aka dlmalloc) of malloc/free/realloc written by
|
||||
Doug Lea and released to the public domain, as explained at
|
||||
https://creativecommons.org/licenses/publicdomain
|
||||
|
||||
===============================================================================
|
||||
@@ -0,0 +1,38 @@
|
||||
Copyright (c) 2014-2016, Marco Mastropaolo
|
||||
All rights reserved.
|
||||
|
||||
Parts of the string library are based on the KopiLua project (https://github.com/NLua/KopiLua)
|
||||
Copyright (c) 2012 LoDC
|
||||
|
||||
Visual Studio Code debugger code is based on code from Microsoft vscode-mono-debug project (https://github.com/Microsoft/vscode-mono-debug).
|
||||
Copyright (c) Microsoft Corporation - released under MIT license.
|
||||
|
||||
Remote Debugger icons are from the Eclipse project (https://www.eclipse.org/).
|
||||
Copyright of The Eclipse Foundation
|
||||
|
||||
The MoonSharp icon is (c) Isaac, 2014-2015
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
* Neither the name of the {organization} nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -1,5 +1,5 @@
|
||||
========================================
|
||||
Luaスクリプト for YMM4 v1.2.0
|
||||
Luaスクリプト for YMM4 v1.4.0
|
||||
========================================
|
||||
YukkuriMovieMaker4(YMM4)上で動作する、Luaスクリプトで映像エフェクトのパラメータや
|
||||
ピクセルを直接制御できるプラグインです。
|
||||
|
||||
@@ -70,6 +70,7 @@ jobs:
|
||||
|
||||
New-Item -ItemType Directory -Path "$stageRoot/docs" -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$stageRoot/native" -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path "$stageRoot/LICENSE" -Force | Out-Null
|
||||
|
||||
Copy-Item "$outDir/LuaScript.dll" "$stageRoot/"
|
||||
Copy-Item "$outDir/MoonSharp.Interpreter.dll" "$stageRoot/"
|
||||
@@ -87,6 +88,7 @@ jobs:
|
||||
}
|
||||
|
||||
Copy-Item "LuaScript/docs/LuaScript.*.txt" "$stageRoot/docs/"
|
||||
Copy-Item ".github/LICENSE/*.txt" "$stageRoot/LICENSE/"
|
||||
Copy-Item ".github/Plugin_Readme.txt" "$stageRoot/Readme.txt"
|
||||
|
||||
Compress-Archive -Path "stage/*" -DestinationPath $pkgName -CompressionLevel Optimal
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using LuaScript.Compat;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class AviUtlRandomEquivalenceTests
|
||||
{
|
||||
[Fact]
|
||||
public void Rand_StaysWithinRequestedRange()
|
||||
{
|
||||
for (int seed = 0; seed < 64; seed++)
|
||||
{
|
||||
double value = AviUtlRandom.Next(-3, 7, seed, seed * 3 + 1);
|
||||
Assert.InRange(value, -3d, 7d);
|
||||
Assert.Equal(Math.Floor(value), value);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rand_IsDeterministicForSameInputs()
|
||||
{
|
||||
Assert.Equal(
|
||||
AviUtlRandom.Next(0, 100, 5, 12),
|
||||
AviUtlRandom.Next(0, 100, 5, 12));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Rand_MatchesBetweenMoonSharpAndLuaJit()
|
||||
{
|
||||
var lane = new LuaJitLane();
|
||||
Assert.True(lane.Available, "native/luajit.exe must be present");
|
||||
|
||||
var cases = new List<(double A, double B, double Seed, double Frame)>();
|
||||
for (int seed = 0; seed < 16; seed++)
|
||||
for (int frame = 0; frame < 4; frame++)
|
||||
{
|
||||
cases.Add((0d, 100d, seed, frame));
|
||||
cases.Add((-50d, 50d, seed + 1, frame * 7));
|
||||
cases.Add((1d, 6d, seed * 13, frame));
|
||||
cases.Add((-3.5d, 3.5d, seed, frame + 1000));
|
||||
}
|
||||
|
||||
var exprs = new List<string>(cases.Count);
|
||||
foreach (var c in cases)
|
||||
exprs.Add($"aviutl_rand({L(c.A)},{L(c.B)},{L(c.Seed)},{L(c.Frame)})");
|
||||
|
||||
string[] lines = lane.Eval(exprs);
|
||||
Assert.Equal(exprs.Count, lines.Length);
|
||||
|
||||
var failures = new List<string>();
|
||||
for (int i = 0; i < cases.Count; i++)
|
||||
{
|
||||
double expected = AviUtlRandom.Next(cases[i].A, cases[i].B, cases[i].Seed, cases[i].Frame);
|
||||
if (!double.TryParse(lines[i], NumberStyles.Float, CultureInfo.InvariantCulture, out var got))
|
||||
{
|
||||
failures.Add($"{exprs[i]} => luajit '{lines[i]}' (not a number), expected {expected}");
|
||||
continue;
|
||||
}
|
||||
if (got != expected)
|
||||
failures.Add($"{exprs[i]} => luajit {got}, moonsharp {expected}");
|
||||
}
|
||||
|
||||
Assert.True(failures.Count == 0,
|
||||
$"{failures.Count}/{cases.Count} mismatches:\n" + string.Join("\n", failures.GetRange(0, Math.Min(25, failures.Count))));
|
||||
}
|
||||
|
||||
private static string L(double value) => value.ToString("R", CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
|
||||
namespace LuaScript.Tests
|
||||
{
|
||||
public class AviUtlScriptTests
|
||||
{
|
||||
private static Script NewScript()
|
||||
{
|
||||
var script = new Script(
|
||||
CoreModules.Basic |
|
||||
CoreModules.Math |
|
||||
CoreModules.String |
|
||||
CoreModules.Table |
|
||||
CoreModules.Bit32 |
|
||||
CoreModules.TableIterators |
|
||||
CoreModules.Metatables |
|
||||
CoreModules.ErrorHandling);
|
||||
script.Globals["obj"] = new Table(script);
|
||||
return script;
|
||||
}
|
||||
|
||||
private static double RunNumber(string transformed, string global = "result")
|
||||
{
|
||||
var script = NewScript();
|
||||
script.DoString(transformed);
|
||||
return script.Globals.Get(global).Number;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PlainScript_IsReturnedUnchanged()
|
||||
{
|
||||
const string source = "obj.x = 1\nobj.y = 2";
|
||||
Assert.Equal(source, AviUtlScript.Transform(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TrackOnlyHeader_IsReturnedUnchanged()
|
||||
{
|
||||
const string source = "--track0:Amp,0,100,10\nobj.ox = obj.track0";
|
||||
Assert.Equal(source, AviUtlScript.Transform(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DirectiveComment_IsNotConfusedWithDirective()
|
||||
{
|
||||
const string source = "-- color reference note\nobj.x = 1";
|
||||
Assert.Equal(source, AviUtlScript.Transform(source));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EngineDirective_IsPreserved()
|
||||
{
|
||||
const string source = "--!native\n--dialog:V,local v=3;\nresult = v";
|
||||
string transformed = AviUtlScript.Transform(source);
|
||||
Assert.Contains("--!native", transformed);
|
||||
Assert.Equal(3d, RunNumber(transformed));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Dialog_InjectsDefaultDeclarations()
|
||||
{
|
||||
const string source = "--dialog:Angle,local angle=45;Dist,local dist=100;\nresult = dist";
|
||||
double result = RunNumber(AviUtlScript.Transform(source));
|
||||
Assert.Equal(100d, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Color_InjectsColorVariable()
|
||||
{
|
||||
const string source = "--color:0x010203\nresult = color";
|
||||
double result = RunNumber(AviUtlScript.Transform(source));
|
||||
Assert.Equal(0x010203, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Check_InjectsObjectField()
|
||||
{
|
||||
const string source = "--check0:Enable,1\nresult = obj.check0";
|
||||
double result = RunNumber(AviUtlScript.Transform(source));
|
||||
Assert.Equal(1d, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Param_InjectsRawLua()
|
||||
{
|
||||
const string source = "--param:result = 7\nlocal x = 1";
|
||||
double result = RunNumber(AviUtlScript.Transform(source));
|
||||
Assert.Equal(7d, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Section_FirstSectionIsSelected()
|
||||
{
|
||||
const string source = "@First\n--dialog:A,local a=5;\nresult = a\n@Second\nresult = 999";
|
||||
double result = RunNumber(AviUtlScript.Transform(source));
|
||||
Assert.Equal(5d, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Section_PreambleBeforeFirstHeaderIsDiscarded()
|
||||
{
|
||||
const string source = "result = 111\n@Only\nresult = 222";
|
||||
double result = RunNumber(AviUtlScript.Transform(source));
|
||||
Assert.Equal(222d, result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClassicTransformScript_RunsAndMovesObject()
|
||||
{
|
||||
const string source =
|
||||
"--track0:Range,0,2000,10\n" +
|
||||
"--dialog:Seed,local seed=3;\n" +
|
||||
"obj.ox = obj.ox + obj.track0 * obj.rand(-100,100,seed,obj.time) / 100";
|
||||
|
||||
var script = NewScript();
|
||||
var obj = script.Globals.Get("obj").Table;
|
||||
obj["ox"] = 0d;
|
||||
obj["track0"] = 500d;
|
||||
obj["time"] = 2d;
|
||||
obj["frame"] = 4d;
|
||||
obj["rand"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
double frameDefault = obj.Get("frame").CastToNumber() ?? 0d;
|
||||
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
|
||||
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
|
||||
});
|
||||
|
||||
script.DoString(AviUtlScript.Transform(source));
|
||||
double moved = obj.Get("ox").Number;
|
||||
|
||||
double expectedRand = AviUtlRandom.Next(-100, 100, 3, 2);
|
||||
Assert.Equal(500d * expectedRand / 100d, moved);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,8 +28,12 @@
|
||||
<Compile Include="..\LuaScript\Compat\Bit32.cs" Link="Linked\Bit32.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\ScriptEngineKind.cs" Link="Linked\ScriptEngineKind.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\NativeProtocol.cs" Link="Linked\NativeProtocol.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\ProcessJobObject.cs" Link="Linked\ProcessJobObject.cs" />
|
||||
<Compile Include="..\LuaScript\Engine\LuaJitWorker.cs" Link="Linked\LuaJitWorker.cs" />
|
||||
<Compile Include="..\LuaScript\SceneObjectInfo.cs" Link="Linked\SceneObjectInfo.cs" />
|
||||
<Compile Include="..\LuaScript\AnimTableRegistrar.cs" Link="Linked\AnimTableRegistrar.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlScript.cs" Link="Linked\AviUtlScript.cs" />
|
||||
<Compile Include="..\LuaScript\Compat\AviUtlRandom.cs" Link="Linked\AviUtlRandom.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -8,6 +8,8 @@ namespace LuaScript.Tests
|
||||
{
|
||||
private static string NativeDir => Path.Combine(AppContext.BaseDirectory, "native");
|
||||
|
||||
private static readonly Func<string, int, SceneObjectInfo?> NoResolver = (_, _) => null;
|
||||
|
||||
private readonly LuaJitWorker _worker = new(NativeDir);
|
||||
|
||||
public void Dispose() => _worker.Dispose();
|
||||
@@ -32,7 +34,7 @@ namespace LuaScript.Tests
|
||||
|
||||
bool ok = _worker.Execute(
|
||||
"obj.rz = obj.time * 90\nobj.alpha = 128",
|
||||
fields, pixels, 4, 4, 5000, out bool dirty, out string? error);
|
||||
fields, pixels, 4, 4, 5000, NoResolver, out bool dirty, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.False(dirty);
|
||||
@@ -67,7 +69,7 @@ namespace LuaScript.Tests
|
||||
"local gray = r*0.299 + g*0.587 + b*0.114 " +
|
||||
"obj.setpixel(x,y,gray,gray,gray,a) end end";
|
||||
|
||||
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, out bool dirty, out string? error);
|
||||
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
@@ -102,7 +104,7 @@ namespace LuaScript.Tests
|
||||
"local gray=r*0.299+g*0.587+b*0.114 " +
|
||||
"pd:set(base+1,gray) pd:set(base+2,gray) pd:set(base+3,gray) end end";
|
||||
|
||||
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, out bool dirty, out string? error);
|
||||
bool ok = _worker.Execute(script, fields, pixels, w, h, 5000, NoResolver, out bool dirty, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.True(dirty);
|
||||
@@ -138,7 +140,7 @@ namespace LuaScript.Tests
|
||||
for (int k = 1; k <= 5; k++)
|
||||
{
|
||||
var fields = Fields(2, 2, k);
|
||||
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, out _, out string? error);
|
||||
bool ok = _worker.Execute("obj.x = obj.time * 10", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(k * 10d, fields[NativeProtocol.X]);
|
||||
}
|
||||
@@ -153,16 +155,94 @@ namespace LuaScript.Tests
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool timedOut = _worker.Execute(
|
||||
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, out _, out string? error);
|
||||
"local x=0 while true do x=x+1 end", fields, pixels, 2, 2, 1500, NoResolver, out _, out string? error);
|
||||
Assert.False(timedOut);
|
||||
Assert.Contains("timed out", error);
|
||||
|
||||
var fields2 = Fields(2, 2, 3d);
|
||||
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, out _, out error);
|
||||
bool ok = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error);
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(3d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetObject_ResolvesThroughCallback()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
var resolved = new SceneObjectInfo("a", true, 12d, 34d, 56d, 2d, 90d, 200d, 7);
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
tag == "a" && frame == 5 ? resolved : null;
|
||||
|
||||
const string script =
|
||||
"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";
|
||||
|
||||
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(12d, fields[NativeProtocol.X]);
|
||||
Assert.Equal(34d, fields[NativeProtocol.Y]);
|
||||
Assert.Equal(56d, fields[NativeProtocol.Z]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Zoom]);
|
||||
Assert.Equal(90d, fields[NativeProtocol.Rz]);
|
||||
Assert.Equal(200d, fields[NativeProtocol.Alpha]);
|
||||
Assert.Equal(2d, fields[NativeProtocol.Sx]);
|
||||
Assert.Equal(90d * Math.PI / 180d, fields[NativeProtocol.Rzr]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetObject_CachesRepeatedQueryAndResetsEachRun()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
int calls = 0;
|
||||
double x = 10d;
|
||||
Func<string, int, SceneObjectInfo?> resolver = (tag, frame) =>
|
||||
{
|
||||
calls++;
|
||||
return tag == "a" ? new SceneObjectInfo("a", true, x, 0, 0, 1, 0, 255, 0) : null;
|
||||
};
|
||||
|
||||
const string script =
|
||||
"local a = obj.getobject(\"a\") " +
|
||||
"local b = obj.getobject(\"a\") " +
|
||||
"obj.x = a.x + b.x";
|
||||
|
||||
bool ok = _worker.Execute(script, Fields(2, 2, 0d), pixels, 2, 2, 5000, resolver, out _, out string? error);
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1, calls);
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
x = 20d;
|
||||
ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, resolver, out _, out error);
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(2, calls);
|
||||
Assert.Equal(40d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void GetObject_ReturnsNil_WhenUnresolved()
|
||||
{
|
||||
Assert.True(LuaJitWorker.IsAvailable(NativeDir), "native/luajit.exe must be present");
|
||||
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
const string script =
|
||||
"local o = obj.getobject(\"missing\") obj.x = o == nil and 1 or 0";
|
||||
|
||||
bool ok = _worker.Execute(script, fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
|
||||
|
||||
Assert.True(ok, error);
|
||||
Assert.Equal(1d, fields[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RuntimeError_IsReported_AndWorkerSurvives()
|
||||
{
|
||||
@@ -171,12 +251,12 @@ namespace LuaScript.Tests
|
||||
var pixels = new byte[16];
|
||||
var fields = Fields(2, 2, 0d);
|
||||
|
||||
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, out _, out string? error);
|
||||
bool ok = _worker.Execute("obj.x = missing.value", fields, pixels, 2, 2, 5000, NoResolver, out _, out string? error);
|
||||
Assert.False(ok);
|
||||
Assert.False(string.IsNullOrEmpty(error));
|
||||
|
||||
var fields2 = Fields(2, 2, 7d);
|
||||
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, out _, out error);
|
||||
bool ok2 = _worker.Execute("obj.x = obj.time", fields2, pixels, 2, 2, 5000, NoResolver, out _, out error);
|
||||
Assert.True(ok2, error);
|
||||
Assert.Equal(7d, fields2[NativeProtocol.X]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
using System;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class AviUtlRandom
|
||||
{
|
||||
public static double Next(double a, double b, double seed, double frame)
|
||||
{
|
||||
long seedBits = BitConverter.DoubleToInt64Bits(seed);
|
||||
long frameBits = BitConverter.DoubleToInt64Bits(frame);
|
||||
uint s = (uint)(seedBits ^ (seedBits >> 32));
|
||||
uint f = (uint)(frameBits ^ (frameBits >> 32));
|
||||
|
||||
uint h = s * 374761393u + f * 668265263u;
|
||||
h = (h ^ (h >> 13)) * 1274126177u;
|
||||
h ^= h >> 16;
|
||||
|
||||
double r = h / 4294967295.0;
|
||||
|
||||
long lo = (long)Math.Floor(Math.Min(a, b));
|
||||
long hi = (long)Math.Floor(Math.Max(a, b));
|
||||
long span = hi - lo + 1L;
|
||||
if (span <= 1L)
|
||||
return lo;
|
||||
|
||||
long value = lo + (long)(r * span);
|
||||
return value > hi ? hi : value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace LuaScript.Compat
|
||||
{
|
||||
internal static class AviUtlScript
|
||||
{
|
||||
private enum DirectiveKind
|
||||
{
|
||||
None,
|
||||
Dialog,
|
||||
Color,
|
||||
Check,
|
||||
Param,
|
||||
}
|
||||
|
||||
public static string Transform(string source)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source))
|
||||
return source;
|
||||
|
||||
var lines = source.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n');
|
||||
|
||||
int sectionStart = 0;
|
||||
int sectionEnd = lines.Length;
|
||||
bool hasSection = false;
|
||||
|
||||
for (int i = 0; i < lines.Length; i++)
|
||||
{
|
||||
if (!IsSectionHeader(lines[i]))
|
||||
continue;
|
||||
|
||||
hasSection = true;
|
||||
sectionStart = i + 1;
|
||||
sectionEnd = lines.Length;
|
||||
for (int j = sectionStart; j < lines.Length; j++)
|
||||
{
|
||||
if (IsSectionHeader(lines[j]))
|
||||
{
|
||||
sectionEnd = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
var prelude = new List<string>();
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
AppendDeclarations(lines[i], prelude);
|
||||
|
||||
if (!hasSection && prelude.Count == 0)
|
||||
return source;
|
||||
|
||||
var builder = new StringBuilder(source.Length + 64);
|
||||
foreach (var declaration in prelude)
|
||||
builder.Append(declaration).Append('\n');
|
||||
for (int i = sectionStart; i < sectionEnd; i++)
|
||||
builder.Append(lines[i]).Append('\n');
|
||||
|
||||
return builder.ToString();
|
||||
}
|
||||
|
||||
private static bool IsSectionHeader(string line)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
return i < line.Length && line[i] == '@';
|
||||
}
|
||||
|
||||
private static void AppendDeclarations(string line, List<string> prelude)
|
||||
{
|
||||
int i = SkipSpaces(line, 0);
|
||||
if (i + 1 >= line.Length || line[i] != '-' || line[i + 1] != '-')
|
||||
return;
|
||||
i += 2;
|
||||
if (i < line.Length && line[i] == '!')
|
||||
return;
|
||||
|
||||
int nameStart = i;
|
||||
while (i < line.Length && IsNameChar(line[i]))
|
||||
i++;
|
||||
if (i >= line.Length || line[i] != ':')
|
||||
return;
|
||||
|
||||
string name = line.Substring(nameStart, i - nameStart);
|
||||
string content = line.Substring(i + 1);
|
||||
|
||||
switch (Classify(name))
|
||||
{
|
||||
case DirectiveKind.Dialog:
|
||||
AppendDialog(content, prelude);
|
||||
break;
|
||||
case DirectiveKind.Color:
|
||||
AppendColor(content, prelude);
|
||||
break;
|
||||
case DirectiveKind.Check:
|
||||
AppendCheck(name, content, prelude);
|
||||
break;
|
||||
case DirectiveKind.Param:
|
||||
AppendParam(content, prelude);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static DirectiveKind Classify(string name)
|
||||
{
|
||||
if (name.Equals("dialog", StringComparison.OrdinalIgnoreCase))
|
||||
return DirectiveKind.Dialog;
|
||||
if (name.Equals("color", StringComparison.OrdinalIgnoreCase))
|
||||
return DirectiveKind.Color;
|
||||
if (name.Equals("param", StringComparison.OrdinalIgnoreCase))
|
||||
return DirectiveKind.Param;
|
||||
if (name.Length > 5 && name.StartsWith("check", StringComparison.OrdinalIgnoreCase) && AllDigits(name, 5))
|
||||
return DirectiveKind.Check;
|
||||
return DirectiveKind.None;
|
||||
}
|
||||
|
||||
private static void AppendDialog(string content, List<string> prelude)
|
||||
{
|
||||
foreach (var segment in content.Split(';'))
|
||||
{
|
||||
string trimmed = segment.Trim();
|
||||
if (trimmed.Length == 0)
|
||||
continue;
|
||||
int comma = trimmed.IndexOf(',');
|
||||
if (comma < 0)
|
||||
continue;
|
||||
string declaration = trimmed.Substring(comma + 1).Trim();
|
||||
if (declaration.Length != 0)
|
||||
prelude.Add(declaration);
|
||||
}
|
||||
}
|
||||
|
||||
private static void AppendColor(string content, List<string> prelude)
|
||||
{
|
||||
string token = FirstToken(content);
|
||||
if (IsColorLiteral(token))
|
||||
prelude.Add("local color = " + token);
|
||||
}
|
||||
|
||||
private static void AppendCheck(string name, string content, List<string> prelude)
|
||||
{
|
||||
string index = name.Substring(5);
|
||||
var parts = content.Split(',');
|
||||
string def = parts[parts.Length - 1].Trim();
|
||||
if (IsIntegerLiteral(def))
|
||||
prelude.Add("obj.check" + index + " = " + def);
|
||||
}
|
||||
|
||||
private static void AppendParam(string content, List<string> prelude)
|
||||
{
|
||||
string trimmed = content.Trim();
|
||||
if (trimmed.Length != 0)
|
||||
prelude.Add(trimmed);
|
||||
}
|
||||
|
||||
private static string FirstToken(string content)
|
||||
{
|
||||
int start = SkipSpaces(content, 0);
|
||||
int i = start;
|
||||
while (i < content.Length && content[i] != ',' && content[i] != ' ' && content[i] != '\t')
|
||||
i++;
|
||||
return content.Substring(start, i - start);
|
||||
}
|
||||
|
||||
private static bool IsColorLiteral(string token)
|
||||
{
|
||||
if (token.Length == 0)
|
||||
return false;
|
||||
if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (token.Length <= 2)
|
||||
return false;
|
||||
for (int k = 2; k < token.Length; k++)
|
||||
if (!IsHexDigit(token[k]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
foreach (char c in token)
|
||||
if (c < '0' || c > '9')
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsIntegerLiteral(string token)
|
||||
{
|
||||
if (token.Length == 0)
|
||||
return false;
|
||||
int start = token[0] == '-' || token[0] == '+' ? 1 : 0;
|
||||
if (start >= token.Length)
|
||||
return false;
|
||||
for (int i = start; i < token.Length; i++)
|
||||
if (token[i] < '0' || token[i] > '9')
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool AllDigits(string text, int start)
|
||||
{
|
||||
for (int i = start; i < text.Length; i++)
|
||||
if (text[i] < '0' || text[i] > '9')
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static int SkipSpaces(string text, int index)
|
||||
{
|
||||
while (index < text.Length && (text[index] == ' ' || text[index] == '\t'))
|
||||
index++;
|
||||
return index;
|
||||
}
|
||||
|
||||
private static bool IsNameChar(char c) =>
|
||||
(c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
|
||||
|
||||
private static bool IsHexDigit(char c) =>
|
||||
(c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,11 @@ namespace LuaScript.Engine
|
||||
private int _height;
|
||||
private bool _alive;
|
||||
|
||||
private readonly byte[] _callbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||
private readonly byte[] _lastCallbackTag = new byte[NativeProtocol.CallbackTagMax];
|
||||
private int _lastCallbackTagLength = -1;
|
||||
private string _lastCallbackTagText = string.Empty;
|
||||
|
||||
public LuaJitWorker(string nativeDir)
|
||||
{
|
||||
_nativeDir = nativeDir;
|
||||
@@ -41,6 +46,7 @@ namespace LuaScript.Engine
|
||||
int width,
|
||||
int height,
|
||||
int timeoutMs,
|
||||
Func<string, int, SceneObjectInfo?> resolveObject,
|
||||
out bool pixelsDirty,
|
||||
out string? error)
|
||||
{
|
||||
@@ -70,14 +76,26 @@ namespace LuaScript.Engine
|
||||
|
||||
_workEvent!.Set();
|
||||
|
||||
if (!_doneEvent!.WaitOne(timeoutMs))
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
int status;
|
||||
while (true)
|
||||
{
|
||||
KillWorker();
|
||||
error = "native script execution timed out";
|
||||
return false;
|
||||
long remaining = timeoutMs - stopwatch.ElapsedMilliseconds;
|
||||
if (remaining <= 0 || !_doneEvent!.WaitOne((int)remaining))
|
||||
{
|
||||
KillWorker();
|
||||
error = "native script execution timed out";
|
||||
return false;
|
||||
}
|
||||
|
||||
status = view.ReadInt32(NativeProtocol.OffStatus);
|
||||
if (status != NativeProtocol.StatusCallback)
|
||||
break;
|
||||
|
||||
ResolveCallback(view, resolveObject);
|
||||
_workEvent.Set();
|
||||
}
|
||||
|
||||
int status = view.ReadInt32(NativeProtocol.OffStatus);
|
||||
if (status == NativeProtocol.StatusError)
|
||||
{
|
||||
int len = view.ReadInt32(NativeProtocol.OffErrorLen);
|
||||
@@ -97,6 +115,48 @@ namespace LuaScript.Engine
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ResolveCallback(MemoryMappedViewAccessor view, Func<string, int, SceneObjectInfo?> resolveObject)
|
||||
{
|
||||
int frame = view.ReadInt32(NativeProtocol.OffCallbackFrame);
|
||||
int tagLen = Math.Clamp(view.ReadInt32(NativeProtocol.OffCallbackTagLen), 0, NativeProtocol.CallbackTagMax);
|
||||
view.ReadArray(NativeProtocol.CallbackTagOffset, _callbackTag, 0, tagLen);
|
||||
string tag = ResolveTag(tagLen);
|
||||
|
||||
SceneObjectInfo? info;
|
||||
try { info = resolveObject(tag, frame); }
|
||||
catch { info = null; }
|
||||
|
||||
if (info is { } value)
|
||||
{
|
||||
long result = NativeProtocol.CallbackResultOffset;
|
||||
view.Write(result + NativeProtocol.CbExist * 8, value.Exist ? 1d : 0d);
|
||||
view.Write(result + NativeProtocol.CbX * 8, value.X);
|
||||
view.Write(result + NativeProtocol.CbY * 8, value.Y);
|
||||
view.Write(result + NativeProtocol.CbZ * 8, value.Z);
|
||||
view.Write(result + NativeProtocol.CbZoom * 8, value.Zoom);
|
||||
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(NativeProtocol.OffCallbackFound, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
view.Write(NativeProtocol.OffCallbackFound, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private string ResolveTag(int tagLen)
|
||||
{
|
||||
if (tagLen == _lastCallbackTagLength &&
|
||||
_callbackTag.AsSpan(0, tagLen).SequenceEqual(_lastCallbackTag.AsSpan(0, tagLen)))
|
||||
return _lastCallbackTagText;
|
||||
|
||||
_lastCallbackTagText = Encoding.UTF8.GetString(_callbackTag, 0, tagLen);
|
||||
_callbackTag.AsSpan(0, tagLen).CopyTo(_lastCallbackTag);
|
||||
_lastCallbackTagLength = tagLen;
|
||||
return _lastCallbackTagText;
|
||||
}
|
||||
|
||||
private void EnsureWorker(int width, int height)
|
||||
{
|
||||
if (_alive && _process is { HasExited: false } && _width == width && _height == height)
|
||||
@@ -139,6 +199,8 @@ namespace LuaScript.Engine
|
||||
psi.ArgumentList.Add(_shimScript);
|
||||
|
||||
_process = Process.Start(psi);
|
||||
if (_process is not null)
|
||||
ProcessJobObject.Assign(_process.Handle);
|
||||
_alive = _process is not null;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ namespace LuaScript.Engine
|
||||
public const int StatusIdle = 0;
|
||||
public const int StatusOk = 1;
|
||||
public const int StatusError = 2;
|
||||
public const int StatusCallback = 3;
|
||||
|
||||
public const int OffMagic = 0;
|
||||
public const int OffCommand = 4;
|
||||
@@ -19,6 +20,9 @@ namespace LuaScript.Engine
|
||||
public const int OffScriptLen = 20;
|
||||
public const int OffPixelsDirty = 24;
|
||||
public const int OffErrorLen = 28;
|
||||
public const int OffCallbackFrame = 32;
|
||||
public const int OffCallbackTagLen = 36;
|
||||
public const int OffCallbackFound = 40;
|
||||
|
||||
public const int HeaderSize = 64;
|
||||
|
||||
@@ -31,7 +35,21 @@ namespace LuaScript.Engine
|
||||
public const int ErrorOffset = ScriptOffset + ScriptMax;
|
||||
public const int ErrorMax = 4 * 1024;
|
||||
|
||||
public const int PixelOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagOffset = ErrorOffset + ErrorMax;
|
||||
public const int CallbackTagMax = 256;
|
||||
public const int CallbackResultOffset = CallbackTagOffset + CallbackTagMax;
|
||||
public const int CallbackResultCount = 8;
|
||||
|
||||
public const int CbExist = 0;
|
||||
public const int CbX = 1;
|
||||
public const int CbY = 2;
|
||||
public const int CbZ = 3;
|
||||
public const int CbZoom = 4;
|
||||
public const int CbRz = 5;
|
||||
public const int CbAlpha = 6;
|
||||
public const int CbLayer = 7;
|
||||
|
||||
public const int PixelOffset = CallbackResultOffset + CallbackResultCount * 8;
|
||||
|
||||
public const int W = 0;
|
||||
public const int H = 1;
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace LuaScript.Engine
|
||||
{
|
||||
internal static class ProcessJobObject
|
||||
{
|
||||
private const uint JobObjectExtendedLimitInformation = 9;
|
||||
private const uint JobObjectLimitKillOnJobClose = 0x2000;
|
||||
|
||||
private static readonly nint Handle = Create();
|
||||
|
||||
public static void Assign(nint processHandle)
|
||||
{
|
||||
if (Handle != nint.Zero && processHandle != nint.Zero)
|
||||
AssignProcessToJobObject(Handle, processHandle);
|
||||
}
|
||||
|
||||
private static nint Create()
|
||||
{
|
||||
nint job = CreateJobObject(nint.Zero, null);
|
||||
if (job == nint.Zero)
|
||||
return nint.Zero;
|
||||
|
||||
var information = new JobObjectExtendedLimitInformationData
|
||||
{
|
||||
BasicLimitInformation = new JobObjectBasicLimitInformationData
|
||||
{
|
||||
LimitFlags = JobObjectLimitKillOnJobClose
|
||||
}
|
||||
};
|
||||
|
||||
int length = Marshal.SizeOf<JobObjectExtendedLimitInformationData>();
|
||||
nint buffer = Marshal.AllocHGlobal(length);
|
||||
try
|
||||
{
|
||||
Marshal.StructureToPtr(information, buffer, false);
|
||||
if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, buffer, (uint)length))
|
||||
{
|
||||
CloseHandle(job);
|
||||
return nint.Zero;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeHGlobal(buffer);
|
||||
}
|
||||
|
||||
return job;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct JobObjectBasicLimitInformationData
|
||||
{
|
||||
public long PerProcessUserTimeLimit;
|
||||
public long PerJobUserTimeLimit;
|
||||
public uint LimitFlags;
|
||||
public nuint MinimumWorkingSetSize;
|
||||
public nuint MaximumWorkingSetSize;
|
||||
public uint ActiveProcessLimit;
|
||||
public nuint Affinity;
|
||||
public uint PriorityClass;
|
||||
public uint SchedulingClass;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct IoCountersData
|
||||
{
|
||||
public ulong ReadOperationCount;
|
||||
public ulong WriteOperationCount;
|
||||
public ulong OtherOperationCount;
|
||||
public ulong ReadTransferCount;
|
||||
public ulong WriteTransferCount;
|
||||
public ulong OtherTransferCount;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct JobObjectExtendedLimitInformationData
|
||||
{
|
||||
public JobObjectBasicLimitInformationData BasicLimitInformation;
|
||||
public IoCountersData IoInfo;
|
||||
public nuint ProcessMemoryLimit;
|
||||
public nuint JobMemoryLimit;
|
||||
public nuint PeakProcessMemoryUsed;
|
||||
public nuint PeakJobMemoryUsed;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern nint CreateJobObject(nint lpJobAttributes, string? lpName);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool SetInformationJobObject(nint hJob, uint jobObjectInformationClass, nint lpJobObjectInformation, uint cbJobObjectInformationLength);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool AssignProcessToJobObject(nint hJob, nint hProcess);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool CloseHandle(nint hObject);
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ namespace LuaScript
|
||||
"obj.time", "obj.totaltime", "obj.t", "obj.frame", "obj.totalframe",
|
||||
"obj.framerate", "obj.layer", "obj.index", "obj.num",
|
||||
"obj.getpixel", "obj.setpixel",
|
||||
"obj.getpixeldata"
|
||||
"obj.getpixeldata", "obj.rand"
|
||||
]),
|
||||
("math", [
|
||||
"math.abs", "math.ceil", "math.cos", "math.exp", "math.floor",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<TargetFramework>net10.0-windows10.0.19041.0</TargetFramework>
|
||||
<UseWPF>true</UseWPF>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Version>1.3.0</Version>
|
||||
<Version>1.4.0</Version>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
|
||||
@@ -4,10 +4,13 @@ using YukkuriMovieMaker.Commons;
|
||||
using YukkuriMovieMaker.Controls;
|
||||
using YukkuriMovieMaker.Exo;
|
||||
using YukkuriMovieMaker.Player.Video;
|
||||
using YukkuriMovieMaker.Plugin;
|
||||
using YukkuriMovieMaker.Plugin.Effects;
|
||||
|
||||
namespace LuaScript
|
||||
{
|
||||
[PluginDetails(AuthorName = "routersys", ContentId = "nc487743")]
|
||||
|
||||
[VideoEffect(nameof(Texts.LuaScript), [VideoEffectCategories.Filtering], ["lua", "script", "スクリプト", "lua script", "アニメーション効果", "animation"], IsAviUtlSupported = false, ResourceType = typeof(Texts))]
|
||||
internal class LuaScriptEffect : VideoEffectBase, IScriptProvider
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.IO;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using LuaScript.Compat;
|
||||
using LuaScript.Engine;
|
||||
using Vortice;
|
||||
using Vortice.DCommon;
|
||||
@@ -77,6 +78,9 @@ namespace LuaScript
|
||||
private RawRectF _cachedBounds;
|
||||
|
||||
private bool _isFirst = true;
|
||||
private string _sourceScript = string.Empty;
|
||||
private string _runnableScript = string.Empty;
|
||||
private bool _runnableCached;
|
||||
private ID2D1Image? _cachedInput;
|
||||
private RenderKey _cachedKey;
|
||||
private SceneObjectQuery[] _cachedQueries = [];
|
||||
@@ -112,6 +116,17 @@ namespace LuaScript
|
||||
return _lastSceneId;
|
||||
}
|
||||
|
||||
private string GetRunnableScript(string source)
|
||||
{
|
||||
if (_runnableCached && string.Equals(source, _sourceScript, StringComparison.Ordinal))
|
||||
return _runnableScript;
|
||||
|
||||
_runnableScript = AviUtlScript.Transform(source);
|
||||
_sourceScript = source;
|
||||
_runnableCached = true;
|
||||
return _runnableScript;
|
||||
}
|
||||
|
||||
protected override void setInput(ID2D1Image? input)
|
||||
{
|
||||
if (!ReferenceEquals(_cachedInput, input))
|
||||
@@ -179,18 +194,19 @@ namespace LuaScript
|
||||
|
||||
try
|
||||
{
|
||||
bool wantNative = ScriptDirective.ResolveAuto(script) == ScriptEngineKind.Native;
|
||||
string runnable = GetRunnableScript(script);
|
||||
bool wantNative = ScriptDirective.ResolveAuto(runnable) == ScriptEngineKind.Native;
|
||||
bool nativeReady = wantNative && LuaJitWorker.IsAvailable(NativeDirectory);
|
||||
if (wantNative && !nativeReady)
|
||||
WarnNativeUnavailableOnce();
|
||||
|
||||
if (nativeReady)
|
||||
{
|
||||
pixelsModified = ExecuteNative(script, ctx, bounds, imgW, imgH);
|
||||
pixelsModified = ExecuteNative(runnable, ctx, bounds, imgW, imgH);
|
||||
}
|
||||
else
|
||||
{
|
||||
_engine.Execute(script, ctx);
|
||||
_engine.Execute(runnable, ctx);
|
||||
|
||||
if (ctx.IsPixelsDirty)
|
||||
{
|
||||
@@ -365,7 +381,9 @@ namespace LuaScript
|
||||
byte[] buffer = LoadInputPixels(bounds, imgW, imgH);
|
||||
|
||||
bool ok = _nativeWorker.Execute(
|
||||
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds, out bool dirty, out string? error);
|
||||
script, _nativeFields, buffer, imgW, imgH, NativeTimeoutMilliseconds,
|
||||
(tag, frame) => ctx.ResolveObject(tag, frame, out var info) ? info : null,
|
||||
out bool dirty, out string? error);
|
||||
|
||||
if (!ok)
|
||||
{
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using LuaScript.Compat;
|
||||
using MoonSharp.Interpreter;
|
||||
using MoonSharp.Interpreter.Debugging;
|
||||
using MoonSharp.Interpreter.Loaders;
|
||||
@@ -451,6 +452,17 @@ namespace LuaScript
|
||||
});
|
||||
|
||||
obj["putpixeldata"] = DynValue.NewCallback((_, _) => DynValue.Void);
|
||||
|
||||
obj["rand"] = DynValue.NewCallback((_, args) =>
|
||||
{
|
||||
_activeCancellation.ThrowIfCancellationRequested();
|
||||
double frameDefault = _activeContext?.Frame ?? 0d;
|
||||
double a = args.Count > 0 ? args[0].CastToNumber() ?? 0d : 0d;
|
||||
double b = args.Count > 1 ? args[1].CastToNumber() ?? 0d : 0d;
|
||||
double seed = args.Count > 2 ? args[2].CastToNumber() ?? 0d : 0d;
|
||||
double frame = args.Count > 3 ? args[3].CastToNumber() ?? frameDefault : frameDefault;
|
||||
return DynValue.NewNumber(AviUtlRandom.Next(a, b, seed, frame));
|
||||
});
|
||||
}
|
||||
|
||||
private static DynValue BuildObjectTable(Script script, SceneObjectInfo info)
|
||||
|
||||
@@ -301,6 +301,19 @@
|
||||
لكن في هذا المكوِّن الإضافي تنعكس التغييرات عبر setpixel/set تلقائياً،
|
||||
لذا لا داعي لاستدعاء هذه الدالة.
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
تُعيد قيمة عشوائية صحيحة حتمية ضمن النطاق st ~ ed.
|
||||
* مع نفس seed و frame، تُعيد دائماً القيمة نفسها.
|
||||
* عند حذف seed يُعتبر 0، وعند حذف frame يُستخدم الإطار الحالي (obj.frame).
|
||||
* تُعيد القيمة نفسها على محرك MoonSharp وعلى زمن التشغيل LuaJIT.
|
||||
إذا لزمت قيمة عشوائية عشرية مستقلة عن المحرك، فاستخدم anim.rand.
|
||||
st : الحد الأدنى للنطاق (يُقتطع إلى عدد صحيح)
|
||||
ed : الحد الأعلى للنطاق (يُقتطع إلى عدد صحيح)
|
||||
seed : بذرة العشوائية (اختياري، الافتراضي 0)
|
||||
frame : الإطار المستخدم للتغيير (اختياري، الافتراضي obj.frame)
|
||||
النتيجة : عدد صحيح ضمن st ~ ed
|
||||
مثال: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -441,10 +454,49 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- التوافق الجزئي مع نصوص AviUtl -
|
||||
|
||||
تتيح طبقة توافق تشغيل الأجزاء الخاصة بالتحويل والشفافية والأرقام العشوائية من
|
||||
نصوص تأثير الحركة في AviUtl (عائلة *.anm) دون إعادة كتابة. عندما لا يحتوي النص
|
||||
على صياغة خاصة بـ AviUtl، لا تتدخل هذه الطبقة على الإطلاق (تبقى سلوكيات النصوص
|
||||
الحالية كما هي تماماً).
|
||||
|
||||
○ توجيهات ترويسة النص
|
||||
تُفسَّر إعلانات المعاملات المكتوبة على هيئة تعليقات، وتُعرَّف المتغيرات التي
|
||||
يشير إليها جسم النص قبل التنفيذ.
|
||||
--dialog:التسمية,local var=الافتراضي;...
|
||||
يوسّع جزء الإعلان لكل عنصر (مثل local var=الافتراضي) إلى بداية الجسم.
|
||||
في AviUtl تُحرَّر هذه القيم في مربع حوار، وهنا تُستخدم القيم الافتراضية.
|
||||
--color:0xRRGGBB
|
||||
يُعرّف المتغير color باللون المحدد.
|
||||
--check0:التسمية,الافتراضي
|
||||
يُعرّف obj.check0 (من 0 إلى 3) بالقيمة الافتراضية.
|
||||
--param:<عبارة Lua>
|
||||
يوسّع عبارة Lua المكتوبة إلى بداية الجسم.
|
||||
--track0: إلى --track3:
|
||||
تُقرأ قيم أشرطة التتبع عبر obj.track0 إلى obj.track3 كما في السابق.
|
||||
لا تنعكس التسمية والنطاق والقيمة الافتراضية في الترويسة على الواجهة.
|
||||
|
||||
○ أقسام متعددة باستخدام @
|
||||
عندما يُعرّف نص واحد عدة تأثيرات باستخدام @الاسم، يُنفَّذ القسم الأول فقط.
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
دالة أرقام عشوائية صحيحة حتمية متوافقة مع AviUtl. انظر "جدول obj - الدوال"
|
||||
للتفاصيل.
|
||||
|
||||
تتطلب الميزات التالية التكامل مع خط أنابيب الرسم، لذا فهي خارج نطاق هذه الطبقة.
|
||||
النصوص التي تستدعيها لن تعمل كما هو متوقع.
|
||||
× تحميل ورسم الصور والأشكال والنصوص والفيديو
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont وما شابه)
|
||||
× تأثيرات المرشّحات وعمليات المخزن المؤقت
|
||||
(obj.effect / obj.copybuffer / obj.setoption وما شابه)
|
||||
× تحميل الوحدات عبر require، والوصول إلى الملفات مثل io
|
||||
|
||||
|
||||
- الميزات غير المدعومة / القيود -
|
||||
|
||||
× obj.effect()، obj.draw()، obj.drawpoly()، obj.load() وما شابه من AviUtl2 غير مدعومة.
|
||||
× obj.rand()، obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
|
||||
× obj.rand1()، obj.setfont()، obj.mes() وما شابه من AviUtl2 غير مدعومة.
|
||||
× obj.setoption()، obj.getoption()، obj.getvalue()، obj.setanchor() وما شابه من AviUtl2 غير مدعومة.
|
||||
× الدوال مثل scene.set() و scene.get() في جدول scene الخاص بـ AviUtl2 غير مدعومة.
|
||||
(يمكن قراءة scene.width و scene.height فقط)
|
||||
@@ -453,5 +505,7 @@
|
||||
لكن دعم الرسم ثلاثي الأبعاد محدود.
|
||||
× إذا تجاوز النص البرمجي مهلة الانتهاء (5 ثوانٍ)، يُنهى التنفيذ قسراً.
|
||||
يجب الانتباه في التطبيق لتجنب الحلقات اللانهائية.
|
||||
× توجيهات الترويسة من AviUtl2 مثل --track@ و --check@ غير مدعومة.
|
||||
يمكن استخدام Track0 ~ Track3 فقط كمعاملات.
|
||||
× توجيهات الترويسة من AviUtl2 مدعومة جزئياً فقط. تُفسَّر القيم الافتراضية لـ
|
||||
--dialog / --color / --check / --param (انظر "التوافق الجزئي مع نصوص AviUtl")،
|
||||
لكن التسمية والنطاق والقيمة الافتراضية لـ --track@ لا تنعكس على الواجهة،
|
||||
وتُستخدم القيم عبر Track0 ~ Track3.
|
||||
@@ -307,6 +307,20 @@
|
||||
but in this plugin changes via setpixel/set are automatically applied,
|
||||
so calling this function is unnecessary.
|
||||
|
||||
o obj.rand(st, ed [, seed [, frame]])
|
||||
Returns a deterministic integer random value within the range st ~ ed.
|
||||
* With the same seed and frame, it always returns the same value.
|
||||
* When seed is omitted it is treated as 0; when frame is omitted the
|
||||
current frame (obj.frame) is used.
|
||||
* Returns the same value on both the MoonSharp engine and the LuaJIT
|
||||
runtime. For an engine-independent floating-point random value, use anim.rand.
|
||||
st : Lower bound of the range (truncated to an integer)
|
||||
ed : Upper bound of the range (truncated to an integer)
|
||||
seed : Random seed (optional, default 0)
|
||||
frame : Frame used for variation (optional, default obj.frame)
|
||||
Returns : An integer within st ~ ed
|
||||
Example: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -447,10 +461,53 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- AviUtl Script Compatibility (Partial) -
|
||||
|
||||
A compatibility layer lets the transform, opacity and random portions of
|
||||
AviUtl animation effect scripts (the *.anm family) run without rewriting.
|
||||
When a script contains no AviUtl-specific notation, this layer does not
|
||||
intervene at all, and existing scripts behave exactly as before.
|
||||
|
||||
o Script header directives
|
||||
Parameter declarations written as comments are interpreted, and the
|
||||
variables that the script body references are defined before execution.
|
||||
--dialog:label,local var=default;...
|
||||
Expands the declaration part of each item
|
||||
(such as local var=default) to the top of the body.
|
||||
In AviUtl these are edited in a dialog; here the default
|
||||
values are used.
|
||||
--color:0xRRGGBB
|
||||
Defines the variable color with the specified color.
|
||||
--check0:label,default
|
||||
Defines obj.check0 (0 to 3) with the default value.
|
||||
--param:<Lua statement>
|
||||
Expands the written Lua statement to the top of the body.
|
||||
--track0: to --track3:
|
||||
Trackbar values are referenced via obj.track0 to obj.track3
|
||||
as before. The label, range and default written in the header
|
||||
are not reflected in the UI.
|
||||
|
||||
o Multiple sections with @
|
||||
When a single script defines multiple effects with @name, only the
|
||||
first section is executed.
|
||||
|
||||
o obj.rand(st, ed [, seed [, frame]])
|
||||
A deterministic integer random function compatible with AviUtl.
|
||||
See "obj Table - Functions" for details.
|
||||
|
||||
The following require integration with the rendering pipeline and are out of
|
||||
scope for this layer. Scripts that call them will not behave as intended.
|
||||
x Loading and drawing of images, figures, text and video
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont, etc.)
|
||||
x Filter effects and buffer operations
|
||||
(obj.effect / obj.copybuffer / obj.setoption, etc.)
|
||||
x Module loading via require, and file access such as io
|
||||
|
||||
|
||||
- Unsupported Features / Limitations -
|
||||
|
||||
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. from AviUtl2 are not supported.
|
||||
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
|
||||
x obj.rand1(), obj.setfont(), obj.mes(), etc. from AviUtl2 are not supported.
|
||||
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. from AviUtl2 are not supported.
|
||||
x Functions such as scene.set() and scene.get() in the AviUtl2 scene table are not supported.
|
||||
(Only scene.width and scene.height can be read)
|
||||
@@ -459,5 +516,7 @@
|
||||
but 3D rendering support is limited.
|
||||
x If the script timeout (5 seconds) is exceeded, execution is forcibly terminated.
|
||||
Care must be taken in implementation to prevent infinite loops.
|
||||
x AviUtl2 header directives such as --track@ and --check@ are not supported.
|
||||
Only Track0 ~ Track3 can be used as parameters.
|
||||
x AviUtl2 header directives are only partially supported. The default values of
|
||||
--dialog / --color / --check / --param are interpreted (see "AviUtl Script
|
||||
Compatibility (Partial)"), but the label, range and default of --track@ are
|
||||
not reflected in the UI; values are used via Track0 ~ Track3.
|
||||
@@ -305,6 +305,20 @@
|
||||
pero en este plugin los cambios mediante setpixel/set se aplican automáticamente,
|
||||
por lo que no es necesario llamar a esta función.
|
||||
|
||||
o obj.rand(st, ed [, seed [, frame]])
|
||||
Devuelve un valor aleatorio entero determinista dentro del rango st ~ ed.
|
||||
* Con el mismo seed y frame, siempre devuelve el mismo valor.
|
||||
* Si se omite seed se trata como 0; si se omite frame se usa el
|
||||
fotograma actual (obj.frame).
|
||||
* Devuelve el mismo valor en el motor MoonSharp y en el runtime LuaJIT.
|
||||
Para un valor aleatorio decimal independiente del motor, use anim.rand.
|
||||
st : Límite inferior del rango (truncado a entero)
|
||||
ed : Límite superior del rango (truncado a entero)
|
||||
seed : Semilla aleatoria (opcional, predeterminado 0)
|
||||
frame : Fotograma usado para la variación (opcional, predeterminado obj.frame)
|
||||
Devuelve: Un entero dentro de st ~ ed
|
||||
Ejemplo: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -445,10 +459,56 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- Compatibilidad parcial con scripts de AviUtl -
|
||||
|
||||
Una capa de compatibilidad permite ejecutar, sin reescritura, las partes de
|
||||
los scripts de efecto de animación de AviUtl (la familia *.anm) relativas a
|
||||
transformación, opacidad y números aleatorios. Cuando un script no contiene
|
||||
notación específica de AviUtl, esta capa no interviene en absoluto (los
|
||||
scripts existentes se comportan exactamente igual que antes).
|
||||
|
||||
o Directivas de encabezado del script
|
||||
Las declaraciones de parámetros escritas como comentarios se
|
||||
interpretan, y las variables que el cuerpo del script referencia se
|
||||
definen antes de la ejecución.
|
||||
--dialog:etiqueta,local var=predeterminado;...
|
||||
Expande la parte de declaración de cada elemento
|
||||
(como local var=predeterminado) al inicio del cuerpo.
|
||||
En AviUtl se editan en un cuadro de diálogo; aquí se usan
|
||||
los valores predeterminados.
|
||||
--color:0xRRGGBB
|
||||
Define la variable color con el color especificado.
|
||||
--check0:etiqueta,predeterminado
|
||||
Define obj.check0 (0 a 3) con el valor predeterminado.
|
||||
--param:<sentencia Lua>
|
||||
Expande la sentencia Lua escrita al inicio del cuerpo.
|
||||
--track0: a --track3:
|
||||
Los valores de las barras de seguimiento se referencian
|
||||
mediante obj.track0 a obj.track3 como antes. La etiqueta, el
|
||||
rango y el valor predeterminado del encabezado no se reflejan en la UI.
|
||||
|
||||
o Múltiples secciones con @
|
||||
Cuando un único script define varios efectos con @nombre, solo se
|
||||
ejecuta la primera sección.
|
||||
|
||||
o obj.rand(st, ed [, seed [, frame]])
|
||||
Función de número aleatorio entero determinista compatible con AviUtl.
|
||||
Consulte "Tabla obj - Funciones" para más detalles.
|
||||
|
||||
Lo siguiente requiere integración con la canalización de renderizado y, por
|
||||
tanto, queda fuera del alcance de esta capa. Los scripts que lo llamen no se
|
||||
comportarán como se espera.
|
||||
x Carga y dibujo de imágenes, figuras, texto y vídeo
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont, etc.)
|
||||
x Efectos de filtro y operaciones de búfer
|
||||
(obj.effect / obj.copybuffer / obj.setoption, etc.)
|
||||
x Carga de módulos mediante require y acceso a archivos como io
|
||||
|
||||
|
||||
- Funciones no admitidas / Limitaciones -
|
||||
|
||||
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), etc. de AviUtl2 no son compatibles.
|
||||
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
|
||||
x obj.rand1(), obj.setfont(), obj.mes(), etc. de AviUtl2 no son compatibles.
|
||||
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), etc. de AviUtl2 no son compatibles.
|
||||
x Las funciones como scene.set() y scene.get() de la tabla scene de AviUtl2 no son compatibles.
|
||||
(Solo se pueden leer scene.width y scene.height)
|
||||
@@ -457,5 +517,7 @@
|
||||
pero el soporte de renderizado 3D es limitado.
|
||||
x Si se supera el tiempo de espera del script (5 segundos), la ejecución se termina forzosamente.
|
||||
Se debe tener cuidado en la implementación para evitar bucles infinitos.
|
||||
x Las directivas de encabezado de AviUtl2 como --track@ y --check@ no son compatibles.
|
||||
Solo Track0 ~ Track3 pueden usarse como parámetros.
|
||||
x Las directivas de encabezado de AviUtl2 solo son compatibles parcialmente. Los valores
|
||||
predeterminados de --dialog / --color / --check / --param se interpretan (consulte
|
||||
"Compatibilidad parcial con scripts de AviUtl"), pero la etiqueta, el rango y el valor
|
||||
predeterminado de --track@ no se reflejan en la UI; los valores se usan vía Track0 ~ Track3.
|
||||
@@ -303,6 +303,20 @@
|
||||
tetapi dalam plugin ini perubahan melalui setpixel/set diterapkan secara otomatis,
|
||||
sehingga tidak perlu memanggil fungsi ini.
|
||||
|
||||
o obj.rand(st, ed [, seed [, frame]])
|
||||
Mengembalikan nilai acak bilangan bulat deterministik dalam rentang st ~ ed.
|
||||
* Dengan seed dan frame yang sama, selalu mengembalikan nilai yang sama.
|
||||
* Jika seed dihilangkan dianggap 0; jika frame dihilangkan digunakan
|
||||
frame saat ini (obj.frame).
|
||||
* Mengembalikan nilai yang sama pada mesin MoonSharp maupun runtime LuaJIT.
|
||||
Untuk nilai acak desimal yang independen dari mesin, gunakan anim.rand.
|
||||
st : Batas bawah rentang (dipotong menjadi bilangan bulat)
|
||||
ed : Batas atas rentang (dipotong menjadi bilangan bulat)
|
||||
seed : Seed acak (opsional, default 0)
|
||||
frame : Frame yang digunakan untuk variasi (opsional, default obj.frame)
|
||||
Hasil : Bilangan bulat dalam st ~ ed
|
||||
Contoh: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 Table -
|
||||
@@ -443,10 +457,55 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- Kompatibilitas Parsial Skrip AviUtl -
|
||||
|
||||
Lapisan kompatibilitas memungkinkan bagian transformasi, opasitas, dan
|
||||
bilangan acak dari skrip efek animasi AviUtl (keluarga *.anm) dijalankan
|
||||
tanpa penulisan ulang. Ketika sebuah skrip tidak mengandung notasi khusus
|
||||
AviUtl, lapisan ini tidak ikut campur sama sekali (skrip yang ada berperilaku
|
||||
persis seperti sebelumnya).
|
||||
|
||||
o Direktif header skrip
|
||||
Deklarasi parameter yang ditulis sebagai komentar diinterpretasikan,
|
||||
dan variabel yang dirujuk oleh badan skrip didefinisikan sebelum eksekusi.
|
||||
--dialog:label,local var=default;...
|
||||
Memperluas bagian deklarasi setiap item
|
||||
(seperti local var=default) ke awal badan skrip.
|
||||
Di AviUtl nilai ini diedit dalam dialog; di sini digunakan
|
||||
nilai default.
|
||||
--color:0xRRGGBB
|
||||
Mendefinisikan variabel color dengan warna yang ditentukan.
|
||||
--check0:label,default
|
||||
Mendefinisikan obj.check0 (0 sampai 3) dengan nilai default.
|
||||
--param:<pernyataan Lua>
|
||||
Memperluas pernyataan Lua yang ditulis ke awal badan skrip.
|
||||
--track0: sampai --track3:
|
||||
Nilai trackbar dirujuk melalui obj.track0 sampai obj.track3
|
||||
seperti sebelumnya. Label, rentang, dan default pada header
|
||||
tidak tercermin di UI.
|
||||
|
||||
o Beberapa bagian dengan @
|
||||
Ketika satu skrip mendefinisikan beberapa efek dengan @nama, hanya
|
||||
bagian pertama yang dijalankan.
|
||||
|
||||
o obj.rand(st, ed [, seed [, frame]])
|
||||
Fungsi bilangan acak bulat deterministik yang kompatibel dengan AviUtl.
|
||||
Lihat "Tabel obj - Fungsi" untuk detailnya.
|
||||
|
||||
Berikut ini memerlukan integrasi dengan pipeline render sehingga berada di
|
||||
luar cakupan lapisan ini. Skrip yang memanggilnya tidak akan berperilaku
|
||||
seperti yang diharapkan.
|
||||
x Pemuatan dan penggambaran gambar, figur, teks, dan video
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont, dll.)
|
||||
x Efek filter dan operasi buffer
|
||||
(obj.effect / obj.copybuffer / obj.setoption, dll.)
|
||||
x Pemuatan modul melalui require, dan akses file seperti io
|
||||
|
||||
|
||||
- Fitur yang Tidak Didukung / Batasan -
|
||||
|
||||
x obj.effect(), obj.draw(), obj.drawpoly(), obj.load(), dll. dari AviUtl2 tidak didukung.
|
||||
x obj.rand(), obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
|
||||
x obj.rand1(), obj.setfont(), obj.mes(), dll. dari AviUtl2 tidak didukung.
|
||||
x obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor(), dll. dari AviUtl2 tidak didukung.
|
||||
x Fungsi seperti scene.set() dan scene.get() dalam tabel scene AviUtl2 tidak didukung.
|
||||
(Hanya scene.width dan scene.height yang dapat dibaca)
|
||||
@@ -455,5 +514,7 @@
|
||||
tetapi dukungan render 3D terbatas.
|
||||
x Jika batas waktu skrip (5 detik) terlampaui, eksekusi dihentikan paksa.
|
||||
Perhatian harus diberikan dalam implementasi untuk mencegah loop tak terbatas.
|
||||
x Direktif header AviUtl2 seperti --track@ dan --check@ tidak didukung.
|
||||
Hanya Track0 ~ Track3 yang dapat digunakan sebagai parameter.
|
||||
x Direktif header AviUtl2 hanya didukung sebagian. Nilai default dari
|
||||
--dialog / --color / --check / --param diinterpretasikan (lihat "Kompatibilitas
|
||||
Parsial Skrip AviUtl"), tetapi label, rentang, dan default dari --track@ tidak
|
||||
tercermin di UI; nilai digunakan melalui Track0 ~ Track3.
|
||||
@@ -303,6 +303,19 @@
|
||||
このプラグインでは setpixel/set による変更が自動的に反映されるため、
|
||||
本関数を呼び出す必要はありません。
|
||||
|
||||
○obj.rand(st, ed [, seed [, frame]])
|
||||
指定範囲 st ~ ed の整数を返す決定論的な乱数です。
|
||||
※ seed と frame が同じであれば常に同じ値を返します。
|
||||
※ seed 省略時は 0、frame 省略時は現在のフレーム(obj.frame)を使用します。
|
||||
※ 従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||
エンジンに依存しない小数の乱数が必要な場合は anim.rand を使用してください。
|
||||
st : 範囲の下限 (小数は切り捨てて整数化)
|
||||
ed : 範囲の上限 (小数は切り捨てて整数化)
|
||||
seed : 乱数シード (省略可, デフォルト 0)
|
||||
frame : 変化に用いるフレーム (省略可, デフォルト obj.frame)
|
||||
戻り値 : st ~ ed の整数
|
||||
例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 テーブル -
|
||||
@@ -443,10 +456,51 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- AviUtl スクリプトの部分互換 -
|
||||
|
||||
AviUtl のアニメーション効果スクリプト(*.anm 系)のうち、座標・拡縮・回転・
|
||||
不透明度の変形と乱数を用いる範囲を、追加の記述変更なしで実行できる互換層です。
|
||||
スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません
|
||||
(従来のスクリプトの挙動は変わりません)。
|
||||
|
||||
○スクリプトヘッダの解釈
|
||||
コメント形式のパラメータ宣言を解釈し、スクリプト本体が参照する変数を
|
||||
実行前に定義します。
|
||||
--dialog:項目名,local 変数=既定値;…
|
||||
各項目の宣言部(local 変数=既定値 など)を本体の先頭へ展開します。
|
||||
AviUtl では対話ダイアログで編集する値ですが、ここでは既定値で
|
||||
動作します。
|
||||
--color:0xRRGGBB
|
||||
変数 color を指定色で定義します。
|
||||
--check0:項目名,既定値
|
||||
obj.check0 (0~3) を既定値で定義します。
|
||||
--param:任意のLua文
|
||||
記述した Lua 文をそのまま本体の先頭へ展開します。
|
||||
--track0: ~ --track3:
|
||||
トラックバーの値は従来どおり obj.track0 ~ obj.track3 から
|
||||
参照します。ヘッダーのラベル・範囲・既定値は UI へ反映しません。
|
||||
|
||||
○@ による複数セクション
|
||||
1 つのスクリプトに @名前 で複数の効果が定義されている場合、先頭の
|
||||
セクションのみを実行します。
|
||||
|
||||
○obj.rand(st, ed [, seed [, frame]])
|
||||
AviUtl 互換の決定論的な整数乱数です。詳細は「obj テーブル - 関数」を
|
||||
参照してください。
|
||||
|
||||
次の機能は本体の描画パイプラインへの統合を要するため、この互換層では対象外です。
|
||||
これらを呼び出すスクリプトは意図どおりには動作しません。
|
||||
×画像・図形・テキスト・動画の読み込みと描画
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont など)
|
||||
×フィルタ効果やバッファ操作
|
||||
(obj.effect / obj.copybuffer / obj.setoption など)
|
||||
×require によるモジュール読み込み、io などのファイルアクセス
|
||||
|
||||
|
||||
- 非対応・制限事項 -
|
||||
|
||||
×AviUtl2 の obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 等には対応していません。
|
||||
×AviUtl2 の obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
|
||||
×AviUtl2 の obj.rand1(), obj.setfont(), obj.mes() 等には対応していません。
|
||||
×AviUtl2 の obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 等には対応していません。
|
||||
×AviUtl2 の scene テーブルの scene.set(), scene.get() 等の関数には対応していません。
|
||||
(scene.width と scene.height の読み取りのみ対応)
|
||||
@@ -455,5 +509,7 @@
|
||||
3D 描画のサポートは限定的です。
|
||||
×スクリプトのタイムアウト(5秒)を超えた場合、実行は強制終了されます。
|
||||
無限ループが発生しないよう実装上の注意が必要です。
|
||||
×AviUtl2 の --track@, --check@ 等のヘッダーディレクティブには対応していません。
|
||||
パラメータは Track0 ~ Track3 のみ使用できます。
|
||||
×AviUtl2 のヘッダーディレクティブは部分的にのみ対応します。
|
||||
--dialog / --color / --check / --param の既定値は解釈されますが
|
||||
(「AviUtl スクリプトの部分互換」を参照)、--track@ のラベル・範囲・
|
||||
既定値は UI へ反映されず、値は Track0 ~ Track3 を使用します。
|
||||
@@ -299,6 +299,19 @@
|
||||
이 플러그인에서는 setpixel/set에 의한 변경이 자동으로 반영되므로,
|
||||
이 함수를 호출할 필요가 없습니다.
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
지정 범위 st ~ ed의 정수를 반환하는 결정론적 난수입니다.
|
||||
※ seed와 frame이 같으면 항상 같은 값을 반환합니다.
|
||||
※ seed 생략 시 0으로, frame 생략 시 현재 프레임(obj.frame)을 사용합니다.
|
||||
※ 기존 엔진(MoonSharp)과 고속 런타임(LuaJIT)에서 같은 값을 반환합니다.
|
||||
엔진에 의존하지 않는 소수 난수가 필요하면 anim.rand를 사용하세요.
|
||||
st : 범위 하한 (소수는 버림하여 정수화)
|
||||
ed : 범위 상한 (소수는 버림하여 정수화)
|
||||
seed : 난수 시드 (생략 가능, 기본값 0)
|
||||
frame : 변화에 사용하는 프레임 (생략 가능, 기본값 obj.frame)
|
||||
반환값 : st ~ ed의 정수
|
||||
예: obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 테이블 -
|
||||
@@ -439,10 +452,51 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- AviUtl 스크립트 부분 호환 -
|
||||
|
||||
AviUtl 애니메이션 효과 스크립트(*.anm 계열) 중 좌표·확대축소·회전·
|
||||
불투명도의 변형과 난수를 사용하는 범위를, 추가 수정 없이 실행할 수 있는
|
||||
호환 계층입니다. 스크립트에 AviUtl 고유 표기가 포함되지 않은 경우 이
|
||||
호환 계층은 전혀 개입하지 않습니다(기존 스크립트의 동작은 변하지 않습니다).
|
||||
|
||||
○ 스크립트 헤더 디렉티브 해석
|
||||
주석 형식의 파라미터 선언을 해석하여, 스크립트 본문이 참조하는
|
||||
변수를 실행 전에 정의합니다.
|
||||
--dialog:항목명,local 변수=기본값;…
|
||||
각 항목의 선언부(local 변수=기본값 등)를 본문 앞에 펼칩니다.
|
||||
AviUtl에서는 대화 상자에서 편집하는 값이지만, 여기서는
|
||||
기본값으로 동작합니다.
|
||||
--color:0xRRGGBB
|
||||
변수 color를 지정한 색으로 정의합니다.
|
||||
--check0:항목명,기본값
|
||||
obj.check0 (0~3)을 기본값으로 정의합니다.
|
||||
--param:임의의 Lua 문
|
||||
작성한 Lua 문을 그대로 본문 앞에 펼칩니다.
|
||||
--track0: ~ --track3:
|
||||
트랙바 값은 기존과 같이 obj.track0 ~ obj.track3에서
|
||||
참조합니다. 헤더의 라벨·범위·기본값은 UI에 반영되지 않습니다.
|
||||
|
||||
○ @를 통한 복수 섹션
|
||||
하나의 스크립트에 @이름으로 여러 효과가 정의된 경우, 첫 번째
|
||||
섹션만 실행합니다.
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
AviUtl 호환의 결정론적 정수 난수입니다. 자세한 내용은
|
||||
"obj 테이블 - 함수"를 참조하세요.
|
||||
|
||||
다음 기능은 본체의 렌더링 파이프라인과의 통합이 필요하므로 이 호환
|
||||
계층의 범위 밖입니다. 이를 호출하는 스크립트는 의도대로 동작하지 않습니다.
|
||||
× 이미지·도형·텍스트·동영상의 로드 및 그리기
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont 등)
|
||||
× 필터 효과 및 버퍼 조작
|
||||
(obj.effect / obj.copybuffer / obj.setoption 등)
|
||||
× require에 의한 모듈 로드 및 io 등의 파일 접근
|
||||
|
||||
|
||||
- 미지원·제한 사항 -
|
||||
|
||||
× AviUtl2의 obj.effect(), obj.draw(), obj.drawpoly(), obj.load() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 obj.rand(), obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 obj.rand1(), obj.setfont(), obj.mes() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 obj.setoption(), obj.getoption(), obj.getvalue(), obj.setanchor() 등은 지원하지 않습니다.
|
||||
× AviUtl2의 scene 테이블의 scene.set(), scene.get() 등의 함수는 지원하지 않습니다.
|
||||
(scene.width와 scene.height의 읽기만 지원)
|
||||
@@ -451,5 +505,6 @@
|
||||
3D 렌더링 지원은 제한적입니다.
|
||||
× 스크립트 타임아웃(5초)을 초과하면 실행이 강제 종료됩니다.
|
||||
무한 루프가 발생하지 않도록 구현 시 주의가 필요합니다.
|
||||
× AviUtl2의 --track@, --check@ 등의 헤더 디렉티브는 지원하지 않습니다.
|
||||
파라미터는 Track0 ~ Track3만 사용할 수 있습니다.
|
||||
× AviUtl2의 헤더 디렉티브는 부분적으로만 지원합니다. --dialog / --color /
|
||||
--check / --param의 기본값은 해석되지만("AviUtl 스크립트 부분 호환" 참조),
|
||||
--track@의 라벨·범위·기본값은 UI에 반영되지 않으며 값은 Track0 ~ Track3을 사용합니다.
|
||||
@@ -297,6 +297,19 @@
|
||||
但本插件中 setpixel/set 的修改会自动反映,
|
||||
因此无需调用此函数。
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
返回指定范围 st ~ ed 内整数的确定性随机数。
|
||||
* seed 与 frame 相同时始终返回相同的值。
|
||||
* 省略 seed 时按 0 处理,省略 frame 时使用当前帧 (obj.frame)。
|
||||
* 在传统引擎 (MoonSharp) 与高速运行时 (LuaJIT) 上返回相同的值。
|
||||
若需要不依赖引擎的小数随机数,请使用 anim.rand。
|
||||
st : 范围下限(小数向下取整为整数)
|
||||
ed : 范围上限(小数向下取整为整数)
|
||||
seed : 随机种子(可省略,默认 0)
|
||||
frame : 用于变化的帧(可省略,默认 obj.frame)
|
||||
返回值 : st ~ ed 的整数
|
||||
示例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 表 -
|
||||
@@ -437,10 +450,46 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- AviUtl 脚本的部分兼容 -
|
||||
|
||||
提供兼容层,使 AviUtl 动画效果脚本(*.anm 系列)中涉及坐标、缩放、旋转、
|
||||
不透明度的变形以及随机数的部分,无需额外修改即可运行。当脚本中不包含
|
||||
AviUtl 专有写法时,此兼容层完全不介入(传统脚本的行为不变)。
|
||||
|
||||
○ 脚本头部指令的解释
|
||||
解释注释形式的参数声明,在执行前定义脚本主体所引用的变量。
|
||||
--dialog:项目名,local 变量=默认值;…
|
||||
将各项目的声明部分(如 local 变量=默认值)展开到主体开头。
|
||||
在 AviUtl 中这些是通过对话框编辑的值,此处以默认值运行。
|
||||
--color:0xRRGGBB
|
||||
以指定颜色定义变量 color。
|
||||
--check0:项目名,默认值
|
||||
以默认值定义 obj.check0 (0~3)。
|
||||
--param:任意 Lua 语句
|
||||
将所写的 Lua 语句原样展开到主体开头。
|
||||
--track0: ~ --track3:
|
||||
轨道条的值仍通过 obj.track0 ~ obj.track3 引用。头部的标签、
|
||||
范围与默认值不会反映到 UI。
|
||||
|
||||
○ 通过 @ 的多区段
|
||||
当一个脚本以 @名称 定义了多个效果时,仅执行第一个区段。
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
与 AviUtl 兼容的确定性整数随机数。详情请参阅“obj 表 - 函数”。
|
||||
|
||||
以下功能需要与本体的绘制管线集成,因此不在此兼容层的范围内。
|
||||
调用它们的脚本不会按预期运行。
|
||||
× 图像、图形、文本、视频的加载与绘制
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont 等)
|
||||
× 滤镜效果与缓冲区操作
|
||||
(obj.effect / obj.copybuffer / obj.setoption 等)
|
||||
× 通过 require 加载模块,以及 io 等文件访问
|
||||
|
||||
|
||||
- 不支持项目·限制事项 -
|
||||
|
||||
× 不支持 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
|
||||
× 不支持 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
|
||||
× 不支持 AviUtl2 的 obj.rand1()、obj.setfont()、obj.mes() 等。
|
||||
× 不支持 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
|
||||
× 不支持 AviUtl2 scene 表中的 scene.set()、scene.get() 等函数。
|
||||
(仅支持读取 scene.width 和 scene.height)
|
||||
@@ -449,5 +498,6 @@
|
||||
但 3D 绘制支持有限。
|
||||
× 超过脚本超时时间(5 秒)时,执行将被强制终止。
|
||||
实现时需注意避免出现无限循环。
|
||||
× 不支持 AviUtl2 的 --track@、--check@ 等头部指令。
|
||||
参数仅可使用 Track0 ~ Track3。
|
||||
× AviUtl2 的头部指令仅部分支持。--dialog / --color / --check / --param 的
|
||||
默认值会被解释(参阅“AviUtl 脚本的部分兼容”),但 --track@ 的标签、范围
|
||||
与默认值不会反映到 UI,值通过 Track0 ~ Track3 使用。
|
||||
@@ -297,6 +297,19 @@
|
||||
但本外掛中 setpixel/set 的修改會自動反映,
|
||||
因此無需呼叫此函式。
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
回傳指定範圍 st ~ ed 內整數的確定性亂數。
|
||||
* seed 與 frame 相同時始終回傳相同的值。
|
||||
* 省略 seed 時以 0 處理,省略 frame 時使用目前影格 (obj.frame)。
|
||||
* 在傳統引擎 (MoonSharp) 與高速執行階段 (LuaJIT) 上回傳相同的值。
|
||||
若需要不依賴引擎的小數亂數,請使用 anim.rand。
|
||||
st : 範圍下限(小數無條件捨去為整數)
|
||||
ed : 範圍上限(小數無條件捨去為整數)
|
||||
seed : 亂數種子(可省略,預設 0)
|
||||
frame : 用於變化的影格(可省略,預設 obj.frame)
|
||||
回傳值 : st ~ ed 的整數
|
||||
範例:obj.ox = obj.ox + obj.rand(-10, 10, 1, obj.frame)
|
||||
|
||||
|
||||
|
||||
- ymm4 表 -
|
||||
@@ -437,10 +450,46 @@
|
||||
obj.zoom = obj.zoom * (1 + obj.track0 / 100)
|
||||
|
||||
|
||||
- AviUtl 腳本的部分相容 -
|
||||
|
||||
提供相容層,使 AviUtl 動畫效果腳本(*.anm 系列)中涉及座標、縮放、旋轉、
|
||||
不透明度的變形以及亂數的部分,無需額外修改即可執行。當腳本中不包含
|
||||
AviUtl 專有寫法時,此相容層完全不介入(傳統腳本的行為不變)。
|
||||
|
||||
○ 腳本標頭指令的解釋
|
||||
解釋註解形式的參數宣告,在執行前定義腳本主體所參考的變數。
|
||||
--dialog:項目名,local 變數=預設值;…
|
||||
將各項目的宣告部分(如 local 變數=預設值)展開至主體開頭。
|
||||
在 AviUtl 中這些是透過對話框編輯的值,此處以預設值執行。
|
||||
--color:0xRRGGBB
|
||||
以指定顏色定義變數 color。
|
||||
--check0:項目名,預設值
|
||||
以預設值定義 obj.check0 (0~3)。
|
||||
--param:任意 Lua 陳述式
|
||||
將所寫的 Lua 陳述式原樣展開至主體開頭。
|
||||
--track0: ~ --track3:
|
||||
軌道列的值仍透過 obj.track0 ~ obj.track3 參考。標頭的標籤、
|
||||
範圍與預設值不會反映至 UI。
|
||||
|
||||
○ 透過 @ 的多區段
|
||||
當一個腳本以 @名稱 定義了多個效果時,僅執行第一個區段。
|
||||
|
||||
○ obj.rand(st, ed [, seed [, frame]])
|
||||
與 AviUtl 相容的確定性整數亂數。詳情請參閱「obj 表 - 函式」。
|
||||
|
||||
以下功能需要與本體的繪製管線整合,因此不在此相容層的範圍內。
|
||||
呼叫它們的腳本不會如預期運作。
|
||||
× 影像、圖形、文字、影片的載入與繪製
|
||||
(obj.load / obj.draw / obj.drawpoly / obj.setfont 等)
|
||||
× 濾鏡效果與緩衝區操作
|
||||
(obj.effect / obj.copybuffer / obj.setoption 等)
|
||||
× 透過 require 載入模組,以及 io 等檔案存取
|
||||
|
||||
|
||||
- 不支援項目·限制事項 -
|
||||
|
||||
× 不支援 AviUtl2 的 obj.effect()、obj.draw()、obj.drawpoly()、obj.load() 等。
|
||||
× 不支援 AviUtl2 的 obj.rand()、obj.rand1()、obj.setfont()、obj.mes() 等。
|
||||
× 不支援 AviUtl2 的 obj.rand1()、obj.setfont()、obj.mes() 等。
|
||||
× 不支援 AviUtl2 的 obj.setoption()、obj.getoption()、obj.getvalue()、obj.setanchor() 等。
|
||||
× 不支援 AviUtl2 scene 表中的 scene.set()、scene.get() 等函式。
|
||||
(僅支援讀取 scene.width 和 scene.height)
|
||||
@@ -449,5 +498,6 @@
|
||||
但 3D 繪製支援有限。
|
||||
× 超過腳本逾時時間(5 秒)時,執行將被強制終止。
|
||||
實作時需注意避免出現無限迴圈。
|
||||
× 不支援 AviUtl2 的 --track@、--check@ 等標頭指令。
|
||||
參數僅可使用 Track0 ~ Track3。
|
||||
× AviUtl2 的標頭指令僅部分支援。--dialog / --color / --check / --param 的
|
||||
預設值會被解釋(參閱「AviUtl 腳本的部分相容」),但 --track@ 的標籤、範圍
|
||||
與預設值不會反映至 UI,值透過 Track0 ~ Track3 使用。
|
||||
@@ -29,6 +29,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- [6. トラックバー(Track0〜Track3)](#6-トラックバーtrack0track3)
|
||||
- [7. スクリプトエディタの支援機能](#7-スクリプトエディタの支援機能)
|
||||
- [8. インポート・エクスポート・クリア](#8-インポートエクスポートクリア)
|
||||
- [9. AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)
|
||||
5. [実行モデル](#実行モデル)
|
||||
- [実行エンジンの自動振り分け](#実行エンジンの自動振り分け)
|
||||
- [実行スレッドとタイムアウト](#実行スレッドとタイムアウト)
|
||||
@@ -47,7 +48,7 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
内部的には MoonSharp(Lua 5.2 互換のスクリプトエンジン)を組み込んでおり、ユーザーが記述した Lua スクリプトをフレームごとに実行します。スクリプト内で `obj.x` や `obj.alpha` といったグローバル変数を書き換えると、その値がオブジェクトの座標・拡縮・回転・不透明度として描画に反映されます。
|
||||
|
||||
このエフェクトは AviUtl2 のスクリプト仕様とは異なる独自実装であり、AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
このエフェクトは独自のスクリプト実行系を基盤としつつ、AviUtl のアニメーション効果スクリプト(`.anm` 系)の一部に対する互換層を備えています(詳細は[AviUtl スクリプトの部分互換](#9-aviutl-スクリプトの部分互換)を参照)。AviUtl 向けの EXO 出力(`.exo`)には対応していません。
|
||||
|
||||
---
|
||||
|
||||
@@ -187,6 +188,28 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
- **インポート**: `.lua` ファイルを選択して読み込み、選択中のすべてのアイテムのスクリプトを置き換えます。
|
||||
- **エクスポート**: 現在のスクリプトを `.lua` ファイルとして保存します。複数のアイテムを選択している場合でも、書き出されるのは先頭の 1 件のスクリプトのみです。
|
||||
- **クリア**: 確認ダイアログの表示後、選択中のすべてのアイテムのスクリプトをデフォルトスクリプト(`obj.alpha = math.min(time * 255, 255)`)に戻します。
|
||||
|
||||
### 9. AviUtl スクリプトの部分互換
|
||||
|
||||
AviUtl のアニメーション効果スクリプト(`.anm` 系)のうち、座標・拡縮・回転・不透明度の変形と乱数を用いる範囲について、追加の記述変更なしに実行できる互換層を備えています。スクリプトに AviUtl 固有の記法が含まれない場合、この互換層は一切介入しません(従来のスクリプトの挙動は変わりません)。
|
||||
|
||||
対応している内容は次のとおりです。
|
||||
|
||||
- **スクリプトヘッダの解釈**: コメント形式のパラメータ宣言を解釈し、スクリプト本体が参照する変数を実行前に定義します。
|
||||
- `--dialog:項目名,local 変数=既定値;…` … 各項目の宣言部(`local 変数=既定値` など)を本体の先頭に展開します。AviUtl では対話ダイアログで編集される値ですが、本プラグインでは既定値で動作します。
|
||||
- `--color:0xRRGGBB` … 変数 `color` を指定色で定義します。
|
||||
- `--check0:項目名,既定値` … `obj.check0`(`0`〜`3`)を既定値で定義します。
|
||||
- `--param:任意のLua文` … 記述した Lua 文をそのまま本体の先頭に展開します。
|
||||
- `--track0:`〜`--track3:` … トラックバーの値は従来どおり `obj.track0`〜`obj.track3` から参照します(ラベル・範囲・既定値の UI 反映は行いません)。
|
||||
- **`@` による複数セクション**: 1 つのスクリプトに `@名前` で複数の効果が定義されている場合、先頭のセクションのみを実行します。
|
||||
- **`obj.rand(st, ed [, seed [, frame]])`**: 指定範囲(`st`〜`ed`)の整数を返す決定論的な乱数です。`seed` と `frame` が同じであれば常に同じ値を返し、`frame` を省略すると現在のフレームを用います。従来エンジン(MoonSharp)と高速ランタイム(LuaJIT)で同じ値を返します。
|
||||
|
||||
次のような機能は、本体の描画パイプラインへの統合を要するため、この互換層では対象外です(呼び出しを含むスクリプトは意図どおりには動作しません)。
|
||||
|
||||
- 画像・図形・テキスト・動画の読み込みと描画(`obj.load` / `obj.draw` / `obj.drawpoly` / `obj.setfont` など)
|
||||
- フィルタ効果やバッファ操作(`obj.effect` / `obj.copybuffer` / `obj.setoption` など)
|
||||
- `require` によるモジュール読み込み、`io` などのファイルアクセス
|
||||
|
||||
---
|
||||
|
||||
## 実行モデル
|
||||
@@ -205,9 +228,10 @@ YukkuriMovieMaker4(YMM4)上で動作する、**Luaスクリプトでオブ
|
||||
|
||||
ネイティブ実行は**専用の別プロセス**で行われ、ピクセルバッファは共有メモリ経由で受け渡されます。スクリプトが無限ループに陥った場合でも **5 秒のタイムアウトでプロセスを強制終了**するため本体は固まらず、終了後は自動的に復帰します。出力結果は従来エンジンと一致します。
|
||||
|
||||
`obj.getobject` はネイティブ実行でも利用できます。呼び出し時に本体プロセスへ同期的に問い合わせてシーンオブジェクトを解決するため、従来エンジンと同じ結果を返します。同じタグ・同じフレームへの連続した問い合わせはフレーム内でキャッシュされ、2 回目以降は往復を行いません。
|
||||
|
||||
ネイティブ実行には次の制約があります。
|
||||
|
||||
- **`obj.getobject` は使用できません**(常に `nil` を返します)。他オブジェクトを参照するスクリプトはピクセル操作と併用しないか、`--!moonsharp` を明示してください。
|
||||
- `bit32` は正しい Lua 5.2 の挙動になります。実用域(0〜2³¹未満の値・0〜31 のシフト量)では従来と一致しますが、`bit32.lshift(1, 32)` のような範囲外の特殊ケースのみ結果が変わります(ネイティブ=0、従来=1)。
|
||||
- `math.random` は両エンジンとも毎フレーム `frame` でシードし直す決定論的乱数ですが、乱数列の実装が異なるためエンジンをまたぐと同じシードでも値が変わります。エンジン非依存の乱数が必要な場合は `anim.rand(min, max, seed)` を使用してください。
|
||||
|
||||
@@ -320,10 +344,10 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
|
||||
## 注意事項
|
||||
|
||||
- **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 へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されますが、**ネイティブ実行では `obj.getobject` が使用できません**(`nil` を返します)。他オブジェクトの参照と併用する場合は `--!moonsharp` を明示してください。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
- **ピクセル操作の負荷**: `obj.getpixel` / `obj.setpixel` / `obj.getpixeldata` は実際の入力画像にアクセスするため、各フレームで最初に呼び出した際に GPU→CPU へのデータ転送が発生します。不要な場合は呼び出しを省略することで処理を高速化できます。これらを含むスクリプトは高速ランタイム(LuaJIT)で自動実行され大幅に高速化されます。詳細は[実行エンジンの自動振り分け](#実行エンジンの自動振り分け)を参照。
|
||||
- **`math.random` はフレームごとの決定論的な乱数**: 毎フレーム `frame` の値でシードし直されるため、同一フレームでは常に同じ値になります。フレームをまたいで変化する乱数的な値が必要な場合は `anim.rand` の利用を検討してください。
|
||||
- **`obj.oz` は出力に反映されません**: スクリプト実行後にコンテキストへ読み戻されますが、現在の実装では中心点オフセットの出力計算に使用されていません。
|
||||
- **エクスポートは先頭の1件のみ**: 複数アイテムを選択した状態でも、エクスポートされるスクリプトは先頭のアイテムのもののみです(インポート・クリアは選択中のすべてのアイテムに適用されます)。
|
||||
@@ -344,7 +368,14 @@ obj.alpha = anim.ease_out(t) * 255
|
||||
|
||||
## サードパーティライセンス
|
||||
|
||||
本プラグインは、Luaスクリプトの実行エンジンとして [MoonSharp](https://github.com/moonsharp-devs/moonsharp)(3-Clause BSD License)を使用しています。
|
||||
本プラグインは以下のサードパーティソフトウェアを同梱・使用しています。各ライセンスの全文は、配布パッケージ(`.ymme`)内の `LICENSE` フォルダーおよびリポジトリの [`.github/LICENSE`](.github/LICENSE) に収録しています。
|
||||
|
||||
| ソフトウェア | 用途 | ライセンス |
|
||||
|---|---|---|
|
||||
| [MoonSharp](https://github.com/moonsharp-devs/moonsharp) | 標準のLua実行エンジン(Lua 5.2 互換) | 3-Clause BSD License |
|
||||
| [LuaJIT](https://github.com/LuaJIT/LuaJIT) | ピクセル操作向け高速ランタイム(`native/luajit.exe`・`lua51.dll`) | MIT License |
|
||||
|
||||
### MoonSharp(3-Clause BSD License)
|
||||
|
||||
```
|
||||
Copyright (c) 2014-2016, Marco Mastropaolo
|
||||
@@ -377,6 +408,34 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
```
|
||||
|
||||
### LuaJIT(MIT License)
|
||||
|
||||
同梱の高速ランタイム(`native/luajit.exe`・`native/lua51.dll`)は LuaJIT v2.1 です。LuaJIT 本体は MIT License で配布されており、その中に Lua 5.1/5.2(Copyright © 1994-2012 Lua.org, PUC-Rio、MIT License)および dlmalloc(パブリックドメイン)のコードを含みます。以下は LuaJIT 本体の著作権表示です(Lua・dlmalloc を含む全文は `LICENSE/LuaJIT.txt` を参照)。
|
||||
|
||||
```
|
||||
LuaJIT -- a Just-In-Time Compiler for Lua. https://luajit.org/
|
||||
|
||||
Copyright (C) 2005-2026 Mike Pall. All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
@@ -307,6 +307,26 @@ function anim.rand(...)
|
||||
return min + r * (max - min)
|
||||
end
|
||||
|
||||
function aviutl_rand(a, b, seed, frame)
|
||||
local ps = ffi.new("double[1]", seed)
|
||||
local ws = ffi.cast("uint32_t*", ps)
|
||||
local s = tou(bit.bxor(ws[0], ws[1]))
|
||||
local pf = ffi.new("double[1]", frame)
|
||||
local wf = ffi.cast("uint32_t*", pf)
|
||||
local f = tou(bit.bxor(wf[0], wf[1]))
|
||||
local h = tou(umul32(s, 374761393) + umul32(f, 668265263))
|
||||
h = umul32(tou(bit.bxor(h, bit.rshift(h, 13))), 1274126177)
|
||||
h = tou(bit.bxor(h, bit.rshift(h, 16)))
|
||||
local r = h / 4294967295.0
|
||||
local lo = floor(math.min(a, b))
|
||||
local hi = floor(math.max(a, b))
|
||||
local span = hi - lo + 1
|
||||
if span <= 1 then return lo end
|
||||
local v = lo + floor(r * span)
|
||||
if v > hi then return hi end
|
||||
return v
|
||||
end
|
||||
|
||||
local function noise_hash(x, y, z)
|
||||
local n = tou(umul32(tou(x), 374761393) + umul32(tou(y), 668265263) + umul32(tou(z), 1013904223))
|
||||
n = umul32(tou(bit.bxor(n, bit.rshift(n, 13))), 1274126177)
|
||||
|
||||
+58
-3
@@ -43,11 +43,18 @@ local OFF_HEIGHT = 4
|
||||
local OFF_SCRIPTLEN = 5
|
||||
local OFF_PIXELSDIRTY = 6
|
||||
local OFF_ERRORLEN = 7
|
||||
local OFF_CB_FRAME = 8
|
||||
local OFF_CB_TAGLEN = 9
|
||||
local OFF_CB_FOUND = 10
|
||||
local SCRIPT_OFFSET = 64 + 64 * 8
|
||||
local ERROR_OFFSET = SCRIPT_OFFSET + 128 * 1024
|
||||
local PIXEL_OFFSET = ERROR_OFFSET + 4 * 1024
|
||||
local CB_TAG_OFFSET = ERROR_OFFSET + 4 * 1024
|
||||
local CB_TAG_MAX = 256
|
||||
local CB_RESULT_OFFSET = CB_TAG_OFFSET + CB_TAG_MAX
|
||||
local PIXEL_OFFSET = CB_RESULT_OFFSET + 8 * 8
|
||||
local FIRST_WRITABLE = 8
|
||||
local LAST_WRITABLE = 25
|
||||
local STATUS_CALLBACK = 3
|
||||
|
||||
assert(loadfile(shimPath))()
|
||||
|
||||
@@ -59,6 +66,7 @@ end
|
||||
|
||||
local width, height = 0, 0
|
||||
local pixels = ffi.cast("uint8_t*", base + PIXEL_OFFSET)
|
||||
local cbResult = ffi.cast("double*", base + CB_RESULT_OFFSET)
|
||||
local dirty = false
|
||||
|
||||
local obj = {}
|
||||
@@ -137,7 +145,52 @@ function obj.getpixeldata()
|
||||
end
|
||||
|
||||
function obj.putpixeldata() end
|
||||
function obj.getobject() return nil end
|
||||
|
||||
function obj.rand(a, b, seed, frame)
|
||||
return aviutl_rand(a or 0, b or 0, seed or 0, frame or obj.frame or 0)
|
||||
end
|
||||
|
||||
local cacheTag, cacheFrame, cacheFound
|
||||
local cacheExist, cacheX, cacheY, cacheZ, cacheZoom, cacheRz, cacheAlpha, cacheLayer
|
||||
|
||||
local function buildObject()
|
||||
return {
|
||||
exist = cacheExist,
|
||||
x = cacheX, y = cacheY, z = cacheZ,
|
||||
zoom = cacheZoom, sx = cacheZoom, sy = cacheZoom,
|
||||
rx = 0, ry = 0, rz = cacheRz,
|
||||
rxr = 0, ryr = 0, rzr = cacheRz * math.pi / 180,
|
||||
alpha = cacheAlpha, layer = cacheLayer,
|
||||
}
|
||||
end
|
||||
|
||||
function obj.getobject(tag, frame)
|
||||
if type(tag) ~= "string" then return nil end
|
||||
if frame then frame = math.floor(frame) else frame = math.floor(obj.timelineframe or 0) end
|
||||
if tag == cacheTag and frame == cacheFrame then
|
||||
if cacheFound then return buildObject() end
|
||||
return nil
|
||||
end
|
||||
local len = #tag
|
||||
if len > CB_TAG_MAX then len = CB_TAG_MAX end
|
||||
ffi.copy(base + CB_TAG_OFFSET, tag, len)
|
||||
i32[OFF_CB_TAGLEN] = len
|
||||
i32[OFF_CB_FRAME] = frame
|
||||
i32[OFF_STATUS] = STATUS_CALLBACK
|
||||
k32.SetEvent(doneEvent)
|
||||
k32.WaitForSingleObject(workEvent, INFINITE)
|
||||
cacheTag = tag
|
||||
cacheFrame = frame
|
||||
if i32[OFF_CB_FOUND] == 0 then
|
||||
cacheFound = false
|
||||
return nil
|
||||
end
|
||||
cacheFound = true
|
||||
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]
|
||||
return buildObject()
|
||||
end
|
||||
|
||||
local sandbox = {
|
||||
obj = obj, scene = scene, ymm4 = ymm4,
|
||||
@@ -214,6 +267,7 @@ while true do
|
||||
|
||||
if compiledChunk and code == compiledCode then
|
||||
loadFields()
|
||||
cacheTag = nil
|
||||
math.randomseed(f64[31])
|
||||
setfenv(compiledChunk, sandbox)
|
||||
local ok, err = pcall(compiledChunk)
|
||||
@@ -221,13 +275,14 @@ while true do
|
||||
storeFields()
|
||||
i32[OFF_PIXELSDIRTY] = dirty and 1 or 0
|
||||
i32[OFF_STATUS] = 1
|
||||
k32.SetEvent(doneEvent)
|
||||
else
|
||||
local msg = tostring(err)
|
||||
ffi.copy(base + ERROR_OFFSET, msg, math.min(#msg, 4096))
|
||||
i32[OFF_ERRORLEN] = math.min(#msg, 4096)
|
||||
i32[OFF_STATUS] = 2
|
||||
k32.SetEvent(doneEvent)
|
||||
end
|
||||
k32.SetEvent(doneEvent)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
新しいイシューから参照
ユーザーをブロックする